@widgetic/design-system 0.5.39 → 0.5.41

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 (143) hide show
  1. package/README.md +73 -0
  2. package/dist/components/ContentRefreshOverlay.svelte +103 -0
  3. package/dist/components/ContentRefreshOverlay.svelte.d.ts +18 -0
  4. package/dist/components/chat/Composer.svelte +381 -20
  5. package/dist/components/chat/Composer.svelte.d.ts +88 -1
  6. package/dist/components/chat/PlanCard.svelte +218 -88
  7. package/dist/components/chat/PlanCard.svelte.d.ts +11 -0
  8. package/dist/components/chat/QuestionCard.svelte +180 -70
  9. package/dist/components/chat/QuestionCard.svelte.d.ts +28 -2
  10. package/dist/components/chat/QuestionCardSummary.svelte +96 -0
  11. package/dist/components/chat/QuestionCardSummary.svelte.d.ts +20 -0
  12. package/dist/components/chat/QueueCard.svelte +185 -0
  13. package/dist/components/chat/QueueCard.svelte.d.ts +40 -0
  14. package/dist/components/chat/composerLogic.d.ts +31 -0
  15. package/dist/components/chat/composerLogic.js +37 -0
  16. package/dist/components/chat/composerReferences.d.ts +28 -0
  17. package/dist/components/chat/composerReferences.js +23 -0
  18. package/dist/components/chat/index.d.ts +8 -3
  19. package/dist/components/chat/index.js +10 -2
  20. package/dist/components/chat/questionCardLogic.d.ts +40 -3
  21. package/dist/components/chat/questionCardLogic.js +54 -3
  22. package/dist/components/chat/queueCardLogic.d.ts +7 -0
  23. package/dist/components/chat/queueCardLogic.js +5 -0
  24. package/dist/components/creator/index.d.ts +1 -2
  25. package/dist/components/creator/index.js +2 -0
  26. package/dist/components/filters/FilterByButton.svelte +2 -1
  27. package/dist/components/index.d.ts +8 -7
  28. package/dist/components/index.js +8 -6
  29. package/dist/components/modals/BaseModal.svelte +14 -4
  30. package/dist/components/navigation/Breadcrumbs.svelte +1 -1
  31. package/dist/components/navigation/breadcrumbSlideIn.d.ts +6 -2
  32. package/dist/components/navigation/breadcrumbSlideIn.js +6 -6
  33. package/dist/components/search-input/SearchInput.svelte +282 -14
  34. package/dist/components/search-input/SearchInput.svelte.d.ts +3 -0
  35. package/dist/components/search-input/index.d.ts +1 -0
  36. package/dist/components/search-input/index.js +1 -0
  37. package/dist/components/search-input/index2.d.ts +4 -0
  38. package/dist/components/search-input/recentSearches.d.ts +12 -0
  39. package/dist/components/search-input/recentSearches.js +124 -0
  40. package/dist/components/toast/ToasterModal.svelte +8 -2
  41. package/dist/components/toast/ToasterModal.svelte.d.ts +2 -0
  42. package/dist/components/ui/chip/chip.svelte +39 -1
  43. package/dist/components/ui/chip/chip.svelte.d.ts +8 -0
  44. package/dist/components/ui/chip/chipProgress.d.ts +14 -0
  45. package/dist/components/ui/chip/chipProgress.js +21 -0
  46. package/dist/components/ui/dropdown-menu/dropdown-menu-content.svelte +1 -1
  47. package/dist/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte +1 -1
  48. package/dist/components/ui/icon-button/icon-button.svelte +2 -0
  49. package/dist/components/ui/icon-button/icon-button.svelte.d.ts +5 -0
  50. package/dist/components/ui/number-controls/index.d.ts +2 -0
  51. package/dist/components/ui/number-controls/index.js +2 -0
  52. package/dist/components/ui/number-controls/number-controls.svelte +530 -0
  53. package/dist/components/ui/number-controls/number-controls.svelte.d.ts +46 -0
  54. package/dist/components/ui/number-controls/numberControlsSteps.d.ts +17 -0
  55. package/dist/components/ui/number-controls/numberControlsSteps.js +23 -0
  56. package/dist/components/ui/number-controls/numberControlsValueArea.d.ts +29 -0
  57. package/dist/components/ui/number-controls/numberControlsValueArea.js +51 -0
  58. package/dist/components/ui/text-flip/index.d.ts +1 -0
  59. package/dist/components/ui/text-flip/index.js +1 -0
  60. package/dist/components/ui/text-flip/text-flip.svelte +103 -0
  61. package/dist/components/ui/text-flip/text-flip.svelte.d.ts +15 -0
  62. package/dist/components/ui/text-flip/textFlipLogic.d.ts +49 -0
  63. package/dist/components/ui/text-flip/textFlipLogic.js +151 -0
  64. package/dist/inline-completion/completionAnswer.d.ts +11 -0
  65. package/dist/inline-completion/completionAnswer.js +49 -0
  66. package/dist/inline-completion/completionCache.d.ts +24 -0
  67. package/dist/inline-completion/completionCache.js +47 -0
  68. package/dist/inline-completion/completionController.d.ts +61 -0
  69. package/dist/inline-completion/completionController.js +280 -0
  70. package/dist/inline-completion/completionKeys.d.ts +21 -0
  71. package/dist/inline-completion/completionKeys.js +19 -0
  72. package/dist/inline-completion/completionText.d.ts +53 -0
  73. package/dist/inline-completion/completionText.js +79 -0
  74. package/dist/inline-completion/completionTypes.d.ts +71 -0
  75. package/dist/inline-completion/completionTypes.js +5 -0
  76. package/dist/inline-completion/gatewayCompletion.d.ts +37 -0
  77. package/dist/inline-completion/gatewayCompletion.js +77 -0
  78. package/dist/inline-completion/ghostTap.d.ts +19 -0
  79. package/dist/inline-completion/ghostTap.js +20 -0
  80. package/dist/inline-completion/hintMemory.d.ts +43 -0
  81. package/dist/inline-completion/hintMemory.js +90 -0
  82. package/dist/inline-completion/httpSource.d.ts +40 -0
  83. package/dist/inline-completion/httpSource.js +149 -0
  84. package/dist/inline-completion/index.d.ts +30 -0
  85. package/dist/inline-completion/index.js +20 -0
  86. package/dist/inline-completion/inlineCompletionAction.d.ts +54 -0
  87. package/dist/inline-completion/inlineCompletionAction.js +310 -0
  88. package/dist/inline-completion/outcomeReporter.d.ts +49 -0
  89. package/dist/inline-completion/outcomeReporter.js +139 -0
  90. package/dist/inline-completion/promiseLike.d.ts +9 -0
  91. package/dist/inline-completion/promiseLike.js +9 -0
  92. package/dist/prompt-references/ReferenceMenu.svelte +344 -0
  93. package/dist/prompt-references/ReferenceMenu.svelte.d.ts +26 -0
  94. package/dist/prompt-references/index.d.ts +27 -0
  95. package/dist/prompt-references/index.js +20 -0
  96. package/dist/prompt-references/neutralizingSource.d.ts +21 -0
  97. package/dist/prompt-references/neutralizingSource.js +29 -0
  98. package/dist/prompt-references/promptReferences.d.ts +28 -0
  99. package/dist/prompt-references/promptReferences.js +766 -0
  100. package/dist/prompt-references/referenceBadge.d.ts +61 -0
  101. package/dist/prompt-references/referenceBadge.js +82 -0
  102. package/dist/prompt-references/referenceBadgePainter.d.ts +31 -0
  103. package/dist/prompt-references/referenceBadgePainter.js +106 -0
  104. package/dist/prompt-references/referenceEditing.d.ts +60 -0
  105. package/dist/prompt-references/referenceEditing.js +135 -0
  106. package/dist/prompt-references/referenceLabels.d.ts +56 -0
  107. package/dist/prompt-references/referenceLabels.js +215 -0
  108. package/dist/prompt-references/referenceMeasure.d.ts +12 -0
  109. package/dist/prompt-references/referenceMeasure.js +63 -0
  110. package/dist/prompt-references/referenceMenuHost.svelte.d.ts +29 -0
  111. package/dist/prompt-references/referenceMenuHost.svelte.js +43 -0
  112. package/dist/prompt-references/referenceMenuKeys.d.ts +26 -0
  113. package/dist/prompt-references/referenceMenuKeys.js +49 -0
  114. package/dist/prompt-references/referenceMenuPlacement.d.ts +63 -0
  115. package/dist/prompt-references/referenceMenuPlacement.js +66 -0
  116. package/dist/prompt-references/referenceTokens.d.ts +175 -0
  117. package/dist/prompt-references/referenceTokens.js +332 -0
  118. package/dist/prompt-references/referenceTrigger.d.ts +52 -0
  119. package/dist/prompt-references/referenceTrigger.js +100 -0
  120. package/dist/prompt-references/referenceTypes.d.ts +38 -0
  121. package/dist/prompt-references/referenceTypes.js +4 -0
  122. package/dist/prompt-references/sentReferences.d.ts +50 -0
  123. package/dist/prompt-references/sentReferences.js +122 -0
  124. package/dist/styles/tokens.css +58 -0
  125. package/dist/textarea-overlay/index.d.ts +9 -0
  126. package/dist/textarea-overlay/index.js +7 -0
  127. package/dist/textarea-overlay/mirrorSegments.d.ts +31 -0
  128. package/dist/textarea-overlay/mirrorSegments.js +47 -0
  129. package/dist/textarea-overlay/mirrorSizing.d.ts +39 -0
  130. package/dist/textarea-overlay/mirrorSizing.js +40 -0
  131. package/dist/textarea-overlay/textareaOverlay.d.ts +25 -0
  132. package/dist/textarea-overlay/textareaOverlay.js +277 -0
  133. package/dist/utils/overlayMotion.d.ts +1 -0
  134. package/dist/utils/overlayMotion.js +3 -3
  135. package/dist/utils/reducedMotion.d.ts +9 -0
  136. package/dist/utils/reducedMotion.js +13 -0
  137. package/package.json +16 -1
  138. package/dist/components/ui/number-stepper/index.d.ts +0 -3
  139. package/dist/components/ui/number-stepper/index.js +0 -3
  140. package/dist/components/ui/number-stepper/number-stepper.svelte +0 -212
  141. package/dist/components/ui/number-stepper/number-stepper.svelte.d.ts +0 -24
  142. package/dist/components/ui/number-stepper/numberStepperSteps.d.ts +0 -26
  143. package/dist/components/ui/number-stepper/numberStepperSteps.js +0 -45
