@lincyaw/workbench 0.2.0-rc.121 → 0.2.0-rc.122

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.121",
3
+ "version": "0.2.0-rc.122",
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": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/design": "1.0.0-rc.120",
59
- "@lincyaw/kernel": "1.0.0-rc.120"
58
+ "@lincyaw/design": "1.0.0-rc.121",
59
+ "@lincyaw/kernel": "1.0.0-rc.121"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.120"
70
+ "@lincyaw/compiler": "1.0.0-rc.121"
71
71
  }
72
72
  }
@@ -14,6 +14,8 @@ export { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
14
14
  export type { ButtonVariant, ControlDensity } from './base-controls.tsx'
15
15
  export { PmSortableList } from './sortable-list.tsx'
16
16
  export type { SortableListItem, SortableListLabels, SortableListProps } from './sortable-list.tsx'
17
+ export { PmBacklinkItem, PmDocMention, PmDocPreviewCard, PmDocTree, PmMentionPicker, PmSyncedBlockFrame, PmToast } from './knowledge-components.tsx'
18
+ export type { BacklinkPlace, DocPreview, DocTreeDrop, DocTreeLabels, DocTreeNode, DocTreeProps, MentionOption, ToastMessage } from './knowledge-components.tsx'
17
19
 
18
20
  const cls = (...names: (string | false | undefined | null)[]) => names.filter(Boolean).join(' ')
19
21
 
@@ -84,6 +86,8 @@ export interface SearchListProps {
84
86
  onActivate?(value: string): void
85
87
  query?: string
86
88
  onQueryChange?(query: string): void
89
+ /** False when `items` already are the results of `query` (a search on the server): they are shown as given. */
90
+ filter?: boolean
87
91
  resultsLabel(count: number): string
88
92
  emptyLabel: string
89
93
  loadingLabel: string
@@ -96,7 +100,7 @@ export interface SearchListProps {
96
100
  }
97
101
 
98
102
  /** Search and a single choice compose with Dialog; Radix owns radio navigation and selection. */
99
- export function PmSearchList({ label, searchLabel, searchPlaceholder, items, value, onValueChange, onActivate, query, onQueryChange, resultsLabel, emptyLabel, loadingLabel, loading, error, disabled, density = 'compact', autoFocus, 'aria-describedby': describedBy }: SearchListProps) {
103
+ export function PmSearchList({ label, searchLabel, searchPlaceholder, items, value, onValueChange, onActivate, query, onQueryChange, filter = true, resultsLabel, emptyLabel, loadingLabel, loading, error, disabled, density = 'compact', autoFocus, 'aria-describedby': describedBy }: SearchListProps) {
100
104
  const id = useId()
101
105
  const [localQuery, setLocalQuery] = useState('')
102
106
  const list = useRef<HTMLDivElement>(null)
@@ -107,12 +111,13 @@ export function PmSearchList({ label, searchLabel, searchPlaceholder, items, val
107
111
  useEffect(() => () => { if (navigationRelease.current) clearTimeout(navigationRelease.current) }, [])
108
112
  const search = query ?? localQuery
109
113
  const matches = useMemo(() => {
114
+ if (!filter) return items
110
115
  const terms = search.normalize('NFKC').toLowerCase().trim().split(/\s+/).filter(Boolean)
111
116
  return items.filter(item => {
112
117
  const text = [item.label, ...item.keywords ?? []].join(' ').normalize('NFKC').toLowerCase()
113
118
  return terms.every(term => text.includes(term))
114
119
  })
115
- }, [items, search])
120
+ }, [items, search, filter])
116
121
  const blocked = Boolean(disabled || loading || error)
117
122
  const errorId = error ? `${id}-error` : undefined
118
123
  return <div className="pm-ui-search-list" data-density={density} onKeyDownCapture={event => {
@@ -347,6 +352,21 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
347
352
  )
348
353
  }
349
354
 
355
+ /** A modal side panel from the start edge (the sidebar on a narrow screen): Esc, the backdrop and `onClose` close it. */
356
+ export function PmDrawer({ open, label, size, onClose, children }: { open: boolean, label: string, size?: 'sidebar', onClose(): void, children?: ReactNode }) {
357
+ return (
358
+ <Dialog.Root open={open} modal onOpenChange={next => { if (!next) onClose() }}>
359
+ <Dialog.Portal>
360
+ <Dialog.Overlay className="pm-ui-dialog-overlay" />
361
+ <Dialog.Content className="pm-ui-drawer pm-ui" data-size={size} aria-describedby={undefined} onEscapeKeyDown={event => event.stopPropagation()}>
362
+ <Dialog.Title className="pm-ui-sr-only">{label}</Dialog.Title>
363
+ {children}
364
+ </Dialog.Content>
365
+ </Dialog.Portal>
366
+ </Dialog.Root>
367
+ )
368
+ }
369
+
350
370
  /** A non-modal floating panel on its trigger, with the shared `pm-ui-popover` surface (host's PmPopover for React pages). */
351
371
  export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, onInteractOutside, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, onInteractOutside?: ComponentProps<typeof Popover.Content>['onInteractOutside'], children?: ReactNode }) {
352
372
  const inDialog = useContext(PmDialogLayerContext)
@@ -374,11 +394,11 @@ export interface MenuItem {
374
394
  }
375
395
 
376
396
  /** `toolbarItem`: the trigger joins the surrounding `PmToolbar`'s arrow-key navigation, e.g. as its overflow ("More") menu. */
377
- export function PmMenu({ label, description, items, icon = 'more', placement = 'below-end', triggerRef, toolbarItem, onSelect }: { label: string, description?: string, items: MenuItem[], icon?: IconName, placement?: PopoverPlacement, triggerRef?: Ref<HTMLButtonElement>, toolbarItem?: boolean, onSelect(id: string): void }) {
397
+ export function PmMenu({ label, description, items, icon = 'more', placement = 'below-end', triggerRef, toolbarItem, onOpenChange, onSelect }: { label: string, description?: string, items: MenuItem[], icon?: IconName, placement?: PopoverPlacement, triggerRef?: Ref<HTMLButtonElement>, toolbarItem?: boolean, onOpenChange?(open: boolean): void, onSelect(id: string): void }) {
378
398
  const descriptionId = useId()
379
399
  const trigger = <PmIconButton ref={triggerRef} icon={icon} label={label} small />
380
400
  return (
381
- <DropdownMenu.Root>
401
+ <DropdownMenu.Root onOpenChange={onOpenChange}>
382
402
  <DropdownMenu.Trigger asChild>{toolbarItem ? <Toolbar.Button asChild>{trigger}</Toolbar.Button> : trigger}</DropdownMenu.Trigger>
383
403
  <DropdownMenu.Portal>
384
404
  <DropdownMenu.Content className="pm-ui-menu pm-ui-floating pm-ui" data-density="compact" data-description={description ? '' : undefined} aria-label={label} aria-describedby={description ? descriptionId : undefined} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onEscapeKeyDown={event => event.stopPropagation()}>
package/src/context.tsx CHANGED
@@ -2,6 +2,8 @@ import { createContext, useContext, useSyncExternalStore } from 'react'
2
2
  import type { ReactNode } from 'react'
3
3
  import { MESSAGES } from './messages.ts'
4
4
  import type { WorkbenchMessages } from './messages.ts'
5
+ import { DOCUMENT_TREE_MESSAGES } from './tree-messages.ts'
6
+ import type { DocumentTreeMessages } from './tree-messages.ts'
5
7
  import type { Workbench } from './workbench.ts'
6
8
  import type { WorkbenchState } from './workbench-state.ts'
7
9
  import { PmDialogActionsContext } from './components.tsx'
@@ -27,3 +29,18 @@ export function useWorkbenchState<T>(select: (state: WorkbenchState) => T): T {
27
29
  export function useMessages(): WorkbenchMessages {
28
30
  return MESSAGES[useWorkbenchState(state => state.locale)]
29
31
  }
32
+
33
+ export function useTreeMessages(): DocumentTreeMessages {
34
+ return DOCUMENT_TREE_MESSAGES[useWorkbenchState(state => state.locale)]
35
+ }
36
+
37
+ /** Where the open document's inherited settings come from: its parent in the document tree, else the workspace defaults. */
38
+ export function useInheritedFrom(): string {
39
+ const t = useTreeMessages()
40
+ const parent = useWorkbenchState(state => {
41
+ const id = state.authoring?.content?.id
42
+ const nodes = state.documentTree?.nodes
43
+ return id && nodes ? nodes[nodes[id]?.parent ?? '']?.title : undefined
44
+ })
45
+ return parent ? t.inheritedFrom(parent) : t.inheritedWorkspace
46
+ }
@@ -163,6 +163,8 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
163
163
  } : undefined,
164
164
  disableExtensions: ['dropFile'],
165
165
  pasteHandler: ({ event, editor, defaultPasteHandler }) => {
166
+ const text = event.clipboardData?.getData('text/plain')
167
+ if (text && !event.clipboardData?.getData('text/html') && current.current.nodeViews?.pasteText?.(text, editor as NativeDocumentEditor)) return true
166
168
  const files = [...event.clipboardData?.files ?? []]
167
169
  if (files.length && !event.clipboardData?.getData('text/html')) {
168
170
  editor.getExtension(imageFileInput)?.insert(files)
@@ -217,10 +219,11 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
217
219
  title: t.animateWithAI, subtext: t.animateWithAIHint, group: dictionary.slash_menu.image.group, icon: <PmIcon name="sparkle" />, aliases: slashAliases('animateWithAIAliases'),
218
220
  // The menu has already taken back the typed “/” and query; the AI is asked, the document stays as it was.
219
221
  onItemClick: () => current.current.animationRequest?.request(editor),
220
- }] : []), {
222
+ }] : []), ...current.current.nodeViews?.slashItems?.(editor) ?? [], {
221
223
  title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
222
224
  onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: randomUUID() }, content: t.untitledPage }], current, 'after') },
