-
Notifications
You must be signed in to change notification settings - Fork 25
/
list.js
409 lines (361 loc) · 13.3 KB
/
list.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import { css, html, LitElement } from 'lit';
import { getNextFocusable, getPreviousFocusable } from '../../helpers/focus.js';
import { SelectionInfo, SelectionMixin } from '../selection/selection-mixin.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { PageableMixin } from '../paging/pageable-mixin.js';
import ResizeObserver from 'resize-observer-polyfill';
import { SubscriberRegistryController } from '../../controllers/subscriber/subscriberControllers.js';
const keyCodes = {
TAB: 9
};
export const listSelectionStates = SelectionInfo.states;
const DEFAULT_BREAKPOINTS = [842, 636, 580, 0];
const SLIM_COLOR_BREAKPOINT = 400;
const ro = new ResizeObserver(entries => {
entries.forEach(entry => {
if (!entry?.target?.resizedCallback) return;
entry.target.resizedCallback(entry.contentRect?.width);
});
});
/**
* A container for a styled list of items ("d2l-list-item"). It provides the appropriate "list" semantics as well as options for displaying separators, etc.
* @slot - Slot for list items (ex. `d2l-list-item`, `d2l-list-item-button`, or custom items)
* @slot controls - Slot for `d2l-list-controls` to be rendered above the list
* @slot pager - Slot for `d2l-pager-load-more` to be rendered below the list
* @fires d2l-list-items-move - Dispatched when one or more items are moved. See [Event Details: d2l-list-items-move](#event-details%3A-%40d2l-list-items-move).
*/
class List extends PageableMixin(SelectionMixin(LitElement)) {
static get properties() {
return {
/**
* When true, show the inline add button after each list item.
* @type {boolean}
*/
addButton: { type: Boolean, reflect: true, attribute: 'add-button' },
/**
* Text to show in label tooltip on inline add button. Defaults to "Add Item".
* @type {string}
*/
addButtonText: { type: String, reflect: true, attribute: 'add-button-text' },
/**
* Breakpoints for responsiveness in pixels. There are four different breakpoints and only the four largest breakpoints will be used.
* @type {array}
*/
breakpoints: { type: Array },
/**
* Whether the user can drag multiple items
* @type {boolean}
*/
dragMultiple: { type: Boolean, reflect: true, attribute: 'drag-multiple' },
/**
* Whether to extend the separators beyond the content's edge
* @type {boolean}
*/
extendSeparators: { type: Boolean, reflect: true, attribute: 'extend-separators' },
/**
* Use grid to manage focus with arrow keys. See [Accessibility](#accessibility).
* @type {boolean}
*/
grid: { type: Boolean },
/**
* Sets an accessible label. For use when the list context is unclear. This property is only valid on top-level lists and will have no effect on nested lists.
* @type {string}
*/
label: { type: String },
/**
* Display separators. Valid values are "all" (default), "between", "none"
* @type {'all'|'between'|'none'}
* @default "all"
*/
separators: { type: String, reflect: true },
_breakpoint: { type: Number, reflect: true },
_slimColor: { type: Boolean, reflect: true, attribute: '_slim-color' }
};
}
static get styles() {
return css`
:host {
--d2l-list-item-color-border-radius: 6px;
--d2l-list-item-color-width: 6px;
--d2l-list-item-illustration-margin-inline-end: 0.9rem;
--d2l-list-item-illustration-max-height: 2.6rem;
--d2l-list-item-illustration-max-width: 4.5rem;
display: block;
}
:host(:not([slot="nested"])) > .d2l-list-content {
padding-bottom: 1px;
}
:host([hidden]) {
display: none;
}
slot[name="pager"]::slotted(*) {
margin-top: 10px;
}
:host([extend-separators]) slot[name="pager"]::slotted(*) {
margin-left: 0.9rem;
margin-right: 0.9rem;
}
:host([_breakpoint="1"]) {
--d2l-list-item-illustration-margin-inline-end: 1rem;
--d2l-list-item-illustration-max-height: 3.55rem;
--d2l-list-item-illustration-max-width: 6rem;
}
:host([_breakpoint="2"]) {
--d2l-list-item-illustration-margin-inline-end: 1rem;
--d2l-list-item-illustration-max-height: 5.1rem;
--d2l-list-item-illustration-max-width: 9rem;
}
:host([_breakpoint="3"]) {
--d2l-list-item-illustration-margin-inline-end: 1rem;
--d2l-list-item-illustration-max-height: 6rem;
--d2l-list-item-illustration-max-width: 10.8rem;
}
:host([_slim-color]) {
--d2l-list-item-color-border-radius: 3px;
--d2l-list-item-color-width: 3px;
}
:host([add-button]) ::slotted([slot="controls"]) {
margin-bottom: calc(6px + 0.4rem); /* controls section margin-bottom + spacing for add-button */
}
`;
}
constructor() {
super();
this.addButton = false;
this.breakpoints = DEFAULT_BREAKPOINTS;
this.dragMultiple = false;
this.extendSeparators = false;
this.grid = false;
this._listItemChanges = [];
this._childHasColor = false;
this._childHasExpandCollapseToggle = false;
this._breakpoint = 0;
this._slimColor = false;
this._width = 0;
this._listChildrenUpdatedSubscribers = new SubscriberRegistryController(this, 'list-child-status', {
onSubscribe: this._updateActiveSubscriber.bind(this),
updateSubscribers: this._updateActiveSubscribers.bind(this)
});
}
get breakpoints() {
return this._breakpoints;
}
set breakpoints(value) {
const oldValue = this._breakpoints;
if (value !== DEFAULT_BREAKPOINTS) this._breakpoints = value.sort((a, b) => b - a).slice(0, 4);
else this._breakpoints = DEFAULT_BREAKPOINTS;
this.requestUpdate('breakpoints', oldValue);
}
connectedCallback() {
super.connectedCallback();
this.addEventListener('d2l-list-item-showing-count-change', this._handleListItemShowingCountChange);
this.addEventListener('d2l-list-item-nested-change', (e) => this._handleListItemNestedChange(e));
this.addEventListener('d2l-list-item-property-change', (e) => this._handleListItemPropertyChange(e));
this.addEventListener('d2l-list-item-add-button-click', (e) => this._handleListItemAddButtonClick(e));
ro.observe(this);
}
disconnectedCallback() {
super.disconnectedCallback();
if (this._intersectionObserver) this._intersectionObserver.disconnect();
ro.unobserve(this);
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
// check if list items are expandable on first render so we adjust sibling spacing appropriately
this._handleListItemNestedChange();
this.addEventListener('d2l-list-item-selected', e => {
// batch the changes from select-all and nested lists
if (this._listItemChanges.length === 0) {
setTimeout(() => {
/** Dispatched once for a set of selection state changes (ex. select-all); event detail includes an array of objects where each object contains the `key` and `selected` state for each changed item */
this.dispatchEvent(new CustomEvent('d2l-list-selection-changes', {
detail: this._listItemChanges
}));
this._listItemChanges = [];
}, 60);
}
this._listItemChanges.push(e.detail);
setTimeout(() => {
/** Dispatched when the selection state changes */
this.dispatchEvent(new CustomEvent('d2l-list-selection-change', {
bubbles: true,
composed: true,
detail: e.detail
}));
}, 0);
});
}
render() {
const role = !this.grid ? 'list' : 'application';
const ariaLabel = this.slot !== 'nested' ? this.label : undefined;
return html`
<slot name="controls"></slot>
<slot name="header"></slot>
<div role="${role}" aria-label="${ifDefined(ariaLabel)}" class="d2l-list-content">
<slot @keydown="${this._handleKeyDown}" @slotchange="${this._handleSlotChange}"></slot>
</div>
${this._renderPagerContainer()}
`;
}
updated(changedProperties) {
super.updated(changedProperties);
if (changedProperties.has('breakpoints') && changedProperties.get('breakpoints') !== undefined) {
this.resizedCallback(this.offsetWidth, true);
}
if (changedProperties.has('add-button') || changedProperties.has('add-button-text')) {
this._listChildrenUpdatedSubscribers.updateSubscribers();
}
if (changedProperties.has('grid') && this.grid) {
this.selectionNoInputArrowKeyBehaviour = true;
}
}
getItems(slot) {
if (!this.shadowRoot) return;
if (!slot) slot = this.shadowRoot.querySelector('slot:not([name])');
if (!slot) return [];
return slot.assignedNodes({ flatten: true }).filter((node) => {
return node.nodeType === Node.ELEMENT_NODE && (node.role === 'rowgroup' || node.role === 'listitem');
});
}
getListItemByKey(key) {
const items = this.getItems();
for (let i = 0; i < items.length; i++) {
if (items[i].key === key) return items[i];
if (items[i]._selectionProvider) {
const tempItem = items[i]._selectionProvider.getListItemByKey(key);
if (tempItem) return tempItem;
}
}
return null;
}
getListItemCount() {
return this.getItems().length;
}
getListItemIndex(item) {
return this.getItems().indexOf(item);
}
getSelectedListItems(includeNested) {
let selectedItems = [];
this.getItems().forEach(item => {
if (item.selected) selectedItems.push(item);
if (includeNested && item._selectionProvider) {
selectedItems = [...selectedItems, ...item._selectionProvider.getSelectedListItems(includeNested)];
}
});
return selectedItems;
}
getSelectionInfo(includeNested) {
const selectionInfo = super.getSelectionInfo();
if (!includeNested) return selectionInfo;
let keys = selectionInfo.keys;
this.getItems().forEach(item => {
if (item._selectionProvider) {
keys = [...keys, ...item._selectionProvider.getSelectionInfo(true).keys];
}
});
return new SelectionInfo(keys, selectionInfo.state);
}
resizedCallback(width, breakpointsChanged) {
if (this._width === width && !breakpointsChanged) return;
this._width = width;
this._slimColor = (width < SLIM_COLOR_BREAKPOINT);
const lastBreakpointIndexToCheck = 3;
this.breakpoints.some((breakpoint, index) => {
if (width >= breakpoint || index > lastBreakpointIndexToCheck) {
this._breakpoint = lastBreakpointIndexToCheck - index - (lastBreakpointIndexToCheck - this.breakpoints.length + 1) * index;
return true;
}
});
}
_getItemByIndex(index) {
const items = this.getItems() || [];
return items[index];
}
_getItemShowingCount() {
return this.getItems().length;
}
_getLazyLoadItems() {
const items = this.getItems();
return items.length > 0 ? items[0]._getFlattenedListItems().lazyLoadListItems : new Map();
}
_handleKeyDown(e) {
if (!this.grid || this.slot === 'nested' || e.keyCode !== keyCodes.TAB) return;
e.preventDefault();
if (!this.shadowRoot) return;
const listSlot = this.shadowRoot.querySelector('slot:not([name])');
const focusable = (e.shiftKey ? getPreviousFocusable(listSlot) : getNextFocusable(listSlot, false, true, true));
if (focusable) focusable.focus();
}
_handleListItemAddButtonClick(e) {
e.stopPropagation();
/**
* Dispatched when the add button directly before or after the item is clicked. Event detail includes position ('before' or 'after') and key.
* The `key` belongs to the list item adjacent to where the new item should be positioned.
* The `position` represents where the new item should be positioned relative to the item with that key.
* */
this.dispatchEvent(new CustomEvent('d2l-list-add-button-click', { detail: { key: e.target.key, position: e.detail.position } }));
}
_handleListItemNestedChange(e) {
if (e) {
e.stopPropagation();
}
const items = this.getItems();
let aChildHasColor = false;
let aChildHasToggleEnabled = false;
for (const item of items) {
if (item.color) aChildHasColor = true;
if (item.expandable) aChildHasToggleEnabled = true;
if (aChildHasToggleEnabled && aChildHasColor) break;
}
this._childHasColor = aChildHasColor;
this._childHasExpandCollapseToggle = aChildHasToggleEnabled;
this._listChildrenUpdatedSubscribers.updateSubscribers();
}
_handleListItemPropertyChange(e) {
e.stopPropagation();
if (e.detail.name === 'color') {
if (e.detail.value) {
this._childHasColor = true;
this._listChildrenUpdatedSubscribers.updateSubscribers();
} else {
// if color has had its value removed then need to loop through all the items to determine if there are still others with colors
this._handleListItemNestedChange(e);
}
}
}
_handleListItemShowingCountChange() {
if (this.slot === 'nested') return;
// debounce the updates for first render case
if (this._updateItemShowingCountRequested) return;
this._updateItemShowingCountRequested = true;
setTimeout(() => {
this._updateItemShowingCount();
this._updateItemShowingCountRequested = false;
}, 0);
}
_handleSlotChange() {
this._updateItemShowingCount();
this.getItems().forEach((item, i) => {
if (i === 0) item.first = true;
else item.first = false;
});
/** @ignore */
this.dispatchEvent(new CustomEvent('d2l-list-item-showing-count-change', {
bubbles: true,
composed: true
}));
}
_updateActiveSubscriber(subscriber) {
subscriber.updateSiblingHasChildren(this._childHasExpandCollapseToggle);
subscriber.updateSiblingHasColor(this._childHasColor);
subscriber.updateParentHasAddButon(this.addButton, this.addButtonText);
}
_updateActiveSubscribers(subscribers) {
subscribers.forEach(subscriber => {
subscriber.updateSiblingHasChildren(this._childHasExpandCollapseToggle);
subscriber.updateSiblingHasColor(this._childHasColor);
subscriber.updateParentHasAddButon(this.addButton, this.addButtonText);
});
}
}
customElements.define('d2l-list', List);