@textbus/platform-browser 3.0.0-alpha.46 → 3.0.0-alpha.48

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,2544 +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
- 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])
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
+ 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
+ const formats = this.formatLoaders.filter(f => {
1288
+ return f.match(el);
1289
+ }).map(f => {
1290
+ return f.read(el);
1291
+ });
1292
+ const startIndex = slot.index;
1293
+ Array.from(el.childNodes).forEach(child => {
1294
+ this.readComponent(child, slot);
1295
+ });
1296
+ const endIndex = slot.index;
1297
+ this.applyFormats(slot, formats.map(i => {
1298
+ return {
1299
+ formatter: i.formatter,
1300
+ value: i.value,
1301
+ startIndex,
1302
+ endIndex
1303
+ };
1304
+ }));
1305
+ slot.retain(endIndex);
1306
+ return slot;
1307
+ }
1308
+ readSlot(childSlot, slotRootElement, slotContentElement) {
1309
+ this.attributeLoaders.filter(a => {
1310
+ return a.match(slotRootElement);
1311
+ }).forEach(a => {
1312
+ const r = a.read(slotRootElement);
1313
+ childSlot.setAttribute(r.attribute, r.value);
1314
+ });
1315
+ this.readFormats(slotContentElement, childSlot);
1316
+ return childSlot;
1317
+ }
1318
+ applyFormats(slot, formatItems) {
1319
+ slot.background(() => {
1320
+ formatItems.forEach(i => {
1321
+ slot.retain(i.startIndex);
1322
+ slot.retain(i.endIndex - i.startIndex, i.formatter, i.value);
1323
+ });
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])
1331
1331
  ], exports.Parser);
1332
1332
 
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
- constructor(scheduler, editorMask) {
1354
- this.scheduler = scheduler;
1355
- this.editorMask = editorMask;
1356
- this.timer = null;
1357
- this.oldPosition = null;
1358
- this._display = true;
1359
- this.flashing = true;
1360
- this.subs = [];
1361
- this.positionChangeEvent = new stream.Subject();
1362
- this.styleChangeEvent = new stream.Subject();
1363
- this.oldRange = null;
1364
- this.isFixed = false;
1365
- this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1366
- this.onStyleChange = this.styleChangeEvent.asObservable();
1367
- this.elementRef = createElement('div', {
1368
- styles: {
1369
- position: 'absolute',
1370
- width: '2px',
1371
- pointerEvents: 'none'
1372
- },
1373
- children: [
1374
- this.caret = createElement('span', {
1375
- styles: {
1376
- width: '100%',
1377
- height: '100%',
1378
- position: 'absolute',
1379
- left: 0,
1380
- top: 0
1381
- }
1382
- })
1383
- ]
1384
- });
1385
- this.subs.push(stream.fromEvent(document, 'mousedown').subscribe(() => {
1386
- this.flashing = false;
1387
- }), stream.fromEvent(document, 'mouseup').subscribe(() => {
1388
- this.flashing = true;
1389
- }));
1390
- this.editorMask.appendChild(this.elementRef);
1391
- }
1392
- get rect() {
1393
- return this.caret.getBoundingClientRect();
1394
- }
1395
- set display(v) {
1396
- this._display = v;
1397
- this.caret.style.visibility = v ? 'visible' : 'hidden';
1398
- }
1399
- get display() {
1400
- return this._display;
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
- constructor(parser, keyboard, commander, selection, controller, scheduler, injector) {
1557
- super();
1558
- this.parser = parser;
1559
- this.keyboard = keyboard;
1560
- this.commander = commander;
1561
- this.selection = selection;
1562
- this.controller = controller;
1563
- this.scheduler = scheduler;
1564
- this.injector = injector;
1565
- this.composition = false;
1566
- this.caret = new ExperimentalCaret(this.scheduler, this.injector.get(VIEW_MASK));
1567
- this._disabled = false;
1568
- this.container = this.createEditableFrame();
1569
- this.subscription = new stream.Subscription();
1570
- this.textarea = null;
1571
- this.isFocus = false;
1572
- this.nativeFocus = false;
1573
- this.isSafari = isSafari();
1574
- this.isMac = isMac();
1575
- this.isWindows = isWindows();
1576
- this.isSougouPinYin = false; // 有 bug 版本搜狗拼音
1577
- this.onReady = new Promise(resolve => {
1578
- this.subscription.add(stream.fromEvent(this.container, 'load').subscribe(() => {
1579
- const doc = this.container.contentDocument;
1580
- doc.open();
1581
- doc.write(iframeHTML);
1582
- doc.close();
1583
- this.doc = doc;
1584
- this.init();
1585
- resolve();
1586
- }), controller.onReadonlyStateChange.subscribe(() => {
1587
- if (controller.readonly) {
1588
- this.blur();
1589
- }
1590
- }));
1591
- });
1592
- this.caret.elementRef.append(this.container);
1593
- }
1594
- set disabled(b) {
1595
- this._disabled = b;
1596
- if (b && this.textarea) {
1597
- this.textarea.disabled = b;
1598
- }
1599
- }
1600
- get disabled() {
1601
- return this._disabled;
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])
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])
1805
1805
  ], exports.MagicInput);
