@tooee/ask 0.1.22 → 0.2.1

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.
@@ -0,0 +1,558 @@
1
+ import { useCallback, useEffect, useRef, useState } from "react"
2
+ import type {
3
+ InputRenderable,
4
+ KeyEvent,
5
+ MouseEvent,
6
+ PasteEvent,
7
+ TextareaRenderable,
8
+ } from "@opentui/core"
9
+ import { readPrimaryText } from "@tooee/clipboard"
10
+ import {
11
+ useActiveCommandSurface,
12
+ useCommand,
13
+ useCommandSurfaceId,
14
+ useMode,
15
+ useProvideCommandContext,
16
+ useSetMode,
17
+ type Mode,
18
+ } from "@tooee/commands"
19
+ import { appendAtCursor, openLineAtCursor, type VimMotionState } from "./vim-motions.js"
20
+
21
+ declare module "@tooee/commands" {
22
+ interface CommandContext {
23
+ /** Contributed by ask editors: the current input value. */
24
+ ask: { value: string }
25
+ }
26
+ }
27
+
28
+ /** Built-in command groups; disable one to take over its keys entirely. */
29
+ export type AskEditorCommandGroup = "motions" | "insert-commands" | "submit" | "cancel" | "escape"
30
+
31
+ export type AskSubmitKey = "enter" | "shift+enter" | "none"
32
+
33
+ export interface UseAskEditorOptions {
34
+ /** Render/edit a multiline textarea instead of a single-line input (default false). */
35
+ multiline?: boolean
36
+ defaultValue?: string
37
+ placeholder?: string
38
+ onSubmit?: (value: string) => void | Promise<void>
39
+ /** Enables the `q` cancel command (cursor mode) when provided. */
40
+ onCancel?: () => void
41
+ /** Which key submits. Default: "shift+enter" when multiline, "enter" otherwise. */
42
+ submitKey?: AskSubmitKey
43
+ /** Prefix for command ids, default "ask" (e.g. "ask:move-left"). */
44
+ commandScope?: string
45
+ /** Disable built-in command groups when a consumer wants full control. */
46
+ disable?: AskEditorCommandGroup[]
47
+ /**
48
+ * Force the editor to blur (e.g. while a legacy overlay covers the host
49
+ * app). ORed with the automatic suspension derived from the command-surface
50
+ * stack; affects focus only, never command gating.
51
+ */
52
+ suspended?: boolean
53
+ }
54
+
55
+ /** Programmatic text control for composites (dictation, prefill, transforms). */
56
+ export interface AskEditorController {
57
+ /** Current text (works for input and textarea). */
58
+ getText(): string
59
+ /** Replace the buffer; optionally move cursor to end (default true). */
60
+ setText(text: string, opts?: { cursorToEnd?: boolean }): void
61
+ /** Insert at the cursor position. */
62
+ insertText(text: string): void
63
+ setCursorToEnd(): void
64
+ submit(): void
65
+ /** Current local mode (live read). */
66
+ readonly mode: Mode
67
+ /** Switch insert/cursor mode; resets any pending vim motion state. */
68
+ setMode(mode: Mode): void
69
+ }
70
+
71
+ /** Everything `<AskEditor/>` needs: refs, focus, mode, handlers. */
72
+ export interface AskEditorViewModel {
73
+ multiline: boolean
74
+ defaultValue?: string
75
+ placeholder?: string
76
+ /** Single-line controlled value + change handler (unused for multiline). */
77
+ value: string
78
+ onInput: (value: string) => void
79
+ textareaRef: { current: TextareaRenderable | null }
80
+ inputRef: { current: InputRenderable | null }
81
+ /** Local surface mode, drives cursor styling. */
82
+ mode: Mode
83
+ /** True while a modal command surface above this one owns keyboard input. */
84
+ suspended: boolean
85
+ /** Editor focus: insert/cursor mode and not suspended. */
86
+ focused: boolean
87
+ /** Scrollbar re-compute revision; bumped whenever the viewport may have moved. */
88
+ scrollRevision: number
89
+ bumpScroll: () => void
90
+ /** Blocks editor input while in cursor mode (wire to onKeyDown/onPaste). */
91
+ onEditorKeyDown: (event: KeyEvent | PasteEvent) => void
92
+ onEditorPaste: (event: KeyEvent | PasteEvent) => void
93
+ submit: () => void
94
+ /** Middle-click primary-selection paste; attach to the surrounding panel/container. */
95
+ onMouseDown: (event: MouseEvent) => void
96
+ }
97
+
98
+ export interface UseAskEditorResult {
99
+ controller: AskEditorController
100
+ editor: AskEditorViewModel
101
+ }
102
+
103
+ /**
104
+ * Headless ask editor core: owns editor state and registers all editing
105
+ * commands (vim motions, insert entries, submit/cancel/escape) on the nearest
106
+ * command surface, so it works identically at the app root, inside an
107
+ * `ownCommands` overlay, or under any `CommandSurfaceProvider`.
108
+ */
109
+ export function useAskEditor(options: UseAskEditorOptions = {}): UseAskEditorResult {
110
+ const { multiline = false, defaultValue, placeholder, commandScope = "ask" } = options
111
+
112
+ const mode = useMode()
113
+ const setMode = useSetMode()
114
+
115
+ const [value, setValue] = useState(defaultValue ?? "")
116
+ const textareaRef = useRef<TextareaRenderable>(null)
117
+ const inputRef = useRef<InputRenderable>(null)
118
+ const didPositionInitialCursorRef = useRef(false)
119
+ const vimMotionStateRef = useRef<VimMotionState>({ pendingG: false })
120
+ // Bumped whenever the editor viewport may have moved (cursor, content, wheel)
121
+ // so the scrollbar thumb re-computes from the editor's internal scroll state.
122
+ const [scrollRevision, setScrollRevision] = useState(0)
123
+ const bumpScroll = useCallback(() => setScrollRevision((r) => r + 1), [])
124
+
125
+ const optionsRef = useRef(options)
126
+ optionsRef.current = options
127
+ const modeRef = useRef(mode)
128
+ modeRef.current = mode
129
+ const multilineRef = useRef(multiline)
130
+ multilineRef.current = multiline
131
+ const valueRef = useRef(value)
132
+ valueRef.current = value
133
+
134
+ // Suspension: while a modal command surface other than our own is topmost,
135
+ // our commands are already suspended by the surface stack; this mirrors that
136
+ // for renderable focus so the editor blurs under a nested picker.
137
+ const surfaceId = useCommandSurfaceId()
138
+ const activeSurface = useActiveCommandSurface()
139
+ const suspended =
140
+ (options.suspended ?? false) || (activeSurface !== null && activeSurface.id !== surfaceId)
141
+
142
+ const focused = (mode === "insert" || mode === "cursor") && !suspended
143
+
144
+ const preventCursorModeEditorInput = useCallback((event: KeyEvent | PasteEvent) => {
145
+ if (modeRef.current === "cursor") event.preventDefault()
146
+ }, [])
147
+
148
+ useEffect(() => {
149
+ if (didPositionInitialCursorRef.current || !defaultValue) return
150
+
151
+ const target = multiline ? textareaRef.current : inputRef.current
152
+ if (!target) return
153
+
154
+ target.cursorOffset = target.plainText.length
155
+ didPositionInitialCursorRef.current = true
156
+ }, [defaultValue, multiline])
157
+
158
+ // Ensure the scrollbar computes once the editor ref and layout exist.
159
+ useEffect(() => {
160
+ bumpScroll()
161
+ }, [bumpScroll])
162
+
163
+ const getTarget = useCallback(
164
+ () => (multilineRef.current ? textareaRef.current : inputRef.current),
165
+ [],
166
+ )
167
+
168
+ const getText = useCallback(
169
+ () =>
170
+ multilineRef.current
171
+ ? (textareaRef.current?.plainText ?? "")
172
+ : // Read the renderable's live text: controller mutations (insertText)
173
+ // must be visible before React state re-syncs on the next render.
174
+ (inputRef.current?.plainText ?? valueRef.current),
175
+ [],
176
+ )
177
+
178
+ const submit = useCallback(() => {
179
+ void optionsRef.current.onSubmit?.(getText())
180
+ }, [getText])
181
+
182
+ useProvideCommandContext(() => ({ ask: { value: getText() } }))
183
+
184
+ const enabled = useCallback(
185
+ (group: AskEditorCommandGroup) => !(optionsRef.current.disable?.includes(group) ?? false),
186
+ [],
187
+ )
188
+
189
+ const resolveSubmitKey = useCallback((): AskSubmitKey => {
190
+ const current = optionsRef.current
191
+ return current.submitKey ?? (current.multiline ? "shift+enter" : "enter")
192
+ }, [])
193
+
194
+ const enterInsertMode = useCallback(() => {
195
+ vimMotionStateRef.current.pendingG = false
196
+ setMode("insert")
197
+ }, [setMode])
198
+
199
+ const appendAndEnterInsertMode = useCallback(() => {
200
+ vimMotionStateRef.current.pendingG = false
201
+ appendAtCursor(getTarget())
202
+ setMode("insert")
203
+ }, [getTarget, setMode])
204
+
205
+ const openLineAbove = useCallback(() => {
206
+ if (!multilineRef.current) return
207
+ vimMotionStateRef.current.pendingG = false
208
+ openLineAtCursor(textareaRef.current, "above")
209
+ setMode("insert")
210
+ }, [setMode])
211
+
212
+ const openLineBelow = useCallback(() => {
213
+ if (!multilineRef.current) return
214
+ vimMotionStateRef.current.pendingG = false
215
+ openLineAtCursor(textareaRef.current, "below")
216
+ setMode("insert")
217
+ }, [setMode])
218
+
219
+ const leaveInsertMode = useCallback(() => {
220
+ vimMotionStateRef.current.pendingG = false
221
+ setMode("cursor")
222
+ }, [setMode])
223
+
224
+ useCommand({
225
+ id: `${commandScope}:leave-insert-mode`,
226
+ title: "Command mode",
227
+ hotkey: "Escape",
228
+ modes: ["insert"],
229
+ hidden: true,
230
+ when: () => enabled("escape"),
231
+ handler: leaveInsertMode,
232
+ })
233
+ useCommand({
234
+ id: `${commandScope}:cancel`,
235
+ title: "Cancel",
236
+ hotkey: "q",
237
+ modes: ["cursor"],
238
+ hidden: true,
239
+ when: () => enabled("cancel") && optionsRef.current.onCancel !== undefined,
240
+ handler: () => optionsRef.current.onCancel?.(),
241
+ })
242
+ useCommand({
243
+ id: `${commandScope}:insert-mode-i`,
244
+ title: "Insert mode",
245
+ hotkey: "i",
246
+ modes: ["cursor"],
247
+ hidden: true,
248
+ when: () => enabled("insert-commands"),
249
+ handler: enterInsertMode,
250
+ })
251
+ useCommand({
252
+ id: `${commandScope}:insert-mode-a`,
253
+ title: "Append",
254
+ hotkey: "a",
255
+ modes: ["cursor"],
256
+ hidden: true,
257
+ when: () => enabled("insert-commands"),
258
+ handler: appendAndEnterInsertMode,
259
+ })
260
+ useCommand({
261
+ id: `${commandScope}:open-line-above`,
262
+ title: "Open line above",
263
+ hotkey: "shift+o",
264
+ modes: ["cursor"],
265
+ hidden: true,
266
+ when: () => enabled("insert-commands") && multilineRef.current,
267
+ handler: openLineAbove,
268
+ })
269
+ useCommand({
270
+ id: `${commandScope}:open-line-below`,
271
+ title: "Open line below",
272
+ hotkey: "o",
273
+ modes: ["cursor"],
274
+ hidden: true,
275
+ when: () => enabled("insert-commands") && multilineRef.current,
276
+ handler: openLineBelow,
277
+ })
278
+ useCommand({
279
+ id: `${commandScope}:submit-single-line`,
280
+ title: "Submit",
281
+ hotkey: "Enter",
282
+ modes: ["insert", "cursor"],
283
+ hidden: true,
284
+ when: () => enabled("submit") && resolveSubmitKey() === "enter",
285
+ handler: submit,
286
+ })
287
+ useCommand({
288
+ id: `${commandScope}:submit-multiline`,
289
+ title: "Submit",
290
+ hotkey: "shift+Enter",
291
+ modes: ["insert", "cursor"],
292
+ hidden: true,
293
+ // Shift+Enter always submits (single-line editors have no newline for it
294
+ // to mean); plain Enter only when it is the configured submit key.
295
+ when: () => enabled("submit") && resolveSubmitKey() !== "none",
296
+ handler: submit,
297
+ })
298
+
299
+ const motion = useCallback(
300
+ (run: (target: TextareaRenderable | InputRenderable) => void) => {
301
+ const target = getTarget()
302
+ if (target) run(target)
303
+ vimMotionStateRef.current.pendingG = false
304
+ bumpScroll()
305
+ },
306
+ [getTarget, bumpScroll],
307
+ )
308
+
309
+ useCommand({
310
+ id: `${commandScope}:move-left`,
311
+ title: "Move left",
312
+ hotkey: "h",
313
+ modes: ["cursor"],
314
+ hidden: true,
315
+ when: () => enabled("motions"),
316
+ handler: () => motion((target) => target.moveCursorLeft()),
317
+ })
318
+ useCommand({
319
+ id: `${commandScope}:move-left-arrow`,
320
+ title: "Move left",
321
+ hotkey: "left",
322
+ modes: ["cursor"],
323
+ hidden: true,
324
+ when: () => enabled("motions"),
325
+ handler: () => motion((target) => target.moveCursorLeft()),
326
+ })
327
+ useCommand({
328
+ id: `${commandScope}:move-right`,
329
+ title: "Move right",
330
+ hotkey: "l",
331
+ modes: ["cursor"],
332
+ hidden: true,
333
+ when: () => enabled("motions"),
334
+ handler: () => motion((target) => target.moveCursorRight()),
335
+ })
336
+ useCommand({
337
+ id: `${commandScope}:move-right-arrow`,
338
+ title: "Move right",
339
+ hotkey: "right",
340
+ modes: ["cursor"],
341
+ hidden: true,
342
+ when: () => enabled("motions"),
343
+ handler: () => motion((target) => target.moveCursorRight()),
344
+ })
345
+ useCommand({
346
+ id: `${commandScope}:move-down`,
347
+ title: "Move down",
348
+ hotkey: "j",
349
+ modes: ["cursor"],
350
+ hidden: true,
351
+ when: () => enabled("motions"),
352
+ handler: () => motion((target) => target.moveCursorDown()),
353
+ })
354
+ useCommand({
355
+ id: `${commandScope}:move-down-arrow`,
356
+ title: "Move down",
357
+ hotkey: "down",
358
+ modes: ["cursor"],
359
+ hidden: true,
360
+ when: () => enabled("motions"),
361
+ handler: () => motion((target) => target.moveCursorDown()),
362
+ })
363
+ useCommand({
364
+ id: `${commandScope}:move-up`,
365
+ title: "Move up",
366
+ hotkey: "k",
367
+ modes: ["cursor"],
368
+ hidden: true,
369
+ when: () => enabled("motions"),
370
+ handler: () => motion((target) => target.moveCursorUp()),
371
+ })
372
+ useCommand({
373
+ id: `${commandScope}:move-up-arrow`,
374
+ title: "Move up",
375
+ hotkey: "up",
376
+ modes: ["cursor"],
377
+ hidden: true,
378
+ when: () => enabled("motions"),
379
+ handler: () => motion((target) => target.moveCursorUp()),
380
+ })
381
+ useCommand({
382
+ id: `${commandScope}:line-home`,
383
+ title: "Line home",
384
+ hotkey: "0",
385
+ modes: ["cursor"],
386
+ hidden: true,
387
+ when: () => enabled("motions"),
388
+ handler: () => motion((target) => target.gotoLineHome()),
389
+ })
390
+ useCommand({
391
+ id: `${commandScope}:line-home-key`,
392
+ title: "Line home",
393
+ hotkey: "home",
394
+ modes: ["cursor"],
395
+ hidden: true,
396
+ when: () => enabled("motions"),
397
+ handler: () => motion((target) => target.gotoLineHome()),
398
+ })
399
+ useCommand({
400
+ id: `${commandScope}:line-end`,
401
+ title: "Line end",
402
+ hotkey: "shift+4",
403
+ modes: ["cursor"],
404
+ hidden: true,
405
+ when: () => enabled("motions"),
406
+ handler: () => motion((target) => target.gotoLineEnd()),
407
+ })
408
+ useCommand({
409
+ id: `${commandScope}:line-end-key`,
410
+ title: "Line end",
411
+ hotkey: "end",
412
+ modes: ["cursor"],
413
+ hidden: true,
414
+ when: () => enabled("motions"),
415
+ handler: () => motion((target) => target.gotoLineEnd()),
416
+ })
417
+ useCommand({
418
+ id: `${commandScope}:word-forward`,
419
+ title: "Word forward",
420
+ hotkey: "w",
421
+ modes: ["cursor"],
422
+ hidden: true,
423
+ when: () => enabled("motions"),
424
+ handler: () => motion((target) => target.moveWordForward()),
425
+ })
426
+ useCommand({
427
+ id: `${commandScope}:word-backward`,
428
+ title: "Word backward",
429
+ hotkey: "b",
430
+ modes: ["cursor"],
431
+ hidden: true,
432
+ when: () => enabled("motions"),
433
+ handler: () => motion((target) => target.moveWordBackward()),
434
+ })
435
+ useCommand({
436
+ id: `${commandScope}:buffer-home`,
437
+ title: "Buffer home",
438
+ hotkey: "g g",
439
+ modes: ["cursor"],
440
+ hidden: true,
441
+ when: () => enabled("motions"),
442
+ handler: () => motion((target) => target.gotoBufferHome()),
443
+ })
444
+ useCommand({
445
+ id: `${commandScope}:buffer-end`,
446
+ title: "Buffer end",
447
+ hotkey: "shift+g",
448
+ modes: ["cursor"],
449
+ hidden: true,
450
+ when: () => enabled("motions"),
451
+ handler: () => motion((target) => target.gotoBufferEnd()),
452
+ })
453
+
454
+ // Middle-click paste from primary selection
455
+ const handleMouseDown = useCallback(
456
+ (event: MouseEvent) => {
457
+ if (event.button === 1) {
458
+ event.preventDefault()
459
+ void readPrimaryText().then((text) => {
460
+ if (!text) return
461
+ getTarget()?.insertText(text)
462
+ })
463
+ }
464
+ },
465
+ [getTarget],
466
+ )
467
+
468
+ const setText = useCallback(
469
+ (text: string, opts?: { cursorToEnd?: boolean }) => {
470
+ const cursorToEnd = opts?.cursorToEnd ?? true
471
+ if (multilineRef.current) {
472
+ const target = textareaRef.current
473
+ if (!target) return
474
+ const prevOffset = target.cursorOffset
475
+ target.replaceText(text)
476
+ target.cursorOffset = cursorToEnd
477
+ ? target.plainText.length
478
+ : Math.min(prevOffset, target.plainText.length)
479
+ } else {
480
+ // Route through React state (the input is controlled) and mirror onto
481
+ // the renderable so the change takes effect before the next render.
482
+ const target = inputRef.current
483
+ const prevOffset = target?.cursorOffset ?? 0
484
+ setValue(text)
485
+ if (target) {
486
+ target.value = text
487
+ target.cursorOffset = cursorToEnd
488
+ ? target.plainText.length
489
+ : Math.min(prevOffset, target.plainText.length)
490
+ }
491
+ }
492
+ bumpScroll()
493
+ },
494
+ [bumpScroll],
495
+ )
496
+
497
+ const insertText = useCallback(
498
+ (text: string) => {
499
+ getTarget()?.insertText(text)
500
+ bumpScroll()
501
+ },
502
+ [getTarget, bumpScroll],
503
+ )
504
+
505
+ const setCursorToEnd = useCallback(() => {
506
+ const target = getTarget()
507
+ if (!target) return
508
+ target.cursorOffset = target.plainText.length
509
+ bumpScroll()
510
+ }, [getTarget, bumpScroll])
511
+
512
+ const setModeExternal = useCallback(
513
+ (next: Mode) => {
514
+ vimMotionStateRef.current.pendingG = false
515
+ setMode(next)
516
+ },
517
+ [setMode],
518
+ )
519
+
520
+ // Stable identity so composites can capture it in refs/effects; `mode` reads
521
+ // live through the getter.
522
+ const controllerRef = useRef<AskEditorController | null>(null)
523
+ if (controllerRef.current === null) {
524
+ controllerRef.current = {
525
+ getText,
526
+ setText,
527
+ insertText,
528
+ setCursorToEnd,
529
+ submit,
530
+ get mode() {
531
+ return modeRef.current
532
+ },
533
+ setMode: setModeExternal,
534
+ }
535
+ }
536
+
537
+ return {
538
+ controller: controllerRef.current,
539
+ editor: {
540
+ multiline,
541
+ defaultValue,
542
+ placeholder,
543
+ value,
544
+ onInput: setValue,
545
+ textareaRef,
546
+ inputRef,
547
+ mode,
548
+ suspended,
549
+ focused,
550
+ scrollRevision,
551
+ bumpScroll,
552
+ onEditorKeyDown: preventCursorModeEditorInput,
553
+ onEditorPaste: preventCursorModeEditorInput,
554
+ submit,
555
+ onMouseDown: handleMouseDown,
556
+ },
557
+ }
558
+ }