@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,51 @@
1
+ /**
2
+ * Pointer routing for the number stepper value hit area (`NumberControls.svelte`).
3
+ * Kept pure so Node can test the rules without mounting Svelte.
4
+ */
5
+ function hasClosest(target) {
6
+ return (typeof target === 'object' &&
7
+ target !== null &&
8
+ 'closest' in target &&
9
+ typeof target.closest === 'function');
10
+ }
11
+ /**
12
+ * True when a mousedown on this target should focus the number input instead of letting the
13
+ * browser move focus to `body` or start a document-level selection in dead space beside the digits.
14
+ */
15
+ export function shouldRoutePointerToNumberInput(target, inputId) {
16
+ if (!hasClosest(target))
17
+ return false;
18
+ if (target.closest('button'))
19
+ return false;
20
+ const input = document.getElementById(inputId);
21
+ if (!input || !('value' in input))
22
+ return false;
23
+ if (target === input)
24
+ return false;
25
+ return Boolean(target.closest('.number-controls-hit-area'));
26
+ }
27
+ /** Caret placement after routing a press into the field. */
28
+ export function selectionAfterValueAreaPress(value, extendSelection) {
29
+ if (extendSelection) {
30
+ return { start: 0, end: value.length };
31
+ }
32
+ const end = value.length;
33
+ return { start: end, end };
34
+ }
35
+ /**
36
+ * True when the pointer is in the empty stretch of an auto-sized field after the last digit
37
+ * (HTML `size` / average ch-width used to leave this dead band).
38
+ */
39
+ export function isPointerPastTextEnd(text, inputLeft, clientX, textWidth) {
40
+ return clientX - inputLeft > textWidth + 0.5;
41
+ }
42
+ /** While dragging from empty chrome into the digits, select the whole value for the next key. */
43
+ export function selectionWhileDraggingFromValueChrome(valueLength, pointerPastTextEnd, extendSelection) {
44
+ if (valueLength === 0)
45
+ return null;
46
+ if (extendSelection)
47
+ return { start: 0, end: valueLength };
48
+ if (pointerPastTextEnd)
49
+ return null;
50
+ return { start: 0, end: valueLength };
51
+ }
@@ -0,0 +1 @@
1
+ export { default as TextFlip } from './text-flip.svelte';
@@ -0,0 +1 @@
1
+ export { default as TextFlip } from './text-flip.svelte';
@@ -0,0 +1,103 @@
1
+ <!--
2
+ TextFlip: a text that changes by sliding its letters up, one at a time. Only the letters that differ move ("9 of 12" becomes
3
+ "10 of 12" by flipping the 9 and bringing in a 0), each inside a box of its own that clips it, so a count or a status word ticks
4
+ over in place instead of jumping.
5
+
6
+ <TextFlip text={progressLabel} />
7
+
8
+ It is for short text that changes (a count, a status word): the letters sit in boxes of their own, so keep it off paragraphs.
9
+ A screen reader gets the whole text once and skips the boxes. With reduced motion the text simply changes.
10
+ -->
11
+ <script lang="ts">
12
+ import { untrack } from 'svelte';
13
+ import type { HTMLAttributes } from 'svelte/elements';
14
+ import { cn } from '../../../utils.js';
15
+ import {
16
+ FLIP_DURATION_MS,
17
+ FLIP_STAGGER_MS,
18
+ createSlots,
19
+ flipDelayMs,
20
+ flipIn,
21
+ flipOut,
22
+ flipSlots,
23
+ splitIntoLetters,
24
+ type FlipSlot
25
+ } from './textFlipLogic.js';
26
+
27
+ type Props = HTMLAttributes<HTMLSpanElement> & {
28
+ class?: string;
29
+ /** The text to show. When it changes, only the letters that differ flip. */
30
+ text: string;
31
+ /** Whether the first text slides in too, letter by letter. Off: it is simply there from the start. */
32
+ appear?: boolean;
33
+ /** How long one letter takes to slide, in ms. */
34
+ durationMs?: number;
35
+ /** How long one letter waits for the one before it, in ms. */
36
+ staggerMs?: number;
37
+ };
38
+
39
+ let {
40
+ class: className,
41
+ text,
42
+ appear = true,
43
+ durationMs = FLIP_DURATION_MS,
44
+ staggerMs = FLIP_STAGGER_MS,
45
+ ...restProps
46
+ }: Props = $props();
47
+
48
+ let lastSlotId = 0;
49
+ const allocateSlotId = (): number => lastSlotId++;
50
+
51
+ // The boxes on screen, one per letter. They are replaced as a whole on every change, so they need no deep reactivity.
52
+ let slots = $state.raw<readonly FlipSlot[]>(
53
+ createSlots(
54
+ splitIntoLetters(untrack(() => text)),
55
+ allocateSlotId,
56
+ untrack(() => appear)
57
+ )
58
+ );
59
+ // The text the boxes spell right now: the effect below acts only when `text` is another one.
60
+ let spelledText = untrack(() => text);
61
+
62
+ // A new text: the letters that differ flip. The new boxes depend on the boxes there were (which letters stay, which box is reused),
63
+ // and a `$derived` cannot see its own previous value, so this is state kept in step with the prop. `$effect.pre` runs before the page
64
+ // is painted, so no frame shows the new text unflipped. A box that lost its letter stays, empty and without width, and is reused by
65
+ // the next text that grows there.
66
+ $effect.pre(() => {
67
+ const incomingText = text;
68
+ if (incomingText === spelledText) return;
69
+ try {
70
+ slots = flipSlots(
71
+ untrack(() => slots),
72
+ splitIntoLetters(incomingText),
73
+ allocateSlotId
74
+ );
75
+ } catch (error) {
76
+ // A text must always get on screen, flipped or not
77
+ console.warn('[TextFlip] The letters could not flip; showing the new text without it', error);
78
+ slots = createSlots(splitIntoLetters(incomingText), allocateSlotId, false);
79
+ }
80
+ spelledText = incomingText;
81
+ });
82
+ </script>
83
+
84
+ <span class={cn('inline-flex tabular-nums', className)} {...restProps}>
85
+ <span class="sr-only">{text}</span>
86
+ <span class="inline-flex" aria-hidden="true">
87
+ {#each slots as slot (slot.slotId)}
88
+ <!-- The box keeps its place and clips the letter that slides through it (`whitespace-pre`: a space is a letter too) -->
89
+ <span class="inline-grid overflow-y-clip whitespace-pre">
90
+ {#key slot.letter}
91
+ <span
92
+ class="col-start-1 row-start-1"
93
+ in:flipIn|global={{
94
+ durationMs: slot.animate ? durationMs : 0,
95
+ delayMs: flipDelayMs(slot.flipOrder, staggerMs)
96
+ }}
97
+ out:flipOut={{ durationMs, delayMs: flipDelayMs(slot.flipOrder, staggerMs) }}>{slot.letter}</span
98
+ >
99
+ {/key}
100
+ </span>
101
+ {/each}
102
+ </span>
103
+ </span>
@@ -0,0 +1,15 @@
1
+ import type { HTMLAttributes } from 'svelte/elements';
2
+ type Props = HTMLAttributes<HTMLSpanElement> & {
3
+ class?: string;
4
+ /** The text to show. When it changes, only the letters that differ flip. */
5
+ text: string;
6
+ /** Whether the first text slides in too, letter by letter. Off: it is simply there from the start. */
7
+ appear?: boolean;
8
+ /** How long one letter takes to slide, in ms. */
9
+ durationMs?: number;
10
+ /** How long one letter waits for the one before it, in ms. */
11
+ staggerMs?: number;
12
+ };
13
+ declare const TextFlip: import("svelte").Component<Props, {}, "">;
14
+ type TextFlip = ReturnType<typeof TextFlip>;
15
+ export default TextFlip;
@@ -0,0 +1,49 @@
1
+ import type { TransitionConfig } from 'svelte/transition';
2
+ /** How long one letter takes to slide, in ms: long enough to be followed, short enough for a counter that ticks often. */
3
+ export declare const FLIP_DURATION_MS = 280;
4
+ /** The wait between one letter and the next, in ms: they go one at a time, in the order of the text. */
5
+ export declare const FLIP_STAGGER_MS = 60;
6
+ /** A long text does not make its last letter wait for ever: the wait stops growing at this many ms. */
7
+ export declare const FLIP_MAX_STAGGER_SPAN_MS = 600;
8
+ /** The box one letter lives in. */
9
+ export type FlipSlot = {
10
+ /**
11
+ * Who the box is. It stays the same while the letter inside changes, so the old letter slides out of it and the new one slides in,
12
+ * and it is what the page keys the boxes by.
13
+ */
14
+ slotId: number;
15
+ /** The letter in the box (or an unbroken run of a joining script, see `splitIntoLetters`). '' while the box is being emptied. */
16
+ letter: string;
17
+ /** False for the letters that are simply there from the start (`appear` off): they do not slide. */
18
+ animate: boolean;
19
+ /** Place among the letters that flip together, from 0: the stagger multiplies it. */
20
+ flipOrder: number;
21
+ };
22
+ export type FlipTransitionParams = {
23
+ durationMs: number;
24
+ delayMs: number;
25
+ };
26
+ /**
27
+ * The letters of a text, one per box. A word of a joining script (Arabic, Syriac, Mongolian...) is one box, because its letters change
28
+ * shape with their neighbours and cannot sit in boxes of their own.
29
+ */
30
+ export declare function splitIntoLetters(text: string): string[];
31
+ /** A box for every letter of the first text. `animate` says whether they slide in or are simply there. */
32
+ export declare function createSlots(letters: readonly string[], allocateSlotId: () => number, animate: boolean): FlipSlot[];
33
+ /**
34
+ * The boxes after the text became another one. The letters the two texts share at the start and at the end stay where they are
35
+ * ("9 of 12" becomes "10 of 12" by flipping the 9 and adding a 0, not by flipping everything after it). In the stretch between them
36
+ * a box takes the new letter in the same place, a box is added when the text grew, and a box is emptied when the text got shorter:
37
+ * its letter slides out and the empty box (no width) waits there for the next text that grows in that place.
38
+ */
39
+ export declare function flipSlots(previousSlots: readonly FlipSlot[], nextLetters: readonly string[], allocateSlotId: () => number): FlipSlot[];
40
+ /** How long a letter waits for its turn, in ms. */
41
+ export declare function flipDelayMs(flipOrder: number, staggerMs: number): number;
42
+ /** The style of a letter that arrives, from just below its box (`remaining` 1) to its place (`remaining` 0). */
43
+ export declare function arrivingLetterStyle(progress: number, remaining: number): string;
44
+ /** The style of a letter that leaves, from its place (`remaining` 0) to just above its box (`remaining` 1). */
45
+ export declare function leavingLetterStyle(progress: number, remaining: number): string;
46
+ /** Svelte transition: the new letter slides up into its box. With reduced motion it is simply there. */
47
+ export declare function flipIn(_node: Element, { durationMs, delayMs }: FlipTransitionParams): TransitionConfig;
48
+ /** Svelte transition: the old letter slides up out of its box. With reduced motion it is simply gone. */
49
+ export declare function flipOut(_node: Element, { durationMs, delayMs }: FlipTransitionParams): TransitionConfig;
@@ -0,0 +1,151 @@
1
+ /**
2
+ * TextFlip: when a text is replaced by another, only the letters that differ slide away (up) and their replacements slide in from
3
+ * below, one letter at a time. This file is the part that needs no page: which letters are on screen, which of them change, in what
4
+ * order, and how a letter moves. The component (`text-flip.svelte`) only draws it.
5
+ */
6
+ import { cubicOut } from 'svelte/easing';
7
+ import { prefersReducedMotion } from "../../../utils/reducedMotion.js";
8
+ /** How long one letter takes to slide, in ms: long enough to be followed, short enough for a counter that ticks often. */
9
+ export const FLIP_DURATION_MS = 280;
10
+ /** The wait between one letter and the next, in ms: they go one at a time, in the order of the text. */
11
+ export const FLIP_STAGGER_MS = 60;
12
+ /** A long text does not make its last letter wait for ever: the wait stops growing at this many ms. */
13
+ export const FLIP_MAX_STAGGER_SPAN_MS = 600;
14
+ /**
15
+ * The scripts whose letters join their neighbours: each letter takes its shape from the letters beside it, so a word of them cannot be
16
+ * cut into boxes without breaking it into isolated letters. A run of their letters is kept together, as one "letter".
17
+ * Only letters count (`\p{L}`): the digits of these scripts belong to them too (Arabic-Indic digits are of the Arabic script), but they
18
+ * do not join anything, so the digits of a count still flip one by one.
19
+ */
20
+ const joiningScriptLetter = /^(?=\p{L})[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Mongolian}\p{Script=Nko}\p{Script=Mandaic}\p{Script=Adlam}\p{Script=Hanifi_Rohingya}]/u;
21
+ /** undefined: not tried yet. null: this browser has no `Intl.Segmenter`. */
22
+ let graphemeSegmenter;
23
+ /** The letters of a text as a person sees them (an "é" made of two characters is one letter), or code points without `Intl.Segmenter`. */
24
+ function splitIntoGraphemes(text) {
25
+ if (graphemeSegmenter === undefined) {
26
+ try {
27
+ graphemeSegmenter =
28
+ typeof Intl !== 'undefined' && 'Segmenter' in Intl
29
+ ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
30
+ : null;
31
+ }
32
+ catch (error) {
33
+ graphemeSegmenter = null;
34
+ console.warn('[TextFlip] The letters of the text could not be told apart; using code points', error);
35
+ }
36
+ }
37
+ if (!graphemeSegmenter)
38
+ return Array.from(text);
39
+ return Array.from(graphemeSegmenter.segment(text), (part) => part.segment);
40
+ }
41
+ /**
42
+ * The letters of a text, one per box. A word of a joining script (Arabic, Syriac, Mongolian...) is one box, because its letters change
43
+ * shape with their neighbours and cannot sit in boxes of their own.
44
+ */
45
+ export function splitIntoLetters(text) {
46
+ const letters = [];
47
+ let previousJoins = false;
48
+ for (const grapheme of splitIntoGraphemes(text)) {
49
+ const joins = joiningScriptLetter.test(grapheme);
50
+ if (joins && previousJoins)
51
+ letters[letters.length - 1] += grapheme;
52
+ else
53
+ letters.push(grapheme);
54
+ previousJoins = joins;
55
+ }
56
+ return letters;
57
+ }
58
+ /** A box for every letter of the first text. `animate` says whether they slide in or are simply there. */
59
+ export function createSlots(letters, allocateSlotId, animate) {
60
+ return letters.map((letter, index) => ({
61
+ slotId: allocateSlotId(),
62
+ letter,
63
+ animate,
64
+ flipOrder: index
65
+ }));
66
+ }
67
+ /** How many letters, from the start, the two texts have in common. */
68
+ function countSharedStart(previousLetters, nextLetters) {
69
+ const limit = Math.min(previousLetters.length, nextLetters.length);
70
+ let count = 0;
71
+ while (count < limit && previousLetters[count] === nextLetters[count])
72
+ count += 1;
73
+ return count;
74
+ }
75
+ /** How many letters, from the end, the two texts have in common, without counting letters already counted from the start. */
76
+ function countSharedEnd(previousLetters, nextLetters, alreadyShared) {
77
+ const limit = Math.min(previousLetters.length, nextLetters.length) - alreadyShared;
78
+ let count = 0;
79
+ while (count < limit &&
80
+ previousLetters[previousLetters.length - 1 - count] === nextLetters[nextLetters.length - 1 - count]) {
81
+ count += 1;
82
+ }
83
+ return count;
84
+ }
85
+ /**
86
+ * The boxes after the text became another one. The letters the two texts share at the start and at the end stay where they are
87
+ * ("9 of 12" becomes "10 of 12" by flipping the 9 and adding a 0, not by flipping everything after it). In the stretch between them
88
+ * a box takes the new letter in the same place, a box is added when the text grew, and a box is emptied when the text got shorter:
89
+ * its letter slides out and the empty box (no width) waits there for the next text that grows in that place.
90
+ */
91
+ export function flipSlots(previousSlots, nextLetters, allocateSlotId) {
92
+ const previousLetters = previousSlots.map((slot) => slot.letter);
93
+ const sharedStartCount = countSharedStart(previousLetters, nextLetters);
94
+ const sharedEndCount = countSharedEnd(previousLetters, nextLetters, sharedStartCount);
95
+ const startSlots = previousSlots.slice(0, sharedStartCount);
96
+ const endSlots = previousSlots.slice(previousSlots.length - sharedEndCount);
97
+ const previousMiddle = previousSlots.slice(sharedStartCount, previousSlots.length - sharedEndCount);
98
+ const nextMiddle = nextLetters.slice(sharedStartCount, nextLetters.length - sharedEndCount);
99
+ const middleSlots = [];
100
+ let nextFlipOrder = 0;
101
+ const middleLength = Math.max(previousMiddle.length, nextMiddle.length);
102
+ for (let index = 0; index < middleLength; index += 1) {
103
+ const previousSlot = previousMiddle[index];
104
+ const nextLetter = nextMiddle[index] ?? '';
105
+ // The same letter inside the changed stretch has nothing to flip
106
+ if (previousSlot && previousSlot.letter === nextLetter) {
107
+ middleSlots.push(previousSlot);
108
+ continue;
109
+ }
110
+ middleSlots.push({
111
+ slotId: previousSlot ? previousSlot.slotId : allocateSlotId(),
112
+ letter: nextLetter,
113
+ animate: true,
114
+ flipOrder: nextFlipOrder
115
+ });
116
+ nextFlipOrder += 1;
117
+ }
118
+ return [...startSlots, ...middleSlots, ...endSlots];
119
+ }
120
+ /** How long a letter waits for its turn, in ms. */
121
+ export function flipDelayMs(flipOrder, staggerMs) {
122
+ return Math.min(Math.max(0, flipOrder) * Math.max(0, staggerMs), FLIP_MAX_STAGGER_SPAN_MS);
123
+ }
124
+ /** The style of a letter that arrives, from just below its box (`remaining` 1) to its place (`remaining` 0). */
125
+ export function arrivingLetterStyle(progress, remaining) {
126
+ return `transform: translateY(${remaining * 100}%); opacity: ${progress};`;
127
+ }
128
+ /** The style of a letter that leaves, from its place (`remaining` 0) to just above its box (`remaining` 1). */
129
+ export function leavingLetterStyle(progress, remaining) {
130
+ return `transform: translateY(${-remaining * 100}%); opacity: ${progress};`;
131
+ }
132
+ /** Svelte transition: the new letter slides up into its box. With reduced motion it is simply there. */
133
+ export function flipIn(_node, { durationMs, delayMs }) {
134
+ const motionAllowed = !prefersReducedMotion();
135
+ return {
136
+ delay: motionAllowed ? delayMs : 0,
137
+ duration: motionAllowed ? durationMs : 0,
138
+ easing: cubicOut,
139
+ css: arrivingLetterStyle
140
+ };
141
+ }
142
+ /** Svelte transition: the old letter slides up out of its box. With reduced motion it is simply gone. */
143
+ export function flipOut(_node, { durationMs, delayMs }) {
144
+ const motionAllowed = !prefersReducedMotion();
145
+ return {
146
+ delay: motionAllowed ? delayMs : 0,
147
+ duration: motionAllowed ? durationMs : 0,
148
+ easing: cubicOut,
149
+ css: leavingLetterStyle
150
+ };
151
+ }
@@ -0,0 +1,11 @@
1
+ import type { CompletionAnswer } from './completionTypes.ts';
2
+ /** The most continuations one answer keeps: the first is shown, the others take over when typing rules it out. */
3
+ export declare const MAX_CONTINUATIONS = 5;
4
+ /** The longest an answer may be kept, whatever the source says: an hour. */
5
+ export declare const MAX_ANSWER_TTL_MS: number;
6
+ /** How long a failed request is remembered, so a source that is down is not asked again at every keystroke. */
7
+ export declare const FAILED_REQUEST_TTL_MS = 10000;
8
+ /** The nothing-to-show answer, kept for `ttlMs` so the same text is not asked again at once. */
9
+ export declare function emptyAnswer(ttlMs?: number): CompletionAnswer;
10
+ /** The answer a source gave, cleaned. A shape that is neither a list nor an object with one is the empty answer. */
11
+ export declare function normalizeAnswer(like: unknown, defaultTtlMs?: number): CompletionAnswer;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Reads what a source answered: whatever shape it came in, the engine works on one (`CompletionAnswer`), with every continuation
3
+ * cleaned and an answer that is not usable read as "nothing to show". Pure.
4
+ */
5
+ import { DEFAULT_CACHE_TTL_MS } from "./completionCache.js";
6
+ import { cleanGhost } from "./completionText.js";
7
+ /** The most continuations one answer keeps: the first is shown, the others take over when typing rules it out. */
8
+ export const MAX_CONTINUATIONS = 5;
9
+ /** The longest an answer may be kept, whatever the source says: an hour. */
10
+ export const MAX_ANSWER_TTL_MS = 60 * 60 * 1000;
11
+ /** How long a failed request is remembered, so a source that is down is not asked again at every keystroke. */
12
+ export const FAILED_REQUEST_TTL_MS = 10_000;
13
+ const KNOWN_SOURCES = ['jev', 'prior', 'disabled'];
14
+ function sourceNameOf(raw) {
15
+ return typeof raw === 'string' && KNOWN_SOURCES.includes(raw)
16
+ ? raw
17
+ : 'unknown';
18
+ }
19
+ /** The nothing-to-show answer, kept for `ttlMs` so the same text is not asked again at once. */
20
+ export function emptyAnswer(ttlMs = DEFAULT_CACHE_TTL_MS) {
21
+ return { continuations: [], ttlMs, source: 'disabled' };
22
+ }
23
+ /** The answer a source gave, cleaned. A shape that is neither a list nor an object with one is the empty answer. */
24
+ export function normalizeAnswer(like, defaultTtlMs = DEFAULT_CACHE_TTL_MS) {
25
+ const raw = Array.isArray(like)
26
+ ? like
27
+ : like !== null && typeof like === 'object'
28
+ ? like.continuations
29
+ : undefined;
30
+ if (!Array.isArray(raw))
31
+ return emptyAnswer(defaultTtlMs);
32
+ const seen = new Set();
33
+ const continuations = [];
34
+ for (const item of raw) {
35
+ const cleaned = cleanGhost(item);
36
+ if (cleaned === '' || seen.has(cleaned))
37
+ continue;
38
+ seen.add(cleaned);
39
+ continuations.push(cleaned);
40
+ if (continuations.length >= MAX_CONTINUATIONS)
41
+ break;
42
+ }
43
+ const object = Array.isArray(like) ? undefined : like;
44
+ const ttl = object?.ttlMs;
45
+ const ttlMs = typeof ttl === 'number' && Number.isFinite(ttl) && ttl > 0
46
+ ? Math.min(ttl, MAX_ANSWER_TTL_MS)
47
+ : defaultTtlMs;
48
+ return { continuations, ttlMs, source: sourceNameOf(object?.source) };
49
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The answers the box has already been given, by the exact text it asked about. A person who deletes a word and types it again, or whose
3
+ * caret comes back to a text it has been at, is answered from here with no request. An answer lives as long as the gateway said it may
4
+ * (`ttlMs`), and the oldest-used answer goes first when the cache is full. Pure: the clock is a parameter.
5
+ */
6
+ /** How many answers one box keeps. A typing session visits a few dozen texts at most. */
7
+ export declare const DEFAULT_CACHE_MAX_ENTRIES = 100;
8
+ /** How long an answer lives when the source did not say: short, so a catalog change is never far off. */
9
+ export declare const DEFAULT_CACHE_TTL_MS = 30000;
10
+ export interface CompletionCache<Answer> {
11
+ /** The answer for exactly this text, or undefined when there is none or it has expired. A hit counts as use. */
12
+ get(text: string): Answer | undefined;
13
+ /** Keeps an answer for `ttlMs` milliseconds. A life of zero or less keeps nothing. */
14
+ set(text: string, answer: Answer, ttlMs: number): void;
15
+ clear(): void;
16
+ /** How many answers are held (expired ones that nobody asked for yet included). */
17
+ readonly size: number;
18
+ }
19
+ export interface CompletionCacheOptions {
20
+ maxEntries?: number;
21
+ /** The clock, in milliseconds. Defaults to `Date.now`. */
22
+ now?: () => number;
23
+ }
24
+ export declare function createCompletionCache<Answer>(options?: CompletionCacheOptions): CompletionCache<Answer>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The answers the box has already been given, by the exact text it asked about. A person who deletes a word and types it again, or whose
3
+ * caret comes back to a text it has been at, is answered from here with no request. An answer lives as long as the gateway said it may
4
+ * (`ttlMs`), and the oldest-used answer goes first when the cache is full. Pure: the clock is a parameter.
5
+ */
6
+ /** How many answers one box keeps. A typing session visits a few dozen texts at most. */
7
+ export const DEFAULT_CACHE_MAX_ENTRIES = 100;
8
+ /** How long an answer lives when the source did not say: short, so a catalog change is never far off. */
9
+ export const DEFAULT_CACHE_TTL_MS = 30_000;
10
+ export function createCompletionCache(options = {}) {
11
+ const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? DEFAULT_CACHE_MAX_ENTRIES));
12
+ const now = options.now ?? Date.now;
13
+ // A Map keeps insertion order, so the first key is the one used longest ago once a hit moves its entry to the end.
14
+ const entries = new Map();
15
+ return {
16
+ get(text) {
17
+ const entry = entries.get(text);
18
+ if (!entry)
19
+ return undefined;
20
+ if (entry.expiresAt <= now()) {
21
+ entries.delete(text);
22
+ return undefined;
23
+ }
24
+ entries.delete(text);
25
+ entries.set(text, entry);
26
+ return entry.answer;
27
+ },
28
+ set(text, answer, ttlMs) {
29
+ entries.delete(text);
30
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0)
31
+ return;
32
+ entries.set(text, { answer, expiresAt: now() + ttlMs });
33
+ while (entries.size > maxEntries) {
34
+ const oldest = entries.keys().next();
35
+ if (oldest.done)
36
+ break;
37
+ entries.delete(oldest.value);
38
+ }
39
+ },
40
+ clear() {
41
+ entries.clear();
42
+ },
43
+ get size() {
44
+ return entries.size;
45
+ }
46
+ };
47
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The state machine of the inline completion ("ghost text"): given what the field looks like now, which ghost (if any) shows, when to ask
3
+ * the source, what to do with an answer that comes back late, and what Tab and Esc mean. No DOM and no timers of its own (the host hands
4
+ * the scheduler in), so Node's test runner drives it step by step.
5
+ *
6
+ * How one answer lives (a "session"): the source answers for the text `base`; the continuations are what could follow it. As the person
7
+ * types, the ghost is the rest of the first continuation they are still following (type-through, no request); when they type something
8
+ * a continuation does not say, the session ends with `diverged` and a new request is made for the new text.
9
+ */
10
+ import { type CompletionCache } from './completionCache.ts';
11
+ import { type FieldSnapshot } from './completionText.ts';
12
+ import type { CompletionAnswer, GhostView, InlineCompletionEvent, InlineCompletionLogger, InlineCompletionSource } from './completionTypes.ts';
13
+ /** The pause after the last keystroke before a request is made: long enough to skip the middle of a word, short enough to feel live. */
14
+ export declare const DEFAULT_DEBOUNCE_MS = 150;
15
+ /** How many dismissals in a row (Esc, with nothing accepted in between) stop the ghost for the rest of the session. */
16
+ export declare const DEFAULT_DISMISSAL_LIMIT = 3;
17
+ export interface CompletionControllerOptions {
18
+ source: InlineCompletionSource;
19
+ debounceMs?: number;
20
+ dismissalLimit?: number;
21
+ /** How many characters of the text a request carries (its end, up to the caret). */
22
+ maxRequestChars?: number;
23
+ /** The answers already received. A host may share one between boxes that ask the same question. */
24
+ cache?: CompletionCache<CompletionAnswer>;
25
+ /**
26
+ * Runs `callback` after `delayMs` and returns a function that cancels it. The default is `setTimeout`; a test passes its own so no
27
+ * real time passes.
28
+ */
29
+ schedule?: (callback: () => void, delayMs: number) => () => void;
30
+ /** Called when the ghost that shows changes (also with `null` when it goes away). Not called when it stays the same. */
31
+ onChange?: (ghost: GhostView | null) => void;
32
+ /** Called once per transition, for the host that measures them. */
33
+ onEvent?: (event: InlineCompletionEvent) => void;
34
+ /** A debug line per transition. Silent by default. */
35
+ log?: InlineCompletionLogger;
36
+ }
37
+ export interface CompletionController {
38
+ /** Tell the controller what the field looks like now: on every input, caret move, focus and blur. */
39
+ update(field: FieldSnapshot): void;
40
+ /**
41
+ * Take the ghost: returns what to insert at the caret (and its place in the answer), or null when no ghost shows (the key that
42
+ * asked is then NOT used up and must do its own work).
43
+ */
44
+ accept(): {
45
+ insert: string;
46
+ rank: number;
47
+ } | null;
48
+ /** Dismiss the ghost: true when one was showing (the key is used up), false when there was none (the key is not). */
49
+ dismiss(): boolean;
50
+ /** Start over after a pause: the dismissals are forgotten and a ghost may show again. */
51
+ resume(): void;
52
+ /** Forget the answers (a new conversation, a sent message): no ghost, no pending request, no remembered answers. A pause stays. */
53
+ reset(): void;
54
+ /** Stop for good: the pending request is cancelled and nothing is reported again. */
55
+ destroy(): void;
56
+ /** The ghost that shows now, or null. */
57
+ readonly ghost: GhostView | null;
58
+ /** Whether the dismissal limit stopped the ghost. */
59
+ readonly paused: boolean;
60
+ }
61
+ export declare function createCompletionController(options: CompletionControllerOptions): CompletionController;