@peerkit-dev/doc-lexical 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +154 -2
- package/dist/index.d.ts +127 -0
- package/dist/index.js +397 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RazorSoft, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,155 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @peerkit-dev/doc-lexical
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reusable **Lexical ↔ PeerKit DocSession** collaboration adapter.
|
|
4
|
+
|
|
5
|
+
Uses the official **`@lexical/yjs`** bindings over an existing `@peerkit-dev/doc-core` `DocSession` (Yjs CRDT sync, awareness, reconnect catch-up, **`waitForInitialSync`**). Preserves **complete structured Lexical editor state** (not plain text), including custom nodes and shared cursors/selections.
|
|
6
|
+
|
|
7
|
+
> PeerKit is **not** the application's canonical content store. The host retains authority over persistence, permissions, and product data. This package syncs **ephemeral session editor state**.
|
|
8
|
+
|
|
9
|
+
## Compatibility
|
|
10
|
+
|
|
11
|
+
| Package | Version |
|
|
12
|
+
| --- | --- |
|
|
13
|
+
| `@peerkit-dev/doc-lexical` | **0.1.1** |
|
|
14
|
+
| `@peerkit-dev/doc-core` | `^0.1.1` (minimum for `waitForInitialSync`) |
|
|
15
|
+
| `lexical` / `@lexical/yjs` | `^0.50.0` (Tirage Editorial uses `^0.50.0`) |
|
|
16
|
+
| `yjs` | `^13.6.33` |
|
|
17
|
+
| Node | `>=22` |
|
|
18
|
+
|
|
19
|
+
Evaluated before shipping:
|
|
20
|
+
|
|
21
|
+
| Option | Verdict |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| **`@lexical/yjs` + DocSession Provider** | Selected. Official structured binding, cursor awareness, custom nodes. |
|
|
24
|
+
| Plain-text `Y.Text` only | Rejected for Lexical hosts — loses marks, element tree, custom nodes. |
|
|
25
|
+
| Custom OT / hand-rolled Lexical diff | Rejected — duplicates `@lexical/yjs` risk. |
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install @peerkit-dev/doc-lexical @peerkit-dev/doc-core @lexical/yjs lexical yjs
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Local Tirage sibling development:
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
{
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@peerkit-dev/doc-lexical": "file:../peerkit.dev/packages/doc-lexical",
|
|
39
|
+
"@peerkit-dev/doc-core": "file:../peerkit.dev/packages/doc-core"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Public exports
|
|
45
|
+
|
|
46
|
+
| Export | Role |
|
|
47
|
+
| --- | --- |
|
|
48
|
+
| `mountDocLexical` | Initialize + mount Lexical ↔ DocSession binding; returns handle |
|
|
49
|
+
| `createDocLexicalProvider` | `@lexical/yjs` `Provider` over DocSession (no second network path) |
|
|
50
|
+
| `hasSharedLexicalContent` | Detect non-empty shared `Y.XmlText` `"root"` before bootstrap |
|
|
51
|
+
| `getLexicalSharedRoot` | Access the Lexical shared root on `session.doc` |
|
|
52
|
+
| `DEFAULT_LEXICAL_ROOT_NAME` | `"root"` (`@lexical/yjs@0.50` convention) |
|
|
53
|
+
| `DocLexicalError` / `isDocLexicalError` | Typed mount/lifecycle errors |
|
|
54
|
+
| Handle: `setReadOnly` / `recover` / `resyncFromYjs` / `dispose` | Lifecycle controls |
|
|
55
|
+
| Types: `DocLexicalHandle`, `DocLexicalMountOptions`, `Provider`, `Binding`, … | Host wiring |
|
|
56
|
+
|
|
57
|
+
## Lifecycle
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { DocSession, PeerKitDocTransport } from "@peerkit-dev/doc-core";
|
|
61
|
+
import {
|
|
62
|
+
hasSharedLexicalContent,
|
|
63
|
+
mountDocLexical,
|
|
64
|
+
} from "@peerkit-dev/doc-lexical";
|
|
65
|
+
|
|
66
|
+
const transport = new PeerKitDocTransport({ session, localPeerId });
|
|
67
|
+
const docSession = new DocSession({ sessionId, transport });
|
|
68
|
+
await docSession.join();
|
|
69
|
+
|
|
70
|
+
// Transport "joined" ≠ document catch-up. Await explicit readiness (no timeouts).
|
|
71
|
+
await docSession.waitForInitialSync();
|
|
72
|
+
|
|
73
|
+
// Decide bootstrap only after catch-up. Concurrent peers must not both seed.
|
|
74
|
+
const shouldBootstrap = !hasSharedLexicalContent(docSession);
|
|
75
|
+
|
|
76
|
+
const handle = mountDocLexical({
|
|
77
|
+
editor, // host LexicalEditor (register custom nodes on the editor)
|
|
78
|
+
session: docSession,
|
|
79
|
+
shouldBootstrap,
|
|
80
|
+
initialEditorState: shouldBootstrap ? seedFromCanonical : undefined,
|
|
81
|
+
username: "Ada",
|
|
82
|
+
cursorColor: "#0a7",
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// Read-only transition (remote updates continue; local → Yjs suppressed)
|
|
86
|
+
handle.setReadOnly(true);
|
|
87
|
+
|
|
88
|
+
// After transport restore — DocSession starts a new sync epoch
|
|
89
|
+
handle.recover(); // handleReconnect + provider reconnect waits for waitForInitialSync again
|
|
90
|
+
|
|
91
|
+
// Optional: pull Yjs → Lexical when the editor is empty or shell-only after catch-up
|
|
92
|
+
handle.resyncFromYjs();
|
|
93
|
+
|
|
94
|
+
// Unmount binding only — host still owns DocSession leave / persistence
|
|
95
|
+
handle.dispose();
|
|
96
|
+
await docSession.leave();
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Document readiness (doc-core)
|
|
100
|
+
|
|
101
|
+
| API | Use |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `docSession.status` | Transport lifecycle only |
|
|
104
|
+
| `docSession.waitForInitialSync()` | Deterministic catch-up before bootstrap decisions |
|
|
105
|
+
| `docSession.initialSyncReady` | Sync-epoch flag (false again after `handleReconnect`) |
|
|
106
|
+
| `hasSharedLexicalContent(session)` | Whether Lexical shared root already has structure |
|
|
107
|
+
|
|
108
|
+
`createDocLexicalProvider` emits `@lexical/yjs` `sync: true` only after `waitForInitialSync()` resolves for the current epoch. Do **not** use `setTimeout` to guess catch-up completion.
|
|
109
|
+
|
|
110
|
+
### Guarantees
|
|
111
|
+
|
|
112
|
+
1. Structured Lexical state syncs via `@lexical/yjs` on shared `Y.XmlText` `"root"`.
|
|
113
|
+
2. Custom nodes registered on the host editor participate in sync.
|
|
114
|
+
3. Cursors/selections use DocSession awareness (bridged `name` ↔ `userName`, `peerId`).
|
|
115
|
+
4. `shouldBootstrap` writes **only** when the shared root is empty — joiners / reconnects do not duplicate hydration.
|
|
116
|
+
5. Catch-up hydration runs for empty *and* shell-only Lexical roots (composer empty paragraphs). Non-empty local content is never overwritten by `resyncFromYjs` / mount hydrate.
|
|
117
|
+
6. Hosts must call `waitForInitialSync()` (or rely on the provider’s sync event) **before** setting `shouldBootstrap` from canonical state, so concurrent participants cannot independently bootstrap conflicting seeds.
|
|
118
|
+
7. Collaboration tags / binding origin prevent sync feedback loops.
|
|
119
|
+
8. `setReadOnly` / `dispose` are safe; `dispose` does **not** call `session.leave()`.
|
|
120
|
+
9. Host persistence of canonical manuscripts stays outside this package.
|
|
121
|
+
|
|
122
|
+
### Non-goals
|
|
123
|
+
|
|
124
|
+
- Tirage manuscript schemas, annotations, or editorial ACL
|
|
125
|
+
- React `CollaborationPlugin` wrapper (hosts may use this headless API from React effects)
|
|
126
|
+
- Replacing DocSession transport / catch-up
|
|
127
|
+
- Publishing canonical content
|
|
128
|
+
|
|
129
|
+
## Tirage integration sketch
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
// After collaboration plugin enables doc-core fan-out and DocSession.join():
|
|
133
|
+
import { hasSharedLexicalContent, mountDocLexical } from "@peerkit-dev/doc-lexical";
|
|
134
|
+
|
|
135
|
+
await docSession.waitForInitialSync();
|
|
136
|
+
const shouldBootstrap = !hasSharedLexicalContent(docSession);
|
|
137
|
+
const collab = mountDocLexical({
|
|
138
|
+
editor: manuscriptEditor,
|
|
139
|
+
session: docSession,
|
|
140
|
+
shouldBootstrap,
|
|
141
|
+
// Seed from Tirage canonical Lexical JSON only when remote root is empty:
|
|
142
|
+
initialEditorState: shouldBootstrap ? canonicalEditorStateJSON : undefined,
|
|
143
|
+
username: participantDisplayName,
|
|
144
|
+
cursorColor: participantColor,
|
|
145
|
+
readOnly: !editorialPermissionsGranted,
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// Persist via existing Tirage APIs from editor update listeners — not via PeerKit.
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Keep `simultaneousEditingClaimed: false` until multi-participant ManuscriptEditor acceptance passes.
|
|
152
|
+
|
|
153
|
+
## License
|
|
154
|
+
|
|
155
|
+
MIT © RazorSoft, Inc.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { Provider, Binding, ExcludedProperties } from '@lexical/yjs';
|
|
2
|
+
export { Binding, ExcludedProperties, Provider, ProviderAwareness, UserState } from '@lexical/yjs';
|
|
3
|
+
import { DocSession } from '@peerkit-dev/doc-core';
|
|
4
|
+
import { EditorState, LexicalEditor } from 'lexical';
|
|
5
|
+
import { Doc, XmlText } from 'yjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Initial Lexical state used only when bootstrapping an empty shared Yjs root.
|
|
9
|
+
* Prefer omitting this when joining a session that already has content.
|
|
10
|
+
*/
|
|
11
|
+
type DocLexicalInitialState = string | EditorState | ((editor: LexicalEditor) => void);
|
|
12
|
+
type DocLexicalMountStatus = "idle" | "mounting" | "connected" | "readonly" | "disposed";
|
|
13
|
+
type DocLexicalMountOptions = {
|
|
14
|
+
/** Lexical editor instance owned by the host application. */
|
|
15
|
+
editor: LexicalEditor;
|
|
16
|
+
/** Joined PeerKit DocSession whose `doc` / `awareness` drive collaboration. */
|
|
17
|
+
session: DocSession;
|
|
18
|
+
/**
|
|
19
|
+
* Binding id stored in the Yjs doc map. Defaults to `session.sessionId`.
|
|
20
|
+
* Must be stable across remounts for the same collaborative document.
|
|
21
|
+
*/
|
|
22
|
+
id?: string;
|
|
23
|
+
/**
|
|
24
|
+
* When true, seed the empty shared Lexical root from `initialEditorState`
|
|
25
|
+
* (or a blank paragraph) after the first sync. Never overwrites a non-empty
|
|
26
|
+
* shared root — safe for joiners and reconnecting peers.
|
|
27
|
+
*/
|
|
28
|
+
shouldBootstrap?: boolean;
|
|
29
|
+
/** Used only when `shouldBootstrap` and the shared root is empty. */
|
|
30
|
+
initialEditorState?: DocLexicalInitialState;
|
|
31
|
+
/** Display name for remote cursors / awareness. */
|
|
32
|
+
username?: string;
|
|
33
|
+
/** Cursor color for remote awareness. */
|
|
34
|
+
cursorColor?: string;
|
|
35
|
+
/** Extra awareness payload merged into Lexical local state. */
|
|
36
|
+
awarenessData?: Record<string, unknown>;
|
|
37
|
+
/** Properties excluded from Yjs property sync (passed to `@lexical/yjs`). */
|
|
38
|
+
excludedProperties?: ExcludedProperties;
|
|
39
|
+
/**
|
|
40
|
+
* Shared `Y.XmlText` name on `session.doc`. Defaults to `"root"`
|
|
41
|
+
* (Lexical/`@lexical/yjs` convention). Independent of DocSession `textKey`.
|
|
42
|
+
*/
|
|
43
|
+
rootName?: string;
|
|
44
|
+
/** Start with the editor non-editable while still receiving remote updates. */
|
|
45
|
+
readOnly?: boolean;
|
|
46
|
+
};
|
|
47
|
+
type DocLexicalHandle = {
|
|
48
|
+
readonly id: string;
|
|
49
|
+
readonly provider: Provider;
|
|
50
|
+
readonly binding: Binding;
|
|
51
|
+
readonly docMap: Map<string, Doc>;
|
|
52
|
+
readonly session: DocSession;
|
|
53
|
+
readonly status: DocLexicalMountStatus;
|
|
54
|
+
/** Toggle local editability. Remote updates continue either way. */
|
|
55
|
+
setReadOnly(readOnly: boolean): void;
|
|
56
|
+
/**
|
|
57
|
+
* After transport restore: ask DocSession for catch-up and re-emit provider
|
|
58
|
+
* sync so the Lexical binding reconciles without wiping local Yjs state.
|
|
59
|
+
*/
|
|
60
|
+
recover(): void;
|
|
61
|
+
/**
|
|
62
|
+
* Pull current shared Yjs Lexical root into the editor (idempotent).
|
|
63
|
+
* Used after join catch-up, remount, or recover when observeDeep did not
|
|
64
|
+
* replay already-applied updates. Shell-only empty paragraphs do not block
|
|
65
|
+
* hydration; non-empty local content is left untouched.
|
|
66
|
+
*/
|
|
67
|
+
resyncFromYjs(): void;
|
|
68
|
+
/**
|
|
69
|
+
* Tear down listeners, clear local awareness, destroy the collab root.
|
|
70
|
+
* Does not call `session.leave()` — the host owns the DocSession lifecycle.
|
|
71
|
+
*/
|
|
72
|
+
dispose(): void;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Mount a Lexical editor onto an already-joined PeerKit `DocSession`.
|
|
77
|
+
*
|
|
78
|
+
* Responsibilities:
|
|
79
|
+
* - Bind structured Lexical state to `session.doc` via official `@lexical/yjs`
|
|
80
|
+
* - Sync remote cursors / selections through session awareness
|
|
81
|
+
* - Bootstrap empty roots only (`shouldBootstrap`), never overwrite joiners
|
|
82
|
+
* - Prevent feedback loops via collaboration tags / binding origin checks
|
|
83
|
+
* - Support read-only transitions and safe dispose without leaving the session
|
|
84
|
+
*
|
|
85
|
+
* Canonical persistence remains the host application's responsibility.
|
|
86
|
+
*
|
|
87
|
+
* Note: `@lexical/yjs@0.50` stores structured state on the shared `Y.XmlText`
|
|
88
|
+
* named `"root"`. That is independent of DocSession's plain-text `textKey`.
|
|
89
|
+
*/
|
|
90
|
+
declare function mountDocLexical(options: DocLexicalMountOptions): DocLexicalHandle;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Lexical `@lexical/yjs` Provider backed by an existing PeerKit `DocSession`.
|
|
94
|
+
*
|
|
95
|
+
* DocSession already syncs `Y.Doc` updates and awareness over `DocTransport`.
|
|
96
|
+
* This provider does **not** open a second network path — it exposes connect /
|
|
97
|
+
* disconnect / sync / status events and bridges awareness for Lexical cursors.
|
|
98
|
+
*
|
|
99
|
+
* Sync events follow `DocSession.waitForInitialSync()` so Lexical bootstrap
|
|
100
|
+
* does not run before document catch-up completes.
|
|
101
|
+
*/
|
|
102
|
+
declare function createDocLexicalProvider(session: DocSession): Provider;
|
|
103
|
+
|
|
104
|
+
/** Default shared type name used by `@lexical/yjs` / Lexical collaboration. */
|
|
105
|
+
declare const DEFAULT_LEXICAL_ROOT_NAME = "root";
|
|
106
|
+
/**
|
|
107
|
+
* Returns the Lexical collaboration `Y.XmlText` on the session doc without
|
|
108
|
+
* creating a second top-level type when one already exists.
|
|
109
|
+
*/
|
|
110
|
+
declare function getLexicalSharedRoot(session: DocSession, rootName?: string): XmlText;
|
|
111
|
+
/**
|
|
112
|
+
* True when the shared Lexical root already has collaborative content.
|
|
113
|
+
* Use before bootstrapping to avoid duplicate initial hydration.
|
|
114
|
+
*/
|
|
115
|
+
declare function hasSharedLexicalContent(session: DocSession, rootName?: string): boolean;
|
|
116
|
+
|
|
117
|
+
type DocLexicalErrorCode = "not_mounted" | "already_mounted" | "session_not_joined" | "disposed";
|
|
118
|
+
declare class DocLexicalError extends Error {
|
|
119
|
+
readonly code: DocLexicalErrorCode;
|
|
120
|
+
readonly cause?: unknown;
|
|
121
|
+
constructor(code: DocLexicalErrorCode, message: string, options?: {
|
|
122
|
+
cause?: unknown;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
declare function isDocLexicalError(error: unknown): error is DocLexicalError;
|
|
126
|
+
|
|
127
|
+
export { DEFAULT_LEXICAL_ROOT_NAME, DocLexicalError, type DocLexicalErrorCode, type DocLexicalHandle, type DocLexicalInitialState, type DocLexicalMountOptions, type DocLexicalMountStatus, createDocLexicalProvider, getLexicalSharedRoot, hasSharedLexicalContent, isDocLexicalError, mountDocLexical };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { createBinding, syncLexicalUpdateToYjs, initLocalState, syncCursorPositions, syncYjsChangesToLexical } from '@lexical/yjs';
|
|
2
|
+
import { SKIP_COLLAB_TAG, $getRoot, $addUpdateTag, SKIP_SCROLL_INTO_VIEW_TAG, COLLABORATION_TAG, $isParagraphNode, $isTextNode, HISTORY_MERGE_TAG, $createParagraphNode, $getSelection } from 'lexical';
|
|
3
|
+
import { XmlText, XmlElement } from 'yjs';
|
|
4
|
+
|
|
5
|
+
// src/mount.ts
|
|
6
|
+
function clearCollabNodeTree(sharedType) {
|
|
7
|
+
if (Object.prototype.hasOwnProperty.call(sharedType, "_collabNode")) {
|
|
8
|
+
Reflect.deleteProperty(sharedType, "_collabNode");
|
|
9
|
+
}
|
|
10
|
+
if (sharedType instanceof XmlText) {
|
|
11
|
+
for (const delta of sharedType.toDelta()) {
|
|
12
|
+
const insert = delta.insert;
|
|
13
|
+
if (insert != null && typeof insert === "object") {
|
|
14
|
+
clearCollabNodeTree(insert);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (sharedType instanceof XmlElement) {
|
|
20
|
+
for (const child of sharedType.toArray()) {
|
|
21
|
+
if (typeof child !== "string") {
|
|
22
|
+
clearCollabNodeTree(child);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function clearDescendantCollabCaches(sharedRoot) {
|
|
28
|
+
for (const delta of sharedRoot.toDelta()) {
|
|
29
|
+
const insert = delta.insert;
|
|
30
|
+
if (insert != null && typeof insert === "object") {
|
|
31
|
+
clearCollabNodeTree(insert);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/errors.ts
|
|
37
|
+
var DocLexicalError = class extends Error {
|
|
38
|
+
code;
|
|
39
|
+
cause;
|
|
40
|
+
constructor(code, message, options) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "DocLexicalError";
|
|
43
|
+
this.code = code;
|
|
44
|
+
if (options?.cause !== void 0) this.cause = options.cause;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
function isDocLexicalError(error) {
|
|
48
|
+
return error instanceof DocLexicalError;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/provider.ts
|
|
52
|
+
function createDocLexicalProvider(session) {
|
|
53
|
+
const syncListeners = /* @__PURE__ */ new Set();
|
|
54
|
+
const statusListeners = /* @__PURE__ */ new Set();
|
|
55
|
+
const updateListeners = /* @__PURE__ */ new Set();
|
|
56
|
+
const reloadListeners = /* @__PURE__ */ new Set();
|
|
57
|
+
let connected = false;
|
|
58
|
+
let connectGeneration = 0;
|
|
59
|
+
const awareness = wrapAwareness(session);
|
|
60
|
+
const provider = {
|
|
61
|
+
awareness,
|
|
62
|
+
connect() {
|
|
63
|
+
if (connected) return;
|
|
64
|
+
connected = true;
|
|
65
|
+
const generation = ++connectGeneration;
|
|
66
|
+
emitStatus("connected");
|
|
67
|
+
for (const listener of syncListeners) listener(false);
|
|
68
|
+
void session.waitForInitialSync().then(() => {
|
|
69
|
+
if (!connected || generation !== connectGeneration) return;
|
|
70
|
+
for (const listener of syncListeners) listener(true);
|
|
71
|
+
}).catch(() => {
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
disconnect() {
|
|
75
|
+
if (!connected) return;
|
|
76
|
+
connected = false;
|
|
77
|
+
connectGeneration += 1;
|
|
78
|
+
emitStatus("disconnected");
|
|
79
|
+
for (const listener of syncListeners) listener(false);
|
|
80
|
+
},
|
|
81
|
+
on(type, cb) {
|
|
82
|
+
if (type === "sync") syncListeners.add(cb);
|
|
83
|
+
else if (type === "status") statusListeners.add(cb);
|
|
84
|
+
else if (type === "update") updateListeners.add(cb);
|
|
85
|
+
else if (type === "reload") reloadListeners.add(cb);
|
|
86
|
+
},
|
|
87
|
+
off(type, cb) {
|
|
88
|
+
if (type === "sync") syncListeners.delete(cb);
|
|
89
|
+
else if (type === "status") statusListeners.delete(cb);
|
|
90
|
+
else if (type === "update") updateListeners.delete(cb);
|
|
91
|
+
else if (type === "reload") reloadListeners.delete(cb);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
function emitStatus(status) {
|
|
95
|
+
for (const listener of statusListeners) listener({ status });
|
|
96
|
+
}
|
|
97
|
+
return provider;
|
|
98
|
+
}
|
|
99
|
+
function wrapAwareness(session) {
|
|
100
|
+
const raw = session.awareness;
|
|
101
|
+
const injectPeerFields = (state) => {
|
|
102
|
+
if (state === null) return null;
|
|
103
|
+
const extra = state;
|
|
104
|
+
return {
|
|
105
|
+
...state,
|
|
106
|
+
peerId: typeof extra.peerId === "string" ? extra.peerId : inferLocalPeerId(session),
|
|
107
|
+
userName: typeof extra.userName === "string" ? extra.userName : state.name
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
return {
|
|
111
|
+
getLocalState: () => raw.getLocalState(),
|
|
112
|
+
getStates: () => raw.getStates(),
|
|
113
|
+
on: (type, cb) => {
|
|
114
|
+
raw.on(type, cb);
|
|
115
|
+
},
|
|
116
|
+
off: (type, cb) => {
|
|
117
|
+
raw.off(type, cb);
|
|
118
|
+
},
|
|
119
|
+
setLocalState: (state) => {
|
|
120
|
+
raw.setLocalState(injectPeerFields(state));
|
|
121
|
+
},
|
|
122
|
+
setLocalStateField: (field, value) => {
|
|
123
|
+
const current = raw.getLocalState() ?? {};
|
|
124
|
+
raw.setLocalState(
|
|
125
|
+
injectPeerFields({
|
|
126
|
+
...current,
|
|
127
|
+
[field]: value
|
|
128
|
+
})
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function inferLocalPeerId(session) {
|
|
134
|
+
const state = session.awareness.getLocalState();
|
|
135
|
+
if (typeof state?.peerId === "string") return state.peerId;
|
|
136
|
+
return `client:${session.doc.clientID}`;
|
|
137
|
+
}
|
|
138
|
+
var DEFAULT_LEXICAL_ROOT_NAME = "root";
|
|
139
|
+
function getLexicalSharedRoot(session, rootName = DEFAULT_LEXICAL_ROOT_NAME) {
|
|
140
|
+
return session.doc.get(rootName, XmlText);
|
|
141
|
+
}
|
|
142
|
+
function hasSharedLexicalContent(session, rootName = DEFAULT_LEXICAL_ROOT_NAME) {
|
|
143
|
+
const root = getLexicalSharedRoot(session, rootName);
|
|
144
|
+
return root.length > 0;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/mount.ts
|
|
148
|
+
function mountDocLexical(options) {
|
|
149
|
+
const {
|
|
150
|
+
editor,
|
|
151
|
+
session,
|
|
152
|
+
shouldBootstrap = false,
|
|
153
|
+
initialEditorState,
|
|
154
|
+
username = "Anonymous",
|
|
155
|
+
cursorColor = "#aaa",
|
|
156
|
+
awarenessData = {},
|
|
157
|
+
excludedProperties,
|
|
158
|
+
readOnly = false
|
|
159
|
+
} = options;
|
|
160
|
+
if (options.rootName && options.rootName !== DEFAULT_LEXICAL_ROOT_NAME) {
|
|
161
|
+
throw new DocLexicalError(
|
|
162
|
+
"not_mounted",
|
|
163
|
+
`rootName "${options.rootName}" is unsupported with @lexical/yjs@0.50; use "${DEFAULT_LEXICAL_ROOT_NAME}".`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
if (session.status !== "joined" && session.status !== "reconnecting") {
|
|
167
|
+
throw new DocLexicalError(
|
|
168
|
+
"session_not_joined",
|
|
169
|
+
"DocSession must be joined before mounting Lexical collaboration."
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
const id = options.id ?? session.sessionId;
|
|
173
|
+
const docMap = /* @__PURE__ */ new Map([[id, session.doc]]);
|
|
174
|
+
const provider = createDocLexicalProvider(session);
|
|
175
|
+
const binding = createBinding(
|
|
176
|
+
editor,
|
|
177
|
+
provider,
|
|
178
|
+
id,
|
|
179
|
+
session.doc,
|
|
180
|
+
docMap,
|
|
181
|
+
excludedProperties
|
|
182
|
+
);
|
|
183
|
+
let status = "mounting";
|
|
184
|
+
let disposed = false;
|
|
185
|
+
let isReadOnly = readOnly;
|
|
186
|
+
const unsubs = [];
|
|
187
|
+
editor.setEditable(!isReadOnly);
|
|
188
|
+
const onYjsTreeChanges = (events, transaction) => {
|
|
189
|
+
if (disposed) return;
|
|
190
|
+
const origin = transaction.origin;
|
|
191
|
+
if (origin === binding) return;
|
|
192
|
+
const isFromUndoManager = isUndoManagerOrigin(origin);
|
|
193
|
+
syncYjsChangesToLexical(
|
|
194
|
+
binding,
|
|
195
|
+
provider,
|
|
196
|
+
events,
|
|
197
|
+
isFromUndoManager,
|
|
198
|
+
safeSyncCursorPositions
|
|
199
|
+
);
|
|
200
|
+
};
|
|
201
|
+
binding.root.getSharedType().observeDeep(onYjsTreeChanges);
|
|
202
|
+
unsubs.push(() => {
|
|
203
|
+
binding.root.getSharedType().unobserveDeep(onYjsTreeChanges);
|
|
204
|
+
});
|
|
205
|
+
unsubs.push(
|
|
206
|
+
editor.registerUpdateListener(
|
|
207
|
+
({
|
|
208
|
+
prevEditorState,
|
|
209
|
+
editorState,
|
|
210
|
+
dirtyLeaves,
|
|
211
|
+
dirtyElements,
|
|
212
|
+
normalizedNodes,
|
|
213
|
+
tags
|
|
214
|
+
}) => {
|
|
215
|
+
if (disposed || isReadOnly) return;
|
|
216
|
+
if (tags.has(SKIP_COLLAB_TAG)) return;
|
|
217
|
+
syncLexicalUpdateToYjs(
|
|
218
|
+
binding,
|
|
219
|
+
provider,
|
|
220
|
+
prevEditorState,
|
|
221
|
+
editorState,
|
|
222
|
+
dirtyElements,
|
|
223
|
+
dirtyLeaves,
|
|
224
|
+
normalizedNodes,
|
|
225
|
+
tags
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
)
|
|
229
|
+
);
|
|
230
|
+
const awarenessUpdate = () => {
|
|
231
|
+
if (disposed) return;
|
|
232
|
+
safeSyncCursorPositions(binding, provider);
|
|
233
|
+
};
|
|
234
|
+
provider.awareness.on("update", awarenessUpdate);
|
|
235
|
+
unsubs.push(() => provider.awareness.off("update", awarenessUpdate));
|
|
236
|
+
const onSync = (isSynced) => {
|
|
237
|
+
if (disposed || !isSynced) return;
|
|
238
|
+
if (binding.root.getSharedType().length > 0) {
|
|
239
|
+
hydrateEditorFromExistingYjs(binding, provider);
|
|
240
|
+
} else {
|
|
241
|
+
maybeBootstrap(binding, editor, shouldBootstrap, initialEditorState);
|
|
242
|
+
}
|
|
243
|
+
status = isReadOnly ? "readonly" : "connected";
|
|
244
|
+
};
|
|
245
|
+
provider.on("sync", onSync);
|
|
246
|
+
unsubs.push(() => provider.off("sync", onSync));
|
|
247
|
+
initLocalState(provider, username, cursorColor, false, {
|
|
248
|
+
...awarenessData,
|
|
249
|
+
peerId: inferPeerId(session)
|
|
250
|
+
});
|
|
251
|
+
provider.connect();
|
|
252
|
+
return {
|
|
253
|
+
id,
|
|
254
|
+
provider,
|
|
255
|
+
binding,
|
|
256
|
+
docMap,
|
|
257
|
+
session,
|
|
258
|
+
get status() {
|
|
259
|
+
return status;
|
|
260
|
+
},
|
|
261
|
+
setReadOnly(next) {
|
|
262
|
+
if (disposed) {
|
|
263
|
+
throw new DocLexicalError("disposed", "DocLexical handle is disposed.");
|
|
264
|
+
}
|
|
265
|
+
isReadOnly = next;
|
|
266
|
+
editor.setEditable(!next);
|
|
267
|
+
status = next ? "readonly" : "connected";
|
|
268
|
+
},
|
|
269
|
+
recover() {
|
|
270
|
+
if (disposed) {
|
|
271
|
+
throw new DocLexicalError("disposed", "DocLexical handle is disposed.");
|
|
272
|
+
}
|
|
273
|
+
session.handleReconnect();
|
|
274
|
+
provider.disconnect();
|
|
275
|
+
provider.connect();
|
|
276
|
+
},
|
|
277
|
+
resyncFromYjs() {
|
|
278
|
+
if (disposed) {
|
|
279
|
+
throw new DocLexicalError("disposed", "DocLexical handle is disposed.");
|
|
280
|
+
}
|
|
281
|
+
hydrateEditorFromExistingYjs(binding, provider);
|
|
282
|
+
},
|
|
283
|
+
dispose() {
|
|
284
|
+
if (disposed) return;
|
|
285
|
+
disposed = true;
|
|
286
|
+
for (const unsub of unsubs.splice(0)) unsub();
|
|
287
|
+
try {
|
|
288
|
+
provider.awareness.setLocalState(null);
|
|
289
|
+
} catch {
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
provider.disconnect();
|
|
293
|
+
} catch {
|
|
294
|
+
}
|
|
295
|
+
clearCollabNodeTree(binding.root.getSharedType());
|
|
296
|
+
binding.root.destroy(binding);
|
|
297
|
+
docMap.delete(id);
|
|
298
|
+
status = "disposed";
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
function maybeBootstrap(binding, editor, shouldBootstrap, initialEditorState) {
|
|
303
|
+
if (!shouldBootstrap) return;
|
|
304
|
+
const shared = binding.root.getSharedType();
|
|
305
|
+
if (!binding.root.isEmpty() || shared.length > 0) return;
|
|
306
|
+
initializeEditor(editor, initialEditorState);
|
|
307
|
+
}
|
|
308
|
+
function hydrateEditorFromExistingYjs(binding, provider) {
|
|
309
|
+
const shared = binding.root.getSharedType();
|
|
310
|
+
if (shared.length === 0) return;
|
|
311
|
+
const hydratable = binding.editor.getEditorState().read(() => $isHydratableEditorRoot());
|
|
312
|
+
if (!hydratable) return;
|
|
313
|
+
binding.editor.update(
|
|
314
|
+
() => {
|
|
315
|
+
if (!$isHydratableEditorRoot()) return;
|
|
316
|
+
$getRoot().clear();
|
|
317
|
+
if (binding.root.isEmpty()) {
|
|
318
|
+
clearDescendantCollabCaches(shared);
|
|
319
|
+
binding.root.syncPropertiesFromYjs(binding, null);
|
|
320
|
+
binding.root.applyChildrenYjsDelta(binding, shared.toDelta());
|
|
321
|
+
} else {
|
|
322
|
+
binding.root.syncPropertiesFromYjs(binding, null);
|
|
323
|
+
}
|
|
324
|
+
binding.root.syncChildrenFromYjs(binding);
|
|
325
|
+
$addUpdateTag(SKIP_SCROLL_INTO_VIEW_TAG);
|
|
326
|
+
},
|
|
327
|
+
{
|
|
328
|
+
onUpdate: () => {
|
|
329
|
+
safeSyncCursorPositions(binding, provider);
|
|
330
|
+
},
|
|
331
|
+
skipTransforms: true,
|
|
332
|
+
tag: COLLABORATION_TAG
|
|
333
|
+
}
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
function $isHydratableEditorRoot() {
|
|
337
|
+
const root = $getRoot();
|
|
338
|
+
if (root.isEmpty()) return true;
|
|
339
|
+
const children = root.getChildren();
|
|
340
|
+
if (children.length === 0) return true;
|
|
341
|
+
return children.every($isShellParagraph);
|
|
342
|
+
}
|
|
343
|
+
function $isShellParagraph(node) {
|
|
344
|
+
if (!$isParagraphNode(node)) return false;
|
|
345
|
+
const kids = node.getChildren();
|
|
346
|
+
if (kids.length === 0) return true;
|
|
347
|
+
return kids.every(
|
|
348
|
+
(child) => $isTextNode(child) && child.getTextContentSize() === 0
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
function initializeEditor(editor, initialEditorState) {
|
|
352
|
+
editor.update(
|
|
353
|
+
() => {
|
|
354
|
+
const root = $getRoot();
|
|
355
|
+
if (!root.isEmpty()) return;
|
|
356
|
+
if (initialEditorState) {
|
|
357
|
+
switch (typeof initialEditorState) {
|
|
358
|
+
case "string": {
|
|
359
|
+
const parsed = editor.parseEditorState(initialEditorState);
|
|
360
|
+
editor.setEditorState(parsed, { tag: HISTORY_MERGE_TAG });
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
case "object": {
|
|
364
|
+
editor.setEditorState(initialEditorState, { tag: HISTORY_MERGE_TAG });
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
case "function": {
|
|
368
|
+
initialEditorState(editor);
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const paragraph = $createParagraphNode();
|
|
375
|
+
root.append(paragraph);
|
|
376
|
+
if ($getSelection() !== null) paragraph.select();
|
|
377
|
+
},
|
|
378
|
+
{ tag: HISTORY_MERGE_TAG }
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
function inferPeerId(session) {
|
|
382
|
+
const local = session.awareness.getLocalState();
|
|
383
|
+
return local?.peerId ?? `client:${session.doc.clientID}`;
|
|
384
|
+
}
|
|
385
|
+
function isUndoManagerOrigin(origin) {
|
|
386
|
+
if (origin == null || typeof origin !== "object") return false;
|
|
387
|
+
const candidate = origin;
|
|
388
|
+
return typeof candidate.undo === "function" && typeof candidate.redo === "function";
|
|
389
|
+
}
|
|
390
|
+
function safeSyncCursorPositions(...args) {
|
|
391
|
+
try {
|
|
392
|
+
syncCursorPositions(...args);
|
|
393
|
+
} catch {
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export { DEFAULT_LEXICAL_ROOT_NAME, DocLexicalError, createDocLexicalProvider, getLexicalSharedRoot, hasSharedLexicalContent, isDocLexicalError, mountDocLexical };
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@peerkit-dev/doc-lexical",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Reusable Lexical ↔ PeerKit DocSession collaboration adapter. Preserves structured Lexical state via @lexical/yjs over DocSession's Yjs lifecycle. Not an authoritative content store.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"homepage": "https://peerkit.dev/components/doc",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://peerkit.dev/contact"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=22"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"import": "./dist/index.js",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public",
|
|
30
|
+
"directory": "npm"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "pnpm --filter @peerkit-dev/doc-core prepack && node build.mjs",
|
|
34
|
+
"typecheck": "pnpm --filter @peerkit-dev/doc-core prepack && tsc -p tsconfig.json --noEmit",
|
|
35
|
+
"test": "pnpm --filter @peerkit-dev/doc-core prepack && tsx --test --test-isolation=process --test-force-exit test/**/*.test.ts",
|
|
36
|
+
"prepack": "pnpm run build && node ../../scripts/ui-pack-manifest.mjs doc-lexical"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@lexical/yjs": "^0.50.0",
|
|
40
|
+
"@peerkit-dev/doc-core": "^0.1.1",
|
|
41
|
+
"lexical": "^0.50.0",
|
|
42
|
+
"yjs": "^13.6.33"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@lexical/headless": "0.50.0",
|
|
46
|
+
"@lexical/list": "0.50.0",
|
|
47
|
+
"@lexical/rich-text": "0.50.0",
|
|
48
|
+
"@lexical/yjs": "0.50.0",
|
|
49
|
+
"@peerkit-dev/doc-core": "workspace:*",
|
|
50
|
+
"lexical": "0.50.0",
|
|
51
|
+
"tsup": "8.5.1",
|
|
52
|
+
"tsx": "4.23.15",
|
|
53
|
+
"typescript": "5.9.3",
|
|
54
|
+
"yjs": "^13.6.33"
|
|
55
|
+
}
|
|
56
|
+
}
|