@lincyaw/workbench 0.2.0-rc.3 → 0.2.0-rc.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/authoring-client.ts +3 -3
  4. package/src/authoring-draft-fragment.ts +3 -1
  5. package/src/component-property-drafts.ts +5 -5
  6. package/src/components.tsx +10 -28
  7. package/src/document-drafts.ts +6 -7
  8. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  9. package/src/document-editor/ComponentMaterials.tsx +3 -9
  10. package/src/document-editor/ComponentPropertiesDialog.tsx +3 -3
  11. package/src/document-editor/DocumentBlockPreview.tsx +2 -0
  12. package/src/document-editor/DocumentComments.tsx +58 -9
  13. package/src/document-editor/DocumentEditor.tsx +44 -7
  14. package/src/document-editor/DocumentStepNarration.tsx +2 -1
  15. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  16. package/src/document-editor/PlaceComment.tsx +150 -0
  17. package/src/document-editor/comment-drafts.ts +16 -14
  18. package/src/document-editor/comments.ts +30 -10
  19. package/src/document-editor/component-label.ts +11 -0
  20. package/src/document-editor/file-input.ts +2 -2
  21. package/src/document-editor/insertion-place.ts +60 -0
  22. package/src/document-editor/messages.ts +3 -3
  23. package/src/document-editor/narration-schema.tsx +3 -2
  24. package/src/document-editor/page-body.ts +60 -0
  25. package/src/document-editor/projection.ts +2 -2
  26. package/src/document-editor/rich-text.ts +3 -2
  27. package/src/document-editor/selection.ts +13 -0
  28. package/src/document-editor/style.css +12 -1
  29. package/src/document-editor/table-identities.ts +2 -1
  30. package/src/document-session.ts +50 -16
  31. package/src/history.ts +2 -2
  32. package/src/index.ts +0 -3
  33. package/src/messages.ts +19 -4
  34. package/src/panels/DocumentView.tsx +10 -10
  35. package/src/panels/ExportPanel.tsx +1 -6
  36. package/src/panels/PreviewPanel.tsx +1 -4
  37. package/src/panels/ProductionCaptionSize.tsx +20 -0
  38. package/src/panels/ProductionCaptionTiming.tsx +3 -3
  39. package/src/panels/ProductionMediaClips.tsx +2 -1
  40. package/src/panels/ProductionPanel.tsx +5 -1
  41. package/src/panels/ProductionRecordingRange.tsx +2 -2
  42. package/src/panels/ProductionTimeline.tsx +6 -1
  43. package/src/panels/ProductionTranscription.tsx +2 -1
  44. package/src/panels/SourceDocumentPanel.tsx +3 -6
  45. package/src/panels/TranscriptionAdoption.tsx +4 -4
  46. package/src/places.ts +1 -36
  47. package/src/production-messages.ts +6 -0
  48. package/src/sha256.ts +9 -0
  49. package/src/styles.css +16 -41
  50. package/src/workbench.ts +80 -33
  51. package/src/workspace-client.ts +2 -1
  52. package/src/assistant-mascot.ts +0 -62
  53. package/src/mascot-preference.ts +0 -37
  54. package/src/panels/ChangeTrail.tsx +0 -79
@@ -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: '新建批注', stepComment: (step: number) => `在第 ${step} 步批注`, stepCommentHint: (step: number, count: number) => count ? `第 ${step} 步 · ${count} 条未解决批注` : `在第 ${step} 步批注`, stepCommentSave: '保存批注', stepCommentCancel: '取消', stepCommentFailed: '无法保存这条批注,请重试。', stepCommentPlaceholder: '写下这里要改的地方', stepCommentStep: '批注位置', stepCommentWhole: '整个内容块', stepCommentOption: (step: number, title: string) => title ? `第 ${step} 步 · ${title}` : `第 ${step} 步`, placeCommentReference: (label: string, step?: number) => step ? `“${label}” · 第 ${step} 步` : `“${label}”`, block: '内容块', 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, or use Comment on step in an animation or chart toolbar.', 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', stepComment: (step: number) => `Comment on step ${step}`, stepCommentHint: (step: number, count: number) => count ? `Step ${step} · ${count} unresolved` : `Comment on step ${step}`, stepCommentSave: 'Save Comment', stepCommentCancel: 'Cancel', stepCommentFailed: 'Couldn’t save this comment. Try again.', stepCommentPlaceholder: 'Write what should change here', stepCommentStep: 'Comment on', stepCommentWhole: 'The whole content block', stepCommentOption: (step: number, title: string) => title ? `Step ${step} · ${title}` : `Step ${step}`, placeCommentReference: (label: string, step?: number) => step ? `“${label}” · Step ${step}` : `“${label}”`, block: 'Content block', 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
  }
