-
-
Notifications
You must be signed in to change notification settings - Fork 377
/
inline-sync.ts
245 lines (196 loc) · 7.46 KB
/
inline-sync.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/* Copyright 2021, Milkdown by Mirone. */
import { createSlice, Ctx, editorViewCtx, parserCtx, serializerCtx } from '@milkdown/core';
import { Attrs, Node } from '@milkdown/prose/model';
import { EditorState, Plugin, PluginKey, TextSelection, Transaction } from '@milkdown/prose/state';
import { pipe } from '@milkdown/utils';
export type ShouldSyncNode = (context: {
prevNode: Node;
nextNode: Node;
ctx: Ctx;
tr: Transaction;
text: string;
}) => boolean;
export type SyncNodePlaceholder = {
hole: string;
punctuation: string;
char: string;
};
export type inlineSyncConfig = {
placeholderConfig: SyncNodePlaceholder;
shouldSyncNode: ShouldSyncNode;
movePlaceholder: (placeholderToMove: string, text: string) => string;
};
export const inlineSyncConfigCtx = createSlice<inlineSyncConfig, 'inlineSyncConfig'>(
{
placeholderConfig: {
hole: '∅',
punctuation: '⁂',
char: '∴',
},
shouldSyncNode: ({ prevNode, nextNode }) =>
prevNode.inlineContent &&
nextNode &&
// if node type changes, do not sync
prevNode.type === nextNode.type &&
// if two node fully equal, we don't modify them
!prevNode.eq(nextNode),
movePlaceholder: (placeholderToMove: string, text: string) => {
const symbolsNeedToMove = ['*', '_'];
let index = text.indexOf(placeholderToMove);
while (
symbolsNeedToMove.includes(text[index - 1] || '') &&
symbolsNeedToMove.includes(text[index + 1] || '')
) {
text = swap(text, index, index + 1);
index = index + 1;
}
return text;
},
},
'inlineSyncConfig',
);
const linkRegexp = /\[(?<span>((www|https:\/\/|http:\/\/)\S+))]\((?<url>\S+)\)/;
const punctuationRegexp = (holePlaceholder: string) => new RegExp(`\\\\(?=[^\\w\\s${holePlaceholder}\\\\]|_)`, 'g');
const keepLink = (str: string) => {
let text = str;
let match = text.match(linkRegexp);
while (match && match.groups) {
const { span } = match.groups;
text = text.replace(linkRegexp, span as string);
match = text.match(linkRegexp);
}
return text;
};
const swap = (text: string, first: number, last: number) => {
const arr = text.split('');
const temp = arr[first];
if (arr[first] && arr[last]) {
arr[first] = arr[last] as string;
arr[last] = temp as string;
}
return arr.join('').toString();
};
const removeLf = (text: string) => text.slice(0, -1);
const replacePunctuation = (holePlaceholder: string) => (text: string) =>
text.replace(punctuationRegexp(holePlaceholder), '');
const calculatePlaceholder = (placeholder: SyncNodePlaceholder) => (text: string) => {
const index = text.indexOf(placeholder.hole);
const left = text.charAt(index - 1);
const right = text.charAt(index + 1);
const notAWord = /[^\w]|_/;
// cursor on the right
if (!right) {
return placeholder.punctuation;
}
// cursor on the left
if (!left) {
return placeholder.char;
}
if (notAWord.test(left) && notAWord.test(right)) {
return placeholder.punctuation;
}
return placeholder.char;
};
const getOffset = (node: Node, from: number, placeholder: string) => {
let offset = from;
let find = false;
node.descendants((n) => {
if (find) return false;
if (n.isText) {
const i = n.text?.indexOf(placeholder);
if (i != null && i >= 0) {
find = true;
offset += i;
return false;
}
}
offset += n.nodeSize;
return;
});
return offset;
};
const getContextByState = (ctx: Ctx, state: EditorState) => {
const { selection } = state;
const { $from } = selection;
const node = $from.node();
const doc = state.schema.topNodeType.create(undefined, node);
const parser = ctx.get(parserCtx);
const serializer = ctx.get(serializerCtx);
const markdown = serializer(doc);
const config = ctx.get(inlineSyncConfigCtx);
const holePlaceholder = config.placeholderConfig.hole;
const movePlaceholder = (text: string) => config.movePlaceholder(holePlaceholder, text);
const handleText = pipe(removeLf, replacePunctuation(holePlaceholder), movePlaceholder, keepLink);
let text = handleText(markdown);
const placeholder = calculatePlaceholder(config.placeholderConfig)(text);
text = text.replace(holePlaceholder, placeholder);
const parsed = parser(text);
if (!parsed) return null;
const target = parsed.firstChild;
if (!target || node.type !== target.type) return null;
// @ts-expect-error hijack the node attribute
target.attrs = { ...node.attrs };
target.descendants((node) => {
const marks = node.marks;
const link = marks.find((mark) => mark.type.name === 'link');
if (link && node.text?.includes(placeholder) && link.attrs['href'].includes(placeholder)) {
// @ts-expect-error hijack the mark attribute
link.attrs['href'] = link.attrs['href'].replace(placeholder, '');
}
});
return {
text,
prevNode: node,
nextNode: target,
placeholder,
};
};
export const inlineSyncPluginKey = new PluginKey('MILKDOWN_INLINE_SYNC');
export const getInlineSyncPlugin = (ctx: Ctx) => {
const runReplacer = (state: EditorState, dispatch: (tr: Transaction) => void, attrs: Attrs) => {
const { placeholderConfig } = ctx.get(inlineSyncConfigCtx);
const holePlaceholder = placeholderConfig.hole;
// insert a placeholder to restore the selection
let tr = state.tr.setMeta(inlineSyncPluginKey, true).insertText(holePlaceholder, state.selection.from);
const nextState = state.apply(tr);
const context = getContextByState(ctx, nextState);
if (!context) return;
const { $from } = nextState.selection;
const from = $from.before();
const to = $from.after();
const offset = getOffset(context.nextNode, from, context.placeholder);
tr = tr
.replaceWith(from, to, context.nextNode)
.setNodeMarkup(from, undefined, attrs)
// delete the placeholder
.delete(offset + 1, offset + 2);
tr = tr.setSelection(TextSelection.near(tr.doc.resolve(offset + 1)));
dispatch(tr);
};
const inlineSyncPlugin = new Plugin<null>({
key: inlineSyncPluginKey,
state: {
init: () => {
return null;
},
apply: (tr, _value, _oldState, newState) => {
if (!tr.docChanged) return null;
const meta = tr.getMeta(inlineSyncPluginKey);
if (meta) {
return null;
}
const context = getContextByState(ctx, newState);
if (!context) return null;
const { prevNode, nextNode, text } = context;
const { shouldSyncNode } = ctx.get(inlineSyncConfigCtx);
if (!shouldSyncNode({ prevNode, nextNode, ctx, tr, text })) return null;
requestAnimationFrame(() => {
const { dispatch, state } = ctx.get(editorViewCtx);
runReplacer(state, dispatch, prevNode.attrs);
});
return null;
},
},
});
return inlineSyncPlugin;
};