@stacksjs/components 0.2.761 → 0.2.764

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.
package/README.md CHANGED
@@ -82,6 +82,19 @@ yarn add @stacksjs/components
82
82
  ### Form Components (3)
83
83
 
84
84
  - **Textarea** - Multi-line input with auto-resize
85
+ - **AiTextarea** - Textarea with AI ghost-text completions: Tab accepts, Escape dismisses, Ctrl/Cmd+Right takes a word
86
+
87
+ ```html
88
+ <AiTextarea
89
+ label="Note"
90
+ kind="note"
91
+ context="Meeting notes"
92
+ fetcher="/api/complete"
93
+ v-model:value="body"
94
+ />
95
+ ```
96
+
97
+ `fetcher` is a URL that answers `POST { before, after, kind, context }` with `{ completion }` (default `/ai/complete`, which Stacks mounts), or a function `(ctx, signal) => Promise<string>` bound with `:fetcher`. `kind` is `note`, `prompt`, `todo` or `text`. `debounceMs` (250) and `minChars` (12) tune when it asks; `:completions="false"` turns it off. The suggestion is drawn on an aria-hidden overlay that copies the textarea's metrics and scroll, and announced politely through a live region. Honours `prefers-reduced-motion` and works in dark mode through the role tokens.
85
98
  - **Checkbox** - Checkbox with indeterminate state
86
99
  - **Radio** - Radio button with descriptions
87
100
 
