@ebbjs/codemirror 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.txt ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # `@ebbjs/codemirror`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CodeMirror 6 bridge for [`@ebbjs/client`](https://github.com/ebbjs/ebbjs/tree/main/packages/client)'s `TextDocument`. Wires a CM6 editor view to a causal-tree document so that:
4
+
5
+ - Local CM edits become `doc.localInsert` / `doc.localExtend` / `doc.localDelete` calls.
6
+ - Remote updates (catch-up / SSE) flow into CM as text changes.
7
+
8
+ A CM `StateField` mirrors `doc.docState.index.spans`, so consumers (presence, cursor anchoring, etc.) can map CM positions to run ids.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @ebbjs/codemirror
14
+ npm install @codemirror/state @codemirror/view codemirror # peers
15
+ ```
16
+
17
+ Node `>=22.8.0`. `@ebbjs/client` is a normal dependency and installs with it.
18
+
19
+ ```ts
20
+ import { createBridgeExtension, mountEditorBridge } from "@ebbjs/codemirror";
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```ts
26
+ import { EditorState } from "@codemirror/state";
27
+ import { EditorView, keymap, lineNumbers } from "@codemirror/view";
28
+ import { defaultKeymap } from "@codemirror/commands";
29
+ import { createClient } from "@ebbjs/client";
30
+ import { createBridgeExtension, createIdMapField, mountEditorBridge } from "@ebbjs/codemirror";
31
+
32
+ const client = createClient({ serverUrl: "http://localhost:4000", actorId: "alice" });
33
+ const doc = client.textDocument("doc_demo");
34
+ const idMapField = createIdMapField();
35
+
36
+ // Capture the view via a closure so the bridge can read it inside
37
+ // the CM updateListener (the listener fires synchronously inside
38
+ // `view.dispatch`).
39
+ const viewRef = { current: null as EditorView | null };
40
+ const bridgeExtension = createBridgeExtension({
41
+ doc,
42
+ idMapField,
43
+ getView: () => viewRef.current,
44
+ });
45
+
46
+ const view = new EditorView({
47
+ state: EditorState.create({
48
+ doc: "",
49
+ extensions: [lineNumbers(), keymap.of(defaultKeymap), bridgeExtension],
50
+ }),
51
+ parent: container,
52
+ });
53
+ viewRef.current = view;
54
+
55
+ const bridge = mountEditorBridge(view, doc, idMapField);
56
+ // later: bridge.detach(); view.destroy();
57
+ ```
58
+
59
+ ## API
60
+
61
+ | Export | What |
62
+ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------ |
63
+ | `createBridgeExtension({ doc, idMapField, getView })` | CM6 Extension that listens for local edits and dispatches `doc.local*` calls. |
64
+ | `mountEditorBridge(view, doc, idMapField)` | Subscribes to `doc.onUpdate` and applies remote updates to the view. Returns `{ detach }`. |
65
+ | `createIdMapField()` | The `StateField` mirroring `doc.docState.index.spans`. |
66
+ | `setIdMapEffect` | The `StateEffect` that replaces the field's value (re-exported for advanced use). |
67
+ | `isRemote` | The `Annotation` marking a CM transaction as originating from the bridge. |
68
+ | `getRunAtPosition(state, position, idMapField)` | Lookup helper: which run contains a document position? |
69
+ | `getPositionOfRun(state, runId, offset, idMapField)` | Inverse: what absolute position does a (runId, offset) pair map to? |
70
+ | `RunSpan` | The `{ runId, length }` shape exposed via the StateField. |
71
+
72
+ ## Peer dependencies
73
+
74
+ ```json
75
+ {
76
+ "@codemirror/state": "^6.5.0",
77
+ "@codemirror/view": "^6.30.0",
78
+ "codemirror": "^6.0.0"
79
+ }
80
+ ```
81
+
82
+ `@ebbjs/client` is a regular dependency.
83
+
84
+ ## How it works
85
+
86
+ The bridge uses a `isRemote` annotation to mark transactions it dispatches itself (e.g., pushing remote updates into CM). The local-CM→doc `updateListener` skips transactions with this annotation, breaking the recursive loop.
87
+
88
+ A second listener (subscribed via `doc.onUpdate`) computes the CM changes needed to reflect a remote update, then dispatches them in a single transaction along with the spans-update effect.
89
+
90
+ The local listener doesn't need to update the spans field — CM is the source of truth during a local edit, and the spans field is updated by the same dispatch that applies remote changes.
@@ -0,0 +1,154 @@
1
+ import * as _codemirror_state from '@codemirror/state';
2
+ import { StateField, Extension } from '@codemirror/state';
3
+ import { EditorView } from '@codemirror/view';
4
+ import { TextDocument, RunSpan, PresenceEntry } from '@ebbjs/client';
5
+ export { CursorPresence, PresenceEntry, ROOT_ID, RunSpan } from '@ebbjs/client';
6
+
7
+ /**
8
+ * Marks a CM transaction as originating from the bridge (i.e., a
9
+ * remote doc update being pushed into CM, not a user keystroke).
10
+ * The local-CM→doc listener skips transactions with this annotation
11
+ * to avoid recursive loops.
12
+ */
13
+ declare const isRemote: _codemirror_state.AnnotationType<boolean>;
14
+ /** Replace the spans StateField's value with a fresh array. */
15
+ declare const setIdMapEffect: _codemirror_state.StateEffectType<readonly RunSpan[]>;
16
+ /**
17
+ * Zero-length span at the document root. The CM-side `idMapField`
18
+ * always carries this so empty-doc clicks resolve to `(ROOT_ID, 0)`
19
+ * for presence anchoring. The doc tree's `PositionIndex.spans` never
20
+ * contains this — it lives only in the CM mirror.
21
+ */
22
+ declare const ROOT_PLACEHOLDER_SPAN: RunSpan;
23
+ /** Ensure the spans array carries the ROOT placeholder so the CM mirror never goes empty. */
24
+ declare const ensureRootSpan: (spans: readonly RunSpan[]) => readonly RunSpan[];
25
+ /**
26
+ * CM StateField mirroring `doc.docState.index.spans`. Always carries
27
+ * at least the ROOT placeholder so empty-doc clicks resolve to
28
+ * `(ROOT_ID, 0)`.
29
+ */
30
+ declare const createIdMapField: () => StateField<readonly RunSpan[]>;
31
+ /**
32
+ * Find the run that contains a given document position, using the
33
+ * StateField. Returns `{ runId, offset, spanIndex }` or undefined.
34
+ *
35
+ * CodeMirror positions are in `[0, doc.length]` inclusive, so a
36
+ * position equal to the sum of all spans' lengths is still inside
37
+ * the last run.
38
+ */
39
+ declare const getRunAtPosition: (state: {
40
+ field: <T>(f: StateField<T>) => T;
41
+ }, position: number, idMapField: StateField<readonly RunSpan[]>) => {
42
+ runId: string;
43
+ offset: number;
44
+ spanIndex: number;
45
+ } | undefined;
46
+ /**
47
+ * Compute the document position of a given (runId, offsetWithinRun).
48
+ * Returns undefined if the run is not visible in the current spans.
49
+ *
50
+ * `offset` may equal `span.length` — that's the position immediately
51
+ * past the last character of the run, a legitimate cursor position.
52
+ */
53
+ declare const getPositionOfRun: (state: {
54
+ field: <T>(f: StateField<T>) => T;
55
+ }, runId: string, offset: number, idMapField: StateField<readonly RunSpan[]>) => number | undefined;
56
+ /**
57
+ * Shared mutable state between the bridge extension (which sets the
58
+ * flag during a local edit) and `mountEditorBridge` (which reads it
59
+ * to skip applying cmChanges for events raised during a local edit).
60
+ *
61
+ * Lives in a plain object so the reference is stable across the
62
+ * two closures — both `createBridgeExtension` and `mountEditorBridge`
63
+ * receive the same object.
64
+ */
65
+ interface LocalEditTracker {
66
+ /** Set to true while inside a local-CM→doc transaction. */
67
+ active: boolean;
68
+ }
69
+ /** Options for {@link createBridgeExtension}. */
70
+ interface BridgeExtensionConfig {
71
+ readonly doc: TextDocument;
72
+ readonly idMapField: StateField<readonly RunSpan[]>;
73
+ /**
74
+ * Returns the current EditorView. The bridge captures this lazily
75
+ * via a closure so the caller can set the view after constructing
76
+ * the EditorState.
77
+ */
78
+ readonly getView: () => EditorView | null;
79
+ /**
80
+ * Shared tracker that the bridge flips on/off around local-CM→doc
81
+ * dispatches. `mountEditorBridge` reads it to skip applying
82
+ * cmChanges for events raised during a local edit. Optional — if
83
+ * omitted, the bridge assumes all doc updates are remote.
84
+ */
85
+ readonly localEdit?: LocalEditTracker;
86
+ }
87
+ /**
88
+ * Create the CM6 Extension that pipes local edits to the document.
89
+ *
90
+ * The extension bundles `idMapField` plus an `updateListener` that
91
+ * intercepts non-remote transactions and dispatches the corresponding
92
+ * `doc.local*` calls. Remote transactions are skipped.
93
+ */
94
+ declare const createBridgeExtension: (config: BridgeExtensionConfig) => Extension;
95
+ /** A handle returned by {@link mountEditorBridge} for tearing down. */
96
+ interface EditorBridge {
97
+ /** Stop listening to doc updates. */
98
+ detach: () => void;
99
+ }
100
+ /**
101
+ * Wire the document's `onUpdate` stream to the given CM view. After
102
+ * calling this, remote updates (catch-up / SSE) flowing through the
103
+ * TextDocument will be applied to the editor.
104
+ *
105
+ * The CM view must already have been created with
106
+ * {@link createBridgeExtension} in its extensions list.
107
+ *
108
+ * If `doc.text` differs from the view's current text (e.g., the
109
+ * document was populated before the bridge was attached, via catch-up),
110
+ * the initial state is synced via a remote-annotated dispatch.
111
+ */
112
+ declare function mountEditorBridge(view: EditorView, doc: TextDocument, idMapField: StateField<readonly RunSpan[]>, localEdit?: LocalEditTracker): EditorBridge;
113
+
114
+ /**
115
+ * CodeMirror 6 ViewPlugin that renders remote peers' cursors and
116
+ * selections as decorations.
117
+ *
118
+ * Reads from a `PresenceManager` (transport lives in
119
+ * `@ebbjs/client/src/presence/presence`). Run IDs are stable across
120
+ * edits so we resolve them to current document positions via the
121
+ * bridge's `idMapField` (a StateField that mirrors the causal tree's
122
+ * span index). If a run was deleted or split in a way the receiver
123
+ * can't resolve, the position falls back to undefined and we skip
124
+ * rendering for that peer.
125
+ *
126
+ * The plugin rebuilds decorations on every CM update. For a prototype
127
+ * with a handful of peers, this is O(peers × spans) per update and
128
+ * fine. For more peers, batching + dirty checking would be the
129
+ * next move.
130
+ */
131
+
132
+ interface PresenceDecorationConfig {
133
+ /**
134
+ * Called to get the current presence entries for this entity.
135
+ * Returns a fresh map each call; the ViewPlugin caches results
136
+ * between CM updates.
137
+ */
138
+ readonly getPresence: () => ReadonlyMap<string, PresenceEntry>;
139
+ /** Called to look up a run's current document position. */
140
+ readonly getPositionOfRun: (runId: string, offset: number) => number | undefined;
141
+ /** Called to map a document position back to (runId, offset). */
142
+ readonly getRunAtPosition: (position: number) => {
143
+ runId: string;
144
+ offset: number;
145
+ } | undefined;
146
+ }
147
+ /**
148
+ * Build a CM6 Extension (ViewPlugin) that renders presence as
149
+ * decorations. Decorations rebuild on every CM update.
150
+ */
151
+ declare function createPresenceExtension(config: PresenceDecorationConfig): Extension;
152
+
153
+ export { ROOT_PLACEHOLDER_SPAN, createBridgeExtension, createIdMapField, createPresenceExtension, ensureRootSpan, getPositionOfRun, getRunAtPosition, isRemote, mountEditorBridge, setIdMapEffect };
154
+ export type { BridgeExtensionConfig, EditorBridge, LocalEditTracker, PresenceDecorationConfig };
package/dist/index.js ADDED
@@ -0,0 +1,274 @@
1
+ import { Annotation as B, StateEffect as V, StateField as W } from "@codemirror/state";
2
+ import { EditorView as $, ViewPlugin as H, Decoration as I, WidgetType as K } from "@codemirror/view";
3
+ import { ROOT_ID as U } from "@ebbjs/client";
4
+ import { ROOT_ID as st } from "@ebbjs/client";
5
+ const x = B.define(), b = V.define(), v = { runId: U, length: 0 }, S = (o) => o.length === 0 ? [v] : o, X = () => W.define({
6
+ create: () => [v],
7
+ update: (o, t) => {
8
+ for (const e of t.effects)
9
+ if (e.is(b))
10
+ return S(e.value);
11
+ return o;
12
+ }
13
+ }), Y = (o, t, e) => {
14
+ const r = o.field(e);
15
+ let a = 0;
16
+ for (let s = 0; s < r.length; s++) {
17
+ const n = r[s];
18
+ if (t <= a + n.length)
19
+ return { runId: n.runId, offset: t - a, spanIndex: s };
20
+ a += n.length;
21
+ }
22
+ }, Z = (o, t, e, r) => {
23
+ const a = o.field(r);
24
+ let s = 0;
25
+ for (const n of a) {
26
+ if (n.runId === t)
27
+ return e > n.length ? void 0 : s + e;
28
+ s += n.length;
29
+ }
30
+ }, tt = (o) => [
31
+ o.idMapField,
32
+ $.updateListener.of((t) => {
33
+ const e = o.getView();
34
+ if (!e || !t.docChanged) return;
35
+ const r = t.transactions.find((l) => l.docChanged && !l.annotation(x));
36
+ if (!r) return;
37
+ const { idMapField: a, doc: s, localEdit: n } = o, c = e.state.field(a);
38
+ n && (n.active = !0);
39
+ try {
40
+ r.changes.iterChanges((l, i, d, g, O) => {
41
+ if (i > l) {
42
+ let h = l;
43
+ for (; h < i; ) {
44
+ const p = L(c, h);
45
+ if (!p) {
46
+ h += 1;
47
+ continue;
48
+ }
49
+ const F = p.spanLength - p.runOffset, N = i - h, E = Math.min(F, N);
50
+ s.localDelete({
51
+ runId: p.runId,
52
+ offset: p.runOffset,
53
+ count: E
54
+ }), h += E;
55
+ }
56
+ }
57
+ const f = O.toString();
58
+ if (f.length === 0) return;
59
+ if (l === 0) {
60
+ s.localInsert(f, { afterRun: "ROOT" });
61
+ return;
62
+ }
63
+ const m = L(c, l - 1);
64
+ if (!m) {
65
+ s.localInsert(f, { afterRun: "ROOT" });
66
+ return;
67
+ }
68
+ const u = s.docState.nodes.get(m.runId);
69
+ if (!u || u.deleted) {
70
+ s.localInsert(f, { afterRun: "ROOT" });
71
+ return;
72
+ }
73
+ const P = m.runOffset === u.text.length - 1, k = u.actorId === s.actorId, A = !u.deleted, _ = (s.docState.children.get(u.id) ?? []).length === 0;
74
+ if (P && k && A && _) {
75
+ s.localExtend({
76
+ runId: u.id,
77
+ appendText: f
78
+ });
79
+ return;
80
+ }
81
+ let y;
82
+ P || (y = m.runOffset + 1), s.localInsert(f, {
83
+ afterRun: u.id,
84
+ ...y !== void 0 && { splitParentAt: y }
85
+ });
86
+ });
87
+ } finally {
88
+ n && (n.active = !1);
89
+ }
90
+ })
91
+ ];
92
+ function et(o, t, e, r) {
93
+ const a = t.text, s = S(D(t.docState.index.spans));
94
+ o.state.doc.toString() !== a ? o.dispatch({
95
+ changes: { from: 0, to: o.state.doc.length, insert: a },
96
+ effects: b.of(s),
97
+ annotations: x.of(!0)
98
+ }) : o.dispatch({
99
+ effects: b.of(s),
100
+ annotations: x.of(!0)
101
+ });
102
+ const n = t.onUpdate((c) => {
103
+ c && q(o, t, e, c, r);
104
+ });
105
+ return {
106
+ detach: () => {
107
+ n();
108
+ }
109
+ };
110
+ }
111
+ function q(o, t, e, r, a) {
112
+ const s = o.state.field(e), n = t.docState.nodes.get(r.runId), c = !!a?.active;
113
+ let l = [];
114
+ if (r.kind === "tombstone") {
115
+ const i = R(s, r.runId);
116
+ i && !c && (l = [{ from: i.start, to: i.end }]);
117
+ } else if (r.kind === "extend") {
118
+ const i = R(s, r.runId);
119
+ i && n && !n.deleted && !c && (l = [{ from: i.start, to: i.end, insert: n.text }]);
120
+ } else if (r.kind === "insert" && n && !n.deleted && !c) {
121
+ const i = R(s, n.parentId);
122
+ l = [{ from: i ? i.end : 0, insert: n.text }];
123
+ }
124
+ o.dispatch({
125
+ changes: l,
126
+ effects: b.of(S(D(t.docState.index.spans))),
127
+ annotations: x.of(!0)
128
+ });
129
+ }
130
+ function L(o, t) {
131
+ let e = 0;
132
+ for (let r = 0; r < o.length; r++) {
133
+ const a = o[r];
134
+ if (t < e + a.length)
135
+ return {
136
+ runId: a.runId,
137
+ runOffset: t - e,
138
+ spanIndex: r,
139
+ spanLength: a.length
140
+ };
141
+ e += a.length;
142
+ }
143
+ }
144
+ function R(o, t) {
145
+ let e = 0;
146
+ for (const r of o) {
147
+ if (r.runId === t)
148
+ return { start: e, end: e + r.length };
149
+ e += r.length;
150
+ }
151
+ }
152
+ function D(o) {
153
+ return o.map((t) => ({ runId: t.runId, length: t.length }));
154
+ }
155
+ class T extends K {
156
+ constructor(t, e) {
157
+ super(), this.color = t, this.label = e;
158
+ }
159
+ toDOM() {
160
+ const t = document.createElement("span");
161
+ t.className = "cm-remote-cursor", t.style.borderLeft = `2px solid ${this.color}`, t.style.height = "1.2em", t.style.display = "inline-block", t.style.width = "0", t.style.verticalAlign = "text-bottom", t.style.position = "relative", t.style.marginLeft = "-1px", t.style.marginRight = "-1px", t.setAttribute("aria-label", `${this.label}'s cursor`);
162
+ const e = document.createElement("span");
163
+ return e.className = "cm-remote-cursor-label", e.textContent = this.label, e.style.position = "absolute", e.style.bottom = "calc(100% + 1px)", e.style.left = "-1px", e.style.padding = "1px 4px", e.style.fontSize = "10px", e.style.lineHeight = "1.2", e.style.backgroundColor = this.color, e.style.color = "white", e.style.borderRadius = "2px", e.style.whiteSpace = "nowrap", e.style.pointerEvents = "none", t.appendChild(e), t;
164
+ }
165
+ eq(t) {
166
+ return this.color === t.color && this.label === t.label;
167
+ }
168
+ ignoreEvent() {
169
+ return !0;
170
+ }
171
+ }
172
+ function nt(o) {
173
+ return H.fromClass(
174
+ class {
175
+ decorations;
176
+ constructor(t) {
177
+ this.decorations = C(t.state, o);
178
+ }
179
+ update(t) {
180
+ this.decorations = C(t.state, o);
181
+ }
182
+ },
183
+ {
184
+ decorations: (t) => t.decorations
185
+ }
186
+ );
187
+ }
188
+ function C(o, t) {
189
+ const e = Array.from(t.getPresence().values()), r = o.doc.length, a = [];
190
+ for (const n of e) {
191
+ const c = t.getPositionOfRun(n.cursor.anchorId, n.cursor.anchorOffset), l = t.getPositionOfRun(n.cursor.headId, n.cursor.headOffset);
192
+ if (c === void 0 || l === void 0) continue;
193
+ const i = Math.min(Math.max(0, c), r), d = Math.min(Math.max(0, l), r), g = z(n.actorId);
194
+ if (i === d)
195
+ a.push({
196
+ from: d,
197
+ to: d,
198
+ dec: I.widget({
199
+ widget: new T(g, n.actorId),
200
+ side: 1
201
+ })
202
+ });
203
+ else {
204
+ const O = Math.min(i, d), f = Math.max(i, d);
205
+ a.push({
206
+ from: O,
207
+ to: f,
208
+ dec: I.mark({
209
+ class: "cm-remote-selection",
210
+ attributes: {
211
+ style: `background-color: ${g}33`
212
+ }
213
+ })
214
+ }), a.push({
215
+ from: d,
216
+ to: d,
217
+ dec: I.widget({
218
+ widget: new T(g, n.actorId),
219
+ side: 1
220
+ })
221
+ });
222
+ }
223
+ }
224
+ a.sort((n, c) => n.from - c.from || n.to - c.to);
225
+ const s = a.map(
226
+ (n) => n.from === n.to ? n.dec.range(n.from) : n.dec.range(n.from, n.to)
227
+ );
228
+ return I.set(s);
229
+ }
230
+ const M = {
231
+ drew: "#60a5fa",
232
+ // blue-400
233
+ alice: "#fbbf24",
234
+ // amber-400
235
+ sarah: "#a78bfa",
236
+ // violet-400
237
+ bob: "#34d399",
238
+ // emerald-400
239
+ charlie: "#f472b6"
240
+ // pink-400
241
+ }, w = [
242
+ "#ef4444",
243
+ // red-500
244
+ "#10b981",
245
+ // emerald-500
246
+ "#8b5cf6",
247
+ // violet-500
248
+ "#ec4899",
249
+ // pink-500
250
+ "#14b8a6",
251
+ // teal-500
252
+ "#f59e0b"
253
+ // amber-500
254
+ ];
255
+ function z(o) {
256
+ if (o in M) return M[o];
257
+ let t = 0;
258
+ for (let e = 0; e < o.length; e++)
259
+ t = t * 31 + o.charCodeAt(e) | 0;
260
+ return w[Math.abs(t) % w.length];
261
+ }
262
+ export {
263
+ st as ROOT_ID,
264
+ v as ROOT_PLACEHOLDER_SPAN,
265
+ tt as createBridgeExtension,
266
+ X as createIdMapField,
267
+ nt as createPresenceExtension,
268
+ S as ensureRootSpan,
269
+ Z as getPositionOfRun,
270
+ Y as getRunAtPosition,
271
+ x as isRemote,
272
+ et as mountEditorBridge,
273
+ b as setIdMapEffect
274
+ };
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@ebbjs/codemirror",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "description": "CodeMirror 6 bridge for @ebbjs/client's TextDocument — bidirectional sync between the causal-tree field and a CM6 editor view.",
6
+ "homepage": "https://ebbjs.com",
7
+ "bugs": {
8
+ "url": "https://github.com/ebbjs/ebbjs/issues"
9
+ },
10
+ "license": "Apache-2.0",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/ebbjs/ebbjs.git",
14
+ "directory": "packages/codemirror"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE.txt"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@ebbjs/client": "^0.1.1"
36
+ },
37
+ "devDependencies": {
38
+ "@codemirror/state": "^6.5.2",
39
+ "@codemirror/view": "^6.36.8",
40
+ "codemirror": "^6.0.1",
41
+ "happy-dom": "^17.4.4",
42
+ "tsx": "^4.20.4",
43
+ "vitest": "^3.2.4",
44
+ "@ebbjs/core": "^0.1.1"
45
+ },
46
+ "peerDependencies": {
47
+ "@codemirror/state": "^6.5.0",
48
+ "@codemirror/view": "^6.30.0",
49
+ "codemirror": "^6.0.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=22.8.0"
53
+ },
54
+ "scripts": {
55
+ "build": "vite build",
56
+ "dev": "vite build --watch",
57
+ "test": "vitest --run",
58
+ "test:watch": "vitest",
59
+ "typecheck": "tsc --noEmit",
60
+ "lint": "pnpm --root ../../ lint",
61
+ "lint:fix": "pnpm --root ../../ lint:fix",
62
+ "fmt": "pnpm --root ../../ fmt",
63
+ "fmt:check": "pnpm --root ../../ fmt:check"
64
+ }
6
65
  }