@dovetail-ts/tiptap 0.0.0-stage → 1.0.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/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +117 -2
- package/dist/binding.d.ts +41 -0
- package/dist/index.d.ts +80 -0
- package/dist/index.js +176 -0
- package/dist/index.js.map +1 -0
- package/dist/loro.d.ts +3 -0
- package/dist/loro.js +187 -0
- package/dist/loro.js.map +1 -0
- package/dist/yjs.d.ts +3 -0
- package/dist/yjs.js +52 -0
- package/dist/yjs.js.map +1 -0
- package/package.json +106 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @dovetail-ts/tiptap
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 480744b: First release of Dovetail: real-time and offline sync for Ember.
|
|
8
|
+
|
|
9
|
+
- `@dovetail-ts/core`: the connection life cycle, live store subscriptions, the optimistic ledger with rebase and rollback, the offline write queue in IndexedDB with a leader tab and dead letters, `DocSession` and `PresenceRoom`.
|
|
10
|
+
- `@dovetail-ts/warp-drive`: the store feed into WarpDrive.
|
|
11
|
+
- `@dovetail-ts/crdt`, `crdt-yjs`, `crdt-loro` and `crdt-automerge`: one `DocEngine` interface with three engines.
|
|
12
|
+
- `@dovetail-ts/tiptap`: co-editing in Tiptap 3 with carets, per-user undo, versions and comment threads.
|
|
13
|
+
- `@dovetail-ts/ember`, `notifications` and `inspector`: presence and status components, the inbox, toasts and activity feeds, and a dev panel.
|
|
14
|
+
- `@dovetail-ts/server`, the transports (`transport-ws`, `transport-sse`, `transport-cable`) and `conformance`: a Node server and one wire protocol that the Rails gems also pass.
|
|
15
|
+
- Adapters for Hocuspocus, Liveblocks, PartyKit and Supabase, and integrations for Switchyard, Millwork, Benchdog and Lattice. The Neon adapter is not in 1.0: it waits for a stable Neon Realtime client (1.1).
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- Updated dependencies [480744b]
|
|
20
|
+
- @dovetail-ts/crdt-loro@1.0.0
|
|
21
|
+
- @dovetail-ts/crdt-yjs@1.0.0
|
|
22
|
+
- @dovetail-ts/crdt@1.0.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joe Gaudet
|
|
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,118 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dovetail-ts/tiptap
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Collaboration, remote carets, per-user undo, version history, comment threads and activity
|
|
4
|
+
events for Tiptap 3. It works on a `DocEngine` of Dovetail that has a binding.
|
|
5
|
+
|
|
6
|
+
Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
|
|
7
|
+
|
|
8
|
+
## Add it to an editor
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { Editor } from '@tiptap/core'
|
|
12
|
+
import StarterKit from '@tiptap/starter-kit'
|
|
13
|
+
import { yjsEngine } from '@dovetail-ts/crdt-yjs'
|
|
14
|
+
import { createDovetail } from '@dovetail-ts/tiptap'
|
|
15
|
+
import { yjsBinding } from '@dovetail-ts/tiptap/yjs'
|
|
16
|
+
|
|
17
|
+
const handle = yjsEngine().create()
|
|
18
|
+
const dovetail = createDovetail({
|
|
19
|
+
handle,
|
|
20
|
+
binding: yjsBinding,
|
|
21
|
+
user: { id: 'u1', name: 'Ann', color: '#ff6b00' },
|
|
22
|
+
onActivity: event => feed.push(event),
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const editor = new Editor({
|
|
26
|
+
element,
|
|
27
|
+
// The CRDT has its own undo, so turn off the undo of StarterKit.
|
|
28
|
+
extensions: [StarterKit.configure({ undoRedo: false }), dovetail.extension],
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Make one `createDovetail` for each editor. Sync `handle` with the peers through a transport (the
|
|
33
|
+
`doc-sync`, `doc-update` and `awareness` messages). This package does not send messages.
|
|
34
|
+
|
|
35
|
+
## The features
|
|
36
|
+
|
|
37
|
+
| Feature | API |
|
|
38
|
+
| --------------- | ---------------------------------------------------------------------------- |
|
|
39
|
+
| Collaboration | The content of the editor is in the `default` root type of the document. |
|
|
40
|
+
| Remote carets | The caret and the selection of each peer, with the name and color of `user`. |
|
|
41
|
+
| Per-user undo | `dovetail.undo()` and `dovetail.redo()` change only the edits of this user. |
|
|
42
|
+
| Version history | `dovetail.versions`: `create`, `list`, `preview`, `restore`, `subscribe`. |
|
|
43
|
+
| Comment threads | `dovetail.threads`: `create`, `reply`, `resolve`, `reopen`, `list`, …. |
|
|
44
|
+
| Activity events | `onActivity` gets `edited`, `commented` and `restored` events. |
|
|
45
|
+
|
|
46
|
+
### Version history
|
|
47
|
+
|
|
48
|
+
- `versions.create(name?)` keeps the content now as a version. The versions are in the
|
|
49
|
+
document, so each peer sees them.
|
|
50
|
+
- `versions.list()` gives the timeline, the oldest version first.
|
|
51
|
+
- `versions.preview(id)` gives the content of a version as Tiptap JSON. The document does not
|
|
52
|
+
change. Show it in a second editor with `editable: false`.
|
|
53
|
+
- `versions.restore(id)` makes the content equal to the version, as an edit of this user. The
|
|
54
|
+
anchors of threads in text that did not change stay.
|
|
55
|
+
|
|
56
|
+
### Comment threads
|
|
57
|
+
|
|
58
|
+
- `threads.create(body)` starts a thread on the selection of the editor. Select some text first.
|
|
59
|
+
- The anchor of a thread follows the edits of all users. `threads.list()` gives `from` and `to`,
|
|
60
|
+
the positions of the anchor now. They are null when the editor cannot find the anchor.
|
|
61
|
+
- `threads.reply(id, body)`, `threads.resolve(id)` and `threads.reopen(id)` change a thread.
|
|
62
|
+
Each reply has its own key in the document, so two replies at the same time both stay.
|
|
63
|
+
- `threads.subscribe(listener)` tells you about each change, also the changes of peers.
|
|
64
|
+
- The editor shows each open thread with the `dovetail-comment` class and a `data-thread-id`
|
|
65
|
+
attribute. Give the class a style.
|
|
66
|
+
- The author of a comment (`by`), and the name and color of a caret, come from the client of
|
|
67
|
+
that user. They are client data, not a verified identity. A changed client can write any
|
|
68
|
+
author or name. If the author must be true, make the server check it: the server
|
|
69
|
+
`authorizeAwareness` hook checks the presence state, and your own server code must check the
|
|
70
|
+
thread data.
|
|
71
|
+
|
|
72
|
+
### Activity events
|
|
73
|
+
|
|
74
|
+
Each event has a `verb`, an `actor` (the user id) and a `createdAt` date, as a notification has.
|
|
75
|
+
|
|
76
|
+
- `edited`: a local edit. At most one event in each minute.
|
|
77
|
+
- `commented`: a new thread or a reply, with `threadId` and `commentId`.
|
|
78
|
+
- `restored`: a restore of a version, with `versionId`.
|
|
79
|
+
|
|
80
|
+
Edits of peers do not make events. Each user sends the events of their own actions.
|
|
81
|
+
|
|
82
|
+
## Capabilities
|
|
83
|
+
|
|
84
|
+
`dovetail.capabilities` is the `capabilities` object of the engine. Check it before you show a
|
|
85
|
+
feature:
|
|
86
|
+
|
|
87
|
+
- No `tiptap`: `createDovetail` throws a `CapabilityError`.
|
|
88
|
+
- No `cursors`: the editor shows no remote carets.
|
|
89
|
+
- No `undo`: `undo()` and `redo()` do nothing and give `false`.
|
|
90
|
+
- No `history`: the `versions` methods throw a `CapabilityError`.
|
|
91
|
+
- No `commentAnchors`: the `threads` methods throw a `CapabilityError`.
|
|
92
|
+
|
|
93
|
+
## Bindings
|
|
94
|
+
|
|
95
|
+
A binding (`EditorBinding`) connects the editor to the documents of one engine. Each binding
|
|
96
|
+
has its own entry, so an app installs only the libraries of its engine:
|
|
97
|
+
|
|
98
|
+
| Entry | Binding | Install these peer dependencies |
|
|
99
|
+
| -------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
100
|
+
| `@dovetail-ts/tiptap/yjs` | `yjsBinding` | `@dovetail-ts/crdt-yjs`, `yjs`, `@tiptap/y-tiptap`, `@tiptap/extension-collaboration`, `@tiptap/extension-collaboration-caret` |
|
|
101
|
+
| `@dovetail-ts/tiptap/loro` | `loroBinding` | `@dovetail-ts/crdt-loro`, `loro-crdt`, `loro-prosemirror` |
|
|
102
|
+
|
|
103
|
+
The main entry `@dovetail-ts/tiptap` has no engine code. It needs only `@tiptap/core` and
|
|
104
|
+
`@tiptap/pm`. The engine libraries are optional peer dependencies.
|
|
105
|
+
|
|
106
|
+
- `yjsBinding` uses the Tiptap extensions `@tiptap/extension-collaboration` and
|
|
107
|
+
`@tiptap/extension-collaboration-caret`, on `@tiptap/y-tiptap`.
|
|
108
|
+
- `loroBinding` uses the sync, undo and caret plugins of `loro-prosemirror`. Its carets have the
|
|
109
|
+
`ProseMirror-loro-cursor` and `loro-selection` classes. The plugins start after a timeout, so
|
|
110
|
+
wait one task before the first edit. Start a new document on one peer only, and load it on
|
|
111
|
+
the other peers before they start an editor. `loro-prosemirror` imports the `prosemirror-*`
|
|
112
|
+
packages, not `@tiptap/pm`: make sure that the app has one copy of each, or ProseMirror
|
|
113
|
+
gives "Applying a mismatched transaction".
|
|
114
|
+
- Automerge has no binding: `@automerge/prosemirror` makes its own schema, and it cannot use the
|
|
115
|
+
schema of a Tiptap editor. `createDovetail` gives a `CapabilityError` for an Automerge
|
|
116
|
+
document.
|
|
117
|
+
|
|
118
|
+
The capability matrix is in the README of each engine package.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { AnyExtension, JSONContent } from '@tiptap/core';
|
|
2
|
+
import type { Schema } from '@tiptap/pm/model';
|
|
3
|
+
import type { EditorState, Transaction } from '@tiptap/pm/state';
|
|
4
|
+
import type { DocHandle, JsonValue } from '@dovetail-ts/crdt';
|
|
5
|
+
/** The user of an editor: the id for threads and activity, the name and color for carets. */
|
|
6
|
+
export interface DovetailUser {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
/**
|
|
10
|
+
* A `#rrggbb` color. The Loro carets also take `#rgb`, `#rgba` and `#rrggbbaa`, and show gray
|
|
11
|
+
* for another value. The Yjs carets take only `#rrggbb`, and show no color for another value.
|
|
12
|
+
*/
|
|
13
|
+
color: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The ProseMirror binding of one engine. The Dovetail extension uses it, so the extension works
|
|
17
|
+
* with each engine that has a binding. An engine package does not need Tiptap: the bindings
|
|
18
|
+
* are in this package.
|
|
19
|
+
*/
|
|
20
|
+
export interface EditorBinding {
|
|
21
|
+
/** The name of the engine of the binding, as `DocEngine.name`. */
|
|
22
|
+
readonly engine: string;
|
|
23
|
+
/**
|
|
24
|
+
* The Tiptap extensions that keep the content in the document, with per-user undo (the
|
|
25
|
+
* `undo` and `redo` commands), and the remote carets when `cursors` is true.
|
|
26
|
+
*/
|
|
27
|
+
extensions(options: {
|
|
28
|
+
handle: DocHandle;
|
|
29
|
+
field: string;
|
|
30
|
+
user: DovetailUser;
|
|
31
|
+
cursors: boolean;
|
|
32
|
+
}): AnyExtension[];
|
|
33
|
+
/** An anchor at `pos` that follows edits. It is JSON, so it can go in a shared map. */
|
|
34
|
+
anchor(state: EditorState, pos: number): JsonValue;
|
|
35
|
+
/** The position of an anchor now, or null when the editor cannot find it. */
|
|
36
|
+
resolve(state: EditorState, anchor: JsonValue): number | null;
|
|
37
|
+
/** The content of the field of a document (a version), as Tiptap JSON. */
|
|
38
|
+
content(handle: DocHandle, field: string, schema: Schema): JSONContent;
|
|
39
|
+
/** True when a transaction applies a change from the document (a peer, or undo). */
|
|
40
|
+
isRemote(transaction: Transaction): boolean;
|
|
41
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { Extension } from '@tiptap/core';
|
|
2
|
+
import type { JSONContent } from '@tiptap/core';
|
|
3
|
+
import type { DocHandle, EngineCapabilities, Version } from '@dovetail-ts/crdt';
|
|
4
|
+
import type { DovetailUser, EditorBinding } from './binding';
|
|
5
|
+
export type { DovetailUser, EditorBinding } from './binding';
|
|
6
|
+
export interface DovetailOptions {
|
|
7
|
+
/** The document of the editor, from `engine.create()` or `engine.load()`. */
|
|
8
|
+
handle: DocHandle;
|
|
9
|
+
/** The binding of the engine of `handle`, as `yjsBinding`. */
|
|
10
|
+
binding: EditorBinding;
|
|
11
|
+
user: DovetailUser;
|
|
12
|
+
/** The root type of the content. The default is `default`, as in Tiptap. */
|
|
13
|
+
field?: string;
|
|
14
|
+
/** Receives the activity of the local user, for the activity feed. */
|
|
15
|
+
onActivity?: (event: ActivityEvent) => void;
|
|
16
|
+
/** The clock of the dates. The default is `Date.now`. */
|
|
17
|
+
now?: () => number;
|
|
18
|
+
}
|
|
19
|
+
/** An action of the local user. The fields match a `notification` (verb, actor, createdAt). */
|
|
20
|
+
export interface ActivityEvent {
|
|
21
|
+
verb: 'edited' | 'commented' | 'restored';
|
|
22
|
+
/** The id of the user. */
|
|
23
|
+
actor: string;
|
|
24
|
+
/** An ISO 8601 date-time. */
|
|
25
|
+
createdAt: string;
|
|
26
|
+
threadId?: string;
|
|
27
|
+
commentId?: string;
|
|
28
|
+
versionId?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface ThreadComment {
|
|
31
|
+
id: string;
|
|
32
|
+
threadId: string;
|
|
33
|
+
body: string;
|
|
34
|
+
by: string;
|
|
35
|
+
createdAt: string;
|
|
36
|
+
}
|
|
37
|
+
/** A comment thread. `from` and `to` are the editor positions of the anchor now, or null. */
|
|
38
|
+
export interface Thread {
|
|
39
|
+
id: string;
|
|
40
|
+
from: number | null;
|
|
41
|
+
to: number | null;
|
|
42
|
+
resolved: boolean;
|
|
43
|
+
by: string;
|
|
44
|
+
createdAt: string;
|
|
45
|
+
/** The comments, the oldest first. The first comment starts the thread. */
|
|
46
|
+
comments: ThreadComment[];
|
|
47
|
+
}
|
|
48
|
+
/** The Dovetail features of one editor. Add `extension` to the extensions of the editor. */
|
|
49
|
+
export interface Dovetail {
|
|
50
|
+
readonly extension: Extension;
|
|
51
|
+
/** The features of the engine. A method of a missing feature throws a `CapabilityError`. */
|
|
52
|
+
readonly capabilities: EngineCapabilities;
|
|
53
|
+
/** Undoes the last change of this user only. False when there is nothing to undo. */
|
|
54
|
+
undo(): boolean;
|
|
55
|
+
redo(): boolean;
|
|
56
|
+
readonly threads: {
|
|
57
|
+
/** The threads, the oldest first. */
|
|
58
|
+
list(): Thread[];
|
|
59
|
+
/** Starts a thread on the selection of the editor. */
|
|
60
|
+
create(body: string): Thread;
|
|
61
|
+
reply(threadId: string, body: string): ThreadComment;
|
|
62
|
+
resolve(threadId: string): void;
|
|
63
|
+
reopen(threadId: string): void;
|
|
64
|
+
/** Calls `listener` when a thread or a comment changes, here or by a peer. */
|
|
65
|
+
subscribe(listener: () => void): () => void;
|
|
66
|
+
};
|
|
67
|
+
readonly versions: {
|
|
68
|
+
/** The versions, the oldest first. */
|
|
69
|
+
list(): Version[];
|
|
70
|
+
/** Keeps the content now as a version. */
|
|
71
|
+
create(name?: string): Version;
|
|
72
|
+
/** The content of a version, as Tiptap JSON. The document does not change. */
|
|
73
|
+
preview(id: string): JSONContent;
|
|
74
|
+
/** Makes the content equal to the version, as a change of this user. */
|
|
75
|
+
restore(id: string): void;
|
|
76
|
+
subscribe(listener: () => void): () => void;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** Makes the Dovetail features for one editor. */
|
|
80
|
+
export declare function createDovetail(options: DovetailOptions): Dovetail;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { Extension } from '@tiptap/core';
|
|
2
|
+
import { PluginKey, Plugin } from '@tiptap/pm/state';
|
|
3
|
+
import { DecorationSet, Decoration } from '@tiptap/pm/view';
|
|
4
|
+
import { requireCapability, CapabilityError } from '@dovetail-ts/crdt';
|
|
5
|
+
|
|
6
|
+
// src/index.ts
|
|
7
|
+
var RESTORE = "dovetail:restore";
|
|
8
|
+
var comments = new PluginKey("dovetailComments");
|
|
9
|
+
var EDITED_INTERVAL = 6e4;
|
|
10
|
+
function records(entries) {
|
|
11
|
+
return entries.map(([, value]) => value).filter((value) => typeof value === "object" && value !== null && "id" in value).map((value) => value);
|
|
12
|
+
}
|
|
13
|
+
var byTime = (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id);
|
|
14
|
+
function createDovetail(options) {
|
|
15
|
+
const { handle, binding, user, field = "default", onActivity, now = Date.now } = options;
|
|
16
|
+
const { engine } = handle;
|
|
17
|
+
requireCapability(engine, "tiptap");
|
|
18
|
+
if (binding.engine !== engine.name) {
|
|
19
|
+
throw new Error(`The "${binding.engine}" binding cannot edit a "${engine.name}" document.`);
|
|
20
|
+
}
|
|
21
|
+
const capabilities = engine.capabilities;
|
|
22
|
+
let editor = null;
|
|
23
|
+
let lastEdited = -Infinity;
|
|
24
|
+
let count = 0;
|
|
25
|
+
const newId = () => `${handle.awareness.clientId}-${now().toString(36)}-${(count++).toString(36)}`;
|
|
26
|
+
const at = () => new Date(now()).toISOString();
|
|
27
|
+
const emit = (verb, extra = {}) => onActivity?.({ verb, actor: user.id, createdAt: at(), ...extra });
|
|
28
|
+
function attached() {
|
|
29
|
+
if (!editor || editor.isDestroyed) throw new Error("Add dovetail.extension to an editor first.");
|
|
30
|
+
return editor;
|
|
31
|
+
}
|
|
32
|
+
function maps() {
|
|
33
|
+
requireCapability(engine, "commentAnchors");
|
|
34
|
+
return { threads: handle.map("dovetail:threads"), comments: handle.map("dovetail:comments") };
|
|
35
|
+
}
|
|
36
|
+
function versions() {
|
|
37
|
+
requireCapability(engine, "history");
|
|
38
|
+
if (!handle.versions) throw new CapabilityError(engine.name, "history");
|
|
39
|
+
return handle.versions;
|
|
40
|
+
}
|
|
41
|
+
function listAt(state) {
|
|
42
|
+
const { threads, comments: comments2 } = maps();
|
|
43
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const comment2 of records(comments2.entries())) {
|
|
45
|
+
grouped.set(comment2.threadId, [...grouped.get(comment2.threadId) ?? [], comment2]);
|
|
46
|
+
}
|
|
47
|
+
return records(threads.entries()).filter((thread) => typeof thread.anchor === "object" && thread.anchor !== null).map(({ anchor, ...thread }) => ({
|
|
48
|
+
...thread,
|
|
49
|
+
from: binding.resolve(state, anchor.from),
|
|
50
|
+
to: binding.resolve(state, anchor.to),
|
|
51
|
+
comments: (grouped.get(thread.id) ?? []).sort(byTime)
|
|
52
|
+
})).sort(byTime);
|
|
53
|
+
}
|
|
54
|
+
function comment(threadId, body) {
|
|
55
|
+
const value = { id: newId(), threadId, body, by: user.id, createdAt: at() };
|
|
56
|
+
maps().comments.set(`${threadId}/${value.id}`, { ...value });
|
|
57
|
+
emit("commented", { threadId, commentId: value.id });
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
function setResolved(threadId, resolved) {
|
|
61
|
+
const { threads } = maps();
|
|
62
|
+
const stored = records(threads.entries()).find((t) => t.id === threadId);
|
|
63
|
+
if (!stored) throw new Error(`No thread "${threadId}" in this document.`);
|
|
64
|
+
threads.set(threadId, { ...stored, resolved });
|
|
65
|
+
}
|
|
66
|
+
function subscribeMaps(listener) {
|
|
67
|
+
const { threads, comments: comments2 } = maps();
|
|
68
|
+
const stops = [threads.onChange(listener), comments2.onChange(listener)];
|
|
69
|
+
return () => stops.forEach((stop) => stop());
|
|
70
|
+
}
|
|
71
|
+
function preview(id) {
|
|
72
|
+
const version = versions().open(id);
|
|
73
|
+
try {
|
|
74
|
+
return binding.content(version, field, attached().schema);
|
|
75
|
+
} finally {
|
|
76
|
+
version.destroy();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
let stopRefresh = () => {
|
|
80
|
+
};
|
|
81
|
+
const extension = Extension.create({
|
|
82
|
+
name: "dovetail",
|
|
83
|
+
addExtensions() {
|
|
84
|
+
return binding.extensions({ handle, field, user, cursors: capabilities.cursors });
|
|
85
|
+
},
|
|
86
|
+
addProseMirrorPlugins() {
|
|
87
|
+
if (!capabilities.commentAnchors) return [];
|
|
88
|
+
return [
|
|
89
|
+
new Plugin({
|
|
90
|
+
key: comments,
|
|
91
|
+
props: {
|
|
92
|
+
// shortcut: resolves each anchor on each render; cache the set for many threads.
|
|
93
|
+
decorations: (state) => DecorationSet.create(
|
|
94
|
+
state.doc,
|
|
95
|
+
listAt(state).flatMap(
|
|
96
|
+
({ id, from, to, resolved }) => !resolved && from !== null && to !== null && from < to ? [
|
|
97
|
+
Decoration.inline(from, to, {
|
|
98
|
+
class: "dovetail-comment",
|
|
99
|
+
"data-thread-id": id
|
|
100
|
+
})
|
|
101
|
+
] : []
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
];
|
|
107
|
+
},
|
|
108
|
+
onBeforeCreate() {
|
|
109
|
+
editor = this.editor;
|
|
110
|
+
if (!capabilities.commentAnchors) return;
|
|
111
|
+
let queued = false;
|
|
112
|
+
stopRefresh = subscribeMaps(() => {
|
|
113
|
+
if (queued) return;
|
|
114
|
+
queued = true;
|
|
115
|
+
queueMicrotask(() => {
|
|
116
|
+
queued = false;
|
|
117
|
+
const view = editor?.isDestroyed === false ? editor.view : null;
|
|
118
|
+
view?.dispatch(view.state.tr.setMeta(comments, true));
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
},
|
|
122
|
+
onDestroy() {
|
|
123
|
+
stopRefresh();
|
|
124
|
+
editor = null;
|
|
125
|
+
},
|
|
126
|
+
onTransaction({ transaction }) {
|
|
127
|
+
if (!transaction.docChanged || binding.isRemote(transaction) || transaction.getMeta(RESTORE)) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (now() - lastEdited < EDITED_INTERVAL) return;
|
|
131
|
+
lastEdited = now();
|
|
132
|
+
emit("edited");
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
extension,
|
|
137
|
+
capabilities,
|
|
138
|
+
undo: () => capabilities.undo && attached().commands.undo(),
|
|
139
|
+
redo: () => capabilities.undo && attached().commands.redo(),
|
|
140
|
+
threads: {
|
|
141
|
+
list: () => listAt(attached().state),
|
|
142
|
+
create(body) {
|
|
143
|
+
const { state } = attached();
|
|
144
|
+
const { threads } = maps();
|
|
145
|
+
const { from, to } = state.selection;
|
|
146
|
+
if (from === to) throw new Error("Select the text of the thread first.");
|
|
147
|
+
const thread = { id: newId(), resolved: false, by: user.id, createdAt: at() };
|
|
148
|
+
const anchor = { from: binding.anchor(state, from), to: binding.anchor(state, to) };
|
|
149
|
+
threads.set(thread.id, { ...thread, anchor });
|
|
150
|
+
return { ...thread, from, to, comments: [comment(thread.id, body)] };
|
|
151
|
+
},
|
|
152
|
+
reply: (threadId, body) => comment(threadId, body),
|
|
153
|
+
resolve: (threadId) => setResolved(threadId, true),
|
|
154
|
+
reopen: (threadId) => setResolved(threadId, false),
|
|
155
|
+
subscribe: subscribeMaps
|
|
156
|
+
},
|
|
157
|
+
versions: {
|
|
158
|
+
list: () => versions().list(),
|
|
159
|
+
create: (name) => versions().create({ name, by: user.id }),
|
|
160
|
+
preview,
|
|
161
|
+
restore(id) {
|
|
162
|
+
const content = preview(id);
|
|
163
|
+
attached().chain().command(({ tr }) => {
|
|
164
|
+
tr.setMeta(RESTORE, true);
|
|
165
|
+
return true;
|
|
166
|
+
}).setContent(content).run();
|
|
167
|
+
emit("restored", { versionId: id });
|
|
168
|
+
},
|
|
169
|
+
subscribe: (listener) => versions().onChange(listener)
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export { createDovetail };
|
|
175
|
+
//# sourceMappingURL=index.js.map
|
|
176
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["comments","comment"],"mappings":";;;;;;AAgGA,IAAM,OAAA,GAAU,kBAAA;AAChB,IAAM,QAAA,GAAW,IAAI,SAAA,CAAyB,kBAAkB,CAAA;AAEhE,IAAM,eAAA,GAAkB,GAAA;AAGxB,SAAS,QAAW,OAAA,EAAqC;AACvD,EAAA,OAAO,OAAA,CACJ,IAAI,CAAC,GAAG,KAAK,CAAA,KAAM,KAAK,CAAA,CACxB,MAAA,CAAO,WAAS,OAAO,KAAA,KAAU,YAAY,KAAA,KAAU,IAAA,IAAQ,QAAQ,KAAK,CAAA,CAC5E,GAAA,CAAI,CAAA,KAAA,KAAS,KAAqB,CAAA;AACvC;AAEA,IAAM,MAAA,GAAS,CAAC,CAAA,EAAsC,CAAA,KACpD,EAAE,SAAA,CAAU,aAAA,CAAc,CAAA,CAAE,SAAS,CAAA,IAAK,CAAA,CAAE,EAAA,CAAG,aAAA,CAAc,EAAE,EAAE,CAAA;AAG5D,SAAS,eAAe,OAAA,EAAoC;AACjE,EA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MACrE,CAAA;AAAA,MAEA,OAAO,CAAC,QAAA,EAAU,IAAA,KAAS,OAAA,CAAQ,UAAU,IAAI,CAAA;AAAA,MACjD,OAAA,EAAS,CAAA,QAAA,KAAY,WAAA,CAAY,QAAA,EAAU,IAAI,CAAA;AAAA,MAC/C,MAAA,EAAQ,CAAA,QAAA,KAAY,WAAA,CAAY,QAAA,EAAU,KAAK,CAAA;AAAA,MAC/C,SAAA,EAAW;AAAA,KACb;AAAA,IAEA,QAAA,EAAU;AAAA,MACR,IAAA,EAAM,MAAM,QAAA,EAAS,CAAE,IAAA,EAAK;AAAA,MAC5B,MAAA,EAAQ,CAAA,IAAA,KAAQ,QAAA,EAAS,CAAE,MAAA,CAAO,EAAE,IAAA,EAAM,EAAA,EAAI,IAAA,CAAK,EAAA,EAAI,CAAA;AAAA,MACvD,OAAA;AAAA,MAEA,QAAQ,EAAA,EAAI;AACV,QAAA,MAAM,OAAA,GAAU,QAAQ,EAAE,CAAA;AAC1B,QAAA,QAAA,GACG,KAAA,EAAM,CACN,QAAQ,CAAC,EAAE,IAAG,KAAM;AACnB,UAAA,EAAA,CAAG,OAAA,CAAQ,SAAS,IAAI,CAAA;AACxB,UAAA,OAAO,IAAA;AAAA,QACT,CAAC,CAAA,CACA,UAAA,CAAW,OAAO,EAClB,GAAA,EAAI;AACP,QAAA,IAAA,CAAK,UAAA,EAAY,EAAE,SAAA,EAAW,EAAA,EAAI,CAAA;AAAA,MACpC,CAAA;AAAA,MAEA,SAAA,EAAW,CAAA,QAAA,KAAY,QAAA,EAAS,CAAE,SAAS,QAAQ;AAAA;AACrD,GACF;AACF","file":"index.js","sourcesContent":["// Collaboration, carets, per-user undo, version history, comment threads and activity events\n// for Tiptap 3, on any `DocEngine` with a binding (ADR 0013).\nimport { Extension } from '@tiptap/core'\nimport type { Editor, JSONContent } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { EditorState } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { CapabilityError, requireCapability } from '@dovetail-ts/crdt'\nimport type { DocHandle, EngineCapabilities, JsonValue, Version } from '@dovetail-ts/crdt'\nimport type { DovetailUser, EditorBinding } from './binding'\n\nexport type { DovetailUser, EditorBinding } from './binding'\n\nexport interface DovetailOptions {\n /** The document of the editor, from `engine.create()` or `engine.load()`. */\n handle: DocHandle\n /** The binding of the engine of `handle`, as `yjsBinding`. */\n binding: EditorBinding\n user: DovetailUser\n /** The root type of the content. The default is `default`, as in Tiptap. */\n field?: string\n /** Receives the activity of the local user, for the activity feed. */\n onActivity?: (event: ActivityEvent) => void\n /** The clock of the dates. The default is `Date.now`. */\n now?: () => number\n}\n\n/** An action of the local user. The fields match a `notification` (verb, actor, createdAt). */\nexport interface ActivityEvent {\n verb: 'edited' | 'commented' | 'restored'\n /** The id of the user. */\n actor: string\n /** An ISO 8601 date-time. */\n createdAt: string\n threadId?: string\n commentId?: string\n versionId?: string\n}\n\nexport interface ThreadComment {\n id: string\n threadId: string\n body: string\n by: string\n createdAt: string\n}\n\n/** A comment thread. `from` and `to` are the editor positions of the anchor now, or null. */\nexport interface Thread {\n id: string\n from: number | null\n to: number | null\n resolved: boolean\n by: string\n createdAt: string\n /** The comments, the oldest first. The first comment starts the thread. */\n comments: ThreadComment[]\n}\n\n/** The Dovetail features of one editor. Add `extension` to the extensions of the editor. */\nexport interface Dovetail {\n readonly extension: Extension\n /** The features of the engine. A method of a missing feature throws a `CapabilityError`. */\n readonly capabilities: EngineCapabilities\n /** Undoes the last change of this user only. False when there is nothing to undo. */\n undo(): boolean\n redo(): boolean\n readonly threads: {\n /** The threads, the oldest first. */\n list(): Thread[]\n /** Starts a thread on the selection of the editor. */\n create(body: string): Thread\n reply(threadId: string, body: string): ThreadComment\n resolve(threadId: string): void\n reopen(threadId: string): void\n /** Calls `listener` when a thread or a comment changes, here or by a peer. */\n subscribe(listener: () => void): () => void\n }\n readonly versions: {\n /** The versions, the oldest first. */\n list(): Version[]\n /** Keeps the content now as a version. */\n create(name?: string): Version\n /** The content of a version, as Tiptap JSON. The document does not change. */\n preview(id: string): JSONContent\n /** Makes the content equal to the version, as a change of this user. */\n restore(id: string): void\n subscribe(listener: () => void): () => void\n }\n}\n\ntype StoredThread = { id: string; anchor: { from: JsonValue; to: JsonValue } } & Omit<\n Thread,\n 'id' | 'from' | 'to' | 'comments'\n>\n\nconst RESTORE = 'dovetail:restore'\nconst comments = new PluginKey<DecorationSet>('dovetailComments')\n// shortcut: one `edited` event a minute at most; make it an option when a feed needs other rates.\nconst EDITED_INTERVAL = 60_000\n\n/** Values of a shared map that have an `id`. Peers write the map, so skip other values. */\nfunction records<T>(entries: [string, JsonValue][]): T[] {\n return entries\n .map(([, value]) => value)\n .filter(value => typeof value === 'object' && value !== null && 'id' in value)\n .map(value => value as unknown as T)\n}\n\nconst byTime = (a: { createdAt: string; id: string }, b: { createdAt: string; id: string }) =>\n a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)\n\n/** Makes the Dovetail features for one editor. */\nexport function createDovetail(options: DovetailOptions): Dovetail {\n const { handle, binding, user, field = 'default', onActivity, now = Date.now } = options\n const { engine } = handle\n requireCapability(engine, 'tiptap')\n if (binding.engine !== engine.name) {\n throw new Error(`The \"${binding.engine}\" binding cannot edit a \"${engine.name}\" document.`)\n }\n const capabilities = engine.capabilities\n\n let editor: Editor | null = null\n let lastEdited = -Infinity\n let count = 0\n const newId = () => `${handle.awareness.clientId}-${now().toString(36)}-${(count++).toString(36)}`\n const at = () => new Date(now()).toISOString()\n const emit = (verb: ActivityEvent['verb'], extra: Partial<ActivityEvent> = {}) =>\n onActivity?.({ verb, actor: user.id, createdAt: at(), ...extra })\n\n function attached(): Editor {\n if (!editor || editor.isDestroyed) throw new Error('Add dovetail.extension to an editor first.')\n return editor\n }\n function maps() {\n requireCapability(engine, 'commentAnchors')\n return { threads: handle.map('dovetail:threads'), comments: handle.map('dovetail:comments') }\n }\n function versions() {\n requireCapability(engine, 'history')\n if (!handle.versions) throw new CapabilityError(engine.name, 'history')\n return handle.versions\n }\n\n function listAt(state: EditorState): Thread[] {\n const { threads, comments } = maps()\n const grouped = new Map<string, ThreadComment[]>()\n for (const comment of records<ThreadComment>(comments.entries())) {\n grouped.set(comment.threadId, [...(grouped.get(comment.threadId) ?? []), comment])\n }\n return records<StoredThread>(threads.entries())\n .filter(thread => typeof thread.anchor === 'object' && thread.anchor !== null)\n .map(({ anchor, ...thread }) => ({\n ...thread,\n from: binding.resolve(state, anchor.from),\n to: binding.resolve(state, anchor.to),\n comments: (grouped.get(thread.id) ?? []).sort(byTime),\n }))\n .sort(byTime)\n }\n\n function comment(threadId: string, body: string): ThreadComment {\n const value: ThreadComment = { id: newId(), threadId, body, by: user.id, createdAt: at() }\n maps().comments.set(`${threadId}/${value.id}`, { ...value })\n emit('commented', { threadId, commentId: value.id })\n return value\n }\n\n function setResolved(threadId: string, resolved: boolean): void {\n const { threads } = maps()\n const stored = records<StoredThread>(threads.entries()).find(t => t.id === threadId)\n if (!stored) throw new Error(`No thread \"${threadId}\" in this document.`)\n threads.set(threadId, { ...stored, resolved })\n }\n\n function subscribeMaps(listener: () => void): () => void {\n const { threads, comments } = maps()\n const stops = [threads.onChange(listener), comments.onChange(listener)]\n return () => stops.forEach(stop => stop())\n }\n\n function preview(id: string): JSONContent {\n const version = versions().open(id)\n try {\n return binding.content(version, field, attached().schema)\n } finally {\n version.destroy()\n }\n }\n\n let stopRefresh = () => {}\n\n const extension = Extension.create({\n name: 'dovetail',\n\n addExtensions() {\n return binding.extensions({ handle, field, user, cursors: capabilities.cursors })\n },\n\n addProseMirrorPlugins() {\n if (!capabilities.commentAnchors) return []\n return [\n new Plugin({\n key: comments,\n props: {\n // shortcut: resolves each anchor on each render; cache the set for many threads.\n decorations: state =>\n DecorationSet.create(\n state.doc,\n listAt(state).flatMap(({ id, from, to, resolved }) =>\n !resolved && from !== null && to !== null && from < to\n ? [\n Decoration.inline(from, to, {\n class: 'dovetail-comment',\n 'data-thread-id': id,\n }),\n ]\n : [],\n ),\n ),\n },\n }),\n ]\n },\n\n onBeforeCreate() {\n // `create` comes after a timeout, so take the editor before it.\n editor = this.editor\n if (!capabilities.commentAnchors) return\n // A thread change of a peer has no editor transaction, so draw the threads again. Do it\n // after the Yjs transaction: a dispatch before the binding renders the remote content\n // writes the old editor content back into the document.\n let queued = false\n stopRefresh = subscribeMaps(() => {\n if (queued) return\n queued = true\n queueMicrotask(() => {\n queued = false\n const view = editor?.isDestroyed === false ? editor.view : null\n view?.dispatch(view.state.tr.setMeta(comments, true))\n })\n })\n },\n\n onDestroy() {\n stopRefresh()\n editor = null\n },\n\n onTransaction({ transaction }) {\n if (\n !transaction.docChanged ||\n binding.isRemote(transaction) ||\n transaction.getMeta(RESTORE)\n ) {\n return\n }\n if (now() - lastEdited < EDITED_INTERVAL) return\n lastEdited = now()\n emit('edited')\n },\n })\n\n return {\n extension,\n capabilities,\n\n undo: () => capabilities.undo && attached().commands.undo(),\n redo: () => capabilities.undo && attached().commands.redo(),\n\n threads: {\n list: () => listAt(attached().state),\n\n create(body) {\n const { state } = attached()\n const { threads } = maps()\n const { from, to } = state.selection\n if (from === to) throw new Error('Select the text of the thread first.')\n const thread = { id: newId(), resolved: false, by: user.id, createdAt: at() }\n const anchor = { from: binding.anchor(state, from), to: binding.anchor(state, to) }\n threads.set(thread.id, { ...thread, anchor })\n return { ...thread, from, to, comments: [comment(thread.id, body)] }\n },\n\n reply: (threadId, body) => comment(threadId, body),\n resolve: threadId => setResolved(threadId, true),\n reopen: threadId => setResolved(threadId, false),\n subscribe: subscribeMaps,\n },\n\n versions: {\n list: () => versions().list(),\n create: name => versions().create({ name, by: user.id }),\n preview,\n\n restore(id) {\n const content = preview(id)\n attached()\n .chain()\n .command(({ tr }) => {\n tr.setMeta(RESTORE, true)\n return true\n })\n .setContent(content)\n .run()\n emit('restored', { versionId: id })\n },\n\n subscribe: listener => versions().onChange(listener),\n },\n }\n}\n"]}
|
package/dist/loro.d.ts
ADDED
package/dist/loro.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { Extension } from '@tiptap/core';
|
|
2
|
+
import { Cursor, UndoManager, LoroText, LoroList } from 'loro-crdt';
|
|
3
|
+
import { loroSyncPluginKey, createNodeFromLoroObj, CursorEphemeralStore, redo, undo, LoroSyncPlugin, LoroUndoPlugin, LoroEphemeralCursorPlugin, CHILDREN_KEY } from 'loro-prosemirror';
|
|
4
|
+
import { LoroDocHandle } from '@dovetail-ts/crdt-loro';
|
|
5
|
+
|
|
6
|
+
// src/loro.ts
|
|
7
|
+
function loroHandle(handle) {
|
|
8
|
+
if (handle instanceof LoroDocHandle) return handle;
|
|
9
|
+
throw new Error("The loro binding needs a document of @dovetail-ts/crdt-loro.");
|
|
10
|
+
}
|
|
11
|
+
function syncState(state) {
|
|
12
|
+
const sync = loroSyncPluginKey.getState(state);
|
|
13
|
+
return sync?.mapping.size ? { doc: sync.doc, mapping: sync.mapping } : null;
|
|
14
|
+
}
|
|
15
|
+
var CURSOR_FIELD = "loroCursor";
|
|
16
|
+
var HEX_COLOR = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
17
|
+
var FALLBACK_COLOR = "#6b7280";
|
|
18
|
+
function caret(store, peer) {
|
|
19
|
+
const user = store.getAll()[peer]?.user;
|
|
20
|
+
const color = typeof user?.color === "string" && HEX_COLOR.test(user.color) ? user.color : FALLBACK_COLOR;
|
|
21
|
+
const element = document.createElement("span");
|
|
22
|
+
element.classList.add("ProseMirror-loro-cursor");
|
|
23
|
+
element.style.borderColor = color;
|
|
24
|
+
const label = document.createElement("div");
|
|
25
|
+
label.style.backgroundColor = color;
|
|
26
|
+
label.textContent = user?.name ?? peer.slice(0, 6);
|
|
27
|
+
element.append("\u2060", label, "\u2060");
|
|
28
|
+
return element;
|
|
29
|
+
}
|
|
30
|
+
var loroBinding = {
|
|
31
|
+
engine: "loro",
|
|
32
|
+
extensions({ handle, field, user, cursors }) {
|
|
33
|
+
const { doc, awareness } = loroHandle(handle);
|
|
34
|
+
const loroDoc = doc;
|
|
35
|
+
const containerId = doc.getMap(field).id;
|
|
36
|
+
const store = new CursorEphemeralStore(doc.peerIdStr);
|
|
37
|
+
const stops = [];
|
|
38
|
+
return [
|
|
39
|
+
Extension.create({
|
|
40
|
+
name: "loroCollaboration",
|
|
41
|
+
addProseMirrorPlugins() {
|
|
42
|
+
const undoManager = new UndoManager(doc, { excludeOriginPrefixes: ["dovetail:"] });
|
|
43
|
+
const plugins = [
|
|
44
|
+
LoroSyncPlugin({ doc: loroDoc, containerId }),
|
|
45
|
+
LoroUndoPlugin({ doc, undoManager })
|
|
46
|
+
];
|
|
47
|
+
if (cursors) {
|
|
48
|
+
plugins.push(
|
|
49
|
+
LoroEphemeralCursorPlugin(store, {
|
|
50
|
+
user: { name: user.name, color: user.color },
|
|
51
|
+
createCursor: (peer) => caret(store, peer)
|
|
52
|
+
})
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return plugins;
|
|
56
|
+
},
|
|
57
|
+
addCommands() {
|
|
58
|
+
return {
|
|
59
|
+
// The Loro plugins dispatch the change, so Tiptap must not dispatch its transaction.
|
|
60
|
+
undo: () => ({ state, tr, dispatch }) => {
|
|
61
|
+
tr.setMeta("preventDispatch", true);
|
|
62
|
+
return undo(state, dispatch);
|
|
63
|
+
},
|
|
64
|
+
redo: () => ({ state, tr, dispatch }) => {
|
|
65
|
+
tr.setMeta("preventDispatch", true);
|
|
66
|
+
return redo(state, dispatch);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
},
|
|
70
|
+
addKeyboardShortcuts() {
|
|
71
|
+
return {
|
|
72
|
+
"Mod-z": () => this.editor.commands.undo(),
|
|
73
|
+
"Shift-Mod-z": () => this.editor.commands.redo(),
|
|
74
|
+
"Mod-y": () => this.editor.commands.redo()
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
onCreate() {
|
|
78
|
+
if (!cursors) return;
|
|
79
|
+
awareness.setLocalStateField("user", { ...user });
|
|
80
|
+
stops.push(
|
|
81
|
+
store.subscribeLocalUpdates(
|
|
82
|
+
(bytes) => awareness.setLocalStateField(CURSOR_FIELD, [...bytes])
|
|
83
|
+
),
|
|
84
|
+
awareness.onChange((change) => {
|
|
85
|
+
if (change.local) return;
|
|
86
|
+
const states = awareness.getStates();
|
|
87
|
+
for (const id of [...change.added, ...change.updated]) {
|
|
88
|
+
const bytes = states.get(id)?.[CURSOR_FIELD];
|
|
89
|
+
if (Array.isArray(bytes) && bytes.every((byte) => typeof byte === "number")) {
|
|
90
|
+
store.apply(Uint8Array.from(bytes));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
})
|
|
94
|
+
);
|
|
95
|
+
},
|
|
96
|
+
onDestroy() {
|
|
97
|
+
for (const stop of stops.splice(0)) stop();
|
|
98
|
+
store.destroy();
|
|
99
|
+
}
|
|
100
|
+
})
|
|
101
|
+
];
|
|
102
|
+
},
|
|
103
|
+
anchor(state, pos) {
|
|
104
|
+
const sync = syncState(state);
|
|
105
|
+
if (!sync) throw new Error("The editor has no Loro content yet.");
|
|
106
|
+
const cursor = absolutePositionToCursor(state.doc, pos, sync.doc, sync.mapping);
|
|
107
|
+
if (!cursor) throw new Error(`No Loro position for ${pos}.`);
|
|
108
|
+
return [...cursor.encode()];
|
|
109
|
+
},
|
|
110
|
+
resolve(state, anchor) {
|
|
111
|
+
const sync = syncState(state);
|
|
112
|
+
if (!sync || !Array.isArray(anchor)) return null;
|
|
113
|
+
const bytes = Uint8Array.from(anchor.filter((byte) => typeof byte === "number"));
|
|
114
|
+
return cursorToAbsolutePosition(Cursor.decode(bytes), sync.doc, sync.mapping);
|
|
115
|
+
},
|
|
116
|
+
content(handle, field, schema) {
|
|
117
|
+
const { doc } = loroHandle(handle);
|
|
118
|
+
return createNodeFromLoroObj(
|
|
119
|
+
schema,
|
|
120
|
+
doc.getMap(field),
|
|
121
|
+
/* @__PURE__ */ new Map()
|
|
122
|
+
).toJSON();
|
|
123
|
+
},
|
|
124
|
+
isRemote(transaction) {
|
|
125
|
+
const meta = transaction.getMeta(loroSyncPluginKey);
|
|
126
|
+
return meta?.type === "non-local-updates" || meta?.type === "update-state";
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
function containerOf(mapping, node) {
|
|
130
|
+
for (const [id, value] of mapping) if (value === node) return id;
|
|
131
|
+
return void 0;
|
|
132
|
+
}
|
|
133
|
+
function absolutePositionToCursor(root, pos, doc, mapping) {
|
|
134
|
+
const resolved = root.resolve(pos);
|
|
135
|
+
const id = containerOf(mapping, resolved.node(resolved.depth));
|
|
136
|
+
if (!id) return void 0;
|
|
137
|
+
const children = doc.getMap(id).get(CHILDREN_KEY);
|
|
138
|
+
if (children.length === 0) return children.getCursor(0);
|
|
139
|
+
let index = resolved.parentOffset;
|
|
140
|
+
for (let childIndex = 0; index >= 0 && childIndex < children.length; ) {
|
|
141
|
+
const child = children.get(childIndex);
|
|
142
|
+
childIndex += 1;
|
|
143
|
+
if (child instanceof LoroText) return child.getCursor(index);
|
|
144
|
+
if (index === 0 && childIndex < children.length) index += 1;
|
|
145
|
+
index -= 1;
|
|
146
|
+
}
|
|
147
|
+
return void 0;
|
|
148
|
+
}
|
|
149
|
+
function cursorToAbsolutePosition(cursor, doc, mapping) {
|
|
150
|
+
const containerId = cursor.containerId();
|
|
151
|
+
let index = -1;
|
|
152
|
+
let target;
|
|
153
|
+
let node;
|
|
154
|
+
if (containerId.endsWith("List")) {
|
|
155
|
+
const list = doc.getContainerById(containerId);
|
|
156
|
+
const parent = list instanceof LoroList ? list.parent() : void 0;
|
|
157
|
+
if (!parent) return null;
|
|
158
|
+
target = parent.id;
|
|
159
|
+
node = parent.parent()?.parent();
|
|
160
|
+
index = 0;
|
|
161
|
+
} else {
|
|
162
|
+
const position = doc.getCursorPos(cursor);
|
|
163
|
+
if (!position) return null;
|
|
164
|
+
const text = doc.getText(containerId);
|
|
165
|
+
index += position.offset;
|
|
166
|
+
target = text.id;
|
|
167
|
+
node = text.parent()?.parent();
|
|
168
|
+
}
|
|
169
|
+
while (node) {
|
|
170
|
+
const children = node.get(CHILDREN_KEY);
|
|
171
|
+
if (!(children instanceof LoroList)) return null;
|
|
172
|
+
for (const child of children.toArray()) {
|
|
173
|
+
if (child.id === target) break;
|
|
174
|
+
const mapped = mapping.get(child.id);
|
|
175
|
+
if (mapped === void 0) return null;
|
|
176
|
+
for (const each of Array.isArray(mapped) ? mapped : [mapped]) index += each.nodeSize;
|
|
177
|
+
}
|
|
178
|
+
target = node.id;
|
|
179
|
+
node = node.parent()?.parent();
|
|
180
|
+
index += 1;
|
|
181
|
+
}
|
|
182
|
+
return index;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export { loroBinding };
|
|
186
|
+
//# sourceMappingURL=loro.js.map
|
|
187
|
+
//# sourceMappingURL=loro.js.map
|
package/dist/loro.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/loro.ts"],"names":[],"mappings":";;;;;;AAsBA,SAAS,WAAW,MAAA,EAAkC;AACpD,EAAA,IAAI,MAAA,YAAkB,eAAe,OAAO,MAAA;AAC5C,EAAA,MAAM,IAAI,MAAM,8DAA8D,CAAA;AAChF;AAGA,SAAS,UAAU,KAAA,EAAoB;AACrC,EAAA,MAAM,IAAA,GAAO,iBAAA,CAAkB,QAAA,CAAS,KAAK,CAAA;AAC7C,EAAA,OAAO,IAAA,EAAM,OAAA,CAAQ,IAAA,GAAO,EAAE,GAAA,EAAK,KAAK,GAAA,EAAK,OAAA,EAAS,IAAA,CAAK,OAAA,EAAQ,GAAI,IAAA;AACzE;AAGA,IAAM,YAAA,GAAe,YAAA;AAMrB,IAAM,SAAA,GAAY,+CAAA;AAGlB,IAAM,cAAA,GAAiB,SAAA;AAOvB,SAAS,KAAA,CAAM,OAA6B,IAAA,EAA2B;AACrE,EAAA,MAAM,IAAA,GAAO,KAAA,CAAM,MAAA,EAAO,CAAE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AAQ,GAAA,CAAI,KAAA,CAAM,EAAE,CAAA;AACnC,MAAA,IAAI,MAAA,KAAW,QAAW,OAAO,IAAA;AACjC,MAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,GAAI,SAAS,CAAC,MAAM,CAAA,EAAG,KAAA,IAAS,IAAA,CAAK,QAAA;AAAA,IAC9E;AACA,IAAA,MAAA,GAAS,IAAA,CAAK,EAAA;AACd,IAAA,IAAA,GAAO,IAAA,CAAK,MAAA,EAAO,EAAG,MAAA,EAAO;AAC7B,IAAA,KAAA,IAAS,CAAA;AAAA,EACX;AACA,EAAA,OAAO,KAAA;AACT","file":"loro.js","sourcesContent":["// The Loro binding. It uses the ProseMirror plugins of `loro-prosemirror` (ADR 0014).\nimport { Extension } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\nimport { Cursor, LoroList, LoroText, UndoManager } from 'loro-crdt'\nimport type { ContainerID, LoroDoc, PeerID } from 'loro-crdt'\nimport {\n CHILDREN_KEY,\n createNodeFromLoroObj,\n CursorEphemeralStore,\n LoroEphemeralCursorPlugin,\n LoroSyncPlugin,\n loroSyncPluginKey,\n LoroUndoPlugin,\n redo,\n undo,\n} from 'loro-prosemirror'\nimport type { LoroDocType, LoroNode, LoroNodeMapping } from 'loro-prosemirror'\nimport { LoroDocHandle } from '@dovetail-ts/crdt-loro'\nimport type { DocHandle } from '@dovetail-ts/crdt'\nimport type { EditorBinding } from './binding'\n\nfunction loroHandle(handle: DocHandle): LoroDocHandle {\n if (handle instanceof LoroDocHandle) return handle\n throw new Error('The loro binding needs a document of @dovetail-ts/crdt-loro.')\n}\n\n/** The Loro state of the editor, or null before the plugin starts. */\nfunction syncState(state: EditorState) {\n const sync = loroSyncPluginKey.getState(state)\n return sync?.mapping.size ? { doc: sync.doc, mapping: sync.mapping } : null\n}\n\n/** The awareness field of the Loro carets: the bytes of a `CursorEphemeralStore` update. */\nconst CURSOR_FIELD = 'loroCursor'\n\n/**\n * A hex color: `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. It is the rule of `isHexColor` of\n * `@dovetail-ts/core`. This package does not depend on core, so it has its own copy.\n */\nconst HEX_COLOR = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\n\n/** The color of a caret when the color of the peer is not a hex color. */\nconst FALLBACK_COLOR = '#6b7280'\n\n/**\n * The caret of a peer, as `loro-prosemirror` draws it. The color and the name come from the\n * peer, so they are not trusted: the color must be a hex color, and the DOM properties take\n * the values, not a style string.\n */\nfunction caret(store: CursorEphemeralStore, peer: PeerID): HTMLElement {\n const user = store.getAll()[peer]?.user\n const color =\n typeof user?.color === 'string' && HEX_COLOR.test(user.color) ? user.color : FALLBACK_COLOR\n const element = document.createElement('span')\n element.classList.add('ProseMirror-loro-cursor')\n element.style.borderColor = color\n const label = document.createElement('div')\n label.style.backgroundColor = color\n label.textContent = user?.name ?? peer.slice(0, 6)\n // The word joiners keep the caret on the line of the text.\n element.append('\\u2060', label, '\\u2060')\n return element\n}\n\n/** The binding of `@dovetail-ts/crdt-loro` documents. */\nexport const loroBinding: EditorBinding = {\n engine: 'loro',\n\n extensions({ handle, field, user, cursors }) {\n const { doc, awareness } = loroHandle(handle)\n // The plugins take a document of the `doc` root map. The binding gives them the map `field`.\n const loroDoc = doc as unknown as LoroDocType\n const containerId = doc.getMap(field).id\n const store = new CursorEphemeralStore(doc.peerIdStr)\n const stops: (() => void)[] = []\n\n return [\n Extension.create({\n name: 'loroCollaboration',\n\n addProseMirrorPlugins() {\n // The undo of this user. It does not undo the threads and versions (`dovetail:` maps).\n const undoManager = new UndoManager(doc, { excludeOriginPrefixes: ['dovetail:'] })\n const plugins = [\n LoroSyncPlugin({ doc: loroDoc, containerId }),\n LoroUndoPlugin({ doc, undoManager }),\n ]\n if (cursors) {\n plugins.push(\n LoroEphemeralCursorPlugin(store, {\n user: { name: user.name, color: user.color },\n createCursor: peer => caret(store, peer),\n }),\n )\n }\n return plugins\n },\n\n addCommands() {\n return {\n // The Loro plugins dispatch the change, so Tiptap must not dispatch its transaction.\n undo:\n () =>\n ({ state, tr, dispatch }) => {\n tr.setMeta('preventDispatch', true)\n return undo(state, dispatch)\n },\n redo:\n () =>\n ({ state, tr, dispatch }) => {\n tr.setMeta('preventDispatch', true)\n return redo(state, dispatch)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-z': () => this.editor.commands.undo(),\n 'Shift-Mod-z': () => this.editor.commands.redo(),\n 'Mod-y': () => this.editor.commands.redo(),\n }\n },\n\n onCreate() {\n if (!cursors) return\n // Dovetail awareness carries JSON, so the carets go in it as the bytes of the store.\n awareness.setLocalStateField('user', { ...user })\n stops.push(\n store.subscribeLocalUpdates(bytes =>\n awareness.setLocalStateField(CURSOR_FIELD, [...bytes]),\n ),\n awareness.onChange(change => {\n if (change.local) return\n const states = awareness.getStates()\n for (const id of [...change.added, ...change.updated]) {\n const bytes = states.get(id)?.[CURSOR_FIELD]\n if (Array.isArray(bytes) && bytes.every(byte => typeof byte === 'number')) {\n store.apply(Uint8Array.from(bytes))\n }\n }\n }),\n )\n },\n\n onDestroy() {\n for (const stop of stops.splice(0)) stop()\n store.destroy()\n },\n }),\n ]\n },\n\n anchor(state, pos) {\n const sync = syncState(state)\n if (!sync) throw new Error('The editor has no Loro content yet.')\n const cursor = absolutePositionToCursor(state.doc, pos, sync.doc, sync.mapping)\n if (!cursor) throw new Error(`No Loro position for ${pos}.`)\n return [...cursor.encode()]\n },\n\n resolve(state, anchor) {\n const sync = syncState(state)\n if (!sync || !Array.isArray(anchor)) return null\n const bytes = Uint8Array.from(anchor.filter((byte): byte is number => typeof byte === 'number'))\n return cursorToAbsolutePosition(Cursor.decode(bytes), sync.doc, sync.mapping)\n },\n\n content(handle, field, schema) {\n const { doc } = loroHandle(handle)\n return createNodeFromLoroObj(\n schema,\n doc.getMap(field) as unknown as LoroNode,\n new Map(),\n ).toJSON()\n },\n\n isRemote(transaction) {\n const meta = transaction.getMeta(loroSyncPluginKey) as { type?: string } | undefined\n return meta?.type === 'non-local-updates' || meta?.type === 'update-state'\n },\n}\n\n// The two functions below come from `loro-prosemirror` 0.4.4 (`src/cursor/common.ts`, MIT\n// license). The package does not export them.\n\nfunction containerOf(mapping: LoroNodeMapping, node: Node): ContainerID | undefined {\n for (const [id, value] of mapping) if (value === node) return id\n return undefined\n}\n\nfunction absolutePositionToCursor(\n root: Node,\n pos: number,\n doc: LoroDoc,\n mapping: LoroNodeMapping,\n): Cursor | undefined {\n const resolved = root.resolve(pos)\n const id = containerOf(mapping, resolved.node(resolved.depth))\n if (!id) return undefined\n const children = (doc.getMap(id) as unknown as LoroNode).get(CHILDREN_KEY)\n if (children.length === 0) return children.getCursor(0)\n let index = resolved.parentOffset\n for (let childIndex = 0; index >= 0 && childIndex < children.length;) {\n const child = children.get(childIndex)\n childIndex += 1\n if (child instanceof LoroText) return child.getCursor(index)\n // An embed (an image or a rule) takes one position.\n if (index === 0 && childIndex < children.length) index += 1\n index -= 1\n }\n return undefined\n}\n\nfunction cursorToAbsolutePosition(\n cursor: Cursor,\n doc: LoroDoc,\n mapping: LoroNodeMapping,\n): number | null {\n const containerId = cursor.containerId()\n let index = -1\n let target: ContainerID\n let node: LoroNode | undefined\n if (containerId.endsWith('List')) {\n const list = doc.getContainerById(containerId)\n const parent = list instanceof LoroList ? list.parent() : undefined\n if (!parent) return null\n target = parent.id\n node = parent.parent()?.parent() as LoroNode | undefined\n index = 0\n } else {\n const position = doc.getCursorPos(cursor)\n if (!position) return null\n const text = doc.getText(containerId)\n index += position.offset\n target = text.id\n node = text.parent()?.parent() as LoroNode | undefined\n }\n while (node) {\n const children = node.get(CHILDREN_KEY)\n if (!(children instanceof LoroList)) return null\n for (const child of children.toArray() as LoroNode[]) {\n if (child.id === target) break\n const mapped = mapping.get(child.id)\n if (mapped === undefined) return null\n for (const each of Array.isArray(mapped) ? mapped : [mapped]) index += each.nodeSize\n }\n target = node.id\n node = node.parent()?.parent() as LoroNode | undefined\n index += 1\n }\n return index\n}\n"]}
|
package/dist/yjs.d.ts
ADDED
package/dist/yjs.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import Collaboration from '@tiptap/extension-collaboration';
|
|
2
|
+
import CollaborationCaret from '@tiptap/extension-collaboration-caret';
|
|
3
|
+
import { ySyncPluginKey, yXmlFragmentToProseMirrorRootNode, relativePositionToAbsolutePosition, absolutePositionToRelativePosition } from '@tiptap/y-tiptap';
|
|
4
|
+
import * as Y from 'yjs';
|
|
5
|
+
import { YjsDocHandle } from '@dovetail-ts/crdt-yjs';
|
|
6
|
+
|
|
7
|
+
// src/yjs.ts
|
|
8
|
+
function yjsHandle(handle) {
|
|
9
|
+
if (handle instanceof YjsDocHandle) return handle;
|
|
10
|
+
throw new Error(`The yjs binding needs a document of @dovetail-ts/crdt-yjs.`);
|
|
11
|
+
}
|
|
12
|
+
function syncState(state) {
|
|
13
|
+
const sync = ySyncPluginKey.getState(state);
|
|
14
|
+
return sync?.binding ? { doc: sync.doc, type: sync.type, mapping: sync.binding.mapping } : null;
|
|
15
|
+
}
|
|
16
|
+
var yjsBinding = {
|
|
17
|
+
engine: "yjs",
|
|
18
|
+
extensions({ handle, field, user, cursors }) {
|
|
19
|
+
const { doc, yAwareness } = yjsHandle(handle);
|
|
20
|
+
const extensions = [Collaboration.configure({ document: doc, field })];
|
|
21
|
+
if (cursors) {
|
|
22
|
+
extensions.push(
|
|
23
|
+
CollaborationCaret.configure({ provider: { awareness: yAwareness }, user: { ...user } })
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
return extensions;
|
|
27
|
+
},
|
|
28
|
+
anchor(state, pos) {
|
|
29
|
+
const sync = syncState(state);
|
|
30
|
+
if (!sync) throw new Error("The editor has no Yjs content yet.");
|
|
31
|
+
const { type, mapping } = sync;
|
|
32
|
+
return Y.relativePositionToJSON(absolutePositionToRelativePosition(pos, type, mapping));
|
|
33
|
+
},
|
|
34
|
+
resolve(state, anchor) {
|
|
35
|
+
const sync = syncState(state);
|
|
36
|
+
if (!sync) return null;
|
|
37
|
+
const { doc, type, mapping } = sync;
|
|
38
|
+
const position = Y.createRelativePositionFromJSON(anchor);
|
|
39
|
+
return relativePositionToAbsolutePosition(doc, type, position, mapping);
|
|
40
|
+
},
|
|
41
|
+
content(handle, field, schema) {
|
|
42
|
+
const fragment = yjsHandle(handle).doc.getXmlFragment(field);
|
|
43
|
+
return yXmlFragmentToProseMirrorRootNode(fragment, schema).toJSON();
|
|
44
|
+
},
|
|
45
|
+
isRemote(transaction) {
|
|
46
|
+
return transaction.getMeta(ySyncPluginKey)?.isChangeOrigin === true;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export { yjsBinding };
|
|
51
|
+
//# sourceMappingURL=yjs.js.map
|
|
52
|
+
//# sourceMappingURL=yjs.js.map
|
package/dist/yjs.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/yjs.ts"],"names":[],"mappings":";;;;;;;AAgBA,SAAS,UAAU,MAAA,EAAiC;AAClD,EAAA,IAAI,MAAA,YAAkB,cAAc,OAAO,MAAA;AAC3C,EAAA,MAAM,IAAI,MAAM,CAAA,0DAAA,CAA4D,CAAA;AAC9E;AAGA,SAAS,UAAU,KAAA,EAAoB;AACrC,EAAA,MAAM,IAAA,GAAO,cAAA,CAAe,QAAA,CAAS,KAAK,CAAA;AAC1C,EAAA,OAAO,IAAA,EAAM,OAAA,GAAU,EAAE,GAAA,EAAK,IAAA,CAAK,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,OAAA,EAAS,IAAA,CAAK,OAAA,CAAQ,SAAQ,GAAI,IAAA;AAC7F;AAGO,IAAM,UAAA,GAA4B;AAAA,EACvC,MAAA,EAAQ,KAAA;AAAA,EAER,WAAW,EAAE,MAAA,EAAQ,KAAA,EAAO,IAAA,EAAM,SAAQ,EAAG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,SAAA,CAAU,MAAM,CAAA,CAAE,GAAA,CAAI,eAAe,KAAK,CAAA;AAC3D,IAAA,OAAO,iCAAA,CAAkC,QAAA,EAAU,MAAM,CAAA,CAAE,MAAA,EAAO;AAAA,EACpE,CAAA;AAAA,EAEA,SAAS,WAAA,EAAa;AACpB,IAAA,OAAO,WAAA,CAAY,OAAA,CAAQ,cAAc,CAAA,EAAG,cAAA,KAAmB,IAAA;AAAA,EACjE;AACF","file":"yjs.js","sourcesContent":["// The Yjs binding. It uses the Tiptap extensions on `@tiptap/y-tiptap` (ADR 0013).\nimport type { AnyExtension } from '@tiptap/core'\nimport Collaboration from '@tiptap/extension-collaboration'\nimport CollaborationCaret from '@tiptap/extension-collaboration-caret'\nimport type { EditorState } from '@tiptap/pm/state'\nimport {\n absolutePositionToRelativePosition,\n relativePositionToAbsolutePosition,\n yXmlFragmentToProseMirrorRootNode,\n ySyncPluginKey,\n} from '@tiptap/y-tiptap'\nimport * as Y from 'yjs'\nimport { YjsDocHandle } from '@dovetail-ts/crdt-yjs'\nimport type { DocHandle } from '@dovetail-ts/crdt'\nimport type { EditorBinding } from './binding'\n\nfunction yjsHandle(handle: DocHandle): YjsDocHandle {\n if (handle instanceof YjsDocHandle) return handle\n throw new Error(`The yjs binding needs a document of @dovetail-ts/crdt-yjs.`)\n}\n\n/** The Yjs state of the editor, or null before the first render. */\nfunction syncState(state: EditorState) {\n const sync = ySyncPluginKey.getState(state)\n return sync?.binding ? { doc: sync.doc, type: sync.type, mapping: sync.binding.mapping } : null\n}\n\n/** The binding of `@dovetail-ts/crdt-yjs` documents. */\nexport const yjsBinding: EditorBinding = {\n engine: 'yjs',\n\n extensions({ handle, field, user, cursors }) {\n const { doc, yAwareness } = yjsHandle(handle)\n const extensions: AnyExtension[] = [Collaboration.configure({ document: doc, field })]\n if (cursors) {\n extensions.push(\n CollaborationCaret.configure({ provider: { awareness: yAwareness }, user: { ...user } }),\n )\n }\n return extensions\n },\n\n anchor(state, pos) {\n const sync = syncState(state)\n if (!sync) throw new Error('The editor has no Yjs content yet.')\n const { type, mapping } = sync\n return Y.relativePositionToJSON(absolutePositionToRelativePosition(pos, type, mapping))\n },\n\n resolve(state, anchor) {\n const sync = syncState(state)\n if (!sync) return null\n const { doc, type, mapping } = sync\n const position = Y.createRelativePositionFromJSON(anchor)\n return relativePositionToAbsolutePosition(doc, type, position, mapping)\n },\n\n content(handle, field, schema) {\n const fragment = yjsHandle(handle).doc.getXmlFragment(field)\n return yXmlFragmentToProseMirrorRootNode(fragment, schema).toJSON()\n },\n\n isRemote(transaction) {\n return transaction.getMeta(ySyncPluginKey)?.isChangeOrigin === true\n },\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,109 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dovetail-ts/tiptap",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Collaboration, cursors, per-user undo, history and comments for Tiptap 3.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Joe Gaudet <joe@joegaudet.com>",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/joegaudet/dovetail.git",
|
|
10
|
+
"directory": "packages/tiptap"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://joegaudet.com/dovetail/",
|
|
13
|
+
"bugs": "https://github.com/joegaudet/dovetail/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"realtime",
|
|
16
|
+
"offline",
|
|
17
|
+
"sync",
|
|
18
|
+
"crdt"
|
|
19
|
+
],
|
|
20
|
+
"type": "module",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./yjs": {
|
|
28
|
+
"types": "./dist/yjs.d.ts",
|
|
29
|
+
"default": "./dist/yjs.js"
|
|
30
|
+
},
|
|
31
|
+
"./loro": {
|
|
32
|
+
"types": "./dist/loro.d.ts",
|
|
33
|
+
"default": "./dist/loro.js"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"CHANGELOG.md",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"sideEffects": false,
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@dovetail-ts/crdt": "1.0.0"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@dovetail-ts/crdt-loro": "1.0.0",
|
|
49
|
+
"@dovetail-ts/crdt-yjs": "1.0.0",
|
|
50
|
+
"@tiptap/core": "^3.0.0",
|
|
51
|
+
"@tiptap/extension-collaboration": "^3.35.1",
|
|
52
|
+
"@tiptap/extension-collaboration-caret": "^3.35.1",
|
|
53
|
+
"@tiptap/pm": "^3.0.0",
|
|
54
|
+
"@tiptap/y-tiptap": "^3.3.1",
|
|
55
|
+
"loro-crdt": "^1.19.1",
|
|
56
|
+
"loro-prosemirror": "^0.4.4",
|
|
57
|
+
"yjs": "^13.6.33"
|
|
58
|
+
},
|
|
59
|
+
"peerDependenciesMeta": {
|
|
60
|
+
"@dovetail-ts/crdt-loro": {
|
|
61
|
+
"optional": true
|
|
62
|
+
},
|
|
63
|
+
"@dovetail-ts/crdt-yjs": {
|
|
64
|
+
"optional": true
|
|
65
|
+
},
|
|
66
|
+
"@tiptap/extension-collaboration": {
|
|
67
|
+
"optional": true
|
|
68
|
+
},
|
|
69
|
+
"@tiptap/extension-collaboration-caret": {
|
|
70
|
+
"optional": true
|
|
71
|
+
},
|
|
72
|
+
"@tiptap/y-tiptap": {
|
|
73
|
+
"optional": true
|
|
74
|
+
},
|
|
75
|
+
"loro-crdt": {
|
|
76
|
+
"optional": true
|
|
77
|
+
},
|
|
78
|
+
"loro-prosemirror": {
|
|
79
|
+
"optional": true
|
|
80
|
+
},
|
|
81
|
+
"yjs": {
|
|
82
|
+
"optional": true
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"devDependencies": {
|
|
86
|
+
"@dovetail-ts/crdt-automerge": "1.0.0",
|
|
87
|
+
"@dovetail-ts/crdt-loro": "1.0.0",
|
|
88
|
+
"@dovetail-ts/crdt-yjs": "1.0.0",
|
|
89
|
+
"@tiptap/core": "^3.35.1",
|
|
90
|
+
"@tiptap/extension-collaboration": "^3.35.1",
|
|
91
|
+
"@tiptap/extension-collaboration-caret": "^3.35.1",
|
|
92
|
+
"@tiptap/pm": "^3.35.1",
|
|
93
|
+
"@tiptap/starter-kit": "^3.35.1",
|
|
94
|
+
"@tiptap/y-tiptap": "^3.3.1",
|
|
95
|
+
"loro-crdt": "^1.19.1",
|
|
96
|
+
"loro-prosemirror": "^0.4.4",
|
|
97
|
+
"tsup": "^8.5.1",
|
|
98
|
+
"yjs": "^13.6.33"
|
|
99
|
+
},
|
|
100
|
+
"publishConfig": {
|
|
101
|
+
"access": "public"
|
|
102
|
+
},
|
|
103
|
+
"engines": {
|
|
104
|
+
"node": ">=22.12.0"
|
|
105
|
+
},
|
|
106
|
+
"scripts": {
|
|
107
|
+
"build": "tsc --build --force && tsup"
|
|
108
|
+
}
|
|
6
109
|
}
|