@uibot/document-editor 0.0.0-stage → 0.2.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.
@@ -0,0 +1,60 @@
1
+ export interface BlockEditorValue {
2
+ blocks: unknown[];
3
+ /** Lossy markdown rendering of `blocks`. */
4
+ markdown: string;
5
+ }
6
+ export interface BlockEditorHandle {
7
+ /** Current content, read at call time (never stale). */
8
+ getValue(): BlockEditorValue;
9
+ /** Replaces the content, e.g. to adopt another revision. Does not fire `onChange`. */
10
+ setContent(content: {
11
+ blocks: unknown[] | null;
12
+ markdown: string;
13
+ }): void;
14
+ }
15
+ type ThemeColor = Partial<{
16
+ text: string;
17
+ background: string;
18
+ }>;
19
+ type BlockEditorColorScheme = Partial<{
20
+ editor: ThemeColor;
21
+ menu: ThemeColor;
22
+ tooltip: ThemeColor;
23
+ hovered: ThemeColor;
24
+ selected: ThemeColor;
25
+ disabled: ThemeColor;
26
+ shadow: string;
27
+ border: string;
28
+ sideMenu: string;
29
+ highlights: Partial<Record<"gray" | "brown" | "red" | "orange" | "yellow" | "green" | "blue" | "purple" | "pink", ThemeColor>>;
30
+ }>;
31
+ type BlockEditorThemeObject = Partial<{
32
+ colors: BlockEditorColorScheme;
33
+ borderRadius: number;
34
+ fontFamily: string;
35
+ }>;
36
+ /** Theme shape owned by this public API, kept independent from BlockNote declarations. */
37
+ export type BlockEditorTheme = "light" | "dark" | BlockEditorThemeObject | {
38
+ light: BlockEditorThemeObject;
39
+ dark: BlockEditorThemeObject;
40
+ };
41
+ export interface BlockEditorProps {
42
+ /** Initial block tree. Null/empty builds the tree from `markdown`. Remount (`key`) to reset. */
43
+ blocks: unknown[] | null;
44
+ markdown: string;
45
+ /** Fires on real edits only: loading content and `setContent` never count. */
46
+ onChange?(value: BlockEditorValue): void;
47
+ readOnly?: boolean;
48
+ locale?: "zh-CN" | "en";
49
+ /** BlockNote theme: "light", "dark" or a theme object carrying the host's brand colours. */
50
+ theme?: BlockEditorTheme;
51
+ /** Uploads a dropped or pasted file and returns its URL. Absent means uploads are off. */
52
+ uploadFile?(file: File): Promise<string>;
53
+ className?: string;
54
+ }
55
+ /**
56
+ * BlockNote surface without any storage or save logic: hosts that own their own save
57
+ * flow (draft + explicit save) use it directly; `DocumentEditor` builds autosave on top.
58
+ */
59
+ export declare const BlockEditor: import("react").ForwardRefExoticComponent<BlockEditorProps & import("react").RefAttributes<BlockEditorHandle>>;
60
+ export {};
@@ -0,0 +1,43 @@
1
+ import type { DocumentEditorClient, EditableDocument } from "@uibot/contracts";
2
+ import { type CSSProperties, type ReactNode } from "react";
3
+ import { type BlockEditorTheme } from "./block-editor.js";
4
+ export interface DocumentConflictContext {
5
+ message: string;
6
+ /** Stored document, when the host supplied it with the conflict. Needed for both resolutions. */
7
+ remote: EditableDocument | null;
8
+ /** Keep the local draft and save it over the stored revision. */
9
+ keepMine(): void;
10
+ /** Drop the draft and load the stored document. */
11
+ useRemote(): void;
12
+ }
13
+ export interface DocumentEditorProps {
14
+ /** Loaded document. Remount (`key`) to open a different one. */
15
+ document: EditableDocument;
16
+ client: DocumentEditorClient;
17
+ locale?: "zh-CN" | "en";
18
+ /** Idle time before a dirty draft saves itself; 0 turns autosave off. Default 1500. */
19
+ autoSaveMs?: number;
20
+ /** BlockNote theme: "light", "dark" or a theme object (host brand colours). */
21
+ theme?: BlockEditorTheme;
22
+ /**
23
+ * Revision the host reached by writing the document elsewhere (tags, notes) while the body
24
+ * stayed as the editor has it. Pass it only for such own writes: adopting a revision another
25
+ * writer produced would let the next save overwrite their body changes.
26
+ */
27
+ revision?: EditableDocument["revision"];
28
+ /** Hide the title input for hosts that render their own page title. */
29
+ hideTitle?: boolean;
30
+ onDirtyChange?(dirty: boolean): void;
31
+ onBusyChange?(busy: boolean): void;
32
+ onSaved?(document: EditableDocument): void;
33
+ /** Replaces the built-in conflict banner. */
34
+ renderConflict?(context: DocumentConflictContext): ReactNode;
35
+ className?: string;
36
+ style?: CSSProperties;
37
+ }
38
+ /**
39
+ * Notion-style block editor over a host-provided revision protocol: autosave with
40
+ * single-flight saves, idempotent retries of unconfirmed saves, and an explicit
41
+ * conflict step that never discards the local draft on its own.
42
+ */
43
+ export declare function DocumentEditor(props: DocumentEditorProps): import("react").JSX.Element;
@@ -0,0 +1,63 @@
1
+ import type { DocumentRevision, EditableDocument } from "@uibot/contracts";
2
+ export type DocumentSavePhase = "clean" | "dirty" | "saving" | "conflict" | "error" | "unknown";
3
+ export interface DocumentSaveState {
4
+ phase: DocumentSavePhase;
5
+ /** Revision the next save is checked against. */
6
+ revision: DocumentRevision;
7
+ message: string;
8
+ /** Stored document reported by a conflict, when the host supplied it. */
9
+ remote: EditableDocument | null;
10
+ /** Edits made while a save was in flight; they stay dirty after it lands. */
11
+ editedWhileSaving: boolean;
12
+ }
13
+ export type DocumentSaveEvent = {
14
+ type: "edit";
15
+ } | {
16
+ type: "save-start";
17
+ } | {
18
+ type: "saved";
19
+ revision: DocumentRevision;
20
+ } | {
21
+ type: "conflict";
22
+ message: string;
23
+ remote: EditableDocument | null;
24
+ } | {
25
+ type: "failed";
26
+ message: string;
27
+ unknown: boolean;
28
+ }
29
+ /**
30
+ * The host wrote the document through another path (tags, notes) and knows the body is
31
+ * unchanged: later saves are checked against this revision. Ignored during a conflict.
32
+ */
33
+ | {
34
+ type: "adopt-revision";
35
+ revision: DocumentRevision;
36
+ }
37
+ /** Conflict resolved by keeping the local draft on top of the stored revision. */
38
+ | {
39
+ type: "keep-mine";
40
+ revision: DocumentRevision;
41
+ }
42
+ /** Conflict resolved by adopting the stored document. */
43
+ | {
44
+ type: "use-remote";
45
+ revision: DocumentRevision;
46
+ };
47
+ export declare function initialDocumentSaveState(revision: DocumentRevision): DocumentSaveState;
48
+ /** Phases in which the draft may be sent. A conflict must be resolved first. */
49
+ export declare function canSaveDocument(state: DocumentSaveState): boolean;
50
+ /** The draft differs from what is stored, so leaving the page would lose edits. */
51
+ export declare function isDocumentDirty(state: DocumentSaveState): boolean;
52
+ export declare function documentSaveReducer(state: DocumentSaveState, event: DocumentSaveEvent): DocumentSaveState;
53
+ /**
54
+ * A retry of an unconfirmed save must reuse its idempotency key; any other
55
+ * save (new content, or the previous attempt was answered) gets a fresh one.
56
+ */
57
+ export declare function nextIdempotencyKey(previous: {
58
+ fingerprint: string;
59
+ key: string;
60
+ } | null, fingerprint: string, create: () => string): {
61
+ fingerprint: string;
62
+ key: string;
63
+ };
@@ -0,0 +1,6 @@
1
+ export { BlockEditor } from "./block-editor.js";
2
+ export type { BlockEditorHandle, BlockEditorProps, BlockEditorTheme, BlockEditorValue, } from "./block-editor.js";
3
+ export { DocumentEditor } from "./document-editor.js";
4
+ export type { DocumentConflictContext, DocumentEditorProps } from "./document-editor.js";
5
+ export { canSaveDocument, documentSaveReducer, initialDocumentSaveState, isDocumentDirty, nextIdempotencyKey, } from "./document-save-state.js";
6
+ export type { DocumentSaveEvent, DocumentSavePhase, DocumentSaveState, } from "./document-save-state.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{en as Z,zh as _}from"@blocknote/core/locales";import{BlockNoteView as ee}from"@blocknote/mantine";import{useCreateBlockNote as te}from"@blocknote/react";import{forwardRef as ne,useCallback as L,useEffect as oe,useImperativeHandle as re,useRef as j}from"react";import{jsx as ie}from"react/jsx-runtime";var P=(e)=>JSON.stringify(e),N=ne(function(n,u){let{blocks:d,markdown:E,onChange:h,readOnly:f,locale:p="zh-CN",uploadFile:r}=n,c=j(""),v=j(h);v.current=h;let i=te({dictionary:p==="en"?Z:_,...d&&d.length>0?{initialContent:d}:{},...r?{uploadFile:r}:{}},[p]),t=L(()=>({blocks:i.document,markdown:i.blocksToMarkdownLossy()}),[i]),s=L((a,k)=>{if(a&&a.length>0)i.replaceBlocks(i.document,a);else if(k)i.replaceBlocks(i.document,i.tryParseMarkdownToBlocks(k));c.current=P(i.document)},[i]);return oe(()=>{if(d&&d.length>0)c.current=P(i.document);else s(null,E)},[i]),re(u,()=>({getValue:t,setContent:(a)=>s(a.blocks,a.markdown)}),[t,s]),ie(ee,{className:n.className,editor:i,editable:!f,theme:n.theme??"light",onChange:()=>{let a=P(i.document);if(a===c.current)return;c.current=a,v.current?.(t())}})});import{useCallback as J,useEffect as D,useReducer as ae,useRef as g,useState as se}from"react";function O(e){return{phase:"clean",revision:e,message:"",remote:null,editedWhileSaving:!1}}function S(e){return e.phase==="dirty"||e.phase==="error"||e.phase==="unknown"}function M(e){return e.phase!=="clean"}function K(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(!S(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 W(e,n,u){return e&&e.fingerprint===n?e:{fingerprint:n,key:u()}}import{jsx as m,jsxs as w,Fragment as me}from"react/jsx-runtime";var ce={"zh-CN":{title:"标题",titlePlaceholder:"无标题",clean:"已保存",dirty:"未保存的更改",saving:"保存中…",error:"保存失败,草稿已保留。",unknown:"保存结果未知,草稿已保留。",retry:"重试保存",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",conflict:"This document was changed elsewhere",keepMine:"Keep my changes and overwrite",useRemote:"Load latest version",readOnly:"Read only"}},le=(e,n)=>`${JSON.stringify(e)}\x00${n}`,ue=()=>typeof crypto<"u"&&("randomUUID"in crypto)?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;function de(e){let{document:n,client:u,locale:d="zh-CN",hideTitle:E,onDirtyChange:h,onBusyChange:f}=e,p=e.autoSaveMs??1500,r=ce[d],c=n.readOnly===!0,v=u.uploadFile?.bind(u),i=g(e.onSaved);i.current=e.onSaved;let[t,s]=ae(K,n.revision,O),a=g(t);a.current=t;let[k,I]=se(n.title),C=g(n.title),x=g(null),y=g(null),B=g(!1),R=e.revision;D(()=>{if(R!==void 0)s({type:"adopt-revision",revision:R})},[R]);let V=J(()=>{if(!c)s({type:"edit"})},[c]),b=J(async()=>{let o=x.current;if(!o||c||B.current||!S(a.current))return;B.current=!0;let{blocks:H,markdown:A}=o.getValue(),U=C.current,G=le(H,U);y.current=W(y.current,G,ue);let Q={id:n.id,title:U,blocks:H,markdown:A,expectedRevision:a.current.revision,idempotencyKey:y.current.key};s({type:"save-start"});try{let l=await u.save(Q);if(l.ok)y.current=null,s({type:"saved",revision:l.document.revision}),i.current?.(l.document);else if(l.error.code==="conflict")s({type:"conflict",message:l.error.message,remote:l.error.remote??null});else s({type:"failed",message:l.error.message,unknown:l.error.code==="unknown"})}catch(l){s({type:"failed",message:l instanceof Error?l.message:r.unknown,unknown:!0})}finally{B.current=!1}},[u,n.id,c,r.unknown]);D(()=>{if(t.phase!=="dirty"||p<=0)return;let o=setTimeout(()=>void b(),p);return()=>clearTimeout(o)},[t.phase,p,b]);let z=M(t),F=t.phase==="saving";D(()=>h?.(z),[z,h]),D(()=>f?.(F),[F,f]);let Y=(o)=>{x.current?.setContent({blocks:o.blocks,markdown:o.markdown}),C.current=o.title,I(o.title),y.current=null,s({type:"use-remote",revision:o.revision})},T={message:t.message,remote:t.remote,keepMine:()=>t.remote&&s({type:"keep-mine",revision:t.remote.revision}),useRemote:()=>t.remote&&Y(t.remote)},X=(o)=>{if((o.metaKey||o.ctrlKey)&&o.key.toLowerCase()==="s")o.preventDefault(),b()},q=t.phase==="clean"?c?r.readOnly:r.clean:t.phase==="saving"?r.saving:t.phase==="error"?`${r.error}${t.message?` ${t.message}`:""}`:t.phase==="unknown"?r.unknown:r.dirty;return w("div",{"data-uibot":"document-editor",className:e.className,style:e.style,onKeyDown:X,children:[E?null:m("input",{"aria-label":r.title,placeholder:r.titlePlaceholder,value:k,readOnly:c,onChange:(o)=>{C.current=o.currentTarget.value,I(o.currentTarget.value),V()},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(T):w("div",{role:"alert","data-uibot":"document-conflict",style:{padding:"8px 0",display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[m("strong",{children:r.conflict}),m("span",{children:t.message}),t.remote?w(me,{children:[m("button",{type:"button",onClick:T.keepMine,children:r.keepMine}),m("button",{type:"button",onClick:T.useRemote,children:r.useRemote})]}):null]}):null,m(N,{ref:x,blocks:n.blocks,markdown:n.markdown,readOnly:c||t.phase==="conflict",locale:d,...e.theme!==void 0?{theme:e.theme}:{},...v?{uploadFile:v}:{},onChange:V}),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:[m("span",{children:q}),t.phase==="error"||t.phase==="unknown"?m("button",{type:"button",onClick:()=>void b(),children:r.retry}):null]})]})}export{N as BlockEditor,de as DocumentEditor,S as canSaveDocument,K as documentSaveReducer,O as initialDocumentSaveState,M as isDocumentDirty,W as nextIdempotencyKey};
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@uibot/document-editor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/Foundj/uibot.git",
8
+ "directory": "packages/document-editor"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.js",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "!dist/**/*.map",
23
+ "!dist/**/*.test.d.ts",
24
+ "!dist/**/*.spec.d.ts"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "peerDependencies": {
30
+ "react": ">=18",
31
+ "react-dom": ">=18"
32
+ },
33
+ "dependencies": {
34
+ "@blocknote/core": "0.56.0",
35
+ "@blocknote/mantine": "0.56.0",
36
+ "@blocknote/react": "0.56.0",
37
+ "@uibot/contracts": "^0.2.0"
38
+ },
39
+ "scripts": {
40
+ "build": "rm -rf dist && bun build --minify ./src/index.ts --outdir ./dist --format esm --target browser --packages external && bun x tsc -p tsconfig.json",
41
+ "typecheck": "bun x tsc -p tsconfig.json --noEmit",
42
+ "test": "bun test"
43
+ }
44
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.