@tensorpass/aiconnect-react 0.1.6 → 0.1.8

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 (87) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.js.map +1 -1
  3. package/dist/moduleMessages.d.ts +22 -0
  4. package/dist/moduleMessages.js +110 -0
  5. package/dist/moduleMessages.js.map +1 -1
  6. package/dist/modules/AiSearch.js +16 -5
  7. package/dist/modules/AiSearch.js.map +1 -1
  8. package/dist/modules/parts/ChatFrame.d.ts +1 -1
  9. package/dist/modules/parts/ChatFrame.js +11 -2
  10. package/dist/modules/parts/ChatFrame.js.map +1 -1
  11. package/dist/modules/parts/Composer.d.ts +9 -2
  12. package/dist/modules/parts/Composer.js +49 -12
  13. package/dist/modules/parts/Composer.js.map +1 -1
  14. package/dist/modules/parts/Conversation.js +14 -11
  15. package/dist/modules/parts/Conversation.js.map +1 -1
  16. package/dist/modules/parts/attachments/AttachButton.d.ts +5 -0
  17. package/dist/modules/parts/attachments/AttachButton.js +29 -0
  18. package/dist/modules/parts/attachments/AttachButton.js.map +1 -0
  19. package/dist/modules/parts/attachments/AttachmentChip.d.ts +12 -0
  20. package/dist/modules/parts/attachments/AttachmentChip.js +17 -0
  21. package/dist/modules/parts/attachments/AttachmentChip.js.map +1 -0
  22. package/dist/modules/parts/attachments/AttachmentRows.d.ts +11 -0
  23. package/dist/modules/parts/attachments/AttachmentRows.js +29 -0
  24. package/dist/modules/parts/attachments/AttachmentRows.js.map +1 -0
  25. package/dist/modules/parts/attachments/DropZone.d.ts +8 -0
  26. package/dist/modules/parts/attachments/DropZone.js +57 -0
  27. package/dist/modules/parts/attachments/DropZone.js.map +1 -0
  28. package/dist/modules/parts/attachments/Lightbox.d.ts +10 -0
  29. package/dist/modules/parts/attachments/Lightbox.js +43 -0
  30. package/dist/modules/parts/attachments/Lightbox.js.map +1 -0
  31. package/dist/modules/parts/attachments/attachmentList.d.ts +25 -0
  32. package/dist/modules/parts/attachments/attachmentList.js +26 -0
  33. package/dist/modules/parts/attachments/attachmentList.js.map +1 -0
  34. package/dist/modules/parts/attachments/fileSize.d.ts +1 -0
  35. package/dist/modules/parts/attachments/fileSize.js +14 -0
  36. package/dist/modules/parts/attachments/fileSize.js.map +1 -0
  37. package/dist/modules/parts/attachments/useAttachments.d.ts +13 -0
  38. package/dist/modules/parts/attachments/useAttachments.js +77 -0
  39. package/dist/modules/parts/attachments/useAttachments.js.map +1 -0
  40. package/dist/modules/parts/dictation/DictationBar.d.ts +4 -0
  41. package/dist/modules/parts/dictation/DictationBar.js +26 -0
  42. package/dist/modules/parts/dictation/DictationBar.js.map +1 -0
  43. package/dist/modules/parts/dictation/MicButton.d.ts +5 -0
  44. package/dist/modules/parts/dictation/MicButton.js +20 -0
  45. package/dist/modules/parts/dictation/MicButton.js.map +1 -0
  46. package/dist/modules/parts/dictation/audioCapture.d.ts +7 -0
  47. package/dist/modules/parts/dictation/audioCapture.js +44 -0
  48. package/dist/modules/parts/dictation/audioCapture.js.map +1 -0
  49. package/dist/modules/parts/dictation/browserSpeech.d.ts +37 -0
  50. package/dist/modules/parts/dictation/browserSpeech.js +32 -0
  51. package/dist/modules/parts/dictation/browserSpeech.js.map +1 -0
  52. package/dist/modules/parts/dictation/dictationLanguage.d.ts +2 -0
  53. package/dist/modules/parts/dictation/dictationLanguage.js +15 -0
  54. package/dist/modules/parts/dictation/dictationLanguage.js.map +1 -0
  55. package/dist/modules/parts/dictation/pcmWorklet.d.ts +1 -0
  56. package/dist/modules/parts/dictation/pcmWorklet.js +48 -0
  57. package/dist/modules/parts/dictation/pcmWorklet.js.map +1 -0
  58. package/dist/modules/parts/dictation/pcmWorkletUrl.d.ts +1 -0
  59. package/dist/modules/parts/dictation/pcmWorkletUrl.js +5 -0
  60. package/dist/modules/parts/dictation/pcmWorkletUrl.js.map +1 -0
  61. package/dist/modules/parts/dictation/recording.d.ts +19 -0
  62. package/dist/modules/parts/dictation/recording.js +45 -0
  63. package/dist/modules/parts/dictation/recording.js.map +1 -0
  64. package/dist/modules/parts/dictation/useDictation.d.ts +22 -0
  65. package/dist/modules/parts/dictation/useDictation.js +164 -0
  66. package/dist/modules/parts/dictation/useDictation.js.map +1 -0
  67. package/dist/modules/parts/icons.d.ts +5 -0
  68. package/dist/modules/parts/icons.js +6 -0
  69. package/dist/modules/parts/icons.js.map +1 -1
  70. package/dist/modules/parts/moduleAnalytics.d.ts +1 -1
  71. package/dist/modules/parts/moduleAnalytics.js.map +1 -1
  72. package/dist/modules/parts/useModuleChat.d.ts +6 -3
  73. package/dist/modules/parts/useModuleChat.js +20 -16
  74. package/dist/modules/parts/useModuleChat.js.map +1 -1
  75. package/dist/modules/types.d.ts +2 -0
  76. package/dist/modules/types.js +3 -2
  77. package/dist/modules/types.js.map +1 -1
  78. package/dist/modules/useOverlay.js +2 -1
  79. package/dist/modules/useOverlay.js.map +1 -1
  80. package/dist/styles.css +394 -0
  81. package/dist/transcriptBudget.d.ts +3 -0
  82. package/dist/transcriptBudget.js +34 -0
  83. package/dist/transcriptBudget.js.map +1 -0
  84. package/dist/useAiChat.d.ts +10 -1
  85. package/dist/useAiChat.js +30 -9
  86. package/dist/useAiChat.js.map +1 -1
  87. package/package.json +5 -4