@@ -0,0 +1,342 @@
1
+ <script server>
2
+ export const value = $props.value || ''
3
+ export const placeholder = $props.placeholder || ''
4
+ export const disabled = $bool($props.disabled)
5
+ export const readonly = $bool($props.readonly)
6
+ export const rows = $num($props.rows) || 4
7
+ export const error = $bool($props.error)
8
+ export const label = $props.label || ''
9
+ /*
10
+ * Ids unique to this instance, for the same reasons Textarea gives: a label
11
+ * derived id collides when two of these share a page. The ghost layer and the
12
+ * announcement hang off the same id.
13
+ */
14
+ export const inputId = $props.id || `ai-textarea-${$uid}`
15
+ export const ghostId = `${inputId}-ghost`
16
+ export const helperId = `${inputId}-helper`
17
+ export const helperText = $props.helperText || ''
18
+ export const required = $bool($props.required)
19
+ export const maxLength = $props.maxLength
20
+ export const resize = $props.resize || 'vertical'
21
+ export const className = $props.className || ''
22
+ export const name = $props.name || ''
23
+ export const autocomplete = $props.autocomplete || $props.autoComplete || ''
24
+ export const form = $props.form || ''
25
+
26
+ /*
27
+ * What is being written. It steers the instruction the model gets, so a todo
28
+ * title completes as a short phrase and a prompt completes as part of the
29
+ * prompt rather than as an answer to it.
30
+ */
31
+ export const kind = ['note', 'prompt', 'todo', 'text'].includes($props.kind) ? $props.kind : 'text'
32
+ export const context = $props.context || ''
33
+ /*
34
+ * `fetcher` is a URL (a string, POSTed `{ before, after, kind, context }`,
35
+ * answered `{ completion }`) or a function `(ctx, signal) => Promise<string>`.
36
+ * The function can only arrive through a bound attribute, so the client reads
37
+ * it live; this is the default for the string form. `/ai/complete` is where
38
+ * Stacks mounts CompleteAction.
39
+ */
40
+ export const endpoint = typeof $props.fetcher === 'string' && $props.fetcher ? $props.fetcher : '/ai/complete'
41
+ export const debounceMs = $num($props.debounceMs, 250)
42
+ export const minChars = $num($props.minChars, 12)
43
+ export const completions = $bool($props.completions, true)
44
+
45
+ const resizeClasses = { none: 'resize-none', vertical: 'resize-y', horizontal: 'resize-x', both: 'resize' }
46
+ const baseClasses = 'block w-full border-0 rounded-control shadow-sm ring-1 ring-inset transition-colors duration-200 focus:ring-2 focus:ring-inset px-control-x py-control-y text-control bg-field'
47
+ export const stateInvalidClasses = 'ring-danger-line text-danger-fg placeholder-danger focus:ring-danger-focus'
48
+ export const stateValidClasses = 'ring-line-strong text-fg placeholder-fg-soft focus:ring-accent'
49
+ const stateClasses = error ? stateInvalidClasses : stateValidClasses
50
+ const disabledClasses = disabled
51
+ ? 'opacity-50 cursor-not-allowed bg-surface'
52
+ : readonly
53
+ ? 'bg-surface cursor-default'
54
+ : 'bg-field'
55
+
56
+ export const textareaClasses = `${baseClasses} ${stateClasses} ${disabledClasses} ${resizeClasses[resize] || resizeClasses.vertical} ${className}`.trim()
57
+ export const labelClasses = `block text-sm font-medium leading-6 mb-2 ${error ? 'text-danger' : 'text-fg'}`.trim()
58
+ export const helperClasses = `mt-2 text-sm ${error ? 'text-danger' : 'text-fg-soft'}`.trim()
59
+ </script>
60
+
61
+ <script client>
62
+ /*
63
+ * <AiTextarea>: a textarea that shows an AI suggestion as grey ghost text after
64
+ * the caret. Tab accepts it, Escape dismisses it, Ctrl/Cmd+Right takes one
65
+ * word, and typing the first letters of it just keeps going.
66
+ *
67
+ * The WHEN of it (debounce, abort, stale answers, IME, selection) is
68
+ * useCompletion; this file is the DOM half: reading the field, drawing the
69
+ * overlay and handling keys.
70
+ *
71
+ * The overlay is a second element laid exactly over the textarea with the same
72
+ * font, padding, border and wrapping (copied from the textarea's computed style
73
+ * whenever it resizes), holding the text before the caret in invisible ink and
74
+ * the suggestion after it in grey. It is aria-hidden and pointer-events none;
75
+ * the suggestion reaches a screen reader through the polite live region.
76
+ */
77
+ const emit = defineEmits(['input', 'accept'])
78
+ const isError = useReactiveProp('error', {{ error }})
79
+ function aiBoolean(value) {
80
+ if (value == null) return false
81
+ if (typeof value === 'string') return !['false', '0', 'off', 'no'].includes(value.trim().toLowerCase())
82
+ return Boolean(value)
83
+ }
84
+ const liveDisabled = useReactiveProp('disabled', {{ disabled }}, { parse: aiBoolean })
85
+ const liveReadonly = useReactiveProp('readonly', {{ readonly }}, { parse: aiBoolean })
86
+ const liveCompletions = useReactiveProp('completions', {{ completions }}, { parse: aiBoolean })
87
+ const isDisabled = derived(() => aiBoolean(liveDisabled()))
88
+ const isReadonly = derived(() => aiBoolean(liveReadonly()))
89
+ const liveKind = useReactiveProp('kind', {{ kind }}, { parse: v => (v == null ? 'text' : String(v)) })
90
+ const liveContext = useReactiveProp('context', {{ context }}, { parse: v => (v == null ? '' : String(v)) })
91
+ // A function when the parent bound one (:fetcher="load"), else the URL string.
92
+ const liveFetcher = useReactiveProp('fetcher', {{ endpoint }}, { parse: v => v })
93
+ const inputValue = useModel('value', { default: {{ value }}, parse: (v) => v == null ? '' : String(v) })
94
+
95
+ async function requestCompletion(ctx, signal) {
96
+ const request = { before: ctx.before, after: ctx.after, caret: ctx.caret, kind: liveKind(), context: liveContext() }
97
+ const source = liveFetcher()
98
+ if (typeof source === 'function') {
99
+ const out = await source(request, signal)
100
+ if (typeof out === 'string') return out
101
+ return out && typeof out.completion === 'string' ? out.completion : ''
102
+ }
103
+ const url = typeof source === 'string' && source ? source : {{ endpoint }}
104
+ const response = await fetch(url, {
105
+ method: 'POST',
106
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
107
+ credentials: 'same-origin',
108
+ signal,
109
+ body: JSON.stringify({ before: request.before, after: request.after, kind: request.kind, context: request.context }),
110
+ })
111
+ // No driver, signed out, rate limited, provider down: all just "no suggestion".
112
+ if (!response.ok) return ''
113
+ const data = await response.json()
114
+ return data && typeof data.completion === 'string' ? data.completion : ''
115
+ }
116
+
117
+ const completion = useCompletion({
118
+ fetch: requestCompletion,
119
+ debounceMs: {{ debounceMs }},
120
+ minChars: {{ minChars }},
121
+ enabled: () => !isDisabled() && !isReadonly() && aiBoolean(liveCompletions()),
122
+ })
123
+ const ghost = completion.ghost
124
+ const mirrorBefore = state('')
125
+ const announcement = derived(() => {
126
+ const text = ghost()
127
+ if (!text) return ''
128
+ const shown = text.trim().slice(0, 120)
129
+ return 'Suggestion available: ' + shown + '. Press Tab to accept or Escape to dismiss.'
130
+ })
131
+ let composing = false
132
+
133
+ function field() { return document.getElementById({{ inputId }}) }
134
+ function overlay() { return document.getElementById({{ ghostId }}) }
135
+
136
+ // The properties that decide where a character lands. Copied, not duplicated
137
+ // in classes, so the overlay follows whatever the app styled the textarea with.
138
+ const MIRRORED = [
139
+ 'boxSizing', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant', 'fontStretch', 'fontKerning',
140
+ 'fontFeatureSettings', 'letterSpacing', 'wordSpacing', 'lineHeight', 'textIndent', 'textTransform', 'textAlign',
141
+ 'tabSize', 'direction', 'whiteSpace', 'wordBreak', 'overflowWrap', 'textRendering',
142
+ 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
143
+ 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth',
144
+ ]
145
+
146
+ function syncMetrics() {
147
+ const t = field()
148
+ const m = overlay()
149
+ if (!t || !m) return
150
+ const cs = window.getComputedStyle(t)
151
+ for (const property of MIRRORED) m.style[property] = cs[property]
152
+ m.style.borderStyle = 'solid'
153
+ m.style.borderColor = 'transparent'
154
+ // A scrollbar takes width from the textarea's text area; the overlay has
155
+ // none, so it pays the same in padding or its lines would wrap differently.
156
+ const bar = t.offsetWidth - t.clientWidth - (Number.parseFloat(cs.borderLeftWidth) || 0) - (Number.parseFloat(cs.borderRightWidth) || 0)
157
+ if (bar > 0) m.style.paddingRight = ((Number.parseFloat(cs.paddingRight) || 0) + bar) + 'px'
158
+ m.scrollTop = t.scrollTop
159
+ m.scrollLeft = t.scrollLeft
160
+ }
161
+
162
+ function syncScroll() {
163
+ const t = field()
164
+ const m = overlay()
165
+ if (t && m) {
166
+ m.scrollTop = t.scrollTop
167
+ m.scrollLeft = t.scrollLeft
168
+ }
169
+ }
170
+
171
+ // Tell the composable what the field looks like now.
172
+ function sync() {
173
+ const t = field()
174
+ if (!t) return
175
+ const text = t.value
176
+ const start = t.selectionStart == null ? text.length : t.selectionStart
177
+ const end = t.selectionEnd == null ? start : t.selectionEnd
178
+ const after = text.slice(end)
179
+ // Ghost text is drawn on the caret's line; with text after the caret on that
180
+ // line it would paint over it, so a suggestion is only asked for at a line end.
181
+ const atLineEnd = after === '' || after.charAt(0) === '\n' || after.charAt(0) === '\r'
182
+ mirrorBefore.set(text.slice(0, start))
183
+ completion.update(text.slice(0, start), after, start, {
184
+ composing: composing,
185
+ selecting: start !== end,
186
+ blocked: !atLineEnd || document.activeElement !== t,
187
+ })
188
+ syncScroll()
189
+ }
190
+
191
+ function onInput(event) {
192
+ const t = event.target
193
+ if (isDisabled() || isReadonly() || t.isConnected === false) {
194
+ t.value = inputValue()
195
+ return
196
+ }
197
+ inputValue.input(t.value)
198
+ if (!inputValue.modifiers.lazy) emit('input', inputValue())
199
+ sync()
200
+ }
201
+
202
+ function onChange(event) {
203
+ if (isDisabled() || isReadonly() || event.target.isConnected === false) {
204
+ event.target.value = inputValue()
205
+ return
206
+ }
207
+ inputValue.change(event.target.value)
208
+ if (inputValue.modifiers.lazy) emit('input', inputValue())
209
+ }
210
+
211
+ function onCompositionStart() {
212
+ composing = true
213
+ sync()
214
+ }
215
+
216
+ function onCompositionEnd() {
217
+ composing = false
218
+ sync()
219
+ }
220
+
221
+ // Insert through the editing pipeline so Undo takes the suggestion back out in
222
+ // one step; setRangeText is the fallback where execCommand is gone.
223
+ function insertText(text) {
224
+ const t = field()
225
+ if (!t || !text) return
226
+ t.focus()
227
+ let done = false
228
+ try { done = document.execCommand('insertText', false, text) }
229
+ catch (e) { done = false }
230
+ if (!done) {
231
+ t.setRangeText(text, t.selectionStart, t.selectionEnd, 'end')
232
+ t.dispatchEvent(new Event('input', { bubbles: true }))
233
+ }
234
+ emit('accept', text)
235
+ }
236
+
237
+ function onKeydown(event) {
238
+ if (event.isComposing || event.keyCode === 229) return
239
+ if (!ghost()) return
240
+ const plain = !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey
241
+ if (event.key === 'Tab' && plain) {
242
+ event.preventDefault()
243
+ insertText(completion.accept())
244
+ }
245
+ else if (event.key === 'Escape') {
246
+ // Only a visible suggestion swallows Escape, so it still closes a dialog otherwise.
247
+ event.preventDefault()
248
+ event.stopPropagation()
249
+ completion.dismiss()
250
+ }
251
+ else if (event.key === 'ArrowRight' && (event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
252
+ event.preventDefault()
253
+ insertText(completion.acceptWord())
254
+ }
255
+ }
256
+
257
+ let resizeObserver
258
+ onMount(() => {
259
+ syncMetrics()
260
+ const t = field()
261
+ if (t && typeof ResizeObserver !== 'undefined') {
262
+ resizeObserver = new ResizeObserver(syncMetrics)
263
+ resizeObserver.observe(t)
264
+ }
265
+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(syncMetrics)
266
+ window.addEventListener('resize', syncMetrics)
267
+ })
268
+
269
+ onDestroy(() => {
270
+ if (resizeObserver) resizeObserver.disconnect()
271
+ window.removeEventListener('resize', syncMetrics)
272
+ completion.destroy()
273
+ })
274
+
275
+ defineExpose({ value: inputValue, ghost, accept: () => insertText(completion.accept()), dismiss: completion.dismiss })
276
+ </script>
277
+
278
+ <div class="w-full">
279
+ @if(label)
280
+ <label for="{{ inputId }}" class="{{ labelClasses }}">
281
+ {{ label }}
282
+ @if(required)
283
+ <span class="text-danger ml-1">*</span>
284
+ @endif
285
+ </label>
286
+ @endif
287
+
288
+ <div class="relative">
289
+ <textarea
290
+ @if(name)name="{{ name }}"@endif
291
+ @if(autocomplete)autocomplete="{{ autocomplete }}"@endif
292
+ @if(form)form="{{ form }}"@endif
293
+ id="{{ inputId }}"
294
+ class="{{ textareaClasses }}"
295
+ rows="{{ rows }}"
296
+ placeholder="{{ placeholder }}"
297
+ @if(disabled)disabled@endif
298
+ :disabled="isDisabled()"
299
+ @if(readonly)readonly@endif
300
+ :readonly="isReadonly()"
301
+ @if(required)required@endif
302
+ @if(maxLength)maxlength="{{ maxLength }}"@endif
303
+ spellcheck="true"
304
+ aria-autocomplete="inline"
305
+ aria-invalid="{{ error ? 'true' : 'false' }}"
306
+ :aria-invalid="isError() ? 'true' : 'false'"
307
+ @if(helperText)aria-describedby="{{ helperId }}"@endif
308
+ :value="inputValue()"
309
+ @input="onInput($event)"
310
+ @change="onChange($event)"
311
+ @keydown="onKeydown($event)"
312
+ @keyup="sync()"
313
+ @mouseup="sync()"
314
+ @select="sync()"
315
+ @focus="sync()"
316
+ @blur="sync()"
317
+ @scroll="syncScroll()"
318
+ @compositionstart="onCompositionStart()"
319
+ @compositionend="onCompositionEnd()"
320
+ :class="{ '{{ stateInvalidClasses }}': isError(), '{{ stateValidClasses }}': !isError(), 'opacity-50 cursor-not-allowed': isDisabled(), 'bg-surface': isDisabled() || isReadonly(), 'bg-field': !isDisabled() && !isReadonly(), 'cursor-default': !isDisabled() && isReadonly() }"
321
+ >{{ value }}</textarea>
322
+
323
+ {{-- The ghost layer. Same box as the textarea (metrics copied at mount and
324
+ on resize), invisible text before the caret so the suggestion starts
325
+ exactly where the caret is. Never read aloud: the live region is. --}}
326
+ <div
327
+ id="{{ ghostId }}"
328
+ aria-hidden="true"
329
+ data-stx-ai-ghost
330
+ class="absolute inset-0 overflow-hidden pointer-events-none select-none"
331
+ style="white-space: pre-wrap; overflow-wrap: break-word;"
332
+ ><span class="invisible" x-text="mirrorBefore()"></span><span class="text-fg-soft motion-safe:transition-opacity motion-safe:duration-150" :class="{ 'opacity-100': ghost() !== '', 'opacity-0': ghost() === '' }" data-stx-ai-ghost-text x-text="ghost()"></span></div>
333
+
334
+ <span class="sr-only" role="status" aria-live="polite" aria-atomic="true" x-text="announcement()"></span>
335
+ </div>
336
+
337
+ @if(helperText)
338
+ <p id="{{ helperId }}" class="{{ helperClasses }}">
339
+ {{ helperText }}
340
+ </p>
341
+ @endif
342
+ </div>