@widgetic/design-system 0.5.40 → 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 (139) 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 +380 -19
  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/index.d.ts +8 -7
  27. package/dist/components/index.js +8 -6
  28. package/dist/components/modals/BaseModal.svelte +14 -4
  29. package/dist/components/navigation/breadcrumbSlideIn.d.ts +6 -2
  30. package/dist/components/navigation/breadcrumbSlideIn.js +6 -6
  31. package/dist/components/search-input/SearchInput.svelte +282 -14
  32. package/dist/components/search-input/SearchInput.svelte.d.ts +3 -0
  33. package/dist/components/search-input/index.d.ts +1 -0
  34. package/dist/components/search-input/index.js +1 -0
  35. package/dist/components/search-input/index2.d.ts +4 -0
  36. package/dist/components/search-input/recentSearches.d.ts +12 -0
  37. package/dist/components/search-input/recentSearches.js +124 -0
  38. package/dist/components/toast/ToasterModal.svelte +8 -3
  39. package/dist/components/toast/ToasterModal.svelte.d.ts +2 -0
  40. package/dist/components/ui/chip/chip.svelte +39 -1
  41. package/dist/components/ui/chip/chip.svelte.d.ts +8 -0
  42. package/dist/components/ui/chip/chipProgress.d.ts +14 -0
  43. package/dist/components/ui/chip/chipProgress.js +21 -0
  44. package/dist/components/ui/icon-button/icon-button.svelte +2 -0
  45. package/dist/components/ui/icon-button/icon-button.svelte.d.ts +5 -0
  46. package/dist/components/ui/number-controls/index.d.ts +2 -0
  47. package/dist/components/ui/number-controls/index.js +2 -0
  48. package/dist/components/ui/number-controls/number-controls.svelte +530 -0
  49. package/dist/components/ui/number-controls/number-controls.svelte.d.ts +46 -0
  50. package/dist/components/ui/number-controls/numberControlsSteps.d.ts +17 -0
  51. package/dist/components/ui/number-controls/numberControlsSteps.js +23 -0
  52. package/dist/components/ui/number-controls/numberControlsValueArea.d.ts +29 -0
  53. package/dist/components/ui/number-controls/numberControlsValueArea.js +51 -0
  54. package/dist/components/ui/text-flip/index.d.ts +1 -0
  55. package/dist/components/ui/text-flip/index.js +1 -0
  56. package/dist/components/ui/text-flip/text-flip.svelte +103 -0
  57. package/dist/components/ui/text-flip/text-flip.svelte.d.ts +15 -0
  58. package/dist/components/ui/text-flip/textFlipLogic.d.ts +49 -0
  59. package/dist/components/ui/text-flip/textFlipLogic.js +151 -0
  60. package/dist/inline-completion/completionAnswer.d.ts +11 -0
  61. package/dist/inline-completion/completionAnswer.js +49 -0
  62. package/dist/inline-completion/completionCache.d.ts +24 -0
  63. package/dist/inline-completion/completionCache.js +47 -0
  64. package/dist/inline-completion/completionController.d.ts +61 -0
  65. package/dist/inline-completion/completionController.js +280 -0
  66. package/dist/inline-completion/completionKeys.d.ts +21 -0
  67. package/dist/inline-completion/completionKeys.js +19 -0
  68. package/dist/inline-completion/completionText.d.ts +53 -0
  69. package/dist/inline-completion/completionText.js +79 -0
  70. package/dist/inline-completion/completionTypes.d.ts +71 -0
  71. package/dist/inline-completion/completionTypes.js +5 -0
  72. package/dist/inline-completion/gatewayCompletion.d.ts +37 -0
  73. package/dist/inline-completion/gatewayCompletion.js +77 -0
  74. package/dist/inline-completion/ghostTap.d.ts +19 -0
  75. package/dist/inline-completion/ghostTap.js +20 -0
  76. package/dist/inline-completion/hintMemory.d.ts +43 -0
  77. package/dist/inline-completion/hintMemory.js +90 -0
  78. package/dist/inline-completion/httpSource.d.ts +40 -0
  79. package/dist/inline-completion/httpSource.js +149 -0
  80. package/dist/inline-completion/index.d.ts +30 -0
  81. package/dist/inline-completion/index.js +20 -0
  82. package/dist/inline-completion/inlineCompletionAction.d.ts +54 -0
  83. package/dist/inline-completion/inlineCompletionAction.js +310 -0
  84. package/dist/inline-completion/outcomeReporter.d.ts +49 -0
  85. package/dist/inline-completion/outcomeReporter.js +139 -0
  86. package/dist/inline-completion/promiseLike.d.ts +9 -0
  87. package/dist/inline-completion/promiseLike.js +9 -0
  88. package/dist/prompt-references/ReferenceMenu.svelte +344 -0
  89. package/dist/prompt-references/ReferenceMenu.svelte.d.ts +26 -0
  90. package/dist/prompt-references/index.d.ts +27 -0
  91. package/dist/prompt-references/index.js +20 -0
  92. package/dist/prompt-references/neutralizingSource.d.ts +21 -0
  93. package/dist/prompt-references/neutralizingSource.js +29 -0
  94. package/dist/prompt-references/promptReferences.d.ts +28 -0
  95. package/dist/prompt-references/promptReferences.js +766 -0
  96. package/dist/prompt-references/referenceBadge.d.ts +61 -0
  97. package/dist/prompt-references/referenceBadge.js +82 -0
  98. package/dist/prompt-references/referenceBadgePainter.d.ts +31 -0
  99. package/dist/prompt-references/referenceBadgePainter.js +106 -0
  100. package/dist/prompt-references/referenceEditing.d.ts +60 -0
  101. package/dist/prompt-references/referenceEditing.js +135 -0
  102. package/dist/prompt-references/referenceLabels.d.ts +56 -0
  103. package/dist/prompt-references/referenceLabels.js +215 -0
  104. package/dist/prompt-references/referenceMeasure.d.ts +12 -0
  105. package/dist/prompt-references/referenceMeasure.js +63 -0
  106. package/dist/prompt-references/referenceMenuHost.svelte.d.ts +29 -0
  107. package/dist/prompt-references/referenceMenuHost.svelte.js +43 -0
  108. package/dist/prompt-references/referenceMenuKeys.d.ts +26 -0
  109. package/dist/prompt-references/referenceMenuKeys.js +49 -0
  110. package/dist/prompt-references/referenceMenuPlacement.d.ts +63 -0
  111. package/dist/prompt-references/referenceMenuPlacement.js +66 -0
  112. package/dist/prompt-references/referenceTokens.d.ts +175 -0
  113. package/dist/prompt-references/referenceTokens.js +332 -0
  114. package/dist/prompt-references/referenceTrigger.d.ts +52 -0
  115. package/dist/prompt-references/referenceTrigger.js +100 -0
  116. package/dist/prompt-references/referenceTypes.d.ts +38 -0
  117. package/dist/prompt-references/referenceTypes.js +4 -0
  118. package/dist/prompt-references/sentReferences.d.ts +50 -0
  119. package/dist/prompt-references/sentReferences.js +122 -0
  120. package/dist/styles/tokens.css +58 -0
  121. package/dist/textarea-overlay/index.d.ts +9 -0
  122. package/dist/textarea-overlay/index.js +7 -0
  123. package/dist/textarea-overlay/mirrorSegments.d.ts +31 -0
  124. package/dist/textarea-overlay/mirrorSegments.js +47 -0
  125. package/dist/textarea-overlay/mirrorSizing.d.ts +39 -0
  126. package/dist/textarea-overlay/mirrorSizing.js +40 -0
  127. package/dist/textarea-overlay/textareaOverlay.d.ts +25 -0
  128. package/dist/textarea-overlay/textareaOverlay.js +277 -0
  129. package/dist/utils/overlayMotion.d.ts +1 -0
  130. package/dist/utils/overlayMotion.js +3 -3
  131. package/dist/utils/reducedMotion.d.ts +9 -0
  132. package/dist/utils/reducedMotion.js +13 -0
  133. package/package.json +16 -1
  134. package/dist/components/ui/number-stepper/index.d.ts +0 -3
  135. package/dist/components/ui/number-stepper/index.js +0 -3
  136. package/dist/components/ui/number-stepper/number-stepper.svelte +0 -212
  137. package/dist/components/ui/number-stepper/number-stepper.svelte.d.ts +0 -24
  138. package/dist/components/ui/number-stepper/numberStepperSteps.d.ts +0 -26
  139. package/dist/components/ui/number-stepper/numberStepperSteps.js +0 -45
