@lincyaw/workbench 0.2.0-rc.2 → 0.2.0-rc.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.2",
3
+ "version": "0.2.0-rc.20",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -54,8 +54,8 @@
54
54
  "@tiptap/pm": "3.32.0",
55
55
  "katex": "0.18.10",
56
56
  "react-resizable-panels": "4.14.5",
57
- "@lincyaw/design": "1.0.0-rc.3",
58
- "@lincyaw/kernel": "1.0.0-rc.3"
57
+ "@lincyaw/design": "1.0.0-rc.21",
58
+ "@lincyaw/kernel": "1.0.0-rc.21"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "react": "^18.3.1",
@@ -66,6 +66,6 @@
66
66
  "@types/react-dom": "18.3.7",
67
67
  "react": "^18.3.1",
68
68
  "react-dom": "^18.3.1",
69
- "@lincyaw/compiler": "1.0.0-rc.3"
69
+ "@lincyaw/compiler": "1.0.0-rc.21"
70
70
  }
71
71
  }
@@ -6,7 +6,7 @@ import { AddCommentButton, BasicTextStyleButton, BlockNoteViewEditor, BlockTypeS
6
6
  import type { ComponentProps, FormattingToolbarProps } from '@blocknote/react'
7
7
  import { useMediaQuery } from '@mantine/hooks'
8
8
  import type { Locale } from '../messages.ts'
9
- import { PmIconButton, PmNotice, PmTooltip } from '../components.tsx'
9
+ import { PmIcon, PmIconButton, PmNotice, PmTooltip } from '../components.tsx'
10
10
  import { DOCUMENT_NODE_VIEWS, documentEditorSchema } from './schema.tsx'
11
11
  import type { DocumentEditorBlock, DocumentEditorInput, DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
12
12
  import { documentSelection } from './selection.ts'
@@ -16,6 +16,7 @@ import { blockNoteDictionary } from './blocknote-messages.ts'
16
16
  import { imageFileInput } from './file-input.ts'
17
17
  import type { ImageImportFailure } from './file-input.ts'
18
18
  import { nativeTextClipboard } from './clipboard.ts'
19
+ import { documentPageBodies, focusDocumentEnd } from './page-body.ts'
19
20
  import { documentBlockColors } from './colors.ts'
20
21
  import { DOCUMENT_EDITOR_LOCALE } from './math.tsx'
21
22
  import { DOCUMENT_LINKS, DocumentColorButton, DocumentLinkToolbar, DocumentSideMenu, DocumentTableCellButton, DocumentTableHandle, FormulaToolbarButton, formulaSlashItems, openDocumentLink } from './authoring.tsx'
@@ -84,6 +85,8 @@ export interface BlockNoteSurfaceProps {
84
85
  onComposition?(composing: boolean): void
85
86
  /** Shows a page of this document from an in-document link; false when none matches. */
86
87
  onSectionLink?(sectionId: string): boolean
88
+ /** The slash menu's request to the AI for an animation where it was opened: it inserts nothing itself. */
89
+ animationRequest?: { available(): boolean, request(editor: NativeDocumentEditor): void }
87
90
  children?: ReactNode
88
91
  }
89
92
 
@@ -113,10 +116,11 @@ function PlainContentComments({ editor }: { editor: NativeDocumentEditor }) {
113
116
  return show && editor.getExtension('comments') ? <div className="pm-document-editor__comment-tools"><FormattingToolbar><AddCommentButton /></FormattingToolbar></div> : null
114
117
  }
115
118
 
116
- // Formulas join the group that holds tables so the menu keeps one heading per group.
117
- function withFormulas<Item extends { group?: string }>(items: Item[], formulas: Item[]): Item[] {
118
- const index = items.findLastIndex(item => item.group === formulas[0]?.group)
119
- return index < 0 ? [...items, ...formulas] : [...items.slice(0, index + 1), ...formulas, ...items.slice(index + 1)]
119
+ // Added items join the end of their group (formulas the one that holds tables, the animation request the one that holds
120
+ // pictures) so the menu keeps one heading per group.
121
+ function withGroupItems<Item extends { group?: string }>(items: Item[], added: Item[]): Item[] {
122
+ const index = items.findLastIndex(item => item.group === added[0]?.group)
123
+ return index < 0 ? [...items, ...added] : [...items.slice(0, index + 1), ...added, ...items.slice(index + 1)]
120
124
  }
121
125
 
122
126
  /** One native editor owns selection, transactions and history across the complete document. */
@@ -156,7 +160,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
156
160
  dictionary, tables: { splitCells: true, cellBackgroundColor: true, cellTextColor: true, headers: true },
157
161
  // The surface's own click handler opens links in editable and read-only states alike.
158
162
  links: { onClick: () => true },
159
- extensions: [nativeTextClipboard, documentBlockColors, imageFileInput({
163
+ extensions: [nativeTextClipboard, documentBlockColors, documentPageBodies(), imageFileInput({
160
164
  onStart: () => { if (current.current.identity === props.identity) setFileErrors(undefined) },
161
165
  onFailure: failure => { if (current.current.identity === props.identity) setFileErrors(value => ({ identity: props.identity, failures: [...(value?.identity === props.identity ? value.failures : []), failure] })) },
162
166
  }), ...props.comments ? [nativeCommentSelection(), nativeComments(props.comments, t.author)] : []],
@@ -196,7 +200,11 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
196
200
  <LinkToolbarController linkToolbar={DocumentLinkToolbar} floatingUIOptions={linkToolbarOptions} />
197
201
  <SideMenuController sideMenu={DocumentSideMenu} />
198
202
  <TableHandlesController tableHandle={DocumentTableHandle} tableCellHandle={DocumentTableCellButton} />
199
- <SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...withFormulas(getDefaultReactSlashMenuItems(editor), formulaSlashItems(editor, props.locale, dictionary.slash_menu.table.group)), {
203
+ <SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...withGroupItems(withGroupItems(getDefaultReactSlashMenuItems(editor), formulaSlashItems(editor, props.locale, dictionary.slash_menu.table.group)), current.current.animationRequest?.available() ? [{
204
+ title: t.animateWithAI, subtext: t.animateWithAIHint, group: dictionary.slash_menu.image.group, icon: <PmIcon name="sparkle" />, aliases: slashAliases('animateWithAIAliases'),
205
+ // The menu has already taken back the typed “/” and query; the AI is asked, the document stays as it was.
206
+ onItemClick: () => current.current.animationRequest?.request(editor),
207
+ }] : []), {
200
208
  title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
201
209
  onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: crypto.randomUUID() }, content: t.untitledPage }], current, 'after') },
202
210
  }], query)} />
