-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGhostInput.svelte
More file actions
510 lines (462 loc) · 16 KB
/
Copy pathGhostInput.svelte
File metadata and controls
510 lines (462 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
<script lang="ts">
// core.css carries the beam/torch anatomy every effect builds on. Importing it here means a bare
// <GhostInput> (no effect selected) still renders the Torch default; effect entries import the
// same file, and bundlers dedupe it to one copy so nothing loads twice. Relative imports only —
// this component ships in the package, so it must not depend on the $lib alias.
import './effects/core.css';
import { tick, untrack } from 'svelte';
import {
DEFAULT_DEBOUNCE_MS,
DEMO_COMPLETION_TEXT,
MAX_INPUT_CHARS,
MIN_INPUT_CHARS,
applyScriptedDemoInput,
splitInlineCompletion,
CompletionCache,
type CompletionMode,
type GlowVariant,
type LoadingGlow,
type ThemeMode,
type VisualState
} from './autocomplete';
import { CompletionEngine, type CompleteFn } from './input/completion.svelte';
import { isScriptedInput, scriptedKeyInput } from './input/demo-script';
import { ghostGlyphs } from './input/glyphs';
import { SelectionTracker } from './input/selection.svelte';
import type { AcceptDetail, CaretState } from './input/types';
import type { EffectDefinition } from './effects/types';
import type { Component, Snippet } from 'svelte';
interface Props {
/**
* The input's text. Two-way bindable (`bind:value`): the parent can read what the user typed
* and set it programmatically. Prediction fires only when the caret sits at the end, so
* setting this to a value the user is not editing-at-end simply won't trigger a suggestion.
*/
value?: string;
/**
* Minimum trimmed length before a prediction is scheduled, compared **strictly greater-than**:
* a suggestion is requested only once `value.trim().length > minChars` (so the default `2`
* needs a 3rd non-space character).
*/
minChars?: number;
maxChars?: number;
debounceMs?: number;
endpoint?: string;
/**
* Built-in effect name, or any custom effect's name (widened to `string` so consumer-defined
* effects type-check while the built-ins keep autocomplete). Set explicitly, or supply
* {@link Props.effect} to derive it. An explicit `glow` wins over `effect`.
*/
glow?: GlowVariant | (string & {});
/** Optional effect-specific DOM layer rendered inside the live prediction. */
layer?: Component<{ suggestion: string; lightFlow: boolean }>;
/**
* Sugar for wiring a whole effect at once: sets `glow` to `effect.meta.name` and `layer` to
* `effect.layer`. Explicit `glow`/`layer` props take precedence over the effect's values.
*/
effect?: EffectDefinition;
/**
* Custom completion source for `llm` mode. When set it REPLACES the `endpoint` fetch (the
* endpoint is ignored) while keeping the same debounce, cache, stale-guard, and abort
* behavior. `demo` mode is unaffected.
*/
complete?: CompleteFn;
loadingGlow?: LoadingGlow;
lightFlow?: boolean;
theme?: ThemeMode;
completionMode?: CompletionMode;
placeholder?: string;
touchAccept?: boolean;
/** Focus the input on mount. Defaults to true; set false to leave host focus untouched. */
autofocus?: boolean;
/** Render override for the caret element (the default `.caret` span is used when omitted). */
caret?: Snippet<[CaretState]>;
/**
* Render override for the waiting-indicator children (the six `.torch-*` beams inside
* `.caret-origin-glow`). It renders only where the default torch stack would — i.e. only while
* the caret glow is shown: the `waiting` state with `loadingGlow='torch'`. With
* `loadingGlow='field'` or `'none'` the caret glow has no `data-mode='waiting'` wrapper, so
* the waiting indicator (snippet or default beams) does not render there. (The READY-mode
* caret glow is a separate subtree and is unaffected by this snippet.)
*/
waiting?: Snippet;
/**
* Fired each time a word is accepted (Tab / → / the mobile accept button). `word` is the
* accepted next word (with any leading space); `text` is the full input value after it is
* appended. Lowercase per Svelte 5 callback-prop convention.
*/
onaccept?: (detail: AcceptDetail) => void;
}
let {
value = $bindable(''),
minChars = MIN_INPUT_CHARS,
maxChars = MAX_INPUT_CHARS,
debounceMs = DEFAULT_DEBOUNCE_MS,
endpoint = '/api/complete',
glow = undefined,
layer = undefined,
effect: effectDef = undefined,
complete = undefined,
loadingGlow = 'torch',
lightFlow = true,
theme = 'dark',
completionMode = 'llm',
placeholder = '',
touchAccept = true,
autofocus = true,
caret = undefined,
waiting = undefined,
onaccept = undefined
}: Props = $props();
// Effect sugar: an explicit `glow`/`layer` prop always wins; otherwise fall back to the effect's
// values, then to the `torch` default. Resolved once here so the rest of the component and the
// engine read a single source of truth.
const resolvedGlow = $derived(glow ?? effectDef?.meta.name ?? 'torch');
const Layer = $derived(layer ?? effectDef?.layer);
let inputEl = $state<HTMLInputElement>();
let focused = $state(false);
let composing = $state(false);
let visualKey = '';
let sourceKey = '';
const sel = new SelectionTracker();
const engine = new CompletionEngine(
{
value: () => value,
mode: () => completionMode,
endpoint: () => endpoint,
complete: () => complete,
debounceMs: () => debounceMs,
shouldPredict
},
new CompletionCache()
);
const collapsed = $derived(sel.start === sel.end);
const hasEnoughText = $derived(value.trim().length > minChars);
const atEnd = $derived(collapsed && sel.start === value.length);
const showGhost = $derived(focused && atEnd && engine.suggestion.length > 0);
const visualState = $derived<VisualState>(
showGhost ? 'ready' : engine.loading ? 'waiting' : engine.error ? 'error' : 'idle'
);
const visibleText = $derived.by(() => {
const start = Math.min(sel.start, sel.end);
const end = Math.max(sel.start, sel.end);
return {
before: value.slice(0, start),
selected: value.slice(start, end),
after: value.slice(end)
};
});
const ghost = $derived.by(() => splitInlineCompletion(engine.suggestion));
const ghostNextGlyphs = $derived.by(() => ghostGlyphs(ghost.next, 0));
const ghostRestGlyphs = $derived.by(() => ghostGlyphs(ghost.rest, ghost.next.length));
const scrolled = $derived(sel.scrollLeft > 1);
const showCaretGlow = $derived(
focused && atEnd && (showGhost || (engine.loading && loadingGlow === 'torch'))
);
function syncSelection(alignEnd = false) {
sel.sync(inputEl, value.length, alignEnd);
}
function hasInputFocus() {
return focused || (inputEl ? document.activeElement === inputEl : false);
}
function shouldPredict() {
return hasInputFocus() && !composing && hasEnoughText && atEnd;
}
function onInput() {
focused = hasInputFocus();
syncSelection(true);
if (composing) {
engine.cancelPending(true);
return;
}
engine.schedulePrediction();
}
function onBeforeInput(event: InputEvent) {
if (completionMode !== 'demo' || composing || !isScriptedInput(event.inputType)) return;
event.preventDefault();
applyScriptedInput(event.inputType, event.data);
}
function onPaste(event: ClipboardEvent) {
if (completionMode !== 'demo' || composing) return;
event.preventDefault();
applyScriptedInput('insertFromPaste', event.clipboardData?.getData('text/plain') ?? '');
}
function applyScriptedInput(inputType: string, data?: string | null) {
engine.cancelPending(true);
focused = true;
engine.error = '';
const target = DEMO_COMPLETION_TEXT.slice(0, maxChars);
const result = applyScriptedDemoInput({
data,
inputType,
selectionEnd: inputEl?.selectionEnd,
selectionStart: inputEl?.selectionStart,
target,
text: value
});
value = result.value;
void syncScriptedInput(result.caret);
}
async function syncScriptedInput(caret: number) {
await tick();
if (!inputEl) return;
inputEl.focus({ preventScroll: true });
inputEl.setSelectionRange(caret, caret);
syncSelection(true);
engine.schedulePrediction();
}
function onCompositionStart() {
composing = true;
engine.cancelPending(true);
}
function onCompositionEnd() {
composing = false;
syncSelection(true);
engine.schedulePrediction();
}
function onFocus() {
focused = true;
syncSelection();
if (!engine.suggestion && shouldPredict()) engine.schedulePrediction();
}
function onBlur() {
focused = false;
engine.cancelPending(false);
}
function onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
event.preventDefault();
engine.error = '';
engine.cancelPending(true);
return;
}
const wantsCompletion =
(event.key === 'Tab' || event.key === 'ArrowRight') &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey;
if (wantsCompletion && showGhost) {
event.preventDefault();
void acceptNextWord();
return;
}
const scriptedInput = scriptedKeyInput(event);
if (completionMode === 'demo' && !composing && scriptedInput) {
event.preventDefault();
applyScriptedInput(scriptedInput.inputType, scriptedInput.data);
}
}
function onAcceptPointerDown(event: PointerEvent) {
event.preventDefault();
void acceptNextWord();
}
async function acceptNextWord() {
if (!showGhost || !ghost.next) return;
const rest = ghost.rest;
const word = ghost.next;
value += word;
engine.suggestion = rest;
engine.error = '';
engine.igniteKey += 1;
// Notify the host of the accepted word and the resulting value. Fired after the value update
// so `text` is the post-acceptance input value, before the async caret/selection sync below.
onaccept?.({ word, text: value });
await tick();
if (!inputEl) return;
inputEl.focus({ preventScroll: true });
inputEl.setSelectionRange(value.length, value.length);
syncSelection(true);
if (!rest.trim()) engine.schedulePrediction();
}
$effect(() => {
const el = inputEl;
if (!el) return;
const handleSelectionChange = () => {
if (document.activeElement === el) syncSelection();
};
document.addEventListener('selectionchange', handleSelectionChange);
// `autofocus` is a MOUNT-ONLY switch: read it untracked so this effect never re-subscribes to
// it. Toggling the prop after mount must not re-run this effect and re-focus the input (which
// would steal host focus or cancel a live suggestion). The effect's only reactive dependency
// is `inputEl`, which is written exactly once when the <input> mounts.
if (untrack(() => autofocus)) {
queueMicrotask(() => {
el.focus();
syncSelection();
});
}
return () => {
document.removeEventListener('selectionchange', handleSelectionChange);
engine.cancelPending(true);
};
});
$effect(() => {
const nextVisualKey = `${resolvedGlow}|${loadingGlow}|${lightFlow}|${theme}`;
if (nextVisualKey === visualKey) return;
visualKey = nextVisualKey;
if (!engine.loading && !engine.suggestion && shouldPredict()) engine.schedulePrediction();
});
$effect(() => {
// The completion source is (endpoint, mode, complete-fn): changing any of them invalidates
// cached suggestions, since they may have come from a now-replaced backend.
// CAVEAT: `complete` is tracked by PRESENCE (`fn`/`none`), not identity — swapping one custom
// `complete` function for a DIFFERENT one (both truthy) leaves the LRU cache intact, so a key
// already cached by the previous function is still served. Change `endpoint` or `mode`, or
// remount, to force a clear when two custom sources can disagree on the same input.
const nextSourceKey = `${endpoint}|${completionMode}|${complete ? 'fn' : 'none'}`;
if (nextSourceKey === sourceKey) return;
sourceKey = nextSourceKey;
engine.clearCache();
engine.cancelPending(true);
if (shouldPredict()) engine.schedulePrediction();
});
</script>
<div
class="stage"
data-state={visualState}
data-glow={resolvedGlow}
data-light-flow={lightFlow ? 'on' : 'off'}
data-theme={theme}
>
<div
class="field"
data-state={visualState}
data-glow={resolvedGlow}
data-loading-glow={loadingGlow}
data-light-flow={lightFlow ? 'on' : 'off'}
data-theme={theme}
>
<div class="viewport" class:scrolled>
<input
bind:this={inputEl}
bind:value
class="input"
type="text"
{placeholder}
autocomplete="off"
autocapitalize="off"
autocorrect="off"
spellcheck="false"
maxlength={maxChars}
aria-label="AI autocomplete input"
aria-describedby="ghost-input-status"
data-testid="ghost-input"
onbeforeinput={onBeforeInput}
onblur={onBlur}
onclick={() => syncSelection()}
oncompositionend={onCompositionEnd}
oncompositionstart={onCompositionStart}
onfocus={onFocus}
oninput={onInput}
onkeydown={onKeydown}
onkeyup={() => syncSelection()}
onpaste={onPaste}
onscroll={() => syncSelection()}
onselect={() => syncSelection()}
/>
<div class="paint" aria-hidden="true">
<div
class="track"
style:transform={`translate3d(calc(${-sel.scrollLeft}px - var(--ghost-offset, 0px)), 0, 0)`}
>
{#if !value && placeholder}
<span class="placeholder">{placeholder}</span>
{:else}
<span class="typed">{visibleText.before}</span>
{#if collapsed}
{#if caret}
{@render caret({ focused, loading: engine.loading, ready: showGhost })}
{:else}
<span
class="caret"
class:active={focused}
class:thinking={engine.loading}
class:steady={showGhost}
></span>
{/if}
{#if showCaretGlow}
<span class="caret-origin-glow" data-mode={showGhost ? 'ready' : 'waiting'}>
{#if waiting}
{@render waiting()}
{:else}
<span class="torch-beam torch-haze"></span>
<span class="torch-beam torch-flow"></span>
<span class="torch-beam torch-core"></span>
<span class="torch-beam torch-aux"></span>
<span class="torch-beam torch-spark"></span>
<span class="torch-beam torch-smoke"></span>
{/if}
</span>
{/if}
{:else}
<span class="selected">{visibleText.selected}</span>
{/if}
<span class="typed">{visibleText.after}</span>
{#if showGhost}
{#key engine.igniteKey}
<span class="prediction"><span class="beam beam-veil"></span><span
class="beam beam-body"
></span><span class="beam beam-hot"></span><span class="beam beam-flow"></span
><span class="beam beam-aux"></span><span class="beam beam-spark"></span><span
class="beam beam-smoke"
></span>{#if Layer}<Layer suggestion={engine.suggestion} {lightFlow} />{/if}<span class="next-word"
>{#each ghostNextGlyphs as glyph (`next-${glyph.index}-${glyph.char}`)}<span
class="glyph"
data-alt={glyph.alt}
data-hard={glyph.hard}
data-soft={glyph.soft}
style={`--i:${glyph.index};--mut-speed:${glyph.speed}ms;--mut-strength:${glyph.strength}`}
>{glyph.char}</span
>{/each}</span
><span class="tail"
>{#each ghostRestGlyphs as glyph (`rest-${glyph.index}-${glyph.char}`)}<span
class="glyph"
data-alt={glyph.alt}
data-hard={glyph.hard}
data-soft={glyph.soft}
style={`--i:${glyph.index};--mut-speed:${glyph.speed}ms;--mut-strength:${glyph.strength}`}
>{glyph.char}</span
>{/each}</span
></span>
{/key}
{/if}
{/if}
</div>
</div>
<div class="edge edge-left"></div>
<div class="edge edge-right"></div>
</div>
{#if showGhost && touchAccept}
<button
type="button"
class="accept-button"
aria-label="Accept next word"
tabindex="-1"
onpointerdown={onAcceptPointerDown}
>
<!-- Inline lucide `arrow-right` (path data + default 24x24 box); no runtime icon dep. -->
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.35"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</svg>
</button>
{/if}
</div>
<div id="ghost-input-status" class="status" aria-live="polite">
{#if engine.error}
{engine.error}
{/if}
</div>
</div>