223
225
  }], query)} />
226
+ {props.nodeViews?.editorChildren?.(editor)}
224
227
  {props.children}
225
228
  </NewCommentDraftProvider></BlockNoteViewEditor>
226
229
  </ComponentsContext.Provider>
@@ -17,7 +17,6 @@ const authorText = (value: unknown) => typeof value === 'string' && value.trim()
17
17
  export function DocumentBlockFallback({ block, document, locale }: { block: DocumentBlock, document: PresmiumDocument, locale: Locale }) {
18
18
  const t = DOCUMENT_EDITOR_MESSAGES[locale], p = BLOCK_PREVIEW_MESSAGES[locale]
19
19
  if (isDiagram(block, document.metadata.plugins)) return <PmNotice>{t.diagram(block.type === 'code' && block.title || '')}</PmNotice>
20
- if (block.type === 'embed') return <PmNotice>{t.syncedBlock(block.source.document)}</PmNotice>
21
20
  if (block.type === 'code') return <PmNotice>{t.codeReference(block.title ?? block.origin?.anchor ?? block.language)}</PmNotice>
22
21
  if (block.type !== 'component') return null
23
22
  const definition = document.definitions[block.definitionId]
@@ -19,6 +19,7 @@ import type { NativeDocumentSelection, NativeTextPoint } from './selection.ts'
19
19
  import { documentInsertionPlace } from './insertion-place.ts'
20
20
  import type { DocumentInsertionPlace } from './insertion-place.ts'
21
21
  import { effectiveOf } from '../effective-settings.ts'
22
+ import { syncedLinkOf } from './references.tsx'
22
23
 
23
24
  export interface DocumentEditingPosition {
24
25
  nativeBlockId: string
@@ -77,6 +78,11 @@ export interface DocumentEditorProps {
77
78
  export function DocumentEditor(props: DocumentEditorProps) {
78
79
  const projection = useMemo(() => createDocumentProjection(props.document, effectiveOf(props.document, props.inherited).metadata.plugins), [props.identity, props.reset])
79
80
  useEffect(() => rememberComponentConfiguration(projection, props.document), [projection, props.version])
81
+ // The drag handle menu's Copy Synced Block Link names the document block that owns the native one.
82
+ const nodeViews = useMemo<DocumentNodeViews>(() => ({ ...props.nodeViews, syncedLink: nativeId => {
83
+ const owner = projection.owners.get(nativeId) ?? nativeId
84
+ return projection.document.blocks[owner] ? syncedLinkOf(projection.document.id, owner) : undefined
85
+ } }), [props.nodeViews, projection])
80
86
  const comments = useMemo(() => new DocumentThreadStore(props.document, props.member, props.version, props.identity, props.commentDrafts), [props.identity, props.reset])
81
87
  useEffect(() => {
82
88
  const latest = current.current, document = latest.getDocument ? latest.getDocument() : latest.document
@@ -158,7 +164,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
158
164
  }
159
165
  return <BlockNoteSurface identity={props.identity} reset={props.reset} initialContent={projection.content} locale={props.locale} contentLang={effectiveOf(props.document, props.inherited).metadata.lang} readOnly={props.readOnly}
160
166
  resolveAssetURL={props.resolveAssetURL} uploadImage={props.uploadImage}
161
- comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
167
+ comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
162
168
  animationRequest={{
163
169
  available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
164
170
  request: value => {
@@ -12,6 +12,8 @@ import { PmIcon } from '../components.tsx'
12
12
  import { DOCUMENT_EDITOR_MESSAGES, slashAliases } from './messages.ts'
13
13
  import { DOCUMENT_EDITOR_LOCALE } from './math.tsx'
14
14
  import type { NativeDocumentEditor } from './schema.tsx'
15
+ import { DOCUMENT_NODE_VIEWS } from './schema.tsx'
16
+ import { DOCUMENT_TREE_MESSAGES } from '../tree-messages.ts'
15
17
 
16
18
  const useMessages = () => DOCUMENT_EDITOR_MESSAGES[useContext(DOCUMENT_EDITOR_LOCALE)]
17
19
 
@@ -110,6 +112,18 @@ function BlockColorsItem({ children }: { children: ReactNode }) {
110
112
  return <ColorSubmenu text={choice('textColor')} background={choice('backgroundColor')}>{children}</ColorSubmenu>
111
113
  }
112
114
 
115
+ /** Copies the link that inserts this block as a synced block in another document (pasted there). */
116
+ function CopySyncedLinkItem() {
117
+ const Components = useComponentsContext()!
118
+ const editor = useBlockNoteEditor<any, any, any>()
119
+ const views = useContext(DOCUMENT_NODE_VIEWS)
120
+ const locale = useContext(DOCUMENT_EDITOR_LOCALE)
121
+ const block = useExtensionState(SideMenuExtension, { editor, selector: state => state?.block })
122
+ const link = block && block.type !== 'presmiumPage' ? views.syncedLink?.(block.id) : undefined
123
+ if (!link || !views.copySyncedLink) return null
124
+ return <Components.Generic.Menu.Item className="bn-menu-item" onClick={() => views.copySyncedLink!(link)}>{DOCUMENT_TREE_MESSAGES[locale].copySyncedLink}</Components.Generic.Menu.Item>
125
+ }
126
+
113
127
  function DocumentDragHandleMenu() {
114
128
  const dict = useDictionary()
115
129
  return <DragHandleMenu>
@@ -117,6 +131,7 @@ function DocumentDragHandleMenu() {
117
131
  <BlockColorsItem>{dict.drag_handle.colors_menuitem}</BlockColorsItem>
118
132
  <TableRowHeaderItem>{dict.drag_handle.header_row_menuitem}</TableRowHeaderItem>
119
133
  <TableColumnHeaderItem>{dict.drag_handle.header_column_menuitem}</TableColumnHeaderItem>
134
+ <CopySyncedLinkItem />
120
135
  </DragHandleMenu>
121
136
  }
122
137
  export function DocumentSideMenu(props: SideMenuProps) { return <SideMenu {...props} dragHandleMenu={DocumentDragHandleMenu} /> }
@@ -62,6 +62,7 @@ export function productInlineToNative(nodes: readonly InlineNode[], context: Inl
62
62
  return nodes.map(node => {
63
63
  if (node.type === 'text' || node.type === 'break') return nativeText(node)
64
64
  if (node.type === 'math') return { type: 'presmiumMathInline', props: {}, content: node.value }
65
+ if (node.type === 'reference') return { type: 'presmiumReference', props: { document: node.target.document, section: node.target.section ?? '', block: node.target.block ?? '', label: node.label ?? '', fallback: node.fallback }, content: undefined }
65
66
  if (isDocumentTextLink(node)) {
66
67
  return { type: 'link', href: node.href, content: node.children.map(child => nativeText(child as Extract<InlineNode, { type: 'text' | 'break' }>)) }
67
68
  }
@@ -86,6 +87,10 @@ export function nativeInlineToProduct(nodes: readonly NativeInline[], context: I
86
87
  if (node.type === 'text') return productText(node)
87
88
  if (node.type === 'link') return [{ type: 'link', href: node.href, children: node.content.flatMap(productText) } satisfies InlineNode]
88
89
  if (node.type === 'presmiumMathInline') return [{ type: 'math', value: node.content } satisfies InlineNode]
90
+ if (node.type === 'presmiumReference') {
91
+ const { document, section, block, label, fallback } = node.props
92
+ return [{ type: 'reference', target: { document, ...section ? { section } : {}, ...block ? { block } : {} }, ...label ? { label } : {}, fallback } satisfies InlineNode]
93
+ }
89
94
  const original = context.opaqueInline.get(node.props.entityId)
90
95
  if (!original) throw new Error('document-inline-reference')
91
96
  return [structuredClone(original)]
@@ -17,12 +17,12 @@ export interface DocumentInsertionPlace {
17
17
  end: boolean
18
18
  }
19
19
 
20
- type Inline = { type: string, text?: string, content?: unknown, props?: { label?: string } }
20
+ type Inline = { type: string, text?: string, content?: unknown, props?: { label?: string, fallback?: string } }
21
21
 
22
22
  function inlineText(content: unknown): string {
23
23
  if (typeof content === 'string') return content
24
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('')
25
+ return (content as Inline[]).map(item => item.type === 'text' ? item.text ?? '' : item.type === 'presmiumInline' ? item.props?.label ?? '' : item.type === 'presmiumReference' ? item.props?.label || item.props?.fallback || '' : inlineText(item.content)).join('')
26
26
  }
27
27
 
28
28
  function textOf(block: DocumentEditorBlock): string {
@@ -4,8 +4,8 @@ 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: '新建批注', stepComment: (step: number) => `在第 ${step} 步批注`, stepCommentHint: (step: number, count: number) => count ? `第 ${step} 步 · ${count} 条未解决批注` : `在第 ${step} 步批注`, stepCommentFailed: '无法保存这条批注,请重试。', 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}`, syncedBlock: (source: string) => `同步块:来自 ${source},将在后续版本中显示`, 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}`, stepCommentFailed: 'Couldn’t save this comment. Try again.', 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}`, syncedBlock: (source: string) => `Synced block from ${source}. It will be shown in a later version.`, 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' },
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} 步批注`, stepCommentFailed: '无法保存这条批注,请重试。', 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}`, stepCommentFailed: 'Couldn’t save this comment. Try again.', 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. */
@@ -52,8 +52,9 @@ function productBlock(blockId: string, context: DocumentProjection, sectionId: s
52
52
  context.owners.set(block.id, block.id)
53
53
  if (block.type === 'container') return [{ id: block.id, type: 'presmiumContainer', props: { entityId: block.id, layout: block.layout, title: block.properties.title ?? '' }, children: block.children.flatMap(child => productBlock(child, context, sectionId)) }]
54
54
  if (block.type === 'image') return [{ id: block.id, type: 'image', props: { url: block.assetId ? document.assets[block.assetId]?.location ?? '' : '', caption: plain(block.caption ?? []), name: block.alt, textAlignment: block.alignment ?? 'left', ...block.width !== undefined ? { previewWidth: block.width } : {} } }]
55
+ if (block.type === 'embed') return [{ id: block.id, type: 'presmiumEmbed', props: { document: block.source.document, block: block.source.block } }]
55
56
  if (block.type === 'code' && block.value !== undefined && !isDiagram(block, context.plugins)) return [{ id: block.id, type: 'codeBlock', props: { language: block.language }, content: block.value }]
56
- return [{ id: block.id, type: 'presmiumAtom', props: { entityId: block.id, kind: block.type, label: block.type === 'code' ? block.title ?? block.origin?.anchor ?? block.language : block.type === 'embed' ? block.source.document : document.definitions[block.definitionId]?.kind ?? block.definitionId }, ...block.type === 'component' && block.children ? { children: block.children.flatMap(child => productBlock(child, context, sectionId)) } : {} }]
57
+ return [{ id: block.id, type: 'presmiumAtom', props: { entityId: block.id, kind: block.type, label: block.type === 'code' ? block.title ?? block.origin?.anchor ?? block.language : document.definitions[block.definitionId]?.kind ?? block.definitionId }, ...block.type === 'component' && block.children ? { children: block.children.flatMap(child => productBlock(child, context, sectionId)) } : {} }]
57
58
  }
58
59
 
59
60
  export function createDocumentProjection(document: PresmiumDocument, plugins: readonly string[] | undefined = document.metadata.plugins): DocumentProjection {
@@ -68,7 +69,7 @@ export function createDocumentProjection(document: PresmiumDocument, plugins: re
68
69
 
69
70
  function structureOf(blocks: readonly DocumentEditorBlock[], context: DocumentProjection): string {
70
71
  const tree = (blocks: readonly DocumentEditorBlock[]): unknown[] => blocks.map(block => [block.id, block.type,
71
- block.type === 'presmiumPage' ? block.props.sectionId : block.type === 'presmiumAtom' ? [block.props.entityId, block.props.kind] : undefined, tree(block.children)])
72
+ block.type === 'presmiumPage' ? block.props.sectionId : block.type === 'presmiumAtom' ? [block.props.entityId, block.props.kind] : block.type === 'presmiumEmbed' ? [block.props.document, block.props.block] : undefined, tree(block.children)])
72
73
  return JSON.stringify([tree(blocks), [...context.tables]])
73
74
  }
74
75
 
@@ -149,7 +150,7 @@ function nativePlain(block: DocumentEditorBlock): string {
149
150
  }
150
151
  function isEntity(block: DocumentEditorBlock, context: DocumentProjection): boolean {
151
152
  if (block.type === 'presmiumAtom') return !block.props.kind.startsWith('rich:')
152
- if (block.type === 'presmiumContainer' || block.type === 'image') return true
153
+ if (block.type === 'presmiumContainer' || block.type === 'image' || block.type === 'presmiumEmbed') return true
153
154
  return block.type === 'codeBlock' && context.document.blocks[context.owners.get(block.id) ?? block.id]?.type !== 'text' && !context.rich.has(block.id)
154
155
  }
155
156
  function nativeChildren(native: readonly DocumentEditorBlock[], context: DocumentProjection, next: PresmiumDocument, usedListIds: Set<string>): string[] {
@@ -200,7 +201,8 @@ function nativeChildren(native: readonly DocumentEditorBlock[], context: Documen
200
201
  product = { ...original?.type === 'image' ? structuredClone(original) : {}, id: block.id, type: 'image', ...assetId ? { assetId } : {}, alt: block.props.name, ...caption ? { caption } : {}, width: block.props.previewWidth, alignment: block.props.textAlignment }
201
202
  if (!assetId) delete product.assetId
202
203
  if (!caption) delete product.caption
203
- } else if (block.type === 'codeBlock') product = { ...original?.type === 'code' ? structuredClone(original) : {}, id: block.id, type: 'code', language: block.props.language, value: nativePlain(block) }
204
+ } else if (block.type === 'presmiumEmbed') product = { ...original?.type === 'embed' ? structuredClone(original) : {}, id: block.id, type: 'embed', source: { document: block.props.document, block: block.props.block } }
205
+ else if (block.type === 'codeBlock') product = { ...original?.type === 'code' ? structuredClone(original) : {}, id: block.id, type: 'code', language: block.props.language, value: nativePlain(block) }
204
206
  else {
205
207
  if (!original) throw new Error('document-opaque-reference')
206
208
  product = structuredClone(original)