@@ -6,6 +6,7 @@ import { Extension } from '@tiptap/core'
6
6
  import { Plugin } from '@tiptap/pm/state'
7
7
  import { Fragment, Slice } from '@tiptap/pm/model'
8
8
  import type { Node } from '@tiptap/pm/model'
9
+ import { randomUUID } from '@lincyaw/kernel'
9
10
  import { PmButton, PmDialog, PmInput } from '../components.tsx'
10
11
  import type { Locale } from '../messages.ts'
11
12
 
@@ -56,7 +57,7 @@ const cueIdentities = createExtension({
56
57
  const copied = (fragment: Fragment): Fragment => {
57
58
  const nodes: Node[] = []
58
59
  fragment.forEach(node => nodes.push(node.type.name === 'narrationAtom' && node.attrs.kind === 'cue'
59
- ? node.type.create({ ...node.attrs, cueId: crypto.randomUUID() }, node.content, node.marks)
60
+ ? node.type.create({ ...node.attrs, cueId: randomUUID() }, node.content, node.marks)
60
61
  : node.isLeaf ? node : node.copy(copied(node.content))))
61
62
  return Fragment.fromArray(nodes)
62
63
  }
@@ -67,7 +68,7 @@ const cueIdentities = createExtension({
67
68
  state.doc.descendants((node, position) => {
68
69
  if (node.type.name !== 'narrationAtom' || node.attrs.kind !== 'cue') return
69
70
  const id = node.attrs.cueId as string
70
- if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: crypto.randomUUID() })
71
+ if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: randomUUID() })
71
72
  else seen.add(id)
72
73
  })
73
74
  return transaction.docChanged ? transaction : null
@@ -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
+ }
@@ -1,4 +1,4 @@
1
- import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING } from '@lincyaw/kernel'
1
+ import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING, randomUUID } from '@lincyaw/kernel'
2
2
  import type { DocumentBlock, DocumentPageIds, NarrationNode, RichTextNode, Section, TeachingDocument, TextBlock } from '@lincyaw/kernel'
3
3
  import { productInlineToNative } from './inline.ts'
4
4
  import { captureRichBaseline, createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
@@ -17,7 +17,7 @@ export interface DocumentProjection extends RichProjection {
17
17
  componentConfiguration: Map<string, string>
18
18
  }
19
19
  export type NativePageCreation = DocumentPageIds
20
- const newId = () => crypto.randomUUID()
20
+ const newId = () => randomUUID()
21
21
  export const pageId = (sectionId: string) => `page:${sectionId}`
22
22
  function plain(nodes: readonly { type: string, text?: string, children?: readonly unknown[] }[]): string {
23
23
  return nodes.map(node => node.type === 'text' ? node.text ?? '' : node.type === 'break' ? '\n' : node.children ? plain(node.children as Parameters<typeof plain>[0]) : '').join('')
@@ -1,4 +1,5 @@
1
1
  import type { InlineNode, JsonValue, ListItemNode, RichTextNode, TableNode } from '@lincyaw/kernel'
2
+ import { randomUUID } from '@lincyaw/kernel'
2
3
  import type { TableCellProps } from '@blocknote/core'
3
4
  import { nativeInlineToProduct, nativeTextStyleToProduct, productInlineToNative, productTextStyleToNative } from './inline.ts'
4
5
  import type { InlineProjectionContext, NativeInline } from './inline.ts'
@@ -27,12 +28,12 @@ export interface RichProjection extends InlineProjectionContext {
27
28
  tables: Map<string, { id: string, cells: string[] }[]>
28
29
  }
29
30
  export function createRichProjection(): RichProjection {
30
- return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => crypto.randomUUID() }
31
+ return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => randomUUID() }
31
32
  }
32
33
  export function captureRichBaseline(blocks: readonly DocumentEditorBlock[], context: RichProjection): void {
33
34
  for (const block of blocks) { context.baseline.set(block.id, JSON.stringify(block)); captureRichBaseline(block.children, context) }
34
35
  }
35
- const id = () => crypto.randomUUID()
36
+ const id = () => randomUUID()
36
37
  const atom = (node: RichTextNode): DocumentEditorInput => ({ id: node.id, type: 'presmiumAtom', props: { entityId: node.id, kind: `rich:${node.type}`, label: node.type === 'extension' ? fallbackText(node.fallback) : fallbackText(node) } })
37
38
 
38
39
  /** The projection records structural identities; the saved document owns all content. */
@@ -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); }
@@ -7,3 +11,10 @@
7
11
  .pm-document-editor__fallback { display: grid; gap: var(--pm-space-2); min-width: 0; }
