@avlcodemonkey/nilla-components 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/LICENSE +21 -0
- package/README.md +219 -3
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/css/alert.css +48 -0
- package/css/autocomplete.css +38 -0
- package/css/dialog.css +61 -0
- package/css/file-to-textarea.css +8 -0
- package/css/html-editor.css +172 -0
- package/css/json.css +44 -0
- package/css/list.css +37 -0
- package/css/nav-toggle.css +92 -0
- package/css/nilla.css +16 -0
- package/css/pjax.css +58 -0
- package/css/slider-input.css +16 -0
- package/css/table.css +99 -0
- package/css/tokens.css +44 -0
- package/css/unsaved-changes.css +10 -0
- package/css/vendor/wysi.css +406 -0
- package/docs/llms.txt +319 -0
- package/package.json +121 -5
- package/src/components/Alert.js +24 -0
- package/src/components/Autocomplete.js +127 -0
- package/src/components/BaseComponent.js +78 -0
- package/src/components/BaseDialog.js +151 -0
- package/src/components/ConfirmDialog.js +34 -0
- package/src/components/CopyToClipboard.js +66 -0
- package/src/components/DateFormatter.js +51 -0
- package/src/components/DateTimeInput.js +63 -0
- package/src/components/DisplayToggle.js +53 -0
- package/src/components/FileToTextarea.js +81 -0
- package/src/components/HtmlEditor.js +309 -0
- package/src/components/InfoDialog.js +38 -0
- package/src/components/JsonFormatter.js +23 -0
- package/src/components/List.js +237 -0
- package/src/components/ListSortable.js +8 -0
- package/src/components/NavToggle.js +119 -0
- package/src/components/PJax.js +888 -0
- package/src/components/Share.js +41 -0
- package/src/components/SliderInput.js +26 -0
- package/src/components/Table.js +758 -0
- package/src/components/TimeOffsetSelect.js +29 -0
- package/src/components/UnsavedChanges.js +187 -0
- package/src/constants/Fetch.js +7 -0
- package/src/constants/HttpHeaders.js +19 -0
- package/src/constants/HttpMethods.js +14 -0
- package/src/constants/SortDirection.js +11 -0
- package/src/constants/TableElements.js +25 -0
- package/src/constants/TableSettings.js +14 -0
- package/src/errors/FetchError.js +7 -0
- package/src/events/ListReorderEvent.js +19 -0
- package/src/events/PJaxErrorEvent.js +38 -0
- package/src/events/PJaxNavigatingEvent.js +46 -0
- package/src/index.js +26 -0
- package/src/locales/en.json +55 -0
- package/src/locales/es.js +9 -0
- package/src/locales/es.json +55 -0
- package/src/models/TableSort.js +20 -0
- package/src/utils/ajaxHeaders.js +10 -0
- package/src/utils/announce.js +40 -0
- package/src/utils/defineElement.js +13 -0
- package/src/utils/editor/blockTools.js +256 -0
- package/src/utils/editor/elements.js +18 -0
- package/src/utils/editor/input.js +350 -0
- package/src/utils/editor/selection.js +125 -0
- package/src/utils/editor/tableTools.js +497 -0
- package/src/utils/escape.js +20 -0
- package/src/utils/fetchJsonArray.js +29 -0
- package/src/utils/filterArray.js +18 -0
- package/src/utils/formActionUrl.js +10 -0
- package/src/utils/formData.js +118 -0
- package/src/utils/index.js +18 -0
- package/src/utils/indexedCompare.js +18 -0
- package/src/utils/isSameOrigin.js +12 -0
- package/src/utils/locale.js +36 -0
- package/src/utils/notifyChange.js +10 -0
- package/src/utils/numberSetting.js +14 -0
- package/src/utils/pageLanguage.js +13 -0
- package/src/utils/parseUtcDate.js +22 -0
- package/src/utils/randomId.js +17 -0
- package/src/utils/registerTabTrap.js +60 -0
- package/src/utils/renderTemplate.js +44 -0
- package/src/utils/requestTimeout.js +12 -0
- package/src/utils/response.js +28 -0
- package/src/utils/sortedCompare.js +67 -0
- package/src/utils/storage.js +40 -0
- package/src/vendor/autocomplete.js +515 -0
- package/src/vendor/formatDate.js +236 -0
- package/src/vendor/licenses/autocomplete.LICENSE.md +21 -0
- package/src/vendor/licenses/fecha.LICENSE.md +21 -0
- package/src/vendor/licenses/pretty-print-json.LICENSE.md +21 -0
- package/src/vendor/licenses/wysi.LICENSE.md +21 -0
- package/src/vendor/prettyPrintJson.js +108 -0
- package/src/vendor/wyzi.js +2024 -0
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import '../vendor/wyzi.js';
|
|
2
|
+
import DOMPurify from 'dompurify';
|
|
3
|
+
import renderTemplate from '../utils/renderTemplate.js';
|
|
4
|
+
import BaseComponent from './BaseComponent.js';
|
|
5
|
+
import './ConfirmDialog.js';
|
|
6
|
+
import defineElement from '../utils/defineElement.js';
|
|
7
|
+
import { getText } from '../utils/locale.js';
|
|
8
|
+
import notifyChange from '../utils/notifyChange.js';
|
|
9
|
+
import numberSetting from '../utils/numberSetting.js';
|
|
10
|
+
import pageLanguage from '../utils/pageLanguage.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Enum for identifiers to query DOM elements.
|
|
14
|
+
* @readonly
|
|
15
|
+
* @enum {string}
|
|
16
|
+
*/
|
|
17
|
+
const Elements = Object.freeze({
|
|
18
|
+
Input: 'input',
|
|
19
|
+
Counter: 'counter',
|
|
20
|
+
Count: 'count',
|
|
21
|
+
Max: 'max',
|
|
22
|
+
Over: 'over',
|
|
23
|
+
Paste: 'paste',
|
|
24
|
+
DeleteTable: 'delete-table',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Share of the maximum length at which the counter starts to warn.
|
|
29
|
+
* @type {number}
|
|
30
|
+
*/
|
|
31
|
+
const WarningThreshold = 0.9;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Toolbar buttons for the editor. Text alignment is left out because it relies on inline styles, which the content security policy blocks.
|
|
35
|
+
* @type {string[]}
|
|
36
|
+
*/
|
|
37
|
+
const Tools = [
|
|
38
|
+
'format',
|
|
39
|
+
'|',
|
|
40
|
+
'bold',
|
|
41
|
+
'italic',
|
|
42
|
+
'strike',
|
|
43
|
+
'code',
|
|
44
|
+
'codeBlock',
|
|
45
|
+
'|',
|
|
46
|
+
'quote',
|
|
47
|
+
'hr',
|
|
48
|
+
'table',
|
|
49
|
+
'|',
|
|
50
|
+
'ul',
|
|
51
|
+
'ol',
|
|
52
|
+
'indent',
|
|
53
|
+
'outdent',
|
|
54
|
+
'|',
|
|
55
|
+
'link',
|
|
56
|
+
'image',
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Tags the editor keeps that don't have their own toolbar button.
|
|
61
|
+
* @type {object[]}
|
|
62
|
+
*/
|
|
63
|
+
const CustomTags = [
|
|
64
|
+
// empty cells are kept, otherwise the cells after them would move into the wrong columns
|
|
65
|
+
{ tags: ['th', 'td'], attributes: ['align', 'colspan', 'rowspan'], isEmpty: true },
|
|
66
|
+
// task list checkboxes
|
|
67
|
+
{ tags: ['input'], attributes: ['type', 'checked', 'disabled'], isEmpty: true },
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Sanitizer used only by the editor, so its rules don't affect anything else.
|
|
72
|
+
*/
|
|
73
|
+
const Purifier = DOMPurify(window);
|
|
74
|
+
|
|
75
|
+
// links that open in a new tab shouldn't be able to reach back into this page
|
|
76
|
+
Purifier.addHook('afterSanitizeAttributes', (node) => {
|
|
77
|
+
if (node.nodeName === 'A' && node.getAttribute('target') === '_blank') {
|
|
78
|
+
node.setAttribute('rel', 'noopener noreferrer');
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Remove anything unsafe from HTML.
|
|
84
|
+
* @param {string} html HTML to clean.
|
|
85
|
+
* @returns {string} Safe HTML.
|
|
86
|
+
*/
|
|
87
|
+
function sanitize(html) {
|
|
88
|
+
return Purifier.sanitize(html, { ADD_ATTR: ['target'] });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Turn plain text into a paragraph for each line that has something on it.
|
|
93
|
+
* @param {string} text Text to convert.
|
|
94
|
+
* @returns {string} HTML for the text.
|
|
95
|
+
*/
|
|
96
|
+
function textToHtml(text) {
|
|
97
|
+
return text.split(/\r\n?|\n/).filter(line => line.trim()).map((line) => {
|
|
98
|
+
const paragraph = document.createElement('p');
|
|
99
|
+
paragraph.textContent = line;
|
|
100
|
+
return paragraph.outerHTML;
|
|
101
|
+
}).join('');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Read HTML from the clipboard, falling back to plain text escaped as HTML.
|
|
106
|
+
* @returns {Promise<string|undefined>} HTML to paste, or undefined if nothing could be read.
|
|
107
|
+
*/
|
|
108
|
+
async function readClipboardHtml() {
|
|
109
|
+
try {
|
|
110
|
+
for (const item of (await navigator.clipboard?.read?.()) ?? []) {
|
|
111
|
+
if (item.types.includes('text/html')) {
|
|
112
|
+
return await (await item.getType('text/html')).text();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
} catch {
|
|
116
|
+
// reading rich content isn't allowed everywhere, so fall back to plain text
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
const text = await navigator.clipboard?.readText();
|
|
121
|
+
return text === undefined ? undefined : textToHtml(text);
|
|
122
|
+
} catch {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Web component that renders an HTML editor.
|
|
129
|
+
* Uses DOMPurify to sanitize the input and prevent XSS attacks with a debounce for performance.
|
|
130
|
+
*/
|
|
131
|
+
class HtmlEditor extends BaseComponent {
|
|
132
|
+
/** @type {HTMLTextAreaElement|null} */
|
|
133
|
+
#textarea;
|
|
134
|
+
|
|
135
|
+
/** @type {number|undefined} */
|
|
136
|
+
#debounceTimer;
|
|
137
|
+
|
|
138
|
+
/** @type {HTMLFormElement|null} */
|
|
139
|
+
#form;
|
|
140
|
+
|
|
141
|
+
/** @type {HTMLElement|null|undefined} */
|
|
142
|
+
#pasteConfirmation;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Sanitize before the form submits, so the latest changes are sent even if a debounce is pending.
|
|
146
|
+
*/
|
|
147
|
+
#submitListener = () => {
|
|
148
|
+
clearTimeout(this.#debounceTimer);
|
|
149
|
+
this.#sanitize();
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Replace the content once pasting is confirmed.
|
|
154
|
+
*/
|
|
155
|
+
#pasteListener = () => {
|
|
156
|
+
this.#paste();
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Whether the editor marked its fields invalid for being too long, so it only removes marks it added.
|
|
161
|
+
*/
|
|
162
|
+
#markedTooLong = false;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Initialize the component.
|
|
166
|
+
*/
|
|
167
|
+
constructor() {
|
|
168
|
+
super('html');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Build the editor. It's built each time the element is added to the page, including when it's moved.
|
|
173
|
+
*/
|
|
174
|
+
connectedCallback() {
|
|
175
|
+
this.#textarea = /** @type {HTMLTextAreaElement|null} */ (this.getElement(Elements.Input));
|
|
176
|
+
if (!this.#textarea) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
this.#sanitize();
|
|
180
|
+
|
|
181
|
+
this.#form = this.closest('form');
|
|
182
|
+
this.#form?.addEventListener('submit', this.#submitListener);
|
|
183
|
+
|
|
184
|
+
const labels = JSON.parse(this.dataset.labels || '{}');
|
|
185
|
+
window.Wysi({
|
|
186
|
+
el: this.#textarea,
|
|
187
|
+
tools: Tools,
|
|
188
|
+
customTags: CustomTags,
|
|
189
|
+
translate: key => labels[key] ?? getText(key, this),
|
|
190
|
+
height: numberSetting(this.dataset.height, 400),
|
|
191
|
+
autoGrow: true,
|
|
192
|
+
autoHide: false,
|
|
193
|
+
onChange: () => {
|
|
194
|
+
// update right away so typing feels live. sanitizing can change the length, so it updates again after the debounce
|
|
195
|
+
this.#updateCounter();
|
|
196
|
+
clearTimeout(this.#debounceTimer);
|
|
197
|
+
this.#debounceTimer = setTimeout(() => this.#sanitize(), 250);
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// again now that there's an editable area to mark
|
|
202
|
+
this.#updateCounter();
|
|
203
|
+
this.#addDeleteTableText();
|
|
204
|
+
|
|
205
|
+
this.#pasteConfirmation = this.getElement(Elements.Paste)?.closest('nilla-confirm');
|
|
206
|
+
this.#pasteConfirmation?.addEventListener('click', this.#pasteListener);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Remove the editor and listeners, keeping the content in the textarea.
|
|
211
|
+
*/
|
|
212
|
+
disconnectedCallback() {
|
|
213
|
+
clearTimeout(this.#debounceTimer);
|
|
214
|
+
this.#form?.removeEventListener('submit', this.#submitListener);
|
|
215
|
+
this.#pasteConfirmation?.removeEventListener('click', this.#pasteListener);
|
|
216
|
+
if (this.#textarea) {
|
|
217
|
+
// don't lose changes still waiting for the debounce
|
|
218
|
+
this.#sanitize();
|
|
219
|
+
window.Wysi.destroy(this.#textarea);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
super.disconnectedCallback();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Sanitize the textarea's value and update the counter.
|
|
227
|
+
*/
|
|
228
|
+
#sanitize() {
|
|
229
|
+
this.#textarea.value = sanitize(this.#textarea.value);
|
|
230
|
+
this.#updateCounter();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Show how much of the textarea's maximum length is used. Counts the HTML, since that's what gets validated.
|
|
235
|
+
*/
|
|
236
|
+
#updateCounter() {
|
|
237
|
+
const max = this.#textarea.maxLength;
|
|
238
|
+
if (max < 0) {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const count = this.#textarea.value.length;
|
|
243
|
+
const over = Math.max(count - max, 0);
|
|
244
|
+
this.#markTooLong(over > 0);
|
|
245
|
+
|
|
246
|
+
const counter = this.getElement(Elements.Counter);
|
|
247
|
+
if (!counter) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
const lang = pageLanguage(this);
|
|
251
|
+
this.getElement(Elements.Count).textContent = count.toLocaleString(lang);
|
|
252
|
+
this.getElement(Elements.Max).textContent = max.toLocaleString(lang);
|
|
253
|
+
this.getElement(Elements.Over).textContent = over ? renderTemplate(counter.dataset.overText, { count: over.toLocaleString(lang) }) : '';
|
|
254
|
+
counter.toggleAttribute('data-over', over > 0);
|
|
255
|
+
counter.toggleAttribute('data-warning', !over && count >= max * WarningThreshold);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Tell assistive technology whether the content is too long, on the textarea and on the editable area people type in.
|
|
260
|
+
* @param {boolean} tooLong True when over the maximum length.
|
|
261
|
+
*/
|
|
262
|
+
#markTooLong(tooLong) {
|
|
263
|
+
if (!(tooLong || this.#markedTooLong)) {
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const editor = this.#textarea.previousElementSibling?.querySelector('.wysi-editor');
|
|
268
|
+
for (const field of [this.#textarea, editor]) {
|
|
269
|
+
if (tooLong) {
|
|
270
|
+
field?.setAttribute('aria-invalid', 'true');
|
|
271
|
+
} else {
|
|
272
|
+
field?.removeAttribute('aria-invalid');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
this.#markedTooLong = tooLong;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Add the translated confirmation text to the delete table button, which the editor builds.
|
|
280
|
+
*/
|
|
281
|
+
#addDeleteTableText() {
|
|
282
|
+
const button = this.getElement(Elements.DeleteTable);
|
|
283
|
+
if (button) {
|
|
284
|
+
const { deleteTableContent, deleteTableOk, deleteTableCancel } = this.dataset;
|
|
285
|
+
Object.assign(button.dataset, {
|
|
286
|
+
dialogContent: deleteTableContent || getText('editor.deleteTableConfirm', this),
|
|
287
|
+
dialogOk: deleteTableOk || getText('delete', this),
|
|
288
|
+
dialogCancel: deleteTableCancel || getText('cancel', this),
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Replace the content with what's on the clipboard.
|
|
295
|
+
*/
|
|
296
|
+
async #paste() {
|
|
297
|
+
const content = await readClipboardHtml();
|
|
298
|
+
if (content && this.#textarea && this.isConnected) {
|
|
299
|
+
window.Wysi.setContent(this.#textarea, sanitize(content));
|
|
300
|
+
this.#sanitize();
|
|
301
|
+
// tell the form, after sanitizing, so listeners see the final content
|
|
302
|
+
notifyChange(this.#textarea);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
defineElement('nilla-html-editor', HtmlEditor);
|
|
308
|
+
|
|
309
|
+
export default HtmlEditor;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import BaseDialog from './BaseDialog.js';
|
|
2
|
+
import defineElement from '../utils/defineElement.js';
|
|
3
|
+
import { getText } from '../utils/locale.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Extend the custom dialog class to create the alert web component.
|
|
7
|
+
*/
|
|
8
|
+
class InfoDialog extends BaseDialog {
|
|
9
|
+
/**
|
|
10
|
+
* Initialize component.
|
|
11
|
+
*/
|
|
12
|
+
constructor() {
|
|
13
|
+
super();
|
|
14
|
+
|
|
15
|
+
this.interceptClicks((_element, data) => this.#show(data));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Manually show the modal.
|
|
20
|
+
*/
|
|
21
|
+
show() {
|
|
22
|
+
if (this.dataset.dialogContent) {
|
|
23
|
+
this.#show(this.dataset);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Show the modal with the given text.
|
|
29
|
+
* @param {DOMStringMap} data Dialog text.
|
|
30
|
+
*/
|
|
31
|
+
#show({ dialogContent, dialogOk }) {
|
|
32
|
+
this.showDialog(dialogContent, dialogOk || getText('ok', this));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
defineElement('nilla-info', InfoDialog);
|
|
37
|
+
|
|
38
|
+
export default InfoDialog;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { prettyPrintJson } from '../vendor/prettyPrintJson.js';
|
|
2
|
+
import defineElement from '../utils/defineElement.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Web component for displaying json in a pretty way.
|
|
6
|
+
*/
|
|
7
|
+
class JsonFormatter extends HTMLElement {
|
|
8
|
+
constructor() {
|
|
9
|
+
super();
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
const json = JSON.parse(this.textContent.length ? this.textContent : '{}');
|
|
13
|
+
const html = prettyPrintJson.toHtml(json);
|
|
14
|
+
this.innerHTML = `<pre class="json-container">${html}</pre>`;
|
|
15
|
+
} catch {
|
|
16
|
+
/* empty */
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
defineElement('nilla-json', JsonFormatter);
|
|
22
|
+
|
|
23
|
+
export default JsonFormatter;
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import ListReorderEvent from '../events/ListReorderEvent.js';
|
|
2
|
+
import BaseComponent from './BaseComponent.js';
|
|
3
|
+
import announce from '../utils/announce.js';
|
|
4
|
+
import defineElement from '../utils/defineElement.js';
|
|
5
|
+
import { getText } from '../utils/locale.js';
|
|
6
|
+
import notifyChange from '../utils/notifyChange.js';
|
|
7
|
+
import randomId from '../utils/randomId.js';
|
|
8
|
+
import renderTemplate from '../utils/renderTemplate.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Enum for identifiers to query DOM elements.
|
|
12
|
+
* @readonly
|
|
13
|
+
* @enum {string}
|
|
14
|
+
*/
|
|
15
|
+
const Elements = Object.freeze({
|
|
16
|
+
AddButton: 'add-button',
|
|
17
|
+
RemoveButton: 'remove-button',
|
|
18
|
+
Template: 'template',
|
|
19
|
+
Container: 'container',
|
|
20
|
+
EmptyMessage: 'empty-message',
|
|
21
|
+
Item: 'item',
|
|
22
|
+
DragHandle: 'drag-handle',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Minimal shape of the SortableJS export used for drag-and-drop reordering.
|
|
27
|
+
* @typedef {{ create: (el: HTMLElement, options: object) => { destroy: () => void } }} SortableLike
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* SortableJS, once registered with `List.useSortable()`.
|
|
32
|
+
* @type {SortableLike|undefined}
|
|
33
|
+
*/
|
|
34
|
+
let sortableLibrary;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Component to manage a list of items that can be added, deleted, and reordered.
|
|
38
|
+
* Items with a `[data-list-drag-handle]` are reordered with the arrow keys on it. Dragging also needs SortableJS, registered
|
|
39
|
+
* with `List.useSortable(Sortable)`.
|
|
40
|
+
*/
|
|
41
|
+
class List extends BaseComponent {
|
|
42
|
+
/**
|
|
43
|
+
* SortableJS instance for the container, when reordering is enabled.
|
|
44
|
+
* @type {{ destroy: () => void }|undefined}
|
|
45
|
+
*/
|
|
46
|
+
#sortable;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Registers SortableJS so lists with drag handles can be reordered, and enables it on lists already in the page.
|
|
50
|
+
* SortableJS is passed in rather than imported, so it is only needed by apps that use reordering.
|
|
51
|
+
* @param {SortableLike} sortable SortableJS default export.
|
|
52
|
+
*/
|
|
53
|
+
static useSortable(sortable) {
|
|
54
|
+
sortableLibrary = sortable;
|
|
55
|
+
document.querySelectorAll('nilla-list').forEach((list) => {
|
|
56
|
+
if (list instanceof List) {
|
|
57
|
+
list.enableSorting();
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Placeholder for substituting a unique index for the item.
|
|
64
|
+
* @type {string}
|
|
65
|
+
*/
|
|
66
|
+
#indexPlaceholder = '';
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Initialize a new instance of the List component.
|
|
70
|
+
*/
|
|
71
|
+
constructor() {
|
|
72
|
+
super('list');
|
|
73
|
+
|
|
74
|
+
this.#indexPlaceholder = this.dataset.indexPlaceholder;
|
|
75
|
+
|
|
76
|
+
// register listener for the add button
|
|
77
|
+
const btn = this.getElement(Elements.AddButton);
|
|
78
|
+
if (btn) {
|
|
79
|
+
btn.addEventListener('click', this);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// render the empty message initially
|
|
83
|
+
this.#renderEmptyMessage();
|
|
84
|
+
|
|
85
|
+
// add event listener to handle clicks on remove buttons within the container
|
|
86
|
+
const container = this.getElement(Elements.Container);
|
|
87
|
+
if (container) {
|
|
88
|
+
container.addEventListener('click', (event) => {
|
|
89
|
+
if (event.target.closest('button')?.matches(`[data-list-${Elements.RemoveButton}]`)) {
|
|
90
|
+
event.preventDefault();
|
|
91
|
+
event.stopPropagation();
|
|
92
|
+
|
|
93
|
+
/** @type {HTMLElement} */
|
|
94
|
+
const item = event.target.closest(`[data-list-${Elements.Item}]`);
|
|
95
|
+
if (item) {
|
|
96
|
+
this.#moveFocusFrom(item);
|
|
97
|
+
item.remove();
|
|
98
|
+
this.#renderEmptyMessage();
|
|
99
|
+
notifyChange(this);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
container.addEventListener('keydown', event => this.#onHandleKey(event));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Moves focus out of an item that's about to be removed, so keyboard users don't lose their place: to the remove button
|
|
109
|
+
* of the next item, or the one before, or else to the add button.
|
|
110
|
+
* @param {HTMLElement} item Item that will be removed.
|
|
111
|
+
*/
|
|
112
|
+
#moveFocusFrom(item) {
|
|
113
|
+
if (item.contains(document.activeElement)) {
|
|
114
|
+
const neighbor = item.nextElementSibling ?? item.previousElementSibling;
|
|
115
|
+
const target = this.getElements(Elements.RemoveButton).find(x => neighbor?.contains(x)) ?? this.getElement(Elements.AddButton);
|
|
116
|
+
target?.focus();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Moves an item up or down when an arrow key is pressed on its drag handle.
|
|
122
|
+
* @param {KeyboardEvent} event Key down event.
|
|
123
|
+
*/
|
|
124
|
+
#onHandleKey(event) {
|
|
125
|
+
// a handle can be a whole row, with fields that use the arrow keys themselves
|
|
126
|
+
const handle = /** @type {HTMLElement} */ (event.target);
|
|
127
|
+
const item = handle.matches(`[data-list-${Elements.DragHandle}]`) ? handle.closest(`[data-list-${Elements.Item}]`) : null;
|
|
128
|
+
if (item?.parentElement !== event.currentTarget || !['ArrowUp', 'ArrowDown'].includes(event.key)) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
event.preventDefault();
|
|
133
|
+
const up = event.key === 'ArrowUp';
|
|
134
|
+
const neighbor = up ? item.previousElementSibling : item.nextElementSibling;
|
|
135
|
+
if (neighbor) {
|
|
136
|
+
neighbor[up ? 'before' : 'after'](item);
|
|
137
|
+
// moving an element takes focus off it
|
|
138
|
+
handle.focus();
|
|
139
|
+
this.#reordered();
|
|
140
|
+
const items = [...item.parentElement.children];
|
|
141
|
+
announce(renderTemplate(getText('list.moved', this), { position: items.indexOf(item) + 1, count: items.length }));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Tells the page that the items are in a new order.
|
|
147
|
+
*/
|
|
148
|
+
#reordered() {
|
|
149
|
+
this.dispatchEvent(new ListReorderEvent());
|
|
150
|
+
notifyChange(this);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Enables reordering each time the list is added to the page, since removing it destroys the SortableJS instance.
|
|
155
|
+
*/
|
|
156
|
+
connectedCallback() {
|
|
157
|
+
this.enableSorting();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Enables drag-and-drop reordering when SortableJS is registered and the template or items have a drag handle.
|
|
162
|
+
* Does nothing if reordering is already enabled.
|
|
163
|
+
*/
|
|
164
|
+
enableSorting() {
|
|
165
|
+
const container = this.getElement(Elements.Container);
|
|
166
|
+
if (!sortableLibrary || this.#sortable || !container) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const handleSelector = `[data-list-${Elements.DragHandle}]`;
|
|
171
|
+
const template = /** @type {HTMLTemplateElement|undefined} */ (this.getElement(Elements.Template));
|
|
172
|
+
if (!(container.querySelector(handleSelector) || template?.content?.querySelector(handleSelector))) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
this.#sortable = sortableLibrary.create(container, {
|
|
177
|
+
handle: handleSelector,
|
|
178
|
+
animation: 150,
|
|
179
|
+
ghostClass: 'is-dragging',
|
|
180
|
+
draggable: `[data-list-${Elements.Item}]`,
|
|
181
|
+
onEnd: () => {
|
|
182
|
+
this.#renderEmptyMessage();
|
|
183
|
+
this.#reordered();
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Clean up when removing component.
|
|
190
|
+
*/
|
|
191
|
+
disconnectedCallback() {
|
|
192
|
+
this.#sortable?.destroy();
|
|
193
|
+
this.#sortable = undefined;
|
|
194
|
+
super.disconnectedCallback();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Copy the node when the button is clicked and append it to the DOM.
|
|
199
|
+
*/
|
|
200
|
+
async handleEvent() {
|
|
201
|
+
const template = this.getElement(Elements.Template);
|
|
202
|
+
const container = this.getElement(Elements.Container);
|
|
203
|
+
|
|
204
|
+
if (template && container) {
|
|
205
|
+
let html = template.innerHTML;
|
|
206
|
+
if (this.#indexPlaceholder) {
|
|
207
|
+
// create a guid to use as a unique index for the copy
|
|
208
|
+
const index = randomId();
|
|
209
|
+
html = html.replaceAll(this.#indexPlaceholder, index);
|
|
210
|
+
}
|
|
211
|
+
container.insertAdjacentHTML('beforeend', html);
|
|
212
|
+
this.#renderEmptyMessage();
|
|
213
|
+
notifyChange(this);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Display a message if the list is empty, or hide it if there are items in the list.
|
|
219
|
+
*/
|
|
220
|
+
#renderEmptyMessage() {
|
|
221
|
+
const container = this.getElement(Elements.Container);
|
|
222
|
+
const emptyMessage = this.getElement(Elements.EmptyMessage);
|
|
223
|
+
|
|
224
|
+
if (container && emptyMessage) {
|
|
225
|
+
// Show the empty message if the list is empty
|
|
226
|
+
if (container.children.length === 0) {
|
|
227
|
+
emptyMessage.hidden = false;
|
|
228
|
+
} else {
|
|
229
|
+
emptyMessage.hidden = true;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
defineElement('nilla-list', List);
|
|
236
|
+
|
|
237
|
+
export default List;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import Sortable from 'sortablejs';
|
|
2
|
+
import List from './List.js';
|
|
3
|
+
|
|
4
|
+
// Registers SortableJS with nilla-list so lists with drag handles can be reordered.
|
|
5
|
+
// Import this entry instead of `./List.js` when you want reordering. Requires the `sortablejs` package.
|
|
6
|
+
List.useSortable(Sortable);
|
|
7
|
+
|
|
8
|
+
export default List;
|