@@ -0,0 +1,164 @@
1
+ // Dictation in a module, as in Claude's and ChatGPT's apps: the visitor speaks, the words appear while they
2
+ // speak where the transcription writes them live, and once the visitor stops, the transcript lands in the
3
+ // question field for them to correct and send. The transcription service of the account that answers writes
4
+ // the words; without one, the browser's speech recognition does. The microphone gives the waveform and the
5
+ // timer either way, and the recording ends on its own after 15 seconds of silence or 2 minutes.
6
+ import { useCallback, useEffect, useRef, useState } from 'react';
7
+ import { useAiConnect } from "../../../AiConnectProvider.js";
8
+ import { startCapture } from "./audioCapture.js";
9
+ import { recognitionClass, startBrowserSpeech } from "./browserSpeech.js";
10
+ import { dictationLanguage } from "./dictationLanguage.js";
11
+ import { countFrame, handOver, newRecording, releaseRecording, spokenSeconds } from "./recording.js";
12
+ // The levels the waveform draws, the newest last.
13
+ export const WAVE_BARS = 40;
14
+ const IDLE = { status: 'idle', partial: '', levels: [], seconds: 0 };
15
+ // Whether this browser can dictate: a microphone, and the account's transcription or the browser's recognition.
16
+ export function dictationAvailable(dictation) {
17
+ const microphone = typeof navigator !== 'undefined' && Boolean(navigator.mediaDevices?.getUserMedia);
18
+ return microphone && (dictation !== null || recognitionClass() !== null);
19
+ }
20
+ // The reason a dictation fails when the site used its dictation of the day and the browser has no recognition.
21
+ const LIMIT_REACHED = 'limit-reached';
22
+ function failureText(reason, copy) {
23
+ if (reason === LIMIT_REACHED) {
24
+ return copy.dictationLimit;
25
+ }
26
+ const name = reason?.name;
27
+ const denied = name === 'NotAllowedError' || name === 'SecurityError' || reason === 'not-allowed';
28
+ return denied ? copy.micDenied : copy.dictationFailed;
29
+ }
30
+ // What the bar shows while the visitor dictates, and the words written so far.
31
+ function useDictationView() {
32
+ const [view, setView] = useState(IDLE);
33
+ const written = useRef('');
34
+ const write = useCallback((text) => {
35
+ written.current = text;
36
+ setView((current) => ({ ...current, partial: text }));
37
+ }, []);
38
+ const level = useCallback((value, seconds) => setView((current) => ({
39
+ ...current, seconds, levels: [...current.levels.slice(1 - WAVE_BARS), value],
40
+ })), []);
41
+ const status = useCallback((next) => setView((current) => ({ ...current, status: next })), []);
42
+ const reset = useCallback(() => {
43
+ written.current = '';
44
+ setView(IDLE);
45
+ }, []);
46
+ return { view, written, write, level, status, reset };
47
+ }
48
+ function listenInBrowser(recording, { language, write, fail }) {
49
+ recording.speech = startBrowserSpeech(language, {
50
+ onText: write,
51
+ onError: (code) => (code === 'no-speech' ? undefined : fail(code)),
52
+ onEnd: recording.markEnded,
53
+ });
54
+ }
55
+ // The account's transcription. A site that used its dictation of the day on the account (429) goes on with
56
+ // the browser's recognition where the browser has one.
57
+ function onAccountEvent(recording, options) {
58
+ return (event) => {
59
+ if (event.kind !== 'error') {
60
+ options.write(event.text);
61
+ }
62
+ else if (event.status === 429 && recognitionClass()) {
63
+ handOver(recording);
64
+ listenInBrowser(recording, options);
65
+ }
66
+ else {
67
+ options.fail(event.status === 429 ? LIMIT_REACHED : new Error(event.message));
68
+ }
69
+ };
70
+ }
71
+ // Opens the microphone, then the account's transcription or the browser's recognition.
72
+ async function openRecording(recording, options) {
73
+ recording.capture = await startCapture({ onFrame: options.onFrame });
74
+ const { dictation, language } = options;
75
+ if (dictation) {
76
+ recording.session = dictation.start({ language }, onAccountEvent(recording, options), recording.controller.signal);
77
+ recording.markEnded();
78
+ return;
79
+ }
80
+ listenInBrowser(recording, options);
81
+ }
82
+ // The whole transcript once the recording stopped: the account's, or the browser's last words.
83
+ async function transcriptOf(recording, written) {
84
+ recording.speech?.stop();
85
+ if (recording.session) {
86
+ return recording.session.finish();
87
+ }
88
+ await recording.ended;
89
+ return written.current;
90
+ }
91
+ // The recording that runs and how it ends: released, or failed with the words that say why. Leaving the page
92
+ // releases the microphone.
93
+ function useRecordingEnd(recordingRef, reset) {
94
+ const { moduleMessages } = useAiConnect();
95
+ const [error, setError] = useState(null);
96
+ const end = useCallback(() => {
97
+ releaseRecording(recordingRef.current);
98
+ recordingRef.current = null;
99
+ reset();
100
+ }, [recordingRef, reset]);
101
+ const fail = useCallback((reason) => {
102
+ end();
103
+ setError(failureText(reason, moduleMessages));
104
+ }, [end, moduleMessages]);
105
+ useEffect(() => () => releaseRecording(recordingRef.current), [recordingRef]);
106
+ return { error, setError, end, fail };
107
+ }
108
+ export function useDictation(dictation, onFinal) {
109
+ const { locale } = useAiConnect();
110
+ const { view, written, write, level, status, reset } = useDictationView();
111
+ const recording = useRef(null);
112
+ const { error, setError, end, fail } = useRecordingEnd(recording, reset);
113
+ const autoStop = useRef(() => undefined);
114
+ const onFrame = useCallback((pcm, value) => {
115
+ const current = recording.current;
116
+ if (!current) {
117
+ return;
118
+ }
119
+ current.session?.sendFrame(pcm);
120
+ const ending = countFrame(current, value);
121
+ level(value, spokenSeconds(current));
122
+ if (ending) {
123
+ autoStop.current();
124
+ }
125
+ }, [level]);
126
+ const start = useCallback(async () => {
127
+ if (recording.current) {
128
+ return;
129
+ }
130
+ setError(null);
131
+ status('listening');
132
+ const current = newRecording();
133
+ recording.current = current;
134
+ const options = { dictation, language: dictationLanguage(locale, navigator.languages), onFrame, write, fail };
135
+ await openRecording(current, options).catch(fail);
136
+ if (current.controller.signal.aborted) {
137
+ releaseRecording(current);
138
+ }
139
+ }, [setError, dictation, locale, onFrame, write, fail, status]);
140
+ // Stops listening and puts the whole transcript in the field.
141
+ const stop = useCallback(async () => {
142
+ const current = recording.current;
143
+ if (!current || current.stopping) {
144
+ return;
145
+ }
146
+ current.stopping = true;
147
+ current.capture?.stop();
148
+ status('transcribing');
149
+ const text = await transcriptOf(current, written).catch((reason) => {
150
+ fail(reason);
151
+ return null;
152
+ });
153
+ // A recording the visitor cancelled while it was transcribed writes nothing.
154
+ if (text !== null && recording.current === current) {
155
+ end();
156
+ onFinal(text.trim());
157
+ }
158
+ }, [onFinal, end, fail, status, written]);
159
+ useEffect(() => {
160
+ autoStop.current = () => void stop();
161
+ }, [stop]);
162
+ return { ...view, error, start, stop, cancel: end, dismissError: () => setError(null) };
163
+ }
164
+ //# sourceMappingURL=useDictation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDictation.js","sourceRoot":"","sources":["../../../../src/modules/parts/dictation/useDictation.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,0GAA0G;AAC1G,4GAA4G;AAC5G,2GAA2G;AAC3G,gGAAgG;AAEhG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAIjE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAAgC,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAE,iB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AE,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAE1C,SAAS,CAAC,GAAG,EAAE;QACb,QAAQ,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC;IACvC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IAEX,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;AAC1F,CAAC","sourcesContent":["// Dictation in a module, as in Claude's and ChatGPT's apps: the visitor speaks, the words appear while they\n// speak where the transcription writes them live, and once the visitor stops, the transcript lands in the\n// question field for them to correct and send. The transcription service of the account that answers writes\n// the words; without one, the browser's speech recognition does. The microphone gives the waveform and the\n// timer either way, and the recording ends on its own after 15 seconds of silence or 2 minutes.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { RefObject } from 'react';\nimport type { Dictation, DictationEvent } from '@tensorpass/aiconnect';\nimport type { ModuleMessages } from '../../../messages.ts';\nimport { useAiConnect } from '../../../AiConnectProvider.tsx';\nimport { startCapture } from './audioCapture.ts';\nimport { recognitionClass, startBrowserSpeech } from './browserSpeech.ts';\nimport { dictationLanguage } from './dictationLanguage.ts';\nimport { countFrame, handOver, newRecording, releaseRecording, spokenSeconds } from './recording.ts';\nimport type { Recording } from './recording.ts';\n\nexport type DictationStatus = 'idle' | 'listening' | 'transcribing';\n\n// The levels the waveform draws, the newest last.\nexport const WAVE_BARS = 40;\n\nexport interface DictationView {\n status: DictationStatus;\n partial: string;\n levels: number[];\n seconds: number;\n}\n\nconst IDLE: DictationView = { status: 'idle', partial: '', levels: [], seconds: 0 };\n\n// Whether this browser can dictate: a microphone, and the account's transcription or the browser's recognition.\nexport function dictationAvailable(dictation: Dictation | null): boolean {\n const microphone = typeof navigator !== 'undefined' && Boolean(navigator.mediaDevices?.getUserMedia);\n return microphone && (dictation !== null || recognitionClass() !== null);\n}\n\n// The reason a dictation fails when the site used its dictation of the day and the browser has no recognition.\nconst LIMIT_REACHED = 'limit-reached';\n\nfunction failureText(reason: unknown, copy: ModuleMessages): string {\n if (reason === LIMIT_REACHED) {\n return copy.dictationLimit;\n }\n const name = (reason as { name?: string } | null)?.name;\n const denied = name === 'NotAllowedError' || name === 'SecurityError' || reason === 'not-allowed';\n return denied ? copy.micDenied : copy.dictationFailed;\n}\n\n// What the bar shows while the visitor dictates, and the words written so far.\nfunction useDictationView() {\n const [view, setView] = useState<DictationView>(IDLE);\n const written = useRef('');\n const write = useCallback((text: string) => {\n written.current = text;\n setView((current) => ({ ...current, partial: text }));\n }, []);\n const level = useCallback((value: number, seconds: number) => setView((current) => ({\n ...current, seconds, levels: [...current.levels.slice(1 - WAVE_BARS), value],\n })), []);\n const status = useCallback((next: DictationStatus) => setView((current) => ({ ...current, status: next })), []);\n const reset = useCallback(() => {\n written.current = '';\n setView(IDLE);\n }, []);\n return { view, written, write, level, status, reset };\n}\n\ninterface OpenOptions {\n dictation: Dictation | null;\n language: string;\n onFrame: (pcm: Int16Array, level: number) => void;\n write: (text: string) => void;\n fail: (reason: unknown) => void;\n}\n\nfunction listenInBrowser(recording: Recording, { language, write, fail }: OpenOptions): void {\n recording.speech = startBrowserSpeech(language, {\n onText: write,\n onError: (code) => (code === 'no-speech' ? undefined : fail(code)),\n onEnd: recording.markEnded,\n });\n}\n\n// The account's transcription. A site that used its dictation of the day on the account (429) goes on with\n// the browser's recognition where the browser has one.\nfunction onAccountEvent(recording: Recording, options: OpenOptions) {\n return (event: DictationEvent) => {\n if (event.kind !== 'error') {\n options.write(event.text);\n } else if (event.status === 429 && recognitionClass()) {\n handOver(recording);\n listenInBrowser(recording, options);\n } else {\n options.fail(event.status === 429 ? LIMIT_REACHED : new Error(event.message));\n }\n };\n}\n\n// Opens the microphone, then the account's transcription or the browser's recognition.\nasync function openRecording(recording: Recording, options: OpenOptions) {\n recording.capture = await startCapture({ onFrame: options.onFrame });\n const { dictation, language } = options;\n if (dictation) {\n recording.session = dictation.start({ language }, onAccountEvent(recording, options), recording.controller.signal);\n recording.markEnded();\n return;\n }\n listenInBrowser(recording, options);\n}\n\n// The whole transcript once the recording stopped: the account's, or the browser's last words.\nasync function transcriptOf(recording: Recording, written: RefObject<string>): Promise<string> {\n recording.speech?.stop();\n if (recording.session) {\n return recording.session.finish();\n }\n await recording.ended;\n return written.current;\n}\n\n// The recording that runs and how it ends: released, or failed with the words that say why. Leaving the page\n// releases the microphone.\nfunction useRecordingEnd(recordingRef: RefObject<Recording | null>, reset: () => void) {\n const { moduleMessages } = useAiConnect();\n const [error, setError] = useState<string | null>(null);\n const end = useCallback(() => {\n releaseRecording(recordingRef.current);\n recordingRef.current = null;\n reset();\n }, [recordingRef, reset]);\n const fail = useCallback((reason: unknown) => {\n end();\n setError(failureText(reason, moduleMessages));\n }, [end, moduleMessages]);\n useEffect(() => () => releaseRecording(recordingRef.current), [recordingRef]);\n return { error, setError, end, fail };\n}\n\nexport function useDictation(dictation: Dictation | null, onFinal: (text: string) => void) {\n const { locale } = useAiConnect();\n const { view, written, write, level, status, reset } = useDictationView();\n const recording = useRef<Recording | null>(null);\n const { error, setError, end, fail } = useRecordingEnd(recording, reset);\n const autoStop = useRef<() => void>(() => undefined);\n const onFrame = useCallback((pcm: Int16Array, value: number) => {\n const current = recording.current;\n if (!current) {\n return;\n }\n current.session?.sendFrame(pcm);\n const ending = countFrame(current, value);\n level(value, spokenSeconds(current));\n if (ending) {\n autoStop.current();\n }\n }, [level]);\n\n const start = useCallback(async () => {\n if (recording.current) {\n return;\n }\n setError(null);\n status('listening');\n const current = newRecording();\n recording.current = current;\n const options = { dictation, language: dictationLanguage(locale, navigator.languages), onFrame, write, fail };\n await openRecording(current, options).catch(fail);\n if (current.controller.signal.aborted) {\n releaseRecording(current);\n }\n }, [setError, dictation, locale, onFrame, write, fail, status]);\n\n // Stops listening and puts the whole transcript in the field.\n const stop = useCallback(async () => {\n const current = recording.current;\n if (!current || current.stopping) {\n return;\n }\n current.stopping = true;\n current.capture?.stop();\n status('transcribing');\n const text = await transcriptOf(current, written).catch((reason: unknown) => {\n fail(reason);\n return null;\n });\n // A recording the visitor cancelled while it was transcribed writes nothing.\n if (text !== null && recording.current === current) {\n end();\n onFinal(text.trim());\n }\n }, [onFinal, end, fail, status, written]);\n\n useEffect(() => {\n autoStop.current = () => void stop();\n }, [stop]);\n\n return { ...view, error, start, stop, cancel: end, dismissError: () => setError(null) };\n}\n\nexport type DictationState = ReturnType<typeof useDictation>;\n"]}
@@ -8,3 +8,8 @@ export declare const NewChatIcon: () => import("react").JSX.Element;
8
8
  export declare const SearchIcon: () => import("react").JSX.Element;