1806
1806
 
1807
- class NativeCaret {
1808
- constructor(scheduler) {
1809
- this.scheduler = scheduler;
1810
- this.oldPosition = null;
1811
- this._nativeRange = null;
1812
- this.subs = [];
1813
- this.positionChangeEvent = new stream.Subject();
1814
- this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1815
- }
1816
- set nativeRange(range) {
1817
- this._nativeRange = range;
1818
- if (range) {
1819
- const r = range.cloneRange();
1820
- r.collapse(true);
1821
- const rect = r.getBoundingClientRect();
1822
- this.positionChangeEvent.next({
1823
- left: rect.left,
1824
- top: rect.top,
1825
- height: rect.height
1826
- });
1827
- }
1828
- else {
1829
- this.positionChangeEvent.next(null);
1830
- }
1831
- }
1832
- get nativeRange() {
1833
- return this._nativeRange;
1834
- }
1835
- get rect() {
1836
- if (this.nativeRange) {
1837
- const range = this.nativeRange.cloneRange();
1838
- range.collapse(true);
1839
- return range.getBoundingClientRect();
1840
- }
1841
- return {
1842
- left: 0,
1843
- top: 0,
1844
- width: 0,
1845
- height: 0
1846
- };
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
- constructor(injector, parser, scheduler, selection, keyboard, commander, controller) {
1911
- super();
1912
- this.injector = injector;
1913
- this.parser = parser;
1914
- this.scheduler = scheduler;
1915
- this.selection = selection;
1916
- this.keyboard = keyboard;
1917
- this.commander = commander;
1918
- this.controller = controller;
1919
- this.caret = new NativeCaret(this.scheduler);
1920
- this.composition = false;
1921
- this.onReady = Promise.resolve();
1922
- this._disabled = false;
1923
- this.nativeSelection = document.getSelection();
1924
- this.subscription = new stream.Subscription();
1925
- this.nativeRange = null;
1926
- this.isSafari = isSafari();
1927
- this.isMac = isMac();
1928
- this.isSougouPinYin = false; // 有 bug 版本搜狗拼音
1929
- this.documentView = injector.get(VIEW_DOCUMENT);
1930
- if (!controller.readonly) {
1931
- this.documentView.contentEditable = 'true';
1932
- }
1933
- this.subscription.add(controller.onReadonlyStateChange.subscribe(() => {
1934
- this.documentView.contentEditable = controller.readonly ? 'false' : 'true';
1935
- }));
1936
- this.handleShortcut(this.documentView);
1937
- this.handleInput(this.documentView);
1938
- this.handleDefaultActions(this.documentView);
1939
- }
1940
- set disabled(b) {
1941
- this._disabled = b;
1942
- if (b && !this.controller.readonly) {
1943
- this.documentView.contentEditable = b ? 'true' : 'false';
1944
- }
1945
- }
1946
- get disabled() {
1947
- return this._disabled;
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])
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])
2106
2106
  ], exports.NativeInput);
2107
2107
 
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()
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()
2199
2199
  ], exports.OutputTranslator);
2200
2200
 