@@ -204,6 +212,11 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
204
212
  </NewCommentDraftProvider></BlockNoteViewEditor>
205
213
  </ComponentsContext.Provider>
206
214
  </BlockNoteView>
215
+ <div className="pm-document-editor__end" aria-hidden="true" data-editable={props.readOnly ? undefined : ''} onMouseDown={event => {
216
+ if (event.button !== 0 || !editor.isEditable || editor.prosemirrorView.composing) return
217
+ event.preventDefault()
218
+ focusDocumentEnd(editor)
219
+ }} />
207
220
  </div>
208
221
  </COMMENT_EDITOR_CONTEXT.Provider></DOCUMENT_NODE_VIEWS.Provider></DOCUMENT_LINKS.Provider></DOCUMENT_EDITOR_LOCALE.Provider>
209
222
  }
@@ -14,15 +14,23 @@ import { captureTableIdentities, seedTableIdentities } from './table-identities.
14
14
  import type { DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
15
15
  import { nativeEditingCursor } from './selection.ts'
16
16
  import type { NativeDocumentSelection } from './selection.ts'
17
+ import { documentInsertionPlace } from './insertion-place.ts'
18
+ import type { DocumentInsertionPlace } from './insertion-place.ts'
17
19
 
18
20
  export interface DocumentEditingPosition {
19
21
  nativeBlockId: string
20
22
  sectionId: string
21
23
  position: number
22
24
  }
25
+ /** Who takes the slash menu's request for an animation where it was opened; while none is available the menu has no such item. */
26
+ export interface DocumentAnimationRequests {
27
+ available(): boolean
28
+ request(place: DocumentInsertionPlace): void
29
+ }
23
30
  export interface DocumentEditorCommands {
24
31
  insertPage(after: string | undefined, title: string): NativePageCreation
25
32
  rememberComponentConfiguration(document: TeachingDocument): void
33
+ handleAnimationRequests(requests: DocumentAnimationRequests | undefined): void
26
34
  }
27
35
 
28
36
  export interface DocumentEditorProps {
@@ -73,6 +81,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
73
81
  return () => comments.close()
74
82
  }, [comments])
75
83
  const current = useRef(props), editor = useRef<NativeDocumentEditor>(), unsubscribe = useRef<() => void>()
84
+ const animationRequests = useRef<DocumentAnimationRequests>()
76
85
  const projectedDocument = useRef<NativeDocumentEditor['prosemirrorState']['doc']>()
77
86
  const pendingTransaction = useRef<Transaction>()
78
87
  const focusFrame = useRef<number>()
@@ -125,7 +134,16 @@ export function DocumentEditor(props: DocumentEditorProps) {
125
134
  }
126
135
  return <BlockNoteSurface identity={props.identity} reset={props.reset} initialContent={projection.content} locale={props.locale} contentLang={props.document.metadata.lang || 'zh-CN'} readOnly={props.readOnly}
127
136
  resolveAssetURL={props.resolveAssetURL} uploadImage={props.uploadImage}