9
9
  export declare const CheckIcon: () => import("react").JSX.Element;
10
10
  export declare const ArrowIcon: () => import("react").JSX.Element;
11
+ export declare const PaperclipIcon: () => import("react").JSX.Element;
12
+ export declare const MicIcon: () => import("react").JSX.Element;
13
+ export declare const FileIcon: () => import("react").JSX.Element;
14
+ export declare const BackIcon: () => import("react").JSX.Element;
15
+ export declare const ForwardIcon: () => import("react").JSX.Element;
@@ -12,4 +12,10 @@ export const SearchIcon = () => (_jsxs(Stroke, { size: 18, children: [_jsx("circ
12
12
  export const CheckIcon = () => _jsx(Stroke, { size: 12, width: 3, children: _jsx("path", { d: "m5 12 5 5 9-10" }) });
13
13
  // Points along the reading direction; the stylesheet mirrors it in right to left.
14
14
  export const ArrowIcon = () => _jsx(Stroke, { size: 16, className: "aic-arrow", children: _jsx("path", { d: "M5 12h14M13 6l6 6-6 6" }) });
15
+ export const PaperclipIcon = () => (_jsx(Stroke, { size: 18, children: _jsx("path", { d: "m20 11.5-7.8 7.8a5 5 0 0 1-7-7l8.4-8.4a3.3 3.3 0 0 1 4.7 4.7l-8.4 8.4a1.7 1.7 0 0 1-2.4-2.4l7.7-7.7" }) }));
16
+ export const MicIcon = () => (_jsxs(Stroke, { size: 18, children: [_jsx("rect", { x: "9", y: "3", width: "6", height: "11", rx: "3" }), _jsx("path", { d: "M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21" })] }));
17
+ export const FileIcon = () => (_jsxs(Stroke, { size: 18, width: 1.8, children: [_jsx("path", { d: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" }), _jsx("path", { d: "M14 3v5h5M9 13h6M9 17h4" })] }));
18
+ // Points back along the reading direction; the stylesheet mirrors it in right to left.
19
+ export const BackIcon = () => _jsx(Stroke, { size: 18, className: "aic-arrow", children: _jsx("path", { d: "m15 6-6 6 6 6" }) });
20
+ export const ForwardIcon = () => _jsx(Stroke, { size: 18, className: "aic-arrow", children: _jsx("path", { d: "m9 6 6 6-6 6" }) });
15
21
  //# sourceMappingURL=icons.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"icons.js","sourceRoot":"","sources":["../../../src/modules/parts/icons.tsx"],"names":[],"mappings":";AAIA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AASjE,SAAS,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,GAAG,CAAC,EAAE,SAAS,EAAe;IACxE,OAAO,CACL,cAAK,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,EACzG,WAAW,EAAE,KAAK,EAAE,aAAa,EAAC,OAAO,EAAC,cAAc,EAAC,OAAO,iBAAa,MAAM,EAAC,SAAS,EAAC,OAAO,YACpG,QAAQ,GACL,CACP,CAAC;AACJ,CAAC;AAED,yFAAyF;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,EAAyC,EAAE,EAAE,CAAC,CAC3F,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,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,SAAS,EAAC,WAAW,YAAC,eAAM,CAAC,EAAC,uBAAuB,GAAG,GAAS,CAAC","sourcesContent":["// The modules' drawn icons, in the AI Wallet's one stroke family (24 grid, round caps and joins).\n// The wave is the wallet's mark: the contactless arcs that light up while the visitor's AI answers.\n\nimport type { ReactNode } from 'react';\nimport { WAVE_ARCS, WAVE_STROKE_WIDTH } from '../../launcher.ts';\n\ninterface StrokeProps {\n children: ReactNode;\n size?: number;\n width?: number;\n className?: string;\n}\n\nfunction Stroke({ children, size = 18, width = 2, className }: StrokeProps) {\n return (\n <svg className={className} width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth={width} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {children}\n </svg>\n );\n}\n\n// The three arcs, each its own path so a live answer can light them one after the other.\nexport const WaveIcon = ({ size = 18, className }: { size?: number; className?: string }) => (\n <Stroke size={size} width={WAVE_STROKE_WIDTH} className={className}>\n {WAVE_ARCS.map((arc, index) => <path key={arc} className={`aic-w${index + 1}`} d={arc} />)}\n </Stroke>\n);\n\nexport const SendIcon = () => <Stroke size={18} width={2.4}><path d=\"M12 19V5M6 11l6-6 6 6\" /></Stroke>;\n\nexport const CloseIcon = () => <Stroke size={18}><path d=\"M6 6l12 12M18 6 6 18\" /></Stroke>;\n\nexport const NewChatIcon = () => (\n <Stroke size={18}>\n <path d=\"M12 4H7a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-5\" />\n <path d=\"M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z\" />\n </Stroke>\n);\n\nexport const SearchIcon = () => (\n <Stroke size={18}><circle cx=\"11\" cy=\"11\" r=\"6.5\" /><path d=\"m20 20-4.2-4.2\" /></Stroke>\n);\n\nexport const CheckIcon = () => <Stroke size={12} width={3}><path d=\"m5 12 5 5 9-10\" /></Stroke>;\n\n// Points along the reading direction; the stylesheet mirrors it in right to left.\nexport const ArrowIcon = () => <Stroke size={16} className=\"aic-arrow\"><path d=\"M5 12h14M13 6l6 6-6 6\" /></Stroke>;\n"]}
1
+ {"version":3,"file":"icons.js","sourceRoot":"","sources":["../../../src/modules/parts/icons.tsx"],"names":[],"mappings":";AAIA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AASjE,SAAS,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,GAAG,CAAC,EAAE,SAAS,EAAe;IACxE,OAAO,CACL,cAAK,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,EACzG,WAAW,EAAE,KAAK,EAAE,aAAa,EAAC,OAAO,EAAC,cAAc,EAAC,OAAO,iBAAa,MAAM,EAAC,SAAS,EAAC,OAAO,YACpG,QAAQ,GACL,CACP,CAAC;AACJ,CAAC;AAED,yFAAyF;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,EAAyC,EAAE,EAAE,CAAC,CAC3F,KAAC,MAAM,IAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,SAAS,YAC/D,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,eAAgB,SAAS,EAAE,QAAQ,KAAK,GAAG,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,IAA3C,GAAG,CAA4C,CAAC,GACnF,CACV,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,GAA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AAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,KAAK,EAAC,GAAG,EAAC,MAAM,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,GAAG,EACjD,eAAM,CAAC,EAAC,uCAAuC,GAAG,IAC3C,CACV,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,CAC5B,MAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,aAC1B,eAAM,CAAC,EAAC,4DAA4D,GAAG,EACvE,eAAM,CAAC,EAAC,yBAAyB,GAAG,IAC7B,CACV,CAAC;AAEF,uFAAuF;AACvF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,SAAS,EAAC,WAAW,YAAC,eAAM,CAAC,EAAC,eAAe,GAAG,GAAS,CAAC;AAE1G,MAAM,CAAC,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,SAAS,EAAC,WAAW,YAAC,eAAM,CAAC,EAAC,cAAc,GAAG,GAAS,CAAC","sourcesContent":["// The modules' drawn icons, in the AI Wallet's one stroke family (24 grid, round caps and joins).\n// The wave is the wallet's mark: the contactless arcs that light up while the visitor's AI answers.\n\nimport type { ReactNode } from 'react';\nimport { WAVE_ARCS, WAVE_STROKE_WIDTH } from '../../launcher.ts';\n\ninterface StrokeProps {\n children: ReactNode;\n size?: number;\n width?: number;\n className?: string;\n}\n\nfunction Stroke({ children, size = 18, width = 2, className }: StrokeProps) {\n return (\n <svg className={className} width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth={width} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {children}\n </svg>\n );\n}\n\n// The three arcs, each its own path so a live answer can light them one after the other.\nexport const WaveIcon = ({ size = 18, className }: { size?: number; className?: string }) => (\n <Stroke size={size} width={WAVE_STROKE_WIDTH} className={className}>\n {WAVE_ARCS.map((arc, index) => <path key={arc} className={`aic-w${index + 1}`} d={arc} />)}\n </Stroke>\n);\n\nexport const SendIcon = () => <Stroke size={18} width={2.4}><path d=\"M12 19V5M6 11l6-6 6 6\" /></Stroke>;\n\nexport const CloseIcon = () => <Stroke size={18}><path d=\"M6 6l12 12M18 6 6 18\" /></Stroke>;\n\nexport const NewChatIcon = () => (\n <Stroke size={18}>\n <path d=\"M12 4H7a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-5\" />\n <path d=\"M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z\" />\n </Stroke>\n);\n\nexport const SearchIcon = () => (\n <Stroke size={18}><circle cx=\"11\" cy=\"11\" r=\"6.5\" /><path d=\"m20 20-4.2-4.2\" /></Stroke>\n);\n\nexport const CheckIcon = () => <Stroke size={12} width={3}><path d=\"m5 12 5 5 9-10\" /></Stroke>;\n\n// Points along the reading direction; the stylesheet mirrors it in right to left.\nexport const ArrowIcon = () => <Stroke size={16} className=\"aic-arrow\"><path d=\"M5 12h14M13 6l6 6-6 6\" /></Stroke>;\n\nexport const PaperclipIcon = () => (\n <Stroke size={18}>\n <path d=\"m20 11.5-7.8 7.8a5 5 0 0 1-7-7l8.4-8.4a3.3 3.3 0 0 1 4.7 4.7l-8.4 8.4a1.7 1.7 0 0 1-2.4-2.4l7.7-7.7\" />\n </Stroke>\n);\n\nexport const MicIcon = () => (\n <Stroke size={18}>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\" />\n </Stroke>\n);\n\nexport const FileIcon = () => (\n <Stroke size={18} width={1.8}>\n <path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z\" />\n <path d=\"M14 3v5h5M9 13h6M9 17h4\" />\n </Stroke>\n);\n\n// Points back along the reading direction; the stylesheet mirrors it in right to left.\nexport const BackIcon = () => <Stroke size={18} className=\"aic-arrow\"><path d=\"m15 6-6 6 6 6\" /></Stroke>;\n\nexport const ForwardIcon = () => <Stroke size={18} className=\"aic-arrow\"><path d=\"m9 6 6 6-6 6\" /></Stroke>;\n"]}
@@ -1,4 +1,4 @@
1
- export type ModuleAction = 'install' | 'connect' | 'send' | 'suggestion';
1
+ export type ModuleAction = 'install' | 'connect' | 'send' | 'suggestion' | 'attach' | 'voice';
2
2
  export declare const ModuleAnalytics: import("react").Context<string | undefined>;
3
3
  export declare function useActionAttribute(action: ModuleAction): {
4
4
  'data-analytics'?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"moduleAnalytics.js","sourceRoot":"","sources":["../../../src/modules/parts/moduleAnalytics.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,0GAA0G;AAE1G,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAIlD,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAAqB,SAAS,CAAC,CAAC;AAE5E,MAAM,UAAU,kBAAkB,CAAC,MAAoB;IACrD,MAAM,IAAI,GAAG,UAAU,CAAC,eAAe,CAAC,CAAC;IACzC,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,GAAG,IAAI,IAAI,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["// The name a site gives a module's actions for its click analytics (`analytics` on the module): each\n// action button of the module carries `data-analytics` with that name and the action, such as `try-send`.\n\nimport { createContext, useContext } from 'react';\n\nexport type ModuleAction = 'install' | 'connect' | 'send' | 'suggestion';\n\nexport const ModuleAnalytics = createContext<string | undefined>(undefined);\n\nexport function useActionAttribute(action: ModuleAction): { 'data-analytics'?: string } {\n const name = useContext(ModuleAnalytics);\n return name ? { 'data-analytics': `${name}-${action}` } : {};\n}\n"]}
1
+ {"version":3,"file":"moduleAnalytics.js","sourceRoot":"","sources":["../../../src/modules/parts/moduleAnalytics.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,0GAA0G;AAE1G,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAIlD,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAAqB,SAAS,CAAC,CAAC;AAE5E,MAAM,UAAU,kBAAkB,CAAC,MAAoB;IACrD,MAAM,IAAI,GAAG,UAAU,CAAC,eAAe,CAAC,CAAC;IACzC,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,GAAG,IAAI,IAAI,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["// The name a site gives a module's actions for its click analytics (`analytics` on the module): each\n// action button of the module carries `data-analytics` with that name and the action, such as `try-send`.\n\nimport { createContext, useContext } from 'react';\n\nexport type ModuleAction = 'install' | 'connect' | 'send' | 'suggestion' | 'attach' | 'voice';\n\nexport const ModuleAnalytics = createContext<string | undefined>(undefined);\n\nexport function useActionAttribute(action: ModuleAction): { 'data-analytics'?: string } {\n const name = useContext(ModuleAnalytics);\n return name ? { 'data-analytics': `${name}-${action}` } : {};\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';
2
+ import type { AskedQuestion } from '../../useAiChat.ts';
2
3
  export interface ModuleChatOptions {
3
4
  system: string;
4
5
  tools?: ToolSource;
@@ -6,19 +7,21 @@ export interface ModuleChatOptions {
6
7
  guards?: GuardPolicy;
7
8
  }
8
9
  export declare function useModuleChat({ system, tools, mcp, guards }: ModuleChatOptions): {
9
- ask: (question: string) => void;
10
+ ask: (question: string, attachments?: AskedQuestion["attachments"]) => void;
10
11
  stop: () => void;
11
12
  reset: () => void;
12
13
  retry: () => void;
13
- pendingQuestion: string | null;
14
+ pendingQuestion: AskedQuestion | null;
14
15
  stopped: number[];
15
16
  turns: import("../../useAiChat.ts").ChatTurn[];
16
- send: (question: string) => Promise<void>;
17
+ send: (question: string | AskedQuestion) => Promise<void>;
17
18
  dropFailedTurn: () => void;
18
19
  busy: boolean;
19
20
  error: string | null;
20
21
  refusal: string | null;
21
22
  connected: boolean;
23
+ reads: import("@tensorpass/aiconnect").ReadableParts;
24
+ dictation: import("@tensorpass/aiconnect").Dictation | null;
22
25
  linkAllowed: (href: string) => boolean;
23
26
  };
24
27
  export type ModuleChat = ReturnType<typeof useModuleChat>;
@@ -1,25 +1,29 @@
1
1
  // The conversation a module runs: the chat on the visitor's AI with the site's tools, plus the
2
- // question a visitor asks before their AI is connected. That question opens the connect window and
3
- // stays on screen; it goes out on its own once the wallet connects the site or the visitor signs in on
4
- // the page, and stays with the connection step while a sign in waits. Signing out of a web account
5
- // starts the conversation again from the connection step.
2
+ // question a visitor asks before their AI is connected, with its attachments. That question opens the
3
+ // connect window and stays on screen; it goes out on its own once the wallet connects the site or the
4
+ // visitor signs in on the page, and stays with the connection step while a sign in waits. Signing out of a
5
+ // web account starts the conversation again from the connection step.
6
6
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
7
- import { McpToolSource } from '@tensorpass/aiconnect';
8
7
  import { useAiConnect } from "../../AiConnectProvider.js";
9
8
  import { useAiChat } from "../../useAiChat.js";
10
9
  // The states in which the connection is still settling on its own, without the visitor.
11
10
  const SETTLING = new Set(['checking', 'connecting']);
12
- // The site's MCP tools, connected on the first question. The module also renders on the server,
13
- // where a relative address has no page to resolve against.
11
+ // The site's MCP tools, loaded and connected on the first question: a page whose visitor asks
12
+ // nothing never downloads the MCP client and its schema library. The module also renders on the
13
+ // server, where a relative address has no page to resolve against. A failed load is forgotten, so the
14
+ // next question loads the client again.
14
15
  function mcpTools(url) {
15
16
  let source = null;
16
17
  const connected = () => {
17
- source ??= new McpToolSource(url);
18
+ source ??= import('@tensorpass/aiconnect/mcp').then(({ McpToolSource }) => new McpToolSource(url), (error) => {
19
+ source = null;
20
+ throw error;
21
+ });
18
22
  return source;
19
23
  };
20
24
  return {
21
- listTools: () => connected().listTools(),
22
- callTool: (name, args) => connected().callTool(name, args),
25
+ listTools: async () => (await connected()).listTools(),
26
+ callTool: async (name, args) => (await connected()).callTool(name, args),
23
27
  };
24
28
  }
25
29
  // The states in which asking a question asks the wallet to connect.
@@ -51,17 +55,17 @@ function usePendingQuestion(send) {
51
55
  void client.connect();
52
56
  }
53
57
  }), [client, keep, send]);
54
- const ask = useCallback((question) => {
55
- const text = question.trim();
56
- if (!text) {
58
+ const ask = useCallback((question, attachments = []) => {
59
+ const asked = { text: question.trim(), attachments };
60
+ if (!asked.text && attachments.length === 0) {
57
61
  return;
58
62
  }
59
63
  const { status } = client.state;
60
64
  if (status === 'connected') {
61
- void send(text);
65
+ void send(asked);
62
66
  return;
63
67
  }
64
- keep(text);
68
+ keep(asked);
65
69
  if (READY_TO_CONNECT.has(status)) {
66
70
  void client.connect();
67
71
  }
@@ -109,7 +113,7 @@ export function useModuleChat({ system, tools, mcp, guards }) {
109
113
  const last = turns.at(-1);
110
114
  if (last) {
111
115
  dropFailedTurn();
112
- ask(last.question);
116
+ ask(last.question, last.attachments);
113
117
  }
114
118
  }, [turns, ask, dropFailedTurn]);
115
119
  return { ...chat, ask, stop, reset, retry, pendingQuestion, stopped };
@@ -1 +1 @@
1
- {"version":3,"file":"useModuleChat.js","sourceRoot":"","sources":["../../../src/modules/parts/useModuleChat.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,mGAAmG;AACnG,uGAAuG;AACvG,mGAAmG;AACnG,0DAA0D;AAE1D,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA6B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM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AAG,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC;AACxE,CAAC","sourcesContent":["// The conversation a module runs: the chat on the visitor's AI with the site's tools, plus the\n// question a visitor asks before their AI is connected. That question opens the connect window and\n// stays on screen; it goes out on its own once the wallet connects the site or the visitor signs in on\n// the page, and stays with the connection step while a sign in waits. Signing out of a web account\n// starts the conversation again from the connection step.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { McpToolSource } from '@tensorpass/aiconnect';\nimport type { ConnectionState, GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport { useAiConnect } from '../../AiConnectProvider.tsx';\nimport { useAiChat } from '../../useAiChat.ts';\n\nexport interface ModuleChatOptions {\n system: string;\n tools?: ToolSource;\n mcp?: string;\n guards?: GuardPolicy;\n}\n\n// The states in which the connection is still settling on its own, without the visitor.\nconst SETTLING = new Set<ConnectionState['status']>(['checking', 'connecting']);\n\n// The site's MCP tools, connected on the first question. The module also renders on the server,\n// where a relative address has no page to resolve against.\nfunction mcpTools(url: string): ToolSource {\n let source: McpToolSource | null = null;\n const connected = () => {\n source ??= new McpToolSource(url);\n return source;\n };\n return {\n listTools: () => connected().listTools(),\n callTool: (name, args) => connected().callTool(name, args),\n };\n}\n\n// The states in which asking a question asks the wallet to connect.\nconst READY_TO_CONNECT = new Set<ConnectionState['status']>(['disconnected', 'error']);\n\n// Keeps the question asked before the connection and sends it once the site is connected. Asking is\n// the visitor's one action: it asks the wallet to connect at once, or as soon as the first wallet\n// check ends, and without the wallet the module's own install step shows with the question kept.\nfunction usePendingQuestion(send: (question: string) => Promise<void>) {\n const { client } = useAiConnect();\n const pending = useRef<string | null>(null);\n const connectAfterCheck = useRef(false);\n const [pendingQuestion, setPendingQuestion] = useState<string | null>(null);\n\n const keep = useCallback((question: string | null) => {\n pending.current = question;\n setPendingQuestion(question);\n }, []);\n\n useEffect(() => client.subscribe((next) => {\n const question = pending.current;\n if (question === null || SETTLING.has(next.status)) {\n return;\n }\n const afterCheck = connectAfterCheck.current;\n connectAfterCheck.current = false;\n if (next.status === 'connected') {\n keep(null);\n void send(question);\n } else if (afterCheck && next.status === 'disconnected') {\n void client.connect();\n }\n }), [client, keep, send]);\n\n const ask = useCallback((question: string) => {\n const text = question.trim();\n if (!text) {\n return;\n }\n const { status } = client.state;\n if (status === 'connected') {\n void send(text);\n return;\n }\n keep(text);\n if (READY_TO_CONNECT.has(status)) {\n void client.connect();\n } else if (status === 'checking') {\n connectAfterCheck.current = true;\n }\n }, [client, keep, send]);\n\n const forget = useCallback(() => keep(null), [keep]);\n return { pendingQuestion, ask, forget };\n}\n\n// Starts the conversation again when the web account that answered it signs out, by the visitor or because\n// its credential stopped opening the account: its answers and errors belong to that account.\nfunction useResetOnSignOut(reset: () => void) {\n const { client } = useAiConnect();\n const previous = useRef<ConnectionState>(client.state);\n useEffect(() => client.subscribe((next) => {\n const before = previous.current;\n previous.current = next;\n if (before.status === 'connected' && before.account && next.status !== 'connected') {\n reset();\n }\n }), [client, reset]);\n}\n\nexport function useModuleChat({ system, tools, mcp, guards }: ModuleChatOptions) {\n const toolSource = useMemo(() => tools ?? (mcp ? mcpTools(mcp) : undefined), [tools, mcp]);\n const chat = useAiChat({ system, tools: toolSource, guards });\n const { pendingQuestion, ask, forget } = usePendingQuestion(chat.send);\n // The turns the visitor stopped, by their place in the conversation.\n const [stopped, setStopped] = useState<number[]>([]);\n const { turns, stop: stopChat, reset: resetChat, busy, dropFailedTurn } = chat;\n\n const stop = useCallback(() => {\n if (busy) {\n setStopped((current) => [...current, turns.length - 1]);\n }\n stopChat();\n }, [busy, turns.length, stopChat]);\n\n const reset = useCallback(() => {\n resetChat();\n forget();\n setStopped([]);\n }, [resetChat, forget]);\n useResetOnSignOut(reset);\n\n // Asks the last question again in place of its failed turn.\n const retry = useCallback(() => {\n const last = turns.at(-1);\n if (last) {\n dropFailedTurn();\n ask(last.question);\n }\n }, [turns, ask, dropFailedTurn]);\n\n return { ...chat, ask, stop, reset, retry, pendingQuestion, stopped };\n}\n\nexport type ModuleChat = ReturnType<typeof useModuleChat>;\n"]}
1
+ {"version":3,"file":"useModuleChat.js","sourceRoot":"","sources":["../../../src/modules/parts/useModuleChat.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,sGAAsG;AACtG,sGAAsG;AACtG,2GAA2G;AAC3G,sEAAsE;AAEtE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE1E,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA6B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAU/C,wFAAwF;AACxF,MAAM,QAAQ,GAAG,IAAI,GAAG,CAA4B,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC;AAEhF,8FAA8F;AAC9F,gGAAgG;AAChG,sGAAsG;AACtG,wCAAwC;AACxC,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAI,MAAM,GAA+B,IAAI,CAAC;IAC9C,MAAM,SAAS,GAAG,GAAG,EAAE;QACrB,MAAM,KAAK,MAAM,CAAC,2BAA2B,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,aAAa,EAAE,EAAE,EAAE,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;YAC3G,MAAM,GAAG,IAAI,CAAC;YACd,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,OAAO;QACL,SAAS,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,SAAS,EAAE,CAAC,CAAC,SAAS,EAAE;QACtD,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,SAAS,EAAE,CAAC,CAAC,QAAQ,CA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AC;YACT,UAAU,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;QAC1D,CAAC;QACD,QAAQ,EAAE,CAAC;IACb,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IAEnC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,CAAC;QACZ,MAAM,EAAE,CAAC;QACT,UAAU,CAAC,EAAE,CAAC,CAAC;IACjB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IACxB,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAEzB,4DAA4D;IAC5D,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,MAAM,IAAI,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,IAAI,EAAE,CAAC;YACT,cAAc,EAAE,CAAC;YACjB,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC;IAEjC,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC;AACxE,CAAC","sourcesContent":["// The conversation a module runs: the chat on the visitor's AI with the site's tools, plus the\n// question a visitor asks before their AI is connected, with its attachments. That question opens the\n// connect window and stays on screen; it goes out on its own once the wallet connects the site or the\n// visitor signs in on the page, and stays with the connection step while a sign in waits. Signing out of a\n// web account starts the conversation again from the connection step.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ConnectionState, GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport { useAiConnect } from '../../AiConnectProvider.tsx';\nimport { useAiChat } from '../../useAiChat.ts';\nimport type { AskedQuestion } from '../../useAiChat.ts';\n\nexport interface ModuleChatOptions {\n system: string;\n tools?: ToolSource;\n mcp?: string;\n guards?: GuardPolicy;\n}\n\n// The states in which the connection is still settling on its own, without the visitor.\nconst SETTLING = new Set<ConnectionState['status']>(['checking', 'connecting']);\n\n// The site's MCP tools, loaded and connected on the first question: a page whose visitor asks\n// nothing never downloads the MCP client and its schema library. The module also renders on the\n// server, where a relative address has no page to resolve against. A failed load is forgotten, so the\n// next question loads the client again.\nfunction mcpTools(url: string): ToolSource {\n let source: Promise<ToolSource> | null = null;\n const connected = () => {\n source ??= import('@tensorpass/aiconnect/mcp').then(({ McpToolSource }) => new McpToolSource(url), (error) => {\n source = null;\n throw error;\n });\n return source;\n };\n return {\n listTools: async () => (await connected()).listTools(),\n callTool: async (name, args) => (await connected()).callTool(name, args),\n };\n}\n\n// The states in which asking a question asks the wallet to connect.\nconst READY_TO_CONNECT = new Set<ConnectionState['status']>(['disconnected', 'error']);\n\n// Keeps the question asked before the connection and sends it once the site is connected. Asking is\n// the visitor's one action: it asks the wallet to connect at once, or as soon as the first wallet\n// check ends, and without the wallet the module's own install step shows with the question kept.\nfunction usePendingQuestion(send: (question: AskedQuestion) => Promise<void>) {\n const { client } = useAiConnect();\n const pending = useRef<AskedQuestion | null>(null);\n const connectAfterCheck = useRef(false);\n const [pendingQuestion, setPendingQuestion] = useState<AskedQuestion | null>(null);\n\n const keep = useCallback((question: AskedQuestion | null) => {\n pending.current = question;\n setPendingQuestion(question);\n }, []);\n\n useEffect(() => client.subscribe((next) => {\n const question = pending.current;\n if (question === null || SETTLING.has(next.status)) {\n return;\n }\n const afterCheck = connectAfterCheck.current;\n connectAfterCheck.current = false;\n if (next.status === 'connected') {\n keep(null);\n void send(question);\n } else if (afterCheck && next.status === 'disconnected') {\n void client.connect();\n }\n }), [client, keep, send]);\n\n const ask = useCallback((question: string, attachments: AskedQuestion['attachments'] = []) => {\n const asked = { text: question.trim(), attachments };\n if (!asked.text && attachments.length === 0) {\n return;\n }\n const { status } = client.state;\n if (status === 'connected') {\n void send(asked);\n return;\n }\n keep(asked);\n if (READY_TO_CONNECT.has(status)) {\n void client.connect();\n } else if (status === 'checking') {\n connectAfterCheck.current = true;\n }\n }, [client, keep, send]);\n\n const forget = useCallback(() => keep(null), [keep]);\n return { pendingQuestion, ask, forget };\n}\n\n// Starts the conversation again when the web account that answered it signs out, by the visitor or because\n// its credential stopped opening the account: its answers and errors belong to that account.\nfunction useResetOnSignOut(reset: () => void) {\n const { client } = useAiConnect();\n const previous = useRef<ConnectionState>(client.state);\n useEffect(() => client.subscribe((next) => {\n const before = previous.current;\n previous.current = next;\n if (before.status === 'connected' && before.account && next.status !== 'connected') {\n reset();\n }\n }), [client, reset]);\n}\n\nexport function useModuleChat({ system, tools, mcp, guards }: ModuleChatOptions) {\n const toolSource = useMemo(() => tools ?? (mcp ? mcpTools(mcp) : undefined), [tools, mcp]);\n const chat = useAiChat({ system, tools: toolSource, guards });\n const { pendingQuestion, ask, forget } = usePendingQuestion(chat.send);\n // The turns the visitor stopped, by their place in the conversation.\n const [stopped, setStopped] = useState<number[]>([]);\n const { turns, stop: stopChat, reset: resetChat, busy, dropFailedTurn } = chat;\n\n const stop = useCallback(() => {\n if (busy) {\n setStopped((current) => [...current, turns.length - 1]);\n }\n stopChat();\n }, [busy, turns.length, stopChat]);\n\n const reset = useCallback(() => {\n resetChat();\n forget();\n setStopped([]);\n }, [resetChat, forget]);\n useResetOnSignOut(reset);\n\n // Asks the last question again in place of its failed turn.\n const retry = useCallback(() => {\n const last = turns.at(-1);\n if (last) {\n dropFailedTurn();\n ask(last.question, last.attachments);\n }\n }, [turns, ask, dropFailedTurn]);\n\n return { ...chat, ask, stop, reset, retry, pendingQuestion, stopped };\n}\n\nexport type ModuleChat = ReturnType<typeof useModuleChat>;\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { ReactNode, Ref } from 'react';
2
2
  import type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';
3
+ import type { AttachmentPolicy } from '@tensorpass/aiconnect/attachments';
3
4
  import type { ChatTurn } from '../useAiChat.ts';
4
5
  export interface AiModuleHandle {
5
6
  ask: (question: string) => void;
@@ -14,6 +15,7 @@ export interface AiModuleProps {
14
15
  suggestions?: string[];
15
16
  toolLabels?: Record<string, string>;
16
17
  guards?: GuardPolicy;
18
+ attachments?: AttachmentPolicy;
17
19
  renderToolResults?: (turn: ChatTurn) => ReactNode;
18
20
  analytics?: string;
19
21
  ref?: Ref<AiModuleHandle>;
@@ -1,5 +1,6 @@
1
1
  // The props every interface module shares: what the visitor's AI is told, the site's tools, the copy
2
- // the site sets for its own voice, the guards it tunes, how the site draws its tool results, and the
3
- // handle its own controls ask through. The modules that float over the page add how they open.
2
+ // the site sets for its own voice, the guards it tunes, the files and voice it takes, how the site draws
3
+ // its tool results, and the handle its own controls ask through. The modules that float over the page add
4
+ // how they open.
4
5
  export {};
5
6
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/modules/types.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,qGAAqG;AACrG,+FAA+F","sourcesContent":["// The props every interface module shares: what the visitor's AI is told, the site's tools, the copy\n// the site sets for its own voice, the guards it tunes, how the site draws its tool results, and the\n// handle its own controls ask through. The modules that float over the page add how they open.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport type { ChatTurn } from '../useAiChat.ts';\n\n// What a site's own controls can do with a module through its `ref`.\nexport interface AiModuleHandle {\n // Sends the question as if the visitor had typed it in the module. A module that floats opens first.\n ask: (question: string) => void;\n}\n\nexport interface AiModuleProps {\n // What the visitor's AI is told about the site and its tools before the first question.\n system: string;\n // The site's tools. Give `mcp` instead to read them from the site's MCP server.\n tools?: ToolSource;\n // The address of the site's MCP server, such as `/api/mcp`. The module connects to it when the\n // first question is sent.\n mcp?: string;\n // The heading of the module. The built in copy says \"Ask AI\" (or \"AI mode\" for the full page).\n title?: string;\n // The heading of an empty conversation.\n intro?: string;\n placeholder?: string;\n // Questions the visitor can send with one click before asking their own.\n suggestions?: string[];\n // A plain name for each tool, shown while it runs in place of the tool's own name.\n toolLabels?: Record<string, string>;\n // The site's own values for the guards the conversation runs under: its internal names, the hosts\n // and addresses its answers may give, the tools it shows, its safe answer. The guards run with their\n // defaults without it.\n guards?: GuardPolicy;\n // Draws a turn's tool results the site's way, such as its own result cards, under the answer.\n // The turn holds the answer and every tool call with its raw result.\n renderToolResults?: (turn: ChatTurn) => ReactNode;\n // A name for the module's actions in the site's click analytics: the install and connect buttons, the\n // send button and the suggestions carry `data-analytics` with it, such as `chat-install` or `chat-send`.\n analytics?: string;\n // Receives the module's handle, for a field or a button of the site's own that sends the module a\n // question, such as an ask bar in the page's opening that opens the side panel.\n ref?: Ref<AiModuleHandle>;\n className?: string;\n}\n\nexport interface AiOverlayProps {\n // Whether the module is open, when the site controls it. Leave it out to let the module keep it.\n open?: boolean;\n // Whether the module starts open, when the module keeps the state itself.\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n // Hides the module's own button, for a site that opens the module from a button of its own.\n hideLauncher?: boolean;\n // The text of the module's own button.\n launcherLabel?: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/modules/types.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,yGAAyG;AACzG,0GAA0G;AAC1G,iBAAiB","sourcesContent":["// The props every interface module shares: what the visitor's AI is told, the site's tools, the copy\n// the site sets for its own voice, the guards it tunes, the files and voice it takes, how the site draws\n// its tool results, and the handle its own controls ask through. The modules that float over the page add\n// how they open.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport type { AttachmentPolicy } from '@tensorpass/aiconnect/attachments';\nimport type { ChatTurn } from '../useAiChat.ts';\n\n// What a site's own controls can do with a module through its `ref`.\nexport interface AiModuleHandle {\n // Sends the question as if the visitor had typed it in the module. A module that floats opens first.\n ask: (question: string) => void;\n}\n\nexport interface AiModuleProps {\n // What the visitor's AI is told about the site and its tools before the first question.\n system: string;\n // The site's tools. Give `mcp` instead to read them from the site's MCP server.\n tools?: ToolSource;\n // The address of the site's MCP server, such as `/api/mcp`. The module connects to it when the\n // first question is sent.\n mcp?: string;\n // The heading of the module. The built in copy says \"Ask AI\" (or \"AI mode\" for the full page).\n title?: string;\n // The heading of an empty conversation.\n intro?: string;\n placeholder?: string;\n // Questions the visitor can send with one click before asking their own.\n suggestions?: string[];\n // A plain name for each tool, shown while it runs in place of the tool's own name.\n toolLabels?: Record<string, string>;\n // The site's own values for the guards the conversation runs under: its internal names, the hosts\n // and addresses its answers may give, the tools it shows, its safe answer. The guards run with their\n // defaults without it.\n guards?: GuardPolicy;\n // The files and the voice the visitor may add to a question: images, PDFs and text files dropped, pasted\n // or attached, and dictation into the question field. Leave it out to keep the question box text only;\n // `{}` turns on every kind with the default caps.\n attachments?: AttachmentPolicy;\n // Draws a turn's tool results the site's way, such as its own result cards, under the answer.\n // The turn holds the answer and every tool call with its raw result.\n renderToolResults?: (turn: ChatTurn) => ReactNode;\n // A name for the module's actions in the site's click analytics: the install and connect buttons, the\n // send button and the suggestions carry `data-analytics` with it, such as `chat-install` or `chat-send`.\n analytics?: string;\n // Receives the module's handle, for a field or a button of the site's own that sends the module a\n // question, such as an ask bar in the page's opening that opens the side panel.\n ref?: Ref<AiModuleHandle>;\n className?: string;\n}\n\nexport interface AiOverlayProps {\n // Whether the module is open, when the site controls it. Leave it out to let the module keep it.\n open?: boolean;\n // Whether the module starts open, when the module keeps the state itself.\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n // Hides the module's own button, for a site that opens the module from a button of its own.\n hideLauncher?: boolean;\n // The text of the module's own button.\n launcherLabel?: string;\n}\n"]}
@@ -7,7 +7,8 @@ import { useCallback, useEffect, useId, useRef, useState } from 'react';
7
7
  import { useAiConnect } from "../AiConnectProvider.js";
8
8
  import { COVERS_SCREEN, pointsByTouch, useMediaQuery } from "./mediaQuery.js";
9
9
  import { useCoveringLayer } from "./pageLock.js";
10
- const FOCUSABLE = 'a[href], button:not([disabled]), textarea, input, [tabindex]:not([tabindex="-1"])';
10
+ const FOCUSABLE = 'a[href], button:not([disabled]):not([tabindex="-1"]), textarea, input:not([tabindex="-1"]), '
11
+ + '[tabindex]:not([tabindex="-1"])';
11
12
  function useOpenState({ open, defaultOpen = false, onOpenChange }) {
12
13
  const [own, setOwn] = useState(defaultOpen);
13
14
  const setOpen = useCallback((next) => {
@@ -1 +1 @@
1
- {"version":3,"file":"useOverlay.js","sourceRoot":"","sources":["../../src/modules/useOverlay.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,oGAAoG;AACpG,sGAAsG;AACtG,mGAAmG;AACnG,QAAQ;AAER,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAExE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAOjD,MAAM,SAAS,GAAG,mFAAmF,CAAC;AAQtG,SAAS,YAAY,CAAC,EAAE,IAAI,EAAE,WAAW,GAAG,KAAK,EAAE,YAAY,EAAkB;IAC/E,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,WAAW,CAAC,CAAC,IAAa,EAAE,EAAE;QAC5C,MAAM,CAAC,IAAI,CAAC,CAAC;QACb,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC,EAAE,CAAC,YAAY,CAAC,C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a,CAAC,aAAa,CAAC,CAAC;IAC3C,gBAAgB,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC;IAClE,cAAc,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1D,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC1F,CAAC","sourcesContent":["// How a module that floats over the page opens and closes: the open state, kept by the site or by\n// the module; Escape to close, which the connect window takes first while it is open; the page held\n// behind the module while it covers the screen (pageLock.ts); focus moved into the module on open and\n// back to the module's button on close. The full page mode also keeps the focus inside while it is\n// open.\n\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport type { RefObject } from 'react';\nimport { useAiConnect } from '../AiConnectProvider.tsx';\nimport { COVERS_SCREEN, pointsByTouch, useMediaQuery } from './mediaQuery.ts';\nimport { useCoveringLayer } from './pageLock.ts';\nimport type { AiOverlayProps } from './types.ts';\n\n// When a module covers the screen: the full page mode always, the panel and the popup on a phone, where\n// forms.css gives them the whole screen. On a wider screen the page beside them stays usable.\nexport type OverlayCover = 'always' | 'phone';\n\nconst FOCUSABLE = 'a[href], button:not([disabled]), textarea, input, [tabindex]:not([tabindex=\"-1\"])';\n\nexport interface OverlayRefs {\n layerRef: RefObject<HTMLElement | null>;\n fieldRef: RefObject<HTMLTextAreaElement | null>;\n launcherRef: RefObject<HTMLButtonElement | null>;\n}\n\nfunction useOpenState({ open, defaultOpen = false, onOpenChange }: AiOverlayProps) {\n const [own, setOwn] = useState(defaultOpen);\n const setOpen = useCallback((next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n }, [onOpenChange]);\n return [open ?? own, setOpen] as const;\n}\n\nfunction useEscape(open: boolean, close: () => void) {\n const { isPickerOpen } = useAiConnect();\n useEffect(() => {\n if (!open || isPickerOpen) {\n return undefined;\n }\n const onKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n close();\n }\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, isPickerOpen, close]);\n}\n\n// On open the focus moves to the question box, or to the module itself on a touch screen, where the\n// box would open the keyboard before the visitor asks for it. On close it goes back to the module's\n// button, or, for a module the site opened from its own control, to the element that held it before.\nfunction useFocusOnOpen(open: boolean, { layerRef, fieldRef, launcherRef }: OverlayRefs) {\n const wasOpen = useRef(open);\n const opener = useRef<HTMLElement | null>(null);\n useEffect(() => {\n if (open === wasOpen.current) {\n return;\n }\n wasOpen.current = open;\n if (open) {\n opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n (pointsByTouch() ? layerRef.current : fieldRef.current ?? layerRef.current)?.focus();\n } else {\n (launcherRef.current ?? opener.current)?.focus();\n }\n }, [open, layerRef, fieldRef, launcherRef]);\n}\n\n// The element with focus, read from the layer's own root so it works inside a shadow root too.\nfunction activeElement(layer: HTMLElement): Element | null {\n return (layer.getRootNode() as Document | ShadowRoot).activeElement;\n}\n\nexport function useFocusTrap(layerRef: RefObject<HTMLElement | null>, enabled: boolean) {\n useEffect(() => {\n const layer = layerRef.current;\n if (!enabled || !layer) {\n return undefined;\n }\n const onKey = (event: KeyboardEvent) => {\n const focusable = [...layer.querySelectorAll<HTMLElement>(FOCUSABLE)];\n if (event.key !== 'Tab' || focusable.length === 0) {\n return;\n }\n const edge = event.shiftKey ? focusable[0] : focusable[focusable.length - 1];\n if (activeElement(layer) === edge) {\n event.preventDefault();\n (event.shiftKey ? focusable[focusable.length - 1] : focusable[0]).focus();\n }\n };\n layer.addEventListener('keydown', onKey);\n return () => layer.removeEventListener('keydown', onKey);\n }, [layerRef, enabled]);\n}\n\nexport function useOverlay(props: AiOverlayProps, cover: OverlayCover) {\n const [open, setOpen] = useOpenState(props);\n const layerRef = useRef<HTMLElement>(null);\n const fieldRef = useRef<HTMLTextAreaElement>(null);\n const launcherRef = useRef<HTMLButtonElement>(null);\n const titleId = useId();\n const layerId = useId();\n const show = useCallback(() => setOpen(true), [setOpen]);\n const close = useCallback(() => setOpen(false), [setOpen]);\n const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n useEscape(open, close);\n // The page is held before the focus moves, so the position the lock gives back is the visitor's.\n const phone = useMediaQuery(COVERS_SCREEN);\n useCoveringLayer(layerRef, open && (cover === 'always' || phone));\n useFocusOnOpen(open, { layerRef, fieldRef, launcherRef });\n return { open, show, close, toggle, layerRef, fieldRef, launcherRef, titleId, layerId };\n}\n"]}
1
+ {"version":3,"file":"useOverlay.js","sourceRoot":"","sources":["../../src/modules/useOverlay.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,oGAAoG;AACpG,sGAAsG;AACtG,mGAAmG;AACnG,QAAQ;AAER,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAExE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAOjD,MAAM,SAAS,GAAG,8FAA8F;MAC5G,iCAAiC,CAAC;AAQtC,SAAS,YAAY,CAAC,EAAE,IAAI,EAAE,WAAW,GAAG,KAAK,EAAE,YAAY,EAAkB;IAC/E,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,WAAW,CAAC,CAAC,IAAa,EAAE,EAAE;QAC5C,MAAM,CAAC,IAAI,CAAC,CAAC;QACb,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;IACnB,OAAO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AAC;IAC3C,gBAAgB,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC;IAClE,cAAc,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1D,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC1F,CAAC","sourcesContent":["// How a module that floats over the page opens and closes: the open state, kept by the site or by\n// the module; Escape to close, which the connect window takes first while it is open; the page held\n// behind the module while it covers the screen (pageLock.ts); focus moved into the module on open and\n// back to the module's button on close. The full page mode also keeps the focus inside while it is\n// open.\n\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport type { RefObject } from 'react';\nimport { useAiConnect } from '../AiConnectProvider.tsx';\nimport { COVERS_SCREEN, pointsByTouch, useMediaQuery } from './mediaQuery.ts';\nimport { useCoveringLayer } from './pageLock.ts';\nimport type { AiOverlayProps } from './types.ts';\n\n// When a module covers the screen: the full page mode always, the panel and the popup on a phone, where\n// forms.css gives them the whole screen. On a wider screen the page beside them stays usable.\nexport type OverlayCover = 'always' | 'phone';\n\nconst FOCUSABLE = 'a[href], button:not([disabled]):not([tabindex=\"-1\"]), textarea, input:not([tabindex=\"-1\"]), '\n + '[tabindex]:not([tabindex=\"-1\"])';\n\nexport interface OverlayRefs {\n layerRef: RefObject<HTMLElement | null>;\n fieldRef: RefObject<HTMLTextAreaElement | null>;\n launcherRef: RefObject<HTMLButtonElement | null>;\n}\n\nfunction useOpenState({ open, defaultOpen = false, onOpenChange }: AiOverlayProps) {\n const [own, setOwn] = useState(defaultOpen);\n const setOpen = useCallback((next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n }, [onOpenChange]);\n return [open ?? own, setOpen] as const;\n}\n\nfunction useEscape(open: boolean, close: () => void) {\n const { isPickerOpen } = useAiConnect();\n useEffect(() => {\n if (!open || isPickerOpen) {\n return undefined;\n }\n const onKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n close();\n }\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, isPickerOpen, close]);\n}\n\n// On open the focus moves to the question box, or to the module itself on a touch screen, where the\n// box would open the keyboard before the visitor asks for it. On close it goes back to the module's\n// button, or, for a module the site opened from its own control, to the element that held it before.\nfunction useFocusOnOpen(open: boolean, { layerRef, fieldRef, launcherRef }: OverlayRefs) {\n const wasOpen = useRef(open);\n const opener = useRef<HTMLElement | null>(null);\n useEffect(() => {\n if (open === wasOpen.current) {\n return;\n }\n wasOpen.current = open;\n if (open) {\n opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n (pointsByTouch() ? layerRef.current : fieldRef.current ?? layerRef.current)?.focus();\n } else {\n (launcherRef.current ?? opener.current)?.focus();\n }\n }, [open, layerRef, fieldRef, launcherRef]);\n}\n\n// The element with focus, read from the layer's own root so it works inside a shadow root too.\nfunction activeElement(layer: HTMLElement): Element | null {\n return (layer.getRootNode() as Document | ShadowRoot).activeElement;\n}\n\nexport function useFocusTrap(layerRef: RefObject<HTMLElement | null>, enabled: boolean) {\n useEffect(() => {\n const layer = layerRef.current;\n if (!enabled || !layer) {\n return undefined;\n }\n const onKey = (event: KeyboardEvent) => {\n const focusable = [...layer.querySelectorAll<HTMLElement>(FOCUSABLE)];\n if (event.key !== 'Tab' || focusable.length === 0) {\n return;\n }\n const edge = event.shiftKey ? focusable[0] : focusable[focusable.length - 1];\n if (activeElement(layer) === edge) {\n event.preventDefault();\n (event.shiftKey ? focusable[focusable.length - 1] : focusable[0]).focus();\n }\n };\n layer.addEventListener('keydown', onKey);\n return () => layer.removeEventListener('keydown', onKey);\n }, [layerRef, enabled]);\n}\n\nexport function useOverlay(props: AiOverlayProps, cover: OverlayCover) {\n const [open, setOpen] = useOpenState(props);\n const layerRef = useRef<HTMLElement>(null);\n const fieldRef = useRef<HTMLTextAreaElement>(null);\n const launcherRef = useRef<HTMLButtonElement>(null);\n const titleId = useId();\n const layerId = useId();\n const show = useCallback(() => setOpen(true), [setOpen]);\n const close = useCallback(() => setOpen(false), [setOpen]);\n const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n useEscape(open, close);\n // The page is held before the focus moves, so the position the lock gives back is the visitor's.\n const phone = useMediaQuery(COVERS_SCREEN);\n useCoveringLayer(layerRef, open && (cover === 'always' || phone));\n useFocusOnOpen(open, { layerRef, fieldRef, launcherRef });\n return { open, show, close, toggle, layerRef, fieldRef, launcherRef, titleId, layerId };\n}\n"]}