@@ -0,0 +1,175 @@
1
+ /** U+2007 FIGURE SPACE: the blank a reference reserves its room with. */
2
+ export declare const FIGURE_SPACE = "\u2007";
3
+ /** The character that starts a reference. An option everywhere, so another picker (the workflows `@`) can reuse the engine. */
4
+ export declare const DEFAULT_TRIGGER_CHARACTER = "#";
5
+ /** How many figure spaces stand before and after a token's `#label`. */
6
+ export interface TokenRoom {
7
+ /** The room of the thumbnail, before the label. */
8
+ leading: number;
9
+ /** The room of the X, after the label. */
10
+ trailing: number;
11
+ }
12
+ /** What a token gets when nothing was measured: 3 before and 2 after, which is right for 14 px text. */
13
+ export declare const DEFAULT_TOKEN_ROOM: TokenRoom;
14
+ /** The width a token's two rooms must have, in pixels: an 18 px thumbnail with its gaps, and a 16 px X. */
15
+ export declare const BADGE_ROOM_PIXELS: TokenRoom;
16
+ /** No room is ever more than this many spaces, whatever was measured (a font that gives a figure space no width at all). */
17
+ export declare const MAX_ROOM_SPACES = 8;
18
+ /** A piece of a reference found in the text. All positions are indexes into the text it was found in. */
19
+ export interface ReferenceToken {
20
+ /** Where the token starts: its first leading figure space. */
21
+ start: number;
22
+ /** Where the token ends: just after its last trailing figure space. */
23
+ end: number;
24
+ /** Where the trigger character (`#`) is. */
25
+ triggerIndex: number;
26
+ /** Where the label starts (just after the trigger character) and ends. */
27
+ labelStart: number;
28
+ labelEnd: number;
29
+ label: string;
30
+ /** The runs this token has, as found. */
31
+ room: TokenRoom;
32
+ }
33
+ /** A character offset range of the text, as a field's selection has. */
34
+ export interface TextSelection {
35
+ start: number;
36
+ end: number;
37
+ }
38
+ export interface TokenReadingOptions {
39
+ /** The character that starts a reference. Default `#`. Must be one character. */
40
+ triggerCharacter?: string;
41
+ }
42
+ /** The trigger character to use: the one given when it is one character, otherwise `#`. */
43
+ export declare function triggerCharacterOf(options?: TokenReadingOptions): string;
44
+ /** Whether a character is a space a person typed: whitespace, but not the figure space a token is made of. */
45
+ export declare function isRegularWhitespace(character: string | undefined): boolean;
46
+ /**
47
+ * Whether a reference may start at `index`: at the start of the text, or after whitespace, an opening bracket or a quote, or after
48
+ * the room of a badge (a badge's figure spaces are blanks like any other: `#` typed straight after a badge starts the next one, and
49
+ * the `#` of a badge itself has its own leading room before it). Never in the middle of a word, a URL or an anchor (`a#b`,
50
+ * `site.com/#top`, `'`).
51
+ */
52
+ export declare function canStartReferenceAt(text: string, index: number): boolean;
53
+ /** One `#word` of a text: where its trigger character is, its label and where the label ends. */
54
+ export interface ReferenceWord {
55
+ triggerIndex: number;
56
+ label: string;
57
+ labelEnd: number;
58
+ }
59
+ /** Every `#word` in the text that a reference may start at, whether it has rooms (a badge) or not (typed by hand), in order. */
60
+ export declare function findReferenceWords(text: string, options?: TokenReadingOptions): ReferenceWord[];
61
+ /**
62
+ * The tokens in the text, in order: a `#label` with at least one figure space on each side. A `#label` with none on a side is plain
63
+ * text (typed by hand, or a token a browser took a space out of). When two tokens touch, the run between them is shared in the
64
+ * proportion tokens are made in, so each still has room on both sides.
65
+ */
66
+ export declare function parseTokens(text: string, options?: TokenReadingOptions): ReferenceToken[];
67
+ /** How many figure spaces each room needs, from the measured width of one (in pixels). A width that is not usable gives the defaults. */
68
+ export declare function roomForFigureSpaceWidth(figureSpaceWidth: number, pixels?: TokenRoom): TokenRoom;
69
+ /**
70
+ * The text of one token: the leading room, the trigger character and the label, the trailing room. A label that is not a valid label
71
+ * (it has a space, or is too long) is written plain, as `#label` with no rooms, so a bad label can never become a badge.
72
+ */
73
+ export declare function buildToken(label: string, room?: TokenRoom, options?: TokenReadingOptions): string;
74
+ /** The text with every figure space taken out: what is sent, kept in history and read by the model ("fix #hero_banner"). */
75
+ export declare function normalizeForSend(text: string): string;
76
+ export interface NeutralizeOptions extends TokenReadingOptions {
77
+ /** The word that stands for a file. Default `file`: "fix #file". A file's name never leaves the browser through a suggestion. */
78
+ neutralWord?: string;
79
+ /** Labels of files that are attached: a `#label` typed by hand that names one of them is made neutral too. */
80
+ knownLabels?: Iterable<string>;
81
+ }
82
+ /**
83
+ * The text as a suggestion service may see it: each reference (a badge, and a hand-typed `#label` that names an attached file) is
84
+ * the neutral word `#file`, and the rooms are gone. A person's file names are theirs; the model that completes a sentence needs only
85
+ * to know that a file was mentioned.
86
+ */
87
+ export declare function neutralizeReferences(text: string, options?: NeutralizeOptions): string;
88
+ export interface SnapOptions extends TokenReadingOptions {
89
+ /** The tokens of the text, when the caller has them already. */
90
+ tokens?: readonly ReferenceToken[];
91
+ /** Where the caret was before it moved: a caret that lands inside a token goes on to the far edge in the direction it was heading. */
92
+ previousCaret?: number;
93
+ }
94
+ /**
95
+ * A selection moved so that no end of it rests INSIDE a token:
96
+ * - a caret inside a token goes to the edge it was heading for (with a previous caret), or to the nearest edge;
97
+ * - a range that starts or ends inside a token grows outward to cover it.
98
+ * Returns the very same object when nothing had to move.
99
+ */
100
+ export declare function snapSelection(text: string, selection: TextSelection, options?: SnapOptions): TextSelection;
101
+ /**
102
+ * What to cut to take a token out: the token, and one space of the pair around it, so no double space is left (`fix [T] now` becomes
103
+ * `fix now`). A token at an edge of the text takes the one space on its inside.
104
+ */
105
+ export declare function removalRangeOf(text: string, token: ReferenceToken): {
106
+ from: number;
107
+ to: number;
108
+ };
109
+ /** The text with one token taken out, and where the caret goes (where the token was). */
110
+ export declare function removeToken(text: string, token: ReferenceToken): {
111
+ text: string;
112
+ caret: number;
113
+ from: number;
114
+ to: number;
115
+ };
116
+ /**
117
+ * The text without the badges of one file (a file leaves the tray): each token with that label is taken out with one adjacent space.
118
+ * A `#label` typed by hand stays: it is the person's own word. `removed` is how many badges went.
119
+ */
120
+ export declare function removeTokensOfLabel(text: string, label: string, options?: TokenReadingOptions): {
121
+ text: string;
122
+ removed: number;
123
+ };
124
+ /**
125
+ * The text with the rooms taken out of every token whose file is not attached any more (a draft restored after its file is gone):
126
+ * the token is plain `#label` again, so it can never show a badge for a picture that is not there.
127
+ */
128
+ export declare function unbadgeTokensWithoutFiles(text: string, knownLabels: Iterable<string>, options?: TokenReadingOptions): string;
129
+ /** What to put in the field when a menu choice becomes a token. */
130
+ export interface TokenInsertionPlan {
131
+ /** The part of the text the token replaces: the trigger character and what was typed after it. */
132
+ from: number;
133
+ to: number;
134
+ /** The text that replaces it: the token, and a space after it unless one (or closing punctuation) follows. */
135
+ insertion: string;
136
+ /** Where the caret goes: after the insertion. */
137
+ caret: number;
138
+ }
139
+ /**
140
+ * How a menu choice is written into the text. `trigger` is where the person's `#` and the word after it are (from `findReferenceTrigger`).
141
+ * The token replaces them, and a space follows it so typing goes on at once, unless a space or closing punctuation is already there.
142
+ */
143
+ export declare function planTokenInsertion(text: string, trigger: {
144
+ start: number;
145
+ end: number;
146
+ }, label: string, options?: TokenReadingOptions & {
147
+ room?: TokenRoom;
148
+ }): TokenInsertionPlan;
149
+ /**
150
+ * Every place the text names a file, in order: the badges (a token is a reference whatever stands before it, so two badges that touch
151
+ * stay two) and the `#label` words typed by hand. One entry per `#`.
152
+ */
153
+ export declare function referenceOccurrences(text: string, options?: TokenReadingOptions): ReferenceWord[];
154
+ /** An attached file, as far as references are concerned. */
155
+ export interface ReferenceAttachment {
156
+ /** What the host knows the file by (the gateway's upload id). */
157
+ id: string;
158
+ /** The label the file got when it joined the tray. Files without one cannot be referenced. */
159
+ label?: string | null;
160
+ }
161
+ /** What a send carries about a reference: which file, and the word the person used for it. */
162
+ export interface CollectedReference {
163
+ id: string;
164
+ label: string;
165
+ }
166
+ export interface CollectReferencesOptions extends TokenReadingOptions {
167
+ /** The most references to return (the request's own cap: 5 pictures for the creator, 20 media for workflows). Default: no cap. */
168
+ max?: number;
169
+ }
170
+ /**
171
+ * The references a message makes: each `#label` word in it that names a file still attached, in order of first appearance, once per
172
+ * file. A badge and a `#label` typed by hand count the same. A label is matched without regard to case; the answer carries the file's
173
+ * own label. Files that are not attached (or have no label) are never named.
174
+ */
175
+ export declare function collectReferences(text: string, attachments: readonly ReferenceAttachment[], options?: CollectReferencesOptions): CollectedReference[];
@@ -0,0 +1,332 @@
1
+ /**
2
+ * The text of a reference: how a file reference is written INSIDE a textarea, and how it is read back. Pure functions, no DOM.
3
+ *
4
+ * A textarea cannot hold a picture, so a reference is text that reserves room for one: a run of U+2007 figure spaces (blank, never
5
+ * broken at the end of a line, one digit wide), then `#label`, then a shorter run. The mirror layer paints the badge (thumbnail,
6
+ * name, X) over those characters; the textarea itself only ever holds text, so typing, selecting, undo and `bind:value` are native.
7
+ *
8
+ * ```
9
+ * fix [figure×3]#hero_banner[figure×2] and brighten #logo
10
+ * ^ room for the thumbnail ^ room for the X
11
+ * ```
12
+ *
13
+ * The parser accepts ANY run length, so a token made at one font size is still a token at another. Counts are chosen at insertion
14
+ * from one measurement of a figure space (`roomForFigureSpaceWidth`).
15
+ *
16
+ * The text that is SENT has the rooms taken out (`normalizeForSend`): "fix #hero_banner and brighten #logo", readable in history and
17
+ * by the model. A `#label` typed by hand has no rooms and counts like a badge when it names an attached file (`collectReferences`).
18
+ */
19
+ import { MAX_REFERENCE_LABEL_LENGTH, isValidReferenceLabel } from "./referenceLabels.js";
20
+ /** U+2007 FIGURE SPACE: the blank a reference reserves its room with. */
21
+ export const FIGURE_SPACE = '\u2007';
22
+ /** The character that starts a reference. An option everywhere, so another picker (the workflows `@`) can reuse the engine. */
23
+ export const DEFAULT_TRIGGER_CHARACTER = '#';
24
+ /** What a token gets when nothing was measured: 3 before and 2 after, which is right for 14 px text. */
25
+ export const DEFAULT_TOKEN_ROOM = { leading: 3, trailing: 2 };
26
+ /** The width a token's two rooms must have, in pixels: an 18 px thumbnail with its gaps, and a 16 px X. */
27
+ export const BADGE_ROOM_PIXELS = { leading: 25, trailing: 16 };
28
+ /** No room is ever more than this many spaces, whatever was measured (a font that gives a figure space no width at all). */
29
+ export const MAX_ROOM_SPACES = 8;
30
+ /** How the run between two tokens that touch is shared: the later token's leading room takes this part of it, the earlier one the rest. */
31
+ const LEADING_SHARE_OF_SHARED_RUN = DEFAULT_TOKEN_ROOM.leading / (DEFAULT_TOKEN_ROOM.leading + DEFAULT_TOKEN_ROOM.trailing);
32
+ /** The characters after which a `#` starts a reference: opening brackets and quotes (whitespace and the start of the text are tested apart). */
33
+ const OPENING_PUNCTUATION = new Set(Array.from('([{<«“‘"\'([{「『【〔〈《'));
34
+ /** The characters a reference may be followed by without a space of its own: closing punctuation. */
35
+ const CLOSING_PUNCTUATION = new Set(Array.from('.,;:!?)]}>»”’"\')]}」』】〕〉》…'));
36
+ /** The trigger character to use: the one given when it is one character, otherwise `#`. */
37
+ export function triggerCharacterOf(options) {
38
+ const candidate = options?.triggerCharacter;
39
+ return candidate !== undefined && Array.from(candidate).length === 1
40
+ ? candidate
41
+ : DEFAULT_TRIGGER_CHARACTER;
42
+ }
43
+ function escapeForRegularExpression(text) {
44
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
45
+ }
46
+ /** The `#word` pattern: the trigger character, then one to 24 label characters, and no label character after them. */
47
+ function referenceWordPattern(triggerCharacter) {
48
+ return new RegExp(`${escapeForRegularExpression(triggerCharacter)}([\\p{L}\\p{M}\\p{N}_]{1,${MAX_REFERENCE_LABEL_LENGTH}})(?![\\p{L}\\p{M}\\p{N}_])`, 'gu');
49
+ }
50
+ /** Whether a character is a space a person typed: whitespace, but not the figure space a token is made of. */
51
+ export function isRegularWhitespace(character) {
52
+ return character !== undefined && character !== FIGURE_SPACE && /\s/u.test(character);
53
+ }
54
+ /**
55
+ * Whether a reference may start at `index`: at the start of the text, or after whitespace, an opening bracket or a quote, or after
56
+ * the room of a badge (a badge's figure spaces are blanks like any other: `#` typed straight after a badge starts the next one, and
57
+ * the `#` of a badge itself has its own leading room before it). Never in the middle of a word, a URL or an anchor (`a#b`,
58
+ * `site.com/#top`, `&#39;`).
59
+ */
60
+ export function canStartReferenceAt(text, index) {
61
+ if (index <= 0)
62
+ return true;
63
+ if (text[index - 1] === FIGURE_SPACE)
64
+ return true;
65
+ const before = Array.from(text.slice(Math.max(0, index - 2), index)).pop();
66
+ return isRegularWhitespace(before) || (before !== undefined && OPENING_PUNCTUATION.has(before));
67
+ }
68
+ /** Every `#word` in the text that a reference may start at, whether it has rooms (a badge) or not (typed by hand), in order. */
69
+ export function findReferenceWords(text, options) {
70
+ const words = [];
71
+ for (const match of text.matchAll(referenceWordPattern(triggerCharacterOf(options)))) {
72
+ const triggerIndex = match.index ?? 0;
73
+ if (!canStartReferenceAt(text, triggerIndex))
74
+ continue;
75
+ words.push({ triggerIndex, label: match[1], labelEnd: triggerIndex + match[0].length });
76
+ }
77
+ return words;
78
+ }
79
+ /** How many figure spaces end exactly at `index` (walking back), and how many start at it (walking forward). */
80
+ function figureSpacesBefore(text, index) {
81
+ let count = 0;
82
+ while (index - count - 1 >= 0 && text[index - count - 1] === FIGURE_SPACE)
83
+ count += 1;
84
+ return count;
85
+ }
86
+ function figureSpacesAfter(text, index) {
87
+ let count = 0;
88
+ while (index + count < text.length && text[index + count] === FIGURE_SPACE)
89
+ count += 1;
90
+ return count;
91
+ }
92
+ /**
93
+ * The tokens in the text, in order: a `#label` with at least one figure space on each side. A `#label` with none on a side is plain
94
+ * text (typed by hand, or a token a browser took a space out of). When two tokens touch, the run between them is shared in the
95
+ * proportion tokens are made in, so each still has room on both sides.
96
+ */
97
+ export function parseTokens(text, options) {
98
+ if (!text.includes(FIGURE_SPACE))
99
+ return [];
100
+ const candidates = [];
101
+ for (const word of findReferenceWords(text, options)) {
102
+ const leading = figureSpacesBefore(text, word.triggerIndex);
103
+ const trailing = figureSpacesAfter(text, word.labelEnd);
104
+ if (leading < 1 || trailing < 1)
105
+ continue;
106
+ candidates.push({
107
+ start: word.triggerIndex - leading,
108
+ end: word.labelEnd + trailing,
109
+ triggerIndex: word.triggerIndex,
110
+ labelStart: word.triggerIndex + 1,
111
+ labelEnd: word.labelEnd,
112
+ label: word.label,
113
+ room: { leading, trailing }
114
+ });
115
+ }
116
+ // Two tokens that touch both found the whole run between them as theirs: it is shared, or the later one is not a token.
117
+ const tokens = [];
118
+ for (const candidate of candidates) {
119
+ const previous = tokens[tokens.length - 1];
120
+ if (!previous || previous.end <= candidate.start) {
121
+ tokens.push(candidate);
122
+ continue;
123
+ }
124
+ const sharedRun = candidate.triggerIndex - previous.labelEnd;
125
+ if (sharedRun < 2)
126
+ continue;
127
+ const leading = Math.max(1, Math.min(sharedRun - 1, Math.round(sharedRun * LEADING_SHARE_OF_SHARED_RUN)));
128
+ previous.end = candidate.triggerIndex - leading;
129
+ previous.room = { ...previous.room, trailing: previous.end - previous.labelEnd };
130
+ tokens.push({
131
+ ...candidate,
132
+ start: candidate.triggerIndex - leading,
133
+ room: { ...candidate.room, leading }
134
+ });
135
+ }
136
+ return tokens;
137
+ }
138
+ /** How many figure spaces each room needs, from the measured width of one (in pixels). A width that is not usable gives the defaults. */
139
+ export function roomForFigureSpaceWidth(figureSpaceWidth, pixels = BADGE_ROOM_PIXELS) {
140
+ if (!Number.isFinite(figureSpaceWidth) || figureSpaceWidth <= 0)
141
+ return { ...DEFAULT_TOKEN_ROOM };
142
+ const spacesFor = (width) => Math.min(MAX_ROOM_SPACES, Math.max(1, Math.ceil(width / figureSpaceWidth)));
143
+ return { leading: spacesFor(pixels.leading), trailing: spacesFor(pixels.trailing) };
144
+ }
145
+ /**
146
+ * The text of one token: the leading room, the trigger character and the label, the trailing room. A label that is not a valid label
147
+ * (it has a space, or is too long) is written plain, as `#label` with no rooms, so a bad label can never become a badge.
148
+ */
149
+ export function buildToken(label, room = DEFAULT_TOKEN_ROOM, options) {
150
+ const trigger = triggerCharacterOf(options);
151
+ if (!isValidReferenceLabel(label))
152
+ return `${trigger}${label}`;
153
+ const spaces = (requested, fallback) => Math.min(MAX_ROOM_SPACES, Math.max(1, Math.floor(Number.isFinite(requested) ? requested : fallback)));
154
+ const leading = spaces(room.leading, DEFAULT_TOKEN_ROOM.leading);
155
+ const trailing = spaces(room.trailing, DEFAULT_TOKEN_ROOM.trailing);
156
+ return `${FIGURE_SPACE.repeat(leading)}${trigger}${label}${FIGURE_SPACE.repeat(trailing)}`;
157
+ }
158
+ /** The text with every figure space taken out: what is sent, kept in history and read by the model ("fix #hero_banner"). */
159
+ export function normalizeForSend(text) {
160
+ return text.includes(FIGURE_SPACE) ? text.split(FIGURE_SPACE).join('') : text;
161
+ }
162
+ /**
163
+ * The text as a suggestion service may see it: each reference (a badge, and a hand-typed `#label` that names an attached file) is
164
+ * the neutral word `#file`, and the rooms are gone. A person's file names are theirs; the model that completes a sentence needs only
165
+ * to know that a file was mentioned.
166
+ */
167
+ export function neutralizeReferences(text, options) {
168
+ const trigger = triggerCharacterOf(options);
169
+ const neutral = `${trigger}${options?.neutralWord ?? 'file'}`;
170
+ const known = new Set(Array.from(options?.knownLabels ?? [], (label) => label.toLowerCase()));
171
+ // Badges first (with their rooms), from the end so earlier positions stay valid.
172
+ let result = text;
173
+ for (const token of parseTokens(result, options).reverse()) {
174
+ result = `${result.slice(0, token.start)}${neutral}${result.slice(token.end)}`;
175
+ }
176
+ result = normalizeForSend(result);
177
+ if (known.size === 0)
178
+ return result;
179
+ const words = findReferenceWords(result, options).filter((word) => known.has(word.label.toLowerCase()));
180
+ for (const word of words.reverse()) {
181
+ result = `${result.slice(0, word.triggerIndex)}${neutral}${result.slice(word.labelEnd)}`;
182
+ }
183
+ return result;
184
+ }
185
+ /**
186
+ * A selection moved so that no end of it rests INSIDE a token:
187
+ * - a caret inside a token goes to the edge it was heading for (with a previous caret), or to the nearest edge;
188
+ * - a range that starts or ends inside a token grows outward to cover it.
189
+ * Returns the very same object when nothing had to move.
190
+ */
191
+ export function snapSelection(text, selection, options) {
192
+ const tokens = options?.tokens ?? parseTokens(text, options);
193
+ if (tokens.length === 0)
194
+ return selection;
195
+ const inside = (position) => tokens.find((token) => position > token.start && position < token.end);
196
+ if (selection.start === selection.end) {
197
+ const token = inside(selection.start);
198
+ if (!token)
199
+ return selection;
200
+ const previous = options?.previousCaret;
201
+ let edge;
202
+ if (previous !== undefined && previous < selection.start)
203
+ edge = token.end;
204
+ else if (previous !== undefined && previous > selection.start)
205
+ edge = token.start;
206
+ else
207
+ edge = selection.start - token.start <= token.end - selection.start ? token.start : token.end;
208
+ return { start: edge, end: edge };
209
+ }
210
+ const first = Math.min(selection.start, selection.end);
211
+ const last = Math.max(selection.start, selection.end);
212
+ const startToken = inside(first);
213
+ const endToken = inside(last);
214
+ if (!startToken && !endToken)
215
+ return selection;
216
+ return { start: startToken ? startToken.start : first, end: endToken ? endToken.end : last };
217
+ }
218
+ /**
219
+ * What to cut to take a token out: the token, and one space of the pair around it, so no double space is left (`fix [T] now` becomes
220
+ * `fix now`). A token at an edge of the text takes the one space on its inside.
221
+ */
222
+ export function removalRangeOf(text, token) {
223
+ let from = token.start;
224
+ let to = token.end;
225
+ const before = from > 0 ? text[from - 1] : undefined;
226
+ const after = to < text.length ? text[to] : undefined;
227
+ if (before === ' ' && after === ' ')
228
+ to += 1;
229
+ else if (before === undefined && after === ' ')
230
+ to += 1;
231
+ else if (after === undefined && before === ' ')
232
+ from -= 1;
233
+ return { from, to };
234
+ }
235
+ /** The text with one token taken out, and where the caret goes (where the token was). */
236
+ export function removeToken(text, token) {
237
+ const { from, to } = removalRangeOf(text, token);
238
+ return { text: `${text.slice(0, from)}${text.slice(to)}`, caret: from, from, to };
239
+ }
240
+ /**
241
+ * The text without the badges of one file (a file leaves the tray): each token with that label is taken out with one adjacent space.
242
+ * A `#label` typed by hand stays: it is the person's own word. `removed` is how many badges went.
243
+ */
244
+ export function removeTokensOfLabel(text, label, options) {
245
+ const wanted = label.toLowerCase();
246
+ let result = text;
247
+ let removed = 0;
248
+ for (const token of parseTokens(text, options)
249
+ .filter((candidate) => candidate.label.toLowerCase() === wanted)
250
+ .reverse()) {
251
+ result = removeToken(result, token).text;
252
+ removed += 1;
253
+ }
254
+ return { text: result, removed };
255
+ }
256
+ /**
257
+ * The text with the rooms taken out of every token whose file is not attached any more (a draft restored after its file is gone):
258
+ * the token is plain `#label` again, so it can never show a badge for a picture that is not there.
259
+ */
260
+ export function unbadgeTokensWithoutFiles(text, knownLabels, options) {
261
+ const known = new Set(Array.from(knownLabels, (label) => label.toLowerCase()));
262
+ let result = text;
263
+ for (const token of parseTokens(text, options).reverse()) {
264
+ if (known.has(token.label.toLowerCase()))
265
+ continue;
266
+ result = `${result.slice(0, token.start)}${triggerCharacterOf(options)}${token.label}${result.slice(token.end)}`;
267
+ }
268
+ return result;
269
+ }
270
+ /**
271
+ * How a menu choice is written into the text. `trigger` is where the person's `#` and the word after it are (from `findReferenceTrigger`).
272
+ * The token replaces them, and a space follows it so typing goes on at once, unless a space or closing punctuation is already there.
273
+ */
274
+ export function planTokenInsertion(text, trigger, label, options) {
275
+ const next = trigger.end < text.length ? Array.from(text.slice(trigger.end, trigger.end + 2))[0] : undefined;
276
+ const needsSpace = next === undefined || !(isRegularWhitespace(next) || CLOSING_PUNCTUATION.has(next));
277
+ const insertion = `${buildToken(label, options?.room ?? DEFAULT_TOKEN_ROOM, options)}${needsSpace ? ' ' : ''}`;
278
+ return {
279
+ from: trigger.start,
280
+ to: trigger.end,
281
+ insertion,
282
+ caret: trigger.start + insertion.length
283
+ };
284
+ }
285
+ /**
286
+ * Every place the text names a file, in order: the badges (a token is a reference whatever stands before it, so two badges that touch
287
+ * stay two) and the `#label` words typed by hand. One entry per `#`.
288
+ */
289
+ export function referenceOccurrences(text, options) {
290
+ const byPosition = new Map();
291
+ for (const word of findReferenceWords(text, options))
292
+ byPosition.set(word.triggerIndex, word);
293
+ for (const token of parseTokens(text, options)) {
294
+ byPosition.set(token.triggerIndex, {
295
+ triggerIndex: token.triggerIndex,
296
+ label: token.label,
297
+ labelEnd: token.labelEnd
298
+ });
299
+ }
300
+ return [...byPosition.values()].sort((first, second) => first.triggerIndex - second.triggerIndex);
301
+ }
302
+ /**
303
+ * The references a message makes: each `#label` word in it that names a file still attached, in order of first appearance, once per
304
+ * file. A badge and a `#label` typed by hand count the same. A label is matched without regard to case; the answer carries the file's
305
+ * own label. Files that are not attached (or have no label) are never named.
306
+ */
307
+ export function collectReferences(text, attachments, options) {
308
+ const byLabel = new Map();
309
+ for (const attachment of attachments) {
310
+ const label = attachment.label;
311
+ if (typeof label !== 'string' || !isValidReferenceLabel(label))
312
+ continue;
313
+ // Two files with one label cannot happen when labels are assigned here; if they do, the first stays the one the word means.
314
+ if (!byLabel.has(label.toLowerCase()))
315
+ byLabel.set(label.toLowerCase(), { ...attachment, label });
316
+ }
317
+ if (byLabel.size === 0)
318
+ return [];
319
+ const max = options?.max === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.floor(options.max));
320
+ const seen = new Set();
321
+ const collected = [];
322
+ for (const word of referenceOccurrences(text, options)) {
323
+ if (collected.length >= max)
324
+ break;
325
+ const attachment = byLabel.get(word.label.toLowerCase());
326
+ if (!attachment || seen.has(attachment.id))
327
+ continue;
328
+ seen.add(attachment.id);
329
+ collected.push({ id: attachment.id, label: attachment.label });
330
+ }
331
+ return collected;
332
+ }
@@ -0,0 +1,52 @@
1
+ import { type TokenReadingOptions } from './referenceTokens.ts';
2
+ /** A `#` the person is typing a reference after. */
3
+ export interface ReferenceTrigger {
4
+ /** Where the trigger character is. */
5
+ start: number;
6
+ /** The caret: the end of what was typed after the trigger character. */
7
+ end: number;
8
+ /** What was typed after the trigger character (`her` in `#her`; empty right after `#`). */
9
+ query: string;
10
+ }
11
+ /**
12
+ * The reference the person is starting at the caret, or null. It is one when the caret ends a word made of the trigger character and
13
+ * up to 24 label characters, and the trigger character may start a reference where it stands: at the start of the text or after
14
+ * whitespace, an opening bracket or a quote, never inside a word, a URL or an anchor (`a#b`, `site.com/#top`). Nothing after the
15
+ * caret may continue the word (a `#` typed in front of an existing word is not a reference), and the `#` of a badge that is already
16
+ * in the text is never a new one.
17
+ */
18
+ export declare function findReferenceTrigger(text: string, caret: number, options?: TokenReadingOptions): ReferenceTrigger | null;
19
+ /** What the menu needs to know about a file to offer it. */
20
+ export interface ReferenceMenuCandidate {
21
+ /** The label the file would be written as (without the trigger character). */
22
+ label: string;
23
+ /** The file's number in the tray, counted from 1: `#2` offers the second file. */
24
+ number: number;
25
+ /** The name of the file, which a person may also start typing. */
26
+ fileName?: string;
27
+ }
28
+ /**
29
+ * The files a query offers, best first: those whose label starts with it, then those whose tray number starts with it (when it is
30
+ * digits), then those with a word of the label or the file name that starts with it. An empty query offers every file, in tray order.
31
+ * The order among equals is the tray's.
32
+ */
33
+ export declare function matchReferenceItems<T extends ReferenceMenuCandidate>(items: readonly T[], query: string): T[];
34
+ /** The menu as it should be shown right now. */
35
+ export interface ReferenceMenuState<T extends ReferenceMenuCandidate> {
36
+ trigger: ReferenceTrigger;
37
+ /** The files to list: never empty (a menu with nothing to list is not shown). */
38
+ matches: T[];
39
+ }
40
+ export interface ResolveReferenceMenuOptions extends TokenReadingOptions {
41
+ /**
42
+ * Where the trigger character was when the person pressed Esc on this word. The menu stays closed for that word, and opens again
43
+ * for the next one.
44
+ */
45
+ dismissedTriggerStart?: number | null;
46
+ }
47
+ /**
48
+ * Whether the menu shows for this text and caret, and what it lists: the trigger, narrowed by what was typed after it. It does not
49
+ * show when there is no trigger, when the person closed it for this word, or when no file matches (so a colour written in hex after
50
+ * the trigger character passes through, and so does any word no file starts with).
51
+ */
52
+ export declare function resolveReferenceMenu<T extends ReferenceMenuCandidate>(text: string, caret: number, items: readonly T[], options?: ResolveReferenceMenuOptions): ReferenceMenuState<T> | null;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * When the `#` menu opens, and which files it lists. Pure functions, no DOM.
3
+ *
4
+ * The menu is an offer, never a trap: it opens only where a person is plainly starting a reference, and it goes away by itself, with
5
+ * the text kept as typed, as soon as the person is plainly typing something else (a hex colour, a link with an anchor, a hashtag no
6
+ * file matches, a space).
7
+ */
8
+ import { MAX_REFERENCE_LABEL_LENGTH } from "./referenceLabels.js";
9
+ import { canStartReferenceAt, parseTokens, triggerCharacterOf } from "./referenceTokens.js";
10
+ const LABEL_CHARACTER = /[\p{L}\p{M}\p{N}_]/u;
11
+ /** The character at `index` as a whole character (a character outside the basic plane is two units). */
12
+ function characterBefore(text, index) {
13
+ return index <= 0 ? undefined : Array.from(text.slice(Math.max(0, index - 2), index)).pop();
14
+ }
15
+ function characterAt(text, index) {
16
+ return index >= text.length ? undefined : Array.from(text.slice(index, index + 2))[0];
17
+ }
18
+ /**
19
+ * The reference the person is starting at the caret, or null. It is one when the caret ends a word made of the trigger character and
20
+ * up to 24 label characters, and the trigger character may start a reference where it stands: at the start of the text or after
21
+ * whitespace, an opening bracket or a quote, never inside a word, a URL or an anchor (`a#b`, `site.com/#top`). Nothing after the
22
+ * caret may continue the word (a `#` typed in front of an existing word is not a reference), and the `#` of a badge that is already
23
+ * in the text is never a new one.
24
+ */
25
+ export function findReferenceTrigger(text, caret, options) {
26
+ if (!Number.isInteger(caret) || caret < 0 || caret > text.length)
27
+ return null;
28
+ const trigger = triggerCharacterOf(options);
29
+ const after = characterAt(text, caret);
30
+ if (after !== undefined && LABEL_CHARACTER.test(after))
31
+ return null;
32
+ // Walk back over the word typed so far, one character at a time, and no further than a label can be.
33
+ let index = caret;
34
+ let typedCharacters = 0;
35
+ for (;;) {
36
+ const before = characterBefore(text, index);
37
+ if (before === undefined || !LABEL_CHARACTER.test(before))
38
+ break;
39
+ typedCharacters += 1;
40
+ if (typedCharacters > MAX_REFERENCE_LABEL_LENGTH)
41
+ return null;
42
+ index -= before.length;
43
+ }
44
+ if (characterBefore(text, index) !== trigger)
45
+ return null;
46
+ const triggerIndex = index - trigger.length;
47
+ if (!canStartReferenceAt(text, triggerIndex))
48
+ return null;
49
+ if (parseTokens(text, options).some((token) => token.triggerIndex === triggerIndex))
50
+ return null;
51
+ return { start: triggerIndex, end: caret, query: text.slice(index, caret) };
52
+ }
53
+ /** The lower-case words of a label, split at underscores: `hero_banner` has `hero` and `banner`. */
54
+ function wordsOfLabel(label) {
55
+ return label.toLowerCase().split('_').filter(Boolean);
56
+ }
57
+ /**
58
+ * The files a query offers, best first: those whose label starts with it, then those whose tray number starts with it (when it is
59
+ * digits), then those with a word of the label or the file name that starts with it. An empty query offers every file, in tray order.
60
+ * The order among equals is the tray's.
61
+ */
62
+ export function matchReferenceItems(items, query) {
63
+ if (query === '')
64
+ return [...items];
65
+ const wanted = query.toLowerCase();
66
+ const digitsOnly = /^\d+$/.test(wanted);
67
+ const ranked = [];
68
+ items.forEach((item, order) => {
69
+ const label = item.label.toLowerCase();
70
+ let rank = -1;
71
+ if (label.startsWith(wanted))
72
+ rank = 0;
73
+ else if (digitsOnly && String(item.number).startsWith(wanted))
74
+ rank = 1;
75
+ else if (wordsOfLabel(item.label).some((word) => word.startsWith(wanted)))
76
+ rank = 2;
77
+ else if (item.fileName && item.fileName.toLowerCase().startsWith(wanted))
78
+ rank = 3;
79
+ if (rank >= 0)
80
+ ranked.push({ item, rank, order });
81
+ });
82
+ ranked.sort((first, second) => first.rank - second.rank || first.order - second.order);
83
+ return ranked.map((entry) => entry.item);
84
+ }
85
+ /**
86
+ * Whether the menu shows for this text and caret, and what it lists: the trigger, narrowed by what was typed after it. It does not
87
+ * show when there is no trigger, when the person closed it for this word, or when no file matches (so a colour written in hex after
88
+ * the trigger character passes through, and so does any word no file starts with).
89
+ */
90
+ export function resolveReferenceMenu(text, caret, items, options) {
91
+ if (items.length === 0)
92
+ return null;
93
+ const trigger = findReferenceTrigger(text, caret, options);
94
+ if (!trigger)
95
+ return null;
96
+ if (options?.dismissedTriggerStart != null && options.dismissedTriggerStart === trigger.start)
97
+ return null;
98
+ const matches = matchReferenceItems(items, trigger.query);
99
+ return matches.length === 0 ? null : { trigger, matches };
100
+ }