@avlcodemonkey/nilla-components 0.0.0-stage → 0.0.1

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.
Files changed (94) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +21 -0
  3. package/README.md +219 -3
  4. package/THIRD_PARTY_NOTICES.md +48 -0
  5. package/css/alert.css +48 -0
  6. package/css/autocomplete.css +38 -0
  7. package/css/dialog.css +61 -0
  8. package/css/file-to-textarea.css +8 -0
  9. package/css/html-editor.css +172 -0
  10. package/css/json.css +44 -0
  11. package/css/list.css +37 -0
  12. package/css/nav-toggle.css +92 -0
  13. package/css/nilla.css +16 -0
  14. package/css/pjax.css +58 -0
  15. package/css/slider-input.css +16 -0
  16. package/css/table.css +99 -0
  17. package/css/tokens.css +44 -0
  18. package/css/unsaved-changes.css +10 -0
  19. package/css/vendor/wysi.css +406 -0
  20. package/docs/llms.txt +319 -0
  21. package/package.json +121 -5
  22. package/src/components/Alert.js +24 -0
  23. package/src/components/Autocomplete.js +127 -0
  24. package/src/components/BaseComponent.js +78 -0
  25. package/src/components/BaseDialog.js +151 -0
  26. package/src/components/ConfirmDialog.js +34 -0
  27. package/src/components/CopyToClipboard.js +66 -0
  28. package/src/components/DateFormatter.js +51 -0
  29. package/src/components/DateTimeInput.js +63 -0
  30. package/src/components/DisplayToggle.js +53 -0
  31. package/src/components/FileToTextarea.js +81 -0
  32. package/src/components/HtmlEditor.js +309 -0
  33. package/src/components/InfoDialog.js +38 -0
  34. package/src/components/JsonFormatter.js +23 -0
  35. package/src/components/List.js +237 -0
  36. package/src/components/ListSortable.js +8 -0
  37. package/src/components/NavToggle.js +119 -0
  38. package/src/components/PJax.js +888 -0
  39. package/src/components/Share.js +41 -0
  40. package/src/components/SliderInput.js +26 -0
  41. package/src/components/Table.js +758 -0
  42. package/src/components/TimeOffsetSelect.js +29 -0
  43. package/src/components/UnsavedChanges.js +187 -0
  44. package/src/constants/Fetch.js +7 -0
  45. package/src/constants/HttpHeaders.js +19 -0
  46. package/src/constants/HttpMethods.js +14 -0
  47. package/src/constants/SortDirection.js +11 -0
  48. package/src/constants/TableElements.js +25 -0
  49. package/src/constants/TableSettings.js +14 -0
  50. package/src/errors/FetchError.js +7 -0
  51. package/src/events/ListReorderEvent.js +19 -0
  52. package/src/events/PJaxErrorEvent.js +38 -0
  53. package/src/events/PJaxNavigatingEvent.js +46 -0
  54. package/src/index.js +26 -0
  55. package/src/locales/en.json +55 -0
  56. package/src/locales/es.js +9 -0
  57. package/src/locales/es.json +55 -0
  58. package/src/models/TableSort.js +20 -0
  59. package/src/utils/ajaxHeaders.js +10 -0
  60. package/src/utils/announce.js +40 -0
  61. package/src/utils/defineElement.js +13 -0
  62. package/src/utils/editor/blockTools.js +256 -0
  63. package/src/utils/editor/elements.js +18 -0
  64. package/src/utils/editor/input.js +350 -0
  65. package/src/utils/editor/selection.js +125 -0
  66. package/src/utils/editor/tableTools.js +497 -0
  67. package/src/utils/escape.js +20 -0
  68. package/src/utils/fetchJsonArray.js +29 -0
  69. package/src/utils/filterArray.js +18 -0
  70. package/src/utils/formActionUrl.js +10 -0
  71. package/src/utils/formData.js +118 -0
  72. package/src/utils/index.js +18 -0
  73. package/src/utils/indexedCompare.js +18 -0
  74. package/src/utils/isSameOrigin.js +12 -0
  75. package/src/utils/locale.js +36 -0
  76. package/src/utils/notifyChange.js +10 -0
  77. package/src/utils/numberSetting.js +14 -0
  78. package/src/utils/pageLanguage.js +13 -0
  79. package/src/utils/parseUtcDate.js +22 -0
  80. package/src/utils/randomId.js +17 -0
  81. package/src/utils/registerTabTrap.js +60 -0
  82. package/src/utils/renderTemplate.js +44 -0
  83. package/src/utils/requestTimeout.js +12 -0
  84. package/src/utils/response.js +28 -0
  85. package/src/utils/sortedCompare.js +67 -0
  86. package/src/utils/storage.js +40 -0
  87. package/src/vendor/autocomplete.js +515 -0
  88. package/src/vendor/formatDate.js +236 -0
  89. package/src/vendor/licenses/autocomplete.LICENSE.md +21 -0
  90. package/src/vendor/licenses/fecha.LICENSE.md +21 -0
  91. package/src/vendor/licenses/pretty-print-json.LICENSE.md +21 -0
  92. package/src/vendor/licenses/wysi.LICENSE.md +21 -0
  93. package/src/vendor/prettyPrintJson.js +108 -0
  94. package/src/vendor/wyzi.js +2024 -0
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Editor tools for inline code, code blocks and quotes.
3
+ */
4
+
5
+ import { LineElements } from './elements.js';
6
+ import { applyEdit, closestInEditor, getEditorRange, placeCaretAtEnd, setRange } from './selection.js';
7
+
8
+ /**
9
+ * Elements that start on their own line.
10
+ * @type {string}
11
+ */
12
+ const BlockSelector = `${LineElements}, ul, ol, hr, table`;
13
+
14
+ /**
15
+ * Elements that inline code can sit inside of.
16
+ * @type {string}
17
+ */
18
+ const TextBlockSelector = 'p, h1, h2, h3, h4, h5, h6, li, td, th, blockquote';
19
+
20
+ /**
21
+ * Content that would be lost by turning it into code.
22
+ * @type {string}
23
+ */
24
+ const UnconvertibleSelector = 'a, img, input';
25
+
26
+ /**
27
+ * Get the text of a node, with a new line for each line break and block element.
28
+ * Non-breaking spaces become normal spaces, since they break code that readers copy.
29
+ * @param {Node} node Node to read.
30
+ * @returns {string} Text of the node.
31
+ */
32
+ export function getPlainText(node) {
33
+ if (node.nodeType === 3) {
34
+ return node.nodeValue.replaceAll('\u00a0', ' ');
35
+ }
36
+ if (node.nodeName === 'BR') {
37
+ return '\n';
38
+ }
39
+ let text = '';
40
+ node.childNodes.forEach((child) => {
41
+ if (child.nodeType === 1 && child.matches(BlockSelector) && text && !text.endsWith('\n')) {
42
+ text += '\n';
43
+ }
44
+ text += getPlainText(child);
45
+ });
46
+ return text;
47
+ }
48
+
49
+ /**
50
+ * Get the direct children of a container that the selection touches.
51
+ * @param {Range} range Selected range.
52
+ * @param {HTMLElement} container Element whose children are wanted.
53
+ * @returns {Node[]} Selected children.
54
+ */
55
+ export function getSelectedBlocks(range, container) {
56
+ const findChild = (node, offset) => {
57
+ if (node === container) {
58
+ return container.childNodes[Math.max(Math.min(offset, container.childNodes.length - 1), 0)];
59
+ }
60
+ let child = node;
61
+ while (child.parentNode !== container) {
62
+ child = child.parentNode;
63
+ }
64
+ return child;
65
+ };
66
+
67
+ const first = findChild(range.startContainer, range.startOffset);
68
+ // end positions in the container point past the last selected child
69
+ let last = findChild(range.endContainer, range.endContainer === container ? range.endOffset - 1 : range.endOffset);
70
+ // selecting a whole line can end at the very start of the next one
71
+ if (!range.collapsed && range.endContainer !== container && last !== first) {
72
+ const selectedPart = document.createRange();
73
+ selectedPart.setStart(last, 0);
74
+ selectedPart.setEnd(range.endContainer, range.endOffset);
75
+ if (!selectedPart.toString()) {
76
+ last = last.previousSibling;
77
+ }
78
+ }
79
+ if (!first) {
80
+ return [];
81
+ }
82
+
83
+ const blocks = [first];
84
+ while (blocks.at(-1) !== last && blocks.at(-1).nextSibling) {
85
+ blocks.push(blocks.at(-1).nextSibling);
86
+ }
87
+ return blocks;
88
+ }
89
+
90
+ /**
91
+ * Wrap the selected text in inline code, or remove the inline code around the selection.
92
+ * @param {HTMLElement} editor Editable region.
93
+ */
94
+ export function toggleInlineCode(editor) {
95
+ const range = getEditorRange(editor);
96
+ if (!range || closestInEditor(range.startContainer, 'pre', editor)) {
97
+ return;
98
+ }
99
+
100
+ const existing = closestInEditor(range.startContainer, 'code', editor);
101
+ if (existing) {
102
+ applyEdit(editor, () => {
103
+ const first = existing.firstChild;
104
+ const last = existing.lastChild;
105
+ existing.replaceWith(...existing.childNodes);
106
+ if (first) {
107
+ const selected = document.createRange();
108
+ selected.setStartBefore(first);
109
+ selected.setEndAfter(last);
110
+ setRange(selected);
111
+ }
112
+ });
113
+ return;
114
+ }
115
+
116
+ // inline code has to start and end in the same block, otherwise it would replace everything in between
117
+ const block = closestInEditor(range.startContainer, TextBlockSelector, editor);
118
+ const text = range.toString();
119
+ if (!text || !block || block !== closestInEditor(range.endContainer, TextBlockSelector, editor)
120
+ || range.cloneContents().querySelector(`${UnconvertibleSelector}, br`)) {
121
+ return;
122
+ }
123
+
124
+ applyEdit(editor, () => {
125
+ const code = document.createElement('code');
126
+ code.textContent = text.replaceAll('\u00a0', ' ');
127
+ range.deleteContents();
128
+ range.insertNode(code);
129
+ const selected = document.createRange();
130
+ selected.selectNodeContents(code);
131
+ setRange(selected);
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Turn a code block back into a paragraph for each line.
137
+ * @param {HTMLElement} editor Editable region.
138
+ * @param {HTMLElement} pre Code block.
139
+ */
140
+ function removeCodeBlock(editor, pre) {
141
+ applyEdit(editor, () => {
142
+ const paragraphs = getPlainText(pre).replace(/\n$/, '').split('\n').map((line) => {
143
+ const paragraph = document.createElement('p');
144
+ if (line) {
145
+ paragraph.textContent = line;
146
+ } else {
147
+ paragraph.appendChild(document.createElement('br'));
148
+ }
149
+ return paragraph;
150
+ });
151
+ pre.replaceWith(...paragraphs);
152
+ placeCaretAtEnd(paragraphs.at(-1));
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Turn the selected paragraphs and headings into a code block, or turn the current code block back into paragraphs.
158
+ * Lists, tables, links and images are left alone, since a code block can't hold them.
159
+ * @param {HTMLElement} editor Editable region.
160
+ */
161
+ export function toggleCodeBlock(editor) {
162
+ const range = getEditorRange(editor);
163
+ if (!range) {
164
+ return;
165
+ }
166
+
167
+ const pre = closestInEditor(range.startContainer, 'pre', editor);
168
+ if (pre) {
169
+ removeCodeBlock(editor, pre);
170
+ return;
171
+ }
172
+
173
+ const quote = closestInEditor(range.startContainer, 'blockquote', editor);
174
+ const container = quote?.contains(range.endContainer) ? quote : editor;
175
+ const blocks = getSelectedBlocks(range, container);
176
+ const canConvert = block => block.nodeType === 3
177
+ || (block.matches('p, h1, h2, h3, h4, h5, h6') && !block.querySelector(UnconvertibleSelector));
178
+ if (!blocks.length || !blocks.every(canConvert)) {
179
+ return;
180
+ }
181
+
182
+ applyEdit(editor, () => {
183
+ const text = blocks.map(block => getPlainText(block).replace(/\n$/, '')).join('\n');
184
+ const code = document.createElement('code');
185
+ if (text) {
186
+ code.textContent = text;
187
+ } else {
188
+ code.appendChild(document.createElement('br'));
189
+ }
190
+ const block = document.createElement('pre');
191
+ block.appendChild(code);
192
+ blocks[0].before(block);
193
+ blocks.forEach(node => node.remove());
194
+ placeCaretAtEnd(code);
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Put the selected blocks in a quote, or take the content back out of the current quote.
200
+ * @param {HTMLElement} editor Editable region.
201
+ */
202
+ export function toggleQuote(editor) {
203
+ const range = getEditorRange(editor);
204
+ if (!range || closestInEditor(range.startContainer, 'table', editor)) {
205
+ return;
206
+ }
207
+
208
+ const isInline = node => node.nodeType === 3 || !node.matches(BlockSelector);
209
+ const quote = closestInEditor(range.startContainer, 'blockquote', editor);
210
+ if (quote) {
211
+ applyEdit(editor, () => {
212
+ const content = [];
213
+ let paragraph;
214
+ [...quote.childNodes].forEach((node) => {
215
+ if (!isInline(node)) {
216
+ paragraph = undefined;
217
+ content.push(node);
218
+ } else if (paragraph || node.nodeType !== 3 || node.nodeValue.trim()) {
219
+ if (!paragraph) {
220
+ paragraph = document.createElement('p');
221
+ content.push(paragraph);
222
+ }
223
+ paragraph.appendChild(node);
224
+ }
225
+ });
226
+ quote.replaceWith(...content);
227
+ if (content.length) {
228
+ placeCaretAtEnd(content.at(-1));
229
+ }
230
+ });
231
+ return;
232
+ }
233
+
234
+ const blocks = getSelectedBlocks(range, editor);
235
+ if (!blocks.length) {
236
+ return;
237
+ }
238
+ applyEdit(editor, () => {
239
+ const wrapper = document.createElement('blockquote');
240
+ blocks[0].before(wrapper);
241
+ let paragraph;
242
+ blocks.forEach((node) => {
243
+ if (isInline(node)) {
244
+ if (!paragraph) {
245
+ paragraph = document.createElement('p');
246
+ wrapper.appendChild(paragraph);
247
+ }
248
+ paragraph.appendChild(node);
249
+ } else {
250
+ paragraph = undefined;
251
+ wrapper.appendChild(node);
252
+ }
253
+ });
254
+ placeCaretAtEnd(wrapper);
255
+ });
256
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Knowledge about elements shared by the HTML editor tools.
3
+ */
4
+
5
+ /**
6
+ * Elements that hold their own line, whether in the editor or in pasted content.
7
+ * @type {string}
8
+ */
9
+ export const LineElements = 'p, h1, h2, h3, h4, h5, h6, li, pre, blockquote, tr';
10
+
11
+ /**
12
+ * Check for a bold element that isn't bold, which some apps, such as Google Docs, wrap their content in.
13
+ * @param {Element} element Element to check.
14
+ * @returns {boolean} True if the element should not be treated as bold.
15
+ */
16
+ export function isUnboldWrapper(element) {
17
+ return element.nodeName === 'B' && /font-weight\s*:\s*(normal|400)/i.test(element.getAttribute('style') ?? '');
18
+ }
@@ -0,0 +1,350 @@
1
+ /**
2
+ * Keyboard and paste handling for code blocks, quotes and table cells.
3
+ */
4
+
5
+ import { getPlainText } from './blockTools.js';
6
+ import { isUnboldWrapper, LineElements } from './elements.js';
7
+ import { applyEdit, closestInEditor, crossesCells, getEditorRange, insertAtRange, placeCaret, placeCaretAtEnd, setRange } from './selection.js';
8
+ import { runTableAction } from './tableTools.js';
9
+
10
+ /**
11
+ * Elements that can be kept when pasting into a table cell, and the element each becomes.
12
+ * @readonly
13
+ * @enum {string}
14
+ */
15
+ const CellElements = Object.freeze({
16
+ A: 'a',
17
+ B: 'strong',
18
+ BR: 'br',
19
+ CODE: 'code',
20
+ DEL: 's',
21
+ EM: 'em',
22
+ I: 'em',
23
+ S: 's',
24
+ STRIKE: 's',
25
+ STRONG: 'strong',
26
+ });
27
+
28
+ /**
29
+ * Pasted elements that start a new line in a table cell.
30
+ * @type {string}
31
+ */
32
+ const PastedBlockSelector = `${LineElements}, div, td, th`;
33
+
34
+ /**
35
+ * Insert a new line inside the element the caret is in.
36
+ * @param {HTMLElement} editor Editable region.
37
+ * @param {Range} range Selected range.
38
+ * @param {HTMLElement} container Code block or table cell.
39
+ * @param {() => Node} createLine Creates the node that ends a line.
40
+ */
41
+ function insertNewLine(editor, range, container, createLine) {
42
+ applyEdit(editor, () => {
43
+ const line = createLine();
44
+ insertAtRange(range, line);
45
+ // new lines at the very end only show up if something follows them
46
+ const rest = document.createRange();
47
+ rest.setStartAfter(line);
48
+ rest.setEnd(container, container.childNodes.length);
49
+ if (!rest.toString() && !rest.cloneContents().querySelector('br')) {
50
+ line.parentNode.insertBefore(createLine(), line.nextSibling);
51
+ }
52
+ });
53
+ }
54
+
55
+ /**
56
+ * Handle the Enter key in code blocks, quotes and tables. Ctrl+Enter or Cmd+Enter leaves them.
57
+ * @param {KeyboardEvent} event Key down event.
58
+ * @param {HTMLElement} editor Editable region.
59
+ * @param {Range} range Selected range.
60
+ */
61
+ function handleEnter(event, editor, range) {
62
+ if (crossesCells(editor, range) && !event.ctrlKey && !event.metaKey) {
63
+ event.preventDefault();
64
+ return;
65
+ }
66
+
67
+ const pre = closestInEditor(range.startContainer, 'pre', editor);
68
+ const cell = closestInEditor(range.startContainer, 'td, th', editor);
69
+
70
+ if (event.ctrlKey || event.metaKey) {
71
+ const container = cell?.closest('table') ?? pre ?? closestInEditor(range.startContainer, 'blockquote', editor);
72
+ if (container) {
73
+ event.preventDefault();
74
+ applyEdit(editor, () => {
75
+ const paragraph = document.createElement('p');
76
+ paragraph.appendChild(document.createElement('br'));
77
+ container.after(paragraph);
78
+ placeCaret(paragraph, 0);
79
+ });
80
+ }
81
+ } else if (pre) {
82
+ event.preventDefault();
83
+ insertNewLine(editor, range, pre, () => document.createTextNode('\n'));
84
+ } else if (cell && !closestInEditor(range.startContainer, 'li', editor)) {
85
+ event.preventDefault();
86
+ insertNewLine(editor, range, cell, () => document.createElement('br'));
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Move between table cells with Tab and Shift+Tab. Tab in the last cell adds a row, unless that row is empty.
92
+ * @param {KeyboardEvent} event Key down event.
93
+ * @param {HTMLElement} editor Editable region.
94
+ * @param {Range} range Selected range.
95
+ */
96
+ function handleTab(event, editor, range) {
97
+ const cell = closestInEditor(range.startContainer, 'td, th', editor);
98
+ if (!cell) {
99
+ return;
100
+ }
101
+ const table = cell.closest('table');
102
+ const cells = [...table.querySelectorAll('td, th')].filter(x => x.closest('table') === table);
103
+ const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)];
104
+ if (next) {
105
+ event.preventDefault();
106
+ placeCaretAtEnd(next);
107
+ } else if (!event.shiftKey && cell.parentElement.textContent.trim()) {
108
+ const rowCount = table.rows.length;
109
+ const rowIndex = cell.parentElement.rowIndex;
110
+ runTableAction(editor, 'rowBelow');
111
+ // merged tables don't get new rows, so Tab is left to move focus on
112
+ if (table.rows.length > rowCount) {
113
+ event.preventDefault();
114
+ placeCaret(table.rows[rowIndex + 1].cells[0], 0);
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Handle keys the browser would get wrong in code blocks, quotes and tables.
121
+ * @param {KeyboardEvent} event Key down event.
122
+ * @param {HTMLElement} editor Editable region.
123
+ */
124
+ export function handleEditorKeydown(event, editor) {
125
+ if (event.isComposing) {
126
+ return;
127
+ }
128
+
129
+ const key = event.key.toLowerCase();
130
+ const range = getEditorRange(editor);
131
+ if (!range) {
132
+ return;
133
+ }
134
+ if (key === 'enter') {
135
+ handleEnter(event, editor, range);
136
+ } else if (key === 'tab') {
137
+ handleTab(event, editor, range);
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Handle changes the browser is about to make, whether from typing, cutting, dropping, or the edit menu.
143
+ * @param {InputEvent} event Before input event.
144
+ * @param {HTMLElement} editor Editable region.
145
+ */
146
+ export function handleEditorBeforeInput(event, editor) {
147
+ if (/^(insert|delete)/.test(event.inputType) && crossesCells(editor, getEditorRange(editor))) {
148
+ event.preventDefault();
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Get the nearest sibling that isn't a comment.
154
+ * @param {Node} node Node to start from.
155
+ * @param {'previousSibling'|'nextSibling'} direction Direction to look in.
156
+ * @returns {Node|null} Sibling, or null.
157
+ */
158
+ function getSibling(node, direction) {
159
+ let sibling = node[direction];
160
+ while (sibling?.nodeType === 8) {
161
+ sibling = sibling[direction];
162
+ }
163
+ return sibling;
164
+ }
165
+
166
+ /**
167
+ * Check whether a pasted node sits on the same line as its neighbors.
168
+ * @param {Node|null} node Node to check.
169
+ * @returns {boolean} True for text and inline elements.
170
+ */
171
+ function isInline(node) {
172
+ return !!node && (node.nodeType === 3 || (node.nodeType === 1 && !node.matches(`${PastedBlockSelector}, br, table, ul, ol, tbody`)));
173
+ }
174
+
175
+ /**
176
+ * Check whether the last thing in the pasted content is a line break.
177
+ * @param {Node} node Content to check.
178
+ * @returns {boolean} True if it ends with a line break.
179
+ */
180
+ function endsWithBreak(node) {
181
+ for (let child = node.lastChild; child; child = child.previousSibling) {
182
+ if (child.nodeName === 'BR') {
183
+ return true;
184
+ }
185
+ if (child.textContent) {
186
+ return child.nodeType === 1 && endsWithBreak(child);
187
+ }
188
+ }
189
+ return false;
190
+ }
191
+
192
+ /**
193
+ * Start a new line in the pasted content, unless it's empty or already on a new line.
194
+ * @param {Node} target Node to add the line break to.
195
+ * @param {DocumentFragment} root All of the pasted content.
196
+ */
197
+ function addLineBreak(target, root) {
198
+ if (root.textContent && !endsWithBreak(root)) {
199
+ target.appendChild(document.createElement('br'));
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Copy pasted text, dropping line breaks that are only source formatting.
205
+ * @param {Text} node Pasted text.
206
+ * @param {Node} target Node to add the copy to.
207
+ */
208
+ function copyText(node, target) {
209
+ const text = node.nodeValue;
210
+ // line breaks between blocks are formatting, but between words they're a space
211
+ const isFormatting = !text.trim() && text.includes('\n')
212
+ && !(isInline(getSibling(node, 'previousSibling')) && isInline(getSibling(node, 'nextSibling')));
213
+ if (!isFormatting) {
214
+ target.appendChild(document.createTextNode(text.replace(/[\r\n]+/g, ' ')));
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Copy a pasted element, keeping it only if it's a link or basic formatting. Its content is kept either way.
220
+ * @param {Element} element Pasted element.
221
+ * @param {Node} target Node to add the copy to.
222
+ * @param {DocumentFragment} root All of the copied content.
223
+ */
224
+ function copyElement(element, target, root) {
225
+ const tag = isUnboldWrapper(element) ? undefined : CellElements[element.nodeName];
226
+ if (!tag) {
227
+ copyCellContent(element, target, root);
228
+ return;
229
+ }
230
+
231
+ const copy = document.createElement(tag);
232
+ const href = element.getAttribute('href');
233
+ if (tag === 'a' && href && !/^\s*(javascript|data|vbscript):/i.test(href)) {
234
+ copy.setAttribute('href', href);
235
+ }
236
+ // added before its content, so line breaks inside it can see what came earlier
237
+ target.appendChild(copy);
238
+ copyCellContent(element, copy, root);
239
+ if (tag !== 'br' && !copy.hasChildNodes()) {
240
+ copy.remove();
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Copy pasted content, keeping only what fits in a table cell: text, line breaks, links and basic formatting.
246
+ * @param {Node} source Pasted content.
247
+ * @param {Node} target Node to add the copy to.
248
+ * @param {DocumentFragment} root All of the copied content.
249
+ */
250
+ function copyCellContent(source, target, root) {
251
+ source.childNodes.forEach((child) => {
252
+ if (child.nodeType === 3) {
253
+ copyText(child, target);
254
+ } else if (child.nodeType === 1 && !child.matches('style, script, title, meta')) {
255
+ const isBlock = child.matches(PastedBlockSelector);
256
+ if (isBlock) {
257
+ addLineBreak(target, root);
258
+ }
259
+ copyElement(child, target, root);
260
+ const next = getSibling(child, 'nextSibling');
261
+ if (isBlock && isInline(next) && next.textContent.trim()) {
262
+ addLineBreak(target, root);
263
+ }
264
+ }
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Build the content to insert into a table cell from the clipboard.
270
+ * @param {DataTransfer} clipboardData Clipboard content.
271
+ * @returns {DocumentFragment} Content to insert.
272
+ */
273
+ function getCellFragment(clipboardData) {
274
+ const fragment = document.createDocumentFragment();
275
+ const html = clipboardData.getData('text/html');
276
+ if (html) {
277
+ const template = document.createElement('template');
278
+ template.innerHTML = html.trim();
279
+ copyCellContent(template.content, fragment, fragment);
280
+ return fragment;
281
+ }
282
+
283
+ const text = clipboardData.getData('text/plain');
284
+ if (text) {
285
+ text.split(/\r\n?|\n/).forEach((line, index) => {
286
+ if (index) {
287
+ fragment.appendChild(document.createElement('br'));
288
+ }
289
+ fragment.appendChild(document.createTextNode(line));
290
+ });
291
+ }
292
+ return fragment;
293
+ }
294
+
295
+ /**
296
+ * Move a caret at the end of inline code out of it, since what's pasted there is meant to follow the code.
297
+ * @param {HTMLElement} editor Editable region.
298
+ * @param {Range} range Selected range.
299
+ */
300
+ function leaveInlineCode(editor, range) {
301
+ const code = closestInEditor(range.startContainer, 'code', editor);
302
+ if (!code || !range.collapsed || closestInEditor(code, 'pre', editor)) {
303
+ return;
304
+ }
305
+ const rest = document.createRange();
306
+ rest.setStart(range.startContainer, range.startOffset);
307
+ rest.setEnd(code, code.childNodes.length);
308
+ if (!rest.toString()) {
309
+ range.setStartAfter(code);
310
+ range.collapse(true);
311
+ setRange(range);
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Handle pasting into code and table cells, where pasted formatting doesn't fit.
317
+ * @param {ClipboardEvent} event Paste event.
318
+ * @param {HTMLElement} editor Editable region.
319
+ * @returns {boolean} True if the paste was handled.
320
+ */
321
+ export function handleEditorPaste(event, editor) {
322
+ const range = getEditorRange(editor);
323
+ if (!range) {
324
+ return false;
325
+ }
326
+ if (crossesCells(editor, range)) {
327
+ event.preventDefault();
328
+ return true;
329
+ }
330
+
331
+ leaveInlineCode(editor, range);
332
+
333
+ let content;
334
+ if (closestInEditor(range.startContainer, 'pre, code', editor)) {
335
+ const text = event.clipboardData.getData('text/plain');
336
+ content = text && document.createTextNode(getPlainText(document.createTextNode(text)).replace(/\r\n?/g, '\n'));
337
+ } else if (closestInEditor(range.startContainer, 'td, th', editor)) {
338
+ const fragment = getCellFragment(event.clipboardData);
339
+ content = fragment.hasChildNodes() && fragment;
340
+ } else {
341
+ return false;
342
+ }
343
+
344
+ event.preventDefault();
345
+ // nothing usable on the clipboard, such as an image, leaves the selection alone
346
+ if (content) {
347
+ applyEdit(editor, () => insertAtRange(range, content));
348
+ }
349
+ return true;
350
+ }