engine
# Engine Core
# 目录
# Engine
class Engine implements EngineInterface {
private _readonly: boolean = false;
private _container: ContainerInterface;
readonly kind = 'engine';
// 默认配置
options: EngineOptions = {
lang: 'zh-CN',
locale: {},
plugins: [],
cards: [],
config: {},
};
language: LanguageInterface;
root: NodeInterface;
change: ChangeInterface;
card: CardModelInterface;
plugin: PluginModelInterface;
node: NodeModelInterface;
nodeId: NodeIdInterface;
list: ListModelInterface;
mark: MarkModelInterface;
inline: InlineModelInterface;
block: BlockModelInterface;
event: EventInterface;
typing: TypingInterface;
ot: OTInterface;
schema: SchemaInterface;
conversion: ConversionInterface;
history: HistoryInterface;
command: CommandInterface;
hotkey: HotkeyInterface;
clipboard: ClipboardInterface;
request: RequestInterface;
#_scrollNode: NodeInterface | null = null;
get container(): NodeInterface {
return this._container.getNode();
}
get readonly(): boolean {
return this._readonly;
}
get scrollNode(): NodeInterface | null {
if (this.#_scrollNode) return this.#_scrollNode;
// 初始化 _scrollNode
const { scrollNode } = this.options;
let sn = scrollNode
? typeof scrollNode === 'function'
? scrollNode()
: scrollNode
: null;
// 查找父级样式 overflow 或者 overflow-y 为 auto 或者 scroll 的节点
const targetValues = ['auto', 'scroll'];
let parent = this.container.parent();
// 向父级查找 scrollNode
while (parent && parent.length > 0 && parent.name !== 'body') {
if (
targetValues.includes(parent.css('overflow')) ||
targetValues.includes(parent.css('overflow-y'))
) {
sn = parent.get<HTMLElement>();
break;
} else {
parent = parent.parent();
}
}
// 找不到则为 documentElement
if (sn === null) sn = document.documentElement;
this.#_scrollNode = sn ? $(sn) : null;
return this.#_scrollNode;
}
set readonly(readonly: boolean) {
if (this.readonly === readonly) return;
// 设置 readonly:处理快捷键和_container的状态
if (readonly) {
this.hotkey.disable();
this._container.setReadonly(true);
} else {
this.hotkey.enable();
this._container.setReadonly(false);
}
this._readonly = readonly;
// 重新渲染 card
this.card.reRender();
// 广播readonly事件
this.trigger('readonly', readonly);
}
constructor(selector: Selector, options?: EngineOptions) {
// 合并配置
this.options = { ...this.options, ...options };
// 多语言
this.language = new Language(
this.options.lang || 'zh-CN',
merge(language, options?.locale),
);
// 事件管理
this.event = new Event();
// 命令
this.command = new Command(this);
// 节点规则
this.schema = new Schema();
// 设置默认的节点规则
this.schema.add(schemaDefaultData);
// 节点转换规则
this.conversion = new Conversion(this);
// 设置默认的节点转换规则
conversionDefault.forEach((rule) =>
this.conversion.add(rule.from, rule.to),
);
// 历史
this.history = new History(this);
// 卡片
this.card = new CardModel(this, this.options.lazyRender);
// 剪贴板
this.clipboard = new Clipboard(this);
// http请求
this.request = new Request();
// 插件
this.plugin = new Plugin(this);
// 节点管理
this.node = new NodeModel(this);
this.nodeId = new NodeId(this);
// 列表
this.list = new List(this);
// 样式标记
this.mark = new Mark(this);
// 行内样式
this.inline = new Inline(this);
// 块级节点
this.block = new Block(this);
// 编辑器容器
this._container = new Container(selector, {
engine: this,
lang: this.options.lang,
className: this.options.className,
tabIndex: this.options.tabIndex,
placeholder: this.options.placeholder,
});
// 编辑器父节点
this.root = $(
this.options.root || this.container.parent() || getDocument().body,
);
// 设置 root position:relative
const rootPosition = this.root.css('position');
if (!rootPosition || rootPosition === 'static')
this.root.css('position', 'relative');
// 实例化容器
this._container.init();
// 编辑器改变时
this.change = new Change(this, {
onChange: (value, trigger) =>
this.trigger('change', value, trigger),
onSelect: () => this.trigger('select'),
onRealtimeChange: (trigger) => {
if (this.isEmpty()) {
this._container.showPlaceholder();
} else {
this._container.hidePlaceholder();
}
this.trigger('realtimeChange', trigger);
},
onSetValue: () => this.trigger('afterSetValue'),
});
this.change.init();
// 事件处理
this.typing = new Typing(this);
// 只读
this._readonly =
this.options.readonly === undefined ? false : this.options.readonly;
this._container.setReadonly(this._readonly);
// 实例化插件
this.mark.init();
this.inline.init();
this.block.init();
this.list.init();
// 快捷键
this.hotkey = new Hotkey(this);
this.card.init(this.options.cards || []);
this.plugin.init(this.options.plugins || [], this.options.config || {});
this.nodeId.init();
// 协同
this.ot = new OT(this);
if (this.isEmpty()) {
this._container.showPlaceholder();
}
this.ot.initLocal();
}
setScrollNode(node?: HTMLElement) {
this.#_scrollNode = node ? $(node) : null;
}
isFocus() {
return this._container.isFocus();
}
isEmpty() {
return this.change.isEmpty();
}
focus(toStart?: boolean) {
this.change.range.focus(toStart);
}
blur() {
this.change.range.blur();
}
on(eventType: string, listener: EventListener, rewrite?: boolean) {
this.event.on(eventType, listener, rewrite);
return this;
}
off(eventType: string, listener: EventListener) {
this.event.off(eventType, listener);
return this;
}
trigger(eventType: string, ...args: any) {
return this.event.trigger(eventType, ...args);
}
getValue(ignoreCursor: boolean = false) {
const value = this.change.getValue({});
return ignoreCursor ? Selection.removeTags(value) : value;
}
async getValueAsync(
ignoreCursor: boolean = false,
callback?: (
name: string,
card?: CardInterface,
...args: any
) => boolean | number | void,
): Promise<string> {
return new Promise(async (resolve, reject) => {
// 编辑插件等待插件执行结果
const pluginNames = Object.keys(this.plugin.components);
for (let i = 0; i < pluginNames.length; i++) {
const plugin = this.plugin.components[pluginNames[i]];
const result = await new Promise((resolve) => {
if (plugin.waiting) {
plugin
.waiting(callback)
.then(() => resolve(true))
.catch(resolve);
} else resolve(true);
});
if (typeof result === 'object') {
reject(result);
return;
}
}
resolve(this.getValue(ignoreCursor));
});
}
getHtml(): string {
// 获取 container 节点
const node = $(this.container[0].cloneNode(true));
// 清除冗余属性
node.removeAttributes('contenteditable');
node.removeAttributes('tabindex');
node.removeAttributes('autocorrect');
node.removeAttributes('autocomplete');
node.removeAttributes('spellcheck');
node.removeAttributes('data-gramm');
node.removeAttributes('role');
return new Parser(node, this).toHTML();
}
setValue(value: string, callback?: (count: number) => void) {
value = this.trigger('beforeSetValue', value) || value;
this.change.setValue(value, undefined, callback);
this.normalize();
// 为顶级根节点创建 data-id
this.nodeId.generateAll(this.container);
// 返回 this 支持链式调用
return this;
}
setHtml(html: string, callback?: (count: number) => void) {
this.change.setHtml(html, (count) => {
this.container.allChildren(true).forEach((child) => {
if (this.node.isInline(child)) {
this.inline.repairCursor(child);
} else if (this.node.isMark(child)) {
this.mark.repairCursor(child);
}
if (callback) callback(count);
});
});
this.nodeId.generateAll(this.container);
return this;
}
setJsonValue(value: Array<any>, callback?: (count: number) => void) {
const dom = $(toDOM(value));
// 设置 container 的属性
const attributes = dom.get<Element>()?.attributes;
for (let i = 0; attributes && i < attributes.length; i++) {
const { nodeName, nodeValue } = attributes.item(i) || {};
if (
/^data-selection-/.test(nodeName || '') &&
nodeValue !== 'null'
) {
this.container.attributes(nodeName, nodeValue!);
}
}
// 设置 container html
const html = this.node.html(dom);
this.change.setValue(html, undefined, callback);
// 节点规范化的处理
this.normalize();
// 为顶级根节点创建 data-id
this.nodeId.generateAll(this.container);
return this;
}
getJsonValue() {
return toJSON0(this.container);
}
private normalize() {
let block = $('<p />');
// 保证所有行内元素都在段落内
let childNodes = this.container.children();
childNodes.each((_, index) => {
const node = childNodes.eq(index);
if (!node) return;
if (this.node.isBlock(node)) {
if (block.get<HTMLElement>()!.childNodes.length > 0) {
node.before(block);
}
block = $('<p />');
} else if (!node.isCursor()) {
block.append(node);
}
});
if (block.get<HTMLElement>()!.childNodes.length > 0) {
this.container.append(block);
}
// 处理空段落
childNodes = this.container.children();
childNodes.each((_, index) => {
const node = childNodes.eq(index);
if (!node) return;
this.node.removeMinusStyle(node, 'text-indent');
if (this.node.isRootBlock(node)) {
const childrenLength =
node.get<HTMLElement>()!.childNodes.length;
if (childrenLength === 0) {
node.append($('<br />'));
} else {
const child = node.first();
if (
childrenLength === 1 &&
child?.name === 'span' &&
[CURSOR, ANCHOR, FOCUS].indexOf(
child.attributes(DATA_ELEMENT),
) >= 0
) {
node.prepend($('<br />'));
}
}
}
});
}
messageSuccess(message: string) {
console.log(`success:${message}`);
}
messageError(error: string) {
console.log(`error:${error}`);
}
messageConfirm(message: string): Promise<boolean> {
console.log(`confirm:${message}`);
return Promise.reject(false);
}
showPlaceholder() {
this._container.showPlaceholder();
}
hidePlaceholder() {
this._container.hidePlaceholder();
}
destroy() {
this._container.destroy();
this.change.destroy();
this.hotkey.destroy();
this.card.destroy();
if (this.ot) {
this.ot.destroy();
}
}
}
export default Engine;
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
编辑 (opens new window)
上次更新: 2022/04/28, 23:58:26