@textbus/platform-browser 3.0.0-alpha.37 → 3.0.0-alpha.39

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