@theoremjs/react 0.3.5-next.1020.g3a48861 → 0.3.5-next.1025.g5523d8f
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 +45 -1
- package/hooks/use-theorem-chat.d.ts +1 -0
- package/hooks/use-theorem-chat.js +1 -0
- package/package.json +3 -3
- package/ui/ChatComposerBar.d.ts +18 -3
- package/ui/ChatComposerBar.js +48 -28
- package/ui/ChatTranscript.d.ts +3 -0
- package/ui/ChatTranscript.js +16 -3
- package/ui/TheoremChat.d.ts +20 -2
- package/ui/TheoremChat.js +9 -8
- package/ui/composer-refs.d.ts +39 -0
- package/ui/composer-refs.js +401 -0
- package/ui/index.d.ts +2 -1
- package/ui/index.js +1 -0
package/README.md
CHANGED
|
@@ -225,6 +225,50 @@ Each part of the look is a CSS custom property. Set it on any element above the
|
|
|
225
225
|
|
|
226
226
|
The words are labels: `@theorem.composer.pill.working_for`, `@theorem.composer.pill.working` (before the start is known), `@theorem.composer.pill.stop`, `@theorem.composer.pill.background`, `@theorem.composer.tray.expand` and `@theorem.composer.tray.collapse`. See [Wording](#wording). For a rule that no property covers, each part has a class: `theorem-composer-row`, `theorem-composer-pills`, `theorem-composer-pill` (with `data-pill="working"`, `"background"` or `"app"`), `theorem-composer-tray` (with `data-open`) and `theorem-composer-surface`.
|
|
227
227
|
|
|
228
|
+
### Refs and your own input
|
|
229
|
+
|
|
230
|
+
Use refs when the person picks one of your app's objects in the composer, and your server must receive which one. A ref is `{ kind, id }`, your own strings. It shows as a chip, and the message carries it typed. See [Name your app's objects in a message](https://github.com/theoremjs/theoremai/blob/main/web/README.md#name-your-apps-objects-in-a-message).
|
|
231
|
+
|
|
232
|
+
```tsx
|
|
233
|
+
import { refToken, TheoremChat } from '@theoremjs/react/ui';
|
|
234
|
+
|
|
235
|
+
<TheoremChat
|
|
236
|
+
endpoint="/api/theorem"
|
|
237
|
+
composerTriggers={[
|
|
238
|
+
{
|
|
239
|
+
character: '@',
|
|
240
|
+
searchSource: documents,
|
|
241
|
+
onSelect: (item) => refToken({ kind: 'document', id: item.id }),
|
|
242
|
+
},
|
|
243
|
+
]}
|
|
244
|
+
renderRef={(ref) => <DocumentName id={ref.id} />}
|
|
245
|
+
/>;
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
| Prop | What it does |
|
|
249
|
+
| --- | --- |
|
|
250
|
+
| `composerTriggers` | The field's triggers, as Astryx's `ChatComposerInput` takes `triggers`. Both layouts pass them on. |
|
|
251
|
+
| `composerInput` | Your own text field. It takes what `ChatComposerInput` takes, and every composer draws it, a call's included. Default: `ChatComposerInput`. |
|
|
252
|
+
| `renderRef` | Draws a ref, as a chip in the composer and in the person's message. Without it, the chip is a badge and the message shows as text. |
|
|
253
|
+
| `refText` | Writes a ref into the message's text. Default: the id. Give the server the same one. |
|
|
254
|
+
|
|
255
|
+
To put a ref in the field from your own button, hold an `inputRef` and call `inputRef.current.insertToken(refToken({ kind, id }))`. Only a chip that `refToken` made is a ref. Typed text is never read as one. A click on a chip can leave the caret inside it. Typing, pasting, and `insertToken` and `insertText` on your `inputRef` then land just after that chip, never inside it.
|
|
256
|
+
|
|
257
|
+
The draft keeps its refs, so a composer drawn again from a saved draft shows its chips again. This holds for a stashed or queued message that you restore.
|
|
258
|
+
|
|
259
|
+
Chips also stay in these two cases:
|
|
260
|
+
|
|
261
|
+
- The up arrow brings back a sent message with its chips. The down arrow brings back your draft with its chips.
|
|
262
|
+
- Text that you copy or cut in a composer, and paste in a composer on the same page, keeps its chips. A paste from anywhere else is plain text.
|
|
263
|
+
|
|
264
|
+
Your own input must keep the markup of Astryx's tokens (`data-astryx-token`) and its handle.
|
|
265
|
+
|
|
266
|
+
Limits:
|
|
267
|
+
|
|
268
|
+
- A call sends a typed line as text. Its refs reach the model as that text.
|
|
269
|
+
- The up arrow brings back the messages that the field itself keeps: those you send with Enter. It matches them by their words: if two have the same words, both come back with the later one's refs.
|
|
270
|
+
- A paste in another tab or another app is plain text.
|
|
271
|
+
|
|
228
272
|
### Tool media
|
|
229
273
|
|
|
230
274
|
A tool can return media for the model, for the person, or for both. The chat shows media from a tool only when the tool marked it `sent`, unless you pass `media="all"`. Media that a model generated and files that the user attached always show.
|
|
@@ -594,7 +638,7 @@ function Dock({ chat, iface }) {
|
|
|
594
638
|
}
|
|
595
639
|
```
|
|
596
640
|
|
|
597
|
-
`TheoremChatComposer` takes `layout`, `icons`, `pills`, `placeholder`, and `
|
|
641
|
+
`TheoremChatComposer` takes `layout`, `icons`, `pills`, `placeholder`, `inputRef`, `inputComponent`, `triggers`, `refText`, and `renderRef`. Pass it the `refText` you gave `useTheoremChat`. `TheoremChatTranscript` takes the props of `ChatTranscript` that the chat does not give: `handle`, `emptyState`, `dividers`, `usage`, `bodyKindPlacement`, `stepLayout`, `showToolDurations`, `showWorkStatus`, and `renderRef`. Its `handle` is the handle of the profile when you leave it out. Put both pieces inside one `TheoremSurface`. It takes what `TheoremChat` takes for the look and the media: `theme`, `mode`, `labels`, `detectCodeLanguage`, `media`, `resolveMedia`, and `mediaViewer`.
|
|
598
642
|
|
|
599
643
|
Use `pills` to show your own notice in the pill row of the `row` layout, for example "New from your agent" while the chat is closed. Each pill is `{ id, label, icon?, onSelect? }`. It comes after the working pill and the background calls, and looks like them. The icon goes before the words. A click calls `onSelect`. A pill without `onSelect` only shows.
|
|
600
644
|
|
|
@@ -32,6 +32,7 @@ export type TheoremChatState = ChatState & {
|
|
|
32
32
|
/** The tool calls still running in the background, oldest first, until their results land. */
|
|
33
33
|
backgroundJobs: BackgroundJob[];
|
|
34
34
|
setDraftText: ChatController['setDraftText'];
|
|
35
|
+
setDraftParts: ChatController['setDraftParts'];
|
|
35
36
|
setPendingFiles: ChatController['setPendingFiles'];
|
|
36
37
|
setPendingVoice: ChatController['setPendingVoice'];
|
|
37
38
|
setPendingMessages: ChatController['setPendingMessages'];
|
|
@@ -30,6 +30,7 @@ export function useTheoremChat(options) {
|
|
|
30
30
|
workingSince: state.runningElsewhere?.since ?? liveTurnStart(groups, turnClock, state.streaming),
|
|
31
31
|
backgroundJobs: jobs,
|
|
32
32
|
setDraftText: chat.setDraftText,
|
|
33
|
+
setDraftParts: chat.setDraftParts,
|
|
33
34
|
setPendingFiles: chat.setPendingFiles,
|
|
34
35
|
setPendingVoice: chat.setPendingVoice,
|
|
35
36
|
setPendingMessages: chat.setPendingMessages,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/react",
|
|
3
|
-
"version": "0.3.5-next.
|
|
3
|
+
"version": "0.3.5-next.1025.g5523d8f",
|
|
4
4
|
"description": "React bindings for Theorem: headless hooks + transport, an Astryx chat UI, and a Web-standard server handler.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -60,8 +60,8 @@
|
|
|
60
60
|
"@stylexjs/stylex": "0.19.0",
|
|
61
61
|
"react": "^19.0.0",
|
|
62
62
|
"react-dom": "^19.0.0",
|
|
63
|
-
"@theoremjs/agents": "^0.3.5-next.
|
|
64
|
-
"@theoremjs/web": "^0.3.5-next.
|
|
63
|
+
"@theoremjs/agents": "^0.3.5-next.1025.g5523d8f",
|
|
64
|
+
"@theoremjs/web": "^0.3.5-next.1025.g5523d8f"
|
|
65
65
|
},
|
|
66
66
|
"peerDependenciesMeta": {
|
|
67
67
|
"@astryxdesign/core": {
|
package/ui/ChatComposerBar.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { type ChatComposerInputHandle } from '@astryxdesign/core/Chat';
|
|
1
|
+
import { ChatComposerInput, type ChatComposerInputHandle, type ChatComposerTrigger } from '@astryxdesign/core/Chat';
|
|
2
|
+
import type { RefText, UserPart, UserRef } from '@theoremjs/agents/interface';
|
|
2
3
|
import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerPendingMessage, type ComposerProfileInterface, type ComposerRunPhase, type LiveProfileInterface } from '@theoremjs/agents/interface';
|
|
3
4
|
import type { ClientFailure } from '@theoremjs/web/client';
|
|
4
|
-
import { type ReactNode } from 'react';
|
|
5
|
+
import { type ComponentProps, type ComponentType, type ReactNode } from 'react';
|
|
5
6
|
import type { BackgroundJob } from '../client/transcript-groups.js';
|
|
6
7
|
import { type ComposerPill, type ComposerRowIcons } from './ChatComposerRow.js';
|
|
7
8
|
/** An option the profile declares: its allowed values, the one chosen, and how to choose another. */
|
|
@@ -27,6 +28,8 @@ export type OptionChoices = {
|
|
|
27
28
|
* pill, and the background jobs; while a reply runs the one button opens the send menu.
|
|
28
29
|
*/
|
|
29
30
|
export type ComposerLayout = 'stacked' | 'row';
|
|
31
|
+
/** A text field that takes what Astryx's `ChatComposerInput` takes. */
|
|
32
|
+
export type ComposerInputComponent = ComponentType<ComponentProps<typeof ChatComposerInput>>;
|
|
30
33
|
export type ChatComposerBarProps = {
|
|
31
34
|
iface: ComposerProfileInterface;
|
|
32
35
|
/** Default `stacked`. */
|
|
@@ -52,6 +55,18 @@ export type ChatComposerBarProps = {
|
|
|
52
55
|
placeholder?: string;
|
|
53
56
|
/** Imperative handle for the editor (focus, insert). */
|
|
54
57
|
inputRef?: React.Ref<ChatComposerInputHandle>;
|
|
58
|
+
/** The text field; Astryx's `ChatComposerInput` when absent. */
|
|
59
|
+
inputComponent?: ComposerInputComponent;
|
|
60
|
+
/** The field's triggers, such as a list opened by a typed character. */
|
|
61
|
+
triggers?: ChatComposerTrigger[];
|
|
62
|
+
/** The draft's words and refs, while it holds a ref (`ChatState.draftParts`). */
|
|
63
|
+
draftParts?: readonly UserPart[];
|
|
64
|
+
/** Called after `onDraftTextChange` with the refs the field holds. Without it, none are kept. */
|
|
65
|
+
onDraftPartsChange?: (parts: UserPart[] | undefined) => void;
|
|
66
|
+
/** Writes a ref into the message's text; the ref's id when absent. */
|
|
67
|
+
refText?: RefText;
|
|
68
|
+
/** Draws a ref's chip; a badge of its text when absent. */
|
|
69
|
+
renderRef?: (ref: UserRef) => ReactNode;
|
|
55
70
|
onDraftTextChange: (text: string) => void;
|
|
56
71
|
onFilesSelected: (files: File[]) => void;
|
|
57
72
|
onAttachmentRemove: (index: number) => void;
|
|
@@ -75,7 +90,7 @@ export type ChatComposerBarProps = {
|
|
|
75
90
|
onPendingSendNow: (id: string) => void;
|
|
76
91
|
};
|
|
77
92
|
/** A Live call's text line: it is sent as typed, so there is nothing to attach, queue, or stop. */
|
|
78
|
-
export type LiveComposerBarProps = Omit<Pick<ChatComposerBarProps, 'draftText' | 'placeholder' | 'inputRef' | 'onDraftTextChange' | 'onSubmit'>, 'onSubmit'> & {
|
|
93
|
+
export type LiveComposerBarProps = Omit<Pick<ChatComposerBarProps, 'draftText' | 'placeholder' | 'inputRef' | 'inputComponent' | 'triggers' | 'draftParts' | 'onDraftPartsChange' | 'refText' | 'renderRef' | 'onDraftTextChange' | 'onSubmit'>, 'onSubmit'> & {
|
|
79
94
|
/** The typed line. The button reads the field, so this is the text, not the click. */
|
|
80
95
|
onSubmit: (text: string) => void;
|
|
81
96
|
/** The live profile, when the host has one. The placeholder uses its handle. */
|
package/ui/ChatComposerBar.js
CHANGED
|
@@ -15,12 +15,13 @@ import { IconAdjustmentsHorizontal, IconArchive, IconArrowBigRightLines, IconArr
|
|
|
15
15
|
import { attachmentIssueText, labelText } from '@theoremjs/agents';
|
|
16
16
|
import { composerPendingMoves, composerPendingPreview, effortSelectEnabled, interfaceEffortOptions, interfaceModelOptions, modelSelectEnabled, } from '@theoremjs/agents/interface';
|
|
17
17
|
import { COMPOSER_SHORTCUTS, composerActionState, composerDrawerSummary, composerShortcut, resolveComposerHint, } from '@theoremjs/web/client';
|
|
18
|
-
import {
|
|
18
|
+
import { useEffect, useMemo, useRef, useState, } from 'react';
|
|
19
19
|
import { stageComposerFiles } from "../client/composer-attachments.js";
|
|
20
20
|
import { useComposerVoice } from "../components/use-composer-voice.js";
|
|
21
21
|
import { useEditorSelection } from "../components/use-editor-selection.js";
|
|
22
22
|
import { ChatComposerRow, } from "./ChatComposerRow.js";
|
|
23
23
|
import { ComposerControls, ComposerSelector } from "./ComposerControls.js";
|
|
24
|
+
import { useEditorRefs } from "./composer-refs.js";
|
|
24
25
|
import { composerDrawerLabel } from "./labels.js";
|
|
25
26
|
import { TheoremLabelsProvider, useLabels } from "./labels-provider.js";
|
|
26
27
|
import { VoiceNote } from "./VoiceNote.js";
|
|
@@ -286,8 +287,8 @@ function composerTray(t, props, stagedFiles, onVoiceRemove) {
|
|
|
286
287
|
* The text field, with the send menu's shortcuts while it has focus: each acts only when the
|
|
287
288
|
* menu offers it. `field` wires it up when it stands outside Astryx's composer (the row layout).
|
|
288
289
|
*/
|
|
289
|
-
function ComposerTextInput({ editorRef, handleRef, menuActions, onMenuAction, onFiles, field, }) {
|
|
290
|
-
return (_jsx(
|
|
290
|
+
function ComposerTextInput({ input: Input = ChatComposerInput, triggers, editorRef, handleRef, menuActions, onMenuAction, onFiles, field, }) {
|
|
291
|
+
return (_jsx(Input, { ref: editorRef, handleRef: handleRef, onFiles: onFiles, ...(triggers ? { triggers } : {}), ...(field
|
|
291
292
|
? {
|
|
292
293
|
value: field.value,
|
|
293
294
|
onChange: field.onChange,
|
|
@@ -314,28 +315,32 @@ export function ChatComposerBar(props) {
|
|
|
314
315
|
}
|
|
315
316
|
function LiveComposerBarBody(props) {
|
|
316
317
|
const t = useLabels();
|
|
317
|
-
const
|
|
318
|
-
const
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
318
|
+
const rootRef = useRef(null);
|
|
319
|
+
const Input = props.inputComponent ?? ChatComposerInput;
|
|
320
|
+
const refs = useEditorRefs({
|
|
321
|
+
rootRef,
|
|
322
|
+
inputRef: props.inputRef,
|
|
323
|
+
drawn: Input,
|
|
324
|
+
value: props.draftText,
|
|
325
|
+
parts: props.draftParts,
|
|
326
|
+
onChange: props.onDraftTextChange,
|
|
327
|
+
onParts: props.onDraftPartsChange,
|
|
328
|
+
refText: props.refText,
|
|
329
|
+
renderRef: props.renderRef,
|
|
330
|
+
});
|
|
326
331
|
// why: The button used to send only the React draft. Typing lives in the field first, so an
|
|
327
332
|
// empty draft left the button dead. Read the field.
|
|
328
333
|
const submitTyped = () => {
|
|
329
|
-
const text = (
|
|
334
|
+
const text = (refs.handle.current?.getValue() ?? props.draftText).trim();
|
|
330
335
|
if (!text || props.isDisabled)
|
|
331
336
|
return;
|
|
332
337
|
props.onSubmit(text);
|
|
333
338
|
props.onDraftTextChange('');
|
|
334
339
|
};
|
|
335
|
-
return (_jsx(ChatComposer, { style: NO_FOCUS_RING, value: props.draftText, onChange:
|
|
340
|
+
return (_jsx(ChatComposer, { style: NO_FOCUS_RING, value: props.draftText, onChange: refs.onChange, onSubmit: props.onSubmit, isDisabled: props.isDisabled, placeholder: props.placeholder ??
|
|
336
341
|
t('@theorem.composer.placeholder', {
|
|
337
342
|
handle: props.handle ?? props.iface?.identity.handle ?? '',
|
|
338
|
-
}), input: _jsx(
|
|
343
|
+
}), input: refs.provide(_jsx(Input, { ref: rootRef, handleRef: refs.handleRef, ...(props.triggers ? { triggers: props.triggers } : {}) })), sendButton: _jsx(ChatSendButton, { isDisabled: props.isDisabled, onSend: submitTyped }) }));
|
|
339
344
|
}
|
|
340
345
|
function ChatComposerBarBody(props) {
|
|
341
346
|
const parts = useComposerParts(props);
|
|
@@ -377,9 +382,22 @@ function useComposerParts(props) {
|
|
|
377
382
|
selectedText: useEditorSelection(editorRef),
|
|
378
383
|
canStash: actions.menuActions.includes('stash'),
|
|
379
384
|
});
|
|
385
|
+
const refs = useEditorRefs({
|
|
386
|
+
rootRef: editorRef,
|
|
387
|
+
inputRef: props.inputRef,
|
|
388
|
+
drawn: `${props.layout}`,
|
|
389
|
+
value: props.draftText,
|
|
390
|
+
parts: props.draftParts,
|
|
391
|
+
onChange: props.onDraftTextChange,
|
|
392
|
+
onParts: props.onDraftPartsChange,
|
|
393
|
+
refText: props.refText,
|
|
394
|
+
renderRef: props.renderRef,
|
|
395
|
+
});
|
|
380
396
|
const runPrimary = () => {
|
|
381
397
|
if (actions.primaryDisabled)
|
|
382
398
|
return;
|
|
399
|
+
// invariant: What is sent holds the refs the field holds now.
|
|
400
|
+
refs.report();
|
|
383
401
|
if (actions.primary === 'stop')
|
|
384
402
|
props.onStop();
|
|
385
403
|
else
|
|
@@ -390,21 +408,23 @@ function useComposerParts(props) {
|
|
|
390
408
|
return {
|
|
391
409
|
...actions,
|
|
392
410
|
runPrimary,
|
|
411
|
+
onDraftTextChange: refs.onChange,
|
|
393
412
|
editorRef,
|
|
394
413
|
placeholder,
|
|
395
414
|
// why: A profile that takes no text has no text field (false, not null: null gets Astryx's default one).
|
|
396
|
-
input: inputs.text &&
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
415
|
+
input: inputs.text &&
|
|
416
|
+
refs.provide(_jsx(ComposerTextInput, { input: props.inputComponent, triggers: props.triggers, editorRef: editorRef, handleRef: refs.handleRef, menuActions: actions.menuActions, onMenuAction: props.onMenuAction,
|
|
417
|
+
// why: A pasted or dropped file goes through the same staging and limits as the attach button.
|
|
418
|
+
onFiles: inputs.attachments ? stageFiles : undefined,
|
|
419
|
+
// why: The row draws its own surface, outside Astryx's ChatComposer, so the field takes its value here.
|
|
420
|
+
field: props.layout === 'row'
|
|
421
|
+
? {
|
|
422
|
+
value: props.draftText,
|
|
423
|
+
onChange: refs.onChange,
|
|
424
|
+
onSubmit: runPrimary,
|
|
425
|
+
placeholder,
|
|
426
|
+
}
|
|
427
|
+
: undefined })),
|
|
408
428
|
tray: composerTray(t, props, stagedFiles, () => voice.discardRecordingOrVoice()),
|
|
409
429
|
attach: inputs.attachments ? (_jsx(AttachFilesButton, { accept: inputs.attachments.acceptAttr, size: props.layout === 'row' ? 'md' : 'sm', onFiles: stageFiles })) : undefined,
|
|
410
430
|
hintNode: hint ? (_jsx(ComposerHint, { hint: hint, onAction: () => props.onMenuAction('stash') })) : undefined,
|
|
@@ -434,7 +454,7 @@ function StackedComposerBar({ props, parts, }) {
|
|
|
434
454
|
, {
|
|
435
455
|
// why: No keyboard focus ring on the composer (product choice): zero Astryx's
|
|
436
456
|
// focus-outline token for this subtree. The editor still shows its caret.
|
|
437
|
-
style: NO_FOCUS_RING, value: props.draftText, onChange:
|
|
457
|
+
style: NO_FOCUS_RING, value: props.draftText, onChange: parts.onDraftTextChange, onSubmit: parts.runPrimary, onStop: props.onStop, isStopShown: isStopShown, placeholder: parts.placeholder, input: parts.input, drawer: parts.tray && (_jsx(ChatComposerDrawer, { count: parts.tray.count, label: parts.tray.label, children: parts.tray.content })), headerActions: parts.attach, headerContext: parts.hintNode, footerActions: parts.controls,
|
|
438
458
|
// why: Astryx: sendActions render to the left of the send button, at size="md".
|
|
439
459
|
sendActions: _jsxs(_Fragment, { children: [_jsx(SendMenu, { actions: parts.menuActions, phase: props.phase, onAction: props.onMenuAction }), parts.record] }), sendButton: _jsx(ChatSendButton, { isStopShown: isStopShown, isDisabled: parts.primaryDisabled, onSend: parts.runPrimary, onStop: props.onStop }), status: parts.status }));
|
|
440
460
|
}
|
package/ui/ChatTranscript.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ChatMessageStatus } from '@astryxdesign/core/Chat';
|
|
2
2
|
import type { LabelOverrides } from '@theoremjs/agents';
|
|
3
|
+
import type { UserRef } from '@theoremjs/agents/interface';
|
|
3
4
|
import { type TranscriptBlock } from '@theoremjs/agents/interface';
|
|
4
5
|
import type { AnsweringGate } from '@theoremjs/web/client';
|
|
5
6
|
import { type ReactNode } from 'react';
|
|
@@ -8,6 +9,8 @@ import { type TurnClock } from '../hooks/use-turn-clock.js';
|
|
|
8
9
|
import { type ToolDecision } from './ToolGateCard.js';
|
|
9
10
|
import { type MediaReference } from './tool-media.js';
|
|
10
11
|
export type ChatTranscriptProps = {
|
|
12
|
+
/** Draws a ref in the person's message; without it the message shows as its plain text. */
|
|
13
|
+
renderRef?: (ref: UserRef) => ReactNode;
|
|
11
14
|
blocks: readonly TranscriptBlock[];
|
|
12
15
|
/** Assistant display name (profile handle). */
|
|
13
16
|
handle: string;
|
package/ui/ChatTranscript.js
CHANGED
|
@@ -21,7 +21,7 @@ import { VStack } from '@astryxdesign/core/VStack';
|
|
|
21
21
|
import { IconCheck, IconCopy } from '@tabler/icons-react';
|
|
22
22
|
import { stopText } from '@theoremjs/agents/interface';
|
|
23
23
|
import { citationsFromBlock } from '@theoremjs/web/client';
|
|
24
|
-
import { createContext, useContext, useEffect, useMemo, useRef, useState, } from 'react';
|
|
24
|
+
import { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, } from 'react';
|
|
25
25
|
import { assistantTurnCopyText, assistantTurnTiming, composeAssistantTurn, groupTranscriptBlocks, pendingPromptOf, promptReplyKey, promptTime, toolCallLabel, workStatus, } from "../client/transcript-groups.js";
|
|
26
26
|
import { useSecondTicker } from "../hooks/use-second-ticker.js";
|
|
27
27
|
import { useTurnClock } from "../hooks/use-turn-clock.js";
|
|
@@ -208,9 +208,22 @@ function ImageAttachment({ src, name, reference, }) {
|
|
|
208
208
|
]);
|
|
209
209
|
return (_jsxs(_Fragment, { children: [_jsx(Thumbnail, { src: src, alt: name, label: name, onClick: () => viewer.open() }), viewer.element] }));
|
|
210
210
|
}
|
|
211
|
+
const RenderRef = createContext(undefined);
|
|
212
|
+
/** The message's words, with each ref as the host draws it. */
|
|
213
|
+
function userParts(parts, renderRef) {
|
|
214
|
+
// why: A saved message's parts never change, so how many came before tells a ref apart.
|
|
215
|
+
let refs = 0;
|
|
216
|
+
return parts.map((part) => {
|
|
217
|
+
if (part.type === 'text')
|
|
218
|
+
return part.text;
|
|
219
|
+
refs += 1;
|
|
220
|
+
return _jsx(Fragment, { children: renderRef(part) }, `ref-${refs}`);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
211
223
|
function UserBlock({ block, metadata }) {
|
|
224
|
+
const renderRef = useContext(RenderRef);
|
|
212
225
|
if (block.kind === 'user-text')
|
|
213
|
-
return _jsx(ChatMessageBubble, { metadata: metadata, children: block.text });
|
|
226
|
+
return (_jsx(ChatMessageBubble, { metadata: metadata, children: renderRef && block.parts ? userParts(block.parts, renderRef) : block.text }));
|
|
214
227
|
if (block.kind !== 'user-attachment' && block.kind !== 'user-voice')
|
|
215
228
|
return null;
|
|
216
229
|
return _jsx(UserFile, { block: block });
|
|
@@ -731,7 +744,7 @@ function isBareFailure(group) {
|
|
|
731
744
|
}
|
|
732
745
|
/** Theorem transcript blocks rendered as Astryx chat messages. */
|
|
733
746
|
export function ChatTranscript(props) {
|
|
734
|
-
return (_jsx(TheoremLabelsProvider, { children: _jsx(ShowUsage.Provider, { value: props.usage === true, children: _jsx(ShowToolData.Provider, { value: props.showToolData !== false, children: _jsx(ShowToolDurations.Provider, { value: props.showToolDurations !== false, children: _jsx(ShowWorkStatus.Provider, { value: props.showWorkStatus !== false, children: _jsx(ShowResumedNotice.Provider, { value: props.showResumedNotice !== false, children: _jsx(ChatTranscriptBody, { ...props }) }) }) }) }) }) }));
|
|
747
|
+
return (_jsx(TheoremLabelsProvider, { children: _jsx(ShowUsage.Provider, { value: props.usage === true, children: _jsx(RenderRef.Provider, { value: props.renderRef, children: _jsx(ShowToolData.Provider, { value: props.showToolData !== false, children: _jsx(ShowToolDurations.Provider, { value: props.showToolDurations !== false, children: _jsx(ShowWorkStatus.Provider, { value: props.showWorkStatus !== false, children: _jsx(ShowResumedNotice.Provider, { value: props.showResumedNotice !== false, children: _jsx(ChatTranscriptBody, { ...props }) }) }) }) }) }) }) }));
|
|
735
748
|
}
|
|
736
749
|
function ChatTranscriptBody({ blocks, handle, streaming = false, delivery, onToolDecision, answering = null, onAuthenticated, emptyState, dividers, imageOutput, bodyKindPlacement, stepLayout, labels, clock, }) {
|
|
737
750
|
const groups = useMemo(() => groupTranscriptBlocks(blocks, dividers && new Set(Object.keys(dividers))), [blocks, dividers]);
|
package/ui/TheoremChat.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { type ChatComposerInputHandle } from '@astryxdesign/core/Chat';
|
|
1
|
+
import { type ChatComposerInputHandle, type ChatComposerTrigger } from '@astryxdesign/core/Chat';
|
|
2
2
|
import type { DefinedTheme } from '@astryxdesign/core/theme';
|
|
3
|
+
import type { RefText, UserRef } from '@theoremjs/agents/interface';
|
|
3
4
|
import { type ComposerPendingMessage, type ComposerProfileInterface } from '@theoremjs/agents/interface';
|
|
4
5
|
import type { ChatController, PageTools, StatedTurn } from '@theoremjs/web/client';
|
|
5
6
|
import { type ConversationView, type HttpTransportOptions, type TheoremTransport } from '@theoremjs/web/client';
|
|
6
7
|
import { type ReactNode, type Ref } from 'react';
|
|
7
8
|
import { type SendTextOptions, type SentTurn, type TheoremChatState, type UseTheoremChatOptions } from '../hooks/use-theorem-chat.js';
|
|
9
|
+
import type { ComposerInputComponent } from './ChatComposerBar.js';
|
|
8
10
|
import { type ComposerLayout } from './ChatComposerBar.js';
|
|
9
11
|
import type { ComposerPill, ComposerRowIcons } from './ChatComposerRow.js';
|
|
10
12
|
import { type ChatTranscriptProps } from './ChatTranscript.js';
|
|
@@ -147,6 +149,14 @@ export type TheoremChatProps = {
|
|
|
147
149
|
* `--theorem-composer-*` CSS properties.
|
|
148
150
|
*/
|
|
149
151
|
composerIcons?: ComposerRowIcons;
|
|
152
|
+
/** The composer's text field; Astryx's `ChatComposerInput` when absent. */
|
|
153
|
+
composerInput?: ComposerInputComponent;
|
|
154
|
+
/** The composer field's triggers, such as a list opened by a typed character. */
|
|
155
|
+
composerTriggers?: ChatComposerTrigger[];
|
|
156
|
+
/** Writes a ref into the message's text; the ref's id when absent. Give the server the same one. */
|
|
157
|
+
refText?: RefText;
|
|
158
|
+
/** Draws a ref, as a chip in the composer and in the person's message. */
|
|
159
|
+
renderRef?: (ref: UserRef) => ReactNode;
|
|
150
160
|
};
|
|
151
161
|
/** What a host can do to a mounted {@link TheoremChat}. */
|
|
152
162
|
export type TheoremChatHandle = {
|
|
@@ -180,6 +190,14 @@ export type TheoremChatComposerProps = {
|
|
|
180
190
|
inputRef?: Ref<ChatComposerInputHandle>;
|
|
181
191
|
layout?: ComposerLayout;
|
|
182
192
|
icons?: ComposerRowIcons;
|
|
193
|
+
/** The text field; Astryx's `ChatComposerInput` when absent. */
|
|
194
|
+
inputComponent?: ComposerInputComponent;
|
|
195
|
+
/** The field's triggers. */
|
|
196
|
+
triggers?: ChatComposerTrigger[];
|
|
197
|
+
/** Writes a ref into the message's text; give the chat's own (`useTheoremChat`). */
|
|
198
|
+
refText?: RefText;
|
|
199
|
+
/** Draws a ref's chip. */
|
|
200
|
+
renderRef?: (ref: UserRef) => ReactNode;
|
|
183
201
|
/** The app's own pills, in the `row` layout's pill row after the background jobs. */
|
|
184
202
|
pills?: readonly ComposerPill[];
|
|
185
203
|
};
|
|
@@ -188,7 +206,7 @@ export type TheoremChatComposerProps = {
|
|
|
188
206
|
* working pill on the chat's turn clock. Place it anywhere; `TheoremChat` is built from it and
|
|
189
207
|
* `TheoremChatTranscript`.
|
|
190
208
|
*/
|
|
191
|
-
export declare function TheoremChatComposer({ chat, iface, placeholder, inputRef, layout, icons, pills, }: TheoremChatComposerProps): import("react").JSX.Element;
|
|
209
|
+
export declare function TheoremChatComposer({ chat, iface, placeholder, inputRef, layout, icons, pills, inputComponent, triggers, refText, renderRef, }: TheoremChatComposerProps): import("react").JSX.Element;
|
|
192
210
|
export type TheoremChatTranscriptProps = Omit<ChatTranscriptProps, 'blocks' | 'handle' | 'streaming' | 'delivery' | 'answering' | 'clock' | 'onToolDecision' | 'onAuthenticated' | 'imageOutput' | 'labels' | 'showToolData'> & {
|
|
193
211
|
/** The chat it shows (`useTheoremChat`). */
|
|
194
212
|
chat: TheoremChatState;
|
package/ui/TheoremChat.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { Banner } from '@astryxdesign/core/Banner';
|
|
3
3
|
import { Center } from '@astryxdesign/core/Center';
|
|
4
|
-
import { ChatLayout } from '@astryxdesign/core/Chat';
|
|
4
|
+
import { ChatLayout, } from '@astryxdesign/core/Chat';
|
|
5
5
|
import { Layout, LayoutContent } from '@astryxdesign/core/Layout';
|
|
6
6
|
import { Text } from '@astryxdesign/core/Text';
|
|
7
7
|
import { VStack } from '@astryxdesign/core/VStack';
|
|
@@ -33,8 +33,8 @@ function ChatColumn({ maxWidth, ref, children, }) {
|
|
|
33
33
|
* working pill on the chat's turn clock. Place it anywhere; `TheoremChat` is built from it and
|
|
34
34
|
* `TheoremChatTranscript`.
|
|
35
35
|
*/
|
|
36
|
-
export function TheoremChatComposer({ chat, iface, placeholder, inputRef, layout, icons, pills, }) {
|
|
37
|
-
return (_jsx(ChatComposerBar, { iface: iface, layout: layout, icons: icons, pills: pills, workingSince: chat.workingSince, backgroundJobs: chat.backgroundJobs, draftText: chat.draftText, pendingFiles: chat.pendingFiles, pendingVoice: chat.pendingVoice, pendingMessages: chat.pendingMessages, issues: chat.issues, phase: chat.phase, failure: chat.failure, selectedModel: chat.session.selectedModel, selectedEffort: chat.session.selectedEffort, placeholder: placeholder, inputRef: inputRef, onDraftTextChange: chat.setDraftText, onFilesSelected: (files) => {
|
|
36
|
+
export function TheoremChatComposer({ chat, iface, placeholder, inputRef, layout, icons, pills, inputComponent, triggers, refText, renderRef, }) {
|
|
37
|
+
return (_jsx(ChatComposerBar, { iface: iface, layout: layout, icons: icons, pills: pills, workingSince: chat.workingSince, backgroundJobs: chat.backgroundJobs, draftText: chat.draftText, pendingFiles: chat.pendingFiles, pendingVoice: chat.pendingVoice, pendingMessages: chat.pendingMessages, issues: chat.issues, phase: chat.phase, failure: chat.failure, selectedModel: chat.session.selectedModel, selectedEffort: chat.session.selectedEffort, placeholder: placeholder, inputRef: inputRef, inputComponent: inputComponent, triggers: triggers, refText: refText, renderRef: renderRef, draftParts: chat.draftParts, onDraftPartsChange: chat.setDraftParts, onDraftTextChange: chat.setDraftText, onFilesSelected: (files) => {
|
|
38
38
|
chat.setPendingFiles((prev) => [...prev, ...files]);
|
|
39
39
|
chat.setIssues([]);
|
|
40
40
|
}, onAttachmentRemove: (index) => {
|
|
@@ -75,7 +75,7 @@ function ChatBodyComposer({ hasComposer, ...props }) {
|
|
|
75
75
|
const failure = props.chat.failure;
|
|
76
76
|
return failure ? _jsx(Banner, { status: "error", role: "alert", title: failure.error }) : null;
|
|
77
77
|
}
|
|
78
|
-
function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth = DEFAULT_CHAT_MAX_WIDTH, scrollRef, trace, usage, className, style, conversation, conversationView, initialText, initialFiles, initialVoice, initialPending, onConversationChange, chatRef, composer: hasComposer = true, composerLayout, composerIcons, options, onOptionsChange, stated, context, pageTools, onTurnEvent, }) {
|
|
78
|
+
function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth = DEFAULT_CHAT_MAX_WIDTH, scrollRef, trace, usage, className, style, conversation, conversationView, initialText, initialFiles, initialVoice, initialPending, onConversationChange, chatRef, composer: hasComposer = true, composerLayout, composerIcons, composerInput, composerTriggers, refText, renderRef, options, onOptionsChange, stated, context, pageTools, onTurnEvent, }) {
|
|
79
79
|
const t = useLabels();
|
|
80
80
|
const chat = useTheoremChat({
|
|
81
81
|
transport,
|
|
@@ -93,6 +93,7 @@ function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth
|
|
|
93
93
|
context,
|
|
94
94
|
pageTools,
|
|
95
95
|
onTurnEvent,
|
|
96
|
+
refText,
|
|
96
97
|
});
|
|
97
98
|
const handle = t('@theorem.agent.handle', { handle: iface.identity.handle });
|
|
98
99
|
const landing = chat.shownBlocks.length === 0;
|
|
@@ -100,9 +101,9 @@ function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth
|
|
|
100
101
|
const composerRef = useGlide(landing, () => inputRef.current?.focus());
|
|
101
102
|
const inspector = useTraceInspector(iface, transport.traces, trace);
|
|
102
103
|
const header = _jsx(SidePanelHeader, { floating: true, children: inspector.toggle });
|
|
103
|
-
const composer = (_jsx(ChatBodyComposer, { hasComposer: hasComposer, chat: chat, iface: iface, placeholder: placeholder, inputRef: inputRef, layout: composerLayout, icons: composerIcons }));
|
|
104
|
+
const composer = (_jsx(ChatBodyComposer, { hasComposer: hasComposer, chat: chat, iface: iface, placeholder: placeholder, inputRef: inputRef, layout: composerLayout, icons: composerIcons, inputComponent: composerInput, triggers: composerTriggers, refText: refText, renderRef: renderRef }));
|
|
104
105
|
const docked = { composer, composerRef, maxWidth };
|
|
105
|
-
return (_jsx(WithTrace, { inspector: inspector, children: _jsx(Layout, { height: "fill", className: className, style: { position: 'relative', ...style }, header: header, content: _jsx(LayoutContent, { padding: 0, isScrollable: landing, children: landing ? (_jsx(ChatLanding, { ...docked, handle: handle, emptyState: emptyState })) : (_jsx(ChatThread, { ...docked, chat: chat, iface: iface, handle: handle, density: density, scrollRef: scrollRef, usage: usage })) }) }) }));
|
|
106
|
+
return (_jsx(WithTrace, { inspector: inspector, children: _jsx(Layout, { height: "fill", className: className, style: { position: 'relative', ...style }, header: header, content: _jsx(LayoutContent, { padding: 0, isScrollable: landing, children: landing ? (_jsx(ChatLanding, { ...docked, handle: handle, emptyState: emptyState })) : (_jsx(ChatThread, { ...docked, chat: chat, iface: iface, handle: handle, density: density, scrollRef: scrollRef, usage: usage, renderRef: renderRef })) }) }) }));
|
|
106
107
|
}
|
|
107
108
|
const CHAT_SCROLL = { overscrollBehavior: 'none' };
|
|
108
109
|
/**
|
|
@@ -118,10 +119,10 @@ function ChatLanding({ composer, composerRef, maxWidth, handle, emptyState, }) {
|
|
|
118
119
|
* why: the dock leaves 12px under the composer; paddingBlockEnd={3} adds 12px more for a 24px
|
|
119
120
|
* bottom margin.
|
|
120
121
|
*/
|
|
121
|
-
function ChatThread({ composer, composerRef, maxWidth, chat, iface, handle, density, scrollRef, usage, }) {
|
|
122
|
+
function ChatThread({ composer, composerRef, maxWidth, chat, iface, handle, density, scrollRef, usage, renderRef, }) {
|
|
122
123
|
return (_jsxs(VStack, { height: "100%", children: [_jsx("style", { href: "theorem-chat-thread", precedence: "default", children: '.theorem-chat-thread > :last-child > div:empty { display: none; }' }), _jsx(ChatLayout, { className: "theorem-chat-thread", density: density, scrollRef: scrollRef,
|
|
123
124
|
// why: Scrolling past either end does not bounce the transcript and its docked composer.
|
|
124
|
-
style: CHAT_SCROLL, composer: composer && (_jsx(VStack, { paddingBlockEnd: 3, children: _jsx(ChatColumn, { ref: composerRef, maxWidth: maxWidth, children: composer }) })), children: _jsx(ChatColumn, { maxWidth: maxWidth, children: _jsx(TheoremChatTranscript, { chat: chat, iface: iface, handle: handle, usage: usage }) }) })] }));
|
|
125
|
+
style: CHAT_SCROLL, composer: composer && (_jsx(VStack, { paddingBlockEnd: 3, children: _jsx(ChatColumn, { ref: composerRef, maxWidth: maxWidth, children: composer }) })), children: _jsx(ChatColumn, { maxWidth: maxWidth, children: _jsx(TheoremChatTranscript, { chat: chat, iface: iface, handle: handle, usage: usage, renderRef: renderRef }) }) })] }));
|
|
125
126
|
}
|
|
126
127
|
/**
|
|
127
128
|
* The transcript bound to a chat: its blocks as they stream, its gates answered through the chat,
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ChatComposerInputHandle, ChatComposerToken } from '@astryxdesign/core/Chat';
|
|
2
|
+
import { type RefText, type UserPart, type UserRef } from '@theoremjs/agents/interface';
|
|
3
|
+
import { type ReactNode, type Ref, type RefObject } from 'react';
|
|
4
|
+
/** How the host writes and draws its refs. */
|
|
5
|
+
export type RefTokenOptions = {
|
|
6
|
+
/** Writes a ref into the message's text; the ref's id when absent. Give the server the same one. */
|
|
7
|
+
refText?: RefText;
|
|
8
|
+
/** Draws a ref's chip; a badge of its text when absent. */
|
|
9
|
+
renderRef?: (ref: UserRef) => ReactNode;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* A ref as a chip for the composer's input: give it to `inputRef.current.insertToken`, or return it
|
|
13
|
+
* from a trigger's `onSelect`. Only a chip made here reaches the message as a ref.
|
|
14
|
+
*/
|
|
15
|
+
export declare function refToken(ref: Omit<UserRef, 'type'>, { refText, renderRef }?: RefTokenOptions): ChatComposerToken;
|
|
16
|
+
export type EditorRefsArgs = RefTokenOptions & {
|
|
17
|
+
/** The input's root element. */
|
|
18
|
+
rootRef: RefObject<HTMLElement | null>;
|
|
19
|
+
/** The host's handle on the input. */
|
|
20
|
+
inputRef: Ref<ChatComposerInputHandle> | undefined;
|
|
21
|
+
/** Names what the field was drawn as; a change means it was drawn again. */
|
|
22
|
+
drawn: unknown;
|
|
23
|
+
value: string;
|
|
24
|
+
parts: readonly UserPart[] | undefined;
|
|
25
|
+
onChange: (text: string) => void;
|
|
26
|
+
onParts: ((parts: UserPart[] | undefined) => void) | undefined;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Keeps a draft's refs with its input: reads them as the person edits, and makes their chips again
|
|
30
|
+
* when the input is drawn from a saved draft, which it would otherwise show as plain text.
|
|
31
|
+
*/
|
|
32
|
+
export declare function useEditorRefs(args: EditorRefsArgs): {
|
|
33
|
+
handleRef: (input: ChatComposerInputHandle | null) => void;
|
|
34
|
+
handle: RefObject<ChatComposerInputHandle | null>;
|
|
35
|
+
onChange: (text: string) => void;
|
|
36
|
+
report: () => void;
|
|
37
|
+
/** Wrap the input in this, so its chips are read once drawn. */
|
|
38
|
+
provide: (input: ReactNode) => import("react").JSX.Element;
|
|
39
|
+
};
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { Badge } from '@astryxdesign/core/Badge';
|
|
3
|
+
import { hasRef, messageParts, refIdText, textOfParts, } from '@theoremjs/agents/interface';
|
|
4
|
+
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useRef, } from 'react';
|
|
5
|
+
// invariant: This file is the one that reads the input's own markup, which a host's input keeps.
|
|
6
|
+
const TOKEN = '[data-astryx-token]';
|
|
7
|
+
const tokenRefs = new WeakMap();
|
|
8
|
+
const RefMounted = createContext(undefined);
|
|
9
|
+
/** Marks the token around it with its ref, which is what makes a chip a ref. */
|
|
10
|
+
function RefChip({ target, children }) {
|
|
11
|
+
const own = useRef(null);
|
|
12
|
+
const mounted = useContext(RefMounted);
|
|
13
|
+
// why: The input draws a token's content after the insert, so the draft is read again here.
|
|
14
|
+
useLayoutEffect(() => {
|
|
15
|
+
const token = own.current?.closest(TOKEN);
|
|
16
|
+
if (!token)
|
|
17
|
+
return;
|
|
18
|
+
tokenRefs.set(token, target);
|
|
19
|
+
mounted?.();
|
|
20
|
+
}, [target, mounted]);
|
|
21
|
+
return _jsx("span", { ref: own, children: children });
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A ref as a chip for the composer's input: give it to `inputRef.current.insertToken`, or return it
|
|
25
|
+
* from a trigger's `onSelect`. Only a chip made here reaches the message as a ref.
|
|
26
|
+
*/
|
|
27
|
+
export function refToken(ref, { refText = refIdText, renderRef } = {}) {
|
|
28
|
+
const target = { type: 'ref', kind: ref.kind, id: ref.id };
|
|
29
|
+
const value = refText(target);
|
|
30
|
+
return {
|
|
31
|
+
value,
|
|
32
|
+
render: () => (_jsx(RefChip, { target: target, children: renderRef?.(target) ?? _jsx(Badge, { label: value }) })),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function addWords(parts, text) {
|
|
36
|
+
const last = parts.at(-1);
|
|
37
|
+
if (last?.type === 'text')
|
|
38
|
+
parts[parts.length - 1] = { type: 'text', text: last.text + text };
|
|
39
|
+
else if (text)
|
|
40
|
+
parts.push({ type: 'text', text });
|
|
41
|
+
}
|
|
42
|
+
function readElement(element, parts, range) {
|
|
43
|
+
if (element.matches(TOKEN)) {
|
|
44
|
+
const ref = tokenRefs.get(element);
|
|
45
|
+
if (ref)
|
|
46
|
+
parts.push(ref);
|
|
47
|
+
else
|
|
48
|
+
addWords(parts, element.getAttribute('data-astryx-token-value') ?? '');
|
|
49
|
+
}
|
|
50
|
+
else if (element.tagName === 'BR')
|
|
51
|
+
addWords(parts, '\n');
|
|
52
|
+
else
|
|
53
|
+
readInto(element, parts, range);
|
|
54
|
+
}
|
|
55
|
+
/** The text of `node`, cut to what `range` selects of it. */
|
|
56
|
+
function textIn(node, range) {
|
|
57
|
+
const text = node.textContent ?? '';
|
|
58
|
+
const from = range?.startContainer === node ? range.startOffset : 0;
|
|
59
|
+
const to = range?.endContainer === node ? range.endOffset : text.length;
|
|
60
|
+
return text.slice(from, to);
|
|
61
|
+
}
|
|
62
|
+
/** Reads `node` into `parts`; with a `range`, only what it selects. */
|
|
63
|
+
function readInto(node, parts, range) {
|
|
64
|
+
for (const child of node.childNodes) {
|
|
65
|
+
if (range && !range.intersectsNode(child))
|
|
66
|
+
continue;
|
|
67
|
+
if (child.nodeType === 3)
|
|
68
|
+
addWords(parts, textIn(child, range));
|
|
69
|
+
else if (child.nodeType === 1)
|
|
70
|
+
readElement(child, parts, range);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** The editor's words and refs, as the input's own value reads them; undefined with no ref. */
|
|
74
|
+
function readEditorParts(editor, range) {
|
|
75
|
+
const parts = [];
|
|
76
|
+
readInto(editor, parts, range);
|
|
77
|
+
return hasRef(parts) ? parts : undefined;
|
|
78
|
+
}
|
|
79
|
+
/** Puts `parts` in at the caret through the input's handle, each ref a chip again. */
|
|
80
|
+
function insertParts(editor, handle, parts, options) {
|
|
81
|
+
for (const part of parts) {
|
|
82
|
+
if (part.type === 'text') {
|
|
83
|
+
handle.insertText(part.text);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const id = handle.insertToken(refToken(part, options));
|
|
87
|
+
const token = id && editor.querySelector(`[data-astryx-token-id="${id}"]`);
|
|
88
|
+
if (!token)
|
|
89
|
+
continue;
|
|
90
|
+
tokenRefs.set(token, part);
|
|
91
|
+
// why: The input adds a space after each token; the parts' own words already hold theirs.
|
|
92
|
+
token.nextSibling?.remove();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Fills an empty editor with `parts`, leaving focus where it was. */
|
|
96
|
+
function writeEditorParts(editor, handle, parts, options) {
|
|
97
|
+
const focused = editor.ownerDocument.activeElement === editor;
|
|
98
|
+
editor.textContent = '';
|
|
99
|
+
insertParts(editor, handle, parts, options);
|
|
100
|
+
if (!focused)
|
|
101
|
+
editor.blur();
|
|
102
|
+
}
|
|
103
|
+
function editorIn(root) {
|
|
104
|
+
if (!root)
|
|
105
|
+
return null;
|
|
106
|
+
const selector = '[contenteditable]';
|
|
107
|
+
return root.matches(selector) ? root : root.querySelector(selector);
|
|
108
|
+
}
|
|
109
|
+
function chipAround(editor, node) {
|
|
110
|
+
const element = node.nodeType === 1 ? node : node.parentElement;
|
|
111
|
+
const chip = element?.closest(TOKEN);
|
|
112
|
+
return chip && editor.contains(chip) ? chip : null;
|
|
113
|
+
}
|
|
114
|
+
/** Moves each end of `range` that sits inside a chip to just after it; true when one moved. */
|
|
115
|
+
function movedOutOfChips(editor, range) {
|
|
116
|
+
const start = chipAround(editor, range.startContainer);
|
|
117
|
+
const end = chipAround(editor, range.endContainer);
|
|
118
|
+
if (start)
|
|
119
|
+
range.setStartAfter(start);
|
|
120
|
+
if (end)
|
|
121
|
+
range.setEndAfter(end);
|
|
122
|
+
return Boolean(start || end);
|
|
123
|
+
}
|
|
124
|
+
/** Takes the editor's selection out of any chip. */
|
|
125
|
+
function leaveChips(editor) {
|
|
126
|
+
const selection = editor?.ownerDocument.defaultView?.getSelection();
|
|
127
|
+
if (!editor || !selection?.rangeCount)
|
|
128
|
+
return;
|
|
129
|
+
const range = selection.getRangeAt(0).cloneRange();
|
|
130
|
+
if (!movedOutOfChips(editor, range))
|
|
131
|
+
return;
|
|
132
|
+
selection.removeAllRanges();
|
|
133
|
+
selection.addRange(range);
|
|
134
|
+
}
|
|
135
|
+
/** The input's handle, whose inserts never land inside a chip. */
|
|
136
|
+
function outsideChips(input, editor) {
|
|
137
|
+
return {
|
|
138
|
+
insertToken: (token) => {
|
|
139
|
+
leaveChips(editor());
|
|
140
|
+
return input.insertToken(token);
|
|
141
|
+
},
|
|
142
|
+
insertText: (text) => {
|
|
143
|
+
leaveChips(editor());
|
|
144
|
+
input.insertText(text);
|
|
145
|
+
},
|
|
146
|
+
expandToken: (id) => input.expandToken(id),
|
|
147
|
+
focus: () => input.focus(),
|
|
148
|
+
getValue: () => input.getValue(),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** The editor's selection, when it has one. */
|
|
152
|
+
function selectionIn(editor) {
|
|
153
|
+
const selection = editor.ownerDocument.defaultView?.getSelection();
|
|
154
|
+
if (!selection?.rangeCount)
|
|
155
|
+
return undefined;
|
|
156
|
+
const range = selection.getRangeAt(0);
|
|
157
|
+
return editor.contains(range.commonAncestorContainer) ? range : undefined;
|
|
158
|
+
}
|
|
159
|
+
function selectAll(editor) {
|
|
160
|
+
const selection = editor.ownerDocument.defaultView?.getSelection();
|
|
161
|
+
const range = editor.ownerDocument.createRange();
|
|
162
|
+
range.selectNodeContents(editor);
|
|
163
|
+
selection?.removeAllRanges();
|
|
164
|
+
selection?.addRange(range);
|
|
165
|
+
}
|
|
166
|
+
// invariant: The clipboard carries only a key; the refs stay in memory, so a paste can make no ref
|
|
167
|
+
// that was not copied from a composer on this page.
|
|
168
|
+
const CLIP = 'application/x-theorem-parts';
|
|
169
|
+
let clipped;
|
|
170
|
+
/** What the editor has selected, as a range holding any chip it touches whole. */
|
|
171
|
+
function wholeChips(editor) {
|
|
172
|
+
const selected = selectionIn(editor);
|
|
173
|
+
if (!selected || selected.collapsed)
|
|
174
|
+
return undefined;
|
|
175
|
+
const range = selected.cloneRange();
|
|
176
|
+
const start = chipAround(editor, range.startContainer);
|
|
177
|
+
const end = chipAround(editor, range.endContainer);
|
|
178
|
+
if (start)
|
|
179
|
+
range.setStartBefore(start);
|
|
180
|
+
if (end)
|
|
181
|
+
range.setEndAfter(end);
|
|
182
|
+
return range;
|
|
183
|
+
}
|
|
184
|
+
/** Copies a selection that holds a chip; any other is left to the browser. */
|
|
185
|
+
function copyChips(editor, event, refText) {
|
|
186
|
+
const range = wholeChips(editor);
|
|
187
|
+
const parts = range && readEditorParts(editor, range);
|
|
188
|
+
if (!range || !parts || !event.clipboardData)
|
|
189
|
+
return;
|
|
190
|
+
// why: Not `randomUUID`, which a page served over plain HTTP lacks.
|
|
191
|
+
clipped = { key: `${Date.now()}-${Math.random()}`, parts };
|
|
192
|
+
event.clipboardData.setData('text/plain', textOfParts(parts, refText));
|
|
193
|
+
event.clipboardData.setData(CLIP, clipped.key);
|
|
194
|
+
event.preventDefault();
|
|
195
|
+
event.stopPropagation();
|
|
196
|
+
if (event.type !== 'cut' || editor.getAttribute('contenteditable') === 'false')
|
|
197
|
+
return;
|
|
198
|
+
range.deleteContents();
|
|
199
|
+
editor.dispatchEvent(new Event('input', { bubbles: true }));
|
|
200
|
+
}
|
|
201
|
+
/** The parts a paste brings from a composer; undefined for anything from elsewhere. */
|
|
202
|
+
function pastedParts(event) {
|
|
203
|
+
const key = event.clipboardData?.getData(CLIP);
|
|
204
|
+
return key && key === clipped?.key ? clipped.parts : undefined;
|
|
205
|
+
}
|
|
206
|
+
/** Pastes a composer's copy as chips; an outside paste goes on to the input, past any chip. */
|
|
207
|
+
function pasteChips(editor, event, field) {
|
|
208
|
+
leaveChips(editor);
|
|
209
|
+
const parts = pastedParts(event);
|
|
210
|
+
const handle = field.handle();
|
|
211
|
+
if (!parts || !handle)
|
|
212
|
+
return;
|
|
213
|
+
event.preventDefault();
|
|
214
|
+
event.stopPropagation();
|
|
215
|
+
if (editor.getAttribute('contenteditable') === 'false')
|
|
216
|
+
return;
|
|
217
|
+
insertParts(editor, handle, parts, field.options());
|
|
218
|
+
field.read();
|
|
219
|
+
}
|
|
220
|
+
/** Typing with the caret in a chip goes after it, never inside. */
|
|
221
|
+
function typePastChips(editor, event, field) {
|
|
222
|
+
if (event.isComposing || !event.inputType.startsWith('insert'))
|
|
223
|
+
return;
|
|
224
|
+
const at = selectionIn(editor)?.startContainer;
|
|
225
|
+
if (!at || !chipAround(editor, at))
|
|
226
|
+
return;
|
|
227
|
+
if (event.inputType !== 'insertText' || !event.data) {
|
|
228
|
+
leaveChips(editor);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
event.preventDefault();
|
|
232
|
+
event.stopPropagation();
|
|
233
|
+
field.handle()?.insertText(event.data);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Moves the caret out of a chip before a key writes: a chip takes no input, so the browser would
|
|
237
|
+
* drop the character.
|
|
238
|
+
*/
|
|
239
|
+
function keyPastChips(editor, event) {
|
|
240
|
+
const writes = event.key.length === 1 || event.key === 'Process' || event.key === 'Unidentified';
|
|
241
|
+
if (writes && !event.ctrlKey && !event.metaKey)
|
|
242
|
+
leaveChips(editor);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Hears the field's own events before the input does. On the document, so a field drawn again
|
|
246
|
+
* needs no new listeners.
|
|
247
|
+
*/
|
|
248
|
+
function listenToField(field) {
|
|
249
|
+
const heard = [
|
|
250
|
+
['copy', (editor, e) => copyChips(editor, e, field.options().refText)],
|
|
251
|
+
['cut', (editor, e) => copyChips(editor, e, field.options().refText)],
|
|
252
|
+
['paste', (editor, e) => pasteChips(editor, e, field)],
|
|
253
|
+
['beforeinput', (editor, e) => typePastChips(editor, e, field)],
|
|
254
|
+
[
|
|
255
|
+
'keydown',
|
|
256
|
+
(editor, e) => {
|
|
257
|
+
const event = e;
|
|
258
|
+
keyPastChips(editor, event);
|
|
259
|
+
field.key(event.key, event.shiftKey);
|
|
260
|
+
},
|
|
261
|
+
],
|
|
262
|
+
['keyup', () => field.released()],
|
|
263
|
+
];
|
|
264
|
+
const page = field.editor()?.ownerDocument ?? document;
|
|
265
|
+
const added = heard.map(([type, act]) => {
|
|
266
|
+
const listener = (event) => {
|
|
267
|
+
const editor = field.editor();
|
|
268
|
+
if (editor && event.composedPath().includes(editor))
|
|
269
|
+
act(editor, event);
|
|
270
|
+
};
|
|
271
|
+
page.addEventListener(type, listener, true);
|
|
272
|
+
return () => page.removeEventListener(type, listener, true);
|
|
273
|
+
});
|
|
274
|
+
return () => {
|
|
275
|
+
for (const remove of added)
|
|
276
|
+
remove();
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The refs of messages sent from the field, by their words: the input's ↑ history keeps words
|
|
281
|
+
* alone. Two sent with the same words give back the later one's refs.
|
|
282
|
+
*/
|
|
283
|
+
function useRecall(editor, words) {
|
|
284
|
+
const kept = useRef(new Map());
|
|
285
|
+
const recalling = useRef(false);
|
|
286
|
+
const reselect = useRef(false);
|
|
287
|
+
return useRef({
|
|
288
|
+
key(key, shift) {
|
|
289
|
+
recalling.current = key === 'ArrowUp' || key === 'ArrowDown';
|
|
290
|
+
const sends = key === 'Enter' && !shift;
|
|
291
|
+
const field = editor();
|
|
292
|
+
if (!field || !(sends || recalling.current))
|
|
293
|
+
return;
|
|
294
|
+
const parts = messageParts(readEditorParts(field));
|
|
295
|
+
if (parts)
|
|
296
|
+
kept.current.set(words().trim(), parts);
|
|
297
|
+
else if (sends)
|
|
298
|
+
kept.current.delete(words().trim());
|
|
299
|
+
},
|
|
300
|
+
released() {
|
|
301
|
+
recalling.current = false;
|
|
302
|
+
},
|
|
303
|
+
/** The refs of `text`, when an arrow key has just brought it back. */
|
|
304
|
+
recalled(text) {
|
|
305
|
+
const parts = recalling.current ? kept.current.get(text.trim()) : undefined;
|
|
306
|
+
reselect.current = Boolean(parts);
|
|
307
|
+
return parts;
|
|
308
|
+
},
|
|
309
|
+
/** Selects a recalled message again, so the next ↑ steps on as the input's own recall does. */
|
|
310
|
+
written(field) {
|
|
311
|
+
if (reselect.current)
|
|
312
|
+
selectAll(field);
|
|
313
|
+
reselect.current = false;
|
|
314
|
+
},
|
|
315
|
+
}).current;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Keeps a draft's refs with its input: reads them as the person edits, and makes their chips again
|
|
319
|
+
* when the input is drawn from a saved draft, which it would otherwise show as plain text.
|
|
320
|
+
*/
|
|
321
|
+
export function useEditorRefs(args) {
|
|
322
|
+
const latest = useRef(args);
|
|
323
|
+
latest.current = args;
|
|
324
|
+
const handle = useRef(null);
|
|
325
|
+
const writing = useRef(false);
|
|
326
|
+
const drawnAs = useRef(args.drawn);
|
|
327
|
+
const editor = useCallback(() => editorIn(latest.current.rootRef.current), []);
|
|
328
|
+
const { inputRef } = args;
|
|
329
|
+
const handleRef = useCallback((input) => {
|
|
330
|
+
// why: An insert with the caret in a chip, as after a click on it, would nest a chip in it.
|
|
331
|
+
const node = input && outsideChips(input, editor);
|
|
332
|
+
handle.current = node;
|
|
333
|
+
if (typeof inputRef === 'function')
|
|
334
|
+
inputRef(node);
|
|
335
|
+
else if (inputRef)
|
|
336
|
+
inputRef.current = node;
|
|
337
|
+
}, [inputRef, editor]);
|
|
338
|
+
const report = useCallback(() => {
|
|
339
|
+
const field = editor();
|
|
340
|
+
if (field && !writing.current)
|
|
341
|
+
latest.current.onParts?.(readEditorParts(field));
|
|
342
|
+
}, [editor]);
|
|
343
|
+
const recall = useRecall(editor, () => handle.current?.getValue() ?? '');
|
|
344
|
+
const onChange = useCallback((text) => {
|
|
345
|
+
if (writing.current)
|
|
346
|
+
return;
|
|
347
|
+
latest.current.onChange(text);
|
|
348
|
+
const parts = recall.recalled(text);
|
|
349
|
+
if (parts)
|
|
350
|
+
latest.current.onParts?.(parts);
|
|
351
|
+
else
|
|
352
|
+
report();
|
|
353
|
+
}, [report, recall]);
|
|
354
|
+
useEffect(() => listenToField({
|
|
355
|
+
editor,
|
|
356
|
+
handle: () => handle.current,
|
|
357
|
+
options: () => latest.current,
|
|
358
|
+
read: () => {
|
|
359
|
+
const text = handle.current?.getValue();
|
|
360
|
+
if (text !== undefined && text !== latest.current.value)
|
|
361
|
+
latest.current.onChange(text);
|
|
362
|
+
report();
|
|
363
|
+
},
|
|
364
|
+
key: recall.key,
|
|
365
|
+
released: recall.released,
|
|
366
|
+
}), [editor, report, recall]);
|
|
367
|
+
const { value, parts, drawn } = args;
|
|
368
|
+
useEffect(() => {
|
|
369
|
+
const editor = editorIn(latest.current.rootRef.current);
|
|
370
|
+
drawnAs.current = drawn;
|
|
371
|
+
if (!editor || !handle.current || !hasRef(parts))
|
|
372
|
+
return;
|
|
373
|
+
// invariant: Words the draft's parts no longer spell are never written over.
|
|
374
|
+
if (textOfParts(parts, latest.current.refText).trim() !== value.trim())
|
|
375
|
+
return;
|
|
376
|
+
// why: A field that has its chips is the draft's source; only one that lost them is written.
|
|
377
|
+
const refs = parts.filter((part) => part.type === 'ref').length;
|
|
378
|
+
if (editor.querySelectorAll(TOKEN).length >= refs)
|
|
379
|
+
return;
|
|
380
|
+
writing.current = true;
|
|
381
|
+
try {
|
|
382
|
+
writeEditorParts(editor, handle.current, parts, latest.current);
|
|
383
|
+
}
|
|
384
|
+
finally {
|
|
385
|
+
writing.current = false;
|
|
386
|
+
}
|
|
387
|
+
const written = handle.current.getValue();
|
|
388
|
+
if (written !== value)
|
|
389
|
+
latest.current.onChange(written);
|
|
390
|
+
report();
|
|
391
|
+
recall.written(editor);
|
|
392
|
+
}, [value, parts, drawn, report, recall]);
|
|
393
|
+
return {
|
|
394
|
+
handleRef,
|
|
395
|
+
handle,
|
|
396
|
+
onChange,
|
|
397
|
+
report,
|
|
398
|
+
/** Wrap the input in this, so its chips are read once drawn. */
|
|
399
|
+
provide: (input) => (_jsx(RefMounted.Provider, { value: report, children: input })),
|
|
400
|
+
};
|
|
401
|
+
}
|
package/ui/index.d.ts
CHANGED
|
@@ -15,10 +15,11 @@ export type { StepLayout } from '../client/transcript-groups.js';
|
|
|
15
15
|
export { InkWaveform, type InkWaveformProps, type InkWaveLevels, } from '../components/InkWaveform.js';
|
|
16
16
|
export { type LiveCall, type LiveCallInput, useLiveCall, } from '../components/live/use-live-call.js';
|
|
17
17
|
export { theoremTheme } from './built/theorem.js';
|
|
18
|
-
export { ChatComposerBar, type ChatComposerBarProps, type ComposerLayout, EFFORT_ICON, generationOptions, type LiveComposerBarProps, } from './ChatComposerBar.js';
|
|
18
|
+
export { ChatComposerBar, type ChatComposerBarProps, type ComposerInputComponent, type ComposerLayout, EFFORT_ICON, generationOptions, type LiveComposerBarProps, } from './ChatComposerBar.js';
|
|
19
19
|
export type { ComposerPill, ComposerRowIcons } from './ChatComposerRow.js';
|
|
20
20
|
export { ChatTranscript, type ChatTranscriptProps } from './ChatTranscript.js';
|
|
21
21
|
export { ConsoleFrame, type ConsoleFrameProps, type ConsolePageProps, RequestCard, ResponseColumn, RunBar, useBytes, } from './ConsoleFrame.js';
|
|
22
|
+
export { type RefTokenOptions, refToken } from './composer-refs.js';
|
|
22
23
|
export { TheoremDecisionAnswers, type TheoremDecisionAnswersProps } from './DecisionAnswers.js';
|
|
23
24
|
export { useDisclosureMotion } from './disclosure-motion.js';
|
|
24
25
|
export { EmbeddingSpaceView, type EmbeddingSpaceViewProps } from './EmbeddingSpace.js';
|
package/ui/index.js
CHANGED
|
@@ -20,6 +20,7 @@ export { theoremTheme } from './built/theorem.js';
|
|
|
20
20
|
export { ChatComposerBar, EFFORT_ICON, generationOptions, } from "./ChatComposerBar.js";
|
|
21
21
|
export { ChatTranscript } from "./ChatTranscript.js";
|
|
22
22
|
export { ConsoleFrame, RequestCard, ResponseColumn, RunBar, useBytes, } from "./ConsoleFrame.js";
|
|
23
|
+
export { refToken } from "./composer-refs.js";
|
|
23
24
|
export { TheoremDecisionAnswers } from "./DecisionAnswers.js";
|
|
24
25
|
export { useDisclosureMotion } from "./disclosure-motion.js";
|
|
25
26
|
export { EmbeddingSpaceView } from "./EmbeddingSpace.js";
|