8
12
  .pm-document-editor__fallback p { margin: 0; white-space: pre-wrap; }
9
13
  .pm-document-editor__comment-tools { position: sticky; top: var(--pm-space-2); z-index: var(--pm-z-site-header); width: fit-content; margin-inline-start: var(--pm-space-5); }
14
+
15
+ /* A place comment's popover: the comment editor, a position picker and its actions. */
16
+ .pm-document-place-comment { width: min(var(--pm-comment-width), calc(100vw - var(--pm-space-8))); }
17
+ .pm-document-place-comment__body { display: grid; gap: var(--pm-space-2); min-width: 0; }
18
+ .pm-document-place-comment__editor { min-width: 0; }
19
+ .pm-document-place-comment__editor .bn-editor { max-height: min(var(--pm-comment-editor-max-height), 45vh); overflow-y: auto; overflow-wrap: anywhere; }
20
+ .pm-document-place-comment__actions { display: flex; justify-content: end; gap: var(--pm-space-2); }
@@ -1,6 +1,7 @@
1
1
  import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
2
2
  import { Extension } from '@tiptap/core'
3
3
  import { Plugin } from '@tiptap/pm/state'
4
+ import { randomUUID } from '@lincyaw/kernel'
4
5
  import type { NativeDocumentEditor } from './schema.tsx'
5
6
  import type { RichProjection } from './rich-text.ts'
6
7
 
