@textbus/platform-browser 3.0.0-alpha.42 → 3.0.0-alpha.44

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/bundles/index.js CHANGED
@@ -5,103 +5,103 @@ var di = require('@tanbo/di');
5
5
  var core = require('@textbus/core');
6
6
  var stream = require('@tanbo/stream');
7
7
 
8
- function createElement(tagName, options = {}) {
9
- const el = document.createElement(tagName);
10
- if (options.classes) {
11
- el.classList.add(...options.classes);
12
- }
13
- if (options.attrs) {
14
- Object.keys(options.attrs).forEach(key => {
15
- el.setAttribute(key, options.attrs[key]);
16
- });
17
- }
18
- if (options.props) {
19
- Object.keys(options.props).forEach(key => {
20
- el[key] = options.props[key];
21
- });
22
- }
23
- if (options.styles) {
24
- Object.assign(el.style, options.styles);
25
- }
26
- if (options.children) {
27
- options.children.filter(i => i).forEach(item => {
28
- el.appendChild(item);
29
- });
30
- }
31
- if (options.on) {
32
- Object.keys(options.on).forEach(key => {
33
- el.addEventListener(key, options.on[key]);
34
- });
35
- }
36
- return el;
37
- }
38
- function createTextNode(content) {
39
- return document.createTextNode(content);
40
- }
41
- function getLayoutRectByRange(range) {
42
- let { startContainer, startOffset } = range;
43
- if (startContainer.nodeType === Node.TEXT_NODE) {
44
- if (startOffset > 0) {
45
- return range.getBoundingClientRect();
46
- }
47
- const parentNode = startContainer.parentNode;
48
- startOffset = Array.from(parentNode.childNodes).indexOf(startContainer);
49
- startContainer = parentNode;
50
- }
51
- const beforeNode = startContainer.childNodes[startOffset - 1];
52
- if (beforeNode) {
53
- if (beforeNode.nodeType === Node.ELEMENT_NODE && beforeNode.nodeName.toLowerCase() !== 'br') {
54
- const rect = beforeNode.getBoundingClientRect();
55
- return {
56
- left: rect.right,
57
- top: rect.top,
58
- width: rect.width,
59
- height: rect.height
60
- };
61
- }
62
- else if (beforeNode.nodeType === Node.TEXT_NODE) {
63
- const range2 = document.createRange();
64
- range2.setStart(beforeNode, beforeNode.textContent.length);
65
- range2.setEnd(beforeNode, beforeNode.textContent.length);
66
- return range2.getBoundingClientRect();
67
- }
68
- }
69
- const offsetNode = startContainer.childNodes[startOffset];
70
- let isInsertBefore = false;
71
- if (!offsetNode) {
72
- const lastChild = startContainer.lastChild;
73
- if (lastChild && lastChild.nodeType === Node.ELEMENT_NODE) {
74
- const rect = lastChild.getBoundingClientRect();
75
- return {
76
- left: rect.right,
77
- top: rect.top,
78
- width: rect.width,
79
- height: rect.height
80
- };
81
- }
82
- }
83
- if (offsetNode) {
84
- if (offsetNode.nodeType === Node.ELEMENT_NODE && offsetNode.nodeName.toLowerCase() !== 'br') {
85
- return offsetNode.getBoundingClientRect();
86
- }
87
- isInsertBefore = true;
88
- }
89
- const span = startContainer.ownerDocument.createElement('span');
90
- span.innerText = '\u200b';
91
- span.style.display = 'inline-block';
92
- if (isInsertBefore) {
93
- startContainer.insertBefore(span, offsetNode);
94
- }
95
- else {
96
- startContainer.appendChild(span);
97
- }
98
- const rect = span.getBoundingClientRect();
99
- startContainer.removeChild(span);
100
- return rect;
8
+ function createElement(tagName, options = {}) {
9
+ const el = document.createElement(tagName);
10
+ if (options.classes) {
11
+ el.classList.add(...options.classes);
12
+ }
13
+ if (options.attrs) {
14
+ Object.keys(options.attrs).forEach(key => {
15
+ el.setAttribute(key, options.attrs[key]);
16
+ });
17
+ }
18
+ if (options.props) {
19
+ Object.keys(options.props).forEach(key => {
20
+ el[key] = options.props[key];
21
+ });
22
+ }
23
+ if (options.styles) {
24
+ Object.assign(el.style, options.styles);
25
+ }
26
+ if (options.children) {
27
+ options.children.filter(i => i).forEach(item => {
28
+ el.appendChild(item);
29
+ });
30
+ }
31
+ if (options.on) {
32
+ Object.keys(options.on).forEach(key => {
33
+ el.addEventListener(key, options.on[key]);
34
+ });
35
+ }
36
+ return el;
37
+ }
38
+ function createTextNode(content) {
39
+ return document.createTextNode(content);
40
+ }
41
+ function getLayoutRectByRange(range) {
42
+ let { startContainer, startOffset } = range;
43
+ if (startContainer.nodeType === Node.TEXT_NODE) {
44
+ if (startOffset > 0) {
45
+ return range.getBoundingClientRect();
46
+ }
47
+ const parentNode = startContainer.parentNode;
48
+ startOffset = Array.from(parentNode.childNodes).indexOf(startContainer);
49
+ startContainer = parentNode;
50
+ }
51
+ const beforeNode = startContainer.childNodes[startOffset - 1];
52
+ if (beforeNode) {
53
+ if (beforeNode.nodeType === Node.ELEMENT_NODE && beforeNode.nodeName.toLowerCase() !== 'br') {
54
+ const rect = beforeNode.getBoundingClientRect();
55
+ return {
56
+ left: rect.right,
57
+ top: rect.top,
58
+ width: rect.width,
59
+ height: rect.height
60
+ };
61
+ }
62
+ else if (beforeNode.nodeType === Node.TEXT_NODE) {
63
+ const range2 = document.createRange();
64
+ range2.setStart(beforeNode, beforeNode.textContent.length);
65
+ range2.setEnd(beforeNode, beforeNode.textContent.length);
66
+ return range2.getBoundingClientRect();
67
+ }
68
+ }
69
+ const offsetNode = startContainer.childNodes[startOffset];
70
+ let isInsertBefore = false;
71
+ if (!offsetNode) {
72
+ const lastChild = startContainer.lastChild;
73
+ if (lastChild && lastChild.nodeType === Node.ELEMENT_NODE) {
74
+ const rect = lastChild.getBoundingClientRect();
75
+ return {
76
+ left: rect.right,
77
+ top: rect.top,
78
+ width: rect.width,
79
+ height: rect.height
80
+ };
81
+ }
82
+ }
83
+ if (offsetNode) {
84
+ if (offsetNode.nodeType === Node.ELEMENT_NODE && offsetNode.nodeName.toLowerCase() !== 'br') {
85
+ return offsetNode.getBoundingClientRect();
86
+ }
87
+ isInsertBefore = true;
88
+ }
89
+ const span = startContainer.ownerDocument.createElement('span');
90
+ span.innerText = '\u200b';
91
+ span.style.display = 'inline-block';
92
+ if (isInsertBefore) {
93
+ startContainer.insertBefore(span, offsetNode);
94
+ }
95
+ else {
96
+ startContainer.appendChild(span);
97
+ }
98
+ const rect = span.getBoundingClientRect();
99
+ startContainer.removeChild(span);
100
+ return rect;
101
101
  }
102
102
 
103
- const isWindows = () => /win(dows|32|64)/i.test(navigator.userAgent);
104
- const isMac = () => /mac os/i.test(navigator.userAgent);
103
+ const isWindows = () => /win(dows|32|64)/i.test(navigator.userAgent);
104
+ const isMac = () => /mac os/i.test(navigator.userAgent);
105
105
  const isSafari = () => /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
106
106
 
107
107
  /******************************************************************************
@@ -144,2534 +144,2544 @@ function __awaiter(thisArg, _arguments, P, generator) {
144
144
  });
145
145
  }
146
146
 
147
- /**
148
- * 编辑器可选项依赖注入 token
149
- */
150
- const EDITOR_OPTIONS = new di.InjectionToken('EDITOR_OPTIONS');
151
- /**
152
- * 编辑器容器依赖注入 token
153
- */
154
- const VIEW_CONTAINER = new di.InjectionToken('VIEW_CONTAINER');
155
- /**
156
- * 编辑器容器依赖注入 token
157
- */
158
- const VIEW_DOCUMENT = new di.InjectionToken('VIEW_DOCUMENT');
159
- /**
160
- * 编辑器容器遮罩层 token
161
- */
147
+ /**
148
+ * 编辑器可选项依赖注入 token
149
+ */
150
+ const EDITOR_OPTIONS = new di.InjectionToken('EDITOR_OPTIONS');
151
+ /**
152
+ * 编辑器容器依赖注入 token
153
+ */
154
+ const VIEW_CONTAINER = new di.InjectionToken('VIEW_CONTAINER');
155
+ /**
156
+ * 编辑器容器依赖注入 token
157
+ */
158
+ const VIEW_DOCUMENT = new di.InjectionToken('VIEW_DOCUMENT');
159
+ /**
160
+ * 编辑器容器遮罩层 token
161
+ */
162
162
  const VIEW_MASK = new di.InjectionToken('VIEW_MASK');
163
163
 
164
- class Input {
164
+ class Input {
165
165
  }
166
166
 
167
- /**
168
- * Textbus PC 端选区桥接实现
169
- */
170
- exports.SelectionBridge = class SelectionBridge {
171
- constructor(config, injector, controller, selection, rootComponentRef, input, renderer) {
172
- this.config = config;
173
- this.injector = injector;
174
- this.controller = controller;
175
- this.selection = selection;
176
- this.rootComponentRef = rootComponentRef;
177
- this.input = input;
178
- this.renderer = renderer;
179
- this.nativeSelection = document.getSelection();
180
- this.selectionMaskElement = createElement('style');
181
- this.selectionChangeEvent = new stream.Subject();
182
- this.subs = [];
183
- this.connector = null;
184
- this.ignoreSelectionChange = false;
185
- this.changeFromUser = false;
186
- this.docContainer = injector.get(VIEW_DOCUMENT);
187
- this.maskContainer = injector.get(VIEW_MASK);
188
- this.onSelectionChange = this.selectionChangeEvent.asObservable().pipe(stream.filter(() => {
189
- return !controller.readonly;
190
- }));
191
- document.head.appendChild(this.selectionMaskElement);
192
- this.sub = this.onSelectionChange.subscribe((r) => {
193
- if (r) {
194
- input.focus(r, this.changeFromUser);
195
- }
196
- else {
197
- input.blur();
198
- }
199
- });
200
- this.sub.add(stream.fromEvent(document, 'focusin').subscribe(ev => {
201
- let target = ev.target;
202
- if (/^(input|textarea|select)$/i.test(target.nodeName)) {
203
- if (target.tagName.toLowerCase() === 'input' && /^(range|date)$/.test(target.type)) {
204
- return;
205
- }
206
- this.ignoreSelectionChange = true;
207
- return;
208
- }
209
- if (!config.useContentEditable) {
210
- while (target) {
211
- if (target.contentEditable === 'true') {
212
- this.ignoreSelectionChange = true;
213
- return;
214
- }
215
- target = target.parentNode;
216
- }
217
- }
218
- }));
219
- this.sub.add(stream.fromEvent(document, 'focusout').subscribe(() => {
220
- this.ignoreSelectionChange = false;
221
- }));
222
- }
223
- connect(connector) {
224
- this.disConnect();
225
- this.connector = connector;
226
- this.syncSelection(connector);
227
- this.listen(connector);
228
- }
229
- disConnect() {
230
- this.connector = null;
231
- this.unListen();
232
- }
233
- getRect(location) {
234
- const { focus, anchor } = this.getPositionByRange({
235
- focusOffset: location.offset,
236
- anchorOffset: location.offset,
237
- focusSlot: location.slot,
238
- anchorSlot: location.slot
239
- });
240
- if (!focus || !anchor) {
241
- return null;
242
- }
243
- const nativeRange = document.createRange();
244
- nativeRange.setStart(focus.node, focus.offset);
245
- nativeRange.collapse();
246
- return getLayoutRectByRange(nativeRange);
247
- }
248
- restore(abstractSelection, formLocal) {
249
- this.changeFromUser = formLocal;
250
- if (this.ignoreSelectionChange || !this.connector) {
251
- return;
252
- }
253
- this.unListen();
254
- if (!abstractSelection) {
255
- this.nativeSelection.removeAllRanges();
256
- this.selectionChangeEvent.next(null);
257
- this.listen(this.connector);
258
- return;
259
- }
260
- const { focus, anchor } = this.getPositionByRange(abstractSelection);
261
- if (!focus || !anchor) {
262
- this.nativeSelection.removeAllRanges();
263
- this.selectionChangeEvent.next(null);
264
- this.listen(this.connector);
265
- return;
266
- }
267
- this.nativeSelection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
268
- if (this.nativeSelection.rangeCount) {
269
- const nativeRange = this.nativeSelection.getRangeAt(0);
270
- this.selectionChangeEvent.next(nativeRange);
271
- }
272
- else {
273
- this.selectionChangeEvent.next(null);
274
- }
275
- // hack start 浏览器会触发上面选区更改事件
276
- const bind = () => {
277
- if (this.connector) {
278
- this.listen(this.connector);
279
- }
280
- };
281
- if (typeof requestIdleCallback === 'function') {
282
- requestIdleCallback(bind);
283
- }
284
- else {
285
- setTimeout(bind, 30);
286
- }
287
- // hack end
288
- }
289
- destroy() {
290
- this.sub.unsubscribe();
291
- }
292
- getPositionByRange(abstractSelection) {
293
- let focus;
294
- let anchor;
295
- try {
296
- focus = this.findSelectedNodeAndOffset(abstractSelection.focusSlot, abstractSelection.focusOffset);
297
- anchor = focus;
298
- if (abstractSelection.anchorSlot !== abstractSelection.focusSlot ||
299
- abstractSelection.anchorOffset !== abstractSelection.focusOffset) {
300
- anchor = this.findSelectedNodeAndOffset(abstractSelection.anchorSlot, abstractSelection.anchorOffset);
301
- }
302
- return {
303
- focus,
304
- anchor
305
- };
306
- }
307
- catch (e) {
308
- return {
309
- focus: null,
310
- anchor: null
311
- };
312
- }
313
- }
314
- getPreviousLinePositionByCurrent(position) {
315
- return this.getLinePosition(position, false);
316
- }
317
- getNextLinePositionByCurrent(position) {
318
- return this.getLinePosition(position, true);
319
- }
320
- // private getLinePosition(currentPosition: SelectionPosition, toNext: boolean): SelectionPosition | null {
321
- // clearTimeout(this.cacheCaretPositionTimer)
322
- // let p: SelectionPosition | null
323
- // if (this.oldCaretPosition) {
324
- // p = this.caretRangeFromPoint(currentPosition, this.oldCaretPosition.left, toNext)
325
- // } else {
326
- // this.oldCaretPosition = this.getRect(currentPosition)!
327
- // p = this.caretRangeFromPoint(currentPosition, this.oldCaretPosition.left, toNext)
328
- // }
329
- // this.cacheCaretPositionTimer = setTimeout(() => {
330
- // this.oldCaretPosition = null
331
- // }, 3000)
332
- // return p
333
- // }
334
- //
335
- // private caretRangeFromPoint(currentPosition: SelectionPosition, x: number, toNext: boolean): SelectionPosition | null {
336
- // const rect = this.getRect(currentPosition)!
337
- // const fn = document.caretRangeFromPoint || function (x: number, y: number) {
338
- // const range = (document as any).caretPositionFromPoint(x, y)
339
- // return {
340
- // startContainer: range.offsetNode,
341
- // startOffset: range.offset
342
- // }
343
- // }
344
- //
345
- // const current = fn.call(document, rect.left, rect.top)!
346
- //
347
- // let startTop = toNext ? rect.top + rect.height : rect.top
348
- // const step = toNext ? 5 : -5
349
- // while (true) {
350
- // startTop += step
351
- // const newPosition = fn.call(document, x, startTop)
352
- // if (!newPosition) {
353
- // return toNext ?
354
- // this.selection.findLastPosition(this.rootComponentRef.component.slots.last, true) :
355
- // this.selection.findFirstPosition(this.rootComponentRef.component.slots.first, true)
356
- // }
357
- // if (newPosition.startContainer !== current.startContainer || newPosition.startOffset !== current.startOffset) {
358
- // return this.getCorrectedPosition(newPosition.startContainer, newPosition.startOffset, toNext)
359
- // }
360
- // }
361
- // return null
362
- // }
363
- getLinePosition(currentPosition, toNext) {
364
- clearTimeout(this.cacheCaretPositionTimer);
365
- let p;
366
- if (this.oldCaretPosition) {
367
- p = toNext ?
368
- this.getNextLinePositionByOffset(currentPosition, this.oldCaretPosition.left) :
369
- this.getPreviousLinePositionByOffset(currentPosition, this.oldCaretPosition.left);
370
- }
371
- else {
372
- this.oldCaretPosition = this.getRect(currentPosition);
373
- p = toNext ?
374
- this.getNextLinePositionByOffset(currentPosition, this.oldCaretPosition.left) :
375
- this.getPreviousLinePositionByOffset(currentPosition, this.oldCaretPosition.left);
376
- }
377
- this.cacheCaretPositionTimer = setTimeout(() => {
378
- this.oldCaretPosition = null;
379
- }, 3000);
380
- return p;
381
- }
382
- /**
383
- * 获取选区向上移动一行的位置。
384
- * @param currentPosition
385
- * @param startLeft 参考位置。
386
- */
387
- getPreviousLinePositionByOffset(currentPosition, startLeft) {
388
- let isToPrevLine = false;
389
- let loopCount = 0;
390
- let minLeft = startLeft;
391
- let focusSlot = currentPosition.slot;
392
- let focusOffset = currentPosition.offset;
393
- let minTop = this.getRect({
394
- slot: focusSlot,
395
- offset: focusOffset
396
- }).top;
397
- let position;
398
- let oldPosition;
399
- let oldLeft = 0;
400
- while (true) {
401
- loopCount++;
402
- position = this.selection.getPreviousPositionByPosition(focusSlot, focusOffset);
403
- focusSlot = position.slot;
404
- focusOffset = position.offset;
405
- const rect2 = this.getRect(position);
406
- if (!isToPrevLine) {
407
- if (rect2.left > minLeft || rect2.top + rect2.height <= minTop) {
408
- isToPrevLine = true;
409
- }
410
- else if (rect2.left === minLeft && rect2.top === minTop) {
411
- return position;
412
- }
413
- minLeft = rect2.left;
414
- minTop = rect2.top;
415
- }
416
- if (isToPrevLine) {
417
- if (rect2.left < startLeft) {
418
- return position;
419
- }
420
- if (oldPosition) {
421
- if (rect2.left >= oldLeft) {
422
- return oldPosition;
423
- }
424
- }
425
- oldLeft = rect2.left;
426
- oldPosition = position;
427
- }
428
- if (loopCount > 10000) {
429
- break;
430
- }
431
- }
432
- return position || {
433
- offset: 0,
434
- slot: focusSlot
435
- };
436
- }
437
- /**
438
- * 获取选区向下移动一行的位置。
439
- * @param currentPosition
440
- * @param startLeft 参考位置。
441
- */
442
- getNextLinePositionByOffset(currentPosition, startLeft) {
443
- let isToNextLine = false;
444
- let loopCount = 0;
445
- let maxRight = startLeft;
446
- let focusSlot = currentPosition.slot;
447
- let focusOffset = currentPosition.offset;
448
- const rect = this.getRect({
449
- slot: focusSlot,
450
- offset: focusOffset
451
- });
452
- let minTop = rect.top;
453
- let oldPosition;
454
- let oldLeft = 0;
455
- while (true) {
456
- loopCount++;
457
- const position = this.selection.getNextPositionByPosition(focusSlot, focusOffset);
458
- focusSlot = position.slot;
459
- focusOffset = position.offset;
460
- const rect2 = this.getRect(position);
461
- if (!isToNextLine) {
462
- if (rect2.left < maxRight || rect2.top >= minTop + rect.height) {
463
- isToNextLine = true;
464
- }
465
- else if (rect2.left === maxRight && rect2.top === minTop) {
466
- return position;
467
- }
468
- maxRight = rect2.left;
469
- minTop = rect2.top;
470
- oldPosition = position;
471
- }
472
- if (isToNextLine) {
473
- if (rect2.left > startLeft) {
474
- return oldPosition;
475
- }
476
- if (oldPosition) {
477
- if (rect2.left <= oldLeft) {
478
- return oldPosition;
479
- }
480
- }
481
- oldPosition = position;
482
- oldLeft = rect2.left;
483
- }
484
- if (loopCount > 10000) {
485
- break;
486
- }
487
- }
488
- return oldPosition || {
489
- offset: focusSlot.length,
490
- slot: focusSlot
491
- };
492
- }
493
- unListen() {
494
- this.subs.forEach(i => i.unsubscribe());
495
- this.subs = [];
496
- }
497
- listen(connector) {
498
- if (!this.config.useContentEditable) {
499
- const selection = this.nativeSelection;
500
- this.subs.push(stream.fromEvent(this.docContainer, 'mousedown').subscribe(ev => {
501
- if (this.ignoreSelectionChange || ev.button === 2) {
502
- return;
503
- }
504
- if (!ev.shiftKey) {
505
- selection.removeAllRanges();
506
- }
507
- }));
508
- }
509
- this.subs.push(stream.fromEvent(document, 'selectionchange').subscribe(() => {
510
- this.syncSelection(connector);
511
- }));
512
- }
513
- syncSelection(connector) {
514
- var _a;
515
- const selection = this.nativeSelection;
516
- this.changeFromUser = true;
517
- if (this.ignoreSelectionChange ||
518
- this.input.composition ||
519
- selection.rangeCount === 0 ||
520
- !this.docContainer.contains(selection.anchorNode) ||
521
- this.rootComponentRef.component.slots.length === 0) {
522
- return;
523
- }
524
- const rawRange = selection.getRangeAt(0);
525
- const nativeRange = rawRange.cloneRange();
526
- const isFocusEnd = selection.focusNode === nativeRange.endContainer && selection.focusOffset === nativeRange.endOffset;
527
- const isFocusStart = selection.focusNode === nativeRange.startContainer && selection.focusOffset === nativeRange.startOffset;
528
- if (!this.docContainer.contains(selection.focusNode)) {
529
- if (isFocusEnd) {
530
- const vEle = this.renderer.getVNodeBySlot(this.rootComponentRef.component.slots.first);
531
- if (!vEle) {
532
- return;
533
- }
534
- const nativeNode = this.renderer.getNativeNodeByVNode(vEle);
535
- if (!nativeNode) {
536
- return;
537
- }
538
- nativeRange.setEndAfter(nativeNode.lastChild);
539
- }
540
- else {
541
- const vEle = this.renderer.getVNodeBySlot(this.rootComponentRef.component.slots.last);
542
- if (!vEle) {
543
- return;
544
- }
545
- const nativeNode = this.renderer.getNativeNodeByVNode(vEle);
546
- if (!nativeNode) {
547
- return;
548
- }
549
- nativeRange.setStartBefore(nativeNode.firstChild);
550
- }
551
- }
552
- const startPosition = this.getCorrectedPosition(nativeRange.startContainer, nativeRange.startOffset, isFocusStart);
553
- const endPosition = nativeRange.collapsed ?
554
- startPosition :
555
- this.getCorrectedPosition(nativeRange.endContainer, nativeRange.endOffset, isFocusEnd);
556
- if ([Node.ELEMENT_NODE, Node.TEXT_NODE].includes((_a = nativeRange.commonAncestorContainer) === null || _a === void 0 ? void 0 : _a.nodeType) &&
557
- startPosition && endPosition) {
558
- const abstractSelection = isFocusEnd ? {
559
- anchorSlot: startPosition.slot,
560
- anchorOffset: startPosition.offset,
561
- focusSlot: endPosition.slot,
562
- focusOffset: endPosition.offset
563
- } : {
564
- focusSlot: startPosition.slot,
565
- focusOffset: startPosition.offset,
566
- anchorSlot: endPosition.slot,
567
- anchorOffset: endPosition.offset
568
- };
569
- const { focus, anchor } = this.getPositionByRange(abstractSelection);
570
- if (focus && anchor) {
571
- let start = anchor;
572
- let end = focus;
573
- if (isFocusStart) {
574
- start = focus;
575
- end = anchor;
576
- }
577
- if (nativeRange.startContainer !== start.node || nativeRange.startOffset !== start.offset) {
578
- nativeRange.setStart(start.node, start.offset);
579
- }
580
- if (nativeRange.endContainer !== end.node || nativeRange.endOffset !== end.offset) {
581
- nativeRange.setEnd(end.node, end.offset);
582
- }
583
- connector.setSelection(abstractSelection);
584
- if (selection.isCollapsed) {
585
- rawRange.setStart(start.node, start.offset);
586
- rawRange.setEnd(end.node, end.offset);
587
- }
588
- this.selectionChangeEvent.next(nativeRange);
589
- }
590
- else {
591
- connector.setSelection(null);
592
- }
593
- return;
594
- }
595
- connector.setSelection(null);
596
- }
597
- findSelectedNodeAndOffset(slot, offset) {
598
- const prev = slot.getContentAtIndex(offset - 1);
599
- const vNodes = this.renderer.getVNodesBySlot(slot);
600
- if (prev) {
601
- if (typeof prev !== 'string') {
602
- const vNode = this.renderer.getVNodeByComponent(prev);
603
- const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
604
- return {
605
- node: nativeNode.parentNode,
606
- offset: Array.from(nativeNode.parentNode.childNodes).indexOf(nativeNode) + 1
607
- };
608
- }
609
- else if (prev === '\n') {
610
- for (const vNode of vNodes) {
611
- if (vNode instanceof core.VTextNode) {
612
- continue;
613
- }
614
- if (vNode.tagName === 'br') {
615
- const position = this.renderer.getLocationByVNode(vNode);
616
- if (position) {
617
- if (position.endIndex === offset) {
618
- const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
619
- const parentNode = nativeNode.parentNode;
620
- return {
621
- node: parentNode,
622
- offset: Array.from(parentNode.childNodes).indexOf(nativeNode) + 1
623
- };
624
- }
625
- }
626
- }
627
- }
628
- }
629
- }
630
- const current = slot.getContentAtIndex(offset);
631
- if (current && typeof current !== 'string') {
632
- const vNode = this.renderer.getVNodeByComponent(current);
633
- const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
634
- return {
635
- node: nativeNode.parentNode,
636
- offset: Array.from(nativeNode.parentNode.childNodes).indexOf(nativeNode)
637
- };
638
- }
639
- for (const vNode of vNodes) {
640
- if (vNode instanceof core.VElement) {
641
- if (vNode.tagName === 'br') {
642
- const position = this.renderer.getLocationByVNode(vNode);
643
- if (position) {
644
- if (position.startIndex === offset) {
645
- const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
646
- const parentNode = nativeNode.parentNode;
647
- return {
648
- node: parentNode,
649
- offset: Array.from(parentNode.childNodes).indexOf(nativeNode)
650
- };
651
- }
652
- }
653
- }
654
- continue;
655
- }
656
- const position = this.renderer.getLocationByVNode(vNode);
657
- if (position) {
658
- if (offset >= position.startIndex && offset <= position.endIndex) {
659
- const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
660
- return {
661
- node: nativeNode,
662
- offset: offset - position.startIndex
663
- };
664
- }
665
- }
666
- }
667
- return null;
668
- }
669
- getCorrectedPosition(node, offset, toAfter, excludeNodes = []) {
670
- excludeNodes.push(node);
671
- if (node.nodeType === Node.ELEMENT_NODE) {
672
- const containerPosition = this.renderer.getLocationByNativeNode(node);
673
- const childNode = node.childNodes[offset];
674
- if (childNode) {
675
- const childPosition = this.renderer.getLocationByNativeNode(childNode);
676
- if (childPosition) {
677
- if (containerPosition) {
678
- return {
679
- slot: childPosition.slot,
680
- offset: childPosition.startIndex
681
- };
682
- }
683
- return this.findFocusNode(childNode, toAfter, excludeNodes);
684
- }
685
- return this.findFocusNode(childNode, toAfter, excludeNodes);
686
- }
687
- const prevNode = node.childNodes[offset - 1];
688
- if (prevNode) {
689
- const prevPosition = this.renderer.getLocationByNativeNode(prevNode);
690
- if (prevPosition && containerPosition) {
691
- return {
692
- slot: prevPosition.slot,
693
- offset: prevPosition.endIndex
694
- };
695
- }
696
- }
697
- if (containerPosition) {
698
- return {
699
- slot: containerPosition.slot,
700
- offset: containerPosition.endIndex
701
- };
702
- }
703
- const nextNode = toAfter ? node.nextSibling : node.previousSibling;
704
- if (nextNode) {
705
- return this.findFocusNode(nextNode, toAfter, excludeNodes);
706
- }
707
- return this.findFocusNodeByParent(node, toAfter, excludeNodes);
708
- }
709
- else if (node.nodeType === Node.TEXT_NODE) {
710
- const containerPosition = this.renderer.getLocationByNativeNode(node);
711
- if (containerPosition) {
712
- return {
713
- slot: containerPosition.slot,
714
- offset: containerPosition.startIndex + offset
715
- };
716
- }
717
- const nextNode = toAfter ? node.nextSibling : node.previousSibling;
718
- if (nextNode) {
719
- return this.findFocusNode(nextNode, toAfter, excludeNodes);
720
- }
721
- return this.findFocusNodeByParent(node, toAfter, excludeNodes);
722
- }
723
- return null;
724
- }
725
- findFocusNode(node, toAfter = false, excludeNodes = []) {
726
- if (excludeNodes.includes(node)) {
727
- const next = toAfter ? node.nextSibling : node.previousSibling;
728
- if (next) {
729
- return this.findFocusNode(next, toAfter, excludeNodes);
730
- }
731
- return this.findFocusNodeByParent(node, toAfter, excludeNodes);
732
- }
733
- excludeNodes.push(node);
734
- const position = this.renderer.getLocationByNativeNode(node);
735
- if (position) {
736
- return {
737
- slot: position.slot,
738
- offset: toAfter ? position.startIndex : position.endIndex
739
- };
740
- }
741
- const firstChild = toAfter ? node.firstChild : node.lastChild;
742
- if (firstChild) {
743
- return this.findFocusNode(firstChild, toAfter, excludeNodes);
744
- }
745
- const nextSibling = toAfter ? node.nextSibling : node.previousSibling;
746
- if (nextSibling) {
747
- return this.findFocusNode(nextSibling, toAfter, excludeNodes);
748
- }
749
- return this.findFocusNodeByParent(node, toAfter, excludeNodes);
750
- }
751
- findFocusNodeByParent(node, toAfter, excludeNodes) {
752
- const parentNode = node.parentNode;
753
- if (parentNode) {
754
- const parentPosition = this.renderer.getLocationByNativeNode(parentNode);
755
- if (parentPosition) {
756
- return {
757
- slot: parentPosition.slot,
758
- offset: toAfter ? parentPosition.endIndex : parentPosition.startIndex
759
- };
760
- }
761
- excludeNodes.push(node);
762
- return this.findFocusNode(parentNode, toAfter, excludeNodes);
763
- }
764
- return null;
765
- }
766
- };
767
- exports.SelectionBridge = __decorate([
768
- di.Injectable(),
769
- __param(0, di.Inject(EDITOR_OPTIONS)),
770
- __metadata("design:paramtypes", [Object, di.Injector,
771
- core.Controller,
772
- core.Selection,
773
- core.RootComponentRef,
774
- Input,
775
- core.Renderer])
167
+ /**
168
+ * Textbus PC 端选区桥接实现
169
+ */
170
+ exports.SelectionBridge = class SelectionBridge {
171
+ constructor(config, injector, controller, selection, rootComponentRef, input, renderer) {
172
+ this.config = config;
173
+ this.injector = injector;
174
+ this.controller = controller;
175
+ this.selection = selection;
176
+ this.rootComponentRef = rootComponentRef;
177
+ this.input = input;
178
+ this.renderer = renderer;
179
+ this.nativeSelection = document.getSelection();
180
+ this.selectionMaskElement = createElement('style');
181
+ this.selectionChangeEvent = new stream.Subject();
182
+ this.subs = [];
183
+ this.connector = null;
184
+ this.ignoreSelectionChange = false;
185
+ this.changeFromUser = false;
186
+ this.docContainer = injector.get(VIEW_DOCUMENT);
187
+ this.maskContainer = injector.get(VIEW_MASK);
188
+ this.onSelectionChange = this.selectionChangeEvent.asObservable().pipe(stream.filter(() => {
189
+ return !controller.readonly;
190
+ }));
191
+ document.head.appendChild(this.selectionMaskElement);
192
+ this.sub = this.onSelectionChange.subscribe((r) => {
193
+ if (r) {
194
+ input.focus(r, this.changeFromUser);
195
+ }
196
+ else {
197
+ input.blur();
198
+ }
199
+ });
200
+ this.sub.add(stream.fromEvent(document, 'focusin').subscribe(ev => {
201
+ let target = ev.target;
202
+ if (/^(input|textarea|select)$/i.test(target.nodeName)) {
203
+ if (target.tagName.toLowerCase() === 'input' && /^(range|date)$/.test(target.type)) {
204
+ return;
205
+ }
206
+ this.ignoreSelectionChange = true;
207
+ return;
208
+ }
209
+ if (!config.useContentEditable) {
210
+ while (target) {
211
+ if (target.contentEditable === 'true') {
212
+ this.ignoreSelectionChange = true;
213
+ return;
214
+ }
215
+ target = target.parentNode;
216
+ }
217
+ }
218
+ }));
219
+ this.sub.add(stream.fromEvent(document, 'focusout').subscribe(() => {
220
+ this.ignoreSelectionChange = false;
221
+ }));
222
+ }
223
+ connect(connector) {
224
+ this.disConnect();
225
+ this.connector = connector;
226
+ this.syncSelection(connector);
227
+ this.listen(connector);
228
+ }
229
+ disConnect() {
230
+ this.connector = null;
231
+ this.unListen();
232
+ }
233
+ getRect(location) {
234
+ const { focus, anchor } = this.getPositionByRange({
235
+ focusOffset: location.offset,
236
+ anchorOffset: location.offset,
237
+ focusSlot: location.slot,
238
+ anchorSlot: location.slot
239
+ });
240
+ if (!focus || !anchor) {
241
+ return null;
242
+ }
243
+ const nativeRange = document.createRange();
244
+ nativeRange.setStart(focus.node, focus.offset);
245
+ nativeRange.collapse();
246
+ return getLayoutRectByRange(nativeRange);
247
+ }
248
+ restore(abstractSelection, formLocal) {
249
+ this.changeFromUser = formLocal;
250
+ if (this.ignoreSelectionChange || !this.connector) {
251
+ return;
252
+ }
253
+ this.unListen();
254
+ if (!abstractSelection) {
255
+ this.nativeSelection.removeAllRanges();
256
+ this.selectionChangeEvent.next(null);
257
+ this.listen(this.connector);
258
+ return;
259
+ }
260
+ const { focus, anchor } = this.getPositionByRange(abstractSelection);
261
+ if (!focus || !anchor) {
262
+ this.nativeSelection.removeAllRanges();
263
+ this.selectionChangeEvent.next(null);
264
+ this.listen(this.connector);
265
+ return;
266
+ }
267
+ this.nativeSelection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
268
+ if (this.nativeSelection.rangeCount) {
269
+ const nativeRange = this.nativeSelection.getRangeAt(0);
270
+ this.selectionChangeEvent.next(nativeRange);
271
+ }
272
+ else {
273
+ this.selectionChangeEvent.next(null);
274
+ }
275
+ // hack start 浏览器会触发上面选区更改事件
276
+ const bind = () => {
277
+ if (this.connector) {
278
+ this.listen(this.connector);
279
+ }
280
+ };
281
+ if (typeof requestIdleCallback === 'function') {
282
+ requestIdleCallback(bind);
283
+ }
284
+ else {
285
+ setTimeout(bind, 30);
286
+ }
287
+ // hack end
288
+ }
289
+ destroy() {
290
+ this.sub.unsubscribe();
291
+ }
292
+ getPositionByRange(abstractSelection) {
293
+ let focus;
294
+ let anchor;
295
+ try {
296
+ focus = this.findSelectedNodeAndOffset(abstractSelection.focusSlot, abstractSelection.focusOffset);
297
+ anchor = focus;
298
+ if (abstractSelection.anchorSlot !== abstractSelection.focusSlot ||
299
+ abstractSelection.anchorOffset !== abstractSelection.focusOffset) {
300
+ anchor = this.findSelectedNodeAndOffset(abstractSelection.anchorSlot, abstractSelection.anchorOffset);
301
+ }
302
+ return {
303
+ focus,
304
+ anchor
305
+ };
306
+ }
307
+ catch (e) {
308
+ return {
309
+ focus: null,
310
+ anchor: null
311
+ };
312
+ }
313
+ }
314
+ getPreviousLinePositionByCurrent(position) {
315
+ return this.getLinePosition(position, false);
316
+ }
317
+ getNextLinePositionByCurrent(position) {
318
+ return this.getLinePosition(position, true);
319
+ }
320
+ // private getLinePosition(currentPosition: SelectionPosition, toNext: boolean): SelectionPosition | null {
321
+ // clearTimeout(this.cacheCaretPositionTimer)
322
+ // let p: SelectionPosition | null
323
+ // if (this.oldCaretPosition) {
324
+ // p = this.caretRangeFromPoint(currentPosition, this.oldCaretPosition.left, toNext)
325
+ // } else {
326
+ // this.oldCaretPosition = this.getRect(currentPosition)!
327
+ // p = this.caretRangeFromPoint(currentPosition, this.oldCaretPosition.left, toNext)
328
+ // }
329
+ // this.cacheCaretPositionTimer = setTimeout(() => {
330
+ // this.oldCaretPosition = null
331
+ // }, 3000)
332
+ // return p
333
+ // }
334
+ //
335
+ // private caretRangeFromPoint(currentPosition: SelectionPosition, x: number, toNext: boolean): SelectionPosition | null {
336
+ // const rect = this.getRect(currentPosition)!
337
+ // const fn = document.caretRangeFromPoint || function (x: number, y: number) {
338
+ // const range = (document as any).caretPositionFromPoint(x, y)
339
+ // return {
340
+ // startContainer: range.offsetNode,
341
+ // startOffset: range.offset
342
+ // }
343
+ // }
344
+ //
345
+ // const current = fn.call(document, rect.left, rect.top)!
346
+ //
347
+ // let startTop = toNext ? rect.top + rect.height : rect.top
348
+ // const step = toNext ? 5 : -5
349
+ // while (true) {
350
+ // startTop += step
351
+ // const newPosition = fn.call(document, x, startTop)
352
+ // if (!newPosition) {
353
+ // return toNext ?
354
+ // this.selection.findLastPosition(this.rootComponentRef.component.slots.last, true) :
355
+ // this.selection.findFirstPosition(this.rootComponentRef.component.slots.first, true)
356
+ // }
357
+ // if (newPosition.startContainer !== current.startContainer || newPosition.startOffset !== current.startOffset) {
358
+ // return this.getCorrectedPosition(newPosition.startContainer, newPosition.startOffset, toNext)
359
+ // }
360
+ // }
361
+ // return null
362
+ // }
363
+ getLinePosition(currentPosition, toNext) {
364
+ clearTimeout(this.cacheCaretPositionTimer);
365
+ let p;
366
+ if (this.oldCaretPosition) {
367
+ p = toNext ?
368
+ this.getNextLinePositionByOffset(currentPosition, this.oldCaretPosition.left) :
369
+ this.getPreviousLinePositionByOffset(currentPosition, this.oldCaretPosition.left);
370
+ }
371
+ else {
372
+ this.oldCaretPosition = this.getRect(currentPosition);
373
+ p = toNext ?
374
+ this.getNextLinePositionByOffset(currentPosition, this.oldCaretPosition.left) :
375
+ this.getPreviousLinePositionByOffset(currentPosition, this.oldCaretPosition.left);
376
+ }
377
+ this.cacheCaretPositionTimer = setTimeout(() => {
378
+ this.oldCaretPosition = null;
379
+ }, 3000);
380
+ return p;
381
+ }
382
+ /**
383
+ * 获取选区向上移动一行的位置。
384
+ * @param currentPosition
385
+ * @param startLeft 参考位置。
386
+ */
387
+ getPreviousLinePositionByOffset(currentPosition, startLeft) {
388
+ let isToPrevLine = false;
389
+ let loopCount = 0;
390
+ let minLeft = startLeft;
391
+ let focusSlot = currentPosition.slot;
392
+ let focusOffset = currentPosition.offset;
393
+ let minTop = this.getRect({
394
+ slot: focusSlot,
395
+ offset: focusOffset
396
+ }).top;
397
+ let position;
398
+ let oldPosition;
399
+ let oldLeft = 0;
400
+ while (true) {
401
+ loopCount++;
402
+ position = this.selection.getPreviousPositionByPosition(focusSlot, focusOffset);
403
+ focusSlot = position.slot;
404
+ focusOffset = position.offset;
405
+ const rect2 = this.getRect(position);
406
+ if (!isToPrevLine) {
407
+ if (rect2.left > minLeft || rect2.top + rect2.height <= minTop) {
408
+ isToPrevLine = true;
409
+ }
410
+ else if (rect2.left === minLeft && rect2.top === minTop) {
411
+ return position;
412
+ }
413
+ minLeft = rect2.left;
414
+ minTop = rect2.top;
415
+ }
416
+ if (isToPrevLine) {
417
+ if (rect2.left < startLeft) {
418
+ return position;
419
+ }
420
+ if (oldPosition) {
421
+ if (rect2.left >= oldLeft) {
422
+ return oldPosition;
423
+ }
424
+ }
425
+ oldLeft = rect2.left;
426
+ oldPosition = position;
427
+ }
428
+ if (loopCount > 10000) {
429
+ break;
430
+ }
431
+ }
432
+ return position || {
433
+ offset: 0,
434
+ slot: focusSlot
435
+ };
436
+ }
437
+ /**
438
+ * 获取选区向下移动一行的位置。
439
+ * @param currentPosition
440
+ * @param startLeft 参考位置。
441
+ */
442
+ getNextLinePositionByOffset(currentPosition, startLeft) {
443
+ let isToNextLine = false;
444
+ let loopCount = 0;
445
+ let maxRight = startLeft;
446
+ let focusSlot = currentPosition.slot;
447
+ let focusOffset = currentPosition.offset;
448
+ const rect = this.getRect({
449
+ slot: focusSlot,
450
+ offset: focusOffset
451
+ });
452
+ let minTop = rect.top;
453
+ let oldPosition;
454
+ let oldLeft = 0;
455
+ while (true) {
456
+ loopCount++;
457
+ const position = this.selection.getNextPositionByPosition(focusSlot, focusOffset);
458
+ focusSlot = position.slot;
459
+ focusOffset = position.offset;
460
+ const rect2 = this.getRect(position);
461
+ if (!isToNextLine) {
462
+ if (rect2.left < maxRight || rect2.top >= minTop + rect.height) {
463
+ isToNextLine = true;
464
+ }
465
+ else if (rect2.left === maxRight && rect2.top === minTop) {
466
+ return position;
467
+ }
468
+ maxRight = rect2.left;
469
+ minTop = rect2.top;
470
+ oldPosition = position;
471
+ }
472
+ if (isToNextLine) {
473
+ if (rect2.left > startLeft) {
474
+ return oldPosition;
475
+ }
476
+ if (oldPosition) {
477
+ if (rect2.left <= oldLeft) {
478
+ return oldPosition;
479
+ }
480
+ }
481
+ oldPosition = position;
482
+ oldLeft = rect2.left;
483
+ }
484
+ if (loopCount > 10000) {
485
+ break;
486
+ }
487
+ }
488
+ return oldPosition || {
489
+ offset: focusSlot.length,
490
+ slot: focusSlot
491
+ };
492
+ }
493
+ unListen() {
494
+ this.subs.forEach(i => i.unsubscribe());
495
+ this.subs = [];
496
+ }
497
+ listen(connector) {
498
+ if (!this.config.useContentEditable) {
499
+ const selection = this.nativeSelection;
500
+ this.subs.push(stream.fromEvent(this.docContainer, 'mousedown').subscribe(ev => {
501
+ if (this.ignoreSelectionChange || ev.button === 2) {
502
+ return;
503
+ }
504
+ if (!ev.shiftKey) {
505
+ selection.removeAllRanges();
506
+ }
507
+ }));
508
+ }
509
+ this.subs.push(stream.fromEvent(document, 'selectionchange').subscribe(() => {
510
+ this.syncSelection(connector);
511
+ }));
512
+ }
513
+ syncSelection(connector) {
514
+ var _a;
515
+ const selection = this.nativeSelection;
516
+ this.changeFromUser = true;
517
+ if (this.ignoreSelectionChange ||
518
+ this.input.composition ||
519
+ selection.rangeCount === 0 ||
520
+ !this.docContainer.contains(selection.anchorNode) ||
521
+ this.rootComponentRef.component.slots.length === 0) {
522
+ return;
523
+ }
524
+ const rawRange = selection.getRangeAt(0);
525
+ const nativeRange = rawRange.cloneRange();
526
+ const isFocusEnd = selection.focusNode === nativeRange.endContainer && selection.focusOffset === nativeRange.endOffset;
527
+ const isFocusStart = selection.focusNode === nativeRange.startContainer && selection.focusOffset === nativeRange.startOffset;
528
+ if (!this.docContainer.contains(selection.focusNode)) {
529
+ if (isFocusEnd) {
530
+ const vEle = this.renderer.getVNodeBySlot(this.rootComponentRef.component.slots.first);
531
+ if (!vEle) {
532
+ return;
533
+ }
534
+ const nativeNode = this.renderer.getNativeNodeByVNode(vEle);
535
+ if (!nativeNode) {
536
+ return;
537
+ }
538
+ nativeRange.setEndAfter(nativeNode.lastChild);
539
+ }
540
+ else {
541
+ const vEle = this.renderer.getVNodeBySlot(this.rootComponentRef.component.slots.last);
542
+ if (!vEle) {
543
+ return;
544
+ }
545
+ const nativeNode = this.renderer.getNativeNodeByVNode(vEle);
546
+ if (!nativeNode) {
547
+ return;
548
+ }
549
+ nativeRange.setStartBefore(nativeNode.firstChild);
550
+ }
551
+ }
552
+ const startPosition = this.getCorrectedPosition(nativeRange.startContainer, nativeRange.startOffset, isFocusStart);
553
+ const endPosition = nativeRange.collapsed ?
554
+ startPosition :
555
+ this.getCorrectedPosition(nativeRange.endContainer, nativeRange.endOffset, isFocusEnd);
556
+ if ([Node.ELEMENT_NODE, Node.TEXT_NODE].includes((_a = nativeRange.commonAncestorContainer) === null || _a === void 0 ? void 0 : _a.nodeType) &&
557
+ startPosition && endPosition) {
558
+ const abstractSelection = isFocusEnd ? {
559
+ anchorSlot: startPosition.slot,
560
+ anchorOffset: startPosition.offset,
561
+ focusSlot: endPosition.slot,
562
+ focusOffset: endPosition.offset
563
+ } : {
564
+ focusSlot: startPosition.slot,
565
+ focusOffset: startPosition.offset,
566
+ anchorSlot: endPosition.slot,
567
+ anchorOffset: endPosition.offset
568
+ };
569
+ const { focus, anchor } = this.getPositionByRange(abstractSelection);
570
+ if (focus && anchor) {
571
+ let start = anchor;
572
+ let end = focus;
573
+ if (isFocusStart) {
574
+ start = focus;
575
+ end = anchor;
576
+ }
577
+ if (nativeRange.startContainer !== start.node || nativeRange.startOffset !== start.offset) {
578
+ nativeRange.setStart(start.node, start.offset);
579
+ }
580
+ if (nativeRange.endContainer !== end.node || nativeRange.endOffset !== end.offset) {
581
+ nativeRange.setEnd(end.node, end.offset);
582
+ }
583
+ connector.setSelection(abstractSelection);
584
+ if (selection.isCollapsed) {
585
+ rawRange.setStart(start.node, start.offset);
586
+ rawRange.setEnd(end.node, end.offset);
587
+ }
588
+ this.selectionChangeEvent.next(nativeRange);
589
+ }
590
+ else {
591
+ connector.setSelection(null);
592
+ }
593
+ return;
594
+ }
595
+ connector.setSelection(null);
596
+ }
597
+ findSelectedNodeAndOffset(slot, offset) {
598
+ const prev = slot.getContentAtIndex(offset - 1);
599
+ const vNodes = this.renderer.getVNodesBySlot(slot);
600
+ if (prev) {
601
+ if (typeof prev !== 'string') {
602
+ const vNode = this.renderer.getVNodeByComponent(prev);
603
+ const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
604
+ return {
605
+ node: nativeNode.parentNode,
606
+ offset: Array.from(nativeNode.parentNode.childNodes).indexOf(nativeNode) + 1
607
+ };
608
+ }
609
+ else if (prev === '\n') {
610
+ for (const vNode of vNodes) {
611
+ if (vNode instanceof core.VTextNode) {
612
+ continue;
613
+ }
614
+ if (vNode.tagName === 'br') {
615
+ const position = this.renderer.getLocationByVNode(vNode);
616
+ if (position) {
617
+ if (position.endIndex === offset) {
618
+ const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
619
+ const parentNode = nativeNode.parentNode;
620
+ return {
621
+ node: parentNode,
622
+ offset: Array.from(parentNode.childNodes).indexOf(nativeNode) + 1
623
+ };
624
+ }
625
+ }
626
+ }
627
+ }
628
+ }
629
+ }
630
+ const current = slot.getContentAtIndex(offset);
631
+ if (current && typeof current !== 'string') {
632
+ const vNode = this.renderer.getVNodeByComponent(current);
633
+ const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
634
+ return {
635
+ node: nativeNode.parentNode,
636
+ offset: Array.from(nativeNode.parentNode.childNodes).indexOf(nativeNode)
637
+ };
638
+ }
639
+ for (const vNode of vNodes) {
640
+ if (vNode instanceof core.VElement) {
641
+ if (vNode.tagName === 'br') {
642
+ const position = this.renderer.getLocationByVNode(vNode);
643
+ if (position) {
644
+ if (position.startIndex === offset) {
645
+ const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
646
+ const parentNode = nativeNode.parentNode;
647
+ return {
648
+ node: parentNode,
649
+ offset: Array.from(parentNode.childNodes).indexOf(nativeNode)
650
+ };
651
+ }
652
+ }
653
+ }
654
+ continue;
655
+ }
656
+ const position = this.renderer.getLocationByVNode(vNode);
657
+ if (position) {
658
+ if (offset >= position.startIndex && offset <= position.endIndex) {
659
+ const nativeNode = this.renderer.getNativeNodeByVNode(vNode);
660
+ return {
661
+ node: nativeNode,
662
+ offset: offset - position.startIndex
663
+ };
664
+ }
665
+ }
666
+ }
667
+ return null;
668
+ }
669
+ getCorrectedPosition(node, offset, toAfter, excludeNodes = []) {
670
+ excludeNodes.push(node);
671
+ if (node.nodeType === Node.ELEMENT_NODE) {
672
+ const containerPosition = this.renderer.getLocationByNativeNode(node);
673
+ const childNode = node.childNodes[offset];
674
+ if (childNode) {
675
+ const childPosition = this.renderer.getLocationByNativeNode(childNode);
676
+ if (childPosition) {
677
+ if (containerPosition) {
678
+ return {
679
+ slot: childPosition.slot,
680
+ offset: childPosition.startIndex
681
+ };
682
+ }
683
+ return this.findFocusNode(childNode, toAfter, excludeNodes);
684
+ }
685
+ return this.findFocusNode(childNode, toAfter, excludeNodes);
686
+ }
687
+ const prevNode = node.childNodes[offset - 1];
688
+ if (prevNode) {
689
+ const prevPosition = this.renderer.getLocationByNativeNode(prevNode);
690
+ if (prevPosition && containerPosition) {
691
+ return {
692
+ slot: prevPosition.slot,
693
+ offset: prevPosition.endIndex
694
+ };
695
+ }
696
+ }
697
+ if (containerPosition) {
698
+ return {
699
+ slot: containerPosition.slot,
700
+ offset: containerPosition.endIndex
701
+ };
702
+ }
703
+ const nextNode = toAfter ? node.nextSibling : node.previousSibling;
704
+ if (nextNode) {
705
+ return this.findFocusNode(nextNode, toAfter, excludeNodes);
706
+ }
707
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
708
+ }
709
+ else if (node.nodeType === Node.TEXT_NODE) {
710
+ const containerPosition = this.renderer.getLocationByNativeNode(node);
711
+ if (containerPosition) {
712
+ return {
713
+ slot: containerPosition.slot,
714
+ offset: containerPosition.startIndex + offset
715
+ };
716
+ }
717
+ const nextNode = toAfter ? node.nextSibling : node.previousSibling;
718
+ if (nextNode) {
719
+ return this.findFocusNode(nextNode, toAfter, excludeNodes);
720
+ }
721
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
722
+ }
723
+ return null;
724
+ }
725
+ findFocusNode(node, toAfter = false, excludeNodes = []) {
726
+ if (excludeNodes.includes(node)) {
727
+ const next = toAfter ? node.nextSibling : node.previousSibling;
728
+ if (next) {
729
+ return this.findFocusNode(next, toAfter, excludeNodes);
730
+ }
731
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
732
+ }
733
+ excludeNodes.push(node);
734
+ const position = this.renderer.getLocationByNativeNode(node);
735
+ if (position) {
736
+ return {
737
+ slot: position.slot,
738
+ offset: toAfter ? position.startIndex : position.endIndex
739
+ };
740
+ }
741
+ const firstChild = toAfter ? node.firstChild : node.lastChild;
742
+ if (firstChild) {
743
+ return this.findFocusNode(firstChild, toAfter, excludeNodes);
744
+ }
745
+ const nextSibling = toAfter ? node.nextSibling : node.previousSibling;
746
+ if (nextSibling) {
747
+ return this.findFocusNode(nextSibling, toAfter, excludeNodes);
748
+ }
749
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
750
+ }
751
+ findFocusNodeByParent(node, toAfter, excludeNodes) {
752
+ const parentNode = node.parentNode;
753
+ if (parentNode) {
754
+ const parentPosition = this.renderer.getLocationByNativeNode(parentNode);
755
+ if (parentPosition) {
756
+ return {
757
+ slot: parentPosition.slot,
758
+ offset: toAfter ? parentPosition.endIndex : parentPosition.startIndex
759
+ };
760
+ }
761
+ excludeNodes.push(node);
762
+ return this.findFocusNode(parentNode, toAfter, excludeNodes);
763
+ }
764
+ return null;
765
+ }
766
+ };
767
+ exports.SelectionBridge = __decorate([
768
+ di.Injectable(),
769
+ __param(0, di.Inject(EDITOR_OPTIONS)),
770
+ __metadata("design:paramtypes", [Object, di.Injector,
771
+ core.Controller,
772
+ core.Selection,
773
+ core.RootComponentRef,
774
+ Input,
775
+ core.Renderer])
776
776
  ], exports.SelectionBridge);
777
777
 
778
- class CollaborateSelectionAwarenessDelegate {
779
- }
780
- exports.CollaborateCursor = class CollaborateCursor {
781
- constructor(injector, nativeSelection, scheduler, selection, awarenessDelegate) {
782
- this.injector = injector;
783
- this.nativeSelection = nativeSelection;
784
- this.scheduler = scheduler;
785
- this.selection = selection;
786
- this.awarenessDelegate = awarenessDelegate;
787
- this.host = createElement('div', {
788
- styles: {
789
- position: 'absolute',
790
- left: 0,
791
- top: 0,
792
- width: '100%',
793
- height: '100%',
794
- pointerEvents: 'none',
795
- zIndex: 1
796
- }
797
- });
798
- this.canvasContainer = createElement('div', {
799
- styles: {
800
- position: 'absolute',
801
- left: 0,
802
- top: 0,
803
- width: '100%',
804
- height: '100%',
805
- overflow: 'hidden'
806
- }
807
- });
808
- this.canvas = createElement('canvas', {
809
- styles: {
810
- position: 'absolute',
811
- opacity: 0.5,
812
- left: 0,
813
- top: 0,
814
- width: '100%',
815
- height: document.documentElement.clientHeight + 'px',
816
- pointerEvents: 'none',
817
- }
818
- });
819
- this.context = this.canvas.getContext('2d');
820
- this.tooltips = createElement('div', {
821
- styles: {
822
- position: 'absolute',
823
- left: 0,
824
- top: 0,
825
- width: '100%',
826
- height: '100%',
827
- pointerEvents: 'none',
828
- fontSize: '12px',
829
- zIndex: 10
830
- }
831
- });
832
- this.onRectsChange = new stream.Subject();
833
- this.subscription = new stream.Subscription();
834
- this.currentSelection = [];
835
- this.container = injector.get(VIEW_CONTAINER);
836
- this.canvasContainer.append(this.canvas);
837
- this.host.append(this.canvasContainer, this.tooltips);
838
- this.container.prepend(this.host);
839
- this.subscription.add(this.onRectsChange.subscribe(rects => {
840
- for (const rect of rects) {
841
- this.context.fillStyle = rect.color;
842
- this.context.beginPath();
843
- this.context.rect(rect.left, rect.top, rect.width, rect.height);
844
- this.context.fill();
845
- this.context.closePath();
846
- }
847
- }), stream.fromEvent(window, 'resize').subscribe(() => {
848
- this.canvas.style.height = document.documentElement.clientHeight + 'px';
849
- this.refresh();
850
- }), this.scheduler.onDocChanged.subscribe(() => {
851
- this.refresh();
852
- }));
853
- }
854
- refresh() {
855
- this.draw(this.currentSelection);
856
- }
857
- destroy() {
858
- this.subscription.unsubscribe();
859
- }
860
- draw(paths) {
861
- this.currentSelection = paths;
862
- const containerRect = this.container.getBoundingClientRect();
863
- this.canvas.style.top = containerRect.top * -1 + 'px';
864
- this.canvas.width = this.canvas.offsetWidth;
865
- this.canvas.height = this.canvas.offsetHeight;
866
- this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
867
- const users = [];
868
- paths.filter(i => {
869
- return i.paths.anchor.length && i.paths.focus.length;
870
- }).forEach(item => {
871
- const anchorPaths = [...item.paths.anchor];
872
- const focusPaths = [...item.paths.focus];
873
- const anchorOffset = anchorPaths.pop();
874
- const anchorSlot = this.selection.findSlotByPaths(anchorPaths);
875
- const focusOffset = focusPaths.pop();
876
- const focusSlot = this.selection.findSlotByPaths(focusPaths);
877
- if (!anchorSlot || !focusSlot) {
878
- return;
879
- }
880
- const { focus, anchor } = this.nativeSelection.getPositionByRange({
881
- focusOffset,
882
- anchorOffset,
883
- focusSlot,
884
- anchorSlot
885
- });
886
- if (!focus || !anchor) {
887
- return;
888
- }
889
- const nativeRange = document.createRange();
890
- nativeRange.setStart(anchor.node, anchor.offset);
891
- nativeRange.setEnd(focus.node, focus.offset);
892
- if ((anchor.node !== focus.node || anchor.offset !== focus.offset) && nativeRange.collapsed) {
893
- nativeRange.setStart(focus.node, focus.offset);
894
- nativeRange.setEnd(anchor.node, anchor.offset);
895
- }
896
- let rects = false;
897
- if (this.awarenessDelegate) {
898
- rects = this.awarenessDelegate.getRects({
899
- focusOffset,
900
- anchorOffset,
901
- focusSlot,
902
- anchorSlot
903
- }, nativeRange);
904
- }
905
- if (!rects) {
906
- rects = nativeRange.getClientRects();
907
- }
908
- const selectionRects = [];
909
- for (let i = rects.length - 1; i >= 0; i--) {
910
- const rect = rects[i];
911
- selectionRects.push({
912
- id: item.id,
913
- color: item.color,
914
- username: item.username,
915
- left: rect.left - containerRect.left,
916
- top: rect.top,
917
- width: rect.width,
918
- height: rect.height,
919
- });
920
- }
921
- this.onRectsChange.next(selectionRects);
922
- const cursorRange = nativeRange.cloneRange();
923
- cursorRange.setStart(focus.node, focus.offset);
924
- cursorRange.collapse(true);
925
- const cursorRect = getLayoutRectByRange(cursorRange);
926
- const rect = {
927
- id: item.id,
928
- username: item.username,
929
- color: item.color,
930
- left: cursorRect.left - containerRect.left,
931
- top: cursorRect.top - containerRect.top,
932
- width: 1,
933
- height: cursorRect.height
934
- };
935
- if (rect.left < 0 || rect.top < 0 || rect.left > containerRect.width) {
936
- return;
937
- }
938
- users.push(rect);
939
- });
940
- this.drawUserCursor(users);
941
- }
942
- drawUserCursor(rects) {
943
- for (let i = 0; i < rects.length; i++) {
944
- const rect = rects[i];
945
- const { cursor, userTip, anchor } = this.getUserCursor(i);
946
- Object.assign(cursor.style, {
947
- left: rect.left + 'px',
948
- top: rect.top + 'px',
949
- width: rect.width + 'px',
950
- height: rect.height + 'px',
951
- background: rect.color,
952
- display: 'block'
953
- });
954
- anchor.style.background = rect.color;
955
- userTip.innerText = rect.username;
956
- userTip.style.background = rect.color;
957
- }
958
- for (let i = rects.length; i < this.tooltips.children.length; i++) {
959
- this.tooltips.removeChild(this.tooltips.children[i]);
960
- }
961
- }
962
- getUserCursor(index) {
963
- let child = this.tooltips.children[index];
964
- if (child) {
965
- const anchor = child.children[0];
966
- return {
967
- cursor: child,
968
- anchor,
969
- userTip: anchor.children[0]
970
- };
971
- }
972
- const userTip = createElement('span', {
973
- styles: {
974
- position: 'absolute',
975
- left: '50%',
976
- transform: 'translateX(-50%)',
977
- marginBottom: '2px',
978
- bottom: '100%',
979
- whiteSpace: 'nowrap',
980
- color: '#fff',
981
- boxShadow: '0 1px 2px rgba(0,0,0,.1)',
982
- opacity: 0.8,
983
- borderRadius: '3px',
984
- padding: '3px 5px',
985
- pointerEvents: 'none',
986
- }
987
- });
988
- const anchor = createElement('span', {
989
- styles: {
990
- position: 'absolute',
991
- top: '-2px',
992
- left: '-2px',
993
- width: '5px',
994
- height: '5px',
995
- borderRadius: '50%',
996
- pointerEvents: 'auto',
997
- pointer: 'cursor',
998
- },
999
- children: [userTip]
1000
- });
1001
- child = createElement('span', {
1002
- styles: {
1003
- position: 'absolute',
1004
- },
1005
- children: [
1006
- anchor
1007
- ]
1008
- });
1009
- this.tooltips.append(child);
1010
- return {
1011
- cursor: child,
1012
- anchor,
1013
- userTip
1014
- };
1015
- }
1016
- };
1017
- exports.CollaborateCursor = __decorate([
1018
- di.Injectable(),
1019
- __param(4, di.Optional()),
1020
- __metadata("design:paramtypes", [di.Injector,
1021
- exports.SelectionBridge,
1022
- core.Scheduler,
1023
- core.Selection,
1024
- CollaborateSelectionAwarenessDelegate])
778
+ class CollaborateSelectionAwarenessDelegate {
779
+ }
780
+ exports.CollaborateCursor = class CollaborateCursor {
781
+ constructor(injector, nativeSelection, scheduler, selection, awarenessDelegate) {
782
+ this.injector = injector;
783
+ this.nativeSelection = nativeSelection;
784
+ this.scheduler = scheduler;
785
+ this.selection = selection;
786
+ this.awarenessDelegate = awarenessDelegate;
787
+ this.host = createElement('div', {
788
+ styles: {
789
+ position: 'absolute',
790
+ left: 0,
791
+ top: 0,
792
+ width: '100%',
793
+ height: '100%',
794
+ pointerEvents: 'none',
795
+ zIndex: 1
796
+ }
797
+ });
798
+ this.canvasContainer = createElement('div', {
799
+ styles: {
800
+ position: 'absolute',
801
+ left: 0,
802
+ top: 0,
803
+ width: '100%',
804
+ height: '100%',
805
+ overflow: 'hidden'
806
+ }
807
+ });
808
+ this.canvas = createElement('canvas', {
809
+ styles: {
810
+ position: 'absolute',
811
+ opacity: 0.5,
812
+ left: 0,
813
+ top: 0,
814
+ width: '100%',
815
+ height: document.documentElement.clientHeight + 'px',
816
+ pointerEvents: 'none',
817
+ }
818
+ });
819
+ this.context = this.canvas.getContext('2d');
820
+ this.tooltips = createElement('div', {
821
+ styles: {
822
+ position: 'absolute',
823
+ left: 0,
824
+ top: 0,
825
+ width: '100%',
826
+ height: '100%',
827
+ pointerEvents: 'none',
828
+ fontSize: '12px',
829
+ zIndex: 10
830
+ }
831
+ });
832
+ this.onRectsChange = new stream.Subject();
833
+ this.subscription = new stream.Subscription();
834
+ this.currentSelection = [];
835
+ this.container = injector.get(VIEW_CONTAINER);
836
+ this.canvasContainer.append(this.canvas);
837
+ this.host.append(this.canvasContainer, this.tooltips);
838
+ this.container.prepend(this.host);
839
+ this.subscription.add(this.onRectsChange.subscribe(rects => {
840
+ for (const rect of rects) {
841
+ this.context.fillStyle = rect.color;
842
+ this.context.beginPath();
843
+ this.context.rect(rect.left, rect.top, rect.width, rect.height);
844
+ this.context.fill();
845
+ this.context.closePath();
846
+ }
847
+ }), stream.fromEvent(window, 'resize').subscribe(() => {
848
+ this.canvas.style.height = document.documentElement.clientHeight + 'px';
849
+ this.refresh();
850
+ }), this.scheduler.onDocChanged.subscribe(() => {
851
+ this.refresh();
852
+ }));
853
+ }
854
+ refresh() {
855
+ this.draw(this.currentSelection);
856
+ }
857
+ destroy() {
858
+ this.subscription.unsubscribe();
859
+ }
860
+ draw(paths) {
861
+ this.currentSelection = paths;
862
+ const containerRect = this.container.getBoundingClientRect();
863
+ this.canvas.style.top = containerRect.top * -1 + 'px';
864
+ this.canvas.width = this.canvas.offsetWidth;
865
+ this.canvas.height = this.canvas.offsetHeight;
866
+ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
867
+ const users = [];
868
+ paths.filter(i => {
869
+ return i.paths.anchor.length && i.paths.focus.length;
870
+ }).forEach(item => {
871
+ const anchorPaths = [...item.paths.anchor];
872
+ const focusPaths = [...item.paths.focus];
873
+ const anchorOffset = anchorPaths.pop();
874
+ const anchorSlot = this.selection.findSlotByPaths(anchorPaths);
875
+ const focusOffset = focusPaths.pop();
876
+ const focusSlot = this.selection.findSlotByPaths(focusPaths);
877
+ if (!anchorSlot || !focusSlot) {
878
+ return;
879
+ }
880
+ const { focus, anchor } = this.nativeSelection.getPositionByRange({
881
+ focusOffset,
882
+ anchorOffset,
883
+ focusSlot,
884
+ anchorSlot
885
+ });
886
+ if (!focus || !anchor) {
887
+ return;
888
+ }
889
+ const nativeRange = document.createRange();
890
+ nativeRange.setStart(anchor.node, anchor.offset);
891
+ nativeRange.setEnd(focus.node, focus.offset);
892
+ if ((anchor.node !== focus.node || anchor.offset !== focus.offset) && nativeRange.collapsed) {
893
+ nativeRange.setStart(focus.node, focus.offset);
894
+ nativeRange.setEnd(anchor.node, anchor.offset);
895
+ }
896
+ let rects = false;
897
+ if (this.awarenessDelegate) {
898
+ rects = this.awarenessDelegate.getRects({
899
+ focusOffset,
900
+ anchorOffset,
901
+ focusSlot,
902
+ anchorSlot
903
+ }, nativeRange);
904
+ }
905
+ if (!rects) {
906
+ rects = nativeRange.getClientRects();
907
+ }
908
+ const selectionRects = [];
909
+ for (let i = rects.length - 1; i >= 0; i--) {
910
+ const rect = rects[i];
911
+ selectionRects.push({
912
+ id: item.id,
913
+ color: item.color,
914
+ username: item.username,
915
+ left: rect.left - containerRect.left,
916
+ top: rect.top,
917
+ width: rect.width,
918
+ height: rect.height,
919
+ });
920
+ }
921
+ this.onRectsChange.next(selectionRects);
922
+ const cursorRange = nativeRange.cloneRange();
923
+ cursorRange.setStart(focus.node, focus.offset);
924
+ cursorRange.collapse(true);
925
+ const cursorRect = getLayoutRectByRange(cursorRange);
926
+ const rect = {
927
+ id: item.id,
928
+ username: item.username,
929
+ color: item.color,
930
+ left: cursorRect.left - containerRect.left,
931
+ top: cursorRect.top - containerRect.top,
932
+ width: 1,
933
+ height: cursorRect.height
934
+ };
935
+ if (rect.left < 0 || rect.top < 0 || rect.left > containerRect.width) {
936
+ return;
937
+ }
938
+ users.push(rect);
939
+ });
940
+ this.drawUserCursor(users);
941
+ }
942
+ drawUserCursor(rects) {
943
+ for (let i = 0; i < rects.length; i++) {
944
+ const rect = rects[i];
945
+ const { cursor, userTip, anchor } = this.getUserCursor(i);
946
+ Object.assign(cursor.style, {
947
+ left: rect.left + 'px',
948
+ top: rect.top + 'px',
949
+ width: rect.width + 'px',
950
+ height: rect.height + 'px',
951
+ background: rect.color,
952
+ display: 'block'
953
+ });
954
+ anchor.style.background = rect.color;
955
+ userTip.innerText = rect.username;
956
+ userTip.style.background = rect.color;
957
+ }
958
+ for (let i = rects.length; i < this.tooltips.children.length; i++) {
959
+ this.tooltips.removeChild(this.tooltips.children[i]);
960
+ }
961
+ }
962
+ getUserCursor(index) {
963
+ let child = this.tooltips.children[index];
964
+ if (child) {
965
+ const anchor = child.children[0];
966
+ return {
967
+ cursor: child,
968
+ anchor,
969
+ userTip: anchor.children[0]
970
+ };
971
+ }
972
+ const userTip = createElement('span', {
973
+ styles: {
974
+ position: 'absolute',
975
+ left: '50%',
976
+ transform: 'translateX(-50%)',
977
+ marginBottom: '2px',
978
+ bottom: '100%',
979
+ whiteSpace: 'nowrap',
980
+ color: '#fff',
981
+ boxShadow: '0 1px 2px rgba(0,0,0,.1)',
982
+ opacity: 0.8,
983
+ borderRadius: '3px',
984
+ padding: '3px 5px',
985
+ pointerEvents: 'none',
986
+ }
987
+ });
988
+ const anchor = createElement('span', {
989
+ styles: {
990
+ position: 'absolute',
991
+ top: '-2px',
992
+ left: '-2px',
993
+ width: '5px',
994
+ height: '5px',
995
+ borderRadius: '50%',
996
+ pointerEvents: 'auto',
997
+ pointer: 'cursor',
998
+ },
999
+ children: [userTip]
1000
+ });
1001
+ child = createElement('span', {
1002
+ styles: {
1003
+ position: 'absolute',
1004
+ },
1005
+ children: [
1006
+ anchor
1007
+ ]
1008
+ });
1009
+ this.tooltips.append(child);
1010
+ return {
1011
+ cursor: child,
1012
+ anchor,
1013
+ userTip
1014
+ };
1015
+ }
1016
+ };
1017
+ exports.CollaborateCursor = __decorate([
1018
+ di.Injectable(),
1019
+ __param(4, di.Optional()),
1020
+ __metadata("design:paramtypes", [di.Injector,
1021
+ exports.SelectionBridge,
1022
+ core.Scheduler,
1023
+ core.Selection,
1024
+ CollaborateSelectionAwarenessDelegate])
1025
1025
  ], exports.CollaborateCursor);
1026
1026
 
1027
- var DomRenderer_1;
1028
- /**
1029
- * Textbus PC 端浏览器渲染能力实现
1030
- */
1031
- exports.DomRenderer = DomRenderer_1 = class DomRenderer {
1032
- constructor() {
1033
- this.isSVG = new RegExp(`^(${[
1034
- // 'a',
1035
- 'animate',
1036
- 'animateMotion',
1037
- 'animateTransform',
1038
- 'circle',
1039
- 'clipPath',
1040
- 'defs',
1041
- 'desc',
1042
- 'ellipse',
1043
- 'feBlend',
1044
- 'feColorMatrix',
1045
- 'feComponentTransfer',
1046
- 'feComposite',
1047
- 'feConvolveMatrix',
1048
- 'feDiffuseLighting',
1049
- 'feDisplacementMap',
1050
- 'feDistantLight',
1051
- 'feDropShadow',
1052
- 'feFlood',
1053
- 'feFuncA',
1054
- 'feFuncB',
1055
- 'feFuncG',
1056
- 'feFuncR',
1057
- 'feGaussianBlur',
1058
- 'feImage',
1059
- 'feMerge',
1060
- 'feMergeNode',
1061
- 'feMorphology',
1062
- 'feOffset',
1063
- 'fePointLight',
1064
- 'feSpecularLighting',
1065
- 'feSpotLight',
1066
- 'feTile',
1067
- 'feTurbulence',
1068
- 'filter',
1069
- 'foreignObject',
1070
- 'g',
1071
- 'image',
1072
- 'line',
1073
- 'linearGradient',
1074
- 'marker',
1075
- 'mask',
1076
- 'metadata',
1077
- 'mpath',
1078
- 'path',
1079
- 'pattern',
1080
- 'polygon',
1081
- 'polyline',
1082
- 'radialGradient',
1083
- 'rect',
1084
- // 'script',
1085
- 'set',
1086
- 'stop',
1087
- // 'style',
1088
- 'svg',
1089
- 'switch',
1090
- 'symbol',
1091
- 'text',
1092
- 'textPath',
1093
- 'title',
1094
- 'tspan',
1095
- 'use',
1096
- 'view'
1097
- ].join('|')})$`, 'i');
1098
- this.xlinkNameSpace = 'http://www.w3.org/1999/xlink';
1099
- this.possibleXlinkNames = {
1100
- xlinkActuate: 'xlink:actuate',
1101
- xlinkactuate: 'xlink:actuate',
1102
- 'xlink:actuate': 'xlink:actuate',
1103
- xlinkArcrole: 'xlink:arcrole',
1104
- xlinkarcrole: 'xlink:arcrole',
1105
- 'xlink:arcrole': 'xlink:arcrole',
1106
- xlinkHref: 'xlink:href',
1107
- xlinkhref: 'xlink:href',
1108
- 'xlink:href': 'xlink:href',
1109
- xlinkRole: 'xlink:role',
1110
- xlinkrole: 'xlink:role',
1111
- 'xlink:role': 'xlink:role',
1112
- xlinkShow: 'xlink:show',
1113
- xlinkshow: 'xlink:show',
1114
- 'xlink:show': 'xlink:show',
1115
- xlinkTitle: 'xlink:title',
1116
- xlinktitle: 'xlink:title',
1117
- 'xlink:title': 'xlink:title',
1118
- xlinkType: 'xlink:type',
1119
- xlinktype: 'xlink:type',
1120
- 'xlink:type': 'xlink:type'
1121
- };
1122
- this.formElement = {
1123
- input: ['disabled', 'readonly', 'value'],
1124
- select: ['disabled', 'readonly'],
1125
- option: ['disabled', 'selected', 'value'],
1126
- button: ['disabled'],
1127
- video: ['controls', 'autoplay', 'loop', 'muted'],
1128
- audio: ['controls', 'autoplay', 'loop', 'muted'],
1129
- };
1130
- }
1131
- listen(node, type, callback) {
1132
- node.addEventListener(type, callback);
1133
- }
1134
- unListen(node, type, callback) {
1135
- node.removeEventListener(type, callback);
1136
- }
1137
- createTextNode(textContent) {
1138
- return document.createTextNode(DomRenderer_1.replaceEmpty(textContent, '\u00a0'));
1139
- }
1140
- createElement(name) {
1141
- if (this.isSVG.test(name)) {
1142
- return document.createElementNS('http://www.w3.org/2000/svg', name);
1143
- }
1144
- return document.createElement(name);
1145
- }
1146
- appendChild(parent, newChild) {
1147
- parent.appendChild(newChild);
1148
- }
1149
- remove(node) {
1150
- var _a;
1151
- (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(node);
1152
- }
1153
- insertBefore(newNode, ref) {
1154
- ref.parentNode.insertBefore(newNode, ref);
1155
- }
1156
- getChildByIndex(parent, index) {
1157
- return parent.childNodes[index] || null;
1158
- }
1159
- addClass(target, name) {
1160
- target.classList.add(name);
1161
- }
1162
- removeClass(target, name) {
1163
- target.classList.remove(name);
1164
- }
1165
- setStyle(target, key, value) {
1166
- target.style[key] = value !== null && value !== void 0 ? value : '';
1167
- }
1168
- syncTextContent(target, content) {
1169
- if (target.textContent !== content) {
1170
- target.textContent = content;
1171
- }
1172
- }
1173
- removeStyle(target, key) {
1174
- target.style[key] = '';
1175
- }
1176
- setAttribute(target, key, value) {
1177
- if (this.possibleXlinkNames[key]) {
1178
- this.setXlinkAttribute(target, this.possibleXlinkNames[key], value);
1179
- return;
1180
- }
1181
- target.setAttribute(key, value);
1182
- const propNames = this.formElement[target.tagName.toLowerCase()];
1183
- if (propNames && propNames.includes(key)) {
1184
- target[key] = Boolean(value);
1185
- }
1186
- }
1187
- removeAttribute(target, key) {
1188
- if (this.possibleXlinkNames[key]) {
1189
- this.removeXlinkAttribute(target, this.possibleXlinkNames[key]);
1190
- }
1191
- target.removeAttribute(key);
1192
- const propNames = this.formElement[target.tagName.toLowerCase()];
1193
- if (propNames && propNames.includes(key)) {
1194
- target[key] = false;
1195
- }
1196
- }
1197
- setXlinkAttribute(target, key, value) {
1198
- target.setAttributeNS(this.xlinkNameSpace, key, value);
1199
- }
1200
- removeXlinkAttribute(target, key) {
1201
- target.removeAttributeNS(this.xlinkNameSpace, key);
1202
- }
1203
- replace(newChild, oldChild) {
1204
- oldChild.parentNode.replaceChild(newChild, oldChild);
1205
- }
1206
- copy() {
1207
- document.execCommand('copy');
1208
- }
1209
- static replaceEmpty(s, target) {
1210
- return s.replace(/\s\s+/g, str => {
1211
- return ' ' + Array.from({
1212
- length: str.length - 1
1213
- }).fill(target).join('');
1214
- }).replace(/^\s|\s$/g, target);
1215
- }
1216
- };
1217
- exports.DomRenderer = DomRenderer_1 = __decorate([
1218
- di.Injectable()
1027
+ var DomRenderer_1;
1028
+ /**
1029
+ * Textbus PC 端浏览器渲染能力实现
1030
+ */
1031
+ exports.DomRenderer = DomRenderer_1 = class DomRenderer {
1032
+ constructor() {
1033
+ this.isSVG = new RegExp(`^(${[
1034
+ // 'a',
1035
+ 'animate',
1036
+ 'animateMotion',
1037
+ 'animateTransform',
1038
+ 'circle',
1039
+ 'clipPath',
1040
+ 'defs',
1041
+ 'desc',
1042
+ 'ellipse',
1043
+ 'feBlend',
1044
+ 'feColorMatrix',
1045
+ 'feComponentTransfer',
1046
+ 'feComposite',
1047
+ 'feConvolveMatrix',
1048
+ 'feDiffuseLighting',
1049
+ 'feDisplacementMap',
1050
+ 'feDistantLight',
1051
+ 'feDropShadow',
1052
+ 'feFlood',
1053
+ 'feFuncA',
1054
+ 'feFuncB',
1055
+ 'feFuncG',
1056
+ 'feFuncR',
1057
+ 'feGaussianBlur',
1058
+ 'feImage',
1059
+ 'feMerge',
1060
+ 'feMergeNode',
1061
+ 'feMorphology',
1062
+ 'feOffset',
1063
+ 'fePointLight',
1064
+ 'feSpecularLighting',
1065
+ 'feSpotLight',
1066
+ 'feTile',
1067
+ 'feTurbulence',
1068
+ 'filter',
1069
+ 'foreignObject',
1070
+ 'g',
1071
+ 'image',
1072
+ 'line',
1073
+ 'linearGradient',
1074
+ 'marker',
1075
+ 'mask',
1076
+ 'metadata',
1077
+ 'mpath',
1078
+ 'path',
1079
+ 'pattern',
1080
+ 'polygon',
1081
+ 'polyline',
1082
+ 'radialGradient',
1083
+ 'rect',
1084
+ // 'script',
1085
+ 'set',
1086
+ 'stop',
1087
+ // 'style',
1088
+ 'svg',
1089
+ 'switch',
1090
+ 'symbol',
1091
+ 'text',
1092
+ 'textPath',
1093
+ 'title',
1094
+ 'tspan',
1095
+ 'use',
1096
+ 'view'
1097
+ ].join('|')})$`, 'i');
1098
+ this.xlinkNameSpace = 'http://www.w3.org/1999/xlink';
1099
+ this.possibleXlinkNames = {
1100
+ xlinkActuate: 'xlink:actuate',
1101
+ xlinkactuate: 'xlink:actuate',
1102
+ 'xlink:actuate': 'xlink:actuate',
1103
+ xlinkArcrole: 'xlink:arcrole',
1104
+ xlinkarcrole: 'xlink:arcrole',
1105
+ 'xlink:arcrole': 'xlink:arcrole',
1106
+ xlinkHref: 'xlink:href',
1107
+ xlinkhref: 'xlink:href',
1108
+ 'xlink:href': 'xlink:href',
1109
+ xlinkRole: 'xlink:role',
1110
+ xlinkrole: 'xlink:role',
1111
+ 'xlink:role': 'xlink:role',
1112
+ xlinkShow: 'xlink:show',
1113
+ xlinkshow: 'xlink:show',
1114
+ 'xlink:show': 'xlink:show',
1115
+ xlinkTitle: 'xlink:title',
1116
+ xlinktitle: 'xlink:title',
1117
+ 'xlink:title': 'xlink:title',
1118
+ xlinkType: 'xlink:type',
1119
+ xlinktype: 'xlink:type',
1120
+ 'xlink:type': 'xlink:type'
1121
+ };
1122
+ this.formElement = {
1123
+ input: ['disabled', 'readonly', 'value'],
1124
+ select: ['disabled', 'readonly'],
1125
+ option: ['disabled', 'selected', 'value'],
1126
+ button: ['disabled'],
1127
+ video: ['controls', 'autoplay', 'loop', 'muted'],
1128
+ audio: ['controls', 'autoplay', 'loop', 'muted'],
1129
+ };
1130
+ }
1131
+ listen(node, type, callback) {
1132
+ node.addEventListener(type, callback);
1133
+ }
1134
+ unListen(node, type, callback) {
1135
+ node.removeEventListener(type, callback);
1136
+ }
1137
+ createTextNode(textContent) {
1138
+ return document.createTextNode(DomRenderer_1.replaceEmpty(textContent, '\u00a0'));
1139
+ }
1140
+ createElement(name) {
1141
+ if (this.isSVG.test(name)) {
1142
+ return document.createElementNS('http://www.w3.org/2000/svg', name);
1143
+ }
1144
+ return document.createElement(name);
1145
+ }
1146
+ appendChild(parent, newChild) {
1147
+ parent.appendChild(newChild);
1148
+ }
1149
+ remove(node) {
1150
+ var _a;
1151
+ (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(node);
1152
+ }
1153
+ insertBefore(newNode, ref) {
1154
+ ref.parentNode.insertBefore(newNode, ref);
1155
+ }
1156
+ getChildByIndex(parent, index) {
1157
+ return parent.childNodes[index] || null;
1158
+ }
1159
+ addClass(target, name) {
1160
+ target.classList.add(name);
1161
+ }
1162
+ removeClass(target, name) {
1163
+ target.classList.remove(name);
1164
+ }
1165
+ setStyle(target, key, value) {
1166
+ target.style[key] = value !== null && value !== void 0 ? value : '';
1167
+ }
1168
+ syncTextContent(target, content) {
1169
+ if (target.textContent !== content) {
1170
+ target.textContent = content;
1171
+ }
1172
+ }
1173
+ removeStyle(target, key) {
1174
+ target.style[key] = '';
1175
+ }
1176
+ setAttribute(target, key, value) {
1177
+ if (this.possibleXlinkNames[key]) {
1178
+ this.setXlinkAttribute(target, this.possibleXlinkNames[key], value);
1179
+ return;
1180
+ }
1181
+ target.setAttribute(key, value);
1182
+ const propNames = this.formElement[target.tagName.toLowerCase()];
1183
+ if (propNames && propNames.includes(key)) {
1184
+ target[key] = Boolean(value);
1185
+ }
1186
+ }
1187
+ removeAttribute(target, key) {
1188
+ if (this.possibleXlinkNames[key]) {
1189
+ this.removeXlinkAttribute(target, this.possibleXlinkNames[key]);
1190
+ }
1191
+ target.removeAttribute(key);
1192
+ const propNames = this.formElement[target.tagName.toLowerCase()];
1193
+ if (propNames && propNames.includes(key)) {
1194
+ target[key] = false;
1195
+ }
1196
+ }
1197
+ setXlinkAttribute(target, key, value) {
1198
+ target.setAttributeNS(this.xlinkNameSpace, key, value);
1199
+ }
1200
+ removeXlinkAttribute(target, key) {
1201
+ target.removeAttributeNS(this.xlinkNameSpace, key);
1202
+ }
1203
+ replace(newChild, oldChild) {
1204
+ oldChild.parentNode.replaceChild(newChild, oldChild);
1205
+ }
1206
+ copy() {
1207
+ document.execCommand('copy');
1208
+ }
1209
+ static replaceEmpty(s, target) {
1210
+ return s.replace(/\s\s+/g, str => {
1211
+ return ' ' + Array.from({
1212
+ length: str.length - 1
1213
+ }).fill(target).join('');
1214
+ }).replace(/^\s|\s$/g, target);
1215
+ }
1216
+ };
1217
+ exports.DomRenderer = DomRenderer_1 = __decorate([
1218
+ di.Injectable()
1219
1219
  ], exports.DomRenderer);
1220
1220
 
1221
- var Parser_1;
1222
- exports.Parser = Parser_1 = class Parser {
1223
- constructor(options, injector) {
1224
- var _a;
1225
- this.options = options;
1226
- this.injector = injector;
1227
- const componentLoaders = [
1228
- ...(options.componentLoaders || [])
1229
- ];
1230
- const formatLoaders = [
1231
- ...(options.formatLoaders || [])
1232
- ];
1233
- const attributeLoaders = [
1234
- ...(options.attributeLoaders || [])
1235
- ];
1236
- (_a = options.imports) === null || _a === void 0 ? void 0 : _a.forEach(i => {
1237
- componentLoaders.push(...(i.componentLoaders || []));
1238
- formatLoaders.push(...(i.formatLoaders || []));
1239
- });
1240
- this.componentLoaders = componentLoaders;
1241
- this.formatLoaders = formatLoaders;
1242
- this.attributeLoaders = attributeLoaders;
1243
- }
1244
- static parseHTML(html) {
1245
- return new DOMParser().parseFromString(html, 'text/html').body;
1246
- }
1247
- parseDoc(html, rootComponentLoader) {
1248
- const element = Parser_1.parseHTML(html);
1249
- return rootComponentLoader.read(element, this.injector, (childSlot, slotRootElement, slotContentHostElement = slotRootElement) => {
1250
- return this.readSlot(childSlot, slotRootElement, slotContentHostElement);
1251
- });
1252
- }
1253
- parse(html, rootSlot) {
1254
- const element = Parser_1.parseHTML(html);
1255
- return this.readFormats(element, rootSlot);
1256
- }
1257
- readComponent(el, slot) {
1258
- if (el.nodeType === Node.ELEMENT_NODE) {
1259
- if (el.tagName === 'BR') {
1260
- slot.insert('\n');
1261
- return;
1262
- }
1263
- for (const t of this.componentLoaders) {
1264
- if (t.match(el)) {
1265
- const result = t.read(el, this.injector, (childSlot, slotRootElement, slotContentHostElement = slotRootElement) => {
1266
- return this.readSlot(childSlot, slotRootElement, slotContentHostElement);
1267
- });
1268
- if (result instanceof core.Slot) {
1269
- result.toDelta().forEach(i => slot.insert(i.insert, i.formats));
1270
- return;
1271
- }
1272
- slot.insert(result);
1273
- return;
1274
- }
1275
- }
1276
- this.readFormats(el, slot);
1277
- }
1278
- else if (el.nodeType === Node.TEXT_NODE) {
1279
- const textContent = el.textContent;
1280
- if (/^\s*[\r\n]+\s*$/.test(textContent)) {
1281
- return;
1282
- }
1283
- slot.insert(textContent);
1284
- }
1285
- }
1286
- readFormats(el, slot) {
1287
- this.formatLoaders.filter(f => {
1288
- return f.match(el);
1289
- }).forEach(f => {
1290
- const v = f.read(el);
1291
- slot.applyFormat(v.formatter, {
1292
- startIndex: 0,
1293
- endIndex: slot.length,
1294
- value: v.value
1295
- });
1296
- });
1297
- Array.from(el.childNodes).forEach(child => {
1298
- this.readComponent(child, slot);
1299
- });
1300
- return slot;
1301
- }
1302
- readSlot(childSlot, slotRootElement, slotContentElement) {
1303
- this.attributeLoaders.filter(a => {
1304
- return a.match(slotRootElement);
1305
- }).forEach(a => {
1306
- const r = a.read(slotRootElement);
1307
- childSlot.setAttribute(r.attribute, r.value);
1308
- });
1309
- return this.readFormats(slotContentElement, childSlot);
1310
- }
1311
- };
1312
- exports.Parser = Parser_1 = __decorate([
1313
- di.Injectable(),
1314
- __param(0, di.Inject(EDITOR_OPTIONS)),
1315
- __metadata("design:paramtypes", [Object, di.Injector])
1221
+ var Parser_1;
1222
+ exports.Parser = Parser_1 = class Parser {
1223
+ static parseHTML(html) {
1224
+ return new DOMParser().parseFromString(html, 'text/html').body;
1225
+ }
1226
+ constructor(options, injector) {
1227
+ var _a;
1228
+ this.options = options;
1229
+ this.injector = injector;
1230
+ const componentLoaders = [
1231
+ ...(options.componentLoaders || [])
1232
+ ];
1233
+ const formatLoaders = [
1234
+ ...(options.formatLoaders || [])
1235
+ ];
1236
+ const attributeLoaders = [
1237
+ ...(options.attributeLoaders || [])
1238
+ ];
1239
+ (_a = options.imports) === null || _a === void 0 ? void 0 : _a.forEach(i => {
1240
+ componentLoaders.push(...(i.componentLoaders || []));
1241
+ formatLoaders.push(...(i.formatLoaders || []));
1242
+ });
1243
+ this.componentLoaders = componentLoaders;
1244
+ this.formatLoaders = formatLoaders;
1245
+ this.attributeLoaders = attributeLoaders;
1246
+ }
1247
+ parseDoc(html, rootComponentLoader) {
1248
+ const element = Parser_1.parseHTML(html);
1249
+ return rootComponentLoader.read(element, this.injector, (childSlot, slotRootElement, slotContentHostElement = slotRootElement) => {
1250
+ return this.readSlot(childSlot, slotRootElement, slotContentHostElement);
1251
+ });
1252
+ }
1253
+ parse(html, rootSlot) {
1254
+ const element = Parser_1.parseHTML(html);
1255
+ const formatItems = this.readFormats(element, rootSlot, []);
1256
+ this.applyFormats(rootSlot, formatItems);
1257
+ return rootSlot;
1258
+ }
1259
+ readComponent(el, slot, formatItems) {
1260
+ if (el.nodeType === Node.ELEMENT_NODE) {
1261
+ if (el.tagName === 'BR') {
1262
+ slot.insert('\n');
1263
+ return;
1264
+ }
1265
+ for (const t of this.componentLoaders) {
1266
+ if (t.match(el)) {
1267
+ const result = t.read(el, this.injector, (childSlot, slotRootElement, slotContentHostElement = slotRootElement) => {
1268
+ return this.readSlot(childSlot, slotRootElement, slotContentHostElement);
1269
+ });
1270
+ if (result instanceof core.Slot) {
1271
+ result.toDelta().forEach(i => slot.insert(i.insert, i.formats));
1272
+ return;
1273
+ }
1274
+ slot.insert(result);
1275
+ return;
1276
+ }
1277
+ }
1278
+ this.readFormats(el, slot, formatItems);
1279
+ }
1280
+ else if (el.nodeType === Node.TEXT_NODE) {
1281
+ const textContent = el.textContent;
1282
+ if (/^\s*[\r\n]+\s*$/.test(textContent)) {
1283
+ return;
1284
+ }
1285
+ slot.insert(textContent);
1286
+ }
1287
+ }
1288
+ readFormats(el, slot, formatItems) {
1289
+ const formats = this.formatLoaders.filter(f => {
1290
+ return f.match(el);
1291
+ }).map(f => {
1292
+ return f.read(el);
1293
+ });
1294
+ const startIndex = slot.index;
1295
+ Array.from(el.childNodes).forEach(child => {
1296
+ this.readComponent(child, slot, formatItems);
1297
+ });
1298
+ const endIndex = slot.index;
1299
+ formatItems.unshift(...formats.map(i => {
1300
+ return {
1301
+ formatter: i.formatter,
1302
+ value: i.value,
1303
+ startIndex,
1304
+ endIndex
1305
+ };
1306
+ }));
1307
+ return formatItems;
1308
+ }
1309
+ readSlot(childSlot, slotRootElement, slotContentElement) {
1310
+ this.attributeLoaders.filter(a => {
1311
+ return a.match(slotRootElement);
1312
+ }).forEach(a => {
1313
+ const r = a.read(slotRootElement);
1314
+ childSlot.setAttribute(r.attribute, r.value);
1315
+ });
1316
+ const childFormatItems = this.readFormats(slotContentElement, childSlot, []);
1317
+ this.applyFormats(childSlot, childFormatItems);
1318
+ return childSlot;
1319
+ }
1320
+ applyFormats(slot, formatItems) {
1321
+ formatItems.forEach(i => {
1322
+ slot.retain(i.startIndex);
1323
+ slot.retain(i.endIndex - i.startIndex, i.formatter, i.value, true);
1324
+ });
1325
+ }
1326
+ };
1327
+ exports.Parser = Parser_1 = __decorate([
1328
+ di.Injectable(),
1329
+ __param(0, di.Inject(EDITOR_OPTIONS)),
1330
+ __metadata("design:paramtypes", [Object, di.Injector])
1316
1331
  ], exports.Parser);
1317
1332
 
1318
- const iframeHTML = `
1319
- <!DOCTYPE html>
1320
- <html>
1321
- <head>
1322
- <meta charset="UTF-8">
1323
- <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
1324
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
1325
- <title>Textbus</title>
1326
- <style>
1327
- html {position: fixed; left:0; overflow: hidden}
1328
- html, body{height: 100%;width:100%}
1329
- body{margin:0; overflow: hidden}
1330
- textarea{width: 2000px;height: 100%;opacity: 0; padding: 0; outline: none; border: none; position: absolute; left:0; top:0;}
1331
- </style>
1332
- </head>
1333
- <body>
1334
- </body>
1335
- </html>
1336
- `;
1337
- class ExperimentalCaret {
1338
- constructor(scheduler, editorMask) {
1339
- this.scheduler = scheduler;
1340
- this.editorMask = editorMask;
1341
- this.timer = null;
1342
- this.oldPosition = null;
1343
- this._display = true;
1344
- this.flashing = true;
1345
- this.subs = [];
1346
- this.positionChangeEvent = new stream.Subject();
1347
- this.styleChangeEvent = new stream.Subject();
1348
- this.oldRange = null;
1349
- this.isFixed = false;
1350
- this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1351
- this.onStyleChange = this.styleChangeEvent.asObservable();
1352
- this.elementRef = createElement('div', {
1353
- styles: {
1354
- position: 'absolute',
1355
- width: '2px',
1356
- pointerEvents: 'none'
1357
- },
1358
- children: [
1359
- this.caret = createElement('span', {
1360
- styles: {
1361
- width: '100%',
1362
- height: '100%',
1363
- position: 'absolute',
1364
- left: 0,
1365
- top: 0
1366
- }
1367
- })
1368
- ]
1369
- });
1370
- this.subs.push(stream.fromEvent(document, 'mousedown').subscribe(() => {
1371
- this.flashing = false;
1372
- }), stream.fromEvent(document, 'mouseup').subscribe(() => {
1373
- this.flashing = true;
1374
- }));
1375
- this.editorMask.appendChild(this.elementRef);
1376
- }
1377
- get rect() {
1378
- return this.caret.getBoundingClientRect();
1379
- }
1380
- set display(v) {
1381
- this._display = v;
1382
- this.caret.style.visibility = v ? 'visible' : 'hidden';
1383
- }
1384
- get display() {
1385
- return this._display;
1386
- }
1387
- refresh(isFixedCaret = false) {
1388
- this.isFixed = isFixedCaret;
1389
- if (this.oldRange) {
1390
- this.show(this.oldRange, false);
1391
- }
1392
- this.isFixed = false;
1393
- }
1394
- show(range, restart) {
1395
- const oldRect = this.elementRef.getBoundingClientRect();
1396
- this.oldPosition = {
1397
- top: oldRect.top,
1398
- left: oldRect.left,
1399
- height: oldRect.height
1400
- };
1401
- this.oldRange = range;
1402
- if (restart || this.scheduler.lastChangesHasLocalUpdate) {
1403
- clearTimeout(this.timer);
1404
- }
1405
- this.updateCursorPosition(range);
1406
- if (range.collapsed) {
1407
- if (restart || this.scheduler.lastChangesHasLocalUpdate) {
1408
- this.display = true;
1409
- const toggleShowHide = () => {
1410
- this.display = !this.display || !this.flashing;
1411
- this.timer = setTimeout(toggleShowHide, 400);
1412
- };
1413
- clearTimeout(this.timer);
1414
- this.timer = setTimeout(toggleShowHide, 400);
1415
- }
1416
- }
1417
- else {
1418
- this.display = false;
1419
- clearTimeout(this.timer);
1420
- }
1421
- }
1422
- hide() {
1423
- this.display = false;
1424
- clearTimeout(this.timer);
1425
- this.positionChangeEvent.next(null);
1426
- }
1427
- destroy() {
1428
- clearTimeout(this.timer);
1429
- this.subs.forEach(i => i.unsubscribe());
1430
- }
1431
- correctScrollTop(scroller) {
1432
- this.subs.forEach(i => i.unsubscribe());
1433
- this.subs = [];
1434
- const scheduler = this.scheduler;
1435
- let docIsChanged = true;
1436
- function limitPosition(position) {
1437
- const { top, bottom } = scroller.getLimit();
1438
- const caretTop = position.top;
1439
- if (caretTop + position.height > bottom) {
1440
- const offset = caretTop - bottom + position.height;
1441
- scroller.setOffset(offset);
1442
- }
1443
- else if (position.top < top) {
1444
- scroller.setOffset(-(top - position.top));
1445
- }
1446
- }
1447
- let isPressed = false;
1448
- this.subs.push(scroller.onScroll.subscribe(() => {
1449
- if (this.oldPosition) {
1450
- const rect = this.rect;
1451
- this.oldPosition.top = rect.top;
1452
- this.oldPosition.left = rect.left;
1453
- this.oldPosition.height = rect.height;
1454
- }
1455
- }), stream.fromEvent(document, 'mousedown', true).subscribe(() => {
1456
- isPressed = true;
1457
- }), stream.fromEvent(document, 'mouseup', true).subscribe(() => {
1458
- isPressed = false;
1459
- }), scheduler.onDocChange.subscribe(() => {
1460
- docIsChanged = true;
1461
- }), this.onPositionChange.subscribe(position => {
1462
- if (position) {
1463
- if (docIsChanged) {
1464
- if (scheduler.lastChangesHasLocalUpdate) {
1465
- limitPosition(position);
1466
- }
1467
- else if (this.oldPosition) {
1468
- const offset = Math.floor(position.top - this.oldPosition.top);
1469
- scroller.setOffset(offset);
1470
- }
1471
- }
1472
- else if (!isPressed) {
1473
- if (this.isFixed && this.oldPosition) {
1474
- const offset = Math.floor(position.top - this.oldPosition.top);
1475
- scroller.setOffset(offset);
1476
- }
1477
- else {
1478
- limitPosition(position);
1479
- }
1480
- }
1481
- }
1482
- docIsChanged = false;
1483
- }));
1484
- }
1485
- updateCursorPosition(nativeRange) {
1486
- const startContainer = nativeRange.startContainer;
1487
- const node = (startContainer.nodeType === Node.ELEMENT_NODE ? startContainer : startContainer.parentNode);
1488
- if ((node === null || node === void 0 ? void 0 : node.nodeType) !== Node.ELEMENT_NODE) {
1489
- this.positionChangeEvent.next(null);
1490
- return;
1491
- }
1492
- const rect = getLayoutRectByRange(nativeRange);
1493
- const { fontSize, lineHeight, color } = getComputedStyle(node);
1494
- let height;
1495
- if (isNaN(+lineHeight)) {
1496
- const f = parseFloat(lineHeight);
1497
- if (isNaN(f)) {
1498
- height = parseFloat(fontSize);
1499
- }
1500
- else {
1501
- height = f;
1502
- }
1503
- }
1504
- else {
1505
- height = parseFloat(fontSize) * parseFloat(lineHeight);
1506
- }
1507
- const boxHeight = Math.floor(Math.max(height, rect.height));
1508
- // const boxHeight = Math.floor(height)
1509
- let rectTop = rect.top;
1510
- if (rect.height < height) {
1511
- rectTop -= (height - rect.height) / 2;
1512
- }
1513
- rectTop = Math.floor(rectTop);
1514
- const containerRect = this.editorMask.getBoundingClientRect();
1515
- const top = Math.floor(rectTop - containerRect.top);
1516
- const left = Math.floor(rect.left - containerRect.left);
1517
- Object.assign(this.elementRef.style, {
1518
- left: left + 'px',
1519
- top: top + 'px',
1520
- height: boxHeight + 'px',
1521
- lineHeight: boxHeight + 'px',
1522
- fontSize
1523
- });
1524
- this.caret.style.backgroundColor = color;
1525
- this.styleChangeEvent.next({
1526
- height: boxHeight + 'px',
1527
- lineHeight: boxHeight + 'px',
1528
- fontSize
1529
- });
1530
- this.positionChangeEvent.next({
1531
- left,
1532
- top: rectTop,
1533
- height: boxHeight
1534
- });
1535
- }
1536
- }
1537
- /**
1538
- * Textbus PC 端输入实现
1539
- */
1540
- exports.MagicInput = class MagicInput extends Input {
1541
- constructor(parser, keyboard, commander, selection, controller, scheduler, injector) {
1542
- super();
1543
- this.parser = parser;
1544
- this.keyboard = keyboard;
1545
- this.commander = commander;
1546
- this.selection = selection;
1547
- this.controller = controller;
1548
- this.scheduler = scheduler;
1549
- this.injector = injector;
1550
- this.composition = false;
1551
- this.caret = new ExperimentalCaret(this.scheduler, this.injector.get(VIEW_MASK));
1552
- this._disabled = false;
1553
- this.container = this.createEditableFrame();
1554
- this.subscription = new stream.Subscription();
1555
- this.textarea = null;
1556
- this.isFocus = false;
1557
- this.nativeFocus = false;
1558
- this.isSafari = isSafari();
1559
- this.isMac = isMac();
1560
- this.isWindows = isWindows();
1561
- this.isSougouPinYin = false; // 有 bug 版本搜狗拼音
1562
- this.onReady = new Promise(resolve => {
1563
- this.subscription.add(stream.fromEvent(this.container, 'load').subscribe(() => {
1564
- const doc = this.container.contentDocument;
1565
- doc.open();
1566
- doc.write(iframeHTML);
1567
- doc.close();
1568
- this.doc = doc;
1569
- this.init();
1570
- resolve();
1571
- }), controller.onReadonlyStateChange.subscribe(() => {
1572
- if (controller.readonly) {
1573
- this.blur();
1574
- }
1575
- }));
1576
- });
1577
- this.caret.elementRef.append(this.container);
1578
- }
1579
- set disabled(b) {
1580
- this._disabled = b;
1581
- if (b && this.textarea) {
1582
- this.textarea.disabled = b;
1583
- }
1584
- }
1585
- get disabled() {
1586
- return this._disabled;
1587
- }
1588
- focus(range, restart) {
1589
- var _a;
1590
- if (!this.disabled) {
1591
- this.caret.show(range, restart);
1592
- }
1593
- if (this.controller.readonly) {
1594
- return;
1595
- }
1596
- if (!this.isFocus) {
1597
- (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.focus();
1598
- setTimeout(() => {
1599
- var _a, _b, _c;
1600
- if (!this.nativeFocus && this.isFocus) {
1601
- this.subscription.unsubscribe();
1602
- (_b = (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(this.textarea);
1603
- this.subscription = new stream.Subscription();
1604
- this.init();
1605
- (_c = this.textarea) === null || _c === void 0 ? void 0 : _c.focus();
1606
- }
1607
- });
1608
- }
1609
- this.isFocus = true;
1610
- }
1611
- blur() {
1612
- var _a;
1613
- this.caret.hide();
1614
- (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.blur();
1615
- this.isFocus = false;
1616
- }
1617
- destroy() {
1618
- this.caret.destroy();
1619
- this.subscription.unsubscribe();
1620
- }
1621
- init() {
1622
- const doc = this.doc;
1623
- const contentBody = doc.body;
1624
- const textarea = doc.createElement('textarea');
1625
- textarea.disabled = this.disabled;
1626
- contentBody.appendChild(textarea);
1627
- this.textarea = textarea;
1628
- this.subscription.add(stream.fromEvent(textarea, 'blur').subscribe(() => {
1629
- this.isFocus = false;
1630
- this.nativeFocus = false;
1631
- this.caret.hide();
1632
- }), stream.fromEvent(textarea, 'focus').subscribe(() => {
1633
- this.nativeFocus = true;
1634
- }), this.caret.onStyleChange.subscribe(style => {
1635
- Object.assign(textarea.style, style);
1636
- }));
1637
- this.handleInput(textarea);
1638
- this.handleShortcut(textarea);
1639
- this.handleDefaultActions(textarea);
1640
- }
1641
- handleDefaultActions(textarea) {
1642
- this.subscription.add(stream.fromEvent(document, 'copy').subscribe(ev => {
1643
- const selection = this.selection;
1644
- if (!selection.isSelected) {
1645
- return;
1646
- }
1647
- if (selection.startSlot === selection.endSlot && selection.endOffset - selection.startOffset === 1) {
1648
- const content = selection.startSlot.getContentAtIndex(selection.startOffset);
1649
- if (typeof content === 'object') {
1650
- const clipboardData = ev.clipboardData;
1651
- const nativeSelection = document.getSelection();
1652
- const range = nativeSelection.getRangeAt(0);
1653
- const div = document.createElement('div');
1654
- const fragment = range.cloneContents();
1655
- div.append(fragment);
1656
- clipboardData.setData('text/html', div.innerHTML);
1657
- clipboardData.setData('text', div.innerText);
1658
- ev.preventDefault();
1659
- }
1660
- }
1661
- }), stream.fromEvent(textarea, 'paste').subscribe(ev => {
1662
- const text = ev.clipboardData.getData('Text');
1663
- const files = Array.from(ev.clipboardData.files);
1664
- if (files.length) {
1665
- Promise.all(files.filter(i => {
1666
- return /image/i.test(i.type);
1667
- }).map(item => {
1668
- const reader = new FileReader();
1669
- return new Promise(resolve => {
1670
- reader.onload = (event) => {
1671
- resolve(event.target.result);
1672
- };
1673
- reader.readAsDataURL(item);
1674
- });
1675
- })).then(urls => {
1676
- const html = urls.map(i => {
1677
- return `<img src=${i}>`;
1678
- }).join('');
1679
- this.handlePaste(html, text);
1680
- });
1681
- ev.preventDefault();
1682
- return;
1683
- }
1684
- const div = this.doc.createElement('div');
1685
- div.style.cssText = 'width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0';
1686
- div.contentEditable = 'true';
1687
- this.doc.body.appendChild(div);
1688
- div.focus();
1689
- setTimeout(() => {
1690
- const html = div.innerHTML;
1691
- this.handlePaste(html, text);
1692
- this.doc.body.removeChild(div);
1693
- });
1694
- }));
1695
- }
1696
- handlePaste(html, text) {
1697
- const slot = this.parser.parse(html, new core.Slot([
1698
- core.ContentType.BlockComponent,
1699
- core.ContentType.InlineComponent,
1700
- core.ContentType.Text
1701
- ]));
1702
- this.commander.paste(slot, text);
1703
- }
1704
- handleShortcut(textarea) {
1705
- let isWriting = false;
1706
- let isIgnore = false;
1707
- this.subscription.add(stream.fromEvent(textarea, 'compositionstart').subscribe(() => {
1708
- isWriting = true;
1709
- }), stream.fromEvent(textarea, 'compositionend').subscribe(() => {
1710
- isWriting = false;
1711
- }), stream.fromEvent(textarea, 'beforeinput').subscribe(ev => {
1712
- if (this.isSafari) {
1713
- if (ev.inputType === 'insertFromComposition') {
1714
- isIgnore = true;
1715
- }
1716
- }
1717
- }), stream.fromEvent(textarea, 'keydown').pipe(stream.filter(() => {
1718
- if (this.isSafari && isIgnore) {
1719
- isIgnore = false;
1720
- return false;
1721
- }
1722
- return !isWriting; // || !this.textarea.value
1723
- })).subscribe(ev => {
1724
- let key = ev.key;
1725
- const b = key === 'Process' && ev.code === 'Digit2';
1726
- if (b) {
1727
- key = '@';
1728
- this.isSougouPinYin = true;
1729
- ev.preventDefault();
1730
- }
1731
- const is = this.keyboard.execShortcut({
1732
- key: key,
1733
- altKey: ev.altKey,
1734
- shiftKey: ev.shiftKey,
1735
- ctrlKey: this.isMac ? ev.metaKey : ev.ctrlKey
1736
- });
1737
- if (is) {
1738
- ev.preventDefault();
1739
- }
1740
- }));
1741
- }
1742
- handleInput(textarea) {
1743
- this.subscription.add(stream.merge(stream.fromEvent(textarea, 'beforeinput').pipe(stream.filter(ev => {
1744
- ev.preventDefault();
1745
- if (this.isSafari) {
1746
- return ev.inputType === 'insertText' || ev.inputType === 'insertFromComposition';
1747
- }
1748
- return !ev.isComposing && !!ev.data;
1749
- }), stream.map(ev => {
1750
- return ev.data;
1751
- })), this.isSafari ? new stream.Observable() : stream.fromEvent(textarea, 'compositionend').pipe(stream.map(ev => {
1752
- ev.preventDefault();
1753
- textarea.value = '';
1754
- return ev.data;
1755
- }), stream.filter(() => {
1756
- const b = this.isSougouPinYin;
1757
- this.isSougouPinYin = false;
1758
- return !b;
1759
- }))).subscribe(text => {
1760
- if (text) {
1761
- this.commander.write(text);
1762
- }
1763
- }));
1764
- }
1765
- createEditableFrame() {
1766
- return createElement('iframe', {
1767
- attrs: {
1768
- scrolling: 'no'
1769
- },
1770
- styles: {
1771
- border: 'none',
1772
- width: '100%',
1773
- display: 'block',
1774
- height: '100%',
1775
- position: 'relative',
1776
- top: this.isWindows ? '6px' : '0'
1777
- }
1778
- });
1779
- }
1780
- };
1781
- exports.MagicInput = __decorate([
1782
- di.Injectable(),
1783
- __metadata("design:paramtypes", [exports.Parser,
1784
- core.Keyboard,
1785
- core.Commander,
1786
- core.Selection,
1787
- core.Controller,
1788
- core.Scheduler,
1789
- di.Injector])
1333
+ const iframeHTML = `
1334
+ <!DOCTYPE html>
1335
+ <html>
1336
+ <head>
1337
+ <meta charset="UTF-8">
1338
+ <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
1339
+ <meta http-equiv="X-UA-Compatible" content="ie=edge">
1340
+ <title>Textbus</title>
1341
+ <style>
1342
+ html {position: fixed; left:0; overflow: hidden}
1343
+ html, body{height: 100%;width:100%}
1344
+ body{margin:0; overflow: hidden}
1345
+ textarea{width: 2000px;height: 100%;opacity: 0; padding: 0; outline: none; border: none; position: absolute; left:0; top:0;}
1346
+ </style>
1347
+ </head>
1348
+ <body>
1349
+ </body>
1350
+ </html>
1351
+ `;
1352
+ class ExperimentalCaret {
1353
+ get rect() {
1354
+ return this.caret.getBoundingClientRect();
1355
+ }
1356
+ set display(v) {
1357
+ this._display = v;
1358
+ this.caret.style.visibility = v ? 'visible' : 'hidden';
1359
+ }
1360
+ get display() {
1361
+ return this._display;
1362
+ }
1363
+ constructor(scheduler, editorMask) {
1364
+ this.scheduler = scheduler;
1365
+ this.editorMask = editorMask;
1366
+ this.timer = null;
1367
+ this.oldPosition = null;
1368
+ this._display = true;
1369
+ this.flashing = true;
1370
+ this.subs = [];
1371
+ this.positionChangeEvent = new stream.Subject();
1372
+ this.styleChangeEvent = new stream.Subject();
1373
+ this.oldRange = null;
1374
+ this.isFixed = false;
1375
+ this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1376
+ this.onStyleChange = this.styleChangeEvent.asObservable();
1377
+ this.elementRef = createElement('div', {
1378
+ styles: {
1379
+ position: 'absolute',
1380
+ width: '2px',
1381
+ pointerEvents: 'none'
1382
+ },
1383
+ children: [
1384
+ this.caret = createElement('span', {
1385
+ styles: {
1386
+ width: '100%',
1387
+ height: '100%',
1388
+ position: 'absolute',
1389
+ left: 0,
1390
+ top: 0
1391
+ }
1392
+ })
1393
+ ]
1394
+ });
1395
+ this.subs.push(stream.fromEvent(document, 'mousedown').subscribe(() => {
1396
+ this.flashing = false;
1397
+ }), stream.fromEvent(document, 'mouseup').subscribe(() => {
1398
+ this.flashing = true;
1399
+ }));
1400
+ this.editorMask.appendChild(this.elementRef);
1401
+ }
1402
+ refresh(isFixedCaret = false) {
1403
+ this.isFixed = isFixedCaret;
1404
+ if (this.oldRange) {
1405
+ this.show(this.oldRange, false);
1406
+ }
1407
+ this.isFixed = false;
1408
+ }
1409
+ show(range, restart) {
1410
+ const oldRect = this.elementRef.getBoundingClientRect();
1411
+ this.oldPosition = {
1412
+ top: oldRect.top,
1413
+ left: oldRect.left,
1414
+ height: oldRect.height
1415
+ };
1416
+ this.oldRange = range;
1417
+ if (restart || this.scheduler.lastChangesHasLocalUpdate) {
1418
+ clearTimeout(this.timer);
1419
+ }
1420
+ this.updateCursorPosition(range);
1421
+ if (range.collapsed) {
1422
+ if (restart || this.scheduler.lastChangesHasLocalUpdate) {
1423
+ this.display = true;
1424
+ const toggleShowHide = () => {
1425
+ this.display = !this.display || !this.flashing;
1426
+ this.timer = setTimeout(toggleShowHide, 400);
1427
+ };
1428
+ clearTimeout(this.timer);
1429
+ this.timer = setTimeout(toggleShowHide, 400);
1430
+ }
1431
+ }
1432
+ else {
1433
+ this.display = false;
1434
+ clearTimeout(this.timer);
1435
+ }
1436
+ }
1437
+ hide() {
1438
+ this.display = false;
1439
+ clearTimeout(this.timer);
1440
+ this.positionChangeEvent.next(null);
1441
+ }
1442
+ destroy() {
1443
+ clearTimeout(this.timer);
1444
+ this.subs.forEach(i => i.unsubscribe());
1445
+ }
1446
+ correctScrollTop(scroller) {
1447
+ this.subs.forEach(i => i.unsubscribe());
1448
+ this.subs = [];
1449
+ const scheduler = this.scheduler;
1450
+ let docIsChanged = true;
1451
+ function limitPosition(position) {
1452
+ const { top, bottom } = scroller.getLimit();
1453
+ const caretTop = position.top;
1454
+ if (caretTop + position.height > bottom) {
1455
+ const offset = caretTop - bottom + position.height;
1456
+ scroller.setOffset(offset);
1457
+ }
1458
+ else if (position.top < top) {
1459
+ scroller.setOffset(-(top - position.top));
1460
+ }
1461
+ }
1462
+ let isPressed = false;
1463
+ this.subs.push(scroller.onScroll.subscribe(() => {
1464
+ if (this.oldPosition) {
1465
+ const rect = this.rect;
1466
+ this.oldPosition.top = rect.top;
1467
+ this.oldPosition.left = rect.left;
1468
+ this.oldPosition.height = rect.height;
1469
+ }
1470
+ }), stream.fromEvent(document, 'mousedown', true).subscribe(() => {
1471
+ isPressed = true;
1472
+ }), stream.fromEvent(document, 'mouseup', true).subscribe(() => {
1473
+ isPressed = false;
1474
+ }), scheduler.onDocChange.subscribe(() => {
1475
+ docIsChanged = true;
1476
+ }), this.onPositionChange.subscribe(position => {
1477
+ if (position) {
1478
+ if (docIsChanged) {
1479
+ if (scheduler.lastChangesHasLocalUpdate) {
1480
+ limitPosition(position);
1481
+ }
1482
+ else if (this.oldPosition) {
1483
+ const offset = Math.floor(position.top - this.oldPosition.top);
1484
+ scroller.setOffset(offset);
1485
+ }
1486
+ }
1487
+ else if (!isPressed) {
1488
+ if (this.isFixed && this.oldPosition) {
1489
+ const offset = Math.floor(position.top - this.oldPosition.top);
1490
+ scroller.setOffset(offset);
1491
+ }
1492
+ else {
1493
+ limitPosition(position);
1494
+ }
1495
+ }
1496
+ }
1497
+ docIsChanged = false;
1498
+ }));
1499
+ }
1500
+ updateCursorPosition(nativeRange) {
1501
+ const startContainer = nativeRange.startContainer;
1502
+ const node = (startContainer.nodeType === Node.ELEMENT_NODE ? startContainer : startContainer.parentNode);
1503
+ if ((node === null || node === void 0 ? void 0 : node.nodeType) !== Node.ELEMENT_NODE) {
1504
+ this.positionChangeEvent.next(null);
1505
+ return;
1506
+ }
1507
+ const rect = getLayoutRectByRange(nativeRange);
1508
+ const { fontSize, lineHeight, color } = getComputedStyle(node);
1509
+ let height;
1510
+ if (isNaN(+lineHeight)) {
1511
+ const f = parseFloat(lineHeight);
1512
+ if (isNaN(f)) {
1513
+ height = parseFloat(fontSize);
1514
+ }
1515
+ else {
1516
+ height = f;
1517
+ }
1518
+ }
1519
+ else {
1520
+ height = parseFloat(fontSize) * parseFloat(lineHeight);
1521
+ }
1522
+ const boxHeight = Math.floor(Math.max(height, rect.height));
1523
+ // const boxHeight = Math.floor(height)
1524
+ let rectTop = rect.top;
1525
+ if (rect.height < height) {
1526
+ rectTop -= (height - rect.height) / 2;
1527
+ }
1528
+ rectTop = Math.floor(rectTop);
1529
+ const containerRect = this.editorMask.getBoundingClientRect();
1530
+ const top = Math.floor(rectTop - containerRect.top);
1531
+ const left = Math.floor(rect.left - containerRect.left);
1532
+ Object.assign(this.elementRef.style, {
1533
+ left: left + 'px',
1534
+ top: top + 'px',
1535
+ height: boxHeight + 'px',
1536
+ lineHeight: boxHeight + 'px',
1537
+ fontSize
1538
+ });
1539
+ this.caret.style.backgroundColor = color;
1540
+ this.styleChangeEvent.next({
1541
+ height: boxHeight + 'px',
1542
+ lineHeight: boxHeight + 'px',
1543
+ fontSize
1544
+ });
1545
+ this.positionChangeEvent.next({
1546
+ left,
1547
+ top: rectTop,
1548
+ height: boxHeight
1549
+ });
1550
+ }
1551
+ }
1552
+ /**
1553
+ * Textbus PC 端输入实现
1554
+ */
1555
+ exports.MagicInput = class MagicInput extends Input {
1556
+ set disabled(b) {
1557
+ this._disabled = b;
1558
+ if (b && this.textarea) {
1559
+ this.textarea.disabled = b;
1560
+ }
1561
+ }
1562
+ get disabled() {
1563
+ return this._disabled;
1564
+ }
1565
+ constructor(parser, keyboard, commander, selection, controller, scheduler, injector) {
1566
+ super();
1567
+ this.parser = parser;
1568
+ this.keyboard = keyboard;
1569
+ this.commander = commander;
1570
+ this.selection = selection;
1571
+ this.controller = controller;
1572
+ this.scheduler = scheduler;
1573
+ this.injector = injector;
1574
+ this.composition = false;
1575
+ this.caret = new ExperimentalCaret(this.scheduler, this.injector.get(VIEW_MASK));
1576
+ this._disabled = false;
1577
+ this.container = this.createEditableFrame();
1578
+ this.subscription = new stream.Subscription();
1579
+ this.textarea = null;
1580
+ this.isFocus = false;
1581
+ this.nativeFocus = false;
1582
+ this.isSafari = isSafari();
1583
+ this.isMac = isMac();
1584
+ this.isWindows = isWindows();
1585
+ this.isSougouPinYin = false; // 有 bug 版本搜狗拼音
1586
+ this.onReady = new Promise(resolve => {
1587
+ this.subscription.add(stream.fromEvent(this.container, 'load').subscribe(() => {
1588
+ const doc = this.container.contentDocument;
1589
+ doc.open();
1590
+ doc.write(iframeHTML);
1591
+ doc.close();
1592
+ this.doc = doc;
1593
+ this.init();
1594
+ resolve();
1595
+ }), controller.onReadonlyStateChange.subscribe(() => {
1596
+ if (controller.readonly) {
1597
+ this.blur();
1598
+ }
1599
+ }));
1600
+ });
1601
+ this.caret.elementRef.append(this.container);
1602
+ }
1603
+ focus(range, restart) {
1604
+ var _a;
1605
+ if (!this.disabled) {
1606
+ this.caret.show(range, restart);
1607
+ }
1608
+ if (this.controller.readonly) {
1609
+ return;
1610
+ }
1611
+ if (!this.isFocus) {
1612
+ (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.focus();
1613
+ setTimeout(() => {
1614
+ var _a, _b, _c;
1615
+ if (!this.nativeFocus && this.isFocus) {
1616
+ this.subscription.unsubscribe();
1617
+ (_b = (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(this.textarea);
1618
+ this.subscription = new stream.Subscription();
1619
+ this.init();
1620
+ (_c = this.textarea) === null || _c === void 0 ? void 0 : _c.focus();
1621
+ }
1622
+ });
1623
+ }
1624
+ this.isFocus = true;
1625
+ }
1626
+ blur() {
1627
+ var _a;
1628
+ this.caret.hide();
1629
+ (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.blur();
1630
+ this.isFocus = false;
1631
+ }
1632
+ destroy() {
1633
+ this.caret.destroy();
1634
+ this.subscription.unsubscribe();
1635
+ }
1636
+ init() {
1637
+ const doc = this.doc;
1638
+ const contentBody = doc.body;
1639
+ const textarea = doc.createElement('textarea');
1640
+ textarea.disabled = this.disabled;
1641
+ contentBody.appendChild(textarea);
1642
+ this.textarea = textarea;
1643
+ this.subscription.add(stream.fromEvent(textarea, 'blur').subscribe(() => {
1644
+ this.isFocus = false;
1645
+ this.nativeFocus = false;
1646
+ this.caret.hide();
1647
+ }), stream.fromEvent(textarea, 'focus').subscribe(() => {
1648
+ this.nativeFocus = true;
1649
+ }), this.caret.onStyleChange.subscribe(style => {
1650
+ Object.assign(textarea.style, style);
1651
+ }));
1652
+ this.handleInput(textarea);
1653
+ this.handleShortcut(textarea);
1654
+ this.handleDefaultActions(textarea);
1655
+ }
1656
+ handleDefaultActions(textarea) {
1657
+ this.subscription.add(stream.fromEvent(document, 'copy').subscribe(ev => {
1658
+ const selection = this.selection;
1659
+ if (!selection.isSelected) {
1660
+ return;
1661
+ }
1662
+ if (selection.startSlot === selection.endSlot && selection.endOffset - selection.startOffset === 1) {
1663
+ const content = selection.startSlot.getContentAtIndex(selection.startOffset);
1664
+ if (typeof content === 'object') {
1665
+ const clipboardData = ev.clipboardData;
1666
+ const nativeSelection = document.getSelection();
1667
+ const range = nativeSelection.getRangeAt(0);
1668
+ const div = document.createElement('div');
1669
+ const fragment = range.cloneContents();
1670
+ div.append(fragment);
1671
+ clipboardData.setData('text/html', div.innerHTML);
1672
+ clipboardData.setData('text', div.innerText);
1673
+ ev.preventDefault();
1674
+ }
1675
+ }
1676
+ }), stream.fromEvent(textarea, 'paste').subscribe(ev => {
1677
+ const text = ev.clipboardData.getData('Text');
1678
+ const files = Array.from(ev.clipboardData.files);
1679
+ if (files.length) {
1680
+ Promise.all(files.filter(i => {
1681
+ return /image/i.test(i.type);
1682
+ }).map(item => {
1683
+ const reader = new FileReader();
1684
+ return new Promise(resolve => {
1685
+ reader.onload = (event) => {
1686
+ resolve(event.target.result);
1687
+ };
1688
+ reader.readAsDataURL(item);
1689
+ });
1690
+ })).then(urls => {
1691
+ const html = urls.map(i => {
1692
+ return `<img src=${i}>`;
1693
+ }).join('');
1694
+ this.handlePaste(html, text);
1695
+ });
1696
+ ev.preventDefault();
1697
+ return;
1698
+ }
1699
+ const div = this.doc.createElement('div');
1700
+ div.style.cssText = 'width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0';
1701
+ div.contentEditable = 'true';
1702
+ this.doc.body.appendChild(div);
1703
+ div.focus();
1704
+ setTimeout(() => {
1705
+ const html = div.innerHTML;
1706
+ this.handlePaste(html, text);
1707
+ this.doc.body.removeChild(div);
1708
+ });
1709
+ }));
1710
+ }
1711
+ handlePaste(html, text) {
1712
+ const slot = this.parser.parse(html, new core.Slot([
1713
+ core.ContentType.BlockComponent,
1714
+ core.ContentType.InlineComponent,
1715
+ core.ContentType.Text
1716
+ ]));
1717
+ this.commander.paste(slot, text);
1718
+ }
1719
+ handleShortcut(textarea) {
1720
+ let isWriting = false;
1721
+ let isIgnore = false;
1722
+ this.subscription.add(stream.fromEvent(textarea, 'compositionstart').subscribe(() => {
1723
+ isWriting = true;
1724
+ }), stream.fromEvent(textarea, 'compositionend').subscribe(() => {
1725
+ isWriting = false;
1726
+ }), stream.fromEvent(textarea, 'beforeinput').subscribe(ev => {
1727
+ if (this.isSafari) {
1728
+ if (ev.inputType === 'insertFromComposition') {
1729
+ isIgnore = true;
1730
+ }
1731
+ }
1732
+ }), stream.fromEvent(textarea, 'keydown').pipe(stream.filter(() => {
1733
+ if (this.isSafari && isIgnore) {
1734
+ isIgnore = false;
1735
+ return false;
1736
+ }
1737
+ return !isWriting; // || !this.textarea.value
1738
+ })).subscribe(ev => {
1739
+ let key = ev.key;
1740
+ const b = key === 'Process' && ev.code === 'Digit2';
1741
+ if (b) {
1742
+ key = '@';
1743
+ this.isSougouPinYin = true;
1744
+ ev.preventDefault();
1745
+ }
1746
+ const is = this.keyboard.execShortcut({
1747
+ key: key,
1748
+ altKey: ev.altKey,
1749
+ shiftKey: ev.shiftKey,
1750
+ ctrlKey: this.isMac ? ev.metaKey : ev.ctrlKey
1751
+ });
1752
+ if (is) {
1753
+ ev.preventDefault();
1754
+ }
1755
+ }));
1756
+ }
1757
+ handleInput(textarea) {
1758
+ this.subscription.add(stream.merge(stream.fromEvent(textarea, 'beforeinput').pipe(stream.filter(ev => {
1759
+ ev.preventDefault();
1760
+ if (this.isSafari) {
1761
+ return ev.inputType === 'insertText' || ev.inputType === 'insertFromComposition';
1762
+ }
1763
+ return !ev.isComposing && !!ev.data;
1764
+ }), stream.map(ev => {
1765
+ return ev.data;
1766
+ })), this.isSafari ? new stream.Observable() : stream.fromEvent(textarea, 'compositionend').pipe(stream.map(ev => {
1767
+ ev.preventDefault();
1768
+ textarea.value = '';
1769
+ return ev.data;
1770
+ }), stream.filter(() => {
1771
+ const b = this.isSougouPinYin;
1772
+ this.isSougouPinYin = false;
1773
+ return !b;
1774
+ }))).subscribe(text => {
1775
+ if (text) {
1776
+ this.commander.write(text);
1777
+ }
1778
+ }));
1779
+ }
1780
+ createEditableFrame() {
1781
+ return createElement('iframe', {
1782
+ attrs: {
1783
+ scrolling: 'no'
1784
+ },
1785
+ styles: {
1786
+ border: 'none',
1787
+ width: '100%',
1788
+ display: 'block',
1789
+ height: '100%',
1790
+ position: 'relative',
1791
+ top: this.isWindows ? '6px' : '0'
1792
+ }
1793
+ });
1794
+ }
1795
+ };
1796
+ exports.MagicInput = __decorate([
1797
+ di.Injectable(),
1798
+ __metadata("design:paramtypes", [exports.Parser,
1799
+ core.Keyboard,
1800
+ core.Commander,
1801
+ core.Selection,
1802
+ core.Controller,
1803
+ core.Scheduler,
1804
+ di.Injector])
1790
1805
  ], exports.MagicInput);
1791
1806
 
1792
- class NativeCaret {
1793
- constructor(scheduler) {
1794
- this.scheduler = scheduler;
1795
- this.oldPosition = null;
1796
- this._nativeRange = null;
1797
- this.subs = [];
1798
- this.positionChangeEvent = new stream.Subject();
1799
- this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1800
- }
1801
- set nativeRange(range) {
1802
- this._nativeRange = range;
1803
- if (range) {
1804
- const r = range.cloneRange();
1805
- r.collapse(true);
1806
- const rect = r.getBoundingClientRect();
1807
- this.positionChangeEvent.next({
1808
- left: rect.left,
1809
- top: rect.top,
1810
- height: rect.height
1811
- });
1812
- }
1813
- else {
1814
- this.positionChangeEvent.next(null);
1815
- }
1816
- }
1817
- get nativeRange() {
1818
- return this._nativeRange;
1819
- }
1820
- get rect() {
1821
- if (this.nativeRange) {
1822
- const range = this.nativeRange.cloneRange();
1823
- range.collapse(true);
1824
- return range.getBoundingClientRect();
1825
- }
1826
- return {
1827
- left: 0,
1828
- top: 0,
1829
- width: 0,
1830
- height: 0
1831
- };
1832
- }
1833
- refresh() {
1834
- //
1835
- }
1836
- correctScrollTop(scroller) {
1837
- this.destroy();
1838
- const scheduler = this.scheduler;
1839
- let docIsChanged = true;
1840
- function limitPosition(position) {
1841
- const { top, bottom } = scroller.getLimit();
1842
- const caretTop = position.top;
1843
- if (caretTop + position.height > bottom) {
1844
- const offset = caretTop - bottom + position.height;
1845
- scroller.setOffset(offset);
1846
- }
1847
- else if (position.top < top) {
1848
- scroller.setOffset(-(top - position.top));
1849
- }
1850
- }
1851
- let isPressed = false;
1852
- this.subs.push(scroller.onScroll.subscribe(() => {
1853
- if (this.oldPosition) {
1854
- const rect = this.rect;
1855
- this.oldPosition.top = rect.top;
1856
- this.oldPosition.left = rect.left;
1857
- this.oldPosition.height = rect.height;
1858
- }
1859
- }), stream.fromEvent(document, 'mousedown', true).subscribe(() => {
1860
- isPressed = true;
1861
- }), stream.fromEvent(document, 'mouseup', true).subscribe(() => {
1862
- isPressed = false;
1863
- }), scheduler.onDocChange.subscribe(() => {
1864
- docIsChanged = true;
1865
- }), this.onPositionChange.subscribe(position => {
1866
- if (position) {
1867
- if (docIsChanged) {
1868
- if (scheduler.lastChangesHasLocalUpdate) {
1869
- limitPosition(position);
1870
- }
1871
- else if (this.oldPosition) {
1872
- const offset = Math.floor(position.top - this.oldPosition.top);
1873
- scroller.setOffset(offset);
1874
- }
1875
- }
1876
- else if (!isPressed) {
1877
- if (this.oldPosition) {
1878
- const offset = Math.floor(position.top - this.oldPosition.top);
1879
- scroller.setOffset(offset);
1880
- }
1881
- else {
1882
- limitPosition(position);
1883
- }
1884
- }
1885
- }
1886
- docIsChanged = false;
1887
- }));
1888
- }
1889
- destroy() {
1890
- this.subs.forEach(i => i.unsubscribe());
1891
- this.subs = [];
1892
- }
1893
- }
1894
- exports.NativeInput = class NativeInput extends Input {
1895
- constructor(injector, parser, scheduler, selection, keyboard, commander, controller) {
1896
- super();
1897
- this.injector = injector;
1898
- this.parser = parser;
1899
- this.scheduler = scheduler;
1900
- this.selection = selection;
1901
- this.keyboard = keyboard;
1902
- this.commander = commander;
1903
- this.controller = controller;
1904
- this.caret = new NativeCaret(this.scheduler);
1905
- this.composition = false;
1906
- this.onReady = Promise.resolve();
1907
- this._disabled = false;
1908
- this.nativeSelection = document.getSelection();
1909
- this.subscription = new stream.Subscription();
1910
- this.nativeRange = null;
1911
- this.isSafari = isSafari();
1912
- this.isMac = isMac();
1913
- this.isSougouPinYin = false; // 有 bug 版本搜狗拼音
1914
- this.documentView = injector.get(VIEW_DOCUMENT);
1915
- if (!controller.readonly) {
1916
- this.documentView.contentEditable = 'true';
1917
- }
1918
- this.subscription.add(controller.onReadonlyStateChange.subscribe(() => {
1919
- this.documentView.contentEditable = controller.readonly ? 'false' : 'true';
1920
- }));
1921
- this.handleShortcut(this.documentView);
1922
- this.handleInput(this.documentView);
1923
- this.handleDefaultActions(this.documentView);
1924
- }
1925
- set disabled(b) {
1926
- this._disabled = b;
1927
- if (b && !this.controller.readonly) {
1928
- this.documentView.contentEditable = b ? 'true' : 'false';
1929
- }
1930
- }
1931
- get disabled() {
1932
- return this._disabled;
1933
- }
1934
- focus(nativeRange) {
1935
- if (this.controller.readonly) {
1936
- return;
1937
- }
1938
- this.caret.nativeRange = nativeRange;
1939
- this.nativeRange = nativeRange;
1940
- }
1941
- blur() {
1942
- if (this.nativeRange && this.nativeSelection.rangeCount > 0) {
1943
- const current = this.nativeSelection.getRangeAt(0);
1944
- if (current === this.nativeRange) {
1945
- this.nativeSelection.removeAllRanges();
1946
- this.nativeRange = null;
1947
- return;
1948
- }
1949
- }
1950
- }
1951
- destroy() {
1952
- this.caret.destroy();
1953
- this.subscription.unsubscribe();
1954
- }
1955
- handleDefaultActions(textarea) {
1956
- this.subscription.add(stream.fromEvent(document, 'copy').subscribe(ev => {
1957
- const selection = this.selection;
1958
- if (!selection.isSelected) {
1959
- return;
1960
- }
1961
- if (selection.startSlot === selection.endSlot && selection.endOffset - selection.startOffset === 1) {
1962
- const content = selection.startSlot.getContentAtIndex(selection.startOffset);
1963
- if (typeof content === 'object') {
1964
- const clipboardData = ev.clipboardData;
1965
- const nativeSelection = document.getSelection();
1966
- const range = nativeSelection.getRangeAt(0);
1967
- const div = document.createElement('div');
1968
- const fragment = range.cloneContents();
1969
- div.append(fragment);
1970
- clipboardData.setData('text/html', div.innerHTML);
1971
- clipboardData.setData('text', div.innerText);
1972
- ev.preventDefault();
1973
- }
1974
- }
1975
- }), stream.fromEvent(textarea, 'paste').subscribe(ev => {
1976
- const text = ev.clipboardData.getData('Text');
1977
- const files = Array.from(ev.clipboardData.files);
1978
- if (files.length) {
1979
- Promise.all(files.filter(i => {
1980
- return /image/i.test(i.type);
1981
- }).map(item => {
1982
- const reader = new FileReader();
1983
- return new Promise(resolve => {
1984
- reader.onload = (event) => {
1985
- resolve(event.target.result);
1986
- };
1987
- reader.readAsDataURL(item);
1988
- });
1989
- })).then(urls => {
1990
- const html = urls.map(i => {
1991
- return `<img src=${i}>`;
1992
- }).join('');
1993
- this.handlePaste(html, text);
1994
- });
1995
- ev.preventDefault();
1996
- return;
1997
- }
1998
- const div = document.createElement('div');
1999
- div.style.cssText = 'width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0';
2000
- div.contentEditable = 'true';
2001
- document.body.appendChild(div);
2002
- div.focus();
2003
- setTimeout(() => {
2004
- const html = div.innerHTML;
2005
- this.handlePaste(html, text);
2006
- document.body.removeChild(div);
2007
- });
2008
- }));
2009
- }
2010
- handlePaste(html, text) {
2011
- const slot = this.parser.parse(html, new core.Slot([
2012
- core.ContentType.BlockComponent,
2013
- core.ContentType.InlineComponent,
2014
- core.ContentType.Text
2015
- ]));
2016
- this.commander.paste(slot, text);
2017
- }
2018
- handleShortcut(input) {
2019
- let isWriting = false;
2020
- let isIgnore = false;
2021
- this.subscription.add(stream.fromEvent(input, 'compositionstart').subscribe(() => {
2022
- isWriting = true;
2023
- }), stream.fromEvent(input, 'compositionend').subscribe(() => {
2024
- isWriting = false;
2025
- }), stream.fromEvent(input, 'beforeinput').subscribe(ev => {
2026
- if (this.isSafari) {
2027
- if (ev.inputType === 'insertFromComposition') {
2028
- isIgnore = true;
2029
- }
2030
- }
2031
- }), stream.fromEvent(input, 'keydown').pipe(stream.filter(() => {
2032
- if (this.isSafari && isIgnore) {
2033
- isIgnore = false;
2034
- return false;
2035
- }
2036
- return !isWriting; // || !this.textarea.value
2037
- })).subscribe(ev => {
2038
- let key = ev.key;
2039
- const b = key === 'Process' && ev.code === 'Digit2';
2040
- if (b) {
2041
- key = '@';
2042
- this.isSougouPinYin = true;
2043
- ev.preventDefault();
2044
- }
2045
- const is = this.keyboard.execShortcut({
2046
- key: key,
2047
- altKey: ev.altKey,
2048
- shiftKey: ev.shiftKey,
2049
- ctrlKey: this.isMac ? ev.metaKey : ev.ctrlKey
2050
- });
2051
- if (is) {
2052
- ev.preventDefault();
2053
- }
2054
- }));
2055
- }
2056
- handleInput(input) {
2057
- this.subscription.add(stream.fromEvent(input, 'compositionstart').subscribe(() => {
2058
- this.composition = true;
2059
- }), stream.merge(stream.fromEvent(input, 'beforeinput').pipe(stream.filter(ev => {
2060
- ev.preventDefault();
2061
- if (this.isSafari) {
2062
- return ev.inputType === 'insertText' || ev.inputType === 'insertFromComposition';
2063
- }
2064
- return !ev.isComposing && !!ev.data;
2065
- }), stream.map(ev => {
2066
- return ev.data;
2067
- })), this.isSafari ? new stream.Observable() : stream.fromEvent(input, 'compositionend').pipe(stream.map(ev => {
2068
- ev.preventDefault();
2069
- return ev.data;
2070
- }), stream.filter(() => {
2071
- const b = this.isSougouPinYin;
2072
- this.isSougouPinYin = false;
2073
- return !b;
2074
- }))).subscribe(text => {
2075
- this.composition = false;
2076
- if (text) {
2077
- this.commander.write(text);
2078
- }
2079
- }));
2080
- }
2081
- };
2082
- exports.NativeInput = __decorate([
2083
- di.Injectable(),
2084
- __metadata("design:paramtypes", [di.Injector,
2085
- exports.Parser,
2086
- core.Scheduler,
2087
- core.Selection,
2088
- core.Keyboard,
2089
- core.Commander,
2090
- core.Controller])
1807
+ class NativeCaret {
1808
+ set nativeRange(range) {
1809
+ this._nativeRange = range;
1810
+ if (range) {
1811
+ const r = range.cloneRange();
1812
+ r.collapse(true);
1813
+ const rect = r.getBoundingClientRect();
1814
+ this.positionChangeEvent.next({
1815
+ left: rect.left,
1816
+ top: rect.top,
1817
+ height: rect.height
1818
+ });
1819
+ }
1820
+ else {
1821
+ this.positionChangeEvent.next(null);
1822
+ }
1823
+ }
1824
+ get nativeRange() {
1825
+ return this._nativeRange;
1826
+ }
1827
+ get rect() {
1828
+ if (this.nativeRange) {
1829
+ const range = this.nativeRange.cloneRange();
1830
+ range.collapse(true);
1831
+ return range.getBoundingClientRect();
1832
+ }
1833
+ return {
1834
+ left: 0,
1835
+ top: 0,
1836
+ width: 0,
1837
+ height: 0
1838
+ };
1839
+ }
1840
+ constructor(scheduler) {
1841
+ this.scheduler = scheduler;
1842
+ this.oldPosition = null;
1843
+ this._nativeRange = null;
1844
+ this.subs = [];
1845
+ this.positionChangeEvent = new stream.Subject();
1846
+ this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1847
+ }
1848
+ refresh() {
1849
+ //
1850
+ }
1851
+ correctScrollTop(scroller) {
1852
+ this.destroy();
1853
+ const scheduler = this.scheduler;
1854
+ let docIsChanged = true;
1855
+ function limitPosition(position) {
1856
+ const { top, bottom } = scroller.getLimit();
1857
+ const caretTop = position.top;
1858
+ if (caretTop + position.height > bottom) {
1859
+ const offset = caretTop - bottom + position.height;
1860
+ scroller.setOffset(offset);
1861
+ }
1862
+ else if (position.top < top) {
1863
+ scroller.setOffset(-(top - position.top));
1864
+ }
1865
+ }
1866
+ let isPressed = false;
1867
+ this.subs.push(scroller.onScroll.subscribe(() => {
1868
+ if (this.oldPosition) {
1869
+ const rect = this.rect;
1870
+ this.oldPosition.top = rect.top;
1871
+ this.oldPosition.left = rect.left;
1872
+ this.oldPosition.height = rect.height;
1873
+ }
1874
+ }), stream.fromEvent(document, 'mousedown', true).subscribe(() => {
1875
+ isPressed = true;
1876
+ }), stream.fromEvent(document, 'mouseup', true).subscribe(() => {
1877
+ isPressed = false;
1878
+ }), scheduler.onDocChange.subscribe(() => {
1879
+ docIsChanged = true;
1880
+ }), this.onPositionChange.subscribe(position => {
1881
+ if (position) {
1882
+ if (docIsChanged) {
1883
+ if (scheduler.lastChangesHasLocalUpdate) {
1884
+ limitPosition(position);
1885
+ }
1886
+ else if (this.oldPosition) {
1887
+ const offset = Math.floor(position.top - this.oldPosition.top);
1888
+ scroller.setOffset(offset);
1889
+ }
1890
+ }
1891
+ else if (!isPressed) {
1892
+ if (this.oldPosition) {
1893
+ const offset = Math.floor(position.top - this.oldPosition.top);
1894
+ scroller.setOffset(offset);
1895
+ }
1896
+ else {
1897
+ limitPosition(position);
1898
+ }
1899
+ }
1900
+ }
1901
+ docIsChanged = false;
1902
+ }));
1903
+ }
1904
+ destroy() {
1905
+ this.subs.forEach(i => i.unsubscribe());
1906
+ this.subs = [];
1907
+ }
1908
+ }
1909
+ exports.NativeInput = class NativeInput extends Input {
1910
+ set disabled(b) {
1911
+ this._disabled = b;
1912
+ if (b && !this.controller.readonly) {
1913
+ this.documentView.contentEditable = b ? 'true' : 'false';
1914
+ }
1915
+ }
1916
+ get disabled() {
1917
+ return this._disabled;
1918
+ }
1919
+ constructor(injector, parser, scheduler, selection, keyboard, commander, controller) {
1920
+ super();
1921
+ this.injector = injector;
1922
+ this.parser = parser;
1923
+ this.scheduler = scheduler;
1924
+ this.selection = selection;
1925
+ this.keyboard = keyboard;
1926
+ this.commander = commander;
1927
+ this.controller = controller;
1928
+ this.caret = new NativeCaret(this.scheduler);
1929
+ this.composition = false;
1930
+ this.onReady = Promise.resolve();
1931
+ this._disabled = false;
1932
+ this.nativeSelection = document.getSelection();
1933
+ this.subscription = new stream.Subscription();
1934
+ this.nativeRange = null;
1935
+ this.isSafari = isSafari();
1936
+ this.isMac = isMac();
1937
+ this.isSougouPinYin = false; // 有 bug 版本搜狗拼音
1938
+ this.documentView = injector.get(VIEW_DOCUMENT);
1939
+ if (!controller.readonly) {
1940
+ this.documentView.contentEditable = 'true';
1941
+ }
1942
+ this.subscription.add(controller.onReadonlyStateChange.subscribe(() => {
1943
+ this.documentView.contentEditable = controller.readonly ? 'false' : 'true';
1944
+ }));
1945
+ this.handleShortcut(this.documentView);
1946
+ this.handleInput(this.documentView);
1947
+ this.handleDefaultActions(this.documentView);
1948
+ }
1949
+ focus(nativeRange) {
1950
+ if (this.controller.readonly) {
1951
+ return;
1952
+ }
1953
+ this.caret.nativeRange = nativeRange;
1954
+ this.nativeRange = nativeRange;
1955
+ }
1956
+ blur() {
1957
+ if (this.nativeRange && this.nativeSelection.rangeCount > 0) {
1958
+ const current = this.nativeSelection.getRangeAt(0);
1959
+ if (current === this.nativeRange) {
1960
+ this.nativeSelection.removeAllRanges();
1961
+ this.nativeRange = null;
1962
+ return;
1963
+ }
1964
+ }
1965
+ }
1966
+ destroy() {
1967
+ this.caret.destroy();
1968
+ this.subscription.unsubscribe();
1969
+ }
1970
+ handleDefaultActions(textarea) {
1971
+ this.subscription.add(stream.fromEvent(document, 'copy').subscribe(ev => {
1972
+ const selection = this.selection;
1973
+ if (!selection.isSelected) {
1974
+ return;
1975
+ }
1976
+ if (selection.startSlot === selection.endSlot && selection.endOffset - selection.startOffset === 1) {
1977
+ const content = selection.startSlot.getContentAtIndex(selection.startOffset);
1978
+ if (typeof content === 'object') {
1979
+ const clipboardData = ev.clipboardData;
1980
+ const nativeSelection = document.getSelection();
1981
+ const range = nativeSelection.getRangeAt(0);
1982
+ const div = document.createElement('div');
1983
+ const fragment = range.cloneContents();
1984
+ div.append(fragment);
1985
+ clipboardData.setData('text/html', div.innerHTML);
1986
+ clipboardData.setData('text', div.innerText);
1987
+ ev.preventDefault();
1988
+ }
1989
+ }
1990
+ }), stream.fromEvent(textarea, 'paste').subscribe(ev => {
1991
+ const text = ev.clipboardData.getData('Text');
1992
+ const files = Array.from(ev.clipboardData.files);
1993
+ if (files.length) {
1994
+ Promise.all(files.filter(i => {
1995
+ return /image/i.test(i.type);
1996
+ }).map(item => {
1997
+ const reader = new FileReader();
1998
+ return new Promise(resolve => {
1999
+ reader.onload = (event) => {
2000
+ resolve(event.target.result);
2001
+ };
2002
+ reader.readAsDataURL(item);
2003
+ });
2004
+ })).then(urls => {
2005
+ const html = urls.map(i => {
2006
+ return `<img src=${i}>`;
2007
+ }).join('');
2008
+ this.handlePaste(html, text);
2009
+ });
2010
+ ev.preventDefault();
2011
+ return;
2012
+ }
2013
+ const div = document.createElement('div');
2014
+ div.style.cssText = 'width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0';
2015
+ div.contentEditable = 'true';
2016
+ document.body.appendChild(div);
2017
+ div.focus();
2018
+ setTimeout(() => {
2019
+ const html = div.innerHTML;
2020
+ this.handlePaste(html, text);
2021
+ document.body.removeChild(div);
2022
+ });
2023
+ }));
2024
+ }
2025
+ handlePaste(html, text) {
2026
+ const slot = this.parser.parse(html, new core.Slot([
2027
+ core.ContentType.BlockComponent,
2028
+ core.ContentType.InlineComponent,
2029
+ core.ContentType.Text
2030
+ ]));
2031
+ this.commander.paste(slot, text);
2032
+ }
2033
+ handleShortcut(input) {
2034
+ let isWriting = false;
2035
+ let isIgnore = false;
2036
+ this.subscription.add(stream.fromEvent(input, 'compositionstart').subscribe(() => {
2037
+ isWriting = true;
2038
+ }), stream.fromEvent(input, 'compositionend').subscribe(() => {
2039
+ isWriting = false;
2040
+ }), stream.fromEvent(input, 'beforeinput').subscribe(ev => {
2041
+ if (this.isSafari) {
2042
+ if (ev.inputType === 'insertFromComposition') {
2043
+ isIgnore = true;
2044
+ }
2045
+ }
2046
+ }), stream.fromEvent(input, 'keydown').pipe(stream.filter(() => {
2047
+ if (this.isSafari && isIgnore) {
2048
+ isIgnore = false;
2049
+ return false;
2050
+ }
2051
+ return !isWriting; // || !this.textarea.value
2052
+ })).subscribe(ev => {
2053
+ let key = ev.key;
2054
+ const b = key === 'Process' && ev.code === 'Digit2';
2055
+ if (b) {
2056
+ key = '@';
2057
+ this.isSougouPinYin = true;
2058
+ ev.preventDefault();
2059
+ }
2060
+ const is = this.keyboard.execShortcut({
2061
+ key: key,
2062
+ altKey: ev.altKey,
2063
+ shiftKey: ev.shiftKey,
2064
+ ctrlKey: this.isMac ? ev.metaKey : ev.ctrlKey
2065
+ });
2066
+ if (is) {
2067
+ ev.preventDefault();
2068
+ }
2069
+ }));
2070
+ }
2071
+ handleInput(input) {
2072
+ this.subscription.add(stream.fromEvent(input, 'compositionstart').subscribe(() => {
2073
+ this.composition = true;
2074
+ }), stream.merge(stream.fromEvent(input, 'beforeinput').pipe(stream.filter(ev => {
2075
+ ev.preventDefault();
2076
+ if (this.isSafari) {
2077
+ return ev.inputType === 'insertText' || ev.inputType === 'insertFromComposition';
2078
+ }
2079
+ return !ev.isComposing && !!ev.data;
2080
+ }), stream.map(ev => {
2081
+ return ev.data;
2082
+ })), this.isSafari ? new stream.Observable() : stream.fromEvent(input, 'compositionend').pipe(stream.map(ev => {
2083
+ ev.preventDefault();
2084
+ return ev.data;
2085
+ }), stream.filter(() => {
2086
+ const b = this.isSougouPinYin;
2087
+ this.isSougouPinYin = false;
2088
+ return !b;
2089
+ }))).subscribe(text => {
2090
+ this.composition = false;
2091
+ if (text) {
2092
+ this.commander.write(text);
2093
+ }
2094
+ }));
2095
+ }
2096
+ };
2097
+ exports.NativeInput = __decorate([
2098
+ di.Injectable(),
2099
+ __metadata("design:paramtypes", [di.Injector,
2100
+ exports.Parser,
2101
+ core.Scheduler,
2102
+ core.Selection,
2103
+ core.Keyboard,
2104
+ core.Commander,
2105
+ core.Controller])
2091
2106
  ], exports.NativeInput);
2092
2107
 
2093
- var OutputTranslator_1;
2094
- /**
2095
- * HTML 输出转换器
2096
- */
2097
- exports.OutputTranslator = OutputTranslator_1 = class OutputTranslator {
2098
- constructor() {
2099
- this.singleTagTest = new RegExp(`^(${OutputTranslator_1.singleTags.join('|')})$`, 'i');
2100
- }
2101
- transform(vDom) {
2102
- return vDom.children.map(child => {
2103
- return this.vDomToHTMLString(child);
2104
- }).join('');
2105
- }
2106
- vDomToHTMLString(vDom) {
2107
- const xssFilter = OutputTranslator_1.simpleXSSFilter;
2108
- if (vDom instanceof core.VTextNode) {
2109
- return this.replaceEmpty(xssFilter.text(vDom.textContent), '&nbsp;');
2110
- }
2111
- const styles = Array.from(vDom.styles.keys()).filter(key => {
2112
- const v = vDom.styles.get(key);
2113
- return !(v === undefined || v === null || v === '');
2114
- }).map(key => {
2115
- const k = key.replace(/(?=[A-Z])/g, '-').toLowerCase();
2116
- return xssFilter.attrValue(`${k}:${vDom.styles.get(key)}`);
2117
- }).join(';');
2118
- const attrs = Array.from(vDom.attrs.keys()).filter(key => key !== 'ref' && vDom.attrs.get(key) !== false).map(k => {
2119
- const key = xssFilter.attrName(k);
2120
- const value = vDom.attrs.get(k);
2121
- return (value === true ? `${key}` : `${key}="${xssFilter.attrValue(`${value}`)}"`);
2122
- });
2123
- if (styles) {
2124
- attrs.push(`style="${styles}"`);
2125
- }
2126
- if (vDom.classes && vDom.classes.size) {
2127
- attrs.push(`class="${xssFilter.attrValue(Array.from(vDom.classes).join(' '))}"`);
2128
- }
2129
- let attrStr = attrs.join(' ');
2130
- attrStr = attrStr ? ' ' + attrStr : '';
2131
- if (this.singleTagTest.test(vDom.tagName)) {
2132
- return `<${vDom.tagName}${attrStr}>`;
2133
- }
2134
- const childHTML = vDom.children.map(child => {
2135
- return this.vDomToHTMLString(child);
2136
- }).join('');
2137
- return [
2138
- `<${vDom.tagName}${attrStr}>`,
2139
- childHTML,
2140
- `</${vDom.tagName}>`
2141
- ].join('');
2142
- }
2143
- replaceEmpty(s, target) {
2144
- return s.replace(/\s\s+/g, str => {
2145
- return ' ' + Array.from({
2146
- length: str.length - 1
2147
- }).fill(target).join('');
2148
- }).replace(/^\s|\s$/g, target);
2149
- }
2150
- };
2151
- exports.OutputTranslator.singleTags = 'br,img,hr'.split(',');
2152
- exports.OutputTranslator.simpleXSSFilter = {
2153
- text(text) {
2154
- return text.replace(/[><&]/g, str => {
2155
- return {
2156
- '<': '&lt;',
2157
- '>': '&gt;',
2158
- '&': '&amp;'
2159
- }[str];
2160
- });
2161
- },
2162
- attrName(text) {
2163
- return text.replace(/[><"'&]/g, str => {
2164
- return {
2165
- '<': '&lt;',
2166
- '>': '&gt;',
2167
- '"': '&quot;',
2168
- '\'': '&#x27;',
2169
- '&': '&amp;'
2170
- }[str];
2171
- });
2172
- },
2173
- attrValue(text) {
2174
- return text.replace(/["']/g, str => {
2175
- return {
2176
- '"': '&quot;',
2177
- '\'': '&#x27;'
2178
- }[str];
2179
- });
2180
- }
2181
- };
2182
- exports.OutputTranslator = OutputTranslator_1 = __decorate([
2183
- di.Injectable()
2108
+ var OutputTranslator_1;
2109
+ /**
2110
+ * HTML 输出转换器
2111
+ */
2112
+ exports.OutputTranslator = OutputTranslator_1 = class OutputTranslator {
2113
+ constructor() {
2114
+ this.singleTagTest = new RegExp(`^(${OutputTranslator_1.singleTags.join('|')})$`, 'i');
2115
+ }
2116
+ transform(vDom) {
2117
+ return vDom.children.map(child => {
2118
+ return this.vDomToHTMLString(child);
2119
+ }).join('');
2120
+ }
2121
+ vDomToHTMLString(vDom) {
2122
+ const xssFilter = OutputTranslator_1.simpleXSSFilter;
2123
+ if (vDom instanceof core.VTextNode) {
2124
+ return this.replaceEmpty(xssFilter.text(vDom.textContent), '&nbsp;');
2125
+ }
2126
+ const styles = Array.from(vDom.styles.keys()).filter(key => {
2127
+ const v = vDom.styles.get(key);
2128
+ return !(v === undefined || v === null || v === '');
2129
+ }).map(key => {
2130
+ const k = key.replace(/(?=[A-Z])/g, '-').toLowerCase();
2131
+ return xssFilter.attrValue(`${k}:${vDom.styles.get(key)}`);
2132
+ }).join(';');
2133
+ const attrs = Array.from(vDom.attrs.keys()).filter(key => key !== 'ref' && vDom.attrs.get(key) !== false).map(k => {
2134
+ const key = xssFilter.attrName(k);
2135
+ const value = vDom.attrs.get(k);
2136
+ return (value === true ? `${key}` : `${key}="${xssFilter.attrValue(`${value}`)}"`);
2137
+ });
2138
+ if (styles) {
2139
+ attrs.push(`style="${styles}"`);
2140
+ }
2141
+ if (vDom.classes && vDom.classes.size) {
2142
+ attrs.push(`class="${xssFilter.attrValue(Array.from(vDom.classes).join(' '))}"`);
2143
+ }
2144
+ let attrStr = attrs.join(' ');
2145
+ attrStr = attrStr ? ' ' + attrStr : '';
2146
+ if (this.singleTagTest.test(vDom.tagName)) {
2147
+ return `<${vDom.tagName}${attrStr}>`;
2148
+ }
2149
+ const childHTML = vDom.children.map(child => {
2150
+ return this.vDomToHTMLString(child);
2151
+ }).join('');
2152
+ return [
2153
+ `<${vDom.tagName}${attrStr}>`,
2154
+ childHTML,
2155
+ `</${vDom.tagName}>`
2156
+ ].join('');
2157
+ }
2158
+ replaceEmpty(s, target) {
2159
+ return s.replace(/\s\s+/g, str => {
2160
+ return ' ' + Array.from({
2161
+ length: str.length - 1
2162
+ }).fill(target).join('');
2163
+ }).replace(/^\s|\s$/g, target);
2164
+ }
2165
+ };
2166
+ exports.OutputTranslator.singleTags = 'br,img,hr'.split(',');
2167
+ exports.OutputTranslator.simpleXSSFilter = {
2168
+ text(text) {
2169
+ return text.replace(/[><&]/g, str => {
2170
+ return {
2171
+ '<': '&lt;',
2172
+ '>': '&gt;',
2173
+ '&': '&amp;'
2174
+ }[str];
2175
+ });
2176
+ },
2177
+ attrName(text) {
2178
+ return text.replace(/[><"'&]/g, str => {
2179
+ return {
2180
+ '<': '&lt;',
2181
+ '>': '&gt;',
2182
+ '"': '&quot;',
2183
+ '\'': '&#x27;',
2184
+ '&': '&amp;'
2185
+ }[str];
2186
+ });
2187
+ },
2188
+ attrValue(text) {
2189
+ return text.replace(/["']/g, str => {
2190
+ return {
2191
+ '"': '&quot;',
2192
+ '\'': '&#x27;'
2193
+ }[str];
2194
+ });
2195
+ }
2196
+ };
2197
+ exports.OutputTranslator = OutputTranslator_1 = __decorate([
2198
+ di.Injectable()
2184
2199
  ], exports.OutputTranslator);
2185
2200
 
2186
- /**
2187
- * Textbus PC 端默认按键绑定
2188
- */
2189
- function setDefaultShortcut(injector) {
2190
- const selection = injector.get(core.Selection);
2191
- const keyboard = injector.get(core.Keyboard);
2192
- const history = injector.get(core.History);
2193
- const commander = injector.get(core.Commander);
2194
- keyboard.addShortcut({
2195
- keymap: {
2196
- key: 'Enter'
2197
- },
2198
- action: () => {
2199
- commander.break();
2200
- }
2201
- });
2202
- keyboard.addShortcut({
2203
- keymap: {
2204
- key: 'Enter',
2205
- shiftKey: true
2206
- },
2207
- action: () => {
2208
- const startOffset = selection.startOffset;
2209
- const startSlot = selection.startSlot;
2210
- const isToEnd = startOffset === startSlot.length || startSlot.isEmpty;
2211
- const content = isToEnd ? '\n\n' : '\n';
2212
- const isInserted = commander.insert(content);
2213
- if (isInserted && isToEnd) {
2214
- selection.setPosition(startSlot, startOffset + 1);
2215
- }
2216
- }
2217
- });
2218
- keyboard.addShortcut({
2219
- keymap: {
2220
- key: ['Delete', 'Backspace']
2221
- },
2222
- action: (key) => {
2223
- commander.delete(key === 'Backspace');
2224
- }
2225
- });
2226
- keyboard.addShortcut({
2227
- keymap: {
2228
- key: ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']
2229
- },
2230
- action: (key) => {
2231
- switch (key) {
2232
- case 'ArrowLeft':
2233
- selection.toPrevious();
2234
- break;
2235
- case 'ArrowRight':
2236
- selection.toNext();
2237
- break;
2238
- case 'ArrowUp':
2239
- selection.toPreviousLine();
2240
- break;
2241
- case 'ArrowDown':
2242
- selection.toNextLine();
2243
- break;
2244
- }
2245
- }
2246
- });
2247
- keyboard.addShortcut({
2248
- keymap: {
2249
- key: ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'],
2250
- shiftKey: true
2251
- },
2252
- action: (key) => {
2253
- switch (key) {
2254
- case 'ArrowLeft':
2255
- selection.wrapToBefore();
2256
- break;
2257
- case 'ArrowRight':
2258
- selection.wrapToAfter();
2259
- break;
2260
- case 'ArrowUp':
2261
- selection.wrapToPreviousLine();
2262
- break;
2263
- case 'ArrowDown':
2264
- selection.wrapToNextLine();
2265
- break;
2266
- }
2267
- }
2268
- });
2269
- keyboard.addShortcut({
2270
- keymap: {
2271
- key: 'Tab'
2272
- },
2273
- action: () => {
2274
- commander.insert(' ');
2275
- }
2276
- });
2277
- keyboard.addShortcut({
2278
- keymap: {
2279
- key: 'a',
2280
- ctrlKey: true
2281
- },
2282
- action: () => {
2283
- selection.selectAll();
2284
- }
2285
- });
2286
- keyboard.addShortcut({
2287
- keymap: {
2288
- key: 'c',
2289
- ctrlKey: true
2290
- },
2291
- action: () => {
2292
- commander.copy();
2293
- }
2294
- });
2295
- keyboard.addShortcut({
2296
- keymap: {
2297
- key: 'x',
2298
- ctrlKey: true
2299
- },
2300
- action: () => {
2301
- commander.cut();
2302
- }
2303
- });
2304
- keyboard.addShortcut({
2305
- keymap: {
2306
- key: 'z',
2307
- ctrlKey: true
2308
- },
2309
- action: () => {
2310
- history.back();
2311
- }
2312
- });
2313
- keyboard.addShortcut({
2314
- keymap: {
2315
- key: 'z',
2316
- ctrlKey: true,
2317
- shiftKey: true
2318
- },
2319
- action: () => {
2320
- history.forward();
2321
- }
2322
- });
2323
- }
2324
-
2325
- const editorError = core.makeError('CoreEditor');
2326
- /**
2327
- * Textbus PC 端编辑器
2328
- */
2329
- class Viewer extends core.Starter {
2330
- constructor(rootComponent, rootComponentLoader, options = {}) {
2331
- const id = 'textbus-' + Number((Math.random() + '').substring(2)).toString(16);
2332
- const { doc, mask, wrapper } = Viewer.createLayout(id, options.minHeight);
2333
- const staticProviders = [{
2334
- provide: EDITOR_OPTIONS,
2335
- useValue: options
2336
- }, {
2337
- provide: VIEW_CONTAINER,
2338
- useValue: wrapper
2339
- }, {
2340
- provide: VIEW_DOCUMENT,
2341
- useValue: doc
2342
- }, {
2343
- provide: VIEW_MASK,
2344
- useValue: mask
2345
- }, {
2346
- provide: core.NativeRenderer,
2347
- useExisting: exports.DomRenderer
2348
- }, {
2349
- provide: core.NativeSelectionBridge,
2350
- useExisting: exports.SelectionBridge
2351
- }, {
2352
- provide: Input,
2353
- useClass: options.useContentEditable ? exports.NativeInput : exports.MagicInput
2354
- }, {
2355
- provide: Viewer,
2356
- useFactory: () => this
2357
- }];
2358
- super(Object.assign(Object.assign({}, options), { plugins: options.plugins || [], providers: [
2359
- ...(options.providers || []),
2360
- ...staticProviders,
2361
- exports.DomRenderer,
2362
- exports.Parser,
2363
- exports.SelectionBridge,
2364
- exports.OutputTranslator,
2365
- exports.CollaborateCursor
2366
- ], setup: options.setup }));
2367
- this.rootComponent = rootComponent;
2368
- this.rootComponentLoader = rootComponentLoader;
2369
- this.options = options;
2370
- /** 编辑器是否已销毁 */
2371
- this.destroyed = false;
2372
- /** 编辑器是否已准备好 */
2373
- this.isReady = false;
2374
- this.changeEvent = new stream.Subject();
2375
- this.subs = [];
2376
- this._isFocus = false;
2377
- this.resourceNodes = [];
2378
- this.focusEvent = new stream.Subject();
2379
- this.blurEvent = new stream.Subject();
2380
- this.saveEvent = new stream.Subject();
2381
- this.styleSheet = '';
2382
- this.scripts = [];
2383
- this.links = [];
2384
- this.id = id;
2385
- this.workbench = wrapper;
2386
- this.onChange = this.changeEvent.asObservable();
2387
- this.onFocus = this.focusEvent.asObservable();
2388
- this.onBlur = this.blurEvent.asObservable();
2389
- this.onSave = this.saveEvent.asObservable();
2390
- this.controller = this.get(core.Controller);
2391
- }
2392
- get readonly() {
2393
- return this.controller.readonly;
2394
- }
2395
- set readonly(b) {
2396
- this.controller.readonly = b;
2397
- }
2398
- isFocus() {
2399
- return this._isFocus;
2400
- }
2401
- /**
2402
- * 初始化编辑器
2403
- * @param host 编辑器容器
2404
- */
2405
- mount(host) {
2406
- const _super = Object.create(null, {
2407
- mount: { get: () => super.mount }
2408
- });
2409
- return __awaiter(this, void 0, void 0, function* () {
2410
- if (this.destroyed) {
2411
- throw editorError('the editor instance is destroyed!');
2412
- }
2413
- if (this.destroyed) {
2414
- return this;
2415
- }
2416
- const parser = this.get(exports.Parser);
2417
- const registry = this.get(core.Registry);
2418
- const doc = this.get(VIEW_DOCUMENT);
2419
- const keyboard = this.get(core.Keyboard);
2420
- keyboard.addShortcut({
2421
- keymap: {
2422
- key: 's',
2423
- ctrlKey: true
2424
- },
2425
- action: () => {
2426
- this.saveEvent.next();
2427
- }
2428
- });
2429
- setDefaultShortcut(this);
2430
- let component;
2431
- const content = this.options.content;
2432
- if (content) {
2433
- if (typeof content === 'string') {
2434
- component = parser.parseDoc(content, this.rootComponentLoader);
2435
- }
2436
- else {
2437
- component = registry.createComponentByFactory(content, this.rootComponent);
2438
- }
2439
- }
2440
- else {
2441
- component = this.rootComponent.createInstance(this);
2442
- }
2443
- this.initDocStyleSheetsAndScripts(this.options);
2444
- host.appendChild(this.workbench);
2445
- yield _super.mount.call(this, doc, component);
2446
- const renderer = this.get(core.Renderer);
2447
- const input = this.get(Input);
2448
- this.subs.push(renderer.onViewUpdated.subscribe(() => {
2449
- this.changeEvent.next();
2450
- }), input.caret.onPositionChange.pipe(stream.map(p => !!p), stream.distinctUntilChanged()).subscribe(b => {
2451
- if (b) {
2452
- this._isFocus = true;
2453
- this.focusEvent.next();
2454
- }
2455
- else {
2456
- this._isFocus = false;
2457
- this.blurEvent.next();
2458
- }
2459
- }));
2460
- this.isReady = true;
2461
- if (this.options.autoFocus) {
2462
- input.onReady.then(() => {
2463
- this.focus();
2464
- });
2465
- }
2466
- return this;
2467
- });
2468
- }
2469
- /**
2470
- * 获取焦点
2471
- */
2472
- focus() {
2473
- this.guardReady();
2474
- const selection = this.get(core.Selection);
2475
- const rootComponentRef = this.get(core.RootComponentRef);
2476
- if (selection.commonAncestorSlot) {
2477
- selection.restore();
2478
- return;
2479
- }
2480
- const location = selection.findFirstPosition(rootComponentRef.component.slots.get(0));
2481
- selection.setPosition(location.slot, location.offset);
2482
- selection.restore();
2483
- }
2484
- /**
2485
- * 取消编辑器焦点
2486
- */
2487
- blur() {
2488
- if (this.isReady) {
2489
- const selection = this.get(core.Selection);
2490
- selection.unSelect();
2491
- selection.restore();
2492
- }
2493
- }
2494
- /**
2495
- * 获取编辑器所有资源
2496
- */
2497
- getResources() {
2498
- var _a;
2499
- return {
2500
- styleSheets: ((_a = this.options) === null || _a === void 0 ? void 0 : _a.styleSheets) || [],
2501
- styleSheet: this.styleSheet,
2502
- links: this.links,
2503
- scripts: this.scripts
2504
- };
2505
- }
2506
- /**
2507
- * 获取 HTML 格式的内容
2508
- */
2509
- getHTML() {
2510
- this.guardReady();
2511
- const outputRenderer = this.get(core.OutputRenderer);
2512
- const outputTranslator = this.get(exports.OutputTranslator);
2513
- const vDom = outputRenderer.render();
2514
- return outputTranslator.transform(vDom);
2515
- }
2516
- /**
2517
- * 获取 JSON 格式的内容
2518
- */
2519
- getJSON() {
2520
- this.guardReady();
2521
- const rootComponentRef = this.get(core.RootComponentRef);
2522
- return rootComponentRef.component.toJSON();
2523
- }
2524
- /**
2525
- * 销毁编辑器
2526
- */
2527
- destroy() {
2528
- var _a;
2529
- if (this.destroyed) {
2530
- return;
2531
- }
2532
- this.destroyed = true;
2533
- this.subs.forEach(i => i.unsubscribe());
2534
- const types = [
2535
- Input
2536
- ];
2537
- types.forEach(i => {
2538
- this.get(i).destroy();
2539
- });
2540
- super.destroy();
2541
- (_a = this.workbench.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.workbench);
2542
- this.resourceNodes.forEach(node => {
2543
- var _a;
2544
- (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(node);
2545
- });
2546
- }
2547
- /**
2548
- * 替换编辑的内容
2549
- * @param content
2550
- */
2551
- replaceContent(content) {
2552
- this.guardReady();
2553
- const parser = this.get(exports.Parser);
2554
- const registry = this.get(core.Registry);
2555
- const rootComponentRef = this.get(core.RootComponentRef);
2556
- const selection = this.get(core.Selection);
2557
- const rootComponentLoader = this.rootComponentLoader;
2558
- let component;
2559
- if (typeof content === 'string') {
2560
- component = parser.parseDoc(content, rootComponentLoader);
2561
- }
2562
- else {
2563
- component = registry.createComponentByFactory(content, this.rootComponent);
2564
- }
2565
- selection.unSelect();
2566
- rootComponentRef.component.slots.clean();
2567
- rootComponentRef.component.slots.push(...component.slots.toArray());
2568
- core.invokeListener(component, 'onDestroy');
2569
- }
2570
- guardReady() {
2571
- if (this.destroyed) {
2572
- throw editorError('the editor instance is destroyed!');
2573
- }
2574
- if (!this.isReady) {
2575
- throw editorError('please wait for the editor to initialize before getting the content!');
2576
- }
2577
- }
2578
- initDocStyleSheetsAndScripts(options) {
2579
- var _a;
2580
- const loaders = [];
2581
- (_a = options.imports) === null || _a === void 0 ? void 0 : _a.forEach(module => {
2582
- loaders.push(...(module.componentLoaders || []));
2583
- });
2584
- loaders.push(...(options.componentLoaders || []));
2585
- const resources = loaders.filter(i => i.resources).map(i => i.resources);
2586
- const docStyles = [];
2587
- const editModeStyles = [];
2588
- resources.forEach(metadata => {
2589
- var _a, _b;
2590
- if (Array.isArray(metadata.links)) {
2591
- this.links.push(...metadata.links);
2592
- }
2593
- docStyles.push(((_a = metadata.styles) === null || _a === void 0 ? void 0 : _a.join('')) || '');
2594
- editModeStyles.push(((_b = metadata.editModeStyles) === null || _b === void 0 ? void 0 : _b.join('')) || '');
2595
- });
2596
- this.links.forEach(link => {
2597
- const linkEle = document.createElement('link');
2598
- Object.assign(linkEle, link);
2599
- this.resourceNodes.push(linkEle);
2600
- document.head.appendChild(linkEle);
2601
- });
2602
- const styleEl = document.createElement('style');
2603
- docStyles.push(...(options.styleSheets || []));
2604
- editModeStyles.push(`#${this.id} *::selection{background-color: rgba(18, 150, 219, .2); color:inherit}`, ...(options.editingStyleSheets || []));
2605
- this.styleSheet = Viewer.cssMin(docStyles.join(''));
2606
- styleEl.innerHTML = this.styleSheet + Viewer.cssMin(editModeStyles.join(''));
2607
- this.resourceNodes.push(styleEl);
2608
- document.head.append(styleEl);
2609
- resources.filter(i => { var _a; return (_a = i.scripts) === null || _a === void 0 ? void 0 : _a.length; }).map(i => i.scripts).flat().forEach(src => {
2610
- if (src) {
2611
- const script = document.createElement('script');
2612
- script.src = src;
2613
- this.scripts.push(src);
2614
- document.head.appendChild(script);
2615
- this.resourceNodes.push(script);
2616
- }
2617
- });
2618
- }
2619
- static createLayout(id, minHeight = '100%') {
2620
- const doc = createElement('div', {
2621
- styles: {
2622
- cursor: 'text',
2623
- wordBreak: 'break-all',
2624
- boxSizing: 'border-box',
2625
- minHeight,
2626
- flex: 1,
2627
- outline: 'none'
2628
- },
2629
- attrs: {
2630
- 'data-textbus-view': VIEW_DOCUMENT,
2631
- },
2632
- props: {
2633
- id
2634
- }
2635
- });
2636
- const mask = createElement('div', {
2637
- attrs: {
2638
- 'data-textbus-view': VIEW_MASK,
2639
- },
2640
- styles: {
2641
- position: 'absolute',
2642
- left: 0,
2643
- right: 0,
2644
- top: 0,
2645
- bottom: 0,
2646
- zIndex: 1,
2647
- pointerEvents: 'none',
2648
- overflow: 'hidden'
2649
- }
2650
- });
2651
- const wrapper = createElement('div', {
2652
- attrs: {
2653
- 'data-textbus-view': VIEW_CONTAINER,
2654
- },
2655
- styles: {
2656
- display: 'flex',
2657
- minHeight: '100%',
2658
- position: 'relative',
2659
- flexDirection: 'column'
2660
- },
2661
- children: [doc, mask]
2662
- });
2663
- return {
2664
- wrapper,
2665
- doc,
2666
- mask
2667
- };
2668
- }
2669
- static cssMin(str) {
2670
- return str
2671
- .replace(/\s*(?=[>{}:;,[])/g, '')
2672
- .replace(/([>{}:;,])\s*/g, '$1')
2673
- .replace(/;}/g, '}').replace(/\s+/, ' ').trim();
2674
- }
2201
+ const editorError = core.makeError('CoreEditor');
2202
+ /**
2203
+ * Textbus PC 端编辑器
2204
+ */
2205
+ class Viewer extends core.Starter {
2206
+ get readonly() {
2207
+ return this.controller.readonly;
2208
+ }
2209
+ set readonly(b) {
2210
+ this.controller.readonly = b;
2211
+ }
2212
+ isFocus() {
2213
+ return this._isFocus;
2214
+ }
2215
+ constructor(rootComponent, rootComponentLoader, options = {}) {
2216
+ const id = 'textbus-' + Number((Math.random() + '').substring(2)).toString(16);
2217
+ const { doc, mask, wrapper } = Viewer.createLayout(id, options.minHeight);
2218
+ const staticProviders = [{
2219
+ provide: EDITOR_OPTIONS,
2220
+ useValue: options
2221
+ }, {
2222
+ provide: VIEW_CONTAINER,
2223
+ useValue: wrapper
2224
+ }, {
2225
+ provide: VIEW_DOCUMENT,
2226
+ useValue: doc
2227
+ }, {
2228
+ provide: VIEW_MASK,
2229
+ useValue: mask
2230
+ }, {
2231
+ provide: core.NativeRenderer,
2232
+ useExisting: exports.DomRenderer
2233
+ }, {
2234
+ provide: core.NativeSelectionBridge,
2235
+ useExisting: exports.SelectionBridge
2236
+ }, {
2237
+ provide: Input,
2238
+ useClass: options.useContentEditable ? exports.NativeInput : exports.MagicInput
2239
+ }, {
2240
+ provide: Viewer,
2241
+ useFactory: () => this
2242
+ }];
2243
+ super(Object.assign(Object.assign({}, options), { plugins: options.plugins || [], providers: [
2244
+ ...(options.providers || []),
2245
+ ...staticProviders,
2246
+ exports.DomRenderer,
2247
+ exports.Parser,
2248
+ exports.SelectionBridge,
2249
+ exports.OutputTranslator,
2250
+ exports.CollaborateCursor
2251
+ ], setup: options.setup }));
2252
+ this.rootComponent = rootComponent;
2253
+ this.rootComponentLoader = rootComponentLoader;
2254
+ this.options = options;
2255
+ /** 编辑器是否已销毁 */
2256
+ this.destroyed = false;
2257
+ /** 编辑器是否已准备好 */
2258
+ this.isReady = false;
2259
+ this.changeEvent = new stream.Subject();
2260
+ this.subs = [];
2261
+ this._isFocus = false;
2262
+ this.resourceNodes = [];
2263
+ this.focusEvent = new stream.Subject();
2264
+ this.blurEvent = new stream.Subject();
2265
+ this.saveEvent = new stream.Subject();
2266
+ this.styleSheet = '';
2267
+ this.scripts = [];
2268
+ this.links = [];
2269
+ this.id = id;
2270
+ this.workbench = wrapper;
2271
+ this.onChange = this.changeEvent.asObservable();
2272
+ this.onFocus = this.focusEvent.asObservable();
2273
+ this.onBlur = this.blurEvent.asObservable();
2274
+ this.onSave = this.saveEvent.asObservable();
2275
+ this.controller = this.get(core.Controller);
2276
+ }
2277
+ /**
2278
+ * 初始化编辑器
2279
+ * @param host 编辑器容器
2280
+ */
2281
+ mount(host) {
2282
+ const _super = Object.create(null, {
2283
+ mount: { get: () => super.mount }
2284
+ });
2285
+ return __awaiter(this, void 0, void 0, function* () {
2286
+ if (this.destroyed) {
2287
+ throw editorError('the editor instance is destroyed!');
2288
+ }
2289
+ if (this.destroyed) {
2290
+ return this;
2291
+ }
2292
+ const parser = this.get(exports.Parser);
2293
+ const registry = this.get(core.Registry);
2294
+ const doc = this.get(VIEW_DOCUMENT);
2295
+ let component;
2296
+ const content = this.options.content;
2297
+ if (content) {
2298
+ if (typeof content === 'string') {
2299
+ component = parser.parseDoc(content, this.rootComponentLoader);
2300
+ }
2301
+ else {
2302
+ component = registry.createComponentByFactory(content, this.rootComponent);
2303
+ }
2304
+ }
2305
+ else {
2306
+ component = this.rootComponent.createInstance(this);
2307
+ }
2308
+ this.initDocStyleSheetsAndScripts(this.options);
2309
+ host.appendChild(this.workbench);
2310
+ yield _super.mount.call(this, doc, component);
2311
+ const renderer = this.get(core.Renderer);
2312
+ const input = this.get(Input);
2313
+ this.subs.push(renderer.onViewUpdated.subscribe(() => {
2314
+ this.changeEvent.next();
2315
+ }), input.caret.onPositionChange.pipe(stream.map(p => !!p), stream.distinctUntilChanged()).subscribe(b => {
2316
+ if (b) {
2317
+ this._isFocus = true;
2318
+ this.focusEvent.next();
2319
+ }
2320
+ else {
2321
+ this._isFocus = false;
2322
+ this.blurEvent.next();
2323
+ }
2324
+ }));
2325
+ this.isReady = true;
2326
+ this.initDefaultShortcut();
2327
+ if (this.options.autoFocus) {
2328
+ input.onReady.then(() => {
2329
+ this.focus();
2330
+ });
2331
+ }
2332
+ return this;
2333
+ });
2334
+ }
2335
+ /**
2336
+ * 获取焦点
2337
+ */
2338
+ focus() {
2339
+ this.guardReady();
2340
+ const selection = this.get(core.Selection);
2341
+ const rootComponentRef = this.get(core.RootComponentRef);
2342
+ if (selection.commonAncestorSlot) {
2343
+ selection.restore();
2344
+ return;
2345
+ }
2346
+ const location = selection.findFirstPosition(rootComponentRef.component.slots.get(0));
2347
+ selection.setPosition(location.slot, location.offset);
2348
+ selection.restore();
2349
+ }
2350
+ /**
2351
+ * 取消编辑器焦点
2352
+ */
2353
+ blur() {
2354
+ if (this.isReady) {
2355
+ const selection = this.get(core.Selection);
2356
+ selection.unSelect();
2357
+ selection.restore();
2358
+ }
2359
+ }
2360
+ /**
2361
+ * 获取编辑器所有资源
2362
+ */
2363
+ getResources() {
2364
+ var _a;
2365
+ return {
2366
+ styleSheets: ((_a = this.options) === null || _a === void 0 ? void 0 : _a.styleSheets) || [],
2367
+ styleSheet: this.styleSheet,
2368
+ links: this.links,
2369
+ scripts: this.scripts
2370
+ };
2371
+ }
2372
+ /**
2373
+ * 获取 HTML 格式的内容
2374
+ */
2375
+ getHTML() {
2376
+ this.guardReady();
2377
+ const outputRenderer = this.get(core.OutputRenderer);
2378
+ const outputTranslator = this.get(exports.OutputTranslator);
2379
+ const vDom = outputRenderer.render();
2380
+ return outputTranslator.transform(vDom);
2381
+ }
2382
+ /**
2383
+ * 获取 JSON 格式的内容
2384
+ */
2385
+ getJSON() {
2386
+ this.guardReady();
2387
+ const rootComponentRef = this.get(core.RootComponentRef);
2388
+ return rootComponentRef.component.toJSON();
2389
+ }
2390
+ /**
2391
+ * 销毁编辑器
2392
+ */
2393
+ destroy() {
2394
+ var _a;
2395
+ if (this.destroyed) {
2396
+ return;
2397
+ }
2398
+ this.destroyed = true;
2399
+ this.subs.forEach(i => i.unsubscribe());
2400
+ const types = [
2401
+ Input
2402
+ ];
2403
+ types.forEach(i => {
2404
+ this.get(i).destroy();
2405
+ });
2406
+ super.destroy();
2407
+ (_a = this.workbench.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.workbench);
2408
+ this.resourceNodes.forEach(node => {
2409
+ var _a;
2410
+ (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(node);
2411
+ });
2412
+ }
2413
+ /**
2414
+ * 替换编辑的内容
2415
+ * @param content
2416
+ */
2417
+ replaceContent(content) {
2418
+ this.guardReady();
2419
+ const parser = this.get(exports.Parser);
2420
+ const registry = this.get(core.Registry);
2421
+ const rootComponentRef = this.get(core.RootComponentRef);
2422
+ const selection = this.get(core.Selection);
2423
+ const rootComponentLoader = this.rootComponentLoader;
2424
+ let component;
2425
+ if (typeof content === 'string') {
2426
+ component = parser.parseDoc(content, rootComponentLoader);
2427
+ }
2428
+ else {
2429
+ component = registry.createComponentByFactory(content, this.rootComponent);
2430
+ }
2431
+ selection.unSelect();
2432
+ rootComponentRef.component.slots.clean();
2433
+ rootComponentRef.component.slots.push(...component.slots.toArray());
2434
+ core.invokeListener(component, 'onDestroy');
2435
+ }
2436
+ guardReady() {
2437
+ if (this.destroyed) {
2438
+ throw editorError('the editor instance is destroyed!');
2439
+ }
2440
+ if (!this.isReady) {
2441
+ throw editorError('please wait for the editor to initialize before getting the content!');
2442
+ }
2443
+ }
2444
+ initDefaultShortcut() {
2445
+ const selection = this.get(core.Selection);
2446
+ const keyboard = this.get(core.Keyboard);
2447
+ const history = this.get(core.History);
2448
+ const commander = this.get(core.Commander);
2449
+ keyboard.addShortcut({
2450
+ keymap: {
2451
+ key: 's',
2452
+ ctrlKey: true
2453
+ },
2454
+ action: () => {
2455
+ this.saveEvent.next();
2456
+ }
2457
+ });
2458
+ keyboard.addShortcut({
2459
+ keymap: {
2460
+ key: 'Enter'
2461
+ },
2462
+ action: () => {
2463
+ commander.break();
2464
+ }
2465
+ });
2466
+ keyboard.addShortcut({
2467
+ keymap: {
2468
+ key: 'Enter',
2469
+ shiftKey: true
2470
+ },
2471
+ action: () => {
2472
+ const startOffset = selection.startOffset;
2473
+ const startSlot = selection.startSlot;
2474
+ const isToEnd = startOffset === startSlot.length || startSlot.isEmpty;
2475
+ const content = isToEnd ? '\n\n' : '\n';
2476
+ const isInserted = commander.insert(content);
2477
+ if (isInserted && isToEnd) {
2478
+ selection.setPosition(startSlot, startOffset + 1);
2479
+ }
2480
+ }
2481
+ });
2482
+ keyboard.addShortcut({
2483
+ keymap: {
2484
+ key: ['Delete', 'Backspace']
2485
+ },
2486
+ action: (key) => {
2487
+ commander.delete(key === 'Backspace');
2488
+ }
2489
+ });
2490
+ keyboard.addShortcut({
2491
+ keymap: {
2492
+ key: ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']
2493
+ },
2494
+ action: (key) => {
2495
+ switch (key) {
2496
+ case 'ArrowLeft':
2497
+ selection.toPrevious();
2498
+ break;
2499
+ case 'ArrowRight':
2500
+ selection.toNext();
2501
+ break;
2502
+ case 'ArrowUp':
2503
+ selection.toPreviousLine();
2504
+ break;
2505
+ case 'ArrowDown':
2506
+ selection.toNextLine();
2507
+ break;
2508
+ }
2509
+ }
2510
+ });
2511
+ keyboard.addShortcut({
2512
+ keymap: {
2513
+ key: ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'],
2514
+ shiftKey: true
2515
+ },
2516
+ action: (key) => {
2517
+ switch (key) {
2518
+ case 'ArrowLeft':
2519
+ selection.wrapToBefore();
2520
+ break;
2521
+ case 'ArrowRight':
2522
+ selection.wrapToAfter();
2523
+ break;
2524
+ case 'ArrowUp':
2525
+ selection.wrapToPreviousLine();
2526
+ break;
2527
+ case 'ArrowDown':
2528
+ selection.wrapToNextLine();
2529
+ break;
2530
+ }
2531
+ }
2532
+ });
2533
+ keyboard.addShortcut({
2534
+ keymap: {
2535
+ key: 'Tab'
2536
+ },
2537
+ action: () => {
2538
+ commander.insert(' ');
2539
+ }
2540
+ });
2541
+ keyboard.addShortcut({
2542
+ keymap: {
2543
+ key: 'a',
2544
+ ctrlKey: true
2545
+ },
2546
+ action: () => {
2547
+ selection.selectAll();
2548
+ }
2549
+ });
2550
+ keyboard.addShortcut({
2551
+ keymap: {
2552
+ key: 'c',
2553
+ ctrlKey: true
2554
+ },
2555
+ action: () => {
2556
+ commander.copy();
2557
+ }
2558
+ });
2559
+ keyboard.addShortcut({
2560
+ keymap: {
2561
+ key: 'x',
2562
+ ctrlKey: true
2563
+ },
2564
+ action: () => {
2565
+ commander.cut();
2566
+ }
2567
+ });
2568
+ keyboard.addShortcut({
2569
+ keymap: {
2570
+ key: 'z',
2571
+ ctrlKey: true
2572
+ },
2573
+ action: () => {
2574
+ history.back();
2575
+ }
2576
+ });
2577
+ keyboard.addShortcut({
2578
+ keymap: {
2579
+ key: 'z',
2580
+ ctrlKey: true,
2581
+ shiftKey: true
2582
+ },
2583
+ action: () => {
2584
+ history.forward();
2585
+ }
2586
+ });
2587
+ }
2588
+ initDocStyleSheetsAndScripts(options) {
2589
+ var _a;
2590
+ const loaders = [];
2591
+ (_a = options.imports) === null || _a === void 0 ? void 0 : _a.forEach(module => {
2592
+ loaders.push(...(module.componentLoaders || []));
2593
+ });
2594
+ loaders.push(...(options.componentLoaders || []));
2595
+ const resources = loaders.filter(i => i.resources).map(i => i.resources);
2596
+ const docStyles = [];
2597
+ const editModeStyles = [];
2598
+ resources.forEach(metadata => {
2599
+ var _a, _b;
2600
+ if (Array.isArray(metadata.links)) {
2601
+ this.links.push(...metadata.links);
2602
+ }
2603
+ docStyles.push(((_a = metadata.styles) === null || _a === void 0 ? void 0 : _a.join('')) || '');
2604
+ editModeStyles.push(((_b = metadata.editModeStyles) === null || _b === void 0 ? void 0 : _b.join('')) || '');
2605
+ });
2606
+ this.links.forEach(link => {
2607
+ const linkEle = document.createElement('link');
2608
+ Object.assign(linkEle, link);
2609
+ this.resourceNodes.push(linkEle);
2610
+ document.head.appendChild(linkEle);
2611
+ });
2612
+ const styleEl = document.createElement('style');
2613
+ docStyles.push(...(options.styleSheets || []));
2614
+ editModeStyles.push(`#${this.id} *::selection{background-color: rgba(18, 150, 219, .2); color:inherit}`, ...(options.editingStyleSheets || []));
2615
+ this.styleSheet = Viewer.cssMin(docStyles.join(''));
2616
+ styleEl.innerHTML = this.styleSheet + Viewer.cssMin(editModeStyles.join(''));
2617
+ this.resourceNodes.push(styleEl);
2618
+ document.head.append(styleEl);
2619
+ resources.filter(i => { var _a; return (_a = i.scripts) === null || _a === void 0 ? void 0 : _a.length; }).map(i => i.scripts).flat().forEach(src => {
2620
+ if (src) {
2621
+ const script = document.createElement('script');
2622
+ script.src = src;
2623
+ this.scripts.push(src);
2624
+ document.head.appendChild(script);
2625
+ this.resourceNodes.push(script);
2626
+ }
2627
+ });
2628
+ }
2629
+ static createLayout(id, minHeight = '100%') {
2630
+ const doc = createElement('div', {
2631
+ styles: {
2632
+ cursor: 'text',
2633
+ wordBreak: 'break-all',
2634
+ boxSizing: 'border-box',
2635
+ minHeight,
2636
+ flex: 1,
2637
+ outline: 'none'
2638
+ },
2639
+ attrs: {
2640
+ 'data-textbus-view': VIEW_DOCUMENT,
2641
+ },
2642
+ props: {
2643
+ id
2644
+ }
2645
+ });
2646
+ const mask = createElement('div', {
2647
+ attrs: {
2648
+ 'data-textbus-view': VIEW_MASK,
2649
+ },
2650
+ styles: {
2651
+ position: 'absolute',
2652
+ left: 0,
2653
+ right: 0,
2654
+ top: 0,
2655
+ bottom: 0,
2656
+ zIndex: 1,
2657
+ pointerEvents: 'none',
2658
+ overflow: 'hidden'
2659
+ }
2660
+ });
2661
+ const wrapper = createElement('div', {
2662
+ attrs: {
2663
+ 'data-textbus-view': VIEW_CONTAINER,
2664
+ },
2665
+ styles: {
2666
+ display: 'flex',
2667
+ minHeight: '100%',
2668
+ position: 'relative',
2669
+ flexDirection: 'column'
2670
+ },
2671
+ children: [doc, mask]
2672
+ });
2673
+ return {
2674
+ wrapper,
2675
+ doc,
2676
+ mask
2677
+ };
2678
+ }
2679
+ static cssMin(str) {
2680
+ return str
2681
+ .replace(/\s*(?=[>{}:;,[])/g, '')
2682
+ .replace(/([>{}:;,])\s*/g, '$1')
2683
+ .replace(/;}/g, '}').replace(/\s+/, ' ').trim();
2684
+ }
2675
2685
  }
2676
2686
 
2677
2687
  exports.CollaborateSelectionAwarenessDelegate = CollaborateSelectionAwarenessDelegate;
@@ -2687,4 +2697,3 @@ exports.getLayoutRectByRange = getLayoutRectByRange;
2687
2697
  exports.isMac = isMac;
2688
2698
  exports.isSafari = isSafari;
2689
2699
  exports.isWindows = isWindows;
2690
- exports.setDefaultShortcut = setDefaultShortcut;