@dou-ui/code 0.0.0-stage → 0.1.0-alpha.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/LICENSE +21 -0
- package/README.md +10 -2
- package/dist/_virtual/_rolldown/runtime.js +12 -0
- package/dist/assets/default-BZBMZKf_.js.map +1 -0
- package/dist/code-diff.js +6 -0
- package/dist/code-diff.js.map +1 -0
- package/dist/code-diff.vue_vue_type_script_setup_true_lang.js +792 -0
- package/dist/code-diff.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/code-editor.js +6 -0
- package/dist/code-editor.js.map +1 -0
- package/dist/code-editor.vue_vue_type_script_setup_true_lang.js +4917 -0
- package/dist/code-editor.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/code-input.js +6 -0
- package/dist/code-input.js.map +1 -0
- package/dist/code-input.vue_vue_type_script_setup_true_lang.js +237 -0
- package/dist/code-input.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/code-keys.js +42 -0
- package/dist/code-keys.js.map +1 -0
- package/dist/code-keys.vue_vue_type_script_setup_true_lang.js +168 -0
- package/dist/code-keys.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/code-keys2.js +6 -0
- package/dist/code-keys2.js.map +1 -0
- package/dist/collaboration/index.js +255 -0
- package/dist/collaboration/index.js.map +1 -0
- package/dist/completion/match.js +55 -0
- package/dist/completion/match.js.map +1 -0
- package/dist/completion/snippet.js +71 -0
- package/dist/completion/snippet.js.map +1 -0
- package/dist/core/brackets.js +55 -0
- package/dist/core/brackets.js.map +1 -0
- package/dist/core/changes.js +185 -0
- package/dist/core/changes.js.map +1 -0
- package/dist/core/chars.js +130 -0
- package/dist/core/chars.js.map +1 -0
- package/dist/core/commands.js +910 -0
- package/dist/core/commands.js.map +1 -0
- package/dist/core/diff.js +215 -0
- package/dist/core/diff.js.map +1 -0
- package/dist/core/folding.js +87 -0
- package/dist/core/folding.js.map +1 -0
- package/dist/core/history.js +74 -0
- package/dist/core/history.js.map +1 -0
- package/dist/core/keymap.js +326 -0
- package/dist/core/keymap.js.map +1 -0
- package/dist/core/search.js +91 -0
- package/dist/core/search.js.map +1 -0
- package/dist/core/selection.js +88 -0
- package/dist/core/selection.js.map +1 -0
- package/dist/core/text.js +320 -0
- package/dist/core/text.js.map +1 -0
- package/dist/core/transaction.js +98 -0
- package/dist/core/transaction.js.map +1 -0
- package/dist/extension.js +16 -0
- package/dist/extension.js.map +1 -0
- package/dist/index.js +38 -0
- package/dist/index.js.map +1 -0
- package/dist/language/highlighter.js +336 -0
- package/dist/language/highlighter.js.map +1 -0
- package/dist/language/language.js +138 -0
- package/dist/language/language.js.map +1 -0
- package/dist/language/stream.js +112 -0
- package/dist/language/stream.js.map +1 -0
- package/dist/language/to-html.js +36 -0
- package/dist/language/to-html.js.map +1 -0
- package/dist/language/worker-client.js +198 -0
- package/dist/language/worker-client.js.map +1 -0
- package/dist/language/worker-protocol.js +48 -0
- package/dist/language/worker-protocol.js.map +1 -0
- package/dist/languages/css.js +128 -0
- package/dist/languages/css.js.map +1 -0
- package/dist/languages/html.js +175 -0
- package/dist/languages/html.js.map +1 -0
- package/dist/languages/javascript.js +300 -0
- package/dist/languages/javascript.js.map +1 -0
- package/dist/languages/json.js +45 -0
- package/dist/languages/json.js.map +1 -0
- package/dist/languages/markdown.js +82 -0
- package/dist/languages/markdown.js.map +1 -0
- package/dist/languages/python.js +88 -0
- package/dist/languages/python.js.map +1 -0
- package/dist/languages/shell.js +153 -0
- package/dist/languages/shell.js.map +1 -0
- package/dist/languages/sql.js +91 -0
- package/dist/languages/sql.js.map +1 -0
- package/dist/languages/yaml.js +85 -0
- package/dist/languages/yaml.js.map +1 -0
- package/dist/locale.js +164 -0
- package/dist/locale.js.map +1 -0
- package/dist/lsp/index.js +715 -0
- package/dist/lsp/index.js.map +1 -0
- package/dist/lsp/markup.js +139 -0
- package/dist/lsp/markup.js.map +1 -0
- package/dist/render-part.js +14 -0
- package/dist/render-part.js.map +1 -0
- package/dist/shiki/index.js +140 -0
- package/dist/shiki/index.js.map +1 -0
- package/dist/style.css +1 -0
- package/dist/style.d.ts +1 -0
- package/dist/style.js +4 -0
- package/dist/types/code-diff.vue.d.ts +45 -0
- package/dist/types/code-editor.vue.d.ts +43 -0
- package/dist/types/code-input.vue.d.ts +32 -0
- package/dist/types/code-keys.d.ts +9 -0
- package/dist/types/code-keys.vue.d.ts +8 -0
- package/dist/types/collaboration/index.d.ts +36 -0
- package/dist/types/completion/match.d.ts +13 -0
- package/dist/types/completion/snippet.d.ts +17 -0
- package/dist/types/core/brackets.d.ts +15 -0
- package/dist/types/core/changes.d.ts +52 -0
- package/dist/types/core/chars.d.ts +24 -0
- package/dist/types/core/commands.d.ts +199 -0
- package/dist/types/core/diff.d.ts +52 -0
- package/dist/types/core/folding.d.ts +23 -0
- package/dist/types/core/history.d.ts +24 -0
- package/dist/types/core/keymap.d.ts +29 -0
- package/dist/types/core/search.d.ts +37 -0
- package/dist/types/core/selection.d.ts +28 -0
- package/dist/types/core/text.d.ts +79 -0
- package/dist/types/core/transaction.d.ts +65 -0
- package/dist/types/extension.d.ts +321 -0
- package/dist/types/index.d.ts +159 -0
- package/dist/types/language/highlighter.d.ts +99 -0
- package/dist/types/language/language.d.ts +100 -0
- package/dist/types/language/stream.d.ts +56 -0
- package/dist/types/language/to-html.d.ts +17 -0
- package/dist/types/language/worker-client.d.ts +52 -0
- package/dist/types/language/worker-protocol.d.ts +50 -0
- package/dist/types/languages/css.d.ts +17 -0
- package/dist/types/languages/html.d.ts +34 -0
- package/dist/types/languages/javascript.d.ts +29 -0
- package/dist/types/languages/json.d.ts +7 -0
- package/dist/types/languages/markdown.d.ts +17 -0
- package/dist/types/languages/python.d.ts +9 -0
- package/dist/types/languages/shell.d.ts +11 -0
- package/dist/types/languages/sql.d.ts +9 -0
- package/dist/types/languages/yaml.d.ts +14 -0
- package/dist/types/locale.d.ts +79 -0
- package/dist/types/lsp/index.d.ts +119 -0
- package/dist/types/lsp/markup.d.ts +14 -0
- package/dist/types/render-part.d.ts +14 -0
- package/dist/types/shiki/index.d.ts +63 -0
- package/dist/types/types.d.ts +267 -0
- package/dist/types/view/input.d.ts +12 -0
- package/dist/types/view/layout.d.ts +55 -0
- package/dist/types/view/measure.d.ts +22 -0
- package/dist/types/worker/default.d.ts +1 -0
- package/dist/types/worker/index.d.ts +34 -0
- package/dist/view/input.js +27 -0
- package/dist/view/input.js.map +1 -0
- package/dist/view/layout.js +194 -0
- package/dist/view/layout.js.map +1 -0
- package/dist/view/measure.js +104 -0
- package/dist/view/measure.js.map +1 -0
- package/dist/worker/default.js +20 -0
- package/dist/worker/default.js.map +1 -0
- package/dist/worker/index.js +139 -0
- package/dist/worker/index.js.map +1 -0
- package/package.json +88 -4
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { mainRange } from "../core/selection.js";
|
|
2
|
+
import { defineCodeExtension } from "../extension.js";
|
|
3
|
+
import { collaborationColors } from "dou-ui";
|
|
4
|
+
import { h, ref, shallowRef, watch } from "vue";
|
|
5
|
+
import * as Y from "yjs";
|
|
6
|
+
// src/collaboration/index.ts
|
|
7
|
+
/** Marks the steps this binding took from the shared text, so they aren't written back. */
|
|
8
|
+
var FROM_SHARED = "collaboration";
|
|
9
|
+
var warnedBreaks = false;
|
|
10
|
+
/** The editor keeps `\n` only; a `\r` from another client would put every position after it off by one. */
|
|
11
|
+
function warnBreaks(insert) {
|
|
12
|
+
if (process.env.NODE_ENV === "production" || warnedBreaks || !insert.includes("\r")) return;
|
|
13
|
+
warnedBreaks = true;
|
|
14
|
+
console.warn("[@dou-ui/code] the shared text has a \"\\r\": the editor only keeps \"\\n\" line breaks, so positions after it no longer match. Write \"\\n\" only into the Y.Text.");
|
|
15
|
+
}
|
|
16
|
+
var warnedEmpty = false;
|
|
17
|
+
/** Filling the shared text from each editor would add one copy per person who opens it at the same time. */
|
|
18
|
+
function warnEmpty() {
|
|
19
|
+
if (process.env.NODE_ENV === "production" || warnedEmpty) return;
|
|
20
|
+
warnedEmpty = true;
|
|
21
|
+
console.warn("[@dou-ui/code] the shared text is empty, so the editor shows it empty, whatever v-model holds. Write the starting text into the Y.Text once, where the document is created.");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Edit together through a Yjs text. The text lives in `text`: the
|
|
25
|
+
* editor starts from it, whatever `v-model` holds, and `v-model` then
|
|
26
|
+
* mirrors it; a new `v-model` value is written into it as a change, to
|
|
27
|
+
* everyone. Undo only takes back this user's own changes.
|
|
28
|
+
*
|
|
29
|
+
* One extension per editor: two editors on the same text each need their own.
|
|
30
|
+
*/
|
|
31
|
+
function collaboration(options) {
|
|
32
|
+
const { text, awareness, user } = options;
|
|
33
|
+
const doc = text.doc;
|
|
34
|
+
if (!doc) throw new Error("[@dou-ui/code] collaboration() needs a Y.Text inside a Y.Doc");
|
|
35
|
+
if (awareness && user) {
|
|
36
|
+
const color = user.color ?? collaborationColors[doc.clientID % collaborationColors.length];
|
|
37
|
+
awareness.setLocalStateField("user", {
|
|
38
|
+
name: user.name,
|
|
39
|
+
color
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** The origin of this editor's own changes, which undo tracks. */
|
|
43
|
+
const origin = { name: "dou-code-collaboration" };
|
|
44
|
+
const undoManager = new Y.UndoManager(text, {
|
|
45
|
+
trackedOrigins: /* @__PURE__ */ new Set([origin]),
|
|
46
|
+
captureTimeout: 500
|
|
47
|
+
});
|
|
48
|
+
const tick = ref(0);
|
|
49
|
+
const bump = () => tick.value++;
|
|
50
|
+
undoManager.on("stack-item-added", bump);
|
|
51
|
+
undoManager.on("stack-item-popped", bump);
|
|
52
|
+
undoManager.on("stack-cleared", bump);
|
|
53
|
+
let context = null;
|
|
54
|
+
/** The selection before the change being written: undo puts the cursor back there. */
|
|
55
|
+
let before = null;
|
|
56
|
+
const relative = (index) => Y.createRelativePositionFromTypeIndex(text, index);
|
|
57
|
+
const absolute = (position) => {
|
|
58
|
+
const found = Y.createAbsolutePositionFromRelativePosition(position, doc);
|
|
59
|
+
return found && found.type === text ? found.index : null;
|
|
60
|
+
};
|
|
61
|
+
const keep = (selection) => ({
|
|
62
|
+
ranges: selection.ranges.map((range) => [relative(range.anchor), relative(range.head)]),
|
|
63
|
+
main: selection.main
|
|
64
|
+
});
|
|
65
|
+
undoManager.on("stack-item-added", (event) => {
|
|
66
|
+
if (!event.stackItem.meta.has("selection") && before) event.stackItem.meta.set("selection", keep(before));
|
|
67
|
+
});
|
|
68
|
+
undoManager.on("stack-item-popped", (event) => {
|
|
69
|
+
const kept = event.stackItem.meta.get("selection");
|
|
70
|
+
if (!context || !kept) return;
|
|
71
|
+
const ranges = [];
|
|
72
|
+
for (const [anchor, head] of kept.ranges) {
|
|
73
|
+
const a = absolute(anchor);
|
|
74
|
+
const b = absolute(head);
|
|
75
|
+
if (a !== null && b !== null) ranges.push({
|
|
76
|
+
anchor: a,
|
|
77
|
+
head: b
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (ranges.length) context.select({
|
|
81
|
+
ranges,
|
|
82
|
+
main: Math.min(kept.main, ranges.length - 1)
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
/** Someone else's change, or an undo: into the editor, kept out of its own undo. */
|
|
86
|
+
const observer = (event, transaction) => {
|
|
87
|
+
if (transaction.origin === origin || !context) return;
|
|
88
|
+
const specs = [];
|
|
89
|
+
let pos = 0;
|
|
90
|
+
for (const op of event.delta) if (op.retain) pos += op.retain;
|
|
91
|
+
else if (op.delete) {
|
|
92
|
+
specs.push({
|
|
93
|
+
from: pos,
|
|
94
|
+
to: pos + op.delete
|
|
95
|
+
});
|
|
96
|
+
pos += op.delete;
|
|
97
|
+
} else if (typeof op.insert === "string") {
|
|
98
|
+
warnBreaks(op.insert);
|
|
99
|
+
specs.push({
|
|
100
|
+
from: pos,
|
|
101
|
+
insert: op.insert
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (!specs.length) return;
|
|
105
|
+
const undo = transaction.origin === undoManager;
|
|
106
|
+
const action = undo ? undoManager.undoing ? "undo" : "redo" : "remote";
|
|
107
|
+
context.transact((tr) => {
|
|
108
|
+
for (const spec of specs) tr.replace(spec.from, spec.to ?? spec.from, spec.insert ?? "");
|
|
109
|
+
}, {
|
|
110
|
+
action,
|
|
111
|
+
history: false,
|
|
112
|
+
scroll: undo,
|
|
113
|
+
[FROM_SHARED]: true
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
const peers = shallowRef([]);
|
|
117
|
+
const readPeers = () => {
|
|
118
|
+
if (!awareness) return;
|
|
119
|
+
const out = [];
|
|
120
|
+
awareness.getStates().forEach((state, client) => {
|
|
121
|
+
if (client === awareness.clientID) return;
|
|
122
|
+
const shared = state.code;
|
|
123
|
+
const who = state.user;
|
|
124
|
+
if (!shared || !Array.isArray(shared.ranges)) return;
|
|
125
|
+
out.push({
|
|
126
|
+
client,
|
|
127
|
+
name: who?.name ?? "",
|
|
128
|
+
color: who?.color ?? collaborationColors[client % collaborationColors.length],
|
|
129
|
+
selection: shared
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
peers.value = out;
|
|
133
|
+
};
|
|
134
|
+
let shared = "";
|
|
135
|
+
const shareSelection = (selection) => {
|
|
136
|
+
if (!awareness) return;
|
|
137
|
+
const value = selection && {
|
|
138
|
+
ranges: selection.ranges.map((range) => ({
|
|
139
|
+
anchor: Y.relativePositionToJSON(relative(range.anchor)),
|
|
140
|
+
head: Y.relativePositionToJSON(relative(range.head))
|
|
141
|
+
})),
|
|
142
|
+
main: selection.main
|
|
143
|
+
};
|
|
144
|
+
const json = JSON.stringify(value);
|
|
145
|
+
if (json === shared) return;
|
|
146
|
+
shared = json;
|
|
147
|
+
awareness.setLocalStateField("code", value);
|
|
148
|
+
};
|
|
149
|
+
const resolve = (json) => {
|
|
150
|
+
try {
|
|
151
|
+
return absolute(Y.createRelativePositionFromJSON(json));
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const decorations = (ctx) => {
|
|
157
|
+
const length = ctx.doc.length;
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const peer of peers.value) {
|
|
160
|
+
const style = { "--dou-code-peer-color": peer.color };
|
|
161
|
+
peer.selection.ranges.forEach((range, i) => {
|
|
162
|
+
const anchor = resolve(range.anchor);
|
|
163
|
+
const head = resolve(range.head);
|
|
164
|
+
if (anchor === null || head === null || head > length || anchor > length) return;
|
|
165
|
+
if (anchor !== head) out.push({
|
|
166
|
+
type: "mark",
|
|
167
|
+
from: Math.min(anchor, head),
|
|
168
|
+
to: Math.max(anchor, head),
|
|
169
|
+
class: "dou-code-peer-selection",
|
|
170
|
+
style
|
|
171
|
+
});
|
|
172
|
+
const named = i === peer.selection.main;
|
|
173
|
+
const below = ctx.doc.lineAt(head).number === 1;
|
|
174
|
+
out.push({
|
|
175
|
+
type: "inline",
|
|
176
|
+
pos: head,
|
|
177
|
+
width: 0,
|
|
178
|
+
id: `peer-${peer.client}-${i}`,
|
|
179
|
+
render: () => h("span", {
|
|
180
|
+
key: JSON.stringify(range.head),
|
|
181
|
+
class: ["dou-code-peer", below && "is-below"],
|
|
182
|
+
style,
|
|
183
|
+
"aria-hidden": "true"
|
|
184
|
+
}, named && peer.name ? h("span", { class: "dou-code-peer__name" }, peer.name) : void 0)
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
};
|
|
190
|
+
const history = {
|
|
191
|
+
undo() {
|
|
192
|
+
if (!undoManager.undoStack.length) return false;
|
|
193
|
+
before = context?.selection ?? null;
|
|
194
|
+
undoManager.undo();
|
|
195
|
+
return true;
|
|
196
|
+
},
|
|
197
|
+
redo() {
|
|
198
|
+
if (!undoManager.redoStack.length) return false;
|
|
199
|
+
before = context?.selection ?? null;
|
|
200
|
+
undoManager.redo();
|
|
201
|
+
return true;
|
|
202
|
+
},
|
|
203
|
+
canUndo: () => (tick.value, undoManager.undoStack.length > 0),
|
|
204
|
+
canRedo: () => (tick.value, undoManager.redoStack.length > 0),
|
|
205
|
+
close: () => undoManager.stopCapturing()
|
|
206
|
+
};
|
|
207
|
+
return defineCodeExtension({
|
|
208
|
+
name: "collaboration",
|
|
209
|
+
setup(ctx) {
|
|
210
|
+
context = ctx;
|
|
211
|
+
const current = text.toString();
|
|
212
|
+
if (!current && ctx.doc.length) warnEmpty();
|
|
213
|
+
if (current !== ctx.doc.toString()) {
|
|
214
|
+
warnBreaks(current);
|
|
215
|
+
const head = Math.min(mainRange(ctx.selection).head, current.length);
|
|
216
|
+
ctx.transact((tr) => tr.replace(0, tr.doc.length, current).select(head), {
|
|
217
|
+
action: "remote",
|
|
218
|
+
history: false,
|
|
219
|
+
scroll: false,
|
|
220
|
+
[FROM_SHARED]: true
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
text.observe(observer);
|
|
224
|
+
awareness?.on("change", readPeers);
|
|
225
|
+
readPeers();
|
|
226
|
+
const stop = watch(() => ctx.focused, (focused) => shareSelection(focused ? ctx.selection : null), { immediate: true });
|
|
227
|
+
return () => {
|
|
228
|
+
stop();
|
|
229
|
+
text.unobserve(observer);
|
|
230
|
+
awareness?.off("change", readPeers);
|
|
231
|
+
shareSelection(null);
|
|
232
|
+
if (context === ctx) context = null;
|
|
233
|
+
};
|
|
234
|
+
},
|
|
235
|
+
update(result, ctx) {
|
|
236
|
+
if (!result.meta[FROM_SHARED] && !result.changes.empty) {
|
|
237
|
+
before = result.before.selection;
|
|
238
|
+
const list = result.changes.changes;
|
|
239
|
+
doc.transact(() => {
|
|
240
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
241
|
+
const change = list[i];
|
|
242
|
+
if (change.to > change.from) text.delete(change.from, change.to - change.from);
|
|
243
|
+
if (change.insert) text.insert(change.from, change.insert);
|
|
244
|
+
}
|
|
245
|
+
}, origin);
|
|
246
|
+
}
|
|
247
|
+
shareSelection(ctx.focused ? result.state.selection : null);
|
|
248
|
+
},
|
|
249
|
+
decorations: awareness ? decorations : void 0,
|
|
250
|
+
history: () => history
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
export { collaboration, collaborationColors };
|
|
254
|
+
|
|
255
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/collaboration/index.ts"],"sourcesContent":["import { collaborationColors } from 'dou-ui'\nimport { h, ref, shallowRef, watch } from 'vue'\nimport * as Y from 'yjs'\nimport type { CodeChangeSpec } from '../core/changes'\nimport { type CodeSelection, mainRange } from '../core/selection'\nimport type { CodeTransactionResult } from '../core/transaction'\nimport {\n type CodeDecoration,\n type CodeExtension,\n type CodeExtensionContext,\n type CodeHistoryHandler,\n defineCodeExtension,\n} from '../extension'\n\n/** What the editor needs of a Yjs awareness instance (`y-protocols/awareness`). */\nexport interface AwarenessLike {\n clientID: number\n getLocalState(): Record<string, unknown> | null\n setLocalStateField(field: string, value: unknown): void\n getStates(): Map<number, Record<string, unknown>>\n on(event: 'change', listener: (...args: unknown[]) => void): void\n off(event: 'change', listener: (...args: unknown[]) => void): void\n}\n\n/** How the people editing together see each other. */\nexport interface CollaborationUser {\n name: string\n /** The color of this user's cursor and selection, any CSS color. Picked from the client id when left out. */\n color?: string\n}\n\nexport interface CollaborationOptions {\n /** Where the text lives, e.g. `ydoc.getText('code')`. */\n text: Y.Text\n /** Shares cursors and selections (`y-protocols/awareness`). Without it, others' cursors are not shown. */\n awareness?: AwarenessLike\n /** This user, shown at their cursor to the others. Needs `awareness`. */\n user?: CollaborationUser\n}\n\nexport { collaborationColors }\n\n/** What each person shares under the awareness field `code`: their selection, as positions that follow edits. */\ninterface SharedSelection {\n ranges: Array<{ anchor: unknown; head: unknown }>\n main: number\n}\n\ninterface Peer {\n client: number\n name: string\n color: string\n selection: SharedSelection\n}\n\n/** Marks the steps this binding took from the shared text, so they aren't written back. */\nconst FROM_SHARED = 'collaboration'\n\nlet warnedBreaks = false\n/** The editor keeps `\\n` only; a `\\r` from another client would put every position after it off by one. */\nfunction warnBreaks(insert: string) {\n if (process.env.NODE_ENV === 'production' || warnedBreaks || !insert.includes('\\r')) return\n warnedBreaks = true\n console.warn(\n '[@dou-ui/code] the shared text has a \"\\\\r\": the editor only keeps \"\\\\n\" line breaks, so positions after it no longer match. Write \"\\\\n\" only into the Y.Text.',\n )\n}\n\nlet warnedEmpty = false\n/** Filling the shared text from each editor would add one copy per person who opens it at the same time. */\nfunction warnEmpty() {\n if (process.env.NODE_ENV === 'production' || warnedEmpty) return\n warnedEmpty = true\n console.warn(\n '[@dou-ui/code] the shared text is empty, so the editor shows it empty, whatever v-model holds. Write the starting text into the Y.Text once, where the document is created.',\n )\n}\n\n/**\n * Edit together through a Yjs text. The text lives in `text`: the\n * editor starts from it, whatever `v-model` holds, and `v-model` then\n * mirrors it; a new `v-model` value is written into it as a change, to\n * everyone. Undo only takes back this user's own changes.\n *\n * One extension per editor: two editors on the same text each need their own.\n */\nexport function collaboration(options: CollaborationOptions): CodeExtension {\n const { text, awareness, user } = options\n const doc = text.doc\n if (!doc) throw new Error('[@dou-ui/code] collaboration() needs a Y.Text inside a Y.Doc')\n if (awareness && user) {\n const color = user.color ?? collaborationColors[doc.clientID % collaborationColors.length]\n awareness.setLocalStateField('user', { name: user.name, color })\n }\n /** The origin of this editor's own changes, which undo tracks. */\n const origin = { name: 'dou-code-collaboration' }\n const undoManager = new Y.UndoManager(text, {\n trackedOrigins: new Set([origin]),\n captureTimeout: 500,\n })\n const tick = ref(0)\n const bump = () => tick.value++\n undoManager.on('stack-item-added', bump)\n undoManager.on('stack-item-popped', bump)\n undoManager.on('stack-cleared', bump)\n\n let context: CodeExtensionContext | null = null\n /** The selection before the change being written: undo puts the cursor back there. */\n let before: CodeSelection | null = null\n\n const relative = (index: number) => Y.createRelativePositionFromTypeIndex(text, index)\n const absolute = (position: Y.RelativePosition) => {\n const found = Y.createAbsolutePositionFromRelativePosition(position, doc)\n return found && found.type === text ? found.index : null\n }\n type Kept = { ranges: Array<[Y.RelativePosition, Y.RelativePosition]>; main: number }\n const keep = (selection: CodeSelection): Kept => ({\n ranges: selection.ranges.map((range) => [relative(range.anchor), relative(range.head)]),\n main: selection.main,\n })\n\n undoManager.on(\n 'stack-item-added',\n (event: { stackItem: { meta: Map<string, unknown> }; type: 'undo' | 'redo' }) => {\n if (!event.stackItem.meta.has('selection') && before)\n event.stackItem.meta.set('selection', keep(before))\n },\n )\n undoManager.on('stack-item-popped', (event: { stackItem: { meta: Map<string, unknown> } }) => {\n const kept = event.stackItem.meta.get('selection') as Kept | undefined\n if (!context || !kept) return\n const ranges = []\n for (const [anchor, head] of kept.ranges) {\n const a = absolute(anchor)\n const b = absolute(head)\n if (a !== null && b !== null) ranges.push({ anchor: a, head: b })\n }\n if (ranges.length) context.select({ ranges, main: Math.min(kept.main, ranges.length - 1) })\n })\n\n /** Someone else's change, or an undo: into the editor, kept out of its own undo. */\n const observer = (event: Y.YTextEvent, transaction: Y.Transaction) => {\n if (transaction.origin === origin || !context) return\n const specs: CodeChangeSpec[] = []\n let pos = 0\n for (const op of event.delta) {\n if (op.retain) pos += op.retain\n else if (op.delete) {\n specs.push({ from: pos, to: pos + op.delete })\n pos += op.delete\n } else if (typeof op.insert === 'string') {\n warnBreaks(op.insert)\n specs.push({ from: pos, insert: op.insert })\n }\n }\n if (!specs.length) return\n const undo = transaction.origin === undoManager\n const action = undo ? (undoManager.undoing ? 'undo' : 'redo') : 'remote'\n context.transact(\n (tr) => {\n for (const spec of specs) tr.replace(spec.from, spec.to ?? spec.from, spec.insert ?? '')\n },\n { action, history: false, scroll: undo, [FROM_SHARED]: true },\n )\n }\n\n // ---------------------------------------------------------------- cursors\n\n const peers = shallowRef<Peer[]>([])\n const readPeers = () => {\n if (!awareness) return\n const out: Peer[] = []\n awareness.getStates().forEach((state, client) => {\n if (client === awareness.clientID) return\n const shared = state.code as SharedSelection | null | undefined\n const who = state.user as { name?: string; color?: string } | undefined\n if (!shared || !Array.isArray(shared.ranges)) return\n out.push({\n client,\n name: who?.name ?? '',\n color: who?.color ?? collaborationColors[client % collaborationColors.length]!,\n selection: shared,\n })\n })\n peers.value = out\n }\n\n let shared = ''\n const shareSelection = (selection: CodeSelection | null) => {\n if (!awareness) return\n const value: SharedSelection | null = selection && {\n ranges: selection.ranges.map((range) => ({\n anchor: Y.relativePositionToJSON(relative(range.anchor)),\n head: Y.relativePositionToJSON(relative(range.head)),\n })),\n main: selection.main,\n }\n const json = JSON.stringify(value)\n if (json === shared) return\n shared = json\n awareness.setLocalStateField('code', value)\n }\n\n const resolve = (json: unknown) => {\n try {\n return absolute(Y.createRelativePositionFromJSON(json))\n } catch {\n return null\n }\n }\n\n const decorations = (ctx: CodeExtensionContext): CodeDecoration[] => {\n // the positions resolve against the text now: follow every change\n const length = ctx.doc.length\n const out: CodeDecoration[] = []\n for (const peer of peers.value) {\n const style = { '--dou-code-peer-color': peer.color }\n peer.selection.ranges.forEach((range, i) => {\n const anchor = resolve(range.anchor)\n const head = resolve(range.head)\n if (anchor === null || head === null || head > length || anchor > length) return\n if (anchor !== head)\n out.push({\n type: 'mark',\n from: Math.min(anchor, head),\n to: Math.max(anchor, head),\n class: 'dou-code-peer-selection',\n style,\n })\n // the name, once per person, on their main cursor\n const named = i === peer.selection.main\n const below = ctx.doc.lineAt(head).number === 1\n out.push({\n type: 'inline',\n pos: head,\n width: 0,\n id: `peer-${peer.client}-${i}`,\n render: () =>\n h(\n 'span',\n {\n // a new element when they move (not when the text around moves), so the name shows again\n key: JSON.stringify(range.head),\n class: ['dou-code-peer', below && 'is-below'],\n style,\n 'aria-hidden': 'true',\n },\n named && peer.name\n ? h('span', { class: 'dou-code-peer__name' }, peer.name)\n : undefined,\n ),\n })\n })\n }\n return out\n }\n\n // ---------------------------------------------------------------- history\n\n const history: CodeHistoryHandler = {\n undo() {\n if (!undoManager.undoStack.length) return false\n before = context?.selection ?? null\n undoManager.undo()\n return true\n },\n redo() {\n if (!undoManager.redoStack.length) return false\n before = context?.selection ?? null\n undoManager.redo()\n return true\n },\n canUndo: () => (void tick.value, undoManager.undoStack.length > 0),\n canRedo: () => (void tick.value, undoManager.redoStack.length > 0),\n close: () => undoManager.stopCapturing(),\n }\n\n return defineCodeExtension({\n name: 'collaboration',\n setup(ctx) {\n context = ctx\n // the shared text wins over whatever the editor started with\n const current = text.toString()\n if (!current && ctx.doc.length) warnEmpty()\n if (current !== ctx.doc.toString()) {\n warnBreaks(current)\n const head = Math.min(mainRange(ctx.selection).head, current.length)\n ctx.transact((tr) => tr.replace(0, tr.doc.length, current).select(head), {\n action: 'remote',\n history: false,\n scroll: false,\n [FROM_SHARED]: true,\n })\n }\n text.observe(observer)\n awareness?.on('change', readPeers)\n readPeers()\n // the cursor is shared only while this person is in the editor\n const stop = watch(\n () => ctx.focused,\n (focused) => shareSelection(focused ? ctx.selection : null),\n { immediate: true },\n )\n return () => {\n stop()\n text.unobserve(observer)\n awareness?.off('change', readPeers)\n shareSelection(null)\n if (context === ctx) context = null\n }\n },\n update(result: CodeTransactionResult, ctx) {\n if (!result.meta[FROM_SHARED] && !result.changes.empty) {\n before = result.before.selection\n const list = result.changes.changes\n doc.transact(() => {\n // from the end, so the positions before each change still hold\n for (let i = list.length - 1; i >= 0; i--) {\n const change = list[i]!\n if (change.to > change.from) text.delete(change.from, change.to - change.from)\n if (change.insert) text.insert(change.from, change.insert)\n }\n }, origin)\n }\n shareSelection(ctx.focused ? result.state.selection : null)\n },\n decorations: awareness ? decorations : undefined,\n history: () => history,\n })\n}\n"],"mappings":";;;;;;;AAwDA,IAAM,cAAc;AAEpB,IAAI,eAAe;;AAEnB,SAAS,WAAW,QAAgB;CAClC,IAAA,QAAA,IAAA,aAA6B,gBAAgB,gBAAgB,CAAC,OAAO,SAAS,IAAI,GAAG;CACrF,eAAe;CACf,QAAQ,KACN,qKACF;AACF;AAEA,IAAI,cAAc;;AAElB,SAAS,YAAY;CACnB,IAAA,QAAA,IA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,MAAM;IACnE,IAAI,UAAU,OAAO,GAAG,QAAQ,GAAG,GAAG,IAAI,QAAQ,OAAO,CAAC,CAAC,OAAO,IAAI,GAAG;KACvE,QAAQ;KACR,SAAS;KACT,QAAQ;MACP,cAAc;IACjB,CAAC;GACH;GACA,KAAK,QAAQ,QAAQ;GACrB,WAAW,GAAG,UAAU,SAAS;GACjC,UAAU;GAEV,MAAM,OAAO,YACL,IAAI,UACT,YAAY,eAAe,UAAU,IAAI,YAAY,IAAI,GAC1D,EAAE,WAAW,KAAK,CACpB;GACA,aAAa;IACX,KAAK;IACL,KAAK,UAAU,QAAQ;IACvB,WAAW,IAAI,UAAU,SAAS;IAClC,eAAe,IAAI;IACnB,IAAI,YAAY,KAAK,UAAU;GACjC;EACF;EACA,OAAO,QAA+B,KAAK;GACzC,IAAI,CAAC,OAAO,KAAK,gBAAgB,CAAC,OAAO,QAAQ,OAAO;IACtD,SAAS,OAAO,OAAO;IACvB,MAAM,OAAO,OAAO,QAAQ;IAC5B,IAAI,eAAe;KAEjB,KAAK,IAAI,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;MACzC,MAAM,SAAS,KAAK;MACpB,IAAI,OAAO,KAAK,OAAO,MAAM,KAAK,OAAO,OAAO,MAAM,OAAO,KAAK,OAAO,IAAI;MAC7E,IAAI,OAAO,QAAQ,KAAK,OAAO,OAAO,MAAM,OAAO,MAAM;KAC3D;IACF,GAAG,MAAM;GACX;GACA,eAAe,IAAI,UAAU,OAAO,MAAM,YAAY,IAAI;EAC5D;EACA,aAAa,YAAY,cAAc,KAAA;EACvC,eAAe;CACjB,CAAC;AACH"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// src/completion/match.ts
|
|
2
|
+
var isUpper = (code) => code >= 65 && code <= 90;
|
|
3
|
+
var isWordChar = (code) => code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
|
|
4
|
+
/** Whether label position `i` starts a word: the first character, after `_`, `-`, `.` or a space, or a capital after a small letter. */
|
|
5
|
+
function startsWord(label, i) {
|
|
6
|
+
if (i === 0) return true;
|
|
7
|
+
const code = label.charCodeAt(i);
|
|
8
|
+
const prev = label.charCodeAt(i - 1);
|
|
9
|
+
if (!isWordChar(prev)) return true;
|
|
10
|
+
return isUpper(code) && !isUpper(prev);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Matches `query` against `label`: its characters in order, ignoring
|
|
14
|
+
* case. A prefix scores best, then characters at word starts (`gEB` for
|
|
15
|
+
* `getElementById`), then characters further apart. `null` when some
|
|
16
|
+
* character can't be found.
|
|
17
|
+
*/
|
|
18
|
+
function matchCompletion(label, query) {
|
|
19
|
+
if (!query) return {
|
|
20
|
+
score: 0,
|
|
21
|
+
ranges: []
|
|
22
|
+
};
|
|
23
|
+
const lower = label.toLowerCase();
|
|
24
|
+
const q = query.toLowerCase();
|
|
25
|
+
if (lower.startsWith(q)) return {
|
|
26
|
+
score: 1e3 + (label.startsWith(query) ? 1 : 0) - label.length / 100,
|
|
27
|
+
ranges: [[0, query.length]]
|
|
28
|
+
};
|
|
29
|
+
const ranges = [];
|
|
30
|
+
let score = 0;
|
|
31
|
+
let at = 0;
|
|
32
|
+
for (let i = 0; i < q.length; i++) {
|
|
33
|
+
const ch = q[i];
|
|
34
|
+
let found = -1;
|
|
35
|
+
for (let j = at; j < lower.length; j++) if (lower[j] === ch && startsWord(label, j)) {
|
|
36
|
+
found = j;
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
const next = lower.indexOf(ch, at);
|
|
40
|
+
if (found < 0 || next >= 0 && next === at) found = next;
|
|
41
|
+
if (found < 0) return null;
|
|
42
|
+
score += found === at ? 3 : startsWord(label, found) ? 2 : 0;
|
|
43
|
+
const last = ranges[ranges.length - 1];
|
|
44
|
+
if (last && last[1] === found) last[1] = found + 1;
|
|
45
|
+
else ranges.push([found, found + 1]);
|
|
46
|
+
at = found + 1;
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
score: score * 10 - ranges.length * 5 - label.length / 100,
|
|
50
|
+
ranges
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export { matchCompletion };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=match.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"match.js","names":[],"sources":["../../src/completion/match.ts"],"sourcesContent":["/** How well a typed word matches a label, and which characters of the label it hit. */\nexport interface CodeCompletionMatch {\n score: number\n /** `[from, to]` pieces of the label that were typed, for drawing them stronger. */\n ranges: Array<[number, number]>\n}\n\nconst isUpper = (code: number) => code >= 65 && code <= 90\nconst isWordChar = (code: number) =>\n (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)\n\n/** Whether label position `i` starts a word: the first character, after `_`, `-`, `.` or a space, or a capital after a small letter. */\nfunction startsWord(label: string, i: number) {\n if (i === 0) return true\n const code = label.charCodeAt(i)\n const prev = label.charCodeAt(i - 1)\n if (!isWordChar(prev)) return true\n return isUpper(code) && !isUpper(prev)\n}\n\n/**\n * Matches `query` against `label`: its characters in order, ignoring\n * case. A prefix scores best, then characters at word starts (`gEB` for\n * `getElementById`), then characters further apart. `null` when some\n * character can't be found.\n */\nexport function matchCompletion(label: string, query: string): CodeCompletionMatch | null {\n if (!query) return { score: 0, ranges: [] }\n const lower = label.toLowerCase()\n const q = query.toLowerCase()\n if (lower.startsWith(q)) {\n // The exact case typed counts a little more.\n const exact = label.startsWith(query) ? 1 : 0\n return { score: 1000 + exact - label.length / 100, ranges: [[0, query.length]] }\n }\n // Characters in order, preferring word starts: greedy with a look for a word start first.\n const ranges: Array<[number, number]> = []\n let score = 0\n let at = 0\n for (let i = 0; i < q.length; i++) {\n const ch = q[i]!\n let found = -1\n for (let j = at; j < lower.length; j++)\n if (lower[j] === ch && startsWord(label, j)) {\n found = j\n break\n }\n // A word start is worth skipping ahead for; else the next one in order.\n const next = lower.indexOf(ch, at)\n if (found < 0 || (next >= 0 && next === at)) found = next\n if (found < 0) return null\n score += found === at ? 3 : startsWord(label, found) ? 2 : 0\n const last = ranges[ranges.length - 1]\n if (last && last[1] === found) last[1] = found + 1\n else ranges.push([found, found + 1])\n at = found + 1\n }\n return { score: score * 10 - ranges.length * 5 - label.length / 100, ranges }\n}\n"],"mappings":";AAOA,IAAM,WAAW,SAAiB,QAAQ,MAAM,QAAQ;AACxD,IAAM,cAAc,SACjB,QAAQ,MAAM,QAAQ,MAAQ,QAAQ,MAAM,QAAQ,MAAQ,QAAQ,MAAM,QAAQ;;AAGrF,SAAS,WAAW,OAAe,GAAW;CAC5C,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,OAAO,MAAM,WAAW,CAAC;CAC/B,MAAM,OAAO,MAAM,WAAW,IAAI,CAAC;CACnC,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,OAAO,QAAQ,IAAI,KAAK,CAAC,QAAQ,IAAI;AACvC;;;;;;;AAQA,SAAgB,gBAAgB,OAAe,OAA2C;CACxF,IAAI,CAAC,OAAO,OAAO;EAAE,OAAO;EAAG,QAAQ,CAAC;CAAE;CAC1C,MAAM,QAAQ,MAAM,YAAY;CAChC,MAAM,IAAI,MAAM,YAAY;CAC5B,IAAI,MAAM,WAAW,CAAC,GAGpB,OAAO;EAAE,OAAO,OADF,MAAM,WAAW,KAAK,IAAI,IAAI,KACb,MAAM,SAAS;EAAK,QAAQ,CAAC,CAAC,GAAG,MAAM,MAAM,CAAC;CAAE;CAGjF,MAAM,SAAkC,CAAC;CACzC,IAAI,QAAQ;CACZ,IAAI,KAAK;CACT,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;EACjC,MAAM,KAAK,EAAE;EACb,IAAI,QAAQ;EACZ,KAAK,IAAI,IAAI,IAAI,IAAI,MAAM,QAAQ,KACjC,IAAI,MAAM,OAAO,MAAM,WAAW,OAAO,CAAC,GAAG;GAC3C,QAAQ;GACR;EACF;EAEF,MAAM,OAAO,MAAM,QAAQ,IAAI,EAAE;EACjC,IAAI,QAAQ,KAAM,QAAQ,KAAK,SAAS,IAAK,QAAQ;EACrD,IAAI,QAAQ,GAAG,OAAO;EACtB,SAAS,UAAU,KAAK,IAAI,WAAW,OAAO,KAAK,IAAI,IAAI;EAC3D,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,IAAI,QAAQ,KAAK,OAAO,OAAO,KAAK,KAAK,QAAQ;OAC5C,OAAO,KAAK,CAAC,OAAO,QAAQ,CAAC,CAAC;EACnC,KAAK,QAAQ;CACf;CACA,OAAO;EAAE,OAAO,QAAQ,KAAK,OAAO,SAAS,IAAI,MAAM,SAAS;EAAK;CAAO;AAC9E"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// src/completion/snippet.ts
|
|
2
|
+
/**
|
|
3
|
+
* Reads a snippet: `${1:name}` is field 1 holding `name`, `$1` or `${1}`
|
|
4
|
+
* field 1 again (holding the same), and `$0` where the cursor ends. Every
|
|
5
|
+
* place of a field is filled in together. `\$` and `\}`
|
|
6
|
+
* are the characters themselves.
|
|
7
|
+
*/
|
|
8
|
+
function parseSnippet(source) {
|
|
9
|
+
let text = "";
|
|
10
|
+
const fields = [];
|
|
11
|
+
const open = [];
|
|
12
|
+
const defaults = /* @__PURE__ */ new Map();
|
|
13
|
+
for (const match of source.matchAll(/(?<!\\)\$\{(\d+):([^${}\\]*)\}/g)) if (!defaults.has(Number(match[1]))) defaults.set(Number(match[1]), match[2]);
|
|
14
|
+
const mirror = (index) => {
|
|
15
|
+
const from = text.length;
|
|
16
|
+
text += defaults.get(index) ?? "";
|
|
17
|
+
fields.push({
|
|
18
|
+
index,
|
|
19
|
+
from,
|
|
20
|
+
to: text.length
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
for (let i = 0; i < source.length; i++) {
|
|
24
|
+
const ch = source[i];
|
|
25
|
+
if (ch === "\\" && (source[i + 1] === "$" || source[i + 1] === "}" || source[i + 1] === "\\")) {
|
|
26
|
+
text += source[++i];
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (ch === "$") {
|
|
30
|
+
const plain = /^\d+/.exec(source.slice(i + 1));
|
|
31
|
+
if (plain) {
|
|
32
|
+
mirror(Number(plain[0]));
|
|
33
|
+
i += plain[0].length;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const braced = /^\{(\d+)(:|\})/.exec(source.slice(i + 1));
|
|
37
|
+
if (braced) {
|
|
38
|
+
i += braced[0].length;
|
|
39
|
+
if (braced[2] === "}") mirror(Number(braced[1]));
|
|
40
|
+
else open.push({
|
|
41
|
+
index: Number(braced[1]),
|
|
42
|
+
from: text.length
|
|
43
|
+
});
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (ch === "}" && open.length) {
|
|
48
|
+
const field = open.pop();
|
|
49
|
+
fields.push({
|
|
50
|
+
index: field.index,
|
|
51
|
+
from: field.from,
|
|
52
|
+
to: text.length
|
|
53
|
+
});
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
text += ch;
|
|
57
|
+
}
|
|
58
|
+
for (const field of open) fields.push({
|
|
59
|
+
index: field.index,
|
|
60
|
+
from: field.from,
|
|
61
|
+
to: text.length
|
|
62
|
+
});
|
|
63
|
+
fields.sort((a, b) => (a.index || Infinity) - (b.index || Infinity) || a.from - b.from);
|
|
64
|
+
return {
|
|
65
|
+
text,
|
|
66
|
+
fields
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
export { parseSnippet };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=snippet.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snippet.js","names":[],"sources":["../../src/completion/snippet.ts"],"sourcesContent":["/** A place in a snippet to fill in, `from`–`to` in its text. */\nexport interface SnippetField {\n /** Its number: Tab goes through them in order, `0` last. */\n index: number\n from: number\n to: number\n}\n\n/**\n * Reads a snippet: `${1:name}` is field 1 holding `name`, `$1` or `${1}`\n * field 1 again (holding the same), and `$0` where the cursor ends. Every\n * place of a field is filled in together. `\\$` and `\\}`\n * are the characters themselves.\n */\nexport function parseSnippet(source: string): { text: string; fields: SnippetField[] } {\n let text = ''\n const fields: SnippetField[] = []\n const open: Array<{ index: number; from: number }> = []\n // What each numbered field holds, so a bare `$1` repeats it.\n const defaults = new Map<number, string>()\n for (const match of source.matchAll(/(?<!\\\\)\\$\\{(\\d+):([^${}\\\\]*)\\}/g))\n if (!defaults.has(Number(match[1]))) defaults.set(Number(match[1]), match[2]!)\n const mirror = (index: number) => {\n const from = text.length\n text += defaults.get(index) ?? ''\n fields.push({ index, from, to: text.length })\n }\n for (let i = 0; i < source.length; i++) {\n const ch = source[i]!\n if (ch === '\\\\' && (source[i + 1] === '$' || source[i + 1] === '}' || source[i + 1] === '\\\\')) {\n text += source[++i]\n continue\n }\n if (ch === '$') {\n const plain = /^\\d+/.exec(source.slice(i + 1))\n if (plain) {\n mirror(Number(plain[0]))\n i += plain[0].length\n continue\n }\n const braced = /^\\{(\\d+)(:|\\})/.exec(source.slice(i + 1))\n if (braced) {\n i += braced[0].length\n if (braced[2] === '}') mirror(Number(braced[1]))\n else open.push({ index: Number(braced[1]), from: text.length })\n continue\n }\n }\n if (ch === '}' && open.length) {\n const field = open.pop()!\n fields.push({ index: field.index, from: field.from, to: text.length })\n continue\n }\n text += ch\n }\n // Unclosed fields end where the text does.\n for (const field of open) fields.push({ index: field.index, from: field.from, to: text.length })\n // In Tab order: 1, 2, … and 0 (or the end) last.\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n fields.sort((a, b) => (a.index || Infinity) - (b.index || Infinity) || a.from - b.from)\n return { text, fields }\n}\n"],"mappings":";;;;;;;AAcA,SAAgB,aAAa,QAA0D;CACrF,IAAI,OAAO;CACX,MAAM,SAAyB,CAAC;CAChC,MAAM,OAA+C,CAAC;CAEtD,MAAM,2BAAW,IAAI,IAAoB;CACzC,KAAK,MAAM,SAAS,OAAO,S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,MAAM,GAAG,OAAO,EAAE,SAAS,aAAa,EAAE,SAAS,aAAa,EAAE,OAAO,EAAE,IAAI;CACtF,OAAO;EAAE;EAAM;CAAO;AACxB"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// src/core/brackets.ts
|
|
2
|
+
/** How far bracket matching looks, in characters, so a huge text never stalls a key press. */
|
|
3
|
+
var SCAN_LIMIT = 2e4;
|
|
4
|
+
/**
|
|
5
|
+
* The bracket at `pos` (the one after it, else the one before) and its
|
|
6
|
+
* partner. `skip(pos)` tells whether a character is inside a string or a
|
|
7
|
+
* comment, where brackets don't count.
|
|
8
|
+
*/
|
|
9
|
+
function matchBracket(doc, pos, brackets, skip) {
|
|
10
|
+
const line = doc.lineAt(pos);
|
|
11
|
+
const col = pos - line.from;
|
|
12
|
+
for (const at of [col, col - 1]) {
|
|
13
|
+
const ch = line.text[at];
|
|
14
|
+
if (ch === void 0) continue;
|
|
15
|
+
const index = brackets.indexOf(ch);
|
|
16
|
+
if (index < 0) continue;
|
|
17
|
+
const from = line.from + at;
|
|
18
|
+
if (skip?.(from)) continue;
|
|
19
|
+
return {
|
|
20
|
+
from,
|
|
21
|
+
match: findPartner(doc, from, brackets, index, skip)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
/** The partner of the bracket at `from`, which is `brackets[index]`. */
|
|
27
|
+
function findPartner(doc, from, brackets, index, skip) {
|
|
28
|
+
const open = index % 2 === 0;
|
|
29
|
+
const self = brackets[index];
|
|
30
|
+
const partner = brackets[open ? index + 1 : index - 1];
|
|
31
|
+
const dir = open ? 1 : -1;
|
|
32
|
+
let depth = 0;
|
|
33
|
+
let line = doc.lineAt(from);
|
|
34
|
+
let col = from - line.from + dir;
|
|
35
|
+
let scanned = 0;
|
|
36
|
+
for (;;) {
|
|
37
|
+
while (col >= 0 && col < line.text.length) {
|
|
38
|
+
const ch = line.text[col];
|
|
39
|
+
if ((ch === self || ch === partner) && !skip?.(line.from + col)) {
|
|
40
|
+
if (ch === self) depth++;
|
|
41
|
+
else if (depth === 0) return line.from + col;
|
|
42
|
+
else depth--;
|
|
43
|
+
}
|
|
44
|
+
col += dir;
|
|
45
|
+
if (++scanned > SCAN_LIMIT) return null;
|
|
46
|
+
}
|
|
47
|
+
const next = line.number + dir;
|
|
48
|
+
if (next < 1 || next > doc.lines) return null;
|
|
49
|
+
line = doc.line(next);
|
|
50
|
+
col = dir > 0 ? 0 : line.text.length - 1;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export { findPartner, matchBracket };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=brackets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"brackets.js","names":[],"sources":["../../src/core/brackets.ts"],"sourcesContent":["import type { CodeText } from './text'\n\n/** How far bracket matching looks, in characters, so a huge text never stalls a key press. */\nconst SCAN_LIMIT = 20_000\n\nexport interface BracketMatch {\n /** The bracket next to the cursor. */\n from: number\n /** Its partner, or `null` when there is none within reach. */\n match: number | null\n}\n\n/**\n * The bracket at `pos` (the one after it, else the one before) and its\n * partner. `skip(pos)` tells whether a character is inside a string or a\n * comment, where brackets don't count.\n */\nexport function matchBracket(\n doc: CodeText,\n pos: number,\n brackets: string,\n skip?: (pos: number) => boolean,\n): BracketMatch | null {\n const line = doc.lineAt(pos)\n const col = pos - line.from\n for (const at of [col, col - 1]) {\n const ch = line.text[at]\n if (ch === undefined) continue\n const index = brackets.indexOf(ch)\n if (index < 0) continue\n const from = line.from + at\n if (skip?.(from)) continue\n return { from, match: findPartner(doc, from, brackets, index, skip) }\n }\n return null\n}\n\n/** The partner of the bracket at `from`, which is `brackets[index]`. */\nexport function findPartner(\n doc: CodeText,\n from: number,\n brackets: string,\n index: number,\n skip?: (pos: number) => boolean,\n): number | null {\n const open = index % 2 === 0\n const self = brackets[index]!\n const partner = brackets[open ? index + 1 : index - 1]!\n const dir = open ? 1 : -1\n let depth = 0\n let line = doc.lineAt(from)\n let col = from - line.from + dir\n let scanned = 0\n for (;;) {\n while (col >= 0 && col < line.text.length) {\n const ch = line.text[col]!\n if ((ch === self || ch === partner) && !skip?.(line.from + col)) {\n if (ch === self) depth++\n else if (depth === 0) return line.from + col\n else depth--\n }\n col += dir\n if (++scanned > SCAN_LIMIT) return null\n }\n const next = line.number + dir\n if (next < 1 || next > doc.lines) return null\n line = doc.line(next)\n col = dir > 0 ? 0 : line.text.length - 1\n }\n}\n"],"mappings":";;AAGA,IAAM,aAAa;;;;;;AAcnB,SAAgB,aACd,KACA,KACA,UACA,MACqB;CACrB,MAAM,OAAO,IAAI,OAAO,GAAG;CAC3B,MAAM,MAAM,MAAM,KAAK;CACvB,KAAK,MAAM,MAAM,CAAC,KAAK,MAAM,CAAC,GAAG;EAC/B,MAAM,KAAK,KAAK,KAAK;EACrB,IAAI,OAAO,KAAA,GAAW;EACtB,MAAM,QAAQ,SAAS,QAAQ,EAAE;EACjC,IAAI,QAAQ,GAAG;EACf,MAAM,OAAO,KAAK,OAAO;EACzB,IAAI,OAAO,IAAI,GAAG;EAClB,OAAO;GAAE;GAAM,OAAO,YAAY,KAAK,MAAM,UAAU,OAAO,IAAI;EAAE;CACtE;CACA,OAAO;AACT;;AAGA,SAAgB,YACd,KACA,MACA,UACA,OACA,MACe;CACf,MAAM,OAAO,QAAQ,MAAM;CAC3B,MAAM,OAAO,SAAS;CACtB,MAAM,UAAU,SAAS,OAAO,QAAQ,IAAI,QAAQ;CACpD,MAAM,MAAM,OAAO,IAAI;CACvB,IAAI,QAAQ;CACZ,IAAI,OAAO,IAAI,OAAO,IAAI;CAC1B,IAAI,MAAM,OAAO,KAAK,OAAO;CAC7B,IAAI,UAAU;CACd,SAAS;EACP,OAAO,OAAO,KAAK,MAAM,KAAK,KAAK,QAAQ;GACzC,MAAM,KAAK,KAAK,KAAK;GACrB,KAAK,OAAO,QAAQ,OAAO,YAAY,CAAC,OAAO,KAAK,OAAO,GAAG,GAAG;IAC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