forked from slab/quill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyntax.ts
345 lines (319 loc) · 10 KB
/
syntax.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import Delta from 'quill-delta';
import { ClassAttributor, Scope, ScrollBlot } from 'parchment';
import Inline from '../blots/inline';
import Quill from '../core/quill';
import Module from '../core/module';
import { blockDelta } from '../blots/block';
import BreakBlot from '../blots/break';
import CursorBlot from '../blots/cursor';
import TextBlot, { escapeText } from '../blots/text';
import CodeBlock, { CodeBlockContainer } from '../formats/code';
import { traverse } from './clipboard';
const TokenAttributor = new ClassAttributor('code-token', 'hljs', {
scope: Scope.INLINE,
});
class CodeToken extends Inline {
static formats(node: Element, scroll: ScrollBlot) {
while (node != null && node !== scroll.domNode) {
if (node.classList && node.classList.contains(CodeBlock.className)) {
// @ts-expect-error
return super.formats(node, scroll);
}
// @ts-expect-error
node = node.parentNode;
}
return undefined;
}
constructor(scroll: ScrollBlot, domNode: Node, value: unknown) {
// @ts-expect-error
super(scroll, domNode, value);
// @ts-expect-error
TokenAttributor.add(this.domNode, value);
}
format(format: string, value: unknown) {
if (format !== CodeToken.blotName) {
super.format(format, value);
} else if (value) {
// @ts-expect-error
TokenAttributor.add(this.domNode, value);
} else {
TokenAttributor.remove(this.domNode);
this.domNode.classList.remove(this.statics.className);
}
}
optimize(...args) {
// @ts-expect-error
super.optimize(...args);
if (!TokenAttributor.value(this.domNode)) {
this.unwrap();
}
}
}
CodeToken.blotName = 'code-token';
CodeToken.className = 'ql-token';
class SyntaxCodeBlock extends CodeBlock {
static create(value: unknown) {
const domNode = super.create(value);
if (typeof value === 'string') {
// @ts-expect-error
domNode.setAttribute('data-language', value);
}
return domNode;
}
static formats(domNode: Node) {
// @ts-expect-error
return domNode.getAttribute('data-language') || 'plain';
}
static register() {} // Syntax module will register
format(name: string, value: unknown) {
if (name === this.statics.blotName && value) {
// @ts-expect-error
this.domNode.setAttribute('data-language', value);
} else {
super.format(name, value);
}
}
replaceWith(name: string, value: unknown) {
this.formatAt(0, this.length(), CodeToken.blotName, false);
return super.replaceWith(name, value);
}
}
class SyntaxCodeBlockContainer extends CodeBlockContainer {
forceNext?: boolean;
cachedText?: string | null;
attach() {
super.attach();
this.forceNext = false;
// @ts-expect-error
this.scroll.emitMount(this);
}
format(name, value) {
if (name === SyntaxCodeBlock.blotName) {
this.forceNext = true;
this.children.forEach(child => {
// @ts-expect-error
child.format(name, value);
});
}
}
formatAt(index: number, length: number, name, value) {
if (name === SyntaxCodeBlock.blotName) {
this.forceNext = true;
}
super.formatAt(index, length, name, value);
}
highlight(
highlight: (text: string, language: string) => Delta,
forced = false,
) {
if (this.children.head == null) return;
const nodes = Array.from(this.domNode.childNodes).filter(
node => node !== this.uiNode,
);
const text = `${nodes.map(node => node.textContent).join('\n')}\n`;
const language = SyntaxCodeBlock.formats(this.children.head.domNode);
if (forced || this.forceNext || this.cachedText !== text) {
if (text.trim().length > 0 || this.cachedText == null) {
const oldDelta = this.children.reduce((delta, child) => {
// @ts-expect-error
return delta.concat(blockDelta(child, false));
}, new Delta());
const delta = highlight(text, language);
oldDelta.diff(delta).reduce((index, { retain, attributes }) => {
// Should be all retains
if (!retain) return index;
if (attributes) {
Object.keys(attributes).forEach(format => {
if (
[SyntaxCodeBlock.blotName, CodeToken.blotName].includes(format)
) {
// @ts-expect-error
this.formatAt(index, retain, format, attributes[format]);
}
});
}
// @ts-expect-error
return index + retain;
}, 0);
}
this.cachedText = text;
this.forceNext = false;
}
}
html(index, length) {
const [codeBlock] = this.children.find(index);
const language = codeBlock
? SyntaxCodeBlock.formats(codeBlock.domNode)
: 'plain';
return `<pre data-language="${language}">\n${escapeText(
this.code(index, length),
)}\n</pre>`;
}
optimize(context: unknown) {
super.optimize(context);
if (
this.parent != null &&
this.children.head != null &&
this.uiNode != null
) {
const language = SyntaxCodeBlock.formats(this.children.head.domNode);
// @ts-expect-error
if (language !== this.uiNode.value) {
// @ts-expect-error
this.uiNode.value = language;
}
}
}
}
// @ts-expect-error
SyntaxCodeBlockContainer.allowedChildren = [SyntaxCodeBlock];
SyntaxCodeBlock.requiredContainer = SyntaxCodeBlockContainer;
SyntaxCodeBlock.allowedChildren = [CodeToken, CursorBlot, TextBlot, BreakBlot];
interface SyntaxOptions {
interval: number;
languages: { key: string; label: string }[];
}
class Syntax extends Module<SyntaxOptions> {
static register() {
Quill.register(CodeToken, true);
// @ts-expect-error
Quill.register(SyntaxCodeBlock, true);
Quill.register(SyntaxCodeBlockContainer, true);
}
languages: Record<string, true>;
constructor(quill: Quill, options: Partial<SyntaxOptions>) {
super(quill, options);
// @ts-expect-error
if (this.options.hljs == null) {
throw new Error(
'Syntax module requires highlight.js. Please include the library on the page before Quill.',
);
}
this.languages = this.options.languages.reduce((memo, { key }) => {
memo[key] = true;
return memo;
}, {});
this.highlightBlot = this.highlightBlot.bind(this);
this.initListener();
this.initTimer();
}
initListener() {
this.quill.on(Quill.events.SCROLL_BLOT_MOUNT, blot => {
if (!(blot instanceof SyntaxCodeBlockContainer)) return;
const select = this.quill.root.ownerDocument.createElement('select');
this.options.languages.forEach(({ key, label }) => {
const option = select.ownerDocument.createElement('option');
option.textContent = label;
option.setAttribute('value', key);
select.appendChild(option);
});
select.addEventListener('change', () => {
blot.format(SyntaxCodeBlock.blotName, select.value);
this.quill.root.focus(); // Prevent scrolling
this.highlight(blot, true);
});
if (blot.uiNode == null) {
blot.attachUI(select);
if (blot.children.head) {
select.value = SyntaxCodeBlock.formats(blot.children.head.domNode);
}
}
});
}
initTimer() {
let timer = null;
this.quill.on(Quill.events.SCROLL_OPTIMIZE, () => {
clearTimeout(timer);
timer = setTimeout(() => {
this.highlight();
timer = null;
}, this.options.interval);
});
}
highlight(blot = null, force = false) {
if (this.quill.selection.composing) return;
this.quill.update(Quill.sources.USER);
const range = this.quill.getSelection();
const blots =
blot == null
? // @ts-expect-error
this.quill.scroll.descendants(SyntaxCodeBlockContainer)
: [blot];
blots.forEach(container => {
container.highlight(this.highlightBlot, force);
});
this.quill.update(Quill.sources.SILENT);
if (range != null) {
this.quill.setSelection(range, Quill.sources.SILENT);
}
}
highlightBlot(text, language = 'plain') {
language = this.languages[language] ? language : 'plain';
if (language === 'plain') {
return escapeText(text)
.split('\n')
.reduce((delta, line, i) => {
if (i !== 0) {
delta.insert('\n', { [CodeBlock.blotName]: language });
}
return delta.insert(line);
}, new Delta());
}
const container = this.quill.root.ownerDocument.createElement('div');
container.classList.add(CodeBlock.className);
// @ts-expect-error
container.innerHTML = this.options.hljs.highlight(language, text).value;
return traverse(
this.quill.scroll,
container,
[
(node, delta) => {
// @ts-expect-error
const value = TokenAttributor.value(node);
if (value) {
return delta.compose(
new Delta().retain(delta.length(), {
[CodeToken.blotName]: value,
}),
);
}
return delta;
},
],
[
(node, delta) => {
// @ts-expect-error
return node.data.split('\n').reduce((memo, nodeText, i) => {
if (i !== 0) memo.insert('\n', { [CodeBlock.blotName]: language });
return memo.insert(nodeText);
}, delta);
},
],
new WeakMap(),
);
}
}
Syntax.DEFAULTS = {
hljs: (() => {
// @ts-expect-error
return window.hljs;
})(),
interval: 1000,
languages: [
{ key: 'plain', label: 'Plain' },
{ key: 'bash', label: 'Bash' },
{ key: 'cpp', label: 'C++' },
{ key: 'cs', label: 'C#' },
{ key: 'css', label: 'CSS' },
{ key: 'diff', label: 'Diff' },
{ key: 'xml', label: 'HTML/XML' },
{ key: 'java', label: 'Java' },
{ key: 'javascript', label: 'Javascript' },
{ key: 'markdown', label: 'Markdown' },
{ key: 'php', label: 'PHP' },
{ key: 'python', label: 'Python' },
{ key: 'ruby', label: 'Ruby' },
{ key: 'sql', label: 'SQL' },
],
};
export { SyntaxCodeBlock as CodeBlock, CodeToken, Syntax as default };