@textbus/platform-browser 5.2.2 → 5.2.4

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/dist/index.js CHANGED
@@ -1,22 +1,3397 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@textbus/core"),c=require("@tanbo/stream"),C=require("@viewfly/core");function y(f,t={}){const s=document.createElement(f);return t.classes&&s.classList.add(...t.classes),t.attrs&&Object.keys(t.attrs).forEach(i=>{s.setAttribute(i,t.attrs[i])}),t.props&&Object.keys(t.props).forEach(i=>{s[i]=t.props[i]}),t.styles&&Object.assign(s.style,t.styles),t.children&&t.children.filter(i=>i).forEach(i=>{s.appendChild(i)}),t.on&&Object.keys(t.on).forEach(i=>{s.addEventListener(i,t.on[i])}),s}function N(f){let{startContainer:t,startOffset:s}=f;if(t.nodeType===Node.TEXT_NODE){if(s>0)return f.getBoundingClientRect();const a=t.parentNode;s=Array.from(a.childNodes).indexOf(t),t=a}const i=t.childNodes[s-1];if(i){if(i.nodeType===Node.ELEMENT_NODE&&i.nodeName.toLowerCase()!=="br"){const a=i.getBoundingClientRect();return{left:a.right,top:a.top,width:f.collapsed?1:a.width,height:a.height}}else if(i.nodeType===Node.TEXT_NODE){const a=document.createRange();a.setStart(i,i.textContent.length),a.setEnd(i,i.textContent.length);const l=a.getBoundingClientRect();return{left:l.right,top:l.top,width:f.collapsed?1:l.width,height:l.height}}}const e=t.childNodes[s];let o=!1;if(!e){const a=t.lastChild;if(a&&a.nodeType===Node.ELEMENT_NODE){const l=a.getBoundingClientRect();return{left:l.right,top:l.top,width:f.collapsed?1:l.width,height:l.height}}}if(e){if(e.nodeType===Node.ELEMENT_NODE&&e.nodeName.toLowerCase()!=="br"){const a=e.getBoundingClientRect();return{left:a.left,top:a.top,width:f.collapsed?1:a.width,height:a.height}}o=!0}const n=t.ownerDocument.createElement("span");n.innerText="​",n.style.display="inline-block",o?t.insertBefore(n,e):t.appendChild(n);const r=n.getBoundingClientRect();return t.removeChild(n),{left:r.left,top:r.top,width:f.collapsed?1:r.width,height:r.height}}const M=()=>/win(dows|32|64)/i.test(navigator.userAgent),_=()=>/mac os/i.test(navigator.userAgent),A=()=>/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent),D=()=>/Firefox/.test(navigator.userAgent),j=()=>/Android|iPhone|iPad/.test(navigator.userAgent),B=new C.InjectionToken("EDITOR_OPTIONS"),I=new C.InjectionToken("VIEW_CONTAINER"),O=new C.InjectionToken("VIEW_DOCUMENT"),L=new C.InjectionToken("VIEW_MASK");var U=Object.getOwnPropertyDescriptor,V=(f,t,s,i)=>{for(var e=i>1?void 0:i?U(t,s):t,o=f.length-1,n;o>=0;o--)(n=f[o])&&(e=n(e)||e);return e},K=(f,t)=>(s,i)=>t(s,i,f);exports.Parser=class{constructor(t,s){this.textbus=s;const i=[...t.componentLoaders||[]],e=[...t.formatLoaders||[]],o=[...t.attributeLoaders||[]];this.componentLoaders=i,this.formatLoaders=e,this.attributeLoaders=o}textbus;static parseHTML(t){return new DOMParser().parseFromString(t,"text/html").body}componentLoaders;formatLoaders;attributeLoaders;parseDoc(t,s){const i=typeof t=="string"?exports.Parser.parseHTML(t):t;return s.read(i,this.textbus,(e,o,n=o)=>this.readSlot(e,o,n))}parse(t,s){const i=typeof t=="string"?exports.Parser.parseHTML(t):t;return this.readFormats(i,s)}readComponent(t,s){if(t.nodeType===Node.ELEMENT_NODE){if(t.tagName==="BR"){s.insert(`
2
- `);return}const i=[...s.schema];for(const e of this.componentLoaders)if(e.match(t,i)){const o=e.read(t,this.textbus,(n,r,a=r)=>this.readSlot(n,r,a));if(!o)return;if(o instanceof u.Slot){o.toDelta().forEach(n=>s.insert(n.insert,n.formats));return}s.insert(o);return}this.readFormats(t,s)}else t.nodeType===Node.TEXT_NODE&&this.readText(s,t)}readText(t,s){const i=s.textContent;/^\s*[\r\n\u200b]+\s*$/.test(i)||t.insert(i)}readFormats(t,s){const i=this.formatLoaders.filter(r=>r.match(t)).map(r=>r.read(t)),e=s.index;let o=t.firstChild;for(;o;)this.readComponent(o,s),o=o.nextSibling;const n=s.index;return this.applyFormats(s,i.map(r=>({formatter:r.formatter,value:r.value,startIndex:e,endIndex:n}))),s.retain(n),s}readSlot(t,s,i){return s.nodeType===Node.ELEMENT_NODE&&this.attributeLoaders.filter(e=>e.match(s)).forEach(e=>{const o=e.read(s);t.setAttribute(o.attribute,o.value)}),i.nodeType===Node.ELEMENT_NODE?this.readFormats(i,t):this.readText(t,i),t}applyFormats(t,s){t.background(()=>{s.forEach(i=>{t.retain(i.startIndex),t.retain(i.endIndex-i.startIndex,i.formatter,i.value)})})}};exports.Parser=V([C.Injectable(),K(0,C.Inject(B))],exports.Parser);var $=Object.getOwnPropertyDescriptor,W=(f,t,s,i)=>{for(var e=i>1?void 0:i?$(t,s):t,o=f.length-1,n;o>=0;o--)(n=f[o])&&(e=n(e)||e);return e},X=(f,t)=>(s,i)=>t(s,i,f);exports.SelectionBridge=class{constructor(t,s,i,e,o,n,r,a){this.config=t,this.selection=e,this.rootComponentRef=o,this.input=n,this.scheduler=r,this.domAdapter=a,this.docContainer=s.get(O),this.onSelectionChange=this.selectionChangeEvent.asObservable().pipe(c.filter(()=>!i.readonly)),this.sub=this.onSelectionChange.subscribe(l=>{l?n.focus(l,this.changeFromUser):n.blur()}),this.sub.add(c.fromEvent(document,"focusin").subscribe(l=>{let d=l.target;if(/^(input|textarea|select)$/i.test(d.nodeName)){if(d.tagName.toLowerCase()==="input"&&/^(range|date)$/.test(d.type))return;this.ignoreSelectionChange=!0;return}if(!t.useContentEditable)for(;d;){if(d.contentEditable==="true"){this.ignoreSelectionChange=!0;return}d=d.parentNode}})),this.sub.add(c.fromEvent(document,"focusout").subscribe(()=>{this.ignoreSelectionChange=!1}))}config;selection;rootComponentRef;input;scheduler;domAdapter;onSelectionChange;nativeSelection=document.getSelection();syncSelectionFromNativeSelectionChange=!0;selectionChangeEvent=new c.Subject;subs=[];sub;connector=null;ignoreSelectionChange=!1;changeFromUser=!1;docContainer;cacheCaretPositionTimer;oldCaretPosition;connect(t){this.disConnect(),this.connector=t,this.syncSelection(t),this.listen(t)}disConnect(){this.connector=null,this.unListen()}getRect(t){const{focus:s,anchor:i}=this.getPositionByRange({focusOffset:t.offset,anchorOffset:t.offset,focusSlot:t.slot,anchorSlot:t.slot});if(!s||!i)return null;const e=document.createRange();return e.setStart(s.node,s.offset),e.collapse(),N(e)}restore(t,s){if(this.changeFromUser=s,this.ignoreSelectionChange||!this.connector)return;if(this.unListen(),!t){this.nativeSelection.removeAllRanges(),this.selectionChangeEvent.next(null),this.listen(this.connector);return}const{focus:i,anchor:e}=this.getPositionByRange(t);if(!i||!e){this.nativeSelection.removeAllRanges(),this.selectionChangeEvent.next(null),this.listen(this.connector);return}function o(r){if(r.node){if(r.node.nodeType===Node.TEXT_NODE){const a=r.node.textContent.length;r.offset>a&&(r.offset=a)}else if(r.node.nodeType===Node.ELEMENT_NODE){const a=r.node.childNodes.length;r.offset>a&&(r.offset=a)}}}try{o(i),o(e),this.nativeSelection.setBaseAndExtent(e.node,e.offset,i.node,i.offset)}catch(r){setTimeout(()=>{throw r})}if(this.nativeSelection.rangeCount){const r=this.nativeSelection.getRangeAt(0);this.selectionChangeEvent.next(r)}else this.selectionChangeEvent.next(null);const n=()=>{this.connector&&this.listen(this.connector)};if(s){Promise.resolve().then(n);return}typeof requestIdleCallback=="function"?requestIdleCallback(n):setTimeout(n,30)}destroy(){this.subs.forEach(t=>t.unsubscribe()),this.sub.unsubscribe()}getPositionByRange(t){let s,i;try{return s=this.findSelectedNodeAndOffset(t.focusSlot,t.focusOffset),i=s,(t.anchorSlot!==t.focusSlot||t.anchorOffset!==t.focusOffset)&&(i=this.findSelectedNodeAndOffset(t.anchorSlot,t.anchorOffset)),{focus:s,anchor:i}}catch{return{focus:null,anchor:null}}}getPreviousLinePositionByCurrent(t){return this.getLinePosition(t,!1)}getNextLinePositionByCurrent(t){return this.getLinePosition(t,!0)}getLinePosition(t,s){clearTimeout(this.cacheCaretPositionTimer);let i;return this.oldCaretPosition?i=s?this.getNextLinePositionByOffset(t,this.oldCaretPosition.left):this.getPreviousLinePositionByOffset(t,this.oldCaretPosition.left):(this.oldCaretPosition=this.getRect(t),i=s?this.getNextLinePositionByOffset(t,this.oldCaretPosition.left):this.getPreviousLinePositionByOffset(t,this.oldCaretPosition.left)),this.cacheCaretPositionTimer=setTimeout(()=>{this.oldCaretPosition=null},3e3),i}getPreviousLinePositionByOffset(t,s){let i=!1,e=0,o=s,n=t.slot,r=t.offset,a=this.getRect({slot:n,offset:r}).top,l,d,m=0;for(;;){e++,l=this.selection.getPreviousPositionByPosition(n,r),n=l.slot,r=l.offset;const h=this.getRect(l);if(!i){if(h.left>o||h.top+h.height<=a)i=!0;else if(h.left===o&&h.top===a)return l;o=h.left,a=h.top}if(i){if(h.left<=s)return l;if(d&&h.left>=m)return d;m=h.left,d=l}if(e>1e4)break}return l||{offset:0,slot:n}}getNextLinePositionByOffset(t,s){let i=!1,e=0,o=s,n=t.slot,r=t.offset;const a=this.getRect({slot:n,offset:r});let l=a.top,d,m=0;for(;;){e++;const h=this.selection.getNextPositionByPosition(n,r);n=h.slot,r=h.offset;const p=this.getRect(h);if(!i){if(p.left<o||p.top>=l+a.height)i=!0;else if(p.left===o&&p.top===l)return h;o=p.left,l=p.top,d=h}if(i){if(p.left>s||d&&p.left<=m)return d;d=h,m=p.left}if(e>1e4)break}return d||{offset:n.length,slot:n}}unListen(){this.subs.forEach(t=>t.unsubscribe()),this.subs=[]}listen(t){if(!this.config.useContentEditable){const i=this.nativeSelection;this.subs.push(c.fromEvent(this.docContainer,"mousedown").subscribe(e=>{this.ignoreSelectionChange||e.button===2||e.shiftKey||i.removeAllRanges()}))}let s=!1;this.subs.push(this.scheduler.onDocChange.subscribe(()=>{s=!0}),this.scheduler.onDocChanged.pipe(c.delay()).subscribe(()=>{s=!1}),c.fromEvent(document,"selectionchange").subscribe(()=>{s||this.syncSelectionFromNativeSelectionChange&&this.syncSelection(t)}))}syncSelection(t){const s=this.nativeSelection;if(this.changeFromUser=!0,this.ignoreSelectionChange||this.input.composition||s.rangeCount===0||!this.docContainer.contains(s.anchorNode)||this.rootComponentRef.component.slots.length===0)return;const i=s.getRangeAt(0),e=i.cloneRange(),o=s.focusNode===e.endContainer&&s.focusOffset===e.endOffset,n=s.focusNode===e.startContainer&&s.focusOffset===e.startOffset;if(!this.docContainer.contains(s.focusNode))if(o){const l=this.domAdapter.getNativeNodeBySlot(this.rootComponentRef.component.slots.at(0));if(!l)return;e.setEndAfter(l.lastChild)}else{const l=this.domAdapter.getNativeNodeBySlot(this.rootComponentRef.component.slots.at(-1));if(!l)return;e.setStartBefore(l.firstChild)}const r=this.getCorrectedPosition(e.startContainer,e.startOffset,n),a=e.collapsed?r:this.getCorrectedPosition(e.endContainer,e.endOffset,o);if([Node.ELEMENT_NODE,Node.TEXT_NODE].includes(e.commonAncestorContainer?.nodeType)&&r&&a){const l=t.beforeChange(o?{anchorSlot:r.slot,anchorOffset:r.offset,focusSlot:a.slot,focusOffset:a.offset}:{focusSlot:r.slot,focusOffset:r.offset,anchorSlot:a.slot,anchorOffset:a.offset});if(!l){this.selectionChangeEvent.next(null),t.setSelection(null);return}const{focus:d,anchor:m}=this.getPositionByRange(l);if(d&&m){let h=m,p=d;n&&(h=d,p=m),(e.startContainer!==h.node||e.startOffset!==h.offset)&&e.setStart(h.node,h.offset),(e.endContainer!==p.node||e.endOffset!==p.offset)&&e.setEnd(p.node,p.offset),t.setSelection(l),s.isCollapsed&&(i.startContainer!==h.node||i.startOffset!==h.offset||i.endContainer!==p.node||i.endOffset!==p.offset)&&(i.setStart(h.node,h.offset),i.setEnd(p.node,p.offset)),this.selectionChangeEvent.next(e)}else t.setSelection(null);return}t.setSelection(null)}findSelectedNodeAndOffset(t,s){const i=t.getContentAtIndex(s-1),e=this.domAdapter.getNodesBySlot(t);if(i){if(typeof i!="string"){const n=this.domAdapter.getNativeNodeByComponent(i);return{node:n.parentNode,offset:Array.from(n.parentNode.childNodes).indexOf(n)+1}}else if(i===`
3
- `){for(const n of e)if(!(n instanceof Text)&&n.nodeName==="BR"){const r=this.domAdapter.getLocationByNativeNode(n);if(r&&r.endIndex===s){const a=n.parentNode;return{node:a,offset:Array.from(a.childNodes).indexOf(n)+1}}}}}const o=t.getContentAtIndex(s);if(o&&typeof o!="string"){const n=this.domAdapter.getNativeNodeByComponent(o);return{node:n.parentNode,offset:Array.from(n.parentNode.childNodes).indexOf(n)}}for(const n of e){if(n instanceof Element){if(n.tagName==="BR"){const a=this.domAdapter.getLocationByNativeNode(n);if(a&&a.startIndex===s){const l=n.parentNode;return{node:l,offset:Array.from(l.childNodes).indexOf(n)}}}continue}const r=this.domAdapter.getLocationByNativeNode(n);if(r&&s>=r.startIndex&&s<=r.endIndex)return{node:n,offset:s-r.startIndex}}return null}getCorrectedPosition(t,s,i,e=[]){if(e.push(t),t.nodeType===Node.ELEMENT_NODE){const o=this.domAdapter.getLocationByNativeNode(t),n=t.childNodes[s];if(n){const l=this.domAdapter.getLocationByNativeNode(n);return l?o?{slot:l.slot,offset:l.startIndex}:this.findFocusNode(n,i,e):this.findFocusNode(n,i,e)}const r=t.childNodes[s-1];if(r){const l=this.domAdapter.getLocationByNativeNode(r);if(l&&o)return{slot:l.slot,offset:l.endIndex}}if(o)return{slot:o.slot,offset:o.endIndex};const a=i?t.nextSibling:t.previousSibling;return a?this.findFocusNode(a,i,e):this.findFocusNodeByParent(t,i,e)}else if(t.nodeType===Node.TEXT_NODE){const o=this.domAdapter.getLocationByNativeNode(t);if(o)return{slot:o.slot,offset:o.startIndex+s};const n=i?t.nextSibling:t.previousSibling;return n?this.findFocusNode(n,i,e):this.findFocusNodeByParent(t,i,e)}return null}findFocusNode(t,s=!1,i=[]){if(i.includes(t)){const r=s?t.nextSibling:t.previousSibling;return r?this.findFocusNode(r,s,i):this.findFocusNodeByParent(t,s,i)}i.push(t);const e=this.domAdapter.getLocationByNativeNode(t);if(e)return{slot:e.slot,offset:s?e.startIndex:e.endIndex};const o=s?t.firstChild:t.lastChild;if(o)return this.findFocusNode(o,s,i);const n=s?t.nextSibling:t.previousSibling;return n?this.findFocusNode(n,s,i):this.findFocusNodeByParent(t,s,i)}findFocusNodeByParent(t,s,i){const e=t.parentNode;if(e){const o=this.domAdapter.getLocationByNativeNode(e);return o?{slot:o.slot,offset:s?o.endIndex:o.startIndex}:(i.push(t),this.findFocusNode(e,s,i))}return null}};exports.SelectionBridge=W([C.Injectable(),X(0,C.Inject(B))],exports.SelectionBridge);class w{}var z=Object.getOwnPropertyDescriptor,q=(f,t,s,i)=>{for(var e=i>1?void 0:i?z(t,s):t,o=f.length-1,n;o>=0;o--)(n=f[o])&&(e=n(e)||e);return e};const Y=`
4
- <!DOCTYPE html>
5
- <html>
6
- <head>
7
- <meta charset="UTF-8">
8
- <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
9
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
10
- <title>Textbus</title>
11
- <style>
12
- html {position: fixed; left:0; overflow: hidden}
13
- html, body{height: 100%;width:100%}
14
- body{margin:0; overflow: hidden}
15
- textarea{width: 2000px;height: 100%;opacity: 0; padding: 0; outline: none; border: none; position: absolute; left:0; top:0;}
16
- </style>
17
- </head>
18
- <body>
19
- </body>
20
- </html>
21
- `;class Z{constructor(t,s,i){this.domRenderer=t,this.scheduler=s,this.editorMask=i,this.onPositionChange=this.positionChangeEvent.pipe(c.distinctUntilChanged()),this.onStyleChange=this.styleChangeEvent.asObservable(),this.elementRef=y("div",{styles:{position:"absolute",width:"2px",pointerEvents:"none"},children:[this.caret=y("span",{styles:{width:"100%",height:"100%",position:"absolute",left:0,top:0}})]}),this.subscription.add(c.fromEvent(document,"mousedown").subscribe(()=>{this.flashing=!1}),c.fromEvent(document,"mouseup").subscribe(()=>{this.flashing=!0})),this.editorMask.appendChild(this.elementRef)}domRenderer;scheduler;editorMask;onPositionChange;onStyleChange;elementRef;changeFromSelf=!1;getLimit=function(){return{top:0,bottom:document.documentElement.clientHeight}};get rect(){return this.caret.getBoundingClientRect()}timer=null;caret;set display(t){this._display=t,this.caret.style.visibility=t?"visible":"hidden"}get display(){return this._display}_display=!0;flashing=!0;subscription=new c.Subscription;positionChangeEvent=new c.Subject;styleChangeEvent=new c.Subject;oldRange=null;refresh(){this.oldRange&&this.show(this.oldRange,!1)}show(t,s){if(this.oldRange=t,(s||this.scheduler.lastChangesHasLocalUpdate)&&clearTimeout(this.timer),this.updateCursorPosition(t),t.collapsed){if(s||this.scheduler.lastChangesHasLocalUpdate){this.display=!0;const i=()=>{this.display=!this.display||!this.flashing,this.timer=setTimeout(i,400)};clearTimeout(this.timer),this.timer=setTimeout(i,400)}}else this.display=!1,clearTimeout(this.timer)}hide(){this.display=!1,clearTimeout(this.timer),this.positionChangeEvent.next(null)}destroy(){clearTimeout(this.timer),this.subscription.unsubscribe()}updateCursorPosition(t){const s=t.startContainer,i=s.nodeType===Node.ELEMENT_NODE?s:s.parentNode;if(i?.nodeType!==Node.ELEMENT_NODE){this.positionChangeEvent.next(null);return}const e=this.domRenderer.compositionNode;e&&(t=t.cloneRange(),t.selectNodeContents(e),t.collapse());const o=N(t),{fontSize:n,lineHeight:r,color:a,writingMode:l}=getComputedStyle(i);let d;if(isNaN(+r)){const g=parseFloat(r);isNaN(g)?d=parseFloat(n):d=g}else d=parseFloat(n)*parseFloat(r);const m=Math.max(Math.floor(Math.max(d,o.height)),12);let h=o.top;o.height<d&&(h-=(d-o.height)/2),h=Math.floor(h);const p=this.editorMask.getBoundingClientRect(),S=Math.floor(h-p.top),T=Math.floor(o.left+o.width/2-p.left);let x=0;if(t.collapsed&&(x=Math.round(Math.atan2(o.width,o.height)*180/Math.PI),x!==0)){const g=document.createElement("span");g.style.cssText="display: inline-block; width: 10px; height: 10px; position: relative; contain: layout style size; writing-mode: inherit";const b=document.createElement("span");b.style.cssText="position: absolute; left: 0; top: 0; width:0;height:0",g.append(b),i.append(g);const v=b.getBoundingClientRect();b.style.right="0",b.style.left="";const E=b.getBoundingClientRect(),R=v.x-E.x,P=v.y-E.y;x=Math.atan2(P,R)*180/Math.PI,g.remove()}if((l==="vertical-lr"||l==="vertical-rl")&&(x+=90),Object.assign(this.elementRef.style,{left:T+"px",top:S+"px",height:m+"px",lineHeight:m+"px",fontSize:n,transform:`rotate(${x}deg)`}),this.caret.style.backgroundColor=a==="rgba(0, 0, 0, 0)"?"#000":a,this.styleChangeEvent.next({height:m+"px",lineHeight:m+"px",fontSize:n}),this.positionChangeEvent.next({left:T,top:h,height:m}),this.changeFromSelf){this.changeFromSelf=!1;const g=this.elementRef.getBoundingClientRect(),b=this.getScrollContainer(s),v=b===document.documentElement?{top:0,bottom:document.documentElement.clientHeight}:b.getBoundingClientRect(),E=this.getLimit(),R=Math.max(E.top,v.top),P=Math.min(E.bottom,v.bottom);g.top<R?b.scrollTop-=R-g.top:g.bottom>P&&(b.scrollTop+=g.bottom-P)}}getScrollContainer(t){for(;t;){if(t instanceof Element){const s=getComputedStyle(t);if(s.overflow!=="visible"||s.overflowX!=="visible"||s.overflowY!=="visible")return t}t=t.parentNode}return document.documentElement}}exports.MagicInput=class extends w{constructor(t,s,i,e,o,n,r,a){super(),this.domAdapter=t,this.parser=s,this.keyboard=i,this.commander=e,this.selection=o,this.controller=n,this.scheduler=r,this.textbus=a,this.caret=new Z(this.domAdapter,this.scheduler,this.textbus.get(L)),this.onReady=new Promise(l=>{this.subscription.add(c.fromEvent(this.container,"load").subscribe(()=>{const d=this.container.contentDocument;d.open(),d.write(Y),d.close(),this.doc=d,this.init(),l()}),n.onReadonlyStateChange.subscribe(()=>{n.readonly&&this.blur()}))}),this.caret.elementRef.append(this.container)}domAdapter;parser;keyboard;commander;selection;controller;scheduler;textbus;composition=!1;onReady;caret;set disabled(t){this._disabled=t,t&&this.textarea&&(this.textarea.disabled=t)}get disabled(){return this._disabled}isSafari=A();isFirefox=D();isMac=_();isWindows=M();_disabled=!1;container=this.createEditableFrame();subscription=new c.Subscription;doc;textarea=null;isFocus=!1;nativeFocus=!1;ignoreComposition=!1;focus(t,s){this.disabled||this.caret.show(t,s),!this.controller.readonly&&(this.isFocus||(this.textarea?.focus(),setTimeout(()=>{!this.nativeFocus&&this.isFocus&&this.reInit()})),this.isFocus=!0)}blur(){this.caret.hide(),this.textarea?.blur(),this.isFocus=!1}destroy(){this.caret.destroy(),this.subscription.unsubscribe()}reInit(t=!1){this.subscription.unsubscribe(),this.textarea?.parentNode?.removeChild(this.textarea),this.subscription=new c.Subscription,this.init(),t?setTimeout(()=>{this.textarea?.focus()}):this.textarea?.focus()}init(){const t=this.doc,s=t.body,i=t.createElement("textarea");i.disabled=this.disabled,s.appendChild(i),this.textarea=i,this.subscription.add(c.fromEvent(i,"blur").subscribe(()=>{if(this.isFocus=!1,this.nativeFocus=!1,this.caret.hide(),this.domAdapter.composition){const e=this.domAdapter.composition.slot;this.domAdapter.composition=null,this.domAdapter.compositionNode=null,e.__changeMarker__.forceMarkDirtied()}}),c.fromEvent(i,"focus").subscribe(()=>{this.nativeFocus=!0}),this.caret.onStyleChange.subscribe(e=>{Object.assign(i.style,e)})),this.handleInput(i),this.handleShortcut(i),this.handleDefaultActions(i)}handleDefaultActions(t){this.subscription.add(c.fromEvent(D()?t:document,"copy").subscribe(s=>{this.copyHandler(s)}),c.fromEvent(t,"paste").subscribe(s=>{this.pasteHandler(s)}))}copyHandler(t){const s=this.selection;if(s.isSelected&&s.startSlot===s.endSlot&&s.endOffset-s.startOffset===1&&typeof s.startSlot.getContentAtIndex(s.startOffset)=="object"){const e=t.clipboardData,n=document.getSelection().getRangeAt(0),r=document.createElement("div"),a=n.cloneContents();r.append(a),e.setData("text/html",r.innerHTML),e.setData("text",r.innerText),t.preventDefault()}}pasteHandler(t){const s=t.clipboardData.getData("Text"),i=Array.from(t.clipboardData.types||[]),e=Array.from(t.clipboardData.files);if(i.every(n=>n==="Files")&&e.length){Promise.all(e.filter(n=>/image/i.test(n.type)).map(n=>{const r=new FileReader;return new Promise(a=>{r.onload=l=>{a(l.target.result)},r.readAsDataURL(n)})})).then(n=>{const r=n.map(a=>`<img src=${a}>`).join("");this.paste(r,s)}),t.preventDefault();return}const o=this.doc.createElement("div");o.style.cssText="width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0",o.contentEditable="true",this.doc.body.appendChild(o),o.focus(),setTimeout(()=>{this.doc.body.removeChild(o),o.style.cssText="",this.paste(o,s)})}paste(t,s){const i=this.parser.parse(t,new u.Slot([u.ContentType.BlockComponent,u.ContentType.InlineComponent,u.ContentType.Text]));this.commander.paste(i,s)}handleShortcut(t){let s=!1,i=!1;this.subscription.add(c.fromEvent(t,"compositionstart").subscribe(()=>{s=!0}),c.fromEvent(t,"compositionend").subscribe(()=>{s=!1}),c.fromEvent(t,"beforeinput").subscribe(e=>{this.ignoreComposition=!1,this.isSafari&&e.inputType==="insertFromComposition"&&(i=!0)}),c.fromEvent(t,"keydown").pipe(c.filter(()=>this.isSafari&&i?(i=!1,!1):!s)).subscribe(e=>{this.ignoreComposition=!1;let o=e.key;o==="Process"&&/Digit\d/.test(e.code)&&e.shiftKey&&(o=")!@#$%^Z&*(".charAt(+e.code.substring(5)),e.preventDefault()),this.caret.changeFromSelf=!0,this.keyboard.execShortcut({key:o,altKey:e.altKey,shiftKey:e.shiftKey,modKey:this.isMac?e.metaKey:e.ctrlKey,agent:{key:e.key,code:e.code,keyCode:e.keyCode}})?(this.ignoreComposition=!0,e.preventDefault()):this.caret.changeFromSelf=!1}))}handleInput(t){let s=0;this.subscription.add(c.fromEvent(t,"compositionstart").pipe(c.filter(()=>!this.ignoreComposition)).subscribe(()=>{this.selection.isCollapsed||(this.caret.changeFromSelf=!0,this.commander.delete()),this.composition=!0,s=this.selection.startOffset;const e=this.selection.startSlot,o=new u.Event(e,{index:s});u.invokeListener(e.parent,"onCompositionStart",o)}),c.fromEvent(t,"compositionupdate").pipe(c.filter(()=>!this.ignoreComposition)).pipe(c.distinctUntilChanged((e,o)=>e.data!==o.data)).subscribe(e=>{if(e.data===" ")return;const o=this.selection.startSlot;this.domAdapter.composition={slot:o,text:e.data,offset:e.data.length,index:s},this.caret.changeFromSelf=!0,this.caret.refresh();const n=new u.Event(o,{index:s,data:e.data});u.invokeListener(o.parent,"onCompositionUpdate",n),o.__changeMarker__.forceMarkDirtied()}));let i=!1;this.subscription.add(c.merge(c.fromEvent(t,"beforeinput").pipe(c.filter(e=>(e.preventDefault(),this.isFirefox&&e.inputType==="insertFromPaste"?!1:this.isSafari?(i=e.inputType==="insertFromComposition",e.inputType==="insertText"||e.inputType==="insertFromComposition"):!e.isComposing&&!!e.data)),c.map(e=>e.data)),this.isSafari?new c.Observable:c.fromEvent(t,"compositionend").pipe(c.filter(()=>!this.ignoreComposition)).pipe(c.map(e=>(i=!0,e.preventDefault(),t.value="",e.data)))).subscribe(e=>{if(this.composition=!1,this.domAdapter.composition=null,e?(this.caret.changeFromSelf=!0,this.commander.write(e)):this.selection.startSlot?.__changeMarker__.forceMarkDirtied(),i){const o=this.selection.startSlot;if(o){const n=new u.Event(o,null);u.invokeListener(o.parent,"onCompositionEnd",n)}}i=!1}))}createEditableFrame(){return y("iframe",{attrs:{scrolling:"no"},styles:{border:"none",width:"100%",display:"block",height:"100%",position:"relative",top:this.isWindows?"3px":"0"}})}};exports.MagicInput=q([C.Injectable()],exports.MagicInput);var G=Object.getOwnPropertyDescriptor,J=(f,t,s,i)=>{for(var e=i>1?void 0:i?G(t,s):t,o=f.length-1,n;o>=0;o--)(n=f[o])&&(e=n(e)||e);return e},Q=(f,t)=>(s,i)=>t(s,i,f);class tt{}exports.CollaborateCursor=class{constructor(t,s,i,e,o){this.nativeSelection=s,this.scheduler=i,this.selection=e,this.awarenessDelegate=o,this.container=t.get(I),this.canvasContainer.append(this.canvas),this.host.append(this.canvasContainer,this.tooltips),this.container.prepend(this.host),this.subscription.add(this.onRectsChange.subscribe(n=>{for(const r of n)this.context.fillStyle=r.color,this.context.beginPath(),this.context.rect(r.left,r.top,r.width,r.height),this.context.fill(),this.context.closePath()}),c.fromEvent(window,"resize").subscribe(()=>{this.canvas.style.height=document.documentElement.clientHeight+"px",this.refresh()}),this.scheduler.onDocChanged.subscribe(()=>{this.refresh()}))}nativeSelection;scheduler;selection;awarenessDelegate;host=y("div",{styles:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:1}});canvasContainer=y("div",{styles:{position:"absolute",left:0,top:0,width:"100%",height:"100%",overflow:"hidden"}});canvas=y("canvas",{styles:{position:"absolute",opacity:.5,left:0,top:0,width:"100%",height:document.documentElement.clientHeight+"px",pointerEvents:"none"}});context=this.canvas.getContext("2d");tooltips=y("div",{styles:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",fontSize:"12px",zIndex:10}});onRectsChange=new c.Subject;subscription=new c.Subscription;selectionCursors=[];container;ratio=window.devicePixelRatio||1;refresh(){this.draw(this.selectionCursors)}destroy(){this.subscription.unsubscribe()}draw(t){this.selectionCursors=t;const s=this.container.getBoundingClientRect();this.canvas.style.top=s.top*-1+"px",this.canvas.width=this.canvas.offsetWidth*this.ratio,this.canvas.height=this.canvas.offsetHeight*this.ratio,this.context.scale(this.ratio,this.ratio),this.context.clearRect(0,0,this.canvas.width,this.canvas.height);const i=[];t.filter(e=>e.selection.anchor.length&&e.selection.focus.length).forEach(e=>{const o=[...e.selection.anchor],n=[...e.selection.focus],r=o.pop(),a=this.selection.findSlotByPaths(o),l=n.pop(),d=this.selection.findSlotByPaths(n);if(!a||!d)return;const{focus:m,anchor:h}=this.nativeSelection.getPositionByRange({focusOffset:l,anchorOffset:r,focusSlot:d,anchorSlot:a});if(!m||!h)return;const p=document.createRange();try{p.setStart(h.node,h.offset),p.setEnd(m.node,m.offset)}catch{return}(h.node!==m.node||h.offset!==m.offset)&&p.collapsed&&(p.setStart(m.node,m.offset),p.setEnd(h.node,h.offset));let S=!1;this.awarenessDelegate&&(S=this.awarenessDelegate.getRects({focusOffset:l,anchorOffset:r,focusSlot:d,anchorSlot:a},p,e)),S||(S=p.getClientRects());const T=[];for(let v=S.length-1;v>=0;v--){const E=S[v];T.push({color:e.color,username:e.username,left:E.left-s.left,top:E.top,width:E.width,height:E.height})}this.onRectsChange.next(T);const x=p.cloneRange();x.setStart(m.node,m.offset),x.collapse(!0);const g=N(x),b={username:e.username,color:e.color,left:g.left-s.left,top:g.top-s.top,width:1,height:g.height};b.left<0||b.top<0||b.left>s.width||i.push(b)}),this.drawUserCursor(i)}drawUserCursor(t){for(let s=0;s<t.length;s++){const i=t[s],{cursor:e,userTip:o,anchor:n}=this.getUserCursor(s);Object.assign(e.style,{left:i.left+"px",top:i.top+"px",width:i.width+"px",height:i.height+"px",background:i.color,display:"block"}),n.style.background=i.color,o.innerText=i.username,o.style.background=i.color}for(let s=t.length;s<this.tooltips.children.length;s++)this.tooltips.removeChild(this.tooltips.children[s])}getUserCursor(t){let s=this.tooltips.children[t];if(s){const o=s.children[0];return{cursor:s,anchor:o,userTip:o.children[0]}}const i=y("span",{styles:{position:"absolute",left:"50%",transform:"translateX(-50%)",marginBottom:"2px",bottom:"100%",whiteSpace:"nowrap",color:"#fff",boxShadow:"0 1px 2px rgba(0,0,0,.1)",opacity:.8,borderRadius:"3px",padding:"3px 5px",pointerEvents:"none"}}),e=y("span",{styles:{position:"absolute",top:"-2px",left:"-2px",width:"5px",height:"5px",borderRadius:"50%",pointerEvents:"auto",pointer:"cursor"},children:[i]});return s=y("span",{styles:{position:"absolute"},children:[e]}),this.tooltips.append(s),{cursor:s,anchor:e,userTip:i}}};exports.CollaborateCursor=J([C.Injectable(),Q(4,C.Optional())],exports.CollaborateCursor);var et=Object.getOwnPropertyDescriptor,st=(f,t,s,i)=>{for(var e=i>1?void 0:i?et(t,s):t,o=f.length-1,n;o>=0;o--)(n=f[o])&&(e=n(e)||e);return e};class it{onPositionChange;set nativeRange(t){if(this._nativeRange=t,t){const s=t.cloneRange();s.collapse(!0);const i=N(s);this.positionChangeEvent.next({left:i.left,top:i.top,height:i.height})}else this.positionChangeEvent.next(null)}get nativeRange(){return this._nativeRange}get rect(){if(this.nativeRange){const t=this.nativeRange.cloneRange();return t.collapse(!0),N(t)}return{left:0,top:0,width:0,height:0}}_nativeRange=null;subs=[];positionChangeEvent=new c.Subject;constructor(){this.onPositionChange=this.positionChangeEvent.pipe(c.distinctUntilChanged())}refresh(){}destroy(){this.subs.forEach(t=>t.unsubscribe()),this.subs=[]}}exports.NativeInput=class extends w{constructor(t,s,i,e,o,n,r){super(),this.parser=s,this.selection=i,this.keyboard=e,this.domAdapter=o,this.commander=n,this.controller=r,this.documentView=t.get(O),r.readonly||(this.documentView.contentEditable="true"),this.subscription.add(r.onReadonlyStateChange.subscribe(()=>{this.documentView.contentEditable=r.readonly?"false":"true"})),this.handleShortcut(this.documentView),this.handleInput(this.documentView),this.handleDefaultActions(this.documentView)}parser;selection;keyboard;domAdapter;commander;controller;caret=new it;composition=!1;onReady=Promise.resolve();set disabled(t){if(this._disabled=t,this.controller.readonly){this.documentView.contentEditable="false";return}this.documentView.contentEditable=t?"false":"true"}get disabled(){return this._disabled}_disabled=!1;documentView;nativeSelection=document.getSelection();subscription=new c.Subscription;nativeRange=null;isSafari=A();isMac=_();isMobileBrowser=j();ignoreComposition=!1;focus(t){this.controller.readonly||(this.caret.nativeRange=t,this.nativeRange=t)}blur(){if(this.nativeRange&&this.nativeSelection.rangeCount>0&&this.nativeSelection.getRangeAt(0)===this.nativeRange){this.nativeSelection.removeAllRanges(),this.nativeRange=null;return}}destroy(){this.caret.destroy(),this.subscription.unsubscribe()}handleDefaultActions(t){this.subscription.add(c.fromEvent(D()?t:document,"copy").subscribe(s=>{this.copyHandler(s)}),c.fromEvent(t,"paste").subscribe(s=>{this.pasteHandler(s)}))}copyHandler(t){const s=this.selection;if(s.isSelected&&s.startSlot===s.endSlot&&s.endOffset-s.startOffset===1&&typeof s.startSlot.getContentAtIndex(s.startOffset)=="object"){const e=t.clipboardData,n=document.getSelection().getRangeAt(0),r=document.createElement("div"),a=n.cloneContents();r.append(a),e.setData("text/html",r.innerHTML),e.setData("text",r.innerText),t.preventDefault()}}pasteHandler(t){const s=t.clipboardData.getData("Text"),i=Array.from(t.clipboardData.types||[]),e=Array.from(t.clipboardData.files);if(i.every(n=>n==="Files")&&e.length){Promise.all(e.filter(n=>/image/i.test(n.type)).map(n=>{const r=new FileReader;return new Promise(a=>{r.onload=l=>{a(l.target.result)},r.readAsDataURL(n)})})).then(n=>{const r=n.map(a=>`<img src=${a}>`).join("");this.paste(r,s)}),t.preventDefault();return}const o=document.createElement("div");o.style.cssText="width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0",o.contentEditable="true",document.body.appendChild(o),o.focus(),setTimeout(()=>{document.body.removeChild(o),o.style.cssText="",this.paste(o,s)})}paste(t,s){const i=this.parser.parse(t,new u.Slot([u.ContentType.BlockComponent,u.ContentType.InlineComponent,u.ContentType.Text]));this.commander.paste(i,s)}handleShortcut(t){let s=!1,i=!1;this.subscription.add(c.fromEvent(t,"compositionstart").subscribe(()=>{s=!0}),c.fromEvent(t,"compositionend").subscribe(()=>{s=!1}),c.fromEvent(t,"beforeinput").subscribe(e=>{this.isSafari&&e.inputType==="insertFromComposition"&&(i=!0)}),c.fromEvent(t,"keydown").pipe(c.filter(()=>this.isSafari&&i?(i=!1,!1):!s)).subscribe(e=>{this.ignoreComposition=!1;let o=e.key;o==="Process"&&/Digit\d/.test(e.code)&&e.shiftKey&&(o=")!@#$%^Z&*(".charAt(+e.code.substring(5)),e.preventDefault()),this.keyboard.execShortcut({key:o,altKey:e.altKey,shiftKey:e.shiftKey,modKey:this.isMac?e.metaKey:e.ctrlKey,agent:{key:e.key,keyCode:e.keyCode,code:e.code}})&&(this.ignoreComposition=!0,e.preventDefault())}))}handleInput(t){this.isMobileBrowser?this.handleMobileInput(t):this.handlePCInput(t)}handleMobileInput(t){let s=!0,i;const e=()=>{this.composition=!0,i=this.selection.startOffset;const r=this.selection.startSlot,a=new u.Event(r,{index:i});u.invokeListener(r.parent,"onCompositionStart",a)},o=r=>{const a=this.selection.startSlot,l=new u.Event(a,{index:i,data:r});u.invokeListener(a.parent,"onCompositionUpdate",l)},n=r=>{this.composition=!1,r&&this.commander.write(r);const a=this.selection.startSlot;if(a){const l=new u.Event(a,null);u.invokeListener(a.parent,"onCompositionEnd",l)}};this.subscription.add(c.fromEvent(t,"compositionstart").subscribe(()=>{e()}),c.fromEvent(t,"compositionupdate").subscribe(r=>{o(r.data)}),c.fromEvent(t,"compositionend").subscribe(r=>{n(r.data);const a=this.nativeSelection.focusNode;a instanceof Text&&a.textContent===r.data&&a.remove()}),c.fromEvent(t,"beforeinput").subscribe(r=>{switch(r.inputType){case"insertText":r.data&&(this.commander.write(r.data),r.preventDefault());break;case"insertCompositionText":s?(s=!1,e()):o(r.data||"");break;case"deleteCompositionText":this.composition=!1;break;case"deleteContentBackward":{this.composition=!1;const a=r.getTargetRanges()[0];if(!a)break;const l=this.domAdapter.getLocationByNativeNode(a.startContainer),d=this.selection.startSlot;d&&(this.selection.setBaseAndExtent(d,l.startIndex+a.startOffset,d,l.startIndex+a.endOffset),this.commander.delete());break}case"insertReplacementText":{this.composition=!1;const a=r.getTargetRanges()[0],l=this.domAdapter.getLocationByNativeNode(a.startContainer),d=this.selection.startSlot;this.selection.setBaseAndExtent(d,l.startIndex+a.startOffset,d,l.startIndex+a.endOffset),this.commander.delete();const m=r.dataTransfer?.getData("text")||r.data||null;m&&this.commander.write(m);break}}}))}handlePCInput(t){let s=0,i=!1;this.subscription.add(c.fromEvent(t,"compositionstart").pipe(c.filter(()=>!this.ignoreComposition)).subscribe(()=>{this.composition=!0,s=this.selection.startOffset;const e=this.selection.startSlot,o=new u.Event(e,{index:s});u.invokeListener(e.parent,"onCompositionStart",o)}),c.fromEvent(t,"compositionupdate").pipe(c.filter(()=>!this.ignoreComposition)).subscribe(e=>{const o=this.selection.startSlot,n=new u.Event(o,{index:s,data:e.data});u.invokeListener(o.parent,"onCompositionUpdate",n)}),c.merge(c.fromEvent(t,"beforeinput").pipe(c.map(e=>{if(e.preventDefault(),e.inputType==="insertCompositionText")return null;if(e.inputType==="insertReplacementText"){const o=e.getTargetRanges()[0],n=this.domAdapter.getLocationByNativeNode(o.startContainer),r=this.selection.startSlot;return this.selection.setBaseAndExtent(r,n.startIndex+o.startOffset,r,n.startIndex+o.endOffset),this.commander.delete(),e.dataTransfer?.getData("text")||e.data||null}return i=e.inputType==="insertFromComposition",i&&this.composition?null:this.isSafari&&(e.inputType==="insertText"||i)||!e.isComposing&&e.data?e.data:null}),c.filter(e=>e)),this.isSafari?new c.Observable:c.fromEvent(t,"compositionend").pipe(c.filter(()=>!this.ignoreComposition)).pipe(c.filter(()=>this.composition),c.map(e=>(i=!0,e.preventDefault(),e.data)),c.filter(()=>{const e=this.ignoreComposition;return this.ignoreComposition=!1,!e}))).subscribe(e=>{if(this.composition=!1,e){const o=this.nativeSelection.focusNode;o instanceof Text&&o.textContent===e&&o.remove(),this.commander.write(e)}if(i){const o=this.selection.startSlot;if(o){const n=new u.Event(o,null);u.invokeListener(o.parent,"onCompositionEnd",n)}}i=!1}))}};exports.NativeInput=st([C.Injectable()],exports.NativeInput);class H extends u.Adapter{onViewUpdated=new c.Subject;host=y("div",{styles:{cursor:"text",wordBreak:"break-all",boxSizing:"border-box",flex:1,outline:"none"},attrs:{"data-textbus-view":O},props:{id:"textbus-"+Number((Math.random()+"").substring(2)).toString(16)}})}const F=u.makeError("BrowserModule");class k{constructor(t){this.config=t;const{mask:s,wrapper:i}=k.createLayout();i.prepend(t.adapter.host),t.minHeight&&(t.adapter.host.style.minHeight=t.minHeight),this.providers=[{provide:B,useValue:t},{provide:I,useValue:i},{provide:O,useValue:t.adapter.host},{provide:L,useValue:s},{provide:u.NativeSelectionBridge,useExisting:exports.SelectionBridge},{provide:w,useClass:t.useContentEditable?exports.NativeInput:exports.MagicInput},{provide:u.Adapter,useValue:t.adapter},{provide:H,useValue:t.adapter},{provide:u.FocusManager,useFactory:e=>{const o=new c.Subject,n=new c.Subject;return e.caret.onPositionChange.pipe(c.map(r=>!!r),c.distinctUntilChanged()).subscribe(r=>{r?o.next():n.next()}),{onFocus:o,onBlur:n}},deps:[w]},exports.Parser,exports.SelectionBridge,exports.CollaborateCursor],this.workbench=i}config;providers;workbench;readDocumentByHTML(t,s,i){const o=i.get(exports.Parser).parseDoc(t,s);if(o instanceof u.Component)return o;throw F("rootComponentLoader must return a component instance.")}readDocumentByComponentLiteral(t,s,i){return i.get(u.Registry).createComponentByFactory(t,s)}async setup(t){const s=this.config.renderTo();if(!(s instanceof HTMLElement))throw F("view container is not a HTMLElement");return s.append(this.workbench),await t.get(w).onReady,()=>{this.workbench.remove()}}onAfterStartup(t){this.config.autoFocus&&t.focus()}onDestroy(t){t.get(w).destroy(),t.get(exports.SelectionBridge).destroy(),t.get(exports.CollaborateCursor).destroy()}static createLayout(){const t=y("div",{attrs:{"data-textbus-view":L},styles:{position:"absolute",left:0,right:0,top:0,bottom:0,pointerEvents:"none"}}),s=y("div",{styles:{position:"absolute",left:0,right:0,top:0,bottom:0,margin:"0 -2px",zIndex:1,pointerEvents:"none",overflow:"hidden"},children:[t]});return{wrapper:y("div",{attrs:{"data-textbus-view":I},styles:{display:"flex",minHeight:"100%",position:"relative",flexDirection:"column"},children:[s]}),mask:t}}}exports.BrowserModule=k;exports.CollaborateSelectionAwarenessDelegate=tt;exports.DomAdapter=H;exports.EDITOR_OPTIONS=B;exports.Input=w;exports.VIEW_CONTAINER=I;exports.VIEW_DOCUMENT=O;exports.VIEW_MASK=L;exports.createElement=y;exports.getLayoutRectByRange=N;exports.isFirefox=D;exports.isMac=_;exports.isMobileBrowser=j;exports.isSafari=A;exports.isWindows=M;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+
5
+ const core$1 = require('@textbus/core');
6
+ const stream = require('@tanbo/stream');
7
+ const core = require('@viewfly/core');
8
+
9
+ /**
10
+ * 选区焦点可视位置
11
+ */ function _array_like_to_array$2(arr, len) {
12
+ if (len == null || len > arr.length) len = arr.length;
13
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
14
+ return arr2;
15
+ }
16
+ function _array_without_holes$2(arr) {
17
+ if (Array.isArray(arr)) return _array_like_to_array$2(arr);
18
+ }
19
+ function _iterable_to_array$2(iter) {
20
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
21
+ }
22
+ function _non_iterable_spread$2() {
23
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
24
+ }
25
+ function _to_consumable_array$2(arr) {
26
+ return _array_without_holes$2(arr) || _iterable_to_array$2(arr) || _unsupported_iterable_to_array$2(arr) || _non_iterable_spread$2();
27
+ }
28
+ function _unsupported_iterable_to_array$2(o, minLen) {
29
+ if (!o) return;
30
+ if (typeof o === "string") return _array_like_to_array$2(o, minLen);
31
+ var n = Object.prototype.toString.call(o).slice(8, -1);
32
+ if (n === "Object" && o.constructor) n = o.constructor.name;
33
+ if (n === "Map" || n === "Set") return Array.from(n);
34
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
35
+ }
36
+ function createElement(tagName) {
37
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
38
+ var el = document.createElement(tagName);
39
+ if (options.classes) {
40
+ var _el_classList;
41
+ (_el_classList = el.classList).add.apply(_el_classList, _to_consumable_array$2(options.classes));
42
+ }
43
+ if (options.attrs) {
44
+ Object.keys(options.attrs).forEach(function(key) {
45
+ el.setAttribute(key, options.attrs[key]);
46
+ });
47
+ }
48
+ if (options.props) {
49
+ Object.keys(options.props).forEach(function(key) {
50
+ el[key] = options.props[key];
51
+ });
52
+ }
53
+ if (options.styles) {
54
+ Object.assign(el.style, options.styles);
55
+ }
56
+ if (options.children) {
57
+ options.children.filter(function(i) {
58
+ return i;
59
+ }).forEach(function(item) {
60
+ el.appendChild(item);
61
+ });
62
+ }
63
+ if (options.on) {
64
+ Object.keys(options.on).forEach(function(key) {
65
+ el.addEventListener(key, options.on[key]);
66
+ });
67
+ }
68
+ return el;
69
+ }
70
+ function getLayoutRectByRange(range) {
71
+ var startContainer = range.startContainer, startOffset = range.startOffset;
72
+ if (startContainer.nodeType === Node.TEXT_NODE) {
73
+ if (startOffset > 0) {
74
+ return range.getBoundingClientRect();
75
+ }
76
+ var parentNode = startContainer.parentNode;
77
+ startOffset = Array.from(parentNode.childNodes).indexOf(startContainer);
78
+ startContainer = parentNode;
79
+ }
80
+ var beforeNode = startContainer.childNodes[startOffset - 1];
81
+ if (beforeNode) {
82
+ if (beforeNode.nodeType === Node.ELEMENT_NODE && beforeNode.nodeName.toLowerCase() !== 'br') {
83
+ var rect = beforeNode.getBoundingClientRect();
84
+ return {
85
+ left: rect.right,
86
+ top: rect.top,
87
+ width: range.collapsed ? 1 : rect.width,
88
+ height: rect.height
89
+ };
90
+ } else if (beforeNode.nodeType === Node.TEXT_NODE) {
91
+ var range2 = document.createRange();
92
+ range2.setStart(beforeNode, beforeNode.textContent.length);
93
+ range2.setEnd(beforeNode, beforeNode.textContent.length);
94
+ var rect1 = range2.getBoundingClientRect();
95
+ return {
96
+ left: rect1.right,
97
+ top: rect1.top,
98
+ width: range.collapsed ? 1 : rect1.width,
99
+ height: rect1.height
100
+ };
101
+ }
102
+ }
103
+ var offsetNode = startContainer.childNodes[startOffset];
104
+ var isInsertBefore = false;
105
+ if (!offsetNode) {
106
+ var lastChild = startContainer.lastChild;
107
+ if (lastChild && lastChild.nodeType === Node.ELEMENT_NODE) {
108
+ var rect2 = lastChild.getBoundingClientRect();
109
+ return {
110
+ left: rect2.right,
111
+ top: rect2.top,
112
+ width: range.collapsed ? 1 : rect2.width,
113
+ height: rect2.height
114
+ };
115
+ }
116
+ }
117
+ if (offsetNode) {
118
+ if (offsetNode.nodeType === Node.ELEMENT_NODE && offsetNode.nodeName.toLowerCase() !== 'br') {
119
+ var rect3 = offsetNode.getBoundingClientRect();
120
+ return {
121
+ left: rect3.left,
122
+ top: rect3.top,
123
+ width: range.collapsed ? 1 : rect3.width,
124
+ height: rect3.height
125
+ };
126
+ }
127
+ isInsertBefore = true;
128
+ }
129
+ var span = startContainer.ownerDocument.createElement('span');
130
+ span.innerText = '\u200b';
131
+ span.style.display = 'inline-block';
132
+ if (isInsertBefore) {
133
+ startContainer.insertBefore(span, offsetNode);
134
+ } else {
135
+ startContainer.appendChild(span);
136
+ }
137
+ var rect4 = span.getBoundingClientRect();
138
+ startContainer.removeChild(span);
139
+ return {
140
+ left: rect4.left,
141
+ top: rect4.top,
142
+ width: range.collapsed ? 1 : rect4.width,
143
+ height: rect4.height
144
+ };
145
+ }
146
+
147
+ var isWindows = function isWindows() {
148
+ return /win(dows|32|64)/i.test(navigator.userAgent);
149
+ };
150
+ var isMac = function isMac() {
151
+ return /mac os/i.test(navigator.userAgent);
152
+ };
153
+ var isSafari = function isSafari() {
154
+ return /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
155
+ };
156
+ var isFirefox = function isFirefox() {
157
+ return /Firefox/.test(navigator.userAgent);
158
+ };
159
+ var isMobileBrowser = function isMobileBrowser() {
160
+ return /Android|iPhone|iPad/.test(navigator.userAgent);
161
+ };
162
+
163
+ /**
164
+ * 编辑器可选项依赖注入 token
165
+ */ var EDITOR_OPTIONS = new core.InjectionToken('EDITOR_OPTIONS');
166
+ /**
167
+ * 编辑器容器依赖注入 token
168
+ */ var VIEW_CONTAINER = new core.InjectionToken('VIEW_CONTAINER');
169
+ /**
170
+ * 编辑器容器依赖注入 token
171
+ */ var VIEW_DOCUMENT = new core.InjectionToken('VIEW_DOCUMENT');
172
+ /**
173
+ * 编辑器容器遮罩层 token
174
+ */ var VIEW_MASK = new core.InjectionToken('VIEW_MASK');
175
+
176
+ function _array_like_to_array$1(arr, len) {
177
+ if (len == null || len > arr.length) len = arr.length;
178
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
179
+ return arr2;
180
+ }
181
+ function _array_without_holes$1(arr) {
182
+ if (Array.isArray(arr)) return _array_like_to_array$1(arr);
183
+ }
184
+ function _class_call_check$7(instance, Constructor) {
185
+ if (!(instance instanceof Constructor)) {
186
+ throw new TypeError("Cannot call a class as a function");
187
+ }
188
+ }
189
+ function _defineProperties$5(target, props) {
190
+ for(var i = 0; i < props.length; i++){
191
+ var descriptor = props[i];
192
+ descriptor.enumerable = descriptor.enumerable || false;
193
+ descriptor.configurable = true;
194
+ if ("value" in descriptor) descriptor.writable = true;
195
+ Object.defineProperty(target, descriptor.key, descriptor);
196
+ }
197
+ }
198
+ function _create_class$5(Constructor, protoProps, staticProps) {
199
+ if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
200
+ if (staticProps) _defineProperties$5(Constructor, staticProps);
201
+ return Constructor;
202
+ }
203
+ function _define_property$6(obj, key, value) {
204
+ if (key in obj) {
205
+ Object.defineProperty(obj, key, {
206
+ value: value,
207
+ enumerable: true,
208
+ configurable: true,
209
+ writable: true
210
+ });
211
+ } else {
212
+ obj[key] = value;
213
+ }
214
+ return obj;
215
+ }
216
+ function _instanceof$4(left, right) {
217
+ "@swc/helpers - instanceof";
218
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
219
+ return !!right[Symbol.hasInstance](left);
220
+ } else {
221
+ return left instanceof right;
222
+ }
223
+ }
224
+ function _iterable_to_array$1(iter) {
225
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
226
+ }
227
+ function _non_iterable_spread$1() {
228
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
229
+ }
230
+ function _to_consumable_array$1(arr) {
231
+ return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
232
+ }
233
+ function _unsupported_iterable_to_array$1(o, minLen) {
234
+ if (!o) return;
235
+ if (typeof o === "string") return _array_like_to_array$1(o, minLen);
236
+ var n = Object.prototype.toString.call(o).slice(8, -1);
237
+ if (n === "Object" && o.constructor) n = o.constructor.name;
238
+ if (n === "Map" || n === "Set") return Array.from(n);
239
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
240
+ }
241
+ function _ts_decorate$4(decorators, target, key, desc) {
242
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
243
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
244
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
245
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
246
+ }
247
+ function _ts_metadata$4(k, v) {
248
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
249
+ }
250
+ function _ts_param$2(paramIndex, decorator) {
251
+ return function(target, key) {
252
+ decorator(target, key, paramIndex);
253
+ };
254
+ }
255
+ exports.Parser = /*#__PURE__*/ function() {
256
+ function Parser(options, textbus) {
257
+ _class_call_check$7(this, Parser);
258
+ _define_property$6(this, "textbus", void 0);
259
+ _define_property$6(this, "componentLoaders", void 0);
260
+ _define_property$6(this, "formatLoaders", void 0);
261
+ _define_property$6(this, "attributeLoaders", void 0);
262
+ this.textbus = textbus;
263
+ var componentLoaders = _to_consumable_array$1(options.componentLoaders || []);
264
+ var formatLoaders = _to_consumable_array$1(options.formatLoaders || []);
265
+ var attributeLoaders = _to_consumable_array$1(options.attributeLoaders || []);
266
+ // options.imports?.forEach(i => {
267
+ // componentLoaders.push(...(i.componentLoaders || []))
268
+ // formatLoaders.push(...(i.formatLoaders || []))
269
+ // })
270
+ this.componentLoaders = componentLoaders;
271
+ this.formatLoaders = formatLoaders;
272
+ this.attributeLoaders = attributeLoaders;
273
+ }
274
+ _create_class$5(Parser, [
275
+ {
276
+ /**
277
+ * 使用指定的组件加载器解析一段 HTML 字符串或 DOM 元素
278
+ * @param html
279
+ * @param rootComponentLoader
280
+ */ key: "parseDoc",
281
+ value: function parseDoc(html, rootComponentLoader) {
282
+ var _this = this;
283
+ var element = typeof html === 'string' ? Parser.parseHTML(html) : html;
284
+ return rootComponentLoader.read(element, this.textbus, function(childSlot, slotRootElement) {
285
+ var slotContentHostElement = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : slotRootElement;
286
+ return _this.readSlot(childSlot, slotRootElement, slotContentHostElement);
287
+ });
288
+ }
289
+ },
290
+ {
291
+ /**
292
+ * 将一段 HTML 或 DOM 元素解析到指定插槽
293
+ * @param html
294
+ * @param rootSlot
295
+ */ key: "parse",
296
+ value: function parse(html, rootSlot) {
297
+ var element = typeof html === 'string' ? Parser.parseHTML(html) : html;
298
+ return this.readFormats(element, rootSlot);
299
+ }
300
+ },
301
+ {
302
+ key: "readComponent",
303
+ value: function readComponent(el, slot) {
304
+ if (el.nodeType === Node.ELEMENT_NODE) {
305
+ if (el.tagName === 'BR') {
306
+ slot.insert('\n');
307
+ return;
308
+ }
309
+ var schema = _to_consumable_array$1(slot.schema);
310
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
311
+ try {
312
+ for(var _iterator = this.componentLoaders[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
313
+ var t = _step.value;
314
+ if (t.match(el, schema)) {
315
+ var _this = this;
316
+ var result = t.read(el, this.textbus, function(childSlot, slotRootElement) {
317
+ var slotContentHostElement = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : slotRootElement;
318
+ return _this.readSlot(childSlot, slotRootElement, slotContentHostElement);
319
+ });
320
+ if (!result) {
321
+ return;
322
+ }
323
+ if (_instanceof$4(result, core$1.Slot)) {
324
+ result.toDelta().forEach(function(i) {
325
+ return slot.insert(i.insert, i.formats);
326
+ });
327
+ return;
328
+ }
329
+ slot.insert(result);
330
+ return;
331
+ }
332
+ }
333
+ } catch (err) {
334
+ _didIteratorError = true;
335
+ _iteratorError = err;
336
+ } finally{
337
+ try {
338
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
339
+ _iterator.return();
340
+ }
341
+ } finally{
342
+ if (_didIteratorError) {
343
+ throw _iteratorError;
344
+ }
345
+ }
346
+ }
347
+ this.readFormats(el, slot);
348
+ } else if (el.nodeType === Node.TEXT_NODE) {
349
+ this.readText(slot, el);
350
+ }
351
+ }
352
+ },
353
+ {
354
+ key: "readText",
355
+ value: function readText(slot, el) {
356
+ var textContent = el.textContent;
357
+ if (/^\s*[\r\n\u200b]+\s*$/.test(textContent)) {
358
+ return;
359
+ }
360
+ slot.insert(textContent);
361
+ }
362
+ },
363
+ {
364
+ key: "readFormats",
365
+ value: function readFormats(el, slot) {
366
+ var formats = this.formatLoaders.filter(function(f) {
367
+ return f.match(el);
368
+ }).map(function(f) {
369
+ return f.read(el);
370
+ });
371
+ var startIndex = slot.index;
372
+ var startNode = el.firstChild;
373
+ while(startNode){
374
+ this.readComponent(startNode, slot);
375
+ startNode = startNode.nextSibling;
376
+ }
377
+ var endIndex = slot.index;
378
+ this.applyFormats(slot, formats.map(function(i) {
379
+ return {
380
+ formatter: i.formatter,
381
+ value: i.value,
382
+ startIndex: startIndex,
383
+ endIndex: endIndex
384
+ };
385
+ }));
386
+ slot.retain(endIndex);
387
+ return slot;
388
+ }
389
+ },
390
+ {
391
+ key: "readSlot",
392
+ value: function readSlot(childSlot, slotRootElement, slotContentElement) {
393
+ if (slotRootElement.nodeType === Node.ELEMENT_NODE) {
394
+ this.attributeLoaders.filter(function(a) {
395
+ return a.match(slotRootElement);
396
+ }).forEach(function(a) {
397
+ var r = a.read(slotRootElement);
398
+ childSlot.setAttribute(r.attribute, r.value);
399
+ });
400
+ }
401
+ if (slotContentElement.nodeType === Node.ELEMENT_NODE) {
402
+ this.readFormats(slotContentElement, childSlot);
403
+ } else {
404
+ this.readText(childSlot, slotContentElement);
405
+ }
406
+ return childSlot;
407
+ }
408
+ },
409
+ {
410
+ key: "applyFormats",
411
+ value: function applyFormats(slot, formatItems) {
412
+ slot.background(function() {
413
+ formatItems.forEach(function(i) {
414
+ slot.retain(i.startIndex);
415
+ slot.retain(i.endIndex - i.startIndex, i.formatter, i.value);
416
+ });
417
+ });
418
+ }
419
+ }
420
+ ], [
421
+ {
422
+ key: "parseHTML",
423
+ value: function parseHTML(html) {
424
+ return new DOMParser().parseFromString(html, 'text/html').body;
425
+ }
426
+ }
427
+ ]);
428
+ return Parser;
429
+ }();
430
+ exports.Parser = _ts_decorate$4([
431
+ core.Injectable(),
432
+ _ts_param$2(0, core.Inject(EDITOR_OPTIONS)),
433
+ _ts_metadata$4("design:type", Function),
434
+ _ts_metadata$4("design:paramtypes", [
435
+ typeof ViewOptions === "undefined" ? Object : ViewOptions,
436
+ typeof core$1.Textbus === "undefined" ? Object : core$1.Textbus
437
+ ])
438
+ ], exports.Parser);
439
+
440
+ function _class_call_check$6(instance, Constructor) {
441
+ if (!(instance instanceof Constructor)) {
442
+ throw new TypeError("Cannot call a class as a function");
443
+ }
444
+ }
445
+ var Input = function Input() {
446
+ _class_call_check$6(this, Input);
447
+ };
448
+
449
+ function _assert_this_initialized$2(self) {
450
+ if (self === void 0) {
451
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
452
+ }
453
+ return self;
454
+ }
455
+ function _call_super$2(_this, derived, args) {
456
+ derived = _get_prototype_of$2(derived);
457
+ return _possible_constructor_return$2(_this, _is_native_reflect_construct$2() ? Reflect.construct(derived, args || [], _get_prototype_of$2(_this).constructor) : derived.apply(_this, args));
458
+ }
459
+ function _class_call_check$5(instance, Constructor) {
460
+ if (!(instance instanceof Constructor)) {
461
+ throw new TypeError("Cannot call a class as a function");
462
+ }
463
+ }
464
+ function _define_property$5(obj, key, value) {
465
+ if (key in obj) {
466
+ Object.defineProperty(obj, key, {
467
+ value: value,
468
+ enumerable: true,
469
+ configurable: true,
470
+ writable: true
471
+ });
472
+ } else {
473
+ obj[key] = value;
474
+ }
475
+ return obj;
476
+ }
477
+ function _get_prototype_of$2(o) {
478
+ _get_prototype_of$2 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
479
+ return o.__proto__ || Object.getPrototypeOf(o);
480
+ };
481
+ return _get_prototype_of$2(o);
482
+ }
483
+ function _inherits$2(subClass, superClass) {
484
+ if (typeof superClass !== "function" && superClass !== null) {
485
+ throw new TypeError("Super expression must either be null or a function");
486
+ }
487
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
488
+ constructor: {
489
+ value: subClass,
490
+ writable: true,
491
+ configurable: true
492
+ }
493
+ });
494
+ if (superClass) _set_prototype_of$2(subClass, superClass);
495
+ }
496
+ function _possible_constructor_return$2(self, call) {
497
+ if (call && (_type_of$2(call) === "object" || typeof call === "function")) {
498
+ return call;
499
+ }
500
+ return _assert_this_initialized$2(self);
501
+ }
502
+ function _set_prototype_of$2(o, p) {
503
+ _set_prototype_of$2 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
504
+ o.__proto__ = p;
505
+ return o;
506
+ };
507
+ return _set_prototype_of$2(o, p);
508
+ }
509
+ function _type_of$2(obj) {
510
+ "@swc/helpers - typeof";
511
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
512
+ }
513
+ function _is_native_reflect_construct$2() {
514
+ try {
515
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
516
+ } catch (_) {}
517
+ return (_is_native_reflect_construct$2 = function() {
518
+ return !!result;
519
+ })();
520
+ }
521
+ var DomAdapter = /*#__PURE__*/ function(Adapter) {
522
+ _inherits$2(DomAdapter, Adapter);
523
+ function DomAdapter() {
524
+ _class_call_check$5(this, DomAdapter);
525
+ var _this;
526
+ _this = _call_super$2(this, DomAdapter, arguments), _define_property$5(_this, "onViewUpdated", new stream.Subject()), _define_property$5(_this, "host", createElement('div', {
527
+ styles: {
528
+ cursor: 'text',
529
+ wordBreak: 'break-all',
530
+ boxSizing: 'border-box',
531
+ flex: 1,
532
+ outline: 'none'
533
+ },
534
+ attrs: {
535
+ 'data-textbus-view': VIEW_DOCUMENT
536
+ },
537
+ props: {
538
+ id: 'textbus-' + Number((Math.random() + '').substring(2)).toString(16)
539
+ }
540
+ }));
541
+ return _this;
542
+ }
543
+ return DomAdapter;
544
+ }(core$1.Adapter);
545
+
546
+ function _class_call_check$4(instance, Constructor) {
547
+ if (!(instance instanceof Constructor)) {
548
+ throw new TypeError("Cannot call a class as a function");
549
+ }
550
+ }
551
+ function _defineProperties$4(target, props) {
552
+ for(var i = 0; i < props.length; i++){
553
+ var descriptor = props[i];
554
+ descriptor.enumerable = descriptor.enumerable || false;
555
+ descriptor.configurable = true;
556
+ if ("value" in descriptor) descriptor.writable = true;
557
+ Object.defineProperty(target, descriptor.key, descriptor);
558
+ }
559
+ }
560
+ function _create_class$4(Constructor, protoProps, staticProps) {
561
+ if (protoProps) _defineProperties$4(Constructor.prototype, protoProps);
562
+ return Constructor;
563
+ }
564
+ function _define_property$4(obj, key, value) {
565
+ if (key in obj) {
566
+ Object.defineProperty(obj, key, {
567
+ value: value,
568
+ enumerable: true,
569
+ configurable: true,
570
+ writable: true
571
+ });
572
+ } else {
573
+ obj[key] = value;
574
+ }
575
+ return obj;
576
+ }
577
+ function _instanceof$3(left, right) {
578
+ "@swc/helpers - instanceof";
579
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
580
+ return !!right[Symbol.hasInstance](left);
581
+ } else {
582
+ return left instanceof right;
583
+ }
584
+ }
585
+ function _ts_decorate$3(decorators, target, key, desc) {
586
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
587
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
588
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
589
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
590
+ }
591
+ function _ts_metadata$3(k, v) {
592
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
593
+ }
594
+ function _ts_param$1(paramIndex, decorator) {
595
+ return function(target, key) {
596
+ decorator(target, key, paramIndex);
597
+ };
598
+ }
599
+ exports.SelectionBridge = /*#__PURE__*/ function() {
600
+ function SelectionBridge(config, textbus, controller, selection, rootComponentRef, input, scheduler, domAdapter) {
601
+ var _this = this;
602
+ _class_call_check$4(this, SelectionBridge);
603
+ _define_property$4(this, "config", void 0);
604
+ _define_property$4(this, "selection", void 0);
605
+ _define_property$4(this, "rootComponentRef", void 0);
606
+ _define_property$4(this, "input", void 0);
607
+ _define_property$4(this, "scheduler", void 0);
608
+ _define_property$4(this, "domAdapter", void 0);
609
+ _define_property$4(this, "onSelectionChange", void 0);
610
+ _define_property$4(this, "nativeSelection", void 0);
611
+ _define_property$4(this, "syncSelectionFromNativeSelectionChange", void 0);
612
+ _define_property$4(this, "selectionChangeEvent", void 0);
613
+ _define_property$4(this, "subs", void 0);
614
+ _define_property$4(this, "sub", void 0);
615
+ _define_property$4(this, "connector", void 0);
616
+ _define_property$4(this, "ignoreSelectionChange", void 0);
617
+ _define_property$4(this, "changeFromUser", void 0);
618
+ _define_property$4(this, "docContainer", void 0);
619
+ _define_property$4(this, "cacheCaretPositionTimer", void 0);
620
+ _define_property$4(this, "oldCaretPosition", void 0);
621
+ this.config = config;
622
+ this.selection = selection;
623
+ this.rootComponentRef = rootComponentRef;
624
+ this.input = input;
625
+ this.scheduler = scheduler;
626
+ this.domAdapter = domAdapter;
627
+ this.nativeSelection = document.getSelection();
628
+ this.syncSelectionFromNativeSelectionChange = true;
629
+ this.selectionChangeEvent = new stream.Subject();
630
+ this.subs = [];
631
+ this.connector = null;
632
+ this.ignoreSelectionChange = false;
633
+ this.changeFromUser = false;
634
+ this.docContainer = textbus.get(VIEW_DOCUMENT);
635
+ this.onSelectionChange = this.selectionChangeEvent.asObservable().pipe(stream.filter(function() {
636
+ return !controller.readonly;
637
+ }));
638
+ this.sub = this.onSelectionChange.subscribe(function(r) {
639
+ if (r) {
640
+ input.focus(r, _this.changeFromUser);
641
+ } else {
642
+ input.blur();
643
+ }
644
+ });
645
+ this.sub.add(stream.fromEvent(document, 'focusin').subscribe(function(ev) {
646
+ var target = ev.target;
647
+ if (/^(input|textarea|select)$/i.test(target.nodeName)) {
648
+ if (target.tagName.toLowerCase() === 'input' && /^(range|date)$/.test(target.type)) {
649
+ return;
650
+ }
651
+ _this.ignoreSelectionChange = true;
652
+ return;
653
+ }
654
+ if (!config.useContentEditable) {
655
+ while(target){
656
+ if (target.contentEditable === 'true') {
657
+ _this.ignoreSelectionChange = true;
658
+ return;
659
+ }
660
+ target = target.parentNode;
661
+ }
662
+ }
663
+ }));
664
+ this.sub.add(stream.fromEvent(document, 'focusout').subscribe(function() {
665
+ _this.ignoreSelectionChange = false;
666
+ }));
667
+ }
668
+ _create_class$4(SelectionBridge, [
669
+ {
670
+ key: "connect",
671
+ value: function connect(connector) {
672
+ this.disConnect();
673
+ this.connector = connector;
674
+ this.syncSelection(connector);
675
+ this.listen(connector);
676
+ }
677
+ },
678
+ {
679
+ key: "disConnect",
680
+ value: function disConnect() {
681
+ this.connector = null;
682
+ this.unListen();
683
+ }
684
+ },
685
+ {
686
+ key: "getRect",
687
+ value: function getRect(location) {
688
+ var _this_getPositionByRange = this.getPositionByRange({
689
+ focusOffset: location.offset,
690
+ anchorOffset: location.offset,
691
+ focusSlot: location.slot,
692
+ anchorSlot: location.slot
693
+ }), focus = _this_getPositionByRange.focus, anchor = _this_getPositionByRange.anchor;
694
+ if (!focus || !anchor) {
695
+ return null;
696
+ }
697
+ var nativeRange = document.createRange();
698
+ nativeRange.setStart(focus.node, focus.offset);
699
+ nativeRange.collapse();
700
+ return getLayoutRectByRange(nativeRange);
701
+ }
702
+ },
703
+ {
704
+ key: "restore",
705
+ value: function restore(abstractSelection, fromLocal) {
706
+ var _this = this;
707
+ this.changeFromUser = fromLocal;
708
+ if (this.ignoreSelectionChange || !this.connector) {
709
+ return;
710
+ }
711
+ this.unListen();
712
+ if (!abstractSelection) {
713
+ this.nativeSelection.removeAllRanges();
714
+ this.selectionChangeEvent.next(null);
715
+ this.listen(this.connector);
716
+ return;
717
+ }
718
+ var _this_getPositionByRange = this.getPositionByRange(abstractSelection), focus = _this_getPositionByRange.focus, anchor = _this_getPositionByRange.anchor;
719
+ if (!focus || !anchor) {
720
+ this.nativeSelection.removeAllRanges();
721
+ this.selectionChangeEvent.next(null);
722
+ this.listen(this.connector);
723
+ return;
724
+ }
725
+ function tryOffset(position) {
726
+ if (!position.node) {
727
+ return;
728
+ }
729
+ if (position.node.nodeType === Node.TEXT_NODE) {
730
+ var len = position.node.textContent.length;
731
+ if (position.offset > len) {
732
+ position.offset = len;
733
+ }
734
+ } else if (position.node.nodeType === Node.ELEMENT_NODE) {
735
+ var len1 = position.node.childNodes.length;
736
+ if (position.offset > len1) {
737
+ position.offset = len1;
738
+ }
739
+ }
740
+ }
741
+ try {
742
+ tryOffset(focus);
743
+ tryOffset(anchor);
744
+ this.nativeSelection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
745
+ } catch (e) {
746
+ setTimeout(function() {
747
+ throw e;
748
+ });
749
+ }
750
+ if (this.nativeSelection.rangeCount) {
751
+ var nativeRange = this.nativeSelection.getRangeAt(0);
752
+ this.selectionChangeEvent.next(nativeRange);
753
+ } else {
754
+ this.selectionChangeEvent.next(null);
755
+ }
756
+ // hack start 浏览器会触发上面选区更改事件
757
+ var bind = function bind() {
758
+ if (_this.connector) {
759
+ _this.listen(_this.connector);
760
+ }
761
+ };
762
+ if (fromLocal) {
763
+ Promise.resolve().then(bind);
764
+ return;
765
+ }
766
+ if (typeof requestIdleCallback === 'function') {
767
+ requestIdleCallback(bind);
768
+ } else {
769
+ setTimeout(bind, 30);
770
+ }
771
+ // hack end
772
+ }
773
+ },
774
+ {
775
+ key: "destroy",
776
+ value: function destroy() {
777
+ this.subs.forEach(function(i) {
778
+ return i.unsubscribe();
779
+ });
780
+ this.sub.unsubscribe();
781
+ }
782
+ },
783
+ {
784
+ key: "getPositionByRange",
785
+ value: function getPositionByRange(abstractSelection) {
786
+ var focus;
787
+ var anchor;
788
+ try {
789
+ focus = this.findSelectedNodeAndOffset(abstractSelection.focusSlot, abstractSelection.focusOffset);
790
+ anchor = focus;
791
+ if (abstractSelection.anchorSlot !== abstractSelection.focusSlot || abstractSelection.anchorOffset !== abstractSelection.focusOffset) {
792
+ anchor = this.findSelectedNodeAndOffset(abstractSelection.anchorSlot, abstractSelection.anchorOffset);
793
+ }
794
+ return {
795
+ focus: focus,
796
+ anchor: anchor
797
+ };
798
+ } catch (e) {
799
+ return {
800
+ focus: null,
801
+ anchor: null
802
+ };
803
+ }
804
+ }
805
+ },
806
+ {
807
+ key: "getPreviousLinePositionByCurrent",
808
+ value: function getPreviousLinePositionByCurrent(position) {
809
+ return this.getLinePosition(position, false);
810
+ }
811
+ },
812
+ {
813
+ key: "getNextLinePositionByCurrent",
814
+ value: function getNextLinePositionByCurrent(position) {
815
+ return this.getLinePosition(position, true);
816
+ }
817
+ },
818
+ {
819
+ key: "getLinePosition",
820
+ value: function getLinePosition(currentPosition, toNext) {
821
+ var _this = this;
822
+ clearTimeout(this.cacheCaretPositionTimer);
823
+ var p;
824
+ if (this.oldCaretPosition) {
825
+ p = toNext ? this.getNextLinePositionByOffset(currentPosition, this.oldCaretPosition.left) : this.getPreviousLinePositionByOffset(currentPosition, this.oldCaretPosition.left);
826
+ } else {
827
+ this.oldCaretPosition = this.getRect(currentPosition);
828
+ p = toNext ? this.getNextLinePositionByOffset(currentPosition, this.oldCaretPosition.left) : this.getPreviousLinePositionByOffset(currentPosition, this.oldCaretPosition.left);
829
+ }
830
+ this.cacheCaretPositionTimer = setTimeout(function() {
831
+ _this.oldCaretPosition = null;
832
+ }, 3000);
833
+ return p;
834
+ }
835
+ },
836
+ {
837
+ key: "getPreviousLinePositionByOffset",
838
+ value: /**
839
+ * 获取选区向上移动一行的位置。
840
+ * @param currentPosition
841
+ * @param startLeft 参考位置。
842
+ */ function getPreviousLinePositionByOffset(currentPosition, startLeft) {
843
+ var isToPrevLine = false;
844
+ var loopCount = 0;
845
+ var minLeft = startLeft;
846
+ var focusSlot = currentPosition.slot;
847
+ var focusOffset = currentPosition.offset;
848
+ var minTop = this.getRect({
849
+ slot: focusSlot,
850
+ offset: focusOffset
851
+ }).top;
852
+ var position;
853
+ var oldPosition;
854
+ var oldLeft = 0;
855
+ while(true){
856
+ loopCount++;
857
+ position = this.selection.getPreviousPositionByPosition(focusSlot, focusOffset);
858
+ focusSlot = position.slot;
859
+ focusOffset = position.offset;
860
+ var rect2 = this.getRect(position);
861
+ if (!isToPrevLine) {
862
+ if (rect2.left > minLeft || rect2.top + rect2.height <= minTop) {
863
+ isToPrevLine = true;
864
+ } else if (rect2.left === minLeft && rect2.top === minTop) {
865
+ return position;
866
+ }
867
+ minLeft = rect2.left;
868
+ minTop = rect2.top;
869
+ // oldPosition = position
870
+ }
871
+ if (isToPrevLine) {
872
+ if (rect2.left <= startLeft) {
873
+ return position;
874
+ }
875
+ if (oldPosition) {
876
+ if (rect2.left >= oldLeft) {
877
+ return oldPosition;
878
+ }
879
+ }
880
+ oldLeft = rect2.left;
881
+ oldPosition = position;
882
+ }
883
+ if (loopCount > 10000) {
884
+ break;
885
+ }
886
+ }
887
+ return position || {
888
+ offset: 0,
889
+ slot: focusSlot
890
+ };
891
+ }
892
+ },
893
+ {
894
+ key: "getNextLinePositionByOffset",
895
+ value: /**
896
+ * 获取选区向下移动一行的位置。
897
+ * @param currentPosition
898
+ * @param startLeft 参考位置。
899
+ */ function getNextLinePositionByOffset(currentPosition, startLeft) {
900
+ var isToNextLine = false;
901
+ var loopCount = 0;
902
+ var maxRight = startLeft;
903
+ var focusSlot = currentPosition.slot;
904
+ var focusOffset = currentPosition.offset;
905
+ var rect = this.getRect({
906
+ slot: focusSlot,
907
+ offset: focusOffset
908
+ });
909
+ var minTop = rect.top;
910
+ var oldPosition;
911
+ var oldLeft = 0;
912
+ while(true){
913
+ loopCount++;
914
+ var position = this.selection.getNextPositionByPosition(focusSlot, focusOffset);
915
+ focusSlot = position.slot;
916
+ focusOffset = position.offset;
917
+ var rect2 = this.getRect(position);
918
+ if (!isToNextLine) {
919
+ if (rect2.left < maxRight || rect2.top >= minTop + rect.height) {
920
+ isToNextLine = true;
921
+ } else if (rect2.left === maxRight && rect2.top === minTop) {
922
+ return position;
923
+ }
924
+ maxRight = rect2.left;
925
+ minTop = rect2.top;
926
+ oldPosition = position;
927
+ }
928
+ if (isToNextLine) {
929
+ if (rect2.left > startLeft) {
930
+ return oldPosition;
931
+ }
932
+ if (oldPosition) {
933
+ if (rect2.left <= oldLeft) {
934
+ return oldPosition;
935
+ }
936
+ }
937
+ oldPosition = position;
938
+ oldLeft = rect2.left;
939
+ }
940
+ if (loopCount > 10000) {
941
+ break;
942
+ }
943
+ }
944
+ return oldPosition || {
945
+ offset: focusSlot.length,
946
+ slot: focusSlot
947
+ };
948
+ }
949
+ },
950
+ {
951
+ key: "unListen",
952
+ value: function unListen() {
953
+ this.subs.forEach(function(i) {
954
+ return i.unsubscribe();
955
+ });
956
+ this.subs = [];
957
+ }
958
+ },
959
+ {
960
+ key: "listen",
961
+ value: function listen(connector) {
962
+ var _this = this;
963
+ if (!this.config.useContentEditable) {
964
+ var selection = this.nativeSelection;
965
+ this.subs.push(stream.fromEvent(this.docContainer, 'mousedown').subscribe(function(ev) {
966
+ if (_this.ignoreSelectionChange || ev.button === 2) {
967
+ return;
968
+ }
969
+ if (!ev.shiftKey) {
970
+ selection.removeAllRanges();
971
+ }
972
+ }));
973
+ }
974
+ var isUpdating = false;
975
+ this.subs.push(this.scheduler.onDocChange.subscribe(function() {
976
+ isUpdating = true;
977
+ }), this.scheduler.onDocChanged.pipe(stream.delay()).subscribe(function() {
978
+ isUpdating = false;
979
+ }), stream.fromEvent(document, 'selectionchange').subscribe(function() {
980
+ if (isUpdating) {
981
+ return;
982
+ }
983
+ if (_this.syncSelectionFromNativeSelectionChange) {
984
+ _this.syncSelection(connector);
985
+ }
986
+ }));
987
+ }
988
+ },
989
+ {
990
+ key: "syncSelection",
991
+ value: function syncSelection(connector) {
992
+ var _nativeRange_commonAncestorContainer;
993
+ var selection = this.nativeSelection;
994
+ this.changeFromUser = true;
995
+ if (this.ignoreSelectionChange || this.input.composition || selection.rangeCount === 0 || !this.docContainer.contains(selection.anchorNode) || this.rootComponentRef.component.slots.length === 0) {
996
+ return;
997
+ }
998
+ var rawRange = selection.getRangeAt(0);
999
+ var nativeRange = rawRange.cloneRange();
1000
+ var isFocusEnd = selection.focusNode === nativeRange.endContainer && selection.focusOffset === nativeRange.endOffset;
1001
+ var isFocusStart = selection.focusNode === nativeRange.startContainer && selection.focusOffset === nativeRange.startOffset;
1002
+ if (!this.docContainer.contains(selection.focusNode)) {
1003
+ if (isFocusEnd) {
1004
+ var nativeNode = this.domAdapter.getNativeNodeBySlot(this.rootComponentRef.component.slots.at(0));
1005
+ if (!nativeNode) {
1006
+ return;
1007
+ }
1008
+ nativeRange.setEndAfter(nativeNode.lastChild);
1009
+ } else {
1010
+ var nativeNode1 = this.domAdapter.getNativeNodeBySlot(this.rootComponentRef.component.slots.at(-1));
1011
+ if (!nativeNode1) {
1012
+ return;
1013
+ }
1014
+ nativeRange.setStartBefore(nativeNode1.firstChild);
1015
+ }
1016
+ }
1017
+ var startPosition = this.getCorrectedPosition(nativeRange.startContainer, nativeRange.startOffset, isFocusStart);
1018
+ var endPosition = nativeRange.collapsed ? startPosition : this.getCorrectedPosition(nativeRange.endContainer, nativeRange.endOffset, isFocusEnd);
1019
+ if ([
1020
+ Node.ELEMENT_NODE,
1021
+ Node.TEXT_NODE
1022
+ ].includes((_nativeRange_commonAncestorContainer = nativeRange.commonAncestorContainer) === null || _nativeRange_commonAncestorContainer === void 0 ? void 0 : _nativeRange_commonAncestorContainer.nodeType) && startPosition && endPosition) {
1023
+ var abstractSelection = connector.beforeChange(isFocusEnd ? {
1024
+ anchorSlot: startPosition.slot,
1025
+ anchorOffset: startPosition.offset,
1026
+ focusSlot: endPosition.slot,
1027
+ focusOffset: endPosition.offset
1028
+ } : {
1029
+ focusSlot: startPosition.slot,
1030
+ focusOffset: startPosition.offset,
1031
+ anchorSlot: endPosition.slot,
1032
+ anchorOffset: endPosition.offset
1033
+ });
1034
+ if (!abstractSelection) {
1035
+ this.selectionChangeEvent.next(null);
1036
+ connector.setSelection(null);
1037
+ return;
1038
+ }
1039
+ var _this_getPositionByRange = this.getPositionByRange(abstractSelection), focus = _this_getPositionByRange.focus, anchor = _this_getPositionByRange.anchor;
1040
+ if (focus && anchor) {
1041
+ var start = anchor;
1042
+ var end = focus;
1043
+ if (isFocusStart) {
1044
+ start = focus;
1045
+ end = anchor;
1046
+ }
1047
+ if (nativeRange.startContainer !== start.node || nativeRange.startOffset !== start.offset) {
1048
+ nativeRange.setStart(start.node, start.offset);
1049
+ }
1050
+ if (nativeRange.endContainer !== end.node || nativeRange.endOffset !== end.offset) {
1051
+ nativeRange.setEnd(end.node, end.offset);
1052
+ }
1053
+ connector.setSelection(abstractSelection);
1054
+ if (selection.isCollapsed && (rawRange.startContainer !== start.node || rawRange.startOffset !== start.offset || rawRange.endContainer !== end.node || rawRange.endOffset !== end.offset)) {
1055
+ rawRange.setStart(start.node, start.offset);
1056
+ rawRange.setEnd(end.node, end.offset);
1057
+ }
1058
+ this.selectionChangeEvent.next(nativeRange);
1059
+ } else {
1060
+ connector.setSelection(null);
1061
+ }
1062
+ return;
1063
+ }
1064
+ connector.setSelection(null);
1065
+ }
1066
+ },
1067
+ {
1068
+ key: "findSelectedNodeAndOffset",
1069
+ value: function findSelectedNodeAndOffset(slot, offset) {
1070
+ var prev = slot.getContentAtIndex(offset - 1);
1071
+ var nodes = this.domAdapter.getNodesBySlot(slot);
1072
+ if (prev) {
1073
+ if (typeof prev !== 'string') {
1074
+ var nativeNode = this.domAdapter.getNativeNodeByComponent(prev);
1075
+ return {
1076
+ node: nativeNode.parentNode,
1077
+ offset: Array.from(nativeNode.parentNode.childNodes).indexOf(nativeNode) + 1
1078
+ };
1079
+ } else if (prev === '\n') {
1080
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1081
+ try {
1082
+ for(var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1083
+ var node = _step.value;
1084
+ if (_instanceof$3(node, Text)) {
1085
+ continue;
1086
+ }
1087
+ if (node.nodeName === 'BR') {
1088
+ var position = this.domAdapter.getLocationByNativeNode(node);
1089
+ if (position) {
1090
+ if (position.endIndex === offset) {
1091
+ var parentNode = node.parentNode;
1092
+ return {
1093
+ node: parentNode,
1094
+ offset: Array.from(parentNode.childNodes).indexOf(node) + 1
1095
+ };
1096
+ }
1097
+ }
1098
+ }
1099
+ }
1100
+ } catch (err) {
1101
+ _didIteratorError = true;
1102
+ _iteratorError = err;
1103
+ } finally{
1104
+ try {
1105
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1106
+ _iterator.return();
1107
+ }
1108
+ } finally{
1109
+ if (_didIteratorError) {
1110
+ throw _iteratorError;
1111
+ }
1112
+ }
1113
+ }
1114
+ }
1115
+ }
1116
+ var current = slot.getContentAtIndex(offset);
1117
+ if (current && typeof current !== 'string') {
1118
+ var nativeNode1 = this.domAdapter.getNativeNodeByComponent(current);
1119
+ return {
1120
+ node: nativeNode1.parentNode,
1121
+ offset: Array.from(nativeNode1.parentNode.childNodes).indexOf(nativeNode1)
1122
+ };
1123
+ }
1124
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1125
+ try {
1126
+ for(var _iterator1 = nodes[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1127
+ var node1 = _step1.value;
1128
+ if (_instanceof$3(node1, Element)) {
1129
+ if (node1.tagName === 'BR') {
1130
+ var position1 = this.domAdapter.getLocationByNativeNode(node1);
1131
+ if (position1) {
1132
+ if (position1.startIndex === offset) {
1133
+ var parentNode1 = node1.parentNode;
1134
+ return {
1135
+ node: parentNode1,
1136
+ offset: Array.from(parentNode1.childNodes).indexOf(node1)
1137
+ };
1138
+ }
1139
+ }
1140
+ }
1141
+ continue;
1142
+ }
1143
+ var position2 = this.domAdapter.getLocationByNativeNode(node1);
1144
+ if (position2) {
1145
+ if (offset >= position2.startIndex && offset <= position2.endIndex) {
1146
+ return {
1147
+ node: node1,
1148
+ offset: offset - position2.startIndex
1149
+ };
1150
+ }
1151
+ }
1152
+ }
1153
+ } catch (err) {
1154
+ _didIteratorError1 = true;
1155
+ _iteratorError1 = err;
1156
+ } finally{
1157
+ try {
1158
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1159
+ _iterator1.return();
1160
+ }
1161
+ } finally{
1162
+ if (_didIteratorError1) {
1163
+ throw _iteratorError1;
1164
+ }
1165
+ }
1166
+ }
1167
+ return null;
1168
+ }
1169
+ },
1170
+ {
1171
+ key: "getCorrectedPosition",
1172
+ value: function getCorrectedPosition(node, offset, toAfter) {
1173
+ var excludeNodes = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : [];
1174
+ excludeNodes.push(node);
1175
+ if (node.nodeType === Node.ELEMENT_NODE) {
1176
+ var containerPosition = this.domAdapter.getLocationByNativeNode(node);
1177
+ var childNode = node.childNodes[offset];
1178
+ if (childNode) {
1179
+ var childPosition = this.domAdapter.getLocationByNativeNode(childNode);
1180
+ if (childPosition) {
1181
+ if (containerPosition) {
1182
+ return {
1183
+ slot: childPosition.slot,
1184
+ offset: childPosition.startIndex
1185
+ };
1186
+ }
1187
+ return this.findFocusNode(childNode, toAfter, excludeNodes);
1188
+ }
1189
+ return this.findFocusNode(childNode, toAfter, excludeNodes);
1190
+ }
1191
+ var prevNode = node.childNodes[offset - 1];
1192
+ if (prevNode) {
1193
+ var prevPosition = this.domAdapter.getLocationByNativeNode(prevNode);
1194
+ if (prevPosition && containerPosition) {
1195
+ return {
1196
+ slot: prevPosition.slot,
1197
+ offset: prevPosition.endIndex
1198
+ };
1199
+ }
1200
+ }
1201
+ if (containerPosition) {
1202
+ return {
1203
+ slot: containerPosition.slot,
1204
+ offset: containerPosition.endIndex
1205
+ };
1206
+ }
1207
+ var nextNode = toAfter ? node.nextSibling : node.previousSibling;
1208
+ if (nextNode) {
1209
+ return this.findFocusNode(nextNode, toAfter, excludeNodes);
1210
+ }
1211
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
1212
+ } else if (node.nodeType === Node.TEXT_NODE) {
1213
+ var containerPosition1 = this.domAdapter.getLocationByNativeNode(node);
1214
+ if (containerPosition1) {
1215
+ return {
1216
+ slot: containerPosition1.slot,
1217
+ offset: containerPosition1.startIndex + offset
1218
+ };
1219
+ }
1220
+ var nextNode1 = toAfter ? node.nextSibling : node.previousSibling;
1221
+ if (nextNode1) {
1222
+ return this.findFocusNode(nextNode1, toAfter, excludeNodes);
1223
+ }
1224
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
1225
+ }
1226
+ return null;
1227
+ }
1228
+ },
1229
+ {
1230
+ key: "findFocusNode",
1231
+ value: function findFocusNode(node) {
1232
+ var toAfter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false, excludeNodes = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
1233
+ if (excludeNodes.includes(node)) {
1234
+ var next = toAfter ? node.nextSibling : node.previousSibling;
1235
+ if (next) {
1236
+ return this.findFocusNode(next, toAfter, excludeNodes);
1237
+ }
1238
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
1239
+ }
1240
+ excludeNodes.push(node);
1241
+ var position = this.domAdapter.getLocationByNativeNode(node);
1242
+ if (position) {
1243
+ return {
1244
+ slot: position.slot,
1245
+ offset: toAfter ? position.startIndex : position.endIndex
1246
+ };
1247
+ }
1248
+ var firstChild = toAfter ? node.firstChild : node.lastChild;
1249
+ if (firstChild) {
1250
+ return this.findFocusNode(firstChild, toAfter, excludeNodes);
1251
+ }
1252
+ var nextSibling = toAfter ? node.nextSibling : node.previousSibling;
1253
+ if (nextSibling) {
1254
+ return this.findFocusNode(nextSibling, toAfter, excludeNodes);
1255
+ }
1256
+ return this.findFocusNodeByParent(node, toAfter, excludeNodes);
1257
+ }
1258
+ },
1259
+ {
1260
+ key: "findFocusNodeByParent",
1261
+ value: function findFocusNodeByParent(node, toAfter, excludeNodes) {
1262
+ var parentNode = node.parentNode;
1263
+ if (parentNode) {
1264
+ var parentPosition = this.domAdapter.getLocationByNativeNode(parentNode);
1265
+ if (parentPosition) {
1266
+ return {
1267
+ slot: parentPosition.slot,
1268
+ offset: toAfter ? parentPosition.endIndex : parentPosition.startIndex
1269
+ };
1270
+ }
1271
+ excludeNodes.push(node);
1272
+ return this.findFocusNode(parentNode, toAfter, excludeNodes);
1273
+ }
1274
+ return null;
1275
+ }
1276
+ }
1277
+ ]);
1278
+ return SelectionBridge;
1279
+ }();
1280
+ exports.SelectionBridge = _ts_decorate$3([
1281
+ core.Injectable(),
1282
+ _ts_param$1(0, core.Inject(EDITOR_OPTIONS)),
1283
+ _ts_metadata$3("design:type", Function),
1284
+ _ts_metadata$3("design:paramtypes", [
1285
+ typeof ViewOptions === "undefined" ? Object : ViewOptions,
1286
+ typeof core$1.Textbus === "undefined" ? Object : core$1.Textbus,
1287
+ typeof core$1.Controller === "undefined" ? Object : core$1.Controller,
1288
+ typeof core$1.Selection === "undefined" ? Object : core$1.Selection,
1289
+ typeof core$1.RootComponentRef === "undefined" ? Object : core$1.RootComponentRef,
1290
+ typeof Input === "undefined" ? Object : Input,
1291
+ typeof core$1.Scheduler === "undefined" ? Object : core$1.Scheduler,
1292
+ typeof DomAdapter === "undefined" ? Object : DomAdapter
1293
+ ])
1294
+ ], exports.SelectionBridge);
1295
+
1296
+ function _assert_this_initialized$1(self) {
1297
+ if (self === void 0) {
1298
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1299
+ }
1300
+ return self;
1301
+ }
1302
+ function _call_super$1(_this, derived, args) {
1303
+ derived = _get_prototype_of$1(derived);
1304
+ return _possible_constructor_return$1(_this, _is_native_reflect_construct$1() ? Reflect.construct(derived, [], _get_prototype_of$1(_this).constructor) : derived.apply(_this, args));
1305
+ }
1306
+ function _class_call_check$3(instance, Constructor) {
1307
+ if (!(instance instanceof Constructor)) {
1308
+ throw new TypeError("Cannot call a class as a function");
1309
+ }
1310
+ }
1311
+ function _defineProperties$3(target, props) {
1312
+ for(var i = 0; i < props.length; i++){
1313
+ var descriptor = props[i];
1314
+ descriptor.enumerable = descriptor.enumerable || false;
1315
+ descriptor.configurable = true;
1316
+ if ("value" in descriptor) descriptor.writable = true;
1317
+ Object.defineProperty(target, descriptor.key, descriptor);
1318
+ }
1319
+ }
1320
+ function _create_class$3(Constructor, protoProps, staticProps) {
1321
+ if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
1322
+ return Constructor;
1323
+ }
1324
+ function _define_property$3(obj, key, value) {
1325
+ if (key in obj) {
1326
+ Object.defineProperty(obj, key, {
1327
+ value: value,
1328
+ enumerable: true,
1329
+ configurable: true,
1330
+ writable: true
1331
+ });
1332
+ } else {
1333
+ obj[key] = value;
1334
+ }
1335
+ return obj;
1336
+ }
1337
+ function _get_prototype_of$1(o) {
1338
+ _get_prototype_of$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
1339
+ return o.__proto__ || Object.getPrototypeOf(o);
1340
+ };
1341
+ return _get_prototype_of$1(o);
1342
+ }
1343
+ function _inherits$1(subClass, superClass) {
1344
+ if (typeof superClass !== "function" && superClass !== null) {
1345
+ throw new TypeError("Super expression must either be null or a function");
1346
+ }
1347
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
1348
+ constructor: {
1349
+ value: subClass,
1350
+ writable: true,
1351
+ configurable: true
1352
+ }
1353
+ });
1354
+ if (superClass) _set_prototype_of$1(subClass, superClass);
1355
+ }
1356
+ function _instanceof$2(left, right) {
1357
+ "@swc/helpers - instanceof";
1358
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1359
+ return !!right[Symbol.hasInstance](left);
1360
+ } else {
1361
+ return left instanceof right;
1362
+ }
1363
+ }
1364
+ function _possible_constructor_return$1(self, call) {
1365
+ if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
1366
+ return call;
1367
+ }
1368
+ return _assert_this_initialized$1(self);
1369
+ }
1370
+ function _set_prototype_of$1(o, p) {
1371
+ _set_prototype_of$1 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
1372
+ o.__proto__ = p;
1373
+ return o;
1374
+ };
1375
+ return _set_prototype_of$1(o, p);
1376
+ }
1377
+ function _type_of$1(obj) {
1378
+ "@swc/helpers - typeof";
1379
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1380
+ }
1381
+ function _is_native_reflect_construct$1() {
1382
+ try {
1383
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1384
+ } catch (_) {}
1385
+ return (_is_native_reflect_construct$1 = function() {
1386
+ return !!result;
1387
+ })();
1388
+ }
1389
+ function _ts_decorate$2(decorators, target, key, desc) {
1390
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1391
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1392
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1393
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1394
+ }
1395
+ function _ts_metadata$2(k, v) {
1396
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1397
+ }
1398
+ var iframeHTML = '\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">\n <meta http-equiv="X-UA-Compatible" content="ie=edge">\n <title>Textbus</title>\n <style>\n html {position: fixed; left:0; overflow: hidden}\n html, body{height: 100%;width:100%}\n body{margin:0; overflow: hidden}\n textarea{width: 2000px;height: 100%;opacity: 0; padding: 0; outline: none; border: none; position: absolute; left:0; top:0;}\n </style>\n</head>\n<body>\n</body>\n</html>\n';
1399
+ var ExperimentalCaret = /*#__PURE__*/ function() {
1400
+ function ExperimentalCaret(domRenderer, scheduler, editorMask) {
1401
+ var _this = this;
1402
+ _class_call_check$3(this, ExperimentalCaret);
1403
+ _define_property$3(this, "domRenderer", void 0);
1404
+ _define_property$3(this, "scheduler", void 0);
1405
+ _define_property$3(this, "editorMask", void 0);
1406
+ _define_property$3(this, "onPositionChange", void 0);
1407
+ _define_property$3(this, "onStyleChange", void 0);
1408
+ _define_property$3(this, "elementRef", void 0);
1409
+ _define_property$3(this, "changeFromSelf", void 0);
1410
+ _define_property$3(this, "getLimit", void 0);
1411
+ _define_property$3(this, "timer", void 0);
1412
+ _define_property$3(this, "caret", void 0);
1413
+ _define_property$3(this, "_display", void 0);
1414
+ _define_property$3(this, "flashing", void 0);
1415
+ _define_property$3(this, "subscription", void 0);
1416
+ _define_property$3(this, "positionChangeEvent", void 0);
1417
+ _define_property$3(this, "styleChangeEvent", void 0);
1418
+ _define_property$3(this, "oldRange", void 0);
1419
+ this.domRenderer = domRenderer;
1420
+ this.scheduler = scheduler;
1421
+ this.editorMask = editorMask;
1422
+ this.changeFromSelf = false;
1423
+ this.getLimit = function() {
1424
+ return {
1425
+ top: 0,
1426
+ bottom: document.documentElement.clientHeight
1427
+ };
1428
+ };
1429
+ this.timer = null;
1430
+ this._display = true;
1431
+ this.flashing = true;
1432
+ this.subscription = new stream.Subscription();
1433
+ this.positionChangeEvent = new stream.Subject();
1434
+ this.styleChangeEvent = new stream.Subject();
1435
+ this.oldRange = null;
1436
+ this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
1437
+ this.onStyleChange = this.styleChangeEvent.asObservable();
1438
+ this.elementRef = createElement('div', {
1439
+ styles: {
1440
+ position: 'absolute',
1441
+ width: '2px',
1442
+ pointerEvents: 'none'
1443
+ },
1444
+ children: [
1445
+ this.caret = createElement('span', {
1446
+ styles: {
1447
+ width: '100%',
1448
+ height: '100%',
1449
+ position: 'absolute',
1450
+ left: 0,
1451
+ top: 0
1452
+ }
1453
+ })
1454
+ ]
1455
+ });
1456
+ this.subscription.add(stream.fromEvent(document, 'mousedown').subscribe(function() {
1457
+ _this.flashing = false;
1458
+ }), stream.fromEvent(document, 'mouseup').subscribe(function() {
1459
+ _this.flashing = true;
1460
+ }));
1461
+ this.editorMask.appendChild(this.elementRef);
1462
+ }
1463
+ _create_class$3(ExperimentalCaret, [
1464
+ {
1465
+ key: "rect",
1466
+ get: function get() {
1467
+ return this.caret.getBoundingClientRect();
1468
+ }
1469
+ },
1470
+ {
1471
+ key: "display",
1472
+ get: function get() {
1473
+ return this._display;
1474
+ },
1475
+ set: function set(v) {
1476
+ this._display = v;
1477
+ this.caret.style.visibility = v ? 'visible' : 'hidden';
1478
+ }
1479
+ },
1480
+ {
1481
+ key: "refresh",
1482
+ value: function refresh() {
1483
+ if (this.oldRange) {
1484
+ this.show(this.oldRange, false);
1485
+ }
1486
+ }
1487
+ },
1488
+ {
1489
+ key: "show",
1490
+ value: function show(range, restart) {
1491
+ var _this = this;
1492
+ this.oldRange = range;
1493
+ if (restart || this.scheduler.lastChangesHasLocalUpdate) {
1494
+ clearTimeout(this.timer);
1495
+ }
1496
+ this.updateCursorPosition(range);
1497
+ if (range.collapsed) {
1498
+ if (restart || this.scheduler.lastChangesHasLocalUpdate) {
1499
+ this.display = true;
1500
+ var toggleShowHide = function toggleShowHide1() {
1501
+ _this.display = !_this.display || !_this.flashing;
1502
+ _this.timer = setTimeout(toggleShowHide, 400);
1503
+ };
1504
+ clearTimeout(this.timer);
1505
+ this.timer = setTimeout(toggleShowHide, 400);
1506
+ }
1507
+ } else {
1508
+ this.display = false;
1509
+ clearTimeout(this.timer);
1510
+ }
1511
+ }
1512
+ },
1513
+ {
1514
+ key: "hide",
1515
+ value: function hide() {
1516
+ this.display = false;
1517
+ clearTimeout(this.timer);
1518
+ this.positionChangeEvent.next(null);
1519
+ }
1520
+ },
1521
+ {
1522
+ key: "destroy",
1523
+ value: function destroy() {
1524
+ clearTimeout(this.timer);
1525
+ // this.caret.
1526
+ this.subscription.unsubscribe();
1527
+ }
1528
+ },
1529
+ {
1530
+ key: "updateCursorPosition",
1531
+ value: function updateCursorPosition(nativeRange) {
1532
+ var startContainer = nativeRange.startContainer;
1533
+ var node = startContainer.nodeType === Node.ELEMENT_NODE ? startContainer : startContainer.parentNode;
1534
+ if ((node === null || node === void 0 ? void 0 : node.nodeType) !== Node.ELEMENT_NODE) {
1535
+ this.positionChangeEvent.next(null);
1536
+ return;
1537
+ }
1538
+ var compositionNode = this.domRenderer.compositionNode;
1539
+ if (compositionNode) {
1540
+ nativeRange = nativeRange.cloneRange();
1541
+ nativeRange.selectNodeContents(compositionNode);
1542
+ nativeRange.collapse();
1543
+ }
1544
+ var rect = getLayoutRectByRange(nativeRange);
1545
+ var _getComputedStyle = getComputedStyle(node), fontSize = _getComputedStyle.fontSize, lineHeight = _getComputedStyle.lineHeight, color = _getComputedStyle.color, writingMode = _getComputedStyle.writingMode;
1546
+ var height;
1547
+ if (isNaN(+lineHeight)) {
1548
+ var f = parseFloat(lineHeight);
1549
+ if (isNaN(f)) {
1550
+ height = parseFloat(fontSize);
1551
+ } else {
1552
+ height = f;
1553
+ }
1554
+ } else {
1555
+ height = parseFloat(fontSize) * parseFloat(lineHeight);
1556
+ }
1557
+ var boxHeight = Math.max(Math.floor(Math.max(height, rect.height)), 12);
1558
+ // const boxHeight = Math.floor(height)
1559
+ var rectTop = rect.top;
1560
+ if (rect.height < height) {
1561
+ rectTop -= (height - rect.height) / 2;
1562
+ }
1563
+ rectTop = Math.floor(rectTop);
1564
+ var containerRect = this.editorMask.getBoundingClientRect();
1565
+ var top = Math.floor(rectTop - containerRect.top);
1566
+ var left = Math.floor(rect.left + rect.width / 2 - containerRect.left);
1567
+ var rotate = 0;
1568
+ if (nativeRange.collapsed) {
1569
+ rotate = Math.round(Math.atan2(rect.width, rect.height) * 180 / Math.PI);
1570
+ if (rotate !== 0) {
1571
+ var hackEle = document.createElement('span');
1572
+ // eslint-disable-next-line max-len
1573
+ hackEle.style.cssText = 'display: inline-block; width: 10px; height: 10px; position: relative; contain: layout style size; writing-mode: inherit';
1574
+ var pointEle = document.createElement('span');
1575
+ pointEle.style.cssText = 'position: absolute; left: 0; top: 0; width:0;height:0';
1576
+ hackEle.append(pointEle);
1577
+ node.append(hackEle);
1578
+ var p1 = pointEle.getBoundingClientRect();
1579
+ pointEle.style.right = '0';
1580
+ pointEle.style.left = '';
1581
+ var p2 = pointEle.getBoundingClientRect();
1582
+ var x = p1.x - p2.x;
1583
+ var y = p1.y - p2.y;
1584
+ rotate = Math.atan2(y, x) * 180 / Math.PI;
1585
+ hackEle.remove();
1586
+ }
1587
+ }
1588
+ if (writingMode === 'vertical-lr' || writingMode === 'vertical-rl') {
1589
+ rotate += 90;
1590
+ }
1591
+ Object.assign(this.elementRef.style, {
1592
+ left: left + 'px',
1593
+ top: top + 'px',
1594
+ height: boxHeight + 'px',
1595
+ lineHeight: boxHeight + 'px',
1596
+ fontSize: fontSize,
1597
+ transform: "rotate(".concat(rotate, "deg)")
1598
+ });
1599
+ this.caret.style.backgroundColor = color === 'rgba(0, 0, 0, 0)' ? '#000' : color;
1600
+ this.styleChangeEvent.next({
1601
+ height: boxHeight + 'px',
1602
+ lineHeight: boxHeight + 'px',
1603
+ fontSize: fontSize
1604
+ });
1605
+ this.positionChangeEvent.next({
1606
+ left: left,
1607
+ top: rectTop,
1608
+ height: boxHeight
1609
+ });
1610
+ if (this.changeFromSelf) {
1611
+ this.changeFromSelf = false;
1612
+ var selfRect = this.elementRef.getBoundingClientRect();
1613
+ var scrollContainer = this.getScrollContainer(startContainer);
1614
+ var scrollRect = scrollContainer === document.documentElement ? {
1615
+ top: 0,
1616
+ bottom: document.documentElement.clientHeight
1617
+ } : scrollContainer.getBoundingClientRect();
1618
+ var limit = this.getLimit();
1619
+ var top1 = Math.max(limit.top, scrollRect.top);
1620
+ var bottom = Math.min(limit.bottom, scrollRect.bottom);
1621
+ if (selfRect.top < top1) {
1622
+ scrollContainer.scrollTop -= top1 - selfRect.top;
1623
+ } else if (selfRect.bottom > bottom) {
1624
+ scrollContainer.scrollTop += selfRect.bottom - bottom;
1625
+ }
1626
+ }
1627
+ }
1628
+ },
1629
+ {
1630
+ key: "getScrollContainer",
1631
+ value: function getScrollContainer(container) {
1632
+ while(container){
1633
+ if (_instanceof$2(container, Element)) {
1634
+ var styles = getComputedStyle(container);
1635
+ if (styles.overflow !== 'visible' || styles.overflowX !== 'visible' || styles.overflowY !== 'visible') {
1636
+ return container;
1637
+ }
1638
+ }
1639
+ container = container.parentNode;
1640
+ }
1641
+ return document.documentElement;
1642
+ }
1643
+ }
1644
+ ]);
1645
+ return ExperimentalCaret;
1646
+ }();
1647
+ exports.MagicInput = /*#__PURE__*/ function(Input) {
1648
+ _inherits$1(MagicInput, Input);
1649
+ function MagicInput(domAdapter, parser, keyboard, commander, selection, controller, scheduler, textbus) {
1650
+ _class_call_check$3(this, MagicInput);
1651
+ var _this;
1652
+ _this = _call_super$1(this, MagicInput), _define_property$3(_this, "domAdapter", void 0), _define_property$3(_this, "parser", void 0), _define_property$3(_this, "keyboard", void 0), _define_property$3(_this, "commander", void 0), _define_property$3(_this, "selection", void 0), _define_property$3(_this, "controller", void 0), _define_property$3(_this, "scheduler", void 0), _define_property$3(_this, "textbus", void 0), _define_property$3(_this, "composition", void 0), _define_property$3(_this, "onReady", void 0), _define_property$3(_this, "caret", void 0), _define_property$3(_this, "isSafari", void 0), _define_property$3(_this, "isFirefox", void 0), _define_property$3(_this, "isMac", void 0), _define_property$3(_this, "isWindows", void 0), _define_property$3(_this, "_disabled", void 0), _define_property$3(_this, "container", void 0), _define_property$3(_this, "subscription", void 0), _define_property$3(_this, "doc", void 0), _define_property$3(_this, "textarea", void 0), _define_property$3(_this, "isFocus", void 0), _define_property$3(_this, "nativeFocus", void 0), _define_property$3(_this, "ignoreComposition", void 0 // 有 bug 版本搜狗拼音
1653
+ ), _this.domAdapter = domAdapter, _this.parser = parser, _this.keyboard = keyboard, _this.commander = commander, _this.selection = selection, _this.controller = controller, _this.scheduler = scheduler, _this.textbus = textbus, _this.composition = false, _this.isSafari = isSafari(), _this.isFirefox = isFirefox(), _this.isMac = isMac(), _this.isWindows = isWindows(), _this._disabled = false, _this.container = _this.createEditableFrame(), _this.subscription = new stream.Subscription(), _this.textarea = null, _this.isFocus = false, _this.nativeFocus = false, _this.ignoreComposition = false;
1654
+ _this.caret = new ExperimentalCaret(_this.domAdapter, _this.scheduler, _this.textbus.get(VIEW_MASK));
1655
+ _this.onReady = new Promise(function(resolve) {
1656
+ _this.subscription.add(stream.fromEvent(_this.container, 'load').subscribe(function() {
1657
+ var doc = _this.container.contentDocument;
1658
+ doc.open();
1659
+ doc.write(iframeHTML);
1660
+ doc.close();
1661
+ _this.doc = doc;
1662
+ _this.init();
1663
+ resolve();
1664
+ }), controller.onReadonlyStateChange.subscribe(function() {
1665
+ if (controller.readonly) {
1666
+ _this.blur();
1667
+ }
1668
+ }));
1669
+ });
1670
+ _this.caret.elementRef.append(_this.container);
1671
+ return _this;
1672
+ }
1673
+ _create_class$3(MagicInput, [
1674
+ {
1675
+ key: "disabled",
1676
+ get: function get() {
1677
+ return this._disabled;
1678
+ },
1679
+ set: function set(b) {
1680
+ this._disabled = b;
1681
+ if (b && this.textarea) {
1682
+ this.textarea.disabled = b;
1683
+ }
1684
+ }
1685
+ },
1686
+ {
1687
+ key: "focus",
1688
+ value: function focus(range, restart) {
1689
+ var _this = this;
1690
+ if (!this.disabled) {
1691
+ this.caret.show(range, restart);
1692
+ }
1693
+ if (this.controller.readonly) {
1694
+ return;
1695
+ }
1696
+ if (!this.isFocus) {
1697
+ var _this_textarea;
1698
+ (_this_textarea = this.textarea) === null || _this_textarea === void 0 ? void 0 : _this_textarea.focus();
1699
+ setTimeout(function() {
1700
+ if (!_this.nativeFocus && _this.isFocus) {
1701
+ _this.reInit();
1702
+ }
1703
+ });
1704
+ }
1705
+ this.isFocus = true;
1706
+ }
1707
+ },
1708
+ {
1709
+ key: "blur",
1710
+ value: function blur() {
1711
+ var _this_textarea;
1712
+ this.caret.hide();
1713
+ (_this_textarea = this.textarea) === null || _this_textarea === void 0 ? void 0 : _this_textarea.blur();
1714
+ this.isFocus = false;
1715
+ }
1716
+ },
1717
+ {
1718
+ key: "destroy",
1719
+ value: function destroy() {
1720
+ this.caret.destroy();
1721
+ this.subscription.unsubscribe();
1722
+ }
1723
+ },
1724
+ {
1725
+ key: "reInit",
1726
+ value: function reInit() {
1727
+ var _this = this;
1728
+ var delay = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
1729
+ var _this_textarea_parentNode, _this_textarea;
1730
+ this.subscription.unsubscribe();
1731
+ (_this_textarea = this.textarea) === null || _this_textarea === void 0 ? void 0 : (_this_textarea_parentNode = _this_textarea.parentNode) === null || _this_textarea_parentNode === void 0 ? void 0 : _this_textarea_parentNode.removeChild(this.textarea);
1732
+ this.subscription = new stream.Subscription();
1733
+ this.init();
1734
+ if (delay) {
1735
+ setTimeout(function() {
1736
+ var _this_textarea;
1737
+ (_this_textarea = _this.textarea) === null || _this_textarea === void 0 ? void 0 : _this_textarea.focus();
1738
+ });
1739
+ } else {
1740
+ var _this_textarea1;
1741
+ (_this_textarea1 = this.textarea) === null || _this_textarea1 === void 0 ? void 0 : _this_textarea1.focus();
1742
+ }
1743
+ }
1744
+ },
1745
+ {
1746
+ key: "init",
1747
+ value: function init() {
1748
+ var _this = this;
1749
+ var doc = this.doc;
1750
+ var contentBody = doc.body;
1751
+ var textarea = doc.createElement('textarea');
1752
+ textarea.disabled = this.disabled;
1753
+ contentBody.appendChild(textarea);
1754
+ this.textarea = textarea;
1755
+ this.subscription.add(stream.fromEvent(textarea, 'blur').subscribe(function() {
1756
+ // if (this.isFocus) {
1757
+ // this.isFocus = false
1758
+ // this.reInit(true)
1759
+ // }
1760
+ _this.isFocus = false;
1761
+ _this.nativeFocus = false;
1762
+ _this.caret.hide();
1763
+ if (_this.domAdapter.composition) {
1764
+ var slot = _this.domAdapter.composition.slot;
1765
+ _this.domAdapter.composition = null;
1766
+ _this.domAdapter.compositionNode = null;
1767
+ slot.__changeMarker__.forceMarkDirtied();
1768
+ }
1769
+ }), stream.fromEvent(textarea, 'focus').subscribe(function() {
1770
+ _this.nativeFocus = true;
1771
+ }), this.caret.onStyleChange.subscribe(function(style) {
1772
+ Object.assign(textarea.style, style);
1773
+ }));
1774
+ this.handleInput(textarea);
1775
+ this.handleShortcut(textarea);
1776
+ this.handleDefaultActions(textarea);
1777
+ }
1778
+ },
1779
+ {
1780
+ key: "handleDefaultActions",
1781
+ value: function handleDefaultActions(textarea) {
1782
+ var _this = this;
1783
+ this.subscription.add(stream.fromEvent(isFirefox() ? textarea : document, 'copy').subscribe(function(ev) {
1784
+ _this.copyHandler(ev);
1785
+ }), stream.fromEvent(textarea, 'paste').subscribe(function(ev) {
1786
+ _this.pasteHandler(ev);
1787
+ }));
1788
+ }
1789
+ },
1790
+ {
1791
+ key: "copyHandler",
1792
+ value: function copyHandler(ev) {
1793
+ var selection = this.selection;
1794
+ if (!selection.isSelected) {
1795
+ return;
1796
+ }
1797
+ if (selection.startSlot === selection.endSlot && selection.endOffset - selection.startOffset === 1) {
1798
+ var content = selection.startSlot.getContentAtIndex(selection.startOffset);
1799
+ if ((typeof content === "undefined" ? "undefined" : _type_of$1(content)) === 'object') {
1800
+ var clipboardData = ev.clipboardData;
1801
+ var nativeSelection = document.getSelection();
1802
+ var range = nativeSelection.getRangeAt(0);
1803
+ var div = document.createElement('div');
1804
+ var fragment = range.cloneContents();
1805
+ div.append(fragment);
1806
+ clipboardData.setData('text/html', div.innerHTML);
1807
+ clipboardData.setData('text', div.innerText);
1808
+ ev.preventDefault();
1809
+ }
1810
+ }
1811
+ }
1812
+ },
1813
+ {
1814
+ key: "pasteHandler",
1815
+ value: function pasteHandler(ev) {
1816
+ var _this = this;
1817
+ var text = ev.clipboardData.getData('Text');
1818
+ var types = Array.from(ev.clipboardData.types || []);
1819
+ var files = Array.from(ev.clipboardData.files);
1820
+ if (types.every(function(type) {
1821
+ return type === 'Files';
1822
+ }) && files.length) {
1823
+ Promise.all(files.filter(function(i) {
1824
+ return /image/i.test(i.type);
1825
+ }).map(function(item) {
1826
+ var reader = new FileReader();
1827
+ return new Promise(function(resolve) {
1828
+ reader.onload = function(event) {
1829
+ resolve(event.target.result);
1830
+ };
1831
+ reader.readAsDataURL(item);
1832
+ });
1833
+ })).then(function(urls) {
1834
+ var html = urls.map(function(i) {
1835
+ return "<img src=".concat(i, ">");
1836
+ }).join('');
1837
+ _this.paste(html, text);
1838
+ });
1839
+ ev.preventDefault();
1840
+ return;
1841
+ }
1842
+ var div = this.doc.createElement('div');
1843
+ div.style.cssText = 'width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0';
1844
+ div.contentEditable = 'true';
1845
+ this.doc.body.appendChild(div);
1846
+ div.focus();
1847
+ setTimeout(function() {
1848
+ _this.doc.body.removeChild(div);
1849
+ div.style.cssText = '';
1850
+ _this.paste(div, text);
1851
+ });
1852
+ }
1853
+ },
1854
+ {
1855
+ key: "paste",
1856
+ value: function paste(dom, text) {
1857
+ var slot = this.parser.parse(dom, new core$1.Slot([
1858
+ core$1.ContentType.BlockComponent,
1859
+ core$1.ContentType.InlineComponent,
1860
+ core$1.ContentType.Text
1861
+ ]));
1862
+ this.commander.paste(slot, text);
1863
+ }
1864
+ },
1865
+ {
1866
+ key: "handleShortcut",
1867
+ value: function handleShortcut(textarea) {
1868
+ var _this = this;
1869
+ var isWriting = false;
1870
+ var isIgnore = false;
1871
+ this.subscription.add(stream.fromEvent(textarea, 'compositionstart').subscribe(function() {
1872
+ isWriting = true;
1873
+ }), stream.fromEvent(textarea, 'compositionend').subscribe(function() {
1874
+ isWriting = false;
1875
+ }), stream.fromEvent(textarea, 'beforeinput').subscribe(function(ev) {
1876
+ _this.ignoreComposition = false;
1877
+ if (_this.isSafari) {
1878
+ if (ev.inputType === 'insertFromComposition') {
1879
+ isIgnore = true;
1880
+ }
1881
+ }
1882
+ }), stream.fromEvent(textarea, 'keydown').pipe(stream.filter(function() {
1883
+ if (_this.isSafari && isIgnore) {
1884
+ isIgnore = false;
1885
+ return false;
1886
+ }
1887
+ return !isWriting // || !this.textarea.value
1888
+ ;
1889
+ })).subscribe(function(ev) {
1890
+ _this.ignoreComposition = false;
1891
+ var key = ev.key;
1892
+ var keys = ')!@#$%^Z&*(';
1893
+ var b = key === 'Process' && /Digit\d/.test(ev.code) && ev.shiftKey;
1894
+ if (b) {
1895
+ // 大小写锁定为大写 + 全角 + shift + 数字键,还存在问题
1896
+ key = keys.charAt(+ev.code.substring(5));
1897
+ ev.preventDefault();
1898
+ }
1899
+ _this.caret.changeFromSelf = true;
1900
+ var is = _this.keyboard.execShortcut({
1901
+ key: key,
1902
+ altKey: ev.altKey,
1903
+ shiftKey: ev.shiftKey,
1904
+ modKey: _this.isMac ? ev.metaKey : ev.ctrlKey,
1905
+ agent: {
1906
+ key: ev.key,
1907
+ code: ev.code,
1908
+ keyCode: ev.keyCode
1909
+ }
1910
+ });
1911
+ if (is) {
1912
+ _this.ignoreComposition = true;
1913
+ ev.preventDefault();
1914
+ } else {
1915
+ _this.caret.changeFromSelf = false;
1916
+ }
1917
+ }));
1918
+ }
1919
+ },
1920
+ {
1921
+ key: "handleInput",
1922
+ value: function handleInput(textarea) {
1923
+ var _this = this;
1924
+ var startIndex = 0;
1925
+ this.subscription.add(stream.fromEvent(textarea, 'compositionstart').pipe(stream.filter(function() {
1926
+ return !_this.ignoreComposition;
1927
+ })).subscribe(function() {
1928
+ if (!_this.selection.isCollapsed) {
1929
+ _this.caret.changeFromSelf = true;
1930
+ _this.commander.delete();
1931
+ }
1932
+ _this.composition = true;
1933
+ startIndex = _this.selection.startOffset;
1934
+ var startSlot = _this.selection.startSlot;
1935
+ var event = new core$1.Event(startSlot, {
1936
+ index: startIndex
1937
+ });
1938
+ core$1.invokeListener(startSlot.parent, 'onCompositionStart', event);
1939
+ }), stream.fromEvent(textarea, 'compositionupdate').pipe(stream.filter(function() {
1940
+ return !_this.ignoreComposition;
1941
+ })).pipe(stream.distinctUntilChanged(function(prev, next) {
1942
+ return prev.data !== next.data;
1943
+ })).subscribe(function(ev) {
1944
+ if (ev.data === ' ') {
1945
+ // 处理搜狗五笔不符合 composition 事件预期,会意外跳光标的问题
1946
+ return;
1947
+ }
1948
+ var startSlot = _this.selection.startSlot;
1949
+ _this.domAdapter.composition = {
1950
+ slot: startSlot,
1951
+ text: ev.data,
1952
+ offset: ev.data.length,
1953
+ index: startIndex
1954
+ };
1955
+ _this.caret.changeFromSelf = true;
1956
+ _this.caret.refresh();
1957
+ var event = new core$1.Event(startSlot, {
1958
+ index: startIndex,
1959
+ data: ev.data
1960
+ });
1961
+ core$1.invokeListener(startSlot.parent, 'onCompositionUpdate', event);
1962
+ startSlot.__changeMarker__.forceMarkDirtied();
1963
+ }));
1964
+ var isCompositionEnd = false;
1965
+ this.subscription.add(stream.merge(stream.fromEvent(textarea, 'beforeinput').pipe(stream.filter(function(ev) {
1966
+ ev.preventDefault();
1967
+ if (_this.isFirefox && ev.inputType === 'insertFromPaste') {
1968
+ return false;
1969
+ }
1970
+ if (_this.isSafari) {
1971
+ isCompositionEnd = ev.inputType === 'insertFromComposition';
1972
+ return ev.inputType === 'insertText' || ev.inputType === 'insertFromComposition';
1973
+ }
1974
+ return !ev.isComposing && !!ev.data;
1975
+ }), stream.map(function(ev) {
1976
+ return ev.data;
1977
+ })), this.isSafari ? new stream.Observable() : stream.fromEvent(textarea, 'compositionend').pipe(stream.filter(function() {
1978
+ return !_this.ignoreComposition;
1979
+ })).pipe(stream.map(function(ev) {
1980
+ isCompositionEnd = true;
1981
+ ev.preventDefault();
1982
+ textarea.value = '';
1983
+ return ev.data;
1984
+ }))).subscribe(function(text) {
1985
+ _this.composition = false;
1986
+ _this.domAdapter.composition = null;
1987
+ if (text) {
1988
+ _this.caret.changeFromSelf = true;
1989
+ _this.commander.write(text);
1990
+ } else {
1991
+ var _this_selection_startSlot;
1992
+ (_this_selection_startSlot = _this.selection.startSlot) === null || _this_selection_startSlot === void 0 ? void 0 : _this_selection_startSlot.__changeMarker__.forceMarkDirtied();
1993
+ }
1994
+ if (isCompositionEnd) {
1995
+ var startSlot = _this.selection.startSlot;
1996
+ if (startSlot) {
1997
+ var event = new core$1.Event(startSlot, null);
1998
+ core$1.invokeListener(startSlot.parent, 'onCompositionEnd', event);
1999
+ }
2000
+ }
2001
+ isCompositionEnd = false;
2002
+ }));
2003
+ }
2004
+ },
2005
+ {
2006
+ key: "createEditableFrame",
2007
+ value: function createEditableFrame() {
2008
+ return createElement('iframe', {
2009
+ attrs: {
2010
+ scrolling: 'no'
2011
+ },
2012
+ styles: {
2013
+ border: 'none',
2014
+ width: '100%',
2015
+ display: 'block',
2016
+ height: '100%',
2017
+ position: 'relative',
2018
+ top: this.isWindows ? '3px' : '0'
2019
+ }
2020
+ });
2021
+ }
2022
+ }
2023
+ ]);
2024
+ return MagicInput;
2025
+ }(Input);
2026
+ exports.MagicInput = _ts_decorate$2([
2027
+ core.Injectable(),
2028
+ _ts_metadata$2("design:type", Function),
2029
+ _ts_metadata$2("design:paramtypes", [
2030
+ typeof DomAdapter === "undefined" ? Object : DomAdapter,
2031
+ typeof exports.Parser === "undefined" ? Object : exports.Parser,
2032
+ typeof core$1.Keyboard === "undefined" ? Object : core$1.Keyboard,
2033
+ typeof core$1.Commander === "undefined" ? Object : core$1.Commander,
2034
+ typeof core$1.Selection === "undefined" ? Object : core$1.Selection,
2035
+ typeof core$1.Controller === "undefined" ? Object : core$1.Controller,
2036
+ typeof core$1.Scheduler === "undefined" ? Object : core$1.Scheduler,
2037
+ typeof core$1.Textbus === "undefined" ? Object : core$1.Textbus
2038
+ ])
2039
+ ], exports.MagicInput);
2040
+
2041
+ function _array_like_to_array(arr, len) {
2042
+ if (len == null || len > arr.length) len = arr.length;
2043
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
2044
+ return arr2;
2045
+ }
2046
+ function _array_without_holes(arr) {
2047
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
2048
+ }
2049
+ function _class_call_check$2(instance, Constructor) {
2050
+ if (!(instance instanceof Constructor)) {
2051
+ throw new TypeError("Cannot call a class as a function");
2052
+ }
2053
+ }
2054
+ function _defineProperties$2(target, props) {
2055
+ for(var i = 0; i < props.length; i++){
2056
+ var descriptor = props[i];
2057
+ descriptor.enumerable = descriptor.enumerable || false;
2058
+ descriptor.configurable = true;
2059
+ if ("value" in descriptor) descriptor.writable = true;
2060
+ Object.defineProperty(target, descriptor.key, descriptor);
2061
+ }
2062
+ }
2063
+ function _create_class$2(Constructor, protoProps, staticProps) {
2064
+ if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);
2065
+ return Constructor;
2066
+ }
2067
+ function _define_property$2(obj, key, value) {
2068
+ if (key in obj) {
2069
+ Object.defineProperty(obj, key, {
2070
+ value: value,
2071
+ enumerable: true,
2072
+ configurable: true,
2073
+ writable: true
2074
+ });
2075
+ } else {
2076
+ obj[key] = value;
2077
+ }
2078
+ return obj;
2079
+ }
2080
+ function _iterable_to_array(iter) {
2081
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2082
+ }
2083
+ function _non_iterable_spread() {
2084
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2085
+ }
2086
+ function _to_consumable_array(arr) {
2087
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
2088
+ }
2089
+ function _unsupported_iterable_to_array(o, minLen) {
2090
+ if (!o) return;
2091
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
2092
+ var n = Object.prototype.toString.call(o).slice(8, -1);
2093
+ if (n === "Object" && o.constructor) n = o.constructor.name;
2094
+ if (n === "Map" || n === "Set") return Array.from(n);
2095
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
2096
+ }
2097
+ function _ts_decorate$1(decorators, target, key, desc) {
2098
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2099
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2100
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2101
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2102
+ }
2103
+ function _ts_metadata$1(k, v) {
2104
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2105
+ }
2106
+ function _ts_param(paramIndex, decorator) {
2107
+ return function(target, key) {
2108
+ decorator(target, key, paramIndex);
2109
+ };
2110
+ }
2111
+ /**
2112
+ * 远程光标绘制范围计算代理类,可用于定制特定场景下的远程选区绘制,如表格有选区,不会遵守常见的文档流形式
2113
+ */ var CollaborateSelectionAwarenessDelegate = function CollaborateSelectionAwarenessDelegate() {
2114
+ _class_call_check$2(this, CollaborateSelectionAwarenessDelegate);
2115
+ };
2116
+ exports.CollaborateCursor = /*#__PURE__*/ function() {
2117
+ function CollaborateCursor(textbus, nativeSelection, scheduler, selection, awarenessDelegate) {
2118
+ var _this = this;
2119
+ _class_call_check$2(this, CollaborateCursor);
2120
+ _define_property$2(this, "nativeSelection", void 0);
2121
+ _define_property$2(this, "scheduler", void 0);
2122
+ _define_property$2(this, "selection", void 0);
2123
+ _define_property$2(this, "awarenessDelegate", void 0);
2124
+ _define_property$2(this, "host", void 0);
2125
+ _define_property$2(this, "canvasContainer", void 0);
2126
+ _define_property$2(this, "canvas", void 0);
2127
+ _define_property$2(this, "context", void 0);
2128
+ _define_property$2(this, "tooltips", void 0);
2129
+ _define_property$2(this, "onRectsChange", void 0);
2130
+ _define_property$2(this, "subscription", void 0);
2131
+ _define_property$2(this, "selectionCursors", void 0);
2132
+ _define_property$2(this, "container", void 0);
2133
+ _define_property$2(this, "ratio", void 0);
2134
+ this.nativeSelection = nativeSelection;
2135
+ this.scheduler = scheduler;
2136
+ this.selection = selection;
2137
+ this.awarenessDelegate = awarenessDelegate;
2138
+ this.host = createElement('div', {
2139
+ styles: {
2140
+ position: 'absolute',
2141
+ left: 0,
2142
+ top: 0,
2143
+ width: '100%',
2144
+ height: '100%',
2145
+ pointerEvents: 'none',
2146
+ zIndex: 1
2147
+ }
2148
+ });
2149
+ this.canvasContainer = createElement('div', {
2150
+ styles: {
2151
+ position: 'absolute',
2152
+ left: 0,
2153
+ top: 0,
2154
+ width: '100%',
2155
+ height: '100%',
2156
+ overflow: 'hidden'
2157
+ }
2158
+ });
2159
+ this.canvas = createElement('canvas', {
2160
+ styles: {
2161
+ position: 'absolute',
2162
+ opacity: 0.5,
2163
+ left: 0,
2164
+ top: 0,
2165
+ width: '100%',
2166
+ height: document.documentElement.clientHeight + 'px',
2167
+ pointerEvents: 'none'
2168
+ }
2169
+ });
2170
+ this.context = this.canvas.getContext('2d');
2171
+ this.tooltips = createElement('div', {
2172
+ styles: {
2173
+ position: 'absolute',
2174
+ left: 0,
2175
+ top: 0,
2176
+ width: '100%',
2177
+ height: '100%',
2178
+ pointerEvents: 'none',
2179
+ fontSize: '12px',
2180
+ zIndex: 10
2181
+ }
2182
+ });
2183
+ this.onRectsChange = new stream.Subject();
2184
+ this.subscription = new stream.Subscription();
2185
+ this.selectionCursors = [];
2186
+ this.ratio = window.devicePixelRatio || 1;
2187
+ this.container = textbus.get(VIEW_CONTAINER);
2188
+ this.canvasContainer.append(this.canvas);
2189
+ this.host.append(this.canvasContainer, this.tooltips);
2190
+ this.container.prepend(this.host);
2191
+ this.subscription.add(this.onRectsChange.subscribe(function(rects) {
2192
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2193
+ try {
2194
+ for(var _iterator = rects[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2195
+ var rect = _step.value;
2196
+ _this.context.fillStyle = rect.color;
2197
+ _this.context.beginPath();
2198
+ _this.context.rect(rect.left, rect.top, rect.width, rect.height);
2199
+ _this.context.fill();
2200
+ _this.context.closePath();
2201
+ }
2202
+ } catch (err) {
2203
+ _didIteratorError = true;
2204
+ _iteratorError = err;
2205
+ } finally{
2206
+ try {
2207
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2208
+ _iterator.return();
2209
+ }
2210
+ } finally{
2211
+ if (_didIteratorError) {
2212
+ throw _iteratorError;
2213
+ }
2214
+ }
2215
+ }
2216
+ }), stream.fromEvent(window, 'resize').subscribe(function() {
2217
+ _this.canvas.style.height = document.documentElement.clientHeight + 'px';
2218
+ _this.refresh();
2219
+ }), this.scheduler.onDocChanged.subscribe(function() {
2220
+ _this.refresh();
2221
+ }));
2222
+ }
2223
+ _create_class$2(CollaborateCursor, [
2224
+ {
2225
+ /**
2226
+ * 刷新协作光标,由于 Textbus 只会绘制可视区域的光标,当可视区域发生变化时,需要重新绘制
2227
+ */ key: "refresh",
2228
+ value: function refresh() {
2229
+ this.draw(this.selectionCursors);
2230
+ }
2231
+ },
2232
+ {
2233
+ key: "destroy",
2234
+ value: function destroy() {
2235
+ this.subscription.unsubscribe();
2236
+ }
2237
+ },
2238
+ {
2239
+ /**
2240
+ * 根据远程用户光标位置,绘制协作光标
2241
+ * @param paths
2242
+ */ key: "draw",
2243
+ value: function draw(paths) {
2244
+ var _this = this;
2245
+ this.selectionCursors = paths;
2246
+ var containerRect = this.container.getBoundingClientRect();
2247
+ this.canvas.style.top = containerRect.top * -1 + 'px';
2248
+ this.canvas.width = this.canvas.offsetWidth * this.ratio;
2249
+ this.canvas.height = this.canvas.offsetHeight * this.ratio;
2250
+ this.context.scale(this.ratio, this.ratio);
2251
+ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
2252
+ var users = [];
2253
+ paths.filter(function(i) {
2254
+ return i.selection.anchor.length && i.selection.focus.length;
2255
+ }).forEach(function(item) {
2256
+ var anchorPaths = _to_consumable_array(item.selection.anchor);
2257
+ var focusPaths = _to_consumable_array(item.selection.focus);
2258
+ var anchorOffset = anchorPaths.pop();
2259
+ var anchorSlot = _this.selection.findSlotByPaths(anchorPaths);
2260
+ var focusOffset = focusPaths.pop();
2261
+ var focusSlot = _this.selection.findSlotByPaths(focusPaths);
2262
+ if (!anchorSlot || !focusSlot) {
2263
+ return;
2264
+ }
2265
+ var _this_nativeSelection_getPositionByRange = _this.nativeSelection.getPositionByRange({
2266
+ focusOffset: focusOffset,
2267
+ anchorOffset: anchorOffset,
2268
+ focusSlot: focusSlot,
2269
+ anchorSlot: anchorSlot
2270
+ }), focus = _this_nativeSelection_getPositionByRange.focus, anchor = _this_nativeSelection_getPositionByRange.anchor;
2271
+ if (!focus || !anchor) {
2272
+ return;
2273
+ }
2274
+ var nativeRange = document.createRange();
2275
+ try {
2276
+ nativeRange.setStart(anchor.node, anchor.offset);
2277
+ nativeRange.setEnd(focus.node, focus.offset);
2278
+ } catch (e) {
2279
+ return;
2280
+ }
2281
+ if ((anchor.node !== focus.node || anchor.offset !== focus.offset) && nativeRange.collapsed) {
2282
+ nativeRange.setStart(focus.node, focus.offset);
2283
+ nativeRange.setEnd(anchor.node, anchor.offset);
2284
+ }
2285
+ var rects = false;
2286
+ if (_this.awarenessDelegate) {
2287
+ rects = _this.awarenessDelegate.getRects({
2288
+ focusOffset: focusOffset,
2289
+ anchorOffset: anchorOffset,
2290
+ focusSlot: focusSlot,
2291
+ anchorSlot: anchorSlot
2292
+ }, nativeRange, item);
2293
+ }
2294
+ if (!rects) {
2295
+ rects = nativeRange.getClientRects();
2296
+ }
2297
+ var selectionRects = [];
2298
+ for(var i = rects.length - 1; i >= 0; i--){
2299
+ var rect = rects[i];
2300
+ selectionRects.push({
2301
+ color: item.color,
2302
+ username: item.username,
2303
+ left: rect.left - containerRect.left,
2304
+ top: rect.top,
2305
+ width: rect.width,
2306
+ height: rect.height
2307
+ });
2308
+ }
2309
+ _this.onRectsChange.next(selectionRects);
2310
+ var cursorRange = nativeRange.cloneRange();
2311
+ cursorRange.setStart(focus.node, focus.offset);
2312
+ cursorRange.collapse(true);
2313
+ var cursorRect = getLayoutRectByRange(cursorRange);
2314
+ var rect1 = {
2315
+ username: item.username,
2316
+ color: item.color,
2317
+ left: cursorRect.left - containerRect.left,
2318
+ top: cursorRect.top - containerRect.top,
2319
+ width: 1,
2320
+ height: cursorRect.height
2321
+ };
2322
+ if (rect1.left < 0 || rect1.top < 0 || rect1.left > containerRect.width) {
2323
+ return;
2324
+ }
2325
+ users.push(rect1);
2326
+ });
2327
+ this.drawUserCursor(users);
2328
+ }
2329
+ },
2330
+ {
2331
+ key: "drawUserCursor",
2332
+ value: function drawUserCursor(rects) {
2333
+ for(var i = 0; i < rects.length; i++){
2334
+ var rect = rects[i];
2335
+ var _this_getUserCursor = this.getUserCursor(i), cursor = _this_getUserCursor.cursor, userTip = _this_getUserCursor.userTip, anchor = _this_getUserCursor.anchor;
2336
+ Object.assign(cursor.style, {
2337
+ left: rect.left + 'px',
2338
+ top: rect.top + 'px',
2339
+ width: rect.width + 'px',
2340
+ height: rect.height + 'px',
2341
+ background: rect.color,
2342
+ display: 'block'
2343
+ });
2344
+ anchor.style.background = rect.color;
2345
+ userTip.innerText = rect.username;
2346
+ userTip.style.background = rect.color;
2347
+ }
2348
+ for(var i1 = rects.length; i1 < this.tooltips.children.length; i1++){
2349
+ this.tooltips.removeChild(this.tooltips.children[i1]);
2350
+ }
2351
+ }
2352
+ },
2353
+ {
2354
+ key: "getUserCursor",
2355
+ value: function getUserCursor(index) {
2356
+ var child = this.tooltips.children[index];
2357
+ if (child) {
2358
+ var anchor = child.children[0];
2359
+ return {
2360
+ cursor: child,
2361
+ anchor: anchor,
2362
+ userTip: anchor.children[0]
2363
+ };
2364
+ }
2365
+ var userTip = createElement('span', {
2366
+ styles: {
2367
+ position: 'absolute',
2368
+ left: '50%',
2369
+ transform: 'translateX(-50%)',
2370
+ marginBottom: '2px',
2371
+ bottom: '100%',
2372
+ whiteSpace: 'nowrap',
2373
+ color: '#fff',
2374
+ boxShadow: '0 1px 2px rgba(0,0,0,.1)',
2375
+ opacity: 0.8,
2376
+ borderRadius: '3px',
2377
+ padding: '3px 5px',
2378
+ pointerEvents: 'none'
2379
+ }
2380
+ });
2381
+ var anchor1 = createElement('span', {
2382
+ styles: {
2383
+ position: 'absolute',
2384
+ top: '-2px',
2385
+ left: '-2px',
2386
+ width: '5px',
2387
+ height: '5px',
2388
+ borderRadius: '50%',
2389
+ pointerEvents: 'auto',
2390
+ pointer: 'cursor'
2391
+ },
2392
+ children: [
2393
+ userTip
2394
+ ]
2395
+ });
2396
+ child = createElement('span', {
2397
+ styles: {
2398
+ position: 'absolute'
2399
+ },
2400
+ children: [
2401
+ anchor1
2402
+ ]
2403
+ });
2404
+ this.tooltips.append(child);
2405
+ return {
2406
+ cursor: child,
2407
+ anchor: anchor1,
2408
+ userTip: userTip
2409
+ };
2410
+ }
2411
+ }
2412
+ ]);
2413
+ return CollaborateCursor;
2414
+ }();
2415
+ exports.CollaborateCursor = _ts_decorate$1([
2416
+ core.Injectable(),
2417
+ _ts_param(4, core.Optional()),
2418
+ _ts_metadata$1("design:type", Function),
2419
+ _ts_metadata$1("design:paramtypes", [
2420
+ typeof core$1.Textbus === "undefined" ? Object : core$1.Textbus,
2421
+ typeof exports.SelectionBridge === "undefined" ? Object : exports.SelectionBridge,
2422
+ typeof core$1.Scheduler === "undefined" ? Object : core$1.Scheduler,
2423
+ typeof core$1.Selection === "undefined" ? Object : core$1.Selection,
2424
+ typeof CollaborateSelectionAwarenessDelegate === "undefined" ? Object : CollaborateSelectionAwarenessDelegate
2425
+ ])
2426
+ ], exports.CollaborateCursor);
2427
+
2428
+ function _assert_this_initialized(self) {
2429
+ if (self === void 0) {
2430
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
2431
+ }
2432
+ return self;
2433
+ }
2434
+ function _call_super(_this, derived, args) {
2435
+ derived = _get_prototype_of(derived);
2436
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
2437
+ }
2438
+ function _class_call_check$1(instance, Constructor) {
2439
+ if (!(instance instanceof Constructor)) {
2440
+ throw new TypeError("Cannot call a class as a function");
2441
+ }
2442
+ }
2443
+ function _defineProperties$1(target, props) {
2444
+ for(var i = 0; i < props.length; i++){
2445
+ var descriptor = props[i];
2446
+ descriptor.enumerable = descriptor.enumerable || false;
2447
+ descriptor.configurable = true;
2448
+ if ("value" in descriptor) descriptor.writable = true;
2449
+ Object.defineProperty(target, descriptor.key, descriptor);
2450
+ }
2451
+ }
2452
+ function _create_class$1(Constructor, protoProps, staticProps) {
2453
+ if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
2454
+ return Constructor;
2455
+ }
2456
+ function _define_property$1(obj, key, value) {
2457
+ if (key in obj) {
2458
+ Object.defineProperty(obj, key, {
2459
+ value: value,
2460
+ enumerable: true,
2461
+ configurable: true,
2462
+ writable: true
2463
+ });
2464
+ } else {
2465
+ obj[key] = value;
2466
+ }
2467
+ return obj;
2468
+ }
2469
+ function _get_prototype_of(o) {
2470
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
2471
+ return o.__proto__ || Object.getPrototypeOf(o);
2472
+ };
2473
+ return _get_prototype_of(o);
2474
+ }
2475
+ function _inherits(subClass, superClass) {
2476
+ if (typeof superClass !== "function" && superClass !== null) {
2477
+ throw new TypeError("Super expression must either be null or a function");
2478
+ }
2479
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
2480
+ constructor: {
2481
+ value: subClass,
2482
+ writable: true,
2483
+ configurable: true
2484
+ }
2485
+ });
2486
+ if (superClass) _set_prototype_of(subClass, superClass);
2487
+ }
2488
+ function _instanceof$1(left, right) {
2489
+ "@swc/helpers - instanceof";
2490
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
2491
+ return !!right[Symbol.hasInstance](left);
2492
+ } else {
2493
+ return left instanceof right;
2494
+ }
2495
+ }
2496
+ function _possible_constructor_return(self, call) {
2497
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
2498
+ return call;
2499
+ }
2500
+ return _assert_this_initialized(self);
2501
+ }
2502
+ function _set_prototype_of(o, p) {
2503
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
2504
+ o.__proto__ = p;
2505
+ return o;
2506
+ };
2507
+ return _set_prototype_of(o, p);
2508
+ }
2509
+ function _type_of(obj) {
2510
+ "@swc/helpers - typeof";
2511
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
2512
+ }
2513
+ function _is_native_reflect_construct() {
2514
+ try {
2515
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2516
+ } catch (_) {}
2517
+ return (_is_native_reflect_construct = function() {
2518
+ return !!result;
2519
+ })();
2520
+ }
2521
+ function _ts_decorate(decorators, target, key, desc) {
2522
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2523
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2524
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2525
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2526
+ }
2527
+ function _ts_metadata(k, v) {
2528
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2529
+ }
2530
+ var NativeCaret = /*#__PURE__*/ function() {
2531
+ function NativeCaret() {
2532
+ _class_call_check$1(this, NativeCaret);
2533
+ _define_property$1(this, "onPositionChange", void 0);
2534
+ _define_property$1(this, "_nativeRange", null);
2535
+ _define_property$1(this, "subs", []);
2536
+ _define_property$1(this, "positionChangeEvent", new stream.Subject());
2537
+ this.onPositionChange = this.positionChangeEvent.pipe(stream.distinctUntilChanged());
2538
+ }
2539
+ _create_class$1(NativeCaret, [
2540
+ {
2541
+ key: "nativeRange",
2542
+ get: function get() {
2543
+ return this._nativeRange;
2544
+ },
2545
+ set: function set(range) {
2546
+ this._nativeRange = range;
2547
+ if (range) {
2548
+ var r = range.cloneRange();
2549
+ r.collapse(true);
2550
+ var rect = getLayoutRectByRange(r);
2551
+ this.positionChangeEvent.next({
2552
+ left: rect.left,
2553
+ top: rect.top,
2554
+ height: rect.height
2555
+ });
2556
+ } else {
2557
+ this.positionChangeEvent.next(null);
2558
+ }
2559
+ }
2560
+ },
2561
+ {
2562
+ key: "rect",
2563
+ get: function get() {
2564
+ if (this.nativeRange) {
2565
+ var range = this.nativeRange.cloneRange();
2566
+ range.collapse(true);
2567
+ return getLayoutRectByRange(range);
2568
+ }
2569
+ return {
2570
+ left: 0,
2571
+ top: 0,
2572
+ width: 0,
2573
+ height: 0
2574
+ };
2575
+ }
2576
+ },
2577
+ {
2578
+ key: "refresh",
2579
+ value: function refresh() {
2580
+ //
2581
+ }
2582
+ },
2583
+ {
2584
+ key: "destroy",
2585
+ value: function destroy() {
2586
+ this.subs.forEach(function(i) {
2587
+ return i.unsubscribe();
2588
+ });
2589
+ this.subs = [];
2590
+ }
2591
+ }
2592
+ ]);
2593
+ return NativeCaret;
2594
+ }();
2595
+ exports.NativeInput = /*#__PURE__*/ function(Input) {
2596
+ _inherits(NativeInput, Input);
2597
+ function NativeInput(textbus, parser, selection, keyboard, domAdapter, commander, controller) {
2598
+ _class_call_check$1(this, NativeInput);
2599
+ var _this;
2600
+ _this = _call_super(this, NativeInput), _define_property$1(_this, "parser", void 0), _define_property$1(_this, "selection", void 0), _define_property$1(_this, "keyboard", void 0), _define_property$1(_this, "domAdapter", void 0), _define_property$1(_this, "commander", void 0), _define_property$1(_this, "controller", void 0), _define_property$1(_this, "caret", void 0), _define_property$1(_this, "composition", void 0), // compositionState: CompositionState | null = null
2601
+ _define_property$1(_this, "onReady", void 0), _define_property$1(_this, "_disabled", void 0), _define_property$1(_this, "documentView", void 0), _define_property$1(_this, "nativeSelection", void 0), _define_property$1(_this, "subscription", void 0), _define_property$1(_this, "nativeRange", void 0), _define_property$1(_this, "isSafari", void 0), _define_property$1(_this, "isMac", void 0), _define_property$1(_this, "isMobileBrowser", void 0), _define_property$1(_this, "ignoreComposition", void 0 // 有 bug 版本搜狗拼音
2602
+ ), _this.parser = parser, _this.selection = selection, _this.keyboard = keyboard, _this.domAdapter = domAdapter, _this.commander = commander, _this.controller = controller, _this.caret = new NativeCaret(), _this.composition = false, _this.onReady = Promise.resolve(), _this._disabled = false, _this.nativeSelection = document.getSelection(), _this.subscription = new stream.Subscription(), _this.nativeRange = null, _this.isSafari = isSafari(), _this.isMac = isMac(), _this.isMobileBrowser = isMobileBrowser(), _this.ignoreComposition = false;
2603
+ _this.documentView = textbus.get(VIEW_DOCUMENT);
2604
+ if (!controller.readonly) {
2605
+ _this.documentView.contentEditable = 'true';
2606
+ }
2607
+ _this.subscription.add(controller.onReadonlyStateChange.subscribe(function() {
2608
+ _this.documentView.contentEditable = controller.readonly ? 'false' : 'true';
2609
+ }));
2610
+ _this.handleShortcut(_this.documentView);
2611
+ _this.handleInput(_this.documentView);
2612
+ _this.handleDefaultActions(_this.documentView);
2613
+ return _this;
2614
+ }
2615
+ _create_class$1(NativeInput, [
2616
+ {
2617
+ key: "disabled",
2618
+ get: function get() {
2619
+ return this._disabled;
2620
+ },
2621
+ set: function set(b) {
2622
+ this._disabled = b;
2623
+ if (this.controller.readonly) {
2624
+ this.documentView.contentEditable = 'false';
2625
+ return;
2626
+ }
2627
+ this.documentView.contentEditable = b ? 'false' : 'true';
2628
+ }
2629
+ },
2630
+ {
2631
+ key: "focus",
2632
+ value: function focus(nativeRange) {
2633
+ if (this.controller.readonly) {
2634
+ return;
2635
+ }
2636
+ this.caret.nativeRange = nativeRange;
2637
+ this.nativeRange = nativeRange;
2638
+ }
2639
+ },
2640
+ {
2641
+ key: "blur",
2642
+ value: function blur() {
2643
+ if (this.nativeRange && this.nativeSelection.rangeCount > 0) {
2644
+ var current = this.nativeSelection.getRangeAt(0);
2645
+ if (current === this.nativeRange) {
2646
+ this.nativeSelection.removeAllRanges();
2647
+ this.nativeRange = null;
2648
+ return;
2649
+ }
2650
+ }
2651
+ }
2652
+ },
2653
+ {
2654
+ key: "destroy",
2655
+ value: function destroy() {
2656
+ this.caret.destroy();
2657
+ this.subscription.unsubscribe();
2658
+ }
2659
+ },
2660
+ {
2661
+ key: "handleDefaultActions",
2662
+ value: function handleDefaultActions(textarea) {
2663
+ var _this = this;
2664
+ this.subscription.add(stream.fromEvent(isFirefox() ? textarea : document, 'copy').subscribe(function(ev) {
2665
+ _this.copyHandler(ev);
2666
+ }), stream.fromEvent(textarea, 'paste').subscribe(function(ev) {
2667
+ _this.pasteHandler(ev);
2668
+ }));
2669
+ }
2670
+ },
2671
+ {
2672
+ key: "copyHandler",
2673
+ value: function copyHandler(ev) {
2674
+ var selection = this.selection;
2675
+ if (!selection.isSelected) {
2676
+ return;
2677
+ }
2678
+ if (selection.startSlot === selection.endSlot && selection.endOffset - selection.startOffset === 1) {
2679
+ var content = selection.startSlot.getContentAtIndex(selection.startOffset);
2680
+ if ((typeof content === "undefined" ? "undefined" : _type_of(content)) === 'object') {
2681
+ var clipboardData = ev.clipboardData;
2682
+ var nativeSelection = document.getSelection();
2683
+ var range = nativeSelection.getRangeAt(0);
2684
+ var div = document.createElement('div');
2685
+ var fragment = range.cloneContents();
2686
+ div.append(fragment);
2687
+ clipboardData.setData('text/html', div.innerHTML);
2688
+ clipboardData.setData('text', div.innerText);
2689
+ ev.preventDefault();
2690
+ }
2691
+ }
2692
+ }
2693
+ },
2694
+ {
2695
+ key: "pasteHandler",
2696
+ value: function pasteHandler(ev) {
2697
+ var _this = this;
2698
+ var text = ev.clipboardData.getData('Text');
2699
+ var types = Array.from(ev.clipboardData.types || []);
2700
+ var files = Array.from(ev.clipboardData.files);
2701
+ if (types.every(function(type) {
2702
+ return type === 'Files';
2703
+ }) && files.length) {
2704
+ Promise.all(files.filter(function(i) {
2705
+ return /image/i.test(i.type);
2706
+ }).map(function(item) {
2707
+ var reader = new FileReader();
2708
+ return new Promise(function(resolve) {
2709
+ reader.onload = function(event) {
2710
+ resolve(event.target.result);
2711
+ };
2712
+ reader.readAsDataURL(item);
2713
+ });
2714
+ })).then(function(urls) {
2715
+ var html = urls.map(function(i) {
2716
+ return "<img src=".concat(i, ">");
2717
+ }).join('');
2718
+ _this.paste(html, text);
2719
+ });
2720
+ ev.preventDefault();
2721
+ return;
2722
+ }
2723
+ var div = document.createElement('div');
2724
+ div.style.cssText = 'width:1px; height:10px; overflow: hidden; position: fixed; left: 50%; top: 50%; opacity:0';
2725
+ div.contentEditable = 'true';
2726
+ document.body.appendChild(div);
2727
+ div.focus();
2728
+ setTimeout(function() {
2729
+ document.body.removeChild(div);
2730
+ div.style.cssText = '';
2731
+ _this.paste(div, text);
2732
+ });
2733
+ }
2734
+ },
2735
+ {
2736
+ key: "paste",
2737
+ value: function paste(dom, text) {
2738
+ var slot = this.parser.parse(dom, new core$1.Slot([
2739
+ core$1.ContentType.BlockComponent,
2740
+ core$1.ContentType.InlineComponent,
2741
+ core$1.ContentType.Text
2742
+ ]));
2743
+ this.commander.paste(slot, text);
2744
+ }
2745
+ },
2746
+ {
2747
+ key: "handleShortcut",
2748
+ value: function handleShortcut(input) {
2749
+ var _this = this;
2750
+ var isWriting = false;
2751
+ var isIgnore = false;
2752
+ this.subscription.add(stream.fromEvent(input, 'compositionstart').subscribe(function() {
2753
+ isWriting = true;
2754
+ }), stream.fromEvent(input, 'compositionend').subscribe(function() {
2755
+ isWriting = false;
2756
+ }), stream.fromEvent(input, 'beforeinput').subscribe(function(ev) {
2757
+ if (_this.isSafari) {
2758
+ if (ev.inputType === 'insertFromComposition') {
2759
+ isIgnore = true;
2760
+ }
2761
+ }
2762
+ }), stream.fromEvent(input, 'keydown').pipe(stream.filter(function() {
2763
+ if (_this.isSafari && isIgnore) {
2764
+ isIgnore = false;
2765
+ return false;
2766
+ }
2767
+ return !isWriting // || !this.textarea.value
2768
+ ;
2769
+ })).subscribe(function(ev) {
2770
+ _this.ignoreComposition = false;
2771
+ var key = ev.key;
2772
+ var keys = ')!@#$%^Z&*(';
2773
+ var b = key === 'Process' && /Digit\d/.test(ev.code) && ev.shiftKey;
2774
+ if (b) {
2775
+ key = keys.charAt(+ev.code.substring(5));
2776
+ ev.preventDefault();
2777
+ }
2778
+ var is = _this.keyboard.execShortcut({
2779
+ key: key,
2780
+ altKey: ev.altKey,
2781
+ shiftKey: ev.shiftKey,
2782
+ modKey: _this.isMac ? ev.metaKey : ev.ctrlKey,
2783
+ agent: {
2784
+ key: ev.key,
2785
+ keyCode: ev.keyCode,
2786
+ code: ev.code
2787
+ }
2788
+ });
2789
+ if (is) {
2790
+ _this.ignoreComposition = true;
2791
+ ev.preventDefault();
2792
+ }
2793
+ }));
2794
+ }
2795
+ },
2796
+ {
2797
+ key: "handleInput",
2798
+ value: function handleInput(input) {
2799
+ if (this.isMobileBrowser) {
2800
+ this.handleMobileInput(input);
2801
+ } else {
2802
+ this.handlePCInput(input);
2803
+ }
2804
+ }
2805
+ },
2806
+ {
2807
+ key: "handleMobileInput",
2808
+ value: function handleMobileInput(input) {
2809
+ var _this = this;
2810
+ var isCompositionStart = true;
2811
+ var startIndex;
2812
+ var compositionStart = function compositionStart() {
2813
+ _this.composition = true;
2814
+ startIndex = _this.selection.startOffset;
2815
+ var startSlot = _this.selection.startSlot;
2816
+ var event = new core$1.Event(startSlot, {
2817
+ index: startIndex
2818
+ });
2819
+ core$1.invokeListener(startSlot.parent, 'onCompositionStart', event);
2820
+ };
2821
+ var compositionUpdate = function compositionUpdate(data) {
2822
+ var startSlot = _this.selection.startSlot;
2823
+ var event = new core$1.Event(startSlot, {
2824
+ index: startIndex,
2825
+ data: data
2826
+ });
2827
+ core$1.invokeListener(startSlot.parent, 'onCompositionUpdate', event);
2828
+ };
2829
+ var compositionEnd = function compositionEnd(data) {
2830
+ _this.composition = false;
2831
+ if (data) {
2832
+ _this.commander.write(data);
2833
+ }
2834
+ var startSlot = _this.selection.startSlot;
2835
+ if (startSlot) {
2836
+ var event = new core$1.Event(startSlot, null);
2837
+ core$1.invokeListener(startSlot.parent, 'onCompositionEnd', event);
2838
+ }
2839
+ };
2840
+ this.subscription.add(stream.fromEvent(input, 'compositionstart').subscribe(function() {
2841
+ compositionStart();
2842
+ }), stream.fromEvent(input, 'compositionupdate').subscribe(function(ev) {
2843
+ compositionUpdate(ev.data);
2844
+ }), stream.fromEvent(input, 'compositionend').subscribe(function(ev) {
2845
+ compositionEnd(ev.data);
2846
+ var startContainer = _this.nativeSelection.focusNode;
2847
+ if (_instanceof$1(startContainer, Text) && startContainer.textContent === ev.data) {
2848
+ startContainer.remove();
2849
+ }
2850
+ }), stream.fromEvent(input, 'beforeinput').subscribe(function(ev) {
2851
+ switch(ev.inputType){
2852
+ case 'insertText':
2853
+ if (ev.data) {
2854
+ _this.commander.write(ev.data);
2855
+ ev.preventDefault();
2856
+ }
2857
+ break;
2858
+ case 'insertCompositionText':
2859
+ if (isCompositionStart) {
2860
+ isCompositionStart = false;
2861
+ compositionStart();
2862
+ } else {
2863
+ compositionUpdate(ev.data || '');
2864
+ }
2865
+ break;
2866
+ case 'deleteCompositionText':
2867
+ _this.composition = false;
2868
+ break;
2869
+ case 'deleteContentBackward':
2870
+ {
2871
+ _this.composition = false;
2872
+ var range = ev.getTargetRanges()[0];
2873
+ if (!range) {
2874
+ break;
2875
+ }
2876
+ var location = _this.domAdapter.getLocationByNativeNode(range.startContainer);
2877
+ var startSlot = _this.selection.startSlot;
2878
+ if (startSlot) {
2879
+ _this.selection.setBaseAndExtent(startSlot, location.startIndex + range.startOffset, startSlot, location.startIndex + range.endOffset);
2880
+ _this.commander.delete();
2881
+ }
2882
+ break;
2883
+ }
2884
+ case 'insertReplacementText':
2885
+ {
2886
+ var _ev_dataTransfer;
2887
+ _this.composition = false;
2888
+ var range1 = ev.getTargetRanges()[0];
2889
+ var location1 = _this.domAdapter.getLocationByNativeNode(range1.startContainer);
2890
+ var startSlot1 = _this.selection.startSlot;
2891
+ _this.selection.setBaseAndExtent(startSlot1, location1.startIndex + range1.startOffset, startSlot1, location1.startIndex + range1.endOffset);
2892
+ _this.commander.delete();
2893
+ var text = ((_ev_dataTransfer = ev.dataTransfer) === null || _ev_dataTransfer === void 0 ? void 0 : _ev_dataTransfer.getData('text')) || ev.data || null;
2894
+ if (text) {
2895
+ _this.commander.write(text);
2896
+ }
2897
+ break;
2898
+ }
2899
+ }
2900
+ }));
2901
+ }
2902
+ },
2903
+ {
2904
+ key: "handlePCInput",
2905
+ value: function handlePCInput(input) {
2906
+ var _this = this;
2907
+ var startIndex = 0;
2908
+ var isCompositionEnd = false;
2909
+ this.subscription.add(stream.fromEvent(input, 'compositionstart').pipe(stream.filter(function() {
2910
+ return !_this.ignoreComposition;
2911
+ })).subscribe(function() {
2912
+ _this.composition = true;
2913
+ startIndex = _this.selection.startOffset;
2914
+ var startSlot = _this.selection.startSlot;
2915
+ var event = new core$1.Event(startSlot, {
2916
+ index: startIndex
2917
+ });
2918
+ core$1.invokeListener(startSlot.parent, 'onCompositionStart', event);
2919
+ }), stream.fromEvent(input, 'compositionupdate').pipe(stream.filter(function() {
2920
+ return !_this.ignoreComposition;
2921
+ })).subscribe(function(ev) {
2922
+ var startSlot = _this.selection.startSlot;
2923
+ var event = new core$1.Event(startSlot, {
2924
+ index: startIndex,
2925
+ data: ev.data
2926
+ });
2927
+ core$1.invokeListener(startSlot.parent, 'onCompositionUpdate', event);
2928
+ }), stream.merge(stream.fromEvent(input, 'beforeinput').pipe(stream.map(function(ev) {
2929
+ ev.preventDefault();
2930
+ if (ev.inputType === 'insertCompositionText') {
2931
+ return null;
2932
+ }
2933
+ if (ev.inputType === 'insertReplacementText') {
2934
+ var _ev_dataTransfer;
2935
+ var range = ev.getTargetRanges()[0];
2936
+ var location = _this.domAdapter.getLocationByNativeNode(range.startContainer);
2937
+ var startSlot = _this.selection.startSlot;
2938
+ _this.selection.setBaseAndExtent(startSlot, location.startIndex + range.startOffset, startSlot, location.startIndex + range.endOffset);
2939
+ _this.commander.delete();
2940
+ return ((_ev_dataTransfer = ev.dataTransfer) === null || _ev_dataTransfer === void 0 ? void 0 : _ev_dataTransfer.getData('text')) || ev.data || null;
2941
+ }
2942
+ isCompositionEnd = ev.inputType === 'insertFromComposition';
2943
+ if (isCompositionEnd && _this.composition) {
2944
+ return null;
2945
+ }
2946
+ if (_this.isSafari) {
2947
+ if (ev.inputType === 'insertText' || isCompositionEnd) {
2948
+ return ev.data;
2949
+ }
2950
+ }
2951
+ if (!ev.isComposing && !!ev.data) {
2952
+ return ev.data;
2953
+ }
2954
+ return null;
2955
+ }), stream.filter(function(text) {
2956
+ return text;
2957
+ })), this.isSafari ? new stream.Observable() : stream.fromEvent(input, 'compositionend').pipe(stream.filter(function() {
2958
+ return !_this.ignoreComposition;
2959
+ })).pipe(stream.filter(function() {
2960
+ return _this.composition;
2961
+ }), stream.map(function(ev) {
2962
+ isCompositionEnd = true;
2963
+ ev.preventDefault();
2964
+ return ev.data;
2965
+ }), stream.filter(function() {
2966
+ var b = _this.ignoreComposition;
2967
+ _this.ignoreComposition = false;
2968
+ return !b;
2969
+ }))).subscribe(function(text) {
2970
+ _this.composition = false;
2971
+ if (text) {
2972
+ var startContainer = _this.nativeSelection.focusNode;
2973
+ if (_instanceof$1(startContainer, Text) && startContainer.textContent === text) {
2974
+ startContainer.remove();
2975
+ }
2976
+ _this.commander.write(text);
2977
+ }
2978
+ if (isCompositionEnd) {
2979
+ var startSlot = _this.selection.startSlot;
2980
+ if (startSlot) {
2981
+ var event = new core$1.Event(startSlot, null);
2982
+ core$1.invokeListener(startSlot.parent, 'onCompositionEnd', event);
2983
+ }
2984
+ }
2985
+ isCompositionEnd = false;
2986
+ }));
2987
+ }
2988
+ }
2989
+ ]);
2990
+ return NativeInput;
2991
+ }(Input);
2992
+ exports.NativeInput = _ts_decorate([
2993
+ core.Injectable(),
2994
+ _ts_metadata("design:type", Function),
2995
+ _ts_metadata("design:paramtypes", [
2996
+ typeof core$1.Textbus === "undefined" ? Object : core$1.Textbus,
2997
+ typeof exports.Parser === "undefined" ? Object : exports.Parser,
2998
+ typeof core$1.Selection === "undefined" ? Object : core$1.Selection,
2999
+ typeof core$1.Keyboard === "undefined" ? Object : core$1.Keyboard,
3000
+ typeof DomAdapter === "undefined" ? Object : DomAdapter,
3001
+ typeof core$1.Commander === "undefined" ? Object : core$1.Commander,
3002
+ typeof core$1.Controller === "undefined" ? Object : core$1.Controller
3003
+ ])
3004
+ ], exports.NativeInput);
3005
+
3006
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
3007
+ try {
3008
+ var info = gen[key](arg);
3009
+ var value = info.value;
3010
+ } catch (error) {
3011
+ reject(error);
3012
+ return;
3013
+ }
3014
+ if (info.done) {
3015
+ resolve(value);
3016
+ } else {
3017
+ Promise.resolve(value).then(_next, _throw);
3018
+ }
3019
+ }
3020
+ function _async_to_generator(fn) {
3021
+ return function() {
3022
+ var self = this, args = arguments;
3023
+ return new Promise(function(resolve, reject) {
3024
+ var gen = fn.apply(self, args);
3025
+ function _next(value) {
3026
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
3027
+ }
3028
+ function _throw(err) {
3029
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
3030
+ }
3031
+ _next(undefined);
3032
+ });
3033
+ };
3034
+ }
3035
+ function _class_call_check(instance, Constructor) {
3036
+ if (!(instance instanceof Constructor)) {
3037
+ throw new TypeError("Cannot call a class as a function");
3038
+ }
3039
+ }
3040
+ function _defineProperties(target, props) {
3041
+ for(var i = 0; i < props.length; i++){
3042
+ var descriptor = props[i];
3043
+ descriptor.enumerable = descriptor.enumerable || false;
3044
+ descriptor.configurable = true;
3045
+ if ("value" in descriptor) descriptor.writable = true;
3046
+ Object.defineProperty(target, descriptor.key, descriptor);
3047
+ }
3048
+ }
3049
+ function _create_class(Constructor, protoProps, staticProps) {
3050
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
3051
+ if (staticProps) _defineProperties(Constructor, staticProps);
3052
+ return Constructor;
3053
+ }
3054
+ function _define_property(obj, key, value) {
3055
+ if (key in obj) {
3056
+ Object.defineProperty(obj, key, {
3057
+ value: value,
3058
+ enumerable: true,
3059
+ configurable: true,
3060
+ writable: true
3061
+ });
3062
+ } else {
3063
+ obj[key] = value;
3064
+ }
3065
+ return obj;
3066
+ }
3067
+ function _instanceof(left, right) {
3068
+ "@swc/helpers - instanceof";
3069
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
3070
+ return !!right[Symbol.hasInstance](left);
3071
+ } else {
3072
+ return left instanceof right;
3073
+ }
3074
+ }
3075
+ function _ts_generator(thisArg, body) {
3076
+ var f, y, t, _ = {
3077
+ label: 0,
3078
+ sent: function() {
3079
+ if (t[0] & 1) throw t[1];
3080
+ return t[1];
3081
+ },
3082
+ trys: [],
3083
+ ops: []
3084
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
3085
+ return d(g, "next", {
3086
+ value: verb(0)
3087
+ }), d(g, "throw", {
3088
+ value: verb(1)
3089
+ }), d(g, "return", {
3090
+ value: verb(2)
3091
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
3092
+ value: function() {
3093
+ return this;
3094
+ }
3095
+ }), g;
3096
+ function verb(n) {
3097
+ return function(v) {
3098
+ return step([
3099
+ n,
3100
+ v
3101
+ ]);
3102
+ };
3103
+ }
3104
+ function step(op) {
3105
+ if (f) throw new TypeError("Generator is already executing.");
3106
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
3107
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
3108
+ if (y = 0, t) op = [
3109
+ op[0] & 2,
3110
+ t.value
3111
+ ];
3112
+ switch(op[0]){
3113
+ case 0:
3114
+ case 1:
3115
+ t = op;
3116
+ break;
3117
+ case 4:
3118
+ _.label++;
3119
+ return {
3120
+ value: op[1],
3121
+ done: false
3122
+ };
3123
+ case 5:
3124
+ _.label++;
3125
+ y = op[1];
3126
+ op = [
3127
+ 0
3128
+ ];
3129
+ continue;
3130
+ case 7:
3131
+ op = _.ops.pop();
3132
+ _.trys.pop();
3133
+ continue;
3134
+ default:
3135
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
3136
+ _ = 0;
3137
+ continue;
3138
+ }
3139
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
3140
+ _.label = op[1];
3141
+ break;
3142
+ }
3143
+ if (op[0] === 6 && _.label < t[1]) {
3144
+ _.label = t[1];
3145
+ t = op;
3146
+ break;
3147
+ }
3148
+ if (t && _.label < t[2]) {
3149
+ _.label = t[2];
3150
+ _.ops.push(op);
3151
+ break;
3152
+ }
3153
+ if (t[2]) _.ops.pop();
3154
+ _.trys.pop();
3155
+ continue;
3156
+ }
3157
+ op = body.call(thisArg, _);
3158
+ } catch (e) {
3159
+ op = [
3160
+ 6,
3161
+ e
3162
+ ];
3163
+ y = 0;
3164
+ } finally{
3165
+ f = t = 0;
3166
+ }
3167
+ if (op[0] & 5) throw op[1];
3168
+ return {
3169
+ value: op[0] ? op[1] : void 0,
3170
+ done: true
3171
+ };
3172
+ }
3173
+ }
3174
+ var browserErrorFn = core$1.makeError('BrowserModule');
3175
+ var BrowserModule = /*#__PURE__*/ function() {
3176
+ function BrowserModule(config) {
3177
+ _class_call_check(this, BrowserModule);
3178
+ _define_property(this, "config", void 0);
3179
+ _define_property(this, "providers", void 0);
3180
+ _define_property(this, "workbench", void 0);
3181
+ this.config = config;
3182
+ var _BrowserModule_createLayout = BrowserModule.createLayout(), mask = _BrowserModule_createLayout.mask, wrapper = _BrowserModule_createLayout.wrapper;
3183
+ wrapper.prepend(config.adapter.host);
3184
+ if (config.minHeight) {
3185
+ config.adapter.host.style.minHeight = config.minHeight;
3186
+ }
3187
+ this.providers = [
3188
+ {
3189
+ provide: EDITOR_OPTIONS,
3190
+ useValue: config
3191
+ },
3192
+ {
3193
+ provide: VIEW_CONTAINER,
3194
+ useValue: wrapper
3195
+ },
3196
+ {
3197
+ provide: VIEW_DOCUMENT,
3198
+ useValue: config.adapter.host
3199
+ },
3200
+ {
3201
+ provide: VIEW_MASK,
3202
+ useValue: mask
3203
+ },
3204
+ {
3205
+ provide: core$1.NativeSelectionBridge,
3206
+ useExisting: exports.SelectionBridge
3207
+ },
3208
+ {
3209
+ provide: Input,
3210
+ useClass: config.useContentEditable ? exports.NativeInput : exports.MagicInput
3211
+ },
3212
+ {
3213
+ provide: core$1.Adapter,
3214
+ useValue: config.adapter
3215
+ },
3216
+ {
3217
+ provide: DomAdapter,
3218
+ useValue: config.adapter
3219
+ },
3220
+ {
3221
+ provide: core$1.FocusManager,
3222
+ useFactory: function useFactory(input) {
3223
+ var focusEvent = new stream.Subject();
3224
+ var blurEvent = new stream.Subject();
3225
+ input.caret.onPositionChange.pipe(stream.map(function(p) {
3226
+ return !!p;
3227
+ }), stream.distinctUntilChanged()).subscribe(function(b) {
3228
+ if (b) {
3229
+ focusEvent.next();
3230
+ } else {
3231
+ blurEvent.next();
3232
+ }
3233
+ });
3234
+ return {
3235
+ onFocus: focusEvent,
3236
+ onBlur: blurEvent
3237
+ };
3238
+ },
3239
+ deps: [
3240
+ Input
3241
+ ]
3242
+ },
3243
+ exports.Parser,
3244
+ exports.SelectionBridge,
3245
+ exports.CollaborateCursor
3246
+ ];
3247
+ this.workbench = wrapper;
3248
+ }
3249
+ _create_class(BrowserModule, [
3250
+ {
3251
+ /**
3252
+ * 解析 HTML 并返回一个组件实例
3253
+ * @param html 要解析的 HTML
3254
+ * @param rootComponentLoader 文档根组件加载器
3255
+ * @param textbus
3256
+ */ key: "readDocumentByHTML",
3257
+ value: function readDocumentByHTML(html, rootComponentLoader, textbus) {
3258
+ var parser = textbus.get(exports.Parser);
3259
+ var doc = parser.parseDoc(html, rootComponentLoader);
3260
+ if (_instanceof(doc, core$1.Component)) {
3261
+ return doc;
3262
+ }
3263
+ throw browserErrorFn('rootComponentLoader must return a component instance.');
3264
+ }
3265
+ },
3266
+ {
3267
+ /**
3268
+ * 将组件数据解析到组件实例中
3269
+ * @param data 要解析的 JSON 数据
3270
+ * @param rootComponent 根组件
3271
+ * @param textbus
3272
+ */ key: "readDocumentByComponentLiteral",
3273
+ value: function readDocumentByComponentLiteral(data, rootComponent, textbus) {
3274
+ var registry = textbus.get(core$1.Registry);
3275
+ return registry.createComponentByFactory(data, rootComponent);
3276
+ }
3277
+ },
3278
+ {
3279
+ key: "setup",
3280
+ value: function setup(textbus) {
3281
+ return _async_to_generator(function() {
3282
+ var _this, host;
3283
+ return _ts_generator(this, function(_state) {
3284
+ switch(_state.label){
3285
+ case 0:
3286
+ _this = this;
3287
+ host = this.config.renderTo();
3288
+ if (!_instanceof(host, HTMLElement)) {
3289
+ throw browserErrorFn('view container is not a HTMLElement');
3290
+ }
3291
+ host.append(this.workbench);
3292
+ return [
3293
+ 4,
3294
+ textbus.get(Input).onReady
3295
+ ];
3296
+ case 1:
3297
+ _state.sent();
3298
+ return [
3299
+ 2,
3300
+ function() {
3301
+ _this.workbench.remove();
3302
+ }
3303
+ ];
3304
+ }
3305
+ });
3306
+ }).call(this);
3307
+ }
3308
+ },
3309
+ {
3310
+ key: "onAfterStartup",
3311
+ value: function onAfterStartup(textbus) {
3312
+ if (this.config.autoFocus) {
3313
+ textbus.focus();
3314
+ }
3315
+ }
3316
+ },
3317
+ {
3318
+ key: "onDestroy",
3319
+ value: function onDestroy(textbus) {
3320
+ textbus.get(Input).destroy();
3321
+ textbus.get(exports.SelectionBridge).destroy();
3322
+ textbus.get(exports.CollaborateCursor).destroy();
3323
+ }
3324
+ }
3325
+ ], [
3326
+ {
3327
+ key: "createLayout",
3328
+ value: function createLayout() {
3329
+ var mask = createElement('div', {
3330
+ attrs: {
3331
+ 'data-textbus-view': VIEW_MASK
3332
+ },
3333
+ styles: {
3334
+ position: 'absolute',
3335
+ left: 0,
3336
+ right: 0,
3337
+ top: 0,
3338
+ bottom: 0,
3339
+ pointerEvents: 'none'
3340
+ }
3341
+ });
3342
+ var maskWrapper = createElement('div', {
3343
+ styles: {
3344
+ position: 'absolute',
3345
+ left: 0,
3346
+ right: 0,
3347
+ top: 0,
3348
+ bottom: 0,
3349
+ margin: '0 -2px',
3350
+ zIndex: 1,
3351
+ pointerEvents: 'none',
3352
+ overflow: 'hidden'
3353
+ },
3354
+ children: [
3355
+ mask
3356
+ ]
3357
+ });
3358
+ var wrapper = createElement('div', {
3359
+ attrs: {
3360
+ 'data-textbus-view': VIEW_CONTAINER
3361
+ },
3362
+ styles: {
3363
+ display: 'flex',
3364
+ minHeight: '100%',
3365
+ position: 'relative',
3366
+ flexDirection: 'column'
3367
+ },
3368
+ children: [
3369
+ maskWrapper
3370
+ ]
3371
+ });
3372
+ return {
3373
+ wrapper: wrapper,
3374
+ mask: mask
3375
+ };
3376
+ }
3377
+ }
3378
+ ]);
3379
+ return BrowserModule;
3380
+ }();
3381
+
3382
+ exports.BrowserModule = BrowserModule;
3383
+ exports.CollaborateSelectionAwarenessDelegate = CollaborateSelectionAwarenessDelegate;
3384
+ exports.DomAdapter = DomAdapter;
3385
+ exports.EDITOR_OPTIONS = EDITOR_OPTIONS;
3386
+ exports.Input = Input;
3387
+ exports.VIEW_CONTAINER = VIEW_CONTAINER;
3388
+ exports.VIEW_DOCUMENT = VIEW_DOCUMENT;
3389
+ exports.VIEW_MASK = VIEW_MASK;
3390
+ exports.createElement = createElement;
3391
+ exports.getLayoutRectByRange = getLayoutRectByRange;
3392
+ exports.isFirefox = isFirefox;
3393
+ exports.isMac = isMac;
3394
+ exports.isMobileBrowser = isMobileBrowser;
3395
+ exports.isSafari = isSafari;
3396
+ exports.isWindows = isWindows;
22
3397
  //# sourceMappingURL=index.js.map