128
- comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection} onSectionLink={sectionId => {
137
+ comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
138
+ animationRequest={{
139
+ available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
140
+ request: value => {
141
+ if (value !== editor.current || binding.current !== projection || active.current !== projection) return
142
+ const place = documentInsertionPlace(value, projection)
143
+ if (place) animationRequests.current?.request(place)
144
+ },
145
+ }}
146
+ onSectionLink={sectionId => {
129
147
  if (!current.current.onSectionLink?.(sectionId)) return false
130
148
  // The click placed the caret in the link; it follows the reader to the page they asked for.
131
149
  const value = editor.current
@@ -162,7 +180,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
162
180
  })
163
181
  unsubscribe.current = () => { stopBefore(); stopComments(); stopSelection(); stopFocus(); cancelFocus() }
164
182
  }
165
- const commands: DocumentEditorCommands | undefined = value ? { rememberComponentConfiguration: document => {
183
+ const commands: DocumentEditorCommands | undefined = value ? { handleAnimationRequests: requests => { animationRequests.current = requests }, rememberComponentConfiguration: document => {
166
184
  if (editor.current === value && active.current === projection && binding.current === projection && !value.prosemirrorView.isDestroyed) rememberComponentConfiguration(projection, document)
167
185
  }, insertPage: (after, title) => {
168
186
  if (current.current.readOnly || editor.current !== value || active.current !== projection || binding.current !== projection || value.prosemirrorView.isDestroyed) throw new Error('page-context-changed')
@@ -0,0 +1,60 @@
1
+ import type { DocumentProjection } from './projection.ts'
2
+ import type { DocumentEditorBlock, NativeDocumentEditor } from './schema.tsx'
3
+
4
+ /** Where the caret is in the document, as a place for new content that the author and the AI can both name. */
5
+ export interface DocumentInsertionPlace {
6
+ sectionId: string
7
+ /** The block (its document ID) the caret is in, then the blocks holding it, innermost first. */
8
+ blocks: string[]
9
+ /** The text of the paragraph the caret is in, when it has any. */
10
+ text?: string
11
+ /**
12
+ * What new content follows: the caret's paragraph, or the content before it when the paragraph is empty, by its text
13
+ * ('' when that content has none). None at the start of the page.
14
+ */
15
+ after?: string
16
+ /** Nothing else follows on the page. */
17
+ end: boolean
18
+ }
19
+
20
+ type Inline = { type: string, text?: string, content?: unknown, props?: { label?: string } }
21
+
22
+ function inlineText(content: unknown): string {
23
+ if (typeof content === 'string') return content
24
+ if (!Array.isArray(content)) return ''
25
+ return (content as Inline[]).map(item => item.type === 'text' ? item.text ?? '' : item.type === 'presmiumInline' ? item.props?.label ?? '' : inlineText(item.content)).join('')
26
+ }
27
+
28
+ function textOf(block: DocumentEditorBlock): string {
29
+ const text = block.type === 'image' ? block.props.caption || block.props.name
30
+ : block.type === 'presmiumAtom' ? block.props.label
31
+ : block.type === 'presmiumContainer' ? block.props.title
32
+ : inlineText(block.content)
33
+ return text.replace(/\s+/g, ' ').trim()
34
+ }
35
+
36
+ // An empty paragraph (or heading, list item…) is where content can go, not content to follow.
37
+ const filled = (block: DocumentEditorBlock) => !Array.isArray(block.content) || block.content.length > 0
38
+
39
+ /** The place of the caret's block, as the slash menu opened in it; none on a page title. */
40
+ export function documentInsertionPlace(editor: NativeDocumentEditor, projection: Pick<DocumentProjection, 'owners' | 'pages'>): DocumentInsertionPlace | undefined {
41
+ const at = editor.getTextCursorPosition().block as DocumentEditorBlock
42
+ if (at.type === 'presmiumPage') return undefined
43
+ const order: DocumentEditorBlock[] = []
44
+ const visit = (blocks: readonly DocumentEditorBlock[]) => { for (const block of blocks) { order.push(block); visit(block.children) } }
45
+ visit(editor.document)
46
+ const index = order.findIndex(block => block.id === at.id)
47
+ const start = order.findLastIndex((block, i) => i < index && block.type === 'presmiumPage')
48
+ const page = order[start]
49
+ if (index < 0 || page?.type !== 'presmiumPage') return undefined
50
+ const next = order.findIndex((block, i) => i > index && block.type === 'presmiumPage')
51
+ const holders: DocumentEditorBlock[] = []
52
+ for (let block = editor.getParentBlock(at); block; block = editor.getParentBlock(block)) holders.push(block as DocumentEditorBlock)
53
+ const anchor = filled(at) ? at : order.slice(start + 1, index).reverse().find(block => filled(block) && !holders.some(holder => holder.id === block.id))
54
+ const text = textOf(at)
55
+ const blocks = [...new Set([at, ...holders].flatMap(block => projection.owners.get(block.id) ?? []))]
56
+ return {
57
+ sectionId: projection.pages.get(page.id) ?? page.props.sectionId, blocks, ...text ? { text } : {},
58
+ ...anchor ? { after: textOf(anchor) } : {}, end: !order.slice(index + 1, next < 0 ? undefined : next).some(filled),
59
+ }
60
+ }
@@ -4,11 +4,11 @@ export const IMAGE_IMPORT_MESSAGES = {
4
4
  }
5
5
 
6
6
  export const DOCUMENT_EDITOR_MESSAGES = {
7
- 'zh-CN': { colors: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', colorDefault: '默认', backgroundDefault: '无底色', colorNames: { muted: '灰色 · 次要', accent: '青色 · 强调', ok: '绿色 · 通过', warn: '橙色 · 提醒', danger: '红色 · 警示' }, backgroundNames: { muted: '灰底', accent: '青底', ok: '绿底', warn: '橙底', danger: '红底' }, formula: '公式', formulaInline: '行内公式', formulaBlock: '公式块', formulaInlineHint: '在文字中插入 LaTeX 公式', formulaBlockHint: '单独一行显示的 LaTeX 公式', openLink: '打开链接', goToSection: (title: string) => `跳到“${title}”`, mathEmpty: '插入公式', mathInvalid: '公式无法识别', mathPlaceholder: '输入 LaTeX 公式', commentRecoveryChanged: '已取消恢复草稿,当前输入已保留。', commentNewDraft: '新建批注', commentsEmpty: '还没有批注。选中正文中的文字,再选“新建批注”。', commentTargetUnavailable: '原选区已改变或不可用,草稿仍可恢复。', commentSessionOnly: '仅本次会话', commentDrafts: '批注草稿', commentChooseDraft: '请选择草稿', commentEditDraft: '编辑稿', commentReplyDraft: '回复稿', commentRecover: '恢复草稿', commentDiscard: '放弃草稿', commentBackupFailed: '最新的批注草稿只在本次会话中保留,请发布后再关闭窗口。', stepNarration: '讲稿', stepCaptions: '字幕', previousStep: '上一步', nextStep: '下一步', narrationStep: (step: number, total: number, title: string) => `第 ${step} / ${total} 步${title ? ` · ${title}` : ''}`, previewFailure: '预览失败', previewLoading: '正在更新预览…', previewPrevious: '上次已保存的预览', previewSnapshot: '文稿内预览', previewRetry: '重试', previewRefresh: '刷新', previewTitle: '内容块只读预览', comment: '新建批注', commentChanged: '这条批注已在别处修改。请先复制草稿,再取消以查看已保存的内容。', commentUnavailable: '无法确认这条批注的版本。请先复制草稿,再关闭并重新打开。', author: '作者', page: '新页面', document: '文稿', untitledPage: '未命名页面', opaque: '组件', animation: (title: string) => `动画:${title}`, component: (title: string) => `组件:${title}`, codeReference: (title: string) => `引用代码:${title}`, diagram: (title: string) => title ? `图表:${title}` : '图表', adapterError: '无法保存这次编辑。请保持页面打开,并查看诊断。', conflict: '文稿已在别处修改。草稿已保留,请先核对当前文稿,再重试或放弃草稿。', saveFailure: '文稿尚未确认保存,草稿已保留。请保持页面打开后重试。', restored: '已恢复尚未保存的草稿,请检查后重新保存或放弃。', loading: '正在加载文稿…', unavailable: '暂时无法加载文稿,请重试。', diagnostics: (count: number) => `${count} 项诊断`, formulaBlockAliases: '公式|数学', formulaInlineAliases: '行内公式|公式', pageAliases: '页面|章节' },
8
- en: { colors: 'Colors', textColor: 'Text color', backgroundColor: 'Highlight', colorDefault: 'Default', backgroundDefault: 'No highlight', colorNames: { muted: 'Gray · subtle', accent: 'Teal · accent', ok: 'Green · success', warn: 'Amber · caution', danger: 'Red · alert' }, backgroundNames: { muted: 'Gray', accent: 'Teal', ok: 'Green', warn: 'Amber', danger: 'Red' }, formula: 'Formula', formulaInline: 'Inline Formula', formulaBlock: 'Formula Block', formulaInlineHint: 'A LaTeX formula within the text', formulaBlockHint: 'A LaTeX formula on its own line', openLink: 'Open Link', goToSection: (title: string) => `Go to “${title}”`, mathEmpty: 'Insert Formula', mathInvalid: 'Formula not recognized', mathPlaceholder: 'Enter a LaTeX formula', commentRecoveryChanged: 'Draft recovery canceled. Your current input is kept.', commentNewDraft: 'New Comment', commentsEmpty: 'No comments yet. Select text in the document, then choose New Comment.', commentTargetUnavailable: 'The original selection changed or is unavailable. You can still recover your draft.', commentSessionOnly: 'This session only', commentDrafts: 'Comment drafts', commentChooseDraft: 'Choose a draft', commentEditDraft: 'Comment edit', commentReplyDraft: 'Reply', commentRecover: 'Recover Draft', commentDiscard: 'Discard Draft', commentBackupFailed: 'The latest comment draft is kept in this session only. Post it before closing this window.', stepNarration: 'Script', stepCaptions: 'Captions', previousStep: 'Previous Step', nextStep: 'Next Step', narrationStep: (step: number, total: number, title: string) => `Step ${step} / ${total}${title ? ` · ${title}` : ''}`, previewFailure: 'Preview failed', previewLoading: 'Updating preview…', previewPrevious: 'Last saved preview', previewSnapshot: 'Document preview', previewRetry: 'Retry', previewRefresh: 'Refresh', previewTitle: 'Read-only block preview', comment: 'New Comment', commentChanged: 'This comment changed elsewhere. Copy your draft, then cancel to view the saved comment.', commentUnavailable: 'Couldn’t confirm this comment’s version. Copy your draft before closing and reopening it.', author: 'Author', page: 'New Page', document: 'Document', untitledPage: 'Untitled page', opaque: 'Component', animation: (title: string) => `Animation: ${title}`, component: (title: string) => `Component: ${title}`, codeReference: (title: string) => `Referenced code: ${title}`, diagram: (title: string) => title ? `Diagram: ${title}` : 'Diagram', adapterError: 'Couldn’t save this edit. Keep this page open and check the diagnostics.', conflict: 'The document changed elsewhere. Your draft is kept; review the current document, then try again or discard your draft.', saveFailure: 'Couldn’t confirm the save. Your draft is kept; keep this page open and try again.', restored: 'A draft that was not saved was recovered. Review it, then save it again or discard it.', loading: 'Loading document…', unavailable: 'Couldn’t load the document. Try again.', diagnostics: (count: number) => `${count} ${count === 1 ? 'diagnostic' : 'diagnostics'}`, formulaBlockAliases: 'formula|math|equation|latex|tex', formulaInlineAliases: 'inline formula|inline math|latex|tex', pageAliases: 'page|section' },
7
+ 'zh-CN': { colors: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', colorDefault: '默认', backgroundDefault: '无底色', colorNames: { muted: '灰色 · 次要', accent: '青色 · 强调', ok: '绿色 · 通过', warn: '橙色 · 提醒', danger: '红色 · 警示' }, backgroundNames: { muted: '灰底', accent: '青底', ok: '绿底', warn: '橙底', danger: '红底' }, formula: '公式', formulaInline: '行内公式', formulaBlock: '公式块', formulaInlineHint: '在文字中插入 LaTeX 公式', formulaBlockHint: '单独一行显示的 LaTeX 公式', openLink: '打开链接', goToSection: (title: string) => `跳到“${title}”`, mathEmpty: '插入公式', mathInvalid: '公式无法识别', mathPlaceholder: '输入 LaTeX 公式', commentRecoveryChanged: '已取消恢复草稿,当前输入已保留。', commentNewDraft: '新建批注', commentsEmpty: '还没有批注。选中正文中的文字,再选“新建批注”。', commentTargetUnavailable: '原选区已改变或不可用,草稿仍可恢复。', commentSessionOnly: '仅本次会话', commentDrafts: '批注草稿', commentChooseDraft: '请选择草稿', commentEditDraft: '编辑稿', commentReplyDraft: '回复稿', commentRecover: '恢复草稿', commentDiscard: '放弃草稿', commentBackupFailed: '最新的批注草稿只在本次会话中保留,请发布后再关闭窗口。', stepNarration: '讲稿', stepCaptions: '字幕', previousStep: '上一步', nextStep: '下一步', narrationStep: (step: number, total: number, title: string) => `第 ${step} / ${total} 步${title ? ` · ${title}` : ''}`, previewFailure: '预览失败', previewLoading: '正在更新预览…', previewPrevious: '上次已保存的预览', previewSnapshot: '文稿内预览', previewRetry: '重试', previewRefresh: '刷新', previewTitle: '内容块只读预览', comment: '新建批注', commentChanged: '这条批注已在别处修改。请先复制草稿,再取消以查看已保存的内容。', commentUnavailable: '无法确认这条批注的版本。请先复制草稿,再关闭并重新打开。', author: '作者', page: '新页面', document: '文稿', untitledPage: '未命名页面', opaque: '组件', animation: (title: string) => `动画:${title}`, component: (title: string) => `组件:${title}`, codeReference: (title: string) => `引用代码:${title}`, diagram: (title: string) => title ? `图表:${title}` : '图表', adapterError: '无法保存这次编辑。请保持页面打开,并查看诊断。', conflict: '文稿已在别处修改。草稿已保留,请先核对当前文稿,再重试或放弃草稿。', saveFailure: '文稿尚未确认保存,草稿已保留。请保持页面打开后重试。', restored: '已恢复尚未保存的草稿,请检查后重新保存或放弃。', loading: '正在加载文稿…', unavailable: '暂时无法加载文稿,请重试。', diagnostics: (count: number) => `${count} 项诊断`, formulaBlockAliases: '公式|数学', formulaInlineAliases: '行内公式|公式', pageAliases: '页面|章节', animateWithAI: '用 AI 插入动画…', animateWithAIHint: '告诉 AI 这里的动画要演示什么', animateWithAIAliases: '动画|场景|演示' },
8
+ en: { colors: 'Colors', textColor: 'Text color', backgroundColor: 'Highlight', colorDefault: 'Default', backgroundDefault: 'No highlight', colorNames: { muted: 'Gray · subtle', accent: 'Teal · accent', ok: 'Green · success', warn: 'Amber · caution', danger: 'Red · alert' }, backgroundNames: { muted: 'Gray', accent: 'Teal', ok: 'Green', warn: 'Amber', danger: 'Red' }, formula: 'Formula', formulaInline: 'Inline Formula', formulaBlock: 'Formula Block', formulaInlineHint: 'A LaTeX formula within the text', formulaBlockHint: 'A LaTeX formula on its own line', openLink: 'Open Link', goToSection: (title: string) => `Go to “${title}”`, mathEmpty: 'Insert Formula', mathInvalid: 'Formula not recognized', mathPlaceholder: 'Enter a LaTeX formula', commentRecoveryChanged: 'Draft recovery canceled. Your current input is kept.', commentNewDraft: 'New Comment', commentsEmpty: 'No comments yet. Select text in the document, then choose New Comment.', commentTargetUnavailable: 'The original selection changed or is unavailable. You can still recover your draft.', commentSessionOnly: 'This session only', commentDrafts: 'Comment drafts', commentChooseDraft: 'Choose a draft', commentEditDraft: 'Comment edit', commentReplyDraft: 'Reply', commentRecover: 'Recover Draft', commentDiscard: 'Discard Draft', commentBackupFailed: 'The latest comment draft is kept in this session only. Post it before closing this window.', stepNarration: 'Script', stepCaptions: 'Captions', previousStep: 'Previous Step', nextStep: 'Next Step', narrationStep: (step: number, total: number, title: string) => `Step ${step} / ${total}${title ? ` · ${title}` : ''}`, previewFailure: 'Preview failed', previewLoading: 'Updating preview…', previewPrevious: 'Last saved preview', previewSnapshot: 'Document preview', previewRetry: 'Retry', previewRefresh: 'Refresh', previewTitle: 'Read-only block preview', comment: 'New Comment', commentChanged: 'This comment changed elsewhere. Copy your draft, then cancel to view the saved comment.', commentUnavailable: 'Couldn’t confirm this comment’s version. Copy your draft before closing and reopening it.', author: 'Author', page: 'New Page', document: 'Document', untitledPage: 'Untitled page', opaque: 'Component', animation: (title: string) => `Animation: ${title}`, component: (title: string) => `Component: ${title}`, codeReference: (title: string) => `Referenced code: ${title}`, diagram: (title: string) => title ? `Diagram: ${title}` : 'Diagram', adapterError: 'Couldn’t save this edit. Keep this page open and check the diagnostics.', conflict: 'The document changed elsewhere. Your draft is kept; review the current document, then try again or discard your draft.', saveFailure: 'Couldn’t confirm the save. Your draft is kept; keep this page open and try again.', restored: 'A draft that was not saved was recovered. Review it, then save it again or discard it.', loading: 'Loading document…', unavailable: 'Couldn’t load the document. Try again.', diagnostics: (count: number) => `${count} ${count === 1 ? 'diagnostic' : 'diagnostics'}`, formulaBlockAliases: 'formula|math|equation|latex|tex', formulaInlineAliases: 'inline formula|inline math|latex|tex', pageAliases: 'page|section', animateWithAI: 'Insert Animation with AI…', animateWithAIHint: 'Tell the AI what the animation here should show', animateWithAIAliases: 'animation|animate|scene|motion' },
9
9
  }
10
10
 
11
11
  /** Slash-menu search words (`|`-separated): an author finds an item by its name in either language, whatever the interface's. */
12
- export function slashAliases(key: 'formulaBlockAliases' | 'formulaInlineAliases' | 'pageAliases'): string[] {
12
+ export function slashAliases(key: 'formulaBlockAliases' | 'formulaInlineAliases' | 'pageAliases' | 'animateWithAIAliases'): string[] {
13
13
  return [...new Set([...DOCUMENT_EDITOR_MESSAGES.en[key].split('|'), ...DOCUMENT_EDITOR_MESSAGES['zh-CN'][key].split('|')])]
14
14
  }
@@ -0,0 +1,60 @@
1
+ import { createExtension } from '@blocknote/core'
2
+ import { Plugin, TextSelection } from '@tiptap/pm/state'
3
+ import type { EditorState } from '@tiptap/pm/state'
4
+ import { Decoration, DecorationSet } from '@tiptap/pm/view'
5
+ import type { Node } from '@tiptap/pm/model'
6
+ import type { NativeDocumentEditor } from './schema.tsx'
7
+
8
+ // Pages are top-level blocks: doc > blockGroup > blockContainer > (content, children?).
9
+ function emptyParagraph(container: Node | null | undefined): boolean {
10
+ return container?.childCount === 1 && container.firstChild!.type.name === 'paragraph' && container.firstChild!.content.size === 0
11
+ }
12
+
13
+ function pageEnds(doc: Node, placeholder: string): DecorationSet {
14
+ const group = doc.firstChild, found: Decoration[] = []
15
+ if (!group) return DecorationSet.empty
16
+ group.forEach((container, offset, index) => {
17
+ const next = index + 1 < group.childCount ? group.child(index + 1) : undefined
18
+ if (!emptyParagraph(container) || next && next.firstChild?.type.name !== 'presmiumPage') return
19
+ const start = 1 + offset + 1
20
+ found.push(Decoration.node(start, start + container.firstChild!.nodeSize, { 'data-page-end': '', 'data-placeholder': placeholder }))
21
+ })
22
+ return DecorationSet.create(doc, found)
23
+ }
24
+
25
+ /**
26
+ * A page's empty last paragraph shows the editor's placeholder even without the caret, so an empty body is visible;
27
+ * Enter at the end of a title goes into that paragraph instead of adding another one before it.
28
+ */
29
+ export const documentPageBodies = createExtension(({ editor }: { editor: NativeDocumentEditor }) => ({
30
+ key: 'presmium-document-page-bodies',
31
+ prosemirrorPlugins: [new Plugin<DecorationSet>({
32
+ state: {
33
+ init: (_, state: EditorState) => pageEnds(state.doc, editor.dictionary.placeholders.default ?? ''),
34
+ apply: (transaction, value) => transaction.docChanged ? pageEnds(transaction.doc, editor.dictionary.placeholders.default ?? '') : value,
35
+ },
36
+ props: { decorations(state) { return editor.isEditable ? this.getState(state) : undefined } },
37
+ })],
38
+ keyboardShortcuts: {
39
+ Enter: () => {
40
+ const { selection } = editor.prosemirrorState, { $head } = selection
41
+ if (!editor.isEditable || !selection.empty || $head.parent.type.name !== 'presmiumPage' || $head.parentOffset !== $head.parent.content.size) return false
42
+ const after = $head.after($head.depth - 1)
43
+ if (!emptyParagraph(editor.prosemirrorState.doc.resolve(after).nodeAfter)) return false
44
+ editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, after + 2)).scrollIntoView())
45
+ return true
46
+ },
47
+ },
48
+ }))
49
+
50
+ /** The caret at the end of the document: in its empty last paragraph, or in a new one after the last block. */
51
+ export function focusDocumentEnd(editor: NativeDocumentEditor): void {
52
+ const last = editor.document.at(-1)
53
+ if (!last) return
54
+ editor.transact(transaction => {
55
+ if (last.type === 'paragraph' && !last.children.length && !last.content.length) editor.setTextCursorPosition(last, 'end')
56
+ else editor.setTextCursorPosition(editor.insertBlocks([{ type: 'paragraph' }], last, 'after')[0]!, 'start')
57
+ transaction.scrollIntoView()
58
+ })
59
+ editor.focus()
60
+ }
@@ -120,6 +120,19 @@ export function nativeTextPosition(editor: NativeDocumentEditor, point: { blockI
120
120
  return nativeTextPositionInDocument(editor.prosemirrorState.doc, point)
121
121
  }
122
122
 
123
+ /** The native range of a block's whole inline text, to select it. */
124
+ export function nativeBlockText(editor: NativeDocumentEditor, blockId: string): { from: number, to: number } | undefined {
125
+ let range: { from: number, to: number } | undefined
126
+ editor.prosemirrorState.doc.descendants((node, beforePos) => {
127
+ if (range) return false
128
+ if (node.attrs.id !== blockId) return
129
+ const info = getBlockInfoFromNode(node, beforePos)
130
+ if (info.hasContent && info.contentKind === 'inline') range = { from: info.contentStart, to: info.contentEnd }
131
+ return false
132
+ })
133
+ return range
134
+ }
135
+
123
136
  /** Stable anchor lookup against a captured native transaction’s input document. */
124
137
  export function nativeTextPositionInDocument(document: ProseMirrorNode, point: { blockId: string, offset: number }): number | undefined {
125
138
  let position: number | undefined
@@ -1,4 +1,8 @@
1
- .pm-document-editor { min-width: 0; }
1
+ .pm-document-editor { display: flex; flex: 1 0 auto; flex-direction: column; min-width: 0; }
2
+ /* The page below the last block, down to the sheet's end: a press there continues the document at its end. */
3
+ .pm-document-editor__end { flex: 1 0 auto; min-height: var(--pm-space-4); }
4
+ .pm-document-editor__end[data-editable] { cursor: text; }
5
+ .pm-document-editor .bn-block-content[data-page-end]:has(.ProseMirror-trailingBreak:only-child)::after { content: attr(data-placeholder); }
2
6
  .pm-document-editor__file-errors { display: flex; align-items: flex-start; gap: var(--pm-space-2); }
3
7
  .pm-document-editor__file-errors ul { flex: 1; min-width: 0; margin: 0; padding-inline-start: var(--pm-space-4); overflow-wrap: anywhere; }
4
8
  .pm-document-editor .pm-document-editor__page-title { margin-block: var(--pm-space-5) var(--pm-space-3); font-family: var(--pm-font-sans); font-size: var(--pm-text-title); font-weight: var(--pm-weight-semibold); line-height: var(--pm-leading-tight); }
package/src/messages.ts CHANGED
@@ -12,6 +12,11 @@ export interface AgentPlace {
12
12
 
13
13
  // A Latin word or a number set after Chinese text is spaced from it (docs/glossary.md 2).
14
14
  const spaced = (text: string) => (/^[A-Za-z0-9]/.test(text) ? ` ${text}` : text)
15
+ // The start of a passage, enough to recognize it.
16
+ const excerpt = (text: string, length: number) => [...text].length > length ? `${[...text].slice(0, length).join('').trimEnd()}…` : text
17
+
18
+ /** Where on a page the author asks for new content: after a passage (its text, '' for content without text), at the start (none) or at the end. */
19
+ interface AgentInsertion { after?: string, end: boolean }
15
20
 
16
21
  // Names of commands follow Microsoft Word's (撤消/Undo, 新建批注/New Comment, 版本历史/Version History…).
17
22
  const zh = {
@@ -329,7 +334,8 @@ const zh = {
329
334
  agentWaiting: (n: number) => `AI 修改了 ${n} 处内容,要接受这些修改吗?`,
330
335
  accept: '接受',
331
336
  reject: '拒绝',
332
- problems: (n: number) => `有 ${n} 处内容无法正确显示。`,
337
+ problems: (n: number) => `文稿有 ${n} 个问题需要处理。`,
338
+ problemsTitle: '文稿中的问题',
333
339
  fixWithAi: '用 AI 修复',
334
340
  fixing: '正在发送给 AI…',
335
341
  fixFailed: (reason: string) => `无法发送给 AI。${reason}`,
@@ -356,6 +362,11 @@ const zh = {
356
362
  place.quote ? `\n原文:“${place.quote}”` : '',
357
363
  ].join('')).filter(Boolean),
358
364
  ].join('\n\n'),
365
+ animationRequest: (page: number, title: string, place: AgentInsertion) => {
366
+ const at = `第 ${page} 页${title ? `“${title}”` : ''}`
367
+ return place.end ? `在${at}的末尾加一个动画:` : place.after === undefined ? `在${at}的开头加一个动画:`
368
+ : place.after ? `在${at}中“${excerpt(place.after, 16)}”这一段之后加一个动画:` : `在${at}的这个位置加一个动画:`
369
+ },
359
370
  commentsRequest: (comments: (AgentPlace & { text: string })[]) => [
360
371
  comments.length === 1 ? '我在文稿上写了一条批注:' : `我在文稿上写了 ${comments.length} 条批注:`,
361
372
  ...comments.map((comment, i) => [
@@ -693,7 +704,8 @@ const en: WorkbenchMessages = {
693
704
  agentWaiting: (n: number) => `The AI changed ${n} file${n === 1 ? '' : 's'}. Accept the changes?`,
694
705
  accept: 'Accept',
695
706
  reject: 'Reject',
696
- problems: (n: number) => `${n} item${n === 1 ? '' : 's'} can’t be displayed correctly.`,
707
+ problems: (n: number) => `The document has ${n} problem${n === 1 ? '' : 's'} to fix.`,
708
+ problemsTitle: 'Problems in the Document',
697
709
  fixWithAi: 'Fix with AI',
698
710
  fixing: 'Sending to the AI…',
699
711
  fixFailed: (reason: string) => `Couldn’t send to the AI. ${reason}`,
@@ -720,6 +732,11 @@ const en: WorkbenchMessages = {
720
732
  place.quote ? `\nText: “${place.quote}”` : '',
721
733
  ].join('')).filter(Boolean),
722
734
  ].join('\n\n'),
735
+ animationRequest: (page: number, title: string, place: AgentInsertion) => {
736
+ const at = `page ${page}${title ? `, “${title}”` : ''}`
737
+ return place.end ? `Add an animation at the end of ${at}: ` : place.after === undefined ? `Add an animation at the start of ${at}: `
738
+ : place.after ? `Add an animation on ${at}, after the paragraph “${excerpt(place.after, 40)}”: ` : `Add an animation at this point on ${at}: `
739
+ },
723
740
  commentsRequest: (comments: (AgentPlace & { text: string })[]) => [
724
741
  comments.length === 1 ? 'I left a comment on the document:' : `I left ${comments.length} comments on the document:`,
725
742
  ...comments.map((comment, i) => [
@@ -1,6 +1,6 @@
1
1
  import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { ReactNode, RefObject } from 'react'
3
- import { PmButton, PmIconButton, PmMascot, PmMenu, PmNotice, PmSkeleton, PmSortableList, PmToolbar, PmToolbarButton } from '../components.tsx'
3
+ import { PmButton, PmDialog, PmIconButton, PmMascot, PmMenu, PmNotice, PmSkeleton, PmSortableList, PmToolbar, PmToolbarButton } from '../components.tsx'
4
4
  import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
5
  import { failureReason, timeAgo } from '../messages.ts'
6
6
  import { SHORTCUTS } from '../shortcuts.ts'
@@ -431,7 +431,7 @@ function DocumentNotices() {
431
431
  )
432
432
  }
433
433
 
434
- /** Content that did not display, said plainly, with the AI to fix it and the details for whoever wants them. */
434
+ /** The document's problems in one line above the page, with the AI to fix them; the list itself opens in a dialog. */
435
435
  function ProblemsNotice() {
436
436
  const t = useMessages()
437
437
  const workbench = useWorkbench()
@@ -440,23 +440,25 @@ function ProblemsNotice() {
440
440
  const canRepair = useWorkbenchState(state => state.canRepairDiagnostics)
441
441
  const repairing = useWorkbenchState(state => state.isRepairingDiagnostics)
442
442
  const repairFailure = useWorkbenchState(state => state.diagnosticsRepairFailure)
443
+ const [open, setOpen] = useState(false)
443
444
  if (workbench.client.capabilities?.diagnostics === 'none') return null
444
445
  const problems = (snapshot?.diagnostics ?? []).filter(diagnostic => diagnostic.severity === 'error' && !diagnostic.checkId.startsWith('presmium.workbench.'))
445
446
  if (unavailable) return <PmNotice tone="warn"><span>{t.diagnosticsUnavailable}</span><PmButton small onClick={() => workbench.retryDiagnostics()}>{t.retry}</PmButton></PmNotice>
446
447
  if (problems.length === 0) return repairFailure ? <PmNotice tone="danger">{t.fixFailed(failureReason(t, repairFailure))}</PmNotice> : null
448
+ const repair = canRepair && <PmButton small variant="accent" icon="sparkle" disabled={repairing} onClick={() => void workbench.requestRepairDiagnostics()}>{repairing ? t.fixing : t.fixWithAi}</PmButton>
447
449
  return (
448
450
  <PmNotice tone="warn">
449
451
  <div className="pmw-problems">
450
452
  <div className="pmw-problems__summary">
451
453
  <span>{t.problems(problems.length)}</span>
452
- {canRepair && <PmButton small variant="accent" icon="sparkle" disabled={repairing} onClick={() => void workbench.requestRepairDiagnostics()}>{repairing ? t.fixing : t.fixWithAi}</PmButton>}
454
+ <PmButton small variant="ghost" onClick={() => setOpen(true)}>{t.details}</PmButton>
455
+ {repair}
453
456
  </div>
454
457
  {repairFailure && <p className="pmw-problems__failure">{t.fixFailed(failureReason(t, repairFailure))}</p>}
455
- <details className="pmw-problems__details">
456
- <summary>{t.details}</summary>
457
- <ul>{problems.map(problem => <li key={problem.id}>{problem.message}</li>)}</ul>
458
- </details>
459
458
  </div>
459
+ <PmDialog open={open} label={t.problemsTitle} closeLabel={t.close} actions={repair || undefined} onClose={() => setOpen(false)}>
460
+ <ul className="pmw-problems__list">{problems.map(problem => <li key={problem.id}><p>{problem.message}</p>{problem.hint && <p className="pmw-problems__hint">{problem.hint}</p>}</li>)}</ul>
461
+ </PmDialog>
460
462
  </PmNotice>
461
463
  )
462
464
  }
package/src/styles.css CHANGED
@@ -265,20 +265,24 @@
265
265
  color: var(--pm-color-danger);
266
266
  }
267
267
 
268
- .pmw-problems__details summary {
269
- color: var(--pm-color-muted);
270
- font-size: var(--pm-text-xs);
271
- cursor: pointer;
272
- }
273
-
274
- .pmw-problems__details ul {
275
- margin: var(--pm-space-1) 0 0;
268
+ .pmw-problems__list {
269
+ display: flex;
270
+ flex-direction: column;
271
+ gap: var(--pm-space-3);
272
+ margin: 0;
276
273
  padding-left: var(--pm-space-4);
277
- font-family: var(--pm-font-mono);
278
- font-size: var(--pm-text-xs);
279
274
  overflow-wrap: anywhere;
280
275
  }
281
276
 
277
+ .pmw-problems__list p {
278
+ margin: 0;
279
+ }
280
+
281
+ .pmw-problems__hint {
282
+ color: var(--pm-color-muted);
283
+ font-size: var(--pm-text-sm);
284
+ }
285
+
282
286
  .pmw-document__body {
283
287
  display: flex;
284
288
  flex: 1;
@@ -931,7 +935,8 @@
931
935
  .pmw-source-document__recovery { display: grid; gap: var(--pm-space-2); min-width: 0; }
932
936
  .pmw-source-document__recovery-actions { display: flex; flex-wrap: wrap; gap: var(--pm-space-2); }
933
937
  .pmw-source-document__diagnostics { margin-block-end: var(--pm-space-3); }
934
- .pmw-source-document__sheet { position: relative; max-width: var(--pm-sheet-width); min-height: 100%; margin-inline: auto; padding-block: var(--pm-space-4); background: var(--pm-color-surface); box-shadow: var(--pm-shadow-page); }
938
+ /* Its end margin is the editor's own end area, which fills the rest of the sheet and takes the presses below the last block. */
939
+ .pmw-source-document__sheet { position: relative; display: flex; flex-direction: column; max-width: var(--pm-sheet-width); min-height: 100%; margin-inline: auto; padding-block-start: var(--pm-space-4); background: var(--pm-color-surface); box-shadow: var(--pm-shadow-page); }
935
940
  /* Opening: the page's own margins, so that the placeholder lines sit where the text will. */
936
941
  .pmw-source-document__sheet--loading { box-sizing: border-box; padding: var(--pm-space-10) var(--pm-space-12); }
937
942
  .pmw-voice__filters { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--pm-space-3); }
package/src/workbench.ts CHANGED
@@ -26,7 +26,8 @@ import type { DocumentReturnPoint } from './document-return-point.ts'
26
26
  import type { DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioImportAnswer, DocumentAudioInspectionAnswer, DocumentChangeAnswer, MediaClip, NarrationNode, TeachingDocument, DocumentTranscriptionRequest, TranscriptionTask, TranscriptionAdoptionDraft, TranscriptionAdoptionApply, TranscriptionAdoptionPlan, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
27
27
  import type { NativeDocumentEditor } from './document-editor/schema.tsx'
28
28
  import type { DocumentEditorCommands } from './document-editor/DocumentEditor.tsx'
29
- import { nativeTextPoint, nativeTextPosition } from './document-editor/selection.ts'
29
+ import type { DocumentInsertionPlace } from './document-editor/insertion-place.ts'
30
+ import { nativeBlockText, nativeTextPoint, nativeTextPosition } from './document-editor/selection.ts'
30
31
  import type { NativeTextPoint } from './document-editor/selection.ts'
31
32
  import type { DocumentFieldBookmark, DocumentFieldRegistration, DocumentHistoryEditor } from './document-editor/focus.ts'
32
33
  import { duplicateDocumentPage, moveDocumentPage, pageDeletion, removeDocumentPage, renameDocumentPage } from '@lincyaw/kernel'
@@ -99,6 +100,12 @@ export interface AgentRequest {
99
100
  focus: FocusReport[]
100
101
  }
101
102
 
103
+ /** A request for the author to finish and send in the conversation, and what it is about: the host only shows it. */
104
+ export interface AgentDraft {
105
+ text: string
106
+ focus: FocusReport[]
107
+ }
108
+
102
109
  /** Where the host put a request: the conversation's session and the request's id, which its user message carries. */
103
110
  export interface AgentAnswer {
104
111
  session: string
@@ -307,6 +314,7 @@ export class Workbench {
307
314
  readonly #jobs: DocumentJobs
308
315
  readonly #voiceover: VoiceoverJobs
309
316
  readonly #askers = new Set<(request: AgentRequest) => Promise<AgentAnswer | void>>()
317
+ readonly #drafters = new Set<(draft: AgentDraft) => void | Promise<void>>()
310
318
  readonly #previewSinks = new Set<PreviewSink>()
311
319
  readonly #playbackKeys = new Set<(command: PlaybackKey) => void>()
312
320
  #unsubscribeIr?: () => void
@@ -506,6 +514,12 @@ export class Workbench {
506
514
  return () => this.#askers.delete(asker)
507
515
  }
508
516
 
517
+ /** The host's way to put a request in the conversation's composer for the author to finish; nothing is sent. */
518
+ onAgentDraft = (drafter: (draft: AgentDraft) => void | Promise<void>): (() => void) => {
519
+ this.#drafters.add(drafter)
520
+ return () => this.#drafters.delete(drafter)
521
+ }
522
+
509
523
  #nextDocumentPosition(): string { return `${this.#positionSeed}:${++this.#positionSequence}` }
510
524
 
511
525
  #restoredDocumentPosition(source: DocumentSessionState): boolean {
@@ -1749,12 +1763,16 @@ export class Workbench {
1749
1763
  if (editor.prosemirrorView.hasFocus()) focus()
1750
1764
  const stopSelection = editor.onSelectionChange(() => { this.#documentSelectionGeneration++ })
1751
1765
  this.#unsubscribeDocumentSelection = () => { this.#stopDocumentLayoutScroll?.(); stopSelection(); element.removeEventListener('focusin', focus) }
1766
+ commands?.handleAnimationRequests({ available: () => this.#drafters.size > 0, request: place => this.draftAnimation(place) })
1752
1767
  } else this.#unsubscribeDocumentSelection = undefined
1753
1768
  this.#finishOpeningDocument()
1754
1769
  }
1755
- #focusDocumentNode(editor: NativeDocumentEditor, nodeId: string): void {
1770
+ /** `selectText`: the node's whole text is selected, so typing replaces it. */
1771
+ #focusDocumentNode(editor: NativeDocumentEditor, nodeId: string, selectText = false): void {
1756
1772
  this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
1757
1773
  editor.setTextCursorPosition(nodeId, 'start')
1774
+ const text = selectText ? nativeBlockText(editor, nodeId) : undefined
1775
+ if (text) editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, text.from, text.to)))
1758
1776
  editor.focus()
1759
1777
  editor.prosemirrorView.dispatch(editor.prosemirrorState.tr.scrollIntoView())
1760
1778
  // React node views can finish sizing after the native editor mounts.
@@ -1888,7 +1906,8 @@ export class Workbench {
1888
1906
  const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
1889
1907
  this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
1890
1908
  this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: crypto.randomUUID() } })
1891
- this.#focusDocumentNode(editor, created.nodeId)
1909
+ // The default title is selected: the author's first words name the page, and Enter goes on to its body.
1910
+ this.#focusDocumentNode(editor, `page:${created.sectionId}`, true)
1892
1911
  return true
1893
1912
  } catch (error) { this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
1894
1913
  }
@@ -1966,6 +1985,40 @@ export class Workbench {
1966
1985
  }
1967
1986
  }
1968
1987
 
1988
+ /**
1989
+ * Opens the conversation with a request, for the author to describe and send, to add an animation at `place` of the
1990
+ * open document; the document's focus points the AI at the place's block. Nothing is inserted or sent.
1991
+ */
1992
+ draftAnimation(place: DocumentInsertionPlace): boolean {
1993
+ const document = this.#state.document, content = this.#state.authoring?.content, drafter = [...this.#drafters][0]
1994
+ const section = content?.sections[place.sectionId]
1995
+ if (document === undefined || !content || !section || !drafter) return false
1996
+ const report = (block?: string): FocusReport => ({ id: 'insertion', from: this.#state.previewRenderer, section: place.sectionId, ...block ? { block } : {}, ...place.text ? { quote: place.text.slice(0, 2000) } : {} })
1997
+ const text = this.#messages.animationRequest(content.sectionOrder.indexOf(place.sectionId) + 1, section.title, place)
1998
+ const focus = [report(place.blocks[0])]
1999
+ void this.#focusFirst(document, [...place.blocks.map(block => [report(block)]), [report()], []])
2000
+ const drafted = (attributes: Record<string, OperationValue>) => this.#record('agent.draft', { 'presmium.ask.kind': 'animation', 'presmium.ask.text': text, 'presmium.section': place.sectionId, 'presmium.block': place.blocks[0], ...attributes })
2001
+ this.#set({ askFailure: undefined })
2002
+ void (async () => drafter({ text, focus }))().then(() => drafted({ 'presmium.outcome': 'drafted' }), (error: unknown) => {
2003
+ drafted({ 'presmium.outcome': 'failed', 'presmium.error': errorMessage(error) })
2004
+ if (this.#state.document === document) this.#set({ askFailure: errorMessage(error) })
2005
+ })
2006
+ return true
2007
+ }
2008
+
2009
+ /**
2010
+ * Sets the first of `choices` the service can locate as the document's focus. Its runtime snapshot is compiled from the
2011
+ * saved source, which may not have a block or page created moments ago yet; the last choice leaves no stale focus.
2012
+ */
2013
+ async #focusFirst(document: string, choices: FocusReport[][]): Promise<void> {
2014
+ for (const focus of choices) {
2015
+ this.setFocus(focus)
2016
+ const version = this.#focusVersion
2017
+ await this.#focusWriting
2018
+ if (version !== this.#focusVersion || this.#state.document !== document || !this.#state.focusFailure) return
2019
+ }
2020
+ }
2021
+
1969
2022
  /** A place as the author sees it: the section's title and the passage. */
1970
2023
  #describe(item: FocusReport & Partial<Focus>): AgentPlace {
1971
2024
  const doc = this.#state.ir?.doc