@@ -24,7 +25,7 @@ export const tableIdentityExtension = createExtension({
24
25
  after.doc.descendants((node, position) => {
25
26
  if (!TYPES.includes(node.type.name)) return
26
27
  let id = node.attrs[ATTR] as string | null
27
- if (!id || used.has(id)) { id = crypto.randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
28
+ if (!id || used.has(id)) { id = randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
28
29
  used.add(id)
29
30
  })
30
31
  if (transaction.steps.length) return transaction.setMeta('addToHistory', false)
@@ -1,8 +1,9 @@
1
- import { hasRole, validateDocument } from '@lincyaw/kernel'
1
+ import { hasRole, isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
  import { DocumentDrafts } from './document-drafts.ts'
6
+ import { sha256 } from './sha256.ts'
6
7
  import type { DocumentDraftChoice, DocumentDraftCommit, DocumentDraftReference, StoredDocumentDraft } from './document-drafts.ts'
7
8
 
8
9
  export interface DocumentSessionState {
@@ -34,6 +35,7 @@ interface Slot {
34
35
  compositions: Set<string>
35
36
  input: number
36
37
  baseHash: string
38
+ baseContent: TeachingDocument
37
39
  storage: string
38
40
  drafts: DocumentDrafts
39
41
  backup?: DocumentDraftCommit
@@ -88,10 +90,21 @@ function keepsEditorContent(before: TeachingDocument, after: TeachingDocument):
88
90
  }
89
91
 
90
92
  async function digest(value: TeachingDocument): Promise<string> {
91
- const text = serialize(value)
92
- if (!globalThis.crypto?.subtle) return `json:${text}`
93
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
94
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
93
+ return sha256(serialize(value))
94
+ }
95
+
96
+ /** Replay pending author input on a newer saved document; an overlapping value belongs to the author. */
97
+ function rebaseDocument(base: TeachingDocument, local: TeachingDocument, remote: TeachingDocument): TeachingDocument {
98
+ const merge = (before: unknown, author: unknown, saved: unknown): unknown => {
99
+ if (serialize(author) === serialize(before)) return structuredClone(saved)
100
+ if (serialize(saved) === serialize(before) || serialize(author) === serialize(saved)) return structuredClone(author)
101
+ if (isRecord(before) && isRecord(author) && isRecord(saved)) return Object.fromEntries([...new Set([...Object.keys(before), ...Object.keys(author), ...Object.keys(saved)])]
102
+ .map(key => [key, merge(before[key], author[key], saved[key])] as const).filter(([, value]) => value !== undefined))
103
+ return structuredClone(author)
104
+ }
105
+ const merged = validateDocument(merge(base, local, remote))
106
+ // A structural conflict is one document operation: preserve the author's valid complete document.
107
+ return merged.document && !merged.issues.some(issue => issue.severity === 'error') ? merged.document : structuredClone(local)
95
108
  }
96
109
 
97
110
  /** One source actor per document. Runtime compilation and iframe lifecycle never own its input. */
@@ -142,7 +155,7 @@ export class DocumentSession {
142
155
  const baseHash = await digest(answer.content)
143
156
  if (this.#disposed || this.#active !== directory || opening !== this.#opening) return
144
157
  const drafts = new DocumentDrafts(() => { if (slot && !this.#disposed) void this.#readDrafts(slot) })
145
- slot = { input: 0, read: 0, compositions: new Set(), drafts, baseHash, storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
158
+ slot = { input: 0, read: 0, compositions: new Set(), drafts, baseHash, baseContent: structuredClone(answer.content), storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
146
159
  this.#slots.set(directory, slot)
147
160
  await this.#restore(slot, answer)
148
161
  } else {
@@ -235,11 +248,19 @@ export class DocumentSession {
235
248
  slot.baseHash = remoteHash; slot.pendingHash = undefined
236
249
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, error: undefined, issues: answer.issues }
237
250
  } else if (remoteHash === slot.baseHash) slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, issues: answer.issues }
238
- else slot.state = { ...slot.state, error: 'document-version-changed', issues: answer.issues }
251
+ else if (!slot.state.composing) {
252
+ const content = rebaseDocument(slot.baseContent, slot.state.content!, answer.content)
253
+ const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, content) ? 0 : 1)
254
+ slot.baseHash = remoteHash
255
+ slot.pendingHash = undefined
256
+ slot.state = { ...slot.state, content, reset, version: answer.version, fingerprint: answer.fingerprint, error: undefined, dirty: true, issues: answer.issues }
257
+ }
258
+ if (slot.state.version === answer.version) slot.baseContent = structuredClone(answer.content)
239
259
  return
240
260
  }
241
261
  const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, answer.content) ? 0 : 1)
242
262
  slot.baseHash = remoteHash
263
+ slot.baseContent = structuredClone(answer.content)
243
264
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, content: answer.content, reset, error: undefined, issues: answer.issues }
244
265
  }
245
266
 
@@ -288,7 +309,7 @@ export class DocumentSession {
288
309
  else if (slot.timer !== undefined) return
289
310
  if (this.#readOnly(slot) || slot.flight || slot.assetFlight || !slot.state.dirty || slot.state.composing || slot.state.restored || slot.state.error || !slot.state.content || !slot.state.version) return
290
311
  slot.read++
291
- const flight = { id: crypto.randomUUID(), input: slot.input, content: structuredClone(slot.state.content), baseVersion: slot.state.version, hash: undefined as string | undefined }
312
+ const flight = { id: randomUUID(), input: slot.input, content: structuredClone(slot.state.content), baseVersion: slot.state.version, hash: undefined as string | undefined }
292
313
  slot.flight = flight
293
314
  slot.state = { ...slot.state, saving: true }; this.#emit(slot)
294
315
  try {
@@ -299,7 +320,12 @@ export class DocumentSession {
299
320
  if (answer.changeId !== flight.id || answer.document !== slot.state.directory || answer.content.id !== flight.content.id) throw new Error('document-confirmation')
300
321
  this.#ack(slot, flight, answer)
301
322
  } catch (error) {
302
- slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
323
+ if (this.#error(error) === 'document-version-changed' && !slot.state.composing) {
324
+ try {
325
+ await this.#adopt(slot, await this.#client.readDocument(slot.state.directory))
326
+ slot.state = { ...slot.state, saving: false }
327
+ } catch (refreshError) { slot.state = { ...slot.state, saving: false, error: this.#error(refreshError), issues: this.#issues(refreshError) } }
328
+ } else slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
303
329
  } finally {
304
330
  if (slot.flight === flight) slot.flight = undefined
305
331
  this.#persist(slot); this.#emit(slot)
@@ -310,6 +336,7 @@ export class DocumentSession {
310
336
  }
311
337
  #ack(slot: Slot, flight: NonNullable<Slot['flight']>, answer: DocumentChangeAnswer): void {
312
338
  slot.baseHash = flight.hash!
339
+ slot.baseContent = structuredClone(answer.content)
313
340
  slot.pendingHash = undefined
314
341
  const same = slot.input === flight.input
315
342
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, ...(same ? { content: answer.content } : {}), dirty: !same, saving: false, error: undefined, issues: answer.issues }
@@ -328,6 +355,7 @@ export class DocumentSession {
328
355
  const same = slot.input === input, content = same ? answer.content : structuredClone(current)
329
356
  if (!same) for (const [id, asset] of added) content.assets[id] = structuredClone(asset)
330
357
  slot.baseHash = baseHash
358
+ slot.baseContent = structuredClone(answer.content)
331
359
  slot.state = { ...slot.state, content, version: answer.version, fingerprint: answer.fingerprint, dirty: !same, error: undefined, issues: answer.issues }
332
360
  return true
333
361
  }
@@ -342,6 +370,7 @@ export class DocumentSession {
342
370
  const checked = validateDocument(content)
343
371
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) return false
344
372
  slot.baseHash = baseHash
373
+ slot.baseContent = structuredClone(answer.content)
345
374
  slot.pendingHash = undefined
346
375
  slot.state = { ...slot.state, content: structuredClone(checked.document), version: answer.version, fingerprint: answer.fingerprint,
347
376
  dirty: slot.input !== input || slot.state.composing || serialize(content) !== serialize(answer.content), error: undefined, issues: answer.issues }
@@ -406,7 +435,7 @@ export class DocumentSession {
406
435
  const before = structuredClone(slot.state.content), input = slot.input, version = slot.state.version
407
436
  let request = this.#imageImports.get(file)
408
437
  if (!request || request.identity !== identity || request.version !== version) {
409
- request = { identity, version, id: crypto.randomUUID() }
438
+ request = { identity, version, id: randomUUID() }
410
439
  this.#imageImports.set(file, request)
411
440
  }
412
441
  const read = ++slot.read
@@ -609,7 +638,12 @@ export class DocumentSession {
609
638
  const answer = await this.#client.readDocument(slot.state.directory)
610
639
  if (!current()) return
611
640
  if (answer.document !== slot.state.directory || answer.content.id !== documentId) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
612
- const [localHash, remoteHash] = await Promise.all([digest(candidate.content), digest(answer.content)])
641
+ // Older LAN HTTP drafts stored canonical JSON in place of a SHA-256 fingerprint.
642
+ const [localHash, remoteHash, candidateBaseHash, pendingHash] = await Promise.all([
643
+ digest(candidate.content), digest(answer.content),
644
+ candidate.baseHash.startsWith('json:') ? sha256(candidate.baseHash.slice(5)) : candidate.baseHash,
645
+ candidate.pendingHash?.startsWith('json:') ? sha256(candidate.pendingHash.slice(5)) : candidate.pendingHash,
646
+ ])
613
647
  if (!current()) return
614
648
  const origins = [...new Map([...(candidate.origins ?? []), { id: candidate.id, revision: candidate.revision, token: candidate.token }].map(value => [JSON.stringify([value.id, value.revision, value.token]), value])).values()]
615
649
  if (localHash === remoteHash && !candidate.composing) {
@@ -618,16 +652,16 @@ export class DocumentSession {
618
652
  slot.persistFailure = !settled
619
653
  return
620
654
  }
621
- const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidate.baseHash && remoteHash !== candidate.pendingHash
622
- const version = remoteHash === candidate.pendingHash || remoteHash === candidate.baseHash ? answer.version : candidate.baseVersion
623
- const baseHash = remoteHash === candidate.pendingHash ? remoteHash : candidate.baseHash
655
+ const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidateBaseHash && remoteHash !== pendingHash
656
+ const version = remoteHash === pendingHash || remoteHash === candidateBaseHash ? answer.version : candidate.baseVersion
657
+ const baseHash = remoteHash === pendingHash ? remoteHash : candidateBaseHash
624
658
  const record = await slot.drafts.fork(identity, { content: candidate.content, baseVersion: version, baseHash, input: input + 1,
625
- pendingHash: candidate.pendingHash, composing: Boolean(candidate.composing), origins })
659
+ pendingHash, composing: Boolean(candidate.composing), origins })
626
660
  if (!current()) { if (record) slot.drafts.archive(record); return }
627
661
  if (!record) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true }; return }
628
662
  clearTimeout(slot.timer); slot.timer = undefined
629
663
  if (slot.draft) slot.drafts.archive(slot.draft)
630
- slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = candidate.pendingHash; slot.draft = record; slot.draftOrigins = origins
664
+ slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = pendingHash; slot.draft = record; slot.draftOrigins = origins
631
665
  slot.backup = undefined; slot.persistFailure = false
632
666
  adopted = true
633
667
  slot.compositions.clear()
package/src/history.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { errorMessage } from '@lincyaw/kernel'
1
+ import { errorMessage, randomUUID } from '@lincyaw/kernel'
2
2
  import type { RevertResult, ReviewChange, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
3
3
  import type { WorkbenchStore } from './workbench.ts'
4
4
  import { WorkspaceServerError } from './workspace-client.ts'
@@ -129,7 +129,7 @@ export class DocumentHistory {
129
129
  #change(which: 'undo' | 'redo' | 'revertRevision', expect: string | undefined): Promise<boolean> {
130
130
  const binding = this.#store.state.history?.historyBinding
131
131
  if (!binding || !expect) return Promise.resolve(false)
132
- const request = { id: crypto.randomUUID(), ...binding, expect }
132
+ const request = { id: randomUUID(), ...binding, expect }
133
133
  return this.#run(dir => this.#client[which](dir, request))
134
134
  }
135
135
 
package/src/index.ts CHANGED
@@ -26,9 +26,6 @@ export { HistoryPanel } from './panels/HistoryPanel.tsx'
26
26
  export type { HistoryPanelProps, HistoryRevisionAction } from './panels/HistoryPanel.tsx'
27
27
  export { HomePanel } from './panels/HomePanel.tsx'
28
28
  export { WorkbenchApprovals } from './approvals.tsx'
29
- export { assistantMascotAction, useAssistantMascot } from './assistant-mascot.ts'
30
- export type { AssistantActivity } from './assistant-mascot.ts'
31
- export { mascotEnabled, setMascotEnabled, useMascotEnabled } from './mascot-preference.ts'
32
29
  export { PreviewPanel } from './panels/PreviewPanel.tsx'
33
30
  export { SpeechSettingsPanel } from './panels/SpeechSettingsPanel.tsx'
34
31
  export { SPEECH_SETTINGS_MESSAGES } from './speech-settings-messages.ts'
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 = {
@@ -325,11 +330,11 @@ const zh = {
325
330
  'history-result-no-longer-current': '之前的结果已不是当前版本,请查看最新的历史。',
326
331
  'authoring-review-required': '有修改等待你审阅,请先接受或放弃。',
327
332
  } as Record<string, string>,
328
- agentWorking: 'AI 正在修改文稿…',
329
333
  agentWaiting: (n: number) => `AI 修改了 ${n} 处内容,要接受这些修改吗?`,
330
334
  accept: '接受',
331
335
  reject: '拒绝',
332
- problems: (n: number) => `有 ${n} 处内容无法正确显示。`,
336
+ problems: (n: number) => `文稿有 ${n} 个问题需要处理。`,
337
+ problemsTitle: '文稿中的问题',
333
338
  fixWithAi: '用 AI 修复',
334
339
  fixing: '正在发送给 AI…',
335
340
  fixFailed: (reason: string) => `无法发送给 AI。${reason}`,
@@ -356,6 +361,11 @@ const zh = {
356
361
  place.quote ? `\n原文:“${place.quote}”` : '',
357
362
  ].join('')).filter(Boolean),
358
363
  ].join('\n\n'),
364
+ animationRequest: (page: number, title: string, place: AgentInsertion) => {
365
+ const at = `第 ${page} 页${title ? `“${title}”` : ''}`
366
+ return place.end ? `在${at}的末尾加一个动画:` : place.after === undefined ? `在${at}的开头加一个动画:`
367
+ : place.after ? `在${at}中“${excerpt(place.after, 16)}”这一段之后加一个动画:` : `在${at}的这个位置加一个动画:`
368
+ },
359
369
  commentsRequest: (comments: (AgentPlace & { text: string })[]) => [
360
370
  comments.length === 1 ? '我在文稿上写了一条批注:' : `我在文稿上写了 ${comments.length} 条批注:`,
361
371
  ...comments.map((comment, i) => [
@@ -689,11 +699,11 @@ const en: WorkbenchMessages = {
689
699
  'history-result-no-longer-current': 'The earlier result is no longer the current version. Review the latest history.',
690
700
  'authoring-review-required': 'Changes are waiting for your review. Accept or discard them first.',
691
701
  },
692
- agentWorking: 'The AI is editing the document…',
693
702
  agentWaiting: (n: number) => `The AI changed ${n} file${n === 1 ? '' : 's'}. Accept the changes?`,
694
703
  accept: 'Accept',
695
704
  reject: 'Reject',
696
- problems: (n: number) => `${n} item${n === 1 ? '' : 's'} can’t be displayed correctly.`,
705
+ problems: (n: number) => `The document has ${n} problem${n === 1 ? '' : 's'} to fix.`,
706
+ problemsTitle: 'Problems in the Document',
697
707
  fixWithAi: 'Fix with AI',
698
708
  fixing: 'Sending to the AI…',
699
709
  fixFailed: (reason: string) => `Couldn’t send to the AI. ${reason}`,
@@ -720,6 +730,11 @@ const en: WorkbenchMessages = {
720
730
  place.quote ? `\nText: “${place.quote}”` : '',
721
731
  ].join('')).filter(Boolean),
722
732
  ].join('\n\n'),
733
+ animationRequest: (page: number, title: string, place: AgentInsertion) => {
734
+ const at = `page ${page}${title ? `, “${title}”` : ''}`
735
+ return place.end ? `Add an animation at the end of ${at}: ` : place.after === undefined ? `Add an animation at the start of ${at}: `
736
+ : place.after ? `Add an animation on ${at}, after the paragraph “${excerpt(place.after, 40)}”: ` : `Add an animation at this point on ${at}: `
737
+ },
723
738
  commentsRequest: (comments: (AgentPlace & { text: string })[]) => [
724
739
  comments.length === 1 ? 'I left a comment on the document:' : `I left ${comments.length} comments on the document:`,
725
740
  ...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, 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'
@@ -198,7 +198,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
198
198
  <DocumentNotices />
199
199
  <div className="pmw-document__body" role="region" aria-label={producing ? PRODUCTION_MESSAGES[workbench.getState().locale].title : presenting ? t.presentationPreview : reading ? t.readDocument : t.documentEditor}>
200
200
  {!presenting && !producing && !reading && navigation && <NavigationPane onClose={() => setNavigation(false)} onSelect={() => { if (matchMedia('(max-width: 1279px)').matches) setNavigation(false) }} />}
201
- <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} /></div>{producing && <ProductionPanel active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
201
+ <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} onOpenComments={() => setAside('comments')} /></div>{producing && <ProductionPanel active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
202
202
  {!presenting && !producing && !reading && aside && (
203
203
  <aside className="pmw-document__aside pm-ui-block-editor" aria-label={{ narration: t.documentNarration, comments: t.comments, export: t.exportPane, history: t.versionHistory }[aside]}>
204
204
  {aside === 'comments' ? <section className="pmw-pane"><header className="pmw-pane__header"><h2 className="pmw-pane__title">{t.comments}</h2><PmIconButton small icon="close" label={t.close} onClick={() => setAside(null)} /></header><div ref={setCommentsPortal} /></section> : aside === 'narration' ? <DocumentNarrationPanel onClose={() => setAside(null)} /> : aside === 'export' ? <ExportPanel documentOnly onClose={() => setAside(null)} /> : <HistoryPanel onClose={() => setAside(null)} revisionAction={historyRevisionAction} />}
@@ -409,10 +409,8 @@ function DocumentNotices() {
409
409
  const askFailure = useWorkbenchState(state => (state.pointer ? undefined : state.askFailure))
410
410
  return (
411
411
  <div className="pmw-notices">
412
- {review?.running && <PmNotice tone="accent"><PmMascot size="small" action={review.changes.length > 0 ? 'write' : 'read'} />{t.agentWorking}</PmNotice>}
413
412
  {review && !review.running && review.changes.length > 0 && (
414
413
  <PmNotice tone="accent">
415
- <PmMascot size="small" action="ask" />
416
414
  <span>{t.agentWaiting(review.changes.length)}</span>
417
415
  <span className="pmw-notice__actions">
418
416
  <PmButton small onClick={() => void workbench.rejectReview()}>{t.reject}</PmButton>
@@ -431,7 +429,7 @@ function DocumentNotices() {
431
429
  )
432
430
  }
433
431
 
434
- /** Content that did not display, said plainly, with the AI to fix it and the details for whoever wants them. */
432
+ /** The document's problems in one line above the page, with the AI to fix them; the list itself opens in a dialog. */
435
433
  function ProblemsNotice() {
436
434
  const t = useMessages()
437
435
  const workbench = useWorkbench()
@@ -440,23 +438,25 @@ function ProblemsNotice() {
440
438
  const canRepair = useWorkbenchState(state => state.canRepairDiagnostics)
441
439
  const repairing = useWorkbenchState(state => state.isRepairingDiagnostics)
442
440
  const repairFailure = useWorkbenchState(state => state.diagnosticsRepairFailure)
441
+ const [open, setOpen] = useState(false)
443
442
  if (workbench.client.capabilities?.diagnostics === 'none') return null
444
443
  const problems = (snapshot?.diagnostics ?? []).filter(diagnostic => diagnostic.severity === 'error' && !diagnostic.checkId.startsWith('presmium.workbench.'))
445
444
  if (unavailable) return <PmNotice tone="warn"><span>{t.diagnosticsUnavailable}</span><PmButton small onClick={() => workbench.retryDiagnostics()}>{t.retry}</PmButton></PmNotice>
446
445
  if (problems.length === 0) return repairFailure ? <PmNotice tone="danger">{t.fixFailed(failureReason(t, repairFailure))}</PmNotice> : null
446
+ const repair = canRepair && <PmButton small variant="accent" icon="sparkle" disabled={repairing} onClick={() => void workbench.requestRepairDiagnostics()}>{repairing ? t.fixing : t.fixWithAi}</PmButton>
447
447
  return (
448
448
  <PmNotice tone="warn">
449
449
  <div className="pmw-problems">
450
450
  <div className="pmw-problems__summary">
451
451
  <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>}
452
+ <PmButton small variant="ghost" onClick={() => setOpen(true)}>{t.details}</PmButton>
453
+ {repair}
453
454
  </div>
454
455
  {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
456
  </div>
457
+ <PmDialog open={open} label={t.problemsTitle} closeLabel={t.close} actions={repair || undefined} onClose={() => setOpen(false)}>
458
+ <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>
459
+ </PmDialog>
460
460
  </PmNotice>
461
461
  )
462
462
  }
@@ -1,8 +1,7 @@
1
1
  import { useEffect, useState } from 'react'
2
- import type { CSSProperties } from 'react'
3
2
  import type { CompileJob, OutputTarget } from '@lincyaw/kernel'
4
3
  import type { IconName } from '@lincyaw/design'
5
- import { PmBadge, PmButton, PmDialog, PmEmpty, PmIcon, PmIconButton, PmMascot, PmNotice } from '../components.tsx'
4
+ import { PmBadge, PmButton, PmDialog, PmEmpty, PmIcon, PmIconButton, PmNotice } from '../components.tsx'
6
5
  import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
7
6
  import { failureReason, timeAgo } from '../messages.ts'
8
7
 
@@ -105,10 +104,6 @@ function JobItem({ job, label, current, onPlay }: { job: CompileJob, label: stri
105
104
  </p>
106
105
  {job.state === 'running' && progress && (
107
106
  <div className="pmw-job__progress">
108
- {/* the kitten runs along the bar to how far the job has come; with no total yet it walks at the start */}
109
- <span className="pmw-job__runner" style={{ '--pmw-job-done': progress.total ? Math.min(1, (progress.done ?? 0) / progress.total) : 0 } as CSSProperties}>
110
- <PmMascot size="small" action={progress.total ? 'run' : 'walk'} />
111
- </span>
112
107
  <progress max={progress.total ?? 1} value={progress.total ? progress.done ?? 0 : undefined} aria-label={label} />
113
108
  <span>{t.jobProgress(t.jobPhases[progress.phase] ?? t.outputLabels[progress.phase] ?? progress.phase, progress.done, progress.total)}</span>
114
109
  </div>
@@ -6,7 +6,6 @@ import { PmButton, PmNotice } from '../components.tsx'
6
6
  import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
7
7
  import { slideAspect } from '../workbench.ts'
8
8
  import { failureReason } from '../messages.ts'
9
- import { PreviewChangeTrail } from './ChangeTrail.tsx'
10
9
 
11
10
  /**
12
11
  * The open document as its readers see it (the web form or the slides), with the tools for what the author points at.
@@ -29,7 +28,6 @@ export function PreviewPanel({ active = true, onPresentationAction, presentation
29
28
  const reload = useWorkbenchState(state => state.previewReload)
30
29
  const aspect = useWorkbenchState(state => (state.previewRenderer === 'slides' ? slideAspect(state.ir) : undefined))
31
30
  const container = useRef<HTMLDivElement>(null)
32
- const stage = useRef<HTMLDivElement>(null)
33
31
  const pool = useRef<ReturnType<typeof createPreviewPool>>()
34
32
  const [loads, setLoads] = useState(0)
35
33
  const [{ ready, mismatch, identityFailure, handshakeFailure, canvasGate }, setStatus] = useState<PreviewFrameStatus>({ ready: false })
@@ -70,9 +68,8 @@ export function PreviewPanel({ active = true, onPresentationAction, presentation
70
68
  {failure && <PmNotice tone="danger"><span>{t.previewFailed(failureReason(t, failure))}</span><PmButton small onClick={() => workbench.retryPreview()}>{t.retry}</PmButton></PmNotice>}
71
69
  {(!ready || !snapshotMatches) && !failure && !handshakeFailure && !(renderer === 'slides' && preview && !preview.slides) && <p className="pmw-muted pmw-preview__loading">{presentation && ready && !snapshotMatches && !preparing ? t.presentationOutdated : address ? t.previewLoading : t.previewPreparing}</p>}
72
70
  {renderer === 'slides' && preview && !preview.slides && <p className="pmw-muted pmw-preview__loading">{t.noSlides}</p>}
73
- <div ref={stage} className="pmw-preview__stage">
71
+ <div className="pmw-preview__stage">
74
72
  <div ref={container} className="pmw-preview__frames" data-renderer={renderer} data-pending-snapshot={!snapshotMatches || undefined} data-presentation-gated={presentation && canvasGate || undefined} style={aspect === undefined ? undefined : { '--pmw-slide-aspect': aspect } as CSSProperties} />
75
- {!presentation && <PreviewChangeTrail stage={stage} frames={container} />}
76
73
  </div>
77
74
  </section>
78
75
  )