@uibot/document-editor 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -0
- package/dist/index.js +1 -1
- package/dist/solutions.js +1 -1
- package/dist/spec.js +16 -16
- package/package.json +2 -2
package/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# UIBot document integration
|
|
2
|
+
|
|
3
|
+
`@uibot/document-editor` provides a rich editor, outline and Spec document pages.
|
|
4
|
+
The host owns document storage, access checks, revisions and model services.
|
|
5
|
+
Source availability does not confirm npm publication or production integration.
|
|
6
|
+
|
|
7
|
+
## Choose a page
|
|
8
|
+
|
|
9
|
+
- `document-writing`: focused editing.
|
|
10
|
+
- `document-reading`: readonly content with an outline derived from current headings.
|
|
11
|
+
- `document-library`: document selection with unsaved-edit protection.
|
|
12
|
+
- `document-assistant`: document editor and an independently bound chat surface.
|
|
13
|
+
|
|
14
|
+
Read the resource's complete Spec, controls, dependencies and limitations. Compile
|
|
15
|
+
with `DOCUMENT_SPEC_CATALOG` from `@uibot/document-editor/catalog`. The assistant
|
|
16
|
+
page also needs `CHAT_SPEC_CATALOG` from `@uibot/ai-chat/catalog` and
|
|
17
|
+
`STUDIO_CATALOG_ENTRIES` from `@uibot/blocks-studio/catalog` for its responsive Grid.
|
|
18
|
+
Register Grid from `@uibot/blocks-studio`, `createDocumentSpecEntries` from
|
|
19
|
+
`@uibot/document-editor/spec`, and `createChatSpecEntries` from `@uibot/ai-chat/spec`.
|
|
20
|
+
Use the consumer's existing registry assembly rather than replacing its entries.
|
|
21
|
+
Import `@uibot/document-editor/style.css` in the browser entry.
|
|
22
|
+
|
|
23
|
+
Spec document pages inherit the nearest host light/dark class or explicit
|
|
24
|
+
`data-theme` / `data-color-scheme` marker, falling back to CSS `color-scheme`
|
|
25
|
+
and then light. The editor and floating controls share that preference even
|
|
26
|
+
when the operating system uses another theme. Switching appearance preserves
|
|
27
|
+
the editor session and unsaved content. Direct `DocumentEditor` / `BlockEditor`
|
|
28
|
+
consumers can still pass `theme="light"` for white paper and dark text or
|
|
29
|
+
`theme="dark"`, or provide their own theme object.
|
|
30
|
+
|
|
31
|
+
## Host document binding
|
|
32
|
+
|
|
33
|
+
`createDocumentSpecEntries({ resolveHost })` resolves each binding ID to a
|
|
34
|
+
`DocumentSpecBinding`. For direct React use:
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
import { DocumentWorkspace, type DocumentSpecBinding } from "@uibot/document-editor/spec";
|
|
38
|
+
import "@uibot/document-editor/style.css";
|
|
39
|
+
|
|
40
|
+
export function WritingPage({ binding }: { binding: DocumentSpecBinding }) {
|
|
41
|
+
return <DocumentWorkspace binding={binding} autoSaveMs={0} />;
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The binding contains `document: EditableDocument` and `client: DocumentEditorClient`.
|
|
46
|
+
Supply blocks when available; markdown is a lossy fallback for initial content.
|
|
47
|
+
Opening another document requires a new document ID or remount. Switch binding ID
|
|
48
|
+
or remount on tenant/authorization changes, even if host-local document IDs match.
|
|
49
|
+
Preview state controls never replace an injected host draft.
|
|
50
|
+
|
|
51
|
+
The save client receives ID, title, blocks, markdown, `expectedRevision` and
|
|
52
|
+
`idempotencyKey`. Authorize the document and fields, compare revisions and write
|
|
53
|
+
atomically, then acknowledge the stored document and revision. A successful HTTP
|
|
54
|
+
request alone is not a successful document save. Handle these outcomes explicitly:
|
|
55
|
+
|
|
56
|
+
- Success advances the next expected revision; edits made during the request stay dirty.
|
|
57
|
+
- Conflict preserves the draft. Supply the remote document to enable the explicit
|
|
58
|
+
keep-local or load-remote actions. Loading an empty remote body clears the editor.
|
|
59
|
+
- Failure preserves input. Unknown results do not retry automatically; an explicit
|
|
60
|
+
retry of identical content keeps the original idempotency key. Reconcile that
|
|
61
|
+
operation in the host before attempting another write.
|
|
62
|
+
|
|
63
|
+
`autoSaveMs: 0` enables manual save; positive values debounce dirty-document saves.
|
|
64
|
+
Readonly documents disable editing and saving. Uploads require `client.uploadFile`.
|
|
65
|
+
|
|
66
|
+
## Assistant context and write boundaries
|
|
67
|
+
|
|
68
|
+
The built-in assistant page has separate `document` and `chat` binding IDs. It does
|
|
69
|
+
not automatically send editor content, selected text or unsaved drafts to a model,
|
|
70
|
+
and a chat reply does not replace document blocks. Map approved context explicitly
|
|
71
|
+
in the host; reauthorize every model request. Read `package:uibot-ai-chat` docs for
|
|
72
|
+
transport, citation identity, stop and late-event behavior.
|
|
73
|
+
|
|
74
|
+
If current unsaved content is required, compose the lower-level `BlockEditor`
|
|
75
|
+
with its `onChange` / `getValue` seam in the host. Make the chosen context and write
|
|
76
|
+
action explicit, protect newer edits and use the normal revision/idempotency
|
|
77
|
+
protocol. Do not mutate the editor DOM or infer authorization from a Spec binding ID.
|
|
78
|
+
|
|
79
|
+
## Preview and adoption checks
|
|
80
|
+
|
|
81
|
+
Only a trusted host can enable `demo: true`; Spec cannot do so. Demo documents and
|
|
82
|
+
chat state are session-local. Their “Saved” status is an in-memory acknowledgement,
|
|
83
|
+
not persistence evidence. Recompilation may reset this data. Playground export
|
|
84
|
+
saves configuration, including authored initial markdown, rather than runtime edits.
|
|
85
|
+
|
|
86
|
+
Verify strict compilation, declared controls, configuration undo/export/reopen,
|
|
87
|
+
manual and automatic saves, failure/unknown/conflict outcomes, empty remote content,
|
|
88
|
+
late acknowledgements, readonly behavior and mobile layout. Verify Studio artifact
|
|
89
|
+
revision saves separately from document-client saves. Record local demonstrations,
|
|
90
|
+
real host integration and distribution evidence separately.
|
package/dist/index.js
CHANGED
|
@@ -10,4 +10,4 @@ import{en as ee,zh as te}from"@blocknote/core/locales";import{BlockNoteView as n
|
|
|
10
10
|
.${a} [data-prev-level="3"]{--prev-level:var(--uibot-doc-h3,1.25em)}
|
|
11
11
|
.${a} [data-prev-level="4"]{--prev-level:var(--uibot-doc-h4,1.125em)}
|
|
12
12
|
.${a} [data-prev-level="5"],.${a} [data-prev-level="6"]{--prev-level:1em}
|
|
13
|
-
`,K=re(function(n,u){let{blocks:m,markdown:x,onChange:y,readOnly:D,locale:p="zh-CN",uploadFile:o}=n,i=O(""),h=O(!1),f=O(y);f.current=y;let t=oe({dictionary:p==="en"?ee:te,...m&&m.length>0?{initialContent:m}:{},...o?{uploadFile:o}:{}},[p]),l=A(()=>({blocks:t.document,markdown:t.blocksToMarkdownLossy()}),[t]),v=A((c,k)=>{h.current=!0;try{if(c&&c.length>0)t.replaceBlocks(t.document,c);else
|
|
13
|
+
`,K=re(function(n,u){let{blocks:m,markdown:x,onChange:y,readOnly:D,locale:p="zh-CN",uploadFile:o}=n,i=O(""),h=O(!1),f=O(y);f.current=y;let t=oe({dictionary:p==="en"?ee:te,...m&&m.length>0?{initialContent:m}:{},...o?{uploadFile:o}:{}},[p]),l=A(()=>({blocks:t.document,markdown:t.blocksToMarkdownLossy()}),[t]),v=A((c,k)=>{h.current=!0;try{if(c&&c.length>0)t.replaceBlocks(t.document,c);else t.replaceBlocks(t.document,k?t.tryParseMarkdownToBlocks(k):[{type:"paragraph"}])}finally{i.current=M(t.document),h.current=!1}},[t]);return ie(()=>{if(m&&m.length>0)i.current=M(t.document);else v(null,x)},[t]),ae(u,()=>({getValue:l,setContent:(c)=>v(c.blocks,c.markdown)}),[l,v]),se(ce,{children:[Y("style",{"data-uibot":"document-type-scale",children:le}),Y(ne,{className:[a,n.className].filter(Boolean).join(" "),editor:t,editable:!D,theme:n.theme??"light",onChange:()=>{if(h.current||!i.current)return;let c=M(t.document);if(c===i.current)return;i.current=c,f.current?.(l())}})]})});import{useCallback as J,useEffect as C,useReducer as de,useRef as g,useState as ue}from"react";function W(e){return{phase:"clean",revision:e,message:"",remote:null,editedWhileSaving:!1}}function E(e){return e.phase==="dirty"||e.phase==="error"||e.phase==="unknown"}function I(e){return e.phase!=="clean"}function V(e,n){switch(n.type){case"edit":if(e.phase==="saving")return{...e,editedWhileSaving:!0};if(e.phase==="conflict")return e;return{...e,phase:"dirty",message:e.phase==="dirty"?e.message:""};case"save-start":if(!E(e))return e;return{...e,phase:"saving",message:"",editedWhileSaving:!1};case"saved":return{phase:e.editedWhileSaving?"dirty":"clean",revision:n.revision,message:"",remote:null,editedWhileSaving:!1};case"conflict":return{...e,phase:"conflict",message:n.message,remote:n.remote};case"failed":return{...e,phase:n.unknown?"unknown":"error",message:n.message,editedWhileSaving:!1};case"adopt-revision":return e.phase==="conflict"?e:{...e,revision:n.revision};case"keep-mine":return{phase:"dirty",revision:n.revision,message:"",remote:null,editedWhileSaving:!1};case"use-remote":return{phase:"clean",revision:n.revision,message:"",remote:null,editedWhileSaving:!1}}}function z(e,n,u){return e&&e.fingerprint===n?e:{fingerprint:n,key:u()}}import{jsx as d,jsxs as w,Fragment as ge}from"react/jsx-runtime";var me={"zh-CN":{title:"标题",titlePlaceholder:"无标题",clean:"已保存",dirty:"未保存的更改",saving:"保存中…",error:"保存失败,草稿已保留。",unknown:"保存结果未知,草稿已保留。",retry:"重试保存",save:"保存",conflict:"文档已在别处被修改",keepMine:"保留我的修改并覆盖",useRemote:"载入最新版本",readOnly:"只读"},en:{title:"Title",titlePlaceholder:"Untitled",clean:"Saved",dirty:"Unsaved changes",saving:"Saving…",error:"Saving failed. Your draft has been kept.",unknown:"The save result is unknown. Your draft has been kept.",retry:"Retry save",save:"Save",conflict:"This document was changed elsewhere",keepMine:"Keep my changes and overwrite",useRemote:"Load latest version",readOnly:"Read only"}},pe=(e,n)=>`${JSON.stringify(e)}\x00${n}`,ve=()=>typeof crypto<"u"&&("randomUUID"in crypto)?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;function he(e){let{document:n,client:u,locale:m="zh-CN",hideTitle:x,onDirtyChange:y,onBusyChange:D}=e,p=e.autoSaveMs??1500,o=me[m],i=n.readOnly===!0,h=u.uploadFile?.bind(u),f=g(e.onSaved);f.current=e.onSaved;let[t,l]=de(V,n.revision,W),v=g(t);v.current=t;let[c,k]=ue(n.title),B=g(n.title),T=g(null),b=g(null),R=g(!1),P=e.revision;C(()=>{if(P!==void 0)l({type:"adopt-revision",revision:P})},[P]);let F=J(()=>{if(!i)l({type:"edit"})},[i]),S=J(async()=>{let r=T.current;if(!r||i||R.current||!E(v.current))return;R.current=!0;let{blocks:U,markdown:G}=r.getValue(),j=B.current,Q=pe(U,j);b.current=z(b.current,Q,ve);let Z={id:n.id,title:j,blocks:U,markdown:G,expectedRevision:v.current.revision,idempotencyKey:b.current.key};l({type:"save-start"});try{let s=await u.save(Z);if(s.ok)b.current=null,l({type:"saved",revision:s.document.revision}),f.current?.(s.document);else if(s.error.code==="conflict")l({type:"conflict",message:s.error.message,remote:s.error.remote??null});else l({type:"failed",message:s.error.message,unknown:s.error.code==="unknown"})}catch(s){l({type:"failed",message:s instanceof Error?s.message:o.unknown,unknown:!0})}finally{R.current=!1}},[u,n.id,i,o.unknown]);C(()=>{if(t.phase!=="dirty"||p<=0)return;let r=setTimeout(()=>void S(),p);return()=>clearTimeout(r)},[t.phase,p,S]);let H=I(t),L=t.phase==="saving";C(()=>y?.(H),[H,y]),C(()=>D?.(L),[L,D]);let _=(r)=>{T.current?.setContent({blocks:r.blocks,markdown:r.markdown}),B.current=r.title,k(r.title),b.current=null,l({type:"use-remote",revision:r.revision})},N={message:t.message,remote:t.remote,keepMine:()=>t.remote&&l({type:"keep-mine",revision:t.remote.revision}),useRemote:()=>t.remote&&_(t.remote)},X=(r)=>{if((r.metaKey||r.ctrlKey)&&r.key.toLowerCase()==="s")r.preventDefault(),S()},q=t.phase==="clean"?i?o.readOnly:o.clean:t.phase==="saving"?o.saving:t.phase==="error"?`${o.error}${t.message?` ${t.message}`:""}`:t.phase==="unknown"?o.unknown:o.dirty;return w("div",{"data-uibot":"document-editor",className:e.className,style:e.style,onKeyDown:X,children:[x?null:d("input",{"aria-label":o.title,placeholder:o.titlePlaceholder,value:c,readOnly:i,onChange:(r)=>{B.current=r.currentTarget.value,k(r.currentTarget.value),F()},style:{width:"100%",border:0,outline:"none",background:"transparent",color:"inherit",font:"inherit",fontSize:30,fontWeight:700,padding:"0 0 12px 54px",boxSizing:"border-box"}}),t.phase==="conflict"?e.renderConflict?e.renderConflict(N):w("div",{role:"alert","data-uibot":"document-conflict",style:{padding:"8px 0",display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[d("strong",{children:o.conflict}),d("span",{children:t.message}),t.remote?w(ge,{children:[d("button",{type:"button",onClick:N.keepMine,children:o.keepMine}),d("button",{type:"button",onClick:N.useRemote,children:o.useRemote})]}):null]}):null,d(K,{ref:T,blocks:n.blocks,markdown:n.markdown,readOnly:i||t.phase==="conflict",locale:m,...e.theme!==void 0?{theme:e.theme}:{},...h?{uploadFile:h}:{},onChange:F}),w("div",{"data-uibot":"document-status",role:t.phase==="error"||t.phase==="unknown"?"alert":"status",style:{fontSize:12,opacity:0.7,padding:"8px 0 0 54px",display:"flex",gap:8,alignItems:"center"},children:[d("span",{children:q}),p<=0&&!i&&t.phase==="dirty"?d("button",{type:"button",onClick:()=>void S(),children:o.save}):null,t.phase==="error"||t.phase==="unknown"?d("button",{type:"button",onClick:()=>void S(),children:o.retry}):null]})]})}export{K as BlockEditor,he as DocumentEditor,E as canSaveDocument,V as documentSaveReducer,W as initialDocumentSaveState,I as isDocumentDirty,z as nextIdempotencyKey};
|
package/dist/solutions.js
CHANGED
|
@@ -9,4 +9,4 @@ Write, select text, and explore the formatting controls.
|
|
|
9
9
|
## Next steps
|
|
10
10
|
|
|
11
11
|
- Review the draft
|
|
12
|
-
- Connect your document host`,readOnly:t==="reading",autoSaveMs:1500,locale:"zh-CN",previewState:"ready",variant:t}};return{id:e,title:{zh:n,en:o},description:`${o}: shared rich editor with revision-aware host saves and protected drafts.`,solution:{functions:t==="assistant"?["documents","chat"]:["documents"],scenarios:[t],unit:"page",industries:["knowledge","education"],readiness:"interactive-demo",hostRequirements:["Authorized document and DocumentEditorClient","Host revision and idempotency handling",...t==="assistant"?["Authorized chat binding"]:[]],limitations:["Preview documents are stored in memory for this compilation only.","Sharing, collaboration, file upload and model editing require host services."]},spec:{version:"2.0",pages:[{id:e,path:`/${e}`,title:o,blocks:t==="assistant"?[{type:"Grid",props:{cols:2,gap:"md"},children:[i,{id:`${e}-chat`,type:"ChatWorkspace",props:{bindingId:"chat",variant:"copilot",title:"Writing assistant / 写作助手"}}]}]:[i]}]},controls:[...t!=="assistant"?[{id:"layout",label:{zh:"文档布局",en:"Document layout"},values:["writing","reading","library"],target:{pageId:e,blockId:`${e}-editor`,property:"variant"}}]:[],{id:"readonly",label:{zh:"只读",en:"Read only"},values:[!1,!0],target:{pageId:e,blockId:`${e}-editor`,property:"readOnly"}},{id:"autosave",label:{zh:"自动保存间隔",en:"Autosave delay"},values:[0,1500,5000],target:{pageId:e,blockId:`${e}-editor`,property:"autoSaveMs"}},{id:"state",label:{zh:"演示状态",en:"Demo state"},values:["ready","empty","loading","error","conflict","readonly"],target:{pageId:e,blockId:`${e}-editor`,property:"previewState"}}]}});export{a as DOCUMENT_SOLUTIONS};
|
|
12
|
+
- Connect your document host`,readOnly:t==="reading",autoSaveMs:1500,locale:"zh-CN",previewState:"ready",variant:t}};return{id:e,title:{zh:n,en:o},description:`${o}: shared rich editor with revision-aware host saves and protected drafts.`,solution:{functions:t==="assistant"?["documents","chat"]:["documents"],scenarios:[t],unit:"page",industries:["knowledge","education"],readiness:"interactive-demo",hostRequirements:["Authorized document and DocumentEditorClient","Host revision and idempotency handling",...t==="assistant"?["Authorized chat binding and explicit host mapping of approved document context"]:[]],limitations:["Preview documents are stored in memory for this compilation only.","Sharing, collaboration, file upload and model editing require host services.",...t==="assistant"?["The assistant does not automatically read or replace the editor's unsaved draft."]:[]]},spec:{version:"2.0",pages:[{id:e,path:`/${e}`,title:o,blocks:t==="assistant"?[{type:"Grid",props:{cols:2,gap:"md",responsive:!0},children:[i,{id:`${e}-chat`,type:"ChatWorkspace",props:{bindingId:"chat",variant:"copilot",title:"Writing assistant / 写作助手"}}]}]:[i]}]},controls:[...t!=="assistant"?[{id:"layout",label:{zh:"文档布局",en:"Document layout"},values:["writing","reading","library"],target:{pageId:e,blockId:`${e}-editor`,property:"variant"}}]:[],{id:"readonly",label:{zh:"只读",en:"Read only"},values:[!1,!0],target:{pageId:e,blockId:`${e}-editor`,property:"readOnly"}},{id:"autosave",label:{zh:"自动保存间隔",en:"Autosave delay"},values:[0,1500,5000],target:{pageId:e,blockId:`${e}-editor`,property:"autoSaveMs"}},{id:"state",label:{zh:"演示状态",en:"Demo state"},values:["ready","empty","loading","error","conflict","readonly"],target:{pageId:e,blockId:`${e}-editor`,property:"previewState"}}]}});export{a as DOCUMENT_SOLUTIONS};
|
package/dist/spec.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import{useMemo as
|
|
2
|
-
.${
|
|
3
|
-
.${
|
|
4
|
-
.${
|
|
5
|
-
.${
|
|
6
|
-
.${
|
|
7
|
-
.${
|
|
8
|
-
.${
|
|
9
|
-
.${
|
|
10
|
-
.${
|
|
11
|
-
.${
|
|
12
|
-
.${
|
|
13
|
-
`,
|
|
1
|
+
import{useEffect as xe,useMemo as oe,useRef as Te,useState as z}from"react";import{BlockNoteContext as Ne}from"@blocknote/react";import{useCallback as Z,useEffect as L,useReducer as he,useRef as P,useState as ye}from"react";import{en as le,zh as se}from"@blocknote/core/locales";import{BlockNoteView as ce}from"@blocknote/mantine";import{useCreateBlockNote as de}from"@blocknote/react";import{forwardRef as ue,useCallback as Y,useEffect as me,useImperativeHandle as ge,useRef as A}from"react";import{jsx as j,jsxs as fe,Fragment as pe}from"react/jsx-runtime";var K=(e)=>JSON.stringify(e),h="uibot-block-editor",ve=`
|
|
2
|
+
.${h} .bn-block-outer{line-height:var(--uibot-doc-line-height,1.75)}
|
|
3
|
+
.${h} [data-content-type=heading]{line-height:1.4;padding-top:var(--uibot-doc-heading-gap,14px);--level:var(--uibot-doc-h1,1.625em)}
|
|
4
|
+
.${h} [data-content-type=heading][data-level="2"]{--level:var(--uibot-doc-h2,1.375em)}
|
|
5
|
+
.${h} [data-content-type=heading][data-level="3"]{--level:var(--uibot-doc-h3,1.25em)}
|
|
6
|
+
.${h} [data-content-type=heading][data-level="4"]{--level:var(--uibot-doc-h4,1.125em)}
|
|
7
|
+
.${h} [data-content-type=heading][data-level="5"],.${h} [data-content-type=heading][data-level="6"]{--level:1em}
|
|
8
|
+
.${h} [data-prev-level="1"]{--prev-level:var(--uibot-doc-h1,1.625em)}
|
|
9
|
+
.${h} [data-prev-level="2"]{--prev-level:var(--uibot-doc-h2,1.375em)}
|
|
10
|
+
.${h} [data-prev-level="3"]{--prev-level:var(--uibot-doc-h3,1.25em)}
|
|
11
|
+
.${h} [data-prev-level="4"]{--prev-level:var(--uibot-doc-h4,1.125em)}
|
|
12
|
+
.${h} [data-prev-level="5"],.${h} [data-prev-level="6"]{--prev-level:1em}
|
|
13
|
+
`,q=ue(function(n,m){let{blocks:g,markdown:y,onChange:v,readOnly:c,locale:d="zh-CN",uploadFile:o}=n,i=A(""),a=A(!1),p=A(v);p.current=v;let t=de({dictionary:d==="en"?le:se,...g&&g.length>0?{initialContent:g}:{},...o?{uploadFile:o}:{}},[d]),s=Y(()=>({blocks:t.document,markdown:t.blocksToMarkdownLossy()}),[t]),k=Y((f,S)=>{a.current=!0;try{if(f&&f.length>0)t.replaceBlocks(t.document,f);else t.replaceBlocks(t.document,S?t.tryParseMarkdownToBlocks(S):[{type:"paragraph"}])}finally{i.current=K(t.document),a.current=!1}},[t]);return me(()=>{if(g&&g.length>0)i.current=K(t.document);else k(null,y)},[t]),ge(m,()=>({getValue:s,setContent:(f)=>k(f.blocks,f.markdown)}),[s,k]),fe(pe,{children:[j("style",{"data-uibot":"document-type-scale",children:ve}),j(ce,{className:[h,n.className].filter(Boolean).join(" "),editor:t,editable:!c,theme:n.theme??"light",onChange:()=>{if(a.current||!i.current)return;let f=K(t.document);if(f===i.current)return;i.current=f,p.current?.(s())}})]})});function G(e){return{phase:"clean",revision:e,message:"",remote:null,editedWhileSaving:!1}}function V(e){return e.phase==="dirty"||e.phase==="error"||e.phase==="unknown"}function J(e){return e.phase!=="clean"}function X(e,n){switch(n.type){case"edit":if(e.phase==="saving")return{...e,editedWhileSaving:!0};if(e.phase==="conflict")return e;return{...e,phase:"dirty",message:e.phase==="dirty"?e.message:""};case"save-start":if(!V(e))return e;return{...e,phase:"saving",message:"",editedWhileSaving:!1};case"saved":return{phase:e.editedWhileSaving?"dirty":"clean",revision:n.revision,message:"",remote:null,editedWhileSaving:!1};case"conflict":return{...e,phase:"conflict",message:n.message,remote:n.remote};case"failed":return{...e,phase:n.unknown?"unknown":"error",message:n.message,editedWhileSaving:!1};case"adopt-revision":return e.phase==="conflict"?e:{...e,revision:n.revision};case"keep-mine":return{phase:"dirty",revision:n.revision,message:"",remote:null,editedWhileSaving:!1};case"use-remote":return{phase:"clean",revision:n.revision,message:"",remote:null,editedWhileSaving:!1}}}function Q(e,n,m){return e&&e.fingerprint===n?e:{fingerprint:n,key:m()}}import{jsx as C,jsxs as W,Fragment as De}from"react/jsx-runtime";var be={"zh-CN":{title:"标题",titlePlaceholder:"无标题",clean:"已保存",dirty:"未保存的更改",saving:"保存中…",error:"保存失败,草稿已保留。",unknown:"保存结果未知,草稿已保留。",retry:"重试保存",save:"保存",conflict:"文档已在别处被修改",keepMine:"保留我的修改并覆盖",useRemote:"载入最新版本",readOnly:"只读"},en:{title:"Title",titlePlaceholder:"Untitled",clean:"Saved",dirty:"Unsaved changes",saving:"Saving…",error:"Saving failed. Your draft has been kept.",unknown:"The save result is unknown. Your draft has been kept.",retry:"Retry save",save:"Save",conflict:"This document was changed elsewhere",keepMine:"Keep my changes and overwrite",useRemote:"Load latest version",readOnly:"Read only"}},ke=(e,n)=>`${JSON.stringify(e)}\x00${n}`,Se=()=>typeof crypto<"u"&&("randomUUID"in crypto)?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;function ee(e){let{document:n,client:m,locale:g="zh-CN",hideTitle:y,onDirtyChange:v,onBusyChange:c}=e,d=e.autoSaveMs??1500,o=be[g],i=n.readOnly===!0,a=m.uploadFile?.bind(m),p=P(e.onSaved);p.current=e.onSaved;let[t,s]=he(X,n.revision,G),k=P(t);k.current=t;let[f,S]=ye(n.title),R=P(n.title),I=P(null),B=P(null),O=P(!1),E=e.revision;L(()=>{if(E!==void 0)s({type:"adopt-revision",revision:E})},[E]);let D=Z(()=>{if(!i)s({type:"edit"})},[i]),x=Z(async()=>{let l=I.current;if(!l||i||O.current||!V(k.current))return;O.current=!0;let{blocks:U,markdown:re}=l.getValue(),_=R.current,ie=ke(U,_);B.current=Q(B.current,ie,Se);let ae={id:n.id,title:_,blocks:U,markdown:re,expectedRevision:k.current.revision,idempotencyKey:B.current.key};s({type:"save-start"});try{let b=await m.save(ae);if(b.ok)B.current=null,s({type:"saved",revision:b.document.revision}),p.current?.(b.document);else if(b.error.code==="conflict")s({type:"conflict",message:b.error.message,remote:b.error.remote??null});else s({type:"failed",message:b.error.message,unknown:b.error.code==="unknown"})}catch(b){s({type:"failed",message:b instanceof Error?b.message:o.unknown,unknown:!0})}finally{O.current=!1}},[m,n.id,i,o.unknown]);L(()=>{if(t.phase!=="dirty"||d<=0)return;let l=setTimeout(()=>void x(),d);return()=>clearTimeout(l)},[t.phase,d,x]);let r=J(t),T=t.phase==="saving";L(()=>v?.(r),[r,v]),L(()=>c?.(T),[T,c]);let M=(l)=>{I.current?.setContent({blocks:l.blocks,markdown:l.markdown}),R.current=l.title,S(l.title),B.current=null,s({type:"use-remote",revision:l.revision})},u={message:t.message,remote:t.remote,keepMine:()=>t.remote&&s({type:"keep-mine",revision:t.remote.revision}),useRemote:()=>t.remote&&M(t.remote)},N=(l)=>{if((l.metaKey||l.ctrlKey)&&l.key.toLowerCase()==="s")l.preventDefault(),x()},H=t.phase==="clean"?i?o.readOnly:o.clean:t.phase==="saving"?o.saving:t.phase==="error"?`${o.error}${t.message?` ${t.message}`:""}`:t.phase==="unknown"?o.unknown:o.dirty;return W("div",{"data-uibot":"document-editor",className:e.className,style:e.style,onKeyDown:N,children:[y?null:C("input",{"aria-label":o.title,placeholder:o.titlePlaceholder,value:f,readOnly:i,onChange:(l)=>{R.current=l.currentTarget.value,S(l.currentTarget.value),D()},style:{width:"100%",border:0,outline:"none",background:"transparent",color:"inherit",font:"inherit",fontSize:30,fontWeight:700,padding:"0 0 12px 54px",boxSizing:"border-box"}}),t.phase==="conflict"?e.renderConflict?e.renderConflict(u):W("div",{role:"alert","data-uibot":"document-conflict",style:{padding:"8px 0",display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[C("strong",{children:o.conflict}),C("span",{children:t.message}),t.remote?W(De,{children:[C("button",{type:"button",onClick:u.keepMine,children:o.keepMine}),C("button",{type:"button",onClick:u.useRemote,children:o.useRemote})]}):null]}):null,C(q,{ref:I,blocks:n.blocks,markdown:n.markdown,readOnly:i||t.phase==="conflict",locale:g,...e.theme!==void 0?{theme:e.theme}:{},...a?{uploadFile:a}:{},onChange:D}),W("div",{"data-uibot":"document-status",role:t.phase==="error"||t.phase==="unknown"?"alert":"status",style:{fontSize:12,opacity:0.7,padding:"8px 0 0 54px",display:"flex",gap:8,alignItems:"center"},children:[C("span",{children:H}),d<=0&&!i&&t.phase==="dirty"?C("button",{type:"button",onClick:()=>void x(),children:o.save}):null,t.phase==="error"||t.phase==="unknown"?C("button",{type:"button",onClick:()=>void x(),children:o.retry}):null]})]})}import{useEffect as Ce,useState as we}from"react";import{jsx as te}from"react/jsx-runtime";function ne({root:e,locale:n}){let[m,g]=we([]);return Ce(()=>{let y=e.current;if(!y)return;let v=new WeakMap,c=0,d=()=>{let i=Array.from(y.querySelectorAll(".bn-block-content[data-content-type=heading]")).flatMap((a)=>{let p=a.textContent?.replace(/\s+/g," ").trim(),t=v.get(a);if(t===void 0)t=c++,v.set(a,t);return p?[{id:t,node:a,text:p,level:Math.max(1,Math.min(6,Number(a.dataset.level)||1))}]:[]});g((a)=>a.length===i.length&&a.every((p,t)=>{let s=i[t];return s?.node===p.node&&s.text===p.text&&s.level===p.level})?a:i)};d();let o=new MutationObserver(d);return o.observe(y,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["data-content-type","data-level"]}),()=>o.disconnect()},[e]),m.length?m.map(({id:y,node:v,text:c,level:d})=>te("button",{type:"button",className:"block text-left text-sm underline",style:{paddingInlineStart:`${(d-1)*0.75}rem`},onClick:()=>{if(e.current?.contains(v))v.scrollIntoView({block:"center",behavior:"smooth"})},children:c},y)):te("p",{className:"text-sm text-muted-foreground",children:n==="en"?"No headings yet":"暂无标题"})}var Ee={DocumentWorkspace:{name:"DocumentWorkspace",description:"Rich document editing using the shared editor and host-owned revision/CAS client.",category:"feature",level:"L2",props:{variant:{enum:["writing","reading","library","assistant"],default:"writing"},bindingId:{type:"string",default:"document"},title:{type:"string",default:"Untitled / 无标题"},markdown:{type:"string",default:`# Your next idea
|
|
14
14
|
|
|
15
|
-
Write something useful.`},readOnly:{type:"boolean",default:!1},autoSaveMs:{type:"number",default:1500},locale:{enum:["zh-CN","en"],default:"zh-CN"},previewState:{enum:["ready","empty","loading","error","conflict","readonly"],default:"ready"}},events:{},tags:["interactive","documents","editor","writing"],constraints:["Inject an authorized document/client binding. Local preview saves are not persistence receipts."]}};import{jsx as
|
|
15
|
+
Write something useful.`},readOnly:{type:"boolean",default:!1},autoSaveMs:{type:"number",default:1500},locale:{enum:["zh-CN","en"],default:"zh-CN"},previewState:{enum:["ready","empty","loading","error","conflict","readonly"],default:"ready"}},events:{},tags:["interactive","documents","editor","writing"],constraints:["Inject an authorized document/client binding. Local preview saves are not persistence receipts."]}};import{jsx as w,jsxs as F}from"react/jsx-runtime";var Be={fontFamily:"var(--font-body, ui-sans-serif, system-ui, sans-serif)",colors:{editor:{text:"var(--foreground)",background:"var(--background)"},menu:{text:"var(--popover-foreground, var(--foreground))",background:"var(--popover, var(--background))"},tooltip:{text:"var(--popover-foreground, var(--foreground))",background:"var(--popover, var(--background))"},hovered:{text:"var(--accent-foreground)",background:"var(--accent)"},selected:{text:"var(--accent-foreground)",background:"var(--accent)"},disabled:{text:"var(--muted-foreground)",background:"var(--muted)"},border:"var(--border)",shadow:"var(--border)",sideMenu:"var(--muted-foreground)"}};function Me({bindingId:e="document",title:n="Your next idea / 新文档",markdown:m=`# Your next idea
|
|
16
16
|
|
|
17
|
-
Write something useful.`,readOnly:
|
|
17
|
+
Write something useful.`,readOnly:g=!1,autoSaveMs:y=1500,locale:v="zh-CN",previewState:c="ready",variant:d="writing",binding:o,demo:i=!1}){let[a,p]=z("main"),[t,s]=z(!1),[k,f]=z(!1),S=Te(null),[R,I]=z("light"),B=oe(()=>({colorSchemePreference:R}),[R]),O=oe(()=>({bindingId:e,title:n,markdown:m,readOnly:g,previewState:c,entries:new Map}),[e,n,m,g,c]),E=O.entries.get(a);if(!E)E=(()=>{let r={id:`${e}:${a}`,title:a==="main"?n:"Integration notes / 接入笔记",markdown:c==="empty"?"":a==="main"?m:`# Integration notes
|
|
18
18
|
|
|
19
|
-
The host owns authorization, revisions and storage.`,blocks:null,revision:1,readOnly:
|
|
19
|
+
The host owns authorization, revisions and storage.`,blocks:null,revision:1,readOnly:g||c==="readonly"},T=!1,M=new Map,u={document:r,client:{async save(N){let H=M.get(N.idempotencyKey);if(H)return H;if(c==="error")return{ok:!1,error:{code:"validation",message:"演示保存错误 / Demo save error"}};if(c==="conflict"&&!T||N.expectedRevision!==r.revision)return T=!0,r={...r,revision:Number(r.revision)+1},{ok:!1,error:{code:"conflict",message:"演示版本冲突 / Demo revision conflict",remote:{...r,revision:r.revision}}};r={...r,title:N.title,blocks:N.blocks,markdown:N.markdown,revision:Number(r.revision)+1},u.document=r;let l={ok:!0,document:r};return M.set(N.idempotencyKey,l),l}}};return u})(),O.entries.set(a,E);let D=o??(i?E:void 0),x=!!D&&!(i&&!o&&c==="loading");if(xe(()=>{if(!x)return;let r=S.current;if(!r)return;let T=()=>{let u=r.closest('.light, .dark, [data-theme="light"], [data-theme="dark"], [data-color-scheme="light"], [data-color-scheme="dark"]');I(u?u.classList.contains("dark")||u.getAttribute("data-theme")==="dark"||u.getAttribute("data-color-scheme")==="dark"?"dark":"light":getComputedStyle(r).colorScheme==="dark"?"dark":"light")};T();let M=new MutationObserver(T);for(let u=r;u;u=u.parentElement)M.observe(u,{attributes:!0,attributeFilter:["class","style","data-theme","data-color-scheme"]});return()=>M.disconnect()},[x]),i&&!o&&c==="loading")return w("p",{role:"status",className:"p-6",children:"演示加载中 / Demo loading…"});if(!D)return w("p",{role:"status",className:"p-6",children:"文档尚未接入:宿主需提供文档与保存接口。Document host required."});return F("section",{ref:S,className:"min-h-80 rounded border bg-background text-foreground",children:[w("p",{className:"border-b px-4 py-2 text-xs text-muted-foreground",children:i&&!o?"本地内存演示 · 刷新后清空 · 不代表持久化保存":"宿主文档 / Host document"}),F("div",{className:"flex flex-col md:flex-row",children:[(d==="reading"||d==="library")&&F("nav",{"aria-label":"Document navigation / 文档导航",className:"shrink-0 space-y-3 border-b p-4 md:w-52 md:border-b-0 md:border-r",children:[d==="library"&&["main","integration"].map((r)=>w("button",{type:"button",disabled:k||!!o,"aria-pressed":a===r,className:"block text-left text-sm underline disabled:opacity-50",onClick:()=>{if(t&&!window.confirm("放弃当前文档的未保存更改?Discard unsaved changes?"))return;s(!1),p(r)},children:r==="main"?"项目笔记 / Project notes":"接入笔记 / Integration notes"},r)),d==="reading"&&w(ne,{root:S,locale:v})]}),w("div",{className:"min-w-0 flex-1",children:w(Ne.Provider,{value:B,children:w(ee,{theme:Be,onDirtyChange:s,onBusyChange:f,document:{...D.document,readOnly:D.document.readOnly||g},client:D.client,autoSaveMs:Math.max(0,y),locale:v},`${D.document.id}:${o?"host":c}`)})})]})]})}function Xe(e={}){return{DocumentWorkspace:{component:(n)=>w(Me,{variant:String(n.variant??"writing"),bindingId:String(n.bindingId??"document"),title:typeof n.title==="string"?n.title:void 0,markdown:typeof n.markdown==="string"?n.markdown:void 0,readOnly:n.readOnly===!0,autoSaveMs:typeof n.autoSaveMs==="number"?n.autoSaveMs:1500,locale:n.locale==="en"?"en":"zh-CN",previewState:String(n.previewState??"ready"),binding:e.resolveHost?.(String(n.bindingId??"document")),demo:e.demo===!0},String(n.bindingId??"document"))}}}export{Ee as DOCUMENT_SPEC_CATALOG,Me as DocumentWorkspace,Xe as createDocumentSpecEntries};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uibot/document-editor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"@blocknote/core": "0.56.0",
|
|
50
50
|
"@blocknote/mantine": "0.56.0",
|
|
51
51
|
"@blocknote/react": "0.56.0",
|
|
52
|
-
"@uibot/contracts": "^0.
|
|
52
|
+
"@uibot/contracts": "^0.20.0"
|
|
53
53
|
},
|
|
54
54
|
"scripts": {
|
|
55
55
|
"build": "rm -rf dist && bun build --minify ./src/index.ts ./src/spec.tsx ./src/spec-catalog.ts ./src/solutions.ts --outdir ./dist --format esm --target browser --packages external && cp ./src/document-editor.css ./dist/ && bun x tsc -p tsconfig.json",
|