2201
- const editorError = core.makeError('CoreEditor');
2202
- /**
2203
- * Textbus PC 端编辑器
2204
- */
2205
- class Viewer extends core.Starter {
2206
- constructor(rootComponent, rootComponentLoader, options = {}) {
2207
- const id = 'textbus-' + Number((Math.random() + '').substring(2)).toString(16);
2208
- const { doc, mask, wrapper } = Viewer.createLayout(id, options.minHeight);
2209
- const staticProviders = [{
2210
- provide: EDITOR_OPTIONS,
2211
- useValue: options
2212
- }, {
2213
- provide: VIEW_CONTAINER,
2214
- useValue: wrapper
2215
- }, {
2216
- provide: VIEW_DOCUMENT,
2217
- useValue: doc
2218
- }, {
2219
- provide: VIEW_MASK,
2220
- useValue: mask
2221
- }, {
2222
- provide: core.NativeRenderer,
2223
- useExisting: exports.DomRenderer
2224
- }, {
2225
- provide: core.NativeSelectionBridge,
2226
- useExisting: exports.SelectionBridge
2227
- }, {
2228
- provide: Input,
2229
- useClass: options.useContentEditable ? exports.NativeInput : exports.MagicInput
2230
- }, {
2231
- provide: Viewer,
2232
- useFactory: () => this
2233
- }];
2234
- super(Object.assign(Object.assign({}, options), { plugins: options.plugins || [], providers: [
2235
- ...(options.providers || []),
2236
- ...staticProviders,
2237
- exports.DomRenderer,
2238
- exports.Parser,
2239
- exports.SelectionBridge,
2240
- exports.OutputTranslator,
2241
- exports.CollaborateCursor
2242
- ], setup: options.setup }));
2243
- this.rootComponent = rootComponent;
2244
- this.rootComponentLoader = rootComponentLoader;
2245
- this.options = options;
2246
- /** 编辑器是否已销毁 */
2247
- this.destroyed = false;
2248
- /** 编辑器是否已准备好 */
2249
- this.isReady = false;
2250
- this.changeEvent = new stream.Subject();
2251
- this.subs = [];
2252
- this._isFocus = false;
2253
- this.resourceNodes = [];
2254
- this.focusEvent = new stream.Subject();
2255
- this.blurEvent = new stream.Subject();
2256
- this.saveEvent = new stream.Subject();
2257
- this.styleSheet = '';
2258
- this.scripts = [];
2259
- this.links = [];
2260
- this.id = id;
2261
- this.workbench = wrapper;
2262
- this.onChange = this.changeEvent.asObservable();
2263
- this.onFocus = this.focusEvent.asObservable();
2264
- this.onBlur = this.blurEvent.asObservable();
2265
- this.onSave = this.saveEvent.asObservable();
2266
- this.controller = this.get(core.Controller);
2267
- }
2268
- get readonly() {
2269
- return this.controller.readonly;
2270
- }
2271
- set readonly(b) {
2272
- this.controller.readonly = b;
2273
- }
2274
- isFocus() {
2275
- return this._isFocus;
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
- this.initDefaultShortcut();
2296
- let component;
2297
- const content = this.options.content;
2298
- if (content) {
2299
- if (typeof content === 'string') {
2300
- component = parser.parseDoc(content, this.rootComponentLoader);
2301
- }
2302
- else {
2303
- component = registry.createComponentByFactory(content, this.rootComponent);
2304
- }
2305
- }
2306
- else {
2307
- component = this.rootComponent.createInstance(this);
2308
- }
2309
- this.initDocStyleSheetsAndScripts(this.options);
2310
- host.appendChild(this.workbench);
2311
- yield _super.mount.call(this, doc, component);
2312
- const renderer = this.get(core.Renderer);
2313
- const input = this.get(Input);
2314
- this.subs.push(renderer.onViewUpdated.subscribe(() => {
2315
- this.changeEvent.next();
2316
- }), input.caret.onPositionChange.pipe(stream.map(p => !!p), stream.distinctUntilChanged()).subscribe(b => {
2317
- if (b) {
2318
- this._isFocus = true;
2319
- this.focusEvent.next();
2320
- }
2321
- else {
2322
- this._isFocus = false;
2323
- this.blurEvent.next();
2324
- }
2325
- }));
2326
- this.isReady = true;
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
- }
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
+ this.initDefaultShortcut();
2296
+ let component;
2297
+ const content = this.options.content;
2298
+ if (content) {
2299
+ if (typeof content === 'string') {
2300
+ component = parser.parseDoc(content, this.rootComponentLoader);
2301
+ }
2302
+ else {
2303
+ component = registry.createComponentByFactory(content, this.rootComponent);
2304
+ }
2305
+ }
2306
+ else {
2307
+ component = this.rootComponent.createInstance(this);
2308
+ }
2309
+ this.initDocStyleSheetsAndScripts(this.options);
2310
+ host.appendChild(this.workbench);
2311
+ yield _super.mount.call(this, doc, component);
2312
+ const renderer = this.get(core.Renderer);
2313
+ const input = this.get(Input);
2314
+ this.subs.push(renderer.onViewUpdated.subscribe(() => {
2315
+ this.changeEvent.next();
2316
+ }), input.caret.onPositionChange.pipe(stream.map(p => !!p), stream.distinctUntilChanged()).subscribe(b => {
2317
+ if (b) {
2318
+ this._isFocus = true;
2319
+ this.focusEvent.next();
2320
+ }
2321
+ else {
2322
+ this._isFocus = false;
2323
+ this.blurEvent.next();
2324
+ }
2325
+ }));
2326
+ this.isReady = true;
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
+ }
2685
2685
  }
2686
2686
 
2687
2687
  exports.CollaborateSelectionAwarenessDelegate = CollaborateSelectionAwarenessDelegate;