@@ -0,0 +1,766 @@
1
+ /**
2
+ * `use:promptReferences` — file references in a text box. The person types `#`, picks an attached file from a menu with thumbnails,
3
+ * and the text box shows it as a badge (thumbnail, name, an X) in the middle of the sentence. The text stays plain text underneath: a
4
+ * badge is `#label` between two runs of figure spaces (see `referenceTokens`), painted over by the mirror layer, so selection, undo,
5
+ * paste, IME and the caret all keep working natively, and what is sent is just text (`normalizeForSend`).
6
+ *
7
+ * What this action does, and where each part lives:
8
+ * - the menu opens at a `#` the person is typing (`referenceTrigger`), is a combobox popup driven from the box (`referenceMenuKeys`,
9
+ * `ReferenceMenu.svelte`), and puts the file in as a token (`referenceTokens`, written with the browser's own edit command so
10
+ * undo brings the typed `#he` back);
11
+ * - the caret never rests inside a badge, a Backspace next to one takes the whole badge, pasted text loses its figure spaces
12
+ * (`referenceEditing`);
13
+ * - the badges are painted on the mirror layer (`referenceBadgePainter`), and are dropped, leaving the plain text, if the mirror ever
14
+ * wraps differently from the box;
15
+ * - the pointer on a badge or the highlight of a menu row is told to the host (`onHover`), so the tray can show the same file.
16
+ *
17
+ * The action holds no English and no file knowledge: the host passes the files (`items`) and the words (`messages`).
18
+ */
19
+ import { acquireTextareaOverlay } from "../textarea-overlay/index.js";
20
+ import { removeLabelFor } from "./referenceBadge.js";
21
+ import { ANCHOR_BOX_SELECTOR, BADGE_START_ATTRIBUTE, createAnchorMarker, createBadgeElement } from "./referenceBadgePainter.js";
22
+ import { decideEdit, findStrayRooms, hasFigureSpace, withoutFigureSpaces } from "./referenceEditing.js";
23
+ import { measureLineHeight, measureTokenRoom } from "./referenceMeasure.js";
24
+ import { createReferenceMenuHost } from "./referenceMenuHost.svelte.js";
25
+ import { interpretMenuKey, keepActiveLabel, moveActiveIndex } from "./referenceMenuKeys.js";
26
+ import { normalizeForSend, parseTokens, planTokenInsertion, removalRangeOf, snapSelection } from "./referenceTokens.js";
27
+ import { findReferenceTrigger, resolveReferenceMenu } from "./referenceTrigger.js";
28
+ /** The name this action paints under on the mirror layer. */
29
+ const OVERLAY_OWNER = 'references';
30
+ /** How far, in pixels, a badge may be from where the text puts the first character of its token before it counts as misplaced. */
31
+ const BADGE_POSITION_TOLERANCE_PX = 2;
32
+ const POPUP_ATTRIBUTES = [
33
+ 'aria-haspopup',
34
+ 'aria-controls',
35
+ 'aria-activedescendant',
36
+ 'aria-autocomplete'
37
+ ];
38
+ function indexItems(items) {
39
+ const byLabel = new Map();
40
+ for (const item of items) {
41
+ const key = item.label.toLowerCase();
42
+ if (!byLabel.has(key))
43
+ byLabel.set(key, item);
44
+ }
45
+ return byLabel;
46
+ }
47
+ function toBox(rect) {
48
+ return { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom };
49
+ }
50
+ export function promptReferences(field, initialParams) {
51
+ const doc = field.ownerDocument;
52
+ const win = doc.defaultView;
53
+ const abort = new AbortController();
54
+ const { signal } = abort;
55
+ let params = initialParams;
56
+ let itemsByLabel = indexItems(params.items);
57
+ let destroyed = false;
58
+ /** The mirror layer, shared with the ghost text of the same box. Null when the box is nowhere a mirror can go. */
59
+ const overlay = acquireTextareaOverlay(field, OVERLAY_OWNER);
60
+ let menuHost = null;
61
+ let openMenu = null;
62
+ /** Where the `#` was when the person pressed Esc on it: the menu stays shut for that word. */
63
+ let dismissedTriggerStart = null;
64
+ let badgeHover = null;
65
+ let composing = false;
66
+ let pointerIsDown = false;
67
+ /** Our own edit is under way: its events are not the person's. */
68
+ let applyingEdit = false;
69
+ /** The badges were dropped for this text because the mirror wrapped it differently from the box. */
70
+ let badgesFellBack = false;
71
+ let layoutCheckQueued = false;
72
+ let lastCaret = field.selectionStart ?? 0;
73
+ /** How the selection last moved: a click goes to the nearest edge of a badge, the arrows go past it. */
74
+ let lastInteraction = 'keyboard';
75
+ let paintedValue = field.value;
76
+ /** The attributes the page had on the box before the popup's were set, to put back. */
77
+ const savedAttributes = new Map();
78
+ function readingOptions() {
79
+ return { triggerCharacter: params.triggerCharacter };
80
+ }
81
+ // --- Logging: one line per transition, and a problem once per kind ----------------------------------------------------------
82
+ const reportedKinds = new Set();
83
+ function log(message, detail) {
84
+ try {
85
+ if (params.logger)
86
+ params.logger(message, detail);
87
+ else
88
+ console.debug(`[prompt-references] ${message}`, detail ?? '');
89
+ }
90
+ catch {
91
+ // A logger that throws must not break typing.
92
+ }
93
+ }
94
+ function logOnce(kind, message, detail) {
95
+ if (reportedKinds.has(kind))
96
+ return;
97
+ reportedKinds.add(kind);
98
+ log(message, detail);
99
+ }
100
+ // --- Reading the box ---------------------------------------------------------------------------------------------------------
101
+ function currentSelection() {
102
+ return { start: field.selectionStart ?? 0, end: field.selectionEnd ?? 0 };
103
+ }
104
+ function readTokens() {
105
+ return parseTokens(field.value, readingOptions());
106
+ }
107
+ function itemOfToken(token) {
108
+ return itemsByLabel.get(token.label.toLowerCase());
109
+ }
110
+ function fieldDirection() {
111
+ return win?.getComputedStyle(field).direction === 'rtl' ? 'rtl' : 'ltr';
112
+ }
113
+ // --- Editing the box the way a person would, so undo works -------------------------------------------------------------------
114
+ /**
115
+ * Replaces `from..to` with `text` through the browser's own edit command, so the change is one undo step and raises the same
116
+ * `beforeinput` and `input` a typed key would. Where the command is not available the text is set directly and `input` is raised by
117
+ * hand (undo then skips this one edit); that is logged once.
118
+ */
119
+ function replaceRange(from, to, text) {
120
+ if (field.disabled || field.readOnly || !field.isConnected)
121
+ return;
122
+ if (from === to && text === '')
123
+ return;
124
+ const before = field.value;
125
+ const expected = `${before.slice(0, from)}${text}${before.slice(to)}`;
126
+ applyingEdit = true;
127
+ try {
128
+ if (doc.activeElement !== field)
129
+ field.focus({ preventScroll: true });
130
+ field.setSelectionRange(from, to);
131
+ let applied = false;
132
+ try {
133
+ applied =
134
+ doc.execCommand(text === '' ? 'delete' : 'insertText', false, text) &&
135
+ field.value === expected;
136
+ }
137
+ catch {
138
+ applied = false;
139
+ }
140
+ if (!applied) {
141
+ logOnce('exec-command', 'the browser would not edit the box; the text was set directly (undo skips this edit)');
142
+ if (field.value !== before)
143
+ field.value = before;
144
+ field.setRangeText(text, from, to, 'end');
145
+ field.dispatchEvent(new InputEvent('input', {
146
+ bubbles: true,
147
+ inputType: text === '' ? 'deleteContent' : 'insertText',
148
+ data: text === '' ? null : text
149
+ }));
150
+ }
151
+ }
152
+ finally {
153
+ applyingEdit = false;
154
+ }
155
+ const caret = from + text.length;
156
+ field.setSelectionRange(caret, caret);
157
+ }
158
+ /** Takes a badge out of the text (the X was pressed, or a key took it). */
159
+ function removeBadge(token) {
160
+ // The token as it is NOW: the text may have changed since the badge was painted.
161
+ const current = readTokens().find((candidate) => candidate.triggerIndex === token.triggerIndex && candidate.label === token.label);
162
+ if (!current)
163
+ return;
164
+ const { from, to } = removalRangeOf(field.value, current);
165
+ replaceRange(from, to, '');
166
+ log('badge removed', { label: current.label });
167
+ }
168
+ /** Takes out the figure spaces a browser deletion left behind when it cut half a badge away. */
169
+ function repairStrayRooms() {
170
+ const value = field.value;
171
+ if (!hasFigureSpace(value))
172
+ return;
173
+ const strays = findStrayRooms(value, parseTokens(value, readingOptions()));
174
+ if (strays.length === 0)
175
+ return;
176
+ let caret = field.selectionStart ?? 0;
177
+ for (const stray of [...strays].reverse()) {
178
+ replaceRange(stray.from, stray.to, '');
179
+ if (caret >= stray.to)
180
+ caret -= stray.to - stray.from;
181
+ else if (caret > stray.from)
182
+ caret = stray.from;
183
+ }
184
+ field.setSelectionRange(caret, caret);
185
+ logOnce('stray-rooms', 'blank space left from half a badge was taken out');
186
+ }
187
+ // --- Painting ----------------------------------------------------------------------------------------------------------------
188
+ function hoveredLabel() {
189
+ return badgeHover ? badgeHover.item.label.toLowerCase() : null;
190
+ }
191
+ /** Paints the badges (and, while the menu is open, the mark it hangs from). */
192
+ function paint() {
193
+ if (destroyed || !overlay)
194
+ return;
195
+ paintedValue = field.value;
196
+ const selection = currentSelection();
197
+ const decorations = [];
198
+ let badgeCount = 0;
199
+ if (!badgesFellBack) {
200
+ for (const token of readTokens()) {
201
+ const item = itemOfToken(token);
202
+ if (!item)
203
+ continue;
204
+ const selected = selection.start !== selection.end &&
205
+ selection.start <= token.start &&
206
+ selection.end >= token.end;
207
+ const highlighted = hoveredLabel() === item.label.toLowerCase();
208
+ badgeCount += 1;
209
+ decorations.push({
210
+ start: token.start,
211
+ end: token.end,
212
+ render: (covered) => createBadgeElement(doc, {
213
+ covered,
214
+ start: token.start,
215
+ item,
216
+ selected,
217
+ highlighted,
218
+ removeLabel: removeLabelFor(params.messages.remove, item.fileName, item.label),
219
+ onRemove: () => removeBadge(token)
220
+ })
221
+ });
222
+ }
223
+ }
224
+ if (openMenu) {
225
+ const lineHeight = measureLineHeight(field);
226
+ decorations.push({
227
+ start: openMenu.trigger.start,
228
+ end: openMenu.trigger.start,
229
+ render: () => createAnchorMarker(doc, lineHeight)
230
+ });
231
+ }
232
+ overlay.setDecorations(decorations);
233
+ if (badgeCount > 0 && !layoutCheckQueued) {
234
+ layoutCheckQueued = true;
235
+ // After the layer's own paint, which is queued first.
236
+ queueMicrotask(verifyLayout);
237
+ }
238
+ }
239
+ /**
240
+ * The labels of the badges that are not standing where the text puts their token.
241
+ *
242
+ * The mirror lays the text out in pieces (text, badge, text, …) where the box lays it out whole, and every piece is rounded to the
243
+ * layout's grid on its own, so a line that fits to a fraction of a pixel can break a word earlier in the mirror than in the box
244
+ * (measured: about one fractional width in two hundred, on a text with five badges). The heights are the same then, and the badges
245
+ * come out a word away from their characters. So the same text is laid out whole, hidden, in a copy of the mirror, and each badge
246
+ * must hold the first character of its token.
247
+ */
248
+ function findMisplacedBadges(mirror, content) {
249
+ const badges = Array.from(content.querySelectorAll(`[${BADGE_START_ATTRIBUTE}]`));
250
+ if (badges.length === 0)
251
+ return [];
252
+ // Every measure of the mirror is an inline style, so a shallow copy is laid out like it, and the scroll offset moves both alike.
253
+ const wholeMirror = mirror.cloneNode(false);
254
+ wholeMirror.removeAttribute('data-textarea-overlay');
255
+ wholeMirror.setAttribute('data-prompt-reference-flow', '');
256
+ wholeMirror.style.visibility = 'hidden';
257
+ const wholeContent = content.cloneNode(false);
258
+ const wholeText = doc.createTextNode(field.value);
259
+ wholeContent.appendChild(wholeText);
260
+ wholeMirror.appendChild(wholeContent);
261
+ mirror.after(wholeMirror);
262
+ try {
263
+ const range = doc.createRange();
264
+ const misplacedLabels = [];
265
+ for (const badge of badges) {
266
+ const start = Number.parseInt(badge.getAttribute(BADGE_START_ATTRIBUTE) ?? '', 10);
267
+ if (!Number.isInteger(start) || start < 0 || start >= wholeText.length)
268
+ continue;
269
+ range.setStart(wholeText, start);
270
+ range.setEnd(wholeText, start + 1);
271
+ const firstCharacterBox = range.getClientRects()[0];
272
+ // A character with no box (nothing laid out) gives nothing to compare with.
273
+ if (!firstCharacterBox)
274
+ continue;
275
+ const centerX = firstCharacterBox.left + firstCharacterBox.width / 2;
276
+ const centerY = firstCharacterBox.top + firstCharacterBox.height / 2;
277
+ // A badge that wrapped has one box per line; the first character is in one of them, in either text direction.
278
+ const holdsFirstCharacter = Array.from(badge.getClientRects()).some((box) => centerX >= box.left - BADGE_POSITION_TOLERANCE_PX &&
279
+ centerX <= box.right + BADGE_POSITION_TOLERANCE_PX &&
280
+ centerY >= box.top - BADGE_POSITION_TOLERANCE_PX &&
281
+ centerY <= box.bottom + BADGE_POSITION_TOLERANCE_PX);
282
+ if (!holdsFirstCharacter)
283
+ misplacedLabels.push(badge.getAttribute('data-label') ?? '');
284
+ }
285
+ return misplacedLabels;
286
+ }
287
+ finally {
288
+ wholeMirror.remove();
289
+ }
290
+ }
291
+ /**
292
+ * A badge is painted over the very characters it stands for, in the same font, so the mirror wraps where the box does. If the two
293
+ * ever differ (a font that arrived late, a sub-pixel at the end of a line) the badge would sit on the wrong line; then the badges
294
+ * are dropped for this text, and the plain `#label` (with its gaps) is what shows, until the text changes or the box changes width.
295
+ * Two checks: the height of the text (a line count that differs), and where each badge stands (a break that moved by a word).
296
+ */
297
+ function verifyLayout() {
298
+ layoutCheckQueued = false;
299
+ if (destroyed || !overlay || badgesFellBack || !win)
300
+ return;
301
+ const mirror = overlay.element;
302
+ const content = mirror.firstElementChild;
303
+ if (!content || mirror.style.display === 'none')
304
+ return;
305
+ try {
306
+ const computed = win.getComputedStyle(field);
307
+ const padding = (Number.parseFloat(computed.paddingTop) || 0) +
308
+ (Number.parseFloat(computed.paddingBottom) || 0);
309
+ const fieldTextHeight = field.scrollHeight - padding;
310
+ const mirrorTextHeight = content.offsetHeight;
311
+ if (Math.abs(fieldTextHeight - mirrorTextHeight) > measureLineHeight(field) / 2) {
312
+ badgesFellBack = true;
313
+ logOnce('layout', 'the mirror wraps differently from the box; the badges are shown as plain text until the text changes', {
314
+ boxHeight: fieldTextHeight,
315
+ mirrorHeight: mirrorTextHeight
316
+ });
317
+ paint();
318
+ return;
319
+ }
320
+ const misplacedLabels = findMisplacedBadges(mirror, content);
321
+ if (misplacedLabels.length === 0)
322
+ return;
323
+ badgesFellBack = true;
324
+ logOnce('layout-position', 'a badge is a word away from its characters in the box; the badges are shown as plain text until the text or the width changes', { misplacedLabels });
325
+ paint();
326
+ }
327
+ catch (error) {
328
+ logOnce('layout-check', 'could not check the badges against the box', error);
329
+ }
330
+ }
331
+ // --- The menu ----------------------------------------------------------------------------------------------------------------
332
+ function ensureMenuHost() {
333
+ if (!menuHost) {
334
+ menuHost = createReferenceMenuHost(field.parentElement ?? doc.body, {
335
+ onChoose: (item) => chooseMenuItem(item),
336
+ onActiveChange: (index) => setActiveIndex(index)
337
+ });
338
+ }
339
+ return menuHost;
340
+ }
341
+ /** Where the menu hangs from: the `#` the person is typing, measured on the mark painted there. Falls back to the box. */
342
+ function measureAnchor() {
343
+ overlay?.refresh();
344
+ const marker = overlay?.element.querySelector(ANCHOR_BOX_SELECTOR);
345
+ const rect = marker?.getBoundingClientRect();
346
+ if (rect && (rect.height > 0 || rect.width > 0))
347
+ return toBox(rect);
348
+ const fallback = field.getBoundingClientRect();
349
+ return {
350
+ left: fallback.left,
351
+ top: fallback.top,
352
+ right: fallback.left + 8,
353
+ bottom: fallback.bottom
354
+ };
355
+ }
356
+ function setPopupAttributes(menu) {
357
+ if (!menuHost)
358
+ return;
359
+ if (menu) {
360
+ for (const name of POPUP_ATTRIBUTES)
361
+ if (!savedAttributes.has(name))
362
+ savedAttributes.set(name, field.getAttribute(name));
363
+ field.setAttribute('aria-haspopup', 'listbox');
364
+ field.setAttribute('aria-autocomplete', 'list');
365
+ field.setAttribute('aria-controls', menuHost.menuId);
366
+ field.setAttribute('aria-activedescendant', menuHost.optionId(menu.activeIndex));
367
+ return;
368
+ }
369
+ for (const [name, previous] of savedAttributes) {
370
+ if (previous === null)
371
+ field.removeAttribute(name);
372
+ else
373
+ field.setAttribute(name, previous);
374
+ }
375
+ savedAttributes.clear();
376
+ }
377
+ /** Tells the menu what to show now: the list when it is open, otherwise the preview of the badge under the pointer, otherwise nothing. */
378
+ function syncMenuView() {
379
+ if (destroyed)
380
+ return;
381
+ if (!menuHost && !openMenu && !badgeHover)
382
+ return;
383
+ const host = ensureMenuHost();
384
+ const base = { menuLabel: params.messages.menuLabel, direction: fieldDirection() };
385
+ if (openMenu) {
386
+ host.update({
387
+ ...base,
388
+ items: openMenu.matches,
389
+ activeIndex: openMenu.activeIndex,
390
+ anchor: measureAnchor(),
391
+ previewItem: openMenu.matches[openMenu.activeIndex] ?? null,
392
+ previewAnchor: null
393
+ });
394
+ }
395
+ else if (badgeHover) {
396
+ host.update({
397
+ ...base,
398
+ items: [],
399
+ activeIndex: -1,
400
+ anchor: null,
401
+ previewItem: badgeHover.item,
402
+ previewAnchor: badgeHover.box
403
+ });
404
+ }
405
+ else {
406
+ host.update({
407
+ ...base,
408
+ items: [],
409
+ activeIndex: -1,
410
+ anchor: null,
411
+ previewItem: null,
412
+ previewAnchor: null
413
+ });
414
+ }
415
+ setPopupAttributes(openMenu);
416
+ }
417
+ function tellHover(label, source) {
418
+ try {
419
+ params.onHover?.({ label, source });
420
+ }
421
+ catch (error) {
422
+ logOnce('hover-callback', "the host's hover callback threw", error);
423
+ }
424
+ }
425
+ function tellMenuStatus(open) {
426
+ try {
427
+ params.onMenuChange?.({ open });
428
+ }
429
+ catch (error) {
430
+ logOnce('menu-callback', "the host's menu callback threw", error);
431
+ }
432
+ }
433
+ function closeMenu() {
434
+ if (!openMenu)
435
+ return;
436
+ openMenu = null;
437
+ paint();
438
+ syncMenuView();
439
+ tellMenuStatus(false);
440
+ tellHover(null, 'menu');
441
+ log('menu closed');
442
+ }
443
+ function setActiveIndex(index) {
444
+ if (!openMenu ||
445
+ index === openMenu.activeIndex ||
446
+ index < 0 ||
447
+ index >= openMenu.matches.length)
448
+ return;
449
+ openMenu.activeIndex = index;
450
+ syncMenuView();
451
+ tellHover(openMenu.matches[index].label, 'menu');
452
+ }
453
+ /** Opens, narrows or closes the menu for the text and caret as they are now. */
454
+ function updateMenu() {
455
+ if (destroyed)
456
+ return;
457
+ const selection = currentSelection();
458
+ const canOpen = params.enabled !== false &&
459
+ !composing &&
460
+ doc.activeElement === field &&
461
+ selection.start === selection.end &&
462
+ !field.readOnly;
463
+ if (!canOpen) {
464
+ closeMenu();
465
+ return;
466
+ }
467
+ // The Esc of one word ends when the caret leaves that word.
468
+ if (dismissedTriggerStart !== null) {
469
+ const found = findReferenceTrigger(field.value, selection.start, readingOptions());
470
+ if (!found || found.start !== dismissedTriggerStart)
471
+ dismissedTriggerStart = null;
472
+ }
473
+ const state = resolveReferenceMenu(field.value, selection.start, params.items, {
474
+ ...readingOptions(),
475
+ dismissedTriggerStart
476
+ });
477
+ if (!state) {
478
+ closeMenu();
479
+ return;
480
+ }
481
+ const wasOpen = openMenu !== null;
482
+ const previousLabel = openMenu ? (openMenu.matches[openMenu.activeIndex]?.label ?? null) : null;
483
+ const nextIndex = keepActiveLabel(previousLabel, state.matches.map((item) => item.label));
484
+ openMenu = { trigger: state.trigger, matches: state.matches, activeIndex: nextIndex };
485
+ // The mark the menu hangs from is part of the paint.
486
+ paint();
487
+ syncMenuView();
488
+ if (!wasOpen) {
489
+ tellMenuStatus(true);
490
+ log('menu opened', { files: state.matches.length });
491
+ }
492
+ const active = openMenu.matches[openMenu.activeIndex];
493
+ if (!wasOpen || previousLabel !== active.label)
494
+ tellHover(active.label, 'menu');
495
+ }
496
+ /** Writes a file into the text at the `#` the person typed. */
497
+ function chooseMenuItem(item) {
498
+ const menu = openMenu;
499
+ if (!menu)
500
+ return;
501
+ const chosen = item ?? menu.matches[menu.activeIndex];
502
+ if (!chosen)
503
+ return;
504
+ const plan = planTokenInsertion(field.value, menu.trigger, chosen.label, {
505
+ ...readingOptions(),
506
+ room: measureTokenRoom(field)
507
+ });
508
+ // Closed before the edit, so the edit's own `input` finds the menu shut.
509
+ closeMenu();
510
+ replaceRange(plan.from, plan.to, plan.insertion);
511
+ log('reference inserted', { label: chosen.label });
512
+ }
513
+ function dismissMenu() {
514
+ if (!openMenu)
515
+ return;
516
+ dismissedTriggerStart = openMenu.trigger.start;
517
+ closeMenu();
518
+ }
519
+ // --- The pointer on a badge ----------------------------------------------------------------------------------------------------
520
+ function badgeAtPoint(x, y) {
521
+ if (!overlay)
522
+ return null;
523
+ for (const element of overlay.element.querySelectorAll('[data-prompt-reference]')) {
524
+ for (const rect of Array.from(element.getClientRects())) {
525
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)
526
+ continue;
527
+ const item = itemsByLabel.get((element.getAttribute('data-label') ?? '').toLowerCase());
528
+ if (item)
529
+ return { item, box: toBox(element.getBoundingClientRect()) };
530
+ }
531
+ }
532
+ return null;
533
+ }
534
+ function setBadgeHover(next) {
535
+ const changed = (badgeHover?.item.label ?? null) !== (next?.item.label ?? null);
536
+ badgeHover = next;
537
+ if (!changed)
538
+ return;
539
+ paint();
540
+ syncMenuView();
541
+ tellHover(next ? next.item.label : null, 'badge');
542
+ }
543
+ // --- Events ----------------------------------------------------------------------------------------------------------------------
544
+ /** The text of a paste or a drop, when the event carries it (a text box gives it as `data`, others as `dataTransfer`). */
545
+ function insertedTextOf(event) {
546
+ return event.data ?? event.dataTransfer?.getData('text/plain') ?? null;
547
+ }
548
+ function onBeforeInput(event) {
549
+ if (applyingEdit || destroyed)
550
+ return;
551
+ try {
552
+ const insertedText = insertedTextOf(event);
553
+ const tokens = readTokens();
554
+ if (tokens.length === 0 && !hasFigureSpace(insertedText))
555
+ return;
556
+ const selection = currentSelection();
557
+ const decision = decideEdit({
558
+ inputType: event.inputType,
559
+ value: field.value,
560
+ selection,
561
+ tokens,
562
+ composing: composing || event.isComposing,
563
+ insertedText
564
+ });
565
+ switch (decision.kind) {
566
+ case 'allow':
567
+ return;
568
+ case 'removeRange':
569
+ event.preventDefault();
570
+ replaceRange(decision.from, decision.to, '');
571
+ log('badge removed', { label: decision.token.label });
572
+ return;
573
+ case 'moveSelection':
574
+ event.preventDefault();
575
+ field.setSelectionRange(decision.selection.start, decision.selection.end, field.selectionDirection ?? 'none');
576
+ return;
577
+ case 'insertInstead':
578
+ event.preventDefault();
579
+ replaceRange(selection.start, selection.end, decision.text);
580
+ return;
581
+ }
582
+ }
583
+ catch (error) {
584
+ // A fault here must never block typing: the edit goes through as the browser would have made it.
585
+ logOnce('before-input', 'could not read an edit; it was left to the browser', error);
586
+ }
587
+ }
588
+ function onInput() {
589
+ if (destroyed)
590
+ return;
591
+ badgesFellBack = false;
592
+ if (!applyingEdit && !composing)
593
+ repairStrayRooms();
594
+ lastCaret = field.selectionStart ?? lastCaret;
595
+ paint();
596
+ updateMenu();
597
+ }
598
+ /** The selection moved: keep it out of the badges (once the pointer is up), repaint the selected ring, and re-read the menu. */
599
+ function onSelectionChange() {
600
+ if (destroyed || applyingEdit || doc.activeElement !== field)
601
+ return;
602
+ const selection = currentSelection();
603
+ if (!pointerIsDown && !composing) {
604
+ const snapped = snapSelection(field.value, selection, {
605
+ ...readingOptions(),
606
+ previousCaret: lastInteraction === 'keyboard' ? lastCaret : undefined
607
+ });
608
+ if (snapped !== selection) {
609
+ field.setSelectionRange(snapped.start, snapped.end, field.selectionDirection ?? 'none');
610
+ // The move raises another selection change, which does the rest.
611
+ return;
612
+ }
613
+ }
614
+ lastCaret = selection.start === selection.end ? selection.start : lastCaret;
615
+ paint();
616
+ updateMenu();
617
+ }
618
+ function onKeyDown(event) {
619
+ lastInteraction = 'keyboard';
620
+ if (!openMenu)
621
+ return;
622
+ const action = interpretMenuKey(event, true);
623
+ if (action === 'none')
624
+ return;
625
+ // The box's own handlers (Enter sends, Tab moves on, Esc closes a dialog) must not also run.
626
+ event.preventDefault();
627
+ event.stopPropagation();
628
+ event.stopImmediatePropagation();
629
+ switch (action) {
630
+ case 'next':
631
+ case 'previous':
632
+ setActiveIndex(moveActiveIndex(openMenu.activeIndex, openMenu.matches.length, action));
633
+ return;
634
+ case 'choose':
635
+ chooseMenuItem();
636
+ return;
637
+ case 'close':
638
+ dismissMenu();
639
+ return;
640
+ }
641
+ }
642
+ function onPointerDown() {
643
+ lastInteraction = 'pointer';
644
+ pointerIsDown = true;
645
+ }
646
+ function onPointerUp() {
647
+ if (!pointerIsDown)
648
+ return;
649
+ pointerIsDown = false;
650
+ // The selection that the drag ended on may rest inside a badge.
651
+ onSelectionChange();
652
+ }
653
+ function onPointerMove(event) {
654
+ if (event.pointerType === 'touch' || openMenu || pointerIsDown)
655
+ return;
656
+ setBadgeHover(badgeAtPoint(event.clientX, event.clientY));
657
+ }
658
+ function onPointerLeave(event) {
659
+ const target = event.relatedTarget;
660
+ // Onto the X of a badge (it is in the mirror, not in the box): still on the badge.
661
+ if (target instanceof Node && overlay?.element.contains(target))
662
+ return;
663
+ setBadgeHover(null);
664
+ }
665
+ function onMirrorPointerOut(event) {
666
+ const target = event.relatedTarget;
667
+ if (target instanceof Node && (overlay?.element.contains(target) || target === field))
668
+ return;
669
+ setBadgeHover(null);
670
+ }
671
+ function onCopyOrCut(event) {
672
+ const selection = currentSelection();
673
+ if (selection.start === selection.end ||
674
+ !hasFigureSpace(field.value.slice(selection.start, selection.end)))
675
+ return;
676
+ // A badge copied out of the box is the plain `#label`: no blanks travel with it.
677
+ try {
678
+ event.clipboardData?.setData('text/plain', normalizeForSend(field.value.slice(selection.start, selection.end)));
679
+ event.preventDefault();
680
+ if (event.type === 'cut')
681
+ replaceRange(selection.start, selection.end, '');
682
+ }
683
+ catch (error) {
684
+ logOnce('clipboard', "could not clean the copied text; the browser's copy was used", error);
685
+ }
686
+ }
687
+ function onFocus() {
688
+ paint();
689
+ updateMenu();
690
+ }
691
+ function onBlur() {
692
+ closeMenu();
693
+ setBadgeHover(null);
694
+ }
695
+ // --- Wiring ----------------------------------------------------------------------------------------------------------------------
696
+ field.addEventListener('beforeinput', onBeforeInput, { signal });
697
+ field.addEventListener('input', onInput, { signal });
698
+ // Capture phase, so the box's own key handlers (they bubble) come after, and can be stopped.
699
+ field.addEventListener('keydown', onKeyDown, { capture: true, signal });
700
+ field.addEventListener('focus', onFocus, { signal });
701
+ field.addEventListener('blur', onBlur, { signal });
702
+ field.addEventListener('compositionstart', () => (composing = true), { signal });
703
+ field.addEventListener('compositionend', () => {
704
+ composing = false;
705
+ paint();
706
+ updateMenu();
707
+ }, { signal });
708
+ field.addEventListener('pointerdown', onPointerDown, { signal });
709
+ doc.addEventListener('pointerup', onPointerUp, { capture: true, signal });
710
+ doc.addEventListener('pointercancel', onPointerUp, { capture: true, signal });
711
+ field.addEventListener('pointermove', onPointerMove, { signal });
712
+ field.addEventListener('pointerleave', onPointerLeave, { signal });
713
+ overlay?.element.addEventListener('pointerout', onMirrorPointerOut, { signal });
714
+ field.addEventListener('scroll', () => setBadgeHover(null), { passive: true, signal });
715
+ field.addEventListener('copy', onCopyOrCut, { signal });
716
+ field.addEventListener('cut', onCopyOrCut, { signal });
717
+ // Some browsers raise the selection change on the box, some on the document: both are heard, and a repeat costs one cheap paint.
718
+ field.addEventListener('selectionchange', onSelectionChange, { signal });
719
+ doc.addEventListener('selectionchange', onSelectionChange, { signal });
720
+ field.addEventListener('keyup', onSelectionChange, { signal });
721
+ // The box can change width with no key pressed (a window dragged, a side panel opened). A break may move with it, so the badges are
722
+ // checked again, and shown again if they had been dropped for a width that is gone.
723
+ if (typeof win?.ResizeObserver === 'function') {
724
+ let lastSeenWidth = field.getBoundingClientRect().width;
725
+ const widthObserver = new win.ResizeObserver(() => {
726
+ if (destroyed)
727
+ return;
728
+ const width = field.getBoundingClientRect().width;
729
+ if (width === lastSeenWidth)
730
+ return;
731
+ lastSeenWidth = width;
732
+ badgesFellBack = false;
733
+ paint();
734
+ });
735
+ widthObserver.observe(field);
736
+ signal.addEventListener('abort', () => widthObserver.disconnect(), { once: true });
737
+ }
738
+ paint();
739
+ return {
740
+ update(nextParams) {
741
+ if (destroyed)
742
+ return;
743
+ const textChanged = nextParams.value !== paintedValue || field.value !== paintedValue;
744
+ params = nextParams;
745
+ itemsByLabel = indexItems(params.items);
746
+ if (textChanged)
747
+ badgesFellBack = false;
748
+ // The files changed (one joined or left the tray), or the text did without an event: the badges and the menu follow.
749
+ paint();
750
+ updateMenu();
751
+ syncMenuView();
752
+ },
753
+ destroy() {
754
+ if (destroyed)
755
+ return;
756
+ destroyed = true;
757
+ abort.abort();
758
+ openMenu = null;
759
+ badgeHover = null;
760
+ setPopupAttributes(null);
761
+ menuHost?.destroy();
762
+ menuHost = null;
763
+ overlay?.release();
764
+ }
765
+ };
766
+ }