@theoremjs/react 0.3.5-next.1020.g3a48861 → 0.3.5-next.1024.g444d79c
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 +37 -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 +201 -0
- package/ui/index.d.ts +2 -1
- package/ui/index.js +1 -0
package/README.md
CHANGED
|
@@ -225,6 +225,42 @@ 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. `insertToken` and `insertText` on your `inputRef` then insert 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. Your own input must keep the markup of Astryx's tokens (`data-astryx-token`) and its handle.
|
|
258
|
+
|
|
259
|
+
Limits:
|
|
260
|
+
|
|
261
|
+
- A call sends a typed line as text. Its refs reach the model as that text.
|
|
262
|
+
- The up-arrow recall and copy and paste give plain text.
|
|
263
|
+
|
|
228
264
|
### Tool media
|
|
229
265
|
|
|
230
266
|
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 +630,7 @@ function Dock({ chat, iface }) {
|
|
|
594
630
|
}
|
|
595
631
|
```
|
|
596
632
|
|
|
597
|
-
`TheoremChatComposer` takes `layout`, `icons`, `pills`, `placeholder`, and `
|
|
633
|
+
`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
634
|
|
|
599
635
|
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
636
|
|
|
@@ -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.1024.g444d79c",
|
|
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.1024.g444d79c",
|
|
64
|
+
"@theoremjs/web": "^0.3.5-next.1024.g444d79c"
|
|
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,201 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { Badge } from '@astryxdesign/core/Badge';
|
|
3
|
+
import { hasRef, 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) {
|
|
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);
|
|
54
|
+
}
|
|
55
|
+
function readInto(node, parts) {
|
|
56
|
+
for (const child of node.childNodes) {
|
|
57
|
+
if (child.nodeType === 3)
|
|
58
|
+
addWords(parts, child.textContent ?? '');
|
|
59
|
+
else if (child.nodeType === 1)
|
|
60
|
+
readElement(child, parts);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** The editor's words and refs, as the input's own value reads them; undefined with no ref. */
|
|
64
|
+
function readEditorParts(editor) {
|
|
65
|
+
const parts = [];
|
|
66
|
+
readInto(editor, parts);
|
|
67
|
+
return hasRef(parts) ? parts : undefined;
|
|
68
|
+
}
|
|
69
|
+
/** Fills an empty editor with `parts` through the input's handle, each ref a chip again. */
|
|
70
|
+
function writeEditorParts(editor, handle, parts, options) {
|
|
71
|
+
const focused = editor.ownerDocument.activeElement === editor;
|
|
72
|
+
editor.textContent = '';
|
|
73
|
+
for (const part of parts) {
|
|
74
|
+
if (part.type === 'text') {
|
|
75
|
+
handle.insertText(part.text);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const id = handle.insertToken(refToken(part, options));
|
|
79
|
+
const token = id && editor.querySelector(`[data-astryx-token-id="${id}"]`);
|
|
80
|
+
if (!token)
|
|
81
|
+
continue;
|
|
82
|
+
tokenRefs.set(token, part);
|
|
83
|
+
// why: The input adds a space after each token; the draft's own words already hold theirs.
|
|
84
|
+
token.nextSibling?.remove();
|
|
85
|
+
}
|
|
86
|
+
if (!focused)
|
|
87
|
+
editor.blur();
|
|
88
|
+
}
|
|
89
|
+
function editorIn(root) {
|
|
90
|
+
if (!root)
|
|
91
|
+
return null;
|
|
92
|
+
const selector = '[contenteditable]';
|
|
93
|
+
return root.matches(selector) ? root : root.querySelector(selector);
|
|
94
|
+
}
|
|
95
|
+
function chipAround(editor, node) {
|
|
96
|
+
const element = node.nodeType === 1 ? node : node.parentElement;
|
|
97
|
+
const chip = element?.closest(TOKEN);
|
|
98
|
+
return chip && editor.contains(chip) ? chip : null;
|
|
99
|
+
}
|
|
100
|
+
/** Moves each end of `range` that sits inside a chip to just after it; true when one moved. */
|
|
101
|
+
function movedOutOfChips(editor, range) {
|
|
102
|
+
const start = chipAround(editor, range.startContainer);
|
|
103
|
+
const end = chipAround(editor, range.endContainer);
|
|
104
|
+
if (start)
|
|
105
|
+
range.setStartAfter(start);
|
|
106
|
+
if (end)
|
|
107
|
+
range.setEndAfter(end);
|
|
108
|
+
return Boolean(start || end);
|
|
109
|
+
}
|
|
110
|
+
/** Takes the editor's selection out of any chip. */
|
|
111
|
+
function leaveChips(editor) {
|
|
112
|
+
const selection = editor?.ownerDocument.defaultView?.getSelection();
|
|
113
|
+
if (!editor || !selection?.rangeCount)
|
|
114
|
+
return;
|
|
115
|
+
const range = selection.getRangeAt(0).cloneRange();
|
|
116
|
+
if (!movedOutOfChips(editor, range))
|
|
117
|
+
return;
|
|
118
|
+
selection.removeAllRanges();
|
|
119
|
+
selection.addRange(range);
|
|
120
|
+
}
|
|
121
|
+
/** The input's handle, whose inserts never land inside a chip. */
|
|
122
|
+
function outsideChips(input, editor) {
|
|
123
|
+
return {
|
|
124
|
+
insertToken: (token) => {
|
|
125
|
+
leaveChips(editor());
|
|
126
|
+
return input.insertToken(token);
|
|
127
|
+
},
|
|
128
|
+
insertText: (text) => {
|
|
129
|
+
leaveChips(editor());
|
|
130
|
+
input.insertText(text);
|
|
131
|
+
},
|
|
132
|
+
expandToken: (id) => input.expandToken(id),
|
|
133
|
+
focus: () => input.focus(),
|
|
134
|
+
getValue: () => input.getValue(),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Keeps a draft's refs with its input: reads them as the person edits, and makes their chips again
|
|
139
|
+
* when the input is drawn from a saved draft, which it would otherwise show as plain text.
|
|
140
|
+
*/
|
|
141
|
+
export function useEditorRefs(args) {
|
|
142
|
+
const latest = useRef(args);
|
|
143
|
+
latest.current = args;
|
|
144
|
+
const handle = useRef(null);
|
|
145
|
+
const writing = useRef(false);
|
|
146
|
+
const drawnAs = useRef(args.drawn);
|
|
147
|
+
const { inputRef } = args;
|
|
148
|
+
const handleRef = useCallback((input) => {
|
|
149
|
+
// why: An insert with the caret in a chip, as after a click on it, would nest a chip in it.
|
|
150
|
+
const node = input && outsideChips(input, () => editorIn(latest.current.rootRef.current));
|
|
151
|
+
handle.current = node;
|
|
152
|
+
if (typeof inputRef === 'function')
|
|
153
|
+
inputRef(node);
|
|
154
|
+
else if (inputRef)
|
|
155
|
+
inputRef.current = node;
|
|
156
|
+
}, [inputRef]);
|
|
157
|
+
const report = useCallback(() => {
|
|
158
|
+
const editor = editorIn(latest.current.rootRef.current);
|
|
159
|
+
if (editor && !writing.current)
|
|
160
|
+
latest.current.onParts?.(readEditorParts(editor));
|
|
161
|
+
}, []);
|
|
162
|
+
const onChange = useCallback((text) => {
|
|
163
|
+
if (writing.current)
|
|
164
|
+
return;
|
|
165
|
+
latest.current.onChange(text);
|
|
166
|
+
report();
|
|
167
|
+
}, [report]);
|
|
168
|
+
const { value, parts, drawn } = args;
|
|
169
|
+
useEffect(() => {
|
|
170
|
+
const editor = editorIn(latest.current.rootRef.current);
|
|
171
|
+
drawnAs.current = drawn;
|
|
172
|
+
if (!editor || !handle.current || !hasRef(parts))
|
|
173
|
+
return;
|
|
174
|
+
// invariant: Words the draft's parts no longer spell are never written over.
|
|
175
|
+
if (textOfParts(parts, latest.current.refText).trim() !== value.trim())
|
|
176
|
+
return;
|
|
177
|
+
// why: A field that has its chips is the draft's source; only one that lost them is written.
|
|
178
|
+
const refs = parts.filter((part) => part.type === 'ref').length;
|
|
179
|
+
if (editor.querySelectorAll(TOKEN).length >= refs)
|
|
180
|
+
return;
|
|
181
|
+
writing.current = true;
|
|
182
|
+
try {
|
|
183
|
+
writeEditorParts(editor, handle.current, parts, latest.current);
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
writing.current = false;
|
|
187
|
+
}
|
|
188
|
+
const written = handle.current.getValue();
|
|
189
|
+
if (written !== value)
|
|
190
|
+
latest.current.onChange(written);
|
|
191
|
+
report();
|
|
192
|
+
}, [value, parts, drawn, report]);
|
|
193
|
+
return {
|
|
194
|
+
handleRef,
|
|
195
|
+
handle,
|
|
196
|
+
onChange,
|
|
197
|
+
report,
|
|
198
|
+
/** Wrap the input in this, so its chips are read once drawn. */
|
|
199
|
+
provide: (input) => (_jsx(RefMounted.Provider, { value: report, children: input })),
|
|
200
|
+
};
|
|
201
|
+
}
|
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";
|