@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,20 @@
1
+ /**
2
+ * Whether a finger's tap landed on the ghost. A phone has no Tab key, so touching the grey text takes it. The ghost lives on a layer
3
+ * that ignores pointers (the box underneath must keep getting them), so the tap arrives at the box itself: the action asks the
4
+ * page where the ghost's lines are, and this decides whether the tap was on one of them. Pure, so it runs under `node --test`.
5
+ */
6
+ /**
7
+ * How far outside a line of the ghost a tap still counts: a fingertip is not a pixel, and the ghost's lines are one text line high.
8
+ * Small on purpose: a tap just beside the ghost is a tap on the typed text before it, which moves the caret.
9
+ */
10
+ export const GHOST_TAP_SLOP_PX = 4;
11
+ /** True when the point (x, y) is on one of the ghost's lines, give or take the slop. A rect with no area (a ghost with no text) never counts. */
12
+ export function isTapOnGhost(x, y, rects, slopPx = GHOST_TAP_SLOP_PX) {
13
+ // A position that is not a number (NaN) compares false with everything, so it is on no line.
14
+ return rects.some((rect) => rect.right > rect.left &&
15
+ rect.bottom > rect.top &&
16
+ x >= rect.left - slopPx &&
17
+ x <= rect.right + slopPx &&
18
+ y >= rect.top - slopPx &&
19
+ y <= rect.bottom + slopPx);
20
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Whether the person has taken a suggestion before. The hint that tells them how ("Tab to accept") teaches the first time and is
3
+ * noise after it, so it shows until a suggestion was taken once, by Tab or by a tap, and never again in this browser.
4
+ *
5
+ * The note is one small word in the page's `localStorage`. A browser that does not give storage out (a server render, private
6
+ * mode, blocked storage, a full disk) is no problem: the note is then held for the life of the page, so the hint still goes after the
7
+ * first suggestion taken, and comes back at the next visit. Nothing but the page's own storage is touched, so Node's test runner
8
+ * loads this file with a stand-in for it.
9
+ */
10
+ import type { InlineCompletionLogger } from './completionTypes.ts';
11
+ /** Where the note is kept. The version is part of the name: a change to what the note means starts everyone over by renaming it. */
12
+ export declare const COMPLETION_HINT_STORAGE_KEY = "widgetic:completion-hint-learned:v1";
13
+ /** The part of the browser's storage the memory uses (and what a test stands in for). */
14
+ export interface HintStorage {
15
+ getItem(key: string): string | null;
16
+ setItem(key: string, value: string): void;
17
+ removeItem(key: string): void;
18
+ }
19
+ export interface CompletionHintMemory {
20
+ /**
21
+ * True once a suggestion was taken in this browser (or on this page, when the browser keeps no note). Read when a hint is about to
22
+ * show, so a suggestion taken in another box of the page, or in another tab, is known by then.
23
+ */
24
+ readonly learned: boolean;
25
+ /** Notes that a suggestion was taken: no hint shows from now on. Safe to call again; it never throws. */
26
+ markLearned(): void;
27
+ /** Forgets the note: the hint shows again with the next suggestion (a demo, a test, a screen that offers the tour again). */
28
+ forget(): void;
29
+ }
30
+ export interface CompletionHintMemoryOptions {
31
+ /** Where the note is kept. Default: the page's `localStorage`, when it gives one out. `null` keeps the note on the page only. */
32
+ storage?: HintStorage | null;
33
+ /** The name of the note in the storage. Default `COMPLETION_HINT_STORAGE_KEY`. */
34
+ key?: string;
35
+ /** A debug line when the storage refuses (once per kind of problem). Default: `console.debug` with the `[inline-completion]` prefix. */
36
+ log?: InlineCompletionLogger;
37
+ }
38
+ export declare function createCompletionHintMemory(options?: CompletionHintMemoryOptions): CompletionHintMemory;
39
+ /**
40
+ * The browser's own note, shared by every box of the page and every package that builds on this one: what the action writes when a
41
+ * suggestion is taken, and what the hints read. Nothing is read or written until the first use.
42
+ */
43
+ export declare const completionHintMemory: CompletionHintMemory;
@@ -0,0 +1,90 @@
1
+ /** Where the note is kept. The version is part of the name: a change to what the note means starts everyone over by renaming it. */
2
+ export const COMPLETION_HINT_STORAGE_KEY = 'widgetic:completion-hint-learned:v1';
3
+ /** What is stored once a suggestion was taken. */
4
+ const LEARNED_VALUE = '1';
5
+ const defaultLog = (message, detail) => {
6
+ console.debug('[inline-completion]', message, detail ?? '');
7
+ };
8
+ /** The page's own storage, or null when there is none (a server render) or the browser refuses to hand it out (it throws). */
9
+ function pageStorage() {
10
+ try {
11
+ return typeof localStorage === 'undefined' ? null : localStorage;
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ export function createCompletionHintMemory(options = {}) {
18
+ const key = options.key ?? COMPLETION_HINT_STORAGE_KEY;
19
+ const log = options.log ?? defaultLog;
20
+ // A storage the caller left out is the page's; one the caller set to null is none at all (the note then lives on the page only).
21
+ const storageOf = () => options.storage === undefined ? pageStorage() : options.storage;
22
+ // Whether a suggestion was taken since this page was opened, or the stored note was found.
23
+ let learnedHere = false;
24
+ // Whether the note is in the storage, so a second `markLearned` does not write it again.
25
+ let stored = false;
26
+ // A problem is told once per kind, not once per keystroke.
27
+ const reported = new Set();
28
+ const reportOnce = (kind, error) => {
29
+ if (reported.has(kind))
30
+ return;
31
+ reported.add(kind);
32
+ log(kind, { reason: error instanceof Error ? error.message : String(error) });
33
+ };
34
+ function readStored() {
35
+ const storage = storageOf();
36
+ if (!storage)
37
+ return false;
38
+ try {
39
+ return storage.getItem(key) === LEARNED_VALUE;
40
+ }
41
+ catch (error) {
42
+ reportOnce('the stored note could not be read', error);
43
+ return false;
44
+ }
45
+ }
46
+ return {
47
+ get learned() {
48
+ if (learnedHere)
49
+ return true;
50
+ // Not learned on this page (yet): the storage may know better (another tab, an earlier visit).
51
+ learnedHere = readStored();
52
+ stored = learnedHere;
53
+ return learnedHere;
54
+ },
55
+ markLearned() {
56
+ // The page knows from here on, whatever the storage does.
57
+ learnedHere = true;
58
+ if (stored)
59
+ return;
60
+ const storage = storageOf();
61
+ if (!storage)
62
+ return;
63
+ try {
64
+ storage.setItem(key, LEARNED_VALUE);
65
+ stored = true;
66
+ }
67
+ catch (error) {
68
+ reportOnce('the note could not be stored', error);
69
+ }
70
+ },
71
+ forget() {
72
+ learnedHere = false;
73
+ stored = false;
74
+ const storage = storageOf();
75
+ if (!storage)
76
+ return;
77
+ try {
78
+ storage.removeItem(key);
79
+ }
80
+ catch (error) {
81
+ reportOnce('the stored note could not be removed', error);
82
+ }
83
+ }
84
+ };
85
+ }
86
+ /**
87
+ * The browser's own note, shared by every box of the page and every package that builds on this one: what the action writes when a
88
+ * suggestion is taken, and what the hints read. Nothing is read or written until the first use.
89
+ */
90
+ export const completionHintMemory = createCompletionHintMemory();
@@ -0,0 +1,40 @@
1
+ import type { CompletionAnswerLike, InlineCompletionLogger, InlineCompletionSource } from './completionTypes.ts';
2
+ import { type MaybePromise } from './promiseLike.ts';
3
+ /** How long one request may take before it is given up: a ghost that arrives after the person has moved on is of no use. */
4
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 4000;
5
+ /**
6
+ * How long a route that said it is `disabled` is believed before it is asked again. Long enough that a surface that is off is
7
+ * not asked at every pause, short enough that switching it on reaches a page that is already open within minutes.
8
+ */
9
+ export declare const DISABLED_MEMO_MS: number;
10
+ export interface HttpCompletionSourceOptions {
11
+ /** The route to POST to. A function is read at every request (a route that depends on the open widget or workspace). */
12
+ url: string | (() => string);
13
+ /**
14
+ * The fields of the body besides `text`: the surface, the language, what the box knows about itself. Read at every request, so a
15
+ * box whose context changes (another element picked) is always asked with its current one.
16
+ */
17
+ body?: () => Record<string, unknown>;
18
+ /**
19
+ * Headers besides `Content-Type`. Read at every request. May be asynchronous: a host whose token is refreshed on demand gives
20
+ * its headers when it has them, and a request that waits for them is still cancelled when the person types on.
21
+ */
22
+ headers?: () => MaybePromise<Record<string, string>>;
23
+ /** The `fetch` to use: the host's own, with the person's credentials. Defaults to the global one. */
24
+ fetchImpl?: typeof fetch;
25
+ /** `credentials` of the request. Default `include` (the gateway's session cookie). */
26
+ credentials?: RequestCredentials;
27
+ timeoutMs?: number;
28
+ /** The clock the `disabled` memo reads, in milliseconds. Defaults to `Date.now`; a test hands in its own. */
29
+ now?: () => number;
30
+ /** A debug line per kind of failure. Silent by default. */
31
+ log?: InlineCompletionLogger;
32
+ }
33
+ /** The object shape of an answer (continuations with their life and source), which is what the suggest routes' answers are read into. */
34
+ type ObjectAnswer = Extract<CompletionAnswerLike, {
35
+ continuations: readonly unknown[];
36
+ }>;
37
+ /** What the gateway's answer says, as the engine reads it; null when the body is not an answer of the suggest routes. */
38
+ export declare function readSuggestResponse(json: unknown): ObjectAnswer | null;
39
+ export declare function createHttpCompletionSource(options: HttpCompletionSourceOptions): InlineCompletionSource;
40
+ export {};
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The source that asks the gateway: one POST per request to a route that answers the way the Widgetic gateway's suggest routes do
3
+ * (`{ success: true, data: { source, continuations: [{ text, score }], ttlMs } }`). The host hands in the route, the fields of the body
4
+ * that only it knows (surface, language, context), and a `fetch` that carries the person's credentials.
5
+ *
6
+ * It never rejects: a request that fails, times out, is cancelled, or answers with something unexpected is "nothing to show", kept for
7
+ * ten seconds so the box does not ask again at every keystroke. What went wrong is logged once per kind of failure.
8
+ *
9
+ * A route that answers `source: 'disabled'` (the surface is switched off, or the language has no catalog) is believed for five minutes:
10
+ * until then the box is told "nothing to show" without a request, so a surface that is off does not cost one request per pause in typing.
11
+ */
12
+ import { emptyAnswer, FAILED_REQUEST_TTL_MS } from "./completionAnswer.js";
13
+ import { isPromiseLike } from "./promiseLike.js";
14
+ /** How long one request may take before it is given up: a ghost that arrives after the person has moved on is of no use. */
15
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 4000;
16
+ /**
17
+ * How long a route that said it is `disabled` is believed before it is asked again. Long enough that a surface that is off is
18
+ * not asked at every pause, short enough that switching it on reaches a page that is already open within minutes.
19
+ */
20
+ export const DISABLED_MEMO_MS = 5 * 60 * 1000;
21
+ /** The nothing-to-show answer of a failed request, kept briefly so the same text is not asked again at once. */
22
+ function failedAnswer() {
23
+ return emptyAnswer(FAILED_REQUEST_TTL_MS);
24
+ }
25
+ /**
26
+ * A signal that fires when either of the two does, without relying on `AbortSignal.any` (older browsers do not have it). The caller
27
+ * has checked that neither has fired yet: an event of a signal that fired earlier is never delivered.
28
+ *
29
+ * `first` is the engine's, which outlives the request and is let go of by `release`; `second` is the request's own clock and goes with it.
30
+ */
31
+ function mergeSignals(first, second) {
32
+ const merged = new AbortController();
33
+ const forward = () => merged.abort();
34
+ first.addEventListener('abort', forward, { once: true });
35
+ second.addEventListener('abort', forward, { once: true });
36
+ return {
37
+ signal: merged.signal,
38
+ release: () => first.removeEventListener('abort', forward)
39
+ };
40
+ }
41
+ /** What the gateway's answer says, as the engine reads it; null when the body is not an answer of the suggest routes. */
42
+ export function readSuggestResponse(json) {
43
+ if (json === null || typeof json !== 'object')
44
+ return null;
45
+ const envelope = json;
46
+ if (envelope.success !== true || envelope.data === null || typeof envelope.data !== 'object')
47
+ return null;
48
+ const data = envelope.data;
49
+ if (!Array.isArray(data.continuations))
50
+ return null;
51
+ const texts = data.continuations.map((item) => item !== null && typeof item === 'object' ? item.text : item);
52
+ return {
53
+ continuations: texts,
54
+ ttlMs: typeof data.ttlMs === 'number' ? data.ttlMs : undefined,
55
+ source: typeof data.source === 'string' ? data.source : undefined
56
+ };
57
+ }
58
+ export function createHttpCompletionSource(options) {
59
+ const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
60
+ const log = options.log ?? (() => { });
61
+ const clock = options.now ?? Date.now;
62
+ // Where the route said it is `disabled`, and until when that is believed. The route is part of it: another route is another question.
63
+ let disabledMemo = null;
64
+ // A failure is logged once per kind (a down gateway is one line, not one per keystroke).
65
+ const reportedFailures = new Set();
66
+ const reportFailure = (kind, detail) => {
67
+ if (reportedFailures.has(kind))
68
+ return;
69
+ reportedFailures.add(kind);
70
+ log(`suggest request failed: ${kind}`, detail);
71
+ };
72
+ /** The host's own `headers` function failed (a token that could not be refreshed): nothing to show, and it is said once. */
73
+ const hostHeadersFailed = (error) => {
74
+ reportFailure('headers', { reason: error instanceof Error ? error.message : String(error) });
75
+ return failedAnswer();
76
+ };
77
+ return {
78
+ async suggest(request) {
79
+ if (request.signal.aborted)
80
+ return failedAnswer();
81
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
82
+ if (typeof fetchImpl !== 'function') {
83
+ reportFailure('no fetch');
84
+ return failedAnswer();
85
+ }
86
+ const timeout = new AbortController();
87
+ const timer = setTimeout(() => timeout.abort(), timeoutMs);
88
+ const { signal, release } = mergeSignals(request.signal, timeout.signal);
89
+ try {
90
+ const url = typeof options.url === 'function' ? options.url() : options.url;
91
+ // A route that said it is off a moment ago is not asked again yet: nothing to show, for as long as that is believed.
92
+ const memoNow = clock();
93
+ if (disabledMemo !== null && disabledMemo.url === url && disabledMemo.until > memoNow) {
94
+ return emptyAnswer(disabledMemo.until - memoNow);
95
+ }
96
+ let hostHeaders;
97
+ try {
98
+ const given = options.headers?.();
99
+ // Only a host that answers late is waited for: one that answers at once keeps the request in this very turn.
100
+ hostHeaders = (isPromiseLike(given) ? await given : given) ?? {};
101
+ }
102
+ catch (error) {
103
+ return hostHeadersFailed(error);
104
+ }
105
+ // The person typed on (or time ran out) while the host was getting its headers: no request is made for it.
106
+ if (signal.aborted) {
107
+ if (!request.signal.aborted)
108
+ reportFailure('timeout');
109
+ return failedAnswer();
110
+ }
111
+ const response = await fetchImpl(url, {
112
+ method: 'POST',
113
+ credentials: options.credentials ?? 'include',
114
+ // The body is JSON whatever the host adds: its headers cannot change that.
115
+ headers: { ...hostHeaders, 'Content-Type': 'application/json' },
116
+ body: JSON.stringify({ ...(options.body?.() ?? {}), text: request.text }),
117
+ signal
118
+ });
119
+ if (!response.ok) {
120
+ reportFailure(`status ${response.status}`, { status: response.status });
121
+ return failedAnswer();
122
+ }
123
+ const answer = readSuggestResponse(await response.json());
124
+ if (answer === null) {
125
+ reportFailure('unexpected answer');
126
+ return failedAnswer();
127
+ }
128
+ // "Disabled" is remembered (a failed request is not: it returned above, and is the engine's ten seconds).
129
+ if (answer.source === 'disabled') {
130
+ disabledMemo = { url, until: clock() + DISABLED_MEMO_MS };
131
+ }
132
+ return answer;
133
+ }
134
+ catch (error) {
135
+ // A cancelled request is the engine moving on, not a failure; a timeout is one.
136
+ if (request.signal.aborted)
137
+ return failedAnswer();
138
+ reportFailure(timeout.signal.aborted ? 'timeout' : 'network', {
139
+ reason: error instanceof Error ? error.message : String(error)
140
+ });
141
+ return failedAnswer();
142
+ }
143
+ finally {
144
+ clearTimeout(timer);
145
+ release();
146
+ }
147
+ }
148
+ };
149
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `@widgetic/design-system/inline-completion` — ghost text after the caret of a text field: Tab takes the suggestion, Esc or typing on
3
+ * sends it away. Generic by design: where suggestions come from (`InlineCompletionSource`) and what the box knows about itself are the
4
+ * host's; the engine knows only text, the caret and keys.
5
+ *
6
+ * Typical use: `use:inlineCompletion={{ source: createHttpCompletionSource({ url, body }), value }}` on a textarea, and
7
+ * `createOutcomeReporter({ surface, url })` fed from the action's `onEvent`, so the gateway can measure whether the order is right.
8
+ * A box that one of the gateway's suggest routes serves gets both from one call: `createGatewayCompletion({ surface, suggestUrl, ... })`.
9
+ *
10
+ * A hint beside a box ("Tab to accept") is for the first time only: the action notes the first suggestion taken in
11
+ * `completionHintMemory`, and a host reads `completionHintMemory.learned` when a suggestion appears to decide whether to show the hint.
12
+ */
13
+ export { inlineCompletion, DEFAULT_GHOST_CLASS, GHOST_OVERLAY_OWNER } from './inlineCompletionAction.ts';
14
+ export type { InlineCompletionParams } from './inlineCompletionAction.ts';
15
+ export { createCompletionController, DEFAULT_DEBOUNCE_MS, DEFAULT_DISMISSAL_LIMIT } from './completionController.ts';
16
+ export type { CompletionController, CompletionControllerOptions } from './completionController.ts';
17
+ export { createCompletionCache } from './completionCache.ts';
18
+ export type { CompletionCache, CompletionCacheOptions } from './completionCache.ts';
19
+ export { createHttpCompletionSource, readSuggestResponse, DEFAULT_REQUEST_TIMEOUT_MS, DISABLED_MEMO_MS } from './httpSource.ts';
20
+ export type { HttpCompletionSourceOptions } from './httpSource.ts';
21
+ export { createOutcomeReporter, DEFAULT_FLUSH_AFTER_SHOWN, DEFAULT_FLUSH_DELAY_MS } from './outcomeReporter.ts';
22
+ export type { OutcomeReporter, OutcomeReporterOptions } from './outcomeReporter.ts';
23
+ export { createGatewayCompletion, localeForGateway, FALLBACK_LOCALE } from './gatewayCompletion.ts';
24
+ export type { GatewayCompletion, GatewayCompletionOptions } from './gatewayCompletion.ts';
25
+ export { interpretGhostKey } from './completionKeys.ts';
26
+ export type { GhostKeyAction, KeyPress } from './completionKeys.ts';
27
+ export { completionHintMemory, createCompletionHintMemory, COMPLETION_HINT_STORAGE_KEY } from './hintMemory.ts';
28
+ export type { CompletionHintMemory, CompletionHintMemoryOptions, HintStorage } from './hintMemory.ts';
29
+ export type { FieldSnapshot } from './completionText.ts';
30
+ export type { CompletionAnswer, CompletionAnswerLike, CompletionSourceName, GhostView, InlineCompletionEvent, InlineCompletionLogger, InlineCompletionRequest, InlineCompletionSource } from './completionTypes.ts';
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `@widgetic/design-system/inline-completion` — ghost text after the caret of a text field: Tab takes the suggestion, Esc or typing on
3
+ * sends it away. Generic by design: where suggestions come from (`InlineCompletionSource`) and what the box knows about itself are the
4
+ * host's; the engine knows only text, the caret and keys.
5
+ *
6
+ * Typical use: `use:inlineCompletion={{ source: createHttpCompletionSource({ url, body }), value }}` on a textarea, and
7
+ * `createOutcomeReporter({ surface, url })` fed from the action's `onEvent`, so the gateway can measure whether the order is right.
8
+ * A box that one of the gateway's suggest routes serves gets both from one call: `createGatewayCompletion({ surface, suggestUrl, ... })`.
9
+ *
10
+ * A hint beside a box ("Tab to accept") is for the first time only: the action notes the first suggestion taken in
11
+ * `completionHintMemory`, and a host reads `completionHintMemory.learned` when a suggestion appears to decide whether to show the hint.
12
+ */
13
+ export { inlineCompletion, DEFAULT_GHOST_CLASS, GHOST_OVERLAY_OWNER } from "./inlineCompletionAction.js";
14
+ export { createCompletionController, DEFAULT_DEBOUNCE_MS, DEFAULT_DISMISSAL_LIMIT } from "./completionController.js";
15
+ export { createCompletionCache } from "./completionCache.js";
16
+ export { createHttpCompletionSource, readSuggestResponse, DEFAULT_REQUEST_TIMEOUT_MS, DISABLED_MEMO_MS } from "./httpSource.js";
17
+ export { createOutcomeReporter, DEFAULT_FLUSH_AFTER_SHOWN, DEFAULT_FLUSH_DELAY_MS } from "./outcomeReporter.js";
18
+ export { createGatewayCompletion, localeForGateway, FALLBACK_LOCALE } from "./gatewayCompletion.js";
19
+ export { interpretGhostKey } from "./completionKeys.js";
20
+ export { completionHintMemory, createCompletionHintMemory, COMPLETION_HINT_STORAGE_KEY } from "./hintMemory.js";
@@ -0,0 +1,54 @@
1
+ /**
2
+ * `use:inlineCompletion` — ghost text after the caret of a textarea or text input. The suggestion comes from a source (usually the
3
+ * gateway: `createHttpCompletionSource`), Tab takes it (so does a finger's tap on it), Esc sends it away, typing on along it follows
4
+ * it with no new request, and typing something else lets it go. The state machine is `createCompletionController`; this file is the
5
+ * DOM around it: the events, the ghost painted on the field's mirror layer, the placeholder that steps aside, and the announcement
6
+ * for assistive technology. The first suggestion taken is noted in `completionHintMemory`, so a hint beside a box ("Tab to accept")
7
+ * is there for the first time only.
8
+ *
9
+ * The ghost has no look of its own: it sits in the mirror's text, which copies the field's typography, so it is the same font, size
10
+ * and line as what is typed, only in the muted colour, and it wraps as a continuation of the text does.
11
+ *
12
+ * The one rule about keys, held by `interpretGhostKey` and tested without a DOM: Tab and Esc are the ghost's only while a ghost shows.
13
+ *
14
+ * ```svelte
15
+ * <textarea bind:value use:inlineCompletion={{ source, value }}></textarea>
16
+ * ```
17
+ * `value` is only there so the action notices a text the page changed by itself (a sent message clears the box, a draft is restored):
18
+ * a change like that raises no event.
19
+ */
20
+ import type { Action } from 'svelte/action';
21
+ import { type OverlayField } from '../textarea-overlay/textareaOverlay.ts';
22
+ import type { GhostView, InlineCompletionEvent, InlineCompletionLogger, InlineCompletionSource } from './completionTypes.ts';
23
+ import { type CompletionHintMemory } from './hintMemory.ts';
24
+ /** The owner name of the ghost on the field's mirror layer. */
25
+ export declare const GHOST_OVERLAY_OWNER = "ghost";
26
+ /** The ghost's colour: the muted text colour of the design system. A host may pass its own classes. */
27
+ export declare const DEFAULT_GHOST_CLASS = "text-muted-foreground";
28
+ export interface InlineCompletionParams {
29
+ /** Where suggestions come from. Without one (null, undefined) the action does nothing. A different source starts over. */
30
+ source: InlineCompletionSource | null | undefined;
31
+ /** The text the page holds for the field, so a change the page makes by itself is noticed (see the file's header). */
32
+ value?: string;
33
+ /** True while suggestions should not show (sending, a surface that is off): no ghost, no request. */
34
+ disabled?: boolean;
35
+ /** Classes of the ghost text. Default `text-muted-foreground`. */
36
+ ghostClass?: string;
37
+ debounceMs?: number;
38
+ dismissalLimit?: number;
39
+ /** What a screen reader hears when a ghost appears ("Suggestion: ideo player. Press Tab to accept."). Without it nothing is announced. */
40
+ announce?: (ghostText: string) => string;
41
+ /** Called when the ghost that shows changes (with null when it goes away): the host may show a hint beside the box. */
42
+ onChange?: (ghost: GhostView | null) => void;
43
+ /** Called once per transition (shown, accepted, dismissed, diverged, paused), for a host that measures them. */
44
+ onEvent?: (event: InlineCompletionEvent) => void;
45
+ /** A debug line per transition. Default: `console.debug` with the `[inline-completion]` prefix. */
46
+ log?: InlineCompletionLogger;
47
+ /**
48
+ * Where the action notes that a suggestion was taken (by Tab or by a tap), so the hints of the page can stop: a hint teaches the
49
+ * first time and is noise after it. Default: the browser's shared note, `completionHintMemory`, which a host reads when it is
50
+ * about to show a hint. `null` notes nothing.
51
+ */
52
+ hintMemory?: CompletionHintMemory | null;
53
+ }
54
+ export declare const inlineCompletion: Action<OverlayField, InlineCompletionParams>;