superdoc 2.0.0-next.52 → 2.0.0-next.53
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/chunks/{create-super-doc-ui-CMnnWkHC.cjs → create-super-doc-ui-BWFYti_W.cjs} +1 -4
- package/dist/chunks/{create-super-doc-ui-9N3-Jxnj.es.js → create-super-doc-ui-Bqkk1Ios.es.js} +1 -4
- package/dist/collaboration-upgrade-engine.cjs +1 -1
- package/dist/collaboration-upgrade-engine.es.js +1 -1
- package/dist/public/ui-react.cjs +1 -1
- package/dist/public/ui-react.es.js +1 -1
- package/dist/public/ui.cjs +1 -1
- package/dist/public/ui.es.js +1 -1
- package/dist/superdoc.cjs +2 -2
- package/dist/superdoc.es.js +2 -2
- package/dist-cdn/superdoc.min.js +7 -7
- package/package.json +2 -2
package/dist-cdn/superdoc.min.js
CHANGED
|
@@ -9,9 +9,9 @@ ${n.toString()}`)};var ox=class{constructor(e){this.patterns=[],this.$state=e}if
|
|
|
9
9
|
`).replace(ET,`
|
|
10
10
|
`).replace(IT,"").replace(xT,"")).replace(/\n{3,}/g,`
|
|
11
11
|
|
|
12
|
-
`).replace(/^\n+/,"").replace(/\n+$/,"")};const ca=Yw("comments",()=>{const e={kind:"story",storyType:"body"},t=x=>{if(!x?.trackedChange)return!1;const D=x?.trackedChangeStory?.storyType;return D==null||D==="body"?!0:x?.trackedChangeAnchorKey?.startsWith?.("tc::body::")===!0},n=x=>x==null?null:e_({storyKey:"body",rawId:String(x)}),r=x=>{if(!x)return null;const D=x.sourceId?String(x.sourceId):"";return D?`word:structural:${D}`:x.id?String(x.id):null},o=nu(),i=zr({name:"comments",readOnly:!1,allowResolve:!0,showResolved:!1}),s=()=>({ok:!1,reason:"read-only-document"}),a=()=>({ok:!1,reason:"resolve-disabled"}),l=()=>i.allowResolve===!1,u=()=>i.readOnly===!0,c=zr({documentMode:"editing",commentsVisible:!1,trackChangesVisible:!1}),d=!1,h={},m=new WeakMap,p=new Map;let g=0;const k=()=>typeof window>"u"?!1:"__labsSuperDocV2PreviewDebug"in window,w=(x,D=null)=>{if(k()){if(D!==null){console.debug("[SuperDoc][comments-store]",x,D);return}console.debug("[SuperDoc][comments-store]",x)}},S=Bh,y=ne(!1),C=ne(!1),T=ne(null),R=ne(!1),M=ne(null),H=ne(null),B=ne(null),z=ne([]),Z=ne([]),P=new Set([]),N=ne(!0),I=ne(""),L=ne([]);let X=new Map;const te=Se(()=>{const x=_T(L.value,X);return X=x,x}),le=x=>{const D=x?.commentId??null;return(D!=null?te.value.get(D):null)??[x].filter(Boolean)};let fe=new Map;const Fe=Se(()=>{const x=ST(L.value,fe);return fe=x,x}),he=ne(!1),ge=ne([]),ae=ne({}),Ce=ne(!1),oe=ne(0),xe=ne([]),qe=ne([]),et=ne(!1),kt=ne(!1),Ie=ne([]),ze=ne(null),Ve=ne(null),Q=ne(null),_=ne(null),$=Ur(null),F=Se(()=>c.documentMode==="viewing"),j=Se(()=>F.value?c.commentsVisible||c.trackChangesVisible:!0),V=Ur(null),G=x=>{V.value=x??null},J=x=>{const D=x?.activeEditor?.v2Comments??null;return D||V.value},K=x=>x?.activeEditor?.editorVersion===2||V.value!==null,W=Ur(null),ue=x=>{W.value=x??null},be=x=>{const D=x?.activeEditor?.v2TrackedChanges??null;return D||W.value},we=(x={})=>{const D={...i,...x};Object.assign(i,D),N.value=i.suppressInternalExternal||!1,x.comments&&x.comments.length&&(L.value=x.comments?.map(ee=>aa(ee))||[])},Te=x=>x==null?null:String(x),rt=x=>Array.isArray(x)?[...new Set(x.map(D=>Te(D)).filter(Boolean))]:[],nt=x=>{if(!x?.trackedChange)return null;const D=Te(x.trackedChangeAnchorKey);if(D?.startsWith("tc::")){const ie=D.indexOf("::",4);if(ie>4)return D.slice(4,ie)}const ee=x.trackedChangeStory;switch(ee?.storyType){case"body":return"body";case"headerFooterPart":return ee.refId?`hf:${ee.refId}`:null;case"footnote":return ee.noteId?`fn:${ee.noteId}`:null;case"endnote":return ee.noteId?`en:${ee.noteId}`:null;case"textbox":return ee.textboxId?`textbox:${ee.textboxId}`:null;default:return null}},wt=x=>x?.startsWith("hf:part:")?`hf:${x.slice(8)}`:x?.startsWith("headerFooterPart:")?`hf:${x.slice(17)}`:x,Zt=(x,D)=>{const ee=wt(nt(D)),ie=wt(Te(x?.storyKey));return!ee||!ie||ie===ee},Ct=x=>{const D=Te(x);return D?D.startsWith("imported:")?D:`imported:${D}`:null},Ot=x=>{const D=Te(x);if(!D)return{key:null,entry:null};const ee=ae.value||{};if(ee[D]!==void 0)return{key:D,entry:ee[D]};for(const[ie,se]of Object.entries(ee)){const de=Te(se?.key),pe=Te(se?.threadId);if(de===D||pe===D)return{key:ie,entry:se}}return{key:null,entry:null}},Bt=(x,D)=>{if(!x||!D)return!1;const ee=Math.max(Number(x.left),Number(D.left)),ie=Math.min(Number(x.right),Number(D.right)),se=Math.max(Number(x.top),Number(D.top)),de=Math.min(Number(x.bottom),Number(D.bottom));return[ee,ie,se,de].every(Number.isFinite)&&ie>ee&&de>se},on=(x,D)=>{if(!x||!D||x.kind!=="trackedChange"||D.kind!=="trackedChange"||x.storyKey&&D.storyKey&&x.storyKey!==D.storyKey)return!1;const ee=Number(x.pageIndex),ie=Number(D.pageIndex);if(Number.isFinite(ee)&&Number.isFinite(ie)&&ee!==ie)return!1;if(Bt(x.bounds,D.bounds))return!0;const se=Number(x.start),de=Number(x.end),pe=Number(D.start),ve=Number(D.end);return[se,de,pe,ve].every(Number.isFinite)&&se===pe&&de===ve},Fn=x=>{const{entry:D}=Ot(x);if(!D)return null;const ee=L.value.filter(ie=>ie?.trackedChange?Dt(ie).some(se=>{const{entry:de}=Ot(se);return on(D,de)}):!1);return ee.length===1?ee[0]:null},Vt=x=>x==null?null:L.value.find(D=>D.commentId==x||D.importedId==x||D.trackedChangeAnchorKey==x||D?.trackedChange&&Ct(D.importedId)==x)||Fn(x),We=x=>x?.parentCommentId?Vt(x.parentCommentId):x,St=x=>x?.trackedChangeThreadParentId?x.trackedChangeThreadParentId:hp(x)&&x?.trackedChange===!0?null:pp(x),Nt=x=>{const D=St(x);return D?!!Vt(D)?.trackedChange:!1},cn=x=>{if(!x)return null;const D=ae.value||{};if(typeof x=="string"){if(D[x])return x;const pe=Vt(x);if(!pe)return x;const ve=pe.commentId??null,Xe=pe.importedId??null,Qe=pe.trackedChange?Ct(Xe):null,tt=pe.trackedChangeAnchorKey??null;return tt&&D[tt]?tt:ve&&D[ve]?ve:Xe&&D[Xe]?Xe:Qe&&D[Qe]?Qe:tt??ve??Qe??Xe??null}const ee=x.commentId??null,ie=x.importedId??null,se=x.trackedChange?Ct(ie):null,de=x.trackedChangeAnchorKey??null;return de&&D[de]?de:ee&&D[ee]?ee:ie&&D[ie]?ie:se&&D[se]?se:de??ee??se??ie??null},Dt=x=>{if(x==null)return[];const D=typeof x=="object"?null:x,ee=typeof x=="object"?x:Vt(x),ie=ee?.trackedChange?rt(ee?.trackedChangePositionAliases):[],se=wt(nt(ee)),de=new Set;return[D,cn(ee),ee?.trackedChangeAnchorKey,ee?.commentId,ee?.importedId,ee?.trackedChange?Ct(ee?.importedId):null,...ie.flatMap(pe=>[se&&!pe.startsWith("tc::")?e_({storyKey:se,rawId:pe}):null,pe])].map(pe=>Te(pe)).filter(pe=>!pe||de.has(pe)?!1:(de.add(pe),!0))},un=(x,D)=>{const ee=ae.value||{},ie=typeof x=="object"?x:Vt(x),se=new Set;for(const de of[D,...Dt(x)].map(pe=>Te(pe)).filter(Boolean)){if(se.has(de))continue;se.add(de);const pe=ee[de];if(pe!==void 0&&Zt(pe,ie))return{key:de,entry:pe}}return{key:null,entry:null}},Ft=x=>{x&&((x.resolvedTime!=null||x.resolvedById!=null||x.resolvedByEmail!=null||x.resolvedByName!=null)&&m.set(x,{resolvedTime:x.resolvedTime??null,resolvedById:x.resolvedById??null,resolvedByEmail:x.resolvedByEmail??null,resolvedByName:x.resolvedByName??null,trackedChangeDecision:x.trackedChangeDecision??null}),x.resolvedTime=null,x.resolvedById=null,x.resolvedByEmail=null,x.resolvedByName=null,x.trackedChangeDecision=null)},Me=x=>{if(!x)return!1;const D=m.get(x);return D?(x.resolvedTime=D.resolvedTime??Date.now(),x.resolvedById=D.resolvedById??null,x.resolvedByEmail=D.resolvedByEmail??null,x.resolvedByName=D.resolvedByName??null,x.trackedChangeDecision=D.trackedChangeDecision??null,!0):!1},Pe=x=>typeof x?.getValues=="function"?x.getValues():{...x},Ze=x=>{const D=x?.selection?.source;return D==null?!0:D===tu},ot=x=>!!x?.trackedChange||!!St(x),Mt=({documentId:x,editor:D}={})=>{if(!D?.state||!L.value?.length)return 0;const ee=ae.value||{};if(!Object.keys(ee).length)return 0;const ie=it=>it.find(dn=>ee[dn]!==void 0)??null,se=new Set,de=new Map;if(L.value.forEach(it=>{if(!it?.trackedChange)return;if(x){const Bn=it?.fileId??null;if(Bn&&Bn!==x)return}const dn=Dt(it),rn=ie(dn);rn&&(se.add(rn),de.set(rn,new Set(dn)))}),!se.size)return 0;const pe=new Set(la.getTrackChanges(D.state).map(({mark:it})=>it?.attrs?.id).filter(it=>it!=null).map(it=>String(it))),ve=typeof iu=="function"?iu(D):null;let Xe=[];try{Xe=ve?.getAll?.()??[]}catch{}const Qe=new Set(Xe.map(it=>it?.anchorKey).filter(it=>typeof it=="string"&&it.length>0)),tt=new Set(Array.from(se).filter(it=>{const dn=de.get(it)??new Set([it]);return Array.from(dn).some(rn=>Qe.has(rn))?!1:!Array.from(dn).some(rn=>pe.has(rn))}));if(!tt.size)return 0;const st=new Set;tt.forEach(it=>{(de.get(it)??new Set([it])).forEach(dn=>st.add(dn))});const vt=new Set(tt);L.value.forEach(it=>{const dn=ie(Dt(it));dn&&[St(it),it?.threadingParentCommentId,it?.parentCommentId].map(rn=>Te(rn)).filter(Boolean).some(rn=>st.has(rn))&&vt.add(dn)});const pt={...ee};if(vt.forEach(it=>{delete pt[it]}),ae.value=pt,M.value!==void 0&&M.value!==null){const it=Vt(M.value),dn=new Set(Dt(it??M.value)),rn=[St(it),it?.threadingParentCommentId,it?.parentCommentId].map(Bn=>Te(Bn)).filter(Boolean);(Array.from(dn).some(Bn=>st.has(Bn))||rn.some(Bn=>st.has(Bn)))&&Wr()}return vt.size},Et=x=>{const D=x?.state?.doc;if(!D||typeof D.descendants!="function")return null;const ee=new Set,ie=new Set;return D.descendants(se=>{se.marks?.filter(ve=>ve?.type?.name==="commentMark").forEach(ve=>{[ve.attrs?.commentId,ve.attrs?.importedId].map(Xe=>Te(Xe)).filter(Boolean).forEach(Xe=>ee.add(Xe))});const de=se.type?.name;if(de!=="commentRangeStart"&&de!=="commentRangeEnd")return;const pe=Te(se.attrs?.["w:id"]);pe&&ie.add(pe)}),{liveMarkIds:ee,resolvedAnchorIds:ie}},sn=()=>{const x=o.documents;if(!Array.isArray(x))return null;for(const D of x){const ee=typeof D?.getEditor=="function"?D.getEditor():null;if(ee?.state?.doc)return ee}return null},Tt=({editor:x}={})=>{if(V.value)return 0;const D=Et(x??sn()),ee=ae.value||{},ie=new Set(Object.keys(ee));if(!D&&!ie.size)return 0;let se=0;return L.value.forEach(de=>{if(!Ze(de)||ot(de))return;if(D){const ve=Dt(de),Xe=ve.some(tt=>D.liveMarkIds.has(tt)),Qe=ve.some(tt=>D.resolvedAnchorIds.has(tt));if(Xe&&de.resolvedTime!=null){Ft(de),se+=1;return}!Xe&&Qe&&de.resolvedTime==null&&Me(de)&&(se+=1);return}const{key:pe}=un(de);pe&&ie.has(String(pe))&&de.resolvedTime!=null&&(Ft(de),se+=1)}),se};Pt(ae,()=>{Tt()}),Pt(L,()=>{Tt()},{deep:!1});const ur=x=>{if(!x)return null;const D=x.start??x.pos??x.from,ee=x.end??x.to??D;return!Number.isFinite(D)||!Number.isFinite(ee)?null:{start:D,end:ee}},dr=x=>un(x).entry??null,jr=(x,D={})=>{const ee=typeof x=="object"?x:Vt(x);if(!ee)return null;const ie=ur(un(x).entry??null);if(!ie)return null;const se=o.getDocument(ee.fileId)?.getEditor?.()?.state?.doc;if(!se?.textBetween)return null;const de=D.separator??" ",pe=se.textBetween(ie.start,ie.end,de,de);return D.trim===!1?pe:pe?.trim()},$t=(x,D={})=>{const ee=dr(x);return ee?{position:ee,anchoredText:jr(x,D)}:null},Vn=x=>{if(!F.value)return!0;const D=We(x);return!D&&x?.parentCommentId?!1:D?.trackedChange||St(x)?c.trackChangesVisible:c.commentsVisible},Mr=(x,D)=>{const ee=x?.activeEditor,ie=J(x);if(D==null){if(Wr(),ie){ie.setActiveComment(null);return}ee?.commands?.setActiveComment({commentId:null});return}const se=Vt(D);if(se){if(M.value=se.commentId,Pu(se.commentId),ie){ie.setActiveComment(se.commentId);return}ee?.commands?.setActiveComment({commentId:M.value})}},_r=({superdoc:x,params:D,broadcastChanges:ee=!0,documentState:ie=void 0})=>{const se=QC("store.trackedChanges.handleUpdate","store-reconciliation",{event:D?.event??null,changeId:D?.changeId??null,documentId:D?.documentId??null});try{const{event:de,changeId:pe,trackedChangeText:ve,trackedChangeType:Xe,trackedChangeDisplayType:Qe,semanticColorKey:tt,semanticColor:st,deletedText:vt,trackedChangeLabel:pt,trackedChangeDetailLines:it,trackedChangeImagePreview:dn,authorId:rn,authorEmail:Bn,authorImage:Gn,date:Wn,author:vo,importedAuthor:Hn,documentId:Mn,coords:Zn,trackedChangeStory:bt,trackedChangeStoryKind:zt,trackedChangeStoryLabel:Kn,trackedChangeAnchorKey:oo,trackedChangeCanonicalId:fr,trackedChangePositionAliases:$i,importedId:gi}=D,yo=pe!=null?String(pe):null,wl=fr!=null?String(fr):null,Ps=Object.prototype.hasOwnProperty.call(D,"trackedChangePositionAliases"),oi=Ps?rt($i):void 0,vi=Object.prototype.hasOwnProperty.call(D,"importedId"),io=vi?gi!=null?String(gi):null:void 0,Do=Mn!=null?String(Mn):null;if(!(Qe==="tableInsert"||Qe==="tableDelete")&&yo){const Qt=Do??(x?.activeEditor?.options?.documentId!=null?String(x.activeEditor.options.documentId):null),Ln=Qt?o.getDocument(Qt)?.getEditor?.():null,Nn=ie!==void 0?ie:Ln?.state??x?.activeEditor?.state??null;if(Nn){const{ranges:Mi,ids:ns}=fc(Nn),Sa=la.getTrackChanges(Nn,yo),Li=Mi.length>0&&Sa.length>0&&vl(Sa,Mi),Po=Sa.length===0&&ns.has(yo);if(Li||Po){Ti({suppressedIds:new Set([yo]),activeDocumentId:Qt,superdoc:x,broadcastChanges:ee});return}}}const yi=bt!==void 0||zt!==void 0||Kn!==void 0||oo!==void 0,Vo=yi?bt??null:e,Cl=yi?zt??null:"body",es=yi&&Kn!==void 0?Kn:"",Ri=oo!==void 0?oo??null:yi?null:n(yo),Os=typeof pt=="string"&&pt.length>0?pt:null,bo=MT(it),ts=DT(dn),Ou=Fr({documentId:Mn,commentId:pe,trackedChange:!0,trackedChangeText:ve,trackedChangeType:Xe,trackedChangeDisplayType:Qe,semanticColorKey:tt,semanticColor:st,deletedText:vt,trackedChangeLabel:Os,trackedChangeDetailLines:bo,trackedChangeImagePreview:ts,createdTime:Wn,creatorId:rn??null,creatorName:vo,creatorEmail:Bn,creatorImage:Gn,isInternal:!1,importedAuthor:Hn,...vi?{importedId:io}:{},trackedChangeStory:Vo,trackedChangeStoryKind:Cl,trackedChangeStoryLabel:es,trackedChangeAnchorKey:Ri,trackedChangeCanonicalId:wl,...Ps?{trackedChangePositionAliases:oi}:{},selection:{source:tu,selectionBounds:Zn}}),_l=()=>{const Qt=Ri!=null?String(Ri):null;if(!yo)return null;const Ln=Nn=>{if(!Nn)return!1;const Mi=Nn.trackedChangeAnchorKey!=null?String(Nn.trackedChangeAnchorKey):null,ns=Nn.commentId!=null?String(Nn.commentId):null,Sa=Nn.importedId!=null?String(Nn.importedId):null,Li=Nn.trackedChangeCanonicalId!=null?String(Nn.trackedChangeCanonicalId):null,Po=wl&&wl!==yo||Li&&Li!==ns;return ns===yo||!Po&&(Sa===yo||io!==void 0&&io!=null&&Sa===io)?!0:Po?!1:Qt&&Mi?Mi===Qt:!1};return Do?L.value.find(Nn=>Ln(Nn)&&Lo(Nn,Do)):L.value.find(Ln)},_a=Qt=>{ee&&(jl(x,Qt),Ei(pe,Qt,x))},dt=(Qt,Ln,Nn)=>Qt?.[Ln]==null&&Nn==null||!Qt||t_(Qt[Ln],Nn)?!1:(Qt[Ln]=Nn,!0),Fu=Qt=>{if(!Qt)return!1;let Ln=!1;return Vo!=null&&(Ln=dt(Qt,"trackedChangeStory",Vo)||Ln),Cl!=null&&(Ln=dt(Qt,"trackedChangeStoryKind",Cl)||Ln),es!==void 0&&es!==""&&(Ln=dt(Qt,"trackedChangeStoryLabel",es)||Ln),Ri!=null&&(Ln=dt(Qt,"trackedChangeAnchorKey",Ri)||Ln),Ln},qt=Qt=>{const Ln={trackedChangeText:ve??null,trackedChangeType:Xe??null,trackedChangeDisplayType:Qe??null,semanticColorKey:tt??null,semanticColor:st??null,deletedText:vt??null,trackedChangeLabel:Os,trackedChangeImagePreview:ts,trackedChangeCanonicalId:wl,creatorId:rn??null,creatorName:vo??null,creatorEmail:Bn??null,creatorImage:Gn??null,createdTime:Wn??null};vi&&(Ln.importedId=io),Ps&&(Ln.trackedChangePositionAliases=oi);let Nn=!1;for(const[Mi,ns]of Object.entries(Ln))Nn=dt(Qt,Mi,ns)||Nn;return Qt&&!(Qt.trackedChangeDetailLines==null&&bo==null)&&!LT(Qt.trackedChangeDetailLines,bo)&&(Qt.trackedChangeDetailLines=bo,Nn=!0),Fu(Qt)||Nn},pc=Qt=>{const Ln=!!(Qt.resolvedTime||Qt.resolvedById||Qt.resolvedByEmail||Qt.resolvedByName);return Ln&&Ft(Qt),qt(Qt)||Ln};if(de==="add"){const Qt=_l();if(Qt){if(!pc(Qt))return;_a({type:S.UPDATE,comment:Pe(Qt)});return}Jo({superdoc:x,comment:Ou,broadcastChanges:ee})}else if(de==="update"){const Qt=_l();if(!Qt||!pc(Qt))return;_a({type:S.UPDATE,comment:Pe(Qt)})}else if(de==="resolve"){const Qt=_l(),Ln={id:D.resolvedById??x?.user?.id??null,email:D.resolvedByEmail??x?.user?.email??null,name:D.resolvedByName??x?.user?.name??null,decision:D.decision??null,superdoc:x};Qt&&!Qt.resolvedTime&&Qt.resolveComment({...Ln,reconciliationToken:VC})}}finally{Zd(se)}},po=(x=[])=>({insertedMark:x.find(({mark:D})=>D?.type?.name==="trackInsert")?.mark??null,deletionMark:x.find(({mark:D})=>D?.type?.name==="trackDelete")?.mark??null,formatMark:x.find(({mark:D})=>D?.type?.name==="trackFormat")?.mark??null}),Kt=({superdoc:x,editor:D,changeIds:ee,broadcastChanges:ie=!0})=>{if(!x||!D?.state||!Array.isArray(ee)||!ee.length)return;const se=D?.options?.documentId!=null?String(D.options.documentId):null;if(se)for(const de of new Set(ee.map(pe=>pe!=null?String(pe):null).filter(Boolean))){const pe=la.getTrackChanges(D.state,de);if(!pe.length)continue;const ve=Hy({event:"update",marks:po(pe),nodes:[],newEditorState:D.state,documentId:se,trackedChangesForId:pe});ve&&(ve.trackedChangeStory=e,ve.trackedChangeStoryKind="body",ve.trackedChangeStoryLabel="",ve.trackedChangeAnchorKey=n(ve.changeId??de),_r({superdoc:x,params:ve,broadcastChanges:ie}))}},yn=(x=null,D=null,ee=null)=>{const ie=Number.isFinite(x);ze.value=ie?x:null,Ve.value=ie&&D!=null?String(D):null;const se=ee??D;Q.value=ie&&se!=null?String(se):null},xo=()=>{const x=ze.value;return Number.isFinite(x)?x:null},Zo=()=>{ze.value=null,Ve.value=null,Q.value=null},Ei=(x,D,ee,ie=1e3)=>{h[x]&&clearTimeout(h[x]),h[x]=setTimeout(()=>{ee&&ee.emit("comments-update",D),delete h[x]},ie)},pi=(x,D)=>{if(D?.source!=="document-editor")return null;const ee=D?.documentId??null,ie=x?.activeEditor?.options?.documentId??null;if(!ee||!ie||ee!==ie)return null;let se;try{se=x?.activeEditor?.doc?.selection?.current}catch{return null}if(typeof se!="function")return null;try{return se()}catch{return null}},Ss=(x,D=null)=>{const ee=J(x),ie=pi(x,o.activeSelection),se={type:S.PENDING,pendingSelection:ie};if(x.emit("comments-update",se),ee){const pe=ee.getCapabilityState?.();return pe&&pe.canWrite===!1?{ok:!1,reason:pe.reason}:Promise.resolve(ee.captureCurrentSelection?.()).then(ve=>{if(!ve?.ok)return{ok:!1,reason:ve?.reason??"editing-range-required",detail:ve?.detail};$.value=ve.target??null;const Xe=ee.documentId??x?.activeEditor?.options?.documentId??null;return _.value=Fr({selection:{source:tu,documentId:Xe,page:1,selectionBounds:{}},documentId:Xe,parentCommentId:null}),x.config.isInternal||(_.value.isInternal=!1),yn(D,"pending"),Ji(null),M.value=_.value.commentId,{ok:!0}}).catch(ve=>({ok:!1,reason:"selection-capture-failed",detail:ve?.message??String(ve)}))}const de={...o.activeSelection};return de.selectionBounds={...de.selectionBounds},o.selectionPosition?.source&&o.selectionPosition.source!=="pdf"&&(o.selectionPosition.source=null),_.value=Fr({selection:de,documentId:de.documentId,parentCommentId:null}),x.config.isInternal||(_.value.isInternal=!1),x.activeEditor?.commands&&x.activeEditor.commands.insertComment({..._.value.getValues(),commentId:"pending",skipEmit:!0}),_.value.selection.source==="document-editor"&&o.selectionPosition&&(o.selectionPosition.source=tu),yn(D,"pending"),Ji(null),M.value=_.value.commentId,{ok:!0}},ks=x=>{const D=un(x).entry;return D?Number.isFinite(D.start)?D.start:Number.isFinite(D.pos)?D.pos:Number.isFinite(D.from)?D.from:Number.isFinite(D.to)?D.to:Number.isFinite(D.pageIndex)&&Number.isFinite(D?.bounds?.top)?D.pageIndex*1e6+D.bounds.top:null:null},As=(x,D)=>(x.createdTime??0)-(D.createdTime??0),al=(x,D)=>{const ee=ks(x),ie=ks(D),se=Number.isFinite(ee),de=Number.isFinite(ie);return se&&de&&ee!==ie?ee-ie:se&&!de?-1:!se&&de?1:As(x,D)},Wi=x=>{const D=[],ee=[],ie=new Map;return L.value.forEach(se=>{if(!Vn(se))return;const de=Nt(se)?St(se):null,pe=se.parentCommentId||de;se.resolvedTime?ee.push(se):!pe&&!se.resolvedTime?D.push({...se}):pe&&(ie.has(pe)||ie.set(pe,[]),ie.get(pe).push(se))}),{parentComments:D.sort(x),resolvedComments:ee.sort(x)}},ro=Se(()=>Wi(As)),ke=Se(()=>ro.value?.parentComments.some(x=>x.trackedChange&&!x.resolvedTime)??!1),Oe=Se(()=>Wi(al)),ht=x=>P.includes(x),lt=Se(()=>o.documents),bn=Se(()=>i),an=(x,D)=>{const ee=x.getContainerLocation(D);return{top:ee.top+x.selectionBounds.top,left:ee.left+x.selectionBounds.left}},Fr=({selection:x,documentId:D,parentCommentId:ee,...ie})=>mo({selection:x,documentId:D,parentCommentId:ee,...ie}),mo=({selection:x,documentId:D,parentCommentId:ee,...ie})=>{let se;return D?se=o.getDocument(D):x&&(se=o.getDocument(x.documentId)),se||(se=o.documents[0]),aa({fileId:se.id,fileType:se.type,parentCommentId:ee,creatorId:o.user.id,creatorEmail:o.user.email,creatorName:o.user.name,creatorImage:o.user.image,commentText:I.value,selection:x,...ie})},go=x=>{const D=!!_.value;I.value="",_.value=null,$.value=null,o.selectionPosition=null,D&&Wr(),!K(x)&&x?.activeEditor?.commands?.removeComment({commentId:"pending"})},To=({superdoc:x,comment:D,skipEditorUpdate:ee=!1,broadcastChanges:ie=!0,isHydration:se=!1})=>{if(u()&&!se)return s();const de=!ee&&!se?J(x):null;if(de&&!D.trackedChange){const Qe=Uy(_.value?I.value:D.commentText),tt=_.value?$.value:null,st=D.parentCommentId?String(D.parentCommentId):(_.value,null);return(async()=>{try{return await(st?de.reply({parentCommentId:st,text:Qe}):de.commitPendingComment({text:Qe,target:tt}))}catch(vt){return{ok:!1,reason:"adapter-threw",detail:vt?.message??String(vt)}}})().then(vt=>{if(!Uo(de))return{ok:!1,reason:"adapter-stale"};if(!vt?.ok)return ie&&x.emit("comments-update",{type:S.PENDING,rejected:!0,reason:vt?.reason??"v2-create-failed",...vt?.committed?{committed:!0}:{}}),vt;const pt=qi({superdoc:x,adapter:de,documentId:de.documentId,items:vt.items});return _.value&&go(x),ie&&x.emit("comments-update",{type:S.ADD,comment:pt?.added?.getValues?.()??null}),{ok:!0,comment:pt?.added??null}})}let pe=L.value.find(Qe=>Qe.commentId===M.value);pe||(pe=D);const ve=aa(D.getValues());_.value?ve.setText({text:I.value,suppressUpdate:!0}):ve.setText({text:D.commentText,suppressUpdate:!0}),ve.selection.source=_.value?.selection?.source??ve.selection.source,pe&&(ve.isInternal=pe.isInternal),x.config.isInternal||(ve.isInternal=!1),L.value.push(ve),go(x),!ee&&!D.trackedChange&&x.activeEditor?.commands&&!D.parentCommentId&&x.activeEditor.commands.insertComment({...ve.getValues(),skipEmit:!0});const Xe={type:S.ADD,comment:ve.getValues()};return ie&&(jl(x,Xe),x.emit("comments-update",Xe)),{ok:!0,comment:ve}},Is=({superdoc:x,comment:D,skipEditorUpdate:ee=!1,broadcastChanges:ie=!0})=>To({superdoc:x,comment:D,skipEditorUpdate:ee,broadcastChanges:ie}),Jo=({superdoc:x,comment:D,skipEditorUpdate:ee=!1,broadcastChanges:ie=!0})=>To({superdoc:x,comment:D,skipEditorUpdate:ee,broadcastChanges:ie,isHydration:!0}),Ro=({commentId:x,superdoc:D})=>{if(u())return Promise.resolve(s());const ee=L.value.findIndex(tt=>tt.commentId===x),ie=L.value[ee];if(!ie)return Promise.resolve({ok:!1,reason:"comment-not-found"});const{commentId:se,importedId:de}=ie,{fileId:pe}=ie,ve=J(D);if(ve&&!ie.trackedChange)return(async()=>{try{return await ve.delete({commentId:se})}catch(tt){return{ok:!1,reason:"adapter-threw",detail:tt?.message??String(tt)}}})().then(tt=>Uo(ve)?tt?.ok?(qi({superdoc:D,adapter:ve,documentId:ve.documentId??pe,items:tt.items}),D.emit("comments-update",{type:S.DELETED,comment:ie.getValues(),changes:[{key:"deleted",commentId:se,fileId:pe}]}),{ok:!0}):(D.emit("comments-update",{type:S.DELETED,rejected:!0,comment:ie.getValues(),reason:tt?.reason??"v2-delete-failed",...tt?.committed?{committed:!0}:{}}),tt):{ok:!1,reason:"adapter-stale"});D.activeEditor?.commands?.removeComment({commentId:se,importedId:de}),L.value.splice(ee,1);const Xe=L.value.filter(tt=>tt.parentCommentId===se).map(tt=>tt.commentId||tt.importedId);L.value=L.value.filter(tt=>!Xe.includes(tt.commentId)),(M.value===se||Xe.includes(M.value))&&Wr();const Qe={type:S.DELETED,comment:ie.getValues(),changes:[{key:"deleted",commentId:se,fileId:pe}]};return D.emit("comments-update",Qe),jl(D,Qe),Promise.resolve({ok:!0})},Ki=async({superdoc:x,adapter:D,fileId:ee,operation:ie,eventType:se,rejectionFallbackReason:de,rejectionEventExtras:pe={},validateOutcome:ve,successEventBuilder:Xe})=>{let Qe;try{Qe=await ie()}catch(pt){Qe={ok:!1,reason:"adapter-threw",detail:pt?.message??String(pt)}}if(!Uo(D))return{ok:!1,reason:"adapter-stale"};if(!Qe?.ok){const pt={type:se,rejected:!0,reason:Qe?.reason??de,...Qe?.committed?{committed:!0}:{},...Qe?.code!==void 0?{code:Qe.code}:{},...Qe?.detail!==void 0?{detail:Qe.detail}:{},...pe};return x?.emit?.("comments-update",pt),Qe}const tt=ve?.({outcome:Qe});if(tt?.ok===!1){const pt={ok:!1,committed:tt.committed??!0,reason:tt.reason??de,...tt.code!==void 0?{code:tt.code}:{},...tt.detail!==void 0?{detail:tt.detail}:{}},it={type:se,rejected:!0,reason:pt.reason,...pt.committed?{committed:!0}:{},...pt.code!==void 0?{code:pt.code}:{},...pt.detail!==void 0?{detail:pt.detail}:{},...pe};return x?.emit?.("comments-update",it),pt}const st=qi({superdoc:x,adapter:D,documentId:D.documentId??ee,items:Qe.items??[]}),vt=Xe?.({outcome:Qe,reconciled:st})??null;return vt&&x?.emit?.("comments-update",vt),{ok:!0,items:Qe.items??[],reconciled:st}},Gr=({outcome:x,adapter:D,fileId:ee})=>(x.items??[]).map(ie=>D.mapV2CommentToUseCommentInput(ie,{fileId:ee,fileType:null})).filter(Boolean),Sr=x=>{const D=x?.commentId??x?.importedId;return D!=null?String(D):null},Mo=x=>x?.parentCommentId!=null?String(x.parentCommentId):null,Ho=({outcome:x,adapter:D,fileId:ee,commentId:ie,expectedResolved:se,operation:de})=>{const pe=ie!=null?String(ie):null,ve=Gr({outcome:x,adapter:D,fileId:ee}),Xe=ve.find(it=>Sr(it)===pe)??null,Qe=Xe?.parentCommentId?ve.find(it=>Sr(it)===Mo(Xe))??null:Xe,tt=Sr(Qe);if(!Qe||!tt)return{ok:!1,reason:`v2-${de}-refresh-missing`,detail:`comment ${pe} was absent from the refreshed v2 comment list after ${de}`};const st=[Qe,...ve.filter(it=>Mo(it)===tt)],vt=it=>!!it?.resolvedTime;if(st.filter(it=>vt(it)!==se).length===0)return{ok:!0};const pt=vt(Qe);return st.some(it=>vt(it)!==pt)?{ok:!1,reason:`v2-${de}-refresh-split-thread`,detail:{rootId:tt,expected:se?"resolved":"open",observed:st.map(it=>({commentId:Sr(it),parentCommentId:Mo(it),status:vt(it)?"resolved":"open"}))}}:{ok:!1,reason:se?`v2-${de}-refresh-still-open`:`v2-${de}-refresh-still-resolved`,detail:`comment ${tt} remained ${pt?"resolved":"open"} after ${de}`}},$o=async({superdoc:x,parentCommentId:D,text:ee}={})=>{if(u())return s();const ie=J(x);if(!ie)return{ok:!1,reason:"v2-comments-adapter-missing"};const se=D!=null?String(D):null;if(!se)return{ok:!1,reason:"parent-comment-id-missing"};const de=Uy(ee);if(de.length===0)return{ok:!1,reason:"comment-text-empty"};const pe=L.value.find(ve=>String(ve.commentId)===se);return Ki({superdoc:x,adapter:ie,fileId:pe?.fileId??ie.documentId??null,operation:()=>ie.reply({parentCommentId:se,text:de}),eventType:S.ADD,rejectionFallbackReason:"v2-reply-failed",rejectionEventExtras:pe?{comment:Pe(pe)}:{},successEventBuilder:({reconciled:ve})=>({type:S.ADD,comment:ve?.added?.getValues?.()??null})})},ll=async({superdoc:x,commentId:D,text:ee}={})=>{if(u())return s();const ie=J(x);if(!ie)return{ok:!1,reason:"v2-comments-adapter-missing"};const se=D!=null?String(D):null;if(!se)return{ok:!1,reason:"comment-id-missing"};const de=Uy(ee);if(de.length===0)return{ok:!1,reason:"comment-text-empty"};const pe=L.value.find(ve=>String(ve.commentId)===se);return Ki({superdoc:x,adapter:ie,fileId:pe?.fileId??ie.documentId??null,operation:()=>ie.edit({commentId:se,text:de}),eventType:S.UPDATE,rejectionFallbackReason:"v2-edit-failed",rejectionEventExtras:pe?{comment:Pe(pe),changes:[{key:"text",value:de}]}:{},successEventBuilder:()=>{const ve=L.value.find(Xe=>String(Xe.commentId)===se)??pe;return ve?{type:S.UPDATE,comment:Pe(ve),changes:[{key:"text",value:ve.commentText??de}]}:null}})},oc=async({superdoc:x,commentId:D}={})=>{if(u())return s();if(l())return a();const ee=J(x);if(!ee)return{ok:!1,reason:"v2-comments-adapter-missing"};const ie=D!=null?String(D):null;if(!ie)return{ok:!1,reason:"comment-id-missing"};const se=L.value.find(ve=>String(ve.commentId)===ie),de=se?.fileId??ee.documentId??null,pe=await Ki({superdoc:x,adapter:ee,fileId:de,operation:()=>ee.resolve({commentId:ie}),eventType:S.RESOLVED,rejectionFallbackReason:"v2-resolve-failed",rejectionEventExtras:se?{comment:Pe(se)}:{},validateOutcome:({outcome:ve})=>Ho({outcome:ve,adapter:ee,fileId:de,commentId:ie,expectedResolved:!0,operation:"resolve"}),successEventBuilder:()=>{const ve=L.value.find(Xe=>String(Xe.commentId)===ie)??se;return ve?{type:S.RESOLVED,comment:Pe(ve)}:null}});if(pe?.ok){const Xe=!!L.value.find(tt=>String(tt.commentId)===ie)?.resolvedTime,Qe=M.value!=null?String(M.value):null;Xe&&Qe===ie&&Wr()}return pe},kr=async({superdoc:x,commentId:D}={})=>{if(u())return s();if(l())return a();const ee=J(x);if(!ee)return{ok:!1,reason:"v2-comments-adapter-missing"};const ie=D!=null?String(D):null;if(!ie)return{ok:!1,reason:"comment-id-missing"};const se=L.value.find(pe=>String(pe.commentId)===ie),de=se?.fileId??ee.documentId??null;return Ki({superdoc:x,adapter:ee,fileId:de,operation:()=>ee.reopen({commentId:ie}),eventType:S.UPDATE,rejectionFallbackReason:"v2-reopen-failed",rejectionEventExtras:se?{comment:Pe(se),changes:[{key:"resolvedTime",value:null}]}:{},validateOutcome:({outcome:pe})=>Ho({outcome:pe,adapter:ee,fileId:de,commentId:ie,expectedResolved:!1,operation:"reopen"}),successEventBuilder:()=>{const pe=L.value.find(ve=>String(ve.commentId)===ie);return!pe||pe.resolvedTime?null:{type:S.UPDATE,comment:Pe(pe),changes:[{key:"resolvedTime",value:null}]}}})},Uo=x=>x?V.value===x:!1,xi=x=>x?W.value===x:!1,cl=async({superdoc:x,adapter:D,documentId:ee}={})=>ou("store.comments.hydrateFromV2","comments-list",{documentId:ee??null},async()=>{const ie=D??J(x);if(!ie||typeof ie.refresh!="function")return{ok:!1,reason:"adapter-missing"};let se;try{se=await ie.refresh()}catch(de){return{ok:!1,reason:"adapter-threw",detail:de?.message??String(de)}}return Uo(ie)?se?.ok?(qi({superdoc:x,adapter:ie,documentId:ee,items:se.items??[]}),{ok:!0,items:se.items??[]}):se:{ok:!1,reason:"adapter-stale"}}),qi=({superdoc:x,adapter:D,documentId:ee,items:ie}={})=>ou("store.comments.reconcile","store-reconciliation",{documentId:ee??null,itemCount:Array.isArray(ie)?ie.length:null},()=>{if(!D||!Array.isArray(ie))return{added:null};if(!Uo(D))return{added:null,dropped:"adapter-stale"};const se=ee??D.documentId??null,de=se!=null?String(se):null,pe=(se?o.getDocument(se):null)?.type??null,ve=bt=>typeof bt!="string"?!0:bt.replace(/<[^>]*>/g,"").replace(/ /gi," ").trim().length===0,Xe=bt=>!bt||bt.trackedChange===!0||!bt.trackedChangeThreadParentId||bt.parentCommentId?!1:ve(bt.commentText),Qe=M.value!=null?String(M.value):null,tt=Qe?L.value.find(bt=>String(bt.commentId)===Qe)??null:null,st=tt!=null&&_.value!=null&&(tt===_.value||_.value.commentId!=null&&String(tt.commentId??"")===String(_.value.commentId)),vt=tt!=null&&!st&&tt.trackedChange!==!0&&!hp(tt)&&(de==null||tt.fileId==null||String(tt.fileId)===de),pt=new Map,it=new Map,dn=[];for(const bt of ie){if(YC(bt))continue;const zt=D.mapV2CommentToUseCommentInput(bt,{fileId:se,fileType:pe});if(zt){if(Xe(zt)){it.set(String(zt.commentId),String(zt.trackedChangeThreadParentId)),w("hydrate:drop-v2-sidecar-comment",{commentId:zt.commentId??null,importedId:zt.importedId??null,parentCommentId:zt.parentCommentId??null,trackedChangeParentId:zt.trackedChangeParentId??null,trackedChangeThreadParentId:zt.trackedChangeThreadParentId??null,trackedChangeSide:zt.trackedChangeSide??null,commentText:zt.commentText??null});continue}dn.push(zt)}}for(const bt of dn){const zt=bt.parentCommentId!=null?String(bt.parentCommentId):null,Kn=zt?it.get(zt):null;Kn&&(bt.threadingParentCommentId=Kn,bt.trackedChangeThreadParentId==null&&(bt.trackedChangeThreadParentId=Kn));const oo=bt.commentId!=null?String(bt.commentId):null;oo&&pt.set(oo,bt)}const rn=bt=>{if(de==null)return!0;const zt=bt?.fileId!=null?String(bt.fileId):null;return zt==null?!0:zt===de},Bn=_.value?.commentId!=null?String(_.value.commentId):null,Gn=bt=>!bt||!_.value?!1:bt===_.value||Bn!=null&&String(bt.commentId??"")===Bn,Wn=bt=>!bt||Gn(bt)||bt.trackedChange===!0||hp(bt)?!1:bt.commentId!=null,vo=(bt,zt)=>{bt.commentText=zt.commentText??bt.commentText,bt.isInternal=typeof zt.isInternal=="boolean"?zt.isInternal:bt.isInternal,typeof zt.resolvedTime=="number"?(bt.resolvedTime=zt.resolvedTimeWasSynthesized===!0&&typeof bt.resolvedTime=="number"?bt.resolvedTime:zt.resolvedTime,bt.resolvedByEmail=zt.resolvedByEmail??null,bt.resolvedByName=zt.resolvedByName??null):(bt.resolvedTime=null,bt.resolvedByEmail=null,bt.resolvedByName=null),zt.parentCommentId!==void 0?bt.parentCommentId=zt.parentCommentId:delete bt.parentCommentId,zt.trackedChangeParentId!==void 0?bt.trackedChangeParentId=zt.trackedChangeParentId:delete bt.trackedChangeParentId,zt.trackedChangeThreadParentId!==void 0?bt.trackedChangeThreadParentId=zt.trackedChangeThreadParentId:bt.trackedChangeThreadParentId=void 0,zt.trackedChangeSide!==void 0?bt.trackedChangeSide=zt.trackedChangeSide:delete bt.trackedChangeSide,zt.threadingParentCommentId!==void 0?bt.threadingParentCommentId=zt.threadingParentCommentId:delete bt.threadingParentCommentId},Hn=[],Mn=new Set,Zn=[];for(const bt of L.value){if(!Wn(bt)||!rn(bt)){Hn.push(bt);continue}const zt=String(bt.commentId),Kn=pt.get(zt);Kn&&(vo(bt,Kn),Mn.add(zt),Hn.push(bt))}for(const[bt,zt]of pt.entries()){if(Mn.has(bt))continue;const Kn=aa(zt);Hn.push(Kn),Zn.push(Kn)}return L.value=Hn,vt&&Qe&&!Hn.some(bt=>String(bt.commentId)===Qe)&&Wr(),{added:Zn[Zn.length-1]??null}}),mi=x=>{go(x)},Rf=x=>typeof x!="string"?null:x.replace(/\s*\(imported\)\s*$/u,"").trim()||null,ei=x=>{if(!x)return null;try{if(x.isDestroyed===!0)return null;const D=x.view;if(!D||D.isDestroyed===!0||D.destroyed===!0)return null;const ee=D.state;return ee?{view:D,state:ee}:null}catch{return null}},ul=x=>x!=null&&String(x).length>0?String(x):null,jn=x=>{const D=ul(x),ee=D?[[D,p.get(D)]]:Array.from(p.entries());let ie=0;for(const[se,de]of ee)de&&(p.delete(se),de.timeoutHandle!==null&&de.timeoutHandle!==void 0&&clearTimeout(de.timeoutHandle),ie+=1);return ie},ic=x=>{const D=ei(x);if(!D)return null;let ee=[];try{ee=la.getTrackChanges(D.state)??[]}catch{return null}const ie=la?.enumerateStructuralRowChanges;let se=[];if(typeof ie=="function")try{se=ie(D.state)??[]}catch{se=[]}let de=[];if(typeof iu=="function")try{de=iu(x)?.getAll?.()??[]}catch{de=[]}return{...D,trackedChanges:ee,structuralChanges:se,storySnapshots:de}},wu=(x,D,ee=null)=>{if(!x||!D)return!1;const ie=ee??ic(x);return ie?(_u(x,D,ie.trackedChanges,{editorState:ie.state,editorView:ie.view}),uc({superdoc:D,editor:x,snapshots:ie.storySnapshots,documentState:ie.state,resolveFromEditor:!1}),Iu({superdoc:D,editor:x,structuralChanges:ie.structuralChanges}),!0):!1},ba=x=>{if(!x||p.get(x.documentId)!==x)return!1;try{const D=x.editor?.options?.documentId;if(D!=null&&String(D)!==x.documentId)return!1;const ee=o.getDocument(x.documentId);if(!ee||ee.getEditor?.()!==x.editor)return!1}catch{return!1}return!0},Yi=x=>{if(!ba(x))return p.get(x?.documentId)===x&&p.delete(x.documentId),!1;const D=ic(x.editor);if(!D||!ba(x))return p.get(x.documentId)===x&&p.delete(x.documentId),!1;try{return wu(x.editor,x.superdoc,D)}finally{p.get(x.documentId)===x&&p.delete(x.documentId)}},Es=({editor:x,superdoc:D,documentId:ee,defer:ie=!0})=>{const se=ul(ee);if(!se||!x||!D)return!1;jn(se);const de={documentId:se,editor:x,superdoc:D,generation:++g,timeoutHandle:null};return p.set(se,de),ie?(de.timeoutHandle=setTimeout(()=>{de.timeoutHandle=null,Yi(de)},0),!0):Yi(de)};function dl(x){const D=x!=null?String(x):null;if(!D)return;jn(D);const ee=L.value.filter(de=>hl(de,D,{allowSingleDocumentMismatch:!0}));if(!ee.length)return;const ie=new Set;if(ee.forEach(de=>{Dt(de).forEach(pe=>ie.add(pe))}),L.value=L.value.filter(de=>!ee.includes(de)),ie.size){const de={...ae.value||{}};ie.forEach(pe=>{delete de[pe]}),ae.value=de}const se=M.value!=null?String(M.value):null;se&&ie.has(se)&&Wr()}function Cu(x){dl(x)}const fl=async({superdoc:x,editor:D,comments:ee,documentId:ie,replacedFile:se=!1})=>{const de=o.getDocument(ie);if(de?.commentThreadingProfile&&(de.commentThreadingProfile.value=D?.converter?.commentThreadingProfile||null),se&&Cu(ie),ee.forEach(pe=>{const ve=Array.isArray(pe.elements)?pe.elements:[],Xe=Ff(ve);if(!Xe&&!pe.trackedChange)return;const Qe=Rf(pe.creatorName),tt=Qe?`${Qe} (imported)`:null;Jo({superdoc:x,comment:aa({fileId:ie,fileType:de.type,docxCommentJSON:ve.length?ve:null,commentId:pe.commentId,isInternal:!1,parentCommentId:pe.parentCommentId,trackedChangeParentId:pe.trackedChangeParentId,trackedChangeThreadParentId:pe.trackedChangeThreadParentId,creatorId:null,creatorName:Qe,createdTime:pe.createdTime,creatorEmail:pe.creatorEmail,importedAuthor:{...tt?{name:tt}:{},email:pe.creatorEmail},commentText:Xe,resolvedTime:pe.isDone?Date.now():null,resolvedById:null,resolvedByEmail:pe.isDone?pe.creatorEmail:null,resolvedByName:pe.isDone?tt||"(Imported)":null,trackedChange:pe.trackedChange||!1,trackedChangeText:pe.trackedChangeText,trackedChangeType:pe.trackedChangeType,trackedChangeDisplayType:pe.trackedChangeDisplayType,deletedText:pe.trackedDeletedText,origin:pe.origin||"word",threadingMethod:pe.threadingMethod,threadingStyleOverride:pe.threadingStyleOverride,threadingParentCommentId:pe.threadingParentCommentId,originalXmlStructure:pe.originalXmlStructure})})}),se){Es({editor:D,superdoc:x,documentId:ie,defer:!1});return}Es({editor:D,superdoc:x,documentId:ie})},_u=(x,D,ee=null,ie={})=>{const{reopenResolved:se=!1,refreshExisting:de=!1,broadcastChanges:pe=!0,editorState:ve=null,editorView:Xe=null}=ie,Qe=ve?{state:ve,view:Xe}:ei(x);if(!Qe?.state)return;const tt=Qe.state,st=ee??la.getTrackChanges(tt),vt=tT(st),pt=x?.options?.documentId!=null?String(x.options.documentId):null;if(!pt)return;const it=new Set,dn=new Map;L.value.forEach(Hn=>{if(!Hn?.trackedChange||!Lo(Hn,pt)||!t(Hn))return;const Mn=[Hn.commentId,Hn.importedId].map(Zn=>Zn!=null?String(Zn):null).filter(Boolean);if(Hn.resolvedTime){se||Mn.forEach(Zn=>it.add(Zn));return}Mn.forEach(Zn=>{dn.set(Zn,Hn),de||it.add(Zn)})});const rn=new Map;for(const Hn of st){const Mn=Hn.mark.attrs.id;rn.has(Mn)||rn.set(Mn,[]),rn.get(Mn).push(Hn)}const Bn=pt,Gn=new Set;vt.forEach(({insertedMark:Hn,deletionMark:Mn,formatMark:Zn})=>{const bt=Hn?.mark.attrs.id||Mn?.mark.attrs.id||Zn?.mark.attrs.id;if(bt==null)return;const zt=String(bt);if(Gn.has(zt)||(Gn.add(zt),!de&&it.has(zt)))return;const Kn=dn.get(zt),oo={...Hn&&{insertedMark:Hn.mark},...Mn&&{deletionMark:Mn.mark},...Zn&&{formatMark:Zn.mark}},fr=Hy({event:Kn?"update":"add",marks:oo,nodes:[],newEditorState:tt,documentId:Bn,trackedChangesForId:rn.get(bt)||[]});if(fr){const $i=n(fr.changeId??bt);fr.trackedChangeStory=e,fr.trackedChangeStoryKind="body",fr.trackedChangeStoryLabel="",fr.trackedChangeAnchorKey=$i,_r({superdoc:D,params:fr,broadcastChanges:pe,documentState:tt}),Kn||(it.add(zt),fr.changeId!=null&&it.add(String(fr.changeId)),fr.importedId!=null&&it.add(String(fr.importedId)))}});const Wn=Qe.view;try{if(!Wn||x.view!==Wn||Wn.isDestroyed===!0||Wn.destroyed===!0)return}catch{return}const{tr:vo}=tt;vo.setMeta(kT,{type:"force"}),Wn.dispatch(vo)},Ti=({suppressedIds:x,activeDocumentId:D,superdoc:ee=null,broadcastChanges:ie=!0})=>{if(!(x instanceof Set)||!x.size||!D)return;const se=[];if(L.value=L.value.filter(ve=>{if(!ve?.trackedChange||!t(ve)||Mu(ve)||!Lo(ve,D))return!0;const Xe=ve.commentId!=null?String(ve.commentId):null,Qe=ve.importedId!=null?String(ve.importedId):null;return Xe&&x.has(Xe)||Qe&&x.has(Qe)?(se.push(ve),!1):!0}),!se.length)return;const de=new Set;se.forEach(ve=>{ve.commentId!=null&&de.add(String(ve.commentId)),ve.importedId!=null&&de.add(String(ve.importedId));const Xe=Pe(ve),Qe={type:S.DELETED,comment:Xe,changes:[{key:"deleted",commentId:Xe.commentId,fileId:Xe.fileId}]};ie&&(jl(ee,Qe),ee?.emit?.("comments-update",Qe))});const pe=M.value!=null?String(M.value):null;pe&&de.has(pe)&&Wr()},xs=x=>x?x.fileId!=null?String(x.fileId):x.documentId!=null?String(x.documentId):x.selection?.documentId!=null?String(x.selection.documentId):null:null,Mf=()=>{const x=Array.isArray(o.documents)?o.documents:o.documents?.value;return Array.isArray(x)?x:[]},Ts=()=>{const x=Mf();return x.length!==1?null:x[0]?.id!=null?String(x[0].id):null},hl=(x,D,ee={})=>{const{allowSingleDocumentMismatch:ie=!1}=ee;if(!D)return!1;const se=xs(x);if(se){if(se===D)return!0;const de=Ts();return ie&&de===D}return Ts()===D},Lo=(x,D)=>hl(x,D,{allowSingleDocumentMismatch:!0}),ti=x=>{const D=typeof x=="string"?x.toLowerCase():"";return D?D==="insert"||D==="insertion"||D==="trackinsert"||D==="tableinsert"||D==="paragraphsplit"?"insertion":D==="delete"||D==="deletion"||D==="trackdelete"||D==="tabledelete"?"deletion":D:null},Su=({comment:x,decision:D}={})=>{const ee=D==="accept"||D==="reject"?D:null;if(!ee)return!1;const ie=ti(x?.trackedChangeDisplayType)??ti(x?.trackedChangeType);return ee==="accept"&&ie==="insertion"||ee==="reject"&&ie==="deletion"},ku=(x,D,ee,ie=null,{broadcastChanges:se=!0}={})=>ou("store.trackedChanges.pruneStaleComments","store-reconciliation",{activeDocumentId:ee??null,liveIdCount:x instanceof Set?x.size:null,liveAnchorKeyCount:D instanceof Set?D.size:null},()=>{if(!(x instanceof Set)||!ee)return;const de=new Set,pe=[],ve=[...L.value];if(L.value=L.value.filter(st=>{if(!st?.trackedChange||!Lo(st,ee))return!0;const vt=st.commentId!=null?String(st.commentId):null,pt=st.importedId!=null?String(st.importedId):null,it=st.trackedChangeAnchorKey!=null?String(st.trackedChangeAnchorKey):null,dn=!!(vt&&x.has(vt)),rn=!!(pt&&x.has(pt)),Bn=!!(it&&D?.has(it));if(!vt&&!pt&&!it||dn||rn||Bn||st.resolvedTime)return!0;const Gn=m.get(st);return Gn?(st.resolvedTime=Gn.resolvedTime??Date.now(),st.resolvedById=Gn.resolvedById??null,st.resolvedByEmail=Gn.resolvedByEmail??null,st.resolvedByName=Gn.resolvedByName??null,st.trackedChangeDecision=Gn.trackedChangeDecision??null,pe.push(st),!0):(vt&&de.add(vt),pt&&de.add(pt),!1)}),pe.forEach(st=>{const vt=Pe(st),pt={type:S.UPDATE,comment:vt};se&&(jl(ie,pt),ie?.emit?.("comments-update",pt))}),!de.size)return;let Xe=!0;for(;Xe;)Xe=!1,L.value=L.value.filter(st=>{if(!Lo(st,ee))return!0;const vt=st.parentCommentId!=null?String(st.parentCommentId):null,pt=St(st)!=null?String(St(st)):null;if(!(vt&&de.has(vt)||pt&&de.has(pt))||st.resolvedTime)return!0;const it=st.commentId!=null?String(st.commentId):null,dn=st.importedId!=null?String(st.importedId):null;return it&&de.add(it),dn&&de.add(dn),Xe=!0,!1});ve.filter(st=>{if(!Lo(st,ee))return!1;const vt=st.commentId!=null?String(st.commentId):null,pt=st.importedId!=null?String(st.importedId):null;return vt&&de.has(vt)||pt&&de.has(pt)}).forEach(st=>{const vt=Pe(st),pt={type:S.DELETED,comment:vt,changes:[{key:"deleted",commentId:vt.commentId,fileId:vt.fileId}]};se&&(jl(ie,pt),ie?.emit?.("comments-update",pt))});const Qe=M.value!=null?String(M.value):null,tt=ve.some(st=>{const vt=st.commentId!=null?String(st.commentId):null,pt=st.importedId!=null?String(st.importedId):null;return Lo(st,ee)&&(vt&&vt===Qe||pt&&pt===Qe)});Qe&&de.has(Qe)&&tt&&Wr()}),ni=({superdoc:x,comment:D,decision:ee}={})=>{if(!D?.trackedChange||Su({comment:D,decision:ee}))return 0;const ie=Rs(D);if(!ie.size)return 0;const se={email:x?.user?.email??null,name:x?.user?.name??null,superdoc:x};let de=0;return pl(D).forEach(pe=>{!pe||pe===D||pe.resolvedTime||[St(pe),pe.threadingParentCommentId,pe.parentCommentId].map(ve=>Te(ve)).filter(Boolean).some(ve=>ie.has(ve))&&typeof pe.resolveComment=="function"&&(pe.resolveComment(se),de+=1)}),de},Rs=x=>{const D=new Set(Dt(x));x?.trackedChangeCanonicalId!=null&&D.add(String(x.trackedChangeCanonicalId));const ee=x?.trackedChangeAnchorKey!=null?String(x.trackedChangeAnchorKey):null;if(ee&&(D.add(ee),ee.startsWith("tc::"))){const ie=ee.slice(ee.lastIndexOf("::")+2);ie&&D.add(ie)}return D},pl=x=>{const D=[],ee=new Set;for(const ie of Rs(x))for(const se of Fe.value.get(String(ie))??[])ee.has(se)||(ee.add(se),D.push(se));return D},wa=x=>{const D=x&&typeof x=="object"?x:null;if(!D?.success)return new Set;const ee=new Set,ie=se=>{const de=se&&typeof se=="object"?se:null;de?.kind!=="entity"||de.entityType!=="trackedChange"||de.entityId!=null&&String(de.entityId).length>0&&ee.add(String(de.entityId))};return Array.isArray(D.removed)&&D.removed.forEach(ie),Array.isArray(D.invalidatedRefs)&&D.invalidatedRefs.forEach(ie),ee},ml=x=>{const D=new Set;return x?.decidedId!=null&&String(x.decidedId).length>0&&D.add(String(x.decidedId)),Array.isArray(x?.decidedIds)&&x.decidedIds.forEach(ee=>{ee!=null&&String(ee).length>0&&D.add(String(ee))}),wa(x?.receipt).forEach(ee=>D.add(ee)),D},Xi=({comment:x,decision:D}={})=>{if(!x?.trackedChange||!Su({comment:x,decision:D}))return 0;const ee=Rs(x);if(!ee.size)return 0;let ie=0;return pl(x).forEach(se=>{if(!se||se===x)return;const de=Te(se.trackedChangeParentId),pe=Te(se.trackedChangeThreadParentId),ve=Te(se.threadingParentCommentId),Xe=Te(se.parentCommentId);(de&&ee.has(de)||pe&&ee.has(pe)||ve&&ee.has(ve)||Xe&&ee.has(Xe))&&(delete se.trackedChangeParentId,se.trackedChangeThreadParentId=void 0,delete se.trackedChangeSide,delete se.threadingParentCommentId,Xe&&ee.has(Xe)&&delete se.parentCommentId,ie+=1)}),ie},sc=({superdoc:x,comment:D,decidedId:ee,decidedIds:ie,documentId:se}={})=>{const de=new Set((Array.isArray(ie)||ie instanceof Set?Array.from(ie):[ee]).map(vt=>Te(vt)).filter(Boolean)),pe=Te(se);if(!de.size||!pe)return{removed:!1,removedIds:new Set};const ve=new Set;let Xe=!1;const Qe=D?L.value.indexOf(D):-1,tt=D?.trackedChange?Rs(D):new Set;if(Qe>=0&&Lo(D,pe)&&Array.from(de).some(vt=>tt.has(vt))?(tt.forEach(vt=>ve.add(vt)),L.value.splice(Qe,1),Xe=!0):L.value=L.value.filter(vt=>{if(!vt?.trackedChange||!Lo(vt,pe))return!0;const pt=Rs(vt);return Array.from(de).some(it=>pt.has(it))?(Xe=!0,pt.forEach(it=>ve.add(it)),!1):!0}),!Xe)return{removed:!1,removedIds:ve};const st=M.value!=null?String(M.value):null;return st&&ve.has(st)&&Wr(),{removed:!0,removedIds:ve}},ac=(x,D)=>{if(!(!D||typeof x?.clearActiveTrackedChangeTargetIfMatches!="function"))try{x.clearActiveTrackedChangeTargetIfMatches(D)}catch{}},lc=async({superdoc:x,receipt:D}={})=>{const ee=x?.activeEditor?.documentMutationReadiness;if(!(D?.success!==!0||typeof D?.txId!="string"||!D.txId||typeof ee?.whenPainted!="function"))try{await ee.whenPainted(D);const ie=globalThis.requestAnimationFrame;typeof ie=="function"&&await new Promise(se=>{let de=!1;const pe=()=>{de||(de=!0,clearTimeout(ve),se())},ve=setTimeout(pe,250);ie(()=>ie(()=>setTimeout(pe,0)))})}catch{}},Au=({superdoc:x,comment:D,decision:ee})=>{if(u())return{ok:!1,reason:"read-only-document"};if(!D?.trackedChange)return{ok:!1};const ie=be(x);if(ie){if(ee!=="accept"&&ee!=="reject")return Promise.resolve({ok:!1,reason:"decision-invalid"});const tt=D?.trackedChangeCanonicalId!=null?String(D.trackedChangeCanonicalId):D?.commentId!=null?String(D.commentId):D?.trackedChangeAnchorKey?.startsWith?.("tc::body::")?D.trackedChangeAnchorKey.slice(10):null,st=tt!=null&&String(M.value??"")===tt;return ou("store.trackedChanges.sidebarDecision","command",{decision:ee,decidedId:tt},()=>(async()=>{try{return await(ee==="accept"?ie.accept(D):ie.reject(D))}catch(vt){return{ok:!1,reason:"adapter-threw",detail:vt?.message??String(vt)}}})().then(async vt=>{if(!xi(ie))return{ok:!1,reason:"adapter-stale"};if(!vt?.ok)return{ok:!1,reason:vt?.reason,detail:vt?.detail};const pt=ml(vt),it=vt?.documentId??ie.documentId??x?.activeEditor?.documentId??x?.activeEditor?.options?.documentId??null,dn=async()=>{let rn;try{rn=await ie.listTrackedChanges({mode:"all",refreshReason:"post-decision-blocking",blocking:!0})}catch(Wn){return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:Wn?.message??String(Wn)}}if(!xi(ie))return{ok:!1,committed:!0,reason:"adapter-stale"};if(!rn?.ok)return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:rn?.reason??rn?.detail??null};ni({superdoc:x,comment:D,decision:ee}),Xi({comment:D,decision:ee}),Ca({superdoc:x,adapter:ie,documentId:it,items:rn.items??[],pruneStale:rn.complete===!0&&rn.sourceCoverageComplete===!0});const Bn=new Set((rn.items??[]).map(Wn=>Wn&&Wn.id!=null?String(Wn.id):null).filter(Boolean));tt!=null&&Bn.has(tt)||(st&&Wr(),ac(ie,tt));const Gn=J(x);if(Gn&&typeof Gn.refresh=="function"&&Uo(Gn)){let Wn;try{Wn=await Gn.refresh()}catch(vo){return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:vo?.message??String(vo)}}if(!Uo(Gn))return{ok:!1,committed:!0,reason:"comments-adapter-stale"};if(!Wn?.ok)return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:Wn?.reason??Wn?.detail??null};qi({superdoc:x,adapter:Gn,documentId:Gn.documentId??it,items:Wn.items??[]})}return{ok:!0,success:!0}};return!pt.size||!it?dn():(pt.forEach(rn=>ac(ie,rn)),await lc({superdoc:x,receipt:vt.receipt}),ni({superdoc:x,comment:D,decision:ee}),Xi({comment:D,decision:ee}),sc({superdoc:x,comment:D,decidedIds:pt,documentId:it}),st&&Wr(),{ok:!0,success:!0})}))}const se=x?.activeEditor;if(!se)return{ok:!1};const de=D.commentId??D.importedId;if(!de)return{ok:!1};const pe=D.trackedChangeStory??void 0,ve=typeof se.doc=="object"?se.doc:null;if(ve?.trackChanges?.decide)try{const tt=pe?{id:de,story:pe}:{id:de};return Promise.resolve(ve.trackChanges.decide({decision:ee,target:tt})).then(st=>({ok:!0,success:!!st?.success}))}catch(tt){if(pe)return{ok:!1,error:tt}}const Xe=ee==="accept"?"acceptTrackedChangeById":"rejectTrackedChangeById",Qe=se.commands?.[Xe];return typeof Qe!="function"?{ok:!1}:{ok:!0,success:!!Qe(de)}},Lf=async({superdoc:x,adapter:D,documentId:ee,trackedChangesListMode:ie="all",refreshReason:se,blocking:de}={})=>ou("store.trackedChanges.hydrateFromV2","tracked-change-list",{documentId:ee??null,trackedChangesListMode:ie,refreshReason:se??null,blocking:de??null},async()=>{const pe=D??be(x);if(!pe||typeof pe.listTrackedChanges!="function")return{ok:!1,reason:"adapter-missing"};let ve;try{const tt={mode:ie};se!=null&&(tt.refreshReason=se),typeof de=="boolean"&&(tt.blocking=de),ve=await pe.listTrackedChanges(tt)}catch(tt){return{ok:!1,reason:"adapter-threw",detail:tt?.message??String(tt)}}if(!xi(pe))return{ok:!1,reason:"adapter-stale"};if(!ve?.ok)return ve;const Xe=!(ie==="startup-page"||ie==="interaction-prime"||ie==="visible-window")&&ve.visibleWindowSource==null&&ve.complete===!0&&ve.sourceCoverageComplete===!0;Ca({superdoc:x,adapter:pe,documentId:ee,items:ve.items??[],pruneStale:Xe});const Qe={ok:!0,items:ve.items??[]};return typeof ve.complete=="boolean"&&(Qe.complete=ve.complete),typeof ve.sourceCoverageComplete=="boolean"&&(Qe.sourceCoverageComplete=ve.sourceCoverageComplete),ve.visibleWindowSource!=null&&(Qe.visibleWindowSource=ve.visibleWindowSource),ve.visibleWindowFallbackReason!=null&&(Qe.visibleWindowFallbackReason=ve.visibleWindowFallbackReason),typeof ve.visibleTrackedChangeExpectedRows=="number"&&(Qe.visibleTrackedChangeExpectedRows=ve.visibleTrackedChangeExpectedRows),typeof ve.visibleTrackedChangeObservedRows=="number"&&(Qe.visibleTrackedChangeObservedRows=ve.visibleTrackedChangeObservedRows),typeof ve.refreshReason=="string"&&(Qe.refreshReason=ve.refreshReason),typeof ve.blocking=="boolean"&&(Qe.blocking=ve.blocking),typeof ve.pageCount=="number"&&(Qe.pageCount=ve.pageCount),typeof ve.totalItems=="number"&&(Qe.totalItems=ve.totalItems),typeof ve.coalesced=="boolean"&&(Qe.coalesced=ve.coalesced),Qe}),cc=async({superdoc:x,adapter:D,documentId:ee,upsertIds:ie=[],removedIds:se=[]}={})=>{const de=D??be(x);if(!de)return{ok:!1,reason:"adapter-missing"};if(!xi(de))return{ok:!1,reason:"adapter-stale"};const pe=ee??de.documentId??x?.activeEditor?.documentId??null,ve=new Set(Array.from(se??[]).map(pt=>Te(pt)).filter(Boolean)),Xe=[...new Set(Array.from(ie??[]).map(pt=>Te(pt)).filter(Boolean))];if(ve.size>0&&Xe.length===0&&pe!=null&&sc({superdoc:x,decidedIds:ve,documentId:pe}),Xe.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};if(typeof de.getTrackedChange!="function")return{ok:!1,reason:"adapter-get-missing"};const Qe=await Promise.all(Xe.map(async pt=>{try{return{id:pt,result:await de.getTrackedChange(pt)}}catch(it){return{id:pt,result:{ok:!1,reason:"adapter-threw",detail:it?.message??String(it)}}}}));if(!xi(de))return{ok:!1,reason:"adapter-stale"};const tt=[],st=[],vt=[];for(const{id:pt,result:it}of Qe){const dn=it?.ok&&Array.isArray(it.items)?it.items.filter(rn=>Te(rn?.id??rn?.changeId??rn?.address?.entityId)===pt):[];dn.length>0?(tt.push(pt),vt.push(...dn)):st.push(pt)}return vt.length>0&&Ca({superdoc:x,adapter:de,documentId:pe,items:vt,pruneStale:!1}),{ok:st.length===0,items:vt,resolvedIds:tt,unresolvedIds:st,failures:Qe.map(({result:pt})=>pt).filter(pt=>!pt?.ok)}},Ca=({superdoc:x,adapter:D,documentId:ee,items:ie,pruneStale:se=!0}={})=>ou("store.trackedChanges.reconcile","store-reconciliation",{documentId:ee??null,itemCount:Array.isArray(ie)?ie.length:null,pruneStale:se},()=>{if(!D||!Array.isArray(ie)||!xi(D))return;const de=ee??D.documentId??x?.activeEditor?.documentId??null,pe=new Set,ve=new Set;for(const Xe of ie){const Qe=D.mapV2TrackedChangeToCommentParams(Xe);if(Qe){if(Qe.event==="omit"){Qe.changeId!=null&&ve.add(String(Qe.changeId));continue}de&&Qe.documentId==null&&(Qe.documentId=de),Qe.changeId!=null&&ve.add(String(Qe.changeId)),Qe.trackedChangeAnchorKey!=null&&pe.add(String(Qe.trackedChangeAnchorKey)),_r({superdoc:x,params:Qe,broadcastChanges:!1})}}!de||!se||ku(ve,pe,String(de),x,{broadcastChanges:!1})}),Df=({superdoc:x,editor:D,broadcastChanges:ee=!0})=>{if(!x||!D)return;const ie=D?.options?.documentId!=null?String(D.options.documentId):null;if(!ie)return;const se=ic(D);if(!se)return;const de=se.trackedChanges,pe=new Set;de.forEach(Xe=>{const Qe=Xe?.mark?.attrs?.id;Qe!=null&&pe.add(String(Qe))});const ve=se.storySnapshots;ku(pe,new Set(ve.map(Xe=>Xe?.anchorKey).filter(Xe=>typeof Xe=="string"&&Xe.length>0)),ie,x,{broadcastChanges:ee}),_u(D,x,de,{reopenResolved:!0,refreshExisting:!0,broadcastChanges:ee,editorState:se.state,editorView:se.view}),uc({superdoc:x,editor:D,broadcastChanges:ee,snapshots:ve,documentState:se.state}),Iu({superdoc:x,editor:D,broadcastChanges:ee,structuralChanges:se.structuralChanges})},Iu=({superdoc:x,editor:D,broadcastChanges:ee=!0,structuralChanges:ie=null})=>{const se=D?.options?.documentId!=null?String(D.options.documentId):null;if(!se)return;const de=la?.enumerateStructuralRowChanges;if(typeof de!="function")return;let pe=ie;if(!Array.isArray(pe)){const ve=ei(D);if(!ve)return;try{pe=de(ve.state)??[]}catch{pe=[]}}for(const ve of pe){if(!ve?.decidable||!ve?.wholeTable)continue;const Xe=r(ve);if(!Xe)continue;const Qe=n(Xe),tt=ve.subtype==="table-insert"?"tableInsert":"tableDelete",st=ve.side==="insertion"?"trackInsert":"trackDelete",vt=String(Xe),pt=Qe!=null?String(Qe):null;_r({superdoc:x,params:{event:L.value.find(it=>{if(!it?.trackedChange||!Lo(it,se))return!1;const dn=it.trackedChangeAnchorKey!=null?String(it.trackedChangeAnchorKey):null;if(pt&&dn)return dn===pt;const rn=it.commentId!=null?String(it.commentId):null,Bn=it.importedId!=null?String(it.importedId):null;return rn===vt||Bn===vt})?"update":"add",changeId:Xe,trackedChangeText:"",trackedChangeType:st,trackedChangeDisplayType:tt,deletedText:null,authorId:null,authorEmail:ve.authorEmail||null,authorImage:ve.authorImage||null,date:ve.date||null,author:ve.author||null,importedAuthor:ve.importedAuthor?{name:ve.importedAuthor}:null,semanticColorKey:ve.semanticColorKey??null,semanticColor:ve.semanticColor??null,documentId:se,coords:null,trackedChangeStory:e,trackedChangeStoryKind:"body",trackedChangeStoryLabel:"",trackedChangeAnchorKey:Qe},broadcastChanges:ee})}},uc=({superdoc:x,editor:D,broadcastChanges:ee=!0,snapshots:ie=null,documentState:se=void 0,resolveFromEditor:de=!0})=>{const pe=D?.options?.documentId!=null?String(D.options.documentId):null;if(!pe)return;let ve=ie;if(!Array.isArray(ve)){if(typeof iu!="function"||!ei(D))return;let Xe=null;try{Xe=iu(D)}catch{return}if(!Xe)return;try{ve=Xe.getAll()}catch{return}}for(const Xe of ve)Xe.storyKind!=="body"&&xu({superdoc:x,editor:D,snapshot:Xe,documentId:pe,broadcastChanges:ee,documentState:se,resolveFromEditor:de})},Ms=x=>x?.type!=="structural"?x?.type??null:x?.subtype==="table-delete"?"tableDelete":"tableInsert",Eu=x=>x?.type!=="structural"?x?.type??null:x?.subtype==="table-delete"?"trackDelete":"trackInsert",Ls=x=>x?x.type==="delete"?!0:x.type==="structural"&&x.subtype==="table-delete":!1,dc=({editor:x,snapshot:D,documentId:ee,event:ie,resolveFromEditor:se=!0})=>{const de=Eu(D),pe=Ms(D),ve={event:ie,changeId:D.runtimeRef.rawId,trackedChangeText:Ls(D)?"":D.excerpt??"",trackedChangeType:de,trackedChangeDisplayType:pe,semanticColorKey:D.semanticColorKey??null,semanticColor:D.semanticColor??null,deletedText:Ls(D)?D.excerpt??"":null,authorId:D.authorId,authorEmail:D.authorEmail,authorImage:D.authorImage,date:D.date,author:D.author,documentId:ee,coords:null,trackedChangeStory:D.story,trackedChangeStoryKind:D.storyKind,trackedChangeStoryLabel:D.storyLabel,trackedChangeAnchorKey:D.anchorKey};if(!se||typeof $C!="function")return ve;let Xe=null;try{Xe=$C(x,{kind:"entity",entityType:"trackedChange",entityId:D.runtimeRef.rawId,story:D.story})}catch{Xe=null}const Qe=Xe?.editor?.state??null;if(!Qe)return ve;let tt=[];try{tt=la.getTrackChanges(Qe,Xe.change.rawId)??[]}catch{tt=[]}const st=Hy({event:ie,marks:po(tt),nodes:[],newEditorState:Qe,documentId:ee,trackedChangesForId:tt});return st?(st.semanticColorKey==null&&D.semanticColorKey!=null&&(st.semanticColorKey=D.semanticColorKey),st.semanticColor==null&&D.semanticColor!=null&&(st.semanticColor=D.semanticColor),st.trackedChangeStory=D.story,st.trackedChangeStoryKind=D.storyKind,st.trackedChangeStoryLabel=D.storyLabel,st.trackedChangeAnchorKey=D.anchorKey,st):ve},xu=({superdoc:x,editor:D,snapshot:ee,documentId:ie,broadcastChanges:se,documentState:de,resolveFromEditor:pe})=>{if(!ee?.runtimeRef?.rawId)return;const ve=L.value.find(Xe=>{if(!Xe?.trackedChange)return!1;const Qe=Xe.trackedChangeAnchorKey!=null?String(Xe.trackedChangeAnchorKey):null;return Qe&&ee.anchorKey?Qe===ee.anchorKey:Qe||ee.anchorKey?!1:Xe.commentId===ee.runtimeRef.rawId||Xe.importedId===ee.runtimeRef.rawId});_r({superdoc:x,params:dc({editor:D,snapshot:ee,documentId:ie,event:ve?"update":"add",resolveFromEditor:pe}),broadcastChanges:se,documentState:de}),ve&&(ve.trackedChangeStory=ee.story,ve.trackedChangeStoryKind=ee.storyKind,ve.trackedChangeStoryLabel=ee.storyLabel,ve.trackedChangeAnchorKey=ee.anchorKey)},Tu=x=>x?(Array.isArray(x)?x:[x]).filter(Boolean):[],Qi=()=>{const x=[];return L.value.forEach(D=>{const ee=D.getValues(),ie=ee.commentText,se=Tu(ee.docxCommentJSON),de=se.length?se:Ru(ie);x.push({...ee,commentJSON:de})}),x},Ru=x=>{const D=new ZC({mode:"text",isHeadless:!0,content:x,extensions:JC()}).getJSON();return Array.isArray(D?.content)?D.content.filter(Boolean):[]},Zi=x=>{if(x==null)return;const D={};Object.entries(x).forEach(([ie,se])=>{D[ie]=se;const de=se?.kind==="trackedChange"&&se?.storyKey==="body"&&se?.threadId!=null?String(se.threadId):null;de&&D[de]===void 0&&(D[de]=se);const pe=typeof se?.key=="string"?se.key:null;pe&&D[pe]===void 0&&(D[pe]=se)});const ee=ie=>{const se=[ie?.trackedChangeAnchorKey,ie?.commentId,ie?.importedId,Ct(ie?.importedId)].map(de=>Te(de)).filter(Boolean);for(const de of se){const pe=D[de];if(pe!==void 0)return{entry:pe,aliasIds:se}}return{entry:null,aliasIds:se}};L.value.forEach(ie=>{if(!ie?.trackedChange)return;const{entry:se,aliasIds:de}=ee(ie);se&&de.forEach(pe=>{D[pe]===void 0&&(D[pe]=se)})}),ae.value=D},Pf=()=>{ae.value={}},Mu=x=>{if(!x?.trackedChange)return!1;const D=x?.trackedChangeDisplayType;return D==="tableInsert"||D==="tableDelete"?!0:[x?.commentId,x?.importedId,x?.trackedChangeAnchorKey].map(ee=>ee!=null?String(ee):"").filter(Boolean).some(ee=>ee.includes("word:structural:"))},gl=new WeakMap,fc=x=>{if(!x)return{ranges:[],ids:new Set};const D=gl.get(x);if(D)return D;const ee=[],ie=new Set,se=ve=>{ve!=null&&ve!==""&&ie.add(String(ve))},de=la?.enumerateStructuralRowChanges;if(typeof de=="function"){let ve=[];try{ve=de(x)??[]}catch{ve=[]}for(const Xe of ve){if(!Xe?.decidable||!Xe?.wholeTable)continue;const Qe=Number(Xe.tableFrom),tt=Number(Xe.tableTo);Number.isFinite(Qe)&&Number.isFinite(tt)&&ee.push({from:Qe,to:tt}),se(Xe.id),se(Xe.revisionId),se(Xe.revisionGroupId),se(Xe.sourceId);for(const st of Xe.rows||[]){const vt=st?.node?.attrs?.trackChange;se(vt?.id),se(vt?.sourceId)}}}const pe={ranges:ee,ids:ie};return gl.set(x,pe),pe},Lu=x=>{const D=o.getDocument(x)?.getEditor?.();return fc(D?.state).ranges},vl=(x,D)=>!D?.length||!x?.length?!1:x.every(ee=>{const ie=Number(ee?.from),se=Number(ee?.to);return!Number.isFinite(ie)||!Number.isFinite(se)?!1:D.some(de=>ie>=de.from&&se<=de.to)}),yl=x=>{if(!x?.trackedChange||Mu(x))return!1;const D=Lu(x?.fileId);if(!D.length)return!1;const ee=un(x).entry,ie=ur(ee);return ie?D.some(se=>ie.start>=se.from&&ie.end<=se.to):!1},Du=Se(()=>ro.value?.parentComments.filter(x=>!x.resolvedTime).filter(x=>!Ze(x)||ot(x)?!0:!!un(x).entry).filter(x=>!yl(x))),bl=Se(()=>Du.value.flatMap(x=>{const{key:D,entry:ee}=un(x);return uT({comment:x,positionKey:D,positionEntry:ee,fallbackId:Te(x?.commentId)??Dt(x)[0]??null})})),ri=x=>x==null?null:String(x),Ji=(x=null)=>{H.value=ri(x)},Wr=()=>{M.value=null,Ji(null)},Of=(x,D)=>x==null||D==null?!1:bl.value.some(ee=>String(ee.id)===String(x)&&String(ee.comment?.commentId??ee.threadId??"")===String(D)),Pu=x=>{Of(H.value,x)||Ji(null)},Ds=({documentMode:x,commentsVisible:D,trackChangesVisible:ee}={})=>{typeof x=="string"&&(c.documentMode=x),typeof D=="boolean"&&(c.commentsVisible=D),typeof ee=="boolean"&&(c.trackChangesVisible=ee)},hc=x=>{if(Array.isArray(x))return x.map(pe=>hc(pe)).flat().filter(Boolean);if(!x||typeof x!="object")return x;const D=pe=>{if(!pe)return pe;const ve={...pe};return delete ve.fontSize,delete ve.fontFamily,delete ve.eastAsiaFontFamily,Object.keys(ve).length?ve:void 0},ee=pe=>{if(!pe)return pe;const ve=typeof pe.type=="string"?pe.type:pe.type?.name,Xe=pe?.attrs?{...pe.attrs}:void 0;return ve==="textStyle"&&Xe?{...pe,attrs:D(Xe)}:{...pe,attrs:Xe}},ie=pe=>Array.isArray(pe)?pe.filter(Boolean).map(ve=>ee(ve)):void 0,se=pe=>pe&&typeof pe=="object"?{...pe}:void 0;if(!Array.isArray(x.content))return{type:x.type,...x.text!==void 0?{text:x.text}:{},...x.attrs?{attrs:se(x.attrs)}:{},...x.marks?{marks:ie(x.marks)}:{}};const de=x.content.map(pe=>hc(pe)).flat().filter(Boolean);return x.type==="run"?de:{type:x.type,...x.attrs?{attrs:se(x.attrs)}:{},...x.marks?{marks:ie(x.marks)}:{},content:de}},Ff=x=>{const D=Array.isArray(x)?x:x?[x]:[];if(D.some(ee=>ee?.content?.length))try{const ee=hc(D),ie=Array.isArray(ee)?ee:ee?[ee]:[];return ie.length?new ZC({mode:"text",isHeadless:!0,content:{type:"doc",content:ie},loadFromSchema:!0,extensions:JC()}).getHTML():null}catch(ee){console.warn("Failed to convert comment",ee);return}};return{COMMENT_EVENTS:S,isDebugging:d,hasInitializedComments:y,hasSyncedCollaborationComments:C,editingCommentId:B,activeComment:M,activeFloatingCommentInstanceId:H,commentDialogs:z,overlappingComments:Z,overlappedIds:P,suppressInternalExternal:N,pendingComment:_,currentCommentText:I,commentsList:L,isCommentsListVisible:he,generalCommentIds:Ie,editorCommentIds:ge,commentsParentElement:T,editorCommentPositions:ae,hasInitializedLocations:R,isCommentHighlighted:Ce,floatingCommentsOffset:oe,sortedConversations:xe,visibleConversations:qe,skipSelectionUpdate:et,isFloatingCommentsReady:kt,instantSidebarAlignmentTargetY:ze,instantSidebarAlignmentThreadId:Ve,instantSidebarAlignmentInstanceId:Q,getConfig:bn,documentsWithConverations:lt,getGroupedComments:ro,hasOpenTrackedChanges:ke,getCommentsByPosition:Oe,getFloatingComments:Du,getFloatingCommentInstances:bl,getCommentAliasIds:Dt,getTrackedChangeThread:le,getCommentPositionKey:cn,getCommentPosition:dr,getCommentAnchoredText:jr,getCommentAnchorData:$t,resolveCommentPositionEntry:un,getCommentDocumentId:xs,belongsToDocument:hl,viewingVisibility:c,isViewingMode:F,shouldRenderReviewInViewing:j,init:we,setViewingVisibility:Ds,getComment:Vt,setActiveComment:Mr,getCommentLocation:an,hasOverlapId:ht,getPendingComment:Fr,showAddComment:Ss,addComment:Is,addHydratedComment:Jo,cancelComment:mi,deleteComment:Ro,removePendingComment:go,cancelImportedTrackedChangeBootstrap:jn,removeCommentsForDocument:dl,processLoadedDocxComments:fl,translateCommentsForExport:Qi,handleEditorLocationsUpdate:Zi,clearEditorCommentPositions:Pf,handleTrackedChangeUpdate:_r,refreshTrackedChangeCommentsByIds:Kt,syncResolvedCommentsWithDocument:Tt,syncTrackedChangePositionsWithDocument:Mt,setActiveFloatingCommentInstance:Ji,requestInstantSidebarAlignment:yn,peekInstantSidebarAlignment:xo,clearInstantSidebarAlignment:Zo,syncTrackedChangeComments:Df,decideTrackedChangeFromSidebar:Au,v2CommentsAdapter:V,setV2CommentsAdapter:G,getV2CommentsAdapter:J,hydrateCommentsFromV2:cl,reconcileCommentsFromV2:qi,isV2EditorActive:K,replyCommentV2:$o,editCommentV2:ll,resolveCommentV2:oc,reopenCommentV2:kr,v2TrackedChangesAdapter:W,setV2TrackedChangesAdapter:ue,getV2TrackedChangesAdapter:be,hydrateTrackedChangesFromV2:Lf,reconcileTrackedChangeMutationFromV2:cc,reconcileTrackedChangesFromV2:Ca}});var n_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M512 240c0 114.9-114.6 208-256 208c-37.1 0-72.3-6.4-104.1-17.9c-11.9 8.7-31.3 20.6-54.3 30.6C73.6 471.1 44.7 480 16 480c-6.5 0-12.3-3.9-14.8-9.9c-2.5-6-1.1-12.8 3.4-17.4c0 0 0 0 0 0s0 0 0 0s0 0 0 0c0 0 0 0 0 0l.3-.3c.3-.3 .7-.7 1.3-1.4c1.1-1.2 2.8-3.1 4.9-5.7c4.1-5 9.6-12.4 15.2-21.6c10-16.6 19.5-38.4 21.4-62.9C17.7 326.8 0 285.1 0 240C0 125.1 114.6 32 256 32s256 93.1 256 208z"/></svg>',r_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M137.4 374.6c12.5 12.5 32.8 12.5 45.3 0l128-128c9.2-9.2 11.9-22.9 6.9-34.9s-16.6-19.8-29.6-19.8L32 192c-12.9 0-24.6 7.8-29.6 19.8s-2.2 25.7 6.9 34.9l128 128z"/></svg>',FT='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M96 128a128 128 0 1 1 256 0A128 128 0 1 1 96 128zM0 482.3C0 383.8 79.8 304 178.3 304l91.4 0C368.2 304 448 383.8 448 482.3c0 16.4-13.3 29.7-29.7 29.7L29.7 512C13.3 512 0 498.7 0 482.3zM625 177L497 305c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L591 143c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>',BT='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M144 0a80 80 0 1 1 0 160A80 80 0 1 1 144 0zM512 0a80 80 0 1 1 0 160A80 80 0 1 1 512 0zM0 298.7C0 239.8 47.8 192 106.7 192l42.7 0c15.9 0 31 3.5 44.6 9.7c-1.3 7.2-1.9 14.7-1.9 22.3c0 38.2 16.8 72.5 43.3 96c-.2 0-.4 0-.7 0L21.3 320C9.6 320 0 310.4 0 298.7zM405.3 320c-.2 0-.4 0-.7 0c26.6-23.5 43.3-57.8 43.3-96c0-7.6-.7-15-1.9-22.3c13.6-6.3 28.7-9.7 44.6-9.7l42.7 0C592.2 192 640 239.8 640 298.7c0 11.8-9.6 21.3-21.3 21.3l-213.3 0zM224 224a96 96 0 1 1 192 0 96 96 0 1 1 -192 0zM128 485.3C128 411.7 187.7 352 261.3 352l117.3 0C452.3 352 512 411.7 512 485.3c0 14.7-11.9 26.7-26.7 26.7l-330.7 0c-14.7 0-26.7-11.9-26.7-26.7z"/></svg>',Vy='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"/></svg>',o_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>',i_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M64 360a56 56 0 1 0 0 112 56 56 0 1 0 0-112zm0-160a56 56 0 1 0 0 112 56 56 0 1 0 0-112zM120 96A56 56 0 1 0 8 96a56 56 0 1 0 112 0z"/></svg>',s_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M48.5 224L40 224c-13.3 0-24-10.7-24-24L16 72c0-9.7 5.8-18.5 14.8-22.2s19.3-1.7 26.2 5.2L98.6 96.6c87.6-86.5 228.7-86.2 315.8 1c87.5 87.5 87.5 229.3 0 316.8s-229.3 87.5-316.8 0c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0c62.5 62.5 163.8 62.5 226.3 0s62.5-163.8 0-226.3c-62.2-62.2-162.7-62.5-225.3-1L185 183c6.9 6.9 8.9 17.2 5.2 26.2s-12.5 14.8-22.2 14.8L48.5 224z"/></svg>';const ua={comment:n_,caretDown:r_,internal:FT,external:BT,markDone:Vy,acceptChange:Vy,rejectChange:o_,overflow:i_,reopen:s_};var NT=.38,zT=".superdoc-comment-highlight",HT=e=>{if(typeof e?.getBoundingClientRect!="function")return!1;const t=e.getBoundingClientRect();return!Number.isFinite(t.top)||!Number.isFinite(t.bottom)?!1:t.bottom>0&&t.top<window.innerHeight},UT=e=>e?e.split(",").map(t=>t.trim()).filter(Boolean):[],VT=e=>{const t=[];return e?(e.split(",").forEach(n=>{const r=n.indexOf("=");r<=0||t.push(n.slice(0,r),n.slice(r+1))}),t.filter(Boolean)):t};const jT=()=>Math.round(window.innerHeight*NT),a_=(e,t)=>{const n=t?.bounds?.top;if(!Number.isFinite(n)||typeof e?.getBoundingClientRect!="function")return null;const r=e.getBoundingClientRect().top+n;return r<0||r>=window.innerHeight?null:r},GT=e=>{if(typeof document>"u")return null;const t=new Set((e??[]).map(o=>String(o)).filter(Boolean));if(t.size===0)return null;let n=null;const r=document.querySelectorAll(zT);for(const o of r){const i=new Set([...UT(o.getAttribute("data-comment-ids")),...VT(o.getAttribute("data-comment-imported-ids"))]);if(![...t].some(a=>i.has(a))||!HT(o))continue;const s=o.getBoundingClientRect().top;Number.isFinite(s)&&(n=n==null?s:Math.min(n,s))}return n},WT=(e,t,n,r)=>{if(!e||!Number.isFinite(r))return null;const o=s=>{if(!s)return null;const a=e.getReachableThreadAnchorClientY(s,r);return Number.isFinite(a)&&e.scrollThreadAnchorToClientY(s,r,{behavior:"auto"})?a:null},i=o(t);return Number.isFinite(i)?i:!n||n===t?null:o(n)};It();const KT="Arial, Helvetica, sans-serif";function jy(){const e=sr();return{uiFontFamily:Se(()=>{const t=e?.proxy?.$superdoc?.config?.uiDisplayFallbackFont;return typeof t=="string"&&t.trim()?t.trim():KT})}}var hn,gn=br((()=>{hn=(e,t)=>{const n=e.__vccOpts||e;for(const[r,o]of t)n[r]=o;return n}}));It(),gn();var qT={class:"comments-dropdown"},YT=["onClick"],XT={key:0,class:"comments-dropdown__option-icon"},QT=["innerHTML"],ZT={class:"comments-dropdown__option-label"},JT={__name:"CommentsDropdown",props:{options:{type:Array,default:()=>[]},disabled:{type:Boolean,default:!1},contentStyle:{type:Object,default:()=>({})}},emits:["select"],setup(e,{emit:t}){const n=e,r=t,o=ne(!1),i=ne(null),s=ne(null),a=ne({top:"0px",left:"0px"}),l=Se(()=>({...n.contentStyle,position:"fixed",top:a.value.top,left:a.value.left,zIndex:1200})),u=C=>{n.disabled&&C||(o.value=C)},c=()=>{n.disabled||u(!o.value)},d=()=>{o.value&&u(!1)},h=()=>{if(!i.value)return;const C=i.value.getBoundingClientRect(),T=s.value?.offsetWidth??0,R=window.innerWidth||document.documentElement.clientWidth||0,M=8;let H=C.left;const B=Math.max(M,R-T-M);H=Math.min(Math.max(M,H),B),a.value={top:`${C.bottom+4}px`,left:`${H}px`}},m=C=>{C.stopPropagation(),c()},p=C=>{C?.disabled||(r("select",C?.key,C),d())},g=C=>!!C?.iconString||!!C?.icon,k=C=>C?.iconString?C.iconString:typeof C?.icon=="function"?C.icon(C):C?.icon||null,w=Ll({name:"CommentsDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(C){return()=>k(C.option)}}),S=C=>{if(!o.value)return;const T=C.target;if(!(T instanceof Element))return;const R=i.value?.contains(T),M=s.value?.contains(T);R||M||d()},y=C=>{C.key==="Escape"&&d()};return Pt(o,async C=>{C&&(await _t(),h())}),Pt(o,C=>{C?(document.addEventListener("pointerdown",S,!0),document.addEventListener("keydown",y,!0),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0)):(document.removeEventListener("pointerdown",S,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0))}),ir(()=>{document.removeEventListener("pointerdown",S,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0)}),(C,T)=>(me(),_e("div",qT,[Le("div",{ref_key:"triggerRef",ref:i,class:"comments-dropdown__trigger",onClick:m},[hd(C.$slots,"default",{},void 0,!0)],512),(me(),fn(Oa,{to:"body"},[o.value?(me(),_e("div",{key:0,ref_key:"menuRef",ref:s,class:"comments-dropdown__menu",style:vn(l.value)},[(me(!0),_e(Wt,null,or(e.options,R=>(me(),_e("div",{key:R.key,class:en(["comments-dropdown__option",{"sd-disabled":R.disabled}]),onClick:M=>p(R)},[g(R)?(me(),_e("span",XT,[R.iconString?(me(),_e("span",{key:0,innerHTML:R.iconString},null,8,QT)):(me(),fn(Ge(w),{key:1,option:R},null,8,["option"]))])):ut("",!0),Le("span",ZT,Ht(R.label),1)],10,YT))),128))],4)):ut("",!0)]))]))}},l_=hn(JT,[["__scopeId","data-v-7eced80a"]]);It(),gn();var $T={class:"sd-comment-option"},e7=["innerHTML"],t7={class:"sd-option-state"},n7=["innerHTML"],r7={__name:"InternalDropdown",props:{state:{type:String,required:!1},isDisabled:{type:Boolean,default:!1}},emits:["select"],setup(e,{emit:t}){const n=t,r=e,{uiFontFamily:o}=jy(),i=[{label:"Internal",key:"internal",iconString:ua.internal,backgroundColor:"var(--sd-ui-comments-internal-bg, #CDE6E6)"},{label:"External",key:"external",iconString:ua.external,backgroundColor:"var(--sd-ui-comments-external-bg, #F5CFDA)"}],s=Se(()=>i.find(d=>d.key===u.value)?.label),a=Se(()=>{if(!r.state)return{};const d=i.find(m=>m.key===u.value);if(!d)return{};const h={backgroundColor:d.backgroundColor};return r.isDisabled&&(h.opacity=.5,h.cursor="default"),h}),l=(d,h=!1)=>{u.value=d,c.value=i.find(m=>m.key===d)?.iconString,!h&&n("select",d)},u=ne(r.state),c=ne(null);return Pt(()=>r.state,d=>{l(d)}),Rn(()=>{l(r.state,!0)}),(d,h)=>(me(),_e("div",{class:"sd-internal-dropdown",style:vn(a.value),"data-sd-part":"dropdown-trigger"},[Gt(l_,{options:i,onSelect:h[0]||(h[0]=m=>l(m)),disabled:e.isDisabled,"content-style":{fontFamily:Ge(o)}},{default:ko(()=>[Le("div",$T,[Le("div",{class:"sd-active-icon",innerHTML:c.value},null,8,e7),Le("div",t7,Ht(s.value),1),Le("div",{class:"sd-dropdown-caret",innerHTML:Ge(ua).caretDown},null,8,n7)])]),_:1},8,["disabled","content-style"])],4))}},c_=hn(r7,[["__scopeId","data-v-138d641e"]]);function o7(e){const t=new Date(e),n=t.getHours(),r=t.getMinutes(),o=n>=12?"PM":"AM",i=n%12||12,s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],a=t.getDate();return`${`${i}:${r.toString().padStart(2,"0")}${o}`} ${s} ${a}`}const eo=Object.freeze({RESOLVE_OWN:"RESOLVE_OWN",RESOLVE_OTHER:"RESOLVE_OTHER",REJECT_OWN:"REJECT_OWN",REJECT_OTHER:"REJECT_OTHER",COMMENTS_OVERFLOW_OWN:"COMMENTS_OVERFLOW",COMMENTS_OVERFLOW_OTHER:"COMMENTS_OVERFLOW_OTHER",COMMENTS_DELETE_OWN:"COMMENTS_DELETE_OWN",COMMENTS_DELETE_OTHER:"COMMENTS_DELETE_OTHER",UPLOAD_VERSION:"UPLOAD_VERSION",VERSION_HISTORY:"VERSION_HISTORY"});var pr=Object.freeze({EDITOR:"editor",SUGGESTER:"suggester",VIEWER:"viewer"}),i7=Object.freeze({[eo.RESOLVE_OWN]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.RESOLVE_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.REJECT_OWN]:{internal:[pr.EDITOR,pr.SUGGESTER],external:[pr.EDITOR,pr.SUGGESTER]},[eo.REJECT_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.COMMENTS_OVERFLOW_OWN]:{internal:[pr.EDITOR,pr.SUGGESTER],external:[pr.EDITOR,pr.SUGGESTER]},[eo.COMMENTS_OVERFLOW_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.COMMENTS_DELETE_OWN]:{internal:[pr.EDITOR,pr.SUGGESTER],external:[pr.EDITOR,pr.SUGGESTER]},[eo.COMMENTS_DELETE_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.UPLOAD_VERSION]:{internal:[pr.EDITOR],external:[]},[eo.VERSION_HISTORY]:{internal:[pr.EDITOR],external:[]}}),s7=(e={})=>{if(typeof e.permissionResolver=="function")return e.permissionResolver;if(e.superdoc?.config?.modules?.comments?.permissionResolver){const t=e.superdoc.config.modules.comments.permissionResolver;if(typeof t=="function")return t}return typeof e.superdoc?.config?.permissionResolver=="function"?e.superdoc.config.permissionResolver:null},a7=(e,t,n)=>{const r=n?"internal":"external";return i7[e]?.[r]?.includes(t)??!1};const da=(e,t,n,r={})=>{const o=a7(e,t,n),i=s7(r);if(typeof i!="function")return o;const s=i({permission:e,role:t,isInternal:n,defaultDecision:o,comment:r.comment??null,currentUser:r.currentUser??r.superdoc?.config?.user??null,superdoc:r.superdoc??null,trackedChange:r.trackedChange??null});return typeof s=="boolean"?s:o};It(),gn();var l7={class:"user-container"},c7=["src"],u7={key:1,class:"user-bg"},d7={__name:"Avatar",props:{user:{type:Object,required:!0}},setup(e){const t=(n,r)=>{if(!(!n&&!r)){if(n){const o=n.trim().split(/\s+/).filter(i=>/^[a-zA-Z]/.test(i));if(o.length>=2)return(o[0][0]+o[o.length-1][0]).toUpperCase();if(o.length===1)return o[0][0].toUpperCase()}return r?.substring(0,1)?.toUpperCase()||null}};return(n,r)=>(me(),_e("div",l7,[e.user.image?(me(),_e("img",{key:0,class:"user-bg",src:e.user.image.startsWith("http")?e.user.image:`data:image/png;base64,${e.user.image}`},null,8,c7)):(me(),_e("span",u7,Ht(t(e.user.name,e.user.email)),1))]))}},u_=hn(d7,[["__scopeId","data-v-c95b2073"]]);It(),gn();var f7={class:"card-section comment-header"},h7={class:"comment-header-left"},p7={class:"user-info"},m7={class:"user-name"},g7={key:0,class:"imported-tag"},v7={key:0,class:"user-timestamp"},y7=["data-disabled-reason","aria-disabled","innerHTML"],b7=["data-disabled-reason","aria-disabled","innerHTML"],w7=["data-disabled-reason","aria-disabled","innerHTML"],C7={class:"overflow-menu__icon"},_7=["innerHTML"],S7={__name:"CommentHeader",props:{timestamp:{type:Number,required:!1},config:{type:Object,required:!0},comment:{type:Object,required:!1},isPendingInput:{type:Boolean,required:!1,default:!1},isActive:{type:Boolean,default:!1},resolveDisabledReason:{type:String,default:null},rejectDisabledReason:{type:String,default:null},reopenDisabledReason:{type:String,default:null},reopenSupported:{type:Boolean,default:!1},writeDisabledReason:{type:String,default:null}},emits:["resolve","reject","reopen","overflow-select"],setup(e,{emit:t}){const n=t,r=ca(),o=e,{proxy:i}=sr(),s=i.$superdoc.config.role,a=i.$superdoc.config.isInternal,l=z=>{const Z=i.$superdoc.config.user,P={id:z?.creatorId,email:z?.creatorEmail};if(Ow({current:Z,other:P}))return!0;const N=Ld(Z),I=Ld(P);if(N.hasId||N.hasEmail||I.hasId||I.hasEmail||z?.origin!=null||z?.importedAuthor?.name)return!1;const L=Pw(Z?.name),X=Pw(z?.creatorName);return!!(L&&X&&L===X)},u=Se(()=>l(o.comment)),c=Se(()=>pp(o.comment)),{uiFontFamily:d}=jy(),h=Object.freeze({edit:{label:"Edit",key:"edit"},delete:{label:"Delete",key:"delete"}}),m=Se(()=>o.config.readOnly!==!0),p=Se(()=>!(!m.value||!o.comment||o.comment.resolvedTime||r.pendingComment||o.isPendingInput)),g=Se(()=>{if(!p.value||!o.comment.trackedChange&&o.config.allowResolve===!1||o.comment.parentCommentId||c.value)return!1;const z={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value||o.comment.trackedChange?da(eo.RESOLVE_OWN,s,a,z):da(eo.RESOLVE_OTHER,s,a,z)}),k=Se(()=>{if(!p.value||!o.comment.trackedChange)return!1;const z={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value||o.comment.trackedChange?da(eo.REJECT_OWN,s,a,z):da(eo.REJECT_OTHER,s,a,z)}),w=Se(()=>{if(!m.value||o.config.allowResolve===!1||!o.reopenSupported||!o.comment||!o.comment.resolvedTime||r.pendingComment||o.isPendingInput||o.comment.parentCommentId||c.value||o.comment.trackedChange)return!1;const z={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value?da(eo.RESOLVE_OWN,s,a,z):da(eo.RESOLVE_OTHER,s,a,z)}),S=Se(()=>!(!p.value||o.comment.trackedChange||o.isPendingInput||y.value.length===0)),y=Se(()=>{if(!m.value)return[];if(!p.value)return[];if(o.writeDisabledReason)return[];const z=[],Z=new Set;l(o.comment)&&Z.add("edit");const P=l(o.comment),N={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return(P&&da(eo.COMMENTS_DELETE_OWN,s,a,N)||!P&&da(eo.COMMENTS_DELETE_OTHER,s,a,N))&&Z.add("delete"),Z.forEach(I=>z.push(h[I])),z}),C=()=>{m.value&&(!o.comment?.trackedChange&&o.config.allowResolve===!1||o.resolveDisabledReason||n("resolve"))},T=()=>{m.value&&(o.rejectDisabledReason||n("reject"))},R=()=>{!m.value||o.config.allowResolve===!1||o.reopenDisabledReason||n("reopen")},M=z=>{m.value&&n("overflow-select",z)},H=Se(()=>!(!(o.comment.origin!=null||o.comment.importedAuthor?.name)||l(o.comment))),B=Se(()=>{if(o.isPendingInput)return i.$superdoc.config.user;const z=o.comment.getCommentUser();if(z?.name){const Z=z.name.replace(/\s*\(imported\)\s*/gi,"").trim();if(Z)return{...z,name:Z}}return z});return(z,Z)=>(me(),_e("div",f7,[Le("div",h7,[Gt(u_,{user:B.value,class:"avatar"},null,8,["user"]),Le("div",p7,[Le("div",m7,[Oi(Ht(B.value.name),1),H.value?(me(),_e("span",g7,"IMPORTED")):ut("",!0)]),o.comment.createdTime?(me(),_e("div",v7,Ht(Ge(o7)(o.comment.createdTime)),1)):ut("",!0)])]),Le("div",{class:en(["overflow-menu",{"is-visible":o.isActive}])},[g.value?(me(),_e("div",{key:0,class:en(["overflow-menu__icon",{"sd-is-disabled":!!e.resolveDisabledReason}]),"data-comment-action":"resolve","data-disabled-reason":e.resolveDisabledReason||null,"aria-disabled":!!e.resolveDisabledReason,innerHTML:Ge(ua).markDone,onClick:Jt(C,["stop","prevent"])},null,10,y7)):ut("",!0),k.value?(me(),_e("div",{key:1,class:en(["overflow-menu__icon",{"sd-is-disabled":!!e.rejectDisabledReason}]),"data-comment-action":"reject","data-disabled-reason":e.rejectDisabledReason||null,"aria-disabled":!!e.rejectDisabledReason,innerHTML:Ge(ua).rejectChange,onClick:Jt(T,["stop","prevent"])},null,10,b7)):ut("",!0),w.value?(me(),_e("div",{key:2,class:en(["overflow-menu__icon overflow-menu__icon--reopen",{"sd-is-disabled":!!e.reopenDisabledReason}]),"data-disabled-reason":e.reopenDisabledReason||null,"data-comment-reopen":!0,"aria-disabled":!!e.reopenDisabledReason,title:"Reopen comment",innerHTML:Ge(ua).reopen,onClick:Jt(R,["stop","prevent"])},null,10,w7)):ut("",!0),S.value?(me(),fn(l_,{key:3,"data-comment-action":"overflow",options:y.value,onSelect:M,"content-style":{fontFamily:Ge(d)}},{default:ko(()=>[Le("div",C7,[Le("div",{class:"overflow-icon",innerHTML:Ge(ua).overflow},null,8,_7)])]),_:1},8,["options","content-style"])):ut("",!0)],2)]))}},Gy=hn(S7,[["__scopeId","data-v-ca6050aa"]]);It(),gn();var k7={class:"input-section"},Wy=28,d_=132,A7={__name:"CommentInput",props:{users:{type:Array,required:!1,default:()=>[]},config:{type:Object,required:!0},isFocused:{type:Boolean,default:!1},includeHeader:{type:Boolean,default:!0},comment:{type:Object,required:!1}},emits:["focus"],setup(e,{expose:t,emit:n}){const r=n,{currentCommentText:o}=ea(ca()),i=ne(null),s=p=>r("focus",p),a=()=>{i.value?.focus?.()},l=()=>{const p=i.value;if(!p)return;p.style.height=`${Wy}px`;const g=p.scrollHeight||Wy,k=Math.min(Math.max(g,Wy),d_);p.style.height=`${k}px`,p.style.overflowY=g>d_?"auto":"hidden"},u=()=>{_t(l)},c=p=>String(p??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),d=p=>{const g=String(p??"");if(!g||g==="<p></p>")return"";if(typeof document>"u")return g.replace(/<br\s*\/?>/gi,`
|
|
12
|
+
`).replace(/^\n+/,"").replace(/\n+$/,"")};const ca=Yw("comments",()=>{const e={kind:"story",storyType:"body"},t=x=>{if(!x?.trackedChange)return!1;const D=x?.trackedChangeStory?.storyType;return D==null||D==="body"?!0:x?.trackedChangeAnchorKey?.startsWith?.("tc::body::")===!0},n=x=>x==null?null:e_({storyKey:"body",rawId:String(x)}),r=x=>{if(!x)return null;const D=x.sourceId?String(x.sourceId):"";return D?`word:structural:${D}`:x.id?String(x.id):null},o=nu(),i=zr({name:"comments",readOnly:!1,allowResolve:!0,showResolved:!1}),s=()=>({ok:!1,reason:"read-only-document"}),a=()=>({ok:!1,reason:"resolve-disabled"}),l=()=>i.allowResolve===!1,u=()=>i.readOnly===!0,c=zr({documentMode:"editing",commentsVisible:!1,trackChangesVisible:!1}),d=!1,h={},m=new WeakMap,p=new Map;let g=0;const k=()=>typeof window>"u"?!1:"__labsSuperDocV2PreviewDebug"in window,w=(x,D=null)=>{if(k()){if(D!==null){console.debug("[SuperDoc][comments-store]",x,D);return}console.debug("[SuperDoc][comments-store]",x)}},S=Bh,y=ne(!1),C=ne(!1),T=ne(null),R=ne(!1),M=ne(null),H=ne(null),B=ne(null),z=ne([]),Z=ne([]),P=new Set([]),N=ne(!0),I=ne(""),L=ne([]);let X=new Map;const te=Se(()=>{const x=_T(L.value,X);return X=x,x}),le=x=>{const D=x?.commentId??null;return(D!=null?te.value.get(D):null)??[x].filter(Boolean)};let fe=new Map;const Fe=Se(()=>{const x=ST(L.value,fe);return fe=x,x}),he=ne(!1),ge=ne([]),ae=ne({}),Ce=ne(!1),oe=ne(0),xe=ne([]),qe=ne([]),et=ne(!1),kt=ne(!1),Ie=ne([]),ze=ne(null),Ve=ne(null),Q=ne(null),_=ne(null),$=Ur(null),F=Se(()=>c.documentMode==="viewing"),j=Se(()=>F.value?c.commentsVisible||c.trackChangesVisible:!0),V=Ur(null),G=x=>{V.value=x??null},J=x=>{const D=x?.activeEditor?.v2Comments??null;return D||V.value},K=x=>x?.activeEditor?.editorVersion===2||V.value!==null,W=Ur(null),ue=x=>{W.value=x??null},be=x=>{const D=x?.activeEditor?.v2TrackedChanges??null;return D||W.value},we=(x={})=>{const D={...i,...x};Object.assign(i,D),N.value=i.suppressInternalExternal||!1,x.comments&&x.comments.length&&(L.value=x.comments?.map(ee=>aa(ee))||[])},Te=x=>x==null?null:String(x),rt=x=>Array.isArray(x)?[...new Set(x.map(D=>Te(D)).filter(Boolean))]:[],nt=x=>{if(!x?.trackedChange)return null;const D=Te(x.trackedChangeAnchorKey);if(D?.startsWith("tc::")){const ie=D.indexOf("::",4);if(ie>4)return D.slice(4,ie)}const ee=x.trackedChangeStory;switch(ee?.storyType){case"body":return"body";case"headerFooterPart":return ee.refId?`hf:${ee.refId}`:null;case"footnote":return ee.noteId?`fn:${ee.noteId}`:null;case"endnote":return ee.noteId?`en:${ee.noteId}`:null;case"textbox":return ee.textboxId?`textbox:${ee.textboxId}`:null;default:return null}},wt=x=>x?.startsWith("hf:part:")?`hf:${x.slice(8)}`:x?.startsWith("headerFooterPart:")?`hf:${x.slice(17)}`:x,Zt=(x,D)=>{const ee=wt(nt(D)),ie=wt(Te(x?.storyKey));return!ee||!ie||ie===ee},Ct=x=>{const D=Te(x);return D?D.startsWith("imported:")?D:`imported:${D}`:null},Ot=x=>{const D=Te(x);if(!D)return{key:null,entry:null};const ee=ae.value||{};if(ee[D]!==void 0)return{key:D,entry:ee[D]};for(const[ie,se]of Object.entries(ee)){const de=Te(se?.key),pe=Te(se?.threadId);if(de===D||pe===D)return{key:ie,entry:se}}return{key:null,entry:null}},Bt=(x,D)=>{if(!x||!D)return!1;const ee=Math.max(Number(x.left),Number(D.left)),ie=Math.min(Number(x.right),Number(D.right)),se=Math.max(Number(x.top),Number(D.top)),de=Math.min(Number(x.bottom),Number(D.bottom));return[ee,ie,se,de].every(Number.isFinite)&&ie>ee&&de>se},on=(x,D)=>{if(!x||!D||x.kind!=="trackedChange"||D.kind!=="trackedChange"||x.storyKey&&D.storyKey&&x.storyKey!==D.storyKey)return!1;const ee=Number(x.pageIndex),ie=Number(D.pageIndex);if(Number.isFinite(ee)&&Number.isFinite(ie)&&ee!==ie)return!1;if(Bt(x.bounds,D.bounds))return!0;const se=Number(x.start),de=Number(x.end),pe=Number(D.start),ve=Number(D.end);return[se,de,pe,ve].every(Number.isFinite)&&se===pe&&de===ve},Fn=x=>{const{entry:D}=Ot(x);if(!D)return null;const ee=L.value.filter(ie=>ie?.trackedChange?Dt(ie).some(se=>{const{entry:de}=Ot(se);return on(D,de)}):!1);return ee.length===1?ee[0]:null},Vt=x=>x==null?null:L.value.find(D=>D.commentId==x||D.importedId==x||D.trackedChangeAnchorKey==x||D?.trackedChange&&Ct(D.importedId)==x)||Fn(x),We=x=>x?.parentCommentId?Vt(x.parentCommentId):x,St=x=>x?.trackedChangeThreadParentId?x.trackedChangeThreadParentId:hp(x)&&x?.trackedChange===!0?null:pp(x),Nt=x=>{const D=St(x);return D?!!Vt(D)?.trackedChange:!1},cn=x=>{if(!x)return null;const D=ae.value||{};if(typeof x=="string"){if(D[x])return x;const pe=Vt(x);if(!pe)return x;const ve=pe.commentId??null,Xe=pe.importedId??null,Qe=pe.trackedChange?Ct(Xe):null,tt=pe.trackedChangeAnchorKey??null;return tt&&D[tt]?tt:ve&&D[ve]?ve:Xe&&D[Xe]?Xe:Qe&&D[Qe]?Qe:tt??ve??Qe??Xe??null}const ee=x.commentId??null,ie=x.importedId??null,se=x.trackedChange?Ct(ie):null,de=x.trackedChangeAnchorKey??null;return de&&D[de]?de:ee&&D[ee]?ee:ie&&D[ie]?ie:se&&D[se]?se:de??ee??se??ie??null},Dt=x=>{if(x==null)return[];const D=typeof x=="object"?null:x,ee=typeof x=="object"?x:Vt(x),ie=ee?.trackedChange?rt(ee?.trackedChangePositionAliases):[],se=wt(nt(ee)),de=new Set;return[D,cn(ee),ee?.trackedChangeAnchorKey,ee?.commentId,ee?.importedId,ee?.trackedChange?Ct(ee?.importedId):null,...ie.flatMap(pe=>[se&&!pe.startsWith("tc::")?e_({storyKey:se,rawId:pe}):null,pe])].map(pe=>Te(pe)).filter(pe=>!pe||de.has(pe)?!1:(de.add(pe),!0))},un=(x,D)=>{const ee=ae.value||{},ie=typeof x=="object"?x:Vt(x),se=new Set;for(const de of[D,...Dt(x)].map(pe=>Te(pe)).filter(Boolean)){if(se.has(de))continue;se.add(de);const pe=ee[de];if(pe!==void 0&&Zt(pe,ie))return{key:de,entry:pe}}return{key:null,entry:null}},Ft=x=>{x&&((x.resolvedTime!=null||x.resolvedById!=null||x.resolvedByEmail!=null||x.resolvedByName!=null)&&m.set(x,{resolvedTime:x.resolvedTime??null,resolvedById:x.resolvedById??null,resolvedByEmail:x.resolvedByEmail??null,resolvedByName:x.resolvedByName??null,trackedChangeDecision:x.trackedChangeDecision??null}),x.resolvedTime=null,x.resolvedById=null,x.resolvedByEmail=null,x.resolvedByName=null,x.trackedChangeDecision=null)},Me=x=>{if(!x)return!1;const D=m.get(x);return D?(x.resolvedTime=D.resolvedTime??Date.now(),x.resolvedById=D.resolvedById??null,x.resolvedByEmail=D.resolvedByEmail??null,x.resolvedByName=D.resolvedByName??null,x.trackedChangeDecision=D.trackedChangeDecision??null,!0):!1},Pe=x=>typeof x?.getValues=="function"?x.getValues():{...x},Ze=x=>{const D=x?.selection?.source;return D==null?!0:D===tu},ot=x=>!!x?.trackedChange||!!St(x),Mt=({documentId:x,editor:D}={})=>{if(!D?.state||!L.value?.length)return 0;const ee=ae.value||{};if(!Object.keys(ee).length)return 0;const ie=it=>it.find(dn=>ee[dn]!==void 0)??null,se=new Set,de=new Map;if(L.value.forEach(it=>{if(!it?.trackedChange)return;if(x){const Bn=it?.fileId??null;if(Bn&&Bn!==x)return}const dn=Dt(it),rn=ie(dn);rn&&(se.add(rn),de.set(rn,new Set(dn)))}),!se.size)return 0;const pe=new Set(la.getTrackChanges(D.state).map(({mark:it})=>it?.attrs?.id).filter(it=>it!=null).map(it=>String(it))),ve=typeof iu=="function"?iu(D):null;let Xe=[];try{Xe=ve?.getAll?.()??[]}catch{}const Qe=new Set(Xe.map(it=>it?.anchorKey).filter(it=>typeof it=="string"&&it.length>0)),tt=new Set(Array.from(se).filter(it=>{const dn=de.get(it)??new Set([it]);return Array.from(dn).some(rn=>Qe.has(rn))?!1:!Array.from(dn).some(rn=>pe.has(rn))}));if(!tt.size)return 0;const st=new Set;tt.forEach(it=>{(de.get(it)??new Set([it])).forEach(dn=>st.add(dn))});const vt=new Set(tt);L.value.forEach(it=>{const dn=ie(Dt(it));dn&&[St(it),it?.threadingParentCommentId,it?.parentCommentId].map(rn=>Te(rn)).filter(Boolean).some(rn=>st.has(rn))&&vt.add(dn)});const pt={...ee};if(vt.forEach(it=>{delete pt[it]}),ae.value=pt,M.value!==void 0&&M.value!==null){const it=Vt(M.value),dn=new Set(Dt(it??M.value)),rn=[St(it),it?.threadingParentCommentId,it?.parentCommentId].map(Bn=>Te(Bn)).filter(Boolean);(Array.from(dn).some(Bn=>st.has(Bn))||rn.some(Bn=>st.has(Bn)))&&Wr()}return vt.size},Et=x=>{const D=x?.state?.doc;if(!D||typeof D.descendants!="function")return null;const ee=new Set,ie=new Set;return D.descendants(se=>{se.marks?.filter(ve=>ve?.type?.name==="commentMark").forEach(ve=>{[ve.attrs?.commentId,ve.attrs?.importedId].map(Xe=>Te(Xe)).filter(Boolean).forEach(Xe=>ee.add(Xe))});const de=se.type?.name;if(de!=="commentRangeStart"&&de!=="commentRangeEnd")return;const pe=Te(se.attrs?.["w:id"]);pe&&ie.add(pe)}),{liveMarkIds:ee,resolvedAnchorIds:ie}},sn=()=>{const x=o.documents;if(!Array.isArray(x))return null;for(const D of x){const ee=typeof D?.getEditor=="function"?D.getEditor():null;if(ee?.state?.doc)return ee}return null},Tt=({editor:x}={})=>{if(V.value)return 0;const D=Et(x??sn()),ee=ae.value||{},ie=new Set(Object.keys(ee));if(!D&&!ie.size)return 0;let se=0;return L.value.forEach(de=>{if(!Ze(de)||ot(de))return;if(D){const ve=Dt(de),Xe=ve.some(tt=>D.liveMarkIds.has(tt)),Qe=ve.some(tt=>D.resolvedAnchorIds.has(tt));if(Xe&&de.resolvedTime!=null){Ft(de),se+=1;return}!Xe&&Qe&&de.resolvedTime==null&&Me(de)&&(se+=1);return}const{key:pe}=un(de);pe&&ie.has(String(pe))&&de.resolvedTime!=null&&(Ft(de),se+=1)}),se};Pt(ae,()=>{Tt()}),Pt(L,()=>{Tt()},{deep:!1});const ur=x=>{if(!x)return null;const D=x.start??x.pos??x.from,ee=x.end??x.to??D;return!Number.isFinite(D)||!Number.isFinite(ee)?null:{start:D,end:ee}},dr=x=>un(x).entry??null,jr=(x,D={})=>{const ee=typeof x=="object"?x:Vt(x);if(!ee)return null;const ie=ur(un(x).entry??null);if(!ie)return null;const se=o.getDocument(ee.fileId)?.getEditor?.()?.state?.doc;if(!se?.textBetween)return null;const de=D.separator??" ",pe=se.textBetween(ie.start,ie.end,de,de);return D.trim===!1?pe:pe?.trim()},$t=(x,D={})=>{const ee=dr(x);return ee?{position:ee,anchoredText:jr(x,D)}:null},Vn=x=>{if(!F.value)return!0;const D=We(x);return!D&&x?.parentCommentId?!1:D?.trackedChange||St(x)?c.trackChangesVisible:c.commentsVisible},Mr=(x,D)=>{const ee=x?.activeEditor,ie=J(x);if(D==null){if(Wr(),ie){ie.setActiveComment(null);return}ee?.commands?.setActiveComment({commentId:null});return}const se=Vt(D);if(se){if(M.value=se.commentId,Pu(se.commentId),ie){ie.setActiveComment(se.commentId);return}ee?.commands?.setActiveComment({commentId:M.value})}},_r=({superdoc:x,params:D,broadcastChanges:ee=!0,documentState:ie=void 0})=>{const se=QC("store.trackedChanges.handleUpdate","store-reconciliation",{event:D?.event??null,changeId:D?.changeId??null,documentId:D?.documentId??null});try{const{event:de,changeId:pe,trackedChangeText:ve,trackedChangeType:Xe,trackedChangeDisplayType:Qe,semanticColorKey:tt,semanticColor:st,deletedText:vt,trackedChangeLabel:pt,trackedChangeDetailLines:it,trackedChangeImagePreview:dn,authorId:rn,authorEmail:Bn,authorImage:Gn,date:Wn,author:vo,importedAuthor:Hn,documentId:Mn,coords:Zn,trackedChangeStory:bt,trackedChangeStoryKind:zt,trackedChangeStoryLabel:Kn,trackedChangeAnchorKey:oo,trackedChangeCanonicalId:fr,trackedChangePositionAliases:$i,importedId:gi}=D,yo=pe!=null?String(pe):null,wl=fr!=null?String(fr):null,Ps=Object.prototype.hasOwnProperty.call(D,"trackedChangePositionAliases"),oi=Ps?rt($i):void 0,vi=Object.prototype.hasOwnProperty.call(D,"importedId"),io=vi?gi!=null?String(gi):null:void 0,Do=Mn!=null?String(Mn):null;if(!(Qe==="tableInsert"||Qe==="tableDelete")&&yo){const Qt=Do??(x?.activeEditor?.options?.documentId!=null?String(x.activeEditor.options.documentId):null),Ln=Qt?o.getDocument(Qt)?.getEditor?.():null,Nn=ie!==void 0?ie:Ln?.state??x?.activeEditor?.state??null;if(Nn){const{ranges:Mi,ids:ns}=fc(Nn),Sa=la.getTrackChanges(Nn,yo),Li=Mi.length>0&&Sa.length>0&&vl(Sa,Mi),Po=Sa.length===0&&ns.has(yo);if(Li||Po){Ti({suppressedIds:new Set([yo]),activeDocumentId:Qt,superdoc:x,broadcastChanges:ee});return}}}const yi=bt!==void 0||zt!==void 0||Kn!==void 0||oo!==void 0,Vo=yi?bt??null:e,Cl=yi?zt??null:"body",es=yi&&Kn!==void 0?Kn:"",Ri=oo!==void 0?oo??null:yi?null:n(yo),Os=typeof pt=="string"&&pt.length>0?pt:null,bo=MT(it),ts=DT(dn),Ou=Fr({documentId:Mn,commentId:pe,trackedChange:!0,trackedChangeText:ve,trackedChangeType:Xe,trackedChangeDisplayType:Qe,semanticColorKey:tt,semanticColor:st,deletedText:vt,trackedChangeLabel:Os,trackedChangeDetailLines:bo,trackedChangeImagePreview:ts,createdTime:Wn,creatorId:rn??null,creatorName:vo,creatorEmail:Bn,creatorImage:Gn,isInternal:!1,importedAuthor:Hn,...vi?{importedId:io}:{},trackedChangeStory:Vo,trackedChangeStoryKind:Cl,trackedChangeStoryLabel:es,trackedChangeAnchorKey:Ri,trackedChangeCanonicalId:wl,...Ps?{trackedChangePositionAliases:oi}:{},selection:{source:tu,selectionBounds:Zn}}),_l=()=>{const Qt=Ri!=null?String(Ri):null;if(!yo)return null;const Ln=Nn=>{if(!Nn)return!1;const Mi=Nn.trackedChangeAnchorKey!=null?String(Nn.trackedChangeAnchorKey):null,ns=Nn.commentId!=null?String(Nn.commentId):null,Sa=Nn.importedId!=null?String(Nn.importedId):null,Li=Nn.trackedChangeCanonicalId!=null?String(Nn.trackedChangeCanonicalId):null,Po=wl&&wl!==yo||Li&&Li!==ns;return ns===yo||!Po&&(Sa===yo||io!==void 0&&io!=null&&Sa===io)?!0:Po?!1:Qt&&Mi?Mi===Qt:!1};return Do?L.value.find(Nn=>Ln(Nn)&&Lo(Nn,Do)):L.value.find(Ln)},_a=Qt=>{ee&&(jl(x,Qt),Ei(pe,Qt,x))},ht=(Qt,Ln,Nn)=>Qt?.[Ln]==null&&Nn==null||!Qt||t_(Qt[Ln],Nn)?!1:(Qt[Ln]=Nn,!0),Fu=Qt=>{if(!Qt)return!1;let Ln=!1;return Vo!=null&&(Ln=ht(Qt,"trackedChangeStory",Vo)||Ln),Cl!=null&&(Ln=ht(Qt,"trackedChangeStoryKind",Cl)||Ln),es!==void 0&&es!==""&&(Ln=ht(Qt,"trackedChangeStoryLabel",es)||Ln),Ri!=null&&(Ln=ht(Qt,"trackedChangeAnchorKey",Ri)||Ln),Ln},qt=Qt=>{const Ln={trackedChangeText:ve??null,trackedChangeType:Xe??null,trackedChangeDisplayType:Qe??null,semanticColorKey:tt??null,semanticColor:st??null,deletedText:vt??null,trackedChangeLabel:Os,trackedChangeImagePreview:ts,trackedChangeCanonicalId:wl,creatorId:rn??null,creatorName:vo??null,creatorEmail:Bn??null,creatorImage:Gn??null,createdTime:Wn??null};vi&&(Ln.importedId=io),Ps&&(Ln.trackedChangePositionAliases=oi);let Nn=!1;for(const[Mi,ns]of Object.entries(Ln))Nn=ht(Qt,Mi,ns)||Nn;return Qt&&!(Qt.trackedChangeDetailLines==null&&bo==null)&&!LT(Qt.trackedChangeDetailLines,bo)&&(Qt.trackedChangeDetailLines=bo,Nn=!0),Fu(Qt)||Nn},pc=Qt=>{const Ln=!!(Qt.resolvedTime||Qt.resolvedById||Qt.resolvedByEmail||Qt.resolvedByName);return Ln&&Ft(Qt),qt(Qt)||Ln};if(de==="add"){const Qt=_l();if(Qt){if(!pc(Qt))return;_a({type:S.UPDATE,comment:Pe(Qt)});return}Jo({superdoc:x,comment:Ou,broadcastChanges:ee})}else if(de==="update"){const Qt=_l();if(!Qt||!pc(Qt))return;_a({type:S.UPDATE,comment:Pe(Qt)})}else if(de==="resolve"){const Qt=_l(),Ln={id:D.resolvedById??x?.user?.id??null,email:D.resolvedByEmail??x?.user?.email??null,name:D.resolvedByName??x?.user?.name??null,decision:D.decision??null,superdoc:x};Qt&&!Qt.resolvedTime&&Qt.resolveComment({...Ln,reconciliationToken:VC})}}finally{Zd(se)}},po=(x=[])=>({insertedMark:x.find(({mark:D})=>D?.type?.name==="trackInsert")?.mark??null,deletionMark:x.find(({mark:D})=>D?.type?.name==="trackDelete")?.mark??null,formatMark:x.find(({mark:D})=>D?.type?.name==="trackFormat")?.mark??null}),Kt=({superdoc:x,editor:D,changeIds:ee,broadcastChanges:ie=!0})=>{if(!x||!D?.state||!Array.isArray(ee)||!ee.length)return;const se=D?.options?.documentId!=null?String(D.options.documentId):null;if(se)for(const de of new Set(ee.map(pe=>pe!=null?String(pe):null).filter(Boolean))){const pe=la.getTrackChanges(D.state,de);if(!pe.length)continue;const ve=Hy({event:"update",marks:po(pe),nodes:[],newEditorState:D.state,documentId:se,trackedChangesForId:pe});ve&&(ve.trackedChangeStory=e,ve.trackedChangeStoryKind="body",ve.trackedChangeStoryLabel="",ve.trackedChangeAnchorKey=n(ve.changeId??de),_r({superdoc:x,params:ve,broadcastChanges:ie}))}},yn=(x=null,D=null,ee=null)=>{const ie=Number.isFinite(x);ze.value=ie?x:null,Ve.value=ie&&D!=null?String(D):null;const se=ee??D;Q.value=ie&&se!=null?String(se):null},xo=()=>{const x=ze.value;return Number.isFinite(x)?x:null},Zo=()=>{ze.value=null,Ve.value=null,Q.value=null},Ei=(x,D,ee,ie=1e3)=>{h[x]&&clearTimeout(h[x]),h[x]=setTimeout(()=>{ee&&ee.emit("comments-update",D),delete h[x]},ie)},pi=(x,D)=>{if(D?.source!=="document-editor")return null;const ee=D?.documentId??null,ie=x?.activeEditor?.options?.documentId??null;if(!ee||!ie||ee!==ie)return null;let se;try{se=x?.activeEditor?.doc?.selection?.current}catch{return null}if(typeof se!="function")return null;try{return se()}catch{return null}},Ss=(x,D=null)=>{const ee=J(x),ie=pi(x,o.activeSelection),se={type:S.PENDING,pendingSelection:ie};if(x.emit("comments-update",se),ee){const pe=ee.getCapabilityState?.();return pe&&pe.canWrite===!1?{ok:!1,reason:pe.reason}:Promise.resolve(ee.captureCurrentSelection?.()).then(ve=>{if(!ve?.ok)return{ok:!1,reason:ve?.reason??"editing-range-required",detail:ve?.detail};$.value=ve.target??null;const Xe=ee.documentId??x?.activeEditor?.options?.documentId??null;return _.value=Fr({selection:{source:tu,documentId:Xe,page:1,selectionBounds:{}},documentId:Xe,parentCommentId:null}),x.config.isInternal||(_.value.isInternal=!1),yn(D,"pending"),Ji(null),M.value=_.value.commentId,{ok:!0}}).catch(ve=>({ok:!1,reason:"selection-capture-failed",detail:ve?.message??String(ve)}))}const de={...o.activeSelection};return de.selectionBounds={...de.selectionBounds},o.selectionPosition?.source&&o.selectionPosition.source!=="pdf"&&(o.selectionPosition.source=null),_.value=Fr({selection:de,documentId:de.documentId,parentCommentId:null}),x.config.isInternal||(_.value.isInternal=!1),x.activeEditor?.commands&&x.activeEditor.commands.insertComment({..._.value.getValues(),commentId:"pending",skipEmit:!0}),_.value.selection.source==="document-editor"&&o.selectionPosition&&(o.selectionPosition.source=tu),yn(D,"pending"),Ji(null),M.value=_.value.commentId,{ok:!0}},ks=x=>{const D=un(x).entry;return D?Number.isFinite(D.start)?D.start:Number.isFinite(D.pos)?D.pos:Number.isFinite(D.from)?D.from:Number.isFinite(D.to)?D.to:Number.isFinite(D.pageIndex)&&Number.isFinite(D?.bounds?.top)?D.pageIndex*1e6+D.bounds.top:null:null},As=(x,D)=>(x.createdTime??0)-(D.createdTime??0),al=(x,D)=>{const ee=ks(x),ie=ks(D),se=Number.isFinite(ee),de=Number.isFinite(ie);return se&&de&&ee!==ie?ee-ie:se&&!de?-1:!se&&de?1:As(x,D)},Wi=x=>{const D=[],ee=[],ie=new Map;return L.value.forEach(se=>{if(!Vn(se))return;const de=Nt(se)?St(se):null,pe=se.parentCommentId||de;se.resolvedTime?ee.push(se):!pe&&!se.resolvedTime?D.push({...se}):pe&&(ie.has(pe)||ie.set(pe,[]),ie.get(pe).push(se))}),{parentComments:D.sort(x),resolvedComments:ee.sort(x)}},ro=Se(()=>Wi(As)),ke=Se(()=>ro.value?.parentComments.some(x=>x.trackedChange&&!x.resolvedTime)??!1),Oe=Se(()=>Wi(al)),ft=x=>P.includes(x),lt=Se(()=>o.documents),bn=Se(()=>i),an=(x,D)=>{const ee=x.getContainerLocation(D);return{top:ee.top+x.selectionBounds.top,left:ee.left+x.selectionBounds.left}},Fr=({selection:x,documentId:D,parentCommentId:ee,...ie})=>mo({selection:x,documentId:D,parentCommentId:ee,...ie}),mo=({selection:x,documentId:D,parentCommentId:ee,...ie})=>{let se;return D?se=o.getDocument(D):x&&(se=o.getDocument(x.documentId)),se||(se=o.documents[0]),aa({fileId:se.id,fileType:se.type,parentCommentId:ee,creatorId:o.user.id,creatorEmail:o.user.email,creatorName:o.user.name,creatorImage:o.user.image,commentText:I.value,selection:x,...ie})},go=x=>{const D=!!_.value;I.value="",_.value=null,$.value=null,o.selectionPosition=null,D&&Wr(),!K(x)&&x?.activeEditor?.commands?.removeComment({commentId:"pending"})},To=({superdoc:x,comment:D,skipEditorUpdate:ee=!1,broadcastChanges:ie=!0,isHydration:se=!1})=>{if(u()&&!se)return s();const de=!ee&&!se?J(x):null;if(de&&!D.trackedChange){const Qe=Uy(_.value?I.value:D.commentText),tt=_.value?$.value:null,st=D.parentCommentId?String(D.parentCommentId):(_.value,null);return(async()=>{try{return await(st?de.reply({parentCommentId:st,text:Qe}):de.commitPendingComment({text:Qe,target:tt}))}catch(vt){return{ok:!1,reason:"adapter-threw",detail:vt?.message??String(vt)}}})().then(vt=>{if(!Uo(de))return{ok:!1,reason:"adapter-stale"};if(!vt?.ok)return ie&&x.emit("comments-update",{type:S.PENDING,rejected:!0,reason:vt?.reason??"v2-create-failed",...vt?.committed?{committed:!0}:{}}),vt;const pt=qi({superdoc:x,adapter:de,documentId:de.documentId,items:vt.items});return _.value&&go(x),ie&&x.emit("comments-update",{type:S.ADD,comment:pt?.added?.getValues?.()??null}),{ok:!0,comment:pt?.added??null}})}let pe=L.value.find(Qe=>Qe.commentId===M.value);pe||(pe=D);const ve=aa(D.getValues());_.value?ve.setText({text:I.value,suppressUpdate:!0}):ve.setText({text:D.commentText,suppressUpdate:!0}),ve.selection.source=_.value?.selection?.source??ve.selection.source,pe&&(ve.isInternal=pe.isInternal),x.config.isInternal||(ve.isInternal=!1),L.value.push(ve),go(x),!ee&&!D.trackedChange&&x.activeEditor?.commands&&!D.parentCommentId&&x.activeEditor.commands.insertComment({...ve.getValues(),skipEmit:!0});const Xe={type:S.ADD,comment:ve.getValues()};return ie&&(jl(x,Xe),x.emit("comments-update",Xe)),{ok:!0,comment:ve}},Is=({superdoc:x,comment:D,skipEditorUpdate:ee=!1,broadcastChanges:ie=!0})=>To({superdoc:x,comment:D,skipEditorUpdate:ee,broadcastChanges:ie}),Jo=({superdoc:x,comment:D,skipEditorUpdate:ee=!1,broadcastChanges:ie=!0})=>To({superdoc:x,comment:D,skipEditorUpdate:ee,broadcastChanges:ie,isHydration:!0}),Ro=({commentId:x,superdoc:D})=>{if(u())return Promise.resolve(s());const ee=L.value.findIndex(tt=>tt.commentId===x),ie=L.value[ee];if(!ie)return Promise.resolve({ok:!1,reason:"comment-not-found"});const{commentId:se,importedId:de}=ie,{fileId:pe}=ie,ve=J(D);if(ve&&!ie.trackedChange)return(async()=>{try{return await ve.delete({commentId:se})}catch(tt){return{ok:!1,reason:"adapter-threw",detail:tt?.message??String(tt)}}})().then(tt=>Uo(ve)?tt?.ok?(qi({superdoc:D,adapter:ve,documentId:ve.documentId??pe,items:tt.items}),D.emit("comments-update",{type:S.DELETED,comment:ie.getValues(),changes:[{key:"deleted",commentId:se,fileId:pe}]}),{ok:!0}):(D.emit("comments-update",{type:S.DELETED,rejected:!0,comment:ie.getValues(),reason:tt?.reason??"v2-delete-failed",...tt?.committed?{committed:!0}:{}}),tt):{ok:!1,reason:"adapter-stale"});D.activeEditor?.commands?.removeComment({commentId:se,importedId:de}),L.value.splice(ee,1);const Xe=L.value.filter(tt=>tt.parentCommentId===se).map(tt=>tt.commentId||tt.importedId);L.value=L.value.filter(tt=>!Xe.includes(tt.commentId)),(M.value===se||Xe.includes(M.value))&&Wr();const Qe={type:S.DELETED,comment:ie.getValues(),changes:[{key:"deleted",commentId:se,fileId:pe}]};return D.emit("comments-update",Qe),jl(D,Qe),Promise.resolve({ok:!0})},Ki=async({superdoc:x,adapter:D,fileId:ee,operation:ie,eventType:se,rejectionFallbackReason:de,rejectionEventExtras:pe={},validateOutcome:ve,successEventBuilder:Xe})=>{let Qe;try{Qe=await ie()}catch(pt){Qe={ok:!1,reason:"adapter-threw",detail:pt?.message??String(pt)}}if(!Uo(D))return{ok:!1,reason:"adapter-stale"};if(!Qe?.ok){const pt={type:se,rejected:!0,reason:Qe?.reason??de,...Qe?.committed?{committed:!0}:{},...Qe?.code!==void 0?{code:Qe.code}:{},...Qe?.detail!==void 0?{detail:Qe.detail}:{},...pe};return x?.emit?.("comments-update",pt),Qe}const tt=ve?.({outcome:Qe});if(tt?.ok===!1){const pt={ok:!1,committed:tt.committed??!0,reason:tt.reason??de,...tt.code!==void 0?{code:tt.code}:{},...tt.detail!==void 0?{detail:tt.detail}:{}},it={type:se,rejected:!0,reason:pt.reason,...pt.committed?{committed:!0}:{},...pt.code!==void 0?{code:pt.code}:{},...pt.detail!==void 0?{detail:pt.detail}:{},...pe};return x?.emit?.("comments-update",it),pt}const st=qi({superdoc:x,adapter:D,documentId:D.documentId??ee,items:Qe.items??[]}),vt=Xe?.({outcome:Qe,reconciled:st})??null;return vt&&x?.emit?.("comments-update",vt),{ok:!0,items:Qe.items??[],reconciled:st}},Gr=({outcome:x,adapter:D,fileId:ee})=>(x.items??[]).map(ie=>D.mapV2CommentToUseCommentInput(ie,{fileId:ee,fileType:null})).filter(Boolean),Sr=x=>{const D=x?.commentId??x?.importedId;return D!=null?String(D):null},Mo=x=>x?.parentCommentId!=null?String(x.parentCommentId):null,Ho=({outcome:x,adapter:D,fileId:ee,commentId:ie,expectedResolved:se,operation:de})=>{const pe=ie!=null?String(ie):null,ve=Gr({outcome:x,adapter:D,fileId:ee}),Xe=ve.find(it=>Sr(it)===pe)??null,Qe=Xe?.parentCommentId?ve.find(it=>Sr(it)===Mo(Xe))??null:Xe,tt=Sr(Qe);if(!Qe||!tt)return{ok:!1,reason:`v2-${de}-refresh-missing`,detail:`comment ${pe} was absent from the refreshed v2 comment list after ${de}`};const st=[Qe,...ve.filter(it=>Mo(it)===tt)],vt=it=>!!it?.resolvedTime;if(st.filter(it=>vt(it)!==se).length===0)return{ok:!0};const pt=vt(Qe);return st.some(it=>vt(it)!==pt)?{ok:!1,reason:`v2-${de}-refresh-split-thread`,detail:{rootId:tt,expected:se?"resolved":"open",observed:st.map(it=>({commentId:Sr(it),parentCommentId:Mo(it),status:vt(it)?"resolved":"open"}))}}:{ok:!1,reason:se?`v2-${de}-refresh-still-open`:`v2-${de}-refresh-still-resolved`,detail:`comment ${tt} remained ${pt?"resolved":"open"} after ${de}`}},$o=async({superdoc:x,parentCommentId:D,text:ee}={})=>{if(u())return s();const ie=J(x);if(!ie)return{ok:!1,reason:"v2-comments-adapter-missing"};const se=D!=null?String(D):null;if(!se)return{ok:!1,reason:"parent-comment-id-missing"};const de=Uy(ee);if(de.length===0)return{ok:!1,reason:"comment-text-empty"};const pe=L.value.find(ve=>String(ve.commentId)===se);return Ki({superdoc:x,adapter:ie,fileId:pe?.fileId??ie.documentId??null,operation:()=>ie.reply({parentCommentId:se,text:de}),eventType:S.ADD,rejectionFallbackReason:"v2-reply-failed",rejectionEventExtras:pe?{comment:Pe(pe)}:{},successEventBuilder:({reconciled:ve})=>({type:S.ADD,comment:ve?.added?.getValues?.()??null})})},ll=async({superdoc:x,commentId:D,text:ee}={})=>{if(u())return s();const ie=J(x);if(!ie)return{ok:!1,reason:"v2-comments-adapter-missing"};const se=D!=null?String(D):null;if(!se)return{ok:!1,reason:"comment-id-missing"};const de=Uy(ee);if(de.length===0)return{ok:!1,reason:"comment-text-empty"};const pe=L.value.find(ve=>String(ve.commentId)===se);return Ki({superdoc:x,adapter:ie,fileId:pe?.fileId??ie.documentId??null,operation:()=>ie.edit({commentId:se,text:de}),eventType:S.UPDATE,rejectionFallbackReason:"v2-edit-failed",rejectionEventExtras:pe?{comment:Pe(pe),changes:[{key:"text",value:de}]}:{},successEventBuilder:()=>{const ve=L.value.find(Xe=>String(Xe.commentId)===se)??pe;return ve?{type:S.UPDATE,comment:Pe(ve),changes:[{key:"text",value:ve.commentText??de}]}:null}})},oc=async({superdoc:x,commentId:D}={})=>{if(u())return s();if(l())return a();const ee=J(x);if(!ee)return{ok:!1,reason:"v2-comments-adapter-missing"};const ie=D!=null?String(D):null;if(!ie)return{ok:!1,reason:"comment-id-missing"};const se=L.value.find(ve=>String(ve.commentId)===ie),de=se?.fileId??ee.documentId??null,pe=await Ki({superdoc:x,adapter:ee,fileId:de,operation:()=>ee.resolve({commentId:ie}),eventType:S.RESOLVED,rejectionFallbackReason:"v2-resolve-failed",rejectionEventExtras:se?{comment:Pe(se)}:{},validateOutcome:({outcome:ve})=>Ho({outcome:ve,adapter:ee,fileId:de,commentId:ie,expectedResolved:!0,operation:"resolve"}),successEventBuilder:()=>{const ve=L.value.find(Xe=>String(Xe.commentId)===ie)??se;return ve?{type:S.RESOLVED,comment:Pe(ve)}:null}});if(pe?.ok){const Xe=!!L.value.find(tt=>String(tt.commentId)===ie)?.resolvedTime,Qe=M.value!=null?String(M.value):null;Xe&&Qe===ie&&Wr()}return pe},kr=async({superdoc:x,commentId:D}={})=>{if(u())return s();if(l())return a();const ee=J(x);if(!ee)return{ok:!1,reason:"v2-comments-adapter-missing"};const ie=D!=null?String(D):null;if(!ie)return{ok:!1,reason:"comment-id-missing"};const se=L.value.find(pe=>String(pe.commentId)===ie),de=se?.fileId??ee.documentId??null;return Ki({superdoc:x,adapter:ee,fileId:de,operation:()=>ee.reopen({commentId:ie}),eventType:S.UPDATE,rejectionFallbackReason:"v2-reopen-failed",rejectionEventExtras:se?{comment:Pe(se),changes:[{key:"resolvedTime",value:null}]}:{},validateOutcome:({outcome:pe})=>Ho({outcome:pe,adapter:ee,fileId:de,commentId:ie,expectedResolved:!1,operation:"reopen"}),successEventBuilder:()=>{const pe=L.value.find(ve=>String(ve.commentId)===ie);return!pe||pe.resolvedTime?null:{type:S.UPDATE,comment:Pe(pe),changes:[{key:"resolvedTime",value:null}]}}})},Uo=x=>x?V.value===x:!1,xi=x=>x?W.value===x:!1,cl=async({superdoc:x,adapter:D,documentId:ee}={})=>ou("store.comments.hydrateFromV2","comments-list",{documentId:ee??null},async()=>{const ie=D??J(x);if(!ie||typeof ie.refresh!="function")return{ok:!1,reason:"adapter-missing"};let se;try{se=await ie.refresh()}catch(de){return{ok:!1,reason:"adapter-threw",detail:de?.message??String(de)}}return Uo(ie)?se?.ok?(qi({superdoc:x,adapter:ie,documentId:ee,items:se.items??[]}),{ok:!0,items:se.items??[]}):se:{ok:!1,reason:"adapter-stale"}}),qi=({superdoc:x,adapter:D,documentId:ee,items:ie}={})=>ou("store.comments.reconcile","store-reconciliation",{documentId:ee??null,itemCount:Array.isArray(ie)?ie.length:null},()=>{if(!D||!Array.isArray(ie))return{added:null};if(!Uo(D))return{added:null,dropped:"adapter-stale"};const se=ee??D.documentId??null,de=se!=null?String(se):null,pe=(se?o.getDocument(se):null)?.type??null,ve=bt=>typeof bt!="string"?!0:bt.replace(/<[^>]*>/g,"").replace(/ /gi," ").trim().length===0,Xe=bt=>!bt||bt.trackedChange===!0||!bt.trackedChangeThreadParentId||bt.parentCommentId?!1:ve(bt.commentText),Qe=M.value!=null?String(M.value):null,tt=Qe?L.value.find(bt=>String(bt.commentId)===Qe)??null:null,st=tt!=null&&_.value!=null&&(tt===_.value||_.value.commentId!=null&&String(tt.commentId??"")===String(_.value.commentId)),vt=tt!=null&&!st&&tt.trackedChange!==!0&&!hp(tt)&&(de==null||tt.fileId==null||String(tt.fileId)===de),pt=new Map,it=new Map,dn=[];for(const bt of ie){if(YC(bt))continue;const zt=D.mapV2CommentToUseCommentInput(bt,{fileId:se,fileType:pe});if(zt){if(Xe(zt)){it.set(String(zt.commentId),String(zt.trackedChangeThreadParentId)),w("hydrate:drop-v2-sidecar-comment",{commentId:zt.commentId??null,importedId:zt.importedId??null,parentCommentId:zt.parentCommentId??null,trackedChangeParentId:zt.trackedChangeParentId??null,trackedChangeThreadParentId:zt.trackedChangeThreadParentId??null,trackedChangeSide:zt.trackedChangeSide??null,commentText:zt.commentText??null});continue}dn.push(zt)}}for(const bt of dn){const zt=bt.parentCommentId!=null?String(bt.parentCommentId):null,Kn=zt?it.get(zt):null;Kn&&(bt.threadingParentCommentId=Kn,bt.trackedChangeThreadParentId==null&&(bt.trackedChangeThreadParentId=Kn));const oo=bt.commentId!=null?String(bt.commentId):null;oo&&pt.set(oo,bt)}const rn=bt=>{if(de==null)return!0;const zt=bt?.fileId!=null?String(bt.fileId):null;return zt==null?!0:zt===de},Bn=_.value?.commentId!=null?String(_.value.commentId):null,Gn=bt=>!bt||!_.value?!1:bt===_.value||Bn!=null&&String(bt.commentId??"")===Bn,Wn=bt=>!bt||Gn(bt)||bt.trackedChange===!0||hp(bt)?!1:bt.commentId!=null,vo=(bt,zt)=>{bt.commentText=zt.commentText??bt.commentText,bt.isInternal=typeof zt.isInternal=="boolean"?zt.isInternal:bt.isInternal,typeof zt.resolvedTime=="number"?(bt.resolvedTime=zt.resolvedTimeWasSynthesized===!0&&typeof bt.resolvedTime=="number"?bt.resolvedTime:zt.resolvedTime,bt.resolvedByEmail=zt.resolvedByEmail??null,bt.resolvedByName=zt.resolvedByName??null):(bt.resolvedTime=null,bt.resolvedByEmail=null,bt.resolvedByName=null),zt.parentCommentId!==void 0?bt.parentCommentId=zt.parentCommentId:delete bt.parentCommentId,zt.trackedChangeParentId!==void 0?bt.trackedChangeParentId=zt.trackedChangeParentId:delete bt.trackedChangeParentId,zt.trackedChangeThreadParentId!==void 0?bt.trackedChangeThreadParentId=zt.trackedChangeThreadParentId:bt.trackedChangeThreadParentId=void 0,zt.trackedChangeSide!==void 0?bt.trackedChangeSide=zt.trackedChangeSide:delete bt.trackedChangeSide,zt.threadingParentCommentId!==void 0?bt.threadingParentCommentId=zt.threadingParentCommentId:delete bt.threadingParentCommentId},Hn=[],Mn=new Set,Zn=[];for(const bt of L.value){if(!Wn(bt)||!rn(bt)){Hn.push(bt);continue}const zt=String(bt.commentId),Kn=pt.get(zt);Kn&&(vo(bt,Kn),Mn.add(zt),Hn.push(bt))}for(const[bt,zt]of pt.entries()){if(Mn.has(bt))continue;const Kn=aa(zt);Hn.push(Kn),Zn.push(Kn)}return L.value=Hn,vt&&Qe&&!Hn.some(bt=>String(bt.commentId)===Qe)&&Wr(),{added:Zn[Zn.length-1]??null}}),mi=x=>{go(x)},Rf=x=>typeof x!="string"?null:x.replace(/\s*\(imported\)\s*$/u,"").trim()||null,ei=x=>{if(!x)return null;try{if(x.isDestroyed===!0)return null;const D=x.view;if(!D||D.isDestroyed===!0||D.destroyed===!0)return null;const ee=D.state;return ee?{view:D,state:ee}:null}catch{return null}},ul=x=>x!=null&&String(x).length>0?String(x):null,jn=x=>{const D=ul(x),ee=D?[[D,p.get(D)]]:Array.from(p.entries());let ie=0;for(const[se,de]of ee)de&&(p.delete(se),de.timeoutHandle!==null&&de.timeoutHandle!==void 0&&clearTimeout(de.timeoutHandle),ie+=1);return ie},ic=x=>{const D=ei(x);if(!D)return null;let ee=[];try{ee=la.getTrackChanges(D.state)??[]}catch{return null}const ie=la?.enumerateStructuralRowChanges;let se=[];if(typeof ie=="function")try{se=ie(D.state)??[]}catch{se=[]}let de=[];if(typeof iu=="function")try{de=iu(x)?.getAll?.()??[]}catch{de=[]}return{...D,trackedChanges:ee,structuralChanges:se,storySnapshots:de}},wu=(x,D,ee=null)=>{if(!x||!D)return!1;const ie=ee??ic(x);return ie?(_u(x,D,ie.trackedChanges,{editorState:ie.state,editorView:ie.view}),uc({superdoc:D,editor:x,snapshots:ie.storySnapshots,documentState:ie.state,resolveFromEditor:!1}),Iu({superdoc:D,editor:x,structuralChanges:ie.structuralChanges}),!0):!1},ba=x=>{if(!x||p.get(x.documentId)!==x)return!1;try{const D=x.editor?.options?.documentId;if(D!=null&&String(D)!==x.documentId)return!1;const ee=o.getDocument(x.documentId);if(!ee||ee.getEditor?.()!==x.editor)return!1}catch{return!1}return!0},Yi=x=>{if(!ba(x))return p.get(x?.documentId)===x&&p.delete(x.documentId),!1;const D=ic(x.editor);if(!D||!ba(x))return p.get(x.documentId)===x&&p.delete(x.documentId),!1;try{return wu(x.editor,x.superdoc,D)}finally{p.get(x.documentId)===x&&p.delete(x.documentId)}},Es=({editor:x,superdoc:D,documentId:ee,defer:ie=!0})=>{const se=ul(ee);if(!se||!x||!D)return!1;jn(se);const de={documentId:se,editor:x,superdoc:D,generation:++g,timeoutHandle:null};return p.set(se,de),ie?(de.timeoutHandle=setTimeout(()=>{de.timeoutHandle=null,Yi(de)},0),!0):Yi(de)};function dl(x){const D=x!=null?String(x):null;if(!D)return;jn(D);const ee=L.value.filter(de=>hl(de,D,{allowSingleDocumentMismatch:!0}));if(!ee.length)return;const ie=new Set;if(ee.forEach(de=>{Dt(de).forEach(pe=>ie.add(pe))}),L.value=L.value.filter(de=>!ee.includes(de)),ie.size){const de={...ae.value||{}};ie.forEach(pe=>{delete de[pe]}),ae.value=de}const se=M.value!=null?String(M.value):null;se&&ie.has(se)&&Wr()}function Cu(x){dl(x)}const fl=async({superdoc:x,editor:D,comments:ee,documentId:ie,replacedFile:se=!1})=>{const de=o.getDocument(ie);if(de?.commentThreadingProfile&&(de.commentThreadingProfile.value=D?.converter?.commentThreadingProfile||null),se&&Cu(ie),ee.forEach(pe=>{const ve=Array.isArray(pe.elements)?pe.elements:[],Xe=Ff(ve);if(!Xe&&!pe.trackedChange)return;const Qe=Rf(pe.creatorName),tt=Qe?`${Qe} (imported)`:null;Jo({superdoc:x,comment:aa({fileId:ie,fileType:de.type,docxCommentJSON:ve.length?ve:null,commentId:pe.commentId,isInternal:!1,parentCommentId:pe.parentCommentId,trackedChangeParentId:pe.trackedChangeParentId,trackedChangeThreadParentId:pe.trackedChangeThreadParentId,creatorId:null,creatorName:Qe,createdTime:pe.createdTime,creatorEmail:pe.creatorEmail,importedAuthor:{...tt?{name:tt}:{},email:pe.creatorEmail},commentText:Xe,resolvedTime:pe.isDone?Date.now():null,resolvedById:null,resolvedByEmail:pe.isDone?pe.creatorEmail:null,resolvedByName:pe.isDone?tt||"(Imported)":null,trackedChange:pe.trackedChange||!1,trackedChangeText:pe.trackedChangeText,trackedChangeType:pe.trackedChangeType,trackedChangeDisplayType:pe.trackedChangeDisplayType,deletedText:pe.trackedDeletedText,origin:pe.origin||"word",threadingMethod:pe.threadingMethod,threadingStyleOverride:pe.threadingStyleOverride,threadingParentCommentId:pe.threadingParentCommentId,originalXmlStructure:pe.originalXmlStructure})})}),se){Es({editor:D,superdoc:x,documentId:ie,defer:!1});return}Es({editor:D,superdoc:x,documentId:ie})},_u=(x,D,ee=null,ie={})=>{const{reopenResolved:se=!1,refreshExisting:de=!1,broadcastChanges:pe=!0,editorState:ve=null,editorView:Xe=null}=ie,Qe=ve?{state:ve,view:Xe}:ei(x);if(!Qe?.state)return;const tt=Qe.state,st=ee??la.getTrackChanges(tt),vt=tT(st),pt=x?.options?.documentId!=null?String(x.options.documentId):null;if(!pt)return;const it=new Set,dn=new Map;L.value.forEach(Hn=>{if(!Hn?.trackedChange||!Lo(Hn,pt)||!t(Hn))return;const Mn=[Hn.commentId,Hn.importedId].map(Zn=>Zn!=null?String(Zn):null).filter(Boolean);if(Hn.resolvedTime){se||Mn.forEach(Zn=>it.add(Zn));return}Mn.forEach(Zn=>{dn.set(Zn,Hn),de||it.add(Zn)})});const rn=new Map;for(const Hn of st){const Mn=Hn.mark.attrs.id;rn.has(Mn)||rn.set(Mn,[]),rn.get(Mn).push(Hn)}const Bn=pt,Gn=new Set;vt.forEach(({insertedMark:Hn,deletionMark:Mn,formatMark:Zn})=>{const bt=Hn?.mark.attrs.id||Mn?.mark.attrs.id||Zn?.mark.attrs.id;if(bt==null)return;const zt=String(bt);if(Gn.has(zt)||(Gn.add(zt),!de&&it.has(zt)))return;const Kn=dn.get(zt),oo={...Hn&&{insertedMark:Hn.mark},...Mn&&{deletionMark:Mn.mark},...Zn&&{formatMark:Zn.mark}},fr=Hy({event:Kn?"update":"add",marks:oo,nodes:[],newEditorState:tt,documentId:Bn,trackedChangesForId:rn.get(bt)||[]});if(fr){const $i=n(fr.changeId??bt);fr.trackedChangeStory=e,fr.trackedChangeStoryKind="body",fr.trackedChangeStoryLabel="",fr.trackedChangeAnchorKey=$i,_r({superdoc:D,params:fr,broadcastChanges:pe,documentState:tt}),Kn||(it.add(zt),fr.changeId!=null&&it.add(String(fr.changeId)),fr.importedId!=null&&it.add(String(fr.importedId)))}});const Wn=Qe.view;try{if(!Wn||x.view!==Wn||Wn.isDestroyed===!0||Wn.destroyed===!0)return}catch{return}const{tr:vo}=tt;vo.setMeta(kT,{type:"force"}),Wn.dispatch(vo)},Ti=({suppressedIds:x,activeDocumentId:D,superdoc:ee=null,broadcastChanges:ie=!0})=>{if(!(x instanceof Set)||!x.size||!D)return;const se=[];if(L.value=L.value.filter(ve=>{if(!ve?.trackedChange||!t(ve)||Mu(ve)||!Lo(ve,D))return!0;const Xe=ve.commentId!=null?String(ve.commentId):null,Qe=ve.importedId!=null?String(ve.importedId):null;return Xe&&x.has(Xe)||Qe&&x.has(Qe)?(se.push(ve),!1):!0}),!se.length)return;const de=new Set;se.forEach(ve=>{ve.commentId!=null&&de.add(String(ve.commentId)),ve.importedId!=null&&de.add(String(ve.importedId));const Xe=Pe(ve),Qe={type:S.DELETED,comment:Xe,changes:[{key:"deleted",commentId:Xe.commentId,fileId:Xe.fileId}]};ie&&(jl(ee,Qe),ee?.emit?.("comments-update",Qe))});const pe=M.value!=null?String(M.value):null;pe&&de.has(pe)&&Wr()},xs=x=>x?x.fileId!=null?String(x.fileId):x.documentId!=null?String(x.documentId):x.selection?.documentId!=null?String(x.selection.documentId):null:null,Mf=()=>{const x=Array.isArray(o.documents)?o.documents:o.documents?.value;return Array.isArray(x)?x:[]},Ts=()=>{const x=Mf();return x.length!==1?null:x[0]?.id!=null?String(x[0].id):null},hl=(x,D,ee={})=>{const{allowSingleDocumentMismatch:ie=!1}=ee;if(!D)return!1;const se=xs(x);if(se){if(se===D)return!0;const de=Ts();return ie&&de===D}return Ts()===D},Lo=(x,D)=>hl(x,D,{allowSingleDocumentMismatch:!0}),ti=x=>{const D=typeof x=="string"?x.toLowerCase():"";return D?D==="insert"||D==="insertion"||D==="trackinsert"||D==="tableinsert"||D==="paragraphsplit"?"insertion":D==="delete"||D==="deletion"||D==="trackdelete"||D==="tabledelete"?"deletion":D:null},Su=({comment:x,decision:D}={})=>{const ee=D==="accept"||D==="reject"?D:null;if(!ee)return!1;const ie=ti(x?.trackedChangeDisplayType)??ti(x?.trackedChangeType);return ee==="accept"&&ie==="insertion"||ee==="reject"&&ie==="deletion"},ku=(x,D,ee,ie=null,{broadcastChanges:se=!0}={})=>ou("store.trackedChanges.pruneStaleComments","store-reconciliation",{activeDocumentId:ee??null,liveIdCount:x instanceof Set?x.size:null,liveAnchorKeyCount:D instanceof Set?D.size:null},()=>{if(!(x instanceof Set)||!ee)return;const de=new Set,pe=[],ve=[...L.value];if(L.value=L.value.filter(st=>{if(!st?.trackedChange||!Lo(st,ee))return!0;const vt=st.commentId!=null?String(st.commentId):null,pt=st.importedId!=null?String(st.importedId):null,it=st.trackedChangeAnchorKey!=null?String(st.trackedChangeAnchorKey):null,dn=!!(vt&&x.has(vt)),rn=!!(pt&&x.has(pt)),Bn=!!(it&&D?.has(it));if(!vt&&!pt&&!it||dn||rn||Bn||st.resolvedTime)return!0;const Gn=m.get(st);return Gn?(st.resolvedTime=Gn.resolvedTime??Date.now(),st.resolvedById=Gn.resolvedById??null,st.resolvedByEmail=Gn.resolvedByEmail??null,st.resolvedByName=Gn.resolvedByName??null,st.trackedChangeDecision=Gn.trackedChangeDecision??null,pe.push(st),!0):(vt&&de.add(vt),pt&&de.add(pt),!1)}),pe.forEach(st=>{const vt=Pe(st),pt={type:S.UPDATE,comment:vt};se&&(jl(ie,pt),ie?.emit?.("comments-update",pt))}),!de.size)return;let Xe=!0;for(;Xe;)Xe=!1,L.value=L.value.filter(st=>{if(!Lo(st,ee))return!0;const vt=st.parentCommentId!=null?String(st.parentCommentId):null,pt=St(st)!=null?String(St(st)):null;if(!(vt&&de.has(vt)||pt&&de.has(pt))||st.resolvedTime)return!0;const it=st.commentId!=null?String(st.commentId):null,dn=st.importedId!=null?String(st.importedId):null;return it&&de.add(it),dn&&de.add(dn),Xe=!0,!1});ve.filter(st=>{if(!Lo(st,ee))return!1;const vt=st.commentId!=null?String(st.commentId):null,pt=st.importedId!=null?String(st.importedId):null;return vt&&de.has(vt)||pt&&de.has(pt)}).forEach(st=>{const vt=Pe(st),pt={type:S.DELETED,comment:vt,changes:[{key:"deleted",commentId:vt.commentId,fileId:vt.fileId}]};se&&(jl(ie,pt),ie?.emit?.("comments-update",pt))});const Qe=M.value!=null?String(M.value):null,tt=ve.some(st=>{const vt=st.commentId!=null?String(st.commentId):null,pt=st.importedId!=null?String(st.importedId):null;return Lo(st,ee)&&(vt&&vt===Qe||pt&&pt===Qe)});Qe&&de.has(Qe)&&tt&&Wr()}),ni=({superdoc:x,comment:D,decision:ee}={})=>{if(!D?.trackedChange||Su({comment:D,decision:ee}))return 0;const ie=Rs(D);if(!ie.size)return 0;const se={email:x?.user?.email??null,name:x?.user?.name??null,superdoc:x};let de=0;return pl(D).forEach(pe=>{!pe||pe===D||pe.resolvedTime||[St(pe),pe.threadingParentCommentId,pe.parentCommentId].map(ve=>Te(ve)).filter(Boolean).some(ve=>ie.has(ve))&&typeof pe.resolveComment=="function"&&(pe.resolveComment(se),de+=1)}),de},Rs=x=>{const D=new Set(Dt(x));x?.trackedChangeCanonicalId!=null&&D.add(String(x.trackedChangeCanonicalId));const ee=x?.trackedChangeAnchorKey!=null?String(x.trackedChangeAnchorKey):null;if(ee&&(D.add(ee),ee.startsWith("tc::"))){const ie=ee.slice(ee.lastIndexOf("::")+2);ie&&D.add(ie)}return D},pl=x=>{const D=[],ee=new Set;for(const ie of Rs(x))for(const se of Fe.value.get(String(ie))??[])ee.has(se)||(ee.add(se),D.push(se));return D},wa=x=>{const D=x&&typeof x=="object"?x:null;if(!D?.success)return new Set;const ee=new Set,ie=se=>{const de=se&&typeof se=="object"?se:null;de?.kind!=="entity"||de.entityType!=="trackedChange"||de.entityId!=null&&String(de.entityId).length>0&&ee.add(String(de.entityId))};return Array.isArray(D.removed)&&D.removed.forEach(ie),Array.isArray(D.invalidatedRefs)&&D.invalidatedRefs.forEach(ie),ee},ml=x=>{const D=new Set;return x?.decidedId!=null&&String(x.decidedId).length>0&&D.add(String(x.decidedId)),Array.isArray(x?.decidedIds)&&x.decidedIds.forEach(ee=>{ee!=null&&String(ee).length>0&&D.add(String(ee))}),wa(x?.receipt).forEach(ee=>D.add(ee)),D},Xi=({comment:x,decision:D}={})=>{if(!x?.trackedChange||!Su({comment:x,decision:D}))return 0;const ee=Rs(x);if(!ee.size)return 0;let ie=0;return pl(x).forEach(se=>{if(!se||se===x)return;const de=Te(se.trackedChangeParentId),pe=Te(se.trackedChangeThreadParentId),ve=Te(se.threadingParentCommentId),Xe=Te(se.parentCommentId);(de&&ee.has(de)||pe&&ee.has(pe)||ve&&ee.has(ve)||Xe&&ee.has(Xe))&&(delete se.trackedChangeParentId,se.trackedChangeThreadParentId=void 0,delete se.trackedChangeSide,delete se.threadingParentCommentId,Xe&&ee.has(Xe)&&delete se.parentCommentId,ie+=1)}),ie},sc=({superdoc:x,comment:D,decidedId:ee,decidedIds:ie,documentId:se}={})=>{const de=new Set((Array.isArray(ie)||ie instanceof Set?Array.from(ie):[ee]).map(vt=>Te(vt)).filter(Boolean)),pe=Te(se);if(!de.size||!pe)return{removed:!1,removedIds:new Set};const ve=new Set;let Xe=!1;const Qe=D?L.value.indexOf(D):-1,tt=D?.trackedChange?Rs(D):new Set;if(Qe>=0&&Lo(D,pe)&&Array.from(de).some(vt=>tt.has(vt))?(tt.forEach(vt=>ve.add(vt)),L.value.splice(Qe,1),Xe=!0):L.value=L.value.filter(vt=>{if(!vt?.trackedChange||!Lo(vt,pe))return!0;const pt=Rs(vt);return Array.from(de).some(it=>pt.has(it))?(Xe=!0,pt.forEach(it=>ve.add(it)),!1):!0}),!Xe)return{removed:!1,removedIds:ve};const st=M.value!=null?String(M.value):null;return st&&ve.has(st)&&Wr(),{removed:!0,removedIds:ve}},ac=(x,D)=>{if(!(!D||typeof x?.clearActiveTrackedChangeTargetIfMatches!="function"))try{x.clearActiveTrackedChangeTargetIfMatches(D)}catch{}},lc=async({superdoc:x,receipt:D}={})=>{const ee=x?.activeEditor?.documentMutationReadiness;if(!(D?.success!==!0||typeof D?.txId!="string"||!D.txId||typeof ee?.whenPainted!="function"))try{await ee.whenPainted(D);const ie=globalThis.requestAnimationFrame;typeof ie=="function"&&await new Promise(se=>{let de=!1;const pe=()=>{de||(de=!0,clearTimeout(ve),se())},ve=setTimeout(pe,250);ie(()=>ie(()=>setTimeout(pe,0)))})}catch{}},Au=({superdoc:x,comment:D,decision:ee})=>{if(u())return{ok:!1,reason:"read-only-document"};if(!D?.trackedChange)return{ok:!1};const ie=be(x);if(ie){if(ee!=="accept"&&ee!=="reject")return Promise.resolve({ok:!1,reason:"decision-invalid"});const tt=D?.trackedChangeCanonicalId!=null?String(D.trackedChangeCanonicalId):D?.commentId!=null?String(D.commentId):D?.trackedChangeAnchorKey?.startsWith?.("tc::body::")?D.trackedChangeAnchorKey.slice(10):null,st=tt!=null&&String(M.value??"")===tt;return ou("store.trackedChanges.sidebarDecision","command",{decision:ee,decidedId:tt},()=>(async()=>{try{return await(ee==="accept"?ie.accept(D):ie.reject(D))}catch(vt){return{ok:!1,reason:"adapter-threw",detail:vt?.message??String(vt)}}})().then(async vt=>{if(!xi(ie))return{ok:!1,reason:"adapter-stale"};if(!vt?.ok)return{ok:!1,reason:vt?.reason,detail:vt?.detail};const pt=ml(vt),it=vt?.documentId??ie.documentId??x?.activeEditor?.documentId??x?.activeEditor?.options?.documentId??null,dn=async()=>{let rn;try{rn=await ie.listTrackedChanges({mode:"all",refreshReason:"post-decision-blocking",blocking:!0})}catch(Wn){return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:Wn?.message??String(Wn)}}if(!xi(ie))return{ok:!1,committed:!0,reason:"adapter-stale"};if(!rn?.ok)return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:rn?.reason??rn?.detail??null};ni({superdoc:x,comment:D,decision:ee}),Xi({comment:D,decision:ee}),Ca({superdoc:x,adapter:ie,documentId:it,items:rn.items??[],pruneStale:rn.complete===!0&&rn.sourceCoverageComplete===!0});const Bn=new Set((rn.items??[]).map(Wn=>Wn&&Wn.id!=null?String(Wn.id):null).filter(Boolean));tt!=null&&Bn.has(tt)||(st&&Wr(),ac(ie,tt));const Gn=J(x);if(Gn&&typeof Gn.refresh=="function"&&Uo(Gn)){let Wn;try{Wn=await Gn.refresh()}catch(vo){return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:vo?.message??String(vo)}}if(!Uo(Gn))return{ok:!1,committed:!0,reason:"comments-adapter-stale"};if(!Wn?.ok)return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:Wn?.reason??Wn?.detail??null};qi({superdoc:x,adapter:Gn,documentId:Gn.documentId??it,items:Wn.items??[]})}return{ok:!0,success:!0}};return!pt.size||!it?dn():(pt.forEach(rn=>ac(ie,rn)),await lc({superdoc:x,receipt:vt.receipt}),ni({superdoc:x,comment:D,decision:ee}),Xi({comment:D,decision:ee}),sc({superdoc:x,comment:D,decidedIds:pt,documentId:it}),st&&Wr(),{ok:!0,success:!0})}))}const se=x?.activeEditor;if(!se)return{ok:!1};const de=D.commentId??D.importedId;if(!de)return{ok:!1};const pe=D.trackedChangeStory??void 0,ve=typeof se.doc=="object"?se.doc:null;if(ve?.trackChanges?.decide)try{const tt=pe?{id:de,story:pe}:{id:de};return Promise.resolve(ve.trackChanges.decide({decision:ee,target:tt})).then(st=>({ok:!0,success:!!st?.success}))}catch(tt){if(pe)return{ok:!1,error:tt}}const Xe=ee==="accept"?"acceptTrackedChangeById":"rejectTrackedChangeById",Qe=se.commands?.[Xe];return typeof Qe!="function"?{ok:!1}:{ok:!0,success:!!Qe(de)}},Lf=async({superdoc:x,adapter:D,documentId:ee,trackedChangesListMode:ie="all",refreshReason:se,blocking:de}={})=>ou("store.trackedChanges.hydrateFromV2","tracked-change-list",{documentId:ee??null,trackedChangesListMode:ie,refreshReason:se??null,blocking:de??null},async()=>{const pe=D??be(x);if(!pe||typeof pe.listTrackedChanges!="function")return{ok:!1,reason:"adapter-missing"};let ve;try{const tt={mode:ie};se!=null&&(tt.refreshReason=se),typeof de=="boolean"&&(tt.blocking=de),ve=await pe.listTrackedChanges(tt)}catch(tt){return{ok:!1,reason:"adapter-threw",detail:tt?.message??String(tt)}}if(!xi(pe))return{ok:!1,reason:"adapter-stale"};if(!ve?.ok)return ve;const Xe=!(ie==="startup-page"||ie==="interaction-prime"||ie==="visible-window")&&ve.visibleWindowSource==null&&ve.complete===!0&&ve.sourceCoverageComplete===!0;Ca({superdoc:x,adapter:pe,documentId:ee,items:ve.items??[],pruneStale:Xe});const Qe={ok:!0,items:ve.items??[]};return typeof ve.complete=="boolean"&&(Qe.complete=ve.complete),typeof ve.sourceCoverageComplete=="boolean"&&(Qe.sourceCoverageComplete=ve.sourceCoverageComplete),ve.visibleWindowSource!=null&&(Qe.visibleWindowSource=ve.visibleWindowSource),ve.visibleWindowFallbackReason!=null&&(Qe.visibleWindowFallbackReason=ve.visibleWindowFallbackReason),typeof ve.visibleTrackedChangeExpectedRows=="number"&&(Qe.visibleTrackedChangeExpectedRows=ve.visibleTrackedChangeExpectedRows),typeof ve.visibleTrackedChangeObservedRows=="number"&&(Qe.visibleTrackedChangeObservedRows=ve.visibleTrackedChangeObservedRows),typeof ve.refreshReason=="string"&&(Qe.refreshReason=ve.refreshReason),typeof ve.blocking=="boolean"&&(Qe.blocking=ve.blocking),typeof ve.pageCount=="number"&&(Qe.pageCount=ve.pageCount),typeof ve.totalItems=="number"&&(Qe.totalItems=ve.totalItems),typeof ve.coalesced=="boolean"&&(Qe.coalesced=ve.coalesced),Qe}),cc=async({superdoc:x,adapter:D,documentId:ee,upsertIds:ie=[],removedIds:se=[]}={})=>{const de=D??be(x);if(!de)return{ok:!1,reason:"adapter-missing"};if(!xi(de))return{ok:!1,reason:"adapter-stale"};const pe=ee??de.documentId??x?.activeEditor?.documentId??null,ve=new Set(Array.from(se??[]).map(pt=>Te(pt)).filter(Boolean)),Xe=[...new Set(Array.from(ie??[]).map(pt=>Te(pt)).filter(Boolean))];if(ve.size>0&&Xe.length===0&&pe!=null&&sc({superdoc:x,decidedIds:ve,documentId:pe}),Xe.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};if(typeof de.getTrackedChange!="function")return{ok:!1,reason:"adapter-get-missing"};const Qe=await Promise.all(Xe.map(async pt=>{try{return{id:pt,result:await de.getTrackedChange(pt)}}catch(it){return{id:pt,result:{ok:!1,reason:"adapter-threw",detail:it?.message??String(it)}}}}));if(!xi(de))return{ok:!1,reason:"adapter-stale"};const tt=[],st=[],vt=[];for(const{id:pt,result:it}of Qe){const dn=it?.ok&&Array.isArray(it.items)?it.items.filter(rn=>Te(rn?.id??rn?.changeId??rn?.address?.entityId)===pt):[];dn.length>0?(tt.push(pt),vt.push(...dn)):st.push(pt)}return vt.length>0&&Ca({superdoc:x,adapter:de,documentId:pe,items:vt,pruneStale:!1}),{ok:st.length===0,items:vt,resolvedIds:tt,unresolvedIds:st,failures:Qe.map(({result:pt})=>pt).filter(pt=>!pt?.ok)}},Ca=({superdoc:x,adapter:D,documentId:ee,items:ie,pruneStale:se=!0}={})=>ou("store.trackedChanges.reconcile","store-reconciliation",{documentId:ee??null,itemCount:Array.isArray(ie)?ie.length:null,pruneStale:se},()=>{if(!D||!Array.isArray(ie)||!xi(D))return;const de=ee??D.documentId??x?.activeEditor?.documentId??null,pe=new Set,ve=new Set;for(const Xe of ie){const Qe=D.mapV2TrackedChangeToCommentParams(Xe);if(Qe){if(Qe.event==="omit"){Qe.changeId!=null&&ve.add(String(Qe.changeId));continue}de&&Qe.documentId==null&&(Qe.documentId=de),Qe.changeId!=null&&ve.add(String(Qe.changeId)),Qe.trackedChangeAnchorKey!=null&&pe.add(String(Qe.trackedChangeAnchorKey)),_r({superdoc:x,params:Qe,broadcastChanges:!1})}}!de||!se||ku(ve,pe,String(de),x,{broadcastChanges:!1})}),Df=({superdoc:x,editor:D,broadcastChanges:ee=!0})=>{if(!x||!D)return;const ie=D?.options?.documentId!=null?String(D.options.documentId):null;if(!ie)return;const se=ic(D);if(!se)return;const de=se.trackedChanges,pe=new Set;de.forEach(Xe=>{const Qe=Xe?.mark?.attrs?.id;Qe!=null&&pe.add(String(Qe))});const ve=se.storySnapshots;ku(pe,new Set(ve.map(Xe=>Xe?.anchorKey).filter(Xe=>typeof Xe=="string"&&Xe.length>0)),ie,x,{broadcastChanges:ee}),_u(D,x,de,{reopenResolved:!0,refreshExisting:!0,broadcastChanges:ee,editorState:se.state,editorView:se.view}),uc({superdoc:x,editor:D,broadcastChanges:ee,snapshots:ve,documentState:se.state}),Iu({superdoc:x,editor:D,broadcastChanges:ee,structuralChanges:se.structuralChanges})},Iu=({superdoc:x,editor:D,broadcastChanges:ee=!0,structuralChanges:ie=null})=>{const se=D?.options?.documentId!=null?String(D.options.documentId):null;if(!se)return;const de=la?.enumerateStructuralRowChanges;if(typeof de!="function")return;let pe=ie;if(!Array.isArray(pe)){const ve=ei(D);if(!ve)return;try{pe=de(ve.state)??[]}catch{pe=[]}}for(const ve of pe){if(!ve?.decidable||!ve?.wholeTable)continue;const Xe=r(ve);if(!Xe)continue;const Qe=n(Xe),tt=ve.subtype==="table-insert"?"tableInsert":"tableDelete",st=ve.side==="insertion"?"trackInsert":"trackDelete",vt=String(Xe),pt=Qe!=null?String(Qe):null;_r({superdoc:x,params:{event:L.value.find(it=>{if(!it?.trackedChange||!Lo(it,se))return!1;const dn=it.trackedChangeAnchorKey!=null?String(it.trackedChangeAnchorKey):null;if(pt&&dn)return dn===pt;const rn=it.commentId!=null?String(it.commentId):null,Bn=it.importedId!=null?String(it.importedId):null;return rn===vt||Bn===vt})?"update":"add",changeId:Xe,trackedChangeText:"",trackedChangeType:st,trackedChangeDisplayType:tt,deletedText:null,authorId:null,authorEmail:ve.authorEmail||null,authorImage:ve.authorImage||null,date:ve.date||null,author:ve.author||null,importedAuthor:ve.importedAuthor?{name:ve.importedAuthor}:null,semanticColorKey:ve.semanticColorKey??null,semanticColor:ve.semanticColor??null,documentId:se,coords:null,trackedChangeStory:e,trackedChangeStoryKind:"body",trackedChangeStoryLabel:"",trackedChangeAnchorKey:Qe},broadcastChanges:ee})}},uc=({superdoc:x,editor:D,broadcastChanges:ee=!0,snapshots:ie=null,documentState:se=void 0,resolveFromEditor:de=!0})=>{const pe=D?.options?.documentId!=null?String(D.options.documentId):null;if(!pe)return;let ve=ie;if(!Array.isArray(ve)){if(typeof iu!="function"||!ei(D))return;let Xe=null;try{Xe=iu(D)}catch{return}if(!Xe)return;try{ve=Xe.getAll()}catch{return}}for(const Xe of ve)Xe.storyKind!=="body"&&xu({superdoc:x,editor:D,snapshot:Xe,documentId:pe,broadcastChanges:ee,documentState:se,resolveFromEditor:de})},Ms=x=>x?.type!=="structural"?x?.type??null:x?.subtype==="table-delete"?"tableDelete":"tableInsert",Eu=x=>x?.type!=="structural"?x?.type??null:x?.subtype==="table-delete"?"trackDelete":"trackInsert",Ls=x=>x?x.type==="delete"?!0:x.type==="structural"&&x.subtype==="table-delete":!1,dc=({editor:x,snapshot:D,documentId:ee,event:ie,resolveFromEditor:se=!0})=>{const de=Eu(D),pe=Ms(D),ve={event:ie,changeId:D.runtimeRef.rawId,trackedChangeText:Ls(D)?"":D.excerpt??"",trackedChangeType:de,trackedChangeDisplayType:pe,semanticColorKey:D.semanticColorKey??null,semanticColor:D.semanticColor??null,deletedText:Ls(D)?D.excerpt??"":null,authorId:D.authorId,authorEmail:D.authorEmail,authorImage:D.authorImage,date:D.date,author:D.author,documentId:ee,coords:null,trackedChangeStory:D.story,trackedChangeStoryKind:D.storyKind,trackedChangeStoryLabel:D.storyLabel,trackedChangeAnchorKey:D.anchorKey};if(!se||typeof $C!="function")return ve;let Xe=null;try{Xe=$C(x,{kind:"entity",entityType:"trackedChange",entityId:D.runtimeRef.rawId,story:D.story})}catch{Xe=null}const Qe=Xe?.editor?.state??null;if(!Qe)return ve;let tt=[];try{tt=la.getTrackChanges(Qe,Xe.change.rawId)??[]}catch{tt=[]}const st=Hy({event:ie,marks:po(tt),nodes:[],newEditorState:Qe,documentId:ee,trackedChangesForId:tt});return st?(st.semanticColorKey==null&&D.semanticColorKey!=null&&(st.semanticColorKey=D.semanticColorKey),st.semanticColor==null&&D.semanticColor!=null&&(st.semanticColor=D.semanticColor),st.trackedChangeStory=D.story,st.trackedChangeStoryKind=D.storyKind,st.trackedChangeStoryLabel=D.storyLabel,st.trackedChangeAnchorKey=D.anchorKey,st):ve},xu=({superdoc:x,editor:D,snapshot:ee,documentId:ie,broadcastChanges:se,documentState:de,resolveFromEditor:pe})=>{if(!ee?.runtimeRef?.rawId)return;const ve=L.value.find(Xe=>{if(!Xe?.trackedChange)return!1;const Qe=Xe.trackedChangeAnchorKey!=null?String(Xe.trackedChangeAnchorKey):null;return Qe&&ee.anchorKey?Qe===ee.anchorKey:Qe||ee.anchorKey?!1:Xe.commentId===ee.runtimeRef.rawId||Xe.importedId===ee.runtimeRef.rawId});_r({superdoc:x,params:dc({editor:D,snapshot:ee,documentId:ie,event:ve?"update":"add",resolveFromEditor:pe}),broadcastChanges:se,documentState:de}),ve&&(ve.trackedChangeStory=ee.story,ve.trackedChangeStoryKind=ee.storyKind,ve.trackedChangeStoryLabel=ee.storyLabel,ve.trackedChangeAnchorKey=ee.anchorKey)},Tu=x=>x?(Array.isArray(x)?x:[x]).filter(Boolean):[],Qi=()=>{const x=[];return L.value.forEach(D=>{const ee=D.getValues(),ie=ee.commentText,se=Tu(ee.docxCommentJSON),de=se.length?se:Ru(ie);x.push({...ee,commentJSON:de})}),x},Ru=x=>{const D=new ZC({mode:"text",isHeadless:!0,content:x,extensions:JC()}).getJSON();return Array.isArray(D?.content)?D.content.filter(Boolean):[]},Zi=x=>{if(x==null)return;const D={};Object.entries(x).forEach(([ie,se])=>{D[ie]=se;const de=se?.kind==="trackedChange"&&se?.storyKey==="body"&&se?.threadId!=null?String(se.threadId):null;de&&D[de]===void 0&&(D[de]=se);const pe=typeof se?.key=="string"?se.key:null;pe&&D[pe]===void 0&&(D[pe]=se)});const ee=ie=>{const se=[ie?.trackedChangeAnchorKey,ie?.commentId,ie?.importedId,Ct(ie?.importedId)].map(de=>Te(de)).filter(Boolean);for(const de of se){const pe=D[de];if(pe!==void 0)return{entry:pe,aliasIds:se}}return{entry:null,aliasIds:se}};L.value.forEach(ie=>{if(!ie?.trackedChange)return;const{entry:se,aliasIds:de}=ee(ie);se&&de.forEach(pe=>{D[pe]===void 0&&(D[pe]=se)})}),ae.value=D},Pf=()=>{ae.value={}},Mu=x=>{if(!x?.trackedChange)return!1;const D=x?.trackedChangeDisplayType;return D==="tableInsert"||D==="tableDelete"?!0:[x?.commentId,x?.importedId,x?.trackedChangeAnchorKey].map(ee=>ee!=null?String(ee):"").filter(Boolean).some(ee=>ee.includes("word:structural:"))},gl=new WeakMap,fc=x=>{if(!x)return{ranges:[],ids:new Set};const D=gl.get(x);if(D)return D;const ee=[],ie=new Set,se=ve=>{ve!=null&&ve!==""&&ie.add(String(ve))},de=la?.enumerateStructuralRowChanges;if(typeof de=="function"){let ve=[];try{ve=de(x)??[]}catch{ve=[]}for(const Xe of ve){if(!Xe?.decidable||!Xe?.wholeTable)continue;const Qe=Number(Xe.tableFrom),tt=Number(Xe.tableTo);Number.isFinite(Qe)&&Number.isFinite(tt)&&ee.push({from:Qe,to:tt}),se(Xe.id),se(Xe.revisionId),se(Xe.revisionGroupId),se(Xe.sourceId);for(const st of Xe.rows||[]){const vt=st?.node?.attrs?.trackChange;se(vt?.id),se(vt?.sourceId)}}}const pe={ranges:ee,ids:ie};return gl.set(x,pe),pe},Lu=x=>{const D=o.getDocument(x)?.getEditor?.();return fc(D?.state).ranges},vl=(x,D)=>!D?.length||!x?.length?!1:x.every(ee=>{const ie=Number(ee?.from),se=Number(ee?.to);return!Number.isFinite(ie)||!Number.isFinite(se)?!1:D.some(de=>ie>=de.from&&se<=de.to)}),yl=x=>{if(!x?.trackedChange||Mu(x))return!1;const D=Lu(x?.fileId);if(!D.length)return!1;const ee=un(x).entry,ie=ur(ee);return ie?D.some(se=>ie.start>=se.from&&ie.end<=se.to):!1},Du=Se(()=>ro.value?.parentComments.filter(x=>!x.resolvedTime).filter(x=>!Ze(x)||ot(x)?!0:!!un(x).entry).filter(x=>!yl(x))),bl=Se(()=>Du.value.flatMap(x=>{const{key:D,entry:ee}=un(x);return uT({comment:x,positionKey:D,positionEntry:ee,fallbackId:Te(x?.commentId)??Dt(x)[0]??null})})),ri=x=>x==null?null:String(x),Ji=(x=null)=>{H.value=ri(x)},Wr=()=>{M.value=null,Ji(null)},Of=(x,D)=>x==null||D==null?!1:bl.value.some(ee=>String(ee.id)===String(x)&&String(ee.comment?.commentId??ee.threadId??"")===String(D)),Pu=x=>{Of(H.value,x)||Ji(null)},Ds=({documentMode:x,commentsVisible:D,trackChangesVisible:ee}={})=>{typeof x=="string"&&(c.documentMode=x),typeof D=="boolean"&&(c.commentsVisible=D),typeof ee=="boolean"&&(c.trackChangesVisible=ee)},hc=x=>{if(Array.isArray(x))return x.map(pe=>hc(pe)).flat().filter(Boolean);if(!x||typeof x!="object")return x;const D=pe=>{if(!pe)return pe;const ve={...pe};return delete ve.fontSize,delete ve.fontFamily,delete ve.eastAsiaFontFamily,Object.keys(ve).length?ve:void 0},ee=pe=>{if(!pe)return pe;const ve=typeof pe.type=="string"?pe.type:pe.type?.name,Xe=pe?.attrs?{...pe.attrs}:void 0;return ve==="textStyle"&&Xe?{...pe,attrs:D(Xe)}:{...pe,attrs:Xe}},ie=pe=>Array.isArray(pe)?pe.filter(Boolean).map(ve=>ee(ve)):void 0,se=pe=>pe&&typeof pe=="object"?{...pe}:void 0;if(!Array.isArray(x.content))return{type:x.type,...x.text!==void 0?{text:x.text}:{},...x.attrs?{attrs:se(x.attrs)}:{},...x.marks?{marks:ie(x.marks)}:{}};const de=x.content.map(pe=>hc(pe)).flat().filter(Boolean);return x.type==="run"?de:{type:x.type,...x.attrs?{attrs:se(x.attrs)}:{},...x.marks?{marks:ie(x.marks)}:{},content:de}},Ff=x=>{const D=Array.isArray(x)?x:x?[x]:[];if(D.some(ee=>ee?.content?.length))try{const ee=hc(D),ie=Array.isArray(ee)?ee:ee?[ee]:[];return ie.length?new ZC({mode:"text",isHeadless:!0,content:{type:"doc",content:ie},loadFromSchema:!0,extensions:JC()}).getHTML():null}catch(ee){console.warn("Failed to convert comment",ee);return}};return{COMMENT_EVENTS:S,isDebugging:d,hasInitializedComments:y,hasSyncedCollaborationComments:C,editingCommentId:B,activeComment:M,activeFloatingCommentInstanceId:H,commentDialogs:z,overlappingComments:Z,overlappedIds:P,suppressInternalExternal:N,pendingComment:_,currentCommentText:I,commentsList:L,isCommentsListVisible:he,generalCommentIds:Ie,editorCommentIds:ge,commentsParentElement:T,editorCommentPositions:ae,hasInitializedLocations:R,isCommentHighlighted:Ce,floatingCommentsOffset:oe,sortedConversations:xe,visibleConversations:qe,skipSelectionUpdate:et,isFloatingCommentsReady:kt,instantSidebarAlignmentTargetY:ze,instantSidebarAlignmentThreadId:Ve,instantSidebarAlignmentInstanceId:Q,getConfig:bn,documentsWithConverations:lt,getGroupedComments:ro,hasOpenTrackedChanges:ke,getCommentsByPosition:Oe,getFloatingComments:Du,getFloatingCommentInstances:bl,getCommentAliasIds:Dt,getTrackedChangeThread:le,getCommentPositionKey:cn,getCommentPosition:dr,getCommentAnchoredText:jr,getCommentAnchorData:$t,resolveCommentPositionEntry:un,getCommentDocumentId:xs,belongsToDocument:hl,viewingVisibility:c,isViewingMode:F,shouldRenderReviewInViewing:j,init:we,setViewingVisibility:Ds,getComment:Vt,setActiveComment:Mr,getCommentLocation:an,hasOverlapId:ft,getPendingComment:Fr,showAddComment:Ss,addComment:Is,addHydratedComment:Jo,cancelComment:mi,deleteComment:Ro,removePendingComment:go,cancelImportedTrackedChangeBootstrap:jn,removeCommentsForDocument:dl,processLoadedDocxComments:fl,translateCommentsForExport:Qi,handleEditorLocationsUpdate:Zi,clearEditorCommentPositions:Pf,handleTrackedChangeUpdate:_r,refreshTrackedChangeCommentsByIds:Kt,syncResolvedCommentsWithDocument:Tt,syncTrackedChangePositionsWithDocument:Mt,setActiveFloatingCommentInstance:Ji,requestInstantSidebarAlignment:yn,peekInstantSidebarAlignment:xo,clearInstantSidebarAlignment:Zo,syncTrackedChangeComments:Df,decideTrackedChangeFromSidebar:Au,v2CommentsAdapter:V,setV2CommentsAdapter:G,getV2CommentsAdapter:J,hydrateCommentsFromV2:cl,reconcileCommentsFromV2:qi,isV2EditorActive:K,replyCommentV2:$o,editCommentV2:ll,resolveCommentV2:oc,reopenCommentV2:kr,v2TrackedChangesAdapter:W,setV2TrackedChangesAdapter:ue,getV2TrackedChangesAdapter:be,hydrateTrackedChangesFromV2:Lf,reconcileTrackedChangeMutationFromV2:cc,reconcileTrackedChangesFromV2:Ca}});var n_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M512 240c0 114.9-114.6 208-256 208c-37.1 0-72.3-6.4-104.1-17.9c-11.9 8.7-31.3 20.6-54.3 30.6C73.6 471.1 44.7 480 16 480c-6.5 0-12.3-3.9-14.8-9.9c-2.5-6-1.1-12.8 3.4-17.4c0 0 0 0 0 0s0 0 0 0s0 0 0 0c0 0 0 0 0 0l.3-.3c.3-.3 .7-.7 1.3-1.4c1.1-1.2 2.8-3.1 4.9-5.7c4.1-5 9.6-12.4 15.2-21.6c10-16.6 19.5-38.4 21.4-62.9C17.7 326.8 0 285.1 0 240C0 125.1 114.6 32 256 32s256 93.1 256 208z"/></svg>',r_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M137.4 374.6c12.5 12.5 32.8 12.5 45.3 0l128-128c9.2-9.2 11.9-22.9 6.9-34.9s-16.6-19.8-29.6-19.8L32 192c-12.9 0-24.6 7.8-29.6 19.8s-2.2 25.7 6.9 34.9l128 128z"/></svg>',FT='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M96 128a128 128 0 1 1 256 0A128 128 0 1 1 96 128zM0 482.3C0 383.8 79.8 304 178.3 304l91.4 0C368.2 304 448 383.8 448 482.3c0 16.4-13.3 29.7-29.7 29.7L29.7 512C13.3 512 0 498.7 0 482.3zM625 177L497 305c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L591 143c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>',BT='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M144 0a80 80 0 1 1 0 160A80 80 0 1 1 144 0zM512 0a80 80 0 1 1 0 160A80 80 0 1 1 512 0zM0 298.7C0 239.8 47.8 192 106.7 192l42.7 0c15.9 0 31 3.5 44.6 9.7c-1.3 7.2-1.9 14.7-1.9 22.3c0 38.2 16.8 72.5 43.3 96c-.2 0-.4 0-.7 0L21.3 320C9.6 320 0 310.4 0 298.7zM405.3 320c-.2 0-.4 0-.7 0c26.6-23.5 43.3-57.8 43.3-96c0-7.6-.7-15-1.9-22.3c13.6-6.3 28.7-9.7 44.6-9.7l42.7 0C592.2 192 640 239.8 640 298.7c0 11.8-9.6 21.3-21.3 21.3l-213.3 0zM224 224a96 96 0 1 1 192 0 96 96 0 1 1 -192 0zM128 485.3C128 411.7 187.7 352 261.3 352l117.3 0C452.3 352 512 411.7 512 485.3c0 14.7-11.9 26.7-26.7 26.7l-330.7 0c-14.7 0-26.7-11.9-26.7-26.7z"/></svg>',Vy='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"/></svg>',o_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>',i_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M64 360a56 56 0 1 0 0 112 56 56 0 1 0 0-112zm0-160a56 56 0 1 0 0 112 56 56 0 1 0 0-112zM120 96A56 56 0 1 0 8 96a56 56 0 1 0 112 0z"/></svg>',s_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M48.5 224L40 224c-13.3 0-24-10.7-24-24L16 72c0-9.7 5.8-18.5 14.8-22.2s19.3-1.7 26.2 5.2L98.6 96.6c87.6-86.5 228.7-86.2 315.8 1c87.5 87.5 87.5 229.3 0 316.8s-229.3 87.5-316.8 0c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0c62.5 62.5 163.8 62.5 226.3 0s62.5-163.8 0-226.3c-62.2-62.2-162.7-62.5-225.3-1L185 183c6.9 6.9 8.9 17.2 5.2 26.2s-12.5 14.8-22.2 14.8L48.5 224z"/></svg>';const ua={comment:n_,caretDown:r_,internal:FT,external:BT,markDone:Vy,acceptChange:Vy,rejectChange:o_,overflow:i_,reopen:s_};var NT=.38,zT=".superdoc-comment-highlight",HT=e=>{if(typeof e?.getBoundingClientRect!="function")return!1;const t=e.getBoundingClientRect();return!Number.isFinite(t.top)||!Number.isFinite(t.bottom)?!1:t.bottom>0&&t.top<window.innerHeight},UT=e=>e?e.split(",").map(t=>t.trim()).filter(Boolean):[],VT=e=>{const t=[];return e?(e.split(",").forEach(n=>{const r=n.indexOf("=");r<=0||t.push(n.slice(0,r),n.slice(r+1))}),t.filter(Boolean)):t};const jT=()=>Math.round(window.innerHeight*NT),a_=(e,t)=>{const n=t?.bounds?.top;if(!Number.isFinite(n)||typeof e?.getBoundingClientRect!="function")return null;const r=e.getBoundingClientRect().top+n;return r<0||r>=window.innerHeight?null:r},GT=e=>{if(typeof document>"u")return null;const t=new Set((e??[]).map(o=>String(o)).filter(Boolean));if(t.size===0)return null;let n=null;const r=document.querySelectorAll(zT);for(const o of r){const i=new Set([...UT(o.getAttribute("data-comment-ids")),...VT(o.getAttribute("data-comment-imported-ids"))]);if(![...t].some(a=>i.has(a))||!HT(o))continue;const s=o.getBoundingClientRect().top;Number.isFinite(s)&&(n=n==null?s:Math.min(n,s))}return n},WT=(e,t,n,r)=>{if(!e||!Number.isFinite(r))return null;const o=s=>{if(!s)return null;const a=e.getReachableThreadAnchorClientY(s,r);return Number.isFinite(a)&&e.scrollThreadAnchorToClientY(s,r,{behavior:"auto"})?a:null},i=o(t);return Number.isFinite(i)?i:!n||n===t?null:o(n)};It();const KT="Arial, Helvetica, sans-serif";function jy(){const e=sr();return{uiFontFamily:Se(()=>{const t=e?.proxy?.$superdoc?.config?.uiDisplayFallbackFont;return typeof t=="string"&&t.trim()?t.trim():KT})}}var hn,gn=br((()=>{hn=(e,t)=>{const n=e.__vccOpts||e;for(const[r,o]of t)n[r]=o;return n}}));It(),gn();var qT={class:"comments-dropdown"},YT=["onClick"],XT={key:0,class:"comments-dropdown__option-icon"},QT=["innerHTML"],ZT={class:"comments-dropdown__option-label"},JT={__name:"CommentsDropdown",props:{options:{type:Array,default:()=>[]},disabled:{type:Boolean,default:!1},contentStyle:{type:Object,default:()=>({})}},emits:["select"],setup(e,{emit:t}){const n=e,r=t,o=ne(!1),i=ne(null),s=ne(null),a=ne({top:"0px",left:"0px"}),l=Se(()=>({...n.contentStyle,position:"fixed",top:a.value.top,left:a.value.left,zIndex:1200})),u=C=>{n.disabled&&C||(o.value=C)},c=()=>{n.disabled||u(!o.value)},d=()=>{o.value&&u(!1)},h=()=>{if(!i.value)return;const C=i.value.getBoundingClientRect(),T=s.value?.offsetWidth??0,R=window.innerWidth||document.documentElement.clientWidth||0,M=8;let H=C.left;const B=Math.max(M,R-T-M);H=Math.min(Math.max(M,H),B),a.value={top:`${C.bottom+4}px`,left:`${H}px`}},m=C=>{C.stopPropagation(),c()},p=C=>{C?.disabled||(r("select",C?.key,C),d())},g=C=>!!C?.iconString||!!C?.icon,k=C=>C?.iconString?C.iconString:typeof C?.icon=="function"?C.icon(C):C?.icon||null,w=Ll({name:"CommentsDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(C){return()=>k(C.option)}}),S=C=>{if(!o.value)return;const T=C.target;if(!(T instanceof Element))return;const R=i.value?.contains(T),M=s.value?.contains(T);R||M||d()},y=C=>{C.key==="Escape"&&d()};return Pt(o,async C=>{C&&(await _t(),h())}),Pt(o,C=>{C?(document.addEventListener("pointerdown",S,!0),document.addEventListener("keydown",y,!0),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0)):(document.removeEventListener("pointerdown",S,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0))}),ir(()=>{document.removeEventListener("pointerdown",S,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0)}),(C,T)=>(me(),_e("div",qT,[Le("div",{ref_key:"triggerRef",ref:i,class:"comments-dropdown__trigger",onClick:m},[hd(C.$slots,"default",{},void 0,!0)],512),(me(),fn(Oa,{to:"body"},[o.value?(me(),_e("div",{key:0,ref_key:"menuRef",ref:s,class:"comments-dropdown__menu",style:vn(l.value)},[(me(!0),_e(Wt,null,or(e.options,R=>(me(),_e("div",{key:R.key,class:en(["comments-dropdown__option",{"sd-disabled":R.disabled}]),onClick:M=>p(R)},[g(R)?(me(),_e("span",XT,[R.iconString?(me(),_e("span",{key:0,innerHTML:R.iconString},null,8,QT)):(me(),fn(Ge(w),{key:1,option:R},null,8,["option"]))])):ut("",!0),Le("span",ZT,Ht(R.label),1)],10,YT))),128))],4)):ut("",!0)]))]))}},l_=hn(JT,[["__scopeId","data-v-7eced80a"]]);It(),gn();var $T={class:"sd-comment-option"},e7=["innerHTML"],t7={class:"sd-option-state"},n7=["innerHTML"],r7={__name:"InternalDropdown",props:{state:{type:String,required:!1},isDisabled:{type:Boolean,default:!1}},emits:["select"],setup(e,{emit:t}){const n=t,r=e,{uiFontFamily:o}=jy(),i=[{label:"Internal",key:"internal",iconString:ua.internal,backgroundColor:"var(--sd-ui-comments-internal-bg, #CDE6E6)"},{label:"External",key:"external",iconString:ua.external,backgroundColor:"var(--sd-ui-comments-external-bg, #F5CFDA)"}],s=Se(()=>i.find(d=>d.key===u.value)?.label),a=Se(()=>{if(!r.state)return{};const d=i.find(m=>m.key===u.value);if(!d)return{};const h={backgroundColor:d.backgroundColor};return r.isDisabled&&(h.opacity=.5,h.cursor="default"),h}),l=(d,h=!1)=>{u.value=d,c.value=i.find(m=>m.key===d)?.iconString,!h&&n("select",d)},u=ne(r.state),c=ne(null);return Pt(()=>r.state,d=>{l(d)}),Rn(()=>{l(r.state,!0)}),(d,h)=>(me(),_e("div",{class:"sd-internal-dropdown",style:vn(a.value),"data-sd-part":"dropdown-trigger"},[Gt(l_,{options:i,onSelect:h[0]||(h[0]=m=>l(m)),disabled:e.isDisabled,"content-style":{fontFamily:Ge(o)}},{default:ko(()=>[Le("div",$T,[Le("div",{class:"sd-active-icon",innerHTML:c.value},null,8,e7),Le("div",t7,Ht(s.value),1),Le("div",{class:"sd-dropdown-caret",innerHTML:Ge(ua).caretDown},null,8,n7)])]),_:1},8,["disabled","content-style"])],4))}},c_=hn(r7,[["__scopeId","data-v-138d641e"]]);function o7(e){const t=new Date(e),n=t.getHours(),r=t.getMinutes(),o=n>=12?"PM":"AM",i=n%12||12,s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],a=t.getDate();return`${`${i}:${r.toString().padStart(2,"0")}${o}`} ${s} ${a}`}const eo=Object.freeze({RESOLVE_OWN:"RESOLVE_OWN",RESOLVE_OTHER:"RESOLVE_OTHER",REJECT_OWN:"REJECT_OWN",REJECT_OTHER:"REJECT_OTHER",COMMENTS_OVERFLOW_OWN:"COMMENTS_OVERFLOW",COMMENTS_OVERFLOW_OTHER:"COMMENTS_OVERFLOW_OTHER",COMMENTS_DELETE_OWN:"COMMENTS_DELETE_OWN",COMMENTS_DELETE_OTHER:"COMMENTS_DELETE_OTHER",UPLOAD_VERSION:"UPLOAD_VERSION",VERSION_HISTORY:"VERSION_HISTORY"});var pr=Object.freeze({EDITOR:"editor",SUGGESTER:"suggester",VIEWER:"viewer"}),i7=Object.freeze({[eo.RESOLVE_OWN]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.RESOLVE_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.REJECT_OWN]:{internal:[pr.EDITOR,pr.SUGGESTER],external:[pr.EDITOR,pr.SUGGESTER]},[eo.REJECT_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.COMMENTS_OVERFLOW_OWN]:{internal:[pr.EDITOR,pr.SUGGESTER],external:[pr.EDITOR,pr.SUGGESTER]},[eo.COMMENTS_OVERFLOW_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.COMMENTS_DELETE_OWN]:{internal:[pr.EDITOR,pr.SUGGESTER],external:[pr.EDITOR,pr.SUGGESTER]},[eo.COMMENTS_DELETE_OTHER]:{internal:[pr.EDITOR],external:[pr.EDITOR]},[eo.UPLOAD_VERSION]:{internal:[pr.EDITOR],external:[]},[eo.VERSION_HISTORY]:{internal:[pr.EDITOR],external:[]}}),s7=(e={})=>{if(typeof e.permissionResolver=="function")return e.permissionResolver;if(e.superdoc?.config?.modules?.comments?.permissionResolver){const t=e.superdoc.config.modules.comments.permissionResolver;if(typeof t=="function")return t}return typeof e.superdoc?.config?.permissionResolver=="function"?e.superdoc.config.permissionResolver:null},a7=(e,t,n)=>{const r=n?"internal":"external";return i7[e]?.[r]?.includes(t)??!1};const da=(e,t,n,r={})=>{const o=a7(e,t,n),i=s7(r);if(typeof i!="function")return o;const s=i({permission:e,role:t,isInternal:n,defaultDecision:o,comment:r.comment??null,currentUser:r.currentUser??r.superdoc?.config?.user??null,superdoc:r.superdoc??null,trackedChange:r.trackedChange??null});return typeof s=="boolean"?s:o};It(),gn();var l7={class:"user-container"},c7=["src"],u7={key:1,class:"user-bg"},d7={__name:"Avatar",props:{user:{type:Object,required:!0}},setup(e){const t=(n,r)=>{if(!(!n&&!r)){if(n){const o=n.trim().split(/\s+/).filter(i=>/^[a-zA-Z]/.test(i));if(o.length>=2)return(o[0][0]+o[o.length-1][0]).toUpperCase();if(o.length===1)return o[0][0].toUpperCase()}return r?.substring(0,1)?.toUpperCase()||null}};return(n,r)=>(me(),_e("div",l7,[e.user.image?(me(),_e("img",{key:0,class:"user-bg",src:e.user.image.startsWith("http")?e.user.image:`data:image/png;base64,${e.user.image}`},null,8,c7)):(me(),_e("span",u7,Ht(t(e.user.name,e.user.email)),1))]))}},u_=hn(d7,[["__scopeId","data-v-c95b2073"]]);It(),gn();var f7={class:"card-section comment-header"},h7={class:"comment-header-left"},p7={class:"user-info"},m7={class:"user-name"},g7={key:0,class:"imported-tag"},v7={key:0,class:"user-timestamp"},y7=["data-disabled-reason","aria-disabled","innerHTML"],b7=["data-disabled-reason","aria-disabled","innerHTML"],w7=["data-disabled-reason","aria-disabled","innerHTML"],C7={class:"overflow-menu__icon"},_7=["innerHTML"],S7={__name:"CommentHeader",props:{timestamp:{type:Number,required:!1},config:{type:Object,required:!0},comment:{type:Object,required:!1},isPendingInput:{type:Boolean,required:!1,default:!1},isActive:{type:Boolean,default:!1},resolveDisabledReason:{type:String,default:null},rejectDisabledReason:{type:String,default:null},reopenDisabledReason:{type:String,default:null},reopenSupported:{type:Boolean,default:!1},writeDisabledReason:{type:String,default:null}},emits:["resolve","reject","reopen","overflow-select"],setup(e,{emit:t}){const n=t,r=ca(),o=e,{proxy:i}=sr(),s=i.$superdoc.config.role,a=i.$superdoc.config.isInternal,l=z=>{const Z=i.$superdoc.config.user,P={id:z?.creatorId,email:z?.creatorEmail};if(Ow({current:Z,other:P}))return!0;const N=Ld(Z),I=Ld(P);if(N.hasId||N.hasEmail||I.hasId||I.hasEmail||z?.origin!=null||z?.importedAuthor?.name)return!1;const L=Pw(Z?.name),X=Pw(z?.creatorName);return!!(L&&X&&L===X)},u=Se(()=>l(o.comment)),c=Se(()=>pp(o.comment)),{uiFontFamily:d}=jy(),h=Object.freeze({edit:{label:"Edit",key:"edit"},delete:{label:"Delete",key:"delete"}}),m=Se(()=>o.config.readOnly!==!0),p=Se(()=>!(!m.value||!o.comment||o.comment.resolvedTime||r.pendingComment||o.isPendingInput)),g=Se(()=>{if(!p.value||!o.comment.trackedChange&&o.config.allowResolve===!1||o.comment.parentCommentId||c.value)return!1;const z={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value||o.comment.trackedChange?da(eo.RESOLVE_OWN,s,a,z):da(eo.RESOLVE_OTHER,s,a,z)}),k=Se(()=>{if(!p.value||!o.comment.trackedChange)return!1;const z={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value||o.comment.trackedChange?da(eo.REJECT_OWN,s,a,z):da(eo.REJECT_OTHER,s,a,z)}),w=Se(()=>{if(!m.value||o.config.allowResolve===!1||!o.reopenSupported||!o.comment||!o.comment.resolvedTime||r.pendingComment||o.isPendingInput||o.comment.parentCommentId||c.value||o.comment.trackedChange)return!1;const z={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value?da(eo.RESOLVE_OWN,s,a,z):da(eo.RESOLVE_OTHER,s,a,z)}),S=Se(()=>!(!p.value||o.comment.trackedChange||o.isPendingInput||y.value.length===0)),y=Se(()=>{if(!m.value)return[];if(!p.value)return[];if(o.writeDisabledReason)return[];const z=[],Z=new Set;l(o.comment)&&Z.add("edit");const P=l(o.comment),N={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return(P&&da(eo.COMMENTS_DELETE_OWN,s,a,N)||!P&&da(eo.COMMENTS_DELETE_OTHER,s,a,N))&&Z.add("delete"),Z.forEach(I=>z.push(h[I])),z}),C=()=>{m.value&&(!o.comment?.trackedChange&&o.config.allowResolve===!1||o.resolveDisabledReason||n("resolve"))},T=()=>{m.value&&(o.rejectDisabledReason||n("reject"))},R=()=>{!m.value||o.config.allowResolve===!1||o.reopenDisabledReason||n("reopen")},M=z=>{m.value&&n("overflow-select",z)},H=Se(()=>!(!(o.comment.origin!=null||o.comment.importedAuthor?.name)||l(o.comment))),B=Se(()=>{if(o.isPendingInput)return i.$superdoc.config.user;const z=o.comment.getCommentUser();if(z?.name){const Z=z.name.replace(/\s*\(imported\)\s*/gi,"").trim();if(Z)return{...z,name:Z}}return z});return(z,Z)=>(me(),_e("div",f7,[Le("div",h7,[Gt(u_,{user:B.value,class:"avatar"},null,8,["user"]),Le("div",p7,[Le("div",m7,[Oi(Ht(B.value.name),1),H.value?(me(),_e("span",g7,"IMPORTED")):ut("",!0)]),o.comment.createdTime?(me(),_e("div",v7,Ht(Ge(o7)(o.comment.createdTime)),1)):ut("",!0)])]),Le("div",{class:en(["overflow-menu",{"is-visible":o.isActive}])},[g.value?(me(),_e("div",{key:0,class:en(["overflow-menu__icon",{"sd-is-disabled":!!e.resolveDisabledReason}]),"data-comment-action":"resolve","data-disabled-reason":e.resolveDisabledReason||null,"aria-disabled":!!e.resolveDisabledReason,innerHTML:Ge(ua).markDone,onClick:Jt(C,["stop","prevent"])},null,10,y7)):ut("",!0),k.value?(me(),_e("div",{key:1,class:en(["overflow-menu__icon",{"sd-is-disabled":!!e.rejectDisabledReason}]),"data-comment-action":"reject","data-disabled-reason":e.rejectDisabledReason||null,"aria-disabled":!!e.rejectDisabledReason,innerHTML:Ge(ua).rejectChange,onClick:Jt(T,["stop","prevent"])},null,10,b7)):ut("",!0),w.value?(me(),_e("div",{key:2,class:en(["overflow-menu__icon overflow-menu__icon--reopen",{"sd-is-disabled":!!e.reopenDisabledReason}]),"data-disabled-reason":e.reopenDisabledReason||null,"data-comment-reopen":!0,"aria-disabled":!!e.reopenDisabledReason,title:"Reopen comment",innerHTML:Ge(ua).reopen,onClick:Jt(R,["stop","prevent"])},null,10,w7)):ut("",!0),S.value?(me(),fn(l_,{key:3,"data-comment-action":"overflow",options:y.value,onSelect:M,"content-style":{fontFamily:Ge(d)}},{default:ko(()=>[Le("div",C7,[Le("div",{class:"overflow-icon",innerHTML:Ge(ua).overflow},null,8,_7)])]),_:1},8,["options","content-style"])):ut("",!0)],2)]))}},Gy=hn(S7,[["__scopeId","data-v-ca6050aa"]]);It(),gn();var k7={class:"input-section"},Wy=28,d_=132,A7={__name:"CommentInput",props:{users:{type:Array,required:!1,default:()=>[]},config:{type:Object,required:!0},isFocused:{type:Boolean,default:!1},includeHeader:{type:Boolean,default:!0},comment:{type:Object,required:!1}},emits:["focus"],setup(e,{expose:t,emit:n}){const r=n,{currentCommentText:o}=ea(ca()),i=ne(null),s=p=>r("focus",p),a=()=>{i.value?.focus?.()},l=()=>{const p=i.value;if(!p)return;p.style.height=`${Wy}px`;const g=p.scrollHeight||Wy,k=Math.min(Math.max(g,Wy),d_);p.style.height=`${k}px`,p.style.overflowY=g>d_?"auto":"hidden"},u=()=>{_t(l)},c=p=>String(p??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),d=p=>{const g=String(p??"");if(!g||g==="<p></p>")return"";if(typeof document>"u")return g.replace(/<br\s*\/?>/gi,`
|
|
13
13
|
`).replace(/<[^>]+>/g,"");const k=document.createElement("div");return k.innerHTML=g,k.innerText||k.textContent||""},h=p=>{const g=String(p??"").replace(/\r\n/g,`
|
|
14
|
-
`).trim();return g?g.split(/\n{2,}/).map(k=>`<p>${c(k).replace(/\n/g,"<br>")}</p>`).join(""):"<p></p>"},m=Se({get:()=>d(o.value),set:p=>{o.value=h(p)}});return Rn(u),Pt(o,u),t({focus:a}),(p,g)=>(me(),_e("div",k7,[e.includeHeader?(me(),fn(Gy,{key:0,config:e.config,comment:e.comment,"is-pending-input":!0},null,8,["config","comment"])):ut("",!0),Le("div",{class:en(["comment-entry",{"sd-input-active":e.isFocused}])},[Ws(Le("textarea",{ref_key:"inputRef",ref:i,class:"superdoc-field",placeholder:"Add a comment","onUpdate:modelValue":g[0]||(g[0]=k=>m.value=k),rows:"1",onInput:l,onFocus:g[1]||(g[1]=k=>s(!0)),onBlur:g[2]||(g[2]=k=>s(!1))},null,544),[[ki,m.value]])],2)]))}},Ky=hn(A7,[["__scopeId","data-v-cc54b489"]]);It(),gn();var I7=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],E7={key:0,class:"existing-internal-input"},x7={class:"new-comment-input-wrapper"},T7={class:"reply-actions"},R7=["disabled"],M7={key:0,class:"resolved-badge"},L7=["innerHTML"],D7={key:1,class:"existing-internal-input"},P7={key:0,class:"card-section comment-body"},O7=["data-track-change-semantic-color-key"],F7={key:0},B7={class:"change-type tracked-change-label"},N7={key:0,class:"tracked-change-detail-lines"},z7={key:0,class:"tracked-change-text"},H7={key:1,class:"change-type"},U7={class:"change-type"},V7={key:1},j7={class:"tracked-change-text is-inserted"},G7={key:2},W7={class:"tracked-change-text is-inserted"},K7={key:3},q7={key:4},Y7={key:5},X7={key:6},Q7={class:"tracked-change-text"},Z7={key:7},J7={class:"tracked-change-text is-deleted"},$7={class:"tracked-change-text is-inserted"},eR={key:8},tR={class:"tracked-change-text is-deleted"},nR={key:9},rR={class:"tracked-change-text is-inserted"},oR=["data-track-change-image-preview-role"],iR=["src","alt"],sR={key:1,class:"card-section comment-body"},aR=["innerHTML"],lR={key:1,class:"comment"},cR={key:2,class:"reply-expanded"},uR={class:"reply-input-wrapper"},dR={class:"reply-actions"},fR=["onClick"],hR=["onClick","disabled","data-disabled-reason"],pR={class:"collapsed-avatars"},mR={key:3,class:"comment-separator"},gR={key:2,class:"tracked-change-decision-alert",role:"alert"},vR={class:"tracked-change-decision-alert__message"},yR=["disabled","data-disabled-reason"],bR={key:1,class:"reply-expanded"},wR={class:"reply-input-wrapper"},CR={class:"reply-actions"},_R=["disabled","data-disabled-reason"],mp=3,f_=90,SR={__name:"CommentDialog",props:{comment:{type:Object,required:!0},autoFocus:{type:Boolean,default:!1},parent:{type:Object,required:!1},floatingInstanceId:{type:String,default:null},floatingPageIndex:{type:Number,default:null},floatingPositionEntry:{type:Object,default:null},isFloatingInstanceActive:{type:Boolean,default:void 0}},emits:["click-outside","ready","dialog-exit","resize"],setup(e,{emit:t}){const n=t,r=e,{proxy:o}=sr(),i=nu(),s=ca(),{addComment:a,cancelComment:l,deleteComment:u,getCommentAliasIds:c,removePendingComment:d,getCommentDocumentId:h,requestInstantSidebarAlignment:m,resolveCommentPositionEntry:p,clearInstantSidebarAlignment:g,setActiveFloatingCommentInstance:k}=s,{suppressInternalExternal:w,getConfig:S,activeComment:y,activeFloatingCommentInstanceId:C,floatingCommentsOffset:T,pendingComment:R,currentCommentText:M,isDebugging:H,editingCommentId:B,editorCommentPositions:z,isCommentHighlighted:Z}=ea(s),P=ne(!0),N=ne(null),I=ne(new Map),L=ne(null),X=[[0,0],[-mp,0],[mp,0],[0,-mp],[0,mp]],te=ke=>{const Oe=typeof ke?.width=="number"&&Number.isFinite(ke.width)?ke.width:null,ht=typeof ke?.height=="number"&&Number.isFinite(ke.height)?ke.height:null;if(!Oe||!ht||Oe<=0||ht<=0)return{};const lt=Math.min(f_/Oe,f_/ht,1);return{width:`${Math.max(1,Math.round(Oe*lt))}px`,height:`${Math.max(1,Math.round(ht*lt))}px`}},le=[".comments-dropdown__option-label",".comments-dropdown__menu",".comments-dropdown__option",".comments-dropdown__option-icon",".comments-dropdown__trigger",".superdoc-comment-highlight",".sd-editor-comment-highlight",".sd-editor-tracked-change-highlight","[data-track-change-id]",".track-insert",".track-insert-dec",".track-delete",".track-delete-dec",".track-format",".track-format-dec"].join(","),fe=ke=>Oe=>{ke&&(Oe?(I.value.set(ke,Oe),B.value===ke&&_t(()=>{ge(ke)})):I.value.delete(ke))},Fe=(ke,Oe,ht)=>{const lt=ke?.getBoundingClientRect?.();return!lt||![lt.left,lt.top,lt.right,lt.bottom].every(Number.isFinite)||lt.width<=0||lt.height<=0?!1:X.some(([bn,an])=>{const Fr=Oe+bn,mo=ht+an;return Fr>=lt.left&&Fr<=lt.right&&mo>=lt.top&&mo<=lt.bottom})},he=(ke,Oe)=>{if(!Number.isFinite(ke)||!Number.isFinite(Oe))return null;const ht=document.querySelectorAll(le);for(const lt of ht)if(lt instanceof HTMLElement&&Fe(lt,ke,Oe))return lt;return null},ge=ke=>{I.value.get(ke)?.focus?.()},ae=ne(null),Ce=ke=>ke.resolvedTime?ke.commentId:ke.importedId||ke.commentId,oe=ke=>ke?ke.trackedChange&&ke.importedId!=null?String(ke.importedId):ke.commentId!=null?String(ke.commentId):null:null,xe=(ke,Oe)=>{const ht=ke?.bounds?.[Oe];return Number.isFinite(ht)?ht:null},qe=(ke,Oe)=>{if(!ke||!Oe||ke.pageIndex!==Oe.pageIndex)return!1;const ht=xe(ke,"top"),lt=xe(Oe,"top");return ht!=null&<!=null&&Math.abs(ht-lt)<.5},et=(ke,Oe)=>{const ht=xe(ke,"left"),lt=xe(Oe,"left"),bn=xe(ke,"right"),an=xe(Oe,"right");return[ht,lt,bn,an].some(Fr=>Fr==null)?!1:lt<bn&&ht<an},kt=(ke,Oe)=>{const ht=ke?.start,lt=ke?.end,bn=Oe?.start,an=Oe?.end;return[ht,lt,bn,an].every(Number.isFinite)?bn<=lt&&ht<=an:!1},Ie=(ke,Oe)=>!ke||!Oe||ke.kind&&Oe.kind&&ke.kind!==Oe.kind||ke.storyKey&&Oe.storyKey&&ke.storyKey!==Oe.storyKey?!1:Oe.start===ke.start&&Oe.end===ke.end?!0:qe(ke,Oe)&&et(ke,Oe)&&kt(ke,Oe),ze=ke=>{const Oe=new Set(c(ke)),{key:ht,entry:lt}=p(ke);return ht&&Oe.add(ht),lt?(Object.entries(z.value??{}).forEach(([bn,an])=>{Ie(lt,an)&&Oe.add(bn)}),[...Oe]):[...Oe]},Ve=(ke,Oe,ht=24)=>{if(!Number.isFinite(Oe)||typeof ke?.getBoundingClientRect!="function")return!1;const lt=ke.getBoundingClientRect().top;return Number.isFinite(lt)&&Math.abs(lt-Oe)<=ht},Q=Se(()=>r.floatingInstanceId??r.comment.commentId??null),_=Se(()=>typeof r.isFloatingInstanceActive=="boolean"?r.isFloatingInstanceActive:y.value!==r.comment.commentId?!1:r.floatingInstanceId==null?!0:C.value===r.floatingInstanceId),$=Se(()=>r.comment.resolvedTime?r.comment.trackedChange?r.comment.trackedChangeDecision==="reject"?"Rejected":"Accepted":"Resolved":null),F=Se(()=>R.value&&R.value.commentId===r.comment.commentId),j=Se(()=>ke=>{const Oe=Fn.value;return V.value&&ke===Oe.length-1?!0:Oe.length>1&&ke!==Oe.length-1}),V=Se(()=>!S.readOnly&&_.value&&!r.comment.resolvedTime&&!Dt.value),G=()=>({ok:!1,reason:"read-only-document"}),J=()=>S.value?.readOnly===!0,K=ne(!1),W=ne(!1),ue=()=>{if(J())return G();if(Tt.value)return{ok:!1,reason:sn.value?.reason??"v2-write-unavailable"};K.value=!0,_t(()=>{N.value?.focus?.(),n("resize")})},be=Se(()=>{const ke=r.comment;return ke.trackedChange?s.getTrackedChangeThread(ke):s.commentsList.filter(Oe=>{const ht=Oe.parentCommentId===ke.commentId,lt=Oe.commentId===ke.commentId;return ht||lt}).sort((Oe,ht)=>Oe.commentId===ke.commentId?-1:ht.commentId===ke.commentId?1:Oe.createdTime-ht.createdTime)}),we=ne(!1),Te=ne(null),rt=ne(!1),nt=Se(()=>!we.value),wt=()=>{we.value=!we.value,_t(()=>n("resize"))},Zt=()=>{if(we.value)return;const ke=Te.value;if(!ke){rt.value=!1;return}rt.value=ke.scrollHeight>ke.clientHeight+1};Pt(Te,()=>{_t(Zt)});const Ct=()=>B.value?be.value.some(ke=>ke.commentId===B.value):!1;Pt(_,ke=>{ke||((K.value||Ct())&&(M.value="",B.value=null),we.value=!1,Ot.value=!1,K.value=!1,_t(()=>n("resize")))});const Ot=ne(!1),Bt=Se(()=>be.value.slice(1)),on=Se(()=>Ot.value?!1:Bt.value.length>=2),Fn=Se(()=>on.value?[be.value[0],Bt.value[Bt.value.length-1]].filter(Boolean):be.value),Vt=Se(()=>on.value?Bt.value.length-1:0),We=Se(()=>{if(!on.value)return[];const ke=Bt.value.slice(0,-1),Oe=new Set;return ke.map(ht=>typeof ht.getCommentUser=="function"?ht.getCommentUser():{name:ht.creatorName,email:ht.creatorEmail||ht.email}).filter(ht=>{if(!ht)return!1;const lt=ht.email||ht.name;return Oe.has(lt)?!1:(Oe.add(lt),!0)}).slice(0,3)}),St=()=>{Ot.value=!0,Me(),_t(()=>n("resize"))},Nt=Se(()=>r.comment.resolvedTime?!0:S.value.readOnly),cn=Se(()=>ke=>_.value&&B.value===ke.commentId),Dt=Se(()=>!B.value||!_.value?!1:be.value.some(ke=>ke.commentId===B.value)),un=Se(()=>S.value.readOnly||!o.$superdoc.config.isInternal||ot.value?!1:!w.value&&!r.comment.trackedChange),Ft=Se(()=>M.value&&M.value!=="<p></p>"),Me=async()=>{const ke=o.$superdoc.activeEditor,Oe=ke?.editorVersion===2?ke?.v2Comments??null:null,ht=!!r.comment?.trackedChange,lt=jT(),bn=r.floatingInstanceId!=null,an=ae.value?.getBoundingClientRect?.().top,Fr=!r.comment.resolvedTime&&(y.value!==r.comment.commentId||bn&&Q.value!==C.value);let mo=lt;if(Oe){const go=!ht&&String(r.comment?.trackedChangeParentId??"").trim()?r.comment.trackedChangeParentId:null,To=ke?.editorVersion===2&&(ht||go!=null)?ke?.v2TrackedChanges??null:null,Is=go!=null?s.getComment(go):null,Jo=ht?r.comment:Is?.trackedChange?Is:go;let Ro=await(To?To.focusTrackedChange(Jo):Oe.focusComment(r.comment));return!ht&&Ro?.reason==="tracked-change-anchor-not-found"&&(Ro=await Oe.focusComment(r.comment)),Ro?.ok?(r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId)),Fr&&!bn?m(lt,r.comment.commentId,r.floatingInstanceId??null):Fr&&Number.isFinite(an)?m(an,r.comment.commentId,r.floatingInstanceId):g(),Ro):(g(),Ro)}if(ke){const{entry:go}=p(r.comment),To=r.floatingPositionEntry??go,Is=Number.isFinite(r.floatingPageIndex)&&r.comment?.trackedChangeStory?.storyType==="headerFooterPart",Jo=a_(r.parent,To),Ro=Is?null:GT(ze(r.comment)),Ki=Number.isFinite(Ro)?Ro:Jo,Gr=Ve(ae.value,Ki),Sr=Ce(r.comment),Mo=null;let Ho=null;if(ht)if(r.comment.trackedChangeStory&&(r.comment.trackedChangeStory,{...Number.isFinite(r.floatingPageIndex)?{pageIndex:r.floatingPageIndex}:{}}),r.comment.resolvedTime)ke.commands?.setCursorById(Sr);else{const $o=r.comment.commentId;ke.commands?.setCursorById(Sr,{activeCommentId:$o})||ke.commands?.setActiveComment({commentId:$o})}else{if(r.comment.resolvedTime)ke.commands?.setCursorById(Sr);else{const ll=r.comment.commentId;ke.commands?.setCursorById(Sr,{activeCommentId:ll})||ke.commands?.setActiveComment({commentId:ll})}const $o=r.comment.commentId;Ho=Gr?null:WT(Mo,Sr,$o,lt)}Number.isFinite(Ro)?mo=Ro:Number.isFinite(Jo)?mo=Jo:Number.isFinite(Ho)&&(mo=Ho)}Fr&&!bn?r.floatingInstanceId?m(mo,r.comment.commentId,r.floatingInstanceId):m(mo,r.comment.commentId):g(),r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId))},Pe=ke=>{const Oe=ke.target instanceof Element?ke.target:ke.target?.parentElement,ht=document.elementFromPoint(ke.clientX,ke.clientY);if(!(Oe?.closest?.(le)||ht?.closest?.(le)||he(ke.clientX,ke.clientY)||Z.value)&&!(ke.target.closest?.(".comments-dialog")&&!ae.value?.contains(ke.target))){if(F.value){l(o.$superdoc);return}_.value&&(T.value=0,n("dialog-exit"),y.value=null,s.setActiveComment(o.$superdoc,y.value),Z.value=!1)}},Ze=async()=>{if(J())return G();if(Tt.value)return{ok:!1,reason:sn.value?.reason??"v2-write-unavailable"};if(ot.value&&Mt.value&&!F.value){if(W.value)return{ok:!1,reason:"reply-submit-in-flight"};W.value=!0;try{const ht=await s.replyCommentV2({superdoc:o.$superdoc,parentCommentId:oe(r.comment),text:M.value});return ht?.ok?(K.value=!1,M.value="",_t(()=>n("resize")),ht):(_t(()=>n("resize")),ht)}finally{W.value=!1}}const ke={documentId:r.comment.fileId,isInternal:R.value?R.value.isInternal:P.value,parentCommentId:R.value?null:r.comment.commentId};R.value&&(ke.selection=R.value.selection.getValues());const Oe=s.getPendingComment(ke);!R.value&&M.value&&Oe.setText({text:M.value,suppressUpdate:!0}),Promise.resolve(a({superdoc:o.$superdoc,comment:Oe})).finally(()=>{K.value=!1,_t(()=>n("resize"))})},ot=Se(()=>o.$superdoc?.activeEditor?.editorVersion===2),Mt=Se(()=>ot.value?o.$superdoc?.activeEditor?.v2Comments??null:null),Et=Se(()=>ot.value?o.$superdoc?.activeEditor?.v2TrackedChanges??null:null),sn=Se(()=>{if(!Mt.value)return null;const ke=s.viewingVisibility.documentMode,Oe=Mt.value.getCapabilityState?.()??null;return ke==="viewing"?{...Oe??{},canWrite:!1,reason:"review-surface-read-only"}:Oe}),Tt=Se(()=>{if(!ot.value)return!1;const ke=sn.value;return ke?ke.canWrite===!1:!1}),ur=Se(()=>W.value?"reply-submit-in-flight":Tt.value?sn.value?.reason??"v2-write-unavailable":null),dr=Se(()=>{if(!Et.value)return null;const ke=s.viewingVisibility.documentMode,Oe=Et.value.getCapabilityState?.()??null;return ke==="viewing"&&Oe?.canDecide!==!1?{canDecide:!1,reason:"review-surface-read-only"}:Oe}),jr=ke=>{if(ot.value&&ke?.trackedChange){if(!Et.value)return"v2-tracked-change-adapter-missing";const Oe=dr.value;return Oe&&Oe.canDecide===!1?Oe.reason??"v2-tracked-change-unavailable":null}return Tt.value?sn.value?.reason??"v2-write-unavailable":null},$t=ke=>{if(ot.value&&ke?.trackedChange){if(!Et.value)return"v2-tracked-change-adapter-missing";const Oe=dr.value;return Oe&&Oe.canDecide===!1?Oe.reason??"v2-tracked-change-unavailable":null}return Tt.value?sn.value?.reason??"v2-write-unavailable":null},Vn=()=>ot.value?Mt.value?S.value?.readOnly?"read-only-document":Tt.value?sn.value?.reason??"v2-write-unavailable":null:"v2-comments-adapter-missing":null,Mr=Se(()=>!ot.value||!Tt.value?null:sn.value?.reason??"v2-write-unavailable"),_r=(ke,Oe)=>{L.value={decision:ke,reason:Oe?.reason??null},_t(()=>n("resize"))},po=()=>{L.value&&(L.value=null,_t(()=>n("resize")))},Kt=Se(()=>{const ke=L.value;if(!ke)return null;const Oe=ke.decision==="reject"?"reject":"accept";return ke.reason==="stale-catalog"?`Couldn't ${Oe} this change because the review list is stale.`:`Couldn't ${Oe} this change.`}),yn=()=>{const ke=L.value;if(ke){if(L.value=null,ke.decision==="reject"){xo();return}Zo()}},xo=async()=>{if(J())return G();const ke=o.$superdoc.config.onTrackedChangeBubbleReject;if(r.comment.trackedChange){if(ot.value){const ht=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});if(!ht?.ok||ht.success===!1){_r("reject",ht);return}po(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Oe=!0;if(typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else{const ht=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});Oe=!!ht?.ok&&ht.success!==!1}Oe&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"reject"})}else if(ot.value&&Mt.value){if(!(await s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId});_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Zo=async()=>{if(J())return G();if(!r.comment.trackedChange&&S.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};const ke=o.$superdoc.config.onTrackedChangeBubbleAccept;if(r.comment.trackedChange&&ot.value){const ht=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});if(!ht?.ok||ht.success===!1){_r("accept",ht);return}po(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Oe=!0;if(r.comment.trackedChange&&typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else if(r.comment.trackedChange){const ht=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});Oe=!!ht?.ok&&ht.success!==!1}else if(ot.value&&Mt.value){if(!(await s.resolveCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc});r.comment.trackedChange&&!ot.value&&Oe&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"accept"}),_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Ei=async()=>{if(J())return G();if(S.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};!ot.value||!Mt.value||(await s.reopenCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok&&_t(()=>{s.lastUpdate=new Date,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},pi=(ke,Oe)=>{if(J())return G();switch(ke){case"edit":M.value=Oe?.commentText?.value??Oe?.commentText??"",y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId),B.value=Oe.commentId,s.setActiveComment(o.$superdoc,y.value),_t(()=>{ge(Oe.commentId)});break;case"delete":u({superdoc:o.$superdoc,commentId:Oe.commentId});break}},Ss=async ke=>{if(J())return G();if(ot.value&&Mt.value){const Oe=await s.editCommentV2({superdoc:o.$superdoc,commentId:ke.commentId,text:M.value});return Oe?.ok&&(B.value=null,d(o.$superdoc)),Oe}B.value=null,ke.setText({text:M.value,superdoc:o.$superdoc}),d(o.$superdoc)},ks=ke=>{if(J())return G();const Oe=!!R.value,ht=ke.toLowerCase()==="internal";Oe?R.value.isInternal=ht:r.comment.setIsInternal({isInternal:ht,superdoc:o.$superdoc})},As=Se(()=>{const ke={};return(_.value||F.value||Dt.value)&&(ke.zIndex=50),ke}),al=ke=>typeof ke=="string"?new Date(ke).getTime():ke,Wi=ke=>{B.value=null,K.value=!1,l(o.$superdoc)},ro=Se(()=>{const ke=o.$superdoc.users;return r.comment.isInternal===!0?ke.filter(Oe=>Oe.access?.role==="internal"):ke});return Rn(()=>{r.autoFocus&&_t(()=>Me()),F.value&&_t(()=>{N.value?.focus?.()}),_t(()=>{n("ready",{commentId:r.floatingInstanceId??(r.comment.importedId!==void 0?r.comment.importedId:r.comment.commentId),elementRef:ae}),Zt()})}),Pt(V,ke=>{ke&&_t(()=>{N.value?.focus?.()})},{immediate:!0}),Pt(B,ke=>{if(!ke||!_.value)return;const Oe=be.value.find(ht=>ht.commentId===ke);!Oe||Oe.trackedChange||_t(()=>{ge(ke)})}),Pt(()=>S.value?.readOnly===!0,ke=>{ke&&(K.value=!1,be.value.some(Oe=>Oe.commentId===B.value)&&(B.value=null),F.value&&l(o.$superdoc),_t(()=>n("resize")))},{immediate:!0}),Pt(Tt,ke=>{ke&&(K.value=!1,_t(()=>n("resize")))}),(ke,Oe)=>{const ht=D2("click-outside");return Ws((me(),_e("div",{class:en(["comments-dialog",{"is-active":_.value||F.value,"is-resolved":r.comment.resolvedTime}]),onClick:Jt(Me,["stop","prevent"]),style:vn(As.value),ref_key:"commentDialogElement",ref:ae,role:"dialog","data-sd-part":"comment-thread","data-editor-ui-surface":"","data-comment-instance-id":r.floatingInstanceId??"","data-comment-thread-id":r.comment.commentId??"","data-comment-position-key":r.comment.trackedChangeAnchorKey??"","data-comment-page-index":Number.isFinite(r.floatingPageIndex)?r.floatingPageIndex:""},[F.value?(me(),_e(Wt,{key:0},[un.value?(me(),_e("div",E7,[Gt(c_,{onClick:Oe[0]||(Oe[0]=Jt(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":!1,state:Ge(R).isInternal?"internal":"external",onSelect:ks},null,8,["state"])])):ut("",!0),Gt(Gy,{config:Ge(S),comment:r.comment,"is-pending-input":!0},null,8,["config","comment"]),Le("div",x7,[Gt(Ky,{ref_key:"commentInput",ref:N,users:ro.value,config:Ge(S),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Le("div",T7,[Le("button",{class:"sd-button reply-btn-cancel",onClick:Jt(Wi,["stop","prevent"])},"Cancel"),Le("button",{class:en(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ft.value}]),onClick:Jt(Ze,["stop","prevent"]),disabled:!Ft.value}," Comment ",10,R7)])],64)):(me(),_e(Wt,{key:1},[$.value?(me(),_e("div",M7,[Le("span",{class:"resolved-badge__icon",innerHTML:Ge(ua).markDone},null,8,L7),Oi(" "+Ht($.value),1)])):ut("",!0),un.value?(me(),_e("div",D7,[Gt(c_,{onClick:Oe[1]||(Oe[1]=Jt(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":Nt.value,state:e.comment.isInternal?"internal":"external",onSelect:ks},null,8,["is-disabled","state"])])):ut("",!0),(me(!0),_e(Wt,null,or(Fn.value,(lt,bn)=>(me(),_e("div",{key:lt.commentId,class:"conversation-item"},[Gt(Gy,{config:Ge(S),timestamp:al(lt.createdTime),comment:lt,"is-active":_.value,"resolve-disabled-reason":jr(lt),"reject-disabled-reason":$t(lt),"reopen-supported":ot.value&&!!Mt.value,"reopen-disabled-reason":Vn(),"write-disabled-reason":Mr.value,onResolve:Zo,onReject:xo,onReopen:Ei,onOverflowSelect:an=>pi(an,lt)},null,8,["config","timestamp","comment","is-active","resolve-disabled-reason","reject-disabled-reason","reopen-supported","reopen-disabled-reason","write-disabled-reason","onOverflowSelect"]),lt.trackedChange?(me(),_e("div",P7,[Le("div",{class:en(["tracked-change",{"is-truncated":nt.value&&bn===0}]),"data-track-change-semantic-color-key":lt.semanticColorKey??void 0,ref_for:!0,ref:bn===0?an=>Te.value=an:void 0},[lt.trackedChangeLabel?(me(),_e("div",F7,[Le("span",B7,Ht(lt.trackedChangeLabel),1),lt.trackedChangeDetailLines&<.trackedChangeDetailLines.length?(me(),_e("div",N7,[(me(!0),_e(Wt,null,or(lt.trackedChangeDetailLines,(an,Fr)=>(me(),_e("div",{key:Fr,class:"tracked-change-detail-line"},[an.excerpt?(me(),_e("span",z7,'"'+Ht(an.excerpt)+'"',1)):ut("",!0),an.excerpt?(me(),_e("span",H7," — ")):ut("",!0),Le("span",U7,Ht(an.label),1)]))),128))])):ut("",!0)])):lt.trackedChangeDisplayType==="hyperlinkAdded"?(me(),_e("div",V7,[Oe[2]||(Oe[2]=Le("span",{class:"change-type"},"Added hyperlink ",-1)),Le("span",j7,'"'+Ht(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="hyperlinkModified"?(me(),_e("div",G7,[Oe[3]||(Oe[3]=Le("span",{class:"change-type"},"Changed hyperlink to ",-1)),Le("span",W7,'"'+Ht(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="paragraphSplit"?(me(),_e("div",K7,[...Oe[4]||(Oe[4]=[Le("span",{class:"change-type"},"Added new line",-1)])])):lt.trackedChangeDisplayType==="tableInsert"?(me(),_e("div",q7,[...Oe[5]||(Oe[5]=[Le("span",{class:"change-type"},"Added table",-1)])])):lt.trackedChangeDisplayType==="tableDelete"?(me(),_e("div",Y7,[...Oe[6]||(Oe[6]=[Le("span",{class:"change-type"},"Deleted table",-1)])])):lt.trackedChangeType==="trackFormat"?(me(),_e("div",X7,[Oe[7]||(Oe[7]=Le("span",{class:"change-type"},"Format: ",-1)),Le("span",Q7,Ht(lt.trackedChangeText),1)])):lt.trackedChangeType==="both"?(me(),_e("div",Z7,[Oe[8]||(Oe[8]=Le("span",{class:"change-type"},"Replaced ",-1)),Le("span",J7,'"'+Ht(lt.deletedText)+'"',1),Oe[9]||(Oe[9]=Le("span",{class:"change-type"}," with ",-1)),Le("span",$7,'"'+Ht(lt.trackedChangeText)+'"',1)])):lt.deletedText?(me(),_e("div",eR,[Oe[10]||(Oe[10]=Le("span",{class:"change-type"},"Deleted ",-1)),Le("span",tR,'"'+Ht(lt.deletedText)+'"',1)])):lt.trackedChangeText?(me(),_e("div",nR,[Oe[11]||(Oe[11]=Le("span",{class:"change-type"},"Added ",-1)),Le("span",rR,'"'+Ht(lt.trackedChangeText)+'"',1)])):ut("",!0),lt.trackedChangeImagePreview?.src?(me(),_e("div",{key:10,class:"tracked-change-image-preview","data-track-change-image-preview-role":lt.trackedChangeImagePreview.role??void 0},[Le("img",{class:"tracked-change-image-preview__image",src:lt.trackedChangeImagePreview.src,alt:lt.trackedChangeImagePreview.alt||"Tracked image preview",style:vn(te(lt.trackedChangeImagePreview)),loading:"lazy",decoding:"async"},null,12,iR)],8,oR)):ut("",!0)],10,O7),nt.value&&rt.value&&bn===0?(me(),_e("div",{key:0,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show more ")):ut("",!0),we.value&&rt.value&&bn===0?(me(),_e("div",{key:1,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show less ")):ut("",!0)])):ut("",!0),lt.trackedChange?ut("",!0):(me(),_e("div",sR,[!Ge(H)&&!cn.value(lt)?(me(),_e("div",{key:0,class:en(["comment",{"is-truncated":nt.value&&bn===0}]),ref_for:!0,ref:bn===0?an=>Te.value=an:void 0,innerHTML:lt.commentText},null,10,aR)):Ge(H)&&!cn.value(lt)?(me(),_e("div",lR,Ht(Ge(z)[lt.importedId!==void 0?lt.importedId:lt.commentId]?.bounds),1)):(me(),_e("div",cR,[Le("div",uR,[Gt(Ky,{ref_for:!0,ref:fe(lt.commentId),users:ro.value,config:Ge(S),"include-header":!1,comment:lt},null,8,["users","config","comment"])]),Le("div",dR,[Le("button",{class:"sd-button reply-btn-cancel",onClick:Jt(an=>Wi(lt),["stop","prevent"])},"Cancel",8,fR),Le("button",{class:en(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ft.value||Tt.value}]),onClick:Jt(an=>Ss(lt),["stop","prevent"]),disabled:!Ft.value||Tt.value,"data-disabled-reason":Tt.value?sn.value?.reason??null:null}," Update ",10,hR)])])),nt.value&&rt.value&&bn===0&&!cn.value(lt)?(me(),_e("div",{key:3,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show more ")):ut("",!0),we.value&&rt.value&&bn===0&&!cn.value(lt)?(me(),_e("div",{key:4,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show less ")):ut("",!0)])),on.value&&bn===0?(me(),_e(Wt,{key:2},[Oe[12]||(Oe[12]=Le("div",{class:"comment-separator"},null,-1)),Le("div",{class:"collapsed-replies",onClick:Jt(St,["stop","prevent"])},[Le("div",pR,[(me(!0),_e(Wt,null,or(We.value,an=>(me(),fn(u_,{key:an.email||an.name,user:an,class:"mini-avatar"},null,8,["user"]))),128))]),Le("span",null,Ht(Vt.value)+" more "+Ht(Vt.value===1?"reply":"replies"),1)])],64)):ut("",!0),j.value(bn)?(me(),_e("div",mR)):ut("",!0)]))),128)),L.value?(me(),_e("div",gR,[Le("span",vR,Ht(Kt.value),1),Le("button",{type:"button",class:"sd-button tracked-change-decision-alert__retry",onClick:Jt(yn,["stop","prevent"])}," Retry ")])):ut("",!0),V.value&&!Ge(S).readOnly?(me(),_e(Wt,{key:3},[K.value?(me(),_e("div",bR,[Le("div",wR,[Gt(Ky,{ref_key:"commentInput",ref:N,users:ro.value,config:Ge(S),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Le("div",CR,[Le("button",{class:"sd-button reply-btn-cancel",onClick:Jt(Wi,["stop","prevent"])},"Cancel"),Le("button",{class:en(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ft.value||Tt.value||W.value}]),onClick:Jt(Ze,["stop","prevent"]),disabled:!Ft.value||Tt.value||W.value,"data-disabled-reason":ur.value}," Reply ",10,_R)])])):(me(),_e("button",{key:0,type:"button",class:en(["reply-pill",{"sd-is-disabled":Tt.value}]),onClick:Jt(ue,["stop","prevent"]),disabled:Tt.value,"data-disabled-reason":Tt.value?sn.value?.reason??null:null}," Reply or add others with @ ",10,yR))],64)):ut("",!0)],64))],14,I7)),[[ht,Pe]])}}},gp=hn(SR,[["__scopeId","data-v-13257a67"]]);It(),gn();var kR={class:"comments-list"},AR={key:0},IR=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],ER={key:1},xR="headerFooterPart",TR={__name:"commentsList",props:{showMainComments:{type:Boolean,default:!0},showResolvedComments:{type:Boolean,default:!0}},setup(e){const t=e,n=ca(),r=$m(n,"isCommentsListVisible"),o=Se(()=>n.getGroupedComments),i=Se(()=>n.getFloatingCommentInstances),{activeComment:s,activeFloatingCommentInstanceId:a}=ea(n),l=m=>{const p=i.value.filter(g=>g?.comment?.commentId===m?.commentId);return p.length<2?[]:m?.trackedChange?m?.trackedChangeStory?.storyType!==xR?[]:p:[]},u=m=>!m?.comment?.commentId||s.value!==m.comment.commentId?!1:a.value==null?m.isPrimary===!0:String(a.value)===String(m.id),c=m=>{const p=l(m);return p.length?p.map(g=>({id:g.id,comment:m,floatingInstanceId:String(g.id),floatingPageIndex:g.pageIndex,floatingPositionEntry:g.positionEntry??null,isFloatingInstanceActive:u(g)})):[{id:m.commentId,comment:m,floatingInstanceId:null,floatingPageIndex:null,floatingPositionEntry:null,isFloatingInstanceActive:void 0}]},d=Se(()=>o.value.parentComments.flatMap(m=>c(m))),h=Se(()=>t.showResolvedComments&&o.value?.resolvedComments?.length>0);return Rn(()=>{r.value=!0}),ir(()=>{r.value=!1}),(m,p)=>(me(),_e("div",kR,[e.showMainComments?(me(),_e("div",AR,[(me(!0),_e(Wt,null,or(d.value,g=>(me(),_e("div",{key:g.id,class:"comment-item","data-comment-instance-id":g.floatingInstanceId??"","data-comment-thread-id":g.comment.commentId??"","data-comment-position-key":g.comment.trackedChangeAnchorKey??"","data-comment-page-index":Number.isFinite(g.floatingPageIndex)?g.floatingPageIndex:""},[Gt(gp,{comment:g.comment,"floating-instance-id":g.floatingInstanceId,"floating-page-index":g.floatingPageIndex,"floating-position-entry":g.floatingPositionEntry,"is-floating-instance-active":g.isFloatingInstanceActive},null,8,["comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])],8,IR))),128))])):ut("",!0),h.value?(me(),_e("div",ER,[p[0]||(p[0]=Le("div",{class:"comment-title"},"Resolved",-1)),(me(!0),_e(Wt,null,or(o.value.resolvedComments,g=>(me(),_e("div",{key:g.commentId,class:"comment-item"},[Gt(gp,{comment:g},null,8,["comment"])]))),128))])):ut("",!0)]))}},RR=hn(TR,[["__scopeId","data-v-e89dbc33"]]);It();var MR=class extends Dm.default{element;config={comments:[],element:null,commentsStore:null};constructor(e,t){super(),this.config={...this.config,...e},this.element=this.config.element,this.app=null,this.superdoc=t,this.open()}createVueApp(){this.app=Hl(RR);const e=this.superdoc?.app?._context?.provides;e&&this.app?._context?.provides&&Object.setPrototypeOf(this.app._context.provides,e),this.superdoc?.pinia&&(Dd(this.superdoc.pinia),this.app.use(this.superdoc.pinia),this.app.config.globalProperties.$pinia=this.superdoc.pinia),this.app.directive("click-outside",Fv),this.app.config.globalProperties.$superdoc=this.superdoc,!this.element&&this.config.selector&&(this.element=document.getElementById(this.config.selector)),this.container=this.app.mount(this.element)}close(){this.app&&(this.app.unmount(),this.app=null,this.container=null,this.element=null)}open(){this.app||this.createVueApp()}},LR,qa,qy=br((()=>{LR=2,qa=96/72}));It(),qy();var DR=96,PR=".superdoc__right-sidebar",OR=".sd-pdf-viewer-page";const Yy=Object.freeze({min:10,max:100,padding:0}),h_=e=>{const t=e&&typeof e=="object"?e:{},n=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a,r=n(t.min,Yy.min),o=n(t.max,Yy.max),i=typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding>=0?t.padding:Yy.padding;return{min:Math.min(r,o),max:Math.max(r,o),padding:i}},p_=(e,t)=>!(e>0)||!(t>0)?null:Math.round(e/t*100),FR=(e,t,n)=>{const r=p_(e-n.padding,t);return r===null?null:Math.max(1,Math.round(Math.min(n.max,Math.max(n.min,r))))},BR=(e,t,n)=>e>0?Number.isFinite(t)&&t>0?e/t*qa:n>0?e/n:e:null;function NR({getSuperdoc:e,superdocContainerWidth:t,isReady:n,activeZoom:r,zoomMode:o,viewportMetrics:i,showCommentsSidebar:s,rightSidebarRef:a,superdocRoot:l,documents:u}){const c=C=>{if(!C)return null;let T=0;try{const H=C.getPages?.();if(Array.isArray(H))for(const B of H){const z=B?.size?.w;typeof z=="number"&&Number.isFinite(z)&&z>T&&(T=z)}}catch{T=0}if(T>0)return T;let R=null;try{R=C.getPageStyles?.()??null}catch{R=null}const M=R?.pageSize?.width;return typeof M=="number"&&Number.isFinite(M)&&M>0?M*DR:null},d=()=>{if(!(u?.value??[]).some(R=>R?.type==="application/pdf"))return null;const C=l.value;if(!C?.querySelectorAll)return null;let T=0;for(const R of C.querySelectorAll(OR)){const M=Number(R.clientWidth)||Number(R.getBoundingClientRect?.().width)||0;let H=NaN;typeof window<"u"&&typeof window.getComputedStyle=="function"&&(H=Number.parseFloat(window.getComputedStyle(R).getPropertyValue("--scale-factor")));const B=(r.value??100)/100,z=BR(M,H,B);z!==null&&z>T&&(T=z)}return T>0?T:null},h=()=>{const C=e();if(!C)return null;const T=[],R=u?.value??[];for(const H of R){if(H?.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")continue;const B=c(H.getEditor?.());B!==null&&T.push(B)}if(T.length===0){const H=c(C.activeEditor);H!==null&&T.push(H)}const M=d();if(M!==null&&T.push(M),T.length>0)return Math.max(...T);if(C.activeEditor){const H=l.value?.querySelector?.(".superdoc__document"),B=Number(H?.clientWidth)||Number(H?.getBoundingClientRect?.().width)||0;if(B>0){const z=(r.value??100)/100;return z>0?B/z:B}}return null},m=()=>{if(!s?.value)return 0;const C=a?.value??l.value?.querySelector?.(PR),T=Number(C?.offsetWidth)||Number(C?.getBoundingClientRect?.().width)||0;return T>0?T:0},p=(C,T)=>{const R=h_(C.config?.zoom?.fitWidth),M=FR(T.availableWidth,T.documentWidth,R);M!==null&&M!==r.value&&(r.value=M,C.emit("zoomChange",{zoom:M,mode:"fit-width"}))},g=()=>{const C=e();if(!C)return;const T=t.value;if(!(T>0)||!n.value)return;const R=h();if(R===null)return;const M=T-m(),H=p_(M,R);if(H===null)return;const B=Object.freeze({availableWidth:M,documentWidth:R,fitZoom:H}),z=i.value;(!z||z.availableWidth!==M||z.documentWidth!==R||z.fitZoom!==H)&&(i.value=B),(!z||z.fitZoom!==H||Math.round(z.documentWidth)!==Math.round(R))&&C.emit("viewport-change",B),o.value==="fit-width"&&p(C,B)};Pt(t,()=>{_t(()=>g())}),Pt(n,C=>{C&&g()}),Pt(o,C=>{C==="fit-width"&&g()}),s&&Pt(s,()=>{_t(()=>g())});const k=()=>{_t(()=>g())},w=()=>{_t(()=>g())},S=()=>{_t(()=>g())},y=e();return y?.on?.("editorCreate",k),y?.on?.("pagination-update",w),y?.on?.("pdf:document-ready",S),ir(()=>{y?.off?.("editorCreate",k),y?.off?.("pagination-update",w),y?.off?.("pdf:document-ready",S)}),{evaluateViewport:g}}const zR=e=>!!e?.trackedChange,HR=e=>e,UR=(e,t,n,r=e)=>!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?!1:(Number.isFinite(r)?r:e)<t||e>n,VR=({comment:e,anchorTop:t,anchorBottom:n,viewportTop:r,viewportBottom:o})=>zR(e)&&UR(t,r,o,n),jR=({comment:e,anchorTop:t,anchorBottom:n,cardHeight:r,viewportTop:o,viewportBottom:i})=>!VR({comment:e,anchorTop:t,anchorBottom:n,viewportTop:o,viewportBottom:i})||!Number.isFinite(r)?null:(Number.isFinite(n)?n:t)<o?Math.min(t,o-r-1):t,GR=({id:e,visibleIds:t,activeCommentInstanceId:n})=>e?!!(e==="pending"||n!=null&&String(e)===String(n)||t?.has?.(e)):!1,m_=({previousIds:e,currentIds:t,removedId:n})=>{if(!Array.isArray(e)||!(t instanceof Set)||!n)return null;const r=e.indexOf(n);if(r<0)return null;for(let o=r+1;o<e.length;o+=1){const i=e[o];if(t.has(i))return i}for(let o=r-1;o>=0;o-=1){const i=e[o];if(t.has(i))return i}return null};It(),gn();var WR=["data-comment-id","data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Gl={},KR={__name:"FloatingComments",props:{currentDocument:{type:Object,required:!0},parent:{type:Object,required:!0}},setup(e){const r=(Me,Pe,Ze)=>{if(Pe>=0){Me[Pe].top=Me[Pe].anchorTop;let ot=Me[Pe].top+Me[Pe].height+Ze;for(let Et=Pe+1;Et<Me.length;Et++)Me[Et].top=Math.max(Me[Et].anchorTop,ot),ot=Me[Et].top+Me[Et].height+Ze;ot=Me[Pe].top-Ze;for(let Et=Pe-1;Et>=0;Et--){const sn=ot-Me[Et].height;Me[Et].top=Math.min(Me[Et].anchorTop,sn),ot=Me[Et].top-Ze}const Mt=Math.min(...Me.map(Et=>Et.top));if(Mt<0){const Et=Math.abs(Mt);for(const sn of Me)sn.top+=Et}}else for(let ot=1;ot<Me.length;ot++){const Mt=Me[ot-1],Et=Mt.top+Mt.height+Ze;Me[ot].top<Et&&(Me[ot].top=Et)}},o=e,i=nu(),s=ca(),{clearInstantSidebarAlignment:a}=s,{activeComment:l,activeFloatingCommentInstanceId:u,editorCommentPositions:c,pendingComment:d,editingCommentId:h,instantSidebarAlignmentTargetY:m,instantSidebarAlignmentThreadId:p,instantSidebarAlignmentInstanceId:g}=ea(s),{activeZoom:k}=ea(i),w=Se(()=>{const Me=s.getFloatingCommentInstances;if(!Array.isArray(Me))return[];const Pe=o.currentDocument?.id;return Pe==null?Me:Me.filter(Ze=>s.belongsToDocument(Ze.comment,String(Pe),{allowSingleDocumentMismatch:!0}))}),S=ne(null),y=ne(0),C=ne(0),T=ne(!1),R=ne(null),M=ne(0),H=Me=>{const Pe=d.value?.commentId;return Pe?typeof Me=="object"?Me?.commentId===Pe:Me===Pe||Me==="pending":!1},B=Me=>Me?.commentId??Me?.importedId??null,z=Se(()=>{const Me=new Map,Pe=new Map;for(const Ze of w.value){Ze?.id!=null&&Me.set(String(Ze.id),Ze);const ot=B(Ze?.comment);if(ot==null)continue;const Mt=String(ot),Et=Pe.get(Mt)??[];Et.push(Ze),Pe.set(Mt,Et)}return{byId:Me,byThreadId:Pe}}),Z=(Me,Pe=null)=>{if(Me==null)return null;const Ze=String(Me),ot=z.value.byThreadId.get(Ze)??[];if(!ot.length)return null;if(Pe!=null){const Mt=ot.find(Et=>String(Et.id)===String(Pe));if(Mt)return Mt.id}return ot.find(Mt=>Mt.isPrimary)?.id??ot[0]?.id??null},P=Se(()=>l.value?Z(l.value,u.value):null),N=Me=>{if(typeof Me=="number")return Number.isFinite(Me)?Me:null;if(typeof Me!="string"||Me.trim()==="")return null;const Pe=Number(Me);return Number.isFinite(Pe)?Pe:null},I=ne({...Gl}),L=ne(new Set),X=ne({});let te=null;const le=new Set;let fe=null;const Fe=()=>{fe==null&&(fe=requestAnimationFrame(()=>{fe=null,M.value+=1}))},he=Me=>{if(o.currentDocument.type==="application/pdf"){const Pe=(k.value??100)/100,Ze=N(Me?.comment?.selection?.selectionBounds?.top);return Ze==null?null:Ze*Pe}return Me?.positionEntry?.bounds?.top},ge=(Me,Pe)=>{if(o.currentDocument.type==="application/pdf"){const ot=(k.value??100)/100,Mt=N(Me?.comment?.selection?.selectionBounds?.bottom);return Mt!=null?Mt*ot:Pe}const Ze=Me?.positionEntry?.bounds?.bottom;return Number.isFinite(Ze)?Ze:Pe},ae=Se(()=>{const Me=[];for(const Pe of w.value){const Ze=Pe?.id,ot=B(Pe?.comment),Mt=he(Pe);if(Ze==null||ot==null||!Number.isFinite(Mt))continue;const Et=HR(Mt,Pe.comment);Me.push({id:Ze,threadId:ot,instance:Pe,top:Et,anchorBottom:ge(Pe,Et)})}return Me}),Ce=()=>{const Me=c.value.pending;if(typeof Me?.bounds?.top=="number"&&!isNaN(Me.bounds.top))return Me.bounds.top;const Pe=o.currentDocument.type==="application/pdf"?(k.value??100)/100:1,Ze=N(d.value?.selection?.selectionBounds?.top);return Ze==null?null:Ze*Pe},oe=Me=>GR({id:Me?.id,visibleIds:L.value,activeCommentInstanceId:P.value,comment:Me?.commentRef}),xe=()=>{const Me=S.value;if(!Me)return null;const Pe=Me.getBoundingClientRect();if(!Number.isFinite(Pe.top)||!Number.isFinite(window.innerHeight))return null;let Ze=0,ot=window.innerHeight;for(let Et=Me.parentElement;Et;Et=Et.parentElement){const sn=window.getComputedStyle(Et).overflowY;if(!["auto","scroll","hidden","clip"].includes(sn))continue;const Tt=Et.getBoundingClientRect();!Number.isFinite(Tt.top)||!Number.isFinite(Tt.bottom)||(Ze=Math.max(Ze,Tt.top),ot=Math.min(ot,Tt.bottom))}if(ot<=Ze)return null;const Mt=o.parent?.getBoundingClientRect?.();if(Mt&&Number.isFinite(Mt.top)&&Number.isFinite(Mt.bottom)){const Et=Math.max(Ze,Mt.top),sn=Math.min(ot,Mt.bottom);sn>Et&&(Ze=Et,ot=sn)}return{top:Ze-Pe.top,bottom:ot-Pe.top}},qe=Se(()=>p.value?Z(p.value,g.value):null),et=Se(()=>{M.value;const Me=ae.value,Pe=d.value&&d.value.fileId===o.currentDocument.id;if(!Me.length&&!w.value.length&&!Pe)return[];const Ze=[],ot=xe()??{top:0,bottom:Math.max(0,o.parent?.clientHeight||window.innerHeight||0)},Mt=ot.top-600,Et=ot.bottom+600,sn=Pe?"pending":P.value,Tt=new Set,ur=({id:$t,threadId:Vn,instance:Mr,top:_r,anchorBottom:po,hasAnchorGeometry:Kt})=>{const yn=String($t);Tt.has(yn)||(Tt.add(yn),Ze.push({id:$t,threadId:Vn,pageIndex:Mr?.pageIndex??null,anchorTop:_r,anchorBottom:po,hasAnchorGeometry:Kt,top:_r,height:I.value[$t]||110,commentRef:Mr.comment,instanceRef:Mr}))};for(const $t of Me){const{id:Vn,threadId:Mr,instance:_r,top:po,anchorBottom:Kt}=$t,yn=sn!=null&&String(Vn)===String(sn),xo=h.value!=null&&String(Mr)===String(h.value);!yn&&!xo&&(Kt<Mt||po>Et)||ur({id:Vn,threadId:Mr,instance:_r,top:po,anchorBottom:Kt,hasAnchorGeometry:!0})}const dr=[];if(sn&&sn!=="pending"){const $t=z.value.byId.get(String(sn));$t&&dr.push($t)}if(h.value!=null){const $t=z.value.byThreadId.get(String(h.value))??[],Vn=$t.find(Mr=>Mr.isPrimary)??$t[0];Vn&&dr.push(Vn)}for(const $t of dr){const Vn=$t.id,Mr=B($t.comment);Vn==null||Mr==null||Tt.has(String(Vn))||ur({id:Vn,threadId:Mr,instance:$t,top:ot.top,anchorBottom:ot.top,hasAnchorGeometry:!1})}if(Pe){const $t=Ce();typeof $t=="number"&&!isNaN($t)&&Ze.push({id:"pending",anchorTop:$t,anchorBottom:$t,hasAnchorGeometry:!0,top:$t,height:I.value.pending||110,commentRef:d.value})}Ze.sort(($t,Vn)=>$t.anchorTop-Vn.anchorTop);const jr=[];for(const $t of Ze){const Vn=$t.hasAnchorGeometry?jR({comment:$t.commentRef,anchorTop:$t.anchorTop,anchorBottom:$t.anchorBottom,cardHeight:$t.height,viewportTop:ot.top,viewportBottom:ot.bottom}):null;Vn==null?jr.push($t):$t.top=Vn}return r(jr,sn?jr.findIndex($t=>$t.id===sn):-1,15),Ze}),kt=Se(()=>(M.value,Math.max(0,o.parent?.clientHeight||0,o.parent?.scrollHeight||0))),Ie=()=>{te&&te.disconnect(),te=new IntersectionObserver(Me=>{const Pe=new Set(L.value);for(const Ze of Me){const ot=Ze.target.dataset.commentId;ot&&(Ze.isIntersecting?Pe.add(ot):Pe.delete(ot))}L.value=Pe},{rootMargin:"600px 0px 600px 0px"})},ze=()=>{if(!te)return;const Me=new Set;for(const Pe of et.value){const Ze=X.value[Pe.id];Ze&&(Me.add(Ze),le.has(Ze)||(te.observe(Ze),le.add(Ze)))}for(const Pe of le)Me.has(Pe)||(te.unobserve(Pe),le.delete(Pe))},Ve=(Me,Pe)=>{Pe<=0||Pe===I.value[Me]||(Gl[Me]=Pe,I.value={...I.value,[Me]:Pe})},Q=Me=>{if(!Me)return;const{elementRef:Pe,commentId:Ze}=Me;Pe&&_t(()=>{const ot=Pe.value?.getBoundingClientRect();!ot||ot.height<=0||Ze&&Ve(Ze,ot.height)})},_=Me=>{const Pe=Me?.id;Pe&&_t(()=>{const Ze=X.value[Pe];if(!Ze)return;const ot=Ze.querySelector(".comments-dialog");if(!ot)return;Ve(Pe,ot.getBoundingClientRect().height);const Mt=Pe===P.value,Et=Pe==="pending",sn=!!h.value&&!!l.value&&Me?.threadId!=null&&String(Me.threadId)===String(l.value);!Mt&&!Et&&!sn||(Ct(et.value.map(Tt=>Tt.id)),on(()=>et.value.map(Tt=>Tt.id)))})},$=Me=>{!Me&&R.value!=null||(T.value=Me)},F=(Me,Pe,Ze)=>{if(!Number.isFinite(Pe)){Ze?.(!1);return}const ot=X.value[Me];if(!ot){Ze?.(!1);return}const Mt=ot.getBoundingClientRect().top;C.value+=Pe-Mt,Ze?.(!0)},j=(Me,Pe)=>{if(Pe)X.value[Me]=Pe,te&&!le.has(Pe)&&(te.observe(Pe),le.add(Pe));else{const Ze=X.value[Me];Ze&&te&&(te.unobserve(Ze),le.delete(Ze)),delete X.value[Me]}};let V=[],G=null,J=[],K=null,W=!1,ue=0,be=null,we=null,Te=null,rt=null;const nt=()=>{Te=null,rt=null,R.value=null,$(!1)},wt=Me=>{if(!Te)return;const Pe=(Me?.target instanceof Element?Me.target:null)?.closest?.("[data-comment-action]"),Ze=Pe?.getAttribute?.("data-comment-action");(Ze==="resolve"||Ze==="reject")&&S.value?.contains?.(Pe)||nt()},Zt=()=>{V.forEach(clearTimeout),V=[]},Ct=Me=>{for(const Pe of Me.filter(Boolean)){const Ze=X.value[Pe];if(!Ze)continue;const ot=Ze.querySelector(".comments-dialog");ot&&Ve(Pe,ot.getBoundingClientRect().height)}},Ot=50,Bt=350,on=Me=>{Zt();const Pe=typeof Me=="function"?Me:()=>Me;V.push(setTimeout(()=>Ct(Pe()),Ot)),V.push(setTimeout(()=>Ct(Pe()),Bt))},Fn=()=>{a(),requestAnimationFrame(()=>{$(!1)})},Vt=(Me,Pe)=>{!Me||!Number.isFinite(Pe)||($(!0),_t(()=>{Ct([Me]),F(Me,Pe,()=>{Fn()})}))},We=()=>{K=null,ue+=1,be!=null&&(cancelAnimationFrame(be),be=null),$(!1)},St=()=>{if(!K||W)return;W=!0;const Me=ue;be!=null&&(cancelAnimationFrame(be),be=null),$(!0),_t(()=>{if(W=!1,Me!==ue){St();return}const{key:Pe,targetClientY:Ze}=K;Ct([Pe]),F(Pe,Ze,ot=>{if(Me===ue){if(!ot){$(!1);return}be=requestAnimationFrame(()=>{be=null,Me===ue&&$(!1)})}})})},Nt=(Me,Pe)=>{const Ze=m_({previousIds:J,currentIds:Pe,removedId:Me}),ot=(Ze?X.value[Ze]:null)?.getBoundingClientRect?.().top;return!Ze||!Number.isFinite(ot)?(We(),!1):(K={key:Ze,targetClientY:ot},ue+=1,St(),!0)},cn=Me=>{const Pe=Me?.target?.closest?.("[data-comment-action]"),Ze=Pe?.getAttribute?.("data-comment-action");if(Ze!=="resolve"&&Ze!=="reject"||(nt(),Pe.getAttribute?.("aria-disabled")==="true"))return;const ot=Pe.closest?.("[data-comment-id]")?.getAttribute?.("data-comment-id");if(!ot||String(P.value??"")===String(ot))return;const Mt=et.value.filter(Tt=>Tt.commentRef?.trackedChange).map((Tt,ur)=>({id:Tt.id,index:ur,top:Tt.top})).filter(Tt=>Number.isFinite(Tt.top)).sort((Tt,ur)=>Tt.top-ur.top||Tt.index-ur.index).map(Tt=>Tt.id),Et=m_({previousIds:Mt,currentIds:new Set(Mt),removedId:ot}),sn=(Et?X.value[Et]:null)?.getBoundingClientRect?.().top;!Et||!Number.isFinite(sn)||(Te={removedKey:ot,targetKey:Et,targetClientY:sn,applied:!1},rt=ot,R.value=Et,$(!0))};Pt(P,(Me,Pe)=>{if(Zt(),!(Te!=null&&rt!=null&&[Me,Pe].some(Mt=>Mt!=null&&String(Mt)===String(rt)))){if(rt=null,Me)nt(),We();else if(Pe){const Mt=new Set(et.value.map(Et=>Et.id));Mt.has(Pe)?We():Nt(Pe,Mt)}}const Ze=[Me,Pe],ot=Me&&Me===qe.value&&Number.isFinite(m.value);_t(()=>{if(ot){Ct(Ze);return}on(Ze)})}),Pt([P,qe,m],([Me,Pe,Ze])=>{!Me||!Pe||Me!==Pe||!Number.isFinite(Ze)||Vt(Me,Ze)}),Pt(h,()=>{Zt(),_t(()=>{on(()=>et.value.map(Me=>Me.id))})}),Pt(l,()=>{if(G&&clearTimeout(G),!l.value){if(a(),K){St();return}$(!1),C.value=0;return}if(!(H(l.value)?d.value:s.getComment(l.value)))return;const Me=H(l.value)?"pending":P.value;if(Me){if(Me===qe.value&&Number.isFinite(m.value)){$(!0);return}_t(()=>{G=setTimeout(()=>{const Ze=X.value[Me];if(!Ze)return;const ot=o.parent?.getBoundingClientRect?.();if(!ot)return;const Mt=et.value.find(ur=>ur.id===Me),Et=Me==="pending"?Ce():Mt?.anchorTop;if(typeof Et!="number"||isNaN(Et))return;const sn=Ze.getBoundingClientRect().top,Tt=ot.top+Et;C.value+=Tt-sn},400)})}}),Pt(k,()=>{if(o.currentDocument.type==="application/pdf"){for(const Me in Gl)delete Gl[Me];I.value={},y.value+=1}});let Dt=new Set,un=null,Ft=null;return Pt(et,Me=>{const Pe=P.value?Me.find(Kt=>Kt.id===P.value):null,Ze=typeof Pe?.anchorTop=="number"&&Number.isFinite(Pe.anchorTop)?Pe.anchorTop:null,ot=Ze!=null&&un!=null&&Math.abs(Ze-un)>1,Mt=typeof Pe?.top=="number"&&Number.isFinite(Pe.top)?Pe.top:null,Et=Mt!=null&&Ft!=null&&Math.abs(Mt-Ft)>1;ot&&C.value!==0&&!Number.isFinite(m.value)?(C.value=0,$(!1)):Et&&C.value!==0&&!Number.isFinite(m.value)&&!K&&($(!0),C.value+=Ft-Mt,we!=null&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{we=null,!K&&!Number.isFinite(m.value)&&$(!1)})),un=Ze,Ft=Mt;const sn=Me.map(Kt=>Kt.id),Tt=new Set(sn);if(Te&&!Te.applied&&!Tt.has(Te.removedKey)){const{targetKey:Kt,targetClientY:yn}=Te;Te.applied=!0,Tt.has(Kt)&&Number.isFinite(yn)?(K={key:Kt,targetClientY:yn},ue+=1,St()):nt()}if(Te?.applied&&!Tt.has(Te.targetKey)&&nt(),K&&!Tt.has(K.key)){const Kt=K.key;Nt(Kt,Tt)||($(!1),C.value=0)}const ur=new Set(L.value);let dr=!1,jr=-1/0,$t=1/0;const Vn=S.value;if(Vn){const Kt=Vn.getBoundingClientRect();jr=-Kt.top-600,$t=-Kt.top+window.innerHeight+600}const Mr=new Map(Me.map(Kt=>[Kt.id,Kt]));for(const Kt of Tt)if(!ur.has(Kt)){const yn=Mr.get(Kt);(!yn||yn.top>=jr&&yn.top<=$t)&&(ur.add(Kt),dr=!0)}for(const Kt of ur)Tt.has(Kt)||(ur.delete(Kt),dr=!0);dr&&(L.value=ur);for(const Kt of Dt)Tt.has(Kt)||delete Gl[Kt];const _r=Dt.size!==Tt.size||[...Dt].some(Kt=>!Tt.has(Kt)),po=J.length!==sn.length||J.some((Kt,yn)=>Kt!==sn[yn]);if(_r){const Kt={};for(const yn of Tt)Gl[yn]&&(Kt[yn]=Gl[yn]);I.value=Kt,_t(()=>{for(const yn of Me){const xo=X.value[yn.id];if(!xo)continue;const Zo=xo.querySelector(".comments-dialog");Zo&&Ve(yn.id,Zo.getBoundingClientRect().height)}})}K&&(_r||po)&&St(),Dt=Tt,_t(()=>{J=sn,ze()})}),Rn(()=>{Ie(),o.parent?.addEventListener?.("scroll",Fe,{passive:!0}),window.addEventListener("resize",Fe,{passive:!0}),document.addEventListener("pointerdown",wt,!0),_t(ze)}),ir(()=>{Zt(),G&&clearTimeout(G),nt(),We(),we!=null&&(cancelAnimationFrame(we),we=null),o.parent?.removeEventListener?.("scroll",Fe),window.removeEventListener("resize",Fe),document.removeEventListener("pointerdown",wt,!0),fe!=null&&(cancelAnimationFrame(fe),fe=null),te&&(te.disconnect(),te=null,le.clear())}),(Me,Pe)=>(me(),_e("div",{class:"section-wrapper",ref_key:"floatingCommentsContainer",ref:S,onClickCapture:cn,style:vn({minHeight:kt.value+"px",transition:T.value?"none":void 0})},[Le("div",{class:"sidebar-container",style:vn({transform:`translateY(${C.value}px)`,transition:T.value?"none":void 0})},[(me(!0),_e(Wt,null,or(et.value,Ze=>(me(),_e("div",{key:Ze.id,ref_for:!0,ref:ot=>j(Ze.id,ot),"data-comment-id":Ze.id,"data-comment-instance-id":Ze.id,"data-comment-thread-id":Ze.threadId,"data-comment-position-key":Ze.instanceRef?.positionKey??"","data-comment-page-index":Ze.pageIndex??"",class:en([{"is-direct-decision-continuity-target":Ze.id===R.value},"comment-placeholder"]),style:vn({top:Ze.top+"px",height:Ze.height+"px",transition:T.value?"none":void 0})},[oe(Ze)?(me(),fn(gp,{key:Ze.id+y.value,onReady:Q,onResize:ot=>_(Ze),class:"floating-comment",parent:e.parent,comment:Ze.commentRef,"floating-instance-id":Ze.id,"floating-page-index":Ze.pageIndex,"floating-position-entry":Ze.instanceRef?.positionEntry??null,"is-floating-instance-active":Ze.id===P.value},null,8,["onResize","parent","comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])):ut("",!0)],14,WR))),128))],4)],36))}},qR=hn(KR,[["__scopeId","data-v-b5be33eb"]]);It(),gn();var YR={class:"superdoc__pdf-comments-layer pdf-comments-layer","aria-hidden":"false"},XR=["data-id","data-comment-id","data-page-number","onClick","onKeydown"],QR="pdf",ZR="#078383",JR="#B1124B",$R={__name:"PdfCommentsLayer",emits:["anchor-activate"],setup(e,{emit:t}){const n=t,r=ca(),o=nu(),{activeComment:i}=ea(r),{documents:s,activeZoom:a}=ea(o),{proxy:l}=sr(),u=y=>typeof y=="number"?Number.isFinite(y):typeof y=="string"&&y.trim()!==""?Number.isFinite(Number(y)):!1,c=y=>!!y&&u(y.top)&&u(y.left)&&u(y.right)&&u(y.bottom),d=Se(()=>{const y=Array.isArray(s.value)?s.value:[];return new Set(y.filter(C=>C?.type===Ul).map(C=>String(C.id)))}),h=y=>{const C=y?.fileId??y?.documentId??y?.selection?.documentId;return C!=null?String(C):null},m=y=>{const C=y?.commentId??y?.importedId;return C!=null&&String(C)!==""?String(C):null},p=y=>{const C=d.value;if(!C.size)return!1;const T=h(y);return T?C.has(T):C.size===1},g=y=>{const C=Math.min(Number(y.top),Number(y.bottom)),T=Math.max(Number(y.top),Number(y.bottom));return{top:C,left:Math.min(Number(y.left),Number(y.right)),right:Math.max(Number(y.left),Number(y.right)),bottom:T}},k=Se(()=>{const y=r.getFloatingComments;return Array.isArray(y)?y.filter(C=>C?.selection?.source===QR).filter(C=>!C.resolvedTime).filter(C=>m(C)!==null).filter(C=>c(C.selection?.selectionBounds)).filter(C=>p(C)).map(C=>{const T=m(C),R=g(C.selection.selectionBounds);return{commentId:T,page:C.selection?.page??null,isInternal:C.isInternal!==!1,bounds:R}}):[]}),w=y=>{const C=(a.value??100)/100,{top:T,left:R,right:M,bottom:H}=y.bounds,B=i.value===y.commentId,z=(y.isInternal?ZR:JR)+(B?"66":"33");return{position:"absolute",top:T*C+"px",left:R*C+"px",width:(M-R)*C+"px",height:(H-T)*C+"px",backgroundColor:z}},S=y=>{r.setActiveComment(l.$superdoc,y.commentId),n("anchor-activate",y.commentId)};return(y,C)=>(me(),_e("div",YR,[(me(!0),_e(Wt,null,or(k.value,T=>(me(),_e("div",{key:T.commentId,class:"sd-comment-anchor sd-highlight",role:"button",tabindex:"0","data-id":T.commentId,"data-comment-id":T.commentId,"data-page-number":T.page,style:vn(w(T)),onClick:Jt(R=>S(T),["stop","prevent"]),onKeydown:[Yo(Jt(R=>S(T),["stop","prevent"]),["enter"]),Yo(Jt(R=>S(T),["stop","prevent"]),["space"])]},null,44,XR))),128))]))}},e9=hn($R,[["__scopeId","data-v-b5ad4c58"]]);It();const t9=({proxy:e,layers:t,documents:n,modules:r})=>{const o=Se(()=>{const z=r.value?.whiteboard??r.whiteboard;return z===!1||z==null?null:z}),i=e?.$superdoc?.whiteboard,s=Ur([]),a=zr({}),l=zr({}),u=ne(!1),c=ne(0),d=ne(0),h=ne(1),m=ne(o.value?.enabled??!1),p=()=>{if(u.value)return;c.value+=1;const z=d.value||s.value.length;z&&c.value>=z&&(u.value=!0,e?.$superdoc?.emit("whiteboard:ready",{whiteboard:i}))},g=z=>{if(!z)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&k(z)},k=z=>{const{pageIndex:Z,width:P,height:N,originalWidth:I,originalHeight:L}=z,X={width:P,height:N,originalWidth:I,originalHeight:L};i?.setPageSize(Z,X),a[Z]=X;const te=i?.getPage(Z);te&&te.setSize(X),i&&(s.value=i.getPages().sort((le,fe)=>le.pageIndex-fe.pageIndex).map(le=>Hr(le)),d.value=s.value.length),_t(()=>{H(),p()})},w=z=>{e?.$superdoc?.emit("whiteboard:change",z)},S=z=>{z.forEach(Z=>{const P=a[Z.pageIndex];P&&Z.setSize(P)}),s.value=z.map(Z=>Hr(Z)),d.value=s.value.length,_t(()=>H())},y=z=>{m.value=z,e?.$superdoc?.emit("whiteboard:enabled",z)},C=z=>{h.value=z},T=z=>{e?.$superdoc?.emit("whiteboard:tool",z)},R=()=>{const z=n.value?.[0];z&&z.type==="application/pdf"&&M({doc:z})},M=({doc:z})=>{s.value.forEach(Z=>{const P=`${z.id}-page-${Z.pageIndex+1}`,N=document.querySelector(`[data-page-id="${P}"]`);if(!N)return;const I=N.getBoundingClientRect(),L=a[Z.pageIndex]||{},X=L.originalWidth??Z.size?.originalWidth??I.width,te=L.originalHeight??Z.size?.originalHeight??I.height,le={width:I.width,height:I.height,originalWidth:X,originalHeight:te};a[Z.pageIndex]=le,Z.setSize(le)})},H=()=>{const z=t.value?.getBoundingClientRect?.();if(!z)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&B({doc:Z,layerBounds:z})},B=({doc:z,layerBounds:Z})=>{s.value.forEach(P=>{const N=`${z.id}-page-${P.pageIndex+1}`,I=document.querySelector(`[data-page-id="${N}"]`);if(!I)return;const L=I.getBoundingClientRect();l[P.pageIndex]={top:L.top-Z.top,left:L.left-Z.left}})};return i&&(i.on("change",w),i.on("setData",S),i.on("enabled",y),i.on("opacity",C),i.on("tool",T)),ir(()=>{i&&(i.off("change",w),i.off("setData",S),i.off("opacity",C),i.off("enabled",y),i.off("tool",T))}),{whiteboard:i,whiteboardModuleConfig:o,whiteboardPages:s,whiteboardPageSizes:a,whiteboardPageOffsets:l,whiteboardEnabled:m,whiteboardOpacity:h,whiteboardReady:u,handleWhiteboardPageReady:g,updateWhiteboardPageSizes:R,updateWhiteboardPageOffsets:H}};It(),gn();var n9=["data-page-index"],r9={__name:"WhiteboardPage",props:{whiteboard:{type:Object,required:!0},page:{type:Object,required:!0},pageSize:{type:Object,default:null},pageOffset:{type:Object,default:null},enabled:{type:Boolean,default:!0}},setup(e){const t=e,n=ne(null),r=()=>{const u=n.value;!u||!t.page||(t.page.mount(u),t.pageSize&&t.page.resize(t.pageSize.width,t.pageSize.height))},o=u=>{if(!t.page||!u?.dataTransfer||!t.enabled||t.whiteboard.getTool()!=="select")return;u.preventDefault(),u.stopPropagation();const c=n.value;if(!c)return;const d=c.getBoundingClientRect(),h=u.clientX-d.left,m=u.clientY-d.top,p=t.pageSize?.width,g=t.pageSize?.originalWidth??p,k=Number.isFinite(p)&&Number.isFinite(g)&&g?p/g:1;i(u,h,m,k)||s(u,h,m,k)||a(u,h,m)||l(u,h,m)},i=(u,c,d,h)=>{const m=u.dataTransfer.getData("application/sticker");if(!m)return!1;const p=(t.whiteboard.getType("stickers")||[]).find(g=>g.id===m);return p?.src?(t.page.addImage({stickerId:p.id,x:c,y:d,src:p.src,width:Number.isFinite(p.width)?p.width*h:p.width,height:Number.isFinite(p.height)?p.height*h:p.height,type:"sticker"}),!0):!1},s=(u,c,d,h)=>{const m=Array.from(u.dataTransfer.files||[]).find(g=>g.type.startsWith("image/"));if(!m)return!1;const p=new FileReader;return p.onload=()=>{typeof p.result=="string"&&t.page.addImage({x:c,y:d,src:p.result,type:"image"})},p.readAsDataURL(m),!0},a=(u,c,d)=>{const h=u.dataTransfer.getData("application/comment");if(!h)return!1;const m=(t.whiteboard.getType("comments")||[]).find(p=>p.id===h);return m?.text?(t.page.addText({x:c,y:d,content:m.text}),!0):!1},l=(u,c,d)=>{const h=u.dataTransfer.getData("text/plain");return h?(t.page.addText({x:c,y:d,content:h}),!0):!1};return Pt(()=>[t.page,t.pageSize?.width,t.pageSize?.height],()=>{_t(r)}),Rn(()=>{r()}),ir(()=>{t.page?.destroy()}),(u,c)=>(me(),_e("div",{ref_key:"containerRef",ref:n,class:"whiteboard-page","data-page-index":e.page.pageIndex,onDragover:c[0]||(c[0]=Jt(()=>{},["prevent"])),onDrop:Jt(o,["prevent"]),style:vn({width:(e.pageSize?.width??e.page.size?.width)+"px",height:(e.pageSize?.height??e.page.size?.height)+"px",transform:`translate(${e.pageOffset?.left??0}px, ${e.pageOffset?.top??0}px)`})},null,44,n9))}},o9=hn(r9,[["__scopeId","data-v-c876c9b5"]]);It(),gn();var i9={__name:"WhiteboardLayer",props:{whiteboard:{type:Object,required:!0},pages:{type:Array,default:()=>[]},pageSizes:{type:Object,default:()=>({})},pageOffsets:{type:Object,default:()=>({})},enabled:{type:Boolean,default:!0},interactive:{type:Boolean,default:null},opacity:{type:Number,default:1}},setup(e){const t=e,n=Se(()=>t.interactive==null?t.enabled:t.interactive);return(r,o)=>(me(),_e("div",{class:"whiteboard-layer","aria-hidden":"true",style:vn({opacity:e.opacity,pointerEvents:n.value?"auto":"none"})},[(me(!0),_e(Wt,null,or(e.pages,i=>(me(),fn(o9,{key:i.pageIndex,page:i,"page-size":e.pageSizes?.[i.pageIndex],"page-offset":e.pageOffsets?.[i.pageIndex],whiteboard:e.whiteboard,enabled:e.enabled},null,8,["page","page-size","page-offset","whiteboard","enabled"]))),128))],4))}},s9=hn(i9,[["__scopeId","data-v-54546c3d"]]);function a9(e){const t=e?.directionContext?.inlineDirection;if(t!=null)return t;const n=e?.paragraphProperties?.rightToLeft;if(n===!0)return"rtl";if(n===!1)return"ltr"}var g_=["#1f6feb","#d1242f","#8250df","#bf3989","#1a7f37","#9a6700","#bc4c00","#0969da","#cf222e","#6639ba","#116329","#7d4e00"];const l9=e=>e?`${typeof e.name=="string"?e.name:""} ${typeof e.email=="string"?e.email:""}`:"";var c9=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0};const u9=e=>g_[c9(l9(e))%g_.length];var Jd=e=>typeof e=="string"&&e.length>0;const d9=e=>{if(!e||e.enabled===!1)return;const t=e.overrides&&typeof e.overrides=="object"?e.overrides:void 0,n=typeof e.resolve=="function"?e.resolve:void 0;return r=>{const o=r??{};if(t){if(Jd(o.email)&&Jd(t[o.email]))return t[o.email];if(Jd(o.name)&&Jd(t[o.name]))return t[o.name]}if(n)try{const i=n(o);if(Jd(i))return i}catch{}return u9(o)}},f9=["insertion","deletion","move","move-from","move-to","table-cell-insertion","table-cell-deletion","cell-merge","cell-split","image-insertion","image-deletion","image-property-change"];var hj=new Set(f9);const mr={externalImageDeferred:"render.media.external-image-deferred",missingRelationship:"render.drawing.missing-relationship",missingMediaPart:"render.media.missing-part",unsupportedRelationshipType:"render.drawing.unsupported-relationship-type",unsupportedMime:"render.media.unsupported-mime",imageTooLarge:"render.media.image-too-large",unsafeSvg:"render.media.unsafe-svg",unsupportedFormat:"render.media.unsupported-format",embeddedObjectNotSupported:"render.embedded-object-not-supported",unsupportedObject:"render.drawing.unsupported-object",vmlUnsupported:"render.drawing.vml-unsupported",vmlImageUnsupported:"render.drawing.vml-image-unsupported",unsupportedGeometryCommand:"render.drawing.unsupported-geometry-command",anchorUnsupported:"render.drawing.anchor-unsupported",wrapUnsupported:"render.drawing.wrap-unsupported",altContentNoSupportedChoice:"render.drawing.altcontent-no-supported-choice",groupChildUnsupported:"render.drawing.group-child-unsupported"},pj={"render.media.missing-relationship":mr.missingRelationship,"render.media.wrong-relationship-type":mr.unsupportedRelationshipType,"render.media.unsupported-target":mr.unsupportedRelationshipType,"render.media.invalid-image-size":mr.imageTooLarge,"render.media-resolver-unavailable":mr.missingMediaPart,"render.chart-not-supported":mr.unsupportedObject,"render.textbox.vml-unsupported":mr.vmlUnsupported},h9={inlineBitmap:{family:"inlineBitmap",support:"supported",description:"wp:inline pic:pic with internal media and browser-safe MIME (PNG/JPEG; WebP/SVG once the host media resolver lands).",contract:"ImageRun"},anchoredBitmap:{family:"anchoredBitmap",support:"supported",description:"wp:anchor bitmap with anchor/wrap expressible by ImageAnchor/ImageWrap. Never silently inlined.",contract:"ImageBlock"},imageChildInGroup:{family:"imageChildInGroup",support:"supported",description:"Bitmap child of a supported DrawingML group/drawing wrapper. Supported only when the parent is.",contract:"ImageDrawing"},vectorShape:{family:"vectorShape",support:"supported",description:"Block/floating DrawingML preset/custom shape with the supported geometry/style subset.",contract:"DrawingBlock",drawingKind:"vectorShape"},shapeGroup:{family:"shapeGroup",support:"supported",description:"DrawingML group whose rendered children are supported vector/image children.",contract:"DrawingBlock",drawingKind:"shapeGroup"},chart:{family:"chart",support:"supported",description:"DrawingML chart projected into a ChartDrawing with parsed cached chart XML data. Complete Word chart fidelity remains deferred to chartFidelity.",contract:"DrawingBlock",drawingKind:"chart"},alternateContent:{family:"alternateContent",support:"supported",description:"mc:AlternateContent traversal/select policy. Selected Choice/Fallback maps to its family contract; unselected branches preserved for save/reopen.",contract:"selected-choice"},externalImage:{family:"externalImage",support:"fail-closed",description:'External image relationship (r:link / TargetMode="External"). Not fetched.',contract:"none",diagnostic:mr.externalImageDeferred},missingRelationship:{family:"missingRelationship",support:"fail-closed",description:"Drawing references a relationship id absent from the owner part .rels.",contract:"none",diagnostic:mr.missingRelationship},missingMediaPart:{family:"missingMediaPart",support:"fail-closed",description:"Relationship resolves but the target media part bytes are missing or empty.",contract:"none",diagnostic:mr.missingMediaPart},wrongRelationshipType:{family:"wrongRelationshipType",support:"fail-closed",description:"Relationship exists but is not an image relationship type.",contract:"none",diagnostic:mr.unsupportedRelationshipType},unsupportedMime:{family:"unsupportedMime",support:"fail-closed",description:"Media MIME outside the supported allowlist (incl. GIF/BMP/ICO).",contract:"none",diagnostic:mr.unsupportedMime},oversizedMediaPart:{family:"oversizedMediaPart",support:"fail-closed",description:"Media part exceeds the host byte-size policy before bytes are materialized.",contract:"none",diagnostic:mr.imageTooLarge},unsafeSvg:{family:"unsafeSvg",support:"fail-closed",description:"SVG content rejected by the SVG safety policy.",contract:"none",diagnostic:mr.unsafeSvg},metafileOrTiff:{family:"metafileOrTiff",support:"fail-closed",description:"EMF/WMF/TIFF and other non-browser-native formats with no approved conversion path.",contract:"none",diagnostic:mr.unsupportedFormat},embeddedObject:{family:"embeddedObject",support:"fail-closed",description:"OLE / ActiveX / embedded package object.",contract:"none",diagnostic:mr.embeddedObjectNotSupported},smartArtOrDiagram:{family:"smartArtOrDiagram",support:"fail-closed",description:"SmartArt / diagram / unknown external graphic-data object.",contract:"none",diagnostic:mr.unsupportedObject},vml:{family:"vml",support:"fail-closed",description:"VML structure outside any supported image-like subset (default fail-closed policy).",contract:"none",diagnostic:mr.vmlUnsupported},vmlImageLike:{family:"vmlImageLike",support:"fail-closed",description:"Simple VML image references (v:imagedata) / watermark image metadata. Fail-closed unless a later change promotes a named subset with deterministic fixtures and exact oracles.",contract:"none",diagnostic:mr.vmlImageUnsupported},unsupportedGeometryCommand:{family:"unsupportedGeometryCommand",support:"fail-closed",description:"Custom geometry command the extractor does not implement, e.g. arcTo.",contract:"none",diagnostic:mr.unsupportedGeometryCommand},unsupportedAnchorFields:{family:"unsupportedAnchorFields",support:"fail-closed",description:"Anchor fields required for honest placement are unsupported (char-relative, alignment modes, etc.).",contract:"none",diagnostic:mr.anchorUnsupported},unsupportedWrapFields:{family:"unsupportedWrapFields",support:"fail-closed",description:"Wrap fields required for honest placement are unsupported (arbitrary wrap polygons, etc.).",contract:"none",diagnostic:mr.wrapUnsupported},alternateContentNoSupportedChoice:{family:"alternateContentNoSupportedChoice",support:"fail-closed",description:"mc:AlternateContent with no supported choice and no usable fallback.",contract:"none",diagnostic:mr.altContentNoSupportedChoice},groupChildUnsupported:{family:"groupChildUnsupported",support:"fail-closed",description:"Unsupported child inside an otherwise-supported group. Supported siblings are not dropped.",contract:"none",diagnostic:mr.groupChildUnsupported},objectEditing:{family:"objectEditing",support:"deferred",description:"Editing/mutation of anchored/vector objects.",contract:"none"},customWrapPolygon:{family:"customWrapPolygon",support:"deferred",description:"Full Word-compatible text wrapping for arbitrary custom wrap polygons.",contract:"none"},chartFidelity:{family:"chartFidelity",support:"deferred",description:"Complete chart fidelity (a dedicated chart effort owns the parsed subset).",contract:"none"},vmlFidelity:{family:"vmlFidelity",support:"deferred",description:"Complete VML fidelity.",contract:"none"},decorativeAccessibilityUi:{family:"decorativeAccessibilityUi",support:"deferred",description:"Full accessibility UI for decorative image semantics beyond preserving source data.",contract:"none"}},mj=Object.keys(h9),gj=Object.freeze(["multiple-sections","furniture-page-tokens","non-balanceable-multi-column-sections","body-anchored-objects","footnotes","page-references","keep-constraints","tables","furniture-anchored-objects"]);It(),gn();var p9={class:"superdoc-html-viewer"},m9={class:"superdoc-html-viewer__document"},g9=["innerHTML"],v9={__name:"HtmlViewer",props:{fileSource:{type:[File,Blob],required:!0},documentId:{type:String,required:!0}},emits:["ready","selection-change"],setup(e,{emit:t}){const n=e,r=ne(""),o=t,i=()=>{const l=window.getSelection();console.debug("selection from html viewer",l),o("selection-change",l)},s=l=>new Promise((u,c)=>{const d=new FileReader;d.onload=h=>{const m=h.target.result;u(m)},d.onerror=h=>c(h),d.readAsText(l)}),a=async()=>{try{r.value=await s(n.fileSource),o("ready",n.documentId)}catch(l){o("error",l),console.error("Error loading document",l)}};return Rn(()=>{a()}),(l,u)=>(me(),_e("div",p9,[Le("div",m9,[Le("div",{class:"superdoc-html-viewer__content",innerHTML:r.value,onMouseup:i},null,40,g9)])]))}},y9=hn(v9,[["__scopeId","data-v-da3494ba"]]);const b9=(e,t,n=()=>!0)=>{const r=new Set(t.map(String)),o=new Set;e.forEach(s=>{if(!n(s))return;const a=s.commentId!=null?String(s.commentId):null,l=s.importedId!=null?String(s.importedId):null;!(a&&r.has(a))&&!(l&&r.has(l))||(a&&o.add(a),l&&o.add(l))});let i=!0;for(;i;)i=!1,e.forEach(s=>{if(!n(s))return;const a=s.commentId!=null?String(s.commentId):null,l=s.importedId!=null?String(s.importedId):null,u=s.parentCommentId!=null?String(s.parentCommentId):null,c=pp(s),d=c!=null?String(c):null,h=a&&o.has(a)||l&&o.has(l),m=u&&o.has(u)||d&&o.has(d);if(!h&&!m)return;const p=o.size;a&&o.add(a),l&&o.add(l),o.size>p&&(i=!0)});return o};It();var v_=ne(!1);function zi(){return{isHighContrastMode:v_,setHighContrastMode:t=>{v_.value=t}}}const vj="[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor",yj=320,bj=24,wj=816,Cj=250,_j="sidebar",y_=new Set(["auto","sidebar","inline"]);function w9(e){if(!e||e===!1||typeof e!="object")return e;const t={...e},n=t.displayMode;y_.has(n)||delete t.displayMode;const r=t.compactBreakpointPx;typeof r=="number"&&Number.isFinite(r)&&r>=0||delete t.compactBreakpointPx;const o=t.compactMeasurementSelector;return typeof o=="string"&&o.trim().length>0?t.compactMeasurementSelector=o.trim():delete t.compactMeasurementSelector,t}It();var C9=".superdoc__document",_9=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,S9=e=>e+320+24;function k9({commentsModuleConfig:e,superdocRoot:t,layers:n}){const r=ne(0),o=ne(!1);let i=null,s=null;const a=m=>{if(!(m instanceof HTMLElement)||(typeof window<"u"?window.getComputedStyle(m):null)?.display==="contents")return!1;const p=Number(m.clientWidth??0),g=Number(m.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0||Number.isFinite(g)&&g>0},l=()=>{const m=t.value,p=e.value?.compactMeasurementSelector;if(typeof p=="string"&&p.trim().length>0&&typeof document<"u"){const k=document.querySelector(p.trim());if(a(k))return k}let g=m?.parentElement??null;for(;g;){if(a(g))return g;g=g.parentElement}return a(m)||m instanceof HTMLElement?m:null},u=()=>{const m=typeof window<"u"?window.ResizeObserver:void 0;if(typeof m>"u")return;const p=l();p!==s&&(i&&(i.disconnect(),i=null),s=p,s&&(i=new m(()=>{h()}),i.observe(s)))},c=()=>{u();const m=Number(s?.clientWidth??0);if(Number.isFinite(m)&&m>0)return m;const p=Number(s?.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0?p:0},d=()=>{const m=t.value?.querySelector?.(C9),p=n.value,g=Number(m?.clientWidth??m?.getBoundingClientRect?.().width??0);if(Number.isFinite(g)&&g>0)return g;const k=Number(p?.clientWidth??p?.getBoundingClientRect?.().width??0);return Number.isFinite(k)&&k>0?k:816},h=()=>{const m=c(),p=e.value,g=p?.displayMode??"sidebar";if(g==="sidebar"){r.value=m,o.value=!1;return}if(g==="inline"){r.value=m,o.value=!0;return}if(!(Number.isFinite(m)&&m>0))return;r.value=m;const k=p?.compactBreakpointPx;if(_9(k)){o.value=m<k;return}o.value=m<S9(d())};return ir(()=>{i&&(i.disconnect(),i=null),s=null}),{superdocContainerWidth:r,isCompactCommentsMode:o,recalculateCompactCommentsMode:h,ensureCompactMeasurementObserver:u}}It();var b_=320,Ya=12,A9=220,I9=16,E9=500,w_=".superdoc-comment-highlight[data-comment-ids]",C_="data-comment-ids",x9=".sd-comment-anchor",Xy=(e,t,n)=>Math.min(Math.max(e,t),n),vs=e=>Number(e),Hi=e=>Number.isFinite(e),Qy=e=>e?.commentId??e?.importedId??null,__=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),T9=e=>{const t=e?.value;if(!t)return null;const n=vs(t.ts);if(!Hi(n)||Date.now()-n>E9)return null;const r=vs(t.x),o=vs(t.anchorRect?.bottom),i=Hi(o)?o:vs(t.y);return!Hi(r)||!Hi(i)?null:{x:r,y:i}},R9=({rootEl:e,comment:t,pendingComment:n})=>{if(n?.value&&t?.commentId===n.value?.commentId){const a=e.querySelectorAll(w_);for(const l of a)if(__(l.getAttribute(C_)).includes("pending")&&typeof l.getBoundingClientRect=="function")return l.getBoundingClientRect()}const r=Qy(t);if(!r)return null;const o=String(r),i=e.querySelectorAll(w_);for(const a of i)if(__(a.getAttribute(C_)).includes(o)&&typeof a.getBoundingClientRect=="function")return a.getBoundingClientRect();const s=e.querySelector(`[data-track-change-id="${o}"]`);return s&&typeof s.getBoundingClientRect=="function"?s.getBoundingClientRect():null},M9=(e,t)=>{const{entry:n}=e(Qy(t)),r=vs(n?.bounds?.bottom);return Hi(r)?r:vs(n?.bounds?.top)},L9=({selectionPosition:e,comment:t,pendingComment:n})=>e.value?.source==="pdf"||t?.selection?.source==="pdf"||n.value?.selection?.source==="pdf",D9=({rootEl:e,layersRect:t,comment:n})=>{const r=Qy(n);if(r==null)return NaN;const o=e.querySelector(`${x9}[data-id="${String(r)}"]`);return!o||typeof o.getBoundingClientRect!="function"?NaN:vs(o.getBoundingClientRect().bottom)-vs(t.top)},P9=({comment:e,pendingComment:t,selectionPosition:n,activeZoom:r})=>{if(!t.value||e?.commentId!==t.value?.commentId)return NaN;const o=vs(n.value?.bottom);if(Hi(o))return o*(n.value?.source==="pdf"?(r.value??100)/100:1);const i=vs(n.value?.top);return Hi(i)?i*(n.value?.source==="pdf"?(r.value??100)/100:1):NaN},O9=({top:e,left:t})=>({top:`${Math.round(e)}px`,left:`${Math.round(t)}px`,right:"auto"}),F9=({rootRect:e,layersRect:t,anchorBottom:n,anchorClientX:r=NaN})=>{const o=Xy(t.top-e.top+n+I9,Ya,Math.max(Ya,e.height-A9)),i=Math.max(Ya,e.width-b_-Ya);let s;if(Hi(r))s=Xy(r-e.left+Ya,Ya,i);else{const a=e.width-(t.left-e.left+t.width)+Ya;s=Xy(e.width-a-b_,Ya,i)}return{top:o,left:s}};function B9({activeComment:e,pendingComment:t,activeCompactComment:n,showCommentsSidebar:r,selectionPosition:o,activeZoom:i,superdocRoot:s,layers:a,documents:l,resolveCommentPositionEntry:u,clearActiveComment:c,clearPendingComment:d}){const h={top:"12px",right:"12px"},m=ne(0),p=ne({x:null,y:null,ts:0,anchorRect:null});let g=null,k=null;const w=()=>{p.value={x:null,y:null,ts:0,anchorRect:null}},S=(R,M,H)=>{if(!l.value?.some(z=>z.type==="application/pdf"))return!1;const B=R.querySelector(".superdoc__compact-comment-popover");return!n.value||!B||B.contains(M)||H?!1:(t.value&&d(),c(),w(),!0)},y=R=>{const M=s.value;if(!M||!a.value?.contains(R.target))return;const H=(typeof document.elementsFromPoint=="function"?document.elementsFromPoint(R.clientX,R.clientY):[]).find(z=>z?.nodeType===1&&M.contains(z)&&z.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"))?.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor")??(R.target?.nodeType===1?R.target.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"):null);if(S(M,R.target,H)||R.button!==0||R.pointerType!=="mouse")return;const B=H&&typeof H.getBoundingClientRect=="function"?H.getBoundingClientRect():null;B&&(p.value={x:R.clientX,y:B.bottom,ts:Date.now(),anchorRect:{left:B.left,right:B.right,top:B.top,bottom:B.bottom}})},C=Se(()=>{m.value;const R=n.value;if(!R)return h;const M=s.value,H=a.value;if(!M||!H)return h;const B=M.getBoundingClientRect(),z=H.getBoundingClientRect(),Z=T9(p),P=Z?null:R9({rootEl:M,comment:R,pendingComment:t});let N=NaN,I=NaN;return Z?(N=Z.y-z.top,I=Z.x):P?(N=P.bottom-z.top,I=P.left):N=M9(u,R),!Hi(N)&&L9({selectionPosition:o,comment:R,pendingComment:t})&&(N=D9({rootEl:M,layersRect:z,comment:R})),Hi(N)||(N=P9({comment:R,pendingComment:t,selectionPosition:o,activeZoom:i})),Hi(N)?O9(F9({rootRect:B,layersRect:z,anchorBottom:N,anchorClientX:I})):h});return Pt([e,t,o,i,r,p],()=>{const R=typeof window<"u"?window.requestAnimationFrame:null,M=typeof window<"u"?window.cancelAnimationFrame:null;g!=null&&M?.(g),R&&(g=R(()=>{m.value+=1,g=null}))},{deep:!1}),Pt(n,(R,M)=>{if(!M&&R){const H=document.activeElement;H instanceof HTMLElement&&(k=H)}},{deep:!1}),Pt(t,(R,M)=>{!M&&R&&w()}),Rn(()=>{document.addEventListener("pointerdown",y,!0)}),ir(()=>{document.removeEventListener("pointerdown",y,!0);const R=typeof window<"u"?window.cancelAnimationFrame:null;g!=null&&(R?.(g),g=null),k=null}),{compactCommentPopoverStyle:C,closeCompactCommentPopover:()=>{n.value&&(t.value&&d(),c(),k&&typeof k.focus=="function"&&k.focus(),k=null)},resetClickAnchor:w}}function S_(e){if(e?.type!=="mutation:committed")return null;const t=e.origin==="history"?e.result:e.receipt;if(!t||typeof t!="object")return null;const n=new Set,r=new Set,o=(i,s)=>{i?.kind!=="entity"||i.entityType!=="trackedChange"||typeof i.entityId=="string"&&i.entityId.length>0&&s.add(i.entityId)};if(Array.isArray(t.inserted)&&t.inserted.forEach(i=>o(i,n)),Array.isArray(t.updated)&&t.updated.forEach(i=>o(i,n)),Array.isArray(t.trackedChangeRefs)&&t.trackedChangeRefs.forEach(i=>o(i,n)),Array.isArray(t.removed)&&t.removed.forEach(i=>o(i,r)),Array.isArray(t.invalidatedRefs)&&t.invalidatedRefs.forEach(i=>o(i,r)),Array.isArray(t.remappedRefs))for(const i of t.remappedRefs)o(i?.from,r),o(i?.to,n);for(const i of r)n.delete(i);return n.size===0&&r.size===0?null:{upsertIds:n,removedIds:r,reconcileMode:e.origin==="history"?"authoritative":"targeted"}}var $d=e=>new Set(Array.from(e??[]).filter(t=>typeof t=="string"&&t.length>0)),N9=e=>typeof e?.id=="string"&&e.id.length>0?e.id:typeof e?.changeId=="string"&&e.changeId.length>0?e.changeId:typeof e?.address?.entityId=="string"&&e.address.entityId.length>0?e.address.entityId:null,z9=(e,t)=>e?.adapter===t?.adapter&&e?.documentId===t?.documentId&&e?.editor===t?.editor&&e?.reconcileToken===t?.reconcileToken;function k_({getContext:e,reconcile:t,hydrate:n,onReconciled:r}){const o=new Map;let i=0,s=0,a=null,l=!1;const u=(R,M)=>s===R&&z9(M,e()),c=(R,M)=>{const H=new Set;for(const B of R)o.get(B)===M.get(B)&&(o.delete(B),H.add(B));return H},d=R=>new Map([...o].filter(([,M])=>M.ready===!0&&M.reconcileMode===R)),h=()=>{let R=!1;for(const M of o.values())M.gate!=="render"||M.ready||(M.ready=!0,R=!0);return R},m=R=>{let M=!1;for(const H of o.values())H.version>R||H.ready||(H.ready=!0,M=!0);return M},p=async(R,M,H,B=!1)=>{if(!(!B&&M.size===0||typeof r!="function"))try{await r(R,M,H)}catch{}},g=R=>$d(R?.resolvedIds??(R?.items??[]).map(N9).filter(Boolean)),k=async(R,M,H)=>{const B=await t(R,{upsertIds:new Set(M.keys()),removedIds:new Set,reconcileMode:"targeted"});if(!u(H,R)||(await p(R,c(g(B),M),B),new Set([...M].filter(([Z,P])=>o.get(Z)===P).map(([Z])=>Z)).size===0))return;const z=await n(R,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1});u(H,R)&&await p(R,c(g(z),M),z)},w=async(R,M,H)=>{const B=await n(R,{trackedChangesListMode:"all",refreshReason:"mutation-history-render-reconcile",blocking:!0});if(!u(H,R)||![...M].some(([I,L])=>o.get(I)===L))return;const z=B?.ok===!0,Z=z&&B?.complete===!0&&B?.sourceCoverageComplete===!0,P=z?g(B):new Set,N=Z?c(new Set(M.keys()),M):new Set;await p(R,Z?N:P,{...B,reconcileMode:"authoritative"},!0)},S=()=>{if(a)return a;const R=d("targeted"),M=d("authoritative");if(R.size===0&&M.size===0)return null;const H=e();if(!H?.adapter)return null;l=!1;const B=s;return a=Promise.resolve().then(async()=>{M.size>0&&await w(H,M,B).catch(()=>{}),R.size>0&&await k(H,R,B).catch(()=>{})}).catch(()=>{}).finally(()=>{a=null,l&&S()}),a},y=(R,M)=>{if(!R)return;const H=R.reconcileMode==="authoritative"?"authoritative":"targeted",B=$d(R.removedIds);for(const Z of B){const P=o.get(Z);P?.reconcileMode==="authoritative"?o.set(Z,{...P,version:++i,gate:M,ready:!1}):o.delete(Z)}const z=e();if(B.size>0&&z?.adapter)try{Promise.resolve(t(z,{upsertIds:new Set,removedIds:B})).catch(()=>{})}catch{}for(const Z of $d(R.upsertIds))if(!B.has(Z)){const P=o.get(Z);o.set(Z,{version:++i,gate:M,ready:!1,reconcileMode:H==="authoritative"||P?.reconcileMode==="authoritative"?"authoritative":"targeted"})}},C=R=>y(R,"render");return{enqueue:C,enqueueAfterPaint(R,M){if(!R||typeof M!="function"){C(R);return}y(R,"exact-paint");const H=e();if(!H?.adapter)return;const B=s,z=i,Z=new Set([...$d(R.upsertIds),...$d(R.removedIds)]),P=new Map([...Z].flatMap(N=>{const I=o.get(N);return I?[[N,I]]:[]}));Promise.resolve().then(()=>M()).then(()=>{if(!u(B,H))return;let N=h();m(z)&&(N=!0);for(const[I,L]of P)o.get(I)===L&&(L.ready||(N=!0),L.ready=!0);a&&(N||z>0)&&(l=!0),S()}).catch(()=>{if(u(B,H))for(const[N,I]of P)o.get(N)===I&&(I.gate="render")})},onRender:(R=!1)=>{const M=h();a&&(M||R)&&(l=!0),S()},reset(){s+=1,o.clear(),l=!1},getPendingIds(){return new Set(o.keys())}}}function H9(e,t){if(!e||typeof e.entityId!="string"||e.entityType!=="comment"&&e.entityType!=="trackedChange")return null;const n=typeof t=="function"?t(e.entityId):null,r=n?.commentId??n?.importedId??e.entityId;return r!=null?String(r):null}var U9=new Set(["insert-text","replace-text","plain-text-paste","delete-backward","delete-forward","text.insert","text.replace","text.pastePlain","text.deleteBackward","text.deleteForward","structural.enter","structural:enter-split-paragraph","structural:enter-insert-paragraph-before","structural:enter-insert-paragraph-after","structural:shift-enter-line-break","structural:backspace-boundary-merge-with-previous","structural:delete-boundary-merge-with-next","backspace:boundary-merge-with-previous","backspace:list-remove","backspace:list-outdent"]);const A_=e=>e?.type!=="mutation:committed"||e.origin!=="command"?!1:U9.has(e.editableCommandKind);function I_(e){return e==null?null:String(e)}function V9({hydrate:e,getActiveDocumentId:t,debounceMs:n=250,ceilingMs:r=1e3,now:o=()=>Date.now(),setTimer:i=(a,l)=>setTimeout(a,l),clearTimer:s=a=>clearTimeout(a)}){let a=null,l=null,u=null;const c=m=>I_(t())===m,d=()=>{a!=null&&s(a),a=null,l=null,u=null};return{schedule:m=>{const p=I_(m);if(!c(p))return!1;u!==p&&d();const g=o();u=p,l??=g,a!=null&&s(a);const k=Math.max(0,r-(g-l));return a=i(()=>{const w=u;a=null,l=null,u=null,c(w)&&e()},Math.min(n,k)),!0},clear:d}}var j9="no-author-configured";const G9="author-required",E_="This edit needs an author identity. Set `user.name` in your SuperDoc configuration and reopen the document to make tracked or revision-overlapping edits.";function x_(e){return typeof e=="string"&&e.includes(j9)}function W9(e){if(!e||e.type!=="mutation:rejected")return!1;if(e.failureSource==="receipt"){const t=e.failure;return t?t.code==="PRECONDITION_FAILED"&&x_(t.message):!1}return e.failureSource==="shell"?e.reason==="author-required"?!0:e.reason==="PRECONDITION_FAILED"&&x_(e.message):!1}function K9(){const e=new Set,t=n=>typeof n=="string"&&n.length>0?n:"__default__";return{shouldNotify(n,r){if(!W9(r))return!1;const o=t(n);return e.has(o)?!1:(e.add(o),!0)},clear(n){e.delete(t(n))}}}const q9=e=>!!(e?.anchor&&e?.focus&&(e.anchor.blockId!==e.focus.blockId||e.anchor.blockOffset!==e.focus.blockOffset)),Y9=(e,t)=>{if(!e||e.rangeCount<1||e.isCollapsed||!t)return!1;const n=e.getRangeAt(0);return!t.contains(n.startContainer)&&!t.contains(n.endContainer)},X9=(e,t)=>e!=="editing"&&e!=="suggesting"?!1:q9(t);var Q9=br((()=>{})),Z9=Gu({default:()=>z_},1),T_,R_,M_,L_,D_,P_,O_,F_,B_,N_,z_,J9=br((()=>{It(),Q9(),gn(),T_=["onKeydown"],R_=["id"],M_={class:"sd-password-prompt__description"},L_={class:"sd-password-prompt__field"},D_=["placeholder","disabled","aria-label"],P_={key:0,class:"sd-password-prompt__error",role:"alert"},O_={class:"sd-password-prompt__actions"},F_=["disabled"],B_=["disabled"],N_={__name:"PasswordPromptSurface",props:{surfaceId:{type:String,default:""},mode:{type:String,default:"dialog"},request:{type:Object,default:()=>({})},resolve:{type:Function,default:()=>{}},close:{type:Function,default:()=>{}},passwordPrompt:{type:Object,required:!0}},setup(e){const t=e,n=ne(""),r=ne(!1),o=ne(t.passwordPrompt.errorCode==="DOCX_PASSWORD_INVALID"),i=ne(o.value?t.passwordPrompt.texts.invalidMessage:""),s=Se(()=>o.value?t.passwordPrompt.texts.invalidTitle:t.passwordPrompt.texts.title),a=Se(()=>n.value.length>0&&!r.value);async function l(){if(!a.value)return;r.value=!0,i.value="";const c=await t.passwordPrompt.attemptPassword(n.value);if(c.success){t.resolve({password:n.value});return}r.value=!1,n.value="",c.errorCode==="DOCX_PASSWORD_INVALID"?(o.value=!0,i.value=t.passwordPrompt.texts.invalidMessage):c.errorCode==="timeout"?i.value=t.passwordPrompt.texts.timeoutMessage:i.value=t.passwordPrompt.texts.genericErrorMessage}function u(){t.close("user-cancelled")}return(c,d)=>(me(),_e("div",{class:"sd-password-prompt",onKeydown:Yo(Jt(l,["prevent"]),["enter"])},[Le("h3",{id:`sd-password-prompt-heading-${e.surfaceId}`,class:"sd-password-prompt__heading"},Ht(s.value),9,R_),Le("p",M_,Ht(e.passwordPrompt.texts.description),1),Le("div",L_,[Ws(Le("input",{"onUpdate:modelValue":d[0]||(d[0]=h=>n.value=h),type:"password",class:"sd-password-prompt__input",placeholder:e.passwordPrompt.texts.placeholder,disabled:r.value,autocomplete:"current-password","aria-label":e.passwordPrompt.texts.inputAriaLabel},null,8,D_),[[ki,n.value]])]),i.value?(me(),_e("p",P_,Ht(i.value),1)):ut("",!0),Le("div",O_,[Le("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--cancel",disabled:r.value,onClick:u},Ht(e.passwordPrompt.texts.cancelLabel),9,F_),Le("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--submit",disabled:!a.value,onClick:l},Ht(r.value?e.passwordPrompt.texts.busyLabel:e.passwordPrompt.texts.submitLabel),9,B_)])],40,T_))}},z_=hn(N_,[["__scopeId","data-v-ecf7f6fb"]])}));It();var $9=["DOCX_PASSWORD_REQUIRED","DOCX_PASSWORD_INVALID"],eM=3e4,Ai={title:"Password Required",invalidTitle:"Incorrect Password",description:"This document is password protected. Enter the password to open it.",placeholder:"Enter password",inputAriaLabel:"Document password",submitLabel:"Open",cancelLabel:"Cancel",busyLabel:"Decrypting…",invalidMessage:"Incorrect password. Please try again.",timeoutMessage:"Timed out while decrypting. Please try again.",genericErrorMessage:"Unable to decrypt this document."};function tM({getSurfaceManager:e,getPasswordPromptConfig:t,onUnhandled:n}){const r=[],o=Ur(null),i=new Map;let s=!1;function a(p,g,k){if(!p||!$9.includes(g)||t()===!1||!e())return!1;const w=i.get(p.id);if(w)return clearTimeout(w.timer),w.resolve({success:!1,errorCode:g}),i.delete(p.id),!0;const S=r.find(y=>y.doc.id===p.id);return S?(S.errorCode=g,S.originalException=k,!0):(o.value?.doc.id===p.id||(r.push({doc:p,errorCode:g,originalException:k}),c()),!0)}function l(p){if(!p)return;const g=i.get(p.id);g&&(clearTimeout(g.timer),g.resolve({success:!0}),i.delete(p.id))}function u(){s=!0;for(const[,p]of i)clearTimeout(p.timer),p.resolve({success:!1,errorCode:"destroyed"});i.clear(),r.length=0,o.value=null}function c(){if(s||o.value||r.length===0)return;const p=r.shift();p&&d(p).catch(g=>{o.value=null,console.error("[SuperDoc] Password prompt error:",g),n?.(p.doc,p.errorCode,p.originalException),c()})}async function d({doc:p,errorCode:g,originalException:k}){const w=e();if(!w||s)return;const S=h(),y=M=>(p.password=M,p.editorMountNonce++,new Promise(H=>{const B=setTimeout(()=>{i.delete(p.id),H({success:!1,errorCode:"timeout"})},eM);i.set(p.id,{resolve:H,timer:B})})),C={documentId:p.id,errorCode:g,texts:S.texts,attemptPassword:y},T=m(S,{documentId:p.id,errorCode:g,texts:S.texts});if(T.suppressed){n?.(p,g,k),c();return}o.value={doc:p,surfaceHandle:null};let R;if(T.component)R=w.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:S.texts.title,component:Hr(T.component),props:{...T.props,passwordPrompt:C}});else if(T.render){const M=T.render;R=w.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:S.texts.title,render:H=>M({container:H.container,passwordPrompt:C,resolve:H.resolve,close:H.close,surfaceId:H.surfaceId,mode:H.mode})})}else{const M=(await Promise.resolve().then(()=>(J9(),Z9))).default,H=`password-prompt-${p.id}`;R=w.open({id:H,mode:"dialog",closeOnBackdrop:!1,ariaLabelledBy:`sd-password-prompt-heading-${H}`,component:Hr(M),props:{passwordPrompt:C}})}o.value={doc:p,surfaceHandle:R},await R.result,o.value=null,c()}function h(){const p=t();if(p===!1)return{enabled:!1,texts:Ai};const g=typeof p=="object"&&p!==null?p:{};if(g.component!=null&&typeof g.render=="function")throw new Error('modules.surfaces.passwordPrompt cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{title:g.title??Ai.title,invalidTitle:g.invalidTitle??Ai.invalidTitle,description:g.description??Ai.description,placeholder:g.placeholder??Ai.placeholder,inputAriaLabel:g.inputAriaLabel??Ai.inputAriaLabel,submitLabel:g.submitLabel??Ai.submitLabel,cancelLabel:g.cancelLabel??Ai.cancelLabel,busyLabel:g.busyLabel??Ai.busyLabel,invalidMessage:g.invalidMessage??Ai.invalidMessage,timeoutMessage:g.timeoutMessage??Ai.timeoutMessage,genericErrorMessage:g.genericErrorMessage??Ai.genericErrorMessage},component:g.component,props:g.props,render:g.render,resolver:g.resolver}}function m(p,g){if(typeof p.resolver=="function"){const k=p.resolver(g);if(k!=null&&k.type!=="default"){if(k.type==="none")return{suppressed:!0};if(k.type==="custom")return{component:k.component,props:k.props};if(k.type==="external")return{render:k.render}}}return p.component!=null?{component:p.component,props:p.props}:typeof p.render=="function"?{render:p.render}:{builtin:!0}}return{handleEncryptionError:a,handleEditorReady:l,destroy:u}}function H_(e,{getCurrentSession:t,applySlice:n,onSettled:r}){return()=>{if(e===t())try{n(e.getSnapshot())}catch{}r()}}var nM=br((()=>{})),rM=Gu({default:()=>cS},1),U_,V_,j_,G_,W_,K_,q_,Y_,X_,Q_,Z_,J_,$_,eS,tS,nS,rS,oS,iS,sS,aS,lS,cS,oM=br((()=>{It(),nM(),gn(),U_=["onKeydown"],V_={class:"sd-find-replace__row"},j_=["title","aria-label","aria-expanded"],G_=["value","placeholder","aria-label"],W_={key:0,class:"sd-find-replace__count"},K_=["title","aria-label","aria-pressed"],q_=["title","aria-label","aria-pressed"],Y_=["title","aria-label","aria-pressed"],X_={class:"sd-find-replace__nav"},Q_=["disabled","title","aria-label"],Z_=["disabled","title","aria-label"],J_=["title","aria-label"],$_={key:0,class:"sd-find-replace__row"},eS={class:"sd-find-replace__field"},tS=["value","placeholder","aria-label"],nS={class:"sd-find-replace__nav sd-find-replace__nav--actions"},rS=["disabled","title"],oS=["disabled","title"],iS={key:1,class:"sd-find-replace__error",role:"alert"},sS={key:0,class:"sd-find-replace__row-indent","aria-hidden":"true"},aS={class:"sd-find-replace__error-text"},lS={__name:"FindReplaceSurface",props:{surfaceId:{type:String,default:""},mode:{type:String,default:"floating"},request:{type:Object,default:()=>({})},resolve:{type:Function,default:()=>{}},close:{type:Function,default:()=>{}},findReplace:{type:Object,required:!0}},setup(e){const t=e,n=ne(null),r=Se(()=>{const p=t.findReplace;return!!(!p.hasMatches?.value||p.replacePending?.value===!0||p.canReplace&&p.canReplace.value===!1)}),o=Se(()=>t.findReplace.ignoreDiacriticsSupported?.value!==!1),i=Se(()=>t.findReplace.replaceEnabled&&t.findReplace.replaceCanMutate?.value!==!1),s=Se(()=>t.findReplace.regexSupported?.value===!0),a=Se(()=>t.findReplace.searchError?.value??null);function l(p){p.key==="Enter"&&!p.shiftKey?(p.preventDefault(),u()):p.key==="Enter"&&p.shiftKey&&(p.preventDefault(),c())}function u(){t.findReplace.goNext(),m()}function c(){t.findReplace.goPrev(),m()}function d(){t.findReplace.close("user-closed")}function h(p){const g=[];let k=p?.parentElement??null;for(;k;){const S=k.ownerDocument?.defaultView?.getComputedStyle?.(k);if(S){const y=`${S.overflowY} ${S.overflowX}`;(y.includes("auto")||y.includes("scroll"))&&g.push(k)}k=k.parentElement}const w=p?.ownerDocument?.scrollingElement;return w&&!g.includes(w)&&g.push(w),g}function m(){const p=n.value;if(!p)return;const g=h(p).map(k=>({el:k,top:k.scrollTop,left:k.scrollLeft}));p.focus({preventScroll:!0});for(const{el:k,top:w,left:S}of g)k.scrollTop!==w&&(k.scrollTop=w),k.scrollLeft!==S&&(k.scrollLeft=S)}return Rn(()=>{n.value?.focus(),t.findReplace.registerFocusFn(m)}),(p,g)=>(me(),_e("div",{class:"sd-find-replace",onKeydown:Yo(Jt(d,["stop"]),["esc"])},[Le("div",V_,[i.value?(me(),_e("button",{key:0,type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--expander",{"sd-find-replace__btn--expander-open":e.findReplace.showReplace.value}]),title:e.findReplace.texts.toggleReplaceLabel,"aria-label":e.findReplace.texts.toggleReplaceAriaLabel,"aria-expanded":e.findReplace.showReplace.value?"true":"false",onClick:g[0]||(g[0]=k=>e.findReplace.showReplace.value=!e.findReplace.showReplace.value)},[...g[14]||(g[14]=[Le("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true"},[Le("path",{d:"M6 3.5 10.5 8 6 12.5",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"})],-1)])],10,j_)):ut("",!0),Le("div",{class:en(["sd-find-replace__field",{"sd-find-replace__field--error":a.value}])},[g[15]||(g[15]=Le("svg",{class:"sd-find-replace__search-icon",viewBox:"0 0 16 16",width:"15",height:"15","aria-hidden":"true"},[Le("path",{d:"M7 1a6 6 0 1 0 3.7 10.7l3.3 3.3 1-1-3.3-3.3A6 6 0 0 0 7 1Zm0 1.5a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Z",fill:"currentColor"})],-1)),Le("input",{ref_key:"findInputRef",ref:n,value:e.findReplace.findQuery.value,onInput:g[1]||(g[1]=k=>e.findReplace.findQuery.value=k.target.value),type:"text",class:"sd-find-replace__input sd-find-replace__input--search","data-sd-autofocus":"",placeholder:e.findReplace.texts.findPlaceholder,"aria-label":e.findReplace.texts.findAriaLabel,onKeydown:l},null,40,G_),e.findReplace.findQuery.value&&!a.value?(me(),_e("span",W_,Ht(e.findReplace.matchLabel.value),1)):ut("",!0),Le("button",{type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--toggle",{"sd-find-replace__btn--active":e.findReplace.caseSensitive.value}]),title:e.findReplace.texts.matchCaseAriaLabel,"aria-label":e.findReplace.texts.matchCaseAriaLabel,"aria-pressed":e.findReplace.caseSensitive.value?"true":"false",onMousedown:g[2]||(g[2]=Jt(()=>{},["prevent"])),onClick:g[3]||(g[3]=k=>e.findReplace.caseSensitive.value=!e.findReplace.caseSensitive.value)},Ht(e.findReplace.texts.matchCaseLabel),43,K_),o.value?(me(),_e("button",{key:1,type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--toggle",{"sd-find-replace__btn--active":e.findReplace.ignoreDiacritics.value}]),title:e.findReplace.texts.ignoreDiacriticsAriaLabel,"aria-label":e.findReplace.texts.ignoreDiacriticsAriaLabel,"aria-pressed":e.findReplace.ignoreDiacritics.value?"true":"false",onMousedown:g[4]||(g[4]=Jt(()=>{},["prevent"])),onClick:g[5]||(g[5]=k=>e.findReplace.ignoreDiacritics.value=!e.findReplace.ignoreDiacritics.value)},Ht(e.findReplace.texts.ignoreDiacriticsLabel),43,q_)):ut("",!0),s.value?(me(),_e("button",{key:2,type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--toggle",{"sd-find-replace__btn--active":e.findReplace.regex.value}]),title:e.findReplace.texts.regexAriaLabel,"aria-label":e.findReplace.texts.regexAriaLabel,"aria-pressed":e.findReplace.regex.value?"true":"false",onMousedown:g[6]||(g[6]=Jt(()=>{},["prevent"])),onClick:g[7]||(g[7]=k=>e.findReplace.regex.value=!e.findReplace.regex.value)},Ht(e.findReplace.texts.regexLabel),43,Y_)):ut("",!0)],2),Le("div",X_,[Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--icon",disabled:!e.findReplace.hasMatches.value,title:e.findReplace.texts.previousMatchLabel,"aria-label":e.findReplace.texts.previousMatchAriaLabel,onClick:g[8]||(g[8]=k=>c())},[...g[16]||(g[16]=[Le("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Le("path",{d:"M10 3.5 5.5 8 10 12.5",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"})],-1)])],8,Q_),Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--icon",disabled:!e.findReplace.hasMatches.value,title:e.findReplace.texts.nextMatchLabel,"aria-label":e.findReplace.texts.nextMatchAriaLabel,onClick:g[9]||(g[9]=k=>u())},[...g[17]||(g[17]=[Le("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Le("path",{d:"M6 3.5 10.5 8 6 12.5",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"})],-1)])],8,Z_),g[19]||(g[19]=Le("span",{class:"sd-find-replace__divider","aria-hidden":"true"},null,-1)),Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--icon",title:e.findReplace.texts.closeLabel,"aria-label":e.findReplace.texts.closeAriaLabel,onClick:d},[...g[18]||(g[18]=[Le("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Le("path",{d:"m4.5 4.5 7 7m0-7-7 7",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,J_)])]),e.findReplace.showReplace.value&&i.value?(me(),_e("div",$_,[g[20]||(g[20]=Le("span",{class:"sd-find-replace__row-indent","aria-hidden":"true"},null,-1)),Le("div",eS,[Le("input",{value:e.findReplace.replaceText.value,onInput:g[10]||(g[10]=k=>e.findReplace.replaceText.value=k.target.value),type:"text",class:"sd-find-replace__input",placeholder:e.findReplace.texts.replacePlaceholder,"aria-label":e.findReplace.texts.replaceAriaLabel,onKeydown:g[11]||(g[11]=Yo(Jt(k=>e.findReplace.replaceCurrent(),["prevent"]),["enter"]))},null,40,tS)]),Le("div",nS,[Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceLabel,onClick:g[12]||(g[12]=k=>e.findReplace.replaceCurrent())},Ht(e.findReplace.texts.replaceLabel),9,rS),Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceAllLabel,onClick:g[13]||(g[13]=k=>e.findReplace.replaceAll())},Ht(e.findReplace.texts.replaceAllLabel),9,oS)])])):ut("",!0),a.value?(me(),_e("div",iS,[i.value?(me(),_e("span",sS)):ut("",!0),Le("span",aS,Ht(a.value),1)])):ut("",!0)],40,U_))}},cS=hn(lS,[["__scopeId","data-v-fed15bd3"]])}));It();var lr={findPlaceholder:"Find",findAriaLabel:"Find text",replacePlaceholder:"Replace",replaceAriaLabel:"Replace text",noResultsLabel:"No results",previousMatchLabel:"Previous match (Shift+Enter)",previousMatchAriaLabel:"Previous match",nextMatchLabel:"Next match (Enter)",nextMatchAriaLabel:"Next match",closeLabel:"Close (Escape)",closeAriaLabel:"Close find and replace",replaceLabel:"Replace",replaceAllLabel:"All",toggleReplaceLabel:"Toggle replace",toggleReplaceAriaLabel:"Toggle replace",matchCaseLabel:"Aa",matchCaseAriaLabel:"Match case",regexLabel:".*",regexAriaLabel:"Use regular expression",invalidPatternLabel:"Invalid pattern",ignoreDiacriticsLabel:"ä≡a",ignoreDiacriticsAriaLabel:"Ignore diacritics"};function iM(e){if(!e)return null;const t=e.extensionStorage,n=e.storage,r=t?.Search??n?.Search;if(r?.searchIndex||r?.searchResults)return r;const o=e.extensionStorage??e.storage;if(o)for(const i of Object.keys(o)){const s=o[i];if(s&&typeof s=="object"&&"searchIndex"in s&&"searchResults"in s)return s}return null}function sM({getSurfaceManager:e,getActiveEditor:t,activeEditorRef:n,getFindReplaceConfig:r,getSuperDocUI:o}){let i=null,s=null,a=null,l=!1,u=!1;const c=ne(!1);let d=null;const h=ne(""),m=ne(""),p=ne(!1),g=ne(!1),k=ne(!1),w=ne(!1),S=ne(0),y=ne(-1),C=ne(!0),T=ne(!1),R=ne(!0),M=ne(!1),H=ne(null);let B=lr;const z=Se(()=>h.value?S.value===0?B.noResultsLabel:`${y.value+1} of ${S.value}`:""),Z=Se(()=>S.value>0),P=Se(()=>Z.value&&!T.value&&C.value);let N=null,I=null;function L(G){return typeof G?.commands?.setSearchSession=="function"}function X(){try{const G=(typeof o=="function"?o():null)?.search;return G&&typeof G.search=="function"?G:null}catch{return null}}function te(G){G&&(S.value=typeof G.total=="number"?G.total:0,y.value=typeof G.activeIndex=="number"?G.activeIndex:-1,C.value=G.canReplace===!0,H.value=G.reason==="search-invalid-pattern"?B.invalidPatternLabel:null)}function le(){if(a){fe();return}if(s){if(!h.value){try{s.commands.clearSearchSession()}catch{}S.value=0,y.value=-1;return}try{const G=s.commands.setSearchSession(h.value,{caseSensitive:p.value,ignoreDiacritics:g.value,highlight:!0,searchModel:Ie().includeDeletedText?"raw":"visible"});S.value=G.matches.length,y.value=G.activeMatchIndex}catch{}}}function fe(){const G=a;if(G){if(!h.value){try{G.clear()}catch{}S.value=0,y.value=-1,H.value=null;return}try{te(G.search(h.value,{caseSensitive:p.value,includeDeletedText:Ie().includeDeletedText===!0,regex:k.value}))}catch{}}}function Fe(){N&&clearTimeout(N),N=setTimeout(le,150)}Pt(h,()=>{c.value&&Fe()}),Pt(p,()=>{c.value&&le()}),Pt(g,()=>{c.value&&le()}),Pt(k,()=>{c.value&&le()});let he=!0;function ge(){if(Z.value){if(a){try{a.next(),te(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.nextSearchMatch().activeMatchIndex}catch{}}}function ae(){if(Z.value){if(a){try{a.previous(),te(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.previousSearchMatch().activeMatchIndex}catch{}}}function Ce(){if(he&&!T.value&&Z.value){if(a){if(!C.value)return;const G=a;T.value=!0;const J=H_(G,{getCurrentSession:()=>a,applySlice:te,onSettled:()=>{T.value=!1}});let K=null;try{K=G.replace(m.value)}catch{}K&&typeof K.then=="function"?Promise.resolve(K).then(J,J):J();return}if(s)try{const G=s.commands.replaceSearchMatch(m.value);S.value=G.matches.length,y.value=G.activeMatchIndex}catch{}}}function oe(){if(he&&!T.value&&Z.value){if(a){if(!C.value)return;const G=a;T.value=!0;const J=H_(G,{getCurrentSession:()=>a,applySlice:te,onSettled:()=>{T.value=!1}});let K=null;try{K=G.replaceAll(m.value)}catch{}K&&typeof K.then=="function"?Promise.resolve(K).then(J,J):J();return}if(s)try{s.commands.replaceAllSearchMatches(m.value),S.value=0,y.value=-1}catch{}}}function xe(){if(a){try{te(a.getSnapshot())}catch{}return}const G=iM(s);if(!G)return;const J=G.searchResults,K=Array.isArray(J)?J.length:0,W=G.activeMatchIndex??-1;K!==S.value&&(S.value=K),W!==y.value&&(y.value=W)}function qe(){et(),I=setInterval(xe,200)}function et(){N&&clearTimeout(N),N=null,I&&clearInterval(I),I=null}function kt(){h.value="",m.value="",p.value=!1,g.value=!1,k.value=!1,H.value=null,w.value=!1,S.value=0,y.value=-1,C.value=!0,T.value=!1}function Ie(){const G=typeof r=="function"?r():void 0;if(G===!1||G==null)return{enabled:!1,texts:lr,replaceEnabled:!0};if(G===!0)return{enabled:!0,texts:lr,replaceEnabled:!0};const J=typeof G=="object"?G:{};if(J.component!=null&&typeof J.render=="function")throw new Error('modules.surfaces.findReplace cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{findPlaceholder:J.findPlaceholder??lr.findPlaceholder,findAriaLabel:J.findAriaLabel??lr.findAriaLabel,replacePlaceholder:J.replacePlaceholder??lr.replacePlaceholder,replaceAriaLabel:J.replaceAriaLabel??lr.replaceAriaLabel,noResultsLabel:J.noResultsLabel??lr.noResultsLabel,previousMatchLabel:J.previousMatchLabel??lr.previousMatchLabel,previousMatchAriaLabel:J.previousMatchAriaLabel??lr.previousMatchAriaLabel,nextMatchLabel:J.nextMatchLabel??lr.nextMatchLabel,nextMatchAriaLabel:J.nextMatchAriaLabel??lr.nextMatchAriaLabel,closeLabel:J.closeLabel??lr.closeLabel,closeAriaLabel:J.closeAriaLabel??lr.closeAriaLabel,replaceLabel:J.replaceLabel??lr.replaceLabel,replaceAllLabel:J.replaceAllLabel??lr.replaceAllLabel,toggleReplaceLabel:J.toggleReplaceLabel??lr.toggleReplaceLabel,toggleReplaceAriaLabel:J.toggleReplaceAriaLabel??lr.toggleReplaceAriaLabel,matchCaseLabel:J.matchCaseLabel??lr.matchCaseLabel,matchCaseAriaLabel:J.matchCaseAriaLabel??lr.matchCaseAriaLabel,regexLabel:J.regexLabel??lr.regexLabel,regexAriaLabel:J.regexAriaLabel??lr.regexAriaLabel,invalidPatternLabel:J.invalidPatternLabel??lr.invalidPatternLabel,ignoreDiacriticsLabel:J.ignoreDiacriticsLabel??lr.ignoreDiacriticsLabel,ignoreDiacriticsAriaLabel:J.ignoreDiacriticsAriaLabel??lr.ignoreDiacriticsAriaLabel},replaceEnabled:J.replaceEnabled??!0,includeDeletedText:J.includeDeletedText??!1,component:J.component,props:J.props,render:J.render,resolver:J.resolver,floating:J.floating&&typeof J.floating=="object"?J.floating:void 0}}function ze(G,J){if(typeof G.resolver=="function"){const K=G.resolver(J);if(K!=null&&K.type!=="default"){if(K.type==="none")return{suppressed:!0};if(K.type==="custom")return{component:K.component,props:K.props};if(K.type==="external")return{render:K.render}}}return G.component!=null?{component:G.component,props:G.props}:typeof G.render=="function"?{render:G.render}:{builtin:!0}}function Ve(G,J){return{findQuery:h,replaceText:m,caseSensitive:p,ignoreDiacritics:g,regex:k,showReplace:w,matchCount:S,activeMatchIndex:y,matchLabel:z,hasMatches:Z,canReplace:P,replaceCanMutate:C,replacePending:T,ignoreDiacriticsSupported:R,regexSupported:M,searchError:H,replaceEnabled:G.replaceEnabled??!0,texts:G.texts,goNext:ge,goPrev:ae,replaceCurrent:Ce,replaceAll:oe,registerFocusFn:K=>{d=K},close:K=>J(K)}}function Q(G){return{get findQuery(){return G.findQuery.value},set findQuery(J){G.findQuery.value=J},get replaceText(){return G.replaceText.value},set replaceText(J){G.replaceText.value=J},get caseSensitive(){return G.caseSensitive.value},set caseSensitive(J){G.caseSensitive.value=J},get ignoreDiacritics(){return G.ignoreDiacritics.value},set ignoreDiacritics(J){G.ignoreDiacritics.value=J},get regex(){return G.regex.value},set regex(J){G.regex.value=J},get regexSupported(){return G.regexSupported.value},get searchError(){return G.searchError.value},get replaceCanMutate(){return G.replaceCanMutate.value},get showReplace(){return G.showReplace.value},set showReplace(J){G.showReplace.value=J},get matchCount(){return G.matchCount.value},get activeMatchIndex(){return G.activeMatchIndex.value},get matchLabel(){return G.matchLabel.value},get hasMatches(){return G.hasMatches.value},get canReplace(){return G.canReplace.value},get replacePending(){return G.replacePending.value},get ignoreDiacriticsSupported(){return G.ignoreDiacriticsSupported.value},replaceEnabled:G.replaceEnabled,texts:G.texts,goNext:G.goNext,goPrev:G.goPrev,replaceCurrent:G.replaceCurrent,replaceAll:G.replaceAll,registerFocusFn:G.registerFocusFn,close:G.close}}function _(G){if(G){if(typeof G?.commands?.clearSearchSession=="function"){try{G.commands.clearSearchSession()}catch{}return}if(a&&G===s)try{a.clear()}catch{}}}function $(){try{if(l||!e()||!t())return!1;if(i&&c.value)return!0;const G=Ie();if(!G.enabled||ze(G,{texts:G.texts,replaceEnabled:G.replaceEnabled??!0}).suppressed)return!1;if(!L(t())){const J=X();if(!J)return!1;try{if(J.getSnapshot?.().available!==!0)return!1}catch{return!1}}return!0}catch{return!1}}async function F(){if(l)return;const G=e();if(G){if(i&&c.value){d?.();return}if(!u){u=!0;try{const J=t();if(!J){u=!1;return}const K=Ie();if(!K.enabled){u=!1;return}const W=ze(K,{texts:K.texts,replaceEnabled:K.replaceEnabled??!0});if(W.suppressed){u=!1;return}kt(),B=K.texts,he=K.replaceEnabled??!0;const ue={placement:"top-right",autoFocus:!0,width:420,...K.floating??{}};if(s&&s!==J&&_(s),s=J,a=L(J)?null:X(),R.value=!a,M.value=!!a,a)try{te(a.getSnapshot())}catch{}d=null;let be=()=>{};const we=Ve(K,nt=>be(nt));let Te;if(W.component)Te=G.open({mode:"floating",ariaLabel:K.texts.findAriaLabel,closeOnEscape:!0,floating:ue,component:Hr(W.component),props:{...W.props,findReplace:we}});else if(W.render){const nt=W.render;Te=G.open({mode:"floating",ariaLabel:K.texts.findAriaLabel,closeOnEscape:!0,floating:ue,render:wt=>nt({container:wt.container,findReplace:Q(we),resolve:wt.resolve,close:wt.close,surfaceId:wt.surfaceId,mode:wt.mode})})}else{let nt;try{nt=(await Promise.resolve().then(()=>(oM(),rM))).default}catch{u=!1;return}if(l||i&&c.value){u=!1;return}const wt=t()||J;s!==wt&&(_(s),s=wt,a=L(wt)?null:X(),R.value=!a),Te=G.open({mode:"floating",ariaLabel:K.texts.findAriaLabel,component:Hr(nt),closeOnEscape:!0,floating:ue,props:{findReplace:we}})}be=nt=>Te.close(nt??"programmatic"),i=Te,c.value=!0,u=!1,qe();const rt=Te.id;Te.result.then(()=>{i?.id===rt?(et(),_(s),i=null,c.value=!1,d=null):_(J!==s?J:null)})}catch(J){throw u=!1,J}}}}function j(){i&&i.close("programmatic")}n&&Pt(n,(G,J)=>{!c.value||!i||G!==J&&(_(J),j())});function V(){l=!0,et(),j(),s=null,a=null,d=null}return{open:F,close:j,isOpen:c,wouldOpen:$,destroy:V}}var ef=null;function Zy(e){e!=null&&(ef=e)}function aM(e){ef===e&&(ef=null)}function lM(e){return ef===null||ef===e}function cM(e,{focusInside:t,owner:n}){if(e.defaultPrevented)return!1;if(t)return!0;const r=document.activeElement;return(!r||r===document.body||r===document.documentElement)&&lM(n)}var uM=/^(https?|mailto|tel):/i,dM=/^(javascript|data|vbscript):/i,fM=/^[a-z][a-z0-9+.-]*:/i;function hM(e){if(typeof e!="string")return null;const t=e.trim();return t?t.startsWith("#")?{href:t}:dM.test(t)?null:fM.test(t)?uM.test(t)?{href:t}:null:{href:t}:null}var pM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M0 64C0 46.3 14.3 32 32 32l48 0 16 0 128 0c70.7 0 128 57.3 128 128c0 31.3-11.3 60.1-30 82.3c37.1 22.4 62 63.1 62 109.7c0 70.7-57.3 128-128 128L96 480l-16 0-48 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l16 0 0-160L48 96 32 96C14.3 96 0 81.7 0 64zM224 224c35.3 0 64-28.7 64-64s-28.7-64-64-64L112 96l0 128 112 0zM112 288l0 128 144 0c35.3 0 64-28.7 64-64s-28.7-64-64-64l-32 0-112 0z"/></svg>',mM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M128 64c0-17.7 14.3-32 32-32l192 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-58.7 0L160 416l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l58.7 0L224 96l-64 0c-17.7 0-32-14.3-32-32z"/></svg>',gM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M16 64c0-17.7 14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 53 43 96 96 96s96-43 96-96l0-128-16 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 88.4-71.6 160-160 160s-160-71.6-160-160L64 96 48 96C30.3 96 16 81.7 16 64zM0 448c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32z"/></svg>',uS='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M40 48C26.7 48 16 58.7 16 72l0 48c0 13.3 10.7 24 24 24l48 0c13.3 0 24-10.7 24-24l0-48c0-13.3-10.7-24-24-24L40 48zM192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 64zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zM16 232l0 48c0 13.3 10.7 24 24 24l48 0c13.3 0 24-10.7 24-24l0-48c0-13.3-10.7-24-24-24l-48 0c-13.3 0-24 10.7-24 24zM40 368c-13.3 0-24 10.7-24 24l0 48c0 13.3 10.7 24 24 24l48 0c13.3 0 24-10.7 24-24l0-48c0-13.3-10.7-24-24-24l-48 0z"/></svg>',vM=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. (bullet shapes modified)--><path fill-rule="evenodd" d="M192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 64zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zM64 48 A48 48 0 1 0 64 144 A48 48 0 1 0 64 48 Z M64 68 A28 28 0 1 1 64 124 A28 28 0 1 1 64 68 Z M64 208 A48 48 0 1 0 64 304 A48 48 0 1 0 64 208 Z M64 228 A28 28 0 1 1 64 284 A28 28 0 1 1 64 228 Z M64 368 A48 48 0 1 0 64 464 A48 48 0 1 0 64 368 Z M64 388 A28 28 0 1 1 64 444 A28 28 0 1 1 64 388 Z"/></svg>
|
|
14
|
+
`).trim();return g?g.split(/\n{2,}/).map(k=>`<p>${c(k).replace(/\n/g,"<br>")}</p>`).join(""):"<p></p>"},m=Se({get:()=>d(o.value),set:p=>{o.value=h(p)}});return Rn(u),Pt(o,u),t({focus:a}),(p,g)=>(me(),_e("div",k7,[e.includeHeader?(me(),fn(Gy,{key:0,config:e.config,comment:e.comment,"is-pending-input":!0},null,8,["config","comment"])):ut("",!0),Le("div",{class:en(["comment-entry",{"sd-input-active":e.isFocused}])},[Ws(Le("textarea",{ref_key:"inputRef",ref:i,class:"superdoc-field",placeholder:"Add a comment","onUpdate:modelValue":g[0]||(g[0]=k=>m.value=k),rows:"1",onInput:l,onFocus:g[1]||(g[1]=k=>s(!0)),onBlur:g[2]||(g[2]=k=>s(!1))},null,544),[[ki,m.value]])],2)]))}},Ky=hn(A7,[["__scopeId","data-v-cc54b489"]]);It(),gn();var I7=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],E7={key:0,class:"existing-internal-input"},x7={class:"new-comment-input-wrapper"},T7={class:"reply-actions"},R7=["disabled"],M7={key:0,class:"resolved-badge"},L7=["innerHTML"],D7={key:1,class:"existing-internal-input"},P7={key:0,class:"card-section comment-body"},O7=["data-track-change-semantic-color-key"],F7={key:0},B7={class:"change-type tracked-change-label"},N7={key:0,class:"tracked-change-detail-lines"},z7={key:0,class:"tracked-change-text"},H7={key:1,class:"change-type"},U7={class:"change-type"},V7={key:1},j7={class:"tracked-change-text is-inserted"},G7={key:2},W7={class:"tracked-change-text is-inserted"},K7={key:3},q7={key:4},Y7={key:5},X7={key:6},Q7={class:"tracked-change-text"},Z7={key:7},J7={class:"tracked-change-text is-deleted"},$7={class:"tracked-change-text is-inserted"},eR={key:8},tR={class:"tracked-change-text is-deleted"},nR={key:9},rR={class:"tracked-change-text is-inserted"},oR=["data-track-change-image-preview-role"],iR=["src","alt"],sR={key:1,class:"card-section comment-body"},aR=["innerHTML"],lR={key:1,class:"comment"},cR={key:2,class:"reply-expanded"},uR={class:"reply-input-wrapper"},dR={class:"reply-actions"},fR=["onClick"],hR=["onClick","disabled","data-disabled-reason"],pR={class:"collapsed-avatars"},mR={key:3,class:"comment-separator"},gR={key:2,class:"tracked-change-decision-alert",role:"alert"},vR={class:"tracked-change-decision-alert__message"},yR=["disabled","data-disabled-reason"],bR={key:1,class:"reply-expanded"},wR={class:"reply-input-wrapper"},CR={class:"reply-actions"},_R=["disabled","data-disabled-reason"],mp=3,f_=90,SR={__name:"CommentDialog",props:{comment:{type:Object,required:!0},autoFocus:{type:Boolean,default:!1},parent:{type:Object,required:!1},floatingInstanceId:{type:String,default:null},floatingPageIndex:{type:Number,default:null},floatingPositionEntry:{type:Object,default:null},isFloatingInstanceActive:{type:Boolean,default:void 0}},emits:["click-outside","ready","dialog-exit","resize"],setup(e,{emit:t}){const n=t,r=e,{proxy:o}=sr(),i=nu(),s=ca(),{addComment:a,cancelComment:l,deleteComment:u,getCommentAliasIds:c,removePendingComment:d,getCommentDocumentId:h,requestInstantSidebarAlignment:m,resolveCommentPositionEntry:p,clearInstantSidebarAlignment:g,setActiveFloatingCommentInstance:k}=s,{suppressInternalExternal:w,getConfig:S,activeComment:y,activeFloatingCommentInstanceId:C,floatingCommentsOffset:T,pendingComment:R,currentCommentText:M,isDebugging:H,editingCommentId:B,editorCommentPositions:z,isCommentHighlighted:Z}=ea(s),P=ne(!0),N=ne(null),I=ne(new Map),L=ne(null),X=[[0,0],[-mp,0],[mp,0],[0,-mp],[0,mp]],te=ke=>{const Oe=typeof ke?.width=="number"&&Number.isFinite(ke.width)?ke.width:null,ft=typeof ke?.height=="number"&&Number.isFinite(ke.height)?ke.height:null;if(!Oe||!ft||Oe<=0||ft<=0)return{};const lt=Math.min(f_/Oe,f_/ft,1);return{width:`${Math.max(1,Math.round(Oe*lt))}px`,height:`${Math.max(1,Math.round(ft*lt))}px`}},le=[".comments-dropdown__option-label",".comments-dropdown__menu",".comments-dropdown__option",".comments-dropdown__option-icon",".comments-dropdown__trigger",".superdoc-comment-highlight",".sd-editor-comment-highlight",".sd-editor-tracked-change-highlight","[data-track-change-id]",".track-insert",".track-insert-dec",".track-delete",".track-delete-dec",".track-format",".track-format-dec"].join(","),fe=ke=>Oe=>{ke&&(Oe?(I.value.set(ke,Oe),B.value===ke&&_t(()=>{ge(ke)})):I.value.delete(ke))},Fe=(ke,Oe,ft)=>{const lt=ke?.getBoundingClientRect?.();return!lt||![lt.left,lt.top,lt.right,lt.bottom].every(Number.isFinite)||lt.width<=0||lt.height<=0?!1:X.some(([bn,an])=>{const Fr=Oe+bn,mo=ft+an;return Fr>=lt.left&&Fr<=lt.right&&mo>=lt.top&&mo<=lt.bottom})},he=(ke,Oe)=>{if(!Number.isFinite(ke)||!Number.isFinite(Oe))return null;const ft=document.querySelectorAll(le);for(const lt of ft)if(lt instanceof HTMLElement&&Fe(lt,ke,Oe))return lt;return null},ge=ke=>{I.value.get(ke)?.focus?.()},ae=ne(null),Ce=ke=>ke.resolvedTime?ke.commentId:ke.importedId||ke.commentId,oe=ke=>ke?ke.trackedChange&&ke.importedId!=null?String(ke.importedId):ke.commentId!=null?String(ke.commentId):null:null,xe=(ke,Oe)=>{const ft=ke?.bounds?.[Oe];return Number.isFinite(ft)?ft:null},qe=(ke,Oe)=>{if(!ke||!Oe||ke.pageIndex!==Oe.pageIndex)return!1;const ft=xe(ke,"top"),lt=xe(Oe,"top");return ft!=null&<!=null&&Math.abs(ft-lt)<.5},et=(ke,Oe)=>{const ft=xe(ke,"left"),lt=xe(Oe,"left"),bn=xe(ke,"right"),an=xe(Oe,"right");return[ft,lt,bn,an].some(Fr=>Fr==null)?!1:lt<bn&&ft<an},kt=(ke,Oe)=>{const ft=ke?.start,lt=ke?.end,bn=Oe?.start,an=Oe?.end;return[ft,lt,bn,an].every(Number.isFinite)?bn<=lt&&ft<=an:!1},Ie=(ke,Oe)=>!ke||!Oe||ke.kind&&Oe.kind&&ke.kind!==Oe.kind||ke.storyKey&&Oe.storyKey&&ke.storyKey!==Oe.storyKey?!1:Oe.start===ke.start&&Oe.end===ke.end?!0:qe(ke,Oe)&&et(ke,Oe)&&kt(ke,Oe),ze=ke=>{const Oe=new Set(c(ke)),{key:ft,entry:lt}=p(ke);return ft&&Oe.add(ft),lt?(Object.entries(z.value??{}).forEach(([bn,an])=>{Ie(lt,an)&&Oe.add(bn)}),[...Oe]):[...Oe]},Ve=(ke,Oe,ft=24)=>{if(!Number.isFinite(Oe)||typeof ke?.getBoundingClientRect!="function")return!1;const lt=ke.getBoundingClientRect().top;return Number.isFinite(lt)&&Math.abs(lt-Oe)<=ft},Q=Se(()=>r.floatingInstanceId??r.comment.commentId??null),_=Se(()=>typeof r.isFloatingInstanceActive=="boolean"?r.isFloatingInstanceActive:y.value!==r.comment.commentId?!1:r.floatingInstanceId==null?!0:C.value===r.floatingInstanceId),$=Se(()=>r.comment.resolvedTime?r.comment.trackedChange?r.comment.trackedChangeDecision==="reject"?"Rejected":"Accepted":"Resolved":null),F=Se(()=>R.value&&R.value.commentId===r.comment.commentId),j=Se(()=>ke=>{const Oe=Fn.value;return V.value&&ke===Oe.length-1?!0:Oe.length>1&&ke!==Oe.length-1}),V=Se(()=>!S.readOnly&&_.value&&!r.comment.resolvedTime&&!Dt.value),G=()=>({ok:!1,reason:"read-only-document"}),J=()=>S.value?.readOnly===!0,K=ne(!1),W=ne(!1),ue=()=>{if(J())return G();if(Tt.value)return{ok:!1,reason:sn.value?.reason??"v2-write-unavailable"};K.value=!0,_t(()=>{N.value?.focus?.(),n("resize")})},be=Se(()=>{const ke=r.comment;return ke.trackedChange?s.getTrackedChangeThread(ke):s.commentsList.filter(Oe=>{const ft=Oe.parentCommentId===ke.commentId,lt=Oe.commentId===ke.commentId;return ft||lt}).sort((Oe,ft)=>Oe.commentId===ke.commentId?-1:ft.commentId===ke.commentId?1:Oe.createdTime-ft.createdTime)}),we=ne(!1),Te=ne(null),rt=ne(!1),nt=Se(()=>!we.value),wt=()=>{we.value=!we.value,_t(()=>n("resize"))},Zt=()=>{if(we.value)return;const ke=Te.value;if(!ke){rt.value=!1;return}rt.value=ke.scrollHeight>ke.clientHeight+1};Pt(Te,()=>{_t(Zt)});const Ct=()=>B.value?be.value.some(ke=>ke.commentId===B.value):!1;Pt(_,ke=>{ke||((K.value||Ct())&&(M.value="",B.value=null),we.value=!1,Ot.value=!1,K.value=!1,_t(()=>n("resize")))});const Ot=ne(!1),Bt=Se(()=>be.value.slice(1)),on=Se(()=>Ot.value?!1:Bt.value.length>=2),Fn=Se(()=>on.value?[be.value[0],Bt.value[Bt.value.length-1]].filter(Boolean):be.value),Vt=Se(()=>on.value?Bt.value.length-1:0),We=Se(()=>{if(!on.value)return[];const ke=Bt.value.slice(0,-1),Oe=new Set;return ke.map(ft=>typeof ft.getCommentUser=="function"?ft.getCommentUser():{name:ft.creatorName,email:ft.creatorEmail||ft.email}).filter(ft=>{if(!ft)return!1;const lt=ft.email||ft.name;return Oe.has(lt)?!1:(Oe.add(lt),!0)}).slice(0,3)}),St=()=>{Ot.value=!0,Me(),_t(()=>n("resize"))},Nt=Se(()=>r.comment.resolvedTime?!0:S.value.readOnly),cn=Se(()=>ke=>_.value&&B.value===ke.commentId),Dt=Se(()=>!B.value||!_.value?!1:be.value.some(ke=>ke.commentId===B.value)),un=Se(()=>S.value.readOnly||!o.$superdoc.config.isInternal||ot.value?!1:!w.value&&!r.comment.trackedChange),Ft=Se(()=>M.value&&M.value!=="<p></p>"),Me=async()=>{const ke=o.$superdoc.activeEditor,Oe=ke?.editorVersion===2?ke?.v2Comments??null:null,ft=!!r.comment?.trackedChange,lt=jT(),bn=r.floatingInstanceId!=null,an=ae.value?.getBoundingClientRect?.().top,Fr=!r.comment.resolvedTime&&(y.value!==r.comment.commentId||bn&&Q.value!==C.value);let mo=lt;if(Oe){const go=!ft&&String(r.comment?.trackedChangeParentId??"").trim()?r.comment.trackedChangeParentId:null,To=ke?.editorVersion===2&&(ft||go!=null)?ke?.v2TrackedChanges??null:null,Is=go!=null?s.getComment(go):null,Jo=ft?r.comment:Is?.trackedChange?Is:go;let Ro=await(To?To.focusTrackedChange(Jo):Oe.focusComment(r.comment));return!ft&&Ro?.reason==="tracked-change-anchor-not-found"&&(Ro=await Oe.focusComment(r.comment)),Ro?.ok?(r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId)),Fr&&!bn?m(lt,r.comment.commentId,r.floatingInstanceId??null):Fr&&Number.isFinite(an)?m(an,r.comment.commentId,r.floatingInstanceId):g(),Ro):(g(),Ro)}if(ke){const{entry:go}=p(r.comment),To=r.floatingPositionEntry??go,Is=Number.isFinite(r.floatingPageIndex)&&r.comment?.trackedChangeStory?.storyType==="headerFooterPart",Jo=a_(r.parent,To),Ro=Is?null:GT(ze(r.comment)),Ki=Number.isFinite(Ro)?Ro:Jo,Gr=Ve(ae.value,Ki),Sr=Ce(r.comment),Mo=null;let Ho=null;if(ft)if(r.comment.trackedChangeStory&&(r.comment.trackedChangeStory,{...Number.isFinite(r.floatingPageIndex)?{pageIndex:r.floatingPageIndex}:{}}),r.comment.resolvedTime)ke.commands?.setCursorById(Sr);else{const $o=r.comment.commentId;ke.commands?.setCursorById(Sr,{activeCommentId:$o})||ke.commands?.setActiveComment({commentId:$o})}else{if(r.comment.resolvedTime)ke.commands?.setCursorById(Sr);else{const ll=r.comment.commentId;ke.commands?.setCursorById(Sr,{activeCommentId:ll})||ke.commands?.setActiveComment({commentId:ll})}const $o=r.comment.commentId;Ho=Gr?null:WT(Mo,Sr,$o,lt)}Number.isFinite(Ro)?mo=Ro:Number.isFinite(Jo)?mo=Jo:Number.isFinite(Ho)&&(mo=Ho)}Fr&&!bn?r.floatingInstanceId?m(mo,r.comment.commentId,r.floatingInstanceId):m(mo,r.comment.commentId):g(),r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId))},Pe=ke=>{const Oe=ke.target instanceof Element?ke.target:ke.target?.parentElement,ft=document.elementFromPoint(ke.clientX,ke.clientY);if(!(Oe?.closest?.(le)||ft?.closest?.(le)||he(ke.clientX,ke.clientY)||Z.value)&&!(ke.target.closest?.(".comments-dialog")&&!ae.value?.contains(ke.target))){if(F.value){l(o.$superdoc);return}_.value&&(T.value=0,n("dialog-exit"),y.value=null,s.setActiveComment(o.$superdoc,y.value),Z.value=!1)}},Ze=async()=>{if(J())return G();if(Tt.value)return{ok:!1,reason:sn.value?.reason??"v2-write-unavailable"};if(ot.value&&Mt.value&&!F.value){if(W.value)return{ok:!1,reason:"reply-submit-in-flight"};W.value=!0;try{const ft=await s.replyCommentV2({superdoc:o.$superdoc,parentCommentId:oe(r.comment),text:M.value});return ft?.ok?(K.value=!1,M.value="",_t(()=>n("resize")),ft):(_t(()=>n("resize")),ft)}finally{W.value=!1}}const ke={documentId:r.comment.fileId,isInternal:R.value?R.value.isInternal:P.value,parentCommentId:R.value?null:r.comment.commentId};R.value&&(ke.selection=R.value.selection.getValues());const Oe=s.getPendingComment(ke);!R.value&&M.value&&Oe.setText({text:M.value,suppressUpdate:!0}),Promise.resolve(a({superdoc:o.$superdoc,comment:Oe})).finally(()=>{K.value=!1,_t(()=>n("resize"))})},ot=Se(()=>o.$superdoc?.activeEditor?.editorVersion===2),Mt=Se(()=>ot.value?o.$superdoc?.activeEditor?.v2Comments??null:null),Et=Se(()=>ot.value?o.$superdoc?.activeEditor?.v2TrackedChanges??null:null),sn=Se(()=>{if(!Mt.value)return null;const ke=s.viewingVisibility.documentMode,Oe=Mt.value.getCapabilityState?.()??null;return ke==="viewing"?{...Oe??{},canWrite:!1,reason:"review-surface-read-only"}:Oe}),Tt=Se(()=>{if(!ot.value)return!1;const ke=sn.value;return ke?ke.canWrite===!1:!1}),ur=Se(()=>W.value?"reply-submit-in-flight":Tt.value?sn.value?.reason??"v2-write-unavailable":null),dr=Se(()=>{if(!Et.value)return null;const ke=s.viewingVisibility.documentMode,Oe=Et.value.getCapabilityState?.()??null;return ke==="viewing"&&Oe?.canDecide!==!1?{canDecide:!1,reason:"review-surface-read-only"}:Oe}),jr=ke=>{if(ot.value&&ke?.trackedChange){if(!Et.value)return"v2-tracked-change-adapter-missing";const Oe=dr.value;return Oe&&Oe.canDecide===!1?Oe.reason??"v2-tracked-change-unavailable":null}return Tt.value?sn.value?.reason??"v2-write-unavailable":null},$t=ke=>{if(ot.value&&ke?.trackedChange){if(!Et.value)return"v2-tracked-change-adapter-missing";const Oe=dr.value;return Oe&&Oe.canDecide===!1?Oe.reason??"v2-tracked-change-unavailable":null}return Tt.value?sn.value?.reason??"v2-write-unavailable":null},Vn=()=>ot.value?Mt.value?S.value?.readOnly?"read-only-document":Tt.value?sn.value?.reason??"v2-write-unavailable":null:"v2-comments-adapter-missing":null,Mr=Se(()=>!ot.value||!Tt.value?null:sn.value?.reason??"v2-write-unavailable"),_r=(ke,Oe)=>{L.value={decision:ke,reason:Oe?.reason??null},_t(()=>n("resize"))},po=()=>{L.value&&(L.value=null,_t(()=>n("resize")))},Kt=Se(()=>{const ke=L.value;if(!ke)return null;const Oe=ke.decision==="reject"?"reject":"accept";return ke.reason==="stale-catalog"?`Couldn't ${Oe} this change because the review list is stale.`:`Couldn't ${Oe} this change.`}),yn=()=>{const ke=L.value;if(ke){if(L.value=null,ke.decision==="reject"){xo();return}Zo()}},xo=async()=>{if(J())return G();const ke=o.$superdoc.config.onTrackedChangeBubbleReject;if(r.comment.trackedChange){if(ot.value){const ft=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});if(!ft?.ok||ft.success===!1){_r("reject",ft);return}po(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Oe=!0;if(typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else{const ft=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});Oe=!!ft?.ok&&ft.success!==!1}Oe&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"reject"})}else if(ot.value&&Mt.value){if(!(await s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId});_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Zo=async()=>{if(J())return G();if(!r.comment.trackedChange&&S.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};const ke=o.$superdoc.config.onTrackedChangeBubbleAccept;if(r.comment.trackedChange&&ot.value){const ft=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});if(!ft?.ok||ft.success===!1){_r("accept",ft);return}po(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Oe=!0;if(r.comment.trackedChange&&typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else if(r.comment.trackedChange){const ft=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});Oe=!!ft?.ok&&ft.success!==!1}else if(ot.value&&Mt.value){if(!(await s.resolveCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc});r.comment.trackedChange&&!ot.value&&Oe&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"accept"}),_t(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Ei=async()=>{if(J())return G();if(S.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};!ot.value||!Mt.value||(await s.reopenCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok&&_t(()=>{s.lastUpdate=new Date,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},pi=(ke,Oe)=>{if(J())return G();switch(ke){case"edit":M.value=Oe?.commentText?.value??Oe?.commentText??"",y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId),B.value=Oe.commentId,s.setActiveComment(o.$superdoc,y.value),_t(()=>{ge(Oe.commentId)});break;case"delete":u({superdoc:o.$superdoc,commentId:Oe.commentId});break}},Ss=async ke=>{if(J())return G();if(ot.value&&Mt.value){const Oe=await s.editCommentV2({superdoc:o.$superdoc,commentId:ke.commentId,text:M.value});return Oe?.ok&&(B.value=null,d(o.$superdoc)),Oe}B.value=null,ke.setText({text:M.value,superdoc:o.$superdoc}),d(o.$superdoc)},ks=ke=>{if(J())return G();const Oe=!!R.value,ft=ke.toLowerCase()==="internal";Oe?R.value.isInternal=ft:r.comment.setIsInternal({isInternal:ft,superdoc:o.$superdoc})},As=Se(()=>{const ke={};return(_.value||F.value||Dt.value)&&(ke.zIndex=50),ke}),al=ke=>typeof ke=="string"?new Date(ke).getTime():ke,Wi=ke=>{B.value=null,K.value=!1,l(o.$superdoc)},ro=Se(()=>{const ke=o.$superdoc.users;return r.comment.isInternal===!0?ke.filter(Oe=>Oe.access?.role==="internal"):ke});return Rn(()=>{r.autoFocus&&_t(()=>Me()),F.value&&_t(()=>{N.value?.focus?.()}),_t(()=>{n("ready",{commentId:r.floatingInstanceId??(r.comment.importedId!==void 0?r.comment.importedId:r.comment.commentId),elementRef:ae}),Zt()})}),Pt(V,ke=>{ke&&_t(()=>{N.value?.focus?.()})},{immediate:!0}),Pt(B,ke=>{if(!ke||!_.value)return;const Oe=be.value.find(ft=>ft.commentId===ke);!Oe||Oe.trackedChange||_t(()=>{ge(ke)})}),Pt(()=>S.value?.readOnly===!0,ke=>{ke&&(K.value=!1,be.value.some(Oe=>Oe.commentId===B.value)&&(B.value=null),F.value&&l(o.$superdoc),_t(()=>n("resize")))},{immediate:!0}),Pt(Tt,ke=>{ke&&(K.value=!1,_t(()=>n("resize")))}),(ke,Oe)=>{const ft=D2("click-outside");return Ws((me(),_e("div",{class:en(["comments-dialog",{"is-active":_.value||F.value,"is-resolved":r.comment.resolvedTime}]),onClick:Jt(Me,["stop","prevent"]),style:vn(As.value),ref_key:"commentDialogElement",ref:ae,role:"dialog","data-sd-part":"comment-thread","data-editor-ui-surface":"","data-comment-instance-id":r.floatingInstanceId??"","data-comment-thread-id":r.comment.commentId??"","data-comment-position-key":r.comment.trackedChangeAnchorKey??"","data-comment-page-index":Number.isFinite(r.floatingPageIndex)?r.floatingPageIndex:""},[F.value?(me(),_e(Wt,{key:0},[un.value?(me(),_e("div",E7,[Gt(c_,{onClick:Oe[0]||(Oe[0]=Jt(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":!1,state:Ge(R).isInternal?"internal":"external",onSelect:ks},null,8,["state"])])):ut("",!0),Gt(Gy,{config:Ge(S),comment:r.comment,"is-pending-input":!0},null,8,["config","comment"]),Le("div",x7,[Gt(Ky,{ref_key:"commentInput",ref:N,users:ro.value,config:Ge(S),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Le("div",T7,[Le("button",{class:"sd-button reply-btn-cancel",onClick:Jt(Wi,["stop","prevent"])},"Cancel"),Le("button",{class:en(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ft.value}]),onClick:Jt(Ze,["stop","prevent"]),disabled:!Ft.value}," Comment ",10,R7)])],64)):(me(),_e(Wt,{key:1},[$.value?(me(),_e("div",M7,[Le("span",{class:"resolved-badge__icon",innerHTML:Ge(ua).markDone},null,8,L7),Oi(" "+Ht($.value),1)])):ut("",!0),un.value?(me(),_e("div",D7,[Gt(c_,{onClick:Oe[1]||(Oe[1]=Jt(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":Nt.value,state:e.comment.isInternal?"internal":"external",onSelect:ks},null,8,["is-disabled","state"])])):ut("",!0),(me(!0),_e(Wt,null,or(Fn.value,(lt,bn)=>(me(),_e("div",{key:lt.commentId,class:"conversation-item"},[Gt(Gy,{config:Ge(S),timestamp:al(lt.createdTime),comment:lt,"is-active":_.value,"resolve-disabled-reason":jr(lt),"reject-disabled-reason":$t(lt),"reopen-supported":ot.value&&!!Mt.value,"reopen-disabled-reason":Vn(),"write-disabled-reason":Mr.value,onResolve:Zo,onReject:xo,onReopen:Ei,onOverflowSelect:an=>pi(an,lt)},null,8,["config","timestamp","comment","is-active","resolve-disabled-reason","reject-disabled-reason","reopen-supported","reopen-disabled-reason","write-disabled-reason","onOverflowSelect"]),lt.trackedChange?(me(),_e("div",P7,[Le("div",{class:en(["tracked-change",{"is-truncated":nt.value&&bn===0}]),"data-track-change-semantic-color-key":lt.semanticColorKey??void 0,ref_for:!0,ref:bn===0?an=>Te.value=an:void 0},[lt.trackedChangeLabel?(me(),_e("div",F7,[Le("span",B7,Ht(lt.trackedChangeLabel),1),lt.trackedChangeDetailLines&<.trackedChangeDetailLines.length?(me(),_e("div",N7,[(me(!0),_e(Wt,null,or(lt.trackedChangeDetailLines,(an,Fr)=>(me(),_e("div",{key:Fr,class:"tracked-change-detail-line"},[an.excerpt?(me(),_e("span",z7,'"'+Ht(an.excerpt)+'"',1)):ut("",!0),an.excerpt?(me(),_e("span",H7," — ")):ut("",!0),Le("span",U7,Ht(an.label),1)]))),128))])):ut("",!0)])):lt.trackedChangeDisplayType==="hyperlinkAdded"?(me(),_e("div",V7,[Oe[2]||(Oe[2]=Le("span",{class:"change-type"},"Added hyperlink ",-1)),Le("span",j7,'"'+Ht(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="hyperlinkModified"?(me(),_e("div",G7,[Oe[3]||(Oe[3]=Le("span",{class:"change-type"},"Changed hyperlink to ",-1)),Le("span",W7,'"'+Ht(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="paragraphSplit"?(me(),_e("div",K7,[...Oe[4]||(Oe[4]=[Le("span",{class:"change-type"},"Added new line",-1)])])):lt.trackedChangeDisplayType==="tableInsert"?(me(),_e("div",q7,[...Oe[5]||(Oe[5]=[Le("span",{class:"change-type"},"Added table",-1)])])):lt.trackedChangeDisplayType==="tableDelete"?(me(),_e("div",Y7,[...Oe[6]||(Oe[6]=[Le("span",{class:"change-type"},"Deleted table",-1)])])):lt.trackedChangeType==="trackFormat"?(me(),_e("div",X7,[Oe[7]||(Oe[7]=Le("span",{class:"change-type"},"Format: ",-1)),Le("span",Q7,Ht(lt.trackedChangeText),1)])):lt.trackedChangeType==="both"?(me(),_e("div",Z7,[Oe[8]||(Oe[8]=Le("span",{class:"change-type"},"Replaced ",-1)),Le("span",J7,'"'+Ht(lt.deletedText)+'"',1),Oe[9]||(Oe[9]=Le("span",{class:"change-type"}," with ",-1)),Le("span",$7,'"'+Ht(lt.trackedChangeText)+'"',1)])):lt.deletedText?(me(),_e("div",eR,[Oe[10]||(Oe[10]=Le("span",{class:"change-type"},"Deleted ",-1)),Le("span",tR,'"'+Ht(lt.deletedText)+'"',1)])):lt.trackedChangeText?(me(),_e("div",nR,[Oe[11]||(Oe[11]=Le("span",{class:"change-type"},"Added ",-1)),Le("span",rR,'"'+Ht(lt.trackedChangeText)+'"',1)])):ut("",!0),lt.trackedChangeImagePreview?.src?(me(),_e("div",{key:10,class:"tracked-change-image-preview","data-track-change-image-preview-role":lt.trackedChangeImagePreview.role??void 0},[Le("img",{class:"tracked-change-image-preview__image",src:lt.trackedChangeImagePreview.src,alt:lt.trackedChangeImagePreview.alt||"Tracked image preview",style:vn(te(lt.trackedChangeImagePreview)),loading:"lazy",decoding:"async"},null,12,iR)],8,oR)):ut("",!0)],10,O7),nt.value&&rt.value&&bn===0?(me(),_e("div",{key:0,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show more ")):ut("",!0),we.value&&rt.value&&bn===0?(me(),_e("div",{key:1,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show less ")):ut("",!0)])):ut("",!0),lt.trackedChange?ut("",!0):(me(),_e("div",sR,[!Ge(H)&&!cn.value(lt)?(me(),_e("div",{key:0,class:en(["comment",{"is-truncated":nt.value&&bn===0}]),ref_for:!0,ref:bn===0?an=>Te.value=an:void 0,innerHTML:lt.commentText},null,10,aR)):Ge(H)&&!cn.value(lt)?(me(),_e("div",lR,Ht(Ge(z)[lt.importedId!==void 0?lt.importedId:lt.commentId]?.bounds),1)):(me(),_e("div",cR,[Le("div",uR,[Gt(Ky,{ref_for:!0,ref:fe(lt.commentId),users:ro.value,config:Ge(S),"include-header":!1,comment:lt},null,8,["users","config","comment"])]),Le("div",dR,[Le("button",{class:"sd-button reply-btn-cancel",onClick:Jt(an=>Wi(lt),["stop","prevent"])},"Cancel",8,fR),Le("button",{class:en(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ft.value||Tt.value}]),onClick:Jt(an=>Ss(lt),["stop","prevent"]),disabled:!Ft.value||Tt.value,"data-disabled-reason":Tt.value?sn.value?.reason??null:null}," Update ",10,hR)])])),nt.value&&rt.value&&bn===0&&!cn.value(lt)?(me(),_e("div",{key:3,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show more ")):ut("",!0),we.value&&rt.value&&bn===0&&!cn.value(lt)?(me(),_e("div",{key:4,class:"show-more-toggle",onClick:Jt(wt,["stop","prevent"])}," Show less ")):ut("",!0)])),on.value&&bn===0?(me(),_e(Wt,{key:2},[Oe[12]||(Oe[12]=Le("div",{class:"comment-separator"},null,-1)),Le("div",{class:"collapsed-replies",onClick:Jt(St,["stop","prevent"])},[Le("div",pR,[(me(!0),_e(Wt,null,or(We.value,an=>(me(),fn(u_,{key:an.email||an.name,user:an,class:"mini-avatar"},null,8,["user"]))),128))]),Le("span",null,Ht(Vt.value)+" more "+Ht(Vt.value===1?"reply":"replies"),1)])],64)):ut("",!0),j.value(bn)?(me(),_e("div",mR)):ut("",!0)]))),128)),L.value?(me(),_e("div",gR,[Le("span",vR,Ht(Kt.value),1),Le("button",{type:"button",class:"sd-button tracked-change-decision-alert__retry",onClick:Jt(yn,["stop","prevent"])}," Retry ")])):ut("",!0),V.value&&!Ge(S).readOnly?(me(),_e(Wt,{key:3},[K.value?(me(),_e("div",bR,[Le("div",wR,[Gt(Ky,{ref_key:"commentInput",ref:N,users:ro.value,config:Ge(S),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Le("div",CR,[Le("button",{class:"sd-button reply-btn-cancel",onClick:Jt(Wi,["stop","prevent"])},"Cancel"),Le("button",{class:en(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ft.value||Tt.value||W.value}]),onClick:Jt(Ze,["stop","prevent"]),disabled:!Ft.value||Tt.value||W.value,"data-disabled-reason":ur.value}," Reply ",10,_R)])])):(me(),_e("button",{key:0,type:"button",class:en(["reply-pill",{"sd-is-disabled":Tt.value}]),onClick:Jt(ue,["stop","prevent"]),disabled:Tt.value,"data-disabled-reason":Tt.value?sn.value?.reason??null:null}," Reply or add others with @ ",10,yR))],64)):ut("",!0)],64))],14,I7)),[[ft,Pe]])}}},gp=hn(SR,[["__scopeId","data-v-13257a67"]]);It(),gn();var kR={class:"comments-list"},AR={key:0},IR=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],ER={key:1},xR="headerFooterPart",TR={__name:"commentsList",props:{showMainComments:{type:Boolean,default:!0},showResolvedComments:{type:Boolean,default:!0}},setup(e){const t=e,n=ca(),r=$m(n,"isCommentsListVisible"),o=Se(()=>n.getGroupedComments),i=Se(()=>n.getFloatingCommentInstances),{activeComment:s,activeFloatingCommentInstanceId:a}=ea(n),l=m=>{const p=i.value.filter(g=>g?.comment?.commentId===m?.commentId);return p.length<2?[]:m?.trackedChange?m?.trackedChangeStory?.storyType!==xR?[]:p:[]},u=m=>!m?.comment?.commentId||s.value!==m.comment.commentId?!1:a.value==null?m.isPrimary===!0:String(a.value)===String(m.id),c=m=>{const p=l(m);return p.length?p.map(g=>({id:g.id,comment:m,floatingInstanceId:String(g.id),floatingPageIndex:g.pageIndex,floatingPositionEntry:g.positionEntry??null,isFloatingInstanceActive:u(g)})):[{id:m.commentId,comment:m,floatingInstanceId:null,floatingPageIndex:null,floatingPositionEntry:null,isFloatingInstanceActive:void 0}]},d=Se(()=>o.value.parentComments.flatMap(m=>c(m))),h=Se(()=>t.showResolvedComments&&o.value?.resolvedComments?.length>0);return Rn(()=>{r.value=!0}),ir(()=>{r.value=!1}),(m,p)=>(me(),_e("div",kR,[e.showMainComments?(me(),_e("div",AR,[(me(!0),_e(Wt,null,or(d.value,g=>(me(),_e("div",{key:g.id,class:"comment-item","data-comment-instance-id":g.floatingInstanceId??"","data-comment-thread-id":g.comment.commentId??"","data-comment-position-key":g.comment.trackedChangeAnchorKey??"","data-comment-page-index":Number.isFinite(g.floatingPageIndex)?g.floatingPageIndex:""},[Gt(gp,{comment:g.comment,"floating-instance-id":g.floatingInstanceId,"floating-page-index":g.floatingPageIndex,"floating-position-entry":g.floatingPositionEntry,"is-floating-instance-active":g.isFloatingInstanceActive},null,8,["comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])],8,IR))),128))])):ut("",!0),h.value?(me(),_e("div",ER,[p[0]||(p[0]=Le("div",{class:"comment-title"},"Resolved",-1)),(me(!0),_e(Wt,null,or(o.value.resolvedComments,g=>(me(),_e("div",{key:g.commentId,class:"comment-item"},[Gt(gp,{comment:g},null,8,["comment"])]))),128))])):ut("",!0)]))}},RR=hn(TR,[["__scopeId","data-v-e89dbc33"]]);It();var MR=class extends Dm.default{element;config={comments:[],element:null,commentsStore:null};constructor(e,t){super(),this.config={...this.config,...e},this.element=this.config.element,this.app=null,this.superdoc=t,this.open()}createVueApp(){this.app=Hl(RR);const e=this.superdoc?.app?._context?.provides;e&&this.app?._context?.provides&&Object.setPrototypeOf(this.app._context.provides,e),this.superdoc?.pinia&&(Dd(this.superdoc.pinia),this.app.use(this.superdoc.pinia),this.app.config.globalProperties.$pinia=this.superdoc.pinia),this.app.directive("click-outside",Fv),this.app.config.globalProperties.$superdoc=this.superdoc,!this.element&&this.config.selector&&(this.element=document.getElementById(this.config.selector)),this.container=this.app.mount(this.element)}close(){this.app&&(this.app.unmount(),this.app=null,this.container=null,this.element=null)}open(){this.app||this.createVueApp()}},LR,qa,qy=br((()=>{LR=2,qa=96/72}));It(),qy();var DR=96,PR=".superdoc__right-sidebar",OR=".sd-pdf-viewer-page";const Yy=Object.freeze({min:10,max:100,padding:0}),h_=e=>{const t=e&&typeof e=="object"?e:{},n=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a,r=n(t.min,Yy.min),o=n(t.max,Yy.max),i=typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding>=0?t.padding:Yy.padding;return{min:Math.min(r,o),max:Math.max(r,o),padding:i}},p_=(e,t)=>!(e>0)||!(t>0)?null:Math.round(e/t*100),FR=(e,t,n)=>{const r=p_(e-n.padding,t);return r===null?null:Math.max(1,Math.round(Math.min(n.max,Math.max(n.min,r))))},BR=(e,t,n)=>e>0?Number.isFinite(t)&&t>0?e/t*qa:n>0?e/n:e:null;function NR({getSuperdoc:e,superdocContainerWidth:t,isReady:n,activeZoom:r,zoomMode:o,viewportMetrics:i,showCommentsSidebar:s,rightSidebarRef:a,superdocRoot:l,documents:u}){const c=C=>{if(!C)return null;let T=0;try{const H=C.getPages?.();if(Array.isArray(H))for(const B of H){const z=B?.size?.w;typeof z=="number"&&Number.isFinite(z)&&z>T&&(T=z)}}catch{T=0}if(T>0)return T;let R=null;try{R=C.getPageStyles?.()??null}catch{R=null}const M=R?.pageSize?.width;return typeof M=="number"&&Number.isFinite(M)&&M>0?M*DR:null},d=()=>{if(!(u?.value??[]).some(R=>R?.type==="application/pdf"))return null;const C=l.value;if(!C?.querySelectorAll)return null;let T=0;for(const R of C.querySelectorAll(OR)){const M=Number(R.clientWidth)||Number(R.getBoundingClientRect?.().width)||0;let H=NaN;typeof window<"u"&&typeof window.getComputedStyle=="function"&&(H=Number.parseFloat(window.getComputedStyle(R).getPropertyValue("--scale-factor")));const B=(r.value??100)/100,z=BR(M,H,B);z!==null&&z>T&&(T=z)}return T>0?T:null},h=()=>{const C=e();if(!C)return null;const T=[],R=u?.value??[];for(const H of R){if(H?.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")continue;const B=c(H.getEditor?.());B!==null&&T.push(B)}if(T.length===0){const H=c(C.activeEditor);H!==null&&T.push(H)}const M=d();if(M!==null&&T.push(M),T.length>0)return Math.max(...T);if(C.activeEditor){const H=l.value?.querySelector?.(".superdoc__document"),B=Number(H?.clientWidth)||Number(H?.getBoundingClientRect?.().width)||0;if(B>0){const z=(r.value??100)/100;return z>0?B/z:B}}return null},m=()=>{if(!s?.value)return 0;const C=a?.value??l.value?.querySelector?.(PR),T=Number(C?.offsetWidth)||Number(C?.getBoundingClientRect?.().width)||0;return T>0?T:0},p=(C,T)=>{const R=h_(C.config?.zoom?.fitWidth),M=FR(T.availableWidth,T.documentWidth,R);M!==null&&M!==r.value&&(r.value=M,C.emit("zoomChange",{zoom:M,mode:"fit-width"}))},g=()=>{const C=e();if(!C)return;const T=t.value;if(!(T>0)||!n.value)return;const R=h();if(R===null)return;const M=T-m(),H=p_(M,R);if(H===null)return;const B=Object.freeze({availableWidth:M,documentWidth:R,fitZoom:H}),z=i.value;(!z||z.availableWidth!==M||z.documentWidth!==R||z.fitZoom!==H)&&(i.value=B),(!z||z.fitZoom!==H||Math.round(z.documentWidth)!==Math.round(R))&&C.emit("viewport-change",B),o.value==="fit-width"&&p(C,B)};Pt(t,()=>{_t(()=>g())}),Pt(n,C=>{C&&g()}),Pt(o,C=>{C==="fit-width"&&g()}),s&&Pt(s,()=>{_t(()=>g())});const k=()=>{_t(()=>g())},w=()=>{_t(()=>g())},S=()=>{_t(()=>g())},y=e();return y?.on?.("editorCreate",k),y?.on?.("pagination-update",w),y?.on?.("pdf:document-ready",S),ir(()=>{y?.off?.("editorCreate",k),y?.off?.("pagination-update",w),y?.off?.("pdf:document-ready",S)}),{evaluateViewport:g}}const zR=e=>!!e?.trackedChange,HR=e=>e,UR=(e,t,n,r=e)=>!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?!1:(Number.isFinite(r)?r:e)<t||e>n,VR=({comment:e,anchorTop:t,anchorBottom:n,viewportTop:r,viewportBottom:o})=>zR(e)&&UR(t,r,o,n),jR=({comment:e,anchorTop:t,anchorBottom:n,cardHeight:r,viewportTop:o,viewportBottom:i})=>!VR({comment:e,anchorTop:t,anchorBottom:n,viewportTop:o,viewportBottom:i})||!Number.isFinite(r)?null:(Number.isFinite(n)?n:t)<o?Math.min(t,o-r-1):t,GR=({id:e,visibleIds:t,activeCommentInstanceId:n})=>e?!!(e==="pending"||n!=null&&String(e)===String(n)||t?.has?.(e)):!1,m_=({previousIds:e,currentIds:t,removedId:n})=>{if(!Array.isArray(e)||!(t instanceof Set)||!n)return null;const r=e.indexOf(n);if(r<0)return null;for(let o=r+1;o<e.length;o+=1){const i=e[o];if(t.has(i))return i}for(let o=r-1;o>=0;o-=1){const i=e[o];if(t.has(i))return i}return null};It(),gn();var WR=["data-comment-id","data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Gl={},KR={__name:"FloatingComments",props:{currentDocument:{type:Object,required:!0},parent:{type:Object,required:!0}},setup(e){const r=(Me,Pe,Ze)=>{if(Pe>=0){Me[Pe].top=Me[Pe].anchorTop;let ot=Me[Pe].top+Me[Pe].height+Ze;for(let Et=Pe+1;Et<Me.length;Et++)Me[Et].top=Math.max(Me[Et].anchorTop,ot),ot=Me[Et].top+Me[Et].height+Ze;ot=Me[Pe].top-Ze;for(let Et=Pe-1;Et>=0;Et--){const sn=ot-Me[Et].height;Me[Et].top=Math.min(Me[Et].anchorTop,sn),ot=Me[Et].top-Ze}const Mt=Math.min(...Me.map(Et=>Et.top));if(Mt<0){const Et=Math.abs(Mt);for(const sn of Me)sn.top+=Et}}else for(let ot=1;ot<Me.length;ot++){const Mt=Me[ot-1],Et=Mt.top+Mt.height+Ze;Me[ot].top<Et&&(Me[ot].top=Et)}},o=e,i=nu(),s=ca(),{clearInstantSidebarAlignment:a}=s,{activeComment:l,activeFloatingCommentInstanceId:u,editorCommentPositions:c,pendingComment:d,editingCommentId:h,instantSidebarAlignmentTargetY:m,instantSidebarAlignmentThreadId:p,instantSidebarAlignmentInstanceId:g}=ea(s),{activeZoom:k}=ea(i),w=Se(()=>{const Me=s.getFloatingCommentInstances;if(!Array.isArray(Me))return[];const Pe=o.currentDocument?.id;return Pe==null?Me:Me.filter(Ze=>s.belongsToDocument(Ze.comment,String(Pe),{allowSingleDocumentMismatch:!0}))}),S=ne(null),y=ne(0),C=ne(0),T=ne(!1),R=ne(null),M=ne(0),H=Me=>{const Pe=d.value?.commentId;return Pe?typeof Me=="object"?Me?.commentId===Pe:Me===Pe||Me==="pending":!1},B=Me=>Me?.commentId??Me?.importedId??null,z=Se(()=>{const Me=new Map,Pe=new Map;for(const Ze of w.value){Ze?.id!=null&&Me.set(String(Ze.id),Ze);const ot=B(Ze?.comment);if(ot==null)continue;const Mt=String(ot),Et=Pe.get(Mt)??[];Et.push(Ze),Pe.set(Mt,Et)}return{byId:Me,byThreadId:Pe}}),Z=(Me,Pe=null)=>{if(Me==null)return null;const Ze=String(Me),ot=z.value.byThreadId.get(Ze)??[];if(!ot.length)return null;if(Pe!=null){const Mt=ot.find(Et=>String(Et.id)===String(Pe));if(Mt)return Mt.id}return ot.find(Mt=>Mt.isPrimary)?.id??ot[0]?.id??null},P=Se(()=>l.value?Z(l.value,u.value):null),N=Me=>{if(typeof Me=="number")return Number.isFinite(Me)?Me:null;if(typeof Me!="string"||Me.trim()==="")return null;const Pe=Number(Me);return Number.isFinite(Pe)?Pe:null},I=ne({...Gl}),L=ne(new Set),X=ne({});let te=null;const le=new Set;let fe=null;const Fe=()=>{fe==null&&(fe=requestAnimationFrame(()=>{fe=null,M.value+=1}))},he=Me=>{if(o.currentDocument.type==="application/pdf"){const Pe=(k.value??100)/100,Ze=N(Me?.comment?.selection?.selectionBounds?.top);return Ze==null?null:Ze*Pe}return Me?.positionEntry?.bounds?.top},ge=(Me,Pe)=>{if(o.currentDocument.type==="application/pdf"){const ot=(k.value??100)/100,Mt=N(Me?.comment?.selection?.selectionBounds?.bottom);return Mt!=null?Mt*ot:Pe}const Ze=Me?.positionEntry?.bounds?.bottom;return Number.isFinite(Ze)?Ze:Pe},ae=Se(()=>{const Me=[];for(const Pe of w.value){const Ze=Pe?.id,ot=B(Pe?.comment),Mt=he(Pe);if(Ze==null||ot==null||!Number.isFinite(Mt))continue;const Et=HR(Mt,Pe.comment);Me.push({id:Ze,threadId:ot,instance:Pe,top:Et,anchorBottom:ge(Pe,Et)})}return Me}),Ce=()=>{const Me=c.value.pending;if(typeof Me?.bounds?.top=="number"&&!isNaN(Me.bounds.top))return Me.bounds.top;const Pe=o.currentDocument.type==="application/pdf"?(k.value??100)/100:1,Ze=N(d.value?.selection?.selectionBounds?.top);return Ze==null?null:Ze*Pe},oe=Me=>GR({id:Me?.id,visibleIds:L.value,activeCommentInstanceId:P.value,comment:Me?.commentRef}),xe=()=>{const Me=S.value;if(!Me)return null;const Pe=Me.getBoundingClientRect();if(!Number.isFinite(Pe.top)||!Number.isFinite(window.innerHeight))return null;let Ze=0,ot=window.innerHeight;for(let Et=Me.parentElement;Et;Et=Et.parentElement){const sn=window.getComputedStyle(Et).overflowY;if(!["auto","scroll","hidden","clip"].includes(sn))continue;const Tt=Et.getBoundingClientRect();!Number.isFinite(Tt.top)||!Number.isFinite(Tt.bottom)||(Ze=Math.max(Ze,Tt.top),ot=Math.min(ot,Tt.bottom))}if(ot<=Ze)return null;const Mt=o.parent?.getBoundingClientRect?.();if(Mt&&Number.isFinite(Mt.top)&&Number.isFinite(Mt.bottom)){const Et=Math.max(Ze,Mt.top),sn=Math.min(ot,Mt.bottom);sn>Et&&(Ze=Et,ot=sn)}return{top:Ze-Pe.top,bottom:ot-Pe.top}},qe=Se(()=>p.value?Z(p.value,g.value):null),et=Se(()=>{M.value;const Me=ae.value,Pe=d.value&&d.value.fileId===o.currentDocument.id;if(!Me.length&&!w.value.length&&!Pe)return[];const Ze=[],ot=xe()??{top:0,bottom:Math.max(0,o.parent?.clientHeight||window.innerHeight||0)},Mt=ot.top-600,Et=ot.bottom+600,sn=Pe?"pending":P.value,Tt=new Set,ur=({id:$t,threadId:Vn,instance:Mr,top:_r,anchorBottom:po,hasAnchorGeometry:Kt})=>{const yn=String($t);Tt.has(yn)||(Tt.add(yn),Ze.push({id:$t,threadId:Vn,pageIndex:Mr?.pageIndex??null,anchorTop:_r,anchorBottom:po,hasAnchorGeometry:Kt,top:_r,height:I.value[$t]||110,commentRef:Mr.comment,instanceRef:Mr}))};for(const $t of Me){const{id:Vn,threadId:Mr,instance:_r,top:po,anchorBottom:Kt}=$t,yn=sn!=null&&String(Vn)===String(sn),xo=h.value!=null&&String(Mr)===String(h.value);!yn&&!xo&&(Kt<Mt||po>Et)||ur({id:Vn,threadId:Mr,instance:_r,top:po,anchorBottom:Kt,hasAnchorGeometry:!0})}const dr=[];if(sn&&sn!=="pending"){const $t=z.value.byId.get(String(sn));$t&&dr.push($t)}if(h.value!=null){const $t=z.value.byThreadId.get(String(h.value))??[],Vn=$t.find(Mr=>Mr.isPrimary)??$t[0];Vn&&dr.push(Vn)}for(const $t of dr){const Vn=$t.id,Mr=B($t.comment);Vn==null||Mr==null||Tt.has(String(Vn))||ur({id:Vn,threadId:Mr,instance:$t,top:ot.top,anchorBottom:ot.top,hasAnchorGeometry:!1})}if(Pe){const $t=Ce();typeof $t=="number"&&!isNaN($t)&&Ze.push({id:"pending",anchorTop:$t,anchorBottom:$t,hasAnchorGeometry:!0,top:$t,height:I.value.pending||110,commentRef:d.value})}Ze.sort(($t,Vn)=>$t.anchorTop-Vn.anchorTop);const jr=[];for(const $t of Ze){const Vn=$t.hasAnchorGeometry?jR({comment:$t.commentRef,anchorTop:$t.anchorTop,anchorBottom:$t.anchorBottom,cardHeight:$t.height,viewportTop:ot.top,viewportBottom:ot.bottom}):null;Vn==null?jr.push($t):$t.top=Vn}return r(jr,sn?jr.findIndex($t=>$t.id===sn):-1,15),Ze}),kt=Se(()=>(M.value,Math.max(0,o.parent?.clientHeight||0,o.parent?.scrollHeight||0))),Ie=()=>{te&&te.disconnect(),te=new IntersectionObserver(Me=>{const Pe=new Set(L.value);for(const Ze of Me){const ot=Ze.target.dataset.commentId;ot&&(Ze.isIntersecting?Pe.add(ot):Pe.delete(ot))}L.value=Pe},{rootMargin:"600px 0px 600px 0px"})},ze=()=>{if(!te)return;const Me=new Set;for(const Pe of et.value){const Ze=X.value[Pe.id];Ze&&(Me.add(Ze),le.has(Ze)||(te.observe(Ze),le.add(Ze)))}for(const Pe of le)Me.has(Pe)||(te.unobserve(Pe),le.delete(Pe))},Ve=(Me,Pe)=>{Pe<=0||Pe===I.value[Me]||(Gl[Me]=Pe,I.value={...I.value,[Me]:Pe})},Q=Me=>{if(!Me)return;const{elementRef:Pe,commentId:Ze}=Me;Pe&&_t(()=>{const ot=Pe.value?.getBoundingClientRect();!ot||ot.height<=0||Ze&&Ve(Ze,ot.height)})},_=Me=>{const Pe=Me?.id;Pe&&_t(()=>{const Ze=X.value[Pe];if(!Ze)return;const ot=Ze.querySelector(".comments-dialog");if(!ot)return;Ve(Pe,ot.getBoundingClientRect().height);const Mt=Pe===P.value,Et=Pe==="pending",sn=!!h.value&&!!l.value&&Me?.threadId!=null&&String(Me.threadId)===String(l.value);!Mt&&!Et&&!sn||(Ct(et.value.map(Tt=>Tt.id)),on(()=>et.value.map(Tt=>Tt.id)))})},$=Me=>{!Me&&R.value!=null||(T.value=Me)},F=(Me,Pe,Ze)=>{if(!Number.isFinite(Pe)){Ze?.(!1);return}const ot=X.value[Me];if(!ot){Ze?.(!1);return}const Mt=ot.getBoundingClientRect().top;C.value+=Pe-Mt,Ze?.(!0)},j=(Me,Pe)=>{if(Pe)X.value[Me]=Pe,te&&!le.has(Pe)&&(te.observe(Pe),le.add(Pe));else{const Ze=X.value[Me];Ze&&te&&(te.unobserve(Ze),le.delete(Ze)),delete X.value[Me]}};let V=[],G=null,J=[],K=null,W=!1,ue=0,be=null,we=null,Te=null,rt=null;const nt=()=>{Te=null,rt=null,R.value=null,$(!1)},wt=Me=>{if(!Te)return;const Pe=(Me?.target instanceof Element?Me.target:null)?.closest?.("[data-comment-action]"),Ze=Pe?.getAttribute?.("data-comment-action");(Ze==="resolve"||Ze==="reject")&&S.value?.contains?.(Pe)||nt()},Zt=()=>{V.forEach(clearTimeout),V=[]},Ct=Me=>{for(const Pe of Me.filter(Boolean)){const Ze=X.value[Pe];if(!Ze)continue;const ot=Ze.querySelector(".comments-dialog");ot&&Ve(Pe,ot.getBoundingClientRect().height)}},Ot=50,Bt=350,on=Me=>{Zt();const Pe=typeof Me=="function"?Me:()=>Me;V.push(setTimeout(()=>Ct(Pe()),Ot)),V.push(setTimeout(()=>Ct(Pe()),Bt))},Fn=()=>{a(),requestAnimationFrame(()=>{$(!1)})},Vt=(Me,Pe)=>{!Me||!Number.isFinite(Pe)||($(!0),_t(()=>{Ct([Me]),F(Me,Pe,()=>{Fn()})}))},We=()=>{K=null,ue+=1,be!=null&&(cancelAnimationFrame(be),be=null),$(!1)},St=()=>{if(!K||W)return;W=!0;const Me=ue;be!=null&&(cancelAnimationFrame(be),be=null),$(!0),_t(()=>{if(W=!1,Me!==ue){St();return}const{key:Pe,targetClientY:Ze}=K;Ct([Pe]),F(Pe,Ze,ot=>{if(Me===ue){if(!ot){$(!1);return}be=requestAnimationFrame(()=>{be=null,Me===ue&&$(!1)})}})})},Nt=(Me,Pe)=>{const Ze=m_({previousIds:J,currentIds:Pe,removedId:Me}),ot=(Ze?X.value[Ze]:null)?.getBoundingClientRect?.().top;return!Ze||!Number.isFinite(ot)?(We(),!1):(K={key:Ze,targetClientY:ot},ue+=1,St(),!0)},cn=Me=>{const Pe=Me?.target?.closest?.("[data-comment-action]"),Ze=Pe?.getAttribute?.("data-comment-action");if(Ze!=="resolve"&&Ze!=="reject"||(nt(),Pe.getAttribute?.("aria-disabled")==="true"))return;const ot=Pe.closest?.("[data-comment-id]")?.getAttribute?.("data-comment-id");if(!ot||String(P.value??"")===String(ot))return;const Mt=et.value.filter(Tt=>Tt.commentRef?.trackedChange).map((Tt,ur)=>({id:Tt.id,index:ur,top:Tt.top})).filter(Tt=>Number.isFinite(Tt.top)).sort((Tt,ur)=>Tt.top-ur.top||Tt.index-ur.index).map(Tt=>Tt.id),Et=m_({previousIds:Mt,currentIds:new Set(Mt),removedId:ot}),sn=(Et?X.value[Et]:null)?.getBoundingClientRect?.().top;!Et||!Number.isFinite(sn)||(Te={removedKey:ot,targetKey:Et,targetClientY:sn,applied:!1},rt=ot,R.value=Et,$(!0))};Pt(P,(Me,Pe)=>{if(Zt(),!(Te!=null&&rt!=null&&[Me,Pe].some(Mt=>Mt!=null&&String(Mt)===String(rt)))){if(rt=null,Me)nt(),We();else if(Pe){const Mt=new Set(et.value.map(Et=>Et.id));Mt.has(Pe)?We():Nt(Pe,Mt)}}const Ze=[Me,Pe],ot=Me&&Me===qe.value&&Number.isFinite(m.value);_t(()=>{if(ot){Ct(Ze);return}on(Ze)})}),Pt([P,qe,m],([Me,Pe,Ze])=>{!Me||!Pe||Me!==Pe||!Number.isFinite(Ze)||Vt(Me,Ze)}),Pt(h,()=>{Zt(),_t(()=>{on(()=>et.value.map(Me=>Me.id))})}),Pt(l,()=>{if(G&&clearTimeout(G),!l.value){if(a(),K){St();return}$(!1),C.value=0;return}if(!(H(l.value)?d.value:s.getComment(l.value)))return;const Me=H(l.value)?"pending":P.value;if(Me){if(Me===qe.value&&Number.isFinite(m.value)){$(!0);return}_t(()=>{G=setTimeout(()=>{const Ze=X.value[Me];if(!Ze)return;const ot=o.parent?.getBoundingClientRect?.();if(!ot)return;const Mt=et.value.find(ur=>ur.id===Me),Et=Me==="pending"?Ce():Mt?.anchorTop;if(typeof Et!="number"||isNaN(Et))return;const sn=Ze.getBoundingClientRect().top,Tt=ot.top+Et;C.value+=Tt-sn},400)})}}),Pt(k,()=>{if(o.currentDocument.type==="application/pdf"){for(const Me in Gl)delete Gl[Me];I.value={},y.value+=1}});let Dt=new Set,un=null,Ft=null;return Pt(et,Me=>{const Pe=P.value?Me.find(Kt=>Kt.id===P.value):null,Ze=typeof Pe?.anchorTop=="number"&&Number.isFinite(Pe.anchorTop)?Pe.anchorTop:null,ot=Ze!=null&&un!=null&&Math.abs(Ze-un)>1,Mt=typeof Pe?.top=="number"&&Number.isFinite(Pe.top)?Pe.top:null,Et=Mt!=null&&Ft!=null&&Math.abs(Mt-Ft)>1;ot&&C.value!==0&&!Number.isFinite(m.value)?(C.value=0,$(!1)):Et&&C.value!==0&&!Number.isFinite(m.value)&&!K&&($(!0),C.value+=Ft-Mt,we!=null&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{we=null,!K&&!Number.isFinite(m.value)&&$(!1)})),un=Ze,Ft=Mt;const sn=Me.map(Kt=>Kt.id),Tt=new Set(sn);if(Te&&!Te.applied&&!Tt.has(Te.removedKey)){const{targetKey:Kt,targetClientY:yn}=Te;Te.applied=!0,Tt.has(Kt)&&Number.isFinite(yn)?(K={key:Kt,targetClientY:yn},ue+=1,St()):nt()}if(Te?.applied&&!Tt.has(Te.targetKey)&&nt(),K&&!Tt.has(K.key)){const Kt=K.key;Nt(Kt,Tt)||($(!1),C.value=0)}const ur=new Set(L.value);let dr=!1,jr=-1/0,$t=1/0;const Vn=S.value;if(Vn){const Kt=Vn.getBoundingClientRect();jr=-Kt.top-600,$t=-Kt.top+window.innerHeight+600}const Mr=new Map(Me.map(Kt=>[Kt.id,Kt]));for(const Kt of Tt)if(!ur.has(Kt)){const yn=Mr.get(Kt);(!yn||yn.top>=jr&&yn.top<=$t)&&(ur.add(Kt),dr=!0)}for(const Kt of ur)Tt.has(Kt)||(ur.delete(Kt),dr=!0);dr&&(L.value=ur);for(const Kt of Dt)Tt.has(Kt)||delete Gl[Kt];const _r=Dt.size!==Tt.size||[...Dt].some(Kt=>!Tt.has(Kt)),po=J.length!==sn.length||J.some((Kt,yn)=>Kt!==sn[yn]);if(_r){const Kt={};for(const yn of Tt)Gl[yn]&&(Kt[yn]=Gl[yn]);I.value=Kt,_t(()=>{for(const yn of Me){const xo=X.value[yn.id];if(!xo)continue;const Zo=xo.querySelector(".comments-dialog");Zo&&Ve(yn.id,Zo.getBoundingClientRect().height)}})}K&&(_r||po)&&St(),Dt=Tt,_t(()=>{J=sn,ze()})}),Rn(()=>{Ie(),o.parent?.addEventListener?.("scroll",Fe,{passive:!0}),window.addEventListener("resize",Fe,{passive:!0}),document.addEventListener("pointerdown",wt,!0),_t(ze)}),ir(()=>{Zt(),G&&clearTimeout(G),nt(),We(),we!=null&&(cancelAnimationFrame(we),we=null),o.parent?.removeEventListener?.("scroll",Fe),window.removeEventListener("resize",Fe),document.removeEventListener("pointerdown",wt,!0),fe!=null&&(cancelAnimationFrame(fe),fe=null),te&&(te.disconnect(),te=null,le.clear())}),(Me,Pe)=>(me(),_e("div",{class:"section-wrapper",ref_key:"floatingCommentsContainer",ref:S,onClickCapture:cn,style:vn({minHeight:kt.value+"px",transition:T.value?"none":void 0})},[Le("div",{class:"sidebar-container",style:vn({transform:`translateY(${C.value}px)`,transition:T.value?"none":void 0})},[(me(!0),_e(Wt,null,or(et.value,Ze=>(me(),_e("div",{key:Ze.id,ref_for:!0,ref:ot=>j(Ze.id,ot),"data-comment-id":Ze.id,"data-comment-instance-id":Ze.id,"data-comment-thread-id":Ze.threadId,"data-comment-position-key":Ze.instanceRef?.positionKey??"","data-comment-page-index":Ze.pageIndex??"",class:en([{"is-direct-decision-continuity-target":Ze.id===R.value},"comment-placeholder"]),style:vn({top:Ze.top+"px",height:Ze.height+"px",transition:T.value?"none":void 0})},[oe(Ze)?(me(),fn(gp,{key:Ze.id+y.value,onReady:Q,onResize:ot=>_(Ze),class:"floating-comment",parent:e.parent,comment:Ze.commentRef,"floating-instance-id":Ze.id,"floating-page-index":Ze.pageIndex,"floating-position-entry":Ze.instanceRef?.positionEntry??null,"is-floating-instance-active":Ze.id===P.value},null,8,["onResize","parent","comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])):ut("",!0)],14,WR))),128))],4)],36))}},qR=hn(KR,[["__scopeId","data-v-b5be33eb"]]);It(),gn();var YR={class:"superdoc__pdf-comments-layer pdf-comments-layer","aria-hidden":"false"},XR=["data-id","data-comment-id","data-page-number","onClick","onKeydown"],QR="pdf",ZR="#078383",JR="#B1124B",$R={__name:"PdfCommentsLayer",emits:["anchor-activate"],setup(e,{emit:t}){const n=t,r=ca(),o=nu(),{activeComment:i}=ea(r),{documents:s,activeZoom:a}=ea(o),{proxy:l}=sr(),u=y=>typeof y=="number"?Number.isFinite(y):typeof y=="string"&&y.trim()!==""?Number.isFinite(Number(y)):!1,c=y=>!!y&&u(y.top)&&u(y.left)&&u(y.right)&&u(y.bottom),d=Se(()=>{const y=Array.isArray(s.value)?s.value:[];return new Set(y.filter(C=>C?.type===Ul).map(C=>String(C.id)))}),h=y=>{const C=y?.fileId??y?.documentId??y?.selection?.documentId;return C!=null?String(C):null},m=y=>{const C=y?.commentId??y?.importedId;return C!=null&&String(C)!==""?String(C):null},p=y=>{const C=d.value;if(!C.size)return!1;const T=h(y);return T?C.has(T):C.size===1},g=y=>{const C=Math.min(Number(y.top),Number(y.bottom)),T=Math.max(Number(y.top),Number(y.bottom));return{top:C,left:Math.min(Number(y.left),Number(y.right)),right:Math.max(Number(y.left),Number(y.right)),bottom:T}},k=Se(()=>{const y=r.getFloatingComments;return Array.isArray(y)?y.filter(C=>C?.selection?.source===QR).filter(C=>!C.resolvedTime).filter(C=>m(C)!==null).filter(C=>c(C.selection?.selectionBounds)).filter(C=>p(C)).map(C=>{const T=m(C),R=g(C.selection.selectionBounds);return{commentId:T,page:C.selection?.page??null,isInternal:C.isInternal!==!1,bounds:R}}):[]}),w=y=>{const C=(a.value??100)/100,{top:T,left:R,right:M,bottom:H}=y.bounds,B=i.value===y.commentId,z=(y.isInternal?ZR:JR)+(B?"66":"33");return{position:"absolute",top:T*C+"px",left:R*C+"px",width:(M-R)*C+"px",height:(H-T)*C+"px",backgroundColor:z}},S=y=>{r.setActiveComment(l.$superdoc,y.commentId),n("anchor-activate",y.commentId)};return(y,C)=>(me(),_e("div",YR,[(me(!0),_e(Wt,null,or(k.value,T=>(me(),_e("div",{key:T.commentId,class:"sd-comment-anchor sd-highlight",role:"button",tabindex:"0","data-id":T.commentId,"data-comment-id":T.commentId,"data-page-number":T.page,style:vn(w(T)),onClick:Jt(R=>S(T),["stop","prevent"]),onKeydown:[Yo(Jt(R=>S(T),["stop","prevent"]),["enter"]),Yo(Jt(R=>S(T),["stop","prevent"]),["space"])]},null,44,XR))),128))]))}},e9=hn($R,[["__scopeId","data-v-b5ad4c58"]]);It();const t9=({proxy:e,layers:t,documents:n,modules:r})=>{const o=Se(()=>{const z=r.value?.whiteboard??r.whiteboard;return z===!1||z==null?null:z}),i=e?.$superdoc?.whiteboard,s=Ur([]),a=zr({}),l=zr({}),u=ne(!1),c=ne(0),d=ne(0),h=ne(1),m=ne(o.value?.enabled??!1),p=()=>{if(u.value)return;c.value+=1;const z=d.value||s.value.length;z&&c.value>=z&&(u.value=!0,e?.$superdoc?.emit("whiteboard:ready",{whiteboard:i}))},g=z=>{if(!z)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&k(z)},k=z=>{const{pageIndex:Z,width:P,height:N,originalWidth:I,originalHeight:L}=z,X={width:P,height:N,originalWidth:I,originalHeight:L};i?.setPageSize(Z,X),a[Z]=X;const te=i?.getPage(Z);te&&te.setSize(X),i&&(s.value=i.getPages().sort((le,fe)=>le.pageIndex-fe.pageIndex).map(le=>Hr(le)),d.value=s.value.length),_t(()=>{H(),p()})},w=z=>{e?.$superdoc?.emit("whiteboard:change",z)},S=z=>{z.forEach(Z=>{const P=a[Z.pageIndex];P&&Z.setSize(P)}),s.value=z.map(Z=>Hr(Z)),d.value=s.value.length,_t(()=>H())},y=z=>{m.value=z,e?.$superdoc?.emit("whiteboard:enabled",z)},C=z=>{h.value=z},T=z=>{e?.$superdoc?.emit("whiteboard:tool",z)},R=()=>{const z=n.value?.[0];z&&z.type==="application/pdf"&&M({doc:z})},M=({doc:z})=>{s.value.forEach(Z=>{const P=`${z.id}-page-${Z.pageIndex+1}`,N=document.querySelector(`[data-page-id="${P}"]`);if(!N)return;const I=N.getBoundingClientRect(),L=a[Z.pageIndex]||{},X=L.originalWidth??Z.size?.originalWidth??I.width,te=L.originalHeight??Z.size?.originalHeight??I.height,le={width:I.width,height:I.height,originalWidth:X,originalHeight:te};a[Z.pageIndex]=le,Z.setSize(le)})},H=()=>{const z=t.value?.getBoundingClientRect?.();if(!z)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&B({doc:Z,layerBounds:z})},B=({doc:z,layerBounds:Z})=>{s.value.forEach(P=>{const N=`${z.id}-page-${P.pageIndex+1}`,I=document.querySelector(`[data-page-id="${N}"]`);if(!I)return;const L=I.getBoundingClientRect();l[P.pageIndex]={top:L.top-Z.top,left:L.left-Z.left}})};return i&&(i.on("change",w),i.on("setData",S),i.on("enabled",y),i.on("opacity",C),i.on("tool",T)),ir(()=>{i&&(i.off("change",w),i.off("setData",S),i.off("opacity",C),i.off("enabled",y),i.off("tool",T))}),{whiteboard:i,whiteboardModuleConfig:o,whiteboardPages:s,whiteboardPageSizes:a,whiteboardPageOffsets:l,whiteboardEnabled:m,whiteboardOpacity:h,whiteboardReady:u,handleWhiteboardPageReady:g,updateWhiteboardPageSizes:R,updateWhiteboardPageOffsets:H}};It(),gn();var n9=["data-page-index"],r9={__name:"WhiteboardPage",props:{whiteboard:{type:Object,required:!0},page:{type:Object,required:!0},pageSize:{type:Object,default:null},pageOffset:{type:Object,default:null},enabled:{type:Boolean,default:!0}},setup(e){const t=e,n=ne(null),r=()=>{const u=n.value;!u||!t.page||(t.page.mount(u),t.pageSize&&t.page.resize(t.pageSize.width,t.pageSize.height))},o=u=>{if(!t.page||!u?.dataTransfer||!t.enabled||t.whiteboard.getTool()!=="select")return;u.preventDefault(),u.stopPropagation();const c=n.value;if(!c)return;const d=c.getBoundingClientRect(),h=u.clientX-d.left,m=u.clientY-d.top,p=t.pageSize?.width,g=t.pageSize?.originalWidth??p,k=Number.isFinite(p)&&Number.isFinite(g)&&g?p/g:1;i(u,h,m,k)||s(u,h,m,k)||a(u,h,m)||l(u,h,m)},i=(u,c,d,h)=>{const m=u.dataTransfer.getData("application/sticker");if(!m)return!1;const p=(t.whiteboard.getType("stickers")||[]).find(g=>g.id===m);return p?.src?(t.page.addImage({stickerId:p.id,x:c,y:d,src:p.src,width:Number.isFinite(p.width)?p.width*h:p.width,height:Number.isFinite(p.height)?p.height*h:p.height,type:"sticker"}),!0):!1},s=(u,c,d,h)=>{const m=Array.from(u.dataTransfer.files||[]).find(g=>g.type.startsWith("image/"));if(!m)return!1;const p=new FileReader;return p.onload=()=>{typeof p.result=="string"&&t.page.addImage({x:c,y:d,src:p.result,type:"image"})},p.readAsDataURL(m),!0},a=(u,c,d)=>{const h=u.dataTransfer.getData("application/comment");if(!h)return!1;const m=(t.whiteboard.getType("comments")||[]).find(p=>p.id===h);return m?.text?(t.page.addText({x:c,y:d,content:m.text}),!0):!1},l=(u,c,d)=>{const h=u.dataTransfer.getData("text/plain");return h?(t.page.addText({x:c,y:d,content:h}),!0):!1};return Pt(()=>[t.page,t.pageSize?.width,t.pageSize?.height],()=>{_t(r)}),Rn(()=>{r()}),ir(()=>{t.page?.destroy()}),(u,c)=>(me(),_e("div",{ref_key:"containerRef",ref:n,class:"whiteboard-page","data-page-index":e.page.pageIndex,onDragover:c[0]||(c[0]=Jt(()=>{},["prevent"])),onDrop:Jt(o,["prevent"]),style:vn({width:(e.pageSize?.width??e.page.size?.width)+"px",height:(e.pageSize?.height??e.page.size?.height)+"px",transform:`translate(${e.pageOffset?.left??0}px, ${e.pageOffset?.top??0}px)`})},null,44,n9))}},o9=hn(r9,[["__scopeId","data-v-c876c9b5"]]);It(),gn();var i9={__name:"WhiteboardLayer",props:{whiteboard:{type:Object,required:!0},pages:{type:Array,default:()=>[]},pageSizes:{type:Object,default:()=>({})},pageOffsets:{type:Object,default:()=>({})},enabled:{type:Boolean,default:!0},interactive:{type:Boolean,default:null},opacity:{type:Number,default:1}},setup(e){const t=e,n=Se(()=>t.interactive==null?t.enabled:t.interactive);return(r,o)=>(me(),_e("div",{class:"whiteboard-layer","aria-hidden":"true",style:vn({opacity:e.opacity,pointerEvents:n.value?"auto":"none"})},[(me(!0),_e(Wt,null,or(e.pages,i=>(me(),fn(o9,{key:i.pageIndex,page:i,"page-size":e.pageSizes?.[i.pageIndex],"page-offset":e.pageOffsets?.[i.pageIndex],whiteboard:e.whiteboard,enabled:e.enabled},null,8,["page","page-size","page-offset","whiteboard","enabled"]))),128))],4))}},s9=hn(i9,[["__scopeId","data-v-54546c3d"]]);function a9(e){const t=e?.directionContext?.inlineDirection;if(t!=null)return t;const n=e?.paragraphProperties?.rightToLeft;if(n===!0)return"rtl";if(n===!1)return"ltr"}var g_=["#1f6feb","#d1242f","#8250df","#bf3989","#1a7f37","#9a6700","#bc4c00","#0969da","#cf222e","#6639ba","#116329","#7d4e00"];const l9=e=>e?`${typeof e.name=="string"?e.name:""} ${typeof e.email=="string"?e.email:""}`:"";var c9=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0};const u9=e=>g_[c9(l9(e))%g_.length];var Jd=e=>typeof e=="string"&&e.length>0;const d9=e=>{if(!e||e.enabled===!1)return;const t=e.overrides&&typeof e.overrides=="object"?e.overrides:void 0,n=typeof e.resolve=="function"?e.resolve:void 0;return r=>{const o=r??{};if(t){if(Jd(o.email)&&Jd(t[o.email]))return t[o.email];if(Jd(o.name)&&Jd(t[o.name]))return t[o.name]}if(n)try{const i=n(o);if(Jd(i))return i}catch{}return u9(o)}},f9=["insertion","deletion","move","move-from","move-to","table-cell-insertion","table-cell-deletion","cell-merge","cell-split","image-insertion","image-deletion","image-property-change"];var hj=new Set(f9);const mr={externalImageDeferred:"render.media.external-image-deferred",missingRelationship:"render.drawing.missing-relationship",missingMediaPart:"render.media.missing-part",unsupportedRelationshipType:"render.drawing.unsupported-relationship-type",unsupportedMime:"render.media.unsupported-mime",imageTooLarge:"render.media.image-too-large",unsafeSvg:"render.media.unsafe-svg",unsupportedFormat:"render.media.unsupported-format",embeddedObjectNotSupported:"render.embedded-object-not-supported",unsupportedObject:"render.drawing.unsupported-object",vmlUnsupported:"render.drawing.vml-unsupported",vmlImageUnsupported:"render.drawing.vml-image-unsupported",unsupportedGeometryCommand:"render.drawing.unsupported-geometry-command",anchorUnsupported:"render.drawing.anchor-unsupported",wrapUnsupported:"render.drawing.wrap-unsupported",altContentNoSupportedChoice:"render.drawing.altcontent-no-supported-choice",groupChildUnsupported:"render.drawing.group-child-unsupported"},pj={"render.media.missing-relationship":mr.missingRelationship,"render.media.wrong-relationship-type":mr.unsupportedRelationshipType,"render.media.unsupported-target":mr.unsupportedRelationshipType,"render.media.invalid-image-size":mr.imageTooLarge,"render.media-resolver-unavailable":mr.missingMediaPart,"render.chart-not-supported":mr.unsupportedObject,"render.textbox.vml-unsupported":mr.vmlUnsupported},h9={inlineBitmap:{family:"inlineBitmap",support:"supported",description:"wp:inline pic:pic with internal media and browser-safe MIME (PNG/JPEG; WebP/SVG once the host media resolver lands).",contract:"ImageRun"},anchoredBitmap:{family:"anchoredBitmap",support:"supported",description:"wp:anchor bitmap with anchor/wrap expressible by ImageAnchor/ImageWrap. Never silently inlined.",contract:"ImageBlock"},imageChildInGroup:{family:"imageChildInGroup",support:"supported",description:"Bitmap child of a supported DrawingML group/drawing wrapper. Supported only when the parent is.",contract:"ImageDrawing"},vectorShape:{family:"vectorShape",support:"supported",description:"Block/floating DrawingML preset/custom shape with the supported geometry/style subset.",contract:"DrawingBlock",drawingKind:"vectorShape"},shapeGroup:{family:"shapeGroup",support:"supported",description:"DrawingML group whose rendered children are supported vector/image children.",contract:"DrawingBlock",drawingKind:"shapeGroup"},chart:{family:"chart",support:"supported",description:"DrawingML chart projected into a ChartDrawing with parsed cached chart XML data. Complete Word chart fidelity remains deferred to chartFidelity.",contract:"DrawingBlock",drawingKind:"chart"},alternateContent:{family:"alternateContent",support:"supported",description:"mc:AlternateContent traversal/select policy. Selected Choice/Fallback maps to its family contract; unselected branches preserved for save/reopen.",contract:"selected-choice"},externalImage:{family:"externalImage",support:"fail-closed",description:'External image relationship (r:link / TargetMode="External"). Not fetched.',contract:"none",diagnostic:mr.externalImageDeferred},missingRelationship:{family:"missingRelationship",support:"fail-closed",description:"Drawing references a relationship id absent from the owner part .rels.",contract:"none",diagnostic:mr.missingRelationship},missingMediaPart:{family:"missingMediaPart",support:"fail-closed",description:"Relationship resolves but the target media part bytes are missing or empty.",contract:"none",diagnostic:mr.missingMediaPart},wrongRelationshipType:{family:"wrongRelationshipType",support:"fail-closed",description:"Relationship exists but is not an image relationship type.",contract:"none",diagnostic:mr.unsupportedRelationshipType},unsupportedMime:{family:"unsupportedMime",support:"fail-closed",description:"Media MIME outside the supported allowlist (incl. GIF/BMP/ICO).",contract:"none",diagnostic:mr.unsupportedMime},oversizedMediaPart:{family:"oversizedMediaPart",support:"fail-closed",description:"Media part exceeds the host byte-size policy before bytes are materialized.",contract:"none",diagnostic:mr.imageTooLarge},unsafeSvg:{family:"unsafeSvg",support:"fail-closed",description:"SVG content rejected by the SVG safety policy.",contract:"none",diagnostic:mr.unsafeSvg},metafileOrTiff:{family:"metafileOrTiff",support:"fail-closed",description:"EMF/WMF/TIFF and other non-browser-native formats with no approved conversion path.",contract:"none",diagnostic:mr.unsupportedFormat},embeddedObject:{family:"embeddedObject",support:"fail-closed",description:"OLE / ActiveX / embedded package object.",contract:"none",diagnostic:mr.embeddedObjectNotSupported},smartArtOrDiagram:{family:"smartArtOrDiagram",support:"fail-closed",description:"SmartArt / diagram / unknown external graphic-data object.",contract:"none",diagnostic:mr.unsupportedObject},vml:{family:"vml",support:"fail-closed",description:"VML structure outside any supported image-like subset (default fail-closed policy).",contract:"none",diagnostic:mr.vmlUnsupported},vmlImageLike:{family:"vmlImageLike",support:"fail-closed",description:"Simple VML image references (v:imagedata) / watermark image metadata. Fail-closed unless a later change promotes a named subset with deterministic fixtures and exact oracles.",contract:"none",diagnostic:mr.vmlImageUnsupported},unsupportedGeometryCommand:{family:"unsupportedGeometryCommand",support:"fail-closed",description:"Custom geometry command the extractor does not implement, e.g. arcTo.",contract:"none",diagnostic:mr.unsupportedGeometryCommand},unsupportedAnchorFields:{family:"unsupportedAnchorFields",support:"fail-closed",description:"Anchor fields required for honest placement are unsupported (char-relative, alignment modes, etc.).",contract:"none",diagnostic:mr.anchorUnsupported},unsupportedWrapFields:{family:"unsupportedWrapFields",support:"fail-closed",description:"Wrap fields required for honest placement are unsupported (arbitrary wrap polygons, etc.).",contract:"none",diagnostic:mr.wrapUnsupported},alternateContentNoSupportedChoice:{family:"alternateContentNoSupportedChoice",support:"fail-closed",description:"mc:AlternateContent with no supported choice and no usable fallback.",contract:"none",diagnostic:mr.altContentNoSupportedChoice},groupChildUnsupported:{family:"groupChildUnsupported",support:"fail-closed",description:"Unsupported child inside an otherwise-supported group. Supported siblings are not dropped.",contract:"none",diagnostic:mr.groupChildUnsupported},objectEditing:{family:"objectEditing",support:"deferred",description:"Editing/mutation of anchored/vector objects.",contract:"none"},customWrapPolygon:{family:"customWrapPolygon",support:"deferred",description:"Full Word-compatible text wrapping for arbitrary custom wrap polygons.",contract:"none"},chartFidelity:{family:"chartFidelity",support:"deferred",description:"Complete chart fidelity (a dedicated chart effort owns the parsed subset).",contract:"none"},vmlFidelity:{family:"vmlFidelity",support:"deferred",description:"Complete VML fidelity.",contract:"none"},decorativeAccessibilityUi:{family:"decorativeAccessibilityUi",support:"deferred",description:"Full accessibility UI for decorative image semantics beyond preserving source data.",contract:"none"}},mj=Object.keys(h9),gj=Object.freeze(["multiple-sections","furniture-page-tokens","non-balanceable-multi-column-sections","body-anchored-objects","footnotes","page-references","keep-constraints","tables","furniture-anchored-objects"]);It(),gn();var p9={class:"superdoc-html-viewer"},m9={class:"superdoc-html-viewer__document"},g9=["innerHTML"],v9={__name:"HtmlViewer",props:{fileSource:{type:[File,Blob],required:!0},documentId:{type:String,required:!0}},emits:["ready","selection-change"],setup(e,{emit:t}){const n=e,r=ne(""),o=t,i=()=>{const l=window.getSelection();console.debug("selection from html viewer",l),o("selection-change",l)},s=l=>new Promise((u,c)=>{const d=new FileReader;d.onload=h=>{const m=h.target.result;u(m)},d.onerror=h=>c(h),d.readAsText(l)}),a=async()=>{try{r.value=await s(n.fileSource),o("ready",n.documentId)}catch(l){o("error",l),console.error("Error loading document",l)}};return Rn(()=>{a()}),(l,u)=>(me(),_e("div",p9,[Le("div",m9,[Le("div",{class:"superdoc-html-viewer__content",innerHTML:r.value,onMouseup:i},null,40,g9)])]))}},y9=hn(v9,[["__scopeId","data-v-da3494ba"]]);const b9=(e,t,n=()=>!0)=>{const r=new Set(t.map(String)),o=new Set;e.forEach(s=>{if(!n(s))return;const a=s.commentId!=null?String(s.commentId):null,l=s.importedId!=null?String(s.importedId):null;!(a&&r.has(a))&&!(l&&r.has(l))||(a&&o.add(a),l&&o.add(l))});let i=!0;for(;i;)i=!1,e.forEach(s=>{if(!n(s))return;const a=s.commentId!=null?String(s.commentId):null,l=s.importedId!=null?String(s.importedId):null,u=s.parentCommentId!=null?String(s.parentCommentId):null,c=pp(s),d=c!=null?String(c):null,h=a&&o.has(a)||l&&o.has(l),m=u&&o.has(u)||d&&o.has(d);if(!h&&!m)return;const p=o.size;a&&o.add(a),l&&o.add(l),o.size>p&&(i=!0)});return o};It();var v_=ne(!1);function zi(){return{isHighContrastMode:v_,setHighContrastMode:t=>{v_.value=t}}}const vj="[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor",yj=320,bj=24,wj=816,Cj=250,_j="sidebar",y_=new Set(["auto","sidebar","inline"]);function w9(e){if(!e||e===!1||typeof e!="object")return e;const t={...e},n=t.displayMode;y_.has(n)||delete t.displayMode;const r=t.compactBreakpointPx;typeof r=="number"&&Number.isFinite(r)&&r>=0||delete t.compactBreakpointPx;const o=t.compactMeasurementSelector;return typeof o=="string"&&o.trim().length>0?t.compactMeasurementSelector=o.trim():delete t.compactMeasurementSelector,t}It();var C9=".superdoc__document",_9=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,S9=e=>e+320+24;function k9({commentsModuleConfig:e,superdocRoot:t,layers:n}){const r=ne(0),o=ne(!1);let i=null,s=null;const a=m=>{if(!(m instanceof HTMLElement)||(typeof window<"u"?window.getComputedStyle(m):null)?.display==="contents")return!1;const p=Number(m.clientWidth??0),g=Number(m.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0||Number.isFinite(g)&&g>0},l=()=>{const m=t.value,p=e.value?.compactMeasurementSelector;if(typeof p=="string"&&p.trim().length>0&&typeof document<"u"){const k=document.querySelector(p.trim());if(a(k))return k}let g=m?.parentElement??null;for(;g;){if(a(g))return g;g=g.parentElement}return a(m)||m instanceof HTMLElement?m:null},u=()=>{const m=typeof window<"u"?window.ResizeObserver:void 0;if(typeof m>"u")return;const p=l();p!==s&&(i&&(i.disconnect(),i=null),s=p,s&&(i=new m(()=>{h()}),i.observe(s)))},c=()=>{u();const m=Number(s?.clientWidth??0);if(Number.isFinite(m)&&m>0)return m;const p=Number(s?.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0?p:0},d=()=>{const m=t.value?.querySelector?.(C9),p=n.value,g=Number(m?.clientWidth??m?.getBoundingClientRect?.().width??0);if(Number.isFinite(g)&&g>0)return g;const k=Number(p?.clientWidth??p?.getBoundingClientRect?.().width??0);return Number.isFinite(k)&&k>0?k:816},h=()=>{const m=c(),p=e.value,g=p?.displayMode??"sidebar";if(g==="sidebar"){r.value=m,o.value=!1;return}if(g==="inline"){r.value=m,o.value=!0;return}if(!(Number.isFinite(m)&&m>0))return;r.value=m;const k=p?.compactBreakpointPx;if(_9(k)){o.value=m<k;return}o.value=m<S9(d())};return ir(()=>{i&&(i.disconnect(),i=null),s=null}),{superdocContainerWidth:r,isCompactCommentsMode:o,recalculateCompactCommentsMode:h,ensureCompactMeasurementObserver:u}}It();var b_=320,Ya=12,A9=220,I9=16,E9=500,w_=".superdoc-comment-highlight[data-comment-ids]",C_="data-comment-ids",x9=".sd-comment-anchor",Xy=(e,t,n)=>Math.min(Math.max(e,t),n),vs=e=>Number(e),Hi=e=>Number.isFinite(e),Qy=e=>e?.commentId??e?.importedId??null,__=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),T9=e=>{const t=e?.value;if(!t)return null;const n=vs(t.ts);if(!Hi(n)||Date.now()-n>E9)return null;const r=vs(t.x),o=vs(t.anchorRect?.bottom),i=Hi(o)?o:vs(t.y);return!Hi(r)||!Hi(i)?null:{x:r,y:i}},R9=({rootEl:e,comment:t,pendingComment:n})=>{if(n?.value&&t?.commentId===n.value?.commentId){const a=e.querySelectorAll(w_);for(const l of a)if(__(l.getAttribute(C_)).includes("pending")&&typeof l.getBoundingClientRect=="function")return l.getBoundingClientRect()}const r=Qy(t);if(!r)return null;const o=String(r),i=e.querySelectorAll(w_);for(const a of i)if(__(a.getAttribute(C_)).includes(o)&&typeof a.getBoundingClientRect=="function")return a.getBoundingClientRect();const s=e.querySelector(`[data-track-change-id="${o}"]`);return s&&typeof s.getBoundingClientRect=="function"?s.getBoundingClientRect():null},M9=(e,t)=>{const{entry:n}=e(Qy(t)),r=vs(n?.bounds?.bottom);return Hi(r)?r:vs(n?.bounds?.top)},L9=({selectionPosition:e,comment:t,pendingComment:n})=>e.value?.source==="pdf"||t?.selection?.source==="pdf"||n.value?.selection?.source==="pdf",D9=({rootEl:e,layersRect:t,comment:n})=>{const r=Qy(n);if(r==null)return NaN;const o=e.querySelector(`${x9}[data-id="${String(r)}"]`);return!o||typeof o.getBoundingClientRect!="function"?NaN:vs(o.getBoundingClientRect().bottom)-vs(t.top)},P9=({comment:e,pendingComment:t,selectionPosition:n,activeZoom:r})=>{if(!t.value||e?.commentId!==t.value?.commentId)return NaN;const o=vs(n.value?.bottom);if(Hi(o))return o*(n.value?.source==="pdf"?(r.value??100)/100:1);const i=vs(n.value?.top);return Hi(i)?i*(n.value?.source==="pdf"?(r.value??100)/100:1):NaN},O9=({top:e,left:t})=>({top:`${Math.round(e)}px`,left:`${Math.round(t)}px`,right:"auto"}),F9=({rootRect:e,layersRect:t,anchorBottom:n,anchorClientX:r=NaN})=>{const o=Xy(t.top-e.top+n+I9,Ya,Math.max(Ya,e.height-A9)),i=Math.max(Ya,e.width-b_-Ya);let s;if(Hi(r))s=Xy(r-e.left+Ya,Ya,i);else{const a=e.width-(t.left-e.left+t.width)+Ya;s=Xy(e.width-a-b_,Ya,i)}return{top:o,left:s}};function B9({activeComment:e,pendingComment:t,activeCompactComment:n,showCommentsSidebar:r,selectionPosition:o,activeZoom:i,superdocRoot:s,layers:a,documents:l,resolveCommentPositionEntry:u,clearActiveComment:c,clearPendingComment:d}){const h={top:"12px",right:"12px"},m=ne(0),p=ne({x:null,y:null,ts:0,anchorRect:null});let g=null,k=null;const w=()=>{p.value={x:null,y:null,ts:0,anchorRect:null}},S=(R,M,H)=>{if(!l.value?.some(z=>z.type==="application/pdf"))return!1;const B=R.querySelector(".superdoc__compact-comment-popover");return!n.value||!B||B.contains(M)||H?!1:(t.value&&d(),c(),w(),!0)},y=R=>{const M=s.value;if(!M||!a.value?.contains(R.target))return;const H=(typeof document.elementsFromPoint=="function"?document.elementsFromPoint(R.clientX,R.clientY):[]).find(z=>z?.nodeType===1&&M.contains(z)&&z.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"))?.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor")??(R.target?.nodeType===1?R.target.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"):null);if(S(M,R.target,H)||R.button!==0||R.pointerType!=="mouse")return;const B=H&&typeof H.getBoundingClientRect=="function"?H.getBoundingClientRect():null;B&&(p.value={x:R.clientX,y:B.bottom,ts:Date.now(),anchorRect:{left:B.left,right:B.right,top:B.top,bottom:B.bottom}})},C=Se(()=>{m.value;const R=n.value;if(!R)return h;const M=s.value,H=a.value;if(!M||!H)return h;const B=M.getBoundingClientRect(),z=H.getBoundingClientRect(),Z=T9(p),P=Z?null:R9({rootEl:M,comment:R,pendingComment:t});let N=NaN,I=NaN;return Z?(N=Z.y-z.top,I=Z.x):P?(N=P.bottom-z.top,I=P.left):N=M9(u,R),!Hi(N)&&L9({selectionPosition:o,comment:R,pendingComment:t})&&(N=D9({rootEl:M,layersRect:z,comment:R})),Hi(N)||(N=P9({comment:R,pendingComment:t,selectionPosition:o,activeZoom:i})),Hi(N)?O9(F9({rootRect:B,layersRect:z,anchorBottom:N,anchorClientX:I})):h});return Pt([e,t,o,i,r,p],()=>{const R=typeof window<"u"?window.requestAnimationFrame:null,M=typeof window<"u"?window.cancelAnimationFrame:null;g!=null&&M?.(g),R&&(g=R(()=>{m.value+=1,g=null}))},{deep:!1}),Pt(n,(R,M)=>{if(!M&&R){const H=document.activeElement;H instanceof HTMLElement&&(k=H)}},{deep:!1}),Pt(t,(R,M)=>{!M&&R&&w()}),Rn(()=>{document.addEventListener("pointerdown",y,!0)}),ir(()=>{document.removeEventListener("pointerdown",y,!0);const R=typeof window<"u"?window.cancelAnimationFrame:null;g!=null&&(R?.(g),g=null),k=null}),{compactCommentPopoverStyle:C,closeCompactCommentPopover:()=>{n.value&&(t.value&&d(),c(),k&&typeof k.focus=="function"&&k.focus(),k=null)},resetClickAnchor:w}}function S_(e){if(e?.type!=="mutation:committed")return null;const t=e.origin==="history"?e.result:e.receipt;if(!t||typeof t!="object")return null;const n=new Set,r=new Set,o=(i,s)=>{i?.kind!=="entity"||i.entityType!=="trackedChange"||typeof i.entityId=="string"&&i.entityId.length>0&&s.add(i.entityId)};if(Array.isArray(t.inserted)&&t.inserted.forEach(i=>o(i,n)),Array.isArray(t.updated)&&t.updated.forEach(i=>o(i,n)),Array.isArray(t.trackedChangeRefs)&&t.trackedChangeRefs.forEach(i=>o(i,n)),Array.isArray(t.removed)&&t.removed.forEach(i=>o(i,r)),Array.isArray(t.invalidatedRefs)&&t.invalidatedRefs.forEach(i=>o(i,r)),Array.isArray(t.remappedRefs))for(const i of t.remappedRefs)o(i?.from,r),o(i?.to,n);for(const i of r)n.delete(i);return n.size===0&&r.size===0?null:{upsertIds:n,removedIds:r,reconcileMode:e.origin==="history"?"authoritative":"targeted"}}var $d=e=>new Set(Array.from(e??[]).filter(t=>typeof t=="string"&&t.length>0)),N9=e=>typeof e?.id=="string"&&e.id.length>0?e.id:typeof e?.changeId=="string"&&e.changeId.length>0?e.changeId:typeof e?.address?.entityId=="string"&&e.address.entityId.length>0?e.address.entityId:null,z9=(e,t)=>e?.adapter===t?.adapter&&e?.documentId===t?.documentId&&e?.editor===t?.editor&&e?.reconcileToken===t?.reconcileToken;function k_({getContext:e,reconcile:t,hydrate:n,onReconciled:r}){const o=new Map;let i=0,s=0,a=null,l=!1;const u=(R,M)=>s===R&&z9(M,e()),c=(R,M)=>{const H=new Set;for(const B of R)o.get(B)===M.get(B)&&(o.delete(B),H.add(B));return H},d=R=>new Map([...o].filter(([,M])=>M.ready===!0&&M.reconcileMode===R)),h=()=>{let R=!1;for(const M of o.values())M.gate!=="render"||M.ready||(M.ready=!0,R=!0);return R},m=R=>{let M=!1;for(const H of o.values())H.version>R||H.ready||(H.ready=!0,M=!0);return M},p=async(R,M,H,B=!1)=>{if(!(!B&&M.size===0||typeof r!="function"))try{await r(R,M,H)}catch{}},g=R=>$d(R?.resolvedIds??(R?.items??[]).map(N9).filter(Boolean)),k=async(R,M,H)=>{const B=await t(R,{upsertIds:new Set(M.keys()),removedIds:new Set,reconcileMode:"targeted"});if(!u(H,R)||(await p(R,c(g(B),M),B),new Set([...M].filter(([Z,P])=>o.get(Z)===P).map(([Z])=>Z)).size===0))return;const z=await n(R,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1});u(H,R)&&await p(R,c(g(z),M),z)},w=async(R,M,H)=>{const B=await n(R,{trackedChangesListMode:"all",refreshReason:"mutation-history-render-reconcile",blocking:!0});if(!u(H,R)||![...M].some(([I,L])=>o.get(I)===L))return;const z=B?.ok===!0,Z=z&&B?.complete===!0&&B?.sourceCoverageComplete===!0,P=z?g(B):new Set,N=Z?c(new Set(M.keys()),M):new Set;await p(R,Z?N:P,{...B,reconcileMode:"authoritative"},!0)},S=()=>{if(a)return a;const R=d("targeted"),M=d("authoritative");if(R.size===0&&M.size===0)return null;const H=e();if(!H?.adapter)return null;l=!1;const B=s;return a=Promise.resolve().then(async()=>{M.size>0&&await w(H,M,B).catch(()=>{}),R.size>0&&await k(H,R,B).catch(()=>{})}).catch(()=>{}).finally(()=>{a=null,l&&S()}),a},y=(R,M)=>{if(!R)return;const H=R.reconcileMode==="authoritative"?"authoritative":"targeted",B=$d(R.removedIds);for(const Z of B){const P=o.get(Z);P?.reconcileMode==="authoritative"?o.set(Z,{...P,version:++i,gate:M,ready:!1}):o.delete(Z)}const z=e();if(B.size>0&&z?.adapter)try{Promise.resolve(t(z,{upsertIds:new Set,removedIds:B})).catch(()=>{})}catch{}for(const Z of $d(R.upsertIds))if(!B.has(Z)){const P=o.get(Z);o.set(Z,{version:++i,gate:M,ready:!1,reconcileMode:H==="authoritative"||P?.reconcileMode==="authoritative"?"authoritative":"targeted"})}},C=R=>y(R,"render");return{enqueue:C,enqueueAfterPaint(R,M){if(!R||typeof M!="function"){C(R);return}y(R,"exact-paint");const H=e();if(!H?.adapter)return;const B=s,z=i,Z=new Set([...$d(R.upsertIds),...$d(R.removedIds)]),P=new Map([...Z].flatMap(N=>{const I=o.get(N);return I?[[N,I]]:[]}));Promise.resolve().then(()=>M()).then(()=>{if(!u(B,H))return;let N=h();m(z)&&(N=!0);for(const[I,L]of P)o.get(I)===L&&(L.ready||(N=!0),L.ready=!0);a&&(N||z>0)&&(l=!0),S()}).catch(()=>{if(u(B,H))for(const[N,I]of P)o.get(N)===I&&(I.gate="render")})},onRender:(R=!1)=>{const M=h();a&&(M||R)&&(l=!0),S()},reset(){s+=1,o.clear(),l=!1},getPendingIds(){return new Set(o.keys())}}}function H9(e,t){if(!e||typeof e.entityId!="string"||e.entityType!=="comment"&&e.entityType!=="trackedChange")return null;const n=typeof t=="function"?t(e.entityId):null,r=n?.commentId??n?.importedId??e.entityId;return r!=null?String(r):null}var U9=new Set(["insert-text","replace-text","plain-text-paste","delete-backward","delete-forward","text.insert","text.replace","text.pastePlain","text.deleteBackward","text.deleteForward","structural.enter","structural:enter-split-paragraph","structural:enter-insert-paragraph-before","structural:enter-insert-paragraph-after","structural:shift-enter-line-break","structural:backspace-boundary-merge-with-previous","structural:delete-boundary-merge-with-next","backspace:boundary-merge-with-previous","backspace:list-remove","backspace:list-outdent"]);const A_=e=>e?.type!=="mutation:committed"||e.origin!=="command"?!1:U9.has(e.editableCommandKind);function I_(e){return e==null?null:String(e)}function V9({hydrate:e,getActiveDocumentId:t,debounceMs:n=250,ceilingMs:r=1e3,now:o=()=>Date.now(),setTimer:i=(a,l)=>setTimeout(a,l),clearTimer:s=a=>clearTimeout(a)}){let a=null,l=null,u=null;const c=m=>I_(t())===m,d=()=>{a!=null&&s(a),a=null,l=null,u=null};return{schedule:m=>{const p=I_(m);if(!c(p))return!1;u!==p&&d();const g=o();u=p,l??=g,a!=null&&s(a);const k=Math.max(0,r-(g-l));return a=i(()=>{const w=u;a=null,l=null,u=null,c(w)&&e()},Math.min(n,k)),!0},clear:d}}var j9="no-author-configured";const G9="author-required",E_="This edit needs an author identity. Set `user.name` in your SuperDoc configuration and reopen the document to make tracked or revision-overlapping edits.";function x_(e){return typeof e=="string"&&e.includes(j9)}function W9(e){if(!e||e.type!=="mutation:rejected")return!1;if(e.failureSource==="receipt"){const t=e.failure;return t?t.code==="PRECONDITION_FAILED"&&x_(t.message):!1}return e.failureSource==="shell"?e.reason==="author-required"?!0:e.reason==="PRECONDITION_FAILED"&&x_(e.message):!1}function K9(){const e=new Set,t=n=>typeof n=="string"&&n.length>0?n:"__default__";return{shouldNotify(n,r){if(!W9(r))return!1;const o=t(n);return e.has(o)?!1:(e.add(o),!0)},clear(n){e.delete(t(n))}}}const q9=e=>!!(e?.anchor&&e?.focus&&(e.anchor.blockId!==e.focus.blockId||e.anchor.blockOffset!==e.focus.blockOffset)),Y9=(e,t)=>{if(!e||e.rangeCount<1||e.isCollapsed||!t)return!1;const n=e.getRangeAt(0);return!t.contains(n.startContainer)&&!t.contains(n.endContainer)},X9=(e,t)=>e!=="editing"&&e!=="suggesting"?!1:q9(t);var Q9=br((()=>{})),Z9=Gu({default:()=>z_},1),T_,R_,M_,L_,D_,P_,O_,F_,B_,N_,z_,J9=br((()=>{It(),Q9(),gn(),T_=["onKeydown"],R_=["id"],M_={class:"sd-password-prompt__description"},L_={class:"sd-password-prompt__field"},D_=["placeholder","disabled","aria-label"],P_={key:0,class:"sd-password-prompt__error",role:"alert"},O_={class:"sd-password-prompt__actions"},F_=["disabled"],B_=["disabled"],N_={__name:"PasswordPromptSurface",props:{surfaceId:{type:String,default:""},mode:{type:String,default:"dialog"},request:{type:Object,default:()=>({})},resolve:{type:Function,default:()=>{}},close:{type:Function,default:()=>{}},passwordPrompt:{type:Object,required:!0}},setup(e){const t=e,n=ne(""),r=ne(!1),o=ne(t.passwordPrompt.errorCode==="DOCX_PASSWORD_INVALID"),i=ne(o.value?t.passwordPrompt.texts.invalidMessage:""),s=Se(()=>o.value?t.passwordPrompt.texts.invalidTitle:t.passwordPrompt.texts.title),a=Se(()=>n.value.length>0&&!r.value);async function l(){if(!a.value)return;r.value=!0,i.value="";const c=await t.passwordPrompt.attemptPassword(n.value);if(c.success){t.resolve({password:n.value});return}r.value=!1,n.value="",c.errorCode==="DOCX_PASSWORD_INVALID"?(o.value=!0,i.value=t.passwordPrompt.texts.invalidMessage):c.errorCode==="timeout"?i.value=t.passwordPrompt.texts.timeoutMessage:i.value=t.passwordPrompt.texts.genericErrorMessage}function u(){t.close("user-cancelled")}return(c,d)=>(me(),_e("div",{class:"sd-password-prompt",onKeydown:Yo(Jt(l,["prevent"]),["enter"])},[Le("h3",{id:`sd-password-prompt-heading-${e.surfaceId}`,class:"sd-password-prompt__heading"},Ht(s.value),9,R_),Le("p",M_,Ht(e.passwordPrompt.texts.description),1),Le("div",L_,[Ws(Le("input",{"onUpdate:modelValue":d[0]||(d[0]=h=>n.value=h),type:"password",class:"sd-password-prompt__input",placeholder:e.passwordPrompt.texts.placeholder,disabled:r.value,autocomplete:"current-password","aria-label":e.passwordPrompt.texts.inputAriaLabel},null,8,D_),[[ki,n.value]])]),i.value?(me(),_e("p",P_,Ht(i.value),1)):ut("",!0),Le("div",O_,[Le("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--cancel",disabled:r.value,onClick:u},Ht(e.passwordPrompt.texts.cancelLabel),9,F_),Le("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--submit",disabled:!a.value,onClick:l},Ht(r.value?e.passwordPrompt.texts.busyLabel:e.passwordPrompt.texts.submitLabel),9,B_)])],40,T_))}},z_=hn(N_,[["__scopeId","data-v-ecf7f6fb"]])}));It();var $9=["DOCX_PASSWORD_REQUIRED","DOCX_PASSWORD_INVALID"],eM=3e4,Ai={title:"Password Required",invalidTitle:"Incorrect Password",description:"This document is password protected. Enter the password to open it.",placeholder:"Enter password",inputAriaLabel:"Document password",submitLabel:"Open",cancelLabel:"Cancel",busyLabel:"Decrypting…",invalidMessage:"Incorrect password. Please try again.",timeoutMessage:"Timed out while decrypting. Please try again.",genericErrorMessage:"Unable to decrypt this document."};function tM({getSurfaceManager:e,getPasswordPromptConfig:t,onUnhandled:n}){const r=[],o=Ur(null),i=new Map;let s=!1;function a(p,g,k){if(!p||!$9.includes(g)||t()===!1||!e())return!1;const w=i.get(p.id);if(w)return clearTimeout(w.timer),w.resolve({success:!1,errorCode:g}),i.delete(p.id),!0;const S=r.find(y=>y.doc.id===p.id);return S?(S.errorCode=g,S.originalException=k,!0):(o.value?.doc.id===p.id||(r.push({doc:p,errorCode:g,originalException:k}),c()),!0)}function l(p){if(!p)return;const g=i.get(p.id);g&&(clearTimeout(g.timer),g.resolve({success:!0}),i.delete(p.id))}function u(){s=!0;for(const[,p]of i)clearTimeout(p.timer),p.resolve({success:!1,errorCode:"destroyed"});i.clear(),r.length=0,o.value=null}function c(){if(s||o.value||r.length===0)return;const p=r.shift();p&&d(p).catch(g=>{o.value=null,console.error("[SuperDoc] Password prompt error:",g),n?.(p.doc,p.errorCode,p.originalException),c()})}async function d({doc:p,errorCode:g,originalException:k}){const w=e();if(!w||s)return;const S=h(),y=M=>(p.password=M,p.editorMountNonce++,new Promise(H=>{const B=setTimeout(()=>{i.delete(p.id),H({success:!1,errorCode:"timeout"})},eM);i.set(p.id,{resolve:H,timer:B})})),C={documentId:p.id,errorCode:g,texts:S.texts,attemptPassword:y},T=m(S,{documentId:p.id,errorCode:g,texts:S.texts});if(T.suppressed){n?.(p,g,k),c();return}o.value={doc:p,surfaceHandle:null};let R;if(T.component)R=w.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:S.texts.title,component:Hr(T.component),props:{...T.props,passwordPrompt:C}});else if(T.render){const M=T.render;R=w.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:S.texts.title,render:H=>M({container:H.container,passwordPrompt:C,resolve:H.resolve,close:H.close,surfaceId:H.surfaceId,mode:H.mode})})}else{const M=(await Promise.resolve().then(()=>(J9(),Z9))).default,H=`password-prompt-${p.id}`;R=w.open({id:H,mode:"dialog",closeOnBackdrop:!1,ariaLabelledBy:`sd-password-prompt-heading-${H}`,component:Hr(M),props:{passwordPrompt:C}})}o.value={doc:p,surfaceHandle:R},await R.result,o.value=null,c()}function h(){const p=t();if(p===!1)return{enabled:!1,texts:Ai};const g=typeof p=="object"&&p!==null?p:{};if(g.component!=null&&typeof g.render=="function")throw new Error('modules.surfaces.passwordPrompt cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{title:g.title??Ai.title,invalidTitle:g.invalidTitle??Ai.invalidTitle,description:g.description??Ai.description,placeholder:g.placeholder??Ai.placeholder,inputAriaLabel:g.inputAriaLabel??Ai.inputAriaLabel,submitLabel:g.submitLabel??Ai.submitLabel,cancelLabel:g.cancelLabel??Ai.cancelLabel,busyLabel:g.busyLabel??Ai.busyLabel,invalidMessage:g.invalidMessage??Ai.invalidMessage,timeoutMessage:g.timeoutMessage??Ai.timeoutMessage,genericErrorMessage:g.genericErrorMessage??Ai.genericErrorMessage},component:g.component,props:g.props,render:g.render,resolver:g.resolver}}function m(p,g){if(typeof p.resolver=="function"){const k=p.resolver(g);if(k!=null&&k.type!=="default"){if(k.type==="none")return{suppressed:!0};if(k.type==="custom")return{component:k.component,props:k.props};if(k.type==="external")return{render:k.render}}}return p.component!=null?{component:p.component,props:p.props}:typeof p.render=="function"?{render:p.render}:{builtin:!0}}return{handleEncryptionError:a,handleEditorReady:l,destroy:u}}function H_(e,{getCurrentSession:t,applySlice:n,onSettled:r}){return()=>{if(e===t())try{n(e.getSnapshot())}catch{}r()}}var nM=br((()=>{})),rM=Gu({default:()=>cS},1),U_,V_,j_,G_,W_,K_,q_,Y_,X_,Q_,Z_,J_,$_,eS,tS,nS,rS,oS,iS,sS,aS,lS,cS,oM=br((()=>{It(),nM(),gn(),U_=["onKeydown"],V_={class:"sd-find-replace__row"},j_=["title","aria-label","aria-expanded"],G_=["value","placeholder","aria-label"],W_={key:0,class:"sd-find-replace__count"},K_=["title","aria-label","aria-pressed"],q_=["title","aria-label","aria-pressed"],Y_=["title","aria-label","aria-pressed"],X_={class:"sd-find-replace__nav"},Q_=["disabled","title","aria-label"],Z_=["disabled","title","aria-label"],J_=["title","aria-label"],$_={key:0,class:"sd-find-replace__row"},eS={class:"sd-find-replace__field"},tS=["value","placeholder","aria-label"],nS={class:"sd-find-replace__nav sd-find-replace__nav--actions"},rS=["disabled","title"],oS=["disabled","title"],iS={key:1,class:"sd-find-replace__error",role:"alert"},sS={key:0,class:"sd-find-replace__row-indent","aria-hidden":"true"},aS={class:"sd-find-replace__error-text"},lS={__name:"FindReplaceSurface",props:{surfaceId:{type:String,default:""},mode:{type:String,default:"floating"},request:{type:Object,default:()=>({})},resolve:{type:Function,default:()=>{}},close:{type:Function,default:()=>{}},findReplace:{type:Object,required:!0}},setup(e){const t=e,n=ne(null),r=Se(()=>{const p=t.findReplace;return!!(!p.hasMatches?.value||p.replacePending?.value===!0||p.canReplace&&p.canReplace.value===!1)}),o=Se(()=>t.findReplace.ignoreDiacriticsSupported?.value!==!1),i=Se(()=>t.findReplace.replaceEnabled&&t.findReplace.replaceCanMutate?.value!==!1),s=Se(()=>t.findReplace.regexSupported?.value===!0),a=Se(()=>t.findReplace.searchError?.value??null);function l(p){p.key==="Enter"&&!p.shiftKey?(p.preventDefault(),u()):p.key==="Enter"&&p.shiftKey&&(p.preventDefault(),c())}function u(){t.findReplace.goNext(),m()}function c(){t.findReplace.goPrev(),m()}function d(){t.findReplace.close("user-closed")}function h(p){const g=[];let k=p?.parentElement??null;for(;k;){const S=k.ownerDocument?.defaultView?.getComputedStyle?.(k);if(S){const y=`${S.overflowY} ${S.overflowX}`;(y.includes("auto")||y.includes("scroll"))&&g.push(k)}k=k.parentElement}const w=p?.ownerDocument?.scrollingElement;return w&&!g.includes(w)&&g.push(w),g}function m(){const p=n.value;if(!p)return;const g=h(p).map(k=>({el:k,top:k.scrollTop,left:k.scrollLeft}));p.focus({preventScroll:!0});for(const{el:k,top:w,left:S}of g)k.scrollTop!==w&&(k.scrollTop=w),k.scrollLeft!==S&&(k.scrollLeft=S)}return Rn(()=>{n.value?.focus(),t.findReplace.registerFocusFn(m)}),(p,g)=>(me(),_e("div",{class:"sd-find-replace",onKeydown:Yo(Jt(d,["stop"]),["esc"])},[Le("div",V_,[i.value?(me(),_e("button",{key:0,type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--expander",{"sd-find-replace__btn--expander-open":e.findReplace.showReplace.value}]),title:e.findReplace.texts.toggleReplaceLabel,"aria-label":e.findReplace.texts.toggleReplaceAriaLabel,"aria-expanded":e.findReplace.showReplace.value?"true":"false",onClick:g[0]||(g[0]=k=>e.findReplace.showReplace.value=!e.findReplace.showReplace.value)},[...g[14]||(g[14]=[Le("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true"},[Le("path",{d:"M6 3.5 10.5 8 6 12.5",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"})],-1)])],10,j_)):ut("",!0),Le("div",{class:en(["sd-find-replace__field",{"sd-find-replace__field--error":a.value}])},[g[15]||(g[15]=Le("svg",{class:"sd-find-replace__search-icon",viewBox:"0 0 16 16",width:"15",height:"15","aria-hidden":"true"},[Le("path",{d:"M7 1a6 6 0 1 0 3.7 10.7l3.3 3.3 1-1-3.3-3.3A6 6 0 0 0 7 1Zm0 1.5a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Z",fill:"currentColor"})],-1)),Le("input",{ref_key:"findInputRef",ref:n,value:e.findReplace.findQuery.value,onInput:g[1]||(g[1]=k=>e.findReplace.findQuery.value=k.target.value),type:"text",class:"sd-find-replace__input sd-find-replace__input--search","data-sd-autofocus":"",placeholder:e.findReplace.texts.findPlaceholder,"aria-label":e.findReplace.texts.findAriaLabel,onKeydown:l},null,40,G_),e.findReplace.findQuery.value&&!a.value?(me(),_e("span",W_,Ht(e.findReplace.matchLabel.value),1)):ut("",!0),Le("button",{type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--toggle",{"sd-find-replace__btn--active":e.findReplace.caseSensitive.value}]),title:e.findReplace.texts.matchCaseAriaLabel,"aria-label":e.findReplace.texts.matchCaseAriaLabel,"aria-pressed":e.findReplace.caseSensitive.value?"true":"false",onMousedown:g[2]||(g[2]=Jt(()=>{},["prevent"])),onClick:g[3]||(g[3]=k=>e.findReplace.caseSensitive.value=!e.findReplace.caseSensitive.value)},Ht(e.findReplace.texts.matchCaseLabel),43,K_),o.value?(me(),_e("button",{key:1,type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--toggle",{"sd-find-replace__btn--active":e.findReplace.ignoreDiacritics.value}]),title:e.findReplace.texts.ignoreDiacriticsAriaLabel,"aria-label":e.findReplace.texts.ignoreDiacriticsAriaLabel,"aria-pressed":e.findReplace.ignoreDiacritics.value?"true":"false",onMousedown:g[4]||(g[4]=Jt(()=>{},["prevent"])),onClick:g[5]||(g[5]=k=>e.findReplace.ignoreDiacritics.value=!e.findReplace.ignoreDiacritics.value)},Ht(e.findReplace.texts.ignoreDiacriticsLabel),43,q_)):ut("",!0),s.value?(me(),_e("button",{key:2,type:"button",class:en(["sd-find-replace__btn sd-find-replace__btn--toggle",{"sd-find-replace__btn--active":e.findReplace.regex.value}]),title:e.findReplace.texts.regexAriaLabel,"aria-label":e.findReplace.texts.regexAriaLabel,"aria-pressed":e.findReplace.regex.value?"true":"false",onMousedown:g[6]||(g[6]=Jt(()=>{},["prevent"])),onClick:g[7]||(g[7]=k=>e.findReplace.regex.value=!e.findReplace.regex.value)},Ht(e.findReplace.texts.regexLabel),43,Y_)):ut("",!0)],2),Le("div",X_,[Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--icon",disabled:!e.findReplace.hasMatches.value,title:e.findReplace.texts.previousMatchLabel,"aria-label":e.findReplace.texts.previousMatchAriaLabel,onClick:g[8]||(g[8]=k=>c())},[...g[16]||(g[16]=[Le("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Le("path",{d:"M10 3.5 5.5 8 10 12.5",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"})],-1)])],8,Q_),Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--icon",disabled:!e.findReplace.hasMatches.value,title:e.findReplace.texts.nextMatchLabel,"aria-label":e.findReplace.texts.nextMatchAriaLabel,onClick:g[9]||(g[9]=k=>u())},[...g[17]||(g[17]=[Le("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Le("path",{d:"M6 3.5 10.5 8 6 12.5",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"})],-1)])],8,Z_),g[19]||(g[19]=Le("span",{class:"sd-find-replace__divider","aria-hidden":"true"},null,-1)),Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--icon",title:e.findReplace.texts.closeLabel,"aria-label":e.findReplace.texts.closeAriaLabel,onClick:d},[...g[18]||(g[18]=[Le("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Le("path",{d:"m4.5 4.5 7 7m0-7-7 7",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,J_)])]),e.findReplace.showReplace.value&&i.value?(me(),_e("div",$_,[g[20]||(g[20]=Le("span",{class:"sd-find-replace__row-indent","aria-hidden":"true"},null,-1)),Le("div",eS,[Le("input",{value:e.findReplace.replaceText.value,onInput:g[10]||(g[10]=k=>e.findReplace.replaceText.value=k.target.value),type:"text",class:"sd-find-replace__input",placeholder:e.findReplace.texts.replacePlaceholder,"aria-label":e.findReplace.texts.replaceAriaLabel,onKeydown:g[11]||(g[11]=Yo(Jt(k=>e.findReplace.replaceCurrent(),["prevent"]),["enter"]))},null,40,tS)]),Le("div",nS,[Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceLabel,onClick:g[12]||(g[12]=k=>e.findReplace.replaceCurrent())},Ht(e.findReplace.texts.replaceLabel),9,rS),Le("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceAllLabel,onClick:g[13]||(g[13]=k=>e.findReplace.replaceAll())},Ht(e.findReplace.texts.replaceAllLabel),9,oS)])])):ut("",!0),a.value?(me(),_e("div",iS,[i.value?(me(),_e("span",sS)):ut("",!0),Le("span",aS,Ht(a.value),1)])):ut("",!0)],40,U_))}},cS=hn(lS,[["__scopeId","data-v-fed15bd3"]])}));It();var lr={findPlaceholder:"Find",findAriaLabel:"Find text",replacePlaceholder:"Replace",replaceAriaLabel:"Replace text",noResultsLabel:"No results",previousMatchLabel:"Previous match (Shift+Enter)",previousMatchAriaLabel:"Previous match",nextMatchLabel:"Next match (Enter)",nextMatchAriaLabel:"Next match",closeLabel:"Close (Escape)",closeAriaLabel:"Close find and replace",replaceLabel:"Replace",replaceAllLabel:"All",toggleReplaceLabel:"Toggle replace",toggleReplaceAriaLabel:"Toggle replace",matchCaseLabel:"Aa",matchCaseAriaLabel:"Match case",regexLabel:".*",regexAriaLabel:"Use regular expression",invalidPatternLabel:"Invalid pattern",ignoreDiacriticsLabel:"ä≡a",ignoreDiacriticsAriaLabel:"Ignore diacritics"};function iM(e){if(!e)return null;const t=e.extensionStorage,n=e.storage,r=t?.Search??n?.Search;if(r?.searchIndex||r?.searchResults)return r;const o=e.extensionStorage??e.storage;if(o)for(const i of Object.keys(o)){const s=o[i];if(s&&typeof s=="object"&&"searchIndex"in s&&"searchResults"in s)return s}return null}function sM({getSurfaceManager:e,getActiveEditor:t,activeEditorRef:n,getFindReplaceConfig:r,getSuperDocUI:o}){let i=null,s=null,a=null,l=!1,u=!1;const c=ne(!1);let d=null;const h=ne(""),m=ne(""),p=ne(!1),g=ne(!1),k=ne(!1),w=ne(!1),S=ne(0),y=ne(-1),C=ne(!0),T=ne(!1),R=ne(!0),M=ne(!1),H=ne(null);let B=lr;const z=Se(()=>h.value?S.value===0?B.noResultsLabel:`${y.value+1} of ${S.value}`:""),Z=Se(()=>S.value>0),P=Se(()=>Z.value&&!T.value&&C.value);let N=null,I=null;function L(G){return typeof G?.commands?.setSearchSession=="function"}function X(){try{const G=(typeof o=="function"?o():null)?.search;return G&&typeof G.search=="function"?G:null}catch{return null}}function te(G){G&&(S.value=typeof G.total=="number"?G.total:0,y.value=typeof G.activeIndex=="number"?G.activeIndex:-1,C.value=G.canReplace===!0,H.value=G.reason==="search-invalid-pattern"?B.invalidPatternLabel:null)}function le(){if(a){fe();return}if(s){if(!h.value){try{s.commands.clearSearchSession()}catch{}S.value=0,y.value=-1;return}try{const G=s.commands.setSearchSession(h.value,{caseSensitive:p.value,ignoreDiacritics:g.value,highlight:!0,searchModel:Ie().includeDeletedText?"raw":"visible"});S.value=G.matches.length,y.value=G.activeMatchIndex}catch{}}}function fe(){const G=a;if(G){if(!h.value){try{G.clear()}catch{}S.value=0,y.value=-1,H.value=null;return}try{te(G.search(h.value,{caseSensitive:p.value,includeDeletedText:Ie().includeDeletedText===!0,regex:k.value}))}catch{}}}function Fe(){N&&clearTimeout(N),N=setTimeout(le,150)}Pt(h,()=>{c.value&&Fe()}),Pt(p,()=>{c.value&&le()}),Pt(g,()=>{c.value&&le()}),Pt(k,()=>{c.value&&le()});let he=!0;function ge(){if(Z.value){if(a){try{a.next(),te(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.nextSearchMatch().activeMatchIndex}catch{}}}function ae(){if(Z.value){if(a){try{a.previous(),te(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.previousSearchMatch().activeMatchIndex}catch{}}}function Ce(){if(he&&!T.value&&Z.value){if(a){if(!C.value)return;const G=a;T.value=!0;const J=H_(G,{getCurrentSession:()=>a,applySlice:te,onSettled:()=>{T.value=!1}});let K=null;try{K=G.replace(m.value)}catch{}K&&typeof K.then=="function"?Promise.resolve(K).then(J,J):J();return}if(s)try{const G=s.commands.replaceSearchMatch(m.value);S.value=G.matches.length,y.value=G.activeMatchIndex}catch{}}}function oe(){if(he&&!T.value&&Z.value){if(a){if(!C.value)return;const G=a;T.value=!0;const J=H_(G,{getCurrentSession:()=>a,applySlice:te,onSettled:()=>{T.value=!1}});let K=null;try{K=G.replaceAll(m.value)}catch{}K&&typeof K.then=="function"?Promise.resolve(K).then(J,J):J();return}if(s)try{s.commands.replaceAllSearchMatches(m.value),S.value=0,y.value=-1}catch{}}}function xe(){if(a){try{te(a.getSnapshot())}catch{}return}const G=iM(s);if(!G)return;const J=G.searchResults,K=Array.isArray(J)?J.length:0,W=G.activeMatchIndex??-1;K!==S.value&&(S.value=K),W!==y.value&&(y.value=W)}function qe(){et(),I=setInterval(xe,200)}function et(){N&&clearTimeout(N),N=null,I&&clearInterval(I),I=null}function kt(){h.value="",m.value="",p.value=!1,g.value=!1,k.value=!1,H.value=null,w.value=!1,S.value=0,y.value=-1,C.value=!0,T.value=!1}function Ie(){const G=typeof r=="function"?r():void 0;if(G===!1||G==null)return{enabled:!1,texts:lr,replaceEnabled:!0};if(G===!0)return{enabled:!0,texts:lr,replaceEnabled:!0};const J=typeof G=="object"?G:{};if(J.component!=null&&typeof J.render=="function")throw new Error('modules.surfaces.findReplace cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{findPlaceholder:J.findPlaceholder??lr.findPlaceholder,findAriaLabel:J.findAriaLabel??lr.findAriaLabel,replacePlaceholder:J.replacePlaceholder??lr.replacePlaceholder,replaceAriaLabel:J.replaceAriaLabel??lr.replaceAriaLabel,noResultsLabel:J.noResultsLabel??lr.noResultsLabel,previousMatchLabel:J.previousMatchLabel??lr.previousMatchLabel,previousMatchAriaLabel:J.previousMatchAriaLabel??lr.previousMatchAriaLabel,nextMatchLabel:J.nextMatchLabel??lr.nextMatchLabel,nextMatchAriaLabel:J.nextMatchAriaLabel??lr.nextMatchAriaLabel,closeLabel:J.closeLabel??lr.closeLabel,closeAriaLabel:J.closeAriaLabel??lr.closeAriaLabel,replaceLabel:J.replaceLabel??lr.replaceLabel,replaceAllLabel:J.replaceAllLabel??lr.replaceAllLabel,toggleReplaceLabel:J.toggleReplaceLabel??lr.toggleReplaceLabel,toggleReplaceAriaLabel:J.toggleReplaceAriaLabel??lr.toggleReplaceAriaLabel,matchCaseLabel:J.matchCaseLabel??lr.matchCaseLabel,matchCaseAriaLabel:J.matchCaseAriaLabel??lr.matchCaseAriaLabel,regexLabel:J.regexLabel??lr.regexLabel,regexAriaLabel:J.regexAriaLabel??lr.regexAriaLabel,invalidPatternLabel:J.invalidPatternLabel??lr.invalidPatternLabel,ignoreDiacriticsLabel:J.ignoreDiacriticsLabel??lr.ignoreDiacriticsLabel,ignoreDiacriticsAriaLabel:J.ignoreDiacriticsAriaLabel??lr.ignoreDiacriticsAriaLabel},replaceEnabled:J.replaceEnabled??!0,includeDeletedText:J.includeDeletedText??!1,component:J.component,props:J.props,render:J.render,resolver:J.resolver,floating:J.floating&&typeof J.floating=="object"?J.floating:void 0}}function ze(G,J){if(typeof G.resolver=="function"){const K=G.resolver(J);if(K!=null&&K.type!=="default"){if(K.type==="none")return{suppressed:!0};if(K.type==="custom")return{component:K.component,props:K.props};if(K.type==="external")return{render:K.render}}}return G.component!=null?{component:G.component,props:G.props}:typeof G.render=="function"?{render:G.render}:{builtin:!0}}function Ve(G,J){return{findQuery:h,replaceText:m,caseSensitive:p,ignoreDiacritics:g,regex:k,showReplace:w,matchCount:S,activeMatchIndex:y,matchLabel:z,hasMatches:Z,canReplace:P,replaceCanMutate:C,replacePending:T,ignoreDiacriticsSupported:R,regexSupported:M,searchError:H,replaceEnabled:G.replaceEnabled??!0,texts:G.texts,goNext:ge,goPrev:ae,replaceCurrent:Ce,replaceAll:oe,registerFocusFn:K=>{d=K},close:K=>J(K)}}function Q(G){return{get findQuery(){return G.findQuery.value},set findQuery(J){G.findQuery.value=J},get replaceText(){return G.replaceText.value},set replaceText(J){G.replaceText.value=J},get caseSensitive(){return G.caseSensitive.value},set caseSensitive(J){G.caseSensitive.value=J},get ignoreDiacritics(){return G.ignoreDiacritics.value},set ignoreDiacritics(J){G.ignoreDiacritics.value=J},get regex(){return G.regex.value},set regex(J){G.regex.value=J},get regexSupported(){return G.regexSupported.value},get searchError(){return G.searchError.value},get replaceCanMutate(){return G.replaceCanMutate.value},get showReplace(){return G.showReplace.value},set showReplace(J){G.showReplace.value=J},get matchCount(){return G.matchCount.value},get activeMatchIndex(){return G.activeMatchIndex.value},get matchLabel(){return G.matchLabel.value},get hasMatches(){return G.hasMatches.value},get canReplace(){return G.canReplace.value},get replacePending(){return G.replacePending.value},get ignoreDiacriticsSupported(){return G.ignoreDiacriticsSupported.value},replaceEnabled:G.replaceEnabled,texts:G.texts,goNext:G.goNext,goPrev:G.goPrev,replaceCurrent:G.replaceCurrent,replaceAll:G.replaceAll,registerFocusFn:G.registerFocusFn,close:G.close}}function _(G){if(G){if(typeof G?.commands?.clearSearchSession=="function"){try{G.commands.clearSearchSession()}catch{}return}if(a&&G===s)try{a.clear()}catch{}}}function $(){try{if(l||!e()||!t())return!1;if(i&&c.value)return!0;const G=Ie();if(!G.enabled||ze(G,{texts:G.texts,replaceEnabled:G.replaceEnabled??!0}).suppressed)return!1;if(!L(t())){const J=X();if(!J)return!1;try{if(J.getSnapshot?.().available!==!0)return!1}catch{return!1}}return!0}catch{return!1}}async function F(){if(l)return;const G=e();if(G){if(i&&c.value){d?.();return}if(!u){u=!0;try{const J=t();if(!J){u=!1;return}const K=Ie();if(!K.enabled){u=!1;return}const W=ze(K,{texts:K.texts,replaceEnabled:K.replaceEnabled??!0});if(W.suppressed){u=!1;return}kt(),B=K.texts,he=K.replaceEnabled??!0;const ue={placement:"top-right",autoFocus:!0,width:420,...K.floating??{}};if(s&&s!==J&&_(s),s=J,a=L(J)?null:X(),R.value=!a,M.value=!!a,a)try{te(a.getSnapshot())}catch{}d=null;let be=()=>{};const we=Ve(K,nt=>be(nt));let Te;if(W.component)Te=G.open({mode:"floating",ariaLabel:K.texts.findAriaLabel,closeOnEscape:!0,floating:ue,component:Hr(W.component),props:{...W.props,findReplace:we}});else if(W.render){const nt=W.render;Te=G.open({mode:"floating",ariaLabel:K.texts.findAriaLabel,closeOnEscape:!0,floating:ue,render:wt=>nt({container:wt.container,findReplace:Q(we),resolve:wt.resolve,close:wt.close,surfaceId:wt.surfaceId,mode:wt.mode})})}else{let nt;try{nt=(await Promise.resolve().then(()=>(oM(),rM))).default}catch{u=!1;return}if(l||i&&c.value){u=!1;return}const wt=t()||J;s!==wt&&(_(s),s=wt,a=L(wt)?null:X(),R.value=!a),Te=G.open({mode:"floating",ariaLabel:K.texts.findAriaLabel,component:Hr(nt),closeOnEscape:!0,floating:ue,props:{findReplace:we}})}be=nt=>Te.close(nt??"programmatic"),i=Te,c.value=!0,u=!1,qe();const rt=Te.id;Te.result.then(()=>{i?.id===rt?(et(),_(s),i=null,c.value=!1,d=null):_(J!==s?J:null)})}catch(J){throw u=!1,J}}}}function j(){i&&i.close("programmatic")}n&&Pt(n,(G,J)=>{!c.value||!i||G!==J&&(_(J),j())});function V(){l=!0,et(),j(),s=null,a=null,d=null}return{open:F,close:j,isOpen:c,wouldOpen:$,destroy:V}}var ef=null;function Zy(e){e!=null&&(ef=e)}function aM(e){ef===e&&(ef=null)}function lM(e){return ef===null||ef===e}function cM(e,{focusInside:t,owner:n}){if(e.defaultPrevented)return!1;if(t)return!0;const r=document.activeElement;return(!r||r===document.body||r===document.documentElement)&&lM(n)}var uM=/^(https?|mailto|tel):/i,dM=/^(javascript|data|vbscript):/i,fM=/^[a-z][a-z0-9+.-]*:/i;function hM(e){if(typeof e!="string")return null;const t=e.trim();return t?t.startsWith("#")?{href:t}:dM.test(t)?null:fM.test(t)?uM.test(t)?{href:t}:null:{href:t}:null}var pM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M0 64C0 46.3 14.3 32 32 32l48 0 16 0 128 0c70.7 0 128 57.3 128 128c0 31.3-11.3 60.1-30 82.3c37.1 22.4 62 63.1 62 109.7c0 70.7-57.3 128-128 128L96 480l-16 0-48 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l16 0 0-160L48 96 32 96C14.3 96 0 81.7 0 64zM224 224c35.3 0 64-28.7 64-64s-28.7-64-64-64L112 96l0 128 112 0zM112 288l0 128 144 0c35.3 0 64-28.7 64-64s-28.7-64-64-64l-32 0-112 0z"/></svg>',mM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M128 64c0-17.7 14.3-32 32-32l192 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-58.7 0L160 416l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l58.7 0L224 96l-64 0c-17.7 0-32-14.3-32-32z"/></svg>',gM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M16 64c0-17.7 14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 53 43 96 96 96s96-43 96-96l0-128-16 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 88.4-71.6 160-160 160s-160-71.6-160-160L64 96 48 96C30.3 96 16 81.7 16 64zM0 448c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32z"/></svg>',uS='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M40 48C26.7 48 16 58.7 16 72l0 48c0 13.3 10.7 24 24 24l48 0c13.3 0 24-10.7 24-24l0-48c0-13.3-10.7-24-24-24L40 48zM192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 64zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zM16 232l0 48c0 13.3 10.7 24 24 24l48 0c13.3 0 24-10.7 24-24l0-48c0-13.3-10.7-24-24-24l-48 0c-13.3 0-24 10.7-24 24zM40 368c-13.3 0-24 10.7-24 24l0 48c0 13.3 10.7 24 24 24l48 0c13.3 0 24-10.7 24-24l0-48c0-13.3-10.7-24-24-24l-48 0z"/></svg>',vM=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. (bullet shapes modified)--><path fill-rule="evenodd" d="M192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 64zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zM64 48 A48 48 0 1 0 64 144 A48 48 0 1 0 64 48 Z M64 68 A28 28 0 1 1 64 124 A28 28 0 1 1 64 68 Z M64 208 A48 48 0 1 0 64 304 A48 48 0 1 0 64 208 Z M64 228 A28 28 0 1 1 64 284 A28 28 0 1 1 64 228 Z M64 368 A48 48 0 1 0 64 464 A48 48 0 1 0 64 368 Z M64 388 A28 28 0 1 1 64 444 A28 28 0 1 1 64 388 Z"/></svg>
|
|
15
15
|
`,yM=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. (bullet shapes modified)--><path d="M192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 64zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zM16 48 L112 48 L112 144 L16 144 Z M16 208 L112 208 L112 304 L16 304 Z M16 368 L112 368 L112 464 L16 464 Z"/></svg>
|
|
16
16
|
`,bM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M24 56c0-13.3 10.7-24 24-24l32 0c13.3 0 24 10.7 24 24l0 120 16 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l16 0 0-96-8 0C34.7 80 24 69.3 24 56zM86.7 341.2c-6.5-7.4-18.3-6.9-24 1.2L51.5 357.9c-7.7 10.8-22.7 13.3-33.5 5.6s-13.3-22.7-5.6-33.5l11.1-15.6c23.7-33.2 72.3-35.6 99.2-4.9c21.3 24.4 20.8 60.9-1.1 84.7L86.8 432l33.2 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-88 0c-9.5 0-18.2-5.6-22-14.4s-2.1-18.9 4.3-25.9l72-78c5.3-5.8 5.4-14.6 .3-20.5zM224 64l256 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-256 0c-17.7 0-32-14.3-32-32s14.3-32 32-32zm0 160l256 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-256 0c-17.7 0-32-14.3-32-32s14.3-32 32-32zm0 160l256 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-256 0c-17.7 0-32-14.3-32-32s14.3-32 32-32z"/></svg>',wM=`<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
17
17
|
<g clip-path="url(#clip0_0_1)">
|
|
@@ -83,7 +83,7 @@ ${n.toString()}`)};var ox=class{constructor(e){this.patterns=[],this.$state=e}if
|
|
|
83
83
|
`,uL=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="96 96 448 448"><!--!Font Awesome Free v7.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2026 Fonticons, Inc.--><path d="M96 160C96 124.7 124.7 96 160 96L480 96C515.3 96 544 124.7 544 160L544 480C544 515.3 515.3 544 480 544L160 544C124.7 544 96 515.3 96 480L96 160zM160 160L160 224L224 224L224 160L160 160zM480 160L288 160L288 224L480 224L480 160zM160 288L160 352L224 352L224 288L160 288zM480 288L288 288L288 352L480 352L480 288zM160 416L160 480L224 480L224 416L160 416zM480 416L288 416L288 480L480 480L480 416z"></path></svg>
|
|
84
84
|
`,dL=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M9 10v5h2V4h2v11h2V4h2V2H9C6.79 2 5 3.79 5 6s1.79 4 4 4zm12 8l-4-4v3H5v2h12v3l4-4z"/></svg>
|
|
85
85
|
`,fL=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M10 10v5h2V4h2v11h2V4h2V2h-8C7.79 2 6 3.79 6 6s1.79 4 4 4zm-2 7v-3l-4 4 4 4v-3h12v-2H8z"/></svg>
|
|
86
|
-
`;const tr={undo:s_,redo:BM,bold:pM,italic:mM,underline:gM,color:VM,link:dS,image:xM,tableOfContents:uL,alignLeft:TM,alignRight:MM,alignCenter:RM,alignJustify:LM,bulletList:uS,bulletListDisc:uS,bulletListCircle:vM,bulletListSquare:yM,numberedList:bM,numberedListDecimal:wM,numberedListDecimalParen:CM,numberedListUpperRoman:_M,numberedListLowerRoman:SM,numberedListUpperAlpha:kM,numberedListUpperAlphaParen:AM,numberedListLowerAlpha:IM,numberedListLowerAlphaParen:EM,indentLeft:PM,indentRight:DM,directionLtr:dL,directionRtl:fL,pageBreak:jM,copyFormat:OM,clearFormatting:FM,trackChanges:HM,trackChangesFinal:UM,trackChangesOriginal:hS,trackChangesAccept:NM,trackChangesReject:zM,documentMode:fS,documentEditingMode:fS,documentSuggestingMode:n_,documentViewingMode:hS,colorOption:GM,colorOptionCheck:Vy,linkInput:dS,removeLink:o_,openLink:WM,overflow:i_,dropdownCaretUp:KM,dropdownCaretDown:r_,ruler:qM,paintbrush:YM,highlight:XM,ai:QM,table:ZM,tableActions:JM,splitCell:$M,mergeCells:eL,addRowBefore:vp,addRowAfter:vp,addColumnBefore:vp,addColumnAfter:vp,deleteRow:Jy,deleteColumn:Jy,deleteTable:Jy,deleteBorders:nL,fixTables:tL,lineHeight:rL,search:oL,cut:iL,copy:sL,paste:aL,strikethrough:lL,formattingMarks:cL};It(),gn();var hL={key:0,class:"link-title"},pL={key:1,class:"link-title"},mL={key:2,class:"link-title"},gL={key:3,class:"link-title"},vL={key:4,class:"link-input-wrapper"},yL={class:"input-row text-input-row"},bL=["readonly","onKeydown"],wL={class:"input-row url-input-row"},CL=["innerHTML"],_L=["readonly","onKeydown"],SL=["innerHTML"],kL={key:0,class:"input-row link-buttons"},AL=["innerHTML"],IL={key:5,class:"input-row go-to-anchor clickable"},EL={__name:"LinkInput",props:{showInput:{type:Boolean,default:!0},showLink:{type:Boolean,default:!0},goToAnchor:{type:Function,default:()=>{}},ui:{type:Object,default:null},linkItem:{type:Object,default:null},closePopover:{type:Function,default:()=>{}},href:{type:String,default:null},target:{type:String,default:null},rel:{type:String,default:null},tooltip:{type:String,default:null},clickedElement:{type:Object,default:null},hyperlinkTarget:{type:Object,default:null},hyperlinkText:{type:String,default:null},textTarget:{type:Object,default:null},restoreSelection:{type:Function,default:()=>{}},documentMode:{type:String,default:null}},setup(e){const t=e,{isHighContrastMode:n}=zi(),r=ne(!1),o=()=>{if(typeof t.hyperlinkText=="string"&&t.hyperlinkText)return t.hyperlinkText;const H=t.ui?.selection?.getSnapshot?.();if(typeof H?.quotedText=="string"&&H.quotedText)return H.quotedText;const B=t.clickedElement?.innerText??t.clickedElement?.textContent;return typeof B=="string"?B:""},i=()=>{if(typeof t.href=="string"&&t.href)return t.href;const H=t.ui?.toolbar?.getSnapshot?.()?.commands?.link?.value;if(typeof H=="string"&&H)return H;const B=t.linkItem?.attributes?.value?.href;return typeof B=="string"?B:""},s=()=>t.documentMode??t.ui?.document?.getSnapshot?.()?.mode??null,a=ne(""),l=ne(""),u=ne(!1),c=/^[a-z][a-z0-9+.-]*:/i,d=Se(()=>{const H=l.value.trim();return H?H.startsWith("#")||c.test(H)?H:"https://"+H:""}),h=Se(()=>d.value?hM(d.value):null),m=Se(()=>h.value!==null),p=ne(!1),g=Se(()=>!u.value&&p.value),k=Se(()=>!m.value),w=Se(()=>s()==="viewing"),S=()=>{const H=h.value?.href;H&&window.open(H,"_blank","noopener")},y=()=>{const H=document.querySelector(".link-input-ctn input");H&&H.focus()};Rn(()=>{a.value=o(),l.value=i(),p.value=!!l.value,u.value=l.value.startsWith("#"),t.showInput&&!w.value&&y()});const C=H=>{const B=t.ui;return B?.commands?.execute?(t.restoreSelection?.(),B.commands.execute("link",H)):!1},T=()=>{if(w.value)return;if(!l.value){C({href:null,hyperlinkTarget:t.hyperlinkTarget}),t.closePopover();return}if(!m.value){r.value=!0;return}const H=h.value?.href;if(!H){r.value=!0;return}const B={href:H,currentText:o(),hyperlinkTarget:t.hyperlinkTarget,textTarget:t.textTarget};a.value?B.text=a.value:g.value||(B.text=H),C(B),t.closePopover()},R=()=>{C({href:null,hyperlinkTarget:t.hyperlinkTarget}),t.closePopover()},M=H=>{t.goToAnchor&&t.goToAnchor(H)};return(H,B)=>(me(),_e("div",{class:en(["link-input-ctn",{"high-contrast":Ge(n)}])},[u.value?(me(),_e("div",hL,"Page anchor")):w.value?(me(),_e("div",pL,"Link details")):g.value?(me(),_e("div",mL,"Edit link")):(me(),_e("div",gL,"Add link")),e.showInput&&!u.value?(me(),_e("div",vL,[Le("div",yL,[B[4]||(B[4]=Le("div",{class:"input-icon text-input-icon"},"T",-1)),Ws(Le("input",{type:"text",name:"text",placeholder:"Text","onUpdate:modelValue":B[0]||(B[0]=z=>a.value=z),readonly:w.value,onKeydown:Yo(Jt(T,["stop","prevent"]),["enter"])},null,40,bL),[[ki,a.value]])]),Le("div",wL,[Le("div",{class:"input-icon",innerHTML:Ge(tr).linkInput},null,8,CL),Ws(Le("input",{type:"text",name:"link",placeholder:"Type or paste a link",class:en({"sd-error":r.value}),"onUpdate:modelValue":B[1]||(B[1]=z=>l.value=z),readonly:w.value,onKeydown:[Yo(Jt(T,["stop","prevent"]),["enter"]),B[2]||(B[2]=z=>r.value=!1)]},null,42,_L),[[ki,l.value]]),Le("div",{class:en(["open-link-icon",{"sd-disabled":!m.value}]),innerHTML:Ge(tr).openLink,onClick:S,"data-item":"btn-link-open"},null,10,SL)]),w.value?ut("",!0):(me(),_e("div",kL,[g.value?(me(),_e("button",{key:0,class:"remove-btn",onClick:R,"data-item":"btn-link-remove"},[Le("div",{class:"remove-btn__icon",innerHTML:Ge(tr).removeLink},null,8,AL),B[5]||(B[5]=Oi(" Remove ",-1))])):ut("",!0),Le("button",{class:en(["sd-submit-btn",{"disable-btn":k.value}]),onClick:T,"data-item":"btn-link-apply"}," Apply ",2)]))])):u.value?(me(),_e("div",IL,[Le("a",{onClick:B[3]||(B[3]=Jt(z=>M(l.value),["stop","prevent"]))},"Go to "+Ht(l.value.startsWith("#_")?l.value.substring(2):l.value),1)])):ut("",!0)],2))}},pS=hn(EL,[["__scopeId","data-v-3e4bd44e"]]);function xL(e){let t=e;for(;t;){const n=window.getComputedStyle(t).overflowY;if(/(auto|scroll)/.test(n)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return document.scrollingElement||document.documentElement}function tf(e,t={behavior:"smooth",block:"start"}){if(!e)return;const n=xL(e),r=n.getBoundingClientRect(),o=e.getBoundingClientRect().top-r.top+n.scrollTop,i=window.getComputedStyle(n).scrollPaddingTop?.trim(),s=i?.endsWith("px")?Number(i.slice(0,-2)):0,a=Number.isFinite(s)&&s>=0?s:0;n.scrollTo({top:t.block==="start"?o-a:o-n.clientHeight+e.offsetHeight,behavior:t.behavior})}It();var TL="link-popover",RL=500,ML=e=>!!(e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"),LL=e=>!!(e&&typeof e=="object"&&!Array.isArray(e));function DL(e){return LL(e)?e.type==="default"||e.type==="none"?!0:e.type==="custom"?e.component!=null:e.type==="external"?typeof e.render=="function":!1:!1}function mS(e){return e instanceof Error?e:new Error(String(e))}function PL(e){return typeof e!="string"?"":e.split(/\s+/).map(t=>t.trim().toLowerCase()).filter(t=>t==="noopener"||t==="noreferrer").filter((t,n,r)=>r.indexOf(t)===n).join(",")}function OL(e,t){const n=PL(e);if(t!=="_blank")return n;const r=n?n.split(","):[];return r.includes("noopener")||r.unshift("noopener"),r.join(",")}function gS(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):String(e).replace(/['"\\]/g,"\\$&")}function FL(e){const t=e?.dataset?.sourceAnchor;if(typeof t!="string")return null;try{const n=JSON.parse(t)?.sourceRef?.xpathLikePath,r=typeof n=="string"?n.match(/w:p\[ordinal=(\d+)\]/):null;return r?Number(r[1]):null}catch{return null}}function BL(e,t){const n=FL(e),r=t?.blocks?.list?.()?.blocks,o=Array.isArray(r)?r.find(i=>i.ordinal===n):null;return typeof o?.nodeId=="string"?o.nodeId:e?.dataset?.blockId}function vS(e,t){const n=e?.closest?.("[data-block-id][data-pm-start]"),r=BL(n,t);if(!r||!n||!e?.ownerDocument)return null;const o=Number(e?.dataset?.pmStart),i=Number(e?.dataset?.pmEnd);if(Number.isFinite(o)&&Number.isFinite(i)&&i>o){const m=Number(n?.dataset?.pmStart),p=Number.isFinite(m)&&o>=m,g=p?o-m:o,k=p?i-m:i;return g<0||k<=g?null:{kind:"selection",start:{kind:"text",blockId:r,offset:g},end:{kind:"text",blockId:r,offset:k}}}const s=e.ownerDocument.defaultView,a=s?.NodeFilter,l=s?.Node;if(!a||!l)return null;let u=0;const c=e.ownerDocument.createTreeWalker(n,a.SHOW_ELEMENT|a.SHOW_TEXT);let d=c.nextNode();for(;d&&d!==e;)d.nodeType===l.TEXT_NODE&&!e.contains(d)&&(u+=d.textContent?.length??0),d=c.nextNode();if(d!==e)return null;const h=u+(e.textContent?.length??0);return h<=u?null:{kind:"selection",start:{kind:"text",blockId:r,offset:u},end:{kind:"text",blockId:r,offset:h}}}function $y(e){if(typeof e!="string")return"";try{return new URL(e,window.location.href).href}catch{return e}}function e0(e){return typeof e?.externalTarget=="string"&&e.externalTarget?e.externalTarget:typeof e?.anchor=="string"&&e.anchor?`#${e.anchor}`:""}function yS(e){const t=e?.anchor?.start,n=e?.anchor?.end;return typeof t?.blockId!="string"||typeof t?.offset!="number"||typeof n?.blockId!="string"||typeof n?.offset!="number"||t.blockId!==n.blockId?null:{kind:"selection",start:{kind:"text",blockId:t.blockId,offset:t.offset},end:{kind:"text",blockId:n.blockId,offset:n.offset}}}function NL(e,t){const n=yS(t);return n?n.start.blockId===e?.start?.blockId&&n.start.offset===e?.start?.offset&&n.end.blockId===e?.end?.blockId&&n.end.offset===e?.end?.offset:!1}function zL(e,t,n){if(typeof t!="string"||!t)return null;const r=e?.query?.match?.({select:{type:"text",pattern:t,caseSensitive:!0},require:"any"}),o=(Array.isArray(r?.items)?r.items:[]).map(s=>s?.target).filter(s=>s?.kind==="selection"&&!!s?.start?.blockId&&!!s?.end?.blockId),i=typeof n=="string"?o.filter(s=>s.start.blockId===n&&s.end.blockId===n):o;return i.length===1?i[0]:typeof n=="string"?null:o.length===1?o[0]:null}function HL(e){return!!(e&&typeof e.closest=="function"&&e.closest(".superdoc-toc-entry"))}function UL({getSurfaceManager:e,getActiveEditor:t,getUi:n,getResolver:r,getLayerElement:o,emitException:i}){let s=null,a=null,l=0;function u(){l+=1}function c(N,I){if(!N||!s||s.handle!==N)return;const L=s;L.unbindPointerDown?.();const X=L.element.ownerDocument?.defaultView?.Node,te=X!=null&&L.pointerDownTarget instanceof X&&L.element.contains(L.pointerDownTarget);I?.status==="closed"&&I.reason===void 0&&te&&(a={href:L.href,element:L.element,closedAt:Date.now()}),s=null}function d(N="closed"){u();const I=s;s=null,a=null,I?.unbindPointerDown?.(),I?.handle?.close?.(N)}function h(N){return{id:TL,mode:"floating",closeOnEscape:!0,floating:{top:N.position.top,left:N.position.left,autoFocus:!0,closeOnOutsidePointerDown:!0,width:"auto"}}}function m(N,I){const L={href:N.href,element:N.element,handle:I,pointerDownTarget:null,unbindPointerDown:null},X=N.element.ownerDocument,te=le=>{L.pointerDownTarget=le.target??null};X.addEventListener("pointerdown",te,!0),L.unbindPointerDown=()=>X.removeEventListener("pointerdown",te,!0),s=L,a=null,I.result?.then?.(le=>c(I,le),()=>c(I))}function p(N,I){return N?.querySelector?.(`a[name='${I}'], [data-bookmark-marker='start'][data-bookmark-name='${I}']`)??null}function g(N,I){if(!N)return null;const L=gS(I);return N.querySelector(`[data-source-node-id='${L}']`)??N.querySelector(`[data-layout-paraid='${L}']`)??N.querySelector(`[data-block-id$='/${L}']`)??N.querySelector(`[data-layout-block-ref$='/${L}']`)??null}function k(N,I=30){return new Promise(L=>{const X=typeof window<"u"?window.requestAnimationFrame:null;let te=0;const le=()=>{const fe=N();if(fe||te>=I||typeof X!="function"){L(fe??null);return}te+=1,X(le)};le()})}async function w(N){const I=t()?.authoring?.setSelectionTarget;if(typeof I!="function")return;const L={kind:"story",storyType:"body"},X={kind:"text",blockId:N,offset:0,story:L},te={kind:"selection",start:X,end:X,story:L};try{await Promise.resolve(I({target:te,collapse:"start",focus:!0}))}catch{}}async function S(N,{placeCaret:I=!1}={}){if(typeof N!="string"||!N.startsWith("#"))return;const L=N.slice(1),X=gS(L),te=p(n()?.viewport?.getHost?.()??null,X);if(te){tf(te);return}const le=t()?.doc;let fe=null;try{fe=await Promise.resolve(le?.bookmarks?.get?.({target:{kind:"entity",entityType:"bookmark",name:L}})),fe??=null}catch{fe=null}const Fe=fe?.address?.story;if(Fe&&Fe.storyType!=="body")return;const he=fe?.range?.from?.blockId;if(typeof he!="string")return;I&&await w(he);const ge=g(n()?.viewport?.getHost?.()??null,he);if(ge){tf(ge);return}const ae=t()?.pageMetrics,Ce=ae?.revealBodyTarget;let oe;try{oe=await Ce?.({paraId:he})}catch{oe=void 0}if(oe?.status==="revealed"){const Ie=g(n()?.viewport?.getHost?.()??null,he);Ie&&tf(Ie);return}if(Ce&&oe?.reason!=="editing-not-mounted")return;const xe=ae?.pageIndexForBodyTarget,qe=ae?.scrollToPage,et=xe?.({paraId:he});if(typeof et!="number"||!qe?.(et))return;const kt=await k(()=>g(n()?.viewport?.getHost?.()??null,he));kt&&tf(kt)}async function y(N){const I=N.editor?.doc;let L;try{L=await Promise.resolve(I?.hyperlinks?.list?.())}catch{return null}const X=Array.isArray(L?.stories)?L.stories:[],te=N.element?.dataset?.linkRid,le=N.element?.textContent??"",fe=$y(N.href),Fe=vS(N.element,I);for(const he of X){const ge=Array.isArray(he?.hyperlinks)?he.hyperlinks:[],ae=async F=>{if(!F?.hyperlinkNodeId||!he?.storyId||F.address)return F;try{const j=await Promise.resolve(I?.hyperlinks?.get?.({storyId:he.storyId,hyperlinkNodeId:F.hyperlinkNodeId}));return j?.success&&j.hyperlink?j.hyperlink:F}catch{return F}},Ce=async F=>{if(!Fe)return null;const j=(await Promise.all(F.map(ae))).filter(V=>NL(Fe,V.address));return j.length===1?j[0]:null},oe=te?ge.filter(F=>F.rId===te):[],xe=oe.filter(F=>F.text===le),qe=ge.filter(F=>$y(e0(F))===fe&&F.text===le),et=ge.filter(F=>F.text===le),kt=ge.filter(F=>{const j=$y(e0(F));return le&&j===fe&&F.text?.includes?.(le)}),Ie=xe.length===1?xe[0]:null,ze=qe.length===1?qe[0]:null,Ve=et.length===1?et[0]:null,Q=kt.length===1?kt[0]:null,_=oe.length===1?oe[0]:null,$=Ie??await Ce(xe)??ze??await Ce(qe)??Ve??await Ce(et)??Q??await Ce(kt)??_??await Ce(oe);if($?.hyperlinkNodeId&&he?.storyId){const F=await ae($),j=yS(F.address);return{storyId:he.storyId,hyperlinkNodeId:F.hyperlinkNodeId,href:e0(F),text:F.text,targetKind:F.targetKind,textTarget:j??zL(I,F.text,Fe?.start?.blockId)}}}return null}function C(N){if(!a)return!1;const I=a.element===N.element&&a.href===N.href,L=Date.now()-a.closedAt<=RL;return!I||!L?!1:(a=null,!0)}function T(N,I){const L=e();if(!L?.open)return;const X=l;queueMicrotask(()=>{X===l&&m(N,L.open(I))})}function R(N){if(d("replace"),N.isAnchorLink&&HL(N.element)){S(N.href,{placeCaret:N.documentMode!=="viewing"});return}if(N.documentMode==="viewing"){if(N.isAnchorLink)S(N.href);else if(N.href){const le=N.target||"_self",fe=OL(N.rel,le);fe?window.open(N.href,le,fe):window.open(N.href,le)}return}const I=()=>d("closed"),L=le=>{I(),S(le,{placeCaret:!0})},X=l,te=le=>{X===l&&T(N,{...h(N),component:Hr(pS),props:{href:le?.href||N.href,target:N.target,rel:N.rel,tooltip:N.tooltip,clickedElement:N.element,hyperlinkTarget:le,hyperlinkText:le?.text,textTarget:le?.textTarget??vS(N.element,N.editor?.doc),documentMode:N.documentMode,ui:n(),closePopover:I,goToAnchor:L}})};y(N).then(te,()=>te(null))}function M(N,I){d("replace");const L=()=>d("closed");T(N,{...h(N),component:Hr(I.component),props:{...I.props,editor:N.editor,href:N.href,closePopover:L}})}function H(N,I){d("replace");const L=I.render;T(N,{...h(N),render:X=>{try{return L({container:X.container,closePopover:()=>X.close("closed"),editor:N.editor,href:N.href})}catch(te){i({error:mS(te),source:"linkPopoverExternalRender"}),X.close("external-error");const le=l;queueMicrotask(()=>{le===l&&R(N)});return}}})}function B(N){const I=o()?.getBoundingClientRect?.(),L=typeof I?.left=="number"?I.left:0,X=typeof I?.top=="number"?I.top:0;return{editor:t(),href:N.href,target:N.target,rel:N.rel,tooltip:N.tooltip,element:N.element,clientX:N.clientX,clientY:N.clientY,isAnchorLink:N.href.startsWith("#"),documentMode:N.documentMode,position:{left:`${Math.max(0,N.clientX-L)}px`,top:`${Math.max(0,N.clientY-X)}px`},closePopover:()=>d("closed")}}function z(N){const I=r();if(typeof I!="function")return{type:"default"};try{const L=I(N);return ML(L)?(i({error:new Error("modules.links.popoverResolver must return synchronously."),source:"linkPopoverResolver"}),{type:"default"}):L==null?{type:"default"}:DL(L)?L:(i({error:new Error("modules.links.popoverResolver returned an invalid resolution."),source:"linkPopoverResolver"}),{type:"default"})}catch(L){return i({error:mS(L),source:"linkPopoverResolver"}),{type:"default"}}}function Z(N){if(!N?.element||typeof N.href!="string")return;if(u(),s&&s.element===N.element&&s.href===N.href){d("toggle");return}if(C(N))return;const I=B(N),L=z(I);if(L.type==="none"){d("none");return}if(L.type==="custom"){M(I,L);return}if(L.type==="external"){H(I,L);return}R(I)}function P(){d("destroyed")}return{handleLinkClick:Z,closeCurrentPopover:d,destroy:P}}var VL=Object.freeze({editorVersion:2,commands:null,state:null,view:null}),jL=["text.insert","text.replace","text.deleteBackward","text.deleteForward","text.paste","history.undo","history.redo","structural.splitBlock","structural.indent","structural.outdent"],bS=["comments.create","comments.resolve","comments.reopen","comments.delete","comments.reply","comments.edit","trackedChanges.accept","trackedChanges.reject","trackedChanges.acceptAll","trackedChanges.rejectAll"],GL=["trackedChanges.setAuthoringMode"];function nf(e){return e.state!=="ready"?e.state:e.documentMode==="viewing"?"review-ready":"editing-ready"}function yp(e){return e==="review-ready"||e==="editing-ready"}function wS(e){switch(e){case"text.insert":return"text.insert";case"text.replace":return"text.replace";case"text.deleteBackward":return"text.deleteBackward";case"text.deleteForward":return"text.deleteForward";case"text.paste":return"text.pastePlain";case"history.undo":return"history.undo";case"history.redo":return"history.redo";case"structural.splitBlock":return"structural.enter";case"structural.indent":return"structural.listIndent";case"structural.outdent":return"structural.listOutdent";default:return null}}function CS(e){switch(e){case"comments.create":return"comments.createFromSelection";case"comments.resolve":return"review.commentResolve";case"comments.reopen":return"review.commentReopen";case"comments.delete":return"review.commentDelete";case"comments.reply":return"review.commentReply";case"comments.edit":return"review.commentEdit";case"trackedChanges.accept":case"trackedChanges.reject":return"review.trackedChangeDecide";case"trackedChanges.acceptAll":return"trackedChanges.acceptAll";case"trackedChanges.rejectAll":return"trackedChanges.rejectAll";default:return null}}function _S(e,t){return e.editableSubset.commands.find(n=>n.command===t)??null}function WL(e){return e?.status==="supported"||e?.enabled===!0}function KL(e){return e?.rejectionCode??e?.reason??null}function qL(e){return e?.detail??void 0}function bp(e,t){return WL(_S(e,t))}function SS(e,t){const n=_S(e,t),r=KL(n);return r?{reason:AS(r),detail:qL(n)}:e.documentMode==="viewing"?{reason:"document-readonly",detail:"review-surface-read-only"}:{reason:"command-unsupported",detail:`unsupported:${t}`}}function kS(e,t){const n=t?.reason;return e==="history.undo"?n==="NO_EFFECT"||n==="apply-rejected"?"no-effect":"nothing-to-undo":n==="NO_EFFECT"||n==="apply-rejected"?"no-effect":"nothing-to-redo"}function AS(e){switch(e){case"host-saving":return"host-saving";case"document-readonly":return"document-readonly";case"selection-invalidated":case"review-target-invalidated":return"selection-invalidated";case"review-command-unavailable":return"review-command-unavailable";case"review-surface-read-only":return"document-readonly";case"editing-selection-required":return"selection-unsupported";case"format-target-unsupported":case"selection-target-unsupported":case"input-target-unsupported":case"composition-target-unsupported":case"enter-context-unsupported":case"boundary-merge-unsupported":case"tracked-structural-edit-unsupported":case"comment-anchor-create-unsupported":case"comment-anchor-move-unsupported":return"target-unsupported";case"unsupported-command":return"command-unsupported";case"editing-mount-required":case"host-not-ready":case"host-disposed":return"runtime-not-ready";default:return"command-failed"}}function YL(e){const{id:t,documentId:n,root:r,host:o,getLegacyEditorProjection:i,onUnregister:s}=e;let a=o.getSnapshot(),l=!1,u=!1,c=null,d=0,h=0,m=null,p=null,g=null,k=null;const w=new Map,S=new Set;function y(ae){for(const Ce of Array.from(S))try{Ce(ae)}catch{}}function C(){d+=1,w.clear()}function T(ae){const Ce=`v2-runtime-pos-${h++}`;return w.set(Ce,ae),{runtimeId:t,tokenId:Ce,revision:d}}function R(ae){return ae.runtimeId!==t?{ok:!1,reason:"wrong-runtime-token"}:ae.revision!==d||!w.has(ae.tokenId)?{ok:!1,reason:"stale-position-token"}:{ok:!0}}function M(){return o.getHandles().editing?.selection??null}function H(){const ae=M()?.getSnapshot()??null;return ae?{isRange:ae.anchor!==ae.focus,isEmpty:ae.anchor===ae.focus,text:"",anchor:T(ae.anchor),focus:T(ae.focus)}:null}function B(){const ae=M();ae!==k&&(m?.(),m=null,k=ae,ae&&(m=ae.subscribe(Ce=>{C(),y({type:"selection-change",selection:Ce?{isRange:Ce.anchor!==Ce.focus,isEmpty:Ce.anchor===Ce.focus,text:"",anchor:T(Ce.anchor),focus:T(Ce.focus)}:{isRange:!1,isEmpty:!0,text:""}})})))}function z(){const ae=o.getDocumentFacade?.()??null;return ae?.available===!0?ae.doc:null}function Z(){const ae=z();return!!(ae?.comments&&ae.trackChanges)}function P(ae){if(!yp(nf(ae)))return[];const Ce=jL.filter(xe=>{const qe=wS(xe);return qe!==null&&bp(ae,qe)}),oe=Z()?bS.filter(xe=>{const qe=CS(xe);return qe!==null&&bp(ae,qe)}):[];return[...Ce,...oe,...GL]}function N(ae=a){const Ce=nf(ae),oe=Ce!=="disposed",xe=P(ae);return{lifecycle:{canFocus:oe,canDispose:!0},selection:{canReadSelectedText:!0,canReadSelectionSnapshot:!0,canMintPositionTokens:!0},commands:{canDispatch:yp(Ce)&&xe.length>0,supportedCommands:xe},layout:{supported:!0,hasSyncSnapshot:!0},zoom:{supported:!0,min:25,max:400},navigation:{supported:!1,targets:[]},persistence:{canSave:!0,canExportDocx:!0},comments:{supported:!0,canMutate:ae.commentCommandsReason!=="author-required"&&["comments.create","comments.resolve","comments.reopen","comments.delete","comments.reply","comments.edit"].some(qe=>xe.includes(qe))},trackedChanges:{supported:!0,canDecide:xe.includes("trackedChanges.accept")||xe.includes("trackedChanges.reject"),canToggleAuthoring:yp(Ce)}}}function I(){const ae=o.getPageMetricsSnapshot();return{pageCount:ae.pages.length,currentPage:1,zoom:ae.zoom.percent}}function L(ae=a){return{id:t,kind:"v2",documentId:n,state:nf(ae),documentMode:ae.documentMode,reason:ae.reason,capabilities:N(ae)}}function X(ae){return ae?.success===!0?(C(),{status:"committed",receipt:ae}):ae&&"failure"in ae?{status:"receipt-failure",failure:ae.failure}:{status:"rejected",reason:"command-failed"}}function te(ae,Ce){return Ce?Ce.noop===!0?{status:"history-noop",reason:kS(ae,Ce),result:Ce}:(C(),{status:"history-committed",result:Ce}):{status:"rejected",reason:"command-failed"}}async function le(ae){const Ce=CS(ae.kind);if(Ce&&!bp(a,Ce)){const qe=SS(a,Ce);return{status:"rejected",reason:qe.reason,detail:qe.detail}}const oe=wS(ae.kind);if((ae.kind==="history.undo"||ae.kind==="history.redo")&&oe&&!bp(a,oe)){const qe=SS(a,oe);return{status:"rejected",reason:qe.reason,detail:qe.detail}}const xe=z();if(!xe)return bS.includes(ae.kind)?{status:"rejected",reason:"review-command-unavailable"}:null;try{switch(ae.kind){case"comments.create":{const qe=await xe.selection?.current?.(),et=qe?.empty===!1?qe.target:void 0;return X(await xe.comments?.create?.({text:ae.text,...et?{target:et}:{}}))}case"comments.resolve":return X(await xe.comments?.patch?.({commentId:ae.commentId,status:"resolved"}));case"comments.reopen":return X(await xe.comments?.patch?.({commentId:ae.commentId,status:"active"}));case"comments.delete":return X(await xe.comments?.delete?.({commentId:ae.commentId}));case"comments.reply":return X(await xe.comments?.create?.({parentCommentId:ae.parentCommentId,text:ae.text}));case"comments.edit":return X(await xe.comments?.patch?.({commentId:ae.commentId,text:ae.text}));case"trackedChanges.accept":return X(await xe.trackChanges?.decide?.({decision:"accept",target:{kind:"id",id:ae.id}}));case"trackedChanges.reject":return X(await xe.trackChanges?.decide?.({decision:"reject",target:{kind:"id",id:ae.id}}));case"trackedChanges.acceptAll":return X(await xe.trackChanges?.decide?.({decision:"accept",target:{kind:"all"}}));case"trackedChanges.rejectAll":return X(await xe.trackChanges?.decide?.({decision:"reject",target:{kind:"all"}}));case"history.undo":return te("history.undo",await xe.history?.undo?.());case"history.redo":return te("history.redo",await xe.history?.redo?.());default:return null}}catch(qe){return{status:"rejected",reason:"command-failed",detail:qe instanceof Error?qe.message:String(qe)}}}function fe(ae){a=ae,C(),B(),y({type:"state-change",state:nf(ae)}),y({type:"capabilities-change",capabilities:N(ae)}),ae.state==="disposed"&&!l&&(l=!0,p?.(),g?.(),m?.(),m=null,y({type:"disposed"}),S.clear(),u||(u=!0,s?.(t)))}p=o.subscribe(fe),g=o.subscribePageMetrics?.(()=>{y({type:"layout-change",layout:I()})})??null,B();async function Fe(ae){const Ce=nf(a);if(Ce==="disposed")return{status:"rejected",reason:"runtime-not-ready"};if(Ce==="saving")return{status:"rejected",reason:"host-saving"};if(!yp(Ce))return{status:"rejected",reason:"runtime-not-ready"};const oe="at"in ae?ae.at:"range"in ae?ae.range:void 0;if(oe){const kt=R(oe);return kt.ok?{status:"rejected",reason:"target-unsupported",detail:"positioned dispatch is deferred until the shared runtime can target host selections explicitly"}:{status:"rejected",reason:kt.reason}}if(ae.kind==="trackedChanges.setAuthoringMode")return o.setDocumentMode(ae.mode==="tracked"?"suggesting":"editing"),C(),{status:"committed"};const xe=await le(ae);if(xe)return xe;let qe=null;switch(ae.kind){case"text.insert":qe={kind:"text.insert",text:ae.text};break;case"text.replace":qe={kind:"text.replace",text:ae.text};break;case"text.deleteBackward":qe={kind:"text.deleteBackward"};break;case"text.deleteForward":qe={kind:"text.deleteForward"};break;case"text.paste":qe={kind:"text.pastePlain",text:ae.text};break;case"history.undo":qe={kind:"history.undo"};break;case"history.redo":qe={kind:"history.redo"};break;case"structural.splitBlock":qe={kind:"structural.enter"};break;case"structural.indent":qe={kind:"structural.listIndent"};break;case"structural.outdent":qe={kind:"structural.listOutdent"};break;default:return{status:"rejected",reason:"command-unsupported",detail:ae.kind}}const et=await o.dispatch(qe);switch(et.status){case"committed":return C(),{status:"committed",receipt:et.receipt};case"history-committed":return C(),{status:"history-committed",result:et.result};case"history-noop":return{status:"history-noop",reason:kS(ae.kind,et.result),result:et.result};case"receipt-failure":return{status:"receipt-failure",failure:et.failure};case"rejected":return{status:"rejected",reason:AS(et.rejection.code),detail:et.rejection.detail}}}async function he(ae){if(l||a.state==="disposed")return!1;const Ce=c?.focus;return Ce&&typeof Ce.focus=="function"?await Ce.focus({restoreSelection:ae?.restoreSelection,preventScroll:ae?.preventScroll})!==!1:typeof r.focus=="function"?(r.focus({preventScroll:ae?.preventScroll}),!0):!1}async function ge(){l||(await o.dispose(),l||(l=!0,p?.(),g?.(),m?.(),m=null,y({type:"disposed"}),S.clear(),u||(u=!0,s?.(t))))}return{runtime:{id:t,kind:"v2",documentId:n,root:r,getCapabilities:()=>N(),getSnapshot:()=>L(),setDocumentMode(ae){o.setDocumentMode(ae)},getDocumentMode:()=>o.getDocumentMode(),getLegacyEditorProjection:()=>i?.()??VL,focus:he,dispose:ge,dispatch:Fe,getSelectedText:()=>"",getSelectionSnapshot:H,getToolbarState(){return{activeMarks:[],disabled:["formatting.applyMark","formatting.applyParagraph"]}},getLayoutSnapshot:I,save:()=>o.save(),exportDocx:ae=>o.save({format:"docx",commentExportMode:ae?.commentsType==="clean"?"strip":"preserve"}),async setZoom(ae){const Ce=o.setZoom(ae);return Ce.status==="ok"?{status:"committed"}:{status:"rejected",reason:Ce.reason==="host-disposed"?"runtime-not-ready":"target-unsupported",detail:Ce.reason}},async reveal(ae){if(ae.kind==="position"){const Ce=R(ae.position);if(!Ce.ok)return{status:"rejected",reason:Ce.reason}}return{status:"rejected",reason:"capability-unsupported",detail:`${ae.kind} reveal is not exposed through the shared runtime yet`}},subscribe(ae){return S.add(ae),()=>{S.delete(ae)}}},attachMountHandle(ae){c=ae,B()}}}var IS=".superdoc-toolbar";function XL(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.items)?e.items:[]}function QL(e){if(e&&typeof e=="object"){const t=e;return t.target??t.address??t.handle??e}return e}function wp(e){return typeof e=="function"}function ES(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}function Cp(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function ZL(e){return Cp(e)&&e.kind==="text"&&Array.isArray(e.segments)&&e.segments.length>0}function JL(e){return Cp(e)&&e.kind==="story"&&(e.storyType==="headerFooterSlot"||e.storyType==="headerFooterPart")}function $L(e){if(!wp(e.selection?.current))return{handled:!1,reason:"page-field-selection-unavailable"};let t;try{t=e.selection.current({includeText:!1})}catch{return{handled:!1,reason:"page-field-selection-unavailable"}}return ES(t)?{handled:!1,reason:"page-field-selection-async"}:!Cp(t)||!ZL(t.target)?{handled:!1,reason:"page-field-selection-unavailable"}:JL(t.target.story)?{handled:!0,target:t.target}:{handled:!1,reason:"page-field-context-unavailable"}}function t0(e,t){return!wp(e)||!wp(t)?!1:(Promise.resolve().then(()=>e()).then(n=>{for(const r of XL(n))try{Promise.resolve(t({target:QL(r)})).catch(()=>{})}catch{}}).catch(()=>{}),!0)}function eD(e){return{focusToolbar:()=>{const o=e.resolveToolbarElement();if(!o)return{handled:!1,reason:"no-toolbar"};const i=typeof o.matches=="function"&&o.matches(IS)?o:o.querySelector?.(IS)??o;return i?(i.hasAttribute("tabindex")||i.setAttribute("tabindex","0"),typeof i.focus!="function"?{handled:!1,reason:"no-toolbar"}:(i.focus(),!0)):{handled:!1,reason:"no-toolbar"}},updateFields:()=>{const o=e.getDocumentApi();if(!o)return{handled:!1,reason:"document-api-unavailable"};let i=t0(o.toc?.list,o.toc?.update);return i=t0(o.fields?.list,o.fields?.rebuild)||i,i=t0(o.index?.list,o.index?.rebuild)||i,i?!0:{handled:!1,reason:"field-update-workflow-unavailable"}},insertPageField:o=>{const i=e.getDocumentApi();if(!i)return{handled:!1,reason:"document-api-unavailable"};if(!wp(i.fields?.insert))return{handled:!1,reason:"page-field-insert-unavailable"};const s=$L(i);if(!s.handled||!s.target)return{handled:!1,reason:s.reason??"page-field-context-unavailable"};const a=o==="page"?"PAGE":"NUMPAGES";try{const l=i.fields.insert({at:s.target,instruction:a,mode:"raw"});if(ES(l))l.catch(()=>{});else if(Cp(l)&&l.success===!1)return{handled:!1,reason:"page-field-insert-failed"}}catch{return{handled:!1,reason:"page-field-insert-failed"}}return!0}}}const _p="data-superdoc-runtime-id";function tD(e,t){e.setAttribute(_p,t)}function xS(e){e.removeAttribute(_p)}function TS(e){if(typeof e!="string"||e.length===0)return"<none>";try{const t=new URL(e);t.search="",t.hash="",t.username="",t.password="";const n=e.includes("?")?"?<redacted>":"";return`${t.toString().replace(/\?$/,"")}${n}`}catch{const t=e.replace(/\/\/[^/@]+@/,"//"),n=t.search(/[?#]/);return n===-1?t:`${t.slice(0,n)}?<redacted>`}}function Sp(e){return typeof e=="string"&&e.length>0?e:null}function nD(e){if(typeof e!="string"||e.length===0)return null;try{const t=new URL(e);return t.protocol==="ws:"||t.protocol==="wss:"?e:null}catch{return null}}function rD(e,t){if(typeof e!="string")return null;const n=e.trim();if(n.length===0)return null;try{const r=new URL(n);return r.protocol==="http:"||r.protocol==="https:"?n:null}catch{if(typeof t!="string"||t.trim().length===0)return null;try{const r=new URL(n,t);return r.protocol==="http:"||r.protocol==="https:"?r.href:null}catch{return null}}}function oD(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function RS(e){return e===void 0?"join":e==="join"||e==="create"?e:null}function MS(){return{ok:!1,reason:"invalid-room-mode",message:'SuperDoc v2 collaboration roomMode must be either "join" or "create".'}}function iD(e){const t=e.providerType;return typeof t=="string"&&t.length>0?t.toLowerCase():null}function sD(e){if(!e||typeof e!="object")return null;const t=typeof e.providerType=="string"?e.providerType.toLowerCase():"";return t==="hocuspocus"?"hocuspocus":t==="liveblocks"?"liveblocks":t==="superdoc"?"superdoc":e.ydoc!=null||e.provider!=null?"external-ydoc-provider":null}function LS(e,t){const n=Sp(t.documentId);if(!n)return{ok:!1,reason:"invalid-document-id",message:`SuperDoc v2 collaboration requires a non-empty v2Collaboration.documentId for the "${e}" provider.`};const r=t.url??t.serverUrl,o=nD(r);if(!o)return{ok:!1,reason:"invalid-server-url",message:`SuperDoc v2 collaboration requires a valid ws:// or wss:// URL for the "${e}" provider (received: ${TS(r)}).`};const i=oD(t.params),s=e==="hocuspocus"?Sp(t.token):null,a=RS(t.roomMode);return a?{ok:!0,target:{providerFamily:e,documentId:n,roomMode:a,serverUrl:o,...i?{params:i}:{},...s?{token:s}:{}}}:MS()}function aD(e,t){const n=Sp(e.documentId??e.roomId);if(!n)return{ok:!1,reason:"invalid-document-id",message:'SuperDoc v2 collaboration requires a non-empty v2Collaboration.documentId (or roomId) for the "liveblocks" provider.'};const r=Sp(e.publicApiKey),o=RS(e.roomMode);if(!o)return MS();const i=e.authEndpoint,s=typeof i=="string"&&i.length>0;if(!r&&!s)return{ok:!1,reason:"missing-auth",message:"SuperDoc v2 Liveblocks collaboration requires exactly one auth mode: a publicApiKey or an authEndpoint. None was provided."};if(r&&s)return{ok:!1,reason:"mixed-auth",message:"SuperDoc v2 Liveblocks collaboration accepts exactly one auth mode; pass either publicApiKey or authEndpoint, not both."};if(r)return{ok:!0,target:{providerFamily:"liveblocks",documentId:n,roomMode:o,publicApiKey:r}};const a=rD(i,t);return a?{ok:!0,target:{providerFamily:"liveblocks",documentId:n,roomMode:o,authEndpoint:a}}:{ok:!1,reason:"invalid-auth-endpoint",message:"SuperDoc v2 Liveblocks collaboration requires a valid http(s) authEndpoint URL (received: <redacted>)."}}function DS(e){const{v2Collaboration:t,legacyCollaboration:n,documentType:r,documentCount:o,authEndpointBaseUrl:i}=e;if(typeof o=="number"&&o>1)return{ok:!1,reason:"unsupported-multi-document",message:`SuperDoc v2 collaboration supports exactly one document per room; received ${o}.`};if(r!=null&&r!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")return{ok:!1,reason:"unsupported-document-type",message:"SuperDoc v2 collaboration supports DOCX documents only."};if(!(t!=null&&typeof t=="object")){const l=sD(n);if(l){const u=l==="external-ydoc-provider"?"unsupported-legacy-provider":"unsupported-provider-family",c=TS(n?.url);return{ok:!1,reason:u,message:l==="external-ydoc-provider"?"SuperDoc v2 collaboration cannot use an external { ydoc, provider } pair. Provide a v2Collaboration target (e.g. { providerType, documentId, url }) instead.":`SuperDoc v2 collaboration does not accept "${l}" through the legacy modules.collaboration block (server: ${c}). Configure it as a v2Collaboration target ({ providerType: "${l}", documentId, ... }) instead.`}}return{ok:!1,reason:"missing-target",message:"SuperDoc v2 collaboration requires a v2Collaboration target ({ documentId, serverUrl } or { providerType, ... }). None was provided."}}const s=t;if(Object.prototype.hasOwnProperty.call(s,"createIfMissing"))return{ok:!1,reason:"invalid-room-mode",message:'SuperDoc v2 collaboration createIfMissing has been removed. Use roomMode: "create" for creation or roomMode: "join" for normal opens.'};if(s.ydoc!=null||s.provider!=null)return{ok:!1,reason:"unsupported-legacy-provider",message:"SuperDoc v2 collaboration cannot use an external { ydoc, provider } pair. v2 owns its provider; pass a v2Collaboration target ({ providerType, documentId, url | publicApiKey | authEndpoint }) instead."};const a=iD(s);return a===null||a==="y-websocket"?LS("y-websocket",s):a==="hocuspocus"?LS("hocuspocus",s):a==="liveblocks"?aD(s,i):{ok:!1,reason:"unsupported-provider-family",message:`SuperDoc v2 collaboration does not support the "${a}" provider family. Supported families are y-websocket, hocuspocus, and liveblocks.`}}It(),gn();var lD={__name:"SurfaceExternalMount",props:{surfaceId:{type:String,required:!0},mode:{type:String,required:!0},request:{type:Object,required:!0},render:{type:Function,required:!0},resolve:{type:Function,required:!0},close:{type:Function,required:!0}},setup(e){const t=e,n=ne(null);let r=null;function o(){i(),!(!n.value||!t.render)&&(r=t.render({container:n.value,surfaceId:t.surfaceId,mode:t.mode,request:t.request,resolve:t.resolve,close:t.close})?.destroy??null)}function i(){typeof r=="function"&&r(),r=null,n.value&&(n.value.innerHTML="")}return Rn(o),ir(i),Pt(()=>t.surfaceId,()=>{o()}),(s,a)=>(me(),_e("div",{ref_key:"container",ref:n,class:"sd-surface-external-mount"},null,512))}},PS=hn(lD,[["__scopeId","data-v-b2412c5d"]]);const n0=["a[href]","button:not([disabled])","textarea:not([disabled])","input:not([disabled])","select:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");It(),gn();var cD=["aria-labelledby","aria-label"],uD=["id"],dD={class:"sd-surface-dialog__content"},fD={__name:"SurfaceDialog",props:{surface:{type:Object,required:!0},scrollLockTarget:{type:Object,default:null}},emits:["close"],setup(e,{emit:t}){const n=e,r=t,o=ne(null),i=Se(()=>n.surface.request.title?`sd-surface-title-${n.surface.id}`:void 0),s=Se(()=>i.value??n.surface.request.ariaLabelledBy??void 0),a=Se(()=>s.value?void 0:n.surface.request.ariaLabel);let l=null;function u(T){if(!o.value)return;const R=o.value.querySelectorAll(n0);if(R.length===0)return;const M=R[0],H=R[R.length-1];T.shiftKey&&document.activeElement===M?(T.preventDefault(),H.focus()):!T.shiftKey&&document.activeElement===H&&(T.preventDefault(),M.focus())}function c(){if(!o.value)return;const T=o.value.querySelector(n0);T?T.focus():o.value.focus()}let d=null,h="";function m(){if(n.scrollLockTarget)d=n.scrollLockTarget;else{const T=o.value?.closest(".superdoc");d=T?.querySelector(".superdoc__layers")??T}d&&(h=d.style.overflow,d.style.overflow="hidden")}function p(){d&&(d.style.overflow=h,d=null,h="")}function g(T){if(T.key==="Tab"){u(T);return}T.key==="Escape"&&n.surface.request.closeOnEscape!==!1&&(T.stopPropagation(),r("close"))}function k(T){T.target===T.currentTarget&&n.surface.request.closeOnBackdrop!==!1&&r("close")}const w=Se(()=>({surfaceId:n.surface.id,mode:"dialog",request:n.surface.request,resolve:n.surface.resolve,close:n.surface.close})),S=Se(()=>({...n.surface.props??{},...w.value})),y=Se(()=>{const T=n.surface.request.dialog?.maxWidth;if(T!=null)return typeof T=="number"?`${T}px`:T}),C=Se(()=>{const T={};return y.value&&(T["max-width"]=y.value),T});return Rn(async()=>{l=document.activeElement,m(),await _t(),c()}),Pt(()=>n.scrollLockTarget,(T,R)=>{T!==R&&(p(),m())}),ir(()=>{p(),l&&typeof l.focus=="function"&&l.focus(),l=null}),(T,R)=>(me(),_e("div",{class:"sd-surface-dialog-backdrop",onMousedown:Jt(k,["self"]),onKeydown:g},[Le("div",{ref_key:"dialogRef",ref:o,class:"sd-surface-dialog",style:vn(C.value),role:"dialog","aria-modal":"true","aria-labelledby":s.value,"aria-label":a.value,tabindex:"-1"},[e.surface.request.title?(me(),_e("div",{key:0,id:i.value,class:"sd-surface-dialog__title"},Ht(e.surface.request.title),9,uD)):ut("",!0),Le("div",dD,[e.surface.render?(me(),fn(PS,{key:0,"surface-id":e.surface.id,mode:"dialog",request:e.surface.request,render:e.surface.render,resolve:e.surface.resolve,close:e.surface.close},null,8,["surface-id","request","render","resolve","close"])):e.surface.component?(me(),fn(yg(e.surface.component),Om(cs({key:1},S.value)),null,16)):ut("",!0)])],12,cD)],32))}},hD=hn(fD,[["__scopeId","data-v-20bf8e4b"]]);It(),gn();var pD=["aria-labelledby","aria-label"],mD=["id"],gD={class:"sd-surface-floating__content"},vD={__name:"SurfaceFloating",props:{surface:{type:Object,required:!0}},setup(e,{expose:t}){const n=e,r=ne(null);t({rootEl:r});const o=ne({}),i=Se(()=>n.surface.request.title?`sd-surface-title-${n.surface.id}`:void 0),s=Se(()=>i.value??n.surface.request.ariaLabelledBy??void 0),a=Se(()=>s.value?void 0:n.surface.request.ariaLabel),l=Se(()=>n.surface.request.floating??{}),u=Se(()=>{const y=l.value;return y.top!=null||y.right!=null||y.bottom!=null||y.left!=null}),c=Se(()=>{const y=["sd-surface-floating"];if(!u.value){const C=l.value.placement??"top-right";y.push(`sd-surface-floating--${C}`)}return y});function d(y){if(y!=null)return typeof y=="number"?`${y}px`:y}const h=Se(()=>{const y=l.value,C={};return y.top!=null&&(C.top=d(y.top)),y.right!=null&&(C.right=d(y.right)),y.bottom!=null&&(C.bottom=d(y.bottom)),y.left!=null&&(C.left=d(y.left)),y.width!=null&&(C.width=d(y.width)),y.maxWidth!=null&&(C["max-width"]=d(y.maxWidth)),y.maxHeight!=null&&(C["max-height"]=d(y.maxHeight)),{...C,...o.value}});async function m(){if(o.value={},!u.value)return;await _t(),await new Promise(z=>requestAnimationFrame(z));const y=r.value,C=y?.parentElement;if(!y||!C)return;const T=8,R=y.getBoundingClientRect(),M=C.getBoundingClientRect(),H={},B=l.value;if(B.left!=null&&B.right==null){const z=R.left-M.left,Z=Math.max(T,M.width-R.width-T),P=Math.min(Math.max(z,T),Z);P!==z&&(H.left=`${P}px`)}if(B.top!=null&&B.bottom==null){const z=R.top-M.top,Z=Math.max(T,M.height-R.height-T),P=Math.min(Math.max(z,T),Z);P!==z&&(H.top=`${P}px`)}o.value=H}Pt(l,m,{deep:!0});const p=Se(()=>({surfaceId:n.surface.id,mode:"floating",request:n.surface.request,resolve:n.surface.resolve,close:n.surface.close})),g=Se(()=>({...n.surface.props??{},...p.value}));let k=null,w=!1,S=null;return Rn(async()=>{if(m(),window.addEventListener("resize",m),typeof ResizeObserver<"u"&&r.value?.parentElement&&(S=new ResizeObserver(m),S.observe(r.value.parentElement),S.observe(r.value)),l.value.autoFocus===!1||(await _t(),!r.value))return;const y=r.value.querySelector("[data-sd-autofocus]")??r.value.querySelector(n0);y&&(k=document.activeElement,y.focus(),w=!0)}),ir(()=>{window.removeEventListener("resize",m),S?.disconnect(),S=null,w&&k&&typeof k.focus=="function"&&k.focus(),k=null,w=!1}),(y,C)=>(me(),_e("div",{ref_key:"floatingRef",ref:r,class:en(c.value),style:vn(h.value),role:"dialog","aria-labelledby":s.value,"aria-label":a.value,"data-editor-ui-surface":""},[e.surface.request.title?(me(),_e("div",{key:0,id:i.value,class:"sd-surface-floating__title"},Ht(e.surface.request.title),9,mD)):ut("",!0),Le("div",gD,[e.surface.render?(me(),fn(PS,{key:0,"surface-id":e.surface.id,mode:"floating",request:e.surface.request,render:e.surface.render,resolve:e.surface.resolve,close:e.surface.close},null,8,["surface-id","request","render","resolve","close"])):e.surface.component?(me(),fn(yg(e.surface.component),Om(cs({key:1},g.value)),null,16)):ut("",!0)])],14,pD))}},yD=hn(vD,[["__scopeId","data-v-cd2be5db"]]);It(),gn();var bD={__name:"SurfaceHost",props:{geometryTarget:{type:Object,default:null}},setup(e){const t=e,n=La("surfaceManager",null),r=Se(()=>n?.activeDialog.value??null),o=Se(()=>n?.activeFloating.value??null),i=Se(()=>r.value!=null||o.value!=null),s=ne(null),a=ne(null),l=ne({}),u=new Set(["hidden","scroll","auto","clip"]);function c(N){const I=[];let L=N.parentElement;for(;L;){const X=getComputedStyle(L);(u.has(X.overflowX)||u.has(X.overflowY))&&I.push(L),L=L.parentElement}return I}function d(N,I){let L=0,X=0,te=window.innerWidth,le=window.innerHeight;for(const Fe of I){const he=Fe.getBoundingClientRect(),ge=getComputedStyle(Fe);u.has(ge.overflowX)&&(X=Math.max(X,he.left),te=Math.min(te,he.right)),u.has(ge.overflowY)&&(L=Math.max(L,he.top),le=Math.min(le,he.bottom))}const fe=N.getBoundingClientRect();return L=Math.max(L,fe.top),X=Math.max(X,fe.left),te=Math.min(te,fe.right),le=Math.min(le,fe.bottom),{top:L,left:X,width:Math.max(te-X,0),height:Math.max(le-L,0)}}let h=null,m=[],p=0,g=null;function k(){if(!h)return;const{top:N,left:I,width:L,height:X}=d(h,m);l.value={position:"fixed",top:`${N}px`,left:`${I}px`,width:`${L}px`,height:`${X}px`}}function w(){p||(p=requestAnimationFrame(()=>{p=0,k()}))}function S(){if(h=t.geometryTarget??null,!!h){m=c(h),k(),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),g=new ResizeObserver(w),g.observe(h);for(const N of m)g.observe(N)}}function y(){p&&(cancelAnimationFrame(p),p=0),window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w),g&&(g.disconnect(),g=null),h=null,m=[]}Pt(i,N=>{N?S():y()}),Pt(()=>t.geometryTarget,N=>{N&&i.value&&!h&&S()}),Rn(()=>{i.value&&S()});function C(N){const I=o.value;!I||I.settled||r.value||N.key==="Escape"&&I.request.closeOnEscape!==!1&&(N.stopPropagation(),n.close(I.id))}let T=!1;function R(){T||(document.addEventListener("keydown",C,!0),T=!0)}function M(){T&&(document.removeEventListener("keydown",C,!0),T=!1)}function H(N){const I=o.value;if(!I||I.settled||r.value)return;const L=a.value?.rootEl;L&&!L.contains(N.target)&&n.close(I.id)}let B=!1;function z(){B||(document.addEventListener("pointerdown",H,!0),B=!0)}function Z(){B&&(document.removeEventListener("pointerdown",H,!0),B=!1)}Pt(o,N=>{N&&!N.settled?(R(),N.request.floating?.closeOnOutsidePointerDown?z():Z()):(M(),Z())},{immediate:!0}),ir(()=>{y(),M(),Z()});function P(){const N=r.value;N&&!N.settled&&n.close(N.id)}return(N,I)=>(me(),fn(Oa,{to:"body"},[i.value?(me(),_e("div",{key:0,ref_key:"hostRef",ref:s,class:"sd-surface-host",style:vn(l.value)},[o.value?(me(),fn(yD,{key:o.value.id,surface:o.value,ref_key:"floatingRef",ref:a},null,8,["surface"])):ut("",!0),r.value?(me(),fn(hD,{key:r.value.id,surface:r.value,"scroll-lock-target":Ge(h),onClose:P},null,8,["surface","scroll-lock-target"])):ut("",!0)],4)):ut("",!0)]))}},wD=hn(bD,[["__scopeId","data-v-c6a3b75f"]]),r0,CD=br((()=>{r0=(e,t)=>{const n=10**(t||0);return Math.floor(e*n)/n}})),OS,_D=br((()=>{OS=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>t(o.target.result),r.onerror=n,r.readAsDataURL(e)})})),FS,SD=br((()=>{FS=(e,t)=>{const n=t-e;return Array.from({length:n},(r,o)=>e+o)}}));function kD(e){return`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${e}/pdf.worker.min.mjs`}var BS,NS,zS,HS,AD=br((()=>{SD(),BS=e=>({adapter:"pdfjs",...e}),NS=class VA{constructor(){if(Object.getPrototypeOf(this).constructor===VA)throw new Error("Abstract class should not be instantiated")}},zS=class extends NS{constructor(e){super(),this.pdfLib=e.pdfLib,this.workerSrc=e.workerSrc,e.setWorker&&(this.workerSrc?this.pdfLib.GlobalWorkerOptions.workerSrc=e.workerSrc:this.pdfLib.GlobalWorkerOptions.workerSrc=kD(this.pdfLib.version))}async getDocument(e){return await this.pdfLib.getDocument(e).promise}async getPages(e,t,n){const r=FS(t,n+1).map(o=>e.getPage(o));return await Promise.all(r)}},HS=class{static create(e){const t={pdfjs:()=>new zS(e),default:()=>{throw new Error("Unsupported adapter")}};return(t[e.adapter]??t.default)()}}})),ID=br((()=>{})),ED=br((()=>{})),US,VS,jS,GS,xD=br((()=>{It(),qy(),ID(),ED(),gn(),US=["data-page-id","data-page-number"],VS={class:"sd-pdf-viewer-page__canvas-wrapper"},jS={__name:"PdfViewerPage",props:{config:{type:Object,required:!0},page:{type:Object,required:!0},pages:{type:Array,required:!0},scale:{type:Number,required:!0},hasTextLayer:{type:Boolean,default:!1},outputScale:{type:Number,default:2},documentEl:{type:[Object],default:null}},emits:["page-rendered","page-error","text-layer-rendered","text-layer-error","selection-raw","bypass-selection"],setup(e,{emit:t}){const n=t,r=e,o=Ur(null),i=ne(null),s=ne(null),a=ne(null);let l;const u=Se(()=>r.pages.findIndex(z=>z.pageId===r.page.pageId)),c=Se(()=>u.value===-1?0:u.value+1);function d(z){const Z=window.getSelection();if(!Z||Z.rangeCount===0)return null;const P=Z.getRangeAt(0).getClientRects();if(!P.length)return null;const N=z.getBoundingClientRect(),I=r.scale??1,L=P[0];let X={top:L.top,left:L.left,bottom:L.bottom,right:L.right};for(let te=1;te<P.length;te+=1){const le=P[te];le.width===0||le.height===0||(X.top=Math.min(X.top,le.top),X.left=Math.min(X.left,le.left),X.bottom=Math.max(X.bottom,le.bottom),X.right=Math.max(X.right,le.right))}return{top:(X.top-N.top)/I+z.scrollTop,left:(X.left-N.left)/I+z.scrollLeft,bottom:(X.bottom-N.top)/I+z.scrollTop,right:(X.right-N.left)/I+z.scrollLeft}}const h=Se(()=>{let{width:z,height:Z}=o.value;return[z,Z]=[z,Z].map(P=>Math.ceil(P)),{width:z,height:Z}}),m=Se(()=>{const{width:z,height:Z}=h.value;return{width:z,height:Z}}),p=Se(()=>{const{width:z,height:Z}=w();return{"--scale-factor":`${y()}`,width:`calc(var(--scale-factor) * ${z}px)`,height:`calc(var(--scale-factor) * ${Z}px)`}});function g(){const z=window.getSelection();if(!z||z.toString().length===0)return;const Z=d(r.documentEl?.value??r.documentEl??i.value);Z&&n("selection-raw",{selectionBounds:Z,documentId:r.page.documentId,page:c.value,source:"pdf"})}function k(z){z?.target&&z.target.tagName!=="SPAN"&&n("bypass-selection",z)}function w(){const z=qa*r.outputScale;let{width:Z,height:P}=o.value;return Z=Z/z,P=P/z,[Z,P]=[Z,P].map(N=>Math.ceil(N)),{width:Z,height:P}}function S(){const{width:z,height:Z}=w(),P=y();return{width:z*P,height:Z*P}}function y(){return(r.scale??1)*qa}function C(){const{pdfjsPage:z}=r.page;o.value=z.getViewport({scale:qa*r.outputScale})}async function T(){if(l)return;const z=s.value;if(!z||!o.value)return;const Z={canvasContext:z.getContext("2d"),viewport:o.value};try{const{pdfjsPage:P}=r.page;l=P.render(Z),await l.promise;const N=S(),I=w();n("page-rendered",{page:r.page,documentId:r.page.documentId,pageIndex:u.value,pageNumber:c.value,width:N.width,height:N.height,originalWidth:I.width*qa,originalHeight:I.height*qa})}catch{B(),n("page-error",r.page)}}async function R(){if(!r.hasTextLayer)return;const z=a.value;if(!z)return;z.innerHTML="";const Z=r.config?.pdfLib?.TextLayer;if(Z)try{const P=(r.scale??1)*qa,N=r.page.pdfjsPage.getViewport({scale:P});await new Z({textContentSource:await r.page.pdfjsPage.getTextContent(),container:z,viewport:N}).render(),n("text-layer-rendered",r.page)}catch(P){n("text-layer-error",r.page),console.error(P)}}async function M(){await T(),await R()}function H(z){z?.pdfjsPage&&z.pdfjsPage.cleanup(),B()}function B(){l&&(l.cancel(),l=null)}return Pt(()=>r.scale,()=>{R()}),C(),Rn(()=>{M()}),ir(()=>{H(r.page)}),(z,Z)=>(me(),_e("div",{class:"sd-pdf-viewer-page","data-page-id":e.page.pageId,"data-page-number":c.value,style:vn(p.value),"data-pdf-page":"",ref_key:"pageRef",ref:i,onMousedown:k,onMouseup:g},[Le("div",VS,[Le("canvas",cs({class:"sd-pdf-viewer-page__canvas"},m.value,{ref_key:"canvasRef",ref:s}),null,16)]),e.hasTextLayer?(me(),_e("div",{key:0,class:"sd-pdf-viewer-page__text-layer",ref_key:"textLayerRef",ref:a},null,512)):ut("",!0)],44,US))}},GS=hn(jS,[["__scopeId","data-v-d7a9857d"]])})),TD=br((()=>{})),WS,KS,RD=br((()=>{It(),xD(),TD(),gn(),WS={__name:"PdfViewerDocument",props:{config:{type:Object,required:!0},pdf:{type:Object},pages:{type:Array,required:!0},scale:{type:Number},hasTextLayer:{type:Boolean,default:!1},outputScale:{type:Number}},emits:["page-focus","page-rendered","page-error","selection-raw","bypass-selection"],setup(e,{emit:t}){const n=t,r=ne(null),o=ne(null);function i(u){n("page-rendered",u)}function s(u){n("page-error",u)}function a(u){n("selection-raw",u)}function l(u){n("bypass-selection",u)}return(u,c)=>(me(),_e("div",{class:"sd-pdf-viewer-document",ref_key:"documentRef",ref:r},[Le("div",{class:"sd-pdf-viewer-document__wrapper",ref_key:"documentWrapper",ref:o},[(me(!0),_e(Wt,null,or(e.pages,d=>(me(),fn(GS,cs({key:d.pageId},{ref_for:!0},{page:d,pages:e.pages,scale:e.scale,config:e.config,hasTextLayer:e.hasTextLayer,outputScale:e.outputScale,documentEl:r.value},{onPageRendered:i,onPageError:s,onSelectionRaw:a,onBypassSelection:l}),null,16))),128))],512)],512))}},KS=hn(WS,[["__scopeId","data-v-2152178b"]])})),MD=br((()=>{})),LD=Gu({default:()=>XS},1),qS,YS,XS,DD=br((()=>{It(),CD(),_D(),qy(),AD(),RD(),MD(),gn(),qS={class:"sd-pdf-viewer__main"},YS={__name:"PdfViewer",props:{config:{type:Object,required:!0},file:{type:Object,required:!0},fileId:{type:String},initialScale:{type:Number,default:1}},emits:["page-rendered","pages-loaded","document-loaded","document-ready","document-error","selection-raw","bypass-selection"],setup(e,{expose:t,emit:n}){const r=n,o=e,i=BS({pdfLib:Hr(o.config.pdfLib),workerSrc:o.config.workerSrc,setWorker:o.config.setWorker}),s=HS.create(i),a=ne(null),l=ne(null),u=ne(null),c=ne([]),d=ne(typeof o.initialScale=="number"&&Number.isFinite(o.initialScale)&&o.initialScale>0?r0(o.initialScale,2):1),h=ne(0),m=ne(0),p=Se(()=>o.config?.textLayer===!0),g=Se(()=>o.config?.outputScale??2);function k(Z){const P=Z?.page;P&&(P.pageIsRendered=!0),y(),r("page-rendered",Z)}function w(Z){r("selection-raw",Z)}function S(Z){r("bypass-selection",Z)}function y(){h.value<=0||(m.value+=1,m.value>=h.value&&r("document-ready",{documentId:u.value?.documentId,viewerContainer:a.value}))}function C(Z){c.value=Z,h.value=Z.length,m.value=0}function T(Z){d.value=r0(Z,2)}t({updateScale:T});async function R(Z){if(Z)try{const P=await OS(Z);u.value={documentId:o.fileId||B("document"),pdfjsDocument:Hr(await s.getDocument(P))},r("document-loaded",Z)}catch(P){r("document-error",P),console.error(P)}}async function M(){if(!u.value)return;const{pdfjsDocument:Z}=u.value,P=1,N=Z.numPages;try{const I=await s.getPages(Z,P,N),L=te=>({documentId:u.value.documentId,pageId:z(u.value.documentId,te.pageNumber),pageNumber:te.pageNumber,pageIsRendered:!1,pdfjsPage:Hr(te)}),X=I.map(L);C(X),r("pages-loaded",X)}catch(I){r("document-error",I),console.error(I)}}function H(){c.value=[],d.value=1}function B(Z){return`pdf-${Z.replace(/\W/g,"")}-${Math.random().toString(36).slice(2)}-${Date.now()}`}function z(Z,P){return`${Z}-page-${P}`}return Pt(()=>o.file,Z=>{R(Z)},{immediate:!0}),Pt(u,(Z,P)=>{Z&&(P&&H(),M())}),(Z,P)=>(me(),_e("div",{class:"sd-pdf-viewer",ref_key:"rootRef",ref:a},[Le("div",qS,[Gt(KS,cs({pdf:u.value,pages:c.value,scale:d.value,config:e.config,hasTextLayer:p.value,outputScale:g.value},{onPageRendered:k,onSelectionRaw:w,onBypassSelection:S,ref_key:"documentRef",ref:l}),null,16)])],512))}},XS=hn(YS,[["__scopeId","data-v-05c9d9b5"]])}));It(),gn();var PD={key:0,class:"sd-visually-hidden",role:"status","aria-live":"assertive","data-superdoc-v2-author-required":""},OD=["innerHTML"],FD={class:"superdoc__document document"},BD={class:"floating-comments"},ND=!1,zD=3,o0=6500,i0=8e3,HD={__name:"SuperDoc",emits:["selection-update"],setup(e,{emit:t}){const n=R2(()=>Promise.resolve().then(()=>(DD(),LD))),r=O=>O.password??F.$superdoc.config.password,o=O=>{const q=O?.v2Collaboration,Ee=q&&typeof q=="object"&&"value"in q?q.value:q;if(Ee==null)return{state:"absent"};const Ne=DS({v2Collaboration:Ee,documentType:O?.type??null,documentCount:a.value.length,...typeof window<"u"?{authEndpointBaseUrl:window.location.href}:{}});if(!Ne.ok)return{state:"invalid",failure:{code:Ne.reason==="invalid-room-mode"?"collaboration-open-intent-invalid":"collaboration-config-invalid",message:`SuperDoc rejected the v2 collaboration configuration (${Ne.reason}).`}};const{providerFamily:mt,...nn}=Ne.target;return{state:"valid",config:{providerType:mt,...nn}}},i=nu(),s=ca(),{documents:a,isReady:l,areDocumentsReady:u,selectionPosition:c,activeSelection:d,activeZoom:h,zoomMode:m,measurementUnit:p,viewportMetrics:g}=ea(i),{handlePageReady:k,modules:w,user:S,getDocument:y}=i,C=La("surfaceManager",null),T=tM({getSurfaceManager:()=>C,getPasswordPromptConfig:()=>F.$superdoc?.config?.modules?.surfaces?.passwordPrompt,onUnhandled:(O,q,Ee)=>{F.$superdoc?.emit("exception",{error:Ee?.error??new Error(`Password prompt unhandled: ${q}`),editor:Ee?.editor??null,code:q,documentId:O?.id})}}),{getConfig:R,documentsWithConverations:M,commentsList:H,pendingComment:B,activeComment:z,skipSelectionUpdate:Z,commentsByDocument:P,isCommentsListVisible:N,isFloatingCommentsReady:I,generalCommentIds:L,hasSyncedCollaborationComments:X,editorCommentPositions:te,hasInitializedLocations:le,isCommentHighlighted:fe,hasOpenTrackedChanges:Fe}=ea(s),{showAddComment:he,handleEditorLocationsUpdate:ge,handleTrackedChangeUpdate:ae,refreshTrackedChangeCommentsByIds:Ce,syncTrackedChangePositionsWithDocument:oe,syncTrackedChangeComments:xe,addComment:qe,addHydratedComment:et,getComment:kt,resolveCommentPositionEntry:Ie,belongsToDocument:ze,COMMENT_EVENTS:Ve,requestInstantSidebarAlignment:Q,peekInstantSidebarAlignment:_,clearInstantSidebarAlignment:$}=s,{proxy:F}=sr();s.proxy=F;const j=wT(F.$superdoc.config),V=Hr(j.EditorComponent),G=j.RulerComponent?Hr(j.RulerComponent):null,J=Se(()=>{const O=Ge(s.getFloatingComments);return Array.isArray(O)?O:[]}),{isHighContrastMode:K}=zi(),{uiFontFamily:W}=jy(),ue=()=>s.viewingVisibility.documentMode==="viewing",be=()=>!!F?.$superdoc?.config?.allowSelectionInViewMode,we=Se(()=>ue()&&s.viewingVisibility.commentsVisible===!0),Te=Se(()=>F?.$superdoc?.uiConfig?.search?.enabled===!0);Se(()=>ue()&&s.viewingVisibility.trackChangesVisible===!0);const rt=Se(()=>s.shouldRenderReviewInViewing),nt=Se(()=>F.$superdoc.config.proofing!==void 0?F.$superdoc.config.proofing:F.$superdoc.config.layoutEngineOptions?.proofing),wt=Se(()=>{const O=w.comments;return O===!1||O==null?null:O}),Zt=Se(()=>{const O={"--sd-ui-font-family":W.value},q=F.$superdoc.config.modules?.comments;if(!q||q===!1)return O;q.highlightHoverColor&&(O["--sd-comments-highlight-hover"]=q.highlightHoverColor);const Ee={...q.trackChangeHighlightColors||{},...q.trackChangeActiveHighlightColors||{}};return Ee.insertBorder&&(O["--sd-tracked-changes-insert-border"]=Ee.insertBorder),Ee.insertBackground&&(O["--sd-tracked-changes-insert-background"]=Ee.insertBackground),Ee.deleteBorder&&(O["--sd-tracked-changes-delete-border"]=Ee.deleteBorder),Ee.deleteBackground&&(O["--sd-tracked-changes-delete-background"]=Ee.deleteBackground),Ee.formatBorder&&(O["--sd-tracked-changes-format-border"]=Ee.formatBorder),O}),Ct=ne(null),Ot=ne(null),Bt=ne(null),on=ne(null),Fn=ne(!1),Vt=zr({top:null,right:"-25px",zIndex:101}),{superdocContainerWidth:We,isCompactCommentsMode:St,recalculateCompactCommentsMode:Nt,ensureCompactMeasurementObserver:cn}=k9({commentsModuleConfig:wt,superdocRoot:Ct,layers:Ot}),Dt=Se(()=>!0),un=Ur(null),Ft=ne(!1),Me=ne(null);let Pe=0;const Ze=Se(()=>F.$superdoc.activeEditor),ot=()=>F.$superdoc?.ui??null,Mt=Object.freeze({enabled:!1,active:!1,supported:!1}),Et=sM({getSurfaceManager:()=>C,getActiveEditor:()=>F.$superdoc?.activeEditor,activeEditorRef:Ze,getFindReplaceConfig:()=>F.$superdoc?.config?.modules?.surfaces?.findReplace,getSuperDocUI:ot}),Tt=UL({getSurfaceManager:()=>C||(typeof F.$superdoc?.openSurface!="function"?null:{open:O=>F.$superdoc.openSurface(O)}),getActiveEditor:()=>F.$superdoc?.activeEditor,getUi:ot,getResolver:()=>F.$superdoc?.uiConfig?.linkPopover?.suppressed?()=>({type:"none"}):F.$superdoc?.config?.modules?.links?.popoverResolver,getLayerElement:()=>Ot.value,emitException:O=>{F.$superdoc?.emit("exception",{...O,editor:F.$superdoc?.activeEditor??null})}}),ur=F.$superdoc.config.modules?.pdf||{},dr=()=>{Fn.value&&(Fn.value=!1,xe({superdoc:F.$superdoc,editor:F.$superdoc?.activeEditor}))},jr=()=>{Fn.value=!0,_t(()=>{dr()})},$t=(O,q)=>{const Ee=y(O);Ee.isReady=!0,Ee.container=q,u.value&&(F.$superdoc.config.collaboration||(l.value=!0)),dt(),I.value=!0,le.value=!0,F.$superdoc.broadcastPdfDocumentReady()},Vn=()=>{if(!c.value||!Ot.value)return null;const O=c.value.source==="pdf"?(h.value??100)/100:1,q=Number(c.value.top);return Number.isFinite(q)?Ot.value.getBoundingClientRect().top+q*O:null},Mr=async()=>{if((await he(F.$superdoc,Vn()))?.ok===!1||!Dt.value)return;const O=Cu();O&&_u(O)},_r=async O=>{const q={comments:()=>Mr()};O in q&&await q[O](d.value,c.value),d.value=null,Vt.top=null},po=()=>Vt.top=null,Kt=new Map,yn=new Map,xo=new Map,Zo=new Map;let Ei=0;const pi=O=>{const q=xo.get(O);if(q){xo.delete(O);try{q.unbind?.()}catch(Ee){console.warn("[SuperDoc] v2 command-shortcut unbind failed",Ee)}}},Ss=()=>{const O=F.$superdoc?.toolbar;return!O||typeof O.getToolbarItemByName!="function"?null:()=>{const q=O.getToolbarItemByName("link");!q||q.disabled?.value===!0||(q.expand&&typeof q.expand=="object"&&"value"in q.expand&&(q.expand.value=!0),O.updateToolbarState?.())}},ks=({documentId:O,bindEditShortcuts:q})=>{if(!O||(pi(O),typeof q!="function"))return;const Ee=Ss(),Ne=q({commandRoute:{executeAsync:(mt,nn)=>{const pn=ot();return pn?pn.commands.executeAsync(mt,nn):Promise.resolve(ND)},getState:mt=>ot()?.commands.get(mt).getState()??Mt},...Ee?{openLinkWorkflow:Ee}:{}});xo.set(O,{unbind:Ne})},As=O=>{const q=Zo.get(O);if(q){Zo.delete(O);try{q.unbind?.()}catch(Ee){console.warn("[SuperDoc] v2 session-shortcut unbind failed",Ee)}}},al=({documentId:O,bindSessionShortcuts:q,documentApi:Ee})=>{if(!O||(As(O),typeof q!="function"))return;const Ne=q({routes:eD({resolveToolbarElement:()=>F.$superdoc?.toolbar?.toolbarContainer??null,getDocumentApi:()=>Ee??null}),isMutationAllowed:()=>!ue()});Zo.set(O,{unbind:Ne})},Wi=(O,q)=>{O?.id&&(q?Kt.set(O.id,q):Kt.delete(O.id))},ro=O=>{pi(O),As(O);const q=yn.get(O);if(!q)return;F.$superdoc.unregisterEditorRuntime(q.runtimeId),yn.delete(O);const Ee=Kt.get(O);Ee&&xS(Ee)},ke=({documentId:O,host:q,mount:Ee,facade:Ne})=>{const mt=Kt.get(O);if(!mt)return console.warn("[SuperDoc] v2 runtime host root unavailable; skipping runtime registration for",O),!1;yn.has(O)&&ro(O);const nn=`v2:${O}:${++Ei}`,pn=YL({id:nn,documentId:O,root:mt,host:q,getLegacyEditorProjection:()=>Ne,onUnregister:Jn=>{F.$superdoc.unregisterEditorRuntime(Jn);const Dn=yn.get(O);Dn&&Dn.runtimeId===Jn&&yn.delete(O);const _n=Kt.get(O);_n&&xS(_n)}});return pn.attachMountHandle(Ee??null),tD(mt,nn),F.$superdoc.registerEditorRuntime(pn.runtime),yn.set(O,{runtimeId:nn,adapter:pn}),F.$superdoc.setActiveRuntime(nn,"v2-editor-ready"),!0},Oe=j.createReviewHydrationController({hydrateComments:O=>s.hydrateCommentsFromV2?.(O),hydrateTrackedChanges:O=>s.hydrateTrackedChangesFromV2?.(O)}),ht=ne({}),lt=K9(),bn=ne({}),an=Se(()=>Object.values(bn.value)[0]??null),Fr=O=>typeof O=="string"&&O.length>0?`document:${O}`:"document:default",mo=O=>{const q=Fr(O);if(lt.clear(q),!bn.value[q])return;const Ee={...bn.value};delete Ee[q],bn.value=Ee},go=(O,q)=>{const Ee=Fr(O);lt.shouldNotify(Ee,q)&&(bn.value={...bn.value,[Ee]:E_},F.$superdoc.emit("exception",{error:new Error(E_),code:G9,editor:null,...typeof O=="string"&&O.length>0?{documentId:O}:{},...q.failureSource==="receipt"&&q.failure?{receipt:q.failure}:{}}))},To=(O,q)=>{O&&(ht.value={...ht.value,[O]:q})},Is=O=>{if(!O||!ht.value[O])return;const q={...ht.value};delete q[O],ht.value=q},Jo=(O=null)=>{const q=F.$superdoc?.activeEditor,Ee=O??q?.documentId??q?.options?.documentId??null;if(!Ee){q?.editorVersion===2&&F.$superdoc.setActiveEditor(null);return}if(O&&q?.editorVersion===2){const nn=q.documentId??q.options?.documentId??null;if(nn&&nn!==O)return}const Ne=Ee?y(Ee):null;Ne&&(Ne.isReady=!1,typeof Ne.setEditor=="function"&&Ne.setEditor(null));const mt=yn.has(Ee);ro(Ee),!mt&&q?.editorVersion===2&&(q.documentId??q.options?.documentId??null)===Ee&&F.$superdoc.setActiveEditor(null)},Ro=O=>{const q=typeof O?.getExtensionManager=="function"?O.getExtensionManager():null;if(!q)return null;const Ee=q.commands;return{commands:{execute:(Ne,mt)=>Ee.execute(Ne,mt),getState:Ne=>{const mt=Ee.get(Ne);return mt?{enabled:!(mt.getState()??{}).disabled,reason:null}:null},list:()=>Ee.list().map(Ne=>{const mt=Ne.getState()??{};return mt.label?{id:Ne.id,label:mt.label}:{id:Ne.id}})},diagnostics:{getSnapshot:()=>q.diagnostics()}}},Ki=O=>{if(!O)return;Is(O.documentId??null),mo(O.documentId??null);const{host:q,mount:Ee,documentId:Ne,capabilities:mt,editCommands:nn,bindEditShortcuts:pn,bindSessionShortcuts:Jn,commentsAdapter:Dn,trackedChangesAdapter:_n,documentApi:An,documentMutationReadiness:so,documentApiUnavailableReason:ao,pageMetrics:ka,pageLayout:Sl,pageFurniture:Oo,presence:kl,lock:hr,fonts:nb,replaceFile:sm}=O,am=async(At={})=>{if(!q||typeof q.save!="function")throw new Error("v2-editor: save unavailable");return q.save(At)},rb=async(At={})=>{const jt=await am({format:"docx",commentExportMode:At?.commentsType==="clean"?"strip":"preserve"});return new Blob([jt],{type:Tr})},Bu=async At=>{if(typeof sm!="function")throw new Error("v2-editor: replaceFile unavailable");return sm(At)},Kr=(At={})=>Ee?.focus&&typeof Ee.focus.focus=="function"?Ee.focus.focus(At):!1,$n=(At,jt=void 0)=>{const wn={ok:!1,reason:At};return jt&&(wn.detail=jt),wn},Aa=At=>Array.isArray(At?.items)?At.items:[],lm=At=>{const jt=Number(At);return Number.isFinite(jt)&&jt>0?Math.floor(jt):0},cm=async({text:At,occurrence:jt=0}={})=>{if(typeof At!="string"||At.length===0)return $n("invalid-text","text must be a non-empty string");if(!An?.query||typeof An.query.match!="function")return $n("query-unavailable","activeEditor.doc.query.match is not available");const wn=lm(jt),yr=await An.query.match({select:{type:"text",pattern:At},limit:wn+1}),Br=Aa(yr),lo=Br[wn]??null;return lo?.target?{ok:!0,item:lo,target:lo.target,ref:typeof lo?.handle?.ref=="string"?lo.handle.ref:null,text:At,occurrence:wn,total:Number.isFinite(Number(yr?.total))?Number(yr.total):Br.length}:$n("text-not-found",`text not found: ${At}`)},Bf=(At,jt)=>{if(!At||typeof At!="object"||At.kind!=="selection"||jt!=="start"&&jt!=="end")return At;const wn=jt==="start"?At.start:At.end;return wn?{kind:"selection",start:wn,end:wn,...At.story?{story:At.story}:{}}:At},um=async({target:At,collapse:jt=null,focus:wn=!0}={})=>{if(!At||typeof At!="object")return $n("invalid-target","target must be a SelectionTarget object");const yr=Bf(At,jt),Br=(q?.getHandles?.()?.editing??null)?.selectionTargets??null;if(typeof Br?.apply!="function")return $n("selection-target-unavailable","editing.selectionTargets.apply is not available");let lo;try{lo=Br.apply(yr)}catch(bi){return $n("selection-target-threw",bi instanceof Error?bi.message:String(bi))}return lo?.ok?(wn!==!1&&await Promise.resolve(Kr()),{ok:!0,mode:lo.mode??"range"}):$n(lo?.reason??"selection-target-rejected",lo?.detail)},dm=()=>F.$superdoc.config.documentMode==="suggesting"?"tracked":"direct",fm=()=>{const At=(q?.getHandles?.()?.editing??null)?.selection??null;if(typeof At?.toSelectionTarget!="function")return $n("selection-target-unavailable","editing.selection.toSelectionTarget is not available");const jt=At.toSelectionTarget();if(!jt||jt.kind==="rejected"){const wn=jt?.rejection??{};return $n(wn.reason??wn.code??"selection-target-rejected",wn.detail)}return!jt.target||typeof jt.target!="object"?$n("selection-target-rejected","selection target was not produced"):{ok:!0,target:jt.target,mode:jt.mode??"range",story:jt.story}},ob=(At,jt)=>{const wn=At?.failure??At;return $n(wn?.code??At?.reason??jt,wn?.message??wn?.detail??At?.detail)},hm={focusEditable:Kr,readBlocks:(At={includeText:!0})=>An?.blocks?.list?.(At),setSelectionTarget:(At={})=>um(At),setSelectionByText:async(At={})=>{const jt=await cm(At);if(!jt.ok)return jt;const wn=await um({target:jt.target,collapse:At?.collapse??null,focus:At?.focus});return wn.ok?{ok:!0,mode:wn.mode,text:jt.text,occurrence:jt.occurrence,target:jt.target}:wn},replaceTextByText:async({findText:At,replacement:jt,occurrence:wn=0,mode:yr="direct"}={})=>{if(typeof jt!="string")return $n("invalid-replacement","replacement must be a string");if(!An?.text||typeof An.text.replace!="function")return $n("text-replace-unavailable","activeEditor.doc.text.replace is not available");const Br=await cm({text:At,occurrence:wn});if(!Br.ok)return Br;const lo=Br.ref?{ref:Br.ref,text:jt,mode:yr}:{target:Br.target,text:jt,mode:yr},bi=await An.text.replace(lo);return bi?.ok===!1?$n(bi.reason??"text-replace-failed",bi.detail):(await Promise.resolve(so?.whenPainted?.(bi)),{ok:!0,receipt:bi,text:jt,replacedText:At,occurrence:lm(wn)})},replaceSelection:async({target:At,replacement:jt="",mode:wn="direct"}={})=>{if(!At||typeof At!="object")return $n("invalid-target","target must be a SelectionTarget object");if(typeof jt!="string")return $n("invalid-replacement","replacement must be a string");if(!An?.text||typeof An.text.replace!="function")return $n("text-replace-unavailable","activeEditor.doc.text.replace is not available");const yr=await An.text.replace({target:At,text:jt,mode:wn});return yr?.ok===!1?$n(yr.reason??"text-replace-failed",yr.detail):(await Promise.resolve(so?.whenPainted?.(yr)),{ok:!0,receipt:yr,text:jt})},serializeSelectionToClipboard:async({includeHtml:At=!0}={})=>{if(!An?.clipboard||typeof An.clipboard.serializeSelection!="function")return $n("clipboard-serialize-unavailable","activeEditor.doc.clipboard.serializeSelection is not available");const jt=fm();if(!jt.ok)return jt;let wn;try{wn=await An.clipboard.serializeSelection({target:jt.target,includeHtml:At!==!1})}catch(yr){return $n("clipboard-serialize-threw",yr instanceof Error?yr.message:String(yr))}return wn?.payload?{ok:!0,payload:wn.payload,plan:wn.plan,target:jt.target,mode:jt.mode}:$n("clipboard-serialize-failed","clipboard serialization did not return a payload")},pasteClipboardPayload:async({payload:At,target:jt=null,mode:wn=dm(),fallback:yr=void 0}={})=>{if(!At||typeof At!="object")return $n("invalid-clipboard-payload","payload must be a ClipboardPayload object");if(!An?.clipboard||typeof An.clipboard.insert!="function")return $n("clipboard-insert-unavailable","activeEditor.doc.clipboard.insert is not available");let Br=jt,lo=null;if(!Br){const Nu=fm();if(!Nu.ok)return Nu;Br=Nu.target,lo=Nu.mode}if(!Br||typeof Br!="object")return $n("invalid-target","target must be a SelectionTarget or ClipboardTarget object");const bi={payload:At,target:Br,changeMode:wn==="tracked"?"tracked":"direct",...yr!==void 0?{fallback:yr}:{}},Al=await An.clipboard.insert(bi);return!Al||Al.success===!1||Al.ok===!1?ob(Al,"clipboard-insert-failed"):(await Promise.resolve(so?.whenPainted?.(Al)),{ok:!0,receipt:Al,target:Br,mode:lo})},pastePlainText:async({text:At,target:jt=null,mode:wn=dm()}={})=>typeof At!="string"?$n("invalid-text","text must be a string"):hm.pasteClipboardPayload({payload:{source:"api",items:[{type:"text/plain",kind:"string",data:At}]},target:jt,mode:wn})},mc={editorVersion:2,documentId:Ne,host:q,mount:Ee,options:{documentId:Ne,documentMode:F.$superdoc.config.documentMode},capabilities:mt??q?.getCapabilities?.()??null,save:am,exportDocx:rb,replaceFile:Bu,doc:An??null,documentMutationReadiness:so??null,documentApiUnavailableReason:ao??null,focus:Kr,authoring:hm,editCommands:nn??null,v2Comments:Dn??null,v2TrackedChanges:_n??null,pageMetrics:ka??null,pageLayout:Sl??null,pageFurniture:Oo??null,presence:kl??null,lock:hr??null,reviewHydration:{getDiagnostics:()=>Oe.getDiagnostics()},extensions:Ro(q),fonts:nb??q?.getFontRuntime?.()??null,commands:null,state:null,view:null},Fs=y(Ne);Fs&&(Fs.isReady=!0,typeof Fs.setEditor=="function"&&Fs.setEditor(mc)),ke({documentId:Ne,host:q,mount:Ee,facade:mc})||F.$superdoc.setActiveEditor(mc),F.$superdoc.broadcastEditorCreate(mc),ks({documentId:Ne,bindEditShortcuts:pn}),al({documentId:Ne,bindSessionShortcuts:Jn,documentApi:An}),o(y(Ne)).state==="valid"&&xu({editor:mc}),ka&&Sl&&(Ps.value=!0);const Nf=F.$superdoc.config.modules?.comments!==!1;if(Dn&&Nf&&s.setV2CommentsAdapter?.(Dn),_n&&Nf&&s.setV2TrackedChangesAdapter?.(_n),Nf&&(Dn||_n)){Oe.setContext({superdoc:F.$superdoc,documentId:Ne,commentsAdapter:Dn??null,trackedChangesAdapter:_n??null});try{const At=q?.getRenderReadinessSnapshot?.();At&&Oe.onRenderReadiness(At)}catch(At){console.warn("[SuperDoc][v2] initial render-readiness snapshot failed",At)}}u.value&&!F.$superdoc.config.collaboration&&(l.value=!0),I.value=!0,le.value=!0},Gr=ne(!1),Sr=Ur(null);let Mo=0,Ho=0,$o=0;const ll=({editor:O,sourceEditor:q,surface:Ee="body",headerId:Ne=null,sectionType:mt=null}={})=>{const nn=F.$superdoc?.activeEditor??null,pn=O??q??nn??void 0;return{editor:pn,sourceEditor:q??pn,surface:Ee,headerId:Ne,sectionType:mt}},oc=(O={})=>{F.$superdoc.emit("editor-update",ll(O))},kr=()=>{Mo&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Mo),Ho&&clearTimeout(Ho),Mo=0,Ho=0},Uo=(O=zD)=>{kr();const q=()=>{Mo=0,Ho=0,fl(),Gr.value&&ri.value&&!c.value&&O>0&&Uo(O-1)};if(typeof requestAnimationFrame=="function"){Mo=requestAnimationFrame(q);return}Ho=setTimeout(q,0)},xi=()=>{$o&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame($o),$o=0},cl=()=>{Gr.value=!1,Sr.value=null,kr(),fl()},qi=(O,q)=>{if(!O||O.rangeCount<1||O.isCollapsed||!q)return!1;const Ee=O.getRangeAt(0);return q.contains(Ee.startContainer)&&q.contains(Ee.endContainer)},mi=()=>{if($o=0,!Dt.value)return;let O=null;try{O=F.$superdoc?.activeEditor?.host?.getHandles?.()??null}catch{O=null}const q=F.$superdoc?.config?.documentMode;if(q==="editing"||q==="suggesting"){const nn=O?.editing?.selection?.getSnapshot?.()??null;if(X9(q,nn)){const pn=jn();if(Y9(window.getSelection?.()??null,pn)){cl();return}Gr.value=!0,Sr.value=nn,Uo();return}}else if(q!=="viewing"){cl();return}const Ee=jn(),Ne=window.getSelection?.()??null;if(!qi(Ne,Ee)){cl();return}const mt=O?.editing?.selectionTargets?.applyDomSelection?.(Ne);if(!mt?.ok||mt.mode!=="range"){cl();return}Gr.value=!0,Sr.value=O?.editing?.selection?.getSnapshot?.()??null,Uo()},Rf=()=>{if(Dt.value){if(xi(),typeof requestAnimationFrame!="function"){mi();return}$o=requestAnimationFrame(mi)}},ei=()=>{Rf()},ul=({hasRangeSelection:O,snapshot:q}={})=>{if(Gr.value=O===!0,Sr.value=O===!0?q??null:null,Gr.value){Uo();return}kr(),fl()},jn=()=>un.value?.mountContainer??F.$superdoc?.activeEditor?.mount?.container??null,ic=O=>{const q=String(O);return globalThis.CSS?.escape?globalThis.CSS.escape(q):q.replace(/["\\]/g,"\\$&")},wu=()=>{const O=Sr.value,q=jn();if(!O||!q?.querySelector)return null;const Ee=O.anchor??null,Ne=[Ee?.fragmentId,Ee?.blockId,Ee?.position?.anchor?.nativeId].filter(mt=>mt!=null&&mt!=="");for(const mt of Ne){const nn=ic(mt),pn=q.querySelector(`[data-source-node-id="${nn}"]`)??q.querySelector(`[data-layout-block-ref="${nn}"]`)??q.querySelector(`[data-layout-fragment-id="${nn}"]`);if(pn instanceof HTMLElement)return pn}return null};function ba(O=null){const q=window.getSelection?.();if(!q||q.rangeCount<1||q.isCollapsed)return null;const Ee=q.getRangeAt(0);if(!Ee)return null;if(O){const{startContainer:Ne,endContainer:mt}=Ee;if(!O.contains(Ne)||!O.contains(mt))return null}try{const Ne=Ee.getBoundingClientRect();return!Ne||Ne.width<=0&&Ne.height<=0?null:Ne}catch{return null}}const Yi=O=>{if(!O||!Ot.value)return null;const q=Ot.value.getBoundingClientRect();return{top:O.top-q.top,left:O.left-q.left,right:O.right-q.left,bottom:O.bottom-q.top,width:O.width,height:O.height}},Es=O=>{let q=O;for(;q&&q.nodeType===1;){const Ee=q.dataset?.pageIndex;if(Ee!=null&&Ee!==""){const Ne=Number(Ee);if(Number.isFinite(Ne))return Ne}q=q.parentElement}return null},dl=()=>{if(!Gr.value||!ri.value)return null;const O=Yi(ba(jn()))??Cu()?.bounds??null;if(!O)return null;const q=F.$superdoc?.activeEditor?.options?.documentId??F.$superdoc?.activeEditor?.documentId;if(!q)return null;const Ee=Es(wu());return Qd({selectionBounds:O,page:Ee!=null?Ee+1:1,documentId:q,source:tu})},Cu=()=>{if(!Ot.value)return null;const O=wu();if(!O)return null;const q=O.getBoundingClientRect();if(!q||q.width<=0&&q.height<=0)return null;const Ee=Ot.value.getBoundingClientRect(),Ne={top:q.top-Ee.top,left:q.left-Ee.left,right:q.right-Ee.left,bottom:q.bottom-Ee.top,width:q.width,height:q.height},mt=Es(O);return{threadId:"pending",key:"pending",kind:"pending",storyKey:"body",bounds:Ne,...mt!=null?{pageIndex:mt}:{},...Me.value!=null?{generation:Me.value}:{}}},fl=()=>{if(!Dt.value)return;if(!Gr.value){d.value=null,Kn();return}const O=dl();if(!O){d.value=null,Kn();return}zt(O)},_u=O=>{O&&ge({...te.value??{},pending:O})},Ti=j.createGeometryPublisher({getLayersContainer:()=>Ot.value??null,isCommentsEnabled:()=>rt.value,publishPositions:O=>ge(O),clearPositions:()=>{s.clearEditorCommentPositions?.()},readCurrentPositions:()=>te.value??{},setGeometryAvailable:O=>{Ft.value=!!O,O&&(Me.value=Ti.getLastEpoch())}}),xs=O=>{if(un.value=O,Pe&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Pe),typeof requestAnimationFrame!="function"){Ti.publish(un.value);return}Pe=requestAnimationFrame(()=>{Pe=0,Ti.publish(un.value)})},Mf=O=>{O&&(xs(O),Gr.value&&Uo())},Ts=O=>{const q=O?.snapshot??O??null;q&&Oe.onRenderReadiness(q)},hl=Ur(null),Lo=new Map;let ti=null;const Su=O=>{if(!O?.snapshot)return;wa.onRender();const q=O.snapshot,Ee=O.stage;if(typeof HTMLElement<"u"&&Ee instanceof HTMLElement){ti=Ee;const mt=Ee.dataset?.superdocV2DocumentId;mt&&Lo.set(mt,Ee)}hl.value=q;const Ne=Array.isArray(q.pages)?q.pages.length:0;F.$superdoc.emit("pagination-update",{totalPages:Ne,superdoc:F.$superdoc}),_t(()=>{es(),Os()})},ku=O=>{Tt.destroy(),xi(),kr(),Pe&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Pe),Pe=0,un.value=null,Me.value=null,Ft.value=!1,Ti.reset(),Gr.value=!1,Sr.value=null,d.value=null,Kn(),hl.value=null;const q=O?.documentId==null?null:String(O.documentId);s.cancelImportedTrackedChangeBootstrap?.(q??void 0),q&&Lo.delete(q),ti&&(q==null||ti.dataset?.superdocV2DocumentId===q)&&(ti=null),Oe.reset("render-cleared"),wa.reset(),sc(),lc.clear(),s.setV2CommentsAdapter?.(null),s.setV2TrackedChangesAdapter?.(null),s.clearEditorCommentPositions?.(),Jo(O?.documentId??null),Ri(),io.value={},Ps.value=!1};let ni=0;const Rs=()=>{const O=F.$superdoc?.activeEditor?.v2Comments??null;O&&s.hydrateCommentsFromV2?.({superdoc:F.$superdoc,adapter:O,documentId:F.$superdoc?.activeEditor?.documentId??null})},pl=(O={})=>{Rs();const q=F.$superdoc?.activeEditor?.v2TrackedChanges??null;q&&s.hydrateTrackedChangesFromV2?.({superdoc:F.$superdoc,adapter:q,documentId:F.$superdoc?.activeEditor?.documentId??null,...O})},wa=k_({getContext:()=>{const O=F.$superdoc?.activeEditor??null,q=O?.v2TrackedChanges??null;return q?{superdoc:F.$superdoc,adapter:q,documentId:O.documentId??null}:null},reconcile:(O,q)=>s.reconcileTrackedChangeMutationFromV2?.({superdoc:O.superdoc,adapter:O.adapter,documentId:O.documentId,...q}),hydrate:(O,q)=>s.hydrateTrackedChangesFromV2?.({superdoc:O.superdoc,adapter:O.adapter,documentId:O.documentId,...q}),onReconciled:()=>Ti.recollect()});let ml=0,Xi=0;const sc=()=>{ni&&typeof clearTimeout=="function"&&clearTimeout(ni),ni=0,ml=0,Xi=0},ac=()=>{ml=Date.now(),Xi||(Xi=ml),ni&&typeof clearTimeout=="function"&&clearTimeout(ni);const O=()=>{ni=0;const Ee=Date.now()-ml,Ne=Date.now()-Xi;if(Ee<o0&&Ne<i0){const mt=o0-Ee,nn=i0-Ne;ni=setTimeout(O,Math.min(mt,nn));return}Xi=0,pl()},q=Math.max(0,i0-(Date.now()-Xi));ni=setTimeout(O,Math.min(o0,q))},lc=V9({hydrate:()=>pl(),getActiveDocumentId:()=>{const O=F.$superdoc?.activeEditor??null;return O?.documentId??O?.options?.documentId??null}}),Au=(O,q)=>{if(!q)return;const Ee=O?.id??null;if(q.type==="reviewTarget:changed"){Du(q.next);return}if(q.type==="collaboration:remote-changed"){lc.schedule(Ee);return}if(q.type==="source:complete"){F.$superdoc.broadcastSourceComplete();return}if(q.type==="source:signals-complete"){F.$superdoc.broadcastSourceSignalsComplete();return}if(q.type==="mutation:rejected"){go(Ee,q);return}if(q.type==="mutation:committed"&&(mo(Ee),oc()),q.type!=="mutation:committed")return;const Ne=S_(q),mt=(F.$superdoc?.activeEditor??null)?.documentMutationReadiness??null,nn=q.origin==="history"?null:q.receipt,pn=Ne&&typeof nn?.txId=="string"&&nn.txId.length>0&&typeof mt?.whenPainted=="function";if(wa.enqueueAfterPaint(Ne,pn?()=>mt.whenPainted.call(mt,nn):null),Ne?.reconcileMode==="authoritative"&&Ne.upsertIds.size>0){Rs();return}if(A_(q)){ac();return}Ne?.removedIds.size>0&&Ne.upsertIds.size===0||pl()},Lf=O=>{Tt.handleLinkClick(O)},cc=()=>{if(Dt.value&&Ti.getLastPayload()){if(Pe&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Pe),typeof requestAnimationFrame!="function"){Ti.recollect();return}Pe=requestAnimationFrame(()=>{Pe=0,Ti.recollect()})}},Ca=()=>{if(!Dt.value)return;try{Oe.hydrateNow("document-mode-change")}catch(q){console.warn("[SuperDoc][v2] document-mode-change rehydrate failed",q)}const O=()=>{Dt.value&&(rt.value?un.value?xs(un.value):cc():(s.clearEditorCommentPositions?.(),Ft.value=!1))};_t(()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>O()):O()})},Df=O=>{switch(O){case"editing-mount-required":return"SuperDoc could not load the document editor because the page did not provide a mount container.";case"source-load-failed":return"SuperDoc could not load the document editor because the document source could not be prepared.";case"unsupported-cdn-v2-editor":return"SuperDoc could not load the document editor because this build does not include the V2 runtime.";case"v2-integration-unavailable":return"SuperDoc could not load the document editor because the bundled V2 runtime is unavailable in this environment.";case"worker-init-failed":return"SuperDoc could not load the document editor because the browser worker failed to start.";case"input-too-large-for-inline-review":return"SuperDoc could not load the document editor because this document is too large to open without the browser worker.";case"collaboration-unsupported-huge-document":return"SuperDoc could not load the document editor because large documents cannot be opened with collaboration enabled yet.";case"collaboration-v1-config-unsupported":return"SuperDoc v2 cannot use modules.collaboration because it is the SuperDoc v1 collaboration API. SuperDoc did not attach the provider or change the document. Configure Document.v2Collaboration with a v2 room instead.";case"collaboration-room-format-unsupported":return"SuperDoc v2 cannot open this collaboration state because it is not stored in the SuperDoc v2 room format. No changes were made.";case"collaboration-room-format-conflict":return"SuperDoc v2 found conflicting room formats in one collaboration document. No changes were made.";case"collaboration-room-corrupt":return"SuperDoc v2 found a structurally invalid collaboration room. No changes were made.";case"collaboration-v2-room-missing":return'SuperDoc v2 could not find a committed v2 collaboration room. No changes were made. Use roomMode: "create" only when creating a new room.';case"collaboration-v2-room-already-exists":return'SuperDoc v2 was asked to create a collaboration room that already exists. Use roomMode: "join" to open it.';case"collaboration-v2-room-initializing":return"The SuperDoc v2 collaboration room is still initializing. Join mode did not modify it.";case"collaboration-open-intent-invalid":return"SuperDoc v2 received an invalid collaboration room mode. No provider was connected.";case"collaboration-config-invalid":return"SuperDoc v2 received an invalid collaboration configuration. No provider was connected.";default:return"SuperDoc could not load the document editor."}},Iu=O=>typeof O=="string"&&O.trim().length>0?O.trim():null,uc=O=>{Jo(O?.documentId??null);const q=typeof O?.reason=="string"&&O.reason.length>0?O.reason:"open-failed",Ee=Iu(O?.detail),Ne=typeof O?.documentId=="string"&&O.documentId.length>0?O.documentId:null,mt=Df(q),nn=O?.workerFailure&&typeof O.workerFailure=="object"?O.workerFailure:null;To(Ne,{reason:q,message:mt,detail:Ee,...nn?{workerFailure:nn}:{}});const pn={...Ee?{detail:Ee}:{},...Ne?{documentId:Ne}:{},...nn?{workerFailure:nn}:{},reason:q};q==="collaboration-v1-config-unsupported"||q==="collaboration-room-format-unsupported"||q==="collaboration-room-format-conflict"||q==="collaboration-room-corrupt"||q==="collaboration-v2-room-missing"||q==="collaboration-v2-room-already-exists"||q==="collaboration-v2-room-initializing"||q==="collaboration-open-intent-invalid"||q==="collaboration-config-invalid"?console.warn(`[SuperDoc] ${mt}`,pn):console.error(`[SuperDoc] ${mt}`,pn),F.$superdoc.emit("exception",{error:new Error(mt),code:q,...Ne?{documentId:Ne}:{},editor:null})},Ms=(O,q)=>{F.$superdoc?.activateRuntimeFromEventTarget?.(O.target,q)},Eu=O=>Ms(O,"focusin"),Ls=O=>Ms(O,"pointerdown"),dc=O=>Ms(O,"mousedown"),xu=({editor:O})=>{F.$superdoc.emit("collaboration-ready",{editor:O}),_t(()=>{l.value=!0;const q=new URLSearchParams(window.location.search).get("commentId");q&&tt(q)})};let Tu=0;const Qi=()=>{Tu=Date.now()+250},Ru=()=>Date.now()<Tu,Zi=O=>{const q=Ct.value;q&&(!(O.target instanceof Node)||!q.contains(O.target)||(Ot.value?.contains(O.target)&&(s.setActiveComment(F.$superdoc,null),s.removePendingComment(F.$superdoc),Xe()),Qi()))},Pf=O=>{const q=F.$superdoc.listeners?.("fonts-resolved")?.length>0?F.$superdoc.listeners("fonts-resolved")[0]:null,Ee=F.$superdoc.config.useLayoutEngine!==!1,Ne=O.isNewFile,mt=F.$superdoc.config?.benchmarkExecutionMode,nn=F.$superdoc.config?.benchmarkTraceEnabled===!0,pn=o(O),Jn=pn.state==="valid"?pn.config:null,Dn=F.$superdoc.config.v2CollaborationPreflightFailure??(pn.state==="invalid"?pn.failure:null);return{isDebug:F.$superdoc.config.isDebug||!1,documentId:O.id,user:F.$superdoc.user,users:F.$superdoc.users,colors:F.$superdoc.colors,role:F.$superdoc.config.role,html:O.html,markdown:O.markdown,documentMode:F.$superdoc.config.documentMode,...mt?{benchmarkExecutionMode:mt}:{},...nn?{benchmarkTraceEnabled:!0}:{},allowSelectionInViewMode:F.$superdoc.config.allowSelectionInViewMode,rulers:O.rulers,rulerContainer:F.$superdoc.config.rulerContainer,isInternal:F.$superdoc.config.isInternal,annotations:F.$superdoc.config.annotations,isCommentsEnabled:!!wt.value,isAiEnabled:F.$superdoc.config.modules?.ai,contextMenuConfig:(F.$superdoc.config.modules?.slashMenu&&!F.$superdoc.config.modules?.contextMenu&&console.warn("[SuperDoc] modules.slashMenu is deprecated. Use modules.contextMenu instead."),F.$superdoc.config.modules?.contextMenu??F.$superdoc.config.modules?.slashMenu),slashMenuConfig:F.$superdoc.config.modules?.contextMenu??F.$superdoc.config.modules?.slashMenu,comments:{highlightColors:wt.value?.highlightColors,highlightOpacity:wt.value?.highlightOpacity},trackedChanges:F.$superdoc.config.modules?.trackChanges,experimental:F.$superdoc.config.experimental,...Jn?{v2Collaboration:Jn}:{},...Dn?{collaborationPreflightFailure:Dn}:{},onCollaborationReady:xu,onCommentsUpdate:bl,onFontsResolved:q,onPageCountKnown:F.$superdoc.config.onPageCountKnown??null,fontAssets:F.$superdoc.config.fonts,proofing:nt.value,isNewFile:Ne,password:r(O),handleImageUpload:F.$superdoc.config.handleImageUpload,externalExtensions:F.$superdoc.config.editorExtensions||[],extensions:F.$superdoc.config.extensions||[],suppressDefaultDocxStyles:F.$superdoc.config.suppressDefaultDocxStyles,disableContextMenu:!F.$superdoc.uiConfig.contextMenu.enabled||F.$superdoc.config.disableContextMenu===!0,jsonOverride:F.$superdoc.config.jsonOverride,viewOptions:F.$superdoc.config.viewOptions,contained:F.$superdoc.config.contained,linkPopoverResolver:F.$superdoc.uiConfig.linkPopover.enabled?F.$superdoc.config.modules?.links?.popoverResolver:void 0,layoutEngineOptions:Ee?{...F.$superdoc.config.layoutEngineOptions||{},proofing:nt.value,debugLabel:F.$superdoc.config.layoutEngineOptions?.debugLabel??O.name??O.id,zoom:(h.value??100)/100,emitCommentPositionsInViewing:ue()&&rt.value,enableCommentsInViewing:we.value,contentControlsChrome:F.$superdoc.uiConfig.contentControls.enabled?F.$superdoc.uiConfig.contentControls.options.chrome??(F.$superdoc.config.modules?.contentControls?.chrome==="none"?void 0:F.$superdoc.config.modules?.contentControls?.chrome):"none",resolveTrackedChangeColor:d9(F.$superdoc.config.modules?.trackChanges?.authorColors)}:void 0,permissionResolver:(_n={})=>F.$superdoc.canPerformPermission({role:F.$superdoc.config.role,isInternal:F.$superdoc.config.isInternal,..._n}),licenseKey:F.$superdoc.config.licenseKey,telemetry:F.$superdoc.config.telemetry?.enabled?{enabled:!0,endpoint:F.$superdoc.config.telemetry?.endpoint,metadata:F.$superdoc.config.telemetry?.metadata,licenseKey:F.$superdoc.config.telemetry?.licenseKey}:null}},Mu=new Set(["commentText","isInternal","parentCommentId","trackedChangeParentId","trackedChangeThreadParentId","threadingParentCommentId","trackedChange","trackedChangeType","trackedChangeText","trackedChangeDisplayType","semanticColorKey","semanticColor","trackedChangeStory","trackedChangeStoryKind","trackedChangeStoryLabel","trackedChangeAnchorKey","trackedChangeLabel","trackedChangeDetailLines","deletedText","resolvedTime","resolvedById","resolvedByEmail","resolvedByName","importedAuthor","docxCommentJSON"]),gl=(O,q={})=>{if(!(!O||q.isDone===void 0)&&!(q.resolvedTime!=null||q.resolvedById!=null||q.resolvedByEmail!=null||q.resolvedByName!=null)){if(q.isDone){O.resolvedTime=O.resolvedTime||Date.now(),O.resolvedById=O.resolvedById||q.creatorId||null,O.resolvedByEmail=O.resolvedByEmail||q.creatorEmail||null,O.resolvedByName=O.resolvedByName||q.creatorName||null;return}O.resolvedTime=null,O.resolvedById=null,O.resolvedByEmail=null,O.resolvedByName=null}},fc=(O,q,Ee)=>{!O||!q||(Array.isArray(q.elements)&&(O.docxCommentJSON=q.elements),Object.entries(q).forEach(([Ne,mt])=>{mt!==void 0&&Ne!=="text"&&Ne!=="elements"&&Mu.has(Ne)&&(O[Ne]=mt)}),Ee!==void 0&&(O.commentText=Ee),gl(O,q))},Lu=(O={})=>{const q={...O};return!q.commentText&&q.text&&(q.commentText=q.text),!q.docxCommentJSON&&Array.isArray(q.elements)&&(q.docxCommentJSON=q.elements),gl(q,q),q},vl=O=>{if(Number.isFinite(_()))return;if(O==null){$();return}const q=Ot.value,{key:Ee,entry:Ne}=Ie(O),mt=a_(q,Ne);if(Number.isFinite(mt)){Q(mt,O,Ee??O);return}$()},yl=O=>O==null||z.value==null?!1:String(z.value)===String(O),Du=O=>{if(O?.origin!=="document"||Ru())return;const q=H9(O,kt);q&&(vl(q),z.value=q,fe.value=!0,setTimeout(()=>{fe.value=!1},0))},bl=(O={})=>{let{activeCommentId:q,type:Ee,comment:Ne}=O,mt=Object.prototype.hasOwnProperty.call(O,"activeCommentId");const nn=Jn=>{const Dn=[Jn?.importedId,Jn?.commentId].filter(Boolean).map(_n=>String(_n));return[...new Set(Dn)]},pn=Jn=>{const Dn=[Jn?.importedId,Jn?.commentId].filter(Boolean).map(An=>String(An)),_n=F.$superdoc?.activeEditor?.options?.documentId!=null?String(F.$superdoc.activeEditor.options.documentId):null;for(const An of Dn){const so=H.value.find(ao=>{const ka=ao?.commentId!=null?String(ao.commentId):null,Sl=ao?.importedId!=null?String(ao.importedId):null;return ka===An||Sl===An?!_n||typeof ze!="function"?!0:ze(ao,_n):!1});if(so){const ao=so?.commentId??so?.importedId??An;return{id:ao!=null?String(ao):null,existingComment:so}}}return{id:Dn[0]||null,existingComment:null}};if(Ee==="replayCompleted"&&jr(),Ve?.ADD&&Ee===Ve.ADD&&Ne){Ne=Lu(Ne);const Jn=F.$superdoc?.user;Jn&&(Ne.creatorId||(Ne.creatorId=Jn.id),Ne.creatorName||(Ne.creatorName=Jn.name),Ne.creatorEmail||(Ne.creatorEmail=Jn.email)),Ne.createdTime||(Ne.createdTime=Date.now());const Dn=Ne.documentId||a.value?.[0]?.id;!Ne.documentId&&Dn&&(Ne.documentId=Dn),!Ne.fileId&&Dn&&(Ne.fileId=Dn);const{id:_n,existingComment:An}=pn(Ne);if(_n&&!An){const so=aa(Ne);et({superdoc:F.$superdoc,comment:so,skipEditorUpdate:!0})}}if(Ve?.UPDATE&&Ee===Ve.UPDATE&&Ne){const{id:Jn,existingComment:Dn}=pn(Ne);if(Jn){const _n=Ne.commentText||Ne.text;if(Dn)fc(Dn,Ne,_n);else{const An=aa(Lu(Ne));et({superdoc:F.$superdoc,comment:An,skipEditorUpdate:!0})}}}if(Ve?.DELETED&&Ee===Ve.DELETED&&Ne){const Jn=nn(Ne);if(Jn.length){const Dn=F.$superdoc?.activeEditor?.options?.documentId!=null?String(F.$superdoc.activeEditor.options.documentId):null,_n=so=>!Dn||typeof ze!="function"?!0:ze(so,Dn),An=b9(H.value,Jn,_n);if(An.size){const so=[...H.value];H.value=H.value.filter(Oo=>{if(!_n(Oo))return!0;const kl=Oo.commentId!=null?String(Oo.commentId):null,hr=Oo.importedId!=null?String(Oo.importedId):null;return!(kl&&An.has(kl)||hr&&An.has(hr))});const ao=z.value!=null?String(z.value):null,ka=ao!=null?so.find(Oo=>{const kl=Oo.commentId!=null?String(Oo.commentId):null,hr=Oo.importedId!=null?String(Oo.importedId):null;return kl===ao||hr===ao}):null,Sl=ka?_n(ka):!1;ao&&An.has(ao)&&Sl&&(q=null,mt=!0)}}}Ee==="trackedChange"&&ae({superdoc:F.$superdoc,params:O}),mt&&q!=null&&Ru()&&(mt=!1),mt&&(q==null||!yl(q))&&vl(q),_t(()=>{B.value||(mt&&s.setActiveComment(F.$superdoc,q),mt&&(fe.value=!0,setTimeout(()=>{fe.value=!1},0)))}),typeof F.$superdoc.config.onCommentsUpdate=="function"&&F.$superdoc.config.onCommentsUpdate(O)},ri=Se(()=>!!wt.value),Ji=Se(()=>Array.isArray(a.value)?a.value.filter(O=>O?.type===Ul):[]),Wr=Se(()=>Ji.value.length>0),Of=Se(()=>Wr.value&&ri.value),Pu=Se(()=>new Set(Ji.value.map(O=>String(O.id)))),Ds=O=>typeof O=="number"?Number.isFinite(O):typeof O=="string"&&O.trim()!==""?Number.isFinite(Number(O)):!1,hc=O=>{const q=O?.selection?.selectionBounds;return!!q&&Ds(q.top)&&Ds(q.left)&&Ds(q.right)&&Ds(q.bottom)},Ff=O=>{const q=O?.fileId??O?.documentId??O?.selection?.documentId;return q!=null?String(q):null},x=O=>{const q=Pu.value;if(!q.size)return!1;const Ee=Ff(O);return Ee?q.has(Ee):q.size===1},D=O=>O?.selection?.source==="pdf"&&hc(O)&&x(O),ee=Se(()=>{if(!Wr.value)return!1;const O=J.value.some(Ee=>D(Ee)),q=D(B.value);return O||q}),ie=Se(()=>{const O=wt.value?.displayMode??"sidebar";return!y_.has(O)||O==="sidebar"?!0:O==="inline"?!1:O!=="auto"?!0:!St.value}),se=Se(()=>Dt.value&&!Ft.value&&!ee.value||!rt.value||!ie.value?!1:B.value||(J.value.length>0||Fe.value)&&l.value&&Ot.value&&ri.value&&!N.value),de=Se(()=>{if(se.value||!ri.value)return null;if(B.value)return B.value;if(!z.value)return null;const O=kt(z.value)??null;return Dt.value&&ie.value&&O?.trackedChange&&!ee.value?null:O}),{compactCommentPopoverStyle:pe,closeCompactCommentPopover:ve,resetClickAnchor:Xe}=B9({activeComment:z,pendingComment:B,activeCompactComment:de,showCommentsSidebar:se,superdocRoot:Ct,layers:Ot,documents:a,resolveCommentPositionEntry:Ie,selectionPosition:c,activeZoom:h,clearActiveComment:()=>s.setActiveComment(F.$superdoc,null),clearPendingComment:()=>s.removePendingComment(F.$superdoc)}),Qe=Se(()=>ri.value?c.value&&Vt.top&&!R.value?.readOnly:!1);Se(()=>ri.value?!R.value?.readOnly&&c.value:!1),Pt(se,O=>{F.$superdoc.broadcastSidebarToggle(O)}),NR({getSuperdoc:()=>F.$superdoc,superdocContainerWidth:We,isReady:l,activeZoom:h,zoomMode:m,viewportMetrics:g,showCommentsSidebar:se,rightSidebarRef:Bt,superdocRoot:Ct,documents:a});const tt=O=>{F.$superdoc.scrollToComment(O)},st=()=>{cc()};Rn(()=>{document.addEventListener("contextmenu",Zi,!0),document.addEventListener("keydown",vo,!0),F.$superdoc?.on?.("search:open",Gn),Zy(dn),Ct.value?.addEventListener("pointerdown",Bn,!0),Ct.value?.addEventListener("focusin",Bn,!0),typeof window<"u"&&(window.addEventListener("scroll",st,!0),window.addEventListener("resize",st,!0)),document.addEventListener("focusin",Eu,!0),document.addEventListener("pointerdown",Ls,!0),document.addEventListener("mousedown",dc,!0),document.addEventListener("pointerup",ei,!0),document.addEventListener("mouseup",ei,!0),document.addEventListener("selectionchange",ei),F.$superdoc?.on?.("document-mode-change",Ca),Nt(),cn()}),Pt(rt,O=>{Dt.value&&(O?un.value&&xs(un.value):(s.clearEditorCommentPositions?.(),Ft.value=!1))}),Pt(Ot,()=>{cc()});function vt(O){return(O.metaKey||O.ctrlKey)&&!O.altKey&&O.key?.toLowerCase?.()==="f"}function pt(O){return(O.metaKey||O.ctrlKey)&&O.shiftKey&&!O.altKey&&(O.code==="Digit8"||O.key==="8"||O.key==="*")}function it(){const O=Ct.value,q=document.activeElement;if(!(q instanceof Node))return!1;if(O?.contains(q))return!0;const Ee=F.$superdoc?.activeEditor?.view?.dom;return Ee instanceof Node&&(q===Ee||Ee.contains?.(q))}const dn={};function rn(O){vt(O)&&Te.value&&cM(O,{focusInside:it(),owner:dn})&&Et.wouldOpen()&&(O.preventDefault(),O.stopPropagation(),Zy(dn),Et.open())}function Bn(){Zy(dn)}function Gn(){Te.value&&Et.open()}function Wn(O){pt(O)&&(Dt.value||it()&&(O.preventDefault(),O.stopPropagation(),F.$superdoc.toggleFormattingMarks?.()))}function vo(O){if(O.key==="Escape"&&de.value){O.preventDefault(),O.stopPropagation(),ve();return}rn(O),!O.defaultPrevented&&Wn(O)}function Hn(O){rn(O),!O.defaultPrevented&&Wn(O)}ir(()=>{s.cancelImportedTrackedChangeBootstrap?.(),T.destroy(),Et.destroy(),Tt.destroy(),xi(),kr();for(const O of Array.from(yn.keys()))ro(O);for(const O of Array.from(xo.keys()))pi(O);for(const O of Array.from(Zo.keys()))As(O);yn.clear(),Kt.clear(),document.removeEventListener("contextmenu",Zi,!0),document.removeEventListener("keydown",vo,!0),F.$superdoc?.off?.("search:open",Gn),Ct.value?.removeEventListener("pointerdown",Bn,!0),Ct.value?.removeEventListener("focusin",Bn,!0),aM(dn),typeof window<"u"&&(window.removeEventListener("scroll",st,!0),window.removeEventListener("resize",st,!0)),Pe&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(Pe),Pe=0),sc(),lc.clear(),document.removeEventListener("focusin",Eu,!0),document.removeEventListener("pointerdown",Ls,!0),document.removeEventListener("mousedown",dc,!0),document.removeEventListener("pointerup",ei,!0),document.removeEventListener("mouseup",ei,!0),document.removeEventListener("selectionchange",ei),F.$superdoc?.off?.("document-mode-change",Ca)});const Mn=ne(null),Zn=ne(!1),bt=Se(()=>{if(!c.value||c.value.source==="document-editor")return{x:null,y:null};const O=c.value.source==="pdf"?(h.value??100)/100:1,q=c.value.top*O,Ee=c.value.left*O,Ne=c.value.right*O,mt=c.value.bottom*O;return{zIndex:500,borderRadius:"4px",top:q+"px",left:Ee+"px",height:Math.abs(q-mt)+"px",width:Math.abs(Ee-Ne)+"px"}}),zt=O=>{if(ue()&&!be()){Kn();return}if(!O.selectionBounds||!ri.value)return;Kn();const q=window.matchMedia("(max-width: 768px)").matches;if(oo({startX:O.selectionBounds.left,startY:O.selectionBounds.top,x:O.selectionBounds.right,y:O.selectionBounds.bottom,source:O.source}),!c.value)return;const Ee=Math.abs(c.value.left-c.value.right)>5,Ne=Math.abs(c.value.top-c.value.bottom)>5;if(!Ee||!Ne){Mn.value?.style&&(Mn.value.style.pointerEvents="none"),Kn();return}d.value=O;const mt=O.source==="pdf"||O.source?.value==="pdf"?(h.value??100)/100:1;Vt.top=O.selectionBounds.top*mt+"px",Vt.right=q?"0":"-25px"},Kn=()=>{c.value=null,Vt.top=null},oo=({startX:O,startY:q,x:Ee,y:Ne,source:mt,page:nn})=>{if(!(typeof O=="number"||typeof q=="number")&&!(typeof Ee=="number"||typeof Ne=="number")){Kn();return}if(!c.value){if(q==null||O==null)return;c.value={top:q,left:O,right:O,bottom:q,startX:O,startY:q,source:mt,page:nn??null}}typeof O=="number"&&(c.value.startX=O),typeof q=="number"&&(c.value.startY=q),typeof Ne=="number"&&(Ne<c.value.startY?c.value.top=Ne:c.value.bottom=Ne),typeof Ee=="number"&&(Ee<c.value.startX?c.value.left=Ee:c.value.right=Ee)},fr=O=>{const q=O?.clientX,Ee=O?.clientY;if(typeof q!="number"||typeof Ee!="number")return null;const Ne=document.elementsFromPoint(q,Ee).find(mt=>mt?.dataset?.pdfPage!=null);if(Ne){const mt=Number(Ne.dataset?.pageNumber);return Number.isFinite(mt)?mt:null}return null},$i=O=>{Kn(),Mn.value.style.pointerEvents="auto",_t(()=>{Zn.value=!0,Mn.value.style.pointerEvents="none";const q=fr(O);if(Mn.value.style.pointerEvents="auto",!q){Zn.value=!1,Mn.value.style.pointerEvents="none";return}const Ee=Mn.value.getBoundingClientRect(),Ne=h.value/100;oo({startX:(O.clientX-Ee.left)/Ne,startY:(O.clientY-Ee.top)/Ne,page:q,source:"pdf"}),Mn.value.addEventListener("mousemove",gi)})},gi=O=>{if(!Zn.value)return;const q=Mn.value.getBoundingClientRect(),Ee=h.value/100;oo({x:(O.clientX-q.left)/Ee,y:(O.clientY-q.top)/Ee})},yo=O=>{if(!Zn.value||(Mn.value.removeEventListener("mousemove",gi),!c.value))return;const q=c.value.page??fr(O);zt(Qd({selectionBounds:{top:c.value.top,left:c.value.left,right:c.value.right,bottom:c.value.bottom},page:q??1,documentId:a.value[0].id,source:"pdf"})),Mn.value.style.pointerEvents="none"},wl=Se(()=>{if(!F.$superdoc.uiConfig.comments.enabled)return!1;const O=F.$superdoc.config.modules?.comments;return!O||O===!1?!1:!O.readOnly}),Ps=ne(!1),oi=O=>O&&typeof O=="object"&&"value"in O?O.value:O,vi=O=>{if(!Dt.value||!O||O.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||F.$superdoc.config.viewOptions?.layout==="web"||F.$superdoc.uiConfig.ruler.suppressed||!oi(O.rulers)||!Ps.value)return!1;const q=F.$superdoc?.activeEditor;if(!q||q.editorVersion!==2)return!1;const Ee=oi(O.id),Ne=q.documentId??q.options?.documentId??null;return Ee&&Ne&&Ee!==Ne?!1:!!(q.pageMetrics&&q.pageLayout)},io=ne({});let Do=null,yi=null;const Vo=()=>{const O=F.$superdoc?.config?.rulerContainer;return O?typeof O=="string"?(typeof document<"u"?document:globalThis.document)?.querySelector(O)??null:typeof HTMLElement<"u"&&O instanceof HTMLElement?O:null:null},Cl=()=>{const O=F.$superdoc?.activeEditor?.documentId??F.$superdoc?.activeEditor?.options?.documentId??null,q=O==null?ti:Lo.get(String(O))??null;return q?.isConnected?(Array.from(q.children).find(Ee=>Ee.dataset?.v2PaintWrapper==="true")??q).getBoundingClientRect():null},es=()=>{if(!Dt.value){io.value={};return}const O=Vo();if(!O){io.value={};return}const q=Cl();if(!q){io.value={};return}const Ee=O.getBoundingClientRect(),Ne=Math.max(0,q.left-Ee.left),mt=Math.max(0,Ee.right-q.right);io.value={paddingLeft:`${Ne}px`,paddingRight:`${mt}px`}},Ri=()=>{try{Do?.disconnect()}catch{}Do=null;try{yi?.disconnect()}catch{}yi=null},Os=()=>{if(Ri(),typeof ResizeObserver>"u")return;const O=Ot.value,q=Vo();O&&(Do=new ResizeObserver(()=>es()),Do.observe(O)),q&&(yi=new ResizeObserver(()=>es()),yi.observe(q))},bo=(O,q)=>{!O||!q||(O.documentMarginsLastChange=q.pageMargins??null,F.$superdoc.emit("page-margins-change",{documentId:O.id,editorVersion:2,sectionId:q.sectionId,sectionIndex:q.sectionIndex,side:q.side,value:q.value,pageMargins:q.pageMargins}))},ts=O=>{ri.value&&(Kn(),Zn.value=!0,$i(O))},Ou=({selectionBounds:O,documentId:q,page:Ee})=>{!O||!q||zt(Qd({selectionBounds:O,documentId:q,page:Ee,source:"pdf"}))},_l=O=>{Ot.value?.querySelectorAll(".superdoc__sub-document")?.forEach(q=>{q.querySelector(".sd-pdf-viewer")||(O===1?(q.style.transformOrigin="",q.style.transform="",q.style.width=""):(q.style.transformOrigin="top left",q.style.transform=`scale(${O})`,q.style.width=`${100/O}%`))})};let _a=!1;const dt=()=>{if(_a||F.$superdoc.config.useLayoutEngine!==!1)return;const O=(h.value??100)/100;O!==1&&(_a=!0,_t(()=>_l(O)))};Pt(()=>h.value,O=>{const q=(O??100)/100,Ee=O??100,Ne=F.$superdoc?.activeEditor?.pageMetrics??null;if(Dt.value&&F.$superdoc?.activeEditor?.editorVersion===2&&Ne?.setZoom)try{Ne.setZoom(Ee)}catch(mt){console.warn("[SuperDoc][v2] setZoom failed",mt)}else _a=!0,_l(q);Po()?.updateScale(q),_t(()=>{Sa(),Li()})}),Pt(J,()=>{le.value||(le.value=!0)});const{whiteboardModuleConfig:Fu,whiteboard:qt,whiteboardPages:pc,whiteboardPageSizes:Qt,whiteboardPageOffsets:Ln,whiteboardEnabled:Nn,whiteboardOpacity:Mi,handleWhiteboardPageReady:ns,updateWhiteboardPageSizes:Sa,updateWhiteboardPageOffsets:Li}=t9({proxy:F,layers:Ot,documents:a,modules:w}),Po=()=>Array.isArray(on.value)?on.value[0]:on.value,Di=Se(()=>Wr.value&&!!Fu.value),tb=Se(()=>Nn.value);return(O,q)=>(me(),_e("div",{ref_key:"superdocRoot",ref:Ct,class:en(["superdoc",{"superdoc--with-sidebar":se.value,"superdoc--web-layout":Ge(F).$superdoc.config.viewOptions?.layout==="web","superdoc--contained":Ge(F).$superdoc.config.contained,"high-contrast":Ge(K)}]),style:vn(Zt.value),onKeydown:Hn},[an.value?(me(),_e("p",PD,Ht(an.value),1)):ut("",!0),Le("div",{class:"superdoc__layers layers",ref_key:"layers",ref:Ot,role:"group"},[Qe.value?(me(),_e("div",{key:0,class:"superdoc__tools tools",style:vn(Vt)},[Le("div",{class:"tools-item","data-id":"is-tool",onMousedown:q[0]||(q[0]=Jt(Ee=>_r("comments"),["stop","prevent"]))},[Le("div",{class:"superdoc__tools-icon",innerHTML:Ge(ua).comment},null,8,OD)],32)],4)):ut("",!0),Le("div",FD,[ri.value?(me(),_e("div",{key:0,class:"superdoc__selection-layer selection-layer",onMousedown:$i,onMouseup:yo,ref_key:"selectionLayer",ref:Mn},[Ge(c)&&wl.value?(me(),_e("div",{key:0,style:vn(bt.value),class:"superdoc__temp-selection temp-selection sd-highlight sd-initial-highlight"},null,4)):ut("",!0)],544)):ut("",!0),(me(!0),_e(Wt,null,or(Ge(a),Ee=>(me(),_e("div",{class:"superdoc__sub-document sub-document",key:`${Ee.id}:${Ee.editorMountNonce}`,ref_for:!0,ref:Ne=>Wi(Ee,Ne)},[Ee.type===Ge("application/pdf")?(me(),fn(Ge(n),{key:0,file:Ee.data,"file-id":Ee.id,"initial-scale":(Ge(h)??100)/100,config:Ge(ur),onSelectionRaw:Ou,onBypassSelection:ts,onPageRendered:Ge(ns),onDocumentReady:q[1]||(q[1]=({documentId:Ne,viewerContainer:mt})=>$t(Ne,mt)),ref_for:!0,ref_key:"pdfViewerRef",ref:on},null,8,["file","file-id","initial-scale","config","onPageRendered"])):ut("",!0),Ee.type===Ge("application/vnd.openxmlformats-officedocument.wordprocessingml.document")&&Ge(G)&&vi(Ee)?(me(),_e(Wt,{key:1},[Ge(F).$superdoc.config.rulerContainer?(me(),fn(Oa,{key:0,to:Ge(F).$superdoc.config.rulerContainer},[Le("div",{class:"v2-ruler-host",style:vn(io.value)},[Gt(Ge(G),{"page-layout":Ge(F).$superdoc.activeEditor.pageLayout,"measurement-unit":Ge(p),onPageMarginsChange:Ne=>bo(Ee,Ne)},null,8,["page-layout","measurement-unit","onPageMarginsChange"])],4)],8,["to"])):(me(),_e("div",{key:1,class:"v2-ruler-host",style:vn(io.value)},[Gt(Ge(G),{"page-layout":Ge(F).$superdoc.activeEditor.pageLayout,"measurement-unit":Ge(p),onPageMarginsChange:Ne=>bo(Ee,Ne)},null,8,["page-layout","measurement-unit","onPageMarginsChange"])],4))],64)):ut("",!0),Ee.type===Ge("application/vnd.openxmlformats-officedocument.wordprocessingml.document")?(me(),fn(Ge(V),{key:2,"file-source":Ee.data,"document-id":Ee.id,options:Pf(Ee),"measurement-unit":Ge(p),onV2EditorReady:Ki,onV2EditorFailed:uc,onV2Render:Mf,onV2RenderCleared:ku,onV2RenderReadiness:Ts,onV2SelectionChanged:ul,onV2HostEvent:Ne=>Au(Ee,Ne),onV2LinkClick:Lf,onV2PageMetrics:Su},null,8,["file-source","document-id","options","measurement-unit","onV2HostEvent"])):ut("",!0),Ee.type===Ge("text/html")?(me(),fn(y9,{key:3,onReady:q[2]||(q[2]=Ne=>$t(Ne,null)),onSelectionChange:zt,"file-source":Ee.data,"document-id":Ee.id},null,8,["file-source","document-id"])):ut("",!0)]))),128)),Di.value?(me(),fn(s9,{key:1,class:"superdoc__whiteboard-layer",whiteboard:Ge(qt),pages:Ge(pc),"page-sizes":Ge(Qt),"page-offsets":Ge(Ln),enabled:Ge(Nn),interactive:tb.value,opacity:Ge(Mi)},null,8,["whiteboard","pages","page-sizes","page-offsets","enabled","interactive","opacity"])):ut("",!0),Of.value?(me(),fn(e9,{key:2,onAnchorActivate:po})):ut("",!0)])],512),se.value?(me(),_e("div",{key:1,ref_key:"rightSidebarRef",ref:Bt,class:"superdoc__right-sidebar right-sidebar"},[Le("div",BD,[Ge(le)&&(J.value.length>0||Ge(B))?(me(!0),_e(Wt,{key:0},or(Ge(M),Ee=>(me(),fn(qR,{parent:Ot.value,"current-document":Ee},null,8,["parent","current-document"]))),256)):ut("",!0)])],512)):ut("",!0),de.value?(me(),_e("div",{key:2,class:"superdoc__compact-comment-popover",style:vn(Ge(pe))},[Gt(gp,{comment:de.value,parent:Ot.value},null,8,["comment","parent"])],4)):ut("",!0),Gt(wD,{"geometry-target":Ot.value},null,8,["geometry-target"])],38))}},UD=hn(HD,[["__scopeId","data-v-2a7bfa95"]]);It();var QS="devtools-plugin:setup",ZS="dev.esm.pinia",ln={disabledAppRefCounts:new Map,hook:null,originalHookEmit:null,isHookPropertyPatched:!1,originalHookPropertyDescriptor:null,hookPropertyValue:void 0,isQueuePropertyPatched:!1,originalQueuePropertyDescriptor:null,queuePropertyValue:void 0,queue:null,originalQueuePush:null},JS=(e,t)=>e===QS&&t?.id===ZS&&t?.app&&ln.disabledAppRefCounts.has(t.app),VD=e=>Array.isArray(e)&&JS(QS,e[0]),jD=e=>{if(ln.isQueuePropertyPatched){ln.queuePropertyValue=e;return}globalThis.__VUE_DEVTOOLS_PLUGINS__=e},GD=e=>{const t=globalThis.__VUE_DEVTOOLS_PLUGINS__;if(Array.isArray(t))for(let n=t.length-1;n>=0;n--){const[r]=t[n];r?.id===ZS&&r?.app===e&&t.splice(n,1)}},$S=()=>{const{queue:e,originalQueuePush:t}=ln;e&&typeof t=="function"&&(e.push=t),ln.queue=null,ln.originalQueuePush=null},e4=()=>{const{hook:e,originalHookEmit:t}=ln;e&&typeof t=="function"&&(e.emit=t),ln.hook=null,ln.originalHookEmit=null},rf=()=>{const e=globalThis.__VUE_DEVTOOLS_PLUGINS__;if(e==null){jD([]),rf();return}if(!Array.isArray(e))return;const t=e;if(ln.queue===t)return;$S();const n=t.push;typeof n=="function"&&(ln.queue=t,ln.originalQueuePush=n,t.push=function(...o){const i=o.filter(s=>!VD(s));return i.length===0?this.length:n.apply(this,i)})},WD=()=>{if(ln.isQueuePropertyPatched){rf();return}const e=Object.getOwnPropertyDescriptor(globalThis,"__VUE_DEVTOOLS_PLUGINS__");if(e?.configurable===!1){rf();return}ln.originalQueuePropertyDescriptor=e??null,ln.queuePropertyValue=globalThis.__VUE_DEVTOOLS_PLUGINS__,Object.defineProperty(globalThis,"__VUE_DEVTOOLS_PLUGINS__",{configurable:!0,enumerable:e?.enumerable??!0,get(){return ln.queuePropertyValue},set(t){ln.queuePropertyValue=t,rf()}}),ln.isQueuePropertyPatched=!0,rf()},KD=()=>{if(!ln.isQueuePropertyPatched)return;const{queuePropertyValue:e,originalQueuePropertyDescriptor:t}=ln;delete globalThis.__VUE_DEVTOOLS_PLUGINS__,t?"value"in t?Object.defineProperty(globalThis,"__VUE_DEVTOOLS_PLUGINS__",{configurable:t.configurable,enumerable:t.enumerable,writable:t.writable,value:e}):(Object.defineProperty(globalThis,"__VUE_DEVTOOLS_PLUGINS__",t),typeof t.set=="function"&&t.set.call(globalThis,e)):e!==void 0&&(globalThis.__VUE_DEVTOOLS_PLUGINS__=e),ln.isQueuePropertyPatched=!1,ln.originalQueuePropertyDescriptor=null,ln.queuePropertyValue=void 0},kp=()=>{const e=globalThis?.__VUE_DEVTOOLS_GLOBAL_HOOK__;if(!e||typeof e.emit!="function"||ln.hook===e)return;e4();const t=e.emit;ln.hook=e,ln.originalHookEmit=t,e.emit=function(r,...o){const[i]=o;if(!JS(r,i))return t.call(this,r,...o)}},qD=()=>{if(ln.isHookPropertyPatched){kp();return}const e=Object.getOwnPropertyDescriptor(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__");if(e?.configurable===!1){kp();return}ln.originalHookPropertyDescriptor=e??null,ln.hookPropertyValue=globalThis.__VUE_DEVTOOLS_GLOBAL_HOOK__,Object.defineProperty(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__",{configurable:!0,enumerable:e?.enumerable??!0,get(){return ln.hookPropertyValue},set(t){ln.hookPropertyValue=t,kp()}}),ln.isHookPropertyPatched=!0,kp()},YD=()=>{if(!ln.isHookPropertyPatched)return;const{hookPropertyValue:e,originalHookPropertyDescriptor:t}=ln;delete globalThis.__VUE_DEVTOOLS_GLOBAL_HOOK__,t?"value"in t?Object.defineProperty(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__",{configurable:t.configurable,enumerable:t.enumerable,writable:t.writable,value:e}):(Object.defineProperty(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__",t),typeof t.set=="function"&&t.set.call(globalThis,e)):e!==void 0&&(globalThis.__VUE_DEVTOOLS_GLOBAL_HOOK__=e),ln.isHookPropertyPatched=!1,ln.originalHookPropertyDescriptor=null,ln.hookPropertyValue=void 0},XD=()=>{ln.disabledAppRefCounts.size>0||(e4(),YD(),$S(),KD())},QD=(e,t)=>{if(!t)return()=>{};const n=ln.disabledAppRefCounts.get(e)??0;return ln.disabledAppRefCounts.set(e,n+1),qD(),WD(),()=>{const r=ln.disabledAppRefCounts.get(e);r&&(r===1?ln.disabledAppRefCounts.delete(e):ln.disabledAppRefCounts.set(e,r-1),XD())}};const ZD=({disablePiniaDevtools:e=!1}={})=>{const t=Hl(UD),n=m6(),r=QD(t,e);let o,i,s;try{t.use(n),e&&GD(t),t.directive("click-outside",Fv),o=nu(),i=ca(),s=zi()}catch(a){throw r(),a}if(typeof t.unmount=="function"){const a=t.unmount.bind(t);t.unmount=(...l)=>(r(),a(...l))}return{app:t,pinia:n,superdocStore:o,commentsStore:i,highContrastModeStore:s}};var JD={docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",pdf:"application/pdf",zip:"application/zip",html:"text/html",txt:"text/plain;charset=utf-8",json:"application/json"},$D=e=>!e||typeof e.toLowerCase!="function"?"application/octet-stream":JD[e.toLowerCase()]||"application/octet-stream",eP=(e,t)=>{if(e instanceof Blob)return e;const n=$D(t);if(e instanceof ArrayBuffer)return new Blob([e],{type:n});if(ArrayBuffer.isView(e)){const{buffer:r,byteOffset:o,byteLength:i}=e,s=r.slice(o,o+i);return new Blob([s],{type:n})}if(typeof e=="string")return new Blob([e],{type:n});throw e==null?new TypeError("createDownload requires a Blob, ArrayBuffer, or ArrayBufferView."):new TypeError(`Cannot create download from value of type ${typeof e}`)};const t4=(e,t,n)=>{const r=eP(e,n);if(typeof URL>"u"||typeof URL.createObjectURL!="function"||typeof document>"u"||typeof document.createElement!="function")return r;const o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${t}.${n}`;const s=document.body&&typeof document.body.appendChild=="function";return s&&document.body.appendChild(i),i.click(),s&&document.body.removeChild(i),typeof URL.revokeObjectURL=="function"&&setTimeout(()=>URL.revokeObjectURL(o),0),r},n4=e=>{const t=e.toLowerCase();return t.endsWith(".docx")?e.slice(0,-5):t.endsWith(".pdf")?e.slice(0,-4):e};var tP=class{#t=new Map;#n=1;idFor(e){const t=this.#t.get(e);if(t!==void 0)return t;const n=this.#n++;return this.#t.set(e,n),n}has(e){return this.#t.has(e)}};function nP(e){const t=typeof e.email=="string"&&e.email.length>0?e.email:null;return t?`email:${t}`:`label:${e.actorLabel}`}function rP(e,t){const n=e.displayName??null,r=e.email??null,o={clientId:t};return n&&(o.name=n),r&&(o.email=r),typeof e.color=="string"&&e.color.length>0&&(o.color=e.color),o}function oP(e){const t={clientId:0};e?.id!=null&&(t.id=e.id),e?.name!=null&&(t.name=e.name),e?.email!=null&&(t.email=e.email);const n=e?.color;return typeof n=="string"&&n.length>0&&(t.color=n),t}function iP(e){const t=new tP;let n=new Set;return{registry:t,next(r){const o=[],i=new Set,s=new Set;for(const u of r.remoteActors){const c=nP(u);if(s.has(c))continue;s.add(c);const d=t.idFor(c);i.add(d),o.push(rP(u,d))}const a=[];for(const u of i)n.has(u)||a.push(u);const l=[];for(const u of n)i.has(u)||l.push(u);return n=i,{states:[oP(e()),...o],added:a,removed:l}}}}var sP=class{#t=new Map;on(e,t){const n=this.#t.get(e);n?n.push(t):this.#t.set(e,[t])}emit(e,...t){const n=this.#t.get(e);if(n)for(const r of n)r.apply(this,t)}off(e,t){const n=this.#t.get(e);n&&(t?this.#t.set(e,n.filter(r=>r!==t)):this.#t.delete(e))}once(e,t){const n=(...r)=>{this.off(e,n),t.apply(this,r)};this.on(e,n)}removeAllListeners(){this.#t=new Map}};function aP(e){return e.flatMap(t=>[t[0],t[1]])}function r4(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function o4(e={}){const{value:t="",left:n,top:r,width:o,height:i,fontSize:s=16,fontFamily:a="Arial, sans-serif",color:l="#000",background:u="transparent",resize:c="none"}=e,d=document.createElement("textarea");d.value=t;const h=d.style;return h.position="absolute",n!=null&&(h.left=`${n}px`),r!=null&&(h.top=`${r}px`),o!=null&&(h.width=typeof o=="number"?`${o}px`:o),i!=null&&(h.height=typeof i=="number"?`${i}px`:i),h.minWidth=120,h.fontSize=typeof s=="number"?`${s}px`:s,h.fontFamily=a,h.color=l,h.background=u,h.border="2px solid #3c97fe80",h.padding="2px 4px",h.margin="0",h.zIndex="1000",h.overflow="hidden",h.resize=c,h.outline="none",d}var Ap=18,lP=class{pageIndex=null;strokes=[];text=[];images=[];size=null;originalSize=null;#t=null;#n=null;#e=null;#i=null;#s=null;#a=null;#u=new Set;#d=!1;#l=null;#f=[];#m=null;#o="select";#r=!1;#p=null;#y="#2293fb";#w=5;#_=null;#S=null;constructor(e){this.#E(e)}#E(e){this.#t=e.Renderer,this.#r=e.enabled,this.pageIndex=e.pageIndex,this.#_=e.onChange,this.#S=e.onToolChange}#x(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{xN:e/n,yN:t/r}}#M(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{x:e*n,y:t*r}}#c(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{wN:e/n,hN:t/r}}#L(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{width:e*n,height:t*r}}#T(e){const{width:t=1,height:n=1}=this.size||{};return{points:(Array.isArray(e.pointsN)?e.pointsN:[]).map(r=>[r[0]*t,r[1]*n]),strokeWidth:Number.isFinite(e.widthN)?e.widthN*((t+n)/2):this.#w}}#D(e){const{width:t=1,height:n=1}=this.size||{};return{pointsN:(Array.isArray(e.points)?e.points:[]).map(r=>[r[0]/t,r[1]/n]),widthN:Number.isFinite(e.width)?e.width/((t+n)/2):void 0}}#k(e){const{width:t=1,height:n=1}=this.size||{};return{x:(e.xN??0)*t,y:(e.yN??0)*n,width:Number.isFinite(e.widthN)?e.widthN*t:void 0,fontSize:Number.isFinite(e.fontSizeN)?e.fontSizeN*n:Ap}}#g(e){const{width:t=1,height:n=1}=this.size||{},r=this.originalSize?.height??n;return{xN:(e.x??0)/t,yN:(e.y??0)/n,widthN:Number.isFinite(e.width)?e.width/t:null,fontSizeN:Number.isFinite(e.fontSize)?e.fontSize/r:Ap/r}}#j(e){const{width:t=1,height:n=1}=this.size||{};return{x:(e.xN??0)*t,y:(e.yN??0)*n,width:Number.isFinite(e.widthN)?e.widthN*t:void 0,height:Number.isFinite(e.heightN)?e.heightN*n:void 0}}#G(e){const{width:t=1,height:n=1}=this.size||{};return{xN:(e.x??0)/t,yN:(e.y??0)/n,widthN:Number.isFinite(e.width)?e.width/t:null,heightN:Number.isFinite(e.height)?e.height/n:null}}#P(){const e=this.size?.width,t=this.originalSize?.width??e;return!Number.isFinite(e)||!Number.isFinite(t)||!t?1:e/t}#O(){!this.#n||!this.#e||(this.#n.on("mousedown touchstart",e=>{this.#Y(e)}),this.#n.on("mousemove touchmove",e=>{this.#X(e)}),this.#n.on("mouseup touchend",e=>{this.#I(e)}),this.#n.on("click tap",e=>{this.#R(e)}),window.addEventListener("keydown",this.#q))}setTool(e){this.#o=e,this.#C(),this.#A(),this.render()}getTool(){return this.#o}setEnabled(e){this.#r=!!e,this.#C(),this.#A(),this.render()}isEnabled(){return this.#r}setSize(e){if(!e)return;const{width:t,height:n,originalWidth:r,originalHeight:o}=e;this.size={width:t,height:n},this.originalSize={width:r??null,height:o??null}}resize(e,t){this.#n&&(this.#n.size({width:e,height:t}),this.#F(),this.render())}mount(e){if(!e||this.#n&&this.#a===e)return;this.#n&&this.destroy();const t=this.size?.width||e.clientWidth||1,n=this.size?.height||e.clientHeight||1;this.#a=e,this.#n=new this.#t.Stage({container:e,width:t,height:n}),this.#e=new this.#t.Layer,this.#i=new this.#t.Layer,this.#n.add(this.#e),this.#n.add(this.#i),this.#F(),this.#C(),this.#O(),this.render()}render(){this.#e&&(this.#s&&(this.#s.destroy(),this.#s=null),this.#e.find(".wb-text").forEach(e=>e.destroy()),this.#i.destroyChildren(),this.renderStrokes(),this.renderText(),this.renderImages(),this.#e.batchDraw(),this.#i.batchDraw())}#F(){const e=Math.min(window.devicePixelRatio||1,1.5);this.#e?.getCanvas&&this.#e.getCanvas().setPixelRatio(e),this.#i?.getCanvas&&this.#i.getCanvas().setPixelRatio(e)}#C(){if(!this.#i)return;const e=this.#o==="draw"||this.#o==="erase",t=!!(this.#r&&e);this.#i.listening(t)}renderStrokes(){this.strokes.forEach(e=>{const{points:t,strokeWidth:n}=this.#T(e),r=new this.#t.Line({points:aP(t),stroke:e.color||this.#y,strokeWidth:n,lineCap:"round",lineJoin:"round",globalCompositeOperation:e.type==="erase"?"destination-out":"source-over"});r.name("wb-stroke"),this.#i.add(r)})}renderText(){this.text.forEach(e=>{const{x:t,y:n,width:r,fontSize:o}=this.#k(e),i=new this.#t.Text({x:t,y:n,text:e.content,fontSize:o,fontFamily:"Arial, sans-serif",fill:"#2293fb",draggable:this.#o==="select",width:r});i.name("wb-text"),i._whiteboardId=e.id,this.#W(i,e),this.#e.add(i)})}#W(e,t){e.on("click tap",n=>{this.#o!=="select"||!this.#r||(n.cancelBubble=!0,this.#B(e))}),e.on("dragend",()=>{const{xN:n,yN:r}=this.#g({x:e.x(),y:e.y(),fontSize:t.fontSizeN?t.fontSizeN*(this.size?.height||1):Ap,width:t.widthN?t.widthN*(this.size?.width||1):null});t.xN=n,t.yN=r,this.#v()}),e.on("transform",()=>{e.scaleY(1),e.setAttrs({width:e.width()*e.scaleX(),scaleX:1})}),e.on("transformend",()=>{e.setAttrs({width:Math.max(1,e.width()*e.scaleX()),scaleX:1,scaleY:1});const n=e.width(),r=this.size?.width||1;t.widthN=n/r,t.xN=e.x()/r,t.yN=e.y()/(this.size?.height||1),this.#v()}),e.on("dblclick dbltap",n=>{this.#o!=="select"||!this.#r||(n.cancelBubble=!0,this.#z(e,t))})}renderImages(){const e=this.#e?.find(".wb-image")??[],t=new Map;e.forEach(o=>{t.set(o._whiteboardId,o)});const n=new Set(this.images.map(o=>o.id));e.forEach(o=>{n.has(o._whiteboardId)||o.destroy()});const r=(o,i)=>{const{x:s,y:a,width:l,height:u}=this.#j(o),c=t.get(o.id);if(c){Number.isFinite(s)&&c.x(s),Number.isFinite(a)&&c.y(a),Number.isFinite(l)&&c.width(l),Number.isFinite(u)&&c.height(u),c.draggable(this.#o==="select");return}if(this.#u.has(o.id))return;this.#u.add(o.id);const d=new window.Image;d.crossOrigin="Anonymous",d.onload=()=>{if(t.get(o.id)){this.#u.delete(o.id);return}if(!this.#e){this.#u.delete(o.id);return}const h=new this.#t.Image({x:s,y:a,image:d,width:l??d.width,height:u??d.height,draggable:this.#o==="select"});h.name(i),h._whiteboardId=o.id,this.#K(h,o),this.#e.add(h),this.#e.batchDraw(),this.#u.delete(o.id)},d.onerror=()=>{this.#u.delete(o.id)},d.src=o.src};this.images.forEach(o=>r(o,"wb-image"))}#K(e,t){e.on("click tap",n=>{this.#o!=="select"||!this.#r||(n.cancelBubble=!0,this.#B(e))}),e.on("dragend",()=>{const n=this.size?.width||1,r=this.size?.height||1;t.xN=e.x()/n,t.yN=e.y()/r,this.#v()}),e.on("transformend",()=>{const n=e.scaleX(),r=e.scaleY(),o=Math.max(1,e.width()*n),i=Math.max(1,e.height()*r);e.scale({x:1,y:1}),e.width(o),e.height(i);const s=this.size?.width||1,a=this.size?.height||1;t.widthN=o/s,t.heightN=i/a,t.xN=e.x()/s,t.yN=e.y()/a,this.#v()})}destroy(){this.#n&&this.#n.destroy(),this.#n=null,this.#e=null,this.#i=null,this.#a=null,this.#d=!1,this.#l=null,this.#f=[],this.#p=null,this.#s=null,window.removeEventListener("keydown",this.#q)}toJSON(){return{strokes:this.strokes,text:this.text,images:this.images}}applyData(e={}){const t=Array.isArray(e.strokes)?e.strokes:[],n=Array.isArray(e.text)?e.text:[],r=Array.isArray(e.images)?e.images:[];this.strokes=t,this.text=n,this.images=r,this.render()}#v(){this.#_&&this.#_()}addStroke(e){if(!e||!Array.isArray(e.points))return;const{pointsN:t,widthN:n}=this.#D(e);this.strokes.push({pointsN:t,widthN:n,color:e.color,type:e.type})}addText(e){if(!e||typeof e.content!="string")return;const{xN:t,yN:n,widthN:r,fontSizeN:o}=this.#g(e);this.text.push({id:e.id??r4("text"),xN:t,yN:n,content:e.content,fontSizeN:o,widthN:r}),this.render(),this.#v()}addImage(e){if(!e||!e.src)return;const{xN:t,yN:n,widthN:r,heightN:o}=this.#G(e),i={id:e.id??r4("image"),stickerId:e.stickerId??(e.type==="sticker"?e.id??null:null),xN:t,yN:n,src:e.src,widthN:r,heightN:o,type:e.type??"image"};this.images.push(i),this.render(),this.#v()}#A(){this.#s&&(this.#s.destroy(),this.#s=null,this.#p=null,this.#e?.batchDraw())}#B(e){if(!this.#e)return;this.#p=e;const t=e.name&&e.name()==="wb-text",n=t?["middle-left","middle-right"]:["top-left","top-right","bottom-left","bottom-right"],r=(o,i)=>i.width<20?o:t?{...i,height:o.height,y:o.y}:i.height<20?o:i;this.#s?(this.#s.nodes([e]),this.#s.enabledAnchors(n),this.#s.boundBoxFunc(r)):(this.#s=new this.#t.Transformer({nodes:[e],enabledAnchors:n,rotateEnabled:!1,keepRatio:!1,boundBoxFunc:r}),this.#e.add(this.#s)),this.#e.batchDraw()}#h(){if(!this.#p)return;const e=this.#p,t=e.name&&e.name(),n={"wb-text":()=>{const r=e._whiteboardId;this.text=this.text.filter(o=>o.id!==r)},"wb-image":()=>{const r=e._whiteboardId;this.images=this.images.filter(o=>o.id!==r)}}[t];n&&n(),e.destroy(),this.#A(),this.render()}#q=e=>{if(!this.#p||!this.#r||this.#o!=="select")return;const t=e.target?.tagName;t==="INPUT"||t==="TEXTAREA"||(e.key==="Backspace"||e.key==="Delete")&&(e.preventDefault(),this.#h(),this.#v())};#R(e){if(!this.#r||!this.#n)return;const t={text:()=>{const n=this.#n.getPointerPosition();n&&this.#N(n.x,n.y)},select:()=>{e?.target===this.#n&&this.#A()}}[this.#o];t&&t()}#Y(){if(!this.#r||this.#o!=="draw"&&this.#o!=="erase")return;this.#d=!0;const e=this.#n.getPointerPosition();if(!e)return;const t=this.#o==="erase",n=this.#w*this.#P();this.#f=[e.x,e.y],this.#l=new this.#t.Line({points:this.#f,stroke:this.#y,strokeWidth:t?n*3:n,lineCap:"round",lineJoin:"round",globalCompositeOperation:t?"destination-out":"source-over"}),this.#m=n,this.#i.add(this.#l)}#X(){if(!this.#r||this.#o!=="draw"&&this.#o!=="erase"||!this.#d||!this.#l)return;const e=this.#n.getPointerPosition();e&&(this.#f.push(e.x,e.y),this.#l.points(this.#f),this.#i.batchDraw())}#I(){if(!this.#r||this.#o!=="draw"&&this.#o!=="erase"||!this.#d||!this.#l)return;this.#d=!1;const e=[];for(let r=0;r<this.#f.length;r+=2)e.push([this.#f[r],this.#f[r+1]]);const t=this.#o==="erase",n=this.#m??this.#w;this.addStroke({points:e,color:this.#y,width:t?n*3:n,type:t?"erase":"draw"}),this.#v(),this.#l=null,this.#f=[],this.#m=null}#N(e,t){if(!this.#a)return;const n=Ap*this.#P(),r=o4({left:e,top:t,height:Math.ceil(n*1.4),background:"transparent",fontSize:n,color:"#2293fb"});this.#a.append(r),r.focus(),r.select();let o=!1;const i=()=>{if(o)return;o=!0;const s=r.value.trim();s&&(this.addText({x:e,y:t,content:s}),this.#o==="text"&&this.#S&&this.#S("select")),r.parentNode===this.#a&&this.#a.removeChild(r)};r.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i()),s.key==="Escape"&&(s.preventDefault(),i())}),r.addEventListener("blur",i)}#z(e,t){if(!this.#a||!this.#n)return;this.#A();const n=e.position(),r=o4({value:e.text(),left:n.x,top:n.y,width:Math.max(e.width(),120),height:Math.max(e.height(),24),fontSize:e.fontSize(),fontFamily:e.fontFamily(),color:e.fill?e.fill():"#2293fb",background:"white",resize:"both"});this.#a.appendChild(r),r.focus(),r.select();let o=!1;const i=()=>{if(o)return;o=!0;const s=r.value.trim();s&&(e.text(s),t.content=s,this.#e.batchDraw(),this.#v()),r.parentNode&&r.parentNode.removeChild(r)};r.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i()),s.key==="Escape"&&(s.preventDefault(),i())}),r.addEventListener("blur",i)}},cP=class extends sP{#t=null;#n=null;#e=new Map;#i=new Map;#s="select";#a=!1;#u=1;#d=null;#l=null;#f=null;constructor(e={}){super(),this.#m(e)}#m(e){this.#t=e.Renderer,this.#n=e.superdoc,this.#a=e.enabled,this.#d=e.onChange,this.#l=e.onSetData,this.#f=e.onEnabledChange}register(e,t){this.#i.set(e,t)}getType(e){return this.#i.get(e)}setTool(e){this.#s=e,this.#e.forEach(t=>t.setTool(e)),this.emit("tool",e)}getTool(){return this.#s}setEnabled(e){this.#a=e,this.#e.forEach(t=>t.setEnabled(this.#a)),this.emit("enabled",this.#a),this.#f&&this.#f(this.#a)}isEnabled(){return this.#a}setOpacity(e){const t=e;this.#u=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1,this.emit("opacity",this.#u)}getOpacity(){return this.#u}getPages(){return Array.from(this.#e.values())}rerender(){this.#e.forEach(e=>e.render())}setPageSize(e,t){this.#o(e).setSize(t)}#o(e){const t=this.#e.get(e);if(t)return t;const n=new lP({Renderer:this.#t,enabled:this.#a,pageIndex:e,onChange:()=>{this.#r()},onToolChange:r=>{this.setTool(r)}});return n.setTool(this.#s),n.setEnabled(this.#a),this.#e.set(e,n),n}getPage(e){return this.#e.get(e)}getWhiteboardData(){const e={},t={};for(const n of this.#e.values())e[n.pageIndex]=n.toJSON(),n.size&&(t[n.pageIndex]={width:n.size.width,height:n.size.height,originalWidth:n.originalSize?.width??null,originalHeight:n.originalSize?.height??null});return{pages:e,meta:{pageSizes:t},version:1}}setWhiteboardData(e){this.#e.clear();const t=e?.pages||{};Object.keys(t).forEach(n=>{const r=Number(n),o=Number.isNaN(r)?n:r;this.#o(o).applyData(t[n])}),this.emit("setData",this.getPages()),this.#l&&this.#l(this.getPages()),this.#r()}#r(){const e=this.getWhiteboardData();this.emit("change",e),this.#d&&this.#d(e)}},uP=Math.PI/180;function dP(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const Wl=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},gt={_global:Wl,version:"10.2.5",isBrowser:dP(),isUnminified:/param/.test(function(e){}.toString()),dblClickWindow:400,getAngle(e){return gt.angleDeg?e*uP:e},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return gt.DD.isDragging},isTransforming(){var e,t;return(t=(e=gt.Transformer)===null||e===void 0?void 0:e.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!gt.DD.node},releaseCanvasOnDestroy:!0,document:Wl.document,_injectGlobal(e){typeof Wl.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),Wl.Konva=e}},vr=e=>{gt[e.prototype.getClassName()]=e};gt._injectGlobal(gt);var fP=`Konva.js unsupported environment.
|
|
86
|
+
`;const tr={undo:s_,redo:BM,bold:pM,italic:mM,underline:gM,color:VM,link:dS,image:xM,tableOfContents:uL,alignLeft:TM,alignRight:MM,alignCenter:RM,alignJustify:LM,bulletList:uS,bulletListDisc:uS,bulletListCircle:vM,bulletListSquare:yM,numberedList:bM,numberedListDecimal:wM,numberedListDecimalParen:CM,numberedListUpperRoman:_M,numberedListLowerRoman:SM,numberedListUpperAlpha:kM,numberedListUpperAlphaParen:AM,numberedListLowerAlpha:IM,numberedListLowerAlphaParen:EM,indentLeft:PM,indentRight:DM,directionLtr:dL,directionRtl:fL,pageBreak:jM,copyFormat:OM,clearFormatting:FM,trackChanges:HM,trackChangesFinal:UM,trackChangesOriginal:hS,trackChangesAccept:NM,trackChangesReject:zM,documentMode:fS,documentEditingMode:fS,documentSuggestingMode:n_,documentViewingMode:hS,colorOption:GM,colorOptionCheck:Vy,linkInput:dS,removeLink:o_,openLink:WM,overflow:i_,dropdownCaretUp:KM,dropdownCaretDown:r_,ruler:qM,paintbrush:YM,highlight:XM,ai:QM,table:ZM,tableActions:JM,splitCell:$M,mergeCells:eL,addRowBefore:vp,addRowAfter:vp,addColumnBefore:vp,addColumnAfter:vp,deleteRow:Jy,deleteColumn:Jy,deleteTable:Jy,deleteBorders:nL,fixTables:tL,lineHeight:rL,search:oL,cut:iL,copy:sL,paste:aL,strikethrough:lL,formattingMarks:cL};It(),gn();var hL={key:0,class:"link-title"},pL={key:1,class:"link-title"},mL={key:2,class:"link-title"},gL={key:3,class:"link-title"},vL={key:4,class:"link-input-wrapper"},yL={class:"input-row text-input-row"},bL=["readonly","onKeydown"],wL={class:"input-row url-input-row"},CL=["innerHTML"],_L=["readonly","onKeydown"],SL=["innerHTML"],kL={key:0,class:"input-row link-buttons"},AL=["innerHTML"],IL={key:5,class:"input-row go-to-anchor clickable"},EL={__name:"LinkInput",props:{showInput:{type:Boolean,default:!0},showLink:{type:Boolean,default:!0},goToAnchor:{type:Function,default:()=>{}},ui:{type:Object,default:null},linkItem:{type:Object,default:null},closePopover:{type:Function,default:()=>{}},href:{type:String,default:null},target:{type:String,default:null},rel:{type:String,default:null},tooltip:{type:String,default:null},clickedElement:{type:Object,default:null},hyperlinkTarget:{type:Object,default:null},hyperlinkText:{type:String,default:null},textTarget:{type:Object,default:null},restoreSelection:{type:Function,default:()=>{}},documentMode:{type:String,default:null}},setup(e){const t=e,{isHighContrastMode:n}=zi(),r=ne(!1),o=()=>{if(typeof t.hyperlinkText=="string"&&t.hyperlinkText)return t.hyperlinkText;const H=t.ui?.selection?.getSnapshot?.();if(typeof H?.quotedText=="string"&&H.quotedText)return H.quotedText;const B=t.clickedElement?.innerText??t.clickedElement?.textContent;return typeof B=="string"?B:""},i=()=>{if(typeof t.href=="string"&&t.href)return t.href;const H=t.ui?.toolbar?.getSnapshot?.()?.commands?.link?.value;if(typeof H=="string"&&H)return H;const B=t.linkItem?.attributes?.value?.href;return typeof B=="string"?B:""},s=()=>t.documentMode??t.ui?.document?.getSnapshot?.()?.mode??null,a=ne(""),l=ne(""),u=ne(!1),c=/^[a-z][a-z0-9+.-]*:/i,d=Se(()=>{const H=l.value.trim();return H?H.startsWith("#")||c.test(H)?H:"https://"+H:""}),h=Se(()=>d.value?hM(d.value):null),m=Se(()=>h.value!==null),p=ne(!1),g=Se(()=>!u.value&&p.value),k=Se(()=>!m.value),w=Se(()=>s()==="viewing"),S=()=>{const H=h.value?.href;H&&window.open(H,"_blank","noopener")},y=()=>{const H=document.querySelector(".link-input-ctn input");H&&H.focus()};Rn(()=>{a.value=o(),l.value=i(),p.value=!!l.value,u.value=l.value.startsWith("#"),t.showInput&&!w.value&&y()});const C=H=>{const B=t.ui;return B?.commands?.execute?(t.restoreSelection?.(),B.commands.execute("link",H)):!1},T=()=>{if(w.value)return;if(!l.value){C({href:null,hyperlinkTarget:t.hyperlinkTarget}),t.closePopover();return}if(!m.value){r.value=!0;return}const H=h.value?.href;if(!H){r.value=!0;return}const B={href:H,currentText:o(),hyperlinkTarget:t.hyperlinkTarget,textTarget:t.textTarget};a.value?B.text=a.value:g.value||(B.text=H),C(B),t.closePopover()},R=()=>{C({href:null,hyperlinkTarget:t.hyperlinkTarget}),t.closePopover()},M=H=>{t.goToAnchor&&t.goToAnchor(H)};return(H,B)=>(me(),_e("div",{class:en(["link-input-ctn",{"high-contrast":Ge(n)}])},[u.value?(me(),_e("div",hL,"Page anchor")):w.value?(me(),_e("div",pL,"Link details")):g.value?(me(),_e("div",mL,"Edit link")):(me(),_e("div",gL,"Add link")),e.showInput&&!u.value?(me(),_e("div",vL,[Le("div",yL,[B[4]||(B[4]=Le("div",{class:"input-icon text-input-icon"},"T",-1)),Ws(Le("input",{type:"text",name:"text",placeholder:"Text","onUpdate:modelValue":B[0]||(B[0]=z=>a.value=z),readonly:w.value,onKeydown:Yo(Jt(T,["stop","prevent"]),["enter"])},null,40,bL),[[ki,a.value]])]),Le("div",wL,[Le("div",{class:"input-icon",innerHTML:Ge(tr).linkInput},null,8,CL),Ws(Le("input",{type:"text",name:"link",placeholder:"Type or paste a link",class:en({"sd-error":r.value}),"onUpdate:modelValue":B[1]||(B[1]=z=>l.value=z),readonly:w.value,onKeydown:[Yo(Jt(T,["stop","prevent"]),["enter"]),B[2]||(B[2]=z=>r.value=!1)]},null,42,_L),[[ki,l.value]]),Le("div",{class:en(["open-link-icon",{"sd-disabled":!m.value}]),innerHTML:Ge(tr).openLink,onClick:S,"data-item":"btn-link-open"},null,10,SL)]),w.value?ut("",!0):(me(),_e("div",kL,[g.value?(me(),_e("button",{key:0,class:"remove-btn",onClick:R,"data-item":"btn-link-remove"},[Le("div",{class:"remove-btn__icon",innerHTML:Ge(tr).removeLink},null,8,AL),B[5]||(B[5]=Oi(" Remove ",-1))])):ut("",!0),Le("button",{class:en(["sd-submit-btn",{"disable-btn":k.value}]),onClick:T,"data-item":"btn-link-apply"}," Apply ",2)]))])):u.value?(me(),_e("div",IL,[Le("a",{onClick:B[3]||(B[3]=Jt(z=>M(l.value),["stop","prevent"]))},"Go to "+Ht(l.value.startsWith("#_")?l.value.substring(2):l.value),1)])):ut("",!0)],2))}},pS=hn(EL,[["__scopeId","data-v-3e4bd44e"]]);function xL(e){let t=e;for(;t;){const n=window.getComputedStyle(t).overflowY;if(/(auto|scroll)/.test(n)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return document.scrollingElement||document.documentElement}function tf(e,t={behavior:"smooth",block:"start"}){if(!e)return;const n=xL(e),r=n.getBoundingClientRect(),o=e.getBoundingClientRect().top-r.top+n.scrollTop,i=window.getComputedStyle(n).scrollPaddingTop?.trim(),s=i?.endsWith("px")?Number(i.slice(0,-2)):0,a=Number.isFinite(s)&&s>=0?s:0;n.scrollTo({top:t.block==="start"?o-a:o-n.clientHeight+e.offsetHeight,behavior:t.behavior})}It();var TL="link-popover",RL=500,ML=e=>!!(e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"),LL=e=>!!(e&&typeof e=="object"&&!Array.isArray(e));function DL(e){return LL(e)?e.type==="default"||e.type==="none"?!0:e.type==="custom"?e.component!=null:e.type==="external"?typeof e.render=="function":!1:!1}function mS(e){return e instanceof Error?e:new Error(String(e))}function PL(e){return typeof e!="string"?"":e.split(/\s+/).map(t=>t.trim().toLowerCase()).filter(t=>t==="noopener"||t==="noreferrer").filter((t,n,r)=>r.indexOf(t)===n).join(",")}function OL(e,t){const n=PL(e);if(t!=="_blank")return n;const r=n?n.split(","):[];return r.includes("noopener")||r.unshift("noopener"),r.join(",")}function gS(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):String(e).replace(/['"\\]/g,"\\$&")}function FL(e){const t=e?.dataset?.sourceAnchor;if(typeof t!="string")return null;try{const n=JSON.parse(t)?.sourceRef?.xpathLikePath,r=typeof n=="string"?n.match(/w:p\[ordinal=(\d+)\]/):null;return r?Number(r[1]):null}catch{return null}}function BL(e,t){const n=FL(e),r=t?.blocks?.list?.()?.blocks,o=Array.isArray(r)?r.find(i=>i.ordinal===n):null;return typeof o?.nodeId=="string"?o.nodeId:e?.dataset?.blockId}function vS(e,t){const n=e?.closest?.("[data-block-id][data-pm-start]"),r=BL(n,t);if(!r||!n||!e?.ownerDocument)return null;const o=Number(e?.dataset?.pmStart),i=Number(e?.dataset?.pmEnd);if(Number.isFinite(o)&&Number.isFinite(i)&&i>o){const m=Number(n?.dataset?.pmStart),p=Number.isFinite(m)&&o>=m,g=p?o-m:o,k=p?i-m:i;return g<0||k<=g?null:{kind:"selection",start:{kind:"text",blockId:r,offset:g},end:{kind:"text",blockId:r,offset:k}}}const s=e.ownerDocument.defaultView,a=s?.NodeFilter,l=s?.Node;if(!a||!l)return null;let u=0;const c=e.ownerDocument.createTreeWalker(n,a.SHOW_ELEMENT|a.SHOW_TEXT);let d=c.nextNode();for(;d&&d!==e;)d.nodeType===l.TEXT_NODE&&!e.contains(d)&&(u+=d.textContent?.length??0),d=c.nextNode();if(d!==e)return null;const h=u+(e.textContent?.length??0);return h<=u?null:{kind:"selection",start:{kind:"text",blockId:r,offset:u},end:{kind:"text",blockId:r,offset:h}}}function $y(e){if(typeof e!="string")return"";try{return new URL(e,window.location.href).href}catch{return e}}function e0(e){return typeof e?.externalTarget=="string"&&e.externalTarget?e.externalTarget:typeof e?.anchor=="string"&&e.anchor?`#${e.anchor}`:""}function yS(e){const t=e?.anchor?.start,n=e?.anchor?.end;return typeof t?.blockId!="string"||typeof t?.offset!="number"||typeof n?.blockId!="string"||typeof n?.offset!="number"||t.blockId!==n.blockId?null:{kind:"selection",start:{kind:"text",blockId:t.blockId,offset:t.offset},end:{kind:"text",blockId:n.blockId,offset:n.offset}}}function NL(e,t){const n=yS(t);return n?n.start.blockId===e?.start?.blockId&&n.start.offset===e?.start?.offset&&n.end.blockId===e?.end?.blockId&&n.end.offset===e?.end?.offset:!1}function zL(e,t,n){if(typeof t!="string"||!t)return null;const r=e?.query?.match?.({select:{type:"text",pattern:t,caseSensitive:!0},require:"any"}),o=(Array.isArray(r?.items)?r.items:[]).map(s=>s?.target).filter(s=>s?.kind==="selection"&&!!s?.start?.blockId&&!!s?.end?.blockId),i=typeof n=="string"?o.filter(s=>s.start.blockId===n&&s.end.blockId===n):o;return i.length===1?i[0]:typeof n=="string"?null:o.length===1?o[0]:null}function HL(e){return!!(e&&typeof e.closest=="function"&&e.closest(".superdoc-toc-entry"))}function UL({getSurfaceManager:e,getActiveEditor:t,getUi:n,getResolver:r,getLayerElement:o,emitException:i}){let s=null,a=null,l=0;function u(){l+=1}function c(N,I){if(!N||!s||s.handle!==N)return;const L=s;L.unbindPointerDown?.();const X=L.element.ownerDocument?.defaultView?.Node,te=X!=null&&L.pointerDownTarget instanceof X&&L.element.contains(L.pointerDownTarget);I?.status==="closed"&&I.reason===void 0&&te&&(a={href:L.href,element:L.element,closedAt:Date.now()}),s=null}function d(N="closed"){u();const I=s;s=null,a=null,I?.unbindPointerDown?.(),I?.handle?.close?.(N)}function h(N){return{id:TL,mode:"floating",closeOnEscape:!0,floating:{top:N.position.top,left:N.position.left,autoFocus:!0,closeOnOutsidePointerDown:!0,width:"auto"}}}function m(N,I){const L={href:N.href,element:N.element,handle:I,pointerDownTarget:null,unbindPointerDown:null},X=N.element.ownerDocument,te=le=>{L.pointerDownTarget=le.target??null};X.addEventListener("pointerdown",te,!0),L.unbindPointerDown=()=>X.removeEventListener("pointerdown",te,!0),s=L,a=null,I.result?.then?.(le=>c(I,le),()=>c(I))}function p(N,I){return N?.querySelector?.(`a[name='${I}'], [data-bookmark-marker='start'][data-bookmark-name='${I}']`)??null}function g(N,I){if(!N)return null;const L=gS(I);return N.querySelector(`[data-source-node-id='${L}']`)??N.querySelector(`[data-layout-paraid='${L}']`)??N.querySelector(`[data-block-id$='/${L}']`)??N.querySelector(`[data-layout-block-ref$='/${L}']`)??null}function k(N,I=30){return new Promise(L=>{const X=typeof window<"u"?window.requestAnimationFrame:null;let te=0;const le=()=>{const fe=N();if(fe||te>=I||typeof X!="function"){L(fe??null);return}te+=1,X(le)};le()})}async function w(N){const I=t()?.authoring?.setSelectionTarget;if(typeof I!="function")return;const L={kind:"story",storyType:"body"},X={kind:"text",blockId:N,offset:0,story:L},te={kind:"selection",start:X,end:X,story:L};try{await Promise.resolve(I({target:te,collapse:"start",focus:!0}))}catch{}}async function S(N,{placeCaret:I=!1}={}){if(typeof N!="string"||!N.startsWith("#"))return;const L=N.slice(1),X=gS(L),te=p(n()?.viewport?.getHost?.()??null,X);if(te){tf(te);return}const le=t()?.doc;let fe=null;try{fe=await Promise.resolve(le?.bookmarks?.get?.({target:{kind:"entity",entityType:"bookmark",name:L}})),fe??=null}catch{fe=null}const Fe=fe?.address?.story;if(Fe&&Fe.storyType!=="body")return;const he=fe?.range?.from?.blockId;if(typeof he!="string")return;I&&await w(he);const ge=g(n()?.viewport?.getHost?.()??null,he);if(ge){tf(ge);return}const ae=t()?.pageMetrics,Ce=ae?.revealBodyTarget;let oe;try{oe=await Ce?.({paraId:he})}catch{oe=void 0}if(oe?.status==="revealed"){const Ie=g(n()?.viewport?.getHost?.()??null,he);Ie&&tf(Ie);return}if(Ce&&oe?.reason!=="editing-not-mounted")return;const xe=ae?.pageIndexForBodyTarget,qe=ae?.scrollToPage,et=xe?.({paraId:he});if(typeof et!="number"||!qe?.(et))return;const kt=await k(()=>g(n()?.viewport?.getHost?.()??null,he));kt&&tf(kt)}async function y(N){const I=N.editor?.doc;let L;try{L=await Promise.resolve(I?.hyperlinks?.list?.())}catch{return null}const X=Array.isArray(L?.stories)?L.stories:[],te=N.element?.dataset?.linkRid,le=N.element?.textContent??"",fe=$y(N.href),Fe=vS(N.element,I);for(const he of X){const ge=Array.isArray(he?.hyperlinks)?he.hyperlinks:[],ae=async F=>{if(!F?.hyperlinkNodeId||!he?.storyId||F.address)return F;try{const j=await Promise.resolve(I?.hyperlinks?.get?.({storyId:he.storyId,hyperlinkNodeId:F.hyperlinkNodeId}));return j?.success&&j.hyperlink?j.hyperlink:F}catch{return F}},Ce=async F=>{if(!Fe)return null;const j=(await Promise.all(F.map(ae))).filter(V=>NL(Fe,V.address));return j.length===1?j[0]:null},oe=te?ge.filter(F=>F.rId===te):[],xe=oe.filter(F=>F.text===le),qe=ge.filter(F=>$y(e0(F))===fe&&F.text===le),et=ge.filter(F=>F.text===le),kt=ge.filter(F=>{const j=$y(e0(F));return le&&j===fe&&F.text?.includes?.(le)}),Ie=xe.length===1?xe[0]:null,ze=qe.length===1?qe[0]:null,Ve=et.length===1?et[0]:null,Q=kt.length===1?kt[0]:null,_=oe.length===1?oe[0]:null,$=Ie??await Ce(xe)??ze??await Ce(qe)??Ve??await Ce(et)??Q??await Ce(kt)??_??await Ce(oe);if($?.hyperlinkNodeId&&he?.storyId){const F=await ae($),j=yS(F.address);return{storyId:he.storyId,hyperlinkNodeId:F.hyperlinkNodeId,href:e0(F),text:F.text,targetKind:F.targetKind,textTarget:j??zL(I,F.text,Fe?.start?.blockId)}}}return null}function C(N){if(!a)return!1;const I=a.element===N.element&&a.href===N.href,L=Date.now()-a.closedAt<=RL;return!I||!L?!1:(a=null,!0)}function T(N,I){const L=e();if(!L?.open)return;const X=l;queueMicrotask(()=>{X===l&&m(N,L.open(I))})}function R(N){if(d("replace"),N.isAnchorLink&&HL(N.element)){S(N.href,{placeCaret:N.documentMode!=="viewing"});return}if(N.documentMode==="viewing"){if(N.isAnchorLink)S(N.href);else if(N.href){const le=N.target||"_self",fe=OL(N.rel,le);fe?window.open(N.href,le,fe):window.open(N.href,le)}return}const I=()=>d("closed"),L=le=>{I(),S(le,{placeCaret:!0})},X=l,te=le=>{X===l&&T(N,{...h(N),component:Hr(pS),props:{href:le?.href||N.href,target:N.target,rel:N.rel,tooltip:N.tooltip,clickedElement:N.element,hyperlinkTarget:le,hyperlinkText:le?.text,textTarget:le?.textTarget??vS(N.element,N.editor?.doc),documentMode:N.documentMode,ui:n(),closePopover:I,goToAnchor:L}})};y(N).then(te,()=>te(null))}function M(N,I){d("replace");const L=()=>d("closed");T(N,{...h(N),component:Hr(I.component),props:{...I.props,editor:N.editor,href:N.href,closePopover:L}})}function H(N,I){d("replace");const L=I.render;T(N,{...h(N),render:X=>{try{return L({container:X.container,closePopover:()=>X.close("closed"),editor:N.editor,href:N.href})}catch(te){i({error:mS(te),source:"linkPopoverExternalRender"}),X.close("external-error");const le=l;queueMicrotask(()=>{le===l&&R(N)});return}}})}function B(N){const I=o()?.getBoundingClientRect?.(),L=typeof I?.left=="number"?I.left:0,X=typeof I?.top=="number"?I.top:0;return{editor:t(),href:N.href,target:N.target,rel:N.rel,tooltip:N.tooltip,element:N.element,clientX:N.clientX,clientY:N.clientY,isAnchorLink:N.href.startsWith("#"),documentMode:N.documentMode,position:{left:`${Math.max(0,N.clientX-L)}px`,top:`${Math.max(0,N.clientY-X)}px`},closePopover:()=>d("closed")}}function z(N){const I=r();if(typeof I!="function")return{type:"default"};try{const L=I(N);return ML(L)?(i({error:new Error("modules.links.popoverResolver must return synchronously."),source:"linkPopoverResolver"}),{type:"default"}):L==null?{type:"default"}:DL(L)?L:(i({error:new Error("modules.links.popoverResolver returned an invalid resolution."),source:"linkPopoverResolver"}),{type:"default"})}catch(L){return i({error:mS(L),source:"linkPopoverResolver"}),{type:"default"}}}function Z(N){if(!N?.element||typeof N.href!="string")return;if(u(),s&&s.element===N.element&&s.href===N.href){d("toggle");return}if(C(N))return;const I=B(N),L=z(I);if(L.type==="none"){d("none");return}if(L.type==="custom"){M(I,L);return}if(L.type==="external"){H(I,L);return}R(I)}function P(){d("destroyed")}return{handleLinkClick:Z,closeCurrentPopover:d,destroy:P}}var VL=Object.freeze({editorVersion:2,commands:null,state:null,view:null}),jL=["text.insert","text.replace","text.deleteBackward","text.deleteForward","text.paste","history.undo","history.redo","structural.splitBlock","structural.indent","structural.outdent"],bS=["comments.create","comments.resolve","comments.reopen","comments.delete","comments.reply","comments.edit","trackedChanges.accept","trackedChanges.reject","trackedChanges.acceptAll","trackedChanges.rejectAll"],GL=["trackedChanges.setAuthoringMode"];function nf(e){return e.state!=="ready"?e.state:e.documentMode==="viewing"?"review-ready":"editing-ready"}function yp(e){return e==="review-ready"||e==="editing-ready"}function wS(e){switch(e){case"text.insert":return"text.insert";case"text.replace":return"text.replace";case"text.deleteBackward":return"text.deleteBackward";case"text.deleteForward":return"text.deleteForward";case"text.paste":return"text.pastePlain";case"history.undo":return"history.undo";case"history.redo":return"history.redo";case"structural.splitBlock":return"structural.enter";case"structural.indent":return"structural.listIndent";case"structural.outdent":return"structural.listOutdent";default:return null}}function CS(e){switch(e){case"comments.create":return"comments.createFromSelection";case"comments.resolve":return"review.commentResolve";case"comments.reopen":return"review.commentReopen";case"comments.delete":return"review.commentDelete";case"comments.reply":return"review.commentReply";case"comments.edit":return"review.commentEdit";case"trackedChanges.accept":case"trackedChanges.reject":return"review.trackedChangeDecide";case"trackedChanges.acceptAll":return"trackedChanges.acceptAll";case"trackedChanges.rejectAll":return"trackedChanges.rejectAll";default:return null}}function _S(e,t){return e.editableSubset.commands.find(n=>n.command===t)??null}function WL(e){return e?.status==="supported"||e?.enabled===!0}function KL(e){return e?.rejectionCode??e?.reason??null}function qL(e){return e?.detail??void 0}function bp(e,t){return WL(_S(e,t))}function SS(e,t){const n=_S(e,t),r=KL(n);return r?{reason:AS(r),detail:qL(n)}:e.documentMode==="viewing"?{reason:"document-readonly",detail:"review-surface-read-only"}:{reason:"command-unsupported",detail:`unsupported:${t}`}}function kS(e,t){const n=t?.reason;return e==="history.undo"?n==="NO_EFFECT"||n==="apply-rejected"?"no-effect":"nothing-to-undo":n==="NO_EFFECT"||n==="apply-rejected"?"no-effect":"nothing-to-redo"}function AS(e){switch(e){case"host-saving":return"host-saving";case"document-readonly":return"document-readonly";case"selection-invalidated":case"review-target-invalidated":return"selection-invalidated";case"review-command-unavailable":return"review-command-unavailable";case"review-surface-read-only":return"document-readonly";case"editing-selection-required":return"selection-unsupported";case"format-target-unsupported":case"selection-target-unsupported":case"input-target-unsupported":case"composition-target-unsupported":case"enter-context-unsupported":case"boundary-merge-unsupported":case"tracked-structural-edit-unsupported":case"comment-anchor-create-unsupported":case"comment-anchor-move-unsupported":return"target-unsupported";case"unsupported-command":return"command-unsupported";case"editing-mount-required":case"host-not-ready":case"host-disposed":return"runtime-not-ready";default:return"command-failed"}}function YL(e){const{id:t,documentId:n,root:r,host:o,getLegacyEditorProjection:i,onUnregister:s}=e;let a=o.getSnapshot(),l=!1,u=!1,c=null,d=0,h=0,m=null,p=null,g=null,k=null;const w=new Map,S=new Set;function y(ae){for(const Ce of Array.from(S))try{Ce(ae)}catch{}}function C(){d+=1,w.clear()}function T(ae){const Ce=`v2-runtime-pos-${h++}`;return w.set(Ce,ae),{runtimeId:t,tokenId:Ce,revision:d}}function R(ae){return ae.runtimeId!==t?{ok:!1,reason:"wrong-runtime-token"}:ae.revision!==d||!w.has(ae.tokenId)?{ok:!1,reason:"stale-position-token"}:{ok:!0}}function M(){return o.getHandles().editing?.selection??null}function H(){const ae=M()?.getSnapshot()??null;return ae?{isRange:ae.anchor!==ae.focus,isEmpty:ae.anchor===ae.focus,text:"",anchor:T(ae.anchor),focus:T(ae.focus)}:null}function B(){const ae=M();ae!==k&&(m?.(),m=null,k=ae,ae&&(m=ae.subscribe(Ce=>{C(),y({type:"selection-change",selection:Ce?{isRange:Ce.anchor!==Ce.focus,isEmpty:Ce.anchor===Ce.focus,text:"",anchor:T(Ce.anchor),focus:T(Ce.focus)}:{isRange:!1,isEmpty:!0,text:""}})})))}function z(){const ae=o.getDocumentFacade?.()??null;return ae?.available===!0?ae.doc:null}function Z(){const ae=z();return!!(ae?.comments&&ae.trackChanges)}function P(ae){if(!yp(nf(ae)))return[];const Ce=jL.filter(xe=>{const qe=wS(xe);return qe!==null&&bp(ae,qe)}),oe=Z()?bS.filter(xe=>{const qe=CS(xe);return qe!==null&&bp(ae,qe)}):[];return[...Ce,...oe,...GL]}function N(ae=a){const Ce=nf(ae),oe=Ce!=="disposed",xe=P(ae);return{lifecycle:{canFocus:oe,canDispose:!0},selection:{canReadSelectedText:!0,canReadSelectionSnapshot:!0,canMintPositionTokens:!0},commands:{canDispatch:yp(Ce)&&xe.length>0,supportedCommands:xe},layout:{supported:!0,hasSyncSnapshot:!0},zoom:{supported:!0,min:25,max:400},navigation:{supported:!1,targets:[]},persistence:{canSave:!0,canExportDocx:!0},comments:{supported:!0,canMutate:ae.commentCommandsReason!=="author-required"&&["comments.create","comments.resolve","comments.reopen","comments.delete","comments.reply","comments.edit"].some(qe=>xe.includes(qe))},trackedChanges:{supported:!0,canDecide:xe.includes("trackedChanges.accept")||xe.includes("trackedChanges.reject"),canToggleAuthoring:yp(Ce)}}}function I(){const ae=o.getPageMetricsSnapshot();return{pageCount:ae.pages.length,currentPage:1,zoom:ae.zoom.percent}}function L(ae=a){return{id:t,kind:"v2",documentId:n,state:nf(ae),documentMode:ae.documentMode,reason:ae.reason,capabilities:N(ae)}}function X(ae){return ae?.success===!0?(C(),{status:"committed",receipt:ae}):ae&&"failure"in ae?{status:"receipt-failure",failure:ae.failure}:{status:"rejected",reason:"command-failed"}}function te(ae,Ce){return Ce?Ce.noop===!0?{status:"history-noop",reason:kS(ae,Ce),result:Ce}:(C(),{status:"history-committed",result:Ce}):{status:"rejected",reason:"command-failed"}}async function le(ae){const Ce=CS(ae.kind);if(Ce&&!bp(a,Ce)){const qe=SS(a,Ce);return{status:"rejected",reason:qe.reason,detail:qe.detail}}const oe=wS(ae.kind);if((ae.kind==="history.undo"||ae.kind==="history.redo")&&oe&&!bp(a,oe)){const qe=SS(a,oe);return{status:"rejected",reason:qe.reason,detail:qe.detail}}const xe=z();if(!xe)return bS.includes(ae.kind)?{status:"rejected",reason:"review-command-unavailable"}:null;try{switch(ae.kind){case"comments.create":{const qe=await xe.selection?.current?.(),et=qe?.empty===!1?qe.target:void 0;return X(await xe.comments?.create?.({text:ae.text,...et?{target:et}:{}}))}case"comments.resolve":return X(await xe.comments?.patch?.({commentId:ae.commentId,status:"resolved"}));case"comments.reopen":return X(await xe.comments?.patch?.({commentId:ae.commentId,status:"active"}));case"comments.delete":return X(await xe.comments?.delete?.({commentId:ae.commentId}));case"comments.reply":return X(await xe.comments?.create?.({parentCommentId:ae.parentCommentId,text:ae.text}));case"comments.edit":return X(await xe.comments?.patch?.({commentId:ae.commentId,text:ae.text}));case"trackedChanges.accept":return X(await xe.trackChanges?.decide?.({decision:"accept",target:{kind:"id",id:ae.id}}));case"trackedChanges.reject":return X(await xe.trackChanges?.decide?.({decision:"reject",target:{kind:"id",id:ae.id}}));case"trackedChanges.acceptAll":return X(await xe.trackChanges?.decide?.({decision:"accept",target:{kind:"all"}}));case"trackedChanges.rejectAll":return X(await xe.trackChanges?.decide?.({decision:"reject",target:{kind:"all"}}));case"history.undo":return te("history.undo",await xe.history?.undo?.());case"history.redo":return te("history.redo",await xe.history?.redo?.());default:return null}}catch(qe){return{status:"rejected",reason:"command-failed",detail:qe instanceof Error?qe.message:String(qe)}}}function fe(ae){a=ae,C(),B(),y({type:"state-change",state:nf(ae)}),y({type:"capabilities-change",capabilities:N(ae)}),ae.state==="disposed"&&!l&&(l=!0,p?.(),g?.(),m?.(),m=null,y({type:"disposed"}),S.clear(),u||(u=!0,s?.(t)))}p=o.subscribe(fe),g=o.subscribePageMetrics?.(()=>{y({type:"layout-change",layout:I()})})??null,B();async function Fe(ae){const Ce=nf(a);if(Ce==="disposed")return{status:"rejected",reason:"runtime-not-ready"};if(Ce==="saving")return{status:"rejected",reason:"host-saving"};if(!yp(Ce))return{status:"rejected",reason:"runtime-not-ready"};const oe="at"in ae?ae.at:"range"in ae?ae.range:void 0;if(oe){const kt=R(oe);return kt.ok?{status:"rejected",reason:"target-unsupported",detail:"positioned dispatch is deferred until the shared runtime can target host selections explicitly"}:{status:"rejected",reason:kt.reason}}if(ae.kind==="trackedChanges.setAuthoringMode")return o.setDocumentMode(ae.mode==="tracked"?"suggesting":"editing"),C(),{status:"committed"};const xe=await le(ae);if(xe)return xe;let qe=null;switch(ae.kind){case"text.insert":qe={kind:"text.insert",text:ae.text};break;case"text.replace":qe={kind:"text.replace",text:ae.text};break;case"text.deleteBackward":qe={kind:"text.deleteBackward"};break;case"text.deleteForward":qe={kind:"text.deleteForward"};break;case"text.paste":qe={kind:"text.pastePlain",text:ae.text};break;case"history.undo":qe={kind:"history.undo"};break;case"history.redo":qe={kind:"history.redo"};break;case"structural.splitBlock":qe={kind:"structural.enter"};break;case"structural.indent":qe={kind:"structural.listIndent"};break;case"structural.outdent":qe={kind:"structural.listOutdent"};break;default:return{status:"rejected",reason:"command-unsupported",detail:ae.kind}}const et=await o.dispatch(qe);switch(et.status){case"committed":return C(),{status:"committed",receipt:et.receipt};case"history-committed":return C(),{status:"history-committed",result:et.result};case"history-noop":return{status:"history-noop",reason:kS(ae.kind,et.result),result:et.result};case"receipt-failure":return{status:"receipt-failure",failure:et.failure};case"rejected":return{status:"rejected",reason:AS(et.rejection.code),detail:et.rejection.detail}}}async function he(ae){if(l||a.state==="disposed")return!1;const Ce=c?.focus;return Ce&&typeof Ce.focus=="function"?await Ce.focus({restoreSelection:ae?.restoreSelection,preventScroll:ae?.preventScroll})!==!1:typeof r.focus=="function"?(r.focus({preventScroll:ae?.preventScroll}),!0):!1}async function ge(){l||(await o.dispose(),l||(l=!0,p?.(),g?.(),m?.(),m=null,y({type:"disposed"}),S.clear(),u||(u=!0,s?.(t))))}return{runtime:{id:t,kind:"v2",documentId:n,root:r,getCapabilities:()=>N(),getSnapshot:()=>L(),setDocumentMode(ae){o.setDocumentMode(ae)},getDocumentMode:()=>o.getDocumentMode(),getLegacyEditorProjection:()=>i?.()??VL,focus:he,dispose:ge,dispatch:Fe,getSelectedText:()=>"",getSelectionSnapshot:H,getToolbarState(){return{activeMarks:[],disabled:["formatting.applyMark","formatting.applyParagraph"]}},getLayoutSnapshot:I,save:()=>o.save(),exportDocx:ae=>o.save({format:"docx",commentExportMode:ae?.commentsType==="clean"?"strip":"preserve"}),async setZoom(ae){const Ce=o.setZoom(ae);return Ce.status==="ok"?{status:"committed"}:{status:"rejected",reason:Ce.reason==="host-disposed"?"runtime-not-ready":"target-unsupported",detail:Ce.reason}},async reveal(ae){if(ae.kind==="position"){const Ce=R(ae.position);if(!Ce.ok)return{status:"rejected",reason:Ce.reason}}return{status:"rejected",reason:"capability-unsupported",detail:`${ae.kind} reveal is not exposed through the shared runtime yet`}},subscribe(ae){return S.add(ae),()=>{S.delete(ae)}}},attachMountHandle(ae){c=ae,B()}}}var IS=".superdoc-toolbar";function XL(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.items)?e.items:[]}function QL(e){if(e&&typeof e=="object"){const t=e;return t.target??t.address??t.handle??e}return e}function wp(e){return typeof e=="function"}function ES(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}function Cp(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function ZL(e){return Cp(e)&&e.kind==="text"&&Array.isArray(e.segments)&&e.segments.length>0}function JL(e){return Cp(e)&&e.kind==="story"&&(e.storyType==="headerFooterSlot"||e.storyType==="headerFooterPart")}function $L(e){if(!wp(e.selection?.current))return{handled:!1,reason:"page-field-selection-unavailable"};let t;try{t=e.selection.current({includeText:!1})}catch{return{handled:!1,reason:"page-field-selection-unavailable"}}return ES(t)?{handled:!1,reason:"page-field-selection-async"}:!Cp(t)||!ZL(t.target)?{handled:!1,reason:"page-field-selection-unavailable"}:JL(t.target.story)?{handled:!0,target:t.target}:{handled:!1,reason:"page-field-context-unavailable"}}function t0(e,t){return!wp(e)||!wp(t)?!1:(Promise.resolve().then(()=>e()).then(n=>{for(const r of XL(n))try{Promise.resolve(t({target:QL(r)})).catch(()=>{})}catch{}}).catch(()=>{}),!0)}function eD(e){return{focusToolbar:()=>{const o=e.resolveToolbarElement();if(!o)return{handled:!1,reason:"no-toolbar"};const i=typeof o.matches=="function"&&o.matches(IS)?o:o.querySelector?.(IS)??o;return i?(i.hasAttribute("tabindex")||i.setAttribute("tabindex","0"),typeof i.focus!="function"?{handled:!1,reason:"no-toolbar"}:(i.focus(),!0)):{handled:!1,reason:"no-toolbar"}},updateFields:()=>{const o=e.getDocumentApi();if(!o)return{handled:!1,reason:"document-api-unavailable"};let i=t0(o.toc?.list,o.toc?.update);return i=t0(o.fields?.list,o.fields?.rebuild)||i,i=t0(o.index?.list,o.index?.rebuild)||i,i?!0:{handled:!1,reason:"field-update-workflow-unavailable"}},insertPageField:o=>{const i=e.getDocumentApi();if(!i)return{handled:!1,reason:"document-api-unavailable"};if(!wp(i.fields?.insert))return{handled:!1,reason:"page-field-insert-unavailable"};const s=$L(i);if(!s.handled||!s.target)return{handled:!1,reason:s.reason??"page-field-context-unavailable"};const a=o==="page"?"PAGE":"NUMPAGES";try{const l=i.fields.insert({at:s.target,instruction:a,mode:"raw"});if(ES(l))l.catch(()=>{});else if(Cp(l)&&l.success===!1)return{handled:!1,reason:"page-field-insert-failed"}}catch{return{handled:!1,reason:"page-field-insert-failed"}}return!0}}}const _p="data-superdoc-runtime-id";function tD(e,t){e.setAttribute(_p,t)}function xS(e){e.removeAttribute(_p)}function TS(e){if(typeof e!="string"||e.length===0)return"<none>";try{const t=new URL(e);t.search="",t.hash="",t.username="",t.password="";const n=e.includes("?")?"?<redacted>":"";return`${t.toString().replace(/\?$/,"")}${n}`}catch{const t=e.replace(/\/\/[^/@]+@/,"//"),n=t.search(/[?#]/);return n===-1?t:`${t.slice(0,n)}?<redacted>`}}function Sp(e){return typeof e=="string"&&e.length>0?e:null}function nD(e){if(typeof e!="string"||e.length===0)return null;try{const t=new URL(e);return t.protocol==="ws:"||t.protocol==="wss:"?e:null}catch{return null}}function rD(e,t){if(typeof e!="string")return null;const n=e.trim();if(n.length===0)return null;try{const r=new URL(n);return r.protocol==="http:"||r.protocol==="https:"?n:null}catch{if(typeof t!="string"||t.trim().length===0)return null;try{const r=new URL(n,t);return r.protocol==="http:"||r.protocol==="https:"?r.href:null}catch{return null}}}function oD(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function RS(e){return e===void 0?"join":e==="join"||e==="create"?e:null}function MS(){return{ok:!1,reason:"invalid-room-mode",message:'SuperDoc v2 collaboration roomMode must be either "join" or "create".'}}function iD(e){const t=e.providerType;return typeof t=="string"&&t.length>0?t.toLowerCase():null}function sD(e){if(!e||typeof e!="object")return null;const t=typeof e.providerType=="string"?e.providerType.toLowerCase():"";return t==="hocuspocus"?"hocuspocus":t==="liveblocks"?"liveblocks":t==="superdoc"?"superdoc":e.ydoc!=null||e.provider!=null?"external-ydoc-provider":null}function LS(e,t){const n=Sp(t.documentId);if(!n)return{ok:!1,reason:"invalid-document-id",message:`SuperDoc v2 collaboration requires a non-empty v2Collaboration.documentId for the "${e}" provider.`};const r=t.url??t.serverUrl,o=nD(r);if(!o)return{ok:!1,reason:"invalid-server-url",message:`SuperDoc v2 collaboration requires a valid ws:// or wss:// URL for the "${e}" provider (received: ${TS(r)}).`};const i=oD(t.params),s=e==="hocuspocus"?Sp(t.token):null,a=RS(t.roomMode);return a?{ok:!0,target:{providerFamily:e,documentId:n,roomMode:a,serverUrl:o,...i?{params:i}:{},...s?{token:s}:{}}}:MS()}function aD(e,t){const n=Sp(e.documentId??e.roomId);if(!n)return{ok:!1,reason:"invalid-document-id",message:'SuperDoc v2 collaboration requires a non-empty v2Collaboration.documentId (or roomId) for the "liveblocks" provider.'};const r=Sp(e.publicApiKey),o=RS(e.roomMode);if(!o)return MS();const i=e.authEndpoint,s=typeof i=="string"&&i.length>0;if(!r&&!s)return{ok:!1,reason:"missing-auth",message:"SuperDoc v2 Liveblocks collaboration requires exactly one auth mode: a publicApiKey or an authEndpoint. None was provided."};if(r&&s)return{ok:!1,reason:"mixed-auth",message:"SuperDoc v2 Liveblocks collaboration accepts exactly one auth mode; pass either publicApiKey or authEndpoint, not both."};if(r)return{ok:!0,target:{providerFamily:"liveblocks",documentId:n,roomMode:o,publicApiKey:r}};const a=rD(i,t);return a?{ok:!0,target:{providerFamily:"liveblocks",documentId:n,roomMode:o,authEndpoint:a}}:{ok:!1,reason:"invalid-auth-endpoint",message:"SuperDoc v2 Liveblocks collaboration requires a valid http(s) authEndpoint URL (received: <redacted>)."}}function DS(e){const{v2Collaboration:t,legacyCollaboration:n,documentType:r,documentCount:o,authEndpointBaseUrl:i}=e;if(typeof o=="number"&&o>1)return{ok:!1,reason:"unsupported-multi-document",message:`SuperDoc v2 collaboration supports exactly one document per room; received ${o}.`};if(r!=null&&r!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")return{ok:!1,reason:"unsupported-document-type",message:"SuperDoc v2 collaboration supports DOCX documents only."};if(!(t!=null&&typeof t=="object")){const l=sD(n);if(l){const u=l==="external-ydoc-provider"?"unsupported-legacy-provider":"unsupported-provider-family",c=TS(n?.url);return{ok:!1,reason:u,message:l==="external-ydoc-provider"?"SuperDoc v2 collaboration cannot use an external { ydoc, provider } pair. Provide a v2Collaboration target (e.g. { providerType, documentId, url }) instead.":`SuperDoc v2 collaboration does not accept "${l}" through the legacy modules.collaboration block (server: ${c}). Configure it as a v2Collaboration target ({ providerType: "${l}", documentId, ... }) instead.`}}return{ok:!1,reason:"missing-target",message:"SuperDoc v2 collaboration requires a v2Collaboration target ({ documentId, serverUrl } or { providerType, ... }). None was provided."}}const s=t;if(Object.prototype.hasOwnProperty.call(s,"createIfMissing"))return{ok:!1,reason:"invalid-room-mode",message:'SuperDoc v2 collaboration createIfMissing has been removed. Use roomMode: "create" for creation or roomMode: "join" for normal opens.'};if(s.ydoc!=null||s.provider!=null)return{ok:!1,reason:"unsupported-legacy-provider",message:"SuperDoc v2 collaboration cannot use an external { ydoc, provider } pair. v2 owns its provider; pass a v2Collaboration target ({ providerType, documentId, url | publicApiKey | authEndpoint }) instead."};const a=iD(s);return a===null||a==="y-websocket"?LS("y-websocket",s):a==="hocuspocus"?LS("hocuspocus",s):a==="liveblocks"?aD(s,i):{ok:!1,reason:"unsupported-provider-family",message:`SuperDoc v2 collaboration does not support the "${a}" provider family. Supported families are y-websocket, hocuspocus, and liveblocks.`}}It(),gn();var lD={__name:"SurfaceExternalMount",props:{surfaceId:{type:String,required:!0},mode:{type:String,required:!0},request:{type:Object,required:!0},render:{type:Function,required:!0},resolve:{type:Function,required:!0},close:{type:Function,required:!0}},setup(e){const t=e,n=ne(null);let r=null;function o(){i(),!(!n.value||!t.render)&&(r=t.render({container:n.value,surfaceId:t.surfaceId,mode:t.mode,request:t.request,resolve:t.resolve,close:t.close})?.destroy??null)}function i(){typeof r=="function"&&r(),r=null,n.value&&(n.value.innerHTML="")}return Rn(o),ir(i),Pt(()=>t.surfaceId,()=>{o()}),(s,a)=>(me(),_e("div",{ref_key:"container",ref:n,class:"sd-surface-external-mount"},null,512))}},PS=hn(lD,[["__scopeId","data-v-b2412c5d"]]);const n0=["a[href]","button:not([disabled])","textarea:not([disabled])","input:not([disabled])","select:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");It(),gn();var cD=["aria-labelledby","aria-label"],uD=["id"],dD={class:"sd-surface-dialog__content"},fD={__name:"SurfaceDialog",props:{surface:{type:Object,required:!0},scrollLockTarget:{type:Object,default:null}},emits:["close"],setup(e,{emit:t}){const n=e,r=t,o=ne(null),i=Se(()=>n.surface.request.title?`sd-surface-title-${n.surface.id}`:void 0),s=Se(()=>i.value??n.surface.request.ariaLabelledBy??void 0),a=Se(()=>s.value?void 0:n.surface.request.ariaLabel);let l=null;function u(T){if(!o.value)return;const R=o.value.querySelectorAll(n0);if(R.length===0)return;const M=R[0],H=R[R.length-1];T.shiftKey&&document.activeElement===M?(T.preventDefault(),H.focus()):!T.shiftKey&&document.activeElement===H&&(T.preventDefault(),M.focus())}function c(){if(!o.value)return;const T=o.value.querySelector(n0);T?T.focus():o.value.focus()}let d=null,h="";function m(){if(n.scrollLockTarget)d=n.scrollLockTarget;else{const T=o.value?.closest(".superdoc");d=T?.querySelector(".superdoc__layers")??T}d&&(h=d.style.overflow,d.style.overflow="hidden")}function p(){d&&(d.style.overflow=h,d=null,h="")}function g(T){if(T.key==="Tab"){u(T);return}T.key==="Escape"&&n.surface.request.closeOnEscape!==!1&&(T.stopPropagation(),r("close"))}function k(T){T.target===T.currentTarget&&n.surface.request.closeOnBackdrop!==!1&&r("close")}const w=Se(()=>({surfaceId:n.surface.id,mode:"dialog",request:n.surface.request,resolve:n.surface.resolve,close:n.surface.close})),S=Se(()=>({...n.surface.props??{},...w.value})),y=Se(()=>{const T=n.surface.request.dialog?.maxWidth;if(T!=null)return typeof T=="number"?`${T}px`:T}),C=Se(()=>{const T={};return y.value&&(T["max-width"]=y.value),T});return Rn(async()=>{l=document.activeElement,m(),await _t(),c()}),Pt(()=>n.scrollLockTarget,(T,R)=>{T!==R&&(p(),m())}),ir(()=>{p(),l&&typeof l.focus=="function"&&l.focus(),l=null}),(T,R)=>(me(),_e("div",{class:"sd-surface-dialog-backdrop",onMousedown:Jt(k,["self"]),onKeydown:g},[Le("div",{ref_key:"dialogRef",ref:o,class:"sd-surface-dialog",style:vn(C.value),role:"dialog","aria-modal":"true","aria-labelledby":s.value,"aria-label":a.value,tabindex:"-1"},[e.surface.request.title?(me(),_e("div",{key:0,id:i.value,class:"sd-surface-dialog__title"},Ht(e.surface.request.title),9,uD)):ut("",!0),Le("div",dD,[e.surface.render?(me(),fn(PS,{key:0,"surface-id":e.surface.id,mode:"dialog",request:e.surface.request,render:e.surface.render,resolve:e.surface.resolve,close:e.surface.close},null,8,["surface-id","request","render","resolve","close"])):e.surface.component?(me(),fn(yg(e.surface.component),Om(cs({key:1},S.value)),null,16)):ut("",!0)])],12,cD)],32))}},hD=hn(fD,[["__scopeId","data-v-20bf8e4b"]]);It(),gn();var pD=["aria-labelledby","aria-label"],mD=["id"],gD={class:"sd-surface-floating__content"},vD={__name:"SurfaceFloating",props:{surface:{type:Object,required:!0}},setup(e,{expose:t}){const n=e,r=ne(null);t({rootEl:r});const o=ne({}),i=Se(()=>n.surface.request.title?`sd-surface-title-${n.surface.id}`:void 0),s=Se(()=>i.value??n.surface.request.ariaLabelledBy??void 0),a=Se(()=>s.value?void 0:n.surface.request.ariaLabel),l=Se(()=>n.surface.request.floating??{}),u=Se(()=>{const y=l.value;return y.top!=null||y.right!=null||y.bottom!=null||y.left!=null}),c=Se(()=>{const y=["sd-surface-floating"];if(!u.value){const C=l.value.placement??"top-right";y.push(`sd-surface-floating--${C}`)}return y});function d(y){if(y!=null)return typeof y=="number"?`${y}px`:y}const h=Se(()=>{const y=l.value,C={};return y.top!=null&&(C.top=d(y.top)),y.right!=null&&(C.right=d(y.right)),y.bottom!=null&&(C.bottom=d(y.bottom)),y.left!=null&&(C.left=d(y.left)),y.width!=null&&(C.width=d(y.width)),y.maxWidth!=null&&(C["max-width"]=d(y.maxWidth)),y.maxHeight!=null&&(C["max-height"]=d(y.maxHeight)),{...C,...o.value}});async function m(){if(o.value={},!u.value)return;await _t(),await new Promise(z=>requestAnimationFrame(z));const y=r.value,C=y?.parentElement;if(!y||!C)return;const T=8,R=y.getBoundingClientRect(),M=C.getBoundingClientRect(),H={},B=l.value;if(B.left!=null&&B.right==null){const z=R.left-M.left,Z=Math.max(T,M.width-R.width-T),P=Math.min(Math.max(z,T),Z);P!==z&&(H.left=`${P}px`)}if(B.top!=null&&B.bottom==null){const z=R.top-M.top,Z=Math.max(T,M.height-R.height-T),P=Math.min(Math.max(z,T),Z);P!==z&&(H.top=`${P}px`)}o.value=H}Pt(l,m,{deep:!0});const p=Se(()=>({surfaceId:n.surface.id,mode:"floating",request:n.surface.request,resolve:n.surface.resolve,close:n.surface.close})),g=Se(()=>({...n.surface.props??{},...p.value}));let k=null,w=!1,S=null;return Rn(async()=>{if(m(),window.addEventListener("resize",m),typeof ResizeObserver<"u"&&r.value?.parentElement&&(S=new ResizeObserver(m),S.observe(r.value.parentElement),S.observe(r.value)),l.value.autoFocus===!1||(await _t(),!r.value))return;const y=r.value.querySelector("[data-sd-autofocus]")??r.value.querySelector(n0);y&&(k=document.activeElement,y.focus(),w=!0)}),ir(()=>{window.removeEventListener("resize",m),S?.disconnect(),S=null,w&&k&&typeof k.focus=="function"&&k.focus(),k=null,w=!1}),(y,C)=>(me(),_e("div",{ref_key:"floatingRef",ref:r,class:en(c.value),style:vn(h.value),role:"dialog","aria-labelledby":s.value,"aria-label":a.value,"data-editor-ui-surface":""},[e.surface.request.title?(me(),_e("div",{key:0,id:i.value,class:"sd-surface-floating__title"},Ht(e.surface.request.title),9,mD)):ut("",!0),Le("div",gD,[e.surface.render?(me(),fn(PS,{key:0,"surface-id":e.surface.id,mode:"floating",request:e.surface.request,render:e.surface.render,resolve:e.surface.resolve,close:e.surface.close},null,8,["surface-id","request","render","resolve","close"])):e.surface.component?(me(),fn(yg(e.surface.component),Om(cs({key:1},g.value)),null,16)):ut("",!0)])],14,pD))}},yD=hn(vD,[["__scopeId","data-v-cd2be5db"]]);It(),gn();var bD={__name:"SurfaceHost",props:{geometryTarget:{type:Object,default:null}},setup(e){const t=e,n=La("surfaceManager",null),r=Se(()=>n?.activeDialog.value??null),o=Se(()=>n?.activeFloating.value??null),i=Se(()=>r.value!=null||o.value!=null),s=ne(null),a=ne(null),l=ne({}),u=new Set(["hidden","scroll","auto","clip"]);function c(N){const I=[];let L=N.parentElement;for(;L;){const X=getComputedStyle(L);(u.has(X.overflowX)||u.has(X.overflowY))&&I.push(L),L=L.parentElement}return I}function d(N,I){let L=0,X=0,te=window.innerWidth,le=window.innerHeight;for(const Fe of I){const he=Fe.getBoundingClientRect(),ge=getComputedStyle(Fe);u.has(ge.overflowX)&&(X=Math.max(X,he.left),te=Math.min(te,he.right)),u.has(ge.overflowY)&&(L=Math.max(L,he.top),le=Math.min(le,he.bottom))}const fe=N.getBoundingClientRect();return L=Math.max(L,fe.top),X=Math.max(X,fe.left),te=Math.min(te,fe.right),le=Math.min(le,fe.bottom),{top:L,left:X,width:Math.max(te-X,0),height:Math.max(le-L,0)}}let h=null,m=[],p=0,g=null;function k(){if(!h)return;const{top:N,left:I,width:L,height:X}=d(h,m);l.value={position:"fixed",top:`${N}px`,left:`${I}px`,width:`${L}px`,height:`${X}px`}}function w(){p||(p=requestAnimationFrame(()=>{p=0,k()}))}function S(){if(h=t.geometryTarget??null,!!h){m=c(h),k(),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),g=new ResizeObserver(w),g.observe(h);for(const N of m)g.observe(N)}}function y(){p&&(cancelAnimationFrame(p),p=0),window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w),g&&(g.disconnect(),g=null),h=null,m=[]}Pt(i,N=>{N?S():y()}),Pt(()=>t.geometryTarget,N=>{N&&i.value&&!h&&S()}),Rn(()=>{i.value&&S()});function C(N){const I=o.value;!I||I.settled||r.value||N.key==="Escape"&&I.request.closeOnEscape!==!1&&(N.stopPropagation(),n.close(I.id))}let T=!1;function R(){T||(document.addEventListener("keydown",C,!0),T=!0)}function M(){T&&(document.removeEventListener("keydown",C,!0),T=!1)}function H(N){const I=o.value;if(!I||I.settled||r.value)return;const L=a.value?.rootEl;L&&!L.contains(N.target)&&n.close(I.id)}let B=!1;function z(){B||(document.addEventListener("pointerdown",H,!0),B=!0)}function Z(){B&&(document.removeEventListener("pointerdown",H,!0),B=!1)}Pt(o,N=>{N&&!N.settled?(R(),N.request.floating?.closeOnOutsidePointerDown?z():Z()):(M(),Z())},{immediate:!0}),ir(()=>{y(),M(),Z()});function P(){const N=r.value;N&&!N.settled&&n.close(N.id)}return(N,I)=>(me(),fn(Oa,{to:"body"},[i.value?(me(),_e("div",{key:0,ref_key:"hostRef",ref:s,class:"sd-surface-host",style:vn(l.value)},[o.value?(me(),fn(yD,{key:o.value.id,surface:o.value,ref_key:"floatingRef",ref:a},null,8,["surface"])):ut("",!0),r.value?(me(),fn(hD,{key:r.value.id,surface:r.value,"scroll-lock-target":Ge(h),onClose:P},null,8,["surface","scroll-lock-target"])):ut("",!0)],4)):ut("",!0)]))}},wD=hn(bD,[["__scopeId","data-v-c6a3b75f"]]),r0,CD=br((()=>{r0=(e,t)=>{const n=10**(t||0);return Math.floor(e*n)/n}})),OS,_D=br((()=>{OS=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>t(o.target.result),r.onerror=n,r.readAsDataURL(e)})})),FS,SD=br((()=>{FS=(e,t)=>{const n=t-e;return Array.from({length:n},(r,o)=>e+o)}}));function kD(e){return`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${e}/pdf.worker.min.mjs`}var BS,NS,zS,HS,AD=br((()=>{SD(),BS=e=>({adapter:"pdfjs",...e}),NS=class VA{constructor(){if(Object.getPrototypeOf(this).constructor===VA)throw new Error("Abstract class should not be instantiated")}},zS=class extends NS{constructor(e){super(),this.pdfLib=e.pdfLib,this.workerSrc=e.workerSrc,e.setWorker&&(this.workerSrc?this.pdfLib.GlobalWorkerOptions.workerSrc=e.workerSrc:this.pdfLib.GlobalWorkerOptions.workerSrc=kD(this.pdfLib.version))}async getDocument(e){return await this.pdfLib.getDocument(e).promise}async getPages(e,t,n){const r=FS(t,n+1).map(o=>e.getPage(o));return await Promise.all(r)}},HS=class{static create(e){const t={pdfjs:()=>new zS(e),default:()=>{throw new Error("Unsupported adapter")}};return(t[e.adapter]??t.default)()}}})),ID=br((()=>{})),ED=br((()=>{})),US,VS,jS,GS,xD=br((()=>{It(),qy(),ID(),ED(),gn(),US=["data-page-id","data-page-number"],VS={class:"sd-pdf-viewer-page__canvas-wrapper"},jS={__name:"PdfViewerPage",props:{config:{type:Object,required:!0},page:{type:Object,required:!0},pages:{type:Array,required:!0},scale:{type:Number,required:!0},hasTextLayer:{type:Boolean,default:!1},outputScale:{type:Number,default:2},documentEl:{type:[Object],default:null}},emits:["page-rendered","page-error","text-layer-rendered","text-layer-error","selection-raw","bypass-selection"],setup(e,{emit:t}){const n=t,r=e,o=Ur(null),i=ne(null),s=ne(null),a=ne(null);let l;const u=Se(()=>r.pages.findIndex(z=>z.pageId===r.page.pageId)),c=Se(()=>u.value===-1?0:u.value+1);function d(z){const Z=window.getSelection();if(!Z||Z.rangeCount===0)return null;const P=Z.getRangeAt(0).getClientRects();if(!P.length)return null;const N=z.getBoundingClientRect(),I=r.scale??1,L=P[0];let X={top:L.top,left:L.left,bottom:L.bottom,right:L.right};for(let te=1;te<P.length;te+=1){const le=P[te];le.width===0||le.height===0||(X.top=Math.min(X.top,le.top),X.left=Math.min(X.left,le.left),X.bottom=Math.max(X.bottom,le.bottom),X.right=Math.max(X.right,le.right))}return{top:(X.top-N.top)/I+z.scrollTop,left:(X.left-N.left)/I+z.scrollLeft,bottom:(X.bottom-N.top)/I+z.scrollTop,right:(X.right-N.left)/I+z.scrollLeft}}const h=Se(()=>{let{width:z,height:Z}=o.value;return[z,Z]=[z,Z].map(P=>Math.ceil(P)),{width:z,height:Z}}),m=Se(()=>{const{width:z,height:Z}=h.value;return{width:z,height:Z}}),p=Se(()=>{const{width:z,height:Z}=w();return{"--scale-factor":`${y()}`,width:`calc(var(--scale-factor) * ${z}px)`,height:`calc(var(--scale-factor) * ${Z}px)`}});function g(){const z=window.getSelection();if(!z||z.toString().length===0)return;const Z=d(r.documentEl?.value??r.documentEl??i.value);Z&&n("selection-raw",{selectionBounds:Z,documentId:r.page.documentId,page:c.value,source:"pdf"})}function k(z){z?.target&&z.target.tagName!=="SPAN"&&n("bypass-selection",z)}function w(){const z=qa*r.outputScale;let{width:Z,height:P}=o.value;return Z=Z/z,P=P/z,[Z,P]=[Z,P].map(N=>Math.ceil(N)),{width:Z,height:P}}function S(){const{width:z,height:Z}=w(),P=y();return{width:z*P,height:Z*P}}function y(){return(r.scale??1)*qa}function C(){const{pdfjsPage:z}=r.page;o.value=z.getViewport({scale:qa*r.outputScale})}async function T(){if(l)return;const z=s.value;if(!z||!o.value)return;const Z={canvasContext:z.getContext("2d"),viewport:o.value};try{const{pdfjsPage:P}=r.page;l=P.render(Z),await l.promise;const N=S(),I=w();n("page-rendered",{page:r.page,documentId:r.page.documentId,pageIndex:u.value,pageNumber:c.value,width:N.width,height:N.height,originalWidth:I.width*qa,originalHeight:I.height*qa})}catch{B(),n("page-error",r.page)}}async function R(){if(!r.hasTextLayer)return;const z=a.value;if(!z)return;z.innerHTML="";const Z=r.config?.pdfLib?.TextLayer;if(Z)try{const P=(r.scale??1)*qa,N=r.page.pdfjsPage.getViewport({scale:P});await new Z({textContentSource:await r.page.pdfjsPage.getTextContent(),container:z,viewport:N}).render(),n("text-layer-rendered",r.page)}catch(P){n("text-layer-error",r.page),console.error(P)}}async function M(){await T(),await R()}function H(z){z?.pdfjsPage&&z.pdfjsPage.cleanup(),B()}function B(){l&&(l.cancel(),l=null)}return Pt(()=>r.scale,()=>{R()}),C(),Rn(()=>{M()}),ir(()=>{H(r.page)}),(z,Z)=>(me(),_e("div",{class:"sd-pdf-viewer-page","data-page-id":e.page.pageId,"data-page-number":c.value,style:vn(p.value),"data-pdf-page":"",ref_key:"pageRef",ref:i,onMousedown:k,onMouseup:g},[Le("div",VS,[Le("canvas",cs({class:"sd-pdf-viewer-page__canvas"},m.value,{ref_key:"canvasRef",ref:s}),null,16)]),e.hasTextLayer?(me(),_e("div",{key:0,class:"sd-pdf-viewer-page__text-layer",ref_key:"textLayerRef",ref:a},null,512)):ut("",!0)],44,US))}},GS=hn(jS,[["__scopeId","data-v-d7a9857d"]])})),TD=br((()=>{})),WS,KS,RD=br((()=>{It(),xD(),TD(),gn(),WS={__name:"PdfViewerDocument",props:{config:{type:Object,required:!0},pdf:{type:Object},pages:{type:Array,required:!0},scale:{type:Number},hasTextLayer:{type:Boolean,default:!1},outputScale:{type:Number}},emits:["page-focus","page-rendered","page-error","selection-raw","bypass-selection"],setup(e,{emit:t}){const n=t,r=ne(null),o=ne(null);function i(u){n("page-rendered",u)}function s(u){n("page-error",u)}function a(u){n("selection-raw",u)}function l(u){n("bypass-selection",u)}return(u,c)=>(me(),_e("div",{class:"sd-pdf-viewer-document",ref_key:"documentRef",ref:r},[Le("div",{class:"sd-pdf-viewer-document__wrapper",ref_key:"documentWrapper",ref:o},[(me(!0),_e(Wt,null,or(e.pages,d=>(me(),fn(GS,cs({key:d.pageId},{ref_for:!0},{page:d,pages:e.pages,scale:e.scale,config:e.config,hasTextLayer:e.hasTextLayer,outputScale:e.outputScale,documentEl:r.value},{onPageRendered:i,onPageError:s,onSelectionRaw:a,onBypassSelection:l}),null,16))),128))],512)],512))}},KS=hn(WS,[["__scopeId","data-v-2152178b"]])})),MD=br((()=>{})),LD=Gu({default:()=>XS},1),qS,YS,XS,DD=br((()=>{It(),CD(),_D(),qy(),AD(),RD(),MD(),gn(),qS={class:"sd-pdf-viewer__main"},YS={__name:"PdfViewer",props:{config:{type:Object,required:!0},file:{type:Object,required:!0},fileId:{type:String},initialScale:{type:Number,default:1}},emits:["page-rendered","pages-loaded","document-loaded","document-ready","document-error","selection-raw","bypass-selection"],setup(e,{expose:t,emit:n}){const r=n,o=e,i=BS({pdfLib:Hr(o.config.pdfLib),workerSrc:o.config.workerSrc,setWorker:o.config.setWorker}),s=HS.create(i),a=ne(null),l=ne(null),u=ne(null),c=ne([]),d=ne(typeof o.initialScale=="number"&&Number.isFinite(o.initialScale)&&o.initialScale>0?r0(o.initialScale,2):1),h=ne(0),m=ne(0),p=Se(()=>o.config?.textLayer===!0),g=Se(()=>o.config?.outputScale??2);function k(Z){const P=Z?.page;P&&(P.pageIsRendered=!0),y(),r("page-rendered",Z)}function w(Z){r("selection-raw",Z)}function S(Z){r("bypass-selection",Z)}function y(){h.value<=0||(m.value+=1,m.value>=h.value&&r("document-ready",{documentId:u.value?.documentId,viewerContainer:a.value}))}function C(Z){c.value=Z,h.value=Z.length,m.value=0}function T(Z){d.value=r0(Z,2)}t({updateScale:T});async function R(Z){if(Z)try{const P=await OS(Z);u.value={documentId:o.fileId||B("document"),pdfjsDocument:Hr(await s.getDocument(P))},r("document-loaded",Z)}catch(P){r("document-error",P),console.error(P)}}async function M(){if(!u.value)return;const{pdfjsDocument:Z}=u.value,P=1,N=Z.numPages;try{const I=await s.getPages(Z,P,N),L=te=>({documentId:u.value.documentId,pageId:z(u.value.documentId,te.pageNumber),pageNumber:te.pageNumber,pageIsRendered:!1,pdfjsPage:Hr(te)}),X=I.map(L);C(X),r("pages-loaded",X)}catch(I){r("document-error",I),console.error(I)}}function H(){c.value=[],d.value=1}function B(Z){return`pdf-${Z.replace(/\W/g,"")}-${Math.random().toString(36).slice(2)}-${Date.now()}`}function z(Z,P){return`${Z}-page-${P}`}return Pt(()=>o.file,Z=>{R(Z)},{immediate:!0}),Pt(u,(Z,P)=>{Z&&(P&&H(),M())}),(Z,P)=>(me(),_e("div",{class:"sd-pdf-viewer",ref_key:"rootRef",ref:a},[Le("div",qS,[Gt(KS,cs({pdf:u.value,pages:c.value,scale:d.value,config:e.config,hasTextLayer:p.value,outputScale:g.value},{onPageRendered:k,onSelectionRaw:w,onBypassSelection:S,ref_key:"documentRef",ref:l}),null,16)])],512))}},XS=hn(YS,[["__scopeId","data-v-05c9d9b5"]])}));It(),gn();var PD={key:0,class:"sd-visually-hidden",role:"status","aria-live":"assertive","data-superdoc-v2-author-required":""},OD=["innerHTML"],FD={class:"superdoc__document document"},BD={class:"floating-comments"},ND=!1,zD=3,o0=6500,i0=8e3,HD={__name:"SuperDoc",emits:["selection-update"],setup(e,{emit:t}){const n=R2(()=>Promise.resolve().then(()=>(DD(),LD))),r=O=>O.password??F.$superdoc.config.password,o=O=>{const q=O?.v2Collaboration,Ee=q&&typeof q=="object"&&"value"in q?q.value:q;if(Ee==null)return{state:"absent"};const Ne=DS({v2Collaboration:Ee,documentType:O?.type??null,documentCount:a.value.length,...typeof window<"u"?{authEndpointBaseUrl:window.location.href}:{}});if(!Ne.ok)return{state:"invalid",failure:{code:Ne.reason==="invalid-room-mode"?"collaboration-open-intent-invalid":"collaboration-config-invalid",message:`SuperDoc rejected the v2 collaboration configuration (${Ne.reason}).`}};const{providerFamily:mt,...nn}=Ne.target;return{state:"valid",config:{providerType:mt,...nn}}},i=nu(),s=ca(),{documents:a,isReady:l,areDocumentsReady:u,selectionPosition:c,activeSelection:d,activeZoom:h,zoomMode:m,measurementUnit:p,viewportMetrics:g}=ea(i),{handlePageReady:k,modules:w,user:S,getDocument:y}=i,C=La("surfaceManager",null),T=tM({getSurfaceManager:()=>C,getPasswordPromptConfig:()=>F.$superdoc?.config?.modules?.surfaces?.passwordPrompt,onUnhandled:(O,q,Ee)=>{F.$superdoc?.emit("exception",{error:Ee?.error??new Error(`Password prompt unhandled: ${q}`),editor:Ee?.editor??null,code:q,documentId:O?.id})}}),{getConfig:R,documentsWithConverations:M,commentsList:H,pendingComment:B,activeComment:z,skipSelectionUpdate:Z,commentsByDocument:P,isCommentsListVisible:N,isFloatingCommentsReady:I,generalCommentIds:L,hasSyncedCollaborationComments:X,editorCommentPositions:te,hasInitializedLocations:le,isCommentHighlighted:fe,hasOpenTrackedChanges:Fe}=ea(s),{showAddComment:he,handleEditorLocationsUpdate:ge,handleTrackedChangeUpdate:ae,refreshTrackedChangeCommentsByIds:Ce,syncTrackedChangePositionsWithDocument:oe,syncTrackedChangeComments:xe,addComment:qe,addHydratedComment:et,getComment:kt,resolveCommentPositionEntry:Ie,belongsToDocument:ze,COMMENT_EVENTS:Ve,requestInstantSidebarAlignment:Q,peekInstantSidebarAlignment:_,clearInstantSidebarAlignment:$}=s,{proxy:F}=sr();s.proxy=F;const j=wT(F.$superdoc.config),V=Hr(j.EditorComponent),G=j.RulerComponent?Hr(j.RulerComponent):null,J=Se(()=>{const O=Ge(s.getFloatingComments);return Array.isArray(O)?O:[]}),{isHighContrastMode:K}=zi(),{uiFontFamily:W}=jy(),ue=()=>s.viewingVisibility.documentMode==="viewing",be=()=>!!F?.$superdoc?.config?.allowSelectionInViewMode,we=Se(()=>ue()&&s.viewingVisibility.commentsVisible===!0),Te=Se(()=>F?.$superdoc?.uiConfig?.search?.enabled===!0);Se(()=>ue()&&s.viewingVisibility.trackChangesVisible===!0);const rt=Se(()=>s.shouldRenderReviewInViewing),nt=Se(()=>F.$superdoc.config.proofing!==void 0?F.$superdoc.config.proofing:F.$superdoc.config.layoutEngineOptions?.proofing),wt=Se(()=>{const O=w.comments;return O===!1||O==null?null:O}),Zt=Se(()=>{const O={"--sd-ui-font-family":W.value},q=F.$superdoc.config.modules?.comments;if(!q||q===!1)return O;q.highlightHoverColor&&(O["--sd-comments-highlight-hover"]=q.highlightHoverColor);const Ee={...q.trackChangeHighlightColors||{},...q.trackChangeActiveHighlightColors||{}};return Ee.insertBorder&&(O["--sd-tracked-changes-insert-border"]=Ee.insertBorder),Ee.insertBackground&&(O["--sd-tracked-changes-insert-background"]=Ee.insertBackground),Ee.deleteBorder&&(O["--sd-tracked-changes-delete-border"]=Ee.deleteBorder),Ee.deleteBackground&&(O["--sd-tracked-changes-delete-background"]=Ee.deleteBackground),Ee.formatBorder&&(O["--sd-tracked-changes-format-border"]=Ee.formatBorder),O}),Ct=ne(null),Ot=ne(null),Bt=ne(null),on=ne(null),Fn=ne(!1),Vt=zr({top:null,right:"-25px",zIndex:101}),{superdocContainerWidth:We,isCompactCommentsMode:St,recalculateCompactCommentsMode:Nt,ensureCompactMeasurementObserver:cn}=k9({commentsModuleConfig:wt,superdocRoot:Ct,layers:Ot}),Dt=Se(()=>!0),un=Ur(null),Ft=ne(!1),Me=ne(null);let Pe=0;const Ze=Se(()=>F.$superdoc.activeEditor),ot=()=>F.$superdoc?.ui??null,Mt=Object.freeze({enabled:!1,active:!1,supported:!1}),Et=sM({getSurfaceManager:()=>C,getActiveEditor:()=>F.$superdoc?.activeEditor,activeEditorRef:Ze,getFindReplaceConfig:()=>F.$superdoc?.config?.modules?.surfaces?.findReplace,getSuperDocUI:ot}),Tt=UL({getSurfaceManager:()=>C||(typeof F.$superdoc?.openSurface!="function"?null:{open:O=>F.$superdoc.openSurface(O)}),getActiveEditor:()=>F.$superdoc?.activeEditor,getUi:ot,getResolver:()=>F.$superdoc?.uiConfig?.linkPopover?.suppressed?()=>({type:"none"}):F.$superdoc?.config?.modules?.links?.popoverResolver,getLayerElement:()=>Ot.value,emitException:O=>{F.$superdoc?.emit("exception",{...O,editor:F.$superdoc?.activeEditor??null})}}),ur=F.$superdoc.config.modules?.pdf||{},dr=()=>{Fn.value&&(Fn.value=!1,xe({superdoc:F.$superdoc,editor:F.$superdoc?.activeEditor}))},jr=()=>{Fn.value=!0,_t(()=>{dr()})},$t=(O,q)=>{const Ee=y(O);Ee.isReady=!0,Ee.container=q,u.value&&(F.$superdoc.config.collaboration||(l.value=!0)),ht(),I.value=!0,le.value=!0,F.$superdoc.broadcastPdfDocumentReady()},Vn=()=>{if(!c.value||!Ot.value)return null;const O=c.value.source==="pdf"?(h.value??100)/100:1,q=Number(c.value.top);return Number.isFinite(q)?Ot.value.getBoundingClientRect().top+q*O:null},Mr=async()=>{if((await he(F.$superdoc,Vn()))?.ok===!1||!Dt.value)return;const O=Cu();O&&_u(O)},_r=async O=>{const q={comments:()=>Mr()};O in q&&await q[O](d.value,c.value),d.value=null,Vt.top=null},po=()=>Vt.top=null,Kt=new Map,yn=new Map,xo=new Map,Zo=new Map;let Ei=0;const pi=O=>{const q=xo.get(O);if(q){xo.delete(O);try{q.unbind?.()}catch(Ee){console.warn("[SuperDoc] v2 command-shortcut unbind failed",Ee)}}},Ss=()=>{const O=F.$superdoc?.toolbar;return!O||typeof O.getToolbarItemByName!="function"?null:()=>{const q=O.getToolbarItemByName("link");!q||q.disabled?.value===!0||(q.expand&&typeof q.expand=="object"&&"value"in q.expand&&(q.expand.value=!0),O.updateToolbarState?.())}},ks=({documentId:O,bindEditShortcuts:q})=>{if(!O||(pi(O),typeof q!="function"))return;const Ee=Ss(),Ne=q({commandRoute:{executeAsync:(mt,nn)=>{const pn=ot();return pn?pn.commands.executeAsync(mt,nn):Promise.resolve(ND)},getState:mt=>ot()?.commands.get(mt).getState()??Mt},...Ee?{openLinkWorkflow:Ee}:{}});xo.set(O,{unbind:Ne})},As=O=>{const q=Zo.get(O);if(q){Zo.delete(O);try{q.unbind?.()}catch(Ee){console.warn("[SuperDoc] v2 session-shortcut unbind failed",Ee)}}},al=({documentId:O,bindSessionShortcuts:q,documentApi:Ee})=>{if(!O||(As(O),typeof q!="function"))return;const Ne=q({routes:eD({resolveToolbarElement:()=>F.$superdoc?.toolbar?.toolbarContainer??null,getDocumentApi:()=>Ee??null}),isMutationAllowed:()=>!ue()});Zo.set(O,{unbind:Ne})},Wi=(O,q)=>{O?.id&&(q?Kt.set(O.id,q):Kt.delete(O.id))},ro=O=>{pi(O),As(O);const q=yn.get(O);if(!q)return;F.$superdoc.unregisterEditorRuntime(q.runtimeId),yn.delete(O);const Ee=Kt.get(O);Ee&&xS(Ee)},ke=({documentId:O,host:q,mount:Ee,facade:Ne})=>{const mt=Kt.get(O);if(!mt)return console.warn("[SuperDoc] v2 runtime host root unavailable; skipping runtime registration for",O),!1;yn.has(O)&&ro(O);const nn=`v2:${O}:${++Ei}`,pn=YL({id:nn,documentId:O,root:mt,host:q,getLegacyEditorProjection:()=>Ne,onUnregister:Jn=>{F.$superdoc.unregisterEditorRuntime(Jn);const Dn=yn.get(O);Dn&&Dn.runtimeId===Jn&&yn.delete(O);const _n=Kt.get(O);_n&&xS(_n)}});return pn.attachMountHandle(Ee??null),tD(mt,nn),F.$superdoc.registerEditorRuntime(pn.runtime),yn.set(O,{runtimeId:nn,adapter:pn}),F.$superdoc.setActiveRuntime(nn,"v2-editor-ready"),!0},Oe=j.createReviewHydrationController({hydrateComments:O=>s.hydrateCommentsFromV2?.(O),hydrateTrackedChanges:O=>s.hydrateTrackedChangesFromV2?.(O)}),ft=ne({}),lt=K9(),bn=ne({}),an=Se(()=>Object.values(bn.value)[0]??null),Fr=O=>typeof O=="string"&&O.length>0?`document:${O}`:"document:default",mo=O=>{const q=Fr(O);if(lt.clear(q),!bn.value[q])return;const Ee={...bn.value};delete Ee[q],bn.value=Ee},go=(O,q)=>{const Ee=Fr(O);lt.shouldNotify(Ee,q)&&(bn.value={...bn.value,[Ee]:E_},F.$superdoc.emit("exception",{error:new Error(E_),code:G9,editor:null,...typeof O=="string"&&O.length>0?{documentId:O}:{},...q.failureSource==="receipt"&&q.failure?{receipt:q.failure}:{}}))},To=(O,q)=>{O&&(ft.value={...ft.value,[O]:q})},Is=O=>{if(!O||!ft.value[O])return;const q={...ft.value};delete q[O],ft.value=q},Jo=(O=null)=>{const q=F.$superdoc?.activeEditor,Ee=O??q?.documentId??q?.options?.documentId??null;if(!Ee){q?.editorVersion===2&&F.$superdoc.setActiveEditor(null);return}if(O&&q?.editorVersion===2){const nn=q.documentId??q.options?.documentId??null;if(nn&&nn!==O)return}const Ne=Ee?y(Ee):null;Ne&&(Ne.isReady=!1,typeof Ne.setEditor=="function"&&Ne.setEditor(null));const mt=yn.has(Ee);ro(Ee),!mt&&q?.editorVersion===2&&(q.documentId??q.options?.documentId??null)===Ee&&F.$superdoc.setActiveEditor(null)},Ro=O=>{const q=typeof O?.getExtensionManager=="function"?O.getExtensionManager():null;if(!q)return null;const Ee=q.commands;return{commands:{execute:(Ne,mt)=>Ee.execute(Ne,mt),getState:Ne=>{const mt=Ee.get(Ne);return mt?{enabled:!(mt.getState()??{}).disabled,reason:null}:null},list:()=>Ee.list().map(Ne=>{const mt=Ne.getState()??{};return mt.label?{id:Ne.id,label:mt.label}:{id:Ne.id}})},diagnostics:{getSnapshot:()=>q.diagnostics()}}},Ki=O=>{if(!O)return;Is(O.documentId??null),mo(O.documentId??null);const{host:q,mount:Ee,documentId:Ne,capabilities:mt,editCommands:nn,bindEditShortcuts:pn,bindSessionShortcuts:Jn,commentsAdapter:Dn,trackedChangesAdapter:_n,documentApi:An,documentMutationReadiness:so,documentApiUnavailableReason:ao,pageMetrics:ka,pageLayout:Sl,pageFurniture:Oo,presence:kl,lock:hr,fonts:nb,replaceFile:sm}=O,am=async(At={})=>{if(!q||typeof q.save!="function")throw new Error("v2-editor: save unavailable");return q.save(At)},rb=async(At={})=>{const jt=await am({format:"docx",commentExportMode:At?.commentsType==="clean"?"strip":"preserve"});return new Blob([jt],{type:Tr})},Bu=async At=>{if(typeof sm!="function")throw new Error("v2-editor: replaceFile unavailable");return sm(At)},Kr=(At={})=>Ee?.focus&&typeof Ee.focus.focus=="function"?Ee.focus.focus(At):!1,$n=(At,jt=void 0)=>{const wn={ok:!1,reason:At};return jt&&(wn.detail=jt),wn},Aa=At=>Array.isArray(At?.items)?At.items:[],lm=At=>{const jt=Number(At);return Number.isFinite(jt)&&jt>0?Math.floor(jt):0},cm=async({text:At,occurrence:jt=0}={})=>{if(typeof At!="string"||At.length===0)return $n("invalid-text","text must be a non-empty string");if(!An?.query||typeof An.query.match!="function")return $n("query-unavailable","activeEditor.doc.query.match is not available");const wn=lm(jt),yr=await An.query.match({select:{type:"text",pattern:At},limit:wn+1}),Br=Aa(yr),lo=Br[wn]??null;return lo?.target?{ok:!0,item:lo,target:lo.target,ref:typeof lo?.handle?.ref=="string"?lo.handle.ref:null,text:At,occurrence:wn,total:Number.isFinite(Number(yr?.total))?Number(yr.total):Br.length}:$n("text-not-found",`text not found: ${At}`)},Bf=(At,jt)=>{if(!At||typeof At!="object"||At.kind!=="selection"||jt!=="start"&&jt!=="end")return At;const wn=jt==="start"?At.start:At.end;return wn?{kind:"selection",start:wn,end:wn,...At.story?{story:At.story}:{}}:At},um=async({target:At,collapse:jt=null,focus:wn=!0}={})=>{if(!At||typeof At!="object")return $n("invalid-target","target must be a SelectionTarget object");const yr=Bf(At,jt),Br=(q?.getHandles?.()?.editing??null)?.selectionTargets??null;if(typeof Br?.apply!="function")return $n("selection-target-unavailable","editing.selectionTargets.apply is not available");let lo;try{lo=Br.apply(yr)}catch(bi){return $n("selection-target-threw",bi instanceof Error?bi.message:String(bi))}return lo?.ok?(wn!==!1&&await Promise.resolve(Kr()),{ok:!0,mode:lo.mode??"range"}):$n(lo?.reason??"selection-target-rejected",lo?.detail)},dm=()=>F.$superdoc.config.documentMode==="suggesting"?"tracked":"direct",fm=()=>{const At=(q?.getHandles?.()?.editing??null)?.selection??null;if(typeof At?.toSelectionTarget!="function")return $n("selection-target-unavailable","editing.selection.toSelectionTarget is not available");const jt=At.toSelectionTarget();if(!jt||jt.kind==="rejected"){const wn=jt?.rejection??{};return $n(wn.reason??wn.code??"selection-target-rejected",wn.detail)}return!jt.target||typeof jt.target!="object"?$n("selection-target-rejected","selection target was not produced"):{ok:!0,target:jt.target,mode:jt.mode??"range",story:jt.story}},ob=(At,jt)=>{const wn=At?.failure??At;return $n(wn?.code??At?.reason??jt,wn?.message??wn?.detail??At?.detail)},hm={focusEditable:Kr,readBlocks:(At={includeText:!0})=>An?.blocks?.list?.(At),setSelectionTarget:(At={})=>um(At),setSelectionByText:async(At={})=>{const jt=await cm(At);if(!jt.ok)return jt;const wn=await um({target:jt.target,collapse:At?.collapse??null,focus:At?.focus});return wn.ok?{ok:!0,mode:wn.mode,text:jt.text,occurrence:jt.occurrence,target:jt.target}:wn},replaceTextByText:async({findText:At,replacement:jt,occurrence:wn=0,mode:yr="direct"}={})=>{if(typeof jt!="string")return $n("invalid-replacement","replacement must be a string");if(!An?.text||typeof An.text.replace!="function")return $n("text-replace-unavailable","activeEditor.doc.text.replace is not available");const Br=await cm({text:At,occurrence:wn});if(!Br.ok)return Br;const lo=Br.ref?{ref:Br.ref,text:jt,mode:yr}:{target:Br.target,text:jt,mode:yr},bi=await An.text.replace(lo);return bi?.ok===!1?$n(bi.reason??"text-replace-failed",bi.detail):(await Promise.resolve(so?.whenPainted?.(bi)),{ok:!0,receipt:bi,text:jt,replacedText:At,occurrence:lm(wn)})},replaceSelection:async({target:At,replacement:jt="",mode:wn="direct"}={})=>{if(!At||typeof At!="object")return $n("invalid-target","target must be a SelectionTarget object");if(typeof jt!="string")return $n("invalid-replacement","replacement must be a string");if(!An?.text||typeof An.text.replace!="function")return $n("text-replace-unavailable","activeEditor.doc.text.replace is not available");const yr=await An.text.replace({target:At,text:jt,mode:wn});return yr?.ok===!1?$n(yr.reason??"text-replace-failed",yr.detail):(await Promise.resolve(so?.whenPainted?.(yr)),{ok:!0,receipt:yr,text:jt})},serializeSelectionToClipboard:async({includeHtml:At=!0}={})=>{if(!An?.clipboard||typeof An.clipboard.serializeSelection!="function")return $n("clipboard-serialize-unavailable","activeEditor.doc.clipboard.serializeSelection is not available");const jt=fm();if(!jt.ok)return jt;let wn;try{wn=await An.clipboard.serializeSelection({target:jt.target,includeHtml:At!==!1})}catch(yr){return $n("clipboard-serialize-threw",yr instanceof Error?yr.message:String(yr))}return wn?.payload?{ok:!0,payload:wn.payload,plan:wn.plan,target:jt.target,mode:jt.mode}:$n("clipboard-serialize-failed","clipboard serialization did not return a payload")},pasteClipboardPayload:async({payload:At,target:jt=null,mode:wn=dm(),fallback:yr=void 0}={})=>{if(!At||typeof At!="object")return $n("invalid-clipboard-payload","payload must be a ClipboardPayload object");if(!An?.clipboard||typeof An.clipboard.insert!="function")return $n("clipboard-insert-unavailable","activeEditor.doc.clipboard.insert is not available");let Br=jt,lo=null;if(!Br){const Nu=fm();if(!Nu.ok)return Nu;Br=Nu.target,lo=Nu.mode}if(!Br||typeof Br!="object")return $n("invalid-target","target must be a SelectionTarget or ClipboardTarget object");const bi={payload:At,target:Br,changeMode:wn==="tracked"?"tracked":"direct",...yr!==void 0?{fallback:yr}:{}},Al=await An.clipboard.insert(bi);return!Al||Al.success===!1||Al.ok===!1?ob(Al,"clipboard-insert-failed"):(await Promise.resolve(so?.whenPainted?.(Al)),{ok:!0,receipt:Al,target:Br,mode:lo})},pastePlainText:async({text:At,target:jt=null,mode:wn=dm()}={})=>typeof At!="string"?$n("invalid-text","text must be a string"):hm.pasteClipboardPayload({payload:{source:"api",items:[{type:"text/plain",kind:"string",data:At}]},target:jt,mode:wn})},mc={editorVersion:2,documentId:Ne,host:q,mount:Ee,options:{documentId:Ne,documentMode:F.$superdoc.config.documentMode},capabilities:mt??q?.getCapabilities?.()??null,save:am,exportDocx:rb,replaceFile:Bu,doc:An??null,documentMutationReadiness:so??null,documentApiUnavailableReason:ao??null,focus:Kr,authoring:hm,editCommands:nn??null,v2Comments:Dn??null,v2TrackedChanges:_n??null,pageMetrics:ka??null,pageLayout:Sl??null,pageFurniture:Oo??null,presence:kl??null,lock:hr??null,reviewHydration:{getDiagnostics:()=>Oe.getDiagnostics()},extensions:Ro(q),fonts:nb??q?.getFontRuntime?.()??null,commands:null,state:null,view:null},Fs=y(Ne);Fs&&(Fs.isReady=!0,typeof Fs.setEditor=="function"&&Fs.setEditor(mc)),ke({documentId:Ne,host:q,mount:Ee,facade:mc})||F.$superdoc.setActiveEditor(mc),F.$superdoc.broadcastEditorCreate(mc),ks({documentId:Ne,bindEditShortcuts:pn}),al({documentId:Ne,bindSessionShortcuts:Jn,documentApi:An}),o(y(Ne)).state==="valid"&&xu({editor:mc}),ka&&Sl&&(Ps.value=!0);const Nf=F.$superdoc.config.modules?.comments!==!1;if(Dn&&Nf&&s.setV2CommentsAdapter?.(Dn),_n&&Nf&&s.setV2TrackedChangesAdapter?.(_n),Nf&&(Dn||_n)){Oe.setContext({superdoc:F.$superdoc,documentId:Ne,commentsAdapter:Dn??null,trackedChangesAdapter:_n??null});try{const At=q?.getRenderReadinessSnapshot?.();At&&Oe.onRenderReadiness(At)}catch(At){console.warn("[SuperDoc][v2] initial render-readiness snapshot failed",At)}}u.value&&!F.$superdoc.config.collaboration&&(l.value=!0),I.value=!0,le.value=!0},Gr=ne(!1),Sr=Ur(null);let Mo=0,Ho=0,$o=0;const ll=({editor:O,sourceEditor:q,surface:Ee="body",headerId:Ne=null,sectionType:mt=null}={})=>{const nn=F.$superdoc?.activeEditor??null,pn=O??q??nn??void 0;return{editor:pn,sourceEditor:q??pn,surface:Ee,headerId:Ne,sectionType:mt}},oc=(O={})=>{F.$superdoc.emit("editor-update",ll(O))},kr=()=>{Mo&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Mo),Ho&&clearTimeout(Ho),Mo=0,Ho=0},Uo=(O=zD)=>{kr();const q=()=>{Mo=0,Ho=0,fl(),Gr.value&&ri.value&&!c.value&&O>0&&Uo(O-1)};if(typeof requestAnimationFrame=="function"){Mo=requestAnimationFrame(q);return}Ho=setTimeout(q,0)},xi=()=>{$o&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame($o),$o=0},cl=()=>{Gr.value=!1,Sr.value=null,kr(),fl()},qi=(O,q)=>{if(!O||O.rangeCount<1||O.isCollapsed||!q)return!1;const Ee=O.getRangeAt(0);return q.contains(Ee.startContainer)&&q.contains(Ee.endContainer)},mi=()=>{if($o=0,!Dt.value)return;let O=null;try{O=F.$superdoc?.activeEditor?.host?.getHandles?.()??null}catch{O=null}const q=F.$superdoc?.config?.documentMode;if(q==="editing"||q==="suggesting"){const nn=O?.editing?.selection?.getSnapshot?.()??null;if(X9(q,nn)){const pn=jn();if(Y9(window.getSelection?.()??null,pn)){cl();return}Gr.value=!0,Sr.value=nn,Uo();return}}else if(q!=="viewing"){cl();return}const Ee=jn(),Ne=window.getSelection?.()??null;if(!qi(Ne,Ee)){cl();return}const mt=O?.editing?.selectionTargets?.applyDomSelection?.(Ne);if(!mt?.ok||mt.mode!=="range"){cl();return}Gr.value=!0,Sr.value=O?.editing?.selection?.getSnapshot?.()??null,Uo()},Rf=()=>{if(Dt.value){if(xi(),typeof requestAnimationFrame!="function"){mi();return}$o=requestAnimationFrame(mi)}},ei=()=>{Rf()},ul=({hasRangeSelection:O,snapshot:q}={})=>{if(Gr.value=O===!0,Sr.value=O===!0?q??null:null,Gr.value){Uo();return}kr(),fl()},jn=()=>un.value?.mountContainer??F.$superdoc?.activeEditor?.mount?.container??null,ic=O=>{const q=String(O);return globalThis.CSS?.escape?globalThis.CSS.escape(q):q.replace(/["\\]/g,"\\$&")},wu=()=>{const O=Sr.value,q=jn();if(!O||!q?.querySelector)return null;const Ee=O.anchor??null,Ne=[Ee?.fragmentId,Ee?.blockId,Ee?.position?.anchor?.nativeId].filter(mt=>mt!=null&&mt!=="");for(const mt of Ne){const nn=ic(mt),pn=q.querySelector(`[data-source-node-id="${nn}"]`)??q.querySelector(`[data-layout-block-ref="${nn}"]`)??q.querySelector(`[data-layout-fragment-id="${nn}"]`);if(pn instanceof HTMLElement)return pn}return null};function ba(O=null){const q=window.getSelection?.();if(!q||q.rangeCount<1||q.isCollapsed)return null;const Ee=q.getRangeAt(0);if(!Ee)return null;if(O){const{startContainer:Ne,endContainer:mt}=Ee;if(!O.contains(Ne)||!O.contains(mt))return null}try{const Ne=Ee.getBoundingClientRect();return!Ne||Ne.width<=0&&Ne.height<=0?null:Ne}catch{return null}}const Yi=O=>{if(!O||!Ot.value)return null;const q=Ot.value.getBoundingClientRect();return{top:O.top-q.top,left:O.left-q.left,right:O.right-q.left,bottom:O.bottom-q.top,width:O.width,height:O.height}},Es=O=>{let q=O;for(;q&&q.nodeType===1;){const Ee=q.dataset?.pageIndex;if(Ee!=null&&Ee!==""){const Ne=Number(Ee);if(Number.isFinite(Ne))return Ne}q=q.parentElement}return null},dl=()=>{if(!Gr.value||!ri.value)return null;const O=Yi(ba(jn()))??Cu()?.bounds??null;if(!O)return null;const q=F.$superdoc?.activeEditor?.options?.documentId??F.$superdoc?.activeEditor?.documentId;if(!q)return null;const Ee=Es(wu());return Qd({selectionBounds:O,page:Ee!=null?Ee+1:1,documentId:q,source:tu})},Cu=()=>{if(!Ot.value)return null;const O=wu();if(!O)return null;const q=O.getBoundingClientRect();if(!q||q.width<=0&&q.height<=0)return null;const Ee=Ot.value.getBoundingClientRect(),Ne={top:q.top-Ee.top,left:q.left-Ee.left,right:q.right-Ee.left,bottom:q.bottom-Ee.top,width:q.width,height:q.height},mt=Es(O);return{threadId:"pending",key:"pending",kind:"pending",storyKey:"body",bounds:Ne,...mt!=null?{pageIndex:mt}:{},...Me.value!=null?{generation:Me.value}:{}}},fl=()=>{if(!Dt.value)return;if(!Gr.value){d.value=null,Kn();return}const O=dl();if(!O){d.value=null,Kn();return}zt(O)},_u=O=>{O&&ge({...te.value??{},pending:O})},Ti=j.createGeometryPublisher({getLayersContainer:()=>Ot.value??null,isCommentsEnabled:()=>rt.value,publishPositions:O=>ge(O),clearPositions:()=>{s.clearEditorCommentPositions?.()},readCurrentPositions:()=>te.value??{},setGeometryAvailable:O=>{Ft.value=!!O,O&&(Me.value=Ti.getLastEpoch())}}),xs=O=>{if(un.value=O,Pe&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Pe),typeof requestAnimationFrame!="function"){Ti.publish(un.value);return}Pe=requestAnimationFrame(()=>{Pe=0,Ti.publish(un.value)})},Mf=O=>{O&&(xs(O),Gr.value&&Uo())},Ts=O=>{const q=O?.snapshot??O??null;q&&Oe.onRenderReadiness(q)},hl=Ur(null),Lo=new Map;let ti=null;const Su=O=>{if(!O?.snapshot)return;wa.onRender();const q=O.snapshot,Ee=O.stage;if(typeof HTMLElement<"u"&&Ee instanceof HTMLElement){ti=Ee;const mt=Ee.dataset?.superdocV2DocumentId;mt&&Lo.set(mt,Ee)}hl.value=q;const Ne=Array.isArray(q.pages)?q.pages.length:0;F.$superdoc.emit("pagination-update",{totalPages:Ne,superdoc:F.$superdoc}),_t(()=>{es(),Os()})},ku=O=>{Tt.destroy(),xi(),kr(),Pe&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Pe),Pe=0,un.value=null,Me.value=null,Ft.value=!1,Ti.reset(),Gr.value=!1,Sr.value=null,d.value=null,Kn(),hl.value=null;const q=O?.documentId==null?null:String(O.documentId);s.cancelImportedTrackedChangeBootstrap?.(q??void 0),q&&Lo.delete(q),ti&&(q==null||ti.dataset?.superdocV2DocumentId===q)&&(ti=null),Oe.reset("render-cleared"),wa.reset(),sc(),lc.clear(),s.setV2CommentsAdapter?.(null),s.setV2TrackedChangesAdapter?.(null),s.clearEditorCommentPositions?.(),Jo(O?.documentId??null),Ri(),io.value={},Ps.value=!1};let ni=0;const Rs=()=>{const O=F.$superdoc?.activeEditor?.v2Comments??null;O&&s.hydrateCommentsFromV2?.({superdoc:F.$superdoc,adapter:O,documentId:F.$superdoc?.activeEditor?.documentId??null})},pl=(O={})=>{Rs();const q=F.$superdoc?.activeEditor?.v2TrackedChanges??null;q&&s.hydrateTrackedChangesFromV2?.({superdoc:F.$superdoc,adapter:q,documentId:F.$superdoc?.activeEditor?.documentId??null,...O})},wa=k_({getContext:()=>{const O=F.$superdoc?.activeEditor??null,q=O?.v2TrackedChanges??null;return q?{superdoc:F.$superdoc,adapter:q,documentId:O.documentId??null}:null},reconcile:(O,q)=>s.reconcileTrackedChangeMutationFromV2?.({superdoc:O.superdoc,adapter:O.adapter,documentId:O.documentId,...q}),hydrate:(O,q)=>s.hydrateTrackedChangesFromV2?.({superdoc:O.superdoc,adapter:O.adapter,documentId:O.documentId,...q}),onReconciled:()=>Ti.recollect()});let ml=0,Xi=0;const sc=()=>{ni&&typeof clearTimeout=="function"&&clearTimeout(ni),ni=0,ml=0,Xi=0},ac=()=>{ml=Date.now(),Xi||(Xi=ml),ni&&typeof clearTimeout=="function"&&clearTimeout(ni);const O=()=>{ni=0;const Ee=Date.now()-ml,Ne=Date.now()-Xi;if(Ee<o0&&Ne<i0){const mt=o0-Ee,nn=i0-Ne;ni=setTimeout(O,Math.min(mt,nn));return}Xi=0,pl()},q=Math.max(0,i0-(Date.now()-Xi));ni=setTimeout(O,Math.min(o0,q))},lc=V9({hydrate:()=>pl(),getActiveDocumentId:()=>{const O=F.$superdoc?.activeEditor??null;return O?.documentId??O?.options?.documentId??null}}),Au=(O,q)=>{if(!q)return;const Ee=O?.id??null;if(q.type==="reviewTarget:changed"){Du(q.next);return}if(q.type==="collaboration:remote-changed"){lc.schedule(Ee);return}if(q.type==="source:complete"){F.$superdoc.broadcastSourceComplete();return}if(q.type==="source:signals-complete"){F.$superdoc.broadcastSourceSignalsComplete();return}if(q.type==="mutation:rejected"){go(Ee,q);return}if(q.type==="mutation:committed"&&(mo(Ee),oc()),q.type!=="mutation:committed")return;const Ne=S_(q),mt=(F.$superdoc?.activeEditor??null)?.documentMutationReadiness??null,nn=q.origin==="history"?null:q.receipt,pn=Ne&&typeof nn?.txId=="string"&&nn.txId.length>0&&typeof mt?.whenPainted=="function";if(wa.enqueueAfterPaint(Ne,pn?()=>mt.whenPainted.call(mt,nn):null),Ne?.reconcileMode==="authoritative"&&Ne.upsertIds.size>0){Rs();return}if(A_(q)){ac();return}Ne?.removedIds.size>0&&Ne.upsertIds.size===0||pl()},Lf=O=>{Tt.handleLinkClick(O)},cc=()=>{if(Dt.value&&Ti.getLastPayload()){if(Pe&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Pe),typeof requestAnimationFrame!="function"){Ti.recollect();return}Pe=requestAnimationFrame(()=>{Pe=0,Ti.recollect()})}},Ca=()=>{if(!Dt.value)return;try{Oe.hydrateNow("document-mode-change")}catch(q){console.warn("[SuperDoc][v2] document-mode-change rehydrate failed",q)}const O=()=>{Dt.value&&(rt.value?un.value?xs(un.value):cc():(s.clearEditorCommentPositions?.(),Ft.value=!1))};_t(()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>O()):O()})},Df=O=>{switch(O){case"editing-mount-required":return"SuperDoc could not load the document editor because the page did not provide a mount container.";case"source-load-failed":return"SuperDoc could not load the document editor because the document source could not be prepared.";case"unsupported-cdn-v2-editor":return"SuperDoc could not load the document editor because this build does not include the V2 runtime.";case"v2-integration-unavailable":return"SuperDoc could not load the document editor because the bundled V2 runtime is unavailable in this environment.";case"worker-init-failed":return"SuperDoc could not load the document editor because the browser worker failed to start.";case"input-too-large-for-inline-review":return"SuperDoc could not load the document editor because this document is too large to open without the browser worker.";case"collaboration-unsupported-huge-document":return"SuperDoc could not load the document editor because large documents cannot be opened with collaboration enabled yet.";case"collaboration-v1-config-unsupported":return"SuperDoc v2 cannot use modules.collaboration because it is the SuperDoc v1 collaboration API. SuperDoc did not attach the provider or change the document. Configure Document.v2Collaboration with a v2 room instead.";case"collaboration-room-format-unsupported":return"SuperDoc v2 cannot open this collaboration state because it is not stored in the SuperDoc v2 room format. No changes were made.";case"collaboration-room-format-conflict":return"SuperDoc v2 found conflicting room formats in one collaboration document. No changes were made.";case"collaboration-room-corrupt":return"SuperDoc v2 found a structurally invalid collaboration room. No changes were made.";case"collaboration-v2-room-missing":return'SuperDoc v2 could not find a committed v2 collaboration room. No changes were made. Use roomMode: "create" only when creating a new room.';case"collaboration-v2-room-already-exists":return'SuperDoc v2 was asked to create a collaboration room that already exists. Use roomMode: "join" to open it.';case"collaboration-v2-room-initializing":return"The SuperDoc v2 collaboration room is still initializing. Join mode did not modify it.";case"collaboration-open-intent-invalid":return"SuperDoc v2 received an invalid collaboration room mode. No provider was connected.";case"collaboration-config-invalid":return"SuperDoc v2 received an invalid collaboration configuration. No provider was connected.";default:return"SuperDoc could not load the document editor."}},Iu=O=>typeof O=="string"&&O.trim().length>0?O.trim():null,uc=O=>{Jo(O?.documentId??null);const q=typeof O?.reason=="string"&&O.reason.length>0?O.reason:"open-failed",Ee=Iu(O?.detail),Ne=typeof O?.documentId=="string"&&O.documentId.length>0?O.documentId:null,mt=Df(q),nn=O?.workerFailure&&typeof O.workerFailure=="object"?O.workerFailure:null;To(Ne,{reason:q,message:mt,detail:Ee,...nn?{workerFailure:nn}:{}});const pn={...Ee?{detail:Ee}:{},...Ne?{documentId:Ne}:{},...nn?{workerFailure:nn}:{},reason:q};q==="collaboration-v1-config-unsupported"||q==="collaboration-room-format-unsupported"||q==="collaboration-room-format-conflict"||q==="collaboration-room-corrupt"||q==="collaboration-v2-room-missing"||q==="collaboration-v2-room-already-exists"||q==="collaboration-v2-room-initializing"||q==="collaboration-open-intent-invalid"||q==="collaboration-config-invalid"?console.warn(`[SuperDoc] ${mt}`,pn):console.error(`[SuperDoc] ${mt}`,pn),F.$superdoc.emit("exception",{error:new Error(mt),code:q,...Ne?{documentId:Ne}:{},editor:null})},Ms=(O,q)=>{F.$superdoc?.activateRuntimeFromEventTarget?.(O.target,q)},Eu=O=>Ms(O,"focusin"),Ls=O=>Ms(O,"pointerdown"),dc=O=>Ms(O,"mousedown"),xu=({editor:O})=>{F.$superdoc.emit("collaboration-ready",{editor:O}),_t(()=>{l.value=!0;const q=new URLSearchParams(window.location.search).get("commentId");q&&tt(q)})};let Tu=0;const Qi=()=>{Tu=Date.now()+250},Ru=()=>Date.now()<Tu,Zi=O=>{const q=Ct.value;q&&(!(O.target instanceof Node)||!q.contains(O.target)||(Ot.value?.contains(O.target)&&(s.setActiveComment(F.$superdoc,null),s.removePendingComment(F.$superdoc),Xe()),Qi()))},Pf=O=>{const q=F.$superdoc.listeners?.("fonts-resolved")?.length>0?F.$superdoc.listeners("fonts-resolved")[0]:null,Ee=F.$superdoc.config.useLayoutEngine!==!1,Ne=O.isNewFile,mt=F.$superdoc.config?.benchmarkExecutionMode,nn=F.$superdoc.config?.benchmarkTraceEnabled===!0,pn=o(O),Jn=pn.state==="valid"?pn.config:null,Dn=F.$superdoc.config.v2CollaborationPreflightFailure??(pn.state==="invalid"?pn.failure:null);return{isDebug:F.$superdoc.config.isDebug||!1,documentId:O.id,user:F.$superdoc.user,users:F.$superdoc.users,colors:F.$superdoc.colors,role:F.$superdoc.config.role,html:O.html,markdown:O.markdown,documentMode:F.$superdoc.config.documentMode,...mt?{benchmarkExecutionMode:mt}:{},...nn?{benchmarkTraceEnabled:!0}:{},allowSelectionInViewMode:F.$superdoc.config.allowSelectionInViewMode,rulers:O.rulers,rulerContainer:F.$superdoc.config.rulerContainer,isInternal:F.$superdoc.config.isInternal,annotations:F.$superdoc.config.annotations,isCommentsEnabled:!!wt.value,isAiEnabled:F.$superdoc.config.modules?.ai,contextMenuConfig:(F.$superdoc.config.modules?.slashMenu&&!F.$superdoc.config.modules?.contextMenu&&console.warn("[SuperDoc] modules.slashMenu is deprecated. Use modules.contextMenu instead."),F.$superdoc.config.modules?.contextMenu??F.$superdoc.config.modules?.slashMenu),slashMenuConfig:F.$superdoc.config.modules?.contextMenu??F.$superdoc.config.modules?.slashMenu,comments:{highlightColors:wt.value?.highlightColors,highlightOpacity:wt.value?.highlightOpacity},trackedChanges:F.$superdoc.config.modules?.trackChanges,experimental:F.$superdoc.config.experimental,...Jn?{v2Collaboration:Jn}:{},...Dn?{collaborationPreflightFailure:Dn}:{},onCollaborationReady:xu,onCommentsUpdate:bl,onFontsResolved:q,onPageCountKnown:F.$superdoc.config.onPageCountKnown??null,fontAssets:F.$superdoc.config.fonts,proofing:nt.value,isNewFile:Ne,password:r(O),handleImageUpload:F.$superdoc.config.handleImageUpload,externalExtensions:F.$superdoc.config.editorExtensions||[],extensions:F.$superdoc.config.extensions||[],suppressDefaultDocxStyles:F.$superdoc.config.suppressDefaultDocxStyles,disableContextMenu:!F.$superdoc.uiConfig.contextMenu.enabled||F.$superdoc.config.disableContextMenu===!0,jsonOverride:F.$superdoc.config.jsonOverride,viewOptions:F.$superdoc.config.viewOptions,contained:F.$superdoc.config.contained,linkPopoverResolver:F.$superdoc.uiConfig.linkPopover.enabled?F.$superdoc.config.modules?.links?.popoverResolver:void 0,layoutEngineOptions:Ee?{...F.$superdoc.config.layoutEngineOptions||{},proofing:nt.value,debugLabel:F.$superdoc.config.layoutEngineOptions?.debugLabel??O.name??O.id,zoom:(h.value??100)/100,emitCommentPositionsInViewing:ue()&&rt.value,enableCommentsInViewing:we.value,contentControlsChrome:F.$superdoc.uiConfig.contentControls.enabled?F.$superdoc.uiConfig.contentControls.options.chrome??(F.$superdoc.config.modules?.contentControls?.chrome==="none"?void 0:F.$superdoc.config.modules?.contentControls?.chrome):"none",resolveTrackedChangeColor:d9(F.$superdoc.config.modules?.trackChanges?.authorColors)}:void 0,permissionResolver:(_n={})=>F.$superdoc.canPerformPermission({role:F.$superdoc.config.role,isInternal:F.$superdoc.config.isInternal,..._n}),licenseKey:F.$superdoc.config.licenseKey,telemetry:F.$superdoc.config.telemetry?.enabled?{enabled:!0,endpoint:F.$superdoc.config.telemetry?.endpoint,metadata:F.$superdoc.config.telemetry?.metadata,licenseKey:F.$superdoc.config.telemetry?.licenseKey}:null}},Mu=new Set(["commentText","isInternal","parentCommentId","trackedChangeParentId","trackedChangeThreadParentId","threadingParentCommentId","trackedChange","trackedChangeType","trackedChangeText","trackedChangeDisplayType","semanticColorKey","semanticColor","trackedChangeStory","trackedChangeStoryKind","trackedChangeStoryLabel","trackedChangeAnchorKey","trackedChangeLabel","trackedChangeDetailLines","deletedText","resolvedTime","resolvedById","resolvedByEmail","resolvedByName","importedAuthor","docxCommentJSON"]),gl=(O,q={})=>{if(!(!O||q.isDone===void 0)&&!(q.resolvedTime!=null||q.resolvedById!=null||q.resolvedByEmail!=null||q.resolvedByName!=null)){if(q.isDone){O.resolvedTime=O.resolvedTime||Date.now(),O.resolvedById=O.resolvedById||q.creatorId||null,O.resolvedByEmail=O.resolvedByEmail||q.creatorEmail||null,O.resolvedByName=O.resolvedByName||q.creatorName||null;return}O.resolvedTime=null,O.resolvedById=null,O.resolvedByEmail=null,O.resolvedByName=null}},fc=(O,q,Ee)=>{!O||!q||(Array.isArray(q.elements)&&(O.docxCommentJSON=q.elements),Object.entries(q).forEach(([Ne,mt])=>{mt!==void 0&&Ne!=="text"&&Ne!=="elements"&&Mu.has(Ne)&&(O[Ne]=mt)}),Ee!==void 0&&(O.commentText=Ee),gl(O,q))},Lu=(O={})=>{const q={...O};return!q.commentText&&q.text&&(q.commentText=q.text),!q.docxCommentJSON&&Array.isArray(q.elements)&&(q.docxCommentJSON=q.elements),gl(q,q),q},vl=O=>{if(Number.isFinite(_()))return;if(O==null){$();return}const q=Ot.value,{key:Ee,entry:Ne}=Ie(O),mt=a_(q,Ne);if(Number.isFinite(mt)){Q(mt,O,Ee??O);return}$()},yl=O=>O==null||z.value==null?!1:String(z.value)===String(O),Du=O=>{if(O?.origin!=="document"||Ru())return;const q=H9(O,kt);q&&(vl(q),z.value=q,fe.value=!0,setTimeout(()=>{fe.value=!1},0))},bl=(O={})=>{let{activeCommentId:q,type:Ee,comment:Ne}=O,mt=Object.prototype.hasOwnProperty.call(O,"activeCommentId");const nn=Jn=>{const Dn=[Jn?.importedId,Jn?.commentId].filter(Boolean).map(_n=>String(_n));return[...new Set(Dn)]},pn=Jn=>{const Dn=[Jn?.importedId,Jn?.commentId].filter(Boolean).map(An=>String(An)),_n=F.$superdoc?.activeEditor?.options?.documentId!=null?String(F.$superdoc.activeEditor.options.documentId):null;for(const An of Dn){const so=H.value.find(ao=>{const ka=ao?.commentId!=null?String(ao.commentId):null,Sl=ao?.importedId!=null?String(ao.importedId):null;return ka===An||Sl===An?!_n||typeof ze!="function"?!0:ze(ao,_n):!1});if(so){const ao=so?.commentId??so?.importedId??An;return{id:ao!=null?String(ao):null,existingComment:so}}}return{id:Dn[0]||null,existingComment:null}};if(Ee==="replayCompleted"&&jr(),Ve?.ADD&&Ee===Ve.ADD&&Ne){Ne=Lu(Ne);const Jn=F.$superdoc?.user;Jn&&(Ne.creatorId||(Ne.creatorId=Jn.id),Ne.creatorName||(Ne.creatorName=Jn.name),Ne.creatorEmail||(Ne.creatorEmail=Jn.email)),Ne.createdTime||(Ne.createdTime=Date.now());const Dn=Ne.documentId||a.value?.[0]?.id;!Ne.documentId&&Dn&&(Ne.documentId=Dn),!Ne.fileId&&Dn&&(Ne.fileId=Dn);const{id:_n,existingComment:An}=pn(Ne);if(_n&&!An){const so=aa(Ne);et({superdoc:F.$superdoc,comment:so,skipEditorUpdate:!0})}}if(Ve?.UPDATE&&Ee===Ve.UPDATE&&Ne){const{id:Jn,existingComment:Dn}=pn(Ne);if(Jn){const _n=Ne.commentText||Ne.text;if(Dn)fc(Dn,Ne,_n);else{const An=aa(Lu(Ne));et({superdoc:F.$superdoc,comment:An,skipEditorUpdate:!0})}}}if(Ve?.DELETED&&Ee===Ve.DELETED&&Ne){const Jn=nn(Ne);if(Jn.length){const Dn=F.$superdoc?.activeEditor?.options?.documentId!=null?String(F.$superdoc.activeEditor.options.documentId):null,_n=so=>!Dn||typeof ze!="function"?!0:ze(so,Dn),An=b9(H.value,Jn,_n);if(An.size){const so=[...H.value];H.value=H.value.filter(Oo=>{if(!_n(Oo))return!0;const kl=Oo.commentId!=null?String(Oo.commentId):null,hr=Oo.importedId!=null?String(Oo.importedId):null;return!(kl&&An.has(kl)||hr&&An.has(hr))});const ao=z.value!=null?String(z.value):null,ka=ao!=null?so.find(Oo=>{const kl=Oo.commentId!=null?String(Oo.commentId):null,hr=Oo.importedId!=null?String(Oo.importedId):null;return kl===ao||hr===ao}):null,Sl=ka?_n(ka):!1;ao&&An.has(ao)&&Sl&&(q=null,mt=!0)}}}Ee==="trackedChange"&&ae({superdoc:F.$superdoc,params:O}),mt&&q!=null&&Ru()&&(mt=!1),mt&&(q==null||!yl(q))&&vl(q),_t(()=>{B.value||(mt&&s.setActiveComment(F.$superdoc,q),mt&&(fe.value=!0,setTimeout(()=>{fe.value=!1},0)))}),typeof F.$superdoc.config.onCommentsUpdate=="function"&&F.$superdoc.config.onCommentsUpdate(O)},ri=Se(()=>!!wt.value),Ji=Se(()=>Array.isArray(a.value)?a.value.filter(O=>O?.type===Ul):[]),Wr=Se(()=>Ji.value.length>0),Of=Se(()=>Wr.value&&ri.value),Pu=Se(()=>new Set(Ji.value.map(O=>String(O.id)))),Ds=O=>typeof O=="number"?Number.isFinite(O):typeof O=="string"&&O.trim()!==""?Number.isFinite(Number(O)):!1,hc=O=>{const q=O?.selection?.selectionBounds;return!!q&&Ds(q.top)&&Ds(q.left)&&Ds(q.right)&&Ds(q.bottom)},Ff=O=>{const q=O?.fileId??O?.documentId??O?.selection?.documentId;return q!=null?String(q):null},x=O=>{const q=Pu.value;if(!q.size)return!1;const Ee=Ff(O);return Ee?q.has(Ee):q.size===1},D=O=>O?.selection?.source==="pdf"&&hc(O)&&x(O),ee=Se(()=>{if(!Wr.value)return!1;const O=J.value.some(Ee=>D(Ee)),q=D(B.value);return O||q}),ie=Se(()=>{const O=wt.value?.displayMode??"sidebar";return!y_.has(O)||O==="sidebar"?!0:O==="inline"?!1:O!=="auto"?!0:!St.value}),se=Se(()=>Dt.value&&!Ft.value&&!ee.value||!rt.value||!ie.value?!1:B.value||(J.value.length>0||Fe.value)&&l.value&&Ot.value&&ri.value&&!N.value),de=Se(()=>{if(se.value||!ri.value)return null;if(B.value)return B.value;if(!z.value)return null;const O=kt(z.value)??null;return Dt.value&&ie.value&&O?.trackedChange&&!ee.value?null:O}),{compactCommentPopoverStyle:pe,closeCompactCommentPopover:ve,resetClickAnchor:Xe}=B9({activeComment:z,pendingComment:B,activeCompactComment:de,showCommentsSidebar:se,superdocRoot:Ct,layers:Ot,documents:a,resolveCommentPositionEntry:Ie,selectionPosition:c,activeZoom:h,clearActiveComment:()=>s.setActiveComment(F.$superdoc,null),clearPendingComment:()=>s.removePendingComment(F.$superdoc)}),Qe=Se(()=>ri.value?c.value&&Vt.top&&!R.value?.readOnly:!1);Se(()=>ri.value?!R.value?.readOnly&&c.value:!1),Pt(se,O=>{F.$superdoc.broadcastSidebarToggle(O)}),NR({getSuperdoc:()=>F.$superdoc,superdocContainerWidth:We,isReady:l,activeZoom:h,zoomMode:m,viewportMetrics:g,showCommentsSidebar:se,rightSidebarRef:Bt,superdocRoot:Ct,documents:a});const tt=O=>{F.$superdoc.scrollToComment(O)},st=()=>{cc()};Rn(()=>{document.addEventListener("contextmenu",Zi,!0),document.addEventListener("keydown",vo,!0),F.$superdoc?.on?.("search:open",Gn),Zy(dn),Ct.value?.addEventListener("pointerdown",Bn,!0),Ct.value?.addEventListener("focusin",Bn,!0),typeof window<"u"&&(window.addEventListener("scroll",st,!0),window.addEventListener("resize",st,!0)),document.addEventListener("focusin",Eu,!0),document.addEventListener("pointerdown",Ls,!0),document.addEventListener("mousedown",dc,!0),document.addEventListener("pointerup",ei,!0),document.addEventListener("mouseup",ei,!0),document.addEventListener("selectionchange",ei),F.$superdoc?.on?.("document-mode-change",Ca),Nt(),cn()}),Pt(rt,O=>{Dt.value&&(O?un.value&&xs(un.value):(s.clearEditorCommentPositions?.(),Ft.value=!1))}),Pt(Ot,()=>{cc()});function vt(O){return(O.metaKey||O.ctrlKey)&&!O.altKey&&O.key?.toLowerCase?.()==="f"}function pt(O){return(O.metaKey||O.ctrlKey)&&O.shiftKey&&!O.altKey&&(O.code==="Digit8"||O.key==="8"||O.key==="*")}function it(){const O=Ct.value,q=document.activeElement;if(!(q instanceof Node))return!1;if(O?.contains(q))return!0;const Ee=F.$superdoc?.activeEditor?.view?.dom;return Ee instanceof Node&&(q===Ee||Ee.contains?.(q))}const dn={};function rn(O){vt(O)&&Te.value&&cM(O,{focusInside:it(),owner:dn})&&Et.wouldOpen()&&(O.preventDefault(),O.stopPropagation(),Zy(dn),Et.open())}function Bn(){Zy(dn)}function Gn(){Te.value&&Et.open()}function Wn(O){pt(O)&&(Dt.value||it()&&(O.preventDefault(),O.stopPropagation(),F.$superdoc.toggleFormattingMarks?.()))}function vo(O){if(O.key==="Escape"&&de.value){O.preventDefault(),O.stopPropagation(),ve();return}rn(O),!O.defaultPrevented&&Wn(O)}function Hn(O){rn(O),!O.defaultPrevented&&Wn(O)}ir(()=>{s.cancelImportedTrackedChangeBootstrap?.(),T.destroy(),Et.destroy(),Tt.destroy(),xi(),kr();for(const O of Array.from(yn.keys()))ro(O);for(const O of Array.from(xo.keys()))pi(O);for(const O of Array.from(Zo.keys()))As(O);yn.clear(),Kt.clear(),document.removeEventListener("contextmenu",Zi,!0),document.removeEventListener("keydown",vo,!0),F.$superdoc?.off?.("search:open",Gn),Ct.value?.removeEventListener("pointerdown",Bn,!0),Ct.value?.removeEventListener("focusin",Bn,!0),aM(dn),typeof window<"u"&&(window.removeEventListener("scroll",st,!0),window.removeEventListener("resize",st,!0)),Pe&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(Pe),Pe=0),sc(),lc.clear(),document.removeEventListener("focusin",Eu,!0),document.removeEventListener("pointerdown",Ls,!0),document.removeEventListener("mousedown",dc,!0),document.removeEventListener("pointerup",ei,!0),document.removeEventListener("mouseup",ei,!0),document.removeEventListener("selectionchange",ei),F.$superdoc?.off?.("document-mode-change",Ca)});const Mn=ne(null),Zn=ne(!1),bt=Se(()=>{if(!c.value||c.value.source==="document-editor")return{x:null,y:null};const O=c.value.source==="pdf"?(h.value??100)/100:1,q=c.value.top*O,Ee=c.value.left*O,Ne=c.value.right*O,mt=c.value.bottom*O;return{zIndex:500,borderRadius:"4px",top:q+"px",left:Ee+"px",height:Math.abs(q-mt)+"px",width:Math.abs(Ee-Ne)+"px"}}),zt=O=>{if(ue()&&!be()){Kn();return}if(!O.selectionBounds||!ri.value)return;Kn();const q=window.matchMedia("(max-width: 768px)").matches;if(oo({startX:O.selectionBounds.left,startY:O.selectionBounds.top,x:O.selectionBounds.right,y:O.selectionBounds.bottom,source:O.source}),!c.value)return;const Ee=Math.abs(c.value.left-c.value.right)>5,Ne=Math.abs(c.value.top-c.value.bottom)>5;if(!Ee||!Ne){Mn.value?.style&&(Mn.value.style.pointerEvents="none"),Kn();return}d.value=O;const mt=O.source==="pdf"||O.source?.value==="pdf"?(h.value??100)/100:1;Vt.top=O.selectionBounds.top*mt+"px",Vt.right=q?"0":"-25px"},Kn=()=>{c.value=null,Vt.top=null},oo=({startX:O,startY:q,x:Ee,y:Ne,source:mt,page:nn})=>{if(!(typeof O=="number"||typeof q=="number")&&!(typeof Ee=="number"||typeof Ne=="number")){Kn();return}if(!c.value){if(q==null||O==null)return;c.value={top:q,left:O,right:O,bottom:q,startX:O,startY:q,source:mt,page:nn??null}}typeof O=="number"&&(c.value.startX=O),typeof q=="number"&&(c.value.startY=q),typeof Ne=="number"&&(Ne<c.value.startY?c.value.top=Ne:c.value.bottom=Ne),typeof Ee=="number"&&(Ee<c.value.startX?c.value.left=Ee:c.value.right=Ee)},fr=O=>{const q=O?.clientX,Ee=O?.clientY;if(typeof q!="number"||typeof Ee!="number")return null;const Ne=document.elementsFromPoint(q,Ee).find(mt=>mt?.dataset?.pdfPage!=null);if(Ne){const mt=Number(Ne.dataset?.pageNumber);return Number.isFinite(mt)?mt:null}return null},$i=O=>{Kn(),Mn.value.style.pointerEvents="auto",_t(()=>{Zn.value=!0,Mn.value.style.pointerEvents="none";const q=fr(O);if(Mn.value.style.pointerEvents="auto",!q){Zn.value=!1,Mn.value.style.pointerEvents="none";return}const Ee=Mn.value.getBoundingClientRect(),Ne=h.value/100;oo({startX:(O.clientX-Ee.left)/Ne,startY:(O.clientY-Ee.top)/Ne,page:q,source:"pdf"}),Mn.value.addEventListener("mousemove",gi)})},gi=O=>{if(!Zn.value)return;const q=Mn.value.getBoundingClientRect(),Ee=h.value/100;oo({x:(O.clientX-q.left)/Ee,y:(O.clientY-q.top)/Ee})},yo=O=>{if(!Zn.value||(Mn.value.removeEventListener("mousemove",gi),!c.value))return;const q=c.value.page??fr(O);zt(Qd({selectionBounds:{top:c.value.top,left:c.value.left,right:c.value.right,bottom:c.value.bottom},page:q??1,documentId:a.value[0].id,source:"pdf"})),Mn.value.style.pointerEvents="none"},wl=Se(()=>{if(!F.$superdoc.uiConfig.comments.enabled)return!1;const O=F.$superdoc.config.modules?.comments;return!O||O===!1?!1:!O.readOnly}),Ps=ne(!1),oi=O=>O&&typeof O=="object"&&"value"in O?O.value:O,vi=O=>{if(!Dt.value||!O||O.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||F.$superdoc.config.viewOptions?.layout==="web"||F.$superdoc.uiConfig.ruler.suppressed||!oi(O.rulers)||!Ps.value)return!1;const q=F.$superdoc?.activeEditor;if(!q||q.editorVersion!==2)return!1;const Ee=oi(O.id),Ne=q.documentId??q.options?.documentId??null;return Ee&&Ne&&Ee!==Ne?!1:!!(q.pageMetrics&&q.pageLayout)},io=ne({});let Do=null,yi=null;const Vo=()=>{const O=F.$superdoc?.config?.rulerContainer;return O?typeof O=="string"?(typeof document<"u"?document:globalThis.document)?.querySelector(O)??null:typeof HTMLElement<"u"&&O instanceof HTMLElement?O:null:null},Cl=()=>{const O=F.$superdoc?.activeEditor?.documentId??F.$superdoc?.activeEditor?.options?.documentId??null,q=O==null?ti:Lo.get(String(O))??null;return q?.isConnected?(Array.from(q.children).find(Ee=>Ee.dataset?.v2PaintWrapper==="true")??q).getBoundingClientRect():null},es=()=>{if(!Dt.value){io.value={};return}const O=Vo();if(!O){io.value={};return}const q=Cl();if(!q){io.value={};return}const Ee=O.getBoundingClientRect(),Ne=Math.max(0,q.left-Ee.left),mt=Math.max(0,Ee.right-q.right);io.value={paddingLeft:`${Ne}px`,paddingRight:`${mt}px`}},Ri=()=>{try{Do?.disconnect()}catch{}Do=null;try{yi?.disconnect()}catch{}yi=null},Os=()=>{if(Ri(),typeof ResizeObserver>"u")return;const O=Ot.value,q=Vo();O&&(Do=new ResizeObserver(()=>es()),Do.observe(O)),q&&(yi=new ResizeObserver(()=>es()),yi.observe(q))},bo=(O,q)=>{!O||!q||(O.documentMarginsLastChange=q.pageMargins??null,F.$superdoc.emit("page-margins-change",{documentId:O.id,editorVersion:2,sectionId:q.sectionId,sectionIndex:q.sectionIndex,side:q.side,value:q.value,pageMargins:q.pageMargins}))},ts=O=>{ri.value&&(Kn(),Zn.value=!0,$i(O))},Ou=({selectionBounds:O,documentId:q,page:Ee})=>{!O||!q||zt(Qd({selectionBounds:O,documentId:q,page:Ee,source:"pdf"}))},_l=O=>{Ot.value?.querySelectorAll(".superdoc__sub-document")?.forEach(q=>{q.querySelector(".sd-pdf-viewer")||(O===1?(q.style.transformOrigin="",q.style.transform="",q.style.width=""):(q.style.transformOrigin="top left",q.style.transform=`scale(${O})`,q.style.width=`${100/O}%`))})};let _a=!1;const ht=()=>{if(_a||F.$superdoc.config.useLayoutEngine!==!1)return;const O=(h.value??100)/100;O!==1&&(_a=!0,_t(()=>_l(O)))};Pt(()=>h.value,O=>{const q=(O??100)/100,Ee=O??100,Ne=F.$superdoc?.activeEditor?.pageMetrics??null;if(Dt.value&&F.$superdoc?.activeEditor?.editorVersion===2&&Ne?.setZoom)try{Ne.setZoom(Ee)}catch(mt){console.warn("[SuperDoc][v2] setZoom failed",mt)}else _a=!0,_l(q);Po()?.updateScale(q),_t(()=>{Sa(),Li()})}),Pt(J,()=>{le.value||(le.value=!0)});const{whiteboardModuleConfig:Fu,whiteboard:qt,whiteboardPages:pc,whiteboardPageSizes:Qt,whiteboardPageOffsets:Ln,whiteboardEnabled:Nn,whiteboardOpacity:Mi,handleWhiteboardPageReady:ns,updateWhiteboardPageSizes:Sa,updateWhiteboardPageOffsets:Li}=t9({proxy:F,layers:Ot,documents:a,modules:w}),Po=()=>Array.isArray(on.value)?on.value[0]:on.value,Di=Se(()=>Wr.value&&!!Fu.value),tb=Se(()=>Nn.value);return(O,q)=>(me(),_e("div",{ref_key:"superdocRoot",ref:Ct,class:en(["superdoc",{"superdoc--with-sidebar":se.value,"superdoc--web-layout":Ge(F).$superdoc.config.viewOptions?.layout==="web","superdoc--contained":Ge(F).$superdoc.config.contained,"high-contrast":Ge(K)}]),style:vn(Zt.value),onKeydown:Hn},[an.value?(me(),_e("p",PD,Ht(an.value),1)):ut("",!0),Le("div",{class:"superdoc__layers layers",ref_key:"layers",ref:Ot,role:"group"},[Qe.value?(me(),_e("div",{key:0,class:"superdoc__tools tools",style:vn(Vt)},[Le("div",{class:"tools-item","data-id":"is-tool",onMousedown:q[0]||(q[0]=Jt(Ee=>_r("comments"),["stop","prevent"]))},[Le("div",{class:"superdoc__tools-icon",innerHTML:Ge(ua).comment},null,8,OD)],32)],4)):ut("",!0),Le("div",FD,[ri.value?(me(),_e("div",{key:0,class:"superdoc__selection-layer selection-layer",onMousedown:$i,onMouseup:yo,ref_key:"selectionLayer",ref:Mn},[Ge(c)&&wl.value?(me(),_e("div",{key:0,style:vn(bt.value),class:"superdoc__temp-selection temp-selection sd-highlight sd-initial-highlight"},null,4)):ut("",!0)],544)):ut("",!0),(me(!0),_e(Wt,null,or(Ge(a),Ee=>(me(),_e("div",{class:"superdoc__sub-document sub-document",key:`${Ee.id}:${Ee.editorMountNonce}`,ref_for:!0,ref:Ne=>Wi(Ee,Ne)},[Ee.type===Ge("application/pdf")?(me(),fn(Ge(n),{key:0,file:Ee.data,"file-id":Ee.id,"initial-scale":(Ge(h)??100)/100,config:Ge(ur),onSelectionRaw:Ou,onBypassSelection:ts,onPageRendered:Ge(ns),onDocumentReady:q[1]||(q[1]=({documentId:Ne,viewerContainer:mt})=>$t(Ne,mt)),ref_for:!0,ref_key:"pdfViewerRef",ref:on},null,8,["file","file-id","initial-scale","config","onPageRendered"])):ut("",!0),Ee.type===Ge("application/vnd.openxmlformats-officedocument.wordprocessingml.document")&&Ge(G)&&vi(Ee)?(me(),_e(Wt,{key:1},[Ge(F).$superdoc.config.rulerContainer?(me(),fn(Oa,{key:0,to:Ge(F).$superdoc.config.rulerContainer},[Le("div",{class:"v2-ruler-host",style:vn(io.value)},[Gt(Ge(G),{"page-layout":Ge(F).$superdoc.activeEditor.pageLayout,"measurement-unit":Ge(p),onPageMarginsChange:Ne=>bo(Ee,Ne)},null,8,["page-layout","measurement-unit","onPageMarginsChange"])],4)],8,["to"])):(me(),_e("div",{key:1,class:"v2-ruler-host",style:vn(io.value)},[Gt(Ge(G),{"page-layout":Ge(F).$superdoc.activeEditor.pageLayout,"measurement-unit":Ge(p),onPageMarginsChange:Ne=>bo(Ee,Ne)},null,8,["page-layout","measurement-unit","onPageMarginsChange"])],4))],64)):ut("",!0),Ee.type===Ge("application/vnd.openxmlformats-officedocument.wordprocessingml.document")?(me(),fn(Ge(V),{key:2,"file-source":Ee.data,"document-id":Ee.id,options:Pf(Ee),"measurement-unit":Ge(p),onV2EditorReady:Ki,onV2EditorFailed:uc,onV2Render:Mf,onV2RenderCleared:ku,onV2RenderReadiness:Ts,onV2SelectionChanged:ul,onV2HostEvent:Ne=>Au(Ee,Ne),onV2LinkClick:Lf,onV2PageMetrics:Su},null,8,["file-source","document-id","options","measurement-unit","onV2HostEvent"])):ut("",!0),Ee.type===Ge("text/html")?(me(),fn(y9,{key:3,onReady:q[2]||(q[2]=Ne=>$t(Ne,null)),onSelectionChange:zt,"file-source":Ee.data,"document-id":Ee.id},null,8,["file-source","document-id"])):ut("",!0)]))),128)),Di.value?(me(),fn(s9,{key:1,class:"superdoc__whiteboard-layer",whiteboard:Ge(qt),pages:Ge(pc),"page-sizes":Ge(Qt),"page-offsets":Ge(Ln),enabled:Ge(Nn),interactive:tb.value,opacity:Ge(Mi)},null,8,["whiteboard","pages","page-sizes","page-offsets","enabled","interactive","opacity"])):ut("",!0),Of.value?(me(),fn(e9,{key:2,onAnchorActivate:po})):ut("",!0)])],512),se.value?(me(),_e("div",{key:1,ref_key:"rightSidebarRef",ref:Bt,class:"superdoc__right-sidebar right-sidebar"},[Le("div",BD,[Ge(le)&&(J.value.length>0||Ge(B))?(me(!0),_e(Wt,{key:0},or(Ge(M),Ee=>(me(),fn(qR,{parent:Ot.value,"current-document":Ee},null,8,["parent","current-document"]))),256)):ut("",!0)])],512)):ut("",!0),de.value?(me(),_e("div",{key:2,class:"superdoc__compact-comment-popover",style:vn(Ge(pe))},[Gt(gp,{comment:de.value,parent:Ot.value},null,8,["comment","parent"])],4)):ut("",!0),Gt(wD,{"geometry-target":Ot.value},null,8,["geometry-target"])],38))}},UD=hn(HD,[["__scopeId","data-v-2a7bfa95"]]);It();var QS="devtools-plugin:setup",ZS="dev.esm.pinia",ln={disabledAppRefCounts:new Map,hook:null,originalHookEmit:null,isHookPropertyPatched:!1,originalHookPropertyDescriptor:null,hookPropertyValue:void 0,isQueuePropertyPatched:!1,originalQueuePropertyDescriptor:null,queuePropertyValue:void 0,queue:null,originalQueuePush:null},JS=(e,t)=>e===QS&&t?.id===ZS&&t?.app&&ln.disabledAppRefCounts.has(t.app),VD=e=>Array.isArray(e)&&JS(QS,e[0]),jD=e=>{if(ln.isQueuePropertyPatched){ln.queuePropertyValue=e;return}globalThis.__VUE_DEVTOOLS_PLUGINS__=e},GD=e=>{const t=globalThis.__VUE_DEVTOOLS_PLUGINS__;if(Array.isArray(t))for(let n=t.length-1;n>=0;n--){const[r]=t[n];r?.id===ZS&&r?.app===e&&t.splice(n,1)}},$S=()=>{const{queue:e,originalQueuePush:t}=ln;e&&typeof t=="function"&&(e.push=t),ln.queue=null,ln.originalQueuePush=null},e4=()=>{const{hook:e,originalHookEmit:t}=ln;e&&typeof t=="function"&&(e.emit=t),ln.hook=null,ln.originalHookEmit=null},rf=()=>{const e=globalThis.__VUE_DEVTOOLS_PLUGINS__;if(e==null){jD([]),rf();return}if(!Array.isArray(e))return;const t=e;if(ln.queue===t)return;$S();const n=t.push;typeof n=="function"&&(ln.queue=t,ln.originalQueuePush=n,t.push=function(...o){const i=o.filter(s=>!VD(s));return i.length===0?this.length:n.apply(this,i)})},WD=()=>{if(ln.isQueuePropertyPatched){rf();return}const e=Object.getOwnPropertyDescriptor(globalThis,"__VUE_DEVTOOLS_PLUGINS__");if(e?.configurable===!1){rf();return}ln.originalQueuePropertyDescriptor=e??null,ln.queuePropertyValue=globalThis.__VUE_DEVTOOLS_PLUGINS__,Object.defineProperty(globalThis,"__VUE_DEVTOOLS_PLUGINS__",{configurable:!0,enumerable:e?.enumerable??!0,get(){return ln.queuePropertyValue},set(t){ln.queuePropertyValue=t,rf()}}),ln.isQueuePropertyPatched=!0,rf()},KD=()=>{if(!ln.isQueuePropertyPatched)return;const{queuePropertyValue:e,originalQueuePropertyDescriptor:t}=ln;delete globalThis.__VUE_DEVTOOLS_PLUGINS__,t?"value"in t?Object.defineProperty(globalThis,"__VUE_DEVTOOLS_PLUGINS__",{configurable:t.configurable,enumerable:t.enumerable,writable:t.writable,value:e}):(Object.defineProperty(globalThis,"__VUE_DEVTOOLS_PLUGINS__",t),typeof t.set=="function"&&t.set.call(globalThis,e)):e!==void 0&&(globalThis.__VUE_DEVTOOLS_PLUGINS__=e),ln.isQueuePropertyPatched=!1,ln.originalQueuePropertyDescriptor=null,ln.queuePropertyValue=void 0},kp=()=>{const e=globalThis?.__VUE_DEVTOOLS_GLOBAL_HOOK__;if(!e||typeof e.emit!="function"||ln.hook===e)return;e4();const t=e.emit;ln.hook=e,ln.originalHookEmit=t,e.emit=function(r,...o){const[i]=o;if(!JS(r,i))return t.call(this,r,...o)}},qD=()=>{if(ln.isHookPropertyPatched){kp();return}const e=Object.getOwnPropertyDescriptor(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__");if(e?.configurable===!1){kp();return}ln.originalHookPropertyDescriptor=e??null,ln.hookPropertyValue=globalThis.__VUE_DEVTOOLS_GLOBAL_HOOK__,Object.defineProperty(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__",{configurable:!0,enumerable:e?.enumerable??!0,get(){return ln.hookPropertyValue},set(t){ln.hookPropertyValue=t,kp()}}),ln.isHookPropertyPatched=!0,kp()},YD=()=>{if(!ln.isHookPropertyPatched)return;const{hookPropertyValue:e,originalHookPropertyDescriptor:t}=ln;delete globalThis.__VUE_DEVTOOLS_GLOBAL_HOOK__,t?"value"in t?Object.defineProperty(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__",{configurable:t.configurable,enumerable:t.enumerable,writable:t.writable,value:e}):(Object.defineProperty(globalThis,"__VUE_DEVTOOLS_GLOBAL_HOOK__",t),typeof t.set=="function"&&t.set.call(globalThis,e)):e!==void 0&&(globalThis.__VUE_DEVTOOLS_GLOBAL_HOOK__=e),ln.isHookPropertyPatched=!1,ln.originalHookPropertyDescriptor=null,ln.hookPropertyValue=void 0},XD=()=>{ln.disabledAppRefCounts.size>0||(e4(),YD(),$S(),KD())},QD=(e,t)=>{if(!t)return()=>{};const n=ln.disabledAppRefCounts.get(e)??0;return ln.disabledAppRefCounts.set(e,n+1),qD(),WD(),()=>{const r=ln.disabledAppRefCounts.get(e);r&&(r===1?ln.disabledAppRefCounts.delete(e):ln.disabledAppRefCounts.set(e,r-1),XD())}};const ZD=({disablePiniaDevtools:e=!1}={})=>{const t=Hl(UD),n=m6(),r=QD(t,e);let o,i,s;try{t.use(n),e&&GD(t),t.directive("click-outside",Fv),o=nu(),i=ca(),s=zi()}catch(a){throw r(),a}if(typeof t.unmount=="function"){const a=t.unmount.bind(t);t.unmount=(...l)=>(r(),a(...l))}return{app:t,pinia:n,superdocStore:o,commentsStore:i,highContrastModeStore:s}};var JD={docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",pdf:"application/pdf",zip:"application/zip",html:"text/html",txt:"text/plain;charset=utf-8",json:"application/json"},$D=e=>!e||typeof e.toLowerCase!="function"?"application/octet-stream":JD[e.toLowerCase()]||"application/octet-stream",eP=(e,t)=>{if(e instanceof Blob)return e;const n=$D(t);if(e instanceof ArrayBuffer)return new Blob([e],{type:n});if(ArrayBuffer.isView(e)){const{buffer:r,byteOffset:o,byteLength:i}=e,s=r.slice(o,o+i);return new Blob([s],{type:n})}if(typeof e=="string")return new Blob([e],{type:n});throw e==null?new TypeError("createDownload requires a Blob, ArrayBuffer, or ArrayBufferView."):new TypeError(`Cannot create download from value of type ${typeof e}`)};const t4=(e,t,n)=>{const r=eP(e,n);if(typeof URL>"u"||typeof URL.createObjectURL!="function"||typeof document>"u"||typeof document.createElement!="function")return r;const o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${t}.${n}`;const s=document.body&&typeof document.body.appendChild=="function";return s&&document.body.appendChild(i),i.click(),s&&document.body.removeChild(i),typeof URL.revokeObjectURL=="function"&&setTimeout(()=>URL.revokeObjectURL(o),0),r},n4=e=>{const t=e.toLowerCase();return t.endsWith(".docx")?e.slice(0,-5):t.endsWith(".pdf")?e.slice(0,-4):e};var tP=class{#t=new Map;#n=1;idFor(e){const t=this.#t.get(e);if(t!==void 0)return t;const n=this.#n++;return this.#t.set(e,n),n}has(e){return this.#t.has(e)}};function nP(e){const t=typeof e.email=="string"&&e.email.length>0?e.email:null;return t?`email:${t}`:`label:${e.actorLabel}`}function rP(e,t){const n=e.displayName??null,r=e.email??null,o={clientId:t};return n&&(o.name=n),r&&(o.email=r),typeof e.color=="string"&&e.color.length>0&&(o.color=e.color),o}function oP(e){const t={clientId:0};e?.id!=null&&(t.id=e.id),e?.name!=null&&(t.name=e.name),e?.email!=null&&(t.email=e.email);const n=e?.color;return typeof n=="string"&&n.length>0&&(t.color=n),t}function iP(e){const t=new tP;let n=new Set;return{registry:t,next(r){const o=[],i=new Set,s=new Set;for(const u of r.remoteActors){const c=nP(u);if(s.has(c))continue;s.add(c);const d=t.idFor(c);i.add(d),o.push(rP(u,d))}const a=[];for(const u of i)n.has(u)||a.push(u);const l=[];for(const u of n)i.has(u)||l.push(u);return n=i,{states:[oP(e()),...o],added:a,removed:l}}}}var sP=class{#t=new Map;on(e,t){const n=this.#t.get(e);n?n.push(t):this.#t.set(e,[t])}emit(e,...t){const n=this.#t.get(e);if(n)for(const r of n)r.apply(this,t)}off(e,t){const n=this.#t.get(e);n&&(t?this.#t.set(e,n.filter(r=>r!==t)):this.#t.delete(e))}once(e,t){const n=(...r)=>{this.off(e,n),t.apply(this,r)};this.on(e,n)}removeAllListeners(){this.#t=new Map}};function aP(e){return e.flatMap(t=>[t[0],t[1]])}function r4(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function o4(e={}){const{value:t="",left:n,top:r,width:o,height:i,fontSize:s=16,fontFamily:a="Arial, sans-serif",color:l="#000",background:u="transparent",resize:c="none"}=e,d=document.createElement("textarea");d.value=t;const h=d.style;return h.position="absolute",n!=null&&(h.left=`${n}px`),r!=null&&(h.top=`${r}px`),o!=null&&(h.width=typeof o=="number"?`${o}px`:o),i!=null&&(h.height=typeof i=="number"?`${i}px`:i),h.minWidth=120,h.fontSize=typeof s=="number"?`${s}px`:s,h.fontFamily=a,h.color=l,h.background=u,h.border="2px solid #3c97fe80",h.padding="2px 4px",h.margin="0",h.zIndex="1000",h.overflow="hidden",h.resize=c,h.outline="none",d}var Ap=18,lP=class{pageIndex=null;strokes=[];text=[];images=[];size=null;originalSize=null;#t=null;#n=null;#e=null;#i=null;#s=null;#a=null;#u=new Set;#d=!1;#l=null;#f=[];#m=null;#o="select";#r=!1;#p=null;#y="#2293fb";#w=5;#_=null;#S=null;constructor(e){this.#E(e)}#E(e){this.#t=e.Renderer,this.#r=e.enabled,this.pageIndex=e.pageIndex,this.#_=e.onChange,this.#S=e.onToolChange}#x(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{xN:e/n,yN:t/r}}#M(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{x:e*n,y:t*r}}#c(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{wN:e/n,hN:t/r}}#L(e,t){const n=this.size?.width||1,r=this.size?.height||1;return{width:e*n,height:t*r}}#T(e){const{width:t=1,height:n=1}=this.size||{};return{points:(Array.isArray(e.pointsN)?e.pointsN:[]).map(r=>[r[0]*t,r[1]*n]),strokeWidth:Number.isFinite(e.widthN)?e.widthN*((t+n)/2):this.#w}}#D(e){const{width:t=1,height:n=1}=this.size||{};return{pointsN:(Array.isArray(e.points)?e.points:[]).map(r=>[r[0]/t,r[1]/n]),widthN:Number.isFinite(e.width)?e.width/((t+n)/2):void 0}}#k(e){const{width:t=1,height:n=1}=this.size||{};return{x:(e.xN??0)*t,y:(e.yN??0)*n,width:Number.isFinite(e.widthN)?e.widthN*t:void 0,fontSize:Number.isFinite(e.fontSizeN)?e.fontSizeN*n:Ap}}#g(e){const{width:t=1,height:n=1}=this.size||{},r=this.originalSize?.height??n;return{xN:(e.x??0)/t,yN:(e.y??0)/n,widthN:Number.isFinite(e.width)?e.width/t:null,fontSizeN:Number.isFinite(e.fontSize)?e.fontSize/r:Ap/r}}#j(e){const{width:t=1,height:n=1}=this.size||{};return{x:(e.xN??0)*t,y:(e.yN??0)*n,width:Number.isFinite(e.widthN)?e.widthN*t:void 0,height:Number.isFinite(e.heightN)?e.heightN*n:void 0}}#G(e){const{width:t=1,height:n=1}=this.size||{};return{xN:(e.x??0)/t,yN:(e.y??0)/n,widthN:Number.isFinite(e.width)?e.width/t:null,heightN:Number.isFinite(e.height)?e.height/n:null}}#P(){const e=this.size?.width,t=this.originalSize?.width??e;return!Number.isFinite(e)||!Number.isFinite(t)||!t?1:e/t}#O(){!this.#n||!this.#e||(this.#n.on("mousedown touchstart",e=>{this.#Y(e)}),this.#n.on("mousemove touchmove",e=>{this.#X(e)}),this.#n.on("mouseup touchend",e=>{this.#I(e)}),this.#n.on("click tap",e=>{this.#R(e)}),window.addEventListener("keydown",this.#q))}setTool(e){this.#o=e,this.#C(),this.#A(),this.render()}getTool(){return this.#o}setEnabled(e){this.#r=!!e,this.#C(),this.#A(),this.render()}isEnabled(){return this.#r}setSize(e){if(!e)return;const{width:t,height:n,originalWidth:r,originalHeight:o}=e;this.size={width:t,height:n},this.originalSize={width:r??null,height:o??null}}resize(e,t){this.#n&&(this.#n.size({width:e,height:t}),this.#F(),this.render())}mount(e){if(!e||this.#n&&this.#a===e)return;this.#n&&this.destroy();const t=this.size?.width||e.clientWidth||1,n=this.size?.height||e.clientHeight||1;this.#a=e,this.#n=new this.#t.Stage({container:e,width:t,height:n}),this.#e=new this.#t.Layer,this.#i=new this.#t.Layer,this.#n.add(this.#e),this.#n.add(this.#i),this.#F(),this.#C(),this.#O(),this.render()}render(){this.#e&&(this.#s&&(this.#s.destroy(),this.#s=null),this.#e.find(".wb-text").forEach(e=>e.destroy()),this.#i.destroyChildren(),this.renderStrokes(),this.renderText(),this.renderImages(),this.#e.batchDraw(),this.#i.batchDraw())}#F(){const e=Math.min(window.devicePixelRatio||1,1.5);this.#e?.getCanvas&&this.#e.getCanvas().setPixelRatio(e),this.#i?.getCanvas&&this.#i.getCanvas().setPixelRatio(e)}#C(){if(!this.#i)return;const e=this.#o==="draw"||this.#o==="erase",t=!!(this.#r&&e);this.#i.listening(t)}renderStrokes(){this.strokes.forEach(e=>{const{points:t,strokeWidth:n}=this.#T(e),r=new this.#t.Line({points:aP(t),stroke:e.color||this.#y,strokeWidth:n,lineCap:"round",lineJoin:"round",globalCompositeOperation:e.type==="erase"?"destination-out":"source-over"});r.name("wb-stroke"),this.#i.add(r)})}renderText(){this.text.forEach(e=>{const{x:t,y:n,width:r,fontSize:o}=this.#k(e),i=new this.#t.Text({x:t,y:n,text:e.content,fontSize:o,fontFamily:"Arial, sans-serif",fill:"#2293fb",draggable:this.#o==="select",width:r});i.name("wb-text"),i._whiteboardId=e.id,this.#W(i,e),this.#e.add(i)})}#W(e,t){e.on("click tap",n=>{this.#o!=="select"||!this.#r||(n.cancelBubble=!0,this.#B(e))}),e.on("dragend",()=>{const{xN:n,yN:r}=this.#g({x:e.x(),y:e.y(),fontSize:t.fontSizeN?t.fontSizeN*(this.size?.height||1):Ap,width:t.widthN?t.widthN*(this.size?.width||1):null});t.xN=n,t.yN=r,this.#v()}),e.on("transform",()=>{e.scaleY(1),e.setAttrs({width:e.width()*e.scaleX(),scaleX:1})}),e.on("transformend",()=>{e.setAttrs({width:Math.max(1,e.width()*e.scaleX()),scaleX:1,scaleY:1});const n=e.width(),r=this.size?.width||1;t.widthN=n/r,t.xN=e.x()/r,t.yN=e.y()/(this.size?.height||1),this.#v()}),e.on("dblclick dbltap",n=>{this.#o!=="select"||!this.#r||(n.cancelBubble=!0,this.#z(e,t))})}renderImages(){const e=this.#e?.find(".wb-image")??[],t=new Map;e.forEach(o=>{t.set(o._whiteboardId,o)});const n=new Set(this.images.map(o=>o.id));e.forEach(o=>{n.has(o._whiteboardId)||o.destroy()});const r=(o,i)=>{const{x:s,y:a,width:l,height:u}=this.#j(o),c=t.get(o.id);if(c){Number.isFinite(s)&&c.x(s),Number.isFinite(a)&&c.y(a),Number.isFinite(l)&&c.width(l),Number.isFinite(u)&&c.height(u),c.draggable(this.#o==="select");return}if(this.#u.has(o.id))return;this.#u.add(o.id);const d=new window.Image;d.crossOrigin="Anonymous",d.onload=()=>{if(t.get(o.id)){this.#u.delete(o.id);return}if(!this.#e){this.#u.delete(o.id);return}const h=new this.#t.Image({x:s,y:a,image:d,width:l??d.width,height:u??d.height,draggable:this.#o==="select"});h.name(i),h._whiteboardId=o.id,this.#K(h,o),this.#e.add(h),this.#e.batchDraw(),this.#u.delete(o.id)},d.onerror=()=>{this.#u.delete(o.id)},d.src=o.src};this.images.forEach(o=>r(o,"wb-image"))}#K(e,t){e.on("click tap",n=>{this.#o!=="select"||!this.#r||(n.cancelBubble=!0,this.#B(e))}),e.on("dragend",()=>{const n=this.size?.width||1,r=this.size?.height||1;t.xN=e.x()/n,t.yN=e.y()/r,this.#v()}),e.on("transformend",()=>{const n=e.scaleX(),r=e.scaleY(),o=Math.max(1,e.width()*n),i=Math.max(1,e.height()*r);e.scale({x:1,y:1}),e.width(o),e.height(i);const s=this.size?.width||1,a=this.size?.height||1;t.widthN=o/s,t.heightN=i/a,t.xN=e.x()/s,t.yN=e.y()/a,this.#v()})}destroy(){this.#n&&this.#n.destroy(),this.#n=null,this.#e=null,this.#i=null,this.#a=null,this.#d=!1,this.#l=null,this.#f=[],this.#p=null,this.#s=null,window.removeEventListener("keydown",this.#q)}toJSON(){return{strokes:this.strokes,text:this.text,images:this.images}}applyData(e={}){const t=Array.isArray(e.strokes)?e.strokes:[],n=Array.isArray(e.text)?e.text:[],r=Array.isArray(e.images)?e.images:[];this.strokes=t,this.text=n,this.images=r,this.render()}#v(){this.#_&&this.#_()}addStroke(e){if(!e||!Array.isArray(e.points))return;const{pointsN:t,widthN:n}=this.#D(e);this.strokes.push({pointsN:t,widthN:n,color:e.color,type:e.type})}addText(e){if(!e||typeof e.content!="string")return;const{xN:t,yN:n,widthN:r,fontSizeN:o}=this.#g(e);this.text.push({id:e.id??r4("text"),xN:t,yN:n,content:e.content,fontSizeN:o,widthN:r}),this.render(),this.#v()}addImage(e){if(!e||!e.src)return;const{xN:t,yN:n,widthN:r,heightN:o}=this.#G(e),i={id:e.id??r4("image"),stickerId:e.stickerId??(e.type==="sticker"?e.id??null:null),xN:t,yN:n,src:e.src,widthN:r,heightN:o,type:e.type??"image"};this.images.push(i),this.render(),this.#v()}#A(){this.#s&&(this.#s.destroy(),this.#s=null,this.#p=null,this.#e?.batchDraw())}#B(e){if(!this.#e)return;this.#p=e;const t=e.name&&e.name()==="wb-text",n=t?["middle-left","middle-right"]:["top-left","top-right","bottom-left","bottom-right"],r=(o,i)=>i.width<20?o:t?{...i,height:o.height,y:o.y}:i.height<20?o:i;this.#s?(this.#s.nodes([e]),this.#s.enabledAnchors(n),this.#s.boundBoxFunc(r)):(this.#s=new this.#t.Transformer({nodes:[e],enabledAnchors:n,rotateEnabled:!1,keepRatio:!1,boundBoxFunc:r}),this.#e.add(this.#s)),this.#e.batchDraw()}#h(){if(!this.#p)return;const e=this.#p,t=e.name&&e.name(),n={"wb-text":()=>{const r=e._whiteboardId;this.text=this.text.filter(o=>o.id!==r)},"wb-image":()=>{const r=e._whiteboardId;this.images=this.images.filter(o=>o.id!==r)}}[t];n&&n(),e.destroy(),this.#A(),this.render()}#q=e=>{if(!this.#p||!this.#r||this.#o!=="select")return;const t=e.target?.tagName;t==="INPUT"||t==="TEXTAREA"||(e.key==="Backspace"||e.key==="Delete")&&(e.preventDefault(),this.#h(),this.#v())};#R(e){if(!this.#r||!this.#n)return;const t={text:()=>{const n=this.#n.getPointerPosition();n&&this.#N(n.x,n.y)},select:()=>{e?.target===this.#n&&this.#A()}}[this.#o];t&&t()}#Y(){if(!this.#r||this.#o!=="draw"&&this.#o!=="erase")return;this.#d=!0;const e=this.#n.getPointerPosition();if(!e)return;const t=this.#o==="erase",n=this.#w*this.#P();this.#f=[e.x,e.y],this.#l=new this.#t.Line({points:this.#f,stroke:this.#y,strokeWidth:t?n*3:n,lineCap:"round",lineJoin:"round",globalCompositeOperation:t?"destination-out":"source-over"}),this.#m=n,this.#i.add(this.#l)}#X(){if(!this.#r||this.#o!=="draw"&&this.#o!=="erase"||!this.#d||!this.#l)return;const e=this.#n.getPointerPosition();e&&(this.#f.push(e.x,e.y),this.#l.points(this.#f),this.#i.batchDraw())}#I(){if(!this.#r||this.#o!=="draw"&&this.#o!=="erase"||!this.#d||!this.#l)return;this.#d=!1;const e=[];for(let r=0;r<this.#f.length;r+=2)e.push([this.#f[r],this.#f[r+1]]);const t=this.#o==="erase",n=this.#m??this.#w;this.addStroke({points:e,color:this.#y,width:t?n*3:n,type:t?"erase":"draw"}),this.#v(),this.#l=null,this.#f=[],this.#m=null}#N(e,t){if(!this.#a)return;const n=Ap*this.#P(),r=o4({left:e,top:t,height:Math.ceil(n*1.4),background:"transparent",fontSize:n,color:"#2293fb"});this.#a.append(r),r.focus(),r.select();let o=!1;const i=()=>{if(o)return;o=!0;const s=r.value.trim();s&&(this.addText({x:e,y:t,content:s}),this.#o==="text"&&this.#S&&this.#S("select")),r.parentNode===this.#a&&this.#a.removeChild(r)};r.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i()),s.key==="Escape"&&(s.preventDefault(),i())}),r.addEventListener("blur",i)}#z(e,t){if(!this.#a||!this.#n)return;this.#A();const n=e.position(),r=o4({value:e.text(),left:n.x,top:n.y,width:Math.max(e.width(),120),height:Math.max(e.height(),24),fontSize:e.fontSize(),fontFamily:e.fontFamily(),color:e.fill?e.fill():"#2293fb",background:"white",resize:"both"});this.#a.appendChild(r),r.focus(),r.select();let o=!1;const i=()=>{if(o)return;o=!0;const s=r.value.trim();s&&(e.text(s),t.content=s,this.#e.batchDraw(),this.#v()),r.parentNode&&r.parentNode.removeChild(r)};r.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i()),s.key==="Escape"&&(s.preventDefault(),i())}),r.addEventListener("blur",i)}},cP=class extends sP{#t=null;#n=null;#e=new Map;#i=new Map;#s="select";#a=!1;#u=1;#d=null;#l=null;#f=null;constructor(e={}){super(),this.#m(e)}#m(e){this.#t=e.Renderer,this.#n=e.superdoc,this.#a=e.enabled,this.#d=e.onChange,this.#l=e.onSetData,this.#f=e.onEnabledChange}register(e,t){this.#i.set(e,t)}getType(e){return this.#i.get(e)}setTool(e){this.#s=e,this.#e.forEach(t=>t.setTool(e)),this.emit("tool",e)}getTool(){return this.#s}setEnabled(e){this.#a=e,this.#e.forEach(t=>t.setEnabled(this.#a)),this.emit("enabled",this.#a),this.#f&&this.#f(this.#a)}isEnabled(){return this.#a}setOpacity(e){const t=e;this.#u=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1,this.emit("opacity",this.#u)}getOpacity(){return this.#u}getPages(){return Array.from(this.#e.values())}rerender(){this.#e.forEach(e=>e.render())}setPageSize(e,t){this.#o(e).setSize(t)}#o(e){const t=this.#e.get(e);if(t)return t;const n=new lP({Renderer:this.#t,enabled:this.#a,pageIndex:e,onChange:()=>{this.#r()},onToolChange:r=>{this.setTool(r)}});return n.setTool(this.#s),n.setEnabled(this.#a),this.#e.set(e,n),n}getPage(e){return this.#e.get(e)}getWhiteboardData(){const e={},t={};for(const n of this.#e.values())e[n.pageIndex]=n.toJSON(),n.size&&(t[n.pageIndex]={width:n.size.width,height:n.size.height,originalWidth:n.originalSize?.width??null,originalHeight:n.originalSize?.height??null});return{pages:e,meta:{pageSizes:t},version:1}}setWhiteboardData(e){this.#e.clear();const t=e?.pages||{};Object.keys(t).forEach(n=>{const r=Number(n),o=Number.isNaN(r)?n:r;this.#o(o).applyData(t[n])}),this.emit("setData",this.getPages()),this.#l&&this.#l(this.getPages()),this.#r()}#r(){const e=this.getWhiteboardData();this.emit("change",e),this.#d&&this.#d(e)}},uP=Math.PI/180;function dP(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const Wl=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},gt={_global:Wl,version:"10.2.5",isBrowser:dP(),isUnminified:/param/.test(function(e){}.toString()),dblClickWindow:400,getAngle(e){return gt.angleDeg?e*uP:e},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return gt.DD.isDragging},isTransforming(){var e,t;return(t=(e=gt.Transformer)===null||e===void 0?void 0:e.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!gt.DD.node},releaseCanvasOnDestroy:!0,document:Wl.document,_injectGlobal(e){typeof Wl.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),Wl.Konva=e}},vr=e=>{gt[e.prototype.getClassName()]=e};gt._injectGlobal(gt);var fP=`Konva.js unsupported environment.
|
|
87
87
|
|
|
88
88
|
Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined.
|
|
89
89
|
|
|
@@ -96,13 +96,13 @@ or
|
|
|
96
96
|
|
|
97
97
|
bash: npm install skia-canvas
|
|
98
98
|
js: import "konva/skia-backend";
|
|
99
|
-
`,i4=()=>{if(typeof document>"u")throw new Error(fP)},Ui=class jA{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new jA(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),o=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,s=this.m[0]*-r+this.m[2]*n,a=this.m[1]*-r+this.m[3]*n;return this.m[0]=o,this.m[1]=i,this.m[2]=s,this.m[3]=a,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,o=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,s=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=o,this.m[2]=i,this.m[3]=s,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],o=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],s=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],a=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=o,this.m[3]=i,this.m[4]=s,this.m[5]=a,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,o=-this.m[2]*t,i=this.m[0]*t,s=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),a=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=o,this.m[3]=i,this.m[4]=s,this.m[5]=a,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],i=this.m[4],s=this.m[5],a=t*o-n*r,l={x:i,y:s,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const u=Math.sqrt(t*t+n*n);l.rotation=n>0?Math.acos(t/u):-Math.acos(t/u),l.scaleX=u,l.scaleY=a/u,l.skewX=(t*r+n*o)/a,l.skewY=0}else if(r!=0||o!=0){const u=Math.sqrt(r*r+o*o);l.rotation=Math.PI/2-(o>0?Math.acos(-r/u):-Math.acos(r/u)),l.scaleX=a/u,l.scaleY=u,l.skewX=0,l.skewY=(t*r+n*o)/a}return l.rotation=Ae._getRotation(l.rotation),l}},hP="[object Array]",pP="[object Number]",mP="[object String]",gP="[object Boolean]",vP=Math.PI/180,yP=180/Math.PI,of="#",bP="",wP="0",CP="Konva warning: ",s4="Konva error: ",_P="rgb(",s0={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},SP=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,Ip=[],sf=null,kP=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(e){setTimeout(e,16)};const Ae={_isElement(e){return!!(e&&e.nodeType==1)},_isFunction(e){return!!(e&&e.constructor&&e.call&&e.apply)},_isPlainObject(e){return!!e&&e.constructor===Object},_isArray(e){return Object.prototype.toString.call(e)===hP},_isNumber(e){return Object.prototype.toString.call(e)===pP&&!isNaN(e)&&isFinite(e)},_isString(e){return Object.prototype.toString.call(e)===mP},_isBoolean(e){return Object.prototype.toString.call(e)===gP},isObject(e){return e instanceof Object},isValidSelector(e){if(typeof e!="string")return!1;const t=e[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(e){return e===0||e>0?1:-1},requestAnimFrame(e){Ip.push(e),Ip.length===1&&kP(function(){const t=Ip;Ip=[],t.forEach(function(n){n()})})},createCanvasElement(){i4();const e=document.createElement("canvas");try{e.style=e.style||{}}catch{}return e},createImageElement(){return i4(),document.createElement("img")},_isInDocument(e){for(;e=e.parentNode;)if(e==document)return!0;return!1},_urlToImage(e,t){const n=Ae.createImageElement();n.onload=function(){t(n)},n.src=e},_rgbToHex(e,t,n){return((1<<24)+(e<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(e){e=e.replace(of,bP);const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let e=(Math.random()*16777215<<0).toString(16);for(;e.length<6;)e=wP+e;return of+e},isCanvasFarblingActive(){if(sf!==null)return sf;if(typeof document>"u")return sf=!1,!1;const e=this.createCanvasElement();e.width=10,e.height=10;const t=e.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let o=0;o<100;o++)if(n[o*4]!==40||n[o*4+1]!==40||n[o*4+2]!==40||n[o*4+3]!==255){r=!0;break}return sf=r,this.releaseCanvas(e),sf},getHitColor(){const e=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(e):e},getHitColorKey(e,t,n){return this.isCanvasFarblingActive()&&(e=Math.round(e/5)*5,t=Math.round(t/5)*5,n=Math.round(n/5)*5),of+this._rgbToHex(e,t,n)},getSnappedHexColor(e){const t=this._hexToRgb(e);return of+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(e){let t;return e in s0?(t=s0[e],{r:t[0],g:t[1],b:t[2]}):e[0]===of?this._hexToRgb(e.substring(1)):e.substr(0,4)===_P?(t=SP.exec(e.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(e){return e=e||"black",Ae._namedColorToRBA(e)||Ae._hex3ColorToRGBA(e)||Ae._hex4ColorToRGBA(e)||Ae._hex6ColorToRGBA(e)||Ae._hex8ColorToRGBA(e)||Ae._rgbColorToRGBA(e)||Ae._rgbaColorToRGBA(e)||Ae._hslColorToRGBA(e)},_namedColorToRBA(e){const t=s0[e.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(e){if(e.indexOf("rgb(")===0){e=e.match(/rgb\(([^)]+)\)/)[1];const t=e.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(e){if(e.indexOf("rgba(")===0){e=e.match(/rgba\(([^)]+)\)/)[1];const t=e.split(/ *, */).map((n,r)=>n.slice(-1)==="%"?r===3?parseInt(n)/100:parseInt(n)/100*255:Number(n));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(e){if(e[0]==="#"&&e.length===9)return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:parseInt(e.slice(7,9),16)/255}},_hex6ColorToRGBA(e){if(e[0]==="#"&&e.length===7)return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1}},_hex4ColorToRGBA(e){if(e[0]==="#"&&e.length===5)return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:parseInt(e[4]+e[4],16)/255}},_hex3ColorToRGBA(e){if(e[0]==="#"&&e.length===4)return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1}},_hslColorToRGBA(e){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(e)){const[t,...n]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(e),r=Number(n[0])/360,o=Number(n[1])/100,i=Number(n[2])/100;let s,a,l;if(o===0)return l=i*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};i<.5?s=i*(1+o):s=i+o-i*o;const u=2*i-s,c=[0,0,0];for(let d=0;d<3;d++)a=r+1/3*-(d-1),a<0&&a++,a>1&&a--,6*a<1?l=u+(s-u)*6*a:2*a<1?l=s:3*a<2?l=u+(s-u)*(2/3-a)*6:l=u,c[d]=l*255;return{r:Math.round(c[0]),g:Math.round(c[1]),b:Math.round(c[2]),a:1}}},haveIntersection(e,t){return!(t.x>e.x+e.width||t.x+t.width<e.x||t.y>e.y+e.height||t.y+t.height<e.y)},cloneObject(e){const t={};for(const n in e)this._isPlainObject(e[n])?t[n]=this.cloneObject(e[n]):this._isArray(e[n])?t[n]=this.cloneArray(e[n]):t[n]=e[n];return t},cloneArray(e){return e.slice(0)},degToRad(e){return e*vP},radToDeg(e){return e*yP},_degToRad(e){return Ae.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),Ae.degToRad(e)},_radToDeg(e){return Ae.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),Ae.radToDeg(e)},_getRotation(e){return gt.angleDeg?Ae.radToDeg(e):e},_capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)},throw(e){throw new Error(s4+e)},error(e){console.error(s4+e)},warn(e){gt.showWarnings&&console.warn(CP+e)},each(e,t){for(const n in e)t(n,e[n])},_inRange(e,t,n){return t<=e&&e<n},_getProjectionToSegment(e,t,n,r,o,i){let s,a,l;const u=(e-n)*(e-n)+(t-r)*(t-r);if(u==0)s=e,a=t,l=(o-n)*(o-n)+(i-r)*(i-r);else{const c=((o-e)*(n-e)+(i-t)*(r-t))/u;c<0?(s=e,a=t,l=(e-o)*(e-o)+(t-i)*(t-i)):c>1?(s=n,a=r,l=(n-o)*(n-o)+(r-i)*(r-i)):(s=e+c*(n-e),a=t+c*(r-t),l=(s-o)*(s-o)+(a-i)*(a-i))}return[s,a,l]},_getProjectionToLine(e,t,n){const r=Ae.cloneObject(e);let o=Number.MAX_VALUE;return t.forEach(function(i,s){if(!n&&s===t.length-1)return;const a=t[(s+1)%t.length],l=Ae._getProjectionToSegment(i.x,i.y,a.x,a.y,e.x,e.y),u=l[0],c=l[1],d=l[2];d<o&&(r.x=u,r.y=c,o=d)}),r},_prepareArrayForTween(e,t,n){const r=[],o=[];if(e.length>t.length){const s=t;t=e,e=s}for(let s=0;s<e.length;s+=2)r.push({x:e[s],y:e[s+1]});for(let s=0;s<t.length;s+=2)o.push({x:t[s],y:t[s+1]});const i=[];return o.forEach(function(s){const a=Ae._getProjectionToLine(s,r,n);i.push(a.x),i.push(a.y)}),i},_prepareToStringify(e){let t;e.visitedByCircularReferenceRemoval=!0;for(const n in e)if(e.hasOwnProperty(n)&&e[n]&&typeof e[n]=="object"){if(t=Object.getOwnPropertyDescriptor(e,n),e[n].visitedByCircularReferenceRemoval||Ae._isElement(e[n]))if(t.configurable)delete e[n];else return null;else if(Ae._prepareToStringify(e[n])===null)if(t.configurable)delete e[n];else return null}return delete e.visitedByCircularReferenceRemoval,e},_assign(e,t){for(const n in t)e[n]=t[n];return e},_getFirstPointerId(e){return e.touches?e.changedTouches[0].identifier:e.pointerId||999},releaseCanvas(...e){gt.releaseCanvasOnDestroy&&e.forEach(t=>{t.width=0,t.height=0})},drawRoundedRectPath(e,t,n,r){let o=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let s=0,a=0,l=0,u=0;typeof r=="number"?s=a=l=u=Math.min(r,t/2,n/2):(s=Math.min(r[0]||0,t/2,n/2),a=Math.min(r[1]||0,t/2,n/2),u=Math.min(r[2]||0,t/2,n/2),l=Math.min(r[3]||0,t/2,n/2)),e.moveTo(o+s,i),e.lineTo(o+t-a,i),e.arc(o+t-a,i+a,a,Math.PI*3/2,0,!1),e.lineTo(o+t,i+n-u),e.arc(o+t-u,i+n-u,u,0,Math.PI/2,!1),e.lineTo(o+l,i+n),e.arc(o+l,i+n-l,l,Math.PI/2,Math.PI,!1),e.lineTo(o,i+s),e.arc(o+s,i+s,s,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(e,t,n,r,o){r=Math.abs(r);for(let i=0;i<n;i++){const s=t[(i-1+n)%n],a=t[i],l=t[(i+1)%n],u={x:a.x-s.x,y:a.y-s.y},c={x:l.x-a.x,y:l.y-a.y},d=Math.hypot(u.x,u.y),h=Math.hypot(c.x,c.y);let m;typeof o=="number"?m=o:m=i<o.length?o[i]:0,m=r*Math.cos(Math.PI/n)*Math.min(1,m/r*2);const p={x:u.x/d,y:u.y/d},g={x:c.x/h,y:c.y/h},k={x:a.x-p.x*m,y:a.y-p.y*m},w={x:a.x+g.x*m,y:a.y+g.y*m};i===0?e.moveTo(k.x,k.y):e.lineTo(k.x,k.y),e.arcTo(a.x,a.y,w.x,w.y,m)}}};function AP(e){const t=[],n=e.length,r=Ae;for(let o=0;o<n;o++){let i=e[o];r._isNumber(i)?i=Math.round(i*1e3)/1e3:r._isString(i)||(i=i+""),t.push(i)}return t}var a4=",",IP="(",EP=")",xP="([",TP="])",RP=";",MP="()",LP="=",l4=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],DP=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],PP=100,Ep=null;function c4(){if(Ep!==null)return Ep;try{const e=Ae.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(Ep=!1,!1)}catch{return Ep=!1,!1}}var xp=class{constructor(e){this.canvas=e,gt.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let n=this.traceArr,r=n.length,o="",i,s,a,l;for(i=0;i<r;i++)s=n[i],a=s.method,a?(l=s.args,o+=a,e?o+=MP:Ae._isArray(l[0])?o+=xP+l.join(a4)+TP:(t&&(l=l.map(u=>typeof u=="number"?Math.floor(u):u)),o+=IP+l.join(a4)+EP)):(o+=s.property,e||(o+=LP+s.val)),o+=RP;return o}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,n;t.push(e),n=t.length,n>=PP&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,n,r,o,i){this._context.arc(e,t,n,r,o,i)}arcTo(e,t,n,r,o){this._context.arcTo(e,t,n,r,o)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,n,r,o,i){this._context.bezierCurveTo(e,t,n,r,o,i)}clearRect(e,t,n,r){this._context.clearRect(e,t,n,r)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const n=arguments;if(n.length===2)return this._context.createImageData(e,t);if(n.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,n,r){return this._context.createLinearGradient(e,t,n,r)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,n,r,o,i){return this._context.createRadialGradient(e,t,n,r,o,i)}drawImage(e,t,n,r,o,i,s,a,l){const u=arguments,c=this._context;u.length===3?c.drawImage(e,t,n):u.length===5?c.drawImage(e,t,n,r,o):u.length===9&&c.drawImage(e,t,n,r,o,i,s,a,l)}ellipse(e,t,n,r,o,i,s,a){this._context.ellipse(e,t,n,r,o,i,s,a)}isPointInPath(e,t,n,r){return n?this._context.isPointInPath(n,e,t,r):this._context.isPointInPath(e,t,r)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,n,r){this._context.fillRect(e,t,n,r)}strokeRect(e,t,n,r){this._context.strokeRect(e,t,n,r)}fillText(e,t,n,r){r?this._context.fillText(e,t,n,r):this._context.fillText(e,t,n)}measureText(e){return this._context.measureText(e)}getImageData(e,t,n,r){return this._context.getImageData(e,t,n,r)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,n,r){this._context.rect(e,t,n,r)}roundRect(e,t,n,r,o){this._context.roundRect(e,t,n,r,o)}putImageData(e,t,n){this._context.putImageData(e,t,n)}quadraticCurveTo(e,t,n,r){this._context.quadraticCurveTo(e,t,n,r)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,n,r,o,i){this._context.setTransform(e,t,n,r,o,i)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,n,r){this._context.strokeText(e,t,n,r)}transform(e,t,n,r,o,i){this._context.transform(e,t,n,r,o,i)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=l4.length,n=this.setAttr,r,o;const i=function(s){let a=e[s],l;e[s]=function(){return o=AP(Array.prototype.slice.call(arguments,0)),l=a.apply(e,arguments),e._trace({method:s,args:o}),l}};for(r=0;r<t;r++)i(l4[r]);e.setAttr=function(){n.apply(e,arguments);const s=arguments[0];let a=arguments[1];(s==="shadowOffsetX"||s==="shadowOffsetY"||s==="shadowBlur")&&(a=a/this.canvas.getPixelRatio()),e._trace({property:s,val:a})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}};DP.forEach(function(e){Object.defineProperty(xp.prototype,e,{get(){return this._context[e]},set(t){this._context[e]=t}})});var OP=class extends xp{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),n=e.getFillPriority();if(t&&n==="color"){this._fillColor(e);return}const r=e.getFillPatternImage();if(r&&n==="pattern"){this._fillPattern(e);return}const o=e.getFillLinearGradientColorStops();if(o&&n==="linear-gradient"){this._fillLinearGradient(e);return}const i=e.getFillRadialGradientColorStops();if(i&&n==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):o?this._fillLinearGradient(e):i&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),n=e.getStrokeLinearGradientEndPoint(),r=e.getStrokeLinearGradientColorStops(),o=this.createLinearGradient(t.x,t.y,n.x,n.y);if(r){for(let i=0;i<r.length;i+=2)o.addColorStop(r[i],r[i+1]);this.setAttr("strokeStyle",o)}}_stroke(e){const t=e.dash(),n=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!n){this.save();const r=this.getCanvas().getPixelRatio();this.setTransform(r,0,0,r,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),n||this.restore()}}_applyShadow(e){var t,n,r;const o=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",i=(n=e.getShadowBlur())!==null&&n!==void 0?n:5,s=(r=e.getShadowOffset())!==null&&r!==void 0?r:{x:0,y:0},a=e.getAbsoluteScale(),l=this.canvas.getPixelRatio(),u=a.x*l,c=a.y*l;this.setAttr("shadowColor",o),this.setAttr("shadowBlur",i*Math.min(Math.abs(u),Math.abs(c))),this.setAttr("shadowOffsetX",s.x*u),this.setAttr("shadowOffsetY",s.y*c)}},FP=class extends xp{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const o=this.getCanvas().getPixelRatio();this.setTransform(o,0,0,o,0,0)}this._applyLineCap(e);const n=e.hitStrokeWidth(),r=n==="auto"?e.strokeWidth():n;this.setAttr("lineWidth",r),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}},Tp;function BP(){if(Tp)return Tp;const e=Ae.createCanvasElement(),t=e.getContext("2d");return Tp=(function(){return(gt._global.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)})(),Ae.releaseCanvas(e),Tp}var a0=class{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1,this.pixelRatio=(e||{}).pixelRatio||gt.pixelRatio||BP(),this._canvas=Ae.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(r){return Ae.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}},Xa=class extends a0{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new OP(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}},l0=class extends a0{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new FP(this),this.setSize(e.width,e.height)}};const En={get isDragging(){let e=!1;return En._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(e=!0)}),e},justDragged:!1,get node(){let e;return En._dragElements.forEach(t=>{e=t.node}),e},_dragElements:new Map,_drag(e){const t=[];En._dragElements.forEach((n,r)=>{const{node:o}=n,i=o.getStage();i.setPointersPositions(e),n.pointerId===void 0&&(n.pointerId=Ae._getFirstPointerId(e));const s=i._changedPointerPositions.find(a=>a.id===n.pointerId);if(s){if(n.dragStatus!=="dragging"){const a=o.dragDistance();if(Math.max(Math.abs(s.x-n.startPointerPos.x),Math.abs(s.y-n.startPointerPos.y))<a||(o.startDrag({evt:e}),!o.isDragging()))return}o._setDragPosition(e,n),t.push(o)}}),t.forEach(n=>{n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:e},!0)})},_endDragBefore(e){const t=[];En._dragElements.forEach(n=>{const{node:r}=n,o=r.getStage();if(e&&o.setPointersPositions(e),!o._changedPointerPositions.find(s=>s.id===n.pointerId))return;(n.dragStatus==="dragging"||n.dragStatus==="stopped")&&(En.justDragged=!0,gt._mouseListenClick=!1,gt._touchListenClick=!1,gt._pointerListenClick=!1,n.dragStatus="stopped");const i=n.node.getLayer()||n.node instanceof gt.Stage&&n.node;i&&t.indexOf(i)===-1&&t.push(i)}),t.forEach(n=>{n.draw()})},_endDragAfter(e){En._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:e},!0),t.dragStatus!=="dragging"&&En._dragElements.delete(n)})}};gt.isBrowser&&(window.addEventListener("mouseup",En._endDragBefore,!0),window.addEventListener("touchend",En._endDragBefore,!0),window.addEventListener("touchcancel",En._endDragBefore,!0),window.addEventListener("mousemove",En._drag),window.addEventListener("touchmove",En._drag),window.addEventListener("mouseup",En._endDragAfter,!1),window.addEventListener("touchend",En._endDragAfter,!1),window.addEventListener("touchcancel",En._endDragAfter,!1));function Qa(e){return Ae._isString(e)?'"'+e+'"':Object.prototype.toString.call(e)==="[object Number]"||Ae._isBoolean(e)?e:Object.prototype.toString.call(e)}function u4(e){return e>255?255:e<0?0:Math.round(e)}function ft(){if(gt.isUnminified)return function(e,t){return Ae._isNumber(e)||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),e}}function Rp(e){if(gt.isUnminified)return function(t,n){let r=Ae._isNumber(t),o=Ae._isArray(t)&&t.length==e;return!r&&!o&&Ae.warn(Qa(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array<number>('+e+")"),t}}function c0(){if(gt.isUnminified)return function(e,t){return Ae._isNumber(e)||e==="auto"||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),e}}function Kl(){if(gt.isUnminified)return function(e,t){return Ae._isString(e)||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),e}}function d4(){if(gt.isUnminified)return function(e,t){const n=Ae._isString(e),r=Object.prototype.toString.call(e)==="[object CanvasGradient]"||e&&e.addColorStop;return n||r||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),e}}function NP(){if(gt.isUnminified)return function(e,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&e instanceof n||(Ae._isArray(e)?e.forEach(function(r){Ae._isNumber(r)||Ae.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),e}}function Vi(){if(gt.isUnminified)return function(e,t){return e===!0||e===!1||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),e}}function zP(e){if(gt.isUnminified)return function(t,n){return t==null||Ae.isObject(t)||Ae.warn(Qa(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+e),t}}var af="get",lf="set";const ce={addGetterSetter(e,t,n,r,o){ce.addGetter(e,t,n),ce.addSetter(e,t,r,o),ce.addOverloadedGetterSetter(e,t)},addGetter(e,t,n){const r=af+Ae._capitalize(t);e.prototype[r]=e.prototype[r]||function(){const o=this.attrs[t];return o===void 0?n:o}},addSetter(e,t,n,r){const o=lf+Ae._capitalize(t);e.prototype[o]||ce.overWriteSetter(e,t,n,r)},overWriteSetter(e,t,n,r){const o=lf+Ae._capitalize(t);e.prototype[o]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(e,t,n,r,o){const i=n.length,s=Ae._capitalize,a=af+s(t),l=lf+s(t);e.prototype[a]=function(){const c={};for(let d=0;d<i;d++){const h=n[d];c[h]=this.getAttr(t+s(h))}return c};const u=zP(n);e.prototype[l]=function(c){const d=this.attrs[t];r&&(c=r.call(this,c,t)),u&&u.call(this,c,t);for(const h in c)c.hasOwnProperty(h)&&this._setAttr(t+s(h),c[h]);return c||n.forEach(h=>{this._setAttr(t+s(h),void 0)}),this._fireChangeEvent(t,d,c),o&&o.call(this),this},ce.addOverloadedGetterSetter(e,t)},addOverloadedGetterSetter(e,t){const n=Ae._capitalize(t),r=lf+n,o=af+n;e.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[o]()}},addDeprecatedGetterSetter(e,t,n,r){Ae.error("Adding deprecated "+t);const o=af+Ae._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";e.prototype[o]=function(){Ae.error(i);const s=this.attrs[t];return s===void 0?n:s},ce.addSetter(e,t,r,function(){Ae.error(i)}),ce.addOverloadedGetterSetter(e,t)},backCompat(e,t){Ae.each(t,function(n,r){const o=e.prototype[r],i=af+Ae._capitalize(n),s=lf+Ae._capitalize(n);function a(){o.apply(this,arguments),Ae.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}e.prototype[n]=a,e.prototype[i]=a,e.prototype[s]=a})},afterSetFilter(){this._filterUpToDate=!1}};function HP(e){const t=/(\w+)\(([^)]+)\)/g;let n;for(;(n=t.exec(e))!==null;){const[,r,o]=n;switch(r){case"blur":{const i=parseFloat(o.replace("px",""));return function(s){this.blurRadius(i*.5);const a=gt.Filters;a&&a.Blur&&a.Blur.call(this,s)}}case"brightness":{const i=o.includes("%")?parseFloat(o)/100:parseFloat(o);return function(s){this.brightness(i);const a=gt.Filters;a&&a.Brightness&&a.Brightness.call(this,s)}}case"contrast":{const i=parseFloat(o);return function(s){const a=100*(Math.sqrt(i)-1);this.contrast(a);const l=gt.Filters;l&&l.Contrast&&l.Contrast.call(this,s)}}case"grayscale":return function(i){const s=gt.Filters;s&&s.Grayscale&&s.Grayscale.call(this,i)};case"sepia":return function(i){const s=gt.Filters;s&&s.Sepia&&s.Sepia.call(this,i)};case"invert":return function(i){const s=gt.Filters;s&&s.Invert&&s.Invert.call(this,i)};default:Ae.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}var Mp="absoluteOpacity",f4="allEventListeners",fa="absoluteTransform",h4="absoluteScale",ql="canvas",UP="Change",VP="children",jP="konva",u0="listening",GP="mouseenter",WP="mouseleave",KP="pointerenter",qP="pointerleave",YP="touchenter",XP="touchleave",p4="set",m4="Shape",Lp=" ",g4="stage",Za="transform",QP="Stage",d0="visible",ZP=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Lp),JP=1,yt=class Uf{constructor(t){this._id=JP++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===Za||t===fa)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,n){let r=this._cache.get(t);return(r===void 0||(t===Za||t===fa)&&r.dirty===!0)&&(r=n.call(this),this._cache.set(t,r)),r}_calculate(t,n,r){if(!this._attachedDepsListeners.get(t)){const o=n.map(i=>i+"Change.konva").join(Lp);this.on(o,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(ql)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===fa&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(ql)){const{scene:t,filter:n,hit:r}=this._cache.get(ql);Ae.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(ql)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let o=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),s=n.pixelRatio,a=n.x===void 0?Math.floor(r.x):n.x,l=n.y===void 0?Math.floor(r.y):n.y,u=n.offset||0,c=n.drawBorder||!1,d=n.hitCanvasPixelRatio||1;if(!o||!i){Ae.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const h=Math.abs(Math.round(r.x)-a)>.5?1:0,m=Math.abs(Math.round(r.y)-l)>.5?1:0;o+=u*2+h,i+=u*2+m,a-=u,l-=u;const p=new Xa({pixelRatio:s,width:o,height:i}),g=new Xa({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),k=new l0({pixelRatio:d,width:o,height:i}),w=p.getContext(),S=k.getContext(),y=new Xa({width:p.width/p.pixelRatio+Math.abs(a),height:p.height/p.pixelRatio+Math.abs(l),pixelRatio:p.pixelRatio}),C=y.getContext();return k.isCache=!0,p.isCache=!0,this._cache.delete(ql),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(p.getContext()._context.imageSmoothingEnabled=!1,g.getContext()._context.imageSmoothingEnabled=!1),w.save(),S.save(),C.save(),w.translate(-a,-l),S.translate(-a,-l),C.translate(-a,-l),y.x=a,y.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Mp),this._clearSelfAndDescendantCache(h4),this.drawScene(p,this,y),this.drawHit(k,this),this._isUnderCache=!1,w.restore(),S.restore(),c&&(w.save(),w.beginPath(),w.rect(0,0,o,i),w.closePath(),w.setAttr("strokeStyle","red"),w.setAttr("lineWidth",5),w.stroke(),w.restore()),Ae.releaseCanvas(y._canvas),this._cache.set(ql,{scene:p,filter:g,hit:k,x:a,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(ql)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let o=1/0,i=1/0,s=-1/0,a=-1/0;const l=this.getAbsoluteTransform(n);return r.forEach(function(u){const c=l.point(u);o===void 0&&(o=s=c.x,i=a=c.y),o=Math.min(o,c.x),i=Math.min(i,c.y),s=Math.max(s,c.x),a=Math.max(a,c.y)}),{x:o,y:i,width:s-o,height:a-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),o=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/o,r.height/o),t.restore()}_drawCachedHitCanvas(t){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),n=this._getCanvasCache(),r=n.scene,o=n.filter,i=o.getContext(),s,a,l,u;if(!t||t.length===0)return r;if(this._filterUpToDate)return o;let c=!0;for(let h=0;h<t.length;h++)if(typeof t[h]=="string"&&c4(),typeof t[h]!="string"||!c4()){c=!1;break}const d=r.pixelRatio;if(o.setSize(r.width/r.pixelRatio,r.height/r.pixelRatio),c){const h=t.join(" ");return i.save(),i.setAttr("filter",h),i.drawImage(r._canvas,0,0,r.getWidth()/d,r.getHeight()/d),i.restore(),this._filterUpToDate=!0,o}try{for(s=t.length,i.clear(),i.drawImage(r._canvas,0,0,r.getWidth()/d,r.getHeight()/d),a=i.getImageData(0,0,o.getWidth(),o.getHeight()),l=0;l<s;l++)u=t[l],typeof u=="string"&&(u=HP(u)),u.call(this,a),i.putImageData(a,0,0)}catch(h){Ae.error("Unable to apply filter. "+h.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,o}on(...t){const n=t[0],r=t[1];if(t[2],this._cache&&this._cache.delete(f4),t.length===3)return this._delegate.apply(this,t);const o=n.split(Lp);for(let i=0;i<o.length;i++){const s=o[i].split("."),a=s[0],l=s[1]||"";this.eventListeners[a]||(this.eventListeners[a]=[]),this.eventListeners[a].push({name:l,handler:r})}return this}off(t,n){let r=(t||"").split(Lp),o=r.length,i,s,a,l,u,c;if(this._cache&&this._cache.delete(f4),!t)for(s in this.eventListeners)this._off(s);for(i=0;i<o;i++)if(a=r[i],l=a.split("."),u=l[0],c=l[1],u)this.eventListeners[u]&&this._off(u,c,n);else for(s in this.eventListeners)this._off(s,c,n);return this}dispatchEvent(t){const n={target:this,type:t.type,evt:t};return this.fire(t.type,n),this}addEventListener(t,n){return this.on(t,function(r){n.call(this,r.evt)}),this}removeEventListener(t){return this.off(t),this}_delegate(t,n,r){const o=this;return this.on(t,function(i){const s=i.target.findAncestors(n,!0,o);for(let a=0;a<s.length;a++)i=Ae.cloneObject(i),i.currentTarget=s[a],r.call(s[a],i)}),this}remove(){return this.isDragging()&&this.stopDrag(),En._dragElements.delete(this._id),En._dragElements.forEach((t,n)=>{this.isAncestorOf(t.node)&&En._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(fa),this._clearSelfAndDescendantCache(Mp),this._clearSelfAndDescendantCache(h4),this._clearSelfAndDescendantCache(g4),this._clearSelfAndDescendantCache(d0),this._clearSelfAndDescendantCache(u0)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+Ae._capitalize(t);return Ae._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==VP&&(r=p4+Ae._capitalize(n),Ae._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(u0,this._isListening)}_isListening(t){if(!this.listening())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isListening(t):!0}isVisible(){return this._getCache(d0,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isVisible(t):!0}shouldDrawHit(t,n=!1){if(t)return this._isVisible(t)&&this._isListening(t);const r=this.getLayer();let o=!1;En._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===r)&&(o=!0)});const i=!n&&!gt.hitOnDragEnabled&&(o||gt.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),n=this,r=0,o,i,s,a;function l(c){for(o=[],i=c.length,s=0;s<i;s++)a=c[s],r++,a.nodeType!==m4&&(o=o.concat(a.getChildren().slice())),a._id===n._id&&(s=i);o.length>0&&o[0].getDepth()<=t&&l(o)}const u=this.getStage();return n.nodeType!==QP&&u&&l(u.getChildren()),r}getDepth(){let t=0,n=this.parent;for(;n;)t++,n=n.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(Za),this._clearSelfAndDescendantCache(fa)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);const o=this.getAbsoluteTransform(t).getMatrix(),i=new Ui,s=this.offset();return i.m=o.slice(),i.translate(s.x,s.y),i.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...o}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(Za);const i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(o),this.setPosition({x:t.x,y:t.y}),this._clearCache(Za),this._clearSelfAndDescendantCache(fa),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let n=t.x,r=t.y,o=this.x(),i=this.y();return n!==void 0&&(o+=n),r!==void 0&&(i+=r),this.setPosition({x:o,y:i}),this}_eachAncestorReverse(t,n){let r=[],o=this.getParent(),i,s;if(!(n&&n._id===this._id)){for(r.unshift(this);o&&(!n||o._id!==n._id);)r.unshift(o),o=o.parent;for(i=r.length,s=0;s<i;s++)t(r[s])}}rotate(t){return this.rotation(this.rotation()+t),this}moveToTop(){if(!this.parent)return Ae.warn("Node has no parent. moveToTop function is ignored."),!1;const t=this.index;return t<this.parent.getChildren().length-1?(this.parent.children.splice(t,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return Ae.warn("Node has no parent. moveUp function is ignored."),!1;const t=this.index;return t<this.parent.getChildren().length-1?(this.parent.children.splice(t,1),this.parent.children.splice(t+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return Ae.warn("Node has no parent. moveDown function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return Ae.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return Ae.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Ae.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Mp,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),n,r,o,i,s;const a={attrs:{},className:this.getClassName()};for(n in t)r=t[n],s=Ae.isObject(r)&&!Ae._isPlainObject(r)&&!Ae._isArray(r),!s&&(o=typeof this[n]=="function"&&this[n],delete t[n],i=o?o.call(this):null,t[n]=r,i!==r&&(a.attrs[n]=r));return Ae._prepareToStringify(a)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const o=[];n&&this._isMatch(t)&&o.push(this);let i=this.parent;for(;i;){if(i===r)return o;i._isMatch(t)&&o.push(i),i=i.parent}return o}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,o,i;for(o=0;o<r;o++)if(i=n[o],Ae.isValidSelector(i)||(Ae.warn('Selector "'+i+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),Ae.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),Ae.warn("Konva is awesome, right?")),i.charAt(0)==="#"){if(this.id()===i.slice(1))return!0}else if(i.charAt(0)==="."){if(this.hasName(i.slice(1)))return!0}else if(this.className===i||this.nodeType===i)return!0;return!1}getLayer(){const t=this.getParent();return t?t.getLayer():null}getStage(){return this._getCache(g4,this._getStage)}_getStage(){const t=this.getParent();return t?t.getStage():null}fire(t,n={},r){return n.target=n.target||this,r?this._fireAndBubble(t,n):this._fire(t,n),this}getAbsoluteTransform(t){return t?this._getAbsoluteTransform(t):this._getCache(fa,this._getAbsoluteTransform)}_getAbsoluteTransform(t){let n;if(t)return n=new Ui,this._eachAncestorReverse(function(r){const o=r.transformsEnabled();o==="all"?n.multiply(r.getTransform()):o==="position"&&n.translate(r.x()-r.offsetX(),r.y()-r.offsetY())},t),n;{n=this._cache.get(fa)||new Ui,this.parent?this.parent.getAbsoluteTransform().copyInto(n):n.reset();const r=this.transformsEnabled();if(r==="all")n.multiply(this.getTransform());else if(r==="position"){const o=this.attrs.x||0,i=this.attrs.y||0,s=this.attrs.offsetX||0,a=this.attrs.offsetY||0;n.translate(o-s,i-a)}return n.dirty=!1,n}}getAbsoluteScale(t){let n=this;for(;n;)n._isUnderCache&&(t=n),n=n.getParent();const r=this.getAbsoluteTransform(t).decompose();return{x:r.scaleX,y:r.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(Za,this._getTransform)}_getTransform(){var t,n;const r=this._cache.get(Za)||new Ui;r.reset();const o=this.x(),i=this.y(),s=gt.getAngle(this.rotation()),a=(t=this.attrs.scaleX)!==null&&t!==void 0?t:1,l=(n=this.attrs.scaleY)!==null&&n!==void 0?n:1,u=this.attrs.skewX||0,c=this.attrs.skewY||0,d=this.attrs.offsetX||0,h=this.attrs.offsetY||0;return(o!==0||i!==0)&&r.translate(o,i),s!==0&&r.rotate(s),(u!==0||c!==0)&&r.skew(u,c),(a!==1||l!==1)&&r.scale(a,l),(d!==0||h!==0)&&r.translate(-1*d,-1*h),r.dirty=!1,r}clone(t){let n=Ae.cloneObject(this.attrs),r,o,i,s,a;for(r in t)n[r]=t[r];const l=new this.constructor(n);for(r in this.eventListeners)for(o=this.eventListeners[r],i=o.length,s=0;s<i;s++)a=o[s],a.name.indexOf(jP)<0&&(l.eventListeners[r]||(l.eventListeners[r]=[]),l.eventListeners[r].push(a));return l}_toKonvaCanvas(t){t=t||{};const n=this.getClientRect(),r=this.getStage(),o=t.x!==void 0?t.x:Math.floor(n.x),i=t.y!==void 0?t.y:Math.floor(n.y),s=t.pixelRatio||1,a=new Xa({width:t.width||Math.ceil(n.width)||(r?r.width():0),height:t.height||Math.ceil(n.height)||(r?r.height():0),pixelRatio:s}),l=a.getContext(),u=new Xa({width:a.width/a.pixelRatio+Math.abs(o),height:a.height/a.pixelRatio+Math.abs(i),pixelRatio:a.pixelRatio});return t.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(o||i)&&l.translate(-1*o,-1*i),this.drawScene(a,void 0,u),l.restore(),a}toCanvas(t){return this._toKonvaCanvas(t)._canvas}toDataURL(t){t=t||{};const n=t.mimeType||null,r=t.quality||null,o=this._toKonvaCanvas(t).toDataURL(n,r);return t.callback&&t.callback(o),o}toImage(t){return new Promise((n,r)=>{try{const o=t?.callback;o&&delete t.callback,Ae._urlToImage(this.toDataURL(t),function(i){n(i),o?.(i)})}catch(o){r(o)}})}toBlob(t){return new Promise((n,r)=>{try{const o=t?.callback;o&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),o?.(i)},t?.mimeType,t?.quality)}catch(o){r(o)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():gt.dragDistance}_off(t,n,r){let o=this.eventListeners[t],i,s,a;for(i=0;i<o.length;i++)if(s=o[i].name,a=o[i].handler,(s!=="konva"||n==="konva")&&(!n||s===n)&&(!r||r===a)){if(o.splice(i,1),o.length===0){delete this.eventListeners[t];break}i--}}_fireChangeEvent(t,n,r){this._fire(t+UP,{oldVal:n,newVal:r})}addName(t){if(!this.hasName(t)){const n=this.name(),r=n?n+" "+t:t;this.name(r)}return this}hasName(t){if(!t)return!1;const n=this.name();return n?(n||"").split(/\s/g).indexOf(t)!==-1:!1}removeName(t){const n=(this.name()||"").split(/\s/g),r=n.indexOf(t);return r!==-1&&(n.splice(r,1),this.name(n.join(" "))),this}setAttr(t,n){const r=this[p4+Ae._capitalize(t)];return Ae._isFunction(r)?r.call(this,n):this._setAttr(t,n),this}_requestDraw(){if(gt.autoDrawEnabled){const t=this.getLayer()||this.getStage();t?.batchDraw()}}_setAttr(t,n){const r=this.attrs[t];r===n&&!Ae.isObject(n)||(n==null?delete this.attrs[t]:this.attrs[t]=n,this._shouldFireChangeEvents&&this._fireChangeEvent(t,r,n),this._requestDraw())}_setComponentAttr(t,n,r){let o;r!==void 0&&(o=this.attrs[t],o||(this.attrs[t]=this.getAttr(t)),this.attrs[t][n]=r,this._fireChangeEvent(t,o,r))}_fireAndBubble(t,n,r){n&&this.nodeType===m4&&(n.target=this);const o=[GP,WP,KP,qP,YP,XP];if(!(o.indexOf(t)!==-1&&(r&&(this===r||this.isAncestorOf&&this.isAncestorOf(r))||this.nodeType==="Stage"&&!r))){this._fire(t,n);const i=o.indexOf(t)!==-1&&r&&r.isAncestorOf&&r.isAncestorOf(this)&&!r.isAncestorOf(this.parent);(n&&!n.cancelBubble||!n)&&this.parent&&this.parent.isListening()&&!i&&(r&&r.parent?this._fireAndBubble.call(this.parent,t,n,r):this._fireAndBubble.call(this.parent,t,n))}}_getProtoListeners(t){var n,r;const{nodeType:o}=this,i=Uf.protoListenerMap.get(o)||{};let s=i?.[t];if(s===void 0){s=[];let a=Object.getPrototypeOf(this);for(;a;){const l=(r=(n=a.eventListeners)===null||n===void 0?void 0:n[t])!==null&&r!==void 0?r:[];s.push(...l),a=Object.getPrototypeOf(a)}i[t]=s,Uf.protoListenerMap.set(o,i)}return s}_fire(t,n){n=n||{},n.currentTarget=this,n.type=t;const r=this._getProtoListeners(t);if(r){const i=r.slice();for(let s=0;s<i.length;s++)i[s].handler.call(this,n)}const o=this.eventListeners[t];if(o){const i=o.slice(),s=i.length;for(let l=0;l<i.length;l++)i[l].handler.call(this,n);const a=this.eventListeners[t];if(a)for(let l=s;l<a.length;l++)a[l].handler.call(this,n)}}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(t){const n=t?t.pointerId:void 0,r=this.getStage(),o=this.getAbsolutePosition();if(!r)return;const i=r._getPointerById(n)||r._changedPointerPositions[0]||o;En._dragElements.set(this._id,{node:this,startPointerPos:i,offset:{x:i.x-o.x,y:i.y-o.y},dragStatus:"ready",pointerId:n,startEvent:t})}startDrag(t,n=!0){En._dragElements.has(this._id)||this._createDragElement(t);const r=En._dragElements.get(this._id);r.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:r.startEvent&&r.startEvent.evt||t&&t.evt},n)}_setDragPosition(t,n){const r=this.getStage()._getPointerById(n.pointerId);if(!r)return;let o={x:r.x-n.offset.x,y:r.y-n.offset.y};const i=this.dragBoundFunc();if(i!==void 0){const s=i.call(this,o,t);s?o=s:Ae.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==o.x||this._lastPos.y!==o.y)&&(this.setAbsolutePosition(o),this._requestDraw()),this._lastPos=o}stopDrag(t){const n=En._dragElements.get(this._id);n&&(n.dragStatus="stopped"),En._endDragBefore(t),En._endDragAfter(t)}setDraggable(t){this._setAttr("draggable",t),this._dragChange()}isDragging(){const t=En._dragElements.get(this._id);return t?t.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(t){if(!(t.evt.button===void 0||gt.dragButtons.indexOf(t.evt.button)>=0)||this.isDragging())return;let n=!1;En._dragElements.forEach(r=>{this.isAncestorOf(r.node)&&(n=!0)}),n||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=En._dragElements.get(this._id),n=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";n?this.stopDrag():r&&En._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return Ae.haveIntersection(r,this.getClientRect())}static create(t,n){return Ae._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=Uf.prototype.getClassName.call(t),o=t.children,i,s,a;n&&(t.attrs.container=n),gt[r]||(Ae.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const l=gt[r];if(i=new l(t.attrs),o)for(s=o.length,a=0;a<s;a++)i.add(Uf._createNode(o[a]));return i}};yt.protoListenerMap=new Map,yt.prototype.nodeType="Node",yt.prototype._attrsAffectingSize=[],yt.prototype.eventListeners={},yt.prototype.on(ZP,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(Za),this._clearSelfAndDescendantCache(fa)}),yt.prototype.on("visibleChange.konva",function(){this._clearSelfAndDescendantCache(d0)}),yt.prototype.on("listeningChange.konva",function(){this._clearSelfAndDescendantCache(u0)}),yt.prototype.on("opacityChange.konva",function(){this._clearSelfAndDescendantCache(Mp)});var Qn=ce.addGetterSetter;Qn(yt,"zIndex"),Qn(yt,"absolutePosition"),Qn(yt,"position"),Qn(yt,"x",0,ft()),Qn(yt,"y",0,ft()),Qn(yt,"globalCompositeOperation","source-over",Kl()),Qn(yt,"opacity",1,ft()),Qn(yt,"name","",Kl()),Qn(yt,"id","",Kl()),Qn(yt,"rotation",0,ft()),ce.addComponentsGetterSetter(yt,"scale",["x","y"]),Qn(yt,"scaleX",1,ft()),Qn(yt,"scaleY",1,ft()),ce.addComponentsGetterSetter(yt,"skew",["x","y"]),Qn(yt,"skewX",0,ft()),Qn(yt,"skewY",0,ft()),ce.addComponentsGetterSetter(yt,"offset",["x","y"]),Qn(yt,"offsetX",0,ft()),Qn(yt,"offsetY",0,ft()),Qn(yt,"dragDistance",void 0,ft()),Qn(yt,"width",0,ft()),Qn(yt,"height",0,ft()),Qn(yt,"listening",!0,Vi()),Qn(yt,"preventDefault",!0,Vi()),Qn(yt,"filters",void 0,function(e){return this._filterUpToDate=!1,e}),Qn(yt,"visible",!0,Vi()),Qn(yt,"transformsEnabled","all",Kl()),Qn(yt,"size"),Qn(yt,"dragBoundFunc"),Qn(yt,"draggable",!1,Vi()),ce.backCompat(yt,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});var fi=class extends yt{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let n=0;n<e.length;n++)this.add(e[n]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const n=[];return this._descendants(r=>{const o=r._isMatch(e);return o&&n.push(r),!!(o&&t)}),n}_descendants(e){let t=!1;const n=this.getChildren();for(const r of n){if(t=e(r),t)return!0;if(r.hasChildren()&&(t=r._descendants(e),t))return!0}return!1}toObject(){const e=yt.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=yt.prototype.clone.call(this,e);return this.getChildren().forEach(function(n){t.add(n.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(n=>{n.isVisible()&&n.intersects(e)&&t.push(n)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(n){n._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,n){t.index=n}),this._requestDraw()}drawScene(e,t,n){const r=this.getLayer(),o=e||r&&r.getCanvas(),i=o&&o.getContext(),s=this._getCanvasCache(),a=s&&s.scene,l=o&&o.isCache;if(!this.isVisible()&&!l)return this;if(a){i.save();const u=this.getAbsoluteTransform(t).getMatrix();i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(i),i.restore()}else this._drawChildren("drawScene",o,t,n);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const n=this.getLayer(),r=e||n&&n.hitCanvas,o=r&&r.getContext(),i=this._getCanvasCache();if(i&&i.hit){o.save();const s=this.getAbsoluteTransform(t).getMatrix();o.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._drawCachedHitCanvas(o),o.restore()}else this._drawChildren("drawHit",r,t);return this}_drawChildren(e,t,n,r){var o;const i=t&&t.getContext(),s=this.clipWidth(),a=this.clipHeight(),l=this.clipFunc(),u=typeof s=="number"&&typeof a=="number"||l,c=n===this;if(u){i.save();const h=this.getAbsoluteTransform(n);let m=h.getMatrix();i.transform(m[0],m[1],m[2],m[3],m[4],m[5]),i.beginPath();let p;if(l)p=l.call(this,i,this);else{const g=this.clipX(),k=this.clipY();i.rect(g||0,k||0,s,a)}i.clip.apply(i,p),m=h.copy().invert().getMatrix(),i.transform(m[0],m[1],m[2],m[3],m[4],m[5])}const d=!c&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";d&&(i.save(),i._applyGlobalCompositeOperation(this)),(o=this.children)===null||o===void 0||o.forEach(function(h){h[e](t,n,r)}),d&&i.restore(),u&&i.restore()}getClientRect(e={}){var t;const n=e.skipTransform,r=e.relativeTo;let o,i,s,a,l={x:1/0,y:1/0,width:0,height:0};const u=this;(t=this.children)===null||t===void 0||t.forEach(function(h){if(!h.visible())return;const m=h.getClientRect({relativeTo:u,skipShadow:e.skipShadow,skipStroke:e.skipStroke});m.width===0&&m.height===0||(o===void 0?(o=m.x,i=m.y,s=m.x+m.width,a=m.y+m.height):(o=Math.min(o,m.x),i=Math.min(i,m.y),s=Math.max(s,m.x+m.width),a=Math.max(a,m.y+m.height)))});const c=this.find("Shape");let d=!1;for(let h=0;h<c.length;h++)if(c[h]._isVisible(this)){d=!0;break}return d&&o!==void 0?l={x:o,y:i,width:s-o,height:a-i}:l={x:0,y:0,width:0,height:0},n?l:this._transformedRect(l,r)}};ce.addComponentsGetterSetter(fi,"clip",["x","y","width","height"]),ce.addGetterSetter(fi,"clipX",void 0,ft()),ce.addGetterSetter(fi,"clipY",void 0,ft()),ce.addGetterSetter(fi,"clipWidth",void 0,ft()),ce.addGetterSetter(fi,"clipHeight",void 0,ft()),ce.addGetterSetter(fi,"clipFunc");var cf=new Map,v4=gt._global.PointerEvent!==void 0;function f0(e){return cf.get(e)}function h0(e){return{evt:e,pointerId:e.pointerId}}function y4(e,t){return cf.get(e)===t}function b4(e,t){uf(e),t.getStage()&&(cf.set(e,t),v4&&t._fire("gotpointercapture",h0(new PointerEvent("gotpointercapture"))))}function uf(e,t){const n=cf.get(e);if(!n)return;const r=n.getStage();r&&r.content,cf.delete(e),v4&&n._fire("lostpointercapture",h0(new PointerEvent("lostpointercapture")))}var $P="Stage",eO="string",w4="px",tO="mouseout",C4="mouseleave",_4="mouseover",S4="mouseenter",k4="mousemove",A4="mousedown",I4="mouseup",df="pointermove",ff="pointerdown",su="pointerup",hf="pointercancel",nO="lostpointercapture",Dp="pointerout",pf="pointerleave",Pp="pointerover",Op="pointerenter",p0="contextmenu",E4="touchstart",x4="touchend",T4="touchmove",R4="touchcancel",m0="wheel",rO=5,oO=[[S4,"_pointerenter"],[A4,"_pointerdown"],[k4,"_pointermove"],[I4,"_pointerup"],[C4,"_pointerleave"],[E4,"_pointerdown"],[T4,"_pointermove"],[x4,"_pointerup"],[R4,"_pointercancel"],[_4,"_pointerover"],[m0,"_wheel"],[p0,"_contextmenu"],[ff,"_pointerdown"],[df,"_pointermove"],[su,"_pointerup"],[hf,"_pointercancel"],[pf,"_pointerleave"],[nO,"_lostpointercapture"]],g0={mouse:{[Dp]:tO,[pf]:C4,[Pp]:_4,[Op]:S4,[df]:k4,[ff]:A4,[su]:I4,[hf]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Dp]:"touchout",[pf]:"touchleave",[Pp]:"touchover",[Op]:"touchenter",[df]:T4,[ff]:E4,[su]:x4,[hf]:R4,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Dp]:Dp,[pf]:pf,[Pp]:Pp,[Op]:Op,[df]:df,[ff]:ff,[su]:su,[hf]:hf,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},mf=e=>e.indexOf("pointer")>=0?"pointer":e.indexOf("touch")>=0?"touch":"mouse",au=e=>{const t=mf(e);if(t==="pointer")return gt.pointerEventsEnabled&&g0.pointer;if(t==="touch")return g0.touch;if(t==="mouse")return g0.mouse};function M4(e={}){return(e.clipFunc||e.clipWidth||e.clipHeight)&&Ae.warn("Stage does not support clipping. Please use clip for Layers or Groups."),e}var iO="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);";const gf=[];var Fp=class extends fi{constructor(e){super(M4(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),gf.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{M4(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",n=e.getType()==="FastLayer";t||n||Ae.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===eO){let t;if(e.charAt(0)==="."){const n=e.slice(1);e=document.getElementsByClassName(n)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let n=0;n<t;n++)e[n].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),fi.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&Ae._isInDocument(e)&&this.container().removeChild(e);const t=gf.indexOf(this);return t>-1&&gf.splice(t,1),Ae.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(Ae.warn(iO),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new Xa({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),n=t.getContext()._context,r=this.children;return(e.x||e.y)&&n.translate(-1*e.x,-1*e.y),r.forEach(function(o){if(!o.isVisible())return;const i=o._toKonvaCanvas(e);n.drawImage(i._canvas,e.x,e.y,i.getWidth()/i.getPixelRatio(),i.getHeight()/i.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,n=t.length-1;for(let r=n;r>=0;r--){const o=t[r].getIntersection(e);if(o)return o}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+w4,this.content.style.height=t+w4),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(n=>{n.setSize({width:e,height:t}),n.draw()})}add(e,...t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}super.add(e);const n=this.children.length;return n>rO&&Ae.warn("The stage has "+n+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),gt.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return y4(e,this)}setPointerCapture(e){b4(e,this)}releaseCapture(e){uf(e,this)}getLayers(){return this.children}_bindContentEvents(){gt.isBrowser&&oO.forEach(([e,t])=>{this.content.addEventListener(e,n=>{this[t](n)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=au(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=au(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=au(e.type),n=mf(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(n),o=!(gt.isDragging()||gt.isTransforming())||gt.hitOnDragEnabled;r&&o?(r._fireAndBubble(t.pointerout,{evt:e}),r._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[n+"targetShape"]=null):o&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=au(e.type),n=mf(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(o=>{const i=this.getIntersection(o);if(En.justDragged=!1,gt["_"+n+"ListenClick"]=!0,!i||!i.isListening()){this[n+"ClickStartShape"]=void 0;return}gt.capturePointerEventsEnabled&&i.setPointerCapture(o.id),this[n+"ClickStartShape"]=i,i._fireAndBubble(t.pointerdown,{evt:e,pointerId:o.id}),r=!0;const s=e.type.indexOf("touch")>=0;i.preventDefault()&&e.cancelable&&s&&e.preventDefault()}),r||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=au(e.type),n=mf(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(gt.isDragging()&&En.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(gt.isDragging()||gt.isTransforming())||gt.hitOnDragEnabled))return;const o={};let i=!1;const s=this._getTargetShape(n);this._changedPointerPositions.forEach(a=>{const l=f0(a.id)||this.getIntersection(a),u=a.id,c={evt:e,pointerId:u},d=s!==l;if(d&&s&&(s._fireAndBubble(t.pointerout,{...c},l),s._fireAndBubble(t.pointerleave,{...c},l)),l){if(o[l._id])return;o[l._id]=!0}l&&l.isListening()?(i=!0,d&&(l._fireAndBubble(t.pointerover,{...c},s),l._fireAndBubble(t.pointerenter,{...c},s),this[n+"targetShape"]=l),l._fireAndBubble(t.pointermove,{...c})):s&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:u}),this[n+"targetShape"]=null)}),i||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=au(e.type),n=mf(e.type);if(!t)return;this.setPointersPositions(e);const r=this[n+"ClickStartShape"],o=this[n+"ClickEndShape"],i={};let s=!1;this._changedPointerPositions.forEach(a=>{const l=f0(a.id)||this.getIntersection(a);if(l){if(l.releaseCapture(a.id),i[l._id])return;i[l._id]=!0}const u=a.id,c={evt:e,pointerId:u};let d=!1;gt["_"+n+"InDblClickWindow"]?(d=!0,clearTimeout(this[n+"DblTimeout"])):En.justDragged||(gt["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"])),this[n+"DblTimeout"]=setTimeout(function(){gt["_"+n+"InDblClickWindow"]=!1},gt.dblClickWindow),l&&l.isListening()?(s=!0,this[n+"ClickEndShape"]=l,l._fireAndBubble(t.pointerup,{...c}),gt["_"+n+"ListenClick"]&&r&&r===l&&(l._fireAndBubble(t.pointerclick,{...c}),d&&o&&o===l&&l._fireAndBubble(t.pointerdblclick,{...c}))):(this[n+"ClickEndShape"]=null,s||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),s=!0),gt["_"+n+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:u}),d&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:u}))}),s||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),gt["_"+n+"ListenClick"]=!1,e.cancelable&&n!=="touch"&&n!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(p0,{evt:e}):this._fire(p0,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(m0,{evt:e}):this._fire(m0,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=f0(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(su,h0(e)),uf(e.pointerId)}_lostpointercapture(e){uf(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let n=null,r=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,o=>{this._pointerPositions.push({id:o.identifier,x:(o.clientX-t.left)/t.scaleX,y:(o.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,o=>{this._changedPointerPositions.push({id:o.identifier,x:(o.clientX-t.left)/t.scaleX,y:(o.clientY-t.top)/t.scaleY})})):(n=(e.clientX-t.left)/t.scaleX,r=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:n,y:r},this._pointerPositions=[{x:n,y:r,id:Ae._getFirstPointerId(e)}],this._changedPointerPositions=[{x:n,y:r,id:Ae._getFirstPointerId(e)}])}_setPointerPosition(e){Ae.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new Xa({width:this.width(),height:this.height()}),this.bufferHitCanvas=new l0({pixelRatio:1,width:this.width(),height:this.height()}),!gt.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return Ae.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}};Fp.prototype.nodeType=$P,vr(Fp),ce.addGetterSetter(Fp,"container"),gt.isBrowser&&document.addEventListener("visibilitychange",()=>{gf.forEach(e=>{e.batchDraw()})});var L4="hasShadow",D4="shadowRGBA",P4="patternImage",O4="linearGradient",F4="radialGradient",Bp;function v0(){return Bp||(Bp=Ae.createCanvasElement().getContext("2d"),Bp)}const vf={};function sO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function aO(e){e.stroke()}function lO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function cO(e){e.stroke()}function uO(){this._clearCache(L4)}function dO(){this._clearCache(D4)}function fO(){this._clearCache(P4)}function hO(){this._clearCache(O4)}function pO(){this._clearCache(F4)}var ct=class extends yt{constructor(e){super(e);let t,n=0;for(;t=Ae.getHitColor(),!(t&&!(t in vf));)if(n++,n>=1e4){Ae.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=Ae.getRandomColor();break}this.colorKey=t,vf[t]=this}getContext(){return Ae.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Ae.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(L4,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(P4,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const e=v0().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(e&&e.setTransform){const t=new Ui;t.translate(this.fillPatternX(),this.fillPatternY()),t.rotate(gt.getAngle(this.fillPatternRotation())),t.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),t.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const n=t.getMatrix(),r=typeof DOMMatrix>"u"?{a:n[0],b:n[1],c:n[2],d:n[3],e:n[4],f:n[5]}:new DOMMatrix(n);e.setTransform(r)}return e}}_getLinearGradient(){return this._getCache(O4,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=v0(),n=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),o=t.createLinearGradient(n.x,n.y,r.x,r.y);for(let i=0;i<e.length;i+=2)o.addColorStop(e[i],e[i+1]);return o}}_getRadialGradient(){return this._getCache(F4,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=v0(),n=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),o=t.createRadialGradient(n.x,n.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let i=0;i<e.length;i+=2)o.addColorStop(e[i],e[i+1]);return o}}getShadowRGBA(){return this._getCache(D4,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=Ae.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const n=t.bufferHitCanvas;return n.getContext().clear(),this.drawHit(n,void 0,!0),n.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return yt.prototype.destroy.call(this),delete vf[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0)||t))return!1;const n=e||this.hasFill(),r=this.hasStroke(),o=this.getAbsoluteOpacity()!==1;if(n&&r&&o)return!0;const i=this.hasShadow(),s=this.shadowForStrokeEnabled();return!!(n&&r&&i&&s)}setStrokeHitEnabled(e){Ae.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,n=this.getParent();for(;n;){if(n.isCached()){t=!0;break}n=n.getParent()}const r=e.skipTransform,o=e.relativeTo||t&&this.getStage()||void 0,i=this.getSelfRect(),s=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,a=i.width+s,l=i.height+s,u=!e.skipShadow&&this.hasShadow(),c=u?this.shadowOffsetX():0,d=u?this.shadowOffsetY():0,h=a+Math.abs(c),m=l+Math.abs(d),p=u&&this.shadowBlur()||0,g={width:h+p*2,height:m+p*2,x:-(s/2+p)+Math.min(c,0)+i.x,y:-(s/2+p)+Math.min(d,0)+i.y};return r?g:this._transformedRect(g,o)}drawScene(e,t,n){const r=this.getLayer(),o=(e||r.getCanvas()).getContext(),i=this._getCanvasCache(),s=this.getSceneFunc(),a=this.hasShadow();let l;const u=t===this;if(!this.isVisible()&&!u)return this;if(i){o.save();const c=this.getAbsoluteTransform(t).getMatrix();return o.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedSceneCanvas(o),o.restore(),this}if(!s)return this;if(o.save(),this._useBufferCanvas()){l=this.getStage();const c=n||l.bufferCanvas,d=c.getContext();n?(d.save(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c.width,c.height),d.restore()):d.clear(),d.save(),d._applyLineJoin(this),d._applyMiterLimit(this);const h=this.getAbsoluteTransform(t).getMatrix();d.transform(h[0],h[1],h[2],h[3],h[4],h[5]),s.call(this,d,this),d.restore();const m=c.pixelRatio;a&&o._applyShadow(this),u||(o._applyOpacity(this),o._applyGlobalCompositeOperation(this)),o.drawImage(c._canvas,c.x||0,c.y||0,c.width/m,c.height/m)}else{if(o._applyLineJoin(this),o._applyMiterLimit(this),!u){const c=this.getAbsoluteTransform(t).getMatrix();o.transform(c[0],c[1],c[2],c[3],c[4],c[5]),o._applyOpacity(this),o._applyGlobalCompositeOperation(this)}a&&o._applyShadow(this),s.call(this,o,this)}return o.restore(),this}drawHit(e,t,n=!1){if(!this.shouldDrawHit(t,n))return this;const r=this.getLayer(),o=e||r.hitCanvas,i=o&&o.getContext(),s=this.hitFunc()||this.sceneFunc(),a=this._getCanvasCache(),l=a&&a.hit;if(this.colorKey||Ae.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),l){i.save();const u=this.getAbsoluteTransform(t).getMatrix();return i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedHitCanvas(i),i.restore(),this}if(!s)return this;if(i.save(),i._applyLineJoin(this),i._applyMiterLimit(this),this!==t){const u=this.getAbsoluteTransform(t).getMatrix();i.transform(u[0],u[1],u[2],u[3],u[4],u[5])}return s.call(this,i,this),i.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),n=this._getCachedSceneCanvas(),r=t.hit,o=r.getContext(),i=r.getWidth(),s=r.getHeight();o.clear(),o.drawImage(n._canvas,0,0,i,s);try{const a=o.getImageData(0,0,i,s),l=a.data,u=l.length,c=Ae._hexToRgb(this.colorKey);for(let d=0;d<u;d+=4)l[d+3]>e?(l[d]=c.r,l[d+1]=c.g,l[d+2]=c.b,l[d+3]=255):l[d+3]=0;o.putImageData(a,0,0)}catch(a){Ae.error("Unable to draw hit graph from cached scene canvas. "+a.message)}return this}hasPointerCapture(e){return y4(e,this)}setPointerCapture(e){b4(e,this)}releaseCapture(e){uf(e,this)}};ct.prototype._fillFunc=sO,ct.prototype._strokeFunc=aO,ct.prototype._fillFuncHit=lO,ct.prototype._strokeFuncHit=cO,ct.prototype._centroid=!1,ct.prototype.nodeType="Shape",vr(ct),ct.prototype.eventListeners={},ct.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",uO),ct.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",dO),ct.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",fO),ct.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",hO),ct.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",pO),ce.addGetterSetter(ct,"stroke",void 0,d4()),ce.addGetterSetter(ct,"strokeWidth",2,ft()),ce.addGetterSetter(ct,"fillAfterStrokeEnabled",!1),ce.addGetterSetter(ct,"hitStrokeWidth","auto",c0()),ce.addGetterSetter(ct,"strokeHitEnabled",!0,Vi()),ce.addGetterSetter(ct,"perfectDrawEnabled",!0,Vi()),ce.addGetterSetter(ct,"shadowForStrokeEnabled",!0,Vi()),ce.addGetterSetter(ct,"lineJoin"),ce.addGetterSetter(ct,"lineCap"),ce.addGetterSetter(ct,"miterLimit"),ce.addGetterSetter(ct,"sceneFunc"),ce.addGetterSetter(ct,"hitFunc"),ce.addGetterSetter(ct,"dash"),ce.addGetterSetter(ct,"dashOffset",0,ft()),ce.addGetterSetter(ct,"shadowColor",void 0,Kl()),ce.addGetterSetter(ct,"shadowBlur",0,ft()),ce.addGetterSetter(ct,"shadowOpacity",1,ft()),ce.addComponentsGetterSetter(ct,"shadowOffset",["x","y"]),ce.addGetterSetter(ct,"shadowOffsetX",0,ft()),ce.addGetterSetter(ct,"shadowOffsetY",0,ft()),ce.addGetterSetter(ct,"fillPatternImage"),ce.addGetterSetter(ct,"fill",void 0,d4()),ce.addGetterSetter(ct,"fillPatternX",0,ft()),ce.addGetterSetter(ct,"fillPatternY",0,ft()),ce.addGetterSetter(ct,"fillLinearGradientColorStops"),ce.addGetterSetter(ct,"strokeLinearGradientColorStops"),ce.addGetterSetter(ct,"fillRadialGradientStartRadius",0),ce.addGetterSetter(ct,"fillRadialGradientEndRadius",0),ce.addGetterSetter(ct,"fillRadialGradientColorStops"),ce.addGetterSetter(ct,"fillPatternRepeat","repeat"),ce.addGetterSetter(ct,"fillEnabled",!0),ce.addGetterSetter(ct,"strokeEnabled",!0),ce.addGetterSetter(ct,"shadowEnabled",!0),ce.addGetterSetter(ct,"dashEnabled",!0),ce.addGetterSetter(ct,"strokeScaleEnabled",!0),ce.addGetterSetter(ct,"fillPriority","color"),ce.addComponentsGetterSetter(ct,"fillPatternOffset",["x","y"]),ce.addGetterSetter(ct,"fillPatternOffsetX",0,ft()),ce.addGetterSetter(ct,"fillPatternOffsetY",0,ft()),ce.addComponentsGetterSetter(ct,"fillPatternScale",["x","y"]),ce.addGetterSetter(ct,"fillPatternScaleX",1,ft()),ce.addGetterSetter(ct,"fillPatternScaleY",1,ft()),ce.addComponentsGetterSetter(ct,"fillLinearGradientStartPoint",["x","y"]),ce.addComponentsGetterSetter(ct,"strokeLinearGradientStartPoint",["x","y"]),ce.addGetterSetter(ct,"fillLinearGradientStartPointX",0),ce.addGetterSetter(ct,"strokeLinearGradientStartPointX",0),ce.addGetterSetter(ct,"fillLinearGradientStartPointY",0),ce.addGetterSetter(ct,"strokeLinearGradientStartPointY",0),ce.addComponentsGetterSetter(ct,"fillLinearGradientEndPoint",["x","y"]),ce.addComponentsGetterSetter(ct,"strokeLinearGradientEndPoint",["x","y"]),ce.addGetterSetter(ct,"fillLinearGradientEndPointX",0),ce.addGetterSetter(ct,"strokeLinearGradientEndPointX",0),ce.addGetterSetter(ct,"fillLinearGradientEndPointY",0),ce.addGetterSetter(ct,"strokeLinearGradientEndPointY",0),ce.addComponentsGetterSetter(ct,"fillRadialGradientStartPoint",["x","y"]),ce.addGetterSetter(ct,"fillRadialGradientStartPointX",0),ce.addGetterSetter(ct,"fillRadialGradientStartPointY",0),ce.addComponentsGetterSetter(ct,"fillRadialGradientEndPoint",["x","y"]),ce.addGetterSetter(ct,"fillRadialGradientEndPointX",0),ce.addGetterSetter(ct,"fillRadialGradientEndPointY",0),ce.addGetterSetter(ct,"fillPatternRotation",0),ce.addGetterSetter(ct,"fillRule",void 0,Kl()),ce.backCompat(ct,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var mO="beforeDraw",gO="draw",B4=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],vO=B4.length,Yl=class extends fi{constructor(e){super(e),this.canvas=new Xa,this.hitCanvas=new l0({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){yt.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!yt.prototype.moveUp.call(this))return!1;const e=this.getStage();return!e||!e.content?!1:(e.content.removeChild(this.getNativeCanvasElement()),this.index<e.children.length-1?e.content.insertBefore(this.getNativeCanvasElement(),e.children[this.index+1].getCanvas()._canvas):e.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(yt.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(yt.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return yt.prototype.remove.call(this),e&&e.parentNode&&Ae._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&Ae.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),yt.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){Ae.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){Ae.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,Ae.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,n=!1;for(;;){for(let r=0;r<vO;r++){const o=B4[r],i=this._getIntersection({x:e.x+o.x*t,y:e.y+o.y*t}),s=i.shape;if(s)return s;if(n=!!i.antialiased,!i.antialiased)break}if(n)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,n=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,r=n[3];if(r===255){const o=vf[Ae.getHitColorKey(n[0],n[1],n[2])];return o?{shape:o}:{antialiased:!0}}else if(r>0)return{antialiased:!0};return{}}drawScene(e,t,n){const r=this.getLayer(),o=e||r&&r.getCanvas();return this._fire(mO,{node:this}),this.clearBeforeDraw()&&o.getContext().clear(),fi.prototype.drawScene.call(this,o,t,n),this._fire(gO,{node:this}),this}drawHit(e,t){const n=this.getLayer(),r=e||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),fi.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){Ae.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return Ae.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return Ae.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};Yl.prototype.nodeType="Layer",vr(Yl),ce.addGetterSetter(Yl,"imageSmoothingEnabled",!0),ce.addGetterSetter(Yl,"clearBeforeDraw",!0),ce.addGetterSetter(Yl,"hitGraphEnabled",!0,Vi());var y0=class extends Yl{constructor(e){super(e),this.listening(!1),Ae.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}};y0.prototype.nodeType="FastLayer",vr(y0);var lu=class extends fi{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&Ae.throw("You may only add groups and shapes to groups.")}};lu.prototype.nodeType="Group",vr(lu);var b0=(function(){return Wl.performance&&Wl.performance.now?function(){return Wl.performance.now()}:function(){return new Date().getTime()}})(),cu=class ju{constructor(t,n){this.id=ju.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:b0(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){let n=[];return t&&(n=Array.isArray(t)?t:[t]),this.layers=n,this}getLayers(){return this.layers}addLayer(t){const n=this.layers,r=n.length;for(let o=0;o<r;o++)if(n[o]._id===t._id)return!1;return this.layers.push(t),!0}isRunning(){const t=ju.animations,n=t.length;for(let r=0;r<n;r++)if(t[r].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=b0(),ju._addAnimation(this),this}stop(){return ju._removeAnimation(this),this}_updateFrameObject(t){this.frame.timeDiff=t-this.frame.lastTime,this.frame.lastTime=t,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(t){this.animations.push(t),this._handleAnimation()}static _removeAnimation(t){const n=t.id,r=this.animations,o=r.length;for(let i=0;i<o;i++)if(r[i].id===n){this.animations.splice(i,1);break}}static _runFrames(){const t={},n=this.animations;for(let r=0;r<n.length;r++){const o=n[r],i=o.layers,s=o.func;o._updateFrameObject(b0());const a=i.length;let l;if(s?l=s.call(o,o.frame)!==!1:l=!0,!!l)for(let u=0;u<a;u++){const c=i[u];c._id!==void 0&&(t[c._id]=c)}}for(const r in t)t.hasOwnProperty(r)&&t[r].batchDraw()}static _animationLoop(){const t=ju;t.animations.length?(t._runFrames(),Ae.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,Ae.requestAnimFrame(this._animationLoop))}};cu.animations=[],cu.animIdCounter=0,cu.animRunning=!1;var yO={node:1,duration:1,easing:1,onFinish:1,yoyo:1},bO=1,N4=2,z4=3,H4=["fill","stroke","shadowColor"],wO=0,CO=class{constructor(e,t,n,r,o,i,s){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=i,this._change=0,this.prevPos=0,this.yoyo=s,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=n,this._change=o-this.begin,this.pause()}fire(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=N4,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=z4,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===N4?this.setTime(e):this.state===z4&&this.setTime(this.duration-e)}pause(){this.state=bO,this.fire("onPause")}getTimer(){return new Date().getTime()}},Np=class Ir{constructor(t){const n=this,r=t.node,o=r._id,i=t.easing||yf.Linear,s=!!t.yoyo;let a,l;typeof t.duration>"u"?a=.3:t.duration===0?a=.001:a=t.duration,this.node=r,this._id=wO++;const u=r.getLayer()||(r instanceof gt.Stage?r.getLayers():null);u||Ae.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new cu(function(){n.tween.onEnterFrame()},u),this.tween=new CO(l,function(c){n._tweenFunc(c)},i,0,1,a*1e3,s),this._addListeners(),Ir.attrs[o]||(Ir.attrs[o]={}),Ir.attrs[o][this._id]||(Ir.attrs[o][this._id]={}),Ir.tweens[o]||(Ir.tweens[o]={});for(l in t)yO[l]===void 0&&this._addAttr(l,t[l]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,n){const r=this.node,o=r._id;let i,s,a,l,u;const c=Ir.tweens[o][t];c&&delete Ir.attrs[o][c][t];let d=r.getAttr(t);if(Ae._isArray(n))if(i=[],s=Math.max(n.length,d.length),t==="points"&&n.length!==d.length&&(n.length>d.length?(l=d,d=Ae._prepareArrayForTween(d,n,r.closed())):(a=n,n=Ae._prepareArrayForTween(n,d,r.closed()))),t.indexOf("fill")===0)for(let h=0;h<s;h++)if(h%2===0)i.push(n[h]-d[h]);else{const m=Ae.colorToRGBA(d[h]);u=Ae.colorToRGBA(n[h]),d[h]=m,i.push({r:u.r-m.r,g:u.g-m.g,b:u.b-m.b,a:u.a-m.a})}else for(let h=0;h<s;h++)i.push(n[h]-d[h]);else H4.indexOf(t)!==-1?(d=Ae.colorToRGBA(d),u=Ae.colorToRGBA(n),i={r:u.r-d.r,g:u.g-d.g,b:u.b-d.b,a:u.a-d.a}):i=n-d;Ir.attrs[o][this._id][t]={start:d,diff:i,end:n,trueEnd:a,trueStart:l},Ir.tweens[o][t]=this._id}_tweenFunc(t){const n=this.node,r=Ir.attrs[n._id][this._id];let o,i,s,a,l,u,c,d;for(o in r){if(i=r[o],s=i.start,a=i.diff,d=i.end,Ae._isArray(s))if(l=[],c=Math.max(s.length,d.length),o.indexOf("fill")===0)for(u=0;u<c;u++)u%2===0?l.push((s[u]||0)+a[u]*t):l.push("rgba("+Math.round(s[u].r+a[u].r*t)+","+Math.round(s[u].g+a[u].g*t)+","+Math.round(s[u].b+a[u].b*t)+","+(s[u].a+a[u].a*t)+")");else for(u=0;u<c;u++)l.push((s[u]||0)+a[u]*t);else H4.indexOf(o)!==-1?l="rgba("+Math.round(s.r+a.r*t)+","+Math.round(s.g+a.g*t)+","+Math.round(s.b+a.b*t)+","+(s.a+a.a*t)+")":l=s+a*t;n.setAttr(o,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=Ir.attrs[t._id][this._id];n.points&&n.points.trueEnd&&t.setAttr("points",n.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,n=Ir.attrs[t._id][this._id];n.points&&n.points.trueStart&&t.points(n.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,n=this._id,r=Ir.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const o in r)delete Ir.tweens[t][o];delete Ir.attrs[t][n],Ir.tweens[t]&&(Object.keys(Ir.tweens[t]).length===0&&delete Ir.tweens[t],Object.keys(Ir.attrs[t]).length===0&&delete Ir.attrs[t])}};Np.attrs={},Np.tweens={},yt.prototype.to=function(e){const t=e.onFinish;e.node=this,e.onFinish=function(){this.destroy(),t&&t()},new Np(e).play()};const yf={BackEaseIn(e,t,n,r){return n*(e/=r)*e*((1.70158+1)*e-1.70158)+t},BackEaseOut(e,t,n,r){return n*((e=e/r-1)*e*((1.70158+1)*e+1.70158)+1)+t},BackEaseInOut(e,t,n,r){let o=1.70158;return(e/=r/2)<1?n/2*(e*e*(((o*=1.525)+1)*e-o))+t:n/2*((e-=2)*e*(((o*=1.525)+1)*e+o)+2)+t},ElasticEaseIn(e,t,n,r,o,i){let s=0;return e===0?t:(e/=r)===1?t+n:(i||(i=r*.3),!o||o<Math.abs(n)?(o=n,s=i/4):s=i/(2*Math.PI)*Math.asin(n/o),-(o*Math.pow(2,10*(e-=1))*Math.sin((e*r-s)*(2*Math.PI)/i))+t)},ElasticEaseOut(e,t,n,r,o,i){let s=0;return e===0?t:(e/=r)===1?t+n:(i||(i=r*.3),!o||o<Math.abs(n)?(o=n,s=i/4):s=i/(2*Math.PI)*Math.asin(n/o),o*Math.pow(2,-10*e)*Math.sin((e*r-s)*(2*Math.PI)/i)+n+t)},ElasticEaseInOut(e,t,n,r,o,i){let s=0;return e===0?t:(e/=r/2)===2?t+n:(i||(i=r*(.3*1.5)),!o||o<Math.abs(n)?(o=n,s=i/4):s=i/(2*Math.PI)*Math.asin(n/o),e<1?-.5*(o*Math.pow(2,10*(e-=1))*Math.sin((e*r-s)*(2*Math.PI)/i))+t:o*Math.pow(2,-10*(e-=1))*Math.sin((e*r-s)*(2*Math.PI)/i)*.5+n+t)},BounceEaseOut(e,t,n,r){return(e/=r)<1/2.75?n*(7.5625*e*e)+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t},BounceEaseIn(e,t,n,r){return n-yf.BounceEaseOut(r-e,0,n,r)+t},BounceEaseInOut(e,t,n,r){return e<r/2?yf.BounceEaseIn(e*2,0,n,r)*.5+t:yf.BounceEaseOut(e*2-r,0,n,r)*.5+n*.5+t},EaseIn(e,t,n,r){return n*(e/=r)*e+t},EaseOut(e,t,n,r){return-n*(e/=r)*(e-2)+t},EaseInOut(e,t,n,r){return(e/=r/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t},StrongEaseIn(e,t,n,r){return n*(e/=r)*e*e*e*e+t},StrongEaseOut(e,t,n,r){return n*((e=e/r-1)*e*e*e*e+1)+t},StrongEaseInOut(e,t,n,r){return(e/=r/2)<1?n/2*e*e*e*e*e+t:n/2*((e-=2)*e*e*e*e+2)+t},Linear(e,t,n,r){return n*e/r+t}},U4=Ae._assign(gt,{Util:Ae,Transform:Ui,Node:yt,Container:fi,Stage:Fp,stages:gf,Layer:Yl,FastLayer:y0,Group:lu,DD:En,Shape:ct,shapes:vf,Animation:cu,Tween:Np,Easings:yf,Context:xp,Canvas:a0});var ha=class extends ct{_sceneFunc(e){const t=gt.getAngle(this.angle()),n=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,n),e.arc(0,0,this.innerRadius(),t,0,!n),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),n=this.clockwise(),r=gt.getAngle(n?360-this.angle():this.angle()),o=Math.cos(Math.min(r,Math.PI)),i=1,s=Math.sin(Math.min(Math.max(Math.PI,r),3*Math.PI/2)),a=Math.sin(Math.min(r,Math.PI/2)),l=o*(o>0?e:t),u=i*(i>0?t:e),c=s*(s>0?e:t),d=a*(a>0?t:e);return{x:l,y:n?-1*d:c,width:u-l,height:d-c}}};ha.prototype._centroid=!0,ha.prototype.className="Arc",ha.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"],vr(ha),ce.addGetterSetter(ha,"innerRadius",0,ft()),ce.addGetterSetter(ha,"outerRadius",0,ft()),ce.addGetterSetter(ha,"angle",0,ft()),ce.addGetterSetter(ha,"clockwise",!1,Vi());function w0(e,t,n,r,o,i,s){const a=Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2)),l=Math.sqrt(Math.pow(o-n,2)+Math.pow(i-r,2)),u=s*a/(a+l),c=s*l/(a+l);return[n-u*(o-e),r-u*(i-t),n+c*(o-e),r+c*(i-t)]}function V4(e,t){const n=e.length,r=[];for(let o=2;o<n-2;o+=2){const i=w0(e[o-2],e[o-1],e[o],e[o+1],e[o+2],e[o+3],t);isNaN(i[0])||(r.push(i[0]),r.push(i[1]),r.push(e[o]),r.push(e[o+1]),r.push(i[2]),r.push(i[3]))}return r}function _O(e){const t=[[e[0],e[2],e[4],e[6]],[e[1],e[3],e[5],e[7]]],n=[];for(const r of t){const o=-3*r[0]+9*r[1]-9*r[2]+3*r[3];if(o!==0){const i=6*r[0]-12*r[1]+6*r[2],s=-3*r[0]+3*r[1],a=i*i-4*o*s;if(a>=0){const l=Math.sqrt(a);n.push((-i+l)/(2*o)),n.push((-i-l)/(2*o))}}}return n.filter(r=>r>0&&r<1).flatMap(r=>t.map(o=>{const i=1-r;return i*i*i*o[0]+3*i*i*r*o[1]+3*i*r*r*o[2]+r*r*r*o[3]}))}var pa=class extends ct{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),n=t.length,r=this.tension(),o=this.closed(),i=this.bezier();if(!n)return;let s=0;if(e.beginPath(),e.moveTo(t[0],t[1]),r!==0&&n>4){const a=this.getTensionPoints(),l=a.length;for(s=o?0:4,o||e.quadraticCurveTo(a[0],a[1],a[2],a[3]);s<l-2;)e.bezierCurveTo(a[s++],a[s++],a[s++],a[s++],a[s++],a[s++]);o||e.quadraticCurveTo(a[l-2],a[l-1],t[n-2],t[n-1])}else if(i)for(s=2;s<n;)e.bezierCurveTo(t[s++],t[s++],t[s++],t[s++],t[s++],t[s++]);else for(s=2;s<n;s+=2)e.lineTo(t[s],t[s+1]);o?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():V4(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,n=this.tension(),r=w0(e[t-2],e[t-1],e[0],e[1],e[2],e[3],n),o=w0(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],n),i=V4(e,n);return[r[2],r[3]].concat(i).concat([o[0],o[1],e[t-2],e[t-1],o[2],o[3],r[0],r[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],..._O(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],n=e[0],r=e[1],o=e[1],i,s;for(let a=0;a<e.length/2;a++)i=e[a*2],s=e[a*2+1],t=Math.min(t,i),n=Math.max(n,i),r=Math.min(r,s),o=Math.max(o,s);return{x:t,y:r,width:n-t,height:o-r}}};pa.prototype.className="Line",pa.prototype._attrsAffectingSize=["points","bezier","tension"],vr(pa),ce.addGetterSetter(pa,"closed",!1),ce.addGetterSetter(pa,"bezier",!1),ce.addGetterSetter(pa,"tension",0,ft()),ce.addGetterSetter(pa,"points",[],NP());const SO=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],kO=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],AO=[[1],[1,1],[1,2,1],[1,3,3,1]],j4=(e,t,n)=>{let r,o;const s=n/2;r=0;for(let a=0;a<20;a++)o=s*SO[20][a]+s,r+=kO[20][a]*IO(e,t,o);return s*r},G4=(e,t,n)=>{n===void 0&&(n=1);const r=e[0]-2*e[1]+e[2],o=t[0]-2*t[1]+t[2],i=2*e[1]-2*e[0],s=2*t[1]-2*t[0],a=4*(r*r+o*o),l=4*(r*i+o*s),u=i*i+s*s;if(a===0)return n*Math.sqrt(Math.pow(e[2]-e[0],2)+Math.pow(t[2]-t[0],2));const c=l/(2*a),d=u/a,h=n+c,m=d-c*c,p=h*h+m>0?Math.sqrt(h*h+m):0,g=c*c+m>0?Math.sqrt(c*c+m):0,k=c+Math.sqrt(c*c+m)!==0?m*Math.log(Math.abs((h+p)/(c+g))):0;return Math.sqrt(a)/2*(h*p-c*g+k)};function IO(e,t,n){const r=C0(1,n,e),o=C0(1,n,t),i=r*r+o*o;return Math.sqrt(i)}var C0=(e,t,n)=>{const r=n.length-1;let o,i;if(r===0)return 0;if(e===0){i=0;for(let s=0;s<=r;s++)i+=AO[r][s]*Math.pow(1-t,r-s)*Math.pow(t,s)*n[s];return i}else{o=new Array(r);for(let s=0;s<r;s++)o[s]=r*(n[s+1]-n[s]);return C0(e-1,t,o)}};const W4=(e,t,n)=>{let r=1,o=e/t,i=(e-n(o))/t,s=0;for(;r>.001;){const a=n(o+i),l=Math.abs(e-a)/t;if(l<r)r=l,o+=i;else{const u=n(o-i),c=Math.abs(e-u)/t;c<r?(r=c,o-=i):i/=2}if(s++,s>500)break}return o};var Ii=class si extends ct{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=si.parsePathData(this.data()),this.pathLength=si.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let o=0;o<n.length;o++){const i=n[o].command,s=n[o].points;switch(i){case"L":t.lineTo(s[0],s[1]);break;case"M":t.moveTo(s[0],s[1]);break;case"C":t.bezierCurveTo(s[0],s[1],s[2],s[3],s[4],s[5]);break;case"Q":t.quadraticCurveTo(s[0],s[1],s[2],s[3]);break;case"A":const a=s[0],l=s[1],u=s[2],c=s[3],d=s[4],h=s[5],m=s[6],p=s[7],g=u>c?u:c,k=u>c?1:u/c,w=u>c?c/u:1;t.translate(a,l),t.rotate(m),t.scale(k,w),t.arc(0,0,g,d,d+h,1-p),t.scale(1/k,1/w),t.rotate(-m),t.translate(-a,-l);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(l){if(l.command==="A"){const u=l.points[4],c=l.points[5],d=l.points[4]+c;let h=Math.PI/180;if(Math.abs(u-d)<h&&(h=Math.abs(u-d)),c<0)for(let m=u-h;m>d;m-=h){const p=si.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],m,0);t.push(p.x,p.y)}else for(let m=u+h;m<d;m+=h){const p=si.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],m,0);t.push(p.x,p.y)}}else if(l.command==="C")for(let u=0;u<=1;u+=.01){const c=si.getPointOnCubicBezier(u,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);t.push(c.x,c.y)}else t=t.concat(l.points)});let n=t[0],r=t[0],o=t[1],i=t[1],s,a;for(let l=0;l<t.length/2;l++)s=t[l*2],a=t[l*2+1],isNaN(s)||(n=Math.min(n,s),r=Math.max(r,s)),isNaN(a)||(o=Math.min(o,a),i=Math.max(i,a));return{x:n,y:o,width:r-n,height:i-o}}getLength(){return this.pathLength}getPointAtLength(t){return si.getPointAtLengthOfDataArray(t,this.dataArray)}static getLineLength(t,n,r,o){return Math.sqrt((r-t)*(r-t)+(o-n)*(o-n))}static getPathLength(t){let n=0;for(let r=0;r<t.length;++r)n+=t[r].pathLength;return n}static getPointAtLengthOfDataArray(t,n){let r,o=0,i=n.length;if(!i)return null;for(;o<i&&t>n[o].pathLength;)t-=n[o].pathLength,++o;if(o===i)return r=n[o-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[o].command==="M"?(r=n[o].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[o].start.x,y:n[o].start.y};const s=n[o],a=s.points;switch(s.command){case"L":return si.getPointOnLine(t,s.start.x,s.start.y,a[0],a[1]);case"C":return si.getPointOnCubicBezier(W4(t,si.getPathLength(n),g=>j4([s.start.x,a[0],a[2],a[4]],[s.start.y,a[1],a[3],a[5]],g)),s.start.x,s.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return si.getPointOnQuadraticBezier(W4(t,si.getPathLength(n),g=>G4([s.start.x,a[0],a[2]],[s.start.y,a[1],a[3]],g)),s.start.x,s.start.y,a[0],a[1],a[2],a[3]);case"A":const l=a[0],u=a[1],c=a[2],d=a[3],h=a[5],m=a[6];let p=a[4];return p+=h*t/s.pathLength,si.getPointOnEllipticalArc(l,u,c,d,p,m)}return null}static getPointOnLine(t,n,r,o,i,s,a){s=s??n,a=a??r;const l=this.getLineLength(n,r,o,i);if(l<1e-10)return{x:n,y:r};if(o===n)return{x:s,y:a+(i>r?t:-t)};const u=(i-r)/(o-n),c=Math.sqrt(t*t/(1+u*u))*(o<n?-1:1),d=u*c;if(Math.abs(a-r-u*(s-n))<1e-10)return{x:s+c,y:a+d};const h=((s-n)*(o-n)+(a-r)*(i-r))/(l*l),m=n+h*(o-n),p=r+h*(i-r),g=this.getLineLength(s,a,m,p),k=Math.sqrt(t*t-g*g),w=Math.sqrt(k*k/(1+u*u))*(o<n?-1:1),S=u*w;return{x:m+w,y:p+S}}static getPointOnCubicBezier(t,n,r,o,i,s,a,l,u){function c(p){return p*p*p}function d(p){return 3*p*p*(1-p)}function h(p){return 3*p*(1-p)*(1-p)}function m(p){return(1-p)*(1-p)*(1-p)}return{x:l*c(t)+s*d(t)+o*h(t)+n*m(t),y:u*c(t)+a*d(t)+i*h(t)+r*m(t)}}static getPointOnQuadraticBezier(t,n,r,o,i,s,a){function l(d){return d*d}function u(d){return 2*d*(1-d)}function c(d){return(1-d)*(1-d)}return{x:s*l(t)+o*u(t)+n*c(t),y:a*l(t)+i*u(t)+r*c(t)}}static getPointOnEllipticalArc(t,n,r,o,i,s){const a=Math.cos(s),l=Math.sin(s),u={x:r*Math.cos(i),y:o*Math.sin(i)};return{x:t+(u.x*a-u.y*l),y:n+(u.x*l+u.y*a)}}static parsePathData(t){if(!t)return[];let n=t;const r=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];n=n.replace(new RegExp(" ","g"),",");for(let d=0;d<r.length;d++)n=n.replace(new RegExp(r[d],"g"),"|"+r[d]);const o=n.split("|"),i=[],s=[];let a=0,l=0;const u=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let c;for(let d=1;d<o.length;d++){let h=o[d],m=h.charAt(0);for(h=h.slice(1),s.length=0;c=u.exec(h);)s.push(c[0]);let p=[],g=m==="A"||m==="a"?0:-1;for(let k=0,w=s.length;k<w;k++){const S=s[k];if(S==="00"){p.push(0,0),g>=0&&(g+=2,g>=7&&(g-=7));continue}if(g>=0){if(g===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){p.push(parseInt(S[0],10)),p.push(parseInt(S[1],10)),p.push(parseFloat(S.slice(2))),g+=3,g>=7&&(g-=7);continue}if(S==="11"||S==="10"||S==="01"){p.push(parseInt(S[0],10)),p.push(parseInt(S[1],10)),g+=2,g>=7&&(g-=7);continue}if(S==="0"||S==="1"){p.push(parseInt(S,10)),g+=1,g>=7&&(g-=7);continue}}else if(g===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){p.push(parseInt(S[0],10)),p.push(parseFloat(S.slice(1))),g+=2,g>=7&&(g-=7);continue}if(S==="0"||S==="1"){p.push(parseInt(S,10)),g+=1,g>=7&&(g-=7);continue}}const y=parseFloat(S);isNaN(y)?p.push(0):p.push(y),g+=1,g>=7&&(g-=7)}else{const y=parseFloat(S);isNaN(y)?p.push(0):p.push(y)}}for(;p.length>0&&!isNaN(p[0]);){let k="",w=[];const S=a,y=l;let C,T,R,M,H,B,z,Z,P,N;switch(m){case"l":a+=p.shift(),l+=p.shift(),k="L",w.push(a,l);break;case"L":a=p.shift(),l=p.shift(),w.push(a,l);break;case"m":const I=p.shift(),L=p.shift();if(a+=I,l+=L,k="M",i.length>2&&i[i.length-1].command==="z"){for(let X=i.length-2;X>=0;X--)if(i[X].command==="M"){a=i[X].points[0]+I,l=i[X].points[1]+L;break}}w.push(a,l),m="l";break;case"M":a=p.shift(),l=p.shift(),k="M",w.push(a,l),m="L";break;case"h":a+=p.shift(),k="L",w.push(a,l);break;case"H":a=p.shift(),k="L",w.push(a,l);break;case"v":l+=p.shift(),k="L",w.push(a,l);break;case"V":l=p.shift(),k="L",w.push(a,l);break;case"C":w.push(p.shift(),p.shift(),p.shift(),p.shift()),a=p.shift(),l=p.shift(),w.push(a,l);break;case"c":w.push(a+p.shift(),l+p.shift(),a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="C",w.push(a,l);break;case"S":T=a,R=l,C=i[i.length-1],C.command==="C"&&(T=a+(a-C.points[2]),R=l+(l-C.points[3])),w.push(T,R,p.shift(),p.shift()),a=p.shift(),l=p.shift(),k="C",w.push(a,l);break;case"s":T=a,R=l,C=i[i.length-1],C.command==="C"&&(T=a+(a-C.points[2]),R=l+(l-C.points[3])),w.push(T,R,a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="C",w.push(a,l);break;case"Q":w.push(p.shift(),p.shift()),a=p.shift(),l=p.shift(),w.push(a,l);break;case"q":w.push(a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="Q",w.push(a,l);break;case"T":T=a,R=l,C=i[i.length-1],C.command==="Q"&&(T=a+(a-C.points[0]),R=l+(l-C.points[1])),a=p.shift(),l=p.shift(),k="Q",w.push(T,R,a,l);break;case"t":T=a,R=l,C=i[i.length-1],C.command==="Q"&&(T=a+(a-C.points[0]),R=l+(l-C.points[1])),a+=p.shift(),l+=p.shift(),k="Q",w.push(T,R,a,l);break;case"A":M=p.shift(),H=p.shift(),B=p.shift(),z=p.shift(),Z=p.shift(),P=a,N=l,a=p.shift(),l=p.shift(),k="A",w=this.convertEndpointToCenterParameterization(P,N,a,l,z,Z,M,H,B);break;case"a":M=p.shift(),H=p.shift(),B=p.shift(),z=p.shift(),Z=p.shift(),P=a,N=l,a+=p.shift(),l+=p.shift(),k="A",w=this.convertEndpointToCenterParameterization(P,N,a,l,z,Z,M,H,B);break}i.push({command:k||m,points:w,start:{x:S,y},pathLength:this.calcLength(S,y,k||m,w)})}(m==="z"||m==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,o){let i,s,a,l;const u=si;switch(r){case"L":return u.getLineLength(t,n,o[0],o[1]);case"C":return j4([t,o[0],o[2],o[4]],[n,o[1],o[3],o[5]],1);case"Q":return G4([t,o[0],o[2]],[n,o[1],o[3]],1);case"A":i=0;const c=o[4],d=o[5],h=o[4]+d;let m=Math.PI/180;if(Math.abs(c-h)<m&&(m=Math.abs(c-h)),s=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],c,0),d<0)for(l=c-m;l>h;l-=m)a=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],l,0),i+=u.getLineLength(s.x,s.y,a.x,a.y),s=a;else for(l=c+m;l<h;l+=m)a=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],l,0),i+=u.getLineLength(s.x,s.y,a.x,a.y),s=a;return a=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],h,0),i+=u.getLineLength(s.x,s.y,a.x,a.y),i}return 0}static convertEndpointToCenterParameterization(t,n,r,o,i,s,a,l,u){const c=u*(Math.PI/180),d=Math.cos(c)*(t-r)/2+Math.sin(c)*(n-o)/2,h=-1*Math.sin(c)*(t-r)/2+Math.cos(c)*(n-o)/2,m=d*d/(a*a)+h*h/(l*l);m>1&&(a*=Math.sqrt(m),l*=Math.sqrt(m));let p=Math.sqrt((a*a*(l*l)-a*a*(h*h)-l*l*(d*d))/(a*a*(h*h)+l*l*(d*d)));i===s&&(p*=-1),isNaN(p)&&(p=0);const g=p*a*h/l,k=p*-l*d/a,w=(t+r)/2+Math.cos(c)*g-Math.sin(c)*k,S=(n+o)/2+Math.sin(c)*g+Math.cos(c)*k,y=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},C=function(z,Z){return(z[0]*Z[0]+z[1]*Z[1])/(y(z)*y(Z))},T=function(z,Z){return(z[0]*Z[1]<z[1]*Z[0]?-1:1)*Math.acos(C(z,Z))},R=T([1,0],[(d-g)/a,(h-k)/l]),M=[(d-g)/a,(h-k)/l],H=[(-1*d-g)/a,(-1*h-k)/l];let B=T(M,H);return C(M,H)<=-1&&(B=Math.PI),C(M,H)>=1&&(B=0),s===0&&B>0&&(B=B-2*Math.PI),s===1&&B<0&&(B=B+2*Math.PI),[w,S,a,l,R,B,c,s]}};Ii.prototype.className="Path",Ii.prototype._attrsAffectingSize=["data"],vr(Ii),ce.addGetterSetter(Ii,"data");var Xl=class extends pa{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,n=this.points();let r=n;const o=this.tension()!==0&&n.length>4;o&&(r=this.getTensionPoints());const i=this.pointerLength(),s=n.length;let a,l;if(o){const d=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],n[s-2],n[s-1]],h=Ii.calcLength(r[r.length-4],r[r.length-3],"C",d),m=Ii.getPointOnQuadraticBezier(Math.min(1,1-i/h),d[0],d[1],d[2],d[3],d[4],d[5]);a=n[s-2]-m.x,l=n[s-1]-m.y}else a=n[s-2]-n[s-4],l=n[s-1]-n[s-3];const u=(Math.atan2(l,a)+t)%t,c=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(n[s-2],n[s-1]),e.rotate(u),e.moveTo(0,0),e.lineTo(-i,c/2),e.lineTo(-i,-c/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(n[0],n[1]),o?(a=(r[0]+r[2])/2-n[0],l=(r[1]+r[3])/2-n[1]):(a=n[2]-n[0],l=n[3]-n[1]),e.rotate((Math.atan2(-l,-a)+t)%t),e.moveTo(0,0),e.lineTo(-i,c/2),e.lineTo(-i,-c/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}};Xl.prototype.className="Arrow",vr(Xl),ce.addGetterSetter(Xl,"pointerLength",10,ft()),ce.addGetterSetter(Xl,"pointerWidth",10,ft()),ce.addGetterSetter(Xl,"pointerAtBeginning",!1),ce.addGetterSetter(Xl,"pointerAtEnding",!0);var uu=class extends ct{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}};uu.prototype._centroid=!0,uu.prototype.className="Circle",uu.prototype._attrsAffectingSize=["radius"],vr(uu),ce.addGetterSetter(uu,"radius",0,ft());var Ja=class extends ct{_sceneFunc(e){const t=this.radiusX(),n=this.radiusY();e.beginPath(),e.save(),t!==n&&e.scale(1,n/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}};Ja.prototype.className="Ellipse",Ja.prototype._centroid=!0,Ja.prototype._attrsAffectingSize=["radiusX","radiusY"],vr(Ja),ce.addComponentsGetterSetter(Ja,"radius",["x","y"]),ce.addGetterSetter(Ja,"radiusX",0,ft()),ce.addGetterSetter(Ja,"radiusY",0,ft());var ji=class GA extends ct{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),o=this.cornerRadius(),i=this.attrs.image;let s;if(i){const a=this.attrs.cropWidth,l=this.attrs.cropHeight;a&&l?s=[i,this.cropX(),this.cropY(),a,l,0,0,n,r]:s=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||o)&&(t.beginPath(),o?Ae.drawRoundedRectPath(t,n,r,o):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(o&&t.clip(),t.drawImage.apply(t,s))}_hitFunc(t){const n=this.width(),r=this.height(),o=this.cornerRadius();t.beginPath(),o?Ae.drawRoundedRectPath(t,n,r,o):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const o=Ae.createImageElement();o.onload=function(){n(new GA({image:o}))},o.onerror=r,o.crossOrigin="Anonymous",o.src=t}};ji.prototype.className="Image",ji.prototype._attrsAffectingSize=["image"],vr(ji),ce.addGetterSetter(ji,"cornerRadius",0,Rp(4)),ce.addGetterSetter(ji,"image"),ce.addComponentsGetterSetter(ji,"crop",["x","y","width","height"]),ce.addGetterSetter(ji,"cropX",0,ft()),ce.addGetterSetter(ji,"cropY",0,ft()),ce.addGetterSetter(ji,"cropWidth",0,ft()),ce.addGetterSetter(ji,"cropHeight",0,ft());var K4=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],EO="Change.konva",xO="none",_0="up",S0="right",k0="down",A0="left",TO=K4.length,I0=class extends lu{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,n;const r=function(){t._sync()};for(n=0;n<TO;n++)e.on(K4[n]+EO,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),n,r,o,i,s,a,l;if(e&&t){switch(n=e.width(),r=e.height(),o=t.pointerDirection(),i=t.pointerWidth(),l=t.pointerHeight(),s=0,a=0,o){case _0:s=n/2,a=-1*l;break;case S0:s=n+i,a=r/2;break;case k0:s=n/2,a=r+l;break;case A0:s=-1*i,a=r/2;break}t.setAttrs({x:-1*s,y:-1*a,width:n,height:r}),e.setAttrs({x:-1*s,y:-1*a})}}};I0.prototype.className="Label",vr(I0);var Ql=class extends ct{_sceneFunc(e){const t=this.width(),n=this.height(),r=this.pointerDirection(),o=this.pointerWidth(),i=this.pointerHeight(),s=this.cornerRadius();let a=0,l=0,u=0,c=0;typeof s=="number"?a=l=u=c=Math.min(s,t/2,n/2):(a=Math.min(s[0]||0,t/2,n/2),l=Math.min(s[1]||0,t/2,n/2),c=Math.min(s[2]||0,t/2,n/2),u=Math.min(s[3]||0,t/2,n/2)),e.beginPath(),e.moveTo(a,0),r===_0&&(e.lineTo((t-o)/2,0),e.lineTo(t/2,-1*i),e.lineTo((t+o)/2,0)),e.lineTo(t-l,0),e.arc(t-l,l,l,Math.PI*3/2,0,!1),r===S0&&(e.lineTo(t,(n-i)/2),e.lineTo(t+o,n/2),e.lineTo(t,(n+i)/2)),e.lineTo(t,n-c),e.arc(t-c,n-c,c,0,Math.PI/2,!1),r===k0&&(e.lineTo((t+o)/2,n),e.lineTo(t/2,n+i),e.lineTo((t-o)/2,n)),e.lineTo(u,n),e.arc(u,n-u,u,Math.PI/2,Math.PI,!1),r===A0&&(e.lineTo(0,(n+i)/2),e.lineTo(-1*o,n/2),e.lineTo(0,(n-i)/2)),e.lineTo(0,a),e.arc(a,a,a,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,n=this.pointerWidth(),r=this.pointerHeight(),o=this.pointerDirection(),i=this.width(),s=this.height();return o===_0?(t-=r,s+=r):o===k0?s+=r:o===A0?(e-=n*1.5,i+=n):o===S0&&(i+=n*1.5),{x:e,y:t,width:i,height:s}}};Ql.prototype.className="Tag",vr(Ql),ce.addGetterSetter(Ql,"pointerDirection",xO),ce.addGetterSetter(Ql,"pointerWidth",0,ft()),ce.addGetterSetter(Ql,"pointerHeight",0,ft()),ce.addGetterSetter(Ql,"cornerRadius",0,Rp(4));var bf=class extends ct{_sceneFunc(e){const t=this.cornerRadius(),n=this.width(),r=this.height();e.beginPath(),t?Ae.drawRoundedRectPath(e,n,r,t):e.rect(0,0,n,r),e.closePath(),e.fillStrokeShape(this)}};bf.prototype.className="Rect",vr(bf),ce.addGetterSetter(bf,"cornerRadius",0,Rp(4));var $a=class extends ct{_sceneFunc(e){const t=this._getPoints(),n=this.radius(),r=this.sides(),o=this.cornerRadius();if(e.beginPath(),o)Ae.drawRoundedPolygonPath(e,t,r,n,o);else{e.moveTo(t[0].x,t[0].y);for(let i=1;i<t.length;i++)e.lineTo(t[i].x,t[i].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,n=[];for(let r=0;r<e;r++)n.push({x:t*Math.sin(r*2*Math.PI/e),y:-1*t*Math.cos(r*2*Math.PI/e)});return n}getSelfRect(){const e=this._getPoints();let t=e[0].x,n=e[0].x,r=e[0].y,o=e[0].y;return e.forEach(i=>{t=Math.min(t,i.x),n=Math.max(n,i.x),r=Math.min(r,i.y),o=Math.max(o,i.y)}),{x:t,y:r,width:n-t,height:o-r}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}};$a.prototype.className="RegularPolygon",$a.prototype._centroid=!0,$a.prototype._attrsAffectingSize=["radius"],vr($a),ce.addGetterSetter($a,"radius",0,ft()),ce.addGetterSetter($a,"sides",0,ft()),ce.addGetterSetter($a,"cornerRadius",0,Rp(4));var q4=Math.PI*2,Zl=class extends ct{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,q4,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),q4,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}};Zl.prototype.className="Ring",Zl.prototype._centroid=!0,Zl.prototype._attrsAffectingSize=["innerRadius","outerRadius"],vr(Zl),ce.addGetterSetter(Zl,"innerRadius",0,ft()),ce.addGetterSetter(Zl,"outerRadius",0,ft());var ys=class extends ct{constructor(e){super(e),this._updated=!0,this.anim=new cu(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),n=this.frameIndex(),r=n*4,o=this.animations()[t],i=this.frameOffsets(),s=o[r+0],a=o[r+1],l=o[r+2],u=o[r+3],c=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,l,u),e.closePath(),e.fillStrokeShape(this)),c)if(i){const d=i[t],h=n*2;e.drawImage(c,s,a,l,u,d[h+0],d[h+1],l,u)}else e.drawImage(c,s,a,l,u,0,0,l,u)}_hitFunc(e){const t=this.animation(),n=this.frameIndex(),r=n*4,o=this.animations()[t],i=this.frameOffsets(),s=o[r+2],a=o[r+3];if(e.beginPath(),i){const l=i[t],u=n*2;e.rect(l[u+0],l[u+1],s,a)}else e.rect(0,0,s,a);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation();e<this.animations()[t].length/4-1?this.frameIndex(e+1):this.frameIndex(0)}};ys.prototype.className="Sprite",vr(ys),ce.addGetterSetter(ys,"animation"),ce.addGetterSetter(ys,"animations"),ce.addGetterSetter(ys,"frameOffsets"),ce.addGetterSetter(ys,"image"),ce.addGetterSetter(ys,"frameIndex",0,ft()),ce.addGetterSetter(ys,"frameRate",17,ft()),ce.backCompat(ys,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});var el=class extends ct{_sceneFunc(e){const t=this.innerRadius(),n=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-n);for(let o=1;o<r*2;o++){const i=o%2===0?n:t,s=i*Math.sin(o*Math.PI/r),a=-1*i*Math.cos(o*Math.PI/r);e.lineTo(s,a)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}};el.prototype.className="Star",el.prototype._centroid=!0,el.prototype._attrsAffectingSize=["innerRadius","outerRadius"],vr(el),ce.addGetterSetter(el,"numPoints",5,ft()),ce.addGetterSetter(el,"innerRadius",0,ft()),ce.addGetterSetter(el,"outerRadius",0,ft());function tl(e){return[...e].reduce((t,n,r,o)=>{if(/\p{Emoji}/u.test(n)){const i=o[r+1];i&&/\p{Emoji_Modifier}|\u200D/u.test(i)?(t.push(n+i),o[r+1]=""):t.push(n)}else/\p{Regional_Indicator}{2}/u.test(n+(o[r+1]||""))?t.push(n+o[r+1]):r>0&&/\p{Mn}|\p{Me}|\p{Mc}/u.test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}var du="auto",RO="center",Y4="inherit",wf="justify",MO="Change.konva",X4="2d",Q4="-",Z4="left",LO="text",DO="Text",PO="top",OO="bottom",J4="middle",$4="normal",FO="px ",zp=" ",BO="right",ek="rtl",NO="word",zO="char",tk="none",E0="…",nk=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],HO=nk.length,Cf=null;function UO(){if(Cf!==null)return Cf;Cf=!1;try{const e=document.createElement("canvas");e.width=10,e.height=10;const t=e.getContext(X4);if(t){t.globalAlpha=0,t.shadowColor="black",t.shadowBlur=5,t.shadowOffsetX=5,t.shadowOffsetY=5,t.fillStyle="black",t.font="10px Arial",t.fillText("X",0,10);const n=t.getImageData(0,0,10,10).data;for(let r=3;r<n.length;r+=4)if(n[r]>0){Cf=!0;break}}}catch{}return Cf}function VO(e){return e.split(",").map(t=>{t=t.trim();const n=t.indexOf(" ")>=0,r=t.indexOf('"')>=0||t.indexOf("'")>=0;return n&&!r&&(t=`"${t}"`),t}).join(", ")}var Hp;function x0(){return Hp||(Hp=Ae.createCanvasElement().getContext(X4),Hp)}function jO(e){e.fillText(this._partialText,this._partialTextX,this._partialTextY)}function GO(e){e.setAttr("miterLimit",2),e.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function WO(e){return e=e||{},!e.fillLinearGradientColorStops&&!e.fillRadialGradientColorStops&&!e.fillPatternImage&&(e.fill=e.fill||"black"),e}var nr=class extends ct{constructor(e){super(WO(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<HO;t++)this.on(nk[t]+MO,this._setTextData);this._setTextData()}_sceneFunc(e){var t,n;const r=this.textArr,o=r.length;if(!this.text())return;let i=this.padding(),s=this.fontSize(),a=this.lineHeight()*s,l=this.verticalAlign(),u=this.direction(),c=0,d=this.align(),h=this.getWidth(),m=this.letterSpacing(),p=this.charRenderFunc(),g=this.fill(),k=this.textDecoration(),w=this.underlineOffset(),S=k.indexOf("underline")!==-1,y=k.indexOf("line-through")!==-1,C;u=u===Y4?e.direction:u;let T=a/2,R=J4;if(!gt.legacyTextRendering){const M=this.measureSize("M");R="alphabetic",T=(((t=M.fontBoundingBoxAscent)!==null&&t!==void 0?t:M.actualBoundingBoxAscent)-((n=M.fontBoundingBoxDescent)!==null&&n!==void 0?n:M.actualBoundingBoxDescent))/2+a/2}for(u===ek&&e.setAttr("direction",u),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",R),e.setAttr("textAlign",Z4),l===J4?c=(this.getHeight()-o*a-i*2)/2:l===OO&&(c=this.getHeight()-o*a-i*2),e.translate(i,c+i),C=0;C<o;C++){let M=0,H=0;const B=r[C],z=B.text,Z=B.width,P=B.lastInParagraph;if(e.save(),d===BO?M+=h-Z-i*2:d===RO&&(M+=(h-Z-i*2)/2),S){e.save(),e.beginPath();const I=w??(gt.legacyTextRendering?Math.round(s/2):Math.round(s/4)),L=M,X=T+H+I;e.moveTo(L,X);const te=d===wf&&!P?h-i*2:Z;e.lineTo(L+Math.round(te),X),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||g,e.stroke(),e.restore()}const N=M;if(u!==ek&&(m!==0||d===wf||p)){const I=z.split(" ").length-1,L=tl(z);for(let X=0;X<L.length;X++){const te=L[X];if(te===" "&&!P&&d===wf&&(M+=(h-i*2-Z)/I),this._partialTextX=M,this._partialTextY=T+H,this._partialText=te,p){e.save();const le=r.slice(0,C).reduce((fe,Fe)=>fe+tl(Fe.text).length,0);p({char:te,index:X+le,x:M,y:T+H,lineIndex:C,column:X,isLastInLine:P,width:this.measureSize(te).width,context:e})}e.fillStrokeShape(this),p&&e.restore(),M+=this.measureSize(te).width+m}}else m!==0&&e.setAttr("letterSpacing",`${m}px`),this._partialTextX=M,this._partialTextY=T+H,this._partialText=z,e.fillStrokeShape(this);if(y){e.save(),e.beginPath();const I=gt.legacyTextRendering?0:-Math.round(s/4),L=N;e.moveTo(L,T+H+I);const X=d===wf&&!P?h-i*2:Z;e.lineTo(L+Math.round(X),T+H+I),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||g,e.stroke(),e.restore()}e.restore(),o>1&&(T+=a)}}_hitFunc(e){const t=this.getWidth(),n=this.getHeight();e.beginPath(),e.rect(0,0,t,n),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=Ae._isString(e)?e:e==null?"":e+"";return this._setAttr(LO,t),this}getWidth(){return this.attrs.width===du||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===du||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Ae.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,n,r,o,i,s,a,l,u,c,d;let h=x0(),m=this.fontSize(),p;h.save(),h.font=this._getContextFont(),p=h.measureText(e),h.restore();const g=m/100;return{actualBoundingBoxAscent:(t=p.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*g,actualBoundingBoxDescent:(n=p.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(r=p.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*g,actualBoundingBoxRight:(o=p.actualBoundingBoxRight)!==null&&o!==void 0?o:75.732421875*g,alphabeticBaseline:(i=p.alphabeticBaseline)!==null&&i!==void 0?i:0,emHeightAscent:(s=p.emHeightAscent)!==null&&s!==void 0?s:100*g,emHeightDescent:(a=p.emHeightDescent)!==null&&a!==void 0?a:-20*g,fontBoundingBoxAscent:(l=p.fontBoundingBoxAscent)!==null&&l!==void 0?l:91*g,fontBoundingBoxDescent:(u=p.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*g,hangingBaseline:(c=p.hangingBaseline)!==null&&c!==void 0?c:72.80000305175781*g,ideographicBaseline:(d=p.ideographicBaseline)!==null&&d!==void 0?d:-21*g,width:p.width,height:m}}_getContextFont(){return this.fontStyle()+zp+this.fontVariant()+zp+(this.fontSize()+FO)+VO(this.fontFamily())}_addTextLine(e){this.align()===wf&&(e=e.trim());const t=this._getTextWidth(e);return this.textArr.push({text:e,width:t,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),n=e.length;return x0().measureText(e).width+t*n}_setTextData(){let e=this.text().split(`
|
|
100
|
-
`),t=+this.fontSize(),n=0,r=this.lineHeight()*t,o=this.attrs.width,i=this.attrs.height,s=o!==du&&o!==void 0,a=i!==du&&i!==void 0,l=this.padding(),u=o-l*2,c=i-l*2,d=0,h=this.wrap(),m=h!==zO&&h!==tk,p=this.ellipsis();this.textArr=[],x0().font=this._getContextFont();const g=p?this._getTextWidth(E0):0;for(let k=0,w=e.length;k<w;++k){let S=e[k],y=this._getTextWidth(S);if(s&&y>u)for(;S.length>0;){let C=0,T=tl(S).length,R="",M=0;for(;C<T;){const H=C+T>>>1,B=tl(S).slice(0,H+1).join(""),z=this._getTextWidth(B);(p&&a&&d+r>c?z+g:z)<=u?(C=H+1,R=B,M=z):T=H}if(R){if(m){const H=tl(S),B=tl(R),z=H[B.length],Z=z===zp||z===Q4;let P;if(Z&&M<=u)P=B.length;else{const N=B.lastIndexOf(zp),I=B.lastIndexOf(Q4);P=Math.max(N,I)+1}P>0&&(C=P,R=H.slice(0,C).join(""),M=this._getTextWidth(R))}if(R=R.trimRight(),this._addTextLine(R),n=Math.max(n,M),d+=r,this._shouldHandleEllipsis(d)){this._tryToAddEllipsisToLastLine();break}if(S=tl(S).slice(C).join("").trimLeft(),S.length>0&&(y=this._getTextWidth(S),y<=u)){this._addTextLine(S),d+=r,n=Math.max(n,y);break}}else break}else this._addTextLine(S),d+=r,n=Math.max(n,y),this._shouldHandleEllipsis(d)&&k<w-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),a&&d+r>c)break}this.textHeight=t,this.textWidth=n}_shouldHandleEllipsis(e){const t=+this.fontSize(),n=this.lineHeight()*t,r=this.attrs.height,o=r!==du&&r!==void 0,i=r-this.padding()*2;return this.wrap()===tk||o&&e+n>i}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==du&&e!==void 0,n=e-this.padding()*2,r=this.ellipsis(),o=this.textArr[this.textArr.length-1];!o||!r||(t&&(this._getTextWidth(o.text+E0)<n||(o.text=o.text.slice(0,o.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(o.text+E0))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t||t&&this.getAbsoluteOpacity()!==1&&UO()?!0:super._useBufferCanvas()}};nr.prototype._fillFunc=jO,nr.prototype._strokeFunc=GO,nr.prototype.className=DO,nr.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],vr(nr),ce.overWriteSetter(nr,"width",c0()),ce.overWriteSetter(nr,"height",c0()),ce.addGetterSetter(nr,"direction",Y4),ce.addGetterSetter(nr,"fontFamily","Arial"),ce.addGetterSetter(nr,"fontSize",12,ft()),ce.addGetterSetter(nr,"fontStyle",$4),ce.addGetterSetter(nr,"fontVariant",$4),ce.addGetterSetter(nr,"padding",0,ft()),ce.addGetterSetter(nr,"align",Z4),ce.addGetterSetter(nr,"verticalAlign",PO),ce.addGetterSetter(nr,"lineHeight",1,ft()),ce.addGetterSetter(nr,"wrap",NO),ce.addGetterSetter(nr,"ellipsis",!1,Vi()),ce.addGetterSetter(nr,"letterSpacing",0,ft()),ce.addGetterSetter(nr,"text","",Kl()),ce.addGetterSetter(nr,"textDecoration",""),ce.addGetterSetter(nr,"underlineOffset",void 0,ft()),ce.addGetterSetter(nr,"charRenderFunc",void 0);var KO="",rk="normal";function ok(e){e.fillText(this.partialText,0,0)}function ik(e){e.strokeText(this.partialText,0,0)}var Vr=class extends ct{constructor(e){super(e),this.dummyCanvas=Ae.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return Ii.getPathLength(this.dataArray)}_getPointAtLength(e){return!this.attrs.data||e>this.pathLength?null:Ii.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=Ii.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),n=this.fill(),r=this.fontSize(),o=this.glyphInfo,i=t.indexOf("underline")!==-1,s=t.indexOf("line-through")!==-1;i&&e.beginPath();for(let a=0;a<o.length;a++){e.save();const l=o[a].p0;e.translate(l.x,l.y),e.rotate(o[a].rotation),this.partialText=o[a].text,e.fillStrokeShape(this),i&&(a===0&&e.moveTo(0,r/2+1),e.lineTo(o[a].width,r/2+1)),e.restore()}if(i&&(e.strokeStyle=n,e.lineWidth=r/20,e.stroke()),s){e.beginPath();for(let a=0;a<o.length;a++){e.save();const l=o[a].p0;e.translate(l.x,l.y),e.rotate(o[a].rotation),a===0&&e.moveTo(0,0),e.lineTo(o[a].width,0),e.restore()}e.strokeStyle=n,e.lineWidth=r/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const n=t[0].p0;e.moveTo(n.x,n.y)}for(let n=0;n<t.length;n++){const r=t[n].p1;e.lineTo(r.x,r.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return Ae.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return nr.prototype.setText.call(this,e)}_getContextFont(){return nr.prototype._getContextFont.call(this)}_getTextSize(e){const t=this.dummyCanvas.getContext("2d");t.save(),t.font=this._getContextFont();const n=t.measureText(e);return t.restore(),{width:n.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=tl(this.text()),t=[];let n=0;for(let h=0;h<e.length;h++)t.push({char:e[h],width:this._getTextSize(e[h]).width}),n+=t[h].width;const{width:r,height:o}=this._getTextSize(this.attrs.text);if(this.textWidth=n,this.textHeight=o,this.glyphInfo=[],!this.attrs.data)return null;const i=this.letterSpacing(),s=this.align(),a=this.kerningFunc(),l=Math.max(0,n-r),u=Math.max(this.textWidth+((this.attrs.text||"").length-1)*i,0);let c=0;s==="center"&&(c=Math.max(0,this.pathLength/2-u/2)),s==="right"&&(c=Math.max(0,this.pathLength-u));let d=c;for(let h=0;h<t.length;h++){const m=this._getPointAtLength(d);if(!m)return;const p=t[h].char;let g=t[h].width+i;if(p===" "&&s==="justify"){const R=this.text().split(" ").length-1;g+=(this.pathLength-u)/R}const k=d+g,w=this._getPointAtLength(k>this.pathLength&&k-this.pathLength<=l?this.pathLength:k);if(!w)return;const S=Ii.getLineLength(m.x,m.y,w.x,w.y);let y=0;if(a)try{y=a(t[h-1].char,p)*this.fontSize()}catch{y=0}m.x+=y,w.x+=y,this.textWidth+=y;const C=Ii.getPointOnLine(y+S/2,m.x,m.y,w.x,w.y),T=Math.atan2(w.y-m.y,w.x-m.x);this.glyphInfo.push({transposeX:C.x,transposeY:C.y,text:e[h],rotation:T,p0:m,p1:w,width:S}),d+=g}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(l){e.push(l.p0.x),e.push(l.p0.y),e.push(l.p1.x),e.push(l.p1.y)});let t=e[0]||0,n=e[0]||0,r=e[1]||0,o=e[1]||0,i,s;for(let l=0;l<e.length/2;l++)i=e[l*2],s=e[l*2+1],t=Math.min(t,i),n=Math.max(n,i),r=Math.min(r,s),o=Math.max(o,s);const a=this.fontSize();return{x:t-a/2,y:r-a/2,width:n-t+a,height:o-r+a}}destroy(){return Ae.releaseCanvas(this.dummyCanvas),super.destroy()}};Vr.prototype._fillFunc=ok,Vr.prototype._strokeFunc=ik,Vr.prototype._fillFuncHit=ok,Vr.prototype._strokeFuncHit=ik,Vr.prototype.className="TextPath",Vr.prototype._attrsAffectingSize=["text","fontSize","data"],vr(Vr),ce.addGetterSetter(Vr,"data"),ce.addGetterSetter(Vr,"fontFamily","Arial"),ce.addGetterSetter(Vr,"fontSize",12,ft()),ce.addGetterSetter(Vr,"fontStyle",rk),ce.addGetterSetter(Vr,"align","left"),ce.addGetterSetter(Vr,"letterSpacing",0,ft()),ce.addGetterSetter(Vr,"textBaseline","middle"),ce.addGetterSetter(Vr,"fontVariant",rk),ce.addGetterSetter(Vr,"text",KO),ce.addGetterSetter(Vr,"textDecoration",""),ce.addGetterSetter(Vr,"kerningFunc",void 0);var sk="tr-konva",qO=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(e=>e+`.${sk}`).join(" "),ak="nodesRect",YO=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],XO={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},QO="ontouchstart"in gt._global;function ZO(e,t,n){if(e==="rotater")return n;t+=Ae.degToRad(XO[e]||0);const r=(Ae.radToDeg(t)%360+360)%360;return Ae._inRange(r,337.5,360)||Ae._inRange(r,0,22.5)?"ns-resize":Ae._inRange(r,22.5,67.5)?"nesw-resize":Ae._inRange(r,67.5,112.5)?"ew-resize":Ae._inRange(r,112.5,157.5)?"nwse-resize":Ae._inRange(r,157.5,202.5)?"ns-resize":Ae._inRange(r,202.5,247.5)?"nesw-resize":Ae._inRange(r,247.5,292.5)?"ew-resize":Ae._inRange(r,292.5,337.5)?"nwse-resize":(Ae.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}var Up=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],lk=1e8;function JO(e){return{x:e.x+e.width/2*Math.cos(e.rotation)+e.height/2*Math.sin(-e.rotation),y:e.y+e.height/2*Math.cos(e.rotation)+e.width/2*Math.sin(e.rotation)}}function ck(e,t,n){const r=n.x+(e.x-n.x)*Math.cos(t)-(e.y-n.y)*Math.sin(t),o=n.y+(e.x-n.x)*Math.sin(t)+(e.y-n.y)*Math.cos(t);return{...e,rotation:e.rotation+t,x:r,y:o}}function $O(e,t){return ck(e,t,JO(e))}function eF(e,t,n){let r=t;for(let o=0;o<e.length;o++){const i=gt.getAngle(e[o]),s=Math.abs(i-t)%(Math.PI*2);Math.min(s,Math.PI*2-s)<n&&(r=i)}return r}var T0=0,kn=class extends lu{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._elementsCreated=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(qO,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return Ae.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return sk+this._id}setNodes(e=[]){return this._nodes&&this._nodes.length&&this.detach(),this._nodes=e=e.filter(t=>t.isAncestorOf(this)?(Ae.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0),e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(t=>{const n=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(t._attrsAffectingSize.length){const r=t._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");t.on(r,n)}t.on(YO.map(r=>r+`.${this._getEventNamespace()}`).join(" "),n),t.on(`absoluteTransformChange.${this._getEventNamespace()}`,n),this._proxyDrag(t)}),this._resetTransformCache(),this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,n=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(n,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,n=>{if(!t)return;const r=e.getAbsolutePosition(),o=r.x-t.x,i=r.y-t.y;this.nodes().forEach(s=>{if(s===e||s.isDragging())return;const a=s.getAbsolutePosition();s.setAbsolutePosition({x:a.x+o,y:a.y+i}),s.startDrag(n)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(ak),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(ak,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),n){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),o=e.getAbsoluteScale(n),i=e.getAbsolutePosition(n),s=r.x*o.x-e.offsetX()*o.x,a=r.y*o.y-e.offsetY()*o.y,l=(gt.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2);return ck({x:i.x+s*Math.cos(l)+a*Math.sin(-l),y:i.y+a*Math.cos(l)+s*Math.sin(l),width:r.width*o.x,height:r.height*o.y,rotation:l},-gt.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-lk,y:-lk,width:0,height:0,rotation:0};const e=[];this.nodes().map(a=>{const l=a.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),u=[{x:l.x,y:l.y},{x:l.x+l.width,y:l.y},{x:l.x+l.width,y:l.y+l.height},{x:l.x,y:l.y+l.height}],c=a.getAbsoluteTransform();u.forEach(function(d){const h=c.point(d);e.push(h)})});const t=new Ui;t.rotate(-gt.getAngle(this.rotation()));let n=1/0,r=1/0,o=-1/0,i=-1/0;e.forEach(function(a){const l=t.point(a);n===void 0&&(n=o=l.x,r=i=l.y),n=Math.min(n,l.x),r=Math.min(r,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y)}),t.invert();const s=t.point({x:n,y:r});return{x:s.x,y:s.y,width:o-n,height:i-r,rotation:gt.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Up.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(e){const t=new bf({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:QO?10:"auto"}),n=this;t.on("mousedown touchstart",function(r){n._handleMouseDown(r)}),t.on("dragstart",r=>{t.stopDrag(),r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),t.on("mouseenter",()=>{const r=ZO(e,gt.getAngle(this.rotation()),this.rotateAnchorCursor());t.getStage().content&&(t.getStage().content.style.cursor=r),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new ct({name:"back",width:0,height:0,sceneFunc(t,n){const r=n.getParent(),o=r.padding(),i=n.width(),s=n.height();if(t.beginPath(),t.rect(-o,-o,i+o*2,s+o*2),r.rotateEnabled()&&r.rotateLineVisible()){const a=r.rotateAnchorAngle(),l=r.rotateAnchorOffset(),u=Ae.degToRad(a),c=Math.sin(u),d=-Math.cos(u),h=i/2,m=s/2;let p=1/0;d<0?p=Math.min(p,-m/d):d>0&&(p=Math.min(p,(s-m)/d)),c<0?p=Math.min(p,-h/c):c>0&&(p=Math.min(p,(i-h)/c));const g=h+c*p,k=m+d*p,w=Ae._sign(s),S=g+c*l*w,y=k+d*l*w;t.moveTo(g,k),t.lineTo(S,y)}t.fillStrokeShape(n)},hitFunc:(t,n)=>{if(!this.shouldOverdrawWholeArea())return;const r=this.padding();t.beginPath(),t.rect(-r,-r,n.width()+r*2,n.height()+r*2),t.fillStrokeShape(n)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),n=t.width,r=t.height,o=Math.sqrt(Math.pow(n,2)+Math.pow(r,2));this.sin=Math.abs(r/o),this.cos=Math.abs(n/o),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const i=e.target.getAbsolutePosition(),s=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:s.x-i.x,y:s.y-i.y},T0++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(a=>{a._fire("transformstart",{evt:e.evt,target:a})})}_handleMouseMove(e){let t,n,r;const o=this.findOne("."+this._movingAnchorName),i=o.getStage();i.setPointersPositions(e);const s=i.getPointerPosition();let a={x:s.x-this._anchorDragOffset.x,y:s.y-this._anchorDragOffset.y};const l=o.getAbsolutePosition();this.anchorDragBoundFunc()&&(a=this.anchorDragBoundFunc()(l,a,e)),o.setAbsolutePosition(a);const u=o.getAbsolutePosition();if(l.x===u.x&&l.y===u.y)return;if(this._movingAnchorName==="rotater"){const w=this._getNodeRect();t=o.x()-w.width/2,n=-o.y()+w.height/2;const S=gt.getAngle(this.rotateAnchorAngle());let y=Math.atan2(-n,t)+Math.PI/2-S;w.height<0&&(y-=Math.PI);const C=gt.getAngle(this.rotation())+y,T=gt.getAngle(this.rotationSnapTolerance()),R=$O(w,eF(this.rotationSnaps(),C,T)-w.rotation);this._fitNodesInto(R,e);return}const c=this.shiftBehavior();let d;c==="inverted"?d=this.keepRatio()&&!e.shiftKey:c==="none"?d=this.keepRatio():d=this.keepRatio()||e.shiftKey;let h=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(w.x-o.x(),2)+Math.pow(w.y-o.y(),2));const S=this.findOne(".top-left").x()>w.x?-1:1,y=this.findOne(".top-left").y()>w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,this.findOne(".top-left").x(w.x-t),this.findOne(".top-left").y(w.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(o.y());else if(this._movingAnchorName==="top-right"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(o.x()-w.x,2)+Math.pow(w.y-o.y(),2));const S=this.findOne(".top-right").x()<w.x?-1:1,y=this.findOne(".top-right").y()>w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,this.findOne(".top-right").x(w.x+t),this.findOne(".top-right").y(w.y-n)}var m=o.position();this.findOne(".top-left").y(m.y),this.findOne(".bottom-right").x(m.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(o.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(o.x());else if(this._movingAnchorName==="bottom-left"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(w.x-o.x(),2)+Math.pow(o.y()-w.y,2));const S=w.x<o.x()?-1:1,y=o.y()<w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,o.x(w.x-t),o.y(w.y+n)}m=o.position(),this.findOne(".top-left").x(m.x),this.findOne(".bottom-right").y(m.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(o.y());else if(this._movingAnchorName==="bottom-right"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(o.x()-w.x,2)+Math.pow(o.y()-w.y,2));const S=this.findOne(".bottom-right").x()<w.x?-1:1,y=this.findOne(".bottom-right").y()<w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,this.findOne(".bottom-right").x(w.x+t),this.findOne(".bottom-right").y(w.y+n)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(h=this.centeredScaling()||e.altKey,h){const w=this.findOne(".top-left"),S=this.findOne(".bottom-right"),y=w.x(),C=w.y(),T=this.getWidth()-S.x(),R=this.getHeight()-S.y();S.move({x:-y,y:-C}),w.move({x:T,y:R})}const p=this.findOne(".top-left").getAbsolutePosition();t=p.x,n=p.y;const g=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),k=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:n,width:g,height:k,rotation:gt.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const n=this.getNode();T0--,this._fire("transformend",{evt:e,target:n}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),n&&this._nodes.forEach(r=>{var o;r._fire("transformend",{evt:e,target:r}),(o=r.getLayer())===null||o===void 0||o.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const n=this._getNodeRect(),r=1;if(Ae._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(Ae._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const o=new Ui;if(o.rotate(gt.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const d=o.point({x:-this.padding()*2,y:0});e.x+=d.x,e.y+=d.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const d=o.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const d=o.point({x:0,y:-this.padding()*2});e.x+=d.x,e.y+=d.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const d=o.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const d=this.boundBoxFunc()(n,e);d?e=d:Ae.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const i=1e7,s=new Ui;s.translate(n.x,n.y),s.rotate(n.rotation),s.scale(n.width/i,n.height/i);const a=new Ui,l=e.width/i,u=e.height/i;this.flipEnabled()===!1?(a.translate(e.x,e.y),a.rotate(e.rotation),a.translate(e.width<0?e.width:0,e.height<0?e.height:0),a.scale(Math.abs(l),Math.abs(u))):(a.translate(e.x,e.y),a.rotate(e.rotation),a.scale(l,u));const c=a.multiply(s.invert());this._nodes.forEach(d=>{var h;if(!d.getStage())return;const m=d.getParent().getAbsoluteTransform(),p=d.getTransform().copy();p.translate(d.offsetX(),d.offsetY());const g=new Ui;g.multiply(m.copy().invert()).multiply(c).multiply(m).multiply(p);const k=g.decompose();d.setAttrs(k),(h=d.getLayer())===null||h===void 0||h.batchDraw()}),this.rotation(Ae._getRotation(e.rotation)),this._nodes.forEach(d=>{this._fire("transform",{evt:t,target:d}),d._fire("transform",{evt:t,target:d})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(Ae._getRotation(t.rotation));const n=t.width,r=t.height,o=this.enabledAnchors(),i=this.resizeEnabled(),s=this.padding(),a=this.anchorSize(),l=this.find("._anchor");l.forEach(T=>{T.setAttrs({width:a,height:a,offsetX:a/2,offsetY:a/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:a/2+s,offsetY:a/2+s,visible:i&&o.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:a/2+s,visible:i&&o.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:a/2-s,offsetY:a/2+s,visible:i&&o.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:a/2+s,visible:i&&o.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:r/2,offsetX:a/2-s,visible:i&&o.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:a/2+s,offsetY:a/2-s,visible:i&&o.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:r,offsetY:a/2-s,visible:i&&o.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:r,offsetX:a/2-s,offsetY:a/2-s,visible:i&&o.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),c=this.rotateAnchorOffset(),d=Ae.degToRad(u),h=Math.sin(d),m=-Math.cos(d),p=n/2,g=r/2;let k=1/0;m<0?k=Math.min(k,-g/m):m>0&&(k=Math.min(k,(r-g)/m)),h<0?k=Math.min(k,-p/h):h>0&&(k=Math.min(k,(n-p)/h));const w=p+h*k,S=g+m*k,y=Ae._sign(r);this._batchChangeChild(".rotater",{x:w+h*c*y,y:S+m*c*y-s*m,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(T=>T.draggable()),x:0,y:0});const C=this.anchorStyleFunc();C&&l.forEach(T=>{C(T)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),lu.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...e){return this._elementsCreated?(Ae.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...e)}toObject(){return yt.prototype.toObject.call(this)}clone(e){return yt.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};kn.isTransforming=()=>T0>0;function tF(e){return e instanceof Array||Ae.warn("enabledAnchors value should be an array"),e instanceof Array&&e.forEach(function(t){Up.indexOf(t)===-1&&Ae.warn("Unknown anchor name: "+t+". Available names are: "+Up.join(", "))}),e||[]}kn.prototype.className="Transformer",vr(kn),ce.addGetterSetter(kn,"enabledAnchors",Up,tF),ce.addGetterSetter(kn,"flipEnabled",!0,Vi()),ce.addGetterSetter(kn,"resizeEnabled",!0),ce.addGetterSetter(kn,"anchorSize",10,ft()),ce.addGetterSetter(kn,"rotateEnabled",!0),ce.addGetterSetter(kn,"rotateLineVisible",!0),ce.addGetterSetter(kn,"rotationSnaps",[]),ce.addGetterSetter(kn,"rotateAnchorOffset",50,ft()),ce.addGetterSetter(kn,"rotateAnchorAngle",0,ft()),ce.addGetterSetter(kn,"rotateAnchorCursor","crosshair"),ce.addGetterSetter(kn,"rotationSnapTolerance",5,ft()),ce.addGetterSetter(kn,"borderEnabled",!0),ce.addGetterSetter(kn,"anchorStroke","rgb(0, 161, 255)"),ce.addGetterSetter(kn,"anchorStrokeWidth",1,ft()),ce.addGetterSetter(kn,"anchorFill","white"),ce.addGetterSetter(kn,"anchorCornerRadius",0,ft()),ce.addGetterSetter(kn,"borderStroke","rgb(0, 161, 255)"),ce.addGetterSetter(kn,"borderStrokeWidth",1,ft()),ce.addGetterSetter(kn,"borderDash"),ce.addGetterSetter(kn,"keepRatio",!0),ce.addGetterSetter(kn,"shiftBehavior","default"),ce.addGetterSetter(kn,"centeredScaling",!1),ce.addGetterSetter(kn,"ignoreStroke",!1),ce.addGetterSetter(kn,"padding",0,ft()),ce.addGetterSetter(kn,"nodes"),ce.addGetterSetter(kn,"node"),ce.addGetterSetter(kn,"boundBoxFunc"),ce.addGetterSetter(kn,"anchorDragBoundFunc"),ce.addGetterSetter(kn,"anchorStyleFunc"),ce.addGetterSetter(kn,"shouldOverdrawWholeArea",!1),ce.addGetterSetter(kn,"useSingleNodeRotation",!0),ce.backCompat(kn,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var ma=class extends ct{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,gt.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}};ma.prototype.className="Wedge",ma.prototype._centroid=!0,ma.prototype._attrsAffectingSize=["radius"],vr(ma),ce.addGetterSetter(ma,"radius",0,ft()),ce.addGetterSetter(ma,"angle",0,ft()),ce.addGetterSetter(ma,"clockwise",!1),ce.backCompat(ma,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function uk(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}var nF=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],rF=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function oF(e,t){const n=e.data,r=e.width,o=e.height;let i,s,a,l,u,c,d,h,m,p,g,k,w,S,y,C,T,R,M,H;const B=t+t+1,z=r-1,Z=o-1,P=t+1,N=P*(P+1)/2,I=new uk,L=nF[t],X=rF[t];let te=null,le=I,fe=null,Fe=null;for(let he=1;he<B;he++)le=le.next=new uk,he===P&&(te=le);le.next=I,a=s=0;for(let he=0;he<o;he++){k=w=S=y=l=u=c=d=0,h=P*(C=n[s]),m=P*(T=n[s+1]),p=P*(R=n[s+2]),g=P*(M=n[s+3]),l+=N*C,u+=N*T,c+=N*R,d+=N*M,le=I;for(let ge=0;ge<P;ge++)le.r=C,le.g=T,le.b=R,le.a=M,le=le.next;for(let ge=1;ge<P;ge++)i=s+((z<ge?z:ge)<<2),l+=(le.r=C=n[i])*(H=P-ge),u+=(le.g=T=n[i+1])*H,c+=(le.b=R=n[i+2])*H,d+=(le.a=M=n[i+3])*H,k+=C,w+=T,S+=R,y+=M,le=le.next;fe=I,Fe=te;for(let ge=0;ge<r;ge++)n[s+3]=M=d*L>>X,M!==0?(M=255/M,n[s]=(l*L>>X)*M,n[s+1]=(u*L>>X)*M,n[s+2]=(c*L>>X)*M):n[s]=n[s+1]=n[s+2]=0,l-=h,u-=m,c-=p,d-=g,h-=fe.r,m-=fe.g,p-=fe.b,g-=fe.a,i=a+((i=ge+t+1)<z?i:z)<<2,k+=fe.r=n[i],w+=fe.g=n[i+1],S+=fe.b=n[i+2],y+=fe.a=n[i+3],l+=k,u+=w,c+=S,d+=y,fe=fe.next,h+=C=Fe.r,m+=T=Fe.g,p+=R=Fe.b,g+=M=Fe.a,k-=C,w-=T,S-=R,y-=M,Fe=Fe.next,s+=4;a+=r}for(let he=0;he<r;he++){w=S=y=k=u=c=d=l=0,s=he<<2,h=P*(C=n[s]),m=P*(T=n[s+1]),p=P*(R=n[s+2]),g=P*(M=n[s+3]),l+=N*C,u+=N*T,c+=N*R,d+=N*M,le=I;for(let ae=0;ae<P;ae++)le.r=C,le.g=T,le.b=R,le.a=M,le=le.next;let ge=r;for(let ae=1;ae<=t;ae++)s=ge+he<<2,l+=(le.r=C=n[s])*(H=P-ae),u+=(le.g=T=n[s+1])*H,c+=(le.b=R=n[s+2])*H,d+=(le.a=M=n[s+3])*H,k+=C,w+=T,S+=R,y+=M,le=le.next,ae<Z&&(ge+=r);s=he,fe=I,Fe=te;for(let ae=0;ae<o;ae++)i=s<<2,n[i+3]=M=d*L>>X,M>0?(M=255/M,n[i]=(l*L>>X)*M,n[i+1]=(u*L>>X)*M,n[i+2]=(c*L>>X)*M):n[i]=n[i+1]=n[i+2]=0,l-=h,u-=m,c-=p,d-=g,h-=fe.r,m-=fe.g,p-=fe.b,g-=fe.a,i=he+((i=ae+P)<Z?i:Z)*r<<2,l+=k+=fe.r=n[i],u+=w+=fe.g=n[i+1],c+=S+=fe.b=n[i+2],d+=y+=fe.a=n[i+3],fe=fe.next,h+=C=Fe.r,m+=T=Fe.g,p+=R=Fe.b,g+=M=Fe.a,k-=C,w-=T,S-=R,y-=M,Fe=Fe.next,s+=r}}const iF=function(t){const n=Math.round(this.blurRadius());n>0&&oF(t,n)};ce.addGetterSetter(yt,"blurRadius",0,ft(),ce.afterSetFilter);const sF=function(e){const t=this.brightness()*255,n=e.data,r=n.length;for(let o=0;o<r;o+=4)n[o]+=t,n[o+1]+=t,n[o+2]+=t};ce.addGetterSetter(yt,"brightness",0,ft(),ce.afterSetFilter);const aF=function(e){const t=this.brightness(),n=e.data,r=n.length;for(let o=0;o<r;o+=4)n[o]=Math.min(255,n[o]*t),n[o+1]=Math.min(255,n[o+1]*t),n[o+2]=Math.min(255,n[o+2]*t)},lF=function(e){const t=Math.pow((this.contrast()+100)/100,2),n=e.data,r=n.length;let o=150,i=150,s=150;for(let a=0;a<r;a+=4)o=n[a],i=n[a+1],s=n[a+2],o/=255,o-=.5,o*=t,o+=.5,o*=255,i/=255,i-=.5,i*=t,i+=.5,i*=255,s/=255,s-=.5,s*=t,s+=.5,s*=255,o=o<0?0:o>255?255:o,i=i<0?0:i>255?255:i,s=s<0?0:s>255?255:s,n[a]=o,n[a+1]=i,n[a+2]=s};ce.addGetterSetter(yt,"contrast",0,ft(),ce.afterSetFilter);const cF=function(e){var t,n,r,o,i,s,a,l,u;const c=e.data,d=e.width,h=e.height,m=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),p=Math.min(1,Math.max(0,(o=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&o!==void 0?o:.5)),g=(a={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(s=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&s!==void 0?s:"top-left"])!==null&&a!==void 0?a:315,k=!!((u=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&u!==void 0&&u),w=m*10,S=p*255,y=g*Math.PI/180,C=Math.cos(y),T=Math.sin(y),R=128/1020*w,M=new Uint8ClampedArray(c),H=new Float32Array(d*h);for(let N=0,I=0;I<c.length;I+=4,N++)H[N]=.2126*M[I]+.7152*M[I+1]+.0722*M[I+2];const B=[-1,0,1,-2,0,2,-1,0,1],z=[-1,-2,-1,0,0,0,1,2,1],Z=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],P=N=>N<0?0:N>255?255:N;for(let N=1;N<h-1;N++)for(let I=1;I<d-1;I++){const L=N*d+I;let X=0,te=0;X+=H[L+Z[0]]*B[0],te+=H[L+Z[0]]*z[0],X+=H[L+Z[1]]*B[1],te+=H[L+Z[1]]*z[1],X+=H[L+Z[2]]*B[2],te+=H[L+Z[2]]*z[2],X+=H[L+Z[3]]*B[3],te+=H[L+Z[3]]*z[3],X+=H[L+Z[5]]*B[5],te+=H[L+Z[5]]*z[5],X+=H[L+Z[6]]*B[6],te+=H[L+Z[6]]*z[6],X+=H[L+Z[7]]*B[7],te+=H[L+Z[7]]*z[7],X+=H[L+Z[8]]*B[8],te+=H[L+Z[8]]*z[8];const le=P(S+(C*X+T*te)*R),fe=L*4;if(k){const Fe=le-S;c[fe]=P(M[fe]+Fe),c[fe+1]=P(M[fe+1]+Fe),c[fe+2]=P(M[fe+2]+Fe),c[fe+3]=M[fe+3]}else c[fe]=c[fe+1]=c[fe+2]=le,c[fe+3]=M[fe+3]}for(let N=0;N<d;N++){let I=N*4,L=((h-1)*d+N)*4;c[I]=M[I],c[I+1]=M[I+1],c[I+2]=M[I+2],c[I+3]=M[I+3],c[L]=M[L],c[L+1]=M[L+1],c[L+2]=M[L+2],c[L+3]=M[L+3]}for(let N=1;N<h-1;N++){let I=N*d*4,L=(N*d+(d-1))*4;c[I]=M[I],c[I+1]=M[I+1],c[I+2]=M[I+2],c[I+3]=M[I+3],c[L]=M[L],c[L+1]=M[L+1],c[L+2]=M[L+2],c[L+3]=M[L+3]}return e};ce.addGetterSetter(yt,"embossStrength",.5,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"embossWhiteLevel",.5,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"embossDirection","top-left",void 0,ce.afterSetFilter),ce.addGetterSetter(yt,"embossBlend",!1,void 0,ce.afterSetFilter);function R0(e,t,n,r,o){const i=n-t,s=o-r;if(i===0)return r+s/2;if(s===0)return r;let a=(e-t)/i;return a=s*a+r,a}const uF=function(e){const t=e.data,n=t.length;let r=t[0],o=r,i,s=t[1],a=s,l,u=t[2],c=u,d;const h=this.enhance();if(h===0)return;for(let y=0;y<n;y+=4)i=t[y+0],i<r?r=i:i>o&&(o=i),l=t[y+1],l<s?s=l:l>a&&(a=l),d=t[y+2],d<u?u=d:d>c&&(c=d);o===r&&(o=255,r=0),a===s&&(a=255,s=0),c===u&&(c=255,u=0);let m,p,g,k,w,S;if(h>0)m=o+h*(255-o),p=r-h*(r-0),g=a+h*(255-a),k=s-h*(s-0),w=c+h*(255-c),S=u-h*(u-0);else{const y=(o+r)*.5;m=o+h*(o-y),p=r+h*(r-y);const C=(a+s)*.5;g=a+h*(a-C),k=s+h*(s-C);const T=(c+u)*.5;w=c+h*(c-T),S=u+h*(u-T)}for(let y=0;y<n;y+=4)t[y+0]=R0(t[y+0],r,o,p,m),t[y+1]=R0(t[y+1],s,a,k,g),t[y+2]=R0(t[y+2],u,c,S,w)};ce.addGetterSetter(yt,"enhance",0,ft(),ce.afterSetFilter);const dF=function(e){const t=e.data,n=t.length;for(let r=0;r<n;r+=4){const o=.34*t[r]+.5*t[r+1]+.16*t[r+2];t[r]=o,t[r+1]=o,t[r+2]=o}};ce.addGetterSetter(yt,"hue",0,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"saturation",0,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"luminance",0,ft(),ce.afterSetFilter);const fF=function(e){const t=e.data,n=t.length,r=1,o=Math.pow(2,this.saturation()),i=Math.abs(this.hue()+360)%360,s=this.luminance()*127,a=r*o*Math.cos(i*Math.PI/180),l=r*o*Math.sin(i*Math.PI/180),u=.299*r+.701*a+.167*l,c=.587*r-.587*a+.33*l,d=.114*r-.114*a-.497*l,h=.299*r-.299*a-.328*l,m=.587*r+.413*a+.035*l,p=.114*r-.114*a+.293*l,g=.299*r-.3*a+1.25*l,k=.587*r-.586*a-1.05*l,w=.114*r+.886*a-.2*l;let S,y,C,T;for(let R=0;R<n;R+=4)S=t[R+0],y=t[R+1],C=t[R+2],T=t[R+3],t[R+0]=u*S+c*y+d*C+s,t[R+1]=h*S+m*y+p*C+s,t[R+2]=g*S+k*y+w*C+s,t[R+3]=T},hF=function(e){const t=e.data,n=t.length,r=Math.pow(2,this.value()),o=Math.pow(2,this.saturation()),i=Math.abs(this.hue()+360)%360,s=r*o*Math.cos(i*Math.PI/180),a=r*o*Math.sin(i*Math.PI/180),l=.299*r+.701*s+.167*a,u=.587*r-.587*s+.33*a,c=.114*r-.114*s-.497*a,d=.299*r-.299*s-.328*a,h=.587*r+.413*s+.035*a,m=.114*r-.114*s+.293*a,p=.299*r-.3*s+1.25*a,g=.587*r-.586*s-1.05*a,k=.114*r+.886*s-.2*a;for(let w=0;w<n;w+=4){const S=t[w+0],y=t[w+1],C=t[w+2],T=t[w+3];t[w+0]=l*S+u*y+c*C,t[w+1]=d*S+h*y+m*C,t[w+2]=p*S+g*y+k*C,t[w+3]=T}};ce.addGetterSetter(yt,"hue",0,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"saturation",0,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"value",0,ft(),ce.afterSetFilter);const pF=function(e){const t=e.data,n=t.length;for(let r=0;r<n;r+=4)t[r]=255-t[r],t[r+1]=255-t[r+1],t[r+2]=255-t[r+2]};var mF=function(e,t,n){const r=e.data,o=t.data,i=e.width,s=e.height,a=n.polarCenterX||i/2,l=n.polarCenterY||s/2;let u=Math.sqrt(a*a+l*l),c=i-a,d=s-l;const h=Math.sqrt(c*c+d*d);u=h>u?h:u;const m=s,p=i,g=360/p*Math.PI/180;for(let k=0;k<p;k+=1){const w=Math.sin(k*g),S=Math.cos(k*g);for(let y=0;y<m;y+=1){c=Math.floor(a+u*y/m*S),d=Math.floor(l+u*y/m*w);let C=(d*i+c)*4;const T=r[C+0],R=r[C+1],M=r[C+2],H=r[C+3];C=(k+y*i)*4,o[C+0]=T,o[C+1]=R,o[C+2]=M,o[C+3]=H}}},gF=function(e,t,n){const r=e.data,o=t.data,i=e.width,s=e.height,a=n.polarCenterX||i/2,l=n.polarCenterY||s/2;let u=Math.sqrt(a*a+l*l),c=i-a,d=s-l;const h=Math.sqrt(c*c+d*d);u=h>u?h:u;const m=s,p=i,g=n.polarRotation||0;let k,w;for(c=0;c<i;c+=1)for(d=0;d<s;d+=1){const S=c-a,y=d-l,C=Math.sqrt(S*S+y*y)*m/u;let T=(Math.atan2(y,S)*180/Math.PI+360+g)%360;T=T*p/360,k=Math.floor(T),w=Math.floor(C);let R=(w*i+k)*4;const M=r[R+0],H=r[R+1],B=r[R+2],z=r[R+3];R=(d*i+c)*4,o[R+0]=M,o[R+1]=H,o[R+2]=B,o[R+3]=z}};const vF=function(e){const t=e.width,n=e.height;let r,o,i,s,a,l,u,c,d,h,m=Math.round(this.kaleidoscopePower());const p=Math.round(this.kaleidoscopeAngle()),g=Math.floor(t*(p%360)/360);if(m<1)return;const k=Ae.createCanvasElement();k.width=t,k.height=n;const w=k.getContext("2d").getImageData(0,0,t,n);Ae.releaseCanvas(k),mF(e,w,{polarCenterX:t/2,polarCenterY:n/2});let S=t/Math.pow(2,m);for(;S<=8;)S=S*2,m-=1;S=Math.ceil(S);let y=S,C=0,T=y,R=1;for(g+S>t&&(C=y,T=0,R=-1),o=0;o<n;o+=1)for(r=C;r!==T;r+=R)i=Math.round(r+g)%t,d=(t*o+i)*4,a=w.data[d+0],l=w.data[d+1],u=w.data[d+2],c=w.data[d+3],h=(t*o+r)*4,w.data[h+0]=a,w.data[h+1]=l,w.data[h+2]=u,w.data[h+3]=c;for(o=0;o<n;o+=1)for(y=Math.floor(S),s=0;s<m;s+=1){for(r=0;r<y+1;r+=1)d=(t*o+r)*4,a=w.data[d+0],l=w.data[d+1],u=w.data[d+2],c=w.data[d+3],h=(t*o+y*2-r-1)*4,w.data[h+0]=a,w.data[h+1]=l,w.data[h+2]=u,w.data[h+3]=c;y*=2}gF(w,e,{polarRotation:0})};ce.addGetterSetter(yt,"kaleidoscopePower",2,ft(),ce.afterSetFilter),ce.addGetterSetter(yt,"kaleidoscopeAngle",0,ft(),ce.afterSetFilter);function Vp(e,t,n){let r=(n*e.width+t)*4;const o=[];return o.push(e.data[r++],e.data[r++],e.data[r++],e.data[r++]),o}function _f(e,t){return Math.sqrt(Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2)+Math.pow(e[2]-t[2],2))}function yF(e){const t=[0,0,0];for(let n=0;n<e.length;n++)t[0]+=e[n][0],t[1]+=e[n][1],t[2]+=e[n][2];return t[0]/=e.length,t[1]/=e.length,t[2]/=e.length,t}function bF(e,t){const n=Vp(e,0,0),r=Vp(e,e.width-1,0),o=Vp(e,0,e.height-1),i=Vp(e,e.width-1,e.height-1),s=t||10;if(_f(n,r)<s&&_f(r,i)<s&&_f(i,o)<s&&_f(o,n)<s){const a=yF([r,n,i,o]),l=[];for(let u=0;u<e.width*e.height;u++)l[u]=_f(a,[e.data[u*4],e.data[u*4+1],e.data[u*4+2]])<s?0:255;return l}}function wF(e,t){for(let n=0;n<e.width*e.height;n++)e.data[4*n+3]=t[n]}function CF(e,t,n){const r=[1,1,1,1,0,1,1,1,1],o=Math.round(Math.sqrt(r.length)),i=Math.floor(o/2),s=[];for(let a=0;a<n;a++)for(let l=0;l<t;l++){const u=a*t+l;let c=0;for(let d=0;d<o;d++)for(let h=0;h<o;h++){const m=a+d-i,p=l+h-i;if(m>=0&&m<n&&p>=0&&p<t){const g=m*t+p,k=r[d*o+h];c+=e[g]*k}}s[u]=c===2040?255:0}return s}function _F(e,t,n){const r=[1,1,1,1,1,1,1,1,1],o=Math.round(Math.sqrt(r.length)),i=Math.floor(o/2),s=[];for(let a=0;a<n;a++)for(let l=0;l<t;l++){const u=a*t+l;let c=0;for(let d=0;d<o;d++)for(let h=0;h<o;h++){const m=a+d-i,p=l+h-i;if(m>=0&&m<n&&p>=0&&p<t){const g=m*t+p,k=r[d*o+h];c+=e[g]*k}}s[u]=c>=1020?255:0}return s}function SF(e,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],o=Math.round(Math.sqrt(r.length)),i=Math.floor(o/2),s=[];for(let a=0;a<n;a++)for(let l=0;l<t;l++){const u=a*t+l;let c=0;for(let d=0;d<o;d++)for(let h=0;h<o;h++){const m=a+d-i,p=l+h-i;if(m>=0&&m<n&&p>=0&&p<t){const g=m*t+p,k=r[d*o+h];c+=e[g]*k}}s[u]=c}return s}const kF=function(e){let t=bF(e,this.threshold());return t&&(t=CF(t,e.width,e.height),t=_F(t,e.width,e.height),t=SF(t,e.width,e.height),wF(e,t)),e};ce.addGetterSetter(yt,"threshold",0,ft(),ce.afterSetFilter);const AF=function(e){const t=this.noise()*255,n=e.data,r=n.length,o=t/2;for(let i=0;i<r;i+=4)n[i+0]+=o-2*o*Math.random(),n[i+1]+=o-2*o*Math.random(),n[i+2]+=o-2*o*Math.random()};ce.addGetterSetter(yt,"noise",.2,ft(),ce.afterSetFilter);const IF=function(e){let t=Math.ceil(this.pixelSize()),n=e.width,r=e.height,o=Math.ceil(n/t),i=Math.ceil(r/t),s=e.data;if(t<=0){Ae.error("pixelSize value can not be <= 0");return}for(let a=0;a<o;a+=1)for(let l=0;l<i;l+=1){let u=0,c=0,d=0,h=0;const m=a*t,p=m+t,g=l*t,k=g+t;let w=0;for(let S=m;S<p;S+=1)if(!(S>=n))for(let y=g;y<k;y+=1){if(y>=r)continue;const C=(n*y+S)*4;u+=s[C+0],c+=s[C+1],d+=s[C+2],h+=s[C+3],w+=1}u=u/w,c=c/w,d=d/w,h=h/w;for(let S=m;S<p;S+=1)if(!(S>=n))for(let y=g;y<k;y+=1){if(y>=r)continue;const C=(n*y+S)*4;s[C+0]=u,s[C+1]=c,s[C+2]=d,s[C+3]=h}}};ce.addGetterSetter(yt,"pixelSize",8,ft(),ce.afterSetFilter);const EF=function(e){const t=Math.round(this.levels()*254)+1,n=e.data,r=n.length,o=255/t;for(let i=0;i<r;i+=1)n[i]=Math.floor(n[i]/o)*o};ce.addGetterSetter(yt,"levels",.5,ft(),ce.afterSetFilter);const xF=function(e){const t=e.data,n=t.length,r=this.red(),o=this.green(),i=this.blue();for(let s=0;s<n;s+=4){const a=(.34*t[s]+.5*t[s+1]+.16*t[s+2])/255;t[s]=a*r,t[s+1]=a*o,t[s+2]=a*i,t[s+3]=t[s+3]}};ce.addGetterSetter(yt,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"blue",0,u4,ce.afterSetFilter);const TF=function(e){const t=e.data,n=t.length,r=this.red(),o=this.green(),i=this.blue(),s=this.alpha();for(let a=0;a<n;a+=4){const l=1-s;t[a]=r*s+t[a]*l,t[a+1]=o*s+t[a+1]*l,t[a+2]=i*s+t[a+2]*l}};ce.addGetterSetter(yt,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"blue",0,u4,ce.afterSetFilter),ce.addGetterSetter(yt,"alpha",1,function(e){return this._filterUpToDate=!1,e>1?1:e<0?0:e});const RF=function(e){const t=e.data,n=t.length;for(let r=0;r<n;r+=4){const o=t[r+0],i=t[r+1],s=t[r+2];t[r+0]=Math.min(255,o*.393+i*.769+s*.189),t[r+1]=Math.min(255,o*.349+i*.686+s*.168),t[r+2]=Math.min(255,o*.272+i*.534+s*.131)}},MF=function(e){const n=e.data;for(let r=0;r<n.length;r+=4){const o=n[r],i=n[r+1],s=n[r+2];.2126*o+.7152*i+.0722*s>=128&&(n[r]=255-o,n[r+1]=255-i,n[r+2]=255-s)}return e},LF=function(e){const t=this.threshold()*255,n=e.data,r=n.length;for(let o=0;o<r;o+=1)n[o]=n[o]<t?0:255};ce.addGetterSetter(yt,"threshold",.5,ft(),ce.afterSetFilter);var DF=U4.Util._assign(U4,{Arc:ha,Arrow:Xl,Circle:uu,Ellipse:Ja,Image:ji,Label:I0,Tag:Ql,Line:pa,Path:Ii,Rect:bf,RegularPolygon:$a,Ring:Zl,Sprite:ys,Star:el,Text:nr,TextPath:Vr,Transformer:kn,Wedge:ma,Filters:{Blur:iF,Brightness:aF,Brighten:sF,Contrast:lF,Emboss:cF,Enhance:uF,Grayscale:dF,HSL:fF,HSV:hF,Invert:pF,Kaleidoscope:vF,Mask:kF,Noise:AF,Pixelate:IF,Posterize:EF,RGB:xF,RGBA:TF,Sepia:RF,Solarize:MF,Threshold:LF}});It();var PF=["dialog","floating"],dk=["top-right","top-left","bottom-right","bottom-left","top-center","bottom-center"];function OF(e){if(!e||typeof e!="object")throw new Error("SurfaceManager: request must be a non-null object.");if(!PF.includes(e.mode))throw new Error(`SurfaceManager: mode must be "dialog" or "floating", got "${e.mode}".`);const t="kind"in e&&e.kind!=null,n="component"in e&&e.component!=null,r="render"in e&&typeof e.render=="function";if(n&&r)throw new Error('SurfaceManager: request cannot provide both "component" and "render". Use one or the other.');if(!t&&!n&&!r)throw new Error('SurfaceManager: request must provide "kind" (intent-based) or "component"/"render" (direct-render).');if(e.mode==="floating"&&e.floating?.placement!=null&&!dk.includes(e.floating.placement))throw new Error(`SurfaceManager: floating.placement must be one of ${dk.join(", ")}, got "${e.floating.placement}".`)}var FF=class{activeDialog=Ur(null);activeFloating=Ur(null);#t=!1;#n=1;#e;constructor({getModuleConfig:e}){this.#e=e}open(e){if(this.#t)return this.#l(e);OF(e);const t=this.#u(e),{component:n,props:r,render:o}=this.#d(t);let i,s=!1;const a=new Promise(m=>{i=p=>s?!1:(s=!0,m(p),!0)});let l;const u=m=>{i({status:"submitted",data:m})&&this.#s(l)},c=m=>{i({status:"closed",reason:m})&&this.#s(l)};l={id:t.id,mode:t.mode,request:t,component:n,props:r,render:o,resolve:u,close:c,settle:m=>i(m),get settled(){return s}};const d=t.mode==="dialog"?"activeDialog":"activeFloating",h=this[d].value;return h&&!h.settled&&h.settle({status:"replaced",replacedBy:t.id}),this[d].value=l,{id:t.id,mode:t.mode,close:m=>this.#i(l,m),result:a}}close(e,t){if(e!=null){const o=this.#a(e);o&&this.#i(o,t);return}const n=this.activeDialog.value;if(n&&!n.settled){this.#i(n,t);return}const r=this.activeFloating.value;r&&!r.settled&&this.#i(r,t)}settleAll(e){for(const t of[this.activeDialog,this.activeFloating]){const n=t.value;n&&!n.settled&&n.settle(e),t.value=null}}destroy(){this.#t=!0,this.settleAll({status:"destroyed"})}#i(e,t){e.settled||(e.settle({status:"closed",reason:t}),this.#s(e))}#s(e){const t=e.mode==="dialog"?this.activeDialog:this.activeFloating;t.value===e&&(t.value=null)}#a(e){return this.activeDialog.value?.id===e?this.activeDialog.value:this.activeFloating.value?.id===e?this.activeFloating.value:null}#u(e){const t=e.id??`surface-${this.#n++}`,n=this.#e()??{},r=e.mode==="dialog"?n.dialog:n.floating,o=e.mode==="dialog"?{maxWidth:r?.maxWidth,...e.dialog}:e.dialog,i=e.mode==="floating"?{placement:r?.placement??"top-right",width:r?.width,maxWidth:r?.maxWidth,maxHeight:r?.maxHeight,autoFocus:r?.autoFocus??!0,closeOnOutsidePointerDown:r?.closeOnOutsidePointerDown??!1,...e.floating}:e.floating;return{...e,id:t,closeOnEscape:e.closeOnEscape??r?.closeOnEscape??!0,closeOnBackdrop:e.mode==="dialog"?e.closeOnBackdrop??r?.closeOnBackdrop??!0:!1,dialog:o,floating:i}}#d(e){if("component"in e&&e.component!=null)return{component:e.component,props:e.props};if("render"in e&&typeof e.render=="function")return{render:e.render};const t=this.#e()?.resolver;if(typeof t=="function"){const n=t(e);if(n!=null){if(n.type==="none")throw new Error(`SurfaceManager: resolver explicitly suppressed surface for kind "${e.kind}".`);if(n.type==="custom")return{component:n.component,props:n.props};if(n.type==="external")return{render:n.render}}}throw new Error(`SurfaceManager: no renderer resolved for kind "${e.kind}". Provide a resolver via surfaces.resolver, or use a direct-render request.`)}#l(e){return{id:e?.id??`surface-${this.#n++}`,mode:e?.mode??"dialog",close:()=>{},result:Promise.resolve({status:"destroyed"})}}},BF="https://docs.superdoc.dev/guides/migration/document-api",fk=new Set;function NF(e,t){fk.has(e)||(fk.add(e),console.warn(t))}var zF={state:"editor.state",view:"editor.view",schema:"editor.schema",commands:"editor.commands",chain:"editor.chain()",can:"editor.can()",dispatch:"editor.dispatch()"},hk=Symbol.for("superdoc:rawEditor"),pk=new WeakMap;function mk(e){return!e||e[hk]?e:new Proxy(e,{get(t,n){if(n===hk)return t;const r=zF[n];r&&NF(`deprecated:${String(n)}`,`[SuperDoc] ${r} is deprecated and will be removed in a future version. Use the Document API (editor.doc) instead. See ${BF}`);const o=Reflect.get(t,n,t);if(typeof o=="function"){let i=pk.get(t);return i||(i=new Map,pk.set(t,i)),i.has(n)||i.set(n,o.bind(t)),i.get(n)}return o}})}var gk=["review","original","final","off"],HF=["paired","independent"],vk=Symbol.for("@superdoc/trackChanges:normalized"),yk=new Set;function bk(e,t){yk.has(e)||(yk.add(e),console.warn(`[SuperDoc] ${e} is deprecated — use ${t} instead.`))}function wk(e,t,n){return typeof e=="boolean"?e:typeof t=="boolean"?t:n}function UF(e,t,n){return typeof e=="string"&&gk.includes(e)?e:typeof t=="string"&&gk.includes(t)?t:n}function VF(e){return typeof e=="string"&&HF.includes(e)?e:null}function Jl(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function jF(e){const t=e[vk]===!0;Jl(e.modules)||(e.modules={});const n=Jl(e.modules.trackChanges),r=Jl(e.trackChanges),o=Jl(e.layoutEngineOptions?.trackedChanges);t||(r&&bk("config.trackChanges","config.modules.trackChanges"),o&&bk("config.layoutEngineOptions.trackedChanges","config.modules.trackChanges"));const i=wk(n?.visible,r?.visible,!1),s=wk(n?.enabled,o?.enabled,!0),a=VF(n?.replacements)??"paired",l=Jl(n?.authorColors)?n.authorColors:void 0,u=Jl(n?.semanticColors)?n.semanticColors:void 0,c=e.documentMode==="viewing"?i?"review":"original":"review",d=UF(n?.mode,o?.mode,c),h={visible:i,mode:d,enabled:s,replacements:a};return l&&(h.authorColors=l),u&&(h.semanticColors=u),e.modules.trackChanges=h,e.trackChanges={visible:i},Jl(e.layoutEngineOptions)||(e.layoutEngineOptions={}),e.layoutEngineOptions.trackedChanges={mode:d,enabled:s},Object.defineProperty(e,vk,{value:!0,writable:!0,configurable:!0,enumerable:!1}),h}const M0=Object.freeze({id:null,name:"Default SuperDoc user",email:null});function GF(e){return!e||typeof e!="object"?{...M0}:{...M0,...e}}function Sf(...e){const t={};for(const n of e)if(!(typeof n!="object"||n===null))for(const[r,o]of Object.entries(n))o!==void 0&&(t[r]=o);return t}function Ck(...e){for(const t of e)if(t!==void 0)return t}var _k=Object.freeze({toolbar:!0,comments:!0,contextMenu:!0,search:!1,linkPopover:!1,ruler:!1,contentControls:!0}),WF=Object.freeze(["left","center","right"]),kj=Object.freeze(Object.keys(_k)),jp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Sk(e,t){const n=e?.[t];return n===!1?!1:n===void 0?_k[t]:!0}function KF(e,t){const n=e?.[t];return jp(n)?n:{}}function kk(e={}){const t=e.ui,n=t===!1,r=jp(t)?t:void 0,o=w=>!n&&Sk(r,w),i=w=>n?!1:r?.[w]===void 0?void 0:Sk(r,w),s=w=>n?{}:KF(r,w),a=n||i("ruler")===!1,l=s("toolbar"),u=e.modules?.toolbar,c=jp(u)?u:{},d=[l.groups,c.groups],h=d.find(jp),m=Ck(d.find(Array.isArray),c.toolbarGroups,e.toolbarGroups),p=Array.isArray(m)?m:null,g=(w,S)=>Object.prototype.hasOwnProperty.call(w,S),k=h&&p?Object.fromEntries([...p.filter(w=>g(h,w)),...Object.keys(h).filter(w=>!WF.includes(w))].map(w=>[w,h[w]])):h;return{enabled:!n,toolbar:{enabled:o("toolbar"),container:n?null:Ck(l.container,c.selector,e.toolbar)??null,options:n?{}:{...Sf(c,l),groups:k,toolbarGroups:m,icons:Sf(e.toolbarIcons,c.icons,l.icons),texts:Sf(e.toolbarTexts,c.texts,l.texts)}},comments:{enabled:i("comments")??(!n&&e.modules?.comments!==!1),options:s("comments")},contextMenu:{enabled:i("contextMenu")??(!n&&e.disableContextMenu!==!0),suppressed:n||i("contextMenu")===!1,options:s("contextMenu")},search:{enabled:i("search")??(!n&&!!e.modules?.surfaces?.findReplace),options:s("search")},linkPopover:{enabled:i("linkPopover")??(!n&&!!e.modules?.links?.popoverResolver),suppressed:n||i("linkPopover")===!1,options:s("linkPopover")},ruler:{enabled:i("ruler")??(!n&&!!e.rulers),suppressed:a,container:a?null:s("ruler").container??e.rulerContainer??null},contentControls:{enabled:i("contentControls")??(!n&&e.modules?.contentControls?.chrome!=="none"),options:s("contentControls")}}}var L0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ak(e={}){const t=L0(e.interaction)?e.interaction:{},n=L0(t.comments)?t.comments:{},r=L0(e.modules?.comments)?e.modules.comments:{};return{comments:{readOnly:(n.readOnly??r.readOnly??!1)===!0,allowResolve:(n.allowResolve??r.allowResolve??!0)!==!1}}}var Ik=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ek(e={}){const t=Ik(e.surfaces)?e.surfaces:{},n=Ik(e.modules?.surfaces)?e.modules.surfaces:{},r=t.resolver===void 0?n.resolver:t.resolver;return{resolver:typeof r=="function"?r:null,dialog:Sf(n.dialog,t.dialog),floating:Sf(n.floating,t.floating)}}var qF=class{#t=new Map;#n=new Map;#e=null;#i=new Set;register(e){if(this.#t.has(e.id))throw new Error(`EditorRuntimeRegistry: duplicate runtime id "${e.id}"`);const t=e.root,n=t?this.#n.get(t):void 0;if(n!==void 0&&n!==e.id)throw new Error(`EditorRuntimeRegistry: root element already registered to runtime "${n}"`);this.#t.set(e.id,e),t&&this.#n.set(t,e.id)}unregister(e){const t=this.#t.get(e);return t?(this.#t.delete(e),t.root&&this.#n.delete(t.root),this.#e===e&&(this.#e=null,this.#s({previousRuntimeId:e,nextRuntimeId:null,reason:"active-runtime-unregistered",legacyEditorProjection:null})),!0):!1}get(e){return this.#t.get(e)??null}getAll(){return Array.from(this.#t.values())}getAllByDocumentId(e){const t=[];for(const n of this.#t.values())n.documentId===e&&t.push(n);return t}getActive(){return this.#e===null?null:this.#t.get(this.#e)}getActiveId(){return this.#e}setActive(e,t){if(e!==null&&!this.#t.has(e))throw new Error(`EditorRuntimeRegistry: cannot activate unknown runtime "${e}"`);if(e===this.#e)return;const n=this.#e;this.#e=e;let r=null;e!==null&&(r=this.#t.get(e).getLegacyEditorProjection?.()??null),this.#s({previousRuntimeId:n,nextRuntimeId:e,reason:t,legacyEditorProjection:r})}resolveFromEventTarget(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;if(!t)return null;const n=t.closest(`[${_p}]`);if(!n)return null;const r=n.getAttribute(_p),o=r?this.get(r):null;return o&&o.root===n?o:null}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}clear(){this.#t.clear(),this.#n.clear(),this.#e=null,this.#i.clear()}#s(e){for(const t of Array.from(this.#i))try{t(e)}catch{}}};const at={notReady:"not-ready",documentApiUnavailable:"document-api-unavailable",documentReadonly:"document-readonly",selectionRequired:"selection-required",rangeSelectionRequired:"range-selection-required",contextUnavailable:"context-unavailable",geometryUnavailable:"geometry-unavailable",targetUnresolved:"target-unresolved",targetNotVisible:"target-not-visible",commandUnsupported:"command-unsupported",commandDeferred:"command-deferred",tableContextUnavailable:"table-context-unavailable",operationUnavailable:"operation-unavailable",bulkDecisionsDisabled:"bulk-decisions-disabled",hostCapabilityUnavailable:"host-capability-unavailable",historyEmpty:"history-empty",searchUnavailable:"search-unavailable",searchInvalidPattern:"search-invalid-pattern",replaceUnsupported:"replace-unsupported",contentControlLocked:"content-control-locked"},xk={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strikethrough",fontFamily:"font-family",fontSize:"font-size",setFontFamily:"setFontFamily",setFontSize:"setFontSize",undo:"undo",redo:"redo",acceptChange:"acceptChange",rejectChange:"rejectChange",acceptAllChanges:"acceptAllChanges",rejectAllChanges:"rejectAllChanges",bulletList:"bullet-list",numberedList:"numbered-list"};function Tk(e){const t=n=>typeof n=="string"?n.replace(/\s*pt$/i,"").trim():n;if(typeof e=="string")return t(e);if(e&&typeof e=="object"&&"value"in e){const n=e;return{...n,value:t(n.value)}}return e}function YF(e){const t=(n,r)=>!r&&n>0&&n<=5?n*100:n;if(typeof e=="string"){const n=e.includes("%"),r=Number.parseFloat(e.replace("%","").trim());return Number.isFinite(r)?t(r,n):e}return typeof e=="number"&&Number.isFinite(e)?t(e,!1):e}function XF(e){const t=e&&typeof e=="object"&&"value"in e?e.value:e;if(t==="in"||t==="cm")return t;if(typeof t=="string"){const n=t.trim().toLowerCase();if(n==="in"||n==="inch"||n==="inches")return"in";if(n==="cm"||n==="centimeter"||n==="centimeters"||n==="centimetre"||n==="centimetres")return"cm"}return t}function Rk(e){const t=n=>{if(n===null)return null;if(typeof n!="string")return n;const r=n.trim();return r===""?n:/^#[0-9a-fA-F]{6}$/.test(r)?r:/^[0-9a-fA-F]{6}$/.test(r)?`#${r}`:r};if(e&&typeof e=="object"&&"value"in e){const n=e;return{...n,value:t(n.value)}}return t(e)}function D0(e,t){if(e&&typeof e=="object"){const n=e;for(const r of t)if(r in n)return n[r]}return e}function QF(e){const t=D0(e,["alignment","value"]);if(typeof t!="string")return t;const n=t.trim().toLowerCase();return n==="justified"||n==="both"?"justify":n}function ZF(e){const t=D0(e,["line","lineHeight","value"]),n=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t.trim()):NaN;return!Number.isFinite(n)||n<=0?t:n<=10?Math.round(n*240):Math.round(n)}function JF(e){if(e&&typeof e=="object"&&"role"in e)return e;const t=D0(e,["styleId","value","style"]);return typeof t=="string"?t.trim():t}function $F(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e.mode;if(typeof t=="string")return t}return e}var eB=at.commandUnsupported,bs=at.tableContextUnavailable;const Mk=[{id:"bold",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.bold",activeMark:"bold",inline:{key:"bold",kind:"toggle"}},{id:"italic",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.italic",activeMark:"italic",inline:{key:"italic",kind:"toggle"}},{id:"underline",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.underline",activeMark:"underline",inline:{key:"underline",kind:"toggle"}},{id:"strikethrough",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.strikethrough",activeMark:"strikethrough",inline:{key:"strike",kind:"toggle"}},{id:"font-family",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontFamily",aliases:["setFontFamily"],inline:{key:"fontFamily",kind:"value-string"}},{id:"font-size",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontSize",aliases:["setFontSize"],normalizePayload:Tk,inline:{key:"fontSize",kind:"value-number"}},{id:"setFontFamily",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontFamily",aliasOf:"font-family",inline:{key:"fontFamily",kind:"value-string"}},{id:"setFontSize",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontSize",aliasOf:"font-size",normalizePayload:Tk,inline:{key:"fontSize",kind:"value-number"}},{id:"undo",family:"history",disposition:"routed",mutates:!0,docRoute:"history.undo"},{id:"redo",family:"history",disposition:"routed",mutates:!0,docRoute:"history.redo"},{id:"acceptChange",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"accept",scope:"id"},aliases:["track-changes-accept-selection"]},{id:"rejectChange",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"reject",scope:"id"},aliases:["track-changes-reject-selection"]},{id:"acceptAllChanges",family:"tracked changes (bulk)",disposition:"routed",mutates:!0,trackDecision:{kind:"accept",scope:"all"}},{id:"rejectAllChanges",family:"tracked changes (bulk)",disposition:"routed",mutates:!0,trackDecision:{kind:"reject",scope:"all"}},{id:"track-changes-accept-selection",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"accept",scope:"id"},aliasOf:"acceptChange"},{id:"track-changes-reject-selection",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"reject",scope:"id"},aliasOf:"rejectChange"},{id:"zoom",family:"zoom",disposition:"routed",mutates:!1,instanceRoute:"setZoom",valueFrom:"zoom",normalizePayload:YF},{id:"zoom-fit-width",family:"zoom",disposition:"routed",mutates:!1,instanceRoute:"setZoomMode",fixedArg:"fit-width",valueFrom:"zoom"},{id:"document-mode",family:"document",disposition:"routed",mutates:!1,instanceRoute:"setDocumentMode",valueFrom:"documentMode",normalizePayload:$F},{id:"measurement-unit",family:"measurement",disposition:"routed",mutates:!1,instanceRoute:"setMeasurementUnit",valueFrom:"measurementUnit",normalizePayload:XF},{id:"text-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.color",inline:{key:"color",kind:"value-string"},normalizePayload:Rk},{id:"highlight-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.highlight",inline:{key:"highlight",kind:"value-string"},normalizePayload:Rk},{id:"link",family:"links",disposition:"routed",mutates:!0,docRoute:"hyperlinks.wrap",activeMark:"link",link:{kind:"link"}},{id:"text-align",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setAlignment",blockParagraph:{kind:"alignment"},normalizePayload:QF},{id:"line-height",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setSpacing",blockParagraph:{kind:"spacing-line"},normalizePayload:ZF},{id:"linked-style",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"styles.paragraph.setStyle",blockParagraph:{kind:"style"},normalizePayload:JF},{id:"bullet-list",family:"lists",disposition:"routed",mutates:!0,docRoute:"lists.apply",list:{mode:"toggle-seed",seed:"bullet"}},{id:"numbered-list",family:"lists",disposition:"routed",mutates:!0,docRoute:"lists.apply",list:{mode:"toggle-seed",seed:"ordered"}},{id:"indent-increase",family:"lists/indent",disposition:"routed",mutates:!0,docRoute:"lists.indent",list:{mode:"indent"}},{id:"indent-decrease",family:"lists/indent",disposition:"routed",mutates:!0,docRoute:"lists.outdent",list:{mode:"outdent"}},{id:"direction-ltr",family:"direction",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setDirection",blockParagraph:{kind:"direction",fixedValue:"ltr"}},{id:"direction-rtl",family:"direction",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setDirection",blockParagraph:{kind:"direction",fixedValue:"rtl"}},{id:"clear-formatting",family:"formatting",disposition:"routed",mutates:!0,docRoute:"format.apply",inline:{key:"*",kind:"clear"}},{id:"image",family:"media",disposition:"routed",mutates:!0,docRoute:"create.image",create:{kind:"image"}},{id:"table-of-contents-insert",family:"TOC",disposition:"routed",mutates:!0,docRoute:"create.tableOfContents",create:{kind:"toc"}},{id:"table-insert",family:"tables",disposition:"routed",mutates:!0,docRoute:"create.table",create:{kind:"table"}},{id:"table-add-row-before",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertRow",table:{action:"insert-row-before",op:"insertRow"},reason:bs},{id:"table-add-row-after",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertRow",table:{action:"insert-row-after",op:"insertRow"},reason:bs},{id:"table-delete-row",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.deleteRow",table:{action:"delete-row",op:"deleteRow"},reason:bs},{id:"table-add-column-before",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertColumn",table:{action:"insert-column-before",op:"insertColumn"},reason:bs},{id:"table-add-column-after",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertColumn",table:{action:"insert-column-after",op:"insertColumn"},reason:bs},{id:"table-delete-column",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.deleteColumn",table:{action:"delete-column",op:"deleteColumn"},reason:bs},{id:"table-delete",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.delete",table:{action:"delete-table",op:"delete"},reason:bs},{id:"table-merge-cells",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.mergeCells",table:{action:"merge-cells",op:"mergeCells"},reason:bs},{id:"table-split-cell",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.splitCell",table:{action:"split-cell",op:"splitCell",requiresCell:!0},reason:bs},{id:"table-remove-borders",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.setBorders",table:{action:"remove-borders",op:"setBorders"},reason:bs},{id:"ruler",family:"UI chrome",disposition:"routed",mutates:!1,instanceRoute:"toggleRuler",valueFrom:"ruler"},{id:"formatting-marks",family:"UI chrome",disposition:"routed",mutates:!1,instanceRoute:"toggleFormattingMarks",valueFrom:"formattingMarks"},{id:"copy-format",family:"formatting",disposition:"routed",mutates:!1},{id:"table-fix",family:"tables",disposition:"unsupported",mutates:!0,reason:eB}];var tB=new Map(Mk.map(e=>[e.id,e]));const nB=Mk.map(e=>e.id);function fu(e){return tB.get(e)??null}var rB=["table-add-row-before","table-add-row-after","table-delete-row","table-add-column-before","table-add-column-after","table-delete-column","table-delete","table-merge-cells","table-split-cell","table-remove-borders"];const Lk=[{name:"bold",commandId:"bold",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"italic",commandId:"italic",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"underline",commandId:"underline",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"strike",commandId:"strikethrough",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"clearFormatting",commandId:"clear-formatting",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"copyFormat",commandId:"copy-format",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"fontFamily",commandId:"font-family",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"fontSize",commandId:"font-size",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"color",commandId:"text-color",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"highlight",commandId:"highlight-color",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"textAlign",commandId:"text-align",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"list",commandId:"bullet-list",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"numberedlist",commandId:"numbered-list",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"indentleft",commandId:"indent-decrease",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"indentright",commandId:"indent-increase",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"lineHeight",commandId:"line-height",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"linkedStyles",commandId:"linked-style",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"link",commandId:"link",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"image",commandId:"image",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"table",commandId:"table-insert",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"tableActions",commandId:null,instanceMethod:null,disposition:"shell-owned",group:"center",memberCommandIds:rB,note:"table editing dropdown is shell chrome; its member commands are controller-routed through the shared table-context facade (ui.tables / host.getTableContext()) and fail closed with table-context-unavailable when the caret is not in a table"},{name:"undo",commandId:"undo",instanceMethod:null,disposition:"controller-routed",group:"left"},{name:"redo",commandId:"redo",instanceMethod:null,disposition:"controller-routed",group:"left"},{name:"search",commandId:null,instanceMethod:null,disposition:"shell-owned",group:"right",note:"built-in search button; opens the shared find/replace surface (the same one Cmd/Ctrl+F opens) by emitting a `search:open` event on the SuperDoc instance, which the shell handles. The surface reads/drives the controller search surface (ui.search), backed by the single V2 host search session (host.search) which owns query, navigation, reveal, and replace. Find/navigation are always available when the host exposes search; replace/replaceAll mutate through the host session and fail closed (document-readonly) in viewing/read-only mode. If a runtime cannot expose search, the surface fails closed with search-unavailable"},{name:"zoom",commandId:"zoom",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"measurementUnit",commandId:"measurement-unit",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"ruler",commandId:null,instanceMethod:"toggleRuler",disposition:"host-routed",group:"right",note:"built-in shell toggles ruler visibility through the public SuperDoc.toggleRuler() instance method; the controller also routes the ruler command through it so custom UIs drive the same chrome (active state from config.rulers)"},{name:"formattingMarks",commandId:null,instanceMethod:"toggleFormattingMarks",disposition:"host-routed",group:"right",note:"built-in shell toggles nonprinting marks through the public SuperDoc.toggleFormattingMarks()/setShowFormattingMarks() instance methods (not a controller command)"},{name:"documentMode",commandId:"document-mode",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"acceptTrackedChangeBySelection",commandId:"track-changes-accept-selection",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"rejectTrackedChangeOnSelection",commandId:"track-changes-reject-selection",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"customButtons",commandId:null,instanceMethod:null,disposition:"shell-owned",group:"center",note:"consumer-defined buttons the rendered shell owns; their execution context surface is phase 2"}];var Dk=new Map(Lk.map(e=>[e.name,e]));const Aj=Lk.map(e=>e.name);function P0(e){return Dk.get(e)??null}function oB(e){const t=Dk.get(e);return t?.disposition==="controller-routed"?t.commandId:null}const iB=".png,.jpg,.jpeg,image/png,image/jpeg";var Pk=new Set(["image/png","image/jpeg","image/jpg"]),sB=/\.(png|jpe?g)$/i;function aB(e){if(!e)return!1;const t=typeof e.type=="string"?e.type.toLowerCase():"";return t?Pk.has(t):sB.test(String(e.name??""))}function Ok(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(lB(String(r.result),e)),r.onerror=()=>n(r.error??new Error("image-read-failed")),r.readAsDataURL(e)})}function lB(e,t){const n=/^data:([^;,]*);base64,/.exec(e);if(!n)return e;const r=n[1].toLowerCase();if(Pk.has(r))return e;const o=String(t?.name??""),i=/\.jpe?g$/i.test(o)?"image/jpeg":/\.png$/i.test(o)?"image/png":null;return i?`data:${i};base64,${e.slice(n[0].length)}`:e}async function cB(e,t){if(typeof t=="function"){const n=await t(e);if(typeof n!="string"||n.trim()==="")throw new Error("handleImageUpload returned an empty result");return n.startsWith("data:")?n:uB(n,e)}return Ok(e)}async function uB(e,t){const n=await fetch(e);if(!n.ok)throw new Error(`image fetch failed: ${n.status}`);const r=await n.blob(),o=(/\.(?:png|jpe?g)(?:$|[?#])/i.test(e)?e.split(/[?#]/)[0]:"")||t?.name||"";return Ok(o?Object.assign(r,{name:o}):r)}function dB({ownerDocument:e=document,onPick:t,onError:n}={}){const r=e.createElement("input");return r.type="file",r.accept=iB,r.hidden=!0,r.tabIndex=-1,r.setAttribute("data-superdoc-image-picker","true"),r.setAttribute("aria-hidden","true"),r.addEventListener("change",()=>{const o=r.files&&r.files[0];if(r.value="",!!o){if(!aB(o)){n?.(new Error(`unsupported image type: ${o.type||o.name}`));return}try{const i=t?.(o);i&&typeof i.then=="function"&&i.catch(s=>n?.(s))}catch(i){n?.(i)}}}),e.body?.appendChild(r),{input:r,open(){r.click()},destroy(){r.remove()}}}var fB=(e,t)=>{let n=e.replace(/[^0-9.]/g,"");return n=parseFloat(n),isNaN(n)&&(n=t),n=parseFloat(n),n},hB=(e,t,n)=>{let r,o,i,s=0;n||(n={});const a=()=>{s=n.leading===!1?0:Date.now(),r=null,i=e(...o),r||(o=null)},l=(...u)=>{const c=Date.now();!s&&n.leading===!1&&(s=c);const d=t-(c-s);return o=u,d<=0||d>t?(r&&(clearTimeout(r),r=null),s=c,i=e(...u),r||(o=null)):!r&&n.trailing!==!1&&(r=setTimeout(a,d)),i};return l.cancel=function(){clearTimeout(r),s=0,r=o=null},l};It(),gn();var pB={class:"sd-toolbar-icon"},mB=["innerHTML"],gB={__name:"ToolbarButtonIcon",props:{name:{type:String,required:!0},color:{type:String,default:null},icon:{type:String,default:null}},setup(e){const t=e,n=Se(()=>{if(t.name==="color")return{backgroundColor:t.color||"#111111"};if(t.name==="highlight")return{backgroundColor:t.color||"#D6D6D6"}}),r=Se(()=>["color","highlight"].includes(t.name));return(o,i)=>(me(),_e("div",pB,[Le("div",{class:en(["sd-toolbar-icon__icon",[`sd-toolbar-icon__icon--${t.name}`]]),innerHTML:e.icon},null,10,mB),r.value?(me(),_e("div",{key:0,class:"color-bar",style:vn(n.value)},null,4)):ut("",!0)]))}},Fk=hn(gB,[["__scopeId","data-v-d7d79424"]]);It(),gn();var vB=["role","aria-label"],yB=["data-item"],bB=["data-item"],wB={key:1,class:"sd-button-label"},CB=["data-item","aria-label"],_B=["innerHTML"],SB={key:2},kB=["onKeydown","id"],AB=["placeholder","onKeydown","id","data-item"],IB=["data-item","innerHTML"],EB={"aria-live":"polite",class:"sd-visually-hidden"},xB={__name:"ToolbarButton",props:{iconColor:{type:String,default:null},active:{type:Boolean,default:!1},isNarrow:{type:Boolean,default:!1},isWide:{type:Boolean,default:!1},toolbarItem:{type:Object,required:!0},defaultLabel:{type:String,default:null},isOverflowItem:{type:Boolean,default:!1},allowEnterPropagation:{type:Boolean,default:!1}},emits:["buttonClick","textSubmit","mainClick"],setup(e,{emit:t}){const n=t,{proxy:r}=sr(),o=e,{name:i,active:s,icon:a,label:l,hideLabel:u,iconColor:c,hasCaret:d,splitButton:h,disabled:m,expand:p,inlineTextInputVisible:g,hasInlineTextInput:k,minWidth:w,style:S,attributes:y}=o.toolbarItem,C=Se(()=>!!h?.value&&!!d?.value),T=Se(()=>i?.value??""),R=ne(""),M=ne(null),{isHighContrastMode:H}=zi();Pt(()=>l?.value,Ce=>{document.activeElement!==M.value&&(R.value=Ce==null?"":String(Ce))},{immediate:!0});const B=()=>{k&&_t(()=>{M.value?.focus(),M.value?.select()}),n("buttonClick")},z=Ce=>{m?.value||(Ce?.stopPropagation(),n("mainClick"))},Z=()=>{C.value||B()},P=Ce=>{if(C.value){z(Ce);return}B()},N=Ce=>{o.allowEnterPropagation||Ce.stopPropagation(),P(Ce)},I=Ce=>{const oe=o.toolbarItem?.nestedOptions?.value??[],xe=Ce.trim();if(!xe)return"";const qe=oe.find(et=>typeof et?.label=="string"&&et.label.toLowerCase()===xe.toLowerCase());return qe?.label?qe.label:oe.find(et=>typeof et?.label=="string"&&et.label.toLowerCase().startsWith(xe.toLowerCase()))?.label??xe},L=()=>{const Ce=String(R.value??"").trim();let oe=Ce;if(T.value==="fontSize"){const xe=Number.parseFloat(Ce);oe=Ce.match(/^\d+(\.5)?$/)?Ce:Number.isFinite(xe)?Math.floor(xe).toString():""}else T.value==="fontFamily"&&(oe=I(Ce));return oe?(n("textSubmit",oe),R.value=oe,!0):!1},X=Ce=>{const oe=Ce?.currentTarget;oe instanceof HTMLInputElement&&(oe.focus({preventScroll:!0}),oe.select())},te=Ce=>{requestAnimationFrame(()=>{const oe=document.getElementById(`inlineTextInput-${Ce}`);oe instanceof HTMLInputElement&&(oe.focus({preventScroll:!0}),oe.select())})},le=()=>{const Ce=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return Ce instanceof HTMLElement?(Ce.focus({preventScroll:!0}),!0):!1},fe=()=>{const Ce=r?.$toolbar?.pendingSelectionCapture,oe=()=>{Ce&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(Ce)};if(le()){oe();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),oe())},Fe=()=>{L()&&fe()},he=Ce=>{if(L(),Ce.shiftKey){T.value==="fontSize"&&(Ce.preventDefault(),_t(()=>te("fontFamily")));return}if(Ce.preventDefault(),T.value==="fontFamily"){_t(()=>te("fontSize"));return}T.value==="fontSize"&&_t(fe)},ge=Se(()=>S.value?S.value:{minWidth:o.minWidth}),ae=Se(()=>p?.value?tr.dropdownCaretUp:tr.dropdownCaretDown);return(Ce,oe)=>(me(),_e("div",{class:en(["sd-toolbar-item",Ge(y).className]),style:vn(ge.value),role:e.isOverflowItem?"menuitem":"button","aria-label":Ge(y).ariaLabel,"data-sd-part":"toolbar-item",onClick:Z,onKeydown:oe[9]||(oe[9]=Yo(xe=>N(xe),["enter"])),tabindex:"0"},[Le("div",{class:en(["sd-toolbar-button",{"sd-active":Ge(s),"sd-disabled":Ge(m),narrow:e.isNarrow,wide:e.isWide,split:C.value,"has-inline-text-input":Ge(k),"high-contrast":Ge(H)}]),"data-item":`btn-${Ge(i)||""}`},[C.value?(me(),_e("div",{key:0,class:"sd-toolbar-button__main","data-item":`btn-${Ge(i)||""}-main`,onClick:oe[0]||(oe[0]=xe=>z(xe))},[Ge(a)?(me(),fn(Fk,{key:0,color:Ge(c),class:"sd-toolbar-icon",icon:Ge(a),name:Ge(i)},null,8,["color","icon","name"])):ut("",!0),Ge(l)&&!Ge(u)&&!Ge(g)?(me(),_e("div",wB,Ht(Ge(l)),1)):ut("",!0)],8,bB)):ut("",!0),C.value?(me(),_e("div",{key:1,class:"sd-toolbar-button__caret","data-item":`btn-${Ge(i)||""}-caret`,"aria-label":`${Ge(y).ariaLabel} options`,role:"button"},[Le("div",{class:"sd-dropdown-caret",innerHTML:ae.value,style:vn({opacity:Ge(m)?.6:1})},null,12,_B)],8,CB)):(me(),_e(Wt,{key:2},[Ge(a)?(me(),fn(Fk,{key:0,color:Ge(c),class:"sd-toolbar-icon",icon:Ge(a),name:Ge(i)},null,8,["color","icon","name"])):ut("",!0),Ge(l)&&!Ge(u)&&(!Ge(g)||T.value==="fontFamily")?(me(),_e("div",{key:1,class:en(["sd-button-label",{"sd-visually-hidden":Ge(g)&&T.value==="fontFamily"}])},Ht(Ge(l)),3)):ut("",!0),Ge(g)?(me(),_e("span",SB,[Ge(i)==="fontSize"?Ws((me(),_e("input",{key:0,"onUpdate:modelValue":oe[1]||(oe[1]=xe=>R.value=xe),onKeydown:[Yo(Jt(Fe,["stop","prevent"]),["enter"]),oe[2]||(oe[2]=Yo(xe=>he(xe),["tab"]))],onClick:oe[3]||(oe[3]=Jt(xe=>X(xe),["stop"])),onFocus:oe[4]||(oe[4]=xe=>X(xe)),type:"text",class:en(["button-text-input button-text-input--font-size",{"high-contrast":Ge(H)}]),id:"inlineTextInput-"+Ge(i),autocomplete:"off",ref_key:"inlineInput",ref:M},null,42,kB)),[[ki,R.value]]):Ws((me(),_e("input",{key:1,"onUpdate:modelValue":oe[5]||(oe[5]=xe=>R.value=xe),placeholder:Ge(l),onKeydown:[Yo(Jt(Fe,["stop","prevent"]),["enter"]),oe[6]||(oe[6]=Yo(xe=>he(xe),["tab"]))],onClick:oe[7]||(oe[7]=Jt(xe=>X(xe),["stop"])),onFocus:oe[8]||(oe[8]=xe=>X(xe)),type:"text",class:en(["button-text-input",{"button-text-input--font-family":T.value==="fontFamily","high-contrast":Ge(H)}]),id:"inlineTextInput-"+Ge(i),"data-item":T.value==="fontFamily"?`btn-${Ge(i)}-input`:void 0,autocomplete:"off",ref_key:"inlineInput",ref:M},null,42,AB)),[[ki,R.value]])])):ut("",!0),Ge(d)?(me(),_e("div",{key:3,class:"sd-dropdown-caret","data-item":`btn-${Ge(i)||""}-toggle`,innerHTML:ae.value,style:vn({opacity:Ge(m)?.6:1})},null,12,IB)):ut("",!0)],64)),Le("div",EB,Ht(`${Ge(y).ariaLabel} ${Ge(s)?"selected":"unset"}`),1)],10,yB)],46,vB))}},O0=hn(xB,[["__scopeId","data-v-dbdea151"]]);It(),gn();var TB={class:"toolbar-separator",role:"separator","aria-label":"Toolbar separator"},RB={__name:"ToolbarSeparator",props:{active:{type:Boolean,default:!1}},emits:["command"],setup(e,{emit:t}){const{isHighContrastMode:n}=zi(),r=()=>n.value?"#000":"var(--sd-ui-border, #dbdbdb)";return(o,i)=>(me(),_e("div",TB,[Le("div",{class:"separator-inner",style:vn({backgroundColor:r()})},null,4)]))}},MB=hn(RB,[["__scopeId","data-v-cb82253a"]]);It(),gn();var LB={class:"overflow-menu"},DB={class:"overflow-menu-trigger"},PB={key:0,class:"overflow-menu_items",role:"group"},OB={__name:"OverflowMenu",props:{toolbarItem:{type:Object,required:!0},overflowItems:{type:Array,required:!0}},emits:["buttonClick","close"],setup(e,{emit:t}){const{proxy:n}=sr(),r=t,o=e,i=Se(()=>o.toolbarItem.expand.value),s=ne(!1),a=Se(()=>({...o.toolbarItem,active:i.value})),l=()=>{r("buttonClick",o.toolbarItem)},u=({item:d,argument:h})=>{n.$toolbar.emitCommand({item:d,argument:h})},c=d=>{d.key==="Escape"&&i.value&&!s.value&&(d.preventDefault(),r("close"))};return Rn(()=>{document.addEventListener("keydown",c,!0)}),ir(()=>{document.removeEventListener("keydown",c,!0)}),(d,h)=>(me(),_e("div",LB,[Le("div",DB,[Gt(O0,{"toolbar-item":a.value,onButtonClick:l},null,8,["toolbar-item"])]),i.value?(me(),_e("div",PB,[Gt(qp,{class:"superdoc-toolbar-overflow","toolbar-items":e.overflowItems,"from-overflow":"",onCommand:u,onDropdownUpdateShow:h[0]||(h[0]=m=>s.value=m)},null,8,["toolbar-items"])])):ut("",!0)]))}},FB=hn(OB,[["__scopeId","data-v-504ecd05"]]);It(),gn();var BB={class:"toolbar-dropdown"},NB=["onClick"],zB={key:0,class:"toolbar-dropdown-option__icon"},HB={class:"toolbar-dropdown-option__label"},Gp='button, [href], input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])',UB={__name:"ToolbarDropdown",props:{options:{type:Array,default:()=>[]},show:{type:Boolean,required:!0},placement:{type:String,default:"bottom-start"},disabled:{type:Boolean,default:!1},contentStyle:{type:Object,default:()=>({})},menuProps:{type:Function,default:null},nodeProps:{type:Function,default:null}},emits:["update:show","select"],setup(e,{emit:t}){const n=e,r=t,o=ne(null),i=ne(null),s=ne({top:"0px",left:"0px",maxHeight:"none"}),a=ne([]),l=ne(-1),u=Se(()=>!!n.show),c=Se(()=>n.options.some(oe=>oe?.type==="render")),d=Se(()=>typeof n.menuProps!="function"?{}:n.menuProps()||{}),h=Se(()=>{const{class:oe,style:xe,...qe}=d.value;return qe}),m=Se(()=>{const oe=d.value.class,xe=n.options.length>0&&n.options.every(qe=>qe&&qe.type==="render");return["toolbar-dropdown-menu",oe,{"toolbar-dropdown-menu--render-only":xe}]}),p=Se(()=>{const oe=d.value.style||{};return{...n.contentStyle,...oe}}),g=Se(()=>({...p.value,position:"fixed",top:s.value.top,left:s.value.left,maxHeight:s.value.maxHeight,zIndex:2e3})),k=oe=>{r("update:show",oe)},w=()=>{u.value&&k(!1)},S=()=>{if(!o.value)return;const oe=o.value.getBoundingClientRect(),xe=i.value,qe=xe?.offsetWidth??0,et=xe?.scrollHeight??xe?.offsetHeight??0,kt=window.innerWidth||document.documentElement.clientWidth||0,Ie=window.innerHeight||document.documentElement.clientHeight||0,ze=8,Ve=4,Q=oe.bottom+Ve,_=oe.top-Ve,$=Math.max(0,Ie-Q-ze),F=Math.max(0,_-ze),j=$<et&&F>$,V=j?F:$,G=et?Math.min(et,V):V,J=j?Math.max(ze,_-G):Q;let K=oe.left;n.placement==="bottom-end"&&(K=oe.right-qe);const W=Math.max(ze,kt-qe-ze);K=Math.min(Math.max(ze,K),W),s.value={top:`${J}px`,left:`${K}px`,maxHeight:`${V}px`}},y=()=>{n.disabled||k(!u.value)},C=oe=>typeof n.nodeProps!="function"?{}:n.nodeProps(oe)||{},T=oe=>{oe?.disabled||oe?.type!=="render"&&(r("select",oe?.key,oe),w())},R=oe=>oe?.type==="render",M=oe=>!oe?.disabled&&oe?.type!=="render",H=oe=>typeof oe?.icon=="function"||!!oe?.icon,B=oe=>typeof oe?.icon=="function"?oe.icon(oe):oe?.icon||null,z=oe=>oe?typeof oe=="string"?oe.split(/\s+/).includes("sd-selected"):Array.isArray(oe)?oe.some(z):typeof oe=="object"?!!oe["sd-selected"]:!1:!1,Z=oe=>z(oe?.props?.class)||z(oe?.class),P=()=>n.options.map((oe,xe)=>M(oe)?xe:-1).filter(oe=>oe>=0),N=()=>{const oe=n.options.findIndex(xe=>M(xe)&&Z(xe));return oe>=0?oe:P()[0]??-1},I=(oe,xe)=>{if(!oe){delete a.value[xe];return}a.value[xe]=oe},L=()=>{a.value.forEach((xe,qe)=>{xe&&xe.setAttribute("tabindex",qe===l.value?"0":"-1")});const oe=a.value[l.value];oe&&typeof oe.focus=="function"&&(oe.focus(),oe.scrollIntoView?.({block:"nearest",inline:"nearest"}))},X=oe=>{const xe=P();if(!xe.length){l.value=-1;return}const qe=xe.indexOf(l.value);if(qe<0){l.value=oe>0?xe[0]:xe[xe.length-1];return}l.value=xe[(qe+oe+xe.length)%xe.length]},te=()=>{let oe=n.options[l.value];if(!M(oe)){const xe=P()[0];oe=xe===void 0?null:n.options[xe]}oe&&T(oe)},le=Ll({name:"ToolbarDropdownRenderOption",props:{option:{type:Object,required:!0}},setup(oe){return()=>typeof oe.option.render!="function"?null:oe.option.render()}}),fe=Ll({name:"ToolbarDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(oe){return()=>B(oe.option)}}),Fe=oe=>{if(!u.value)return;const xe=oe.target;if(!(xe instanceof Element))return;const qe=o.value?.contains(xe),et=i.value?.contains(xe);qe||et||w()},he=ne(null),ge=()=>{const oe=o.value,xe=document.activeElement;if(oe&&xe instanceof HTMLElement&&oe.contains(xe)){he.value=xe;return}he.value=oe?.matches?.(Gp)?oe:oe?.querySelector(Gp)},ae=()=>{const oe=he.value;if(oe instanceof HTMLElement&&document.contains(oe)){oe.focus();return}const xe=o.value;if(!xe)return;const qe=xe.matches?.(Gp)?xe:xe.querySelector(Gp);if(qe instanceof HTMLElement){qe.focus();return}xe.setAttribute("tabindex","-1"),xe.focus()},Ce=oe=>{if(!u.value)return;const{key:xe}=oe;if(["Escape","ArrowDown","ArrowUp","Enter"].includes(xe)){if(xe==="Escape"){oe.preventDefault(),w(),_t(()=>{requestAnimationFrame(ae)});return}if(!c.value){if(oe.preventDefault(),xe==="ArrowDown"){X(1),L();return}if(xe==="ArrowUp"){X(-1),L();return}xe==="Enter"&&te()}}};return Pt(u,async oe=>{if(!oe){l.value=-1,a.value=[];return}ge(),await _t(),S(),!c.value&&(l.value=N(),await _t(),L())},{immediate:!0}),Pt(u,oe=>{oe?(document.addEventListener("pointerdown",Fe,!0),document.addEventListener("keydown",Ce,!0),window.addEventListener("resize",S),window.addEventListener("scroll",S,!0)):(document.removeEventListener("pointerdown",Fe,!0),document.removeEventListener("keydown",Ce,!0),window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0))},{immediate:!0}),ir(()=>{document.removeEventListener("pointerdown",Fe,!0),document.removeEventListener("keydown",Ce,!0),window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0)}),(oe,xe)=>(me(),_e("div",BB,[Le("div",{ref_key:"triggerRef",ref:o,class:"toolbar-dropdown-trigger","data-sd-part":"dropdown-trigger",onClick:y},[hd(oe.$slots,"trigger",{},void 0,!0)],512),(me(),fn(Oa,{to:"body"},[Gt(Mh,{name:"fade-in-scale-up-transition"},{default:ko(()=>[u.value?(me(),_e("div",cs({key:0,ref_key:"menuRef",ref:i,"data-sd-part":"dropdown-menu",class:m.value,style:g.value},h.value),[(me(!0),_e(Wt,null,or(e.options,(qe,et)=>(me(),_e("div",cs({key:qe.key,ref_for:!0,ref:kt=>I(kt,et),class:["toolbar-dropdown-option",[qe.class,qe.props?.class,{"sd-disabled":qe.disabled,"sd-render":R(qe)}]],tabindex:"-1",onClick:kt=>T(qe)},{ref_for:!0},{...qe.props,...C(qe)}),[R(qe)?(me(),fn(Ge(le),{key:0,option:qe},null,8,["option"])):(me(),_e(Wt,{key:1},[H(qe)?(me(),_e("span",zB,[Gt(Ge(fe),{option:qe},null,8,["option"])])):ut("",!0),Le("span",HB,Ht(qe.label),1)],64))],16,NB))),128))],16)):ut("",!0)]),_:1})]))]))}},VB=hn(UB,[["__scopeId","data-v-fef410f7"]]),Bk=e=>String(e??"").trim().toLowerCase();const Wp=(e,t)=>{const n=Bk(e);if(!n)return-1;for(let r=0;r<t.length;r+=1)if(Bk(t[r]).startsWith(n))return r;return-1},jB=(e,t,{autocomplete:n=!0}={})=>{const r=String(e??""),o=Wp(r,t),i=o>=0?String(t[o]??""):"";return n&&o>=0&&i.length>r.length?{matchIndex:o,display:i,selectionStart:r.length,selectionEnd:i.length}:{matchIndex:o,display:r,selectionStart:r.length,selectionEnd:r.length}};var GB=e=>{let t=String(e??"").trim();for(;t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"));)t=t.slice(1,-1).trim();return t},WB=e=>e<=31||e===127,KB=e=>e===32||e===160||e===65279,qB=e=>Array.from(String(e)).filter(t=>!WB(t.charCodeAt(0))).join(""),YB=e=>{let t="",n=!1;for(const r of String(e)){if(KB(r.charCodeAt(0))){n=t.length>0;continue}n&&(t+=" "),n=!1,t+=r}return t};const XB=e=>YB(GB(qB(String(e??"").split(",")[0]??""))).trim();var QB=1,ZB=1638;const JB=e=>{const t=String(e??"").replace(/[^0-9.-]/g,""),n=Number.parseFloat(t);if(!Number.isFinite(n))return"";const r=Math.round(n*2)/2;return r<QB?"":String(Math.min(r,ZB))};It(),gn();var $B=["data-item"],eN=["id","value","disabled","aria-label","aria-expanded","aria-controls","aria-activedescendant","data-item"],tN=["data-item","aria-label","disabled"],nN=["innerHTML"],rN=["id","aria-label"],oN=["id","aria-selected","aria-label","onMousedown","onMouseenter"],iN={class:"toolbar-dropdown-option__label"},sN={class:"sd-button-label sd-font-combobox__legacy-label","aria-hidden":"true"},aN={__name:"ToolbarComboBox",props:{item:{type:Object,required:!0},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"},showPreview:{type:Boolean,default:!1},normalizeValue:{type:Function,default:e=>String(e??"").trim()}},emits:["command","item-clicked","tab-out","editor-handoff"],setup(e,{emit:t}){const n=e,r=t,{isHighContrastMode:o}=zi(),i=ne(null),s=ne(null),a=ne(null),l=ne([]),u=ne(!1),c=ne(!1),d=ne(-1),h=ne(""),m=ne(""),p=ne(!1),g=ne({top:"0px",left:"0px",minWidth:"0px",maxHeight:"none"}),k=Se(()=>n.item.nestedOptions?.value??[]),w=Se(()=>k.value.map(K=>String(K?.label??""))),S=Se(()=>String(n.item.label?.value??"")),y=Se(()=>!!n.item.disabled?.value),C=Se(()=>String(n.item.name?.value??"")),T=Se(()=>n.item.attributes?.value?.ariaLabel??"Font family"),R=Se(()=>u.value?m.value:S.value),M=Se(()=>`sd-${C.value||"combobox"}-listbox-${n.item.id?.value??"default"}`),H=K=>`${M.value}-option-${K}`,B=Se(()=>c.value&&d.value>=0?H(d.value):void 0),z=Se(()=>c.value?tr.dropdownCaretUp:tr.dropdownCaretDown),Z=K=>{const W=String(K??"").trim().toLowerCase();return k.value.find(ue=>String(ue?.label??"").trim().toLowerCase()===W)?.props?.style?.fontFamily||K||n.uiFontFamily},P=Se(()=>n.showPreview?{fontFamily:Z(u.value?m.value:S.value)}:{fontFamily:n.uiFontFamily}),N=()=>{const K=n.item.selectedValue?.value;if(K){const W=k.value.findIndex(ue=>ue?.key===K);if(W>=0)return W}return w.value.findIndex(W=>W.toLowerCase()===S.value.toLowerCase())},I=(K,W)=>{const ue=i.value;if(!(!ue||typeof ue.setSelectionRange!="function"))try{ue.setSelectionRange(K,W)}catch{}},L=()=>{l.value[d.value]?.scrollIntoView?.({block:"nearest",inline:"nearest"})},X=()=>{l.value[d.value]?.focus?.()},te=()=>{const K=s.value;if(!K)return;const W=K.getBoundingClientRect(),ue=a.value,be=ue?.scrollHeight??ue?.offsetHeight??0,we=window.innerHeight||document.documentElement.clientHeight||0,Te=window.innerWidth||document.documentElement.clientWidth||0,rt=8,nt=4,wt=W.bottom+nt,Zt=W.top-nt,Ct=Math.max(0,we-wt-rt),Ot=Math.max(0,Zt-rt),Bt=Ct<be&&Ot>Ct,on=Bt?Ot:Ct,Fn=be?Math.min(be,on):on,Vt=Bt?Math.max(rt,Zt-Fn):wt,We=Math.min(Math.max(rt,W.left),Math.max(rt,Te-W.width-rt));g.value={top:`${Vt}px`,left:`${We}px`,minWidth:`${W.width}px`,maxHeight:`${on}px`}},le=Se(()=>({position:"fixed",top:g.value.top,left:g.value.left,minWidth:g.value.minWidth,maxHeight:g.value.maxHeight,fontFamily:n.uiFontFamily,zIndex:2e3})),fe=K=>{n.item.expand&&typeof n.item.expand=="object"&&"value"in n.item.expand&&(n.item.expand.value=K)},Fe=(K,{focusInput:W=!1,focusOption:ue=!1}={})=>{if(y.value||!k.value.length){fe(!1);return}c.value=!0,fe(!0),d.value=K??-1,W&&(u.value=!0,m.value=S.value,i.value?.focus()),_t(()=>{te(),L(),ue&&X()})},he=({syncItem:K=!0}={})=>{c.value=!1,d.value=-1,K&&fe(!1)},ge=()=>{he(),u.value=!1,h.value="",m.value=S.value},ae=()=>{y.value||(c.value||r("item-clicked"),u.value=!0,h.value="",m.value=S.value,_t(()=>I(0,m.value.length)))},Ce=K=>{if(y.value)return;const W=document.activeElement===i.value;if(r("item-clicked"),u.value=!0,W||(h.value="",m.value=S.value,K.preventDefault(),i.value?.focus({preventScroll:!0}),I(0,S.value.length)),!c.value){const ue=N();Fe(ue>=0?ue:0)}},oe=K=>{const W=K.relatedTarget;W instanceof Node&&s.value?.contains(W)||W instanceof Node&&a.value?.contains(W)||ge()},xe=K=>{if(p.value)return;const W=K.target,ue=W.value,be=typeof W.selectionStart=="number"?W.selectionStart:ue.length,we=typeof W.selectionEnd=="number"?W.selectionEnd:be,Te=typeof K.inputType=="string"&&K.inputType.startsWith("delete"),rt=be===ue.length&&we===ue.length;h.value=ue;const nt=jB(ue,w.value,{autocomplete:!Te&&rt});m.value=nt.display,W.value=nt.display,nt.display===ue&&!rt?I(be,we):I(nt.selectionStart,nt.selectionEnd),c.value&&(d.value=nt.matchIndex,_t(L))},qe=K=>{p.value=!1,xe(K)},et=K=>{if(!k.value.length)return;const W=k.value.length;d.value=((d.value<0?K>0?-1:0:d.value)+K+W)%W,_t(L)},kt=(K,W)=>{r("item-clicked"),r("command",{item:n.item,argument:K,option:W}),W&&(n.item.selectedValue.value=W.key)},Ie=K=>{K&&(kt(K.label,K),u.value=!1,h.value="",m.value=K.label,he())},ze=()=>{if(c.value&&d.value>=0)return Ie(k.value[d.value]),!0;const K=Wp(h.value,w.value);if(K>=0)return Ie(k.value[K]),!0;const W=n.normalizeValue(h.value);return W?(kt(W,null),u.value=!1,h.value="",m.value=W,he(),!0):!1},Ve=K=>{if(!(K.isComposing||p.value||K.keyCode===229)&&!(K.ctrlKey||K.metaKey||K.altKey))switch(K.key){case"ArrowDown":if(K.preventDefault(),c.value)X();else{const W=Wp(h.value,w.value),ue=W>=0?W:N();Fe(ue>=0?ue:0,{focusOption:!0})}break;case"ArrowUp":if(K.preventDefault(),c.value)X();else{const W=Wp(h.value,w.value),ue=W>=0?W:N();Fe(ue>=0?ue:k.value.length-1,{focusOption:!0})}break;case"Enter":K.preventDefault(),ze()&&r("editor-handoff"),i.value?.blur();break;case"Tab":K.preventDefault(),ze(),he(),i.value?.blur(),r("tab-out",K);break;case"Escape":K.preventDefault(),ge(),_t(()=>i.value?.focus());break;default:break}},Q=K=>{if(K.preventDefault(),!y.value)if(r("item-clicked"),c.value)he(),i.value?.focus();else{const W=N();Fe(W>=0?W:0,{focusOption:!0})}},_=(K,W)=>{K.preventDefault(),Ie(W),r("editor-handoff"),i.value?.blur()},$=K=>{d.value=K},F=K=>{if(!(K.ctrlKey||K.metaKey||K.altKey))switch(K.key){case"ArrowDown":K.preventDefault(),et(1),X();break;case"ArrowUp":K.preventDefault(),et(-1),X();break;case"Enter":K.preventDefault(),d.value>=0&&(Ie(k.value[d.value]),r("editor-handoff"));break;case"Escape":K.preventDefault(),ge(),_t(()=>i.value?.focus());break;case"Tab":K.preventDefault(),d.value>=0?Ie(k.value[d.value]):he(),r("tab-out",{shiftKey:K.shiftKey,target:i.value});break;default:break}},j=K=>{if(!c.value)return;const W=K.target;W instanceof Element&&(s.value?.contains(W)||a.value?.contains(W)||ge())};Pt(c,K=>{K?(document.addEventListener("pointerdown",j,!0),window.addEventListener("resize",te),window.addEventListener("scroll",te,!0)):(document.removeEventListener("pointerdown",j,!0),window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),l.value=[])},{immediate:!0}),ir(()=>{document.removeEventListener("pointerdown",j,!0),window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0)});const V=(K,W)=>{if(!K){delete l.value[W];return}l.value[W]=K},G=K=>K===d.value,J=K=>K?.key&&K.key===n.item.selectedValue?.value;return Pt(S,K=>{u.value||(m.value=K)}),Pt(()=>!!n.item.expand?.value,K=>{if(K&&!c.value){const W=N();Fe(W>=0?W:0,{focusInput:!0});return}!K&&c.value&&he({syncItem:!1})}),(K,W)=>(me(),_e("div",{ref_key:"rootRef",ref:s,class:en(["sd-font-combobox sd-toolbar-split-field",{"sd-disabled":y.value,"high-contrast":Ge(o)}]),style:vn(n.item.style?.value),"data-item":`btn-${C.value}`},[Le("span",{class:"sd-font-combobox__field sd-toolbar-split-field__main",onMousedown:Ce},[Le("input",{ref_key:"inputRef",ref:i,id:`inlineTextInput-${C.value}`,class:"button-text-input sd-font-combobox__input",type:"text",role:"combobox",autocomplete:"off",spellcheck:"false",value:R.value,style:vn(P.value),disabled:y.value,"aria-label":T.value,"aria-expanded":c.value?"true":"false","aria-controls":M.value,"aria-activedescendant":B.value,"aria-haspopup":"listbox","aria-autocomplete":"both","data-item":`btn-${C.value}-input`,onFocus:ae,onBlur:oe,onInput:xe,onKeydown:Ve,onCompositionstart:W[0]||(W[0]=ue=>p.value=!0),onCompositionend:qe},null,44,eN)],32),Le("button",{type:"button",class:"sd-font-combobox__caret sd-toolbar-split-field__caret","data-item":`btn-${C.value}-toggle`,tabindex:"-1","aria-label":`${T.value} options`,disabled:y.value,onMousedown:Q},[Le("span",{class:"sd-dropdown-caret",innerHTML:z.value},null,8,nN)],40,tN),(me(),fn(Oa,{to:"body"},[c.value?(me(),_e("div",{key:0,ref_key:"popupRef",ref:a,role:"listbox",id:M.value,"aria-label":T.value,class:en(["sd-font-combobox__listbox",{"high-contrast":Ge(o)}]),style:vn(le.value)},[(me(!0),_e(Wt,null,or(k.value,(ue,be)=>(me(),_e("div",cs({key:ue.key,ref_for:!0,ref:we=>V(we,be),id:H(be),role:"option",tabindex:"-1",class:["toolbar-dropdown-option sd-font-combobox__option",{"sd-active":G(be),"sd-selected":J(ue)}],"aria-selected":J(ue)?"true":"false","aria-label":`${T.value} - ${ue.label}`},{ref_for:!0},ue.props,{onMousedown:we=>_(we,ue),onMouseenter:we=>$(be),onKeydown:F}),[Le("span",iN,Ht(ue.label),1)],16,oN))),128))],14,rN)):ut("",!0)])),Le("span",sN,Ht(S.value),1)],14,$B))}},Nk=hn(aN,[["__scopeId","data-v-99070b63"]]);It();var lN={__name:"FontFamilyCombobox",props:{item:{type:Object,required:!0},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"}},emits:["command","item-clicked","tab-out","editor-handoff"],setup(e,{emit:t}){const n=e,r=t;return(o,i)=>(me(),fn(Nk,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!0,"normalize-value":Ge(XB),onCommand:i[0]||(i[0]=s=>r("command",s)),onItemClicked:i[1]||(i[1]=s=>r("item-clicked")),onTabOut:i[2]||(i[2]=s=>r("tab-out",s)),onEditorHandoff:i[3]||(i[3]=s=>r("editor-handoff"))},null,8,["item","ui-font-family","normalize-value"]))}},cN=lN;It();var uN={__name:"FontSizeCombobox",props:{item:{type:Object,required:!0},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"}},emits:["command","item-clicked","tab-out","editor-handoff"],setup(e,{emit:t}){const n=e,r=t;return(o,i)=>(me(),fn(Nk,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!1,"normalize-value":Ge(JB),onCommand:i[0]||(i[0]=s=>r("command",s)),onItemClicked:i[1]||(i[1]=s=>r("item-clicked")),onTabOut:i[2]||(i[2]=s=>r("tab-out",s)),onEditorHandoff:i[3]||(i[3]=s=>r("editor-handoff"))},null,8,["item","ui-font-family","normalize-value"]))}},dN=uN;It(),gn();var fN=2500,hN=Object.assign({inheritAttrs:!1},{__name:"SdTooltip",props:{trigger:{type:String,default:"hover"},delay:{type:Number,default:100},duration:{type:Number,default:100},disabled:{type:Boolean,default:!1},contentStyle:{type:Object,default:()=>({})}},setup(e){const t=e,n=O2(),r=ne(!1),o=ne(null),i=ne(null),s=ne({top:"0px",left:"0px"});let a=null,l=null,u=null;const c=Se(()=>["sd-tooltip-content",n.class]),d=Se(()=>({...t.contentStyle,...n.style||{},position:"fixed",top:s.value.top,left:s.value.left,zIndex:2100})),h=()=>{a&&(window.clearTimeout(a),a=null)},m=()=>{l&&(window.clearTimeout(l),l=null)},p=()=>{u&&(window.clearTimeout(u),u=null)},g=()=>{p(),u=window.setTimeout(()=>{u=null,S()},fN)},k=()=>{if(!o.value||!i.value)return;const z=o.value.getBoundingClientRect(),Z=i.value.offsetWidth,P=i.value.offsetHeight,N=window.innerWidth||document.documentElement.clientWidth||0,I=8;let L=z.left+z.width/2-Z/2;L=Math.max(I,Math.min(L,N-Z-I)),s.value={top:`${z.top-P-10}px`,left:`${L}px`}},w=async()=>{t.disabled||(h(),m(),!r.value&&(r.value=!0,g(),await _t(),k()))},S=()=>{m(),h(),p(),r.value&&(r.value=!1)},y=()=>{if(h(),m(),!r.value){if(t.delay===0){w();return}l=window.setTimeout(()=>{l=null,w()},t.delay)}},C=()=>{if(m(),h(),!!r.value){if(t.duration===0){S();return}a=window.setTimeout(()=>{a=null,S()},t.duration)}},T=()=>{t.trigger==="hover"&&y()},R=()=>{t.trigger==="hover"&&C()},M=()=>{m(),h()},H=()=>{C()},B=z=>{z.key==="Escape"&&S()};return Pt(()=>t.disabled,z=>{z&&S()}),Pt(r,z=>{z?(window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),document.addEventListener("keydown",B,!0)):(window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),document.removeEventListener("keydown",B,!0))}),ir(()=>{m(),h(),p(),window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),document.removeEventListener("keydown",B,!0)}),(z,Z)=>(me(),_e(Wt,null,[Le("span",{ref_key:"triggerRef",ref:o,class:"sd-tooltip-trigger",onMouseenter:T,onMouseleave:R,onFocusin:T,onFocusout:R},[hd(z.$slots,"trigger",{},void 0,!0)],544),(me(),fn(Oa,{to:"body"},[Gt(Mh,{name:"fade-in-scale-up-transition"},{default:ko(()=>[r.value&&!e.disabled?(me(),_e("div",{key:0,ref_key:"contentRef",ref:i,class:en(c.value),style:vn(d.value),onMouseenter:M,onMouseleave:H},[Z[0]||(Z[0]=Le("span",{class:"sd-tooltip-arrow","aria-hidden":"true"},null,-1)),hd(z.$slots,"default",{},void 0,!0)],38)):ut("",!0)]),_:3})]))],64))}}),Kp=hn(hN,[["__scopeId","data-v-2a872eae"]]);It(),gn();var pN=["onKeydown","tabindex","data-item-id"],mN={key:0},gN={key:0},vN={key:0},yN={key:0},bN={key:0},wN={__name:"ButtonGroup",props:{toolbarItems:{type:Array,required:!0},overflowItems:{type:Array,default:()=>[]},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"},position:{type:String,default:"left"},fromOverflow:{type:Boolean,default:!1},compactSideGroups:{type:Boolean,default:!1}},emits:["command","item-clicked","dropdown-update-show"],setup(e,{emit:t}){const n=t,{proxy:r}=sr(),o=ne([]),i=ne(null),s=e,a=ne(null),{isHighContrastMode:l}=zi(),u=window.matchMedia("(max-width: 768px)").matches,c=Se(()=>s.position==="left"?{minWidth:s.compactSideGroups?"auto":"120px",justifyContent:"flex-start"}:s.position==="right"?{minWidth:s.compactSideGroups?"auto":"120px",justifyContent:"flex-end"}:{flexGrow:u?0:1,justifyContent:"center"}),d=Ie=>Ie.type==="button",h=Ie=>Ie.type==="dropdown",m=Ie=>Ie.type==="dropdown"&&Ie.name?.value==="fontFamily",p=Ie=>Ie.type==="dropdown"&&Ie.name?.value==="fontSize",g=Ie=>Ie.type==="separator",k=Ie=>Ie.type==="overflow",w=Ie=>!!Ie.nestedOptions?.value?.length,S=Ie=>{if(!Ie)return!1;const ze=Ie.expand;return typeof ze=="object"&&ze!==null&&"value"in ze?!!ze.value:!!ze},y=(Ie,ze)=>{Ie?.expand&&(Ie.expand.value=ze)},C=(Ie,ze=void 0)=>{if(Ie.disabled.value)return;if(k(Ie)){const Q=!S(Ie);Q&&M(),y(Ie,Q),a.value=Q?Ie:null,n("item-clicked");return}if(h(Ie))return;a.value&&h(a.value)&&S(a.value)&&M(),n("item-clicked");const Ve=ze!==void 0?ze:Ie.argument?.value;n("command",Ve===void 0?{item:Ie}:{item:Ie,argument:Ve})},T=(Ie,ze)=>{Ie.disabled.value||(a.value=null,n("command",{item:Ie,argument:ze}))},R=Ie=>{if(Ie.disabled.value)return;M();const ze=Ie.splitButtonCommand,Ve=Ie.command,Q=ze||Ve;if(!Q)return;const _={...Ie,command:Q};n("item-clicked"),n("command",{item:_})},M=()=>{const Ie=r?.$toolbar?.toolbarItems||[],ze=r?.$toolbar?.overflowItems||[],Ve=[...Ie,...ze];(Ve.length?Ve:s.toolbarItems).forEach(Q=>{const _=k(Q)&&!s.fromOverflow;(h(Q)||_)&&y(Q,!1)}),a.value=null},H=(Ie,ze)=>{M(),n("command",{item:Ie,argument:Ie.dropdownValueKey.value?ze[Ie.dropdownValueKey.value]:ze.label,option:ze}),Ie.selectedValue.value=ze.key},B=Ie=>{n("command",Ie)},z=()=>{M(),n("item-clicked")},Z=()=>{const Ie=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return Ie instanceof HTMLElement?(Ie.focus({preventScroll:!0}),!0):!1},P=()=>{const Ie=r?.$toolbar?.pendingSelectionCapture,ze=()=>{Ie&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(Ie)};if(Z()){ze();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),ze())},N=Ie=>!(Ie instanceof HTMLElement)||Ie.classList.contains("sd-disabled")?null:Ie.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")||Ie.querySelector('button:not([disabled]), [role="button"]:not(.sd-disabled), [tabindex]:not([tabindex="-1"])'),I=(Ie,ze)=>{const Ve=Ie?.target?.closest?.(".sd-toolbar-item-ctn");if(!(Ve instanceof HTMLElement))return!1;let Q=ze>0?Ve.nextElementSibling:Ve.previousElementSibling;for(;Q;){const _=N(Q);if(_ instanceof HTMLElement)return Ve.setAttribute("tabindex","-1"),Q.setAttribute("tabindex","0"),_.focus(),!0;Q=ze>0?Q.nextElementSibling:Q.previousElementSibling}return!1},L=Ie=>{M(),I(Ie,Ie?.shiftKey?-1:1)||P()},X=Ie=>{if(M(),Ie?.shiftKey){I(Ie,-1)||P();return}P()},te=()=>{P()},le=Ie=>Ie.nestedOptions?.value?.length?Ie.nestedOptions.value.map(ze=>{const Ve=ze?.type!=="render"&&Ie.selectedValue.value===ze.key;return{...ze,props:{...ze.props,class:Ve?"sd-selected":""}}}):[],fe=(Ie,ze)=>({role:"menuitem",ariaLabel:`${ze.attributes.value.ariaLabel} - ${Ie.label}`}),Fe=Ie=>{const ze=Ie.target,Ve=Ie.target.closest(".sd-toolbar-item-ctn").nextElementSibling;Ve&&(ze.setAttribute("tabindex","-1"),Ve.setAttribute("tabindex","0"),Ve.focus())},he=Ie=>{const ze=Ie.target,Ve=Ie.target.closest(".sd-toolbar-item-ctn").previousElementSibling;Ve&&(ze.setAttribute("tabindex","-1"),Ve.setAttribute("tabindex","0"),Ve.focus())},ge=Ie=>{const ze=Ie.target.closest(".button-group").nextElementSibling;if(ze)ze.setAttribute("tabindex","0"),ze.focus();else{const Ve=document.querySelector(".ProseMirror");Ve&&Ve.focus()}},ae=Ie=>{const ze=Ie.target.closest(".button-group").previousElementSibling;ze&&(ze.setAttribute("tabindex","0"),ze.focus())},Ce=Ie=>{if(!Ie.disabled.value){if(h(Ie)){qe(!S(Ie),Ie);return}C(Ie)}},oe=(Ie,ze)=>{const Ve=Ie.target.nodeName==="INPUT"||Ie.target.nodeName==="TEXTAREA",Q=ze.name.value==="fontSize"||ze.name.value==="fontFamily";if(!(Ve&&Q)&&["Enter"," ","Spacebar","Escape","ArrowRight","ArrowLeft","Tab"].includes(Ie.key))switch(Ie.preventDefault(),Ie.key){case"Enter":case" ":case"Spacebar":Ce(ze);break;case"Escape":M();break;case"ArrowRight":M(),Fe(Ie);break;case"ArrowLeft":M(),he(Ie);break;case"Tab":Ie.shiftKey?ae(Ie):ge(Ie);break;default:break}},xe=Ie=>{const ze=o.value.find(Ve=>!Ve.classList.contains("sd-disabled"));ze&&(ze.setAttribute("tabindex","0"),ze.focus())},qe=(Ie,ze)=>{if(n("item-clicked"),!Ie){M(),n("dropdown-update-show",!1);return}M(),a.value=ze,y(ze,!0),n("dropdown-update-show",!0)},et=Ie=>{if(!a.value)return;const ze=Ie.target;ze instanceof Element&&(ze.closest(".sd-toolbar-dropdown-menu")||i.value?.contains(ze)||M())};return Pt(()=>S(a.value),Ie=>{Ie?document.addEventListener("pointerdown",et,!0):document.removeEventListener("pointerdown",et,!0)},{immediate:!0}),ir(()=>{document.removeEventListener("pointerdown",et,!0)}),(Ie,ze)=>(me(),_e("div",{style:vn(c.value),class:"button-group",role:"group",onFocus:xe,ref_key:"buttonGroupRef",ref:i},[(me(!0),_e(Wt,null,or(e.toolbarItems,(Ve,Q)=>(me(),_e("div",{key:Ve.id.value,class:en([{narrow:Ve.isNarrow.value,wide:Ve.isWide.value,"sd-disabled":Ve.disabled.value},"sd-toolbar-item-ctn"]),onKeydown:_=>oe(_,Ve),ref_for:!0,ref_key:"toolbarItemRefs",ref:o,tabindex:Q===0?0:-1,"data-item-id":Ve.id.value},[g(Ve)?(me(),fn(MB,{key:0,style:{width:"20px"}})):ut("",!0),m(Ve)&&w(Ve)?(me(),fn(Kp,{key:1,trigger:"hover",disabled:!Ve.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(cN,{item:Ve,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:B,onItemClicked:z,onTabOut:ze[0]||(ze[0]=_=>L(_)),onEditorHandoff:te},null,8,["item","ui-font-family"])]),default:ko(()=>[Le("div",null,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",mN,"(disabled)")):ut("",!0)])]),_:2},1032,["disabled","content-style"])):p(Ve)&&w(Ve)?(me(),fn(Kp,{key:2,trigger:"hover",disabled:!Ve.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(dN,{item:Ve,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:B,onItemClicked:z,onTabOut:ze[1]||(ze[1]=_=>X(_)),onEditorHandoff:te},null,8,["item","ui-font-family"])]),default:ko(()=>[Le("div",null,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",gN,"(disabled)")):ut("",!0)])]),_:2},1032,["disabled","content-style"])):h(Ve)&&Ve.nestedOptions?.value?.length?(me(),fn(VB,{key:3,options:le(Ve),disabled:Ve.disabled.value,show:S(Ve),"content-style":{fontFamily:s.uiFontFamily},placement:"bottom-start",class:"sd-toolbar-button sd-editor-toolbar-dropdown",onSelect:(_,$)=>H(Ve,$),"onUpdate:show":_=>qe(_,Ve),style:vn(Ve.dropdownStyles.value),"menu-props":()=>({role:"menu",style:{fontFamily:s.uiFontFamily},class:["sd-toolbar-dropdown-menu",{"high-contrast":Ge(l)}]}),"node-props":_=>fe(_,Ve)},{trigger:ko(()=>[Gt(Kp,{trigger:"hover",disabled:!Ve.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(O0,{"toolbar-item":Ve,disabled:Ve.disabled.value,"allow-enter-propagation":!0,onTextSubmit:_=>T(Ve,_),onMainClick:_=>R(Ve)},null,8,["toolbar-item","disabled","onTextSubmit","onMainClick"])]),default:ko(()=>[Le("div",null,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",vN,"(disabled)")):ut("",!0)])]),_:2},1032,["disabled","content-style"])]),_:2},1032,["options","disabled","show","content-style","onSelect","onUpdate:show","style","menu-props","node-props"])):d(Ve)?(me(),fn(Kp,{key:4,trigger:"hover",class:"sd-editor-toolbar-tooltip","content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(O0,{"toolbar-item":Ve,"is-overflow-item":e.fromOverflow,onTextSubmit:_=>T(Ve,_),onButtonClick:_=>C(Ve)},null,8,["toolbar-item","is-overflow-item","onTextSubmit","onButtonClick"])]),default:ko(()=>[Ve.tooltip?(me(),_e("div",yN,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",bN,"(disabled)")):ut("",!0)])):ut("",!0)]),_:2},1032,["content-style"])):ut("",!0),k(Ve)&&e.overflowItems.length?(me(),fn(FB,{key:5,"toolbar-item":Ve,onButtonClick:_=>C(Ve),"overflow-items":e.overflowItems,onClose:M},null,8,["toolbar-item","onButtonClick","overflow-items"])):ut("",!0)],42,pN))),128))],36))}},qp=hn(wN,[["__scopeId","data-v-590293ab"]]),CN=[["Arial","sans-serif"],["Arial Black","sans-serif"],["Arial Narrow","sans-serif"],["Baskerville Old Face","serif"],["Bookman Old Style","serif"],["Brush Script MT","cursive"],["Calibri","sans-serif"],["Century","serif"],["Century Gothic","sans-serif"],["Comic Sans MS","sans-serif"],["Cooper Black","serif"],["Courier New","monospace"],["Garamond","serif"],["Georgia","serif"],["Gill Sans MT Condensed","sans-serif"],["Helvetica","sans-serif"],["Lucida Console","monospace"],["Segoe UI","sans-serif"],["Tahoma","sans-serif"],["Times New Roman","serif"],["Trebuchet MS","sans-serif"],["Verdana","sans-serif"]];const _N=CN.map(([e,t])=>({label:e,key:e,fontWeight:400,props:{style:{fontFamily:`${e}, ${t}`},"data-item":"btn-fontFamily-option"}}));function SN(e){if(e?.length)return e.map(t=>({label:t.label,key:t.value,fontWeight:400,props:{style:{fontFamily:t.previewFamily||t.label},"data-item":"btn-fontFamily-option"}}))}const kN=[{label:"8",key:"8pt",props:{"data-item":"btn-fontSize-option"}},{label:"9",key:"9pt",props:{"data-item":"btn-fontSize-option"}},{label:"10",key:"10pt",props:{"data-item":"btn-fontSize-option"}},{label:"11",key:"11pt",props:{"data-item":"btn-fontSize-option"}},{label:"12",key:"12pt",props:{"data-item":"btn-fontSize-option"}},{label:"14",key:"14pt",props:{"data-item":"btn-fontSize-option"}},{label:"18",key:"18pt",props:{"data-item":"btn-fontSize-option"}},{label:"24",key:"24pt",props:{"data-item":"btn-fontSize-option"}},{label:"30",key:"30pt",props:{"data-item":"btn-fontSize-option"}},{label:"36",key:"36pt",props:{"data-item":"btn-fontSize-option"}},{label:"48",key:"48pt",props:{"data-item":"btn-fontSize-option"}},{label:"60",key:"60pt",props:{"data-item":"btn-fontSize-option"}},{label:"72",key:"72pt",props:{"data-item":"btn-fontSize-option"}},{label:"96",key:"96pt",props:{"data-item":"btn-fontSize-option"}}],kf={sm:768,md:1024,lg:1280,xl:1410},F0={undo:"undo",redo:"redo",bold:"bold",italic:"italic",underline:"underline",strike:"strikethrough",acceptTrackedChangeBySelection:"track-changes-accept-selection",rejectTrackedChangeOnSelection:"track-changes-reject-selection",ruler:"ruler",formattingMarks:"formatting-marks",zoom:"zoom",measurementUnit:"measurement-unit",documentMode:"document-mode",link:"link",fontFamily:"font-family",fontSize:"font-size",list:"bullet-list",numberedlist:"numbered-list",table:"table-insert",image:"image",tableOfContents:"table-of-contents-insert",color:"text-color",highlight:"highlight-color",textAlign:"text-align",lineHeight:"line-height",linkedStyles:"linked-style",indentleft:"indent-decrease",indentright:"indent-increase",directionLtr:"direction-ltr",directionRtl:"direction-rtl",clearFormatting:"clear-formatting",copyFormat:"copy-format"},zk={addRowBefore:"table-add-row-before",addRowAfter:"table-add-row-after",deleteRow:"table-delete-row",addColumnBefore:"table-add-column-before",addColumnAfter:"table-add-column-after",deleteColumn:"table-delete-column",deleteTable:"table-delete",deleteCellAndTableBorders:"table-remove-borders",mergeCells:"table-merge-cells",splitCell:"table-split-cell",fixTables:"table-fix"},Hk=Object.values(zk),Ij=[...new Set([...Object.values(F0),...Hk])];var AN=new Set(["link"]);const Ej=new Set(Object.keys(F0).filter(e=>!AN.has(e)));It(),gn();var IN="Arial, Helvetica, sans-serif",EN={__name:"Toolbar",emits:["command","toggle","select"],setup(e,{emit:t}){const{proxy:n}=sr();let r=ne(1);const o=ne(0),i=ne(!1);let s=null,a=null;const l=Se(()=>{const H=n?.$toolbar?.config?.uiDisplayFallbackFont;return typeof H=="string"&&H.trim()?H.trim():IN}),u=n.$toolbar.config?.toolbarGroups?.includes("left"),c=n.$toolbar.config?.toolbarGroups?.includes("right"),d=n.$toolbar.config?.toolbarButtonsExclude||[],h=H=>(o.value,n.$toolbar.getToolbarItemByGroup(H).filter(B=>!d.includes(B.name.value))),m=()=>{i.value=n.$toolbar.getAvailableWidth()<=kf.lg},g=hB(async()=>{await n.$toolbar.onToolbarResize(),m(),r.value+=1},300),k=()=>{r.value+=1},w=()=>{o.value+=1};function S(){window.removeEventListener("resize",g),n.$toolbar.off?.("toolbar-items-changed",k),n.$toolbar.off?.("toolbar-state-change",w),s?.disconnect(),s=null}function y(){S(),window.addEventListener("resize",g),n.$toolbar.on?.("toolbar-items-changed",k),n.$toolbar.on?.("toolbar-state-change",w),typeof ResizeObserver<"u"&&n.$toolbar.config?.responsiveToContainer&&n.$toolbar.toolbarContainer&&(s=new ResizeObserver(()=>{g()}),s.observe(n.$toolbar.toolbarContainer)),m()}Rn(y),mg(y),gg(S),ir(S);const C=()=>{if(!n.$toolbar.activeEditor){a=null,n.$toolbar.pendingSelectionCapture=null;return}a=n.$toolbar.ui?.selection?.capture?.()??null,n.$toolbar.pendingSelectionCapture=a},T=({item:H,argument:B,option:z})=>{R(),n.$toolbar.emitCommand({item:H,argument:B,option:z})},R=()=>{const H=n.$toolbar.activeEditor;if(!H)return;const B=n.$toolbar.pendingSelectionCapture??a;if(B&&typeof n.$toolbar.ui?.selection?.restore=="function"){n.$toolbar.ui.selection.restore(B);return}H.commands?.restoreSelection?.()},M=H=>{C(),!H.target.closest('input, textarea, [contenteditable="true"]')&&H.preventDefault()};return(H,B)=>(me(),_e("div",{class:"superdoc-toolbar",key:Ge(r),role:"toolbar","aria-label":"Toolbar","data-sd-part":"toolbar","data-editor-ui-surface":"",onMousedown:M},[Ge(u)?(me(),fn(qp,{key:0,tabindex:"0","toolbar-items":h("left"),"overflow-items":Ge(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"left",onCommand:T,class:"superdoc-toolbar-group-side"},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"])):ut("",!0),Gt(qp,{tabindex:"0","toolbar-items":h("center"),"overflow-items":Ge(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"center",onCommand:T},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"]),Ge(c)?(me(),fn(qp,{key:1,tabindex:"0","toolbar-items":h("right"),"overflow-items":Ge(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"right",onCommand:T,class:"superdoc-toolbar-group-side"},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"])):ut("",!0)],32))}},xN=hn(EN,[["__scopeId","data-v-55b5af7a"]]);const TN=e=>{if(!e)return e;const t=e.props?.style?.fontFamily??e.label??e.key;return{...e,props:{...e.props,style:{...e.props?.style,fontFamily:t},"data-item":e.props?.["data-item"]??"btn-fontFamily-option"}}};It();const Cn=e=>{if(!["button","options","separator","dropdown","overflow"].includes(e.type))throw new Error("Invalid toolbar item type - "+e.type);if(e.type==="button"&&!e.defaultLabel&&!e.icon)throw new Error("Toolbar button item needs either icon or label - "+e.name);if(!e.name)throw new Error("Invalid toolbar item name - "+e.name);const t=ne(os()),n=e.type,r=ne(e.name),o=e.command,i=e.noArgumentCommand,s=ne(e.icon),a=ne(e.group||"center"),l=ne(e.allowWithoutEditor),u=ne(e.attributes||{}),c=e.disabled||!1,d=ne(e.disabled),h=ne(!1),m=ne(!1),p=ne(e.style),g=ne(e.isNarrow),k=ne(e.isWide),w=ne(e.minWidth),S=ne(e.suppressActiveHighlight||!1),y=ne(e.argument),C=ne(null),T=ne(null),R=ne(e.iconColor),M=ne(e.hasCaret),H=ne(!!e.splitButton),B=e.splitButtonCommand,z=!!e.restoreEditorFocus,Z=ne(e.dropdownStyles),P=ne(e.tooltip),N=ne(e.tooltipVisible),I=ne(e.tooltipTimeout),L=ne(e.defaultLabel),X=ne(e.label),te=ne(e.hideLabel),le=ne(e.inlineTextInputVisible),fe=ne(e.hasInlineTextInput),Fe=ne(e.markName),he=ne(e.labelAttr),ge=ne(e.selectedValue),ae=ne(e.dropdownValueKey),Ce=ne(e.inputRef||null),oe=ne([]);if(e.options){if(!Array.isArray(e.options))throw new Error("Invalid toolbar item options - "+e.options);oe.value?.push(...e.options)}const xe=(_={},...$)=>{Ie(_,...$),!S.value&&(h.value=!0)},qe=()=>{ze(),h.value=!1},et=_=>{d.value=_},kt=()=>{d.value=c},Ie=e.onActivate||(()=>null),ze=e.onDeactivate||(()=>null),Ve=()=>{const _={};return Object.keys(Q).forEach($=>{Q[$].value!==void 0&&(_[$]=Q[$].value)}),_},Q={id:t,name:r,type:n,command:o,noArgumentCommand:i,icon:s,tooltip:P,group:a,attributes:u,disabled:d,active:h,expand:m,nestedOptions:oe,style:p,isNarrow:g,isWide:k,minWidth:w,argument:y,parentItem:T,iconColor:R,hasCaret:M,splitButton:H,splitButtonCommand:B,dropdownStyles:Z,tooltipVisible:N,tooltipTimeout:I,defaultLabel:L,label:X,hideLabel:te,inlineTextInputVisible:le,hasInlineTextInput:fe,restoreEditorFocus:z,markName:Fe,labelAttr:he,childItem:C,allowWithoutEditor:l,dropdownValueKey:ae,selectedValue:ge,inputRef:Ce};return{...Q,unref:Ve,activate:xe,deactivate:qe,setDisabled:et,resetDisabled:kt,onActivate:Ie,onDeactivate:ze}};It(),gn();var RN=["onClick","innerHTML","aria-label","onKeydown"],MN={__name:"AlignmentButtons",emits:["select"],setup(e,{emit:t}){const{isHighContrastMode:n}=zi(),r=t,o=ne([]),i=[{key:"left",ariaLabel:"Align left",icon:tr.alignLeft},{key:"center",ariaLabel:"Align center",icon:tr.alignCenter},{key:"right",ariaLabel:"Align right",icon:tr.alignRight},{key:"justify",ariaLabel:"Justify",icon:tr.alignJustify}],s=c=>{r("select",c)},a=c=>{if(c===o.value.length-1)return;const d=o.value[c+1];d&&(d.setAttribute("tabindex","0"),d.focus())},l=c=>{if(c===0)return;const d=o.value[c-1];d&&(d.setAttribute("tabindex","0"),d.focus())},u=(c,d)=>{switch(c.key){case"ArrowLeft":l(d);break;case"ArrowRight":a(d);break;case"Enter":s(i[d].key);break;default:break}};return Rn(()=>{const c=o.value[0];c&&(c.setAttribute("tabindex","0"),c.focus())}),(c,d)=>(me(),_e("div",{class:en(["alignment-buttons",{"high-contrast":Ge(n)}])},[(me(),_e(Wt,null,or(i,(h,m)=>Le("div",{key:h.key,class:"sd-button-icon",onClick:p=>s(h.key),innerHTML:h.icon,"data-item":"btn-textAlign-option",role:"menuitem","aria-label":h.ariaLabel,ref_for:!0,ref_key:"alignmentButtonsRefs",ref:o,onKeydown:Jt(p=>u(p,m),["prevent"])},null,40,RN)),64))],2))}},LN=hn(MN,[["__scopeId","data-v-13e5f7a4"]]);It(),gn();var DN=["onClick","innerHTML","aria-label","onKeydown"],PN={__name:"StyleButtonsList",props:{buttons:{type:Array,required:!0},selectedStyle:{type:String,default:null},iconSize:{type:Number,default:25}},emits:["select"],setup(e,{emit:t}){const{isHighContrastMode:n}=zi(),r=t,o=e,i=ne([]),s=Se(()=>({width:`${o.iconSize}px`,height:`${o.iconSize}px`})),a=d=>{r("select",d)},l=d=>{if(d===i.value.length-1)return;const h=i.value[d+1];h&&(h.setAttribute("tabindex","0"),h.focus())},u=d=>{if(d===0)return;const h=i.value[d-1];h&&(h.setAttribute("tabindex","0"),h.focus())},c=(d,h)=>{switch(d.key){case"ArrowLeft":u(h);break;case"ArrowRight":l(h);break;case"Enter":a(o.buttons[h].key);break;default:break}};return Rn(()=>{const d=i.value[0];d&&(d.setAttribute("tabindex","0"),d.focus())}),(d,h)=>(me(),_e("div",{class:en(["style-buttons-list",{"high-contrast":Ge(n)}])},[(me(!0),_e(Wt,null,or(o.buttons,(m,p)=>(me(),_e("div",{key:m.key,class:en(["sd-button-icon",{"sd-selected":o.selectedStyle===m.key}]),style:vn(s.value),onClick:g=>a(m.key),innerHTML:m.icon,role:"menuitem","aria-label":m.ariaLabel,ref_for:!0,ref_key:"buttonRefs",ref:i,onKeydown:Jt(g=>c(g,p),["prevent"])},null,46,DN))),128))],2))}},Uk=hn(PN,[["__scopeId","data-v-44f37ff6"]]);const ON=[{key:"disc",icon:tr.bulletListDisc,ariaLabel:"Opaque circle"},{key:"circle",icon:tr.bulletListCircle,ariaLabel:"Outline circle"},{key:"square",icon:tr.bulletListSquare,ariaLabel:"Opaque square"}],FN=[{key:"decimal",icon:tr.numberedListDecimal,ariaLabel:"1. 2. 3."},{key:"decimal-paren",icon:tr.numberedListDecimalParen,ariaLabel:"1) 2) 3)"},{key:"upper-roman",icon:tr.numberedListUpperRoman,ariaLabel:"I. II. III."},{key:"lower-roman",icon:tr.numberedListLowerRoman,ariaLabel:"i. ii. iii."},{key:"upper-alpha",icon:tr.numberedListUpperAlpha,ariaLabel:"A. B. C."},{key:"upper-alpha-paren",icon:tr.numberedListUpperAlphaParen,ariaLabel:"A) B) C)"},{key:"lower-alpha",icon:tr.numberedListLowerAlpha,ariaLabel:"a. b. c."},{key:"lower-alpha-paren",icon:tr.numberedListLowerAlphaParen,ariaLabel:"a) b) c)"}];It(),gn();var BN=["onClick","onKeydown"],NN={class:"document-mode-column icon-column"},zN=["innerHTML"],HN={class:"document-mode-column text-column"},UN={class:"document-mode-type"},VN={class:"document-mode-description"},jN={__name:"DocumentMode",props:{options:{type:Array}},emits:["select"],setup(e,{emit:t}){const n=t,r=ne([]),{isHighContrastMode:o}=zi(),i=e,s=c=>{n("select",c)},a=c=>{if(c===r.value.length-1)return;const d=r.value[c+1];d&&(d.setAttribute("tabindex","0"),d.focus())},l=c=>{if(c===0)return;const d=r.value[c-1];d&&(d.setAttribute("tabindex","0"),d.focus())},u=(c,d)=>{switch(c.key){case"ArrowDown":a(d);break;case"ArrowUp":l(d);break;case"Enter":s(i.options[d]);break;default:break}};return Rn(()=>{r.value[0].setAttribute("tabindex","0"),r.value[0].focus()}),(c,d)=>(me(),_e("div",{class:en(["document-mode",{"high-contrast":Ge(o)}])},[(me(!0),_e(Wt,null,or(e.options,(h,m)=>(me(),_e("div",{class:en(["sd-option-item",{"sd-disabled":h.disabled}]),onClick:p=>s(h),"data-item":"btn-documentMode-option",role:"menuitem",ref_for:!0,ref_key:"documentModeRefs",ref:r,onKeydown:Jt(p=>u(p,m),["prevent"])},[Le("div",NN,[Le("div",{class:"icon-column__icon",innerHTML:h.icon},null,8,zN)]),Le("div",HN,[Le("div",UN,Ht(h.label),1),Le("div",VN,Ht(h.description),1)])],42,BN))),256))],2))}},GN=hn(jN,[["__scopeId","data-v-bee14d7a"]]);It(),gn();var WN={class:"linked-style-buttons","data-editor-ui-surface":""},KN=["onClick","onKeydown","aria-label"],qN={__name:"LinkedStyle",props:{styles:{type:Array,default:()=>[]},selectedOption:{type:String,default:null}},emits:["select"],setup(e,{emit:t}){const n=t,r=ne([]),o=e,i=d=>{n("select",d)},s=d=>{if(d===r.value.length-1)return;const h=r.value[d+1];h.setAttribute("tabindex","0"),h.focus()},a=d=>{if(d===0)return;const h=r.value[d-1];h.setAttribute("tabindex","0"),h.focus()},l=(d,h,m)=>{switch(d.key){case"ArrowDown":s(h);break;case"ArrowUp":a(h);break;case"Enter":d.preventDefault(),i(m);break;default:break}},u=d=>d?.name??d?.id??"",c=d=>{const h=d?.preview?.css;return h&&typeof h=="object"?h:void 0};return Rn(()=>{r.value[0]&&(r.value[0].setAttribute("tabindex","0"),r.value[0].focus())}),(d,h)=>(me(),_e("div",WN,[(me(!0),_e(Wt,null,or(o.styles,(m,p)=>(me(),_e("div",{key:m.id??p,class:en(["style-item",{selected:e.selectedOption===m.id}]),onClick:g=>i(m),onKeydown:g=>l(g,p,m),"aria-label":`Linked style - ${m.id??u(m)}`,ref_for:!0,ref_key:"styleRefs",ref:r},[Le("div",{class:"style-name","data-item":"btn-linkedStyles-option",style:vn(c(m))},Ht(u(m)),5)],42,KN))),128))]))}},YN=hn(qN,[["__scopeId","data-v-43b5dcca"]]);It(),gn();var XN=["placeholder"],QN={class:"sd-ai-writer__footer"},ZN={key:0,class:"sd-ai-writer__error",role:"alert"},JN=["disabled"],$N="https://sd-dev-express-gateway-i6xtm.ondigitalocean.app/insights",ez="You are an expert copywriter and you are immersed in a document editor. Only write what is asked for.",tz={__name:"AIWriter",props:{selectedText:{type:String,default:""},target:{type:Object,default:null},doc:{type:Object,default:null},apiKey:{type:String,default:""},endpoint:{type:String,default:""},restoreSelection:{type:Function,default:null},handleClose:{type:Function,required:!0}},setup(e){const t=e,n=ne(""),r=ne(!1),o=ne(""),i=ne(null),s=Se(()=>t.selectedText?"Insert prompt to update text":"Insert prompt to generate text"),a=Se(()=>n.value.trim().length>0&&!r.value);Rn(()=>{_t(()=>{i.value?.focus()})});function l(p){if(typeof p=="string")return p;if(!p||typeof p!="object")return"";const g=p.custom_prompt;if(Array.isArray(g)){const k=g[0];if(k&&typeof k.value=="string")return k.value}return g&&typeof g=="object"&&typeof g.value=="string"?g.value:typeof p.value=="string"?p.value:typeof p.text=="string"?p.text:""}async function u(p){const g={"Content-Type":"application/json"};t.apiKey&&(g["x-api-key"]=t.apiKey);const k=t.selectedText.trim(),w=k?`Rewrite the following text: "${k}" using these instructions: ${p}`:`Generate text based on the following prompt: ${p}`,S=await fetch(t.endpoint||$N,{method:"POST",headers:g,body:JSON.stringify({stream:!1,context:ez,insights:[{type:"custom_prompt",name:k?"text_rewrite":"text_generation",message:w,format:[{value:""}]}]})});if(!S.ok){const C=await S.text().catch(()=>"");throw new Error(C||`AI request failed with ${S.status}`)}const y=l((S.headers.get("content-type")||"").includes("application/json")?await S.json():await S.text()).trim();if(!y)throw new Error("AI returned no text.");return y}function c(p){return!p||typeof p!="object"?!0:!(p.success===!1||p.ok===!1)}function d(p){const g=t.doc;if(!g)throw new Error("Document API is unavailable.");t.restoreSelection?.();let k=null,w=!1;if(t.selectedText&&t.target&&typeof g.replace=="function"?(k=g.replace({target:t.target,text:p}),w=!0):t.target&&typeof g.insert=="function"?(k=g.insert({target:t.target,value:p,type:"text"}),w=!0):typeof g.insert=="function"&&(k=g.insert({value:p,type:"text"}),w=!0),!w)throw new Error("Document text insertion is unavailable.");if(!c(k))throw new Error("Unable to insert generated text.")}async function h(){if(a.value){o.value="",r.value=!0;try{d(await u(n.value.trim())),t.handleClose()}catch(p){o.value=p instanceof Error?p.message:String(p)}finally{r.value=!1}}}function m(p){p.key!=="Enter"||p.shiftKey||(p.preventDefault(),h())}return(p,g)=>(me(),_e("form",{class:"sd-ai-writer","data-item":"ai-writer",onSubmit:Jt(h,["prevent"])},[Ws(Le("textarea",{ref_key:"textareaRef",ref:i,"onUpdate:modelValue":g[0]||(g[0]=k=>n.value=k),class:"sd-ai-writer__input",placeholder:s.value,rows:"4",onKeydown:m},null,40,XN),[[ki,n.value]]),Le("div",QN,[o.value?(me(),_e("p",ZN,Ht(o.value),1)):ut("",!0),Le("button",{class:"sd-ai-writer__submit",type:"submit",disabled:!a.value},Ht(r.value?"Generating":"Generate"),9,JN)])],32))}},nz=hn(tz,[["__scopeId","data-v-67f6c6f7"]]);It(),gn();var rz=["aria-label","onClick","onKeydown"],oz=["innerHTML"],iz=["innerHTML"],Yp=7,sz={__name:"IconGridRow",props:{icons:{type:Array,required:!0},activeColor:{type:Object,required:!1}},emits:["select","clickoutside"],setup(e,{emit:t}){const n=t,r=e,o=Se(()=>p=>r.activeColor.value?r.activeColor.value.toUpperCase()===p.value:!1),i=(p,g)=>g===5||["#FFFFFF","#FAFF09"].includes(p)?{color:"#000"}:{color:"#FFF"},s=p=>{n("select",p.value)},a=ne([]),l=ne([]);Rn(()=>{if(!r.icons.every(g=>Array.isArray(g)))throw new Error("icon props must be 2d array");const p=l.value[0];p&&(p.setAttribute("tabindex","0"),p.focus({preventScroll:!0}))});const u=(p,g)=>{const k=Yp*p+g+1,w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},c=(p,g)=>{const k=Yp*p+g-1,w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},d=(p,g)=>{const k=g+Yp*(p+1),w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},h=(p,g)=>{const k=g+Yp*(p-1),w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},m=(p,g,k,w)=>{switch(p.key){case"ArrowRight":u(g,k);break;case"ArrowLeft":c(g,k);break;case"ArrowDown":d(g,k);break;case"ArrowUp":h(g,k);break;case"Enter":s(w);break;case"Escape":n("clickoutside");break;default:break}};return(p,g)=>(me(!0),_e(Wt,null,or(e.icons,(k,w)=>(me(),_e("div",{class:"sd-option-row",key:w,role:"group",ref_for:!0,ref_key:"rowRefs",ref:a},[(me(!0),_e(Wt,null,or(k,(S,y)=>(me(),_e("div",{class:"sd-option",key:y,"aria-label":S.label,role:"menuitem",ref_for:!0,ref_key:"iconRefs",ref:l,onClick:Jt(C=>s(S),["stop","prevent"]),onKeydown:Jt(C=>m(C,w,y,S),["prevent"])},[Le("div",{class:"sd-option__icon",innerHTML:S.icon,style:vn(S.style)},null,12,oz),o.value(S)?(me(),_e("div",{key:0,class:"sd-option__check",innerHTML:Ge(tr).colorOptionCheck,style:vn(i(S.value,y))},null,12,iz)):ut("",!0)],40,rz))),128))]))),128))}},Vk=hn(sz,[["__scopeId","data-v-05eb02fc"]]),az=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M320 512c53.2 0 101.4-21.6 136.1-56.6l-298.3-235C140 257.1 128 292.3 128 320c0 106 86 192 192 192zM505.2 370.7c4.4-16.2 6.8-33.1 6.8-50.7c0-91.2-130.2-262.3-166.6-308.3C339.4 4.2 330.5 0 320.9 0l-1.8 0c-9.6 0-18.5 4.2-24.5 11.7C277.8 33 240.7 81.3 205.8 136L38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L505.2 370.7zM224 336c0 44.2 35.8 80 80 80c8.8 0 16 7.2 16 16s-7.2 16-16 16c-61.9 0-112-50.1-112-112c0-8.8 7.2-16 16-16s16 7.2 16 16z"/></svg>
|
|
99
|
+
`,i4=()=>{if(typeof document>"u")throw new Error(fP)},Ui=class jA{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new jA(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),o=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,s=this.m[0]*-r+this.m[2]*n,a=this.m[1]*-r+this.m[3]*n;return this.m[0]=o,this.m[1]=i,this.m[2]=s,this.m[3]=a,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,o=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,s=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=o,this.m[2]=i,this.m[3]=s,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],o=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],s=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],a=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=o,this.m[3]=i,this.m[4]=s,this.m[5]=a,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,o=-this.m[2]*t,i=this.m[0]*t,s=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),a=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=o,this.m[3]=i,this.m[4]=s,this.m[5]=a,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],i=this.m[4],s=this.m[5],a=t*o-n*r,l={x:i,y:s,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const u=Math.sqrt(t*t+n*n);l.rotation=n>0?Math.acos(t/u):-Math.acos(t/u),l.scaleX=u,l.scaleY=a/u,l.skewX=(t*r+n*o)/a,l.skewY=0}else if(r!=0||o!=0){const u=Math.sqrt(r*r+o*o);l.rotation=Math.PI/2-(o>0?Math.acos(-r/u):-Math.acos(r/u)),l.scaleX=a/u,l.scaleY=u,l.skewX=0,l.skewY=(t*r+n*o)/a}return l.rotation=Ae._getRotation(l.rotation),l}},hP="[object Array]",pP="[object Number]",mP="[object String]",gP="[object Boolean]",vP=Math.PI/180,yP=180/Math.PI,of="#",bP="",wP="0",CP="Konva warning: ",s4="Konva error: ",_P="rgb(",s0={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},SP=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,Ip=[],sf=null,kP=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(e){setTimeout(e,16)};const Ae={_isElement(e){return!!(e&&e.nodeType==1)},_isFunction(e){return!!(e&&e.constructor&&e.call&&e.apply)},_isPlainObject(e){return!!e&&e.constructor===Object},_isArray(e){return Object.prototype.toString.call(e)===hP},_isNumber(e){return Object.prototype.toString.call(e)===pP&&!isNaN(e)&&isFinite(e)},_isString(e){return Object.prototype.toString.call(e)===mP},_isBoolean(e){return Object.prototype.toString.call(e)===gP},isObject(e){return e instanceof Object},isValidSelector(e){if(typeof e!="string")return!1;const t=e[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(e){return e===0||e>0?1:-1},requestAnimFrame(e){Ip.push(e),Ip.length===1&&kP(function(){const t=Ip;Ip=[],t.forEach(function(n){n()})})},createCanvasElement(){i4();const e=document.createElement("canvas");try{e.style=e.style||{}}catch{}return e},createImageElement(){return i4(),document.createElement("img")},_isInDocument(e){for(;e=e.parentNode;)if(e==document)return!0;return!1},_urlToImage(e,t){const n=Ae.createImageElement();n.onload=function(){t(n)},n.src=e},_rgbToHex(e,t,n){return((1<<24)+(e<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(e){e=e.replace(of,bP);const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let e=(Math.random()*16777215<<0).toString(16);for(;e.length<6;)e=wP+e;return of+e},isCanvasFarblingActive(){if(sf!==null)return sf;if(typeof document>"u")return sf=!1,!1;const e=this.createCanvasElement();e.width=10,e.height=10;const t=e.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let o=0;o<100;o++)if(n[o*4]!==40||n[o*4+1]!==40||n[o*4+2]!==40||n[o*4+3]!==255){r=!0;break}return sf=r,this.releaseCanvas(e),sf},getHitColor(){const e=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(e):e},getHitColorKey(e,t,n){return this.isCanvasFarblingActive()&&(e=Math.round(e/5)*5,t=Math.round(t/5)*5,n=Math.round(n/5)*5),of+this._rgbToHex(e,t,n)},getSnappedHexColor(e){const t=this._hexToRgb(e);return of+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(e){let t;return e in s0?(t=s0[e],{r:t[0],g:t[1],b:t[2]}):e[0]===of?this._hexToRgb(e.substring(1)):e.substr(0,4)===_P?(t=SP.exec(e.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(e){return e=e||"black",Ae._namedColorToRBA(e)||Ae._hex3ColorToRGBA(e)||Ae._hex4ColorToRGBA(e)||Ae._hex6ColorToRGBA(e)||Ae._hex8ColorToRGBA(e)||Ae._rgbColorToRGBA(e)||Ae._rgbaColorToRGBA(e)||Ae._hslColorToRGBA(e)},_namedColorToRBA(e){const t=s0[e.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(e){if(e.indexOf("rgb(")===0){e=e.match(/rgb\(([^)]+)\)/)[1];const t=e.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(e){if(e.indexOf("rgba(")===0){e=e.match(/rgba\(([^)]+)\)/)[1];const t=e.split(/ *, */).map((n,r)=>n.slice(-1)==="%"?r===3?parseInt(n)/100:parseInt(n)/100*255:Number(n));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(e){if(e[0]==="#"&&e.length===9)return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:parseInt(e.slice(7,9),16)/255}},_hex6ColorToRGBA(e){if(e[0]==="#"&&e.length===7)return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1}},_hex4ColorToRGBA(e){if(e[0]==="#"&&e.length===5)return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:parseInt(e[4]+e[4],16)/255}},_hex3ColorToRGBA(e){if(e[0]==="#"&&e.length===4)return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1}},_hslColorToRGBA(e){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(e)){const[t,...n]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(e),r=Number(n[0])/360,o=Number(n[1])/100,i=Number(n[2])/100;let s,a,l;if(o===0)return l=i*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};i<.5?s=i*(1+o):s=i+o-i*o;const u=2*i-s,c=[0,0,0];for(let d=0;d<3;d++)a=r+1/3*-(d-1),a<0&&a++,a>1&&a--,6*a<1?l=u+(s-u)*6*a:2*a<1?l=s:3*a<2?l=u+(s-u)*(2/3-a)*6:l=u,c[d]=l*255;return{r:Math.round(c[0]),g:Math.round(c[1]),b:Math.round(c[2]),a:1}}},haveIntersection(e,t){return!(t.x>e.x+e.width||t.x+t.width<e.x||t.y>e.y+e.height||t.y+t.height<e.y)},cloneObject(e){const t={};for(const n in e)this._isPlainObject(e[n])?t[n]=this.cloneObject(e[n]):this._isArray(e[n])?t[n]=this.cloneArray(e[n]):t[n]=e[n];return t},cloneArray(e){return e.slice(0)},degToRad(e){return e*vP},radToDeg(e){return e*yP},_degToRad(e){return Ae.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),Ae.degToRad(e)},_radToDeg(e){return Ae.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),Ae.radToDeg(e)},_getRotation(e){return gt.angleDeg?Ae.radToDeg(e):e},_capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)},throw(e){throw new Error(s4+e)},error(e){console.error(s4+e)},warn(e){gt.showWarnings&&console.warn(CP+e)},each(e,t){for(const n in e)t(n,e[n])},_inRange(e,t,n){return t<=e&&e<n},_getProjectionToSegment(e,t,n,r,o,i){let s,a,l;const u=(e-n)*(e-n)+(t-r)*(t-r);if(u==0)s=e,a=t,l=(o-n)*(o-n)+(i-r)*(i-r);else{const c=((o-e)*(n-e)+(i-t)*(r-t))/u;c<0?(s=e,a=t,l=(e-o)*(e-o)+(t-i)*(t-i)):c>1?(s=n,a=r,l=(n-o)*(n-o)+(r-i)*(r-i)):(s=e+c*(n-e),a=t+c*(r-t),l=(s-o)*(s-o)+(a-i)*(a-i))}return[s,a,l]},_getProjectionToLine(e,t,n){const r=Ae.cloneObject(e);let o=Number.MAX_VALUE;return t.forEach(function(i,s){if(!n&&s===t.length-1)return;const a=t[(s+1)%t.length],l=Ae._getProjectionToSegment(i.x,i.y,a.x,a.y,e.x,e.y),u=l[0],c=l[1],d=l[2];d<o&&(r.x=u,r.y=c,o=d)}),r},_prepareArrayForTween(e,t,n){const r=[],o=[];if(e.length>t.length){const s=t;t=e,e=s}for(let s=0;s<e.length;s+=2)r.push({x:e[s],y:e[s+1]});for(let s=0;s<t.length;s+=2)o.push({x:t[s],y:t[s+1]});const i=[];return o.forEach(function(s){const a=Ae._getProjectionToLine(s,r,n);i.push(a.x),i.push(a.y)}),i},_prepareToStringify(e){let t;e.visitedByCircularReferenceRemoval=!0;for(const n in e)if(e.hasOwnProperty(n)&&e[n]&&typeof e[n]=="object"){if(t=Object.getOwnPropertyDescriptor(e,n),e[n].visitedByCircularReferenceRemoval||Ae._isElement(e[n]))if(t.configurable)delete e[n];else return null;else if(Ae._prepareToStringify(e[n])===null)if(t.configurable)delete e[n];else return null}return delete e.visitedByCircularReferenceRemoval,e},_assign(e,t){for(const n in t)e[n]=t[n];return e},_getFirstPointerId(e){return e.touches?e.changedTouches[0].identifier:e.pointerId||999},releaseCanvas(...e){gt.releaseCanvasOnDestroy&&e.forEach(t=>{t.width=0,t.height=0})},drawRoundedRectPath(e,t,n,r){let o=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let s=0,a=0,l=0,u=0;typeof r=="number"?s=a=l=u=Math.min(r,t/2,n/2):(s=Math.min(r[0]||0,t/2,n/2),a=Math.min(r[1]||0,t/2,n/2),u=Math.min(r[2]||0,t/2,n/2),l=Math.min(r[3]||0,t/2,n/2)),e.moveTo(o+s,i),e.lineTo(o+t-a,i),e.arc(o+t-a,i+a,a,Math.PI*3/2,0,!1),e.lineTo(o+t,i+n-u),e.arc(o+t-u,i+n-u,u,0,Math.PI/2,!1),e.lineTo(o+l,i+n),e.arc(o+l,i+n-l,l,Math.PI/2,Math.PI,!1),e.lineTo(o,i+s),e.arc(o+s,i+s,s,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(e,t,n,r,o){r=Math.abs(r);for(let i=0;i<n;i++){const s=t[(i-1+n)%n],a=t[i],l=t[(i+1)%n],u={x:a.x-s.x,y:a.y-s.y},c={x:l.x-a.x,y:l.y-a.y},d=Math.hypot(u.x,u.y),h=Math.hypot(c.x,c.y);let m;typeof o=="number"?m=o:m=i<o.length?o[i]:0,m=r*Math.cos(Math.PI/n)*Math.min(1,m/r*2);const p={x:u.x/d,y:u.y/d},g={x:c.x/h,y:c.y/h},k={x:a.x-p.x*m,y:a.y-p.y*m},w={x:a.x+g.x*m,y:a.y+g.y*m};i===0?e.moveTo(k.x,k.y):e.lineTo(k.x,k.y),e.arcTo(a.x,a.y,w.x,w.y,m)}}};function AP(e){const t=[],n=e.length,r=Ae;for(let o=0;o<n;o++){let i=e[o];r._isNumber(i)?i=Math.round(i*1e3)/1e3:r._isString(i)||(i=i+""),t.push(i)}return t}var a4=",",IP="(",EP=")",xP="([",TP="])",RP=";",MP="()",LP="=",l4=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],DP=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],PP=100,Ep=null;function c4(){if(Ep!==null)return Ep;try{const e=Ae.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(Ep=!1,!1)}catch{return Ep=!1,!1}}var xp=class{constructor(e){this.canvas=e,gt.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let n=this.traceArr,r=n.length,o="",i,s,a,l;for(i=0;i<r;i++)s=n[i],a=s.method,a?(l=s.args,o+=a,e?o+=MP:Ae._isArray(l[0])?o+=xP+l.join(a4)+TP:(t&&(l=l.map(u=>typeof u=="number"?Math.floor(u):u)),o+=IP+l.join(a4)+EP)):(o+=s.property,e||(o+=LP+s.val)),o+=RP;return o}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,n;t.push(e),n=t.length,n>=PP&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,n,r,o,i){this._context.arc(e,t,n,r,o,i)}arcTo(e,t,n,r,o){this._context.arcTo(e,t,n,r,o)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,n,r,o,i){this._context.bezierCurveTo(e,t,n,r,o,i)}clearRect(e,t,n,r){this._context.clearRect(e,t,n,r)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const n=arguments;if(n.length===2)return this._context.createImageData(e,t);if(n.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,n,r){return this._context.createLinearGradient(e,t,n,r)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,n,r,o,i){return this._context.createRadialGradient(e,t,n,r,o,i)}drawImage(e,t,n,r,o,i,s,a,l){const u=arguments,c=this._context;u.length===3?c.drawImage(e,t,n):u.length===5?c.drawImage(e,t,n,r,o):u.length===9&&c.drawImage(e,t,n,r,o,i,s,a,l)}ellipse(e,t,n,r,o,i,s,a){this._context.ellipse(e,t,n,r,o,i,s,a)}isPointInPath(e,t,n,r){return n?this._context.isPointInPath(n,e,t,r):this._context.isPointInPath(e,t,r)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,n,r){this._context.fillRect(e,t,n,r)}strokeRect(e,t,n,r){this._context.strokeRect(e,t,n,r)}fillText(e,t,n,r){r?this._context.fillText(e,t,n,r):this._context.fillText(e,t,n)}measureText(e){return this._context.measureText(e)}getImageData(e,t,n,r){return this._context.getImageData(e,t,n,r)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,n,r){this._context.rect(e,t,n,r)}roundRect(e,t,n,r,o){this._context.roundRect(e,t,n,r,o)}putImageData(e,t,n){this._context.putImageData(e,t,n)}quadraticCurveTo(e,t,n,r){this._context.quadraticCurveTo(e,t,n,r)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,n,r,o,i){this._context.setTransform(e,t,n,r,o,i)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,n,r){this._context.strokeText(e,t,n,r)}transform(e,t,n,r,o,i){this._context.transform(e,t,n,r,o,i)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=l4.length,n=this.setAttr,r,o;const i=function(s){let a=e[s],l;e[s]=function(){return o=AP(Array.prototype.slice.call(arguments,0)),l=a.apply(e,arguments),e._trace({method:s,args:o}),l}};for(r=0;r<t;r++)i(l4[r]);e.setAttr=function(){n.apply(e,arguments);const s=arguments[0];let a=arguments[1];(s==="shadowOffsetX"||s==="shadowOffsetY"||s==="shadowBlur")&&(a=a/this.canvas.getPixelRatio()),e._trace({property:s,val:a})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}};DP.forEach(function(e){Object.defineProperty(xp.prototype,e,{get(){return this._context[e]},set(t){this._context[e]=t}})});var OP=class extends xp{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),n=e.getFillPriority();if(t&&n==="color"){this._fillColor(e);return}const r=e.getFillPatternImage();if(r&&n==="pattern"){this._fillPattern(e);return}const o=e.getFillLinearGradientColorStops();if(o&&n==="linear-gradient"){this._fillLinearGradient(e);return}const i=e.getFillRadialGradientColorStops();if(i&&n==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):o?this._fillLinearGradient(e):i&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),n=e.getStrokeLinearGradientEndPoint(),r=e.getStrokeLinearGradientColorStops(),o=this.createLinearGradient(t.x,t.y,n.x,n.y);if(r){for(let i=0;i<r.length;i+=2)o.addColorStop(r[i],r[i+1]);this.setAttr("strokeStyle",o)}}_stroke(e){const t=e.dash(),n=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!n){this.save();const r=this.getCanvas().getPixelRatio();this.setTransform(r,0,0,r,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),n||this.restore()}}_applyShadow(e){var t,n,r;const o=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",i=(n=e.getShadowBlur())!==null&&n!==void 0?n:5,s=(r=e.getShadowOffset())!==null&&r!==void 0?r:{x:0,y:0},a=e.getAbsoluteScale(),l=this.canvas.getPixelRatio(),u=a.x*l,c=a.y*l;this.setAttr("shadowColor",o),this.setAttr("shadowBlur",i*Math.min(Math.abs(u),Math.abs(c))),this.setAttr("shadowOffsetX",s.x*u),this.setAttr("shadowOffsetY",s.y*c)}},FP=class extends xp{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const o=this.getCanvas().getPixelRatio();this.setTransform(o,0,0,o,0,0)}this._applyLineCap(e);const n=e.hitStrokeWidth(),r=n==="auto"?e.strokeWidth():n;this.setAttr("lineWidth",r),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}},Tp;function BP(){if(Tp)return Tp;const e=Ae.createCanvasElement(),t=e.getContext("2d");return Tp=(function(){return(gt._global.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)})(),Ae.releaseCanvas(e),Tp}var a0=class{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1,this.pixelRatio=(e||{}).pixelRatio||gt.pixelRatio||BP(),this._canvas=Ae.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(r){return Ae.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}},Xa=class extends a0{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new OP(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}},l0=class extends a0{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new FP(this),this.setSize(e.width,e.height)}};const En={get isDragging(){let e=!1;return En._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(e=!0)}),e},justDragged:!1,get node(){let e;return En._dragElements.forEach(t=>{e=t.node}),e},_dragElements:new Map,_drag(e){const t=[];En._dragElements.forEach((n,r)=>{const{node:o}=n,i=o.getStage();i.setPointersPositions(e),n.pointerId===void 0&&(n.pointerId=Ae._getFirstPointerId(e));const s=i._changedPointerPositions.find(a=>a.id===n.pointerId);if(s){if(n.dragStatus!=="dragging"){const a=o.dragDistance();if(Math.max(Math.abs(s.x-n.startPointerPos.x),Math.abs(s.y-n.startPointerPos.y))<a||(o.startDrag({evt:e}),!o.isDragging()))return}o._setDragPosition(e,n),t.push(o)}}),t.forEach(n=>{n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:e},!0)})},_endDragBefore(e){const t=[];En._dragElements.forEach(n=>{const{node:r}=n,o=r.getStage();if(e&&o.setPointersPositions(e),!o._changedPointerPositions.find(s=>s.id===n.pointerId))return;(n.dragStatus==="dragging"||n.dragStatus==="stopped")&&(En.justDragged=!0,gt._mouseListenClick=!1,gt._touchListenClick=!1,gt._pointerListenClick=!1,n.dragStatus="stopped");const i=n.node.getLayer()||n.node instanceof gt.Stage&&n.node;i&&t.indexOf(i)===-1&&t.push(i)}),t.forEach(n=>{n.draw()})},_endDragAfter(e){En._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:e},!0),t.dragStatus!=="dragging"&&En._dragElements.delete(n)})}};gt.isBrowser&&(window.addEventListener("mouseup",En._endDragBefore,!0),window.addEventListener("touchend",En._endDragBefore,!0),window.addEventListener("touchcancel",En._endDragBefore,!0),window.addEventListener("mousemove",En._drag),window.addEventListener("touchmove",En._drag),window.addEventListener("mouseup",En._endDragAfter,!1),window.addEventListener("touchend",En._endDragAfter,!1),window.addEventListener("touchcancel",En._endDragAfter,!1));function Qa(e){return Ae._isString(e)?'"'+e+'"':Object.prototype.toString.call(e)==="[object Number]"||Ae._isBoolean(e)?e:Object.prototype.toString.call(e)}function u4(e){return e>255?255:e<0?0:Math.round(e)}function dt(){if(gt.isUnminified)return function(e,t){return Ae._isNumber(e)||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),e}}function Rp(e){if(gt.isUnminified)return function(t,n){let r=Ae._isNumber(t),o=Ae._isArray(t)&&t.length==e;return!r&&!o&&Ae.warn(Qa(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array<number>('+e+")"),t}}function c0(){if(gt.isUnminified)return function(e,t){return Ae._isNumber(e)||e==="auto"||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),e}}function Kl(){if(gt.isUnminified)return function(e,t){return Ae._isString(e)||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),e}}function d4(){if(gt.isUnminified)return function(e,t){const n=Ae._isString(e),r=Object.prototype.toString.call(e)==="[object CanvasGradient]"||e&&e.addColorStop;return n||r||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),e}}function NP(){if(gt.isUnminified)return function(e,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&e instanceof n||(Ae._isArray(e)?e.forEach(function(r){Ae._isNumber(r)||Ae.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),e}}function Vi(){if(gt.isUnminified)return function(e,t){return e===!0||e===!1||Ae.warn(Qa(e)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),e}}function zP(e){if(gt.isUnminified)return function(t,n){return t==null||Ae.isObject(t)||Ae.warn(Qa(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+e),t}}var af="get",lf="set";const ce={addGetterSetter(e,t,n,r,o){ce.addGetter(e,t,n),ce.addSetter(e,t,r,o),ce.addOverloadedGetterSetter(e,t)},addGetter(e,t,n){const r=af+Ae._capitalize(t);e.prototype[r]=e.prototype[r]||function(){const o=this.attrs[t];return o===void 0?n:o}},addSetter(e,t,n,r){const o=lf+Ae._capitalize(t);e.prototype[o]||ce.overWriteSetter(e,t,n,r)},overWriteSetter(e,t,n,r){const o=lf+Ae._capitalize(t);e.prototype[o]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(e,t,n,r,o){const i=n.length,s=Ae._capitalize,a=af+s(t),l=lf+s(t);e.prototype[a]=function(){const c={};for(let d=0;d<i;d++){const h=n[d];c[h]=this.getAttr(t+s(h))}return c};const u=zP(n);e.prototype[l]=function(c){const d=this.attrs[t];r&&(c=r.call(this,c,t)),u&&u.call(this,c,t);for(const h in c)c.hasOwnProperty(h)&&this._setAttr(t+s(h),c[h]);return c||n.forEach(h=>{this._setAttr(t+s(h),void 0)}),this._fireChangeEvent(t,d,c),o&&o.call(this),this},ce.addOverloadedGetterSetter(e,t)},addOverloadedGetterSetter(e,t){const n=Ae._capitalize(t),r=lf+n,o=af+n;e.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[o]()}},addDeprecatedGetterSetter(e,t,n,r){Ae.error("Adding deprecated "+t);const o=af+Ae._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";e.prototype[o]=function(){Ae.error(i);const s=this.attrs[t];return s===void 0?n:s},ce.addSetter(e,t,r,function(){Ae.error(i)}),ce.addOverloadedGetterSetter(e,t)},backCompat(e,t){Ae.each(t,function(n,r){const o=e.prototype[r],i=af+Ae._capitalize(n),s=lf+Ae._capitalize(n);function a(){o.apply(this,arguments),Ae.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}e.prototype[n]=a,e.prototype[i]=a,e.prototype[s]=a})},afterSetFilter(){this._filterUpToDate=!1}};function HP(e){const t=/(\w+)\(([^)]+)\)/g;let n;for(;(n=t.exec(e))!==null;){const[,r,o]=n;switch(r){case"blur":{const i=parseFloat(o.replace("px",""));return function(s){this.blurRadius(i*.5);const a=gt.Filters;a&&a.Blur&&a.Blur.call(this,s)}}case"brightness":{const i=o.includes("%")?parseFloat(o)/100:parseFloat(o);return function(s){this.brightness(i);const a=gt.Filters;a&&a.Brightness&&a.Brightness.call(this,s)}}case"contrast":{const i=parseFloat(o);return function(s){const a=100*(Math.sqrt(i)-1);this.contrast(a);const l=gt.Filters;l&&l.Contrast&&l.Contrast.call(this,s)}}case"grayscale":return function(i){const s=gt.Filters;s&&s.Grayscale&&s.Grayscale.call(this,i)};case"sepia":return function(i){const s=gt.Filters;s&&s.Sepia&&s.Sepia.call(this,i)};case"invert":return function(i){const s=gt.Filters;s&&s.Invert&&s.Invert.call(this,i)};default:Ae.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}var Mp="absoluteOpacity",f4="allEventListeners",fa="absoluteTransform",h4="absoluteScale",ql="canvas",UP="Change",VP="children",jP="konva",u0="listening",GP="mouseenter",WP="mouseleave",KP="pointerenter",qP="pointerleave",YP="touchenter",XP="touchleave",p4="set",m4="Shape",Lp=" ",g4="stage",Za="transform",QP="Stage",d0="visible",ZP=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Lp),JP=1,yt=class Uf{constructor(t){this._id=JP++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===Za||t===fa)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,n){let r=this._cache.get(t);return(r===void 0||(t===Za||t===fa)&&r.dirty===!0)&&(r=n.call(this),this._cache.set(t,r)),r}_calculate(t,n,r){if(!this._attachedDepsListeners.get(t)){const o=n.map(i=>i+"Change.konva").join(Lp);this.on(o,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(ql)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===fa&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(ql)){const{scene:t,filter:n,hit:r}=this._cache.get(ql);Ae.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(ql)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let o=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),s=n.pixelRatio,a=n.x===void 0?Math.floor(r.x):n.x,l=n.y===void 0?Math.floor(r.y):n.y,u=n.offset||0,c=n.drawBorder||!1,d=n.hitCanvasPixelRatio||1;if(!o||!i){Ae.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const h=Math.abs(Math.round(r.x)-a)>.5?1:0,m=Math.abs(Math.round(r.y)-l)>.5?1:0;o+=u*2+h,i+=u*2+m,a-=u,l-=u;const p=new Xa({pixelRatio:s,width:o,height:i}),g=new Xa({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),k=new l0({pixelRatio:d,width:o,height:i}),w=p.getContext(),S=k.getContext(),y=new Xa({width:p.width/p.pixelRatio+Math.abs(a),height:p.height/p.pixelRatio+Math.abs(l),pixelRatio:p.pixelRatio}),C=y.getContext();return k.isCache=!0,p.isCache=!0,this._cache.delete(ql),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(p.getContext()._context.imageSmoothingEnabled=!1,g.getContext()._context.imageSmoothingEnabled=!1),w.save(),S.save(),C.save(),w.translate(-a,-l),S.translate(-a,-l),C.translate(-a,-l),y.x=a,y.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Mp),this._clearSelfAndDescendantCache(h4),this.drawScene(p,this,y),this.drawHit(k,this),this._isUnderCache=!1,w.restore(),S.restore(),c&&(w.save(),w.beginPath(),w.rect(0,0,o,i),w.closePath(),w.setAttr("strokeStyle","red"),w.setAttr("lineWidth",5),w.stroke(),w.restore()),Ae.releaseCanvas(y._canvas),this._cache.set(ql,{scene:p,filter:g,hit:k,x:a,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(ql)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let o=1/0,i=1/0,s=-1/0,a=-1/0;const l=this.getAbsoluteTransform(n);return r.forEach(function(u){const c=l.point(u);o===void 0&&(o=s=c.x,i=a=c.y),o=Math.min(o,c.x),i=Math.min(i,c.y),s=Math.max(s,c.x),a=Math.max(a,c.y)}),{x:o,y:i,width:s-o,height:a-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),o=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/o,r.height/o),t.restore()}_drawCachedHitCanvas(t){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),n=this._getCanvasCache(),r=n.scene,o=n.filter,i=o.getContext(),s,a,l,u;if(!t||t.length===0)return r;if(this._filterUpToDate)return o;let c=!0;for(let h=0;h<t.length;h++)if(typeof t[h]=="string"&&c4(),typeof t[h]!="string"||!c4()){c=!1;break}const d=r.pixelRatio;if(o.setSize(r.width/r.pixelRatio,r.height/r.pixelRatio),c){const h=t.join(" ");return i.save(),i.setAttr("filter",h),i.drawImage(r._canvas,0,0,r.getWidth()/d,r.getHeight()/d),i.restore(),this._filterUpToDate=!0,o}try{for(s=t.length,i.clear(),i.drawImage(r._canvas,0,0,r.getWidth()/d,r.getHeight()/d),a=i.getImageData(0,0,o.getWidth(),o.getHeight()),l=0;l<s;l++)u=t[l],typeof u=="string"&&(u=HP(u)),u.call(this,a),i.putImageData(a,0,0)}catch(h){Ae.error("Unable to apply filter. "+h.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,o}on(...t){const n=t[0],r=t[1];if(t[2],this._cache&&this._cache.delete(f4),t.length===3)return this._delegate.apply(this,t);const o=n.split(Lp);for(let i=0;i<o.length;i++){const s=o[i].split("."),a=s[0],l=s[1]||"";this.eventListeners[a]||(this.eventListeners[a]=[]),this.eventListeners[a].push({name:l,handler:r})}return this}off(t,n){let r=(t||"").split(Lp),o=r.length,i,s,a,l,u,c;if(this._cache&&this._cache.delete(f4),!t)for(s in this.eventListeners)this._off(s);for(i=0;i<o;i++)if(a=r[i],l=a.split("."),u=l[0],c=l[1],u)this.eventListeners[u]&&this._off(u,c,n);else for(s in this.eventListeners)this._off(s,c,n);return this}dispatchEvent(t){const n={target:this,type:t.type,evt:t};return this.fire(t.type,n),this}addEventListener(t,n){return this.on(t,function(r){n.call(this,r.evt)}),this}removeEventListener(t){return this.off(t),this}_delegate(t,n,r){const o=this;return this.on(t,function(i){const s=i.target.findAncestors(n,!0,o);for(let a=0;a<s.length;a++)i=Ae.cloneObject(i),i.currentTarget=s[a],r.call(s[a],i)}),this}remove(){return this.isDragging()&&this.stopDrag(),En._dragElements.delete(this._id),En._dragElements.forEach((t,n)=>{this.isAncestorOf(t.node)&&En._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(fa),this._clearSelfAndDescendantCache(Mp),this._clearSelfAndDescendantCache(h4),this._clearSelfAndDescendantCache(g4),this._clearSelfAndDescendantCache(d0),this._clearSelfAndDescendantCache(u0)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+Ae._capitalize(t);return Ae._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==VP&&(r=p4+Ae._capitalize(n),Ae._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(u0,this._isListening)}_isListening(t){if(!this.listening())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isListening(t):!0}isVisible(){return this._getCache(d0,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isVisible(t):!0}shouldDrawHit(t,n=!1){if(t)return this._isVisible(t)&&this._isListening(t);const r=this.getLayer();let o=!1;En._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===r)&&(o=!0)});const i=!n&&!gt.hitOnDragEnabled&&(o||gt.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),n=this,r=0,o,i,s,a;function l(c){for(o=[],i=c.length,s=0;s<i;s++)a=c[s],r++,a.nodeType!==m4&&(o=o.concat(a.getChildren().slice())),a._id===n._id&&(s=i);o.length>0&&o[0].getDepth()<=t&&l(o)}const u=this.getStage();return n.nodeType!==QP&&u&&l(u.getChildren()),r}getDepth(){let t=0,n=this.parent;for(;n;)t++,n=n.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(Za),this._clearSelfAndDescendantCache(fa)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);const o=this.getAbsoluteTransform(t).getMatrix(),i=new Ui,s=this.offset();return i.m=o.slice(),i.translate(s.x,s.y),i.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...o}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(Za);const i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(o),this.setPosition({x:t.x,y:t.y}),this._clearCache(Za),this._clearSelfAndDescendantCache(fa),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let n=t.x,r=t.y,o=this.x(),i=this.y();return n!==void 0&&(o+=n),r!==void 0&&(i+=r),this.setPosition({x:o,y:i}),this}_eachAncestorReverse(t,n){let r=[],o=this.getParent(),i,s;if(!(n&&n._id===this._id)){for(r.unshift(this);o&&(!n||o._id!==n._id);)r.unshift(o),o=o.parent;for(i=r.length,s=0;s<i;s++)t(r[s])}}rotate(t){return this.rotation(this.rotation()+t),this}moveToTop(){if(!this.parent)return Ae.warn("Node has no parent. moveToTop function is ignored."),!1;const t=this.index;return t<this.parent.getChildren().length-1?(this.parent.children.splice(t,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return Ae.warn("Node has no parent. moveUp function is ignored."),!1;const t=this.index;return t<this.parent.getChildren().length-1?(this.parent.children.splice(t,1),this.parent.children.splice(t+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return Ae.warn("Node has no parent. moveDown function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return Ae.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return Ae.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Ae.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Mp,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),n,r,o,i,s;const a={attrs:{},className:this.getClassName()};for(n in t)r=t[n],s=Ae.isObject(r)&&!Ae._isPlainObject(r)&&!Ae._isArray(r),!s&&(o=typeof this[n]=="function"&&this[n],delete t[n],i=o?o.call(this):null,t[n]=r,i!==r&&(a.attrs[n]=r));return Ae._prepareToStringify(a)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const o=[];n&&this._isMatch(t)&&o.push(this);let i=this.parent;for(;i;){if(i===r)return o;i._isMatch(t)&&o.push(i),i=i.parent}return o}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,o,i;for(o=0;o<r;o++)if(i=n[o],Ae.isValidSelector(i)||(Ae.warn('Selector "'+i+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),Ae.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),Ae.warn("Konva is awesome, right?")),i.charAt(0)==="#"){if(this.id()===i.slice(1))return!0}else if(i.charAt(0)==="."){if(this.hasName(i.slice(1)))return!0}else if(this.className===i||this.nodeType===i)return!0;return!1}getLayer(){const t=this.getParent();return t?t.getLayer():null}getStage(){return this._getCache(g4,this._getStage)}_getStage(){const t=this.getParent();return t?t.getStage():null}fire(t,n={},r){return n.target=n.target||this,r?this._fireAndBubble(t,n):this._fire(t,n),this}getAbsoluteTransform(t){return t?this._getAbsoluteTransform(t):this._getCache(fa,this._getAbsoluteTransform)}_getAbsoluteTransform(t){let n;if(t)return n=new Ui,this._eachAncestorReverse(function(r){const o=r.transformsEnabled();o==="all"?n.multiply(r.getTransform()):o==="position"&&n.translate(r.x()-r.offsetX(),r.y()-r.offsetY())},t),n;{n=this._cache.get(fa)||new Ui,this.parent?this.parent.getAbsoluteTransform().copyInto(n):n.reset();const r=this.transformsEnabled();if(r==="all")n.multiply(this.getTransform());else if(r==="position"){const o=this.attrs.x||0,i=this.attrs.y||0,s=this.attrs.offsetX||0,a=this.attrs.offsetY||0;n.translate(o-s,i-a)}return n.dirty=!1,n}}getAbsoluteScale(t){let n=this;for(;n;)n._isUnderCache&&(t=n),n=n.getParent();const r=this.getAbsoluteTransform(t).decompose();return{x:r.scaleX,y:r.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(Za,this._getTransform)}_getTransform(){var t,n;const r=this._cache.get(Za)||new Ui;r.reset();const o=this.x(),i=this.y(),s=gt.getAngle(this.rotation()),a=(t=this.attrs.scaleX)!==null&&t!==void 0?t:1,l=(n=this.attrs.scaleY)!==null&&n!==void 0?n:1,u=this.attrs.skewX||0,c=this.attrs.skewY||0,d=this.attrs.offsetX||0,h=this.attrs.offsetY||0;return(o!==0||i!==0)&&r.translate(o,i),s!==0&&r.rotate(s),(u!==0||c!==0)&&r.skew(u,c),(a!==1||l!==1)&&r.scale(a,l),(d!==0||h!==0)&&r.translate(-1*d,-1*h),r.dirty=!1,r}clone(t){let n=Ae.cloneObject(this.attrs),r,o,i,s,a;for(r in t)n[r]=t[r];const l=new this.constructor(n);for(r in this.eventListeners)for(o=this.eventListeners[r],i=o.length,s=0;s<i;s++)a=o[s],a.name.indexOf(jP)<0&&(l.eventListeners[r]||(l.eventListeners[r]=[]),l.eventListeners[r].push(a));return l}_toKonvaCanvas(t){t=t||{};const n=this.getClientRect(),r=this.getStage(),o=t.x!==void 0?t.x:Math.floor(n.x),i=t.y!==void 0?t.y:Math.floor(n.y),s=t.pixelRatio||1,a=new Xa({width:t.width||Math.ceil(n.width)||(r?r.width():0),height:t.height||Math.ceil(n.height)||(r?r.height():0),pixelRatio:s}),l=a.getContext(),u=new Xa({width:a.width/a.pixelRatio+Math.abs(o),height:a.height/a.pixelRatio+Math.abs(i),pixelRatio:a.pixelRatio});return t.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(o||i)&&l.translate(-1*o,-1*i),this.drawScene(a,void 0,u),l.restore(),a}toCanvas(t){return this._toKonvaCanvas(t)._canvas}toDataURL(t){t=t||{};const n=t.mimeType||null,r=t.quality||null,o=this._toKonvaCanvas(t).toDataURL(n,r);return t.callback&&t.callback(o),o}toImage(t){return new Promise((n,r)=>{try{const o=t?.callback;o&&delete t.callback,Ae._urlToImage(this.toDataURL(t),function(i){n(i),o?.(i)})}catch(o){r(o)}})}toBlob(t){return new Promise((n,r)=>{try{const o=t?.callback;o&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),o?.(i)},t?.mimeType,t?.quality)}catch(o){r(o)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():gt.dragDistance}_off(t,n,r){let o=this.eventListeners[t],i,s,a;for(i=0;i<o.length;i++)if(s=o[i].name,a=o[i].handler,(s!=="konva"||n==="konva")&&(!n||s===n)&&(!r||r===a)){if(o.splice(i,1),o.length===0){delete this.eventListeners[t];break}i--}}_fireChangeEvent(t,n,r){this._fire(t+UP,{oldVal:n,newVal:r})}addName(t){if(!this.hasName(t)){const n=this.name(),r=n?n+" "+t:t;this.name(r)}return this}hasName(t){if(!t)return!1;const n=this.name();return n?(n||"").split(/\s/g).indexOf(t)!==-1:!1}removeName(t){const n=(this.name()||"").split(/\s/g),r=n.indexOf(t);return r!==-1&&(n.splice(r,1),this.name(n.join(" "))),this}setAttr(t,n){const r=this[p4+Ae._capitalize(t)];return Ae._isFunction(r)?r.call(this,n):this._setAttr(t,n),this}_requestDraw(){if(gt.autoDrawEnabled){const t=this.getLayer()||this.getStage();t?.batchDraw()}}_setAttr(t,n){const r=this.attrs[t];r===n&&!Ae.isObject(n)||(n==null?delete this.attrs[t]:this.attrs[t]=n,this._shouldFireChangeEvents&&this._fireChangeEvent(t,r,n),this._requestDraw())}_setComponentAttr(t,n,r){let o;r!==void 0&&(o=this.attrs[t],o||(this.attrs[t]=this.getAttr(t)),this.attrs[t][n]=r,this._fireChangeEvent(t,o,r))}_fireAndBubble(t,n,r){n&&this.nodeType===m4&&(n.target=this);const o=[GP,WP,KP,qP,YP,XP];if(!(o.indexOf(t)!==-1&&(r&&(this===r||this.isAncestorOf&&this.isAncestorOf(r))||this.nodeType==="Stage"&&!r))){this._fire(t,n);const i=o.indexOf(t)!==-1&&r&&r.isAncestorOf&&r.isAncestorOf(this)&&!r.isAncestorOf(this.parent);(n&&!n.cancelBubble||!n)&&this.parent&&this.parent.isListening()&&!i&&(r&&r.parent?this._fireAndBubble.call(this.parent,t,n,r):this._fireAndBubble.call(this.parent,t,n))}}_getProtoListeners(t){var n,r;const{nodeType:o}=this,i=Uf.protoListenerMap.get(o)||{};let s=i?.[t];if(s===void 0){s=[];let a=Object.getPrototypeOf(this);for(;a;){const l=(r=(n=a.eventListeners)===null||n===void 0?void 0:n[t])!==null&&r!==void 0?r:[];s.push(...l),a=Object.getPrototypeOf(a)}i[t]=s,Uf.protoListenerMap.set(o,i)}return s}_fire(t,n){n=n||{},n.currentTarget=this,n.type=t;const r=this._getProtoListeners(t);if(r){const i=r.slice();for(let s=0;s<i.length;s++)i[s].handler.call(this,n)}const o=this.eventListeners[t];if(o){const i=o.slice(),s=i.length;for(let l=0;l<i.length;l++)i[l].handler.call(this,n);const a=this.eventListeners[t];if(a)for(let l=s;l<a.length;l++)a[l].handler.call(this,n)}}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(t){const n=t?t.pointerId:void 0,r=this.getStage(),o=this.getAbsolutePosition();if(!r)return;const i=r._getPointerById(n)||r._changedPointerPositions[0]||o;En._dragElements.set(this._id,{node:this,startPointerPos:i,offset:{x:i.x-o.x,y:i.y-o.y},dragStatus:"ready",pointerId:n,startEvent:t})}startDrag(t,n=!0){En._dragElements.has(this._id)||this._createDragElement(t);const r=En._dragElements.get(this._id);r.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:r.startEvent&&r.startEvent.evt||t&&t.evt},n)}_setDragPosition(t,n){const r=this.getStage()._getPointerById(n.pointerId);if(!r)return;let o={x:r.x-n.offset.x,y:r.y-n.offset.y};const i=this.dragBoundFunc();if(i!==void 0){const s=i.call(this,o,t);s?o=s:Ae.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==o.x||this._lastPos.y!==o.y)&&(this.setAbsolutePosition(o),this._requestDraw()),this._lastPos=o}stopDrag(t){const n=En._dragElements.get(this._id);n&&(n.dragStatus="stopped"),En._endDragBefore(t),En._endDragAfter(t)}setDraggable(t){this._setAttr("draggable",t),this._dragChange()}isDragging(){const t=En._dragElements.get(this._id);return t?t.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(t){if(!(t.evt.button===void 0||gt.dragButtons.indexOf(t.evt.button)>=0)||this.isDragging())return;let n=!1;En._dragElements.forEach(r=>{this.isAncestorOf(r.node)&&(n=!0)}),n||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=En._dragElements.get(this._id),n=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";n?this.stopDrag():r&&En._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return Ae.haveIntersection(r,this.getClientRect())}static create(t,n){return Ae._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=Uf.prototype.getClassName.call(t),o=t.children,i,s,a;n&&(t.attrs.container=n),gt[r]||(Ae.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const l=gt[r];if(i=new l(t.attrs),o)for(s=o.length,a=0;a<s;a++)i.add(Uf._createNode(o[a]));return i}};yt.protoListenerMap=new Map,yt.prototype.nodeType="Node",yt.prototype._attrsAffectingSize=[],yt.prototype.eventListeners={},yt.prototype.on(ZP,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(Za),this._clearSelfAndDescendantCache(fa)}),yt.prototype.on("visibleChange.konva",function(){this._clearSelfAndDescendantCache(d0)}),yt.prototype.on("listeningChange.konva",function(){this._clearSelfAndDescendantCache(u0)}),yt.prototype.on("opacityChange.konva",function(){this._clearSelfAndDescendantCache(Mp)});var Qn=ce.addGetterSetter;Qn(yt,"zIndex"),Qn(yt,"absolutePosition"),Qn(yt,"position"),Qn(yt,"x",0,dt()),Qn(yt,"y",0,dt()),Qn(yt,"globalCompositeOperation","source-over",Kl()),Qn(yt,"opacity",1,dt()),Qn(yt,"name","",Kl()),Qn(yt,"id","",Kl()),Qn(yt,"rotation",0,dt()),ce.addComponentsGetterSetter(yt,"scale",["x","y"]),Qn(yt,"scaleX",1,dt()),Qn(yt,"scaleY",1,dt()),ce.addComponentsGetterSetter(yt,"skew",["x","y"]),Qn(yt,"skewX",0,dt()),Qn(yt,"skewY",0,dt()),ce.addComponentsGetterSetter(yt,"offset",["x","y"]),Qn(yt,"offsetX",0,dt()),Qn(yt,"offsetY",0,dt()),Qn(yt,"dragDistance",void 0,dt()),Qn(yt,"width",0,dt()),Qn(yt,"height",0,dt()),Qn(yt,"listening",!0,Vi()),Qn(yt,"preventDefault",!0,Vi()),Qn(yt,"filters",void 0,function(e){return this._filterUpToDate=!1,e}),Qn(yt,"visible",!0,Vi()),Qn(yt,"transformsEnabled","all",Kl()),Qn(yt,"size"),Qn(yt,"dragBoundFunc"),Qn(yt,"draggable",!1,Vi()),ce.backCompat(yt,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});var fi=class extends yt{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let n=0;n<e.length;n++)this.add(e[n]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const n=[];return this._descendants(r=>{const o=r._isMatch(e);return o&&n.push(r),!!(o&&t)}),n}_descendants(e){let t=!1;const n=this.getChildren();for(const r of n){if(t=e(r),t)return!0;if(r.hasChildren()&&(t=r._descendants(e),t))return!0}return!1}toObject(){const e=yt.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=yt.prototype.clone.call(this,e);return this.getChildren().forEach(function(n){t.add(n.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(n=>{n.isVisible()&&n.intersects(e)&&t.push(n)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(n){n._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,n){t.index=n}),this._requestDraw()}drawScene(e,t,n){const r=this.getLayer(),o=e||r&&r.getCanvas(),i=o&&o.getContext(),s=this._getCanvasCache(),a=s&&s.scene,l=o&&o.isCache;if(!this.isVisible()&&!l)return this;if(a){i.save();const u=this.getAbsoluteTransform(t).getMatrix();i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(i),i.restore()}else this._drawChildren("drawScene",o,t,n);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const n=this.getLayer(),r=e||n&&n.hitCanvas,o=r&&r.getContext(),i=this._getCanvasCache();if(i&&i.hit){o.save();const s=this.getAbsoluteTransform(t).getMatrix();o.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._drawCachedHitCanvas(o),o.restore()}else this._drawChildren("drawHit",r,t);return this}_drawChildren(e,t,n,r){var o;const i=t&&t.getContext(),s=this.clipWidth(),a=this.clipHeight(),l=this.clipFunc(),u=typeof s=="number"&&typeof a=="number"||l,c=n===this;if(u){i.save();const h=this.getAbsoluteTransform(n);let m=h.getMatrix();i.transform(m[0],m[1],m[2],m[3],m[4],m[5]),i.beginPath();let p;if(l)p=l.call(this,i,this);else{const g=this.clipX(),k=this.clipY();i.rect(g||0,k||0,s,a)}i.clip.apply(i,p),m=h.copy().invert().getMatrix(),i.transform(m[0],m[1],m[2],m[3],m[4],m[5])}const d=!c&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";d&&(i.save(),i._applyGlobalCompositeOperation(this)),(o=this.children)===null||o===void 0||o.forEach(function(h){h[e](t,n,r)}),d&&i.restore(),u&&i.restore()}getClientRect(e={}){var t;const n=e.skipTransform,r=e.relativeTo;let o,i,s,a,l={x:1/0,y:1/0,width:0,height:0};const u=this;(t=this.children)===null||t===void 0||t.forEach(function(h){if(!h.visible())return;const m=h.getClientRect({relativeTo:u,skipShadow:e.skipShadow,skipStroke:e.skipStroke});m.width===0&&m.height===0||(o===void 0?(o=m.x,i=m.y,s=m.x+m.width,a=m.y+m.height):(o=Math.min(o,m.x),i=Math.min(i,m.y),s=Math.max(s,m.x+m.width),a=Math.max(a,m.y+m.height)))});const c=this.find("Shape");let d=!1;for(let h=0;h<c.length;h++)if(c[h]._isVisible(this)){d=!0;break}return d&&o!==void 0?l={x:o,y:i,width:s-o,height:a-i}:l={x:0,y:0,width:0,height:0},n?l:this._transformedRect(l,r)}};ce.addComponentsGetterSetter(fi,"clip",["x","y","width","height"]),ce.addGetterSetter(fi,"clipX",void 0,dt()),ce.addGetterSetter(fi,"clipY",void 0,dt()),ce.addGetterSetter(fi,"clipWidth",void 0,dt()),ce.addGetterSetter(fi,"clipHeight",void 0,dt()),ce.addGetterSetter(fi,"clipFunc");var cf=new Map,v4=gt._global.PointerEvent!==void 0;function f0(e){return cf.get(e)}function h0(e){return{evt:e,pointerId:e.pointerId}}function y4(e,t){return cf.get(e)===t}function b4(e,t){uf(e),t.getStage()&&(cf.set(e,t),v4&&t._fire("gotpointercapture",h0(new PointerEvent("gotpointercapture"))))}function uf(e,t){const n=cf.get(e);if(!n)return;const r=n.getStage();r&&r.content,cf.delete(e),v4&&n._fire("lostpointercapture",h0(new PointerEvent("lostpointercapture")))}var $P="Stage",eO="string",w4="px",tO="mouseout",C4="mouseleave",_4="mouseover",S4="mouseenter",k4="mousemove",A4="mousedown",I4="mouseup",df="pointermove",ff="pointerdown",su="pointerup",hf="pointercancel",nO="lostpointercapture",Dp="pointerout",pf="pointerleave",Pp="pointerover",Op="pointerenter",p0="contextmenu",E4="touchstart",x4="touchend",T4="touchmove",R4="touchcancel",m0="wheel",rO=5,oO=[[S4,"_pointerenter"],[A4,"_pointerdown"],[k4,"_pointermove"],[I4,"_pointerup"],[C4,"_pointerleave"],[E4,"_pointerdown"],[T4,"_pointermove"],[x4,"_pointerup"],[R4,"_pointercancel"],[_4,"_pointerover"],[m0,"_wheel"],[p0,"_contextmenu"],[ff,"_pointerdown"],[df,"_pointermove"],[su,"_pointerup"],[hf,"_pointercancel"],[pf,"_pointerleave"],[nO,"_lostpointercapture"]],g0={mouse:{[Dp]:tO,[pf]:C4,[Pp]:_4,[Op]:S4,[df]:k4,[ff]:A4,[su]:I4,[hf]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Dp]:"touchout",[pf]:"touchleave",[Pp]:"touchover",[Op]:"touchenter",[df]:T4,[ff]:E4,[su]:x4,[hf]:R4,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Dp]:Dp,[pf]:pf,[Pp]:Pp,[Op]:Op,[df]:df,[ff]:ff,[su]:su,[hf]:hf,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},mf=e=>e.indexOf("pointer")>=0?"pointer":e.indexOf("touch")>=0?"touch":"mouse",au=e=>{const t=mf(e);if(t==="pointer")return gt.pointerEventsEnabled&&g0.pointer;if(t==="touch")return g0.touch;if(t==="mouse")return g0.mouse};function M4(e={}){return(e.clipFunc||e.clipWidth||e.clipHeight)&&Ae.warn("Stage does not support clipping. Please use clip for Layers or Groups."),e}var iO="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);";const gf=[];var Fp=class extends fi{constructor(e){super(M4(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),gf.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{M4(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",n=e.getType()==="FastLayer";t||n||Ae.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===eO){let t;if(e.charAt(0)==="."){const n=e.slice(1);e=document.getElementsByClassName(n)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let n=0;n<t;n++)e[n].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),fi.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&Ae._isInDocument(e)&&this.container().removeChild(e);const t=gf.indexOf(this);return t>-1&&gf.splice(t,1),Ae.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(Ae.warn(iO),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new Xa({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),n=t.getContext()._context,r=this.children;return(e.x||e.y)&&n.translate(-1*e.x,-1*e.y),r.forEach(function(o){if(!o.isVisible())return;const i=o._toKonvaCanvas(e);n.drawImage(i._canvas,e.x,e.y,i.getWidth()/i.getPixelRatio(),i.getHeight()/i.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,n=t.length-1;for(let r=n;r>=0;r--){const o=t[r].getIntersection(e);if(o)return o}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+w4,this.content.style.height=t+w4),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(n=>{n.setSize({width:e,height:t}),n.draw()})}add(e,...t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}super.add(e);const n=this.children.length;return n>rO&&Ae.warn("The stage has "+n+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),gt.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return y4(e,this)}setPointerCapture(e){b4(e,this)}releaseCapture(e){uf(e,this)}getLayers(){return this.children}_bindContentEvents(){gt.isBrowser&&oO.forEach(([e,t])=>{this.content.addEventListener(e,n=>{this[t](n)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=au(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=au(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=au(e.type),n=mf(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(n),o=!(gt.isDragging()||gt.isTransforming())||gt.hitOnDragEnabled;r&&o?(r._fireAndBubble(t.pointerout,{evt:e}),r._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[n+"targetShape"]=null):o&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=au(e.type),n=mf(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(o=>{const i=this.getIntersection(o);if(En.justDragged=!1,gt["_"+n+"ListenClick"]=!0,!i||!i.isListening()){this[n+"ClickStartShape"]=void 0;return}gt.capturePointerEventsEnabled&&i.setPointerCapture(o.id),this[n+"ClickStartShape"]=i,i._fireAndBubble(t.pointerdown,{evt:e,pointerId:o.id}),r=!0;const s=e.type.indexOf("touch")>=0;i.preventDefault()&&e.cancelable&&s&&e.preventDefault()}),r||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=au(e.type),n=mf(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(gt.isDragging()&&En.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(gt.isDragging()||gt.isTransforming())||gt.hitOnDragEnabled))return;const o={};let i=!1;const s=this._getTargetShape(n);this._changedPointerPositions.forEach(a=>{const l=f0(a.id)||this.getIntersection(a),u=a.id,c={evt:e,pointerId:u},d=s!==l;if(d&&s&&(s._fireAndBubble(t.pointerout,{...c},l),s._fireAndBubble(t.pointerleave,{...c},l)),l){if(o[l._id])return;o[l._id]=!0}l&&l.isListening()?(i=!0,d&&(l._fireAndBubble(t.pointerover,{...c},s),l._fireAndBubble(t.pointerenter,{...c},s),this[n+"targetShape"]=l),l._fireAndBubble(t.pointermove,{...c})):s&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:u}),this[n+"targetShape"]=null)}),i||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=au(e.type),n=mf(e.type);if(!t)return;this.setPointersPositions(e);const r=this[n+"ClickStartShape"],o=this[n+"ClickEndShape"],i={};let s=!1;this._changedPointerPositions.forEach(a=>{const l=f0(a.id)||this.getIntersection(a);if(l){if(l.releaseCapture(a.id),i[l._id])return;i[l._id]=!0}const u=a.id,c={evt:e,pointerId:u};let d=!1;gt["_"+n+"InDblClickWindow"]?(d=!0,clearTimeout(this[n+"DblTimeout"])):En.justDragged||(gt["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"])),this[n+"DblTimeout"]=setTimeout(function(){gt["_"+n+"InDblClickWindow"]=!1},gt.dblClickWindow),l&&l.isListening()?(s=!0,this[n+"ClickEndShape"]=l,l._fireAndBubble(t.pointerup,{...c}),gt["_"+n+"ListenClick"]&&r&&r===l&&(l._fireAndBubble(t.pointerclick,{...c}),d&&o&&o===l&&l._fireAndBubble(t.pointerdblclick,{...c}))):(this[n+"ClickEndShape"]=null,s||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),s=!0),gt["_"+n+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:u}),d&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:u}))}),s||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),gt["_"+n+"ListenClick"]=!1,e.cancelable&&n!=="touch"&&n!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(p0,{evt:e}):this._fire(p0,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(m0,{evt:e}):this._fire(m0,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=f0(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(su,h0(e)),uf(e.pointerId)}_lostpointercapture(e){uf(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let n=null,r=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,o=>{this._pointerPositions.push({id:o.identifier,x:(o.clientX-t.left)/t.scaleX,y:(o.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,o=>{this._changedPointerPositions.push({id:o.identifier,x:(o.clientX-t.left)/t.scaleX,y:(o.clientY-t.top)/t.scaleY})})):(n=(e.clientX-t.left)/t.scaleX,r=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:n,y:r},this._pointerPositions=[{x:n,y:r,id:Ae._getFirstPointerId(e)}],this._changedPointerPositions=[{x:n,y:r,id:Ae._getFirstPointerId(e)}])}_setPointerPosition(e){Ae.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new Xa({width:this.width(),height:this.height()}),this.bufferHitCanvas=new l0({pixelRatio:1,width:this.width(),height:this.height()}),!gt.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return Ae.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}};Fp.prototype.nodeType=$P,vr(Fp),ce.addGetterSetter(Fp,"container"),gt.isBrowser&&document.addEventListener("visibilitychange",()=>{gf.forEach(e=>{e.batchDraw()})});var L4="hasShadow",D4="shadowRGBA",P4="patternImage",O4="linearGradient",F4="radialGradient",Bp;function v0(){return Bp||(Bp=Ae.createCanvasElement().getContext("2d"),Bp)}const vf={};function sO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function aO(e){e.stroke()}function lO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function cO(e){e.stroke()}function uO(){this._clearCache(L4)}function dO(){this._clearCache(D4)}function fO(){this._clearCache(P4)}function hO(){this._clearCache(O4)}function pO(){this._clearCache(F4)}var ct=class extends yt{constructor(e){super(e);let t,n=0;for(;t=Ae.getHitColor(),!(t&&!(t in vf));)if(n++,n>=1e4){Ae.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=Ae.getRandomColor();break}this.colorKey=t,vf[t]=this}getContext(){return Ae.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Ae.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(L4,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(P4,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const e=v0().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(e&&e.setTransform){const t=new Ui;t.translate(this.fillPatternX(),this.fillPatternY()),t.rotate(gt.getAngle(this.fillPatternRotation())),t.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),t.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const n=t.getMatrix(),r=typeof DOMMatrix>"u"?{a:n[0],b:n[1],c:n[2],d:n[3],e:n[4],f:n[5]}:new DOMMatrix(n);e.setTransform(r)}return e}}_getLinearGradient(){return this._getCache(O4,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=v0(),n=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),o=t.createLinearGradient(n.x,n.y,r.x,r.y);for(let i=0;i<e.length;i+=2)o.addColorStop(e[i],e[i+1]);return o}}_getRadialGradient(){return this._getCache(F4,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=v0(),n=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),o=t.createRadialGradient(n.x,n.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let i=0;i<e.length;i+=2)o.addColorStop(e[i],e[i+1]);return o}}getShadowRGBA(){return this._getCache(D4,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=Ae.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const n=t.bufferHitCanvas;return n.getContext().clear(),this.drawHit(n,void 0,!0),n.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return yt.prototype.destroy.call(this),delete vf[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0)||t))return!1;const n=e||this.hasFill(),r=this.hasStroke(),o=this.getAbsoluteOpacity()!==1;if(n&&r&&o)return!0;const i=this.hasShadow(),s=this.shadowForStrokeEnabled();return!!(n&&r&&i&&s)}setStrokeHitEnabled(e){Ae.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,n=this.getParent();for(;n;){if(n.isCached()){t=!0;break}n=n.getParent()}const r=e.skipTransform,o=e.relativeTo||t&&this.getStage()||void 0,i=this.getSelfRect(),s=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,a=i.width+s,l=i.height+s,u=!e.skipShadow&&this.hasShadow(),c=u?this.shadowOffsetX():0,d=u?this.shadowOffsetY():0,h=a+Math.abs(c),m=l+Math.abs(d),p=u&&this.shadowBlur()||0,g={width:h+p*2,height:m+p*2,x:-(s/2+p)+Math.min(c,0)+i.x,y:-(s/2+p)+Math.min(d,0)+i.y};return r?g:this._transformedRect(g,o)}drawScene(e,t,n){const r=this.getLayer(),o=(e||r.getCanvas()).getContext(),i=this._getCanvasCache(),s=this.getSceneFunc(),a=this.hasShadow();let l;const u=t===this;if(!this.isVisible()&&!u)return this;if(i){o.save();const c=this.getAbsoluteTransform(t).getMatrix();return o.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedSceneCanvas(o),o.restore(),this}if(!s)return this;if(o.save(),this._useBufferCanvas()){l=this.getStage();const c=n||l.bufferCanvas,d=c.getContext();n?(d.save(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c.width,c.height),d.restore()):d.clear(),d.save(),d._applyLineJoin(this),d._applyMiterLimit(this);const h=this.getAbsoluteTransform(t).getMatrix();d.transform(h[0],h[1],h[2],h[3],h[4],h[5]),s.call(this,d,this),d.restore();const m=c.pixelRatio;a&&o._applyShadow(this),u||(o._applyOpacity(this),o._applyGlobalCompositeOperation(this)),o.drawImage(c._canvas,c.x||0,c.y||0,c.width/m,c.height/m)}else{if(o._applyLineJoin(this),o._applyMiterLimit(this),!u){const c=this.getAbsoluteTransform(t).getMatrix();o.transform(c[0],c[1],c[2],c[3],c[4],c[5]),o._applyOpacity(this),o._applyGlobalCompositeOperation(this)}a&&o._applyShadow(this),s.call(this,o,this)}return o.restore(),this}drawHit(e,t,n=!1){if(!this.shouldDrawHit(t,n))return this;const r=this.getLayer(),o=e||r.hitCanvas,i=o&&o.getContext(),s=this.hitFunc()||this.sceneFunc(),a=this._getCanvasCache(),l=a&&a.hit;if(this.colorKey||Ae.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),l){i.save();const u=this.getAbsoluteTransform(t).getMatrix();return i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedHitCanvas(i),i.restore(),this}if(!s)return this;if(i.save(),i._applyLineJoin(this),i._applyMiterLimit(this),this!==t){const u=this.getAbsoluteTransform(t).getMatrix();i.transform(u[0],u[1],u[2],u[3],u[4],u[5])}return s.call(this,i,this),i.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),n=this._getCachedSceneCanvas(),r=t.hit,o=r.getContext(),i=r.getWidth(),s=r.getHeight();o.clear(),o.drawImage(n._canvas,0,0,i,s);try{const a=o.getImageData(0,0,i,s),l=a.data,u=l.length,c=Ae._hexToRgb(this.colorKey);for(let d=0;d<u;d+=4)l[d+3]>e?(l[d]=c.r,l[d+1]=c.g,l[d+2]=c.b,l[d+3]=255):l[d+3]=0;o.putImageData(a,0,0)}catch(a){Ae.error("Unable to draw hit graph from cached scene canvas. "+a.message)}return this}hasPointerCapture(e){return y4(e,this)}setPointerCapture(e){b4(e,this)}releaseCapture(e){uf(e,this)}};ct.prototype._fillFunc=sO,ct.prototype._strokeFunc=aO,ct.prototype._fillFuncHit=lO,ct.prototype._strokeFuncHit=cO,ct.prototype._centroid=!1,ct.prototype.nodeType="Shape",vr(ct),ct.prototype.eventListeners={},ct.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",uO),ct.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",dO),ct.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",fO),ct.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",hO),ct.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",pO),ce.addGetterSetter(ct,"stroke",void 0,d4()),ce.addGetterSetter(ct,"strokeWidth",2,dt()),ce.addGetterSetter(ct,"fillAfterStrokeEnabled",!1),ce.addGetterSetter(ct,"hitStrokeWidth","auto",c0()),ce.addGetterSetter(ct,"strokeHitEnabled",!0,Vi()),ce.addGetterSetter(ct,"perfectDrawEnabled",!0,Vi()),ce.addGetterSetter(ct,"shadowForStrokeEnabled",!0,Vi()),ce.addGetterSetter(ct,"lineJoin"),ce.addGetterSetter(ct,"lineCap"),ce.addGetterSetter(ct,"miterLimit"),ce.addGetterSetter(ct,"sceneFunc"),ce.addGetterSetter(ct,"hitFunc"),ce.addGetterSetter(ct,"dash"),ce.addGetterSetter(ct,"dashOffset",0,dt()),ce.addGetterSetter(ct,"shadowColor",void 0,Kl()),ce.addGetterSetter(ct,"shadowBlur",0,dt()),ce.addGetterSetter(ct,"shadowOpacity",1,dt()),ce.addComponentsGetterSetter(ct,"shadowOffset",["x","y"]),ce.addGetterSetter(ct,"shadowOffsetX",0,dt()),ce.addGetterSetter(ct,"shadowOffsetY",0,dt()),ce.addGetterSetter(ct,"fillPatternImage"),ce.addGetterSetter(ct,"fill",void 0,d4()),ce.addGetterSetter(ct,"fillPatternX",0,dt()),ce.addGetterSetter(ct,"fillPatternY",0,dt()),ce.addGetterSetter(ct,"fillLinearGradientColorStops"),ce.addGetterSetter(ct,"strokeLinearGradientColorStops"),ce.addGetterSetter(ct,"fillRadialGradientStartRadius",0),ce.addGetterSetter(ct,"fillRadialGradientEndRadius",0),ce.addGetterSetter(ct,"fillRadialGradientColorStops"),ce.addGetterSetter(ct,"fillPatternRepeat","repeat"),ce.addGetterSetter(ct,"fillEnabled",!0),ce.addGetterSetter(ct,"strokeEnabled",!0),ce.addGetterSetter(ct,"shadowEnabled",!0),ce.addGetterSetter(ct,"dashEnabled",!0),ce.addGetterSetter(ct,"strokeScaleEnabled",!0),ce.addGetterSetter(ct,"fillPriority","color"),ce.addComponentsGetterSetter(ct,"fillPatternOffset",["x","y"]),ce.addGetterSetter(ct,"fillPatternOffsetX",0,dt()),ce.addGetterSetter(ct,"fillPatternOffsetY",0,dt()),ce.addComponentsGetterSetter(ct,"fillPatternScale",["x","y"]),ce.addGetterSetter(ct,"fillPatternScaleX",1,dt()),ce.addGetterSetter(ct,"fillPatternScaleY",1,dt()),ce.addComponentsGetterSetter(ct,"fillLinearGradientStartPoint",["x","y"]),ce.addComponentsGetterSetter(ct,"strokeLinearGradientStartPoint",["x","y"]),ce.addGetterSetter(ct,"fillLinearGradientStartPointX",0),ce.addGetterSetter(ct,"strokeLinearGradientStartPointX",0),ce.addGetterSetter(ct,"fillLinearGradientStartPointY",0),ce.addGetterSetter(ct,"strokeLinearGradientStartPointY",0),ce.addComponentsGetterSetter(ct,"fillLinearGradientEndPoint",["x","y"]),ce.addComponentsGetterSetter(ct,"strokeLinearGradientEndPoint",["x","y"]),ce.addGetterSetter(ct,"fillLinearGradientEndPointX",0),ce.addGetterSetter(ct,"strokeLinearGradientEndPointX",0),ce.addGetterSetter(ct,"fillLinearGradientEndPointY",0),ce.addGetterSetter(ct,"strokeLinearGradientEndPointY",0),ce.addComponentsGetterSetter(ct,"fillRadialGradientStartPoint",["x","y"]),ce.addGetterSetter(ct,"fillRadialGradientStartPointX",0),ce.addGetterSetter(ct,"fillRadialGradientStartPointY",0),ce.addComponentsGetterSetter(ct,"fillRadialGradientEndPoint",["x","y"]),ce.addGetterSetter(ct,"fillRadialGradientEndPointX",0),ce.addGetterSetter(ct,"fillRadialGradientEndPointY",0),ce.addGetterSetter(ct,"fillPatternRotation",0),ce.addGetterSetter(ct,"fillRule",void 0,Kl()),ce.backCompat(ct,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var mO="beforeDraw",gO="draw",B4=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],vO=B4.length,Yl=class extends fi{constructor(e){super(e),this.canvas=new Xa,this.hitCanvas=new l0({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){yt.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!yt.prototype.moveUp.call(this))return!1;const e=this.getStage();return!e||!e.content?!1:(e.content.removeChild(this.getNativeCanvasElement()),this.index<e.children.length-1?e.content.insertBefore(this.getNativeCanvasElement(),e.children[this.index+1].getCanvas()._canvas):e.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(yt.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(yt.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return yt.prototype.remove.call(this),e&&e.parentNode&&Ae._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&Ae.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),yt.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){Ae.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){Ae.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,Ae.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,n=!1;for(;;){for(let r=0;r<vO;r++){const o=B4[r],i=this._getIntersection({x:e.x+o.x*t,y:e.y+o.y*t}),s=i.shape;if(s)return s;if(n=!!i.antialiased,!i.antialiased)break}if(n)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,n=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,r=n[3];if(r===255){const o=vf[Ae.getHitColorKey(n[0],n[1],n[2])];return o?{shape:o}:{antialiased:!0}}else if(r>0)return{antialiased:!0};return{}}drawScene(e,t,n){const r=this.getLayer(),o=e||r&&r.getCanvas();return this._fire(mO,{node:this}),this.clearBeforeDraw()&&o.getContext().clear(),fi.prototype.drawScene.call(this,o,t,n),this._fire(gO,{node:this}),this}drawHit(e,t){const n=this.getLayer(),r=e||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),fi.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){Ae.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return Ae.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return Ae.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};Yl.prototype.nodeType="Layer",vr(Yl),ce.addGetterSetter(Yl,"imageSmoothingEnabled",!0),ce.addGetterSetter(Yl,"clearBeforeDraw",!0),ce.addGetterSetter(Yl,"hitGraphEnabled",!0,Vi());var y0=class extends Yl{constructor(e){super(e),this.listening(!1),Ae.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}};y0.prototype.nodeType="FastLayer",vr(y0);var lu=class extends fi{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&Ae.throw("You may only add groups and shapes to groups.")}};lu.prototype.nodeType="Group",vr(lu);var b0=(function(){return Wl.performance&&Wl.performance.now?function(){return Wl.performance.now()}:function(){return new Date().getTime()}})(),cu=class ju{constructor(t,n){this.id=ju.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:b0(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){let n=[];return t&&(n=Array.isArray(t)?t:[t]),this.layers=n,this}getLayers(){return this.layers}addLayer(t){const n=this.layers,r=n.length;for(let o=0;o<r;o++)if(n[o]._id===t._id)return!1;return this.layers.push(t),!0}isRunning(){const t=ju.animations,n=t.length;for(let r=0;r<n;r++)if(t[r].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=b0(),ju._addAnimation(this),this}stop(){return ju._removeAnimation(this),this}_updateFrameObject(t){this.frame.timeDiff=t-this.frame.lastTime,this.frame.lastTime=t,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(t){this.animations.push(t),this._handleAnimation()}static _removeAnimation(t){const n=t.id,r=this.animations,o=r.length;for(let i=0;i<o;i++)if(r[i].id===n){this.animations.splice(i,1);break}}static _runFrames(){const t={},n=this.animations;for(let r=0;r<n.length;r++){const o=n[r],i=o.layers,s=o.func;o._updateFrameObject(b0());const a=i.length;let l;if(s?l=s.call(o,o.frame)!==!1:l=!0,!!l)for(let u=0;u<a;u++){const c=i[u];c._id!==void 0&&(t[c._id]=c)}}for(const r in t)t.hasOwnProperty(r)&&t[r].batchDraw()}static _animationLoop(){const t=ju;t.animations.length?(t._runFrames(),Ae.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,Ae.requestAnimFrame(this._animationLoop))}};cu.animations=[],cu.animIdCounter=0,cu.animRunning=!1;var yO={node:1,duration:1,easing:1,onFinish:1,yoyo:1},bO=1,N4=2,z4=3,H4=["fill","stroke","shadowColor"],wO=0,CO=class{constructor(e,t,n,r,o,i,s){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=i,this._change=0,this.prevPos=0,this.yoyo=s,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=n,this._change=o-this.begin,this.pause()}fire(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=N4,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=z4,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===N4?this.setTime(e):this.state===z4&&this.setTime(this.duration-e)}pause(){this.state=bO,this.fire("onPause")}getTimer(){return new Date().getTime()}},Np=class Ir{constructor(t){const n=this,r=t.node,o=r._id,i=t.easing||yf.Linear,s=!!t.yoyo;let a,l;typeof t.duration>"u"?a=.3:t.duration===0?a=.001:a=t.duration,this.node=r,this._id=wO++;const u=r.getLayer()||(r instanceof gt.Stage?r.getLayers():null);u||Ae.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new cu(function(){n.tween.onEnterFrame()},u),this.tween=new CO(l,function(c){n._tweenFunc(c)},i,0,1,a*1e3,s),this._addListeners(),Ir.attrs[o]||(Ir.attrs[o]={}),Ir.attrs[o][this._id]||(Ir.attrs[o][this._id]={}),Ir.tweens[o]||(Ir.tweens[o]={});for(l in t)yO[l]===void 0&&this._addAttr(l,t[l]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,n){const r=this.node,o=r._id;let i,s,a,l,u;const c=Ir.tweens[o][t];c&&delete Ir.attrs[o][c][t];let d=r.getAttr(t);if(Ae._isArray(n))if(i=[],s=Math.max(n.length,d.length),t==="points"&&n.length!==d.length&&(n.length>d.length?(l=d,d=Ae._prepareArrayForTween(d,n,r.closed())):(a=n,n=Ae._prepareArrayForTween(n,d,r.closed()))),t.indexOf("fill")===0)for(let h=0;h<s;h++)if(h%2===0)i.push(n[h]-d[h]);else{const m=Ae.colorToRGBA(d[h]);u=Ae.colorToRGBA(n[h]),d[h]=m,i.push({r:u.r-m.r,g:u.g-m.g,b:u.b-m.b,a:u.a-m.a})}else for(let h=0;h<s;h++)i.push(n[h]-d[h]);else H4.indexOf(t)!==-1?(d=Ae.colorToRGBA(d),u=Ae.colorToRGBA(n),i={r:u.r-d.r,g:u.g-d.g,b:u.b-d.b,a:u.a-d.a}):i=n-d;Ir.attrs[o][this._id][t]={start:d,diff:i,end:n,trueEnd:a,trueStart:l},Ir.tweens[o][t]=this._id}_tweenFunc(t){const n=this.node,r=Ir.attrs[n._id][this._id];let o,i,s,a,l,u,c,d;for(o in r){if(i=r[o],s=i.start,a=i.diff,d=i.end,Ae._isArray(s))if(l=[],c=Math.max(s.length,d.length),o.indexOf("fill")===0)for(u=0;u<c;u++)u%2===0?l.push((s[u]||0)+a[u]*t):l.push("rgba("+Math.round(s[u].r+a[u].r*t)+","+Math.round(s[u].g+a[u].g*t)+","+Math.round(s[u].b+a[u].b*t)+","+(s[u].a+a[u].a*t)+")");else for(u=0;u<c;u++)l.push((s[u]||0)+a[u]*t);else H4.indexOf(o)!==-1?l="rgba("+Math.round(s.r+a.r*t)+","+Math.round(s.g+a.g*t)+","+Math.round(s.b+a.b*t)+","+(s.a+a.a*t)+")":l=s+a*t;n.setAttr(o,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=Ir.attrs[t._id][this._id];n.points&&n.points.trueEnd&&t.setAttr("points",n.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,n=Ir.attrs[t._id][this._id];n.points&&n.points.trueStart&&t.points(n.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,n=this._id,r=Ir.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const o in r)delete Ir.tweens[t][o];delete Ir.attrs[t][n],Ir.tweens[t]&&(Object.keys(Ir.tweens[t]).length===0&&delete Ir.tweens[t],Object.keys(Ir.attrs[t]).length===0&&delete Ir.attrs[t])}};Np.attrs={},Np.tweens={},yt.prototype.to=function(e){const t=e.onFinish;e.node=this,e.onFinish=function(){this.destroy(),t&&t()},new Np(e).play()};const yf={BackEaseIn(e,t,n,r){return n*(e/=r)*e*((1.70158+1)*e-1.70158)+t},BackEaseOut(e,t,n,r){return n*((e=e/r-1)*e*((1.70158+1)*e+1.70158)+1)+t},BackEaseInOut(e,t,n,r){let o=1.70158;return(e/=r/2)<1?n/2*(e*e*(((o*=1.525)+1)*e-o))+t:n/2*((e-=2)*e*(((o*=1.525)+1)*e+o)+2)+t},ElasticEaseIn(e,t,n,r,o,i){let s=0;return e===0?t:(e/=r)===1?t+n:(i||(i=r*.3),!o||o<Math.abs(n)?(o=n,s=i/4):s=i/(2*Math.PI)*Math.asin(n/o),-(o*Math.pow(2,10*(e-=1))*Math.sin((e*r-s)*(2*Math.PI)/i))+t)},ElasticEaseOut(e,t,n,r,o,i){let s=0;return e===0?t:(e/=r)===1?t+n:(i||(i=r*.3),!o||o<Math.abs(n)?(o=n,s=i/4):s=i/(2*Math.PI)*Math.asin(n/o),o*Math.pow(2,-10*e)*Math.sin((e*r-s)*(2*Math.PI)/i)+n+t)},ElasticEaseInOut(e,t,n,r,o,i){let s=0;return e===0?t:(e/=r/2)===2?t+n:(i||(i=r*(.3*1.5)),!o||o<Math.abs(n)?(o=n,s=i/4):s=i/(2*Math.PI)*Math.asin(n/o),e<1?-.5*(o*Math.pow(2,10*(e-=1))*Math.sin((e*r-s)*(2*Math.PI)/i))+t:o*Math.pow(2,-10*(e-=1))*Math.sin((e*r-s)*(2*Math.PI)/i)*.5+n+t)},BounceEaseOut(e,t,n,r){return(e/=r)<1/2.75?n*(7.5625*e*e)+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t},BounceEaseIn(e,t,n,r){return n-yf.BounceEaseOut(r-e,0,n,r)+t},BounceEaseInOut(e,t,n,r){return e<r/2?yf.BounceEaseIn(e*2,0,n,r)*.5+t:yf.BounceEaseOut(e*2-r,0,n,r)*.5+n*.5+t},EaseIn(e,t,n,r){return n*(e/=r)*e+t},EaseOut(e,t,n,r){return-n*(e/=r)*(e-2)+t},EaseInOut(e,t,n,r){return(e/=r/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t},StrongEaseIn(e,t,n,r){return n*(e/=r)*e*e*e*e+t},StrongEaseOut(e,t,n,r){return n*((e=e/r-1)*e*e*e*e+1)+t},StrongEaseInOut(e,t,n,r){return(e/=r/2)<1?n/2*e*e*e*e*e+t:n/2*((e-=2)*e*e*e*e+2)+t},Linear(e,t,n,r){return n*e/r+t}},U4=Ae._assign(gt,{Util:Ae,Transform:Ui,Node:yt,Container:fi,Stage:Fp,stages:gf,Layer:Yl,FastLayer:y0,Group:lu,DD:En,Shape:ct,shapes:vf,Animation:cu,Tween:Np,Easings:yf,Context:xp,Canvas:a0});var ha=class extends ct{_sceneFunc(e){const t=gt.getAngle(this.angle()),n=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,n),e.arc(0,0,this.innerRadius(),t,0,!n),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),n=this.clockwise(),r=gt.getAngle(n?360-this.angle():this.angle()),o=Math.cos(Math.min(r,Math.PI)),i=1,s=Math.sin(Math.min(Math.max(Math.PI,r),3*Math.PI/2)),a=Math.sin(Math.min(r,Math.PI/2)),l=o*(o>0?e:t),u=i*(i>0?t:e),c=s*(s>0?e:t),d=a*(a>0?t:e);return{x:l,y:n?-1*d:c,width:u-l,height:d-c}}};ha.prototype._centroid=!0,ha.prototype.className="Arc",ha.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"],vr(ha),ce.addGetterSetter(ha,"innerRadius",0,dt()),ce.addGetterSetter(ha,"outerRadius",0,dt()),ce.addGetterSetter(ha,"angle",0,dt()),ce.addGetterSetter(ha,"clockwise",!1,Vi());function w0(e,t,n,r,o,i,s){const a=Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2)),l=Math.sqrt(Math.pow(o-n,2)+Math.pow(i-r,2)),u=s*a/(a+l),c=s*l/(a+l);return[n-u*(o-e),r-u*(i-t),n+c*(o-e),r+c*(i-t)]}function V4(e,t){const n=e.length,r=[];for(let o=2;o<n-2;o+=2){const i=w0(e[o-2],e[o-1],e[o],e[o+1],e[o+2],e[o+3],t);isNaN(i[0])||(r.push(i[0]),r.push(i[1]),r.push(e[o]),r.push(e[o+1]),r.push(i[2]),r.push(i[3]))}return r}function _O(e){const t=[[e[0],e[2],e[4],e[6]],[e[1],e[3],e[5],e[7]]],n=[];for(const r of t){const o=-3*r[0]+9*r[1]-9*r[2]+3*r[3];if(o!==0){const i=6*r[0]-12*r[1]+6*r[2],s=-3*r[0]+3*r[1],a=i*i-4*o*s;if(a>=0){const l=Math.sqrt(a);n.push((-i+l)/(2*o)),n.push((-i-l)/(2*o))}}}return n.filter(r=>r>0&&r<1).flatMap(r=>t.map(o=>{const i=1-r;return i*i*i*o[0]+3*i*i*r*o[1]+3*i*r*r*o[2]+r*r*r*o[3]}))}var pa=class extends ct{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),n=t.length,r=this.tension(),o=this.closed(),i=this.bezier();if(!n)return;let s=0;if(e.beginPath(),e.moveTo(t[0],t[1]),r!==0&&n>4){const a=this.getTensionPoints(),l=a.length;for(s=o?0:4,o||e.quadraticCurveTo(a[0],a[1],a[2],a[3]);s<l-2;)e.bezierCurveTo(a[s++],a[s++],a[s++],a[s++],a[s++],a[s++]);o||e.quadraticCurveTo(a[l-2],a[l-1],t[n-2],t[n-1])}else if(i)for(s=2;s<n;)e.bezierCurveTo(t[s++],t[s++],t[s++],t[s++],t[s++],t[s++]);else for(s=2;s<n;s+=2)e.lineTo(t[s],t[s+1]);o?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():V4(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,n=this.tension(),r=w0(e[t-2],e[t-1],e[0],e[1],e[2],e[3],n),o=w0(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],n),i=V4(e,n);return[r[2],r[3]].concat(i).concat([o[0],o[1],e[t-2],e[t-1],o[2],o[3],r[0],r[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],..._O(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],n=e[0],r=e[1],o=e[1],i,s;for(let a=0;a<e.length/2;a++)i=e[a*2],s=e[a*2+1],t=Math.min(t,i),n=Math.max(n,i),r=Math.min(r,s),o=Math.max(o,s);return{x:t,y:r,width:n-t,height:o-r}}};pa.prototype.className="Line",pa.prototype._attrsAffectingSize=["points","bezier","tension"],vr(pa),ce.addGetterSetter(pa,"closed",!1),ce.addGetterSetter(pa,"bezier",!1),ce.addGetterSetter(pa,"tension",0,dt()),ce.addGetterSetter(pa,"points",[],NP());const SO=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],kO=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],AO=[[1],[1,1],[1,2,1],[1,3,3,1]],j4=(e,t,n)=>{let r,o;const s=n/2;r=0;for(let a=0;a<20;a++)o=s*SO[20][a]+s,r+=kO[20][a]*IO(e,t,o);return s*r},G4=(e,t,n)=>{n===void 0&&(n=1);const r=e[0]-2*e[1]+e[2],o=t[0]-2*t[1]+t[2],i=2*e[1]-2*e[0],s=2*t[1]-2*t[0],a=4*(r*r+o*o),l=4*(r*i+o*s),u=i*i+s*s;if(a===0)return n*Math.sqrt(Math.pow(e[2]-e[0],2)+Math.pow(t[2]-t[0],2));const c=l/(2*a),d=u/a,h=n+c,m=d-c*c,p=h*h+m>0?Math.sqrt(h*h+m):0,g=c*c+m>0?Math.sqrt(c*c+m):0,k=c+Math.sqrt(c*c+m)!==0?m*Math.log(Math.abs((h+p)/(c+g))):0;return Math.sqrt(a)/2*(h*p-c*g+k)};function IO(e,t,n){const r=C0(1,n,e),o=C0(1,n,t),i=r*r+o*o;return Math.sqrt(i)}var C0=(e,t,n)=>{const r=n.length-1;let o,i;if(r===0)return 0;if(e===0){i=0;for(let s=0;s<=r;s++)i+=AO[r][s]*Math.pow(1-t,r-s)*Math.pow(t,s)*n[s];return i}else{o=new Array(r);for(let s=0;s<r;s++)o[s]=r*(n[s+1]-n[s]);return C0(e-1,t,o)}};const W4=(e,t,n)=>{let r=1,o=e/t,i=(e-n(o))/t,s=0;for(;r>.001;){const a=n(o+i),l=Math.abs(e-a)/t;if(l<r)r=l,o+=i;else{const u=n(o-i),c=Math.abs(e-u)/t;c<r?(r=c,o-=i):i/=2}if(s++,s>500)break}return o};var Ii=class si extends ct{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=si.parsePathData(this.data()),this.pathLength=si.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let o=0;o<n.length;o++){const i=n[o].command,s=n[o].points;switch(i){case"L":t.lineTo(s[0],s[1]);break;case"M":t.moveTo(s[0],s[1]);break;case"C":t.bezierCurveTo(s[0],s[1],s[2],s[3],s[4],s[5]);break;case"Q":t.quadraticCurveTo(s[0],s[1],s[2],s[3]);break;case"A":const a=s[0],l=s[1],u=s[2],c=s[3],d=s[4],h=s[5],m=s[6],p=s[7],g=u>c?u:c,k=u>c?1:u/c,w=u>c?c/u:1;t.translate(a,l),t.rotate(m),t.scale(k,w),t.arc(0,0,g,d,d+h,1-p),t.scale(1/k,1/w),t.rotate(-m),t.translate(-a,-l);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(l){if(l.command==="A"){const u=l.points[4],c=l.points[5],d=l.points[4]+c;let h=Math.PI/180;if(Math.abs(u-d)<h&&(h=Math.abs(u-d)),c<0)for(let m=u-h;m>d;m-=h){const p=si.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],m,0);t.push(p.x,p.y)}else for(let m=u+h;m<d;m+=h){const p=si.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],m,0);t.push(p.x,p.y)}}else if(l.command==="C")for(let u=0;u<=1;u+=.01){const c=si.getPointOnCubicBezier(u,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);t.push(c.x,c.y)}else t=t.concat(l.points)});let n=t[0],r=t[0],o=t[1],i=t[1],s,a;for(let l=0;l<t.length/2;l++)s=t[l*2],a=t[l*2+1],isNaN(s)||(n=Math.min(n,s),r=Math.max(r,s)),isNaN(a)||(o=Math.min(o,a),i=Math.max(i,a));return{x:n,y:o,width:r-n,height:i-o}}getLength(){return this.pathLength}getPointAtLength(t){return si.getPointAtLengthOfDataArray(t,this.dataArray)}static getLineLength(t,n,r,o){return Math.sqrt((r-t)*(r-t)+(o-n)*(o-n))}static getPathLength(t){let n=0;for(let r=0;r<t.length;++r)n+=t[r].pathLength;return n}static getPointAtLengthOfDataArray(t,n){let r,o=0,i=n.length;if(!i)return null;for(;o<i&&t>n[o].pathLength;)t-=n[o].pathLength,++o;if(o===i)return r=n[o-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[o].command==="M"?(r=n[o].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[o].start.x,y:n[o].start.y};const s=n[o],a=s.points;switch(s.command){case"L":return si.getPointOnLine(t,s.start.x,s.start.y,a[0],a[1]);case"C":return si.getPointOnCubicBezier(W4(t,si.getPathLength(n),g=>j4([s.start.x,a[0],a[2],a[4]],[s.start.y,a[1],a[3],a[5]],g)),s.start.x,s.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return si.getPointOnQuadraticBezier(W4(t,si.getPathLength(n),g=>G4([s.start.x,a[0],a[2]],[s.start.y,a[1],a[3]],g)),s.start.x,s.start.y,a[0],a[1],a[2],a[3]);case"A":const l=a[0],u=a[1],c=a[2],d=a[3],h=a[5],m=a[6];let p=a[4];return p+=h*t/s.pathLength,si.getPointOnEllipticalArc(l,u,c,d,p,m)}return null}static getPointOnLine(t,n,r,o,i,s,a){s=s??n,a=a??r;const l=this.getLineLength(n,r,o,i);if(l<1e-10)return{x:n,y:r};if(o===n)return{x:s,y:a+(i>r?t:-t)};const u=(i-r)/(o-n),c=Math.sqrt(t*t/(1+u*u))*(o<n?-1:1),d=u*c;if(Math.abs(a-r-u*(s-n))<1e-10)return{x:s+c,y:a+d};const h=((s-n)*(o-n)+(a-r)*(i-r))/(l*l),m=n+h*(o-n),p=r+h*(i-r),g=this.getLineLength(s,a,m,p),k=Math.sqrt(t*t-g*g),w=Math.sqrt(k*k/(1+u*u))*(o<n?-1:1),S=u*w;return{x:m+w,y:p+S}}static getPointOnCubicBezier(t,n,r,o,i,s,a,l,u){function c(p){return p*p*p}function d(p){return 3*p*p*(1-p)}function h(p){return 3*p*(1-p)*(1-p)}function m(p){return(1-p)*(1-p)*(1-p)}return{x:l*c(t)+s*d(t)+o*h(t)+n*m(t),y:u*c(t)+a*d(t)+i*h(t)+r*m(t)}}static getPointOnQuadraticBezier(t,n,r,o,i,s,a){function l(d){return d*d}function u(d){return 2*d*(1-d)}function c(d){return(1-d)*(1-d)}return{x:s*l(t)+o*u(t)+n*c(t),y:a*l(t)+i*u(t)+r*c(t)}}static getPointOnEllipticalArc(t,n,r,o,i,s){const a=Math.cos(s),l=Math.sin(s),u={x:r*Math.cos(i),y:o*Math.sin(i)};return{x:t+(u.x*a-u.y*l),y:n+(u.x*l+u.y*a)}}static parsePathData(t){if(!t)return[];let n=t;const r=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];n=n.replace(new RegExp(" ","g"),",");for(let d=0;d<r.length;d++)n=n.replace(new RegExp(r[d],"g"),"|"+r[d]);const o=n.split("|"),i=[],s=[];let a=0,l=0;const u=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let c;for(let d=1;d<o.length;d++){let h=o[d],m=h.charAt(0);for(h=h.slice(1),s.length=0;c=u.exec(h);)s.push(c[0]);let p=[],g=m==="A"||m==="a"?0:-1;for(let k=0,w=s.length;k<w;k++){const S=s[k];if(S==="00"){p.push(0,0),g>=0&&(g+=2,g>=7&&(g-=7));continue}if(g>=0){if(g===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){p.push(parseInt(S[0],10)),p.push(parseInt(S[1],10)),p.push(parseFloat(S.slice(2))),g+=3,g>=7&&(g-=7);continue}if(S==="11"||S==="10"||S==="01"){p.push(parseInt(S[0],10)),p.push(parseInt(S[1],10)),g+=2,g>=7&&(g-=7);continue}if(S==="0"||S==="1"){p.push(parseInt(S,10)),g+=1,g>=7&&(g-=7);continue}}else if(g===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){p.push(parseInt(S[0],10)),p.push(parseFloat(S.slice(1))),g+=2,g>=7&&(g-=7);continue}if(S==="0"||S==="1"){p.push(parseInt(S,10)),g+=1,g>=7&&(g-=7);continue}}const y=parseFloat(S);isNaN(y)?p.push(0):p.push(y),g+=1,g>=7&&(g-=7)}else{const y=parseFloat(S);isNaN(y)?p.push(0):p.push(y)}}for(;p.length>0&&!isNaN(p[0]);){let k="",w=[];const S=a,y=l;let C,T,R,M,H,B,z,Z,P,N;switch(m){case"l":a+=p.shift(),l+=p.shift(),k="L",w.push(a,l);break;case"L":a=p.shift(),l=p.shift(),w.push(a,l);break;case"m":const I=p.shift(),L=p.shift();if(a+=I,l+=L,k="M",i.length>2&&i[i.length-1].command==="z"){for(let X=i.length-2;X>=0;X--)if(i[X].command==="M"){a=i[X].points[0]+I,l=i[X].points[1]+L;break}}w.push(a,l),m="l";break;case"M":a=p.shift(),l=p.shift(),k="M",w.push(a,l),m="L";break;case"h":a+=p.shift(),k="L",w.push(a,l);break;case"H":a=p.shift(),k="L",w.push(a,l);break;case"v":l+=p.shift(),k="L",w.push(a,l);break;case"V":l=p.shift(),k="L",w.push(a,l);break;case"C":w.push(p.shift(),p.shift(),p.shift(),p.shift()),a=p.shift(),l=p.shift(),w.push(a,l);break;case"c":w.push(a+p.shift(),l+p.shift(),a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="C",w.push(a,l);break;case"S":T=a,R=l,C=i[i.length-1],C.command==="C"&&(T=a+(a-C.points[2]),R=l+(l-C.points[3])),w.push(T,R,p.shift(),p.shift()),a=p.shift(),l=p.shift(),k="C",w.push(a,l);break;case"s":T=a,R=l,C=i[i.length-1],C.command==="C"&&(T=a+(a-C.points[2]),R=l+(l-C.points[3])),w.push(T,R,a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="C",w.push(a,l);break;case"Q":w.push(p.shift(),p.shift()),a=p.shift(),l=p.shift(),w.push(a,l);break;case"q":w.push(a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="Q",w.push(a,l);break;case"T":T=a,R=l,C=i[i.length-1],C.command==="Q"&&(T=a+(a-C.points[0]),R=l+(l-C.points[1])),a=p.shift(),l=p.shift(),k="Q",w.push(T,R,a,l);break;case"t":T=a,R=l,C=i[i.length-1],C.command==="Q"&&(T=a+(a-C.points[0]),R=l+(l-C.points[1])),a+=p.shift(),l+=p.shift(),k="Q",w.push(T,R,a,l);break;case"A":M=p.shift(),H=p.shift(),B=p.shift(),z=p.shift(),Z=p.shift(),P=a,N=l,a=p.shift(),l=p.shift(),k="A",w=this.convertEndpointToCenterParameterization(P,N,a,l,z,Z,M,H,B);break;case"a":M=p.shift(),H=p.shift(),B=p.shift(),z=p.shift(),Z=p.shift(),P=a,N=l,a+=p.shift(),l+=p.shift(),k="A",w=this.convertEndpointToCenterParameterization(P,N,a,l,z,Z,M,H,B);break}i.push({command:k||m,points:w,start:{x:S,y},pathLength:this.calcLength(S,y,k||m,w)})}(m==="z"||m==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,o){let i,s,a,l;const u=si;switch(r){case"L":return u.getLineLength(t,n,o[0],o[1]);case"C":return j4([t,o[0],o[2],o[4]],[n,o[1],o[3],o[5]],1);case"Q":return G4([t,o[0],o[2]],[n,o[1],o[3]],1);case"A":i=0;const c=o[4],d=o[5],h=o[4]+d;let m=Math.PI/180;if(Math.abs(c-h)<m&&(m=Math.abs(c-h)),s=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],c,0),d<0)for(l=c-m;l>h;l-=m)a=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],l,0),i+=u.getLineLength(s.x,s.y,a.x,a.y),s=a;else for(l=c+m;l<h;l+=m)a=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],l,0),i+=u.getLineLength(s.x,s.y,a.x,a.y),s=a;return a=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],h,0),i+=u.getLineLength(s.x,s.y,a.x,a.y),i}return 0}static convertEndpointToCenterParameterization(t,n,r,o,i,s,a,l,u){const c=u*(Math.PI/180),d=Math.cos(c)*(t-r)/2+Math.sin(c)*(n-o)/2,h=-1*Math.sin(c)*(t-r)/2+Math.cos(c)*(n-o)/2,m=d*d/(a*a)+h*h/(l*l);m>1&&(a*=Math.sqrt(m),l*=Math.sqrt(m));let p=Math.sqrt((a*a*(l*l)-a*a*(h*h)-l*l*(d*d))/(a*a*(h*h)+l*l*(d*d)));i===s&&(p*=-1),isNaN(p)&&(p=0);const g=p*a*h/l,k=p*-l*d/a,w=(t+r)/2+Math.cos(c)*g-Math.sin(c)*k,S=(n+o)/2+Math.sin(c)*g+Math.cos(c)*k,y=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},C=function(z,Z){return(z[0]*Z[0]+z[1]*Z[1])/(y(z)*y(Z))},T=function(z,Z){return(z[0]*Z[1]<z[1]*Z[0]?-1:1)*Math.acos(C(z,Z))},R=T([1,0],[(d-g)/a,(h-k)/l]),M=[(d-g)/a,(h-k)/l],H=[(-1*d-g)/a,(-1*h-k)/l];let B=T(M,H);return C(M,H)<=-1&&(B=Math.PI),C(M,H)>=1&&(B=0),s===0&&B>0&&(B=B-2*Math.PI),s===1&&B<0&&(B=B+2*Math.PI),[w,S,a,l,R,B,c,s]}};Ii.prototype.className="Path",Ii.prototype._attrsAffectingSize=["data"],vr(Ii),ce.addGetterSetter(Ii,"data");var Xl=class extends pa{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,n=this.points();let r=n;const o=this.tension()!==0&&n.length>4;o&&(r=this.getTensionPoints());const i=this.pointerLength(),s=n.length;let a,l;if(o){const d=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],n[s-2],n[s-1]],h=Ii.calcLength(r[r.length-4],r[r.length-3],"C",d),m=Ii.getPointOnQuadraticBezier(Math.min(1,1-i/h),d[0],d[1],d[2],d[3],d[4],d[5]);a=n[s-2]-m.x,l=n[s-1]-m.y}else a=n[s-2]-n[s-4],l=n[s-1]-n[s-3];const u=(Math.atan2(l,a)+t)%t,c=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(n[s-2],n[s-1]),e.rotate(u),e.moveTo(0,0),e.lineTo(-i,c/2),e.lineTo(-i,-c/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(n[0],n[1]),o?(a=(r[0]+r[2])/2-n[0],l=(r[1]+r[3])/2-n[1]):(a=n[2]-n[0],l=n[3]-n[1]),e.rotate((Math.atan2(-l,-a)+t)%t),e.moveTo(0,0),e.lineTo(-i,c/2),e.lineTo(-i,-c/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}};Xl.prototype.className="Arrow",vr(Xl),ce.addGetterSetter(Xl,"pointerLength",10,dt()),ce.addGetterSetter(Xl,"pointerWidth",10,dt()),ce.addGetterSetter(Xl,"pointerAtBeginning",!1),ce.addGetterSetter(Xl,"pointerAtEnding",!0);var uu=class extends ct{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}};uu.prototype._centroid=!0,uu.prototype.className="Circle",uu.prototype._attrsAffectingSize=["radius"],vr(uu),ce.addGetterSetter(uu,"radius",0,dt());var Ja=class extends ct{_sceneFunc(e){const t=this.radiusX(),n=this.radiusY();e.beginPath(),e.save(),t!==n&&e.scale(1,n/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}};Ja.prototype.className="Ellipse",Ja.prototype._centroid=!0,Ja.prototype._attrsAffectingSize=["radiusX","radiusY"],vr(Ja),ce.addComponentsGetterSetter(Ja,"radius",["x","y"]),ce.addGetterSetter(Ja,"radiusX",0,dt()),ce.addGetterSetter(Ja,"radiusY",0,dt());var ji=class GA extends ct{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),o=this.cornerRadius(),i=this.attrs.image;let s;if(i){const a=this.attrs.cropWidth,l=this.attrs.cropHeight;a&&l?s=[i,this.cropX(),this.cropY(),a,l,0,0,n,r]:s=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||o)&&(t.beginPath(),o?Ae.drawRoundedRectPath(t,n,r,o):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(o&&t.clip(),t.drawImage.apply(t,s))}_hitFunc(t){const n=this.width(),r=this.height(),o=this.cornerRadius();t.beginPath(),o?Ae.drawRoundedRectPath(t,n,r,o):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const o=Ae.createImageElement();o.onload=function(){n(new GA({image:o}))},o.onerror=r,o.crossOrigin="Anonymous",o.src=t}};ji.prototype.className="Image",ji.prototype._attrsAffectingSize=["image"],vr(ji),ce.addGetterSetter(ji,"cornerRadius",0,Rp(4)),ce.addGetterSetter(ji,"image"),ce.addComponentsGetterSetter(ji,"crop",["x","y","width","height"]),ce.addGetterSetter(ji,"cropX",0,dt()),ce.addGetterSetter(ji,"cropY",0,dt()),ce.addGetterSetter(ji,"cropWidth",0,dt()),ce.addGetterSetter(ji,"cropHeight",0,dt());var K4=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],EO="Change.konva",xO="none",_0="up",S0="right",k0="down",A0="left",TO=K4.length,I0=class extends lu{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,n;const r=function(){t._sync()};for(n=0;n<TO;n++)e.on(K4[n]+EO,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),n,r,o,i,s,a,l;if(e&&t){switch(n=e.width(),r=e.height(),o=t.pointerDirection(),i=t.pointerWidth(),l=t.pointerHeight(),s=0,a=0,o){case _0:s=n/2,a=-1*l;break;case S0:s=n+i,a=r/2;break;case k0:s=n/2,a=r+l;break;case A0:s=-1*i,a=r/2;break}t.setAttrs({x:-1*s,y:-1*a,width:n,height:r}),e.setAttrs({x:-1*s,y:-1*a})}}};I0.prototype.className="Label",vr(I0);var Ql=class extends ct{_sceneFunc(e){const t=this.width(),n=this.height(),r=this.pointerDirection(),o=this.pointerWidth(),i=this.pointerHeight(),s=this.cornerRadius();let a=0,l=0,u=0,c=0;typeof s=="number"?a=l=u=c=Math.min(s,t/2,n/2):(a=Math.min(s[0]||0,t/2,n/2),l=Math.min(s[1]||0,t/2,n/2),c=Math.min(s[2]||0,t/2,n/2),u=Math.min(s[3]||0,t/2,n/2)),e.beginPath(),e.moveTo(a,0),r===_0&&(e.lineTo((t-o)/2,0),e.lineTo(t/2,-1*i),e.lineTo((t+o)/2,0)),e.lineTo(t-l,0),e.arc(t-l,l,l,Math.PI*3/2,0,!1),r===S0&&(e.lineTo(t,(n-i)/2),e.lineTo(t+o,n/2),e.lineTo(t,(n+i)/2)),e.lineTo(t,n-c),e.arc(t-c,n-c,c,0,Math.PI/2,!1),r===k0&&(e.lineTo((t+o)/2,n),e.lineTo(t/2,n+i),e.lineTo((t-o)/2,n)),e.lineTo(u,n),e.arc(u,n-u,u,Math.PI/2,Math.PI,!1),r===A0&&(e.lineTo(0,(n+i)/2),e.lineTo(-1*o,n/2),e.lineTo(0,(n-i)/2)),e.lineTo(0,a),e.arc(a,a,a,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,n=this.pointerWidth(),r=this.pointerHeight(),o=this.pointerDirection(),i=this.width(),s=this.height();return o===_0?(t-=r,s+=r):o===k0?s+=r:o===A0?(e-=n*1.5,i+=n):o===S0&&(i+=n*1.5),{x:e,y:t,width:i,height:s}}};Ql.prototype.className="Tag",vr(Ql),ce.addGetterSetter(Ql,"pointerDirection",xO),ce.addGetterSetter(Ql,"pointerWidth",0,dt()),ce.addGetterSetter(Ql,"pointerHeight",0,dt()),ce.addGetterSetter(Ql,"cornerRadius",0,Rp(4));var bf=class extends ct{_sceneFunc(e){const t=this.cornerRadius(),n=this.width(),r=this.height();e.beginPath(),t?Ae.drawRoundedRectPath(e,n,r,t):e.rect(0,0,n,r),e.closePath(),e.fillStrokeShape(this)}};bf.prototype.className="Rect",vr(bf),ce.addGetterSetter(bf,"cornerRadius",0,Rp(4));var $a=class extends ct{_sceneFunc(e){const t=this._getPoints(),n=this.radius(),r=this.sides(),o=this.cornerRadius();if(e.beginPath(),o)Ae.drawRoundedPolygonPath(e,t,r,n,o);else{e.moveTo(t[0].x,t[0].y);for(let i=1;i<t.length;i++)e.lineTo(t[i].x,t[i].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,n=[];for(let r=0;r<e;r++)n.push({x:t*Math.sin(r*2*Math.PI/e),y:-1*t*Math.cos(r*2*Math.PI/e)});return n}getSelfRect(){const e=this._getPoints();let t=e[0].x,n=e[0].x,r=e[0].y,o=e[0].y;return e.forEach(i=>{t=Math.min(t,i.x),n=Math.max(n,i.x),r=Math.min(r,i.y),o=Math.max(o,i.y)}),{x:t,y:r,width:n-t,height:o-r}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}};$a.prototype.className="RegularPolygon",$a.prototype._centroid=!0,$a.prototype._attrsAffectingSize=["radius"],vr($a),ce.addGetterSetter($a,"radius",0,dt()),ce.addGetterSetter($a,"sides",0,dt()),ce.addGetterSetter($a,"cornerRadius",0,Rp(4));var q4=Math.PI*2,Zl=class extends ct{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,q4,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),q4,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}};Zl.prototype.className="Ring",Zl.prototype._centroid=!0,Zl.prototype._attrsAffectingSize=["innerRadius","outerRadius"],vr(Zl),ce.addGetterSetter(Zl,"innerRadius",0,dt()),ce.addGetterSetter(Zl,"outerRadius",0,dt());var ys=class extends ct{constructor(e){super(e),this._updated=!0,this.anim=new cu(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),n=this.frameIndex(),r=n*4,o=this.animations()[t],i=this.frameOffsets(),s=o[r+0],a=o[r+1],l=o[r+2],u=o[r+3],c=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,l,u),e.closePath(),e.fillStrokeShape(this)),c)if(i){const d=i[t],h=n*2;e.drawImage(c,s,a,l,u,d[h+0],d[h+1],l,u)}else e.drawImage(c,s,a,l,u,0,0,l,u)}_hitFunc(e){const t=this.animation(),n=this.frameIndex(),r=n*4,o=this.animations()[t],i=this.frameOffsets(),s=o[r+2],a=o[r+3];if(e.beginPath(),i){const l=i[t],u=n*2;e.rect(l[u+0],l[u+1],s,a)}else e.rect(0,0,s,a);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation();e<this.animations()[t].length/4-1?this.frameIndex(e+1):this.frameIndex(0)}};ys.prototype.className="Sprite",vr(ys),ce.addGetterSetter(ys,"animation"),ce.addGetterSetter(ys,"animations"),ce.addGetterSetter(ys,"frameOffsets"),ce.addGetterSetter(ys,"image"),ce.addGetterSetter(ys,"frameIndex",0,dt()),ce.addGetterSetter(ys,"frameRate",17,dt()),ce.backCompat(ys,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});var el=class extends ct{_sceneFunc(e){const t=this.innerRadius(),n=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-n);for(let o=1;o<r*2;o++){const i=o%2===0?n:t,s=i*Math.sin(o*Math.PI/r),a=-1*i*Math.cos(o*Math.PI/r);e.lineTo(s,a)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}};el.prototype.className="Star",el.prototype._centroid=!0,el.prototype._attrsAffectingSize=["innerRadius","outerRadius"],vr(el),ce.addGetterSetter(el,"numPoints",5,dt()),ce.addGetterSetter(el,"innerRadius",0,dt()),ce.addGetterSetter(el,"outerRadius",0,dt());function tl(e){return[...e].reduce((t,n,r,o)=>{if(/\p{Emoji}/u.test(n)){const i=o[r+1];i&&/\p{Emoji_Modifier}|\u200D/u.test(i)?(t.push(n+i),o[r+1]=""):t.push(n)}else/\p{Regional_Indicator}{2}/u.test(n+(o[r+1]||""))?t.push(n+o[r+1]):r>0&&/\p{Mn}|\p{Me}|\p{Mc}/u.test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}var du="auto",RO="center",Y4="inherit",wf="justify",MO="Change.konva",X4="2d",Q4="-",Z4="left",LO="text",DO="Text",PO="top",OO="bottom",J4="middle",$4="normal",FO="px ",zp=" ",BO="right",ek="rtl",NO="word",zO="char",tk="none",E0="…",nk=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],HO=nk.length,Cf=null;function UO(){if(Cf!==null)return Cf;Cf=!1;try{const e=document.createElement("canvas");e.width=10,e.height=10;const t=e.getContext(X4);if(t){t.globalAlpha=0,t.shadowColor="black",t.shadowBlur=5,t.shadowOffsetX=5,t.shadowOffsetY=5,t.fillStyle="black",t.font="10px Arial",t.fillText("X",0,10);const n=t.getImageData(0,0,10,10).data;for(let r=3;r<n.length;r+=4)if(n[r]>0){Cf=!0;break}}}catch{}return Cf}function VO(e){return e.split(",").map(t=>{t=t.trim();const n=t.indexOf(" ")>=0,r=t.indexOf('"')>=0||t.indexOf("'")>=0;return n&&!r&&(t=`"${t}"`),t}).join(", ")}var Hp;function x0(){return Hp||(Hp=Ae.createCanvasElement().getContext(X4),Hp)}function jO(e){e.fillText(this._partialText,this._partialTextX,this._partialTextY)}function GO(e){e.setAttr("miterLimit",2),e.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function WO(e){return e=e||{},!e.fillLinearGradientColorStops&&!e.fillRadialGradientColorStops&&!e.fillPatternImage&&(e.fill=e.fill||"black"),e}var nr=class extends ct{constructor(e){super(WO(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<HO;t++)this.on(nk[t]+MO,this._setTextData);this._setTextData()}_sceneFunc(e){var t,n;const r=this.textArr,o=r.length;if(!this.text())return;let i=this.padding(),s=this.fontSize(),a=this.lineHeight()*s,l=this.verticalAlign(),u=this.direction(),c=0,d=this.align(),h=this.getWidth(),m=this.letterSpacing(),p=this.charRenderFunc(),g=this.fill(),k=this.textDecoration(),w=this.underlineOffset(),S=k.indexOf("underline")!==-1,y=k.indexOf("line-through")!==-1,C;u=u===Y4?e.direction:u;let T=a/2,R=J4;if(!gt.legacyTextRendering){const M=this.measureSize("M");R="alphabetic",T=(((t=M.fontBoundingBoxAscent)!==null&&t!==void 0?t:M.actualBoundingBoxAscent)-((n=M.fontBoundingBoxDescent)!==null&&n!==void 0?n:M.actualBoundingBoxDescent))/2+a/2}for(u===ek&&e.setAttr("direction",u),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",R),e.setAttr("textAlign",Z4),l===J4?c=(this.getHeight()-o*a-i*2)/2:l===OO&&(c=this.getHeight()-o*a-i*2),e.translate(i,c+i),C=0;C<o;C++){let M=0,H=0;const B=r[C],z=B.text,Z=B.width,P=B.lastInParagraph;if(e.save(),d===BO?M+=h-Z-i*2:d===RO&&(M+=(h-Z-i*2)/2),S){e.save(),e.beginPath();const I=w??(gt.legacyTextRendering?Math.round(s/2):Math.round(s/4)),L=M,X=T+H+I;e.moveTo(L,X);const te=d===wf&&!P?h-i*2:Z;e.lineTo(L+Math.round(te),X),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||g,e.stroke(),e.restore()}const N=M;if(u!==ek&&(m!==0||d===wf||p)){const I=z.split(" ").length-1,L=tl(z);for(let X=0;X<L.length;X++){const te=L[X];if(te===" "&&!P&&d===wf&&(M+=(h-i*2-Z)/I),this._partialTextX=M,this._partialTextY=T+H,this._partialText=te,p){e.save();const le=r.slice(0,C).reduce((fe,Fe)=>fe+tl(Fe.text).length,0);p({char:te,index:X+le,x:M,y:T+H,lineIndex:C,column:X,isLastInLine:P,width:this.measureSize(te).width,context:e})}e.fillStrokeShape(this),p&&e.restore(),M+=this.measureSize(te).width+m}}else m!==0&&e.setAttr("letterSpacing",`${m}px`),this._partialTextX=M,this._partialTextY=T+H,this._partialText=z,e.fillStrokeShape(this);if(y){e.save(),e.beginPath();const I=gt.legacyTextRendering?0:-Math.round(s/4),L=N;e.moveTo(L,T+H+I);const X=d===wf&&!P?h-i*2:Z;e.lineTo(L+Math.round(X),T+H+I),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||g,e.stroke(),e.restore()}e.restore(),o>1&&(T+=a)}}_hitFunc(e){const t=this.getWidth(),n=this.getHeight();e.beginPath(),e.rect(0,0,t,n),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=Ae._isString(e)?e:e==null?"":e+"";return this._setAttr(LO,t),this}getWidth(){return this.attrs.width===du||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===du||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Ae.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,n,r,o,i,s,a,l,u,c,d;let h=x0(),m=this.fontSize(),p;h.save(),h.font=this._getContextFont(),p=h.measureText(e),h.restore();const g=m/100;return{actualBoundingBoxAscent:(t=p.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*g,actualBoundingBoxDescent:(n=p.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(r=p.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*g,actualBoundingBoxRight:(o=p.actualBoundingBoxRight)!==null&&o!==void 0?o:75.732421875*g,alphabeticBaseline:(i=p.alphabeticBaseline)!==null&&i!==void 0?i:0,emHeightAscent:(s=p.emHeightAscent)!==null&&s!==void 0?s:100*g,emHeightDescent:(a=p.emHeightDescent)!==null&&a!==void 0?a:-20*g,fontBoundingBoxAscent:(l=p.fontBoundingBoxAscent)!==null&&l!==void 0?l:91*g,fontBoundingBoxDescent:(u=p.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*g,hangingBaseline:(c=p.hangingBaseline)!==null&&c!==void 0?c:72.80000305175781*g,ideographicBaseline:(d=p.ideographicBaseline)!==null&&d!==void 0?d:-21*g,width:p.width,height:m}}_getContextFont(){return this.fontStyle()+zp+this.fontVariant()+zp+(this.fontSize()+FO)+VO(this.fontFamily())}_addTextLine(e){this.align()===wf&&(e=e.trim());const t=this._getTextWidth(e);return this.textArr.push({text:e,width:t,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),n=e.length;return x0().measureText(e).width+t*n}_setTextData(){let e=this.text().split(`
|
|
100
|
+
`),t=+this.fontSize(),n=0,r=this.lineHeight()*t,o=this.attrs.width,i=this.attrs.height,s=o!==du&&o!==void 0,a=i!==du&&i!==void 0,l=this.padding(),u=o-l*2,c=i-l*2,d=0,h=this.wrap(),m=h!==zO&&h!==tk,p=this.ellipsis();this.textArr=[],x0().font=this._getContextFont();const g=p?this._getTextWidth(E0):0;for(let k=0,w=e.length;k<w;++k){let S=e[k],y=this._getTextWidth(S);if(s&&y>u)for(;S.length>0;){let C=0,T=tl(S).length,R="",M=0;for(;C<T;){const H=C+T>>>1,B=tl(S).slice(0,H+1).join(""),z=this._getTextWidth(B);(p&&a&&d+r>c?z+g:z)<=u?(C=H+1,R=B,M=z):T=H}if(R){if(m){const H=tl(S),B=tl(R),z=H[B.length],Z=z===zp||z===Q4;let P;if(Z&&M<=u)P=B.length;else{const N=B.lastIndexOf(zp),I=B.lastIndexOf(Q4);P=Math.max(N,I)+1}P>0&&(C=P,R=H.slice(0,C).join(""),M=this._getTextWidth(R))}if(R=R.trimRight(),this._addTextLine(R),n=Math.max(n,M),d+=r,this._shouldHandleEllipsis(d)){this._tryToAddEllipsisToLastLine();break}if(S=tl(S).slice(C).join("").trimLeft(),S.length>0&&(y=this._getTextWidth(S),y<=u)){this._addTextLine(S),d+=r,n=Math.max(n,y);break}}else break}else this._addTextLine(S),d+=r,n=Math.max(n,y),this._shouldHandleEllipsis(d)&&k<w-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),a&&d+r>c)break}this.textHeight=t,this.textWidth=n}_shouldHandleEllipsis(e){const t=+this.fontSize(),n=this.lineHeight()*t,r=this.attrs.height,o=r!==du&&r!==void 0,i=r-this.padding()*2;return this.wrap()===tk||o&&e+n>i}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==du&&e!==void 0,n=e-this.padding()*2,r=this.ellipsis(),o=this.textArr[this.textArr.length-1];!o||!r||(t&&(this._getTextWidth(o.text+E0)<n||(o.text=o.text.slice(0,o.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(o.text+E0))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t||t&&this.getAbsoluteOpacity()!==1&&UO()?!0:super._useBufferCanvas()}};nr.prototype._fillFunc=jO,nr.prototype._strokeFunc=GO,nr.prototype.className=DO,nr.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],vr(nr),ce.overWriteSetter(nr,"width",c0()),ce.overWriteSetter(nr,"height",c0()),ce.addGetterSetter(nr,"direction",Y4),ce.addGetterSetter(nr,"fontFamily","Arial"),ce.addGetterSetter(nr,"fontSize",12,dt()),ce.addGetterSetter(nr,"fontStyle",$4),ce.addGetterSetter(nr,"fontVariant",$4),ce.addGetterSetter(nr,"padding",0,dt()),ce.addGetterSetter(nr,"align",Z4),ce.addGetterSetter(nr,"verticalAlign",PO),ce.addGetterSetter(nr,"lineHeight",1,dt()),ce.addGetterSetter(nr,"wrap",NO),ce.addGetterSetter(nr,"ellipsis",!1,Vi()),ce.addGetterSetter(nr,"letterSpacing",0,dt()),ce.addGetterSetter(nr,"text","",Kl()),ce.addGetterSetter(nr,"textDecoration",""),ce.addGetterSetter(nr,"underlineOffset",void 0,dt()),ce.addGetterSetter(nr,"charRenderFunc",void 0);var KO="",rk="normal";function ok(e){e.fillText(this.partialText,0,0)}function ik(e){e.strokeText(this.partialText,0,0)}var Vr=class extends ct{constructor(e){super(e),this.dummyCanvas=Ae.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return Ii.getPathLength(this.dataArray)}_getPointAtLength(e){return!this.attrs.data||e>this.pathLength?null:Ii.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=Ii.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),n=this.fill(),r=this.fontSize(),o=this.glyphInfo,i=t.indexOf("underline")!==-1,s=t.indexOf("line-through")!==-1;i&&e.beginPath();for(let a=0;a<o.length;a++){e.save();const l=o[a].p0;e.translate(l.x,l.y),e.rotate(o[a].rotation),this.partialText=o[a].text,e.fillStrokeShape(this),i&&(a===0&&e.moveTo(0,r/2+1),e.lineTo(o[a].width,r/2+1)),e.restore()}if(i&&(e.strokeStyle=n,e.lineWidth=r/20,e.stroke()),s){e.beginPath();for(let a=0;a<o.length;a++){e.save();const l=o[a].p0;e.translate(l.x,l.y),e.rotate(o[a].rotation),a===0&&e.moveTo(0,0),e.lineTo(o[a].width,0),e.restore()}e.strokeStyle=n,e.lineWidth=r/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const n=t[0].p0;e.moveTo(n.x,n.y)}for(let n=0;n<t.length;n++){const r=t[n].p1;e.lineTo(r.x,r.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return Ae.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return nr.prototype.setText.call(this,e)}_getContextFont(){return nr.prototype._getContextFont.call(this)}_getTextSize(e){const t=this.dummyCanvas.getContext("2d");t.save(),t.font=this._getContextFont();const n=t.measureText(e);return t.restore(),{width:n.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=tl(this.text()),t=[];let n=0;for(let h=0;h<e.length;h++)t.push({char:e[h],width:this._getTextSize(e[h]).width}),n+=t[h].width;const{width:r,height:o}=this._getTextSize(this.attrs.text);if(this.textWidth=n,this.textHeight=o,this.glyphInfo=[],!this.attrs.data)return null;const i=this.letterSpacing(),s=this.align(),a=this.kerningFunc(),l=Math.max(0,n-r),u=Math.max(this.textWidth+((this.attrs.text||"").length-1)*i,0);let c=0;s==="center"&&(c=Math.max(0,this.pathLength/2-u/2)),s==="right"&&(c=Math.max(0,this.pathLength-u));let d=c;for(let h=0;h<t.length;h++){const m=this._getPointAtLength(d);if(!m)return;const p=t[h].char;let g=t[h].width+i;if(p===" "&&s==="justify"){const R=this.text().split(" ").length-1;g+=(this.pathLength-u)/R}const k=d+g,w=this._getPointAtLength(k>this.pathLength&&k-this.pathLength<=l?this.pathLength:k);if(!w)return;const S=Ii.getLineLength(m.x,m.y,w.x,w.y);let y=0;if(a)try{y=a(t[h-1].char,p)*this.fontSize()}catch{y=0}m.x+=y,w.x+=y,this.textWidth+=y;const C=Ii.getPointOnLine(y+S/2,m.x,m.y,w.x,w.y),T=Math.atan2(w.y-m.y,w.x-m.x);this.glyphInfo.push({transposeX:C.x,transposeY:C.y,text:e[h],rotation:T,p0:m,p1:w,width:S}),d+=g}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(l){e.push(l.p0.x),e.push(l.p0.y),e.push(l.p1.x),e.push(l.p1.y)});let t=e[0]||0,n=e[0]||0,r=e[1]||0,o=e[1]||0,i,s;for(let l=0;l<e.length/2;l++)i=e[l*2],s=e[l*2+1],t=Math.min(t,i),n=Math.max(n,i),r=Math.min(r,s),o=Math.max(o,s);const a=this.fontSize();return{x:t-a/2,y:r-a/2,width:n-t+a,height:o-r+a}}destroy(){return Ae.releaseCanvas(this.dummyCanvas),super.destroy()}};Vr.prototype._fillFunc=ok,Vr.prototype._strokeFunc=ik,Vr.prototype._fillFuncHit=ok,Vr.prototype._strokeFuncHit=ik,Vr.prototype.className="TextPath",Vr.prototype._attrsAffectingSize=["text","fontSize","data"],vr(Vr),ce.addGetterSetter(Vr,"data"),ce.addGetterSetter(Vr,"fontFamily","Arial"),ce.addGetterSetter(Vr,"fontSize",12,dt()),ce.addGetterSetter(Vr,"fontStyle",rk),ce.addGetterSetter(Vr,"align","left"),ce.addGetterSetter(Vr,"letterSpacing",0,dt()),ce.addGetterSetter(Vr,"textBaseline","middle"),ce.addGetterSetter(Vr,"fontVariant",rk),ce.addGetterSetter(Vr,"text",KO),ce.addGetterSetter(Vr,"textDecoration",""),ce.addGetterSetter(Vr,"kerningFunc",void 0);var sk="tr-konva",qO=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(e=>e+`.${sk}`).join(" "),ak="nodesRect",YO=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],XO={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},QO="ontouchstart"in gt._global;function ZO(e,t,n){if(e==="rotater")return n;t+=Ae.degToRad(XO[e]||0);const r=(Ae.radToDeg(t)%360+360)%360;return Ae._inRange(r,337.5,360)||Ae._inRange(r,0,22.5)?"ns-resize":Ae._inRange(r,22.5,67.5)?"nesw-resize":Ae._inRange(r,67.5,112.5)?"ew-resize":Ae._inRange(r,112.5,157.5)?"nwse-resize":Ae._inRange(r,157.5,202.5)?"ns-resize":Ae._inRange(r,202.5,247.5)?"nesw-resize":Ae._inRange(r,247.5,292.5)?"ew-resize":Ae._inRange(r,292.5,337.5)?"nwse-resize":(Ae.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}var Up=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],lk=1e8;function JO(e){return{x:e.x+e.width/2*Math.cos(e.rotation)+e.height/2*Math.sin(-e.rotation),y:e.y+e.height/2*Math.cos(e.rotation)+e.width/2*Math.sin(e.rotation)}}function ck(e,t,n){const r=n.x+(e.x-n.x)*Math.cos(t)-(e.y-n.y)*Math.sin(t),o=n.y+(e.x-n.x)*Math.sin(t)+(e.y-n.y)*Math.cos(t);return{...e,rotation:e.rotation+t,x:r,y:o}}function $O(e,t){return ck(e,t,JO(e))}function eF(e,t,n){let r=t;for(let o=0;o<e.length;o++){const i=gt.getAngle(e[o]),s=Math.abs(i-t)%(Math.PI*2);Math.min(s,Math.PI*2-s)<n&&(r=i)}return r}var T0=0,kn=class extends lu{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._elementsCreated=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(qO,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return Ae.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return sk+this._id}setNodes(e=[]){return this._nodes&&this._nodes.length&&this.detach(),this._nodes=e=e.filter(t=>t.isAncestorOf(this)?(Ae.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0),e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(t=>{const n=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(t._attrsAffectingSize.length){const r=t._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");t.on(r,n)}t.on(YO.map(r=>r+`.${this._getEventNamespace()}`).join(" "),n),t.on(`absoluteTransformChange.${this._getEventNamespace()}`,n),this._proxyDrag(t)}),this._resetTransformCache(),this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,n=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(n,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,n=>{if(!t)return;const r=e.getAbsolutePosition(),o=r.x-t.x,i=r.y-t.y;this.nodes().forEach(s=>{if(s===e||s.isDragging())return;const a=s.getAbsolutePosition();s.setAbsolutePosition({x:a.x+o,y:a.y+i}),s.startDrag(n)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(ak),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(ak,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),n){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),o=e.getAbsoluteScale(n),i=e.getAbsolutePosition(n),s=r.x*o.x-e.offsetX()*o.x,a=r.y*o.y-e.offsetY()*o.y,l=(gt.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2);return ck({x:i.x+s*Math.cos(l)+a*Math.sin(-l),y:i.y+a*Math.cos(l)+s*Math.sin(l),width:r.width*o.x,height:r.height*o.y,rotation:l},-gt.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-lk,y:-lk,width:0,height:0,rotation:0};const e=[];this.nodes().map(a=>{const l=a.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),u=[{x:l.x,y:l.y},{x:l.x+l.width,y:l.y},{x:l.x+l.width,y:l.y+l.height},{x:l.x,y:l.y+l.height}],c=a.getAbsoluteTransform();u.forEach(function(d){const h=c.point(d);e.push(h)})});const t=new Ui;t.rotate(-gt.getAngle(this.rotation()));let n=1/0,r=1/0,o=-1/0,i=-1/0;e.forEach(function(a){const l=t.point(a);n===void 0&&(n=o=l.x,r=i=l.y),n=Math.min(n,l.x),r=Math.min(r,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y)}),t.invert();const s=t.point({x:n,y:r});return{x:s.x,y:s.y,width:o-n,height:i-r,rotation:gt.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Up.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(e){const t=new bf({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:QO?10:"auto"}),n=this;t.on("mousedown touchstart",function(r){n._handleMouseDown(r)}),t.on("dragstart",r=>{t.stopDrag(),r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),t.on("mouseenter",()=>{const r=ZO(e,gt.getAngle(this.rotation()),this.rotateAnchorCursor());t.getStage().content&&(t.getStage().content.style.cursor=r),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new ct({name:"back",width:0,height:0,sceneFunc(t,n){const r=n.getParent(),o=r.padding(),i=n.width(),s=n.height();if(t.beginPath(),t.rect(-o,-o,i+o*2,s+o*2),r.rotateEnabled()&&r.rotateLineVisible()){const a=r.rotateAnchorAngle(),l=r.rotateAnchorOffset(),u=Ae.degToRad(a),c=Math.sin(u),d=-Math.cos(u),h=i/2,m=s/2;let p=1/0;d<0?p=Math.min(p,-m/d):d>0&&(p=Math.min(p,(s-m)/d)),c<0?p=Math.min(p,-h/c):c>0&&(p=Math.min(p,(i-h)/c));const g=h+c*p,k=m+d*p,w=Ae._sign(s),S=g+c*l*w,y=k+d*l*w;t.moveTo(g,k),t.lineTo(S,y)}t.fillStrokeShape(n)},hitFunc:(t,n)=>{if(!this.shouldOverdrawWholeArea())return;const r=this.padding();t.beginPath(),t.rect(-r,-r,n.width()+r*2,n.height()+r*2),t.fillStrokeShape(n)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),n=t.width,r=t.height,o=Math.sqrt(Math.pow(n,2)+Math.pow(r,2));this.sin=Math.abs(r/o),this.cos=Math.abs(n/o),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const i=e.target.getAbsolutePosition(),s=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:s.x-i.x,y:s.y-i.y},T0++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(a=>{a._fire("transformstart",{evt:e.evt,target:a})})}_handleMouseMove(e){let t,n,r;const o=this.findOne("."+this._movingAnchorName),i=o.getStage();i.setPointersPositions(e);const s=i.getPointerPosition();let a={x:s.x-this._anchorDragOffset.x,y:s.y-this._anchorDragOffset.y};const l=o.getAbsolutePosition();this.anchorDragBoundFunc()&&(a=this.anchorDragBoundFunc()(l,a,e)),o.setAbsolutePosition(a);const u=o.getAbsolutePosition();if(l.x===u.x&&l.y===u.y)return;if(this._movingAnchorName==="rotater"){const w=this._getNodeRect();t=o.x()-w.width/2,n=-o.y()+w.height/2;const S=gt.getAngle(this.rotateAnchorAngle());let y=Math.atan2(-n,t)+Math.PI/2-S;w.height<0&&(y-=Math.PI);const C=gt.getAngle(this.rotation())+y,T=gt.getAngle(this.rotationSnapTolerance()),R=$O(w,eF(this.rotationSnaps(),C,T)-w.rotation);this._fitNodesInto(R,e);return}const c=this.shiftBehavior();let d;c==="inverted"?d=this.keepRatio()&&!e.shiftKey:c==="none"?d=this.keepRatio():d=this.keepRatio()||e.shiftKey;let h=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(w.x-o.x(),2)+Math.pow(w.y-o.y(),2));const S=this.findOne(".top-left").x()>w.x?-1:1,y=this.findOne(".top-left").y()>w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,this.findOne(".top-left").x(w.x-t),this.findOne(".top-left").y(w.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(o.y());else if(this._movingAnchorName==="top-right"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(o.x()-w.x,2)+Math.pow(w.y-o.y(),2));const S=this.findOne(".top-right").x()<w.x?-1:1,y=this.findOne(".top-right").y()>w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,this.findOne(".top-right").x(w.x+t),this.findOne(".top-right").y(w.y-n)}var m=o.position();this.findOne(".top-left").y(m.y),this.findOne(".bottom-right").x(m.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(o.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(o.x());else if(this._movingAnchorName==="bottom-left"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(w.x-o.x(),2)+Math.pow(o.y()-w.y,2));const S=w.x<o.x()?-1:1,y=o.y()<w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,o.x(w.x-t),o.y(w.y+n)}m=o.position(),this.findOne(".top-left").x(m.x),this.findOne(".bottom-right").y(m.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(o.y());else if(this._movingAnchorName==="bottom-right"){if(d){const w=h?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(o.x()-w.x,2)+Math.pow(o.y()-w.y,2));const S=this.findOne(".bottom-right").x()<w.x?-1:1,y=this.findOne(".bottom-right").y()<w.y?-1:1;t=r*this.cos*S,n=r*this.sin*y,this.findOne(".bottom-right").x(w.x+t),this.findOne(".bottom-right").y(w.y+n)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(h=this.centeredScaling()||e.altKey,h){const w=this.findOne(".top-left"),S=this.findOne(".bottom-right"),y=w.x(),C=w.y(),T=this.getWidth()-S.x(),R=this.getHeight()-S.y();S.move({x:-y,y:-C}),w.move({x:T,y:R})}const p=this.findOne(".top-left").getAbsolutePosition();t=p.x,n=p.y;const g=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),k=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:n,width:g,height:k,rotation:gt.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const n=this.getNode();T0--,this._fire("transformend",{evt:e,target:n}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),n&&this._nodes.forEach(r=>{var o;r._fire("transformend",{evt:e,target:r}),(o=r.getLayer())===null||o===void 0||o.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const n=this._getNodeRect(),r=1;if(Ae._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(Ae._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const o=new Ui;if(o.rotate(gt.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const d=o.point({x:-this.padding()*2,y:0});e.x+=d.x,e.y+=d.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const d=o.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const d=o.point({x:0,y:-this.padding()*2});e.x+=d.x,e.y+=d.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const d=o.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const d=this.boundBoxFunc()(n,e);d?e=d:Ae.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const i=1e7,s=new Ui;s.translate(n.x,n.y),s.rotate(n.rotation),s.scale(n.width/i,n.height/i);const a=new Ui,l=e.width/i,u=e.height/i;this.flipEnabled()===!1?(a.translate(e.x,e.y),a.rotate(e.rotation),a.translate(e.width<0?e.width:0,e.height<0?e.height:0),a.scale(Math.abs(l),Math.abs(u))):(a.translate(e.x,e.y),a.rotate(e.rotation),a.scale(l,u));const c=a.multiply(s.invert());this._nodes.forEach(d=>{var h;if(!d.getStage())return;const m=d.getParent().getAbsoluteTransform(),p=d.getTransform().copy();p.translate(d.offsetX(),d.offsetY());const g=new Ui;g.multiply(m.copy().invert()).multiply(c).multiply(m).multiply(p);const k=g.decompose();d.setAttrs(k),(h=d.getLayer())===null||h===void 0||h.batchDraw()}),this.rotation(Ae._getRotation(e.rotation)),this._nodes.forEach(d=>{this._fire("transform",{evt:t,target:d}),d._fire("transform",{evt:t,target:d})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(Ae._getRotation(t.rotation));const n=t.width,r=t.height,o=this.enabledAnchors(),i=this.resizeEnabled(),s=this.padding(),a=this.anchorSize(),l=this.find("._anchor");l.forEach(T=>{T.setAttrs({width:a,height:a,offsetX:a/2,offsetY:a/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:a/2+s,offsetY:a/2+s,visible:i&&o.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:a/2+s,visible:i&&o.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:a/2-s,offsetY:a/2+s,visible:i&&o.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:a/2+s,visible:i&&o.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:r/2,offsetX:a/2-s,visible:i&&o.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:a/2+s,offsetY:a/2-s,visible:i&&o.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:r,offsetY:a/2-s,visible:i&&o.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:r,offsetX:a/2-s,offsetY:a/2-s,visible:i&&o.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),c=this.rotateAnchorOffset(),d=Ae.degToRad(u),h=Math.sin(d),m=-Math.cos(d),p=n/2,g=r/2;let k=1/0;m<0?k=Math.min(k,-g/m):m>0&&(k=Math.min(k,(r-g)/m)),h<0?k=Math.min(k,-p/h):h>0&&(k=Math.min(k,(n-p)/h));const w=p+h*k,S=g+m*k,y=Ae._sign(r);this._batchChangeChild(".rotater",{x:w+h*c*y,y:S+m*c*y-s*m,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(T=>T.draggable()),x:0,y:0});const C=this.anchorStyleFunc();C&&l.forEach(T=>{C(T)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),lu.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...e){return this._elementsCreated?(Ae.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...e)}toObject(){return yt.prototype.toObject.call(this)}clone(e){return yt.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};kn.isTransforming=()=>T0>0;function tF(e){return e instanceof Array||Ae.warn("enabledAnchors value should be an array"),e instanceof Array&&e.forEach(function(t){Up.indexOf(t)===-1&&Ae.warn("Unknown anchor name: "+t+". Available names are: "+Up.join(", "))}),e||[]}kn.prototype.className="Transformer",vr(kn),ce.addGetterSetter(kn,"enabledAnchors",Up,tF),ce.addGetterSetter(kn,"flipEnabled",!0,Vi()),ce.addGetterSetter(kn,"resizeEnabled",!0),ce.addGetterSetter(kn,"anchorSize",10,dt()),ce.addGetterSetter(kn,"rotateEnabled",!0),ce.addGetterSetter(kn,"rotateLineVisible",!0),ce.addGetterSetter(kn,"rotationSnaps",[]),ce.addGetterSetter(kn,"rotateAnchorOffset",50,dt()),ce.addGetterSetter(kn,"rotateAnchorAngle",0,dt()),ce.addGetterSetter(kn,"rotateAnchorCursor","crosshair"),ce.addGetterSetter(kn,"rotationSnapTolerance",5,dt()),ce.addGetterSetter(kn,"borderEnabled",!0),ce.addGetterSetter(kn,"anchorStroke","rgb(0, 161, 255)"),ce.addGetterSetter(kn,"anchorStrokeWidth",1,dt()),ce.addGetterSetter(kn,"anchorFill","white"),ce.addGetterSetter(kn,"anchorCornerRadius",0,dt()),ce.addGetterSetter(kn,"borderStroke","rgb(0, 161, 255)"),ce.addGetterSetter(kn,"borderStrokeWidth",1,dt()),ce.addGetterSetter(kn,"borderDash"),ce.addGetterSetter(kn,"keepRatio",!0),ce.addGetterSetter(kn,"shiftBehavior","default"),ce.addGetterSetter(kn,"centeredScaling",!1),ce.addGetterSetter(kn,"ignoreStroke",!1),ce.addGetterSetter(kn,"padding",0,dt()),ce.addGetterSetter(kn,"nodes"),ce.addGetterSetter(kn,"node"),ce.addGetterSetter(kn,"boundBoxFunc"),ce.addGetterSetter(kn,"anchorDragBoundFunc"),ce.addGetterSetter(kn,"anchorStyleFunc"),ce.addGetterSetter(kn,"shouldOverdrawWholeArea",!1),ce.addGetterSetter(kn,"useSingleNodeRotation",!0),ce.backCompat(kn,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var ma=class extends ct{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,gt.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}};ma.prototype.className="Wedge",ma.prototype._centroid=!0,ma.prototype._attrsAffectingSize=["radius"],vr(ma),ce.addGetterSetter(ma,"radius",0,dt()),ce.addGetterSetter(ma,"angle",0,dt()),ce.addGetterSetter(ma,"clockwise",!1),ce.backCompat(ma,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function uk(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}var nF=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],rF=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function oF(e,t){const n=e.data,r=e.width,o=e.height;let i,s,a,l,u,c,d,h,m,p,g,k,w,S,y,C,T,R,M,H;const B=t+t+1,z=r-1,Z=o-1,P=t+1,N=P*(P+1)/2,I=new uk,L=nF[t],X=rF[t];let te=null,le=I,fe=null,Fe=null;for(let he=1;he<B;he++)le=le.next=new uk,he===P&&(te=le);le.next=I,a=s=0;for(let he=0;he<o;he++){k=w=S=y=l=u=c=d=0,h=P*(C=n[s]),m=P*(T=n[s+1]),p=P*(R=n[s+2]),g=P*(M=n[s+3]),l+=N*C,u+=N*T,c+=N*R,d+=N*M,le=I;for(let ge=0;ge<P;ge++)le.r=C,le.g=T,le.b=R,le.a=M,le=le.next;for(let ge=1;ge<P;ge++)i=s+((z<ge?z:ge)<<2),l+=(le.r=C=n[i])*(H=P-ge),u+=(le.g=T=n[i+1])*H,c+=(le.b=R=n[i+2])*H,d+=(le.a=M=n[i+3])*H,k+=C,w+=T,S+=R,y+=M,le=le.next;fe=I,Fe=te;for(let ge=0;ge<r;ge++)n[s+3]=M=d*L>>X,M!==0?(M=255/M,n[s]=(l*L>>X)*M,n[s+1]=(u*L>>X)*M,n[s+2]=(c*L>>X)*M):n[s]=n[s+1]=n[s+2]=0,l-=h,u-=m,c-=p,d-=g,h-=fe.r,m-=fe.g,p-=fe.b,g-=fe.a,i=a+((i=ge+t+1)<z?i:z)<<2,k+=fe.r=n[i],w+=fe.g=n[i+1],S+=fe.b=n[i+2],y+=fe.a=n[i+3],l+=k,u+=w,c+=S,d+=y,fe=fe.next,h+=C=Fe.r,m+=T=Fe.g,p+=R=Fe.b,g+=M=Fe.a,k-=C,w-=T,S-=R,y-=M,Fe=Fe.next,s+=4;a+=r}for(let he=0;he<r;he++){w=S=y=k=u=c=d=l=0,s=he<<2,h=P*(C=n[s]),m=P*(T=n[s+1]),p=P*(R=n[s+2]),g=P*(M=n[s+3]),l+=N*C,u+=N*T,c+=N*R,d+=N*M,le=I;for(let ae=0;ae<P;ae++)le.r=C,le.g=T,le.b=R,le.a=M,le=le.next;let ge=r;for(let ae=1;ae<=t;ae++)s=ge+he<<2,l+=(le.r=C=n[s])*(H=P-ae),u+=(le.g=T=n[s+1])*H,c+=(le.b=R=n[s+2])*H,d+=(le.a=M=n[s+3])*H,k+=C,w+=T,S+=R,y+=M,le=le.next,ae<Z&&(ge+=r);s=he,fe=I,Fe=te;for(let ae=0;ae<o;ae++)i=s<<2,n[i+3]=M=d*L>>X,M>0?(M=255/M,n[i]=(l*L>>X)*M,n[i+1]=(u*L>>X)*M,n[i+2]=(c*L>>X)*M):n[i]=n[i+1]=n[i+2]=0,l-=h,u-=m,c-=p,d-=g,h-=fe.r,m-=fe.g,p-=fe.b,g-=fe.a,i=he+((i=ae+P)<Z?i:Z)*r<<2,l+=k+=fe.r=n[i],u+=w+=fe.g=n[i+1],c+=S+=fe.b=n[i+2],d+=y+=fe.a=n[i+3],fe=fe.next,h+=C=Fe.r,m+=T=Fe.g,p+=R=Fe.b,g+=M=Fe.a,k-=C,w-=T,S-=R,y-=M,Fe=Fe.next,s+=r}}const iF=function(t){const n=Math.round(this.blurRadius());n>0&&oF(t,n)};ce.addGetterSetter(yt,"blurRadius",0,dt(),ce.afterSetFilter);const sF=function(e){const t=this.brightness()*255,n=e.data,r=n.length;for(let o=0;o<r;o+=4)n[o]+=t,n[o+1]+=t,n[o+2]+=t};ce.addGetterSetter(yt,"brightness",0,dt(),ce.afterSetFilter);const aF=function(e){const t=this.brightness(),n=e.data,r=n.length;for(let o=0;o<r;o+=4)n[o]=Math.min(255,n[o]*t),n[o+1]=Math.min(255,n[o+1]*t),n[o+2]=Math.min(255,n[o+2]*t)},lF=function(e){const t=Math.pow((this.contrast()+100)/100,2),n=e.data,r=n.length;let o=150,i=150,s=150;for(let a=0;a<r;a+=4)o=n[a],i=n[a+1],s=n[a+2],o/=255,o-=.5,o*=t,o+=.5,o*=255,i/=255,i-=.5,i*=t,i+=.5,i*=255,s/=255,s-=.5,s*=t,s+=.5,s*=255,o=o<0?0:o>255?255:o,i=i<0?0:i>255?255:i,s=s<0?0:s>255?255:s,n[a]=o,n[a+1]=i,n[a+2]=s};ce.addGetterSetter(yt,"contrast",0,dt(),ce.afterSetFilter);const cF=function(e){var t,n,r,o,i,s,a,l,u;const c=e.data,d=e.width,h=e.height,m=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),p=Math.min(1,Math.max(0,(o=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&o!==void 0?o:.5)),g=(a={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(s=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&s!==void 0?s:"top-left"])!==null&&a!==void 0?a:315,k=!!((u=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&u!==void 0&&u),w=m*10,S=p*255,y=g*Math.PI/180,C=Math.cos(y),T=Math.sin(y),R=128/1020*w,M=new Uint8ClampedArray(c),H=new Float32Array(d*h);for(let N=0,I=0;I<c.length;I+=4,N++)H[N]=.2126*M[I]+.7152*M[I+1]+.0722*M[I+2];const B=[-1,0,1,-2,0,2,-1,0,1],z=[-1,-2,-1,0,0,0,1,2,1],Z=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],P=N=>N<0?0:N>255?255:N;for(let N=1;N<h-1;N++)for(let I=1;I<d-1;I++){const L=N*d+I;let X=0,te=0;X+=H[L+Z[0]]*B[0],te+=H[L+Z[0]]*z[0],X+=H[L+Z[1]]*B[1],te+=H[L+Z[1]]*z[1],X+=H[L+Z[2]]*B[2],te+=H[L+Z[2]]*z[2],X+=H[L+Z[3]]*B[3],te+=H[L+Z[3]]*z[3],X+=H[L+Z[5]]*B[5],te+=H[L+Z[5]]*z[5],X+=H[L+Z[6]]*B[6],te+=H[L+Z[6]]*z[6],X+=H[L+Z[7]]*B[7],te+=H[L+Z[7]]*z[7],X+=H[L+Z[8]]*B[8],te+=H[L+Z[8]]*z[8];const le=P(S+(C*X+T*te)*R),fe=L*4;if(k){const Fe=le-S;c[fe]=P(M[fe]+Fe),c[fe+1]=P(M[fe+1]+Fe),c[fe+2]=P(M[fe+2]+Fe),c[fe+3]=M[fe+3]}else c[fe]=c[fe+1]=c[fe+2]=le,c[fe+3]=M[fe+3]}for(let N=0;N<d;N++){let I=N*4,L=((h-1)*d+N)*4;c[I]=M[I],c[I+1]=M[I+1],c[I+2]=M[I+2],c[I+3]=M[I+3],c[L]=M[L],c[L+1]=M[L+1],c[L+2]=M[L+2],c[L+3]=M[L+3]}for(let N=1;N<h-1;N++){let I=N*d*4,L=(N*d+(d-1))*4;c[I]=M[I],c[I+1]=M[I+1],c[I+2]=M[I+2],c[I+3]=M[I+3],c[L]=M[L],c[L+1]=M[L+1],c[L+2]=M[L+2],c[L+3]=M[L+3]}return e};ce.addGetterSetter(yt,"embossStrength",.5,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"embossWhiteLevel",.5,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"embossDirection","top-left",void 0,ce.afterSetFilter),ce.addGetterSetter(yt,"embossBlend",!1,void 0,ce.afterSetFilter);function R0(e,t,n,r,o){const i=n-t,s=o-r;if(i===0)return r+s/2;if(s===0)return r;let a=(e-t)/i;return a=s*a+r,a}const uF=function(e){const t=e.data,n=t.length;let r=t[0],o=r,i,s=t[1],a=s,l,u=t[2],c=u,d;const h=this.enhance();if(h===0)return;for(let y=0;y<n;y+=4)i=t[y+0],i<r?r=i:i>o&&(o=i),l=t[y+1],l<s?s=l:l>a&&(a=l),d=t[y+2],d<u?u=d:d>c&&(c=d);o===r&&(o=255,r=0),a===s&&(a=255,s=0),c===u&&(c=255,u=0);let m,p,g,k,w,S;if(h>0)m=o+h*(255-o),p=r-h*(r-0),g=a+h*(255-a),k=s-h*(s-0),w=c+h*(255-c),S=u-h*(u-0);else{const y=(o+r)*.5;m=o+h*(o-y),p=r+h*(r-y);const C=(a+s)*.5;g=a+h*(a-C),k=s+h*(s-C);const T=(c+u)*.5;w=c+h*(c-T),S=u+h*(u-T)}for(let y=0;y<n;y+=4)t[y+0]=R0(t[y+0],r,o,p,m),t[y+1]=R0(t[y+1],s,a,k,g),t[y+2]=R0(t[y+2],u,c,S,w)};ce.addGetterSetter(yt,"enhance",0,dt(),ce.afterSetFilter);const dF=function(e){const t=e.data,n=t.length;for(let r=0;r<n;r+=4){const o=.34*t[r]+.5*t[r+1]+.16*t[r+2];t[r]=o,t[r+1]=o,t[r+2]=o}};ce.addGetterSetter(yt,"hue",0,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"saturation",0,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"luminance",0,dt(),ce.afterSetFilter);const fF=function(e){const t=e.data,n=t.length,r=1,o=Math.pow(2,this.saturation()),i=Math.abs(this.hue()+360)%360,s=this.luminance()*127,a=r*o*Math.cos(i*Math.PI/180),l=r*o*Math.sin(i*Math.PI/180),u=.299*r+.701*a+.167*l,c=.587*r-.587*a+.33*l,d=.114*r-.114*a-.497*l,h=.299*r-.299*a-.328*l,m=.587*r+.413*a+.035*l,p=.114*r-.114*a+.293*l,g=.299*r-.3*a+1.25*l,k=.587*r-.586*a-1.05*l,w=.114*r+.886*a-.2*l;let S,y,C,T;for(let R=0;R<n;R+=4)S=t[R+0],y=t[R+1],C=t[R+2],T=t[R+3],t[R+0]=u*S+c*y+d*C+s,t[R+1]=h*S+m*y+p*C+s,t[R+2]=g*S+k*y+w*C+s,t[R+3]=T},hF=function(e){const t=e.data,n=t.length,r=Math.pow(2,this.value()),o=Math.pow(2,this.saturation()),i=Math.abs(this.hue()+360)%360,s=r*o*Math.cos(i*Math.PI/180),a=r*o*Math.sin(i*Math.PI/180),l=.299*r+.701*s+.167*a,u=.587*r-.587*s+.33*a,c=.114*r-.114*s-.497*a,d=.299*r-.299*s-.328*a,h=.587*r+.413*s+.035*a,m=.114*r-.114*s+.293*a,p=.299*r-.3*s+1.25*a,g=.587*r-.586*s-1.05*a,k=.114*r+.886*s-.2*a;for(let w=0;w<n;w+=4){const S=t[w+0],y=t[w+1],C=t[w+2],T=t[w+3];t[w+0]=l*S+u*y+c*C,t[w+1]=d*S+h*y+m*C,t[w+2]=p*S+g*y+k*C,t[w+3]=T}};ce.addGetterSetter(yt,"hue",0,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"saturation",0,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"value",0,dt(),ce.afterSetFilter);const pF=function(e){const t=e.data,n=t.length;for(let r=0;r<n;r+=4)t[r]=255-t[r],t[r+1]=255-t[r+1],t[r+2]=255-t[r+2]};var mF=function(e,t,n){const r=e.data,o=t.data,i=e.width,s=e.height,a=n.polarCenterX||i/2,l=n.polarCenterY||s/2;let u=Math.sqrt(a*a+l*l),c=i-a,d=s-l;const h=Math.sqrt(c*c+d*d);u=h>u?h:u;const m=s,p=i,g=360/p*Math.PI/180;for(let k=0;k<p;k+=1){const w=Math.sin(k*g),S=Math.cos(k*g);for(let y=0;y<m;y+=1){c=Math.floor(a+u*y/m*S),d=Math.floor(l+u*y/m*w);let C=(d*i+c)*4;const T=r[C+0],R=r[C+1],M=r[C+2],H=r[C+3];C=(k+y*i)*4,o[C+0]=T,o[C+1]=R,o[C+2]=M,o[C+3]=H}}},gF=function(e,t,n){const r=e.data,o=t.data,i=e.width,s=e.height,a=n.polarCenterX||i/2,l=n.polarCenterY||s/2;let u=Math.sqrt(a*a+l*l),c=i-a,d=s-l;const h=Math.sqrt(c*c+d*d);u=h>u?h:u;const m=s,p=i,g=n.polarRotation||0;let k,w;for(c=0;c<i;c+=1)for(d=0;d<s;d+=1){const S=c-a,y=d-l,C=Math.sqrt(S*S+y*y)*m/u;let T=(Math.atan2(y,S)*180/Math.PI+360+g)%360;T=T*p/360,k=Math.floor(T),w=Math.floor(C);let R=(w*i+k)*4;const M=r[R+0],H=r[R+1],B=r[R+2],z=r[R+3];R=(d*i+c)*4,o[R+0]=M,o[R+1]=H,o[R+2]=B,o[R+3]=z}};const vF=function(e){const t=e.width,n=e.height;let r,o,i,s,a,l,u,c,d,h,m=Math.round(this.kaleidoscopePower());const p=Math.round(this.kaleidoscopeAngle()),g=Math.floor(t*(p%360)/360);if(m<1)return;const k=Ae.createCanvasElement();k.width=t,k.height=n;const w=k.getContext("2d").getImageData(0,0,t,n);Ae.releaseCanvas(k),mF(e,w,{polarCenterX:t/2,polarCenterY:n/2});let S=t/Math.pow(2,m);for(;S<=8;)S=S*2,m-=1;S=Math.ceil(S);let y=S,C=0,T=y,R=1;for(g+S>t&&(C=y,T=0,R=-1),o=0;o<n;o+=1)for(r=C;r!==T;r+=R)i=Math.round(r+g)%t,d=(t*o+i)*4,a=w.data[d+0],l=w.data[d+1],u=w.data[d+2],c=w.data[d+3],h=(t*o+r)*4,w.data[h+0]=a,w.data[h+1]=l,w.data[h+2]=u,w.data[h+3]=c;for(o=0;o<n;o+=1)for(y=Math.floor(S),s=0;s<m;s+=1){for(r=0;r<y+1;r+=1)d=(t*o+r)*4,a=w.data[d+0],l=w.data[d+1],u=w.data[d+2],c=w.data[d+3],h=(t*o+y*2-r-1)*4,w.data[h+0]=a,w.data[h+1]=l,w.data[h+2]=u,w.data[h+3]=c;y*=2}gF(w,e,{polarRotation:0})};ce.addGetterSetter(yt,"kaleidoscopePower",2,dt(),ce.afterSetFilter),ce.addGetterSetter(yt,"kaleidoscopeAngle",0,dt(),ce.afterSetFilter);function Vp(e,t,n){let r=(n*e.width+t)*4;const o=[];return o.push(e.data[r++],e.data[r++],e.data[r++],e.data[r++]),o}function _f(e,t){return Math.sqrt(Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2)+Math.pow(e[2]-t[2],2))}function yF(e){const t=[0,0,0];for(let n=0;n<e.length;n++)t[0]+=e[n][0],t[1]+=e[n][1],t[2]+=e[n][2];return t[0]/=e.length,t[1]/=e.length,t[2]/=e.length,t}function bF(e,t){const n=Vp(e,0,0),r=Vp(e,e.width-1,0),o=Vp(e,0,e.height-1),i=Vp(e,e.width-1,e.height-1),s=t||10;if(_f(n,r)<s&&_f(r,i)<s&&_f(i,o)<s&&_f(o,n)<s){const a=yF([r,n,i,o]),l=[];for(let u=0;u<e.width*e.height;u++)l[u]=_f(a,[e.data[u*4],e.data[u*4+1],e.data[u*4+2]])<s?0:255;return l}}function wF(e,t){for(let n=0;n<e.width*e.height;n++)e.data[4*n+3]=t[n]}function CF(e,t,n){const r=[1,1,1,1,0,1,1,1,1],o=Math.round(Math.sqrt(r.length)),i=Math.floor(o/2),s=[];for(let a=0;a<n;a++)for(let l=0;l<t;l++){const u=a*t+l;let c=0;for(let d=0;d<o;d++)for(let h=0;h<o;h++){const m=a+d-i,p=l+h-i;if(m>=0&&m<n&&p>=0&&p<t){const g=m*t+p,k=r[d*o+h];c+=e[g]*k}}s[u]=c===2040?255:0}return s}function _F(e,t,n){const r=[1,1,1,1,1,1,1,1,1],o=Math.round(Math.sqrt(r.length)),i=Math.floor(o/2),s=[];for(let a=0;a<n;a++)for(let l=0;l<t;l++){const u=a*t+l;let c=0;for(let d=0;d<o;d++)for(let h=0;h<o;h++){const m=a+d-i,p=l+h-i;if(m>=0&&m<n&&p>=0&&p<t){const g=m*t+p,k=r[d*o+h];c+=e[g]*k}}s[u]=c>=1020?255:0}return s}function SF(e,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],o=Math.round(Math.sqrt(r.length)),i=Math.floor(o/2),s=[];for(let a=0;a<n;a++)for(let l=0;l<t;l++){const u=a*t+l;let c=0;for(let d=0;d<o;d++)for(let h=0;h<o;h++){const m=a+d-i,p=l+h-i;if(m>=0&&m<n&&p>=0&&p<t){const g=m*t+p,k=r[d*o+h];c+=e[g]*k}}s[u]=c}return s}const kF=function(e){let t=bF(e,this.threshold());return t&&(t=CF(t,e.width,e.height),t=_F(t,e.width,e.height),t=SF(t,e.width,e.height),wF(e,t)),e};ce.addGetterSetter(yt,"threshold",0,dt(),ce.afterSetFilter);const AF=function(e){const t=this.noise()*255,n=e.data,r=n.length,o=t/2;for(let i=0;i<r;i+=4)n[i+0]+=o-2*o*Math.random(),n[i+1]+=o-2*o*Math.random(),n[i+2]+=o-2*o*Math.random()};ce.addGetterSetter(yt,"noise",.2,dt(),ce.afterSetFilter);const IF=function(e){let t=Math.ceil(this.pixelSize()),n=e.width,r=e.height,o=Math.ceil(n/t),i=Math.ceil(r/t),s=e.data;if(t<=0){Ae.error("pixelSize value can not be <= 0");return}for(let a=0;a<o;a+=1)for(let l=0;l<i;l+=1){let u=0,c=0,d=0,h=0;const m=a*t,p=m+t,g=l*t,k=g+t;let w=0;for(let S=m;S<p;S+=1)if(!(S>=n))for(let y=g;y<k;y+=1){if(y>=r)continue;const C=(n*y+S)*4;u+=s[C+0],c+=s[C+1],d+=s[C+2],h+=s[C+3],w+=1}u=u/w,c=c/w,d=d/w,h=h/w;for(let S=m;S<p;S+=1)if(!(S>=n))for(let y=g;y<k;y+=1){if(y>=r)continue;const C=(n*y+S)*4;s[C+0]=u,s[C+1]=c,s[C+2]=d,s[C+3]=h}}};ce.addGetterSetter(yt,"pixelSize",8,dt(),ce.afterSetFilter);const EF=function(e){const t=Math.round(this.levels()*254)+1,n=e.data,r=n.length,o=255/t;for(let i=0;i<r;i+=1)n[i]=Math.floor(n[i]/o)*o};ce.addGetterSetter(yt,"levels",.5,dt(),ce.afterSetFilter);const xF=function(e){const t=e.data,n=t.length,r=this.red(),o=this.green(),i=this.blue();for(let s=0;s<n;s+=4){const a=(.34*t[s]+.5*t[s+1]+.16*t[s+2])/255;t[s]=a*r,t[s+1]=a*o,t[s+2]=a*i,t[s+3]=t[s+3]}};ce.addGetterSetter(yt,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"blue",0,u4,ce.afterSetFilter);const TF=function(e){const t=e.data,n=t.length,r=this.red(),o=this.green(),i=this.blue(),s=this.alpha();for(let a=0;a<n;a+=4){const l=1-s;t[a]=r*s+t[a]*l,t[a+1]=o*s+t[a+1]*l,t[a+2]=i*s+t[a+2]*l}};ce.addGetterSetter(yt,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ce.addGetterSetter(yt,"blue",0,u4,ce.afterSetFilter),ce.addGetterSetter(yt,"alpha",1,function(e){return this._filterUpToDate=!1,e>1?1:e<0?0:e});const RF=function(e){const t=e.data,n=t.length;for(let r=0;r<n;r+=4){const o=t[r+0],i=t[r+1],s=t[r+2];t[r+0]=Math.min(255,o*.393+i*.769+s*.189),t[r+1]=Math.min(255,o*.349+i*.686+s*.168),t[r+2]=Math.min(255,o*.272+i*.534+s*.131)}},MF=function(e){const n=e.data;for(let r=0;r<n.length;r+=4){const o=n[r],i=n[r+1],s=n[r+2];.2126*o+.7152*i+.0722*s>=128&&(n[r]=255-o,n[r+1]=255-i,n[r+2]=255-s)}return e},LF=function(e){const t=this.threshold()*255,n=e.data,r=n.length;for(let o=0;o<r;o+=1)n[o]=n[o]<t?0:255};ce.addGetterSetter(yt,"threshold",.5,dt(),ce.afterSetFilter);var DF=U4.Util._assign(U4,{Arc:ha,Arrow:Xl,Circle:uu,Ellipse:Ja,Image:ji,Label:I0,Tag:Ql,Line:pa,Path:Ii,Rect:bf,RegularPolygon:$a,Ring:Zl,Sprite:ys,Star:el,Text:nr,TextPath:Vr,Transformer:kn,Wedge:ma,Filters:{Blur:iF,Brightness:aF,Brighten:sF,Contrast:lF,Emboss:cF,Enhance:uF,Grayscale:dF,HSL:fF,HSV:hF,Invert:pF,Kaleidoscope:vF,Mask:kF,Noise:AF,Pixelate:IF,Posterize:EF,RGB:xF,RGBA:TF,Sepia:RF,Solarize:MF,Threshold:LF}});It();var PF=["dialog","floating"],dk=["top-right","top-left","bottom-right","bottom-left","top-center","bottom-center"];function OF(e){if(!e||typeof e!="object")throw new Error("SurfaceManager: request must be a non-null object.");if(!PF.includes(e.mode))throw new Error(`SurfaceManager: mode must be "dialog" or "floating", got "${e.mode}".`);const t="kind"in e&&e.kind!=null,n="component"in e&&e.component!=null,r="render"in e&&typeof e.render=="function";if(n&&r)throw new Error('SurfaceManager: request cannot provide both "component" and "render". Use one or the other.');if(!t&&!n&&!r)throw new Error('SurfaceManager: request must provide "kind" (intent-based) or "component"/"render" (direct-render).');if(e.mode==="floating"&&e.floating?.placement!=null&&!dk.includes(e.floating.placement))throw new Error(`SurfaceManager: floating.placement must be one of ${dk.join(", ")}, got "${e.floating.placement}".`)}var FF=class{activeDialog=Ur(null);activeFloating=Ur(null);#t=!1;#n=1;#e;constructor({getModuleConfig:e}){this.#e=e}open(e){if(this.#t)return this.#l(e);OF(e);const t=this.#u(e),{component:n,props:r,render:o}=this.#d(t);let i,s=!1;const a=new Promise(m=>{i=p=>s?!1:(s=!0,m(p),!0)});let l;const u=m=>{i({status:"submitted",data:m})&&this.#s(l)},c=m=>{i({status:"closed",reason:m})&&this.#s(l)};l={id:t.id,mode:t.mode,request:t,component:n,props:r,render:o,resolve:u,close:c,settle:m=>i(m),get settled(){return s}};const d=t.mode==="dialog"?"activeDialog":"activeFloating",h=this[d].value;return h&&!h.settled&&h.settle({status:"replaced",replacedBy:t.id}),this[d].value=l,{id:t.id,mode:t.mode,close:m=>this.#i(l,m),result:a}}close(e,t){if(e!=null){const o=this.#a(e);o&&this.#i(o,t);return}const n=this.activeDialog.value;if(n&&!n.settled){this.#i(n,t);return}const r=this.activeFloating.value;r&&!r.settled&&this.#i(r,t)}settleAll(e){for(const t of[this.activeDialog,this.activeFloating]){const n=t.value;n&&!n.settled&&n.settle(e),t.value=null}}destroy(){this.#t=!0,this.settleAll({status:"destroyed"})}#i(e,t){e.settled||(e.settle({status:"closed",reason:t}),this.#s(e))}#s(e){const t=e.mode==="dialog"?this.activeDialog:this.activeFloating;t.value===e&&(t.value=null)}#a(e){return this.activeDialog.value?.id===e?this.activeDialog.value:this.activeFloating.value?.id===e?this.activeFloating.value:null}#u(e){const t=e.id??`surface-${this.#n++}`,n=this.#e()??{},r=e.mode==="dialog"?n.dialog:n.floating,o=e.mode==="dialog"?{maxWidth:r?.maxWidth,...e.dialog}:e.dialog,i=e.mode==="floating"?{placement:r?.placement??"top-right",width:r?.width,maxWidth:r?.maxWidth,maxHeight:r?.maxHeight,autoFocus:r?.autoFocus??!0,closeOnOutsidePointerDown:r?.closeOnOutsidePointerDown??!1,...e.floating}:e.floating;return{...e,id:t,closeOnEscape:e.closeOnEscape??r?.closeOnEscape??!0,closeOnBackdrop:e.mode==="dialog"?e.closeOnBackdrop??r?.closeOnBackdrop??!0:!1,dialog:o,floating:i}}#d(e){if("component"in e&&e.component!=null)return{component:e.component,props:e.props};if("render"in e&&typeof e.render=="function")return{render:e.render};const t=this.#e()?.resolver;if(typeof t=="function"){const n=t(e);if(n!=null){if(n.type==="none")throw new Error(`SurfaceManager: resolver explicitly suppressed surface for kind "${e.kind}".`);if(n.type==="custom")return{component:n.component,props:n.props};if(n.type==="external")return{render:n.render}}}throw new Error(`SurfaceManager: no renderer resolved for kind "${e.kind}". Provide a resolver via surfaces.resolver, or use a direct-render request.`)}#l(e){return{id:e?.id??`surface-${this.#n++}`,mode:e?.mode??"dialog",close:()=>{},result:Promise.resolve({status:"destroyed"})}}},BF="https://docs.superdoc.dev/guides/migration/document-api",fk=new Set;function NF(e,t){fk.has(e)||(fk.add(e),console.warn(t))}var zF={state:"editor.state",view:"editor.view",schema:"editor.schema",commands:"editor.commands",chain:"editor.chain()",can:"editor.can()",dispatch:"editor.dispatch()"},hk=Symbol.for("superdoc:rawEditor"),pk=new WeakMap;function mk(e){return!e||e[hk]?e:new Proxy(e,{get(t,n){if(n===hk)return t;const r=zF[n];r&&NF(`deprecated:${String(n)}`,`[SuperDoc] ${r} is deprecated and will be removed in a future version. Use the Document API (editor.doc) instead. See ${BF}`);const o=Reflect.get(t,n,t);if(typeof o=="function"){let i=pk.get(t);return i||(i=new Map,pk.set(t,i)),i.has(n)||i.set(n,o.bind(t)),i.get(n)}return o}})}var gk=["review","original","final","off"],HF=["paired","independent"],vk=Symbol.for("@superdoc/trackChanges:normalized"),yk=new Set;function bk(e,t){yk.has(e)||(yk.add(e),console.warn(`[SuperDoc] ${e} is deprecated — use ${t} instead.`))}function wk(e,t,n){return typeof e=="boolean"?e:typeof t=="boolean"?t:n}function UF(e,t,n){return typeof e=="string"&&gk.includes(e)?e:typeof t=="string"&&gk.includes(t)?t:n}function VF(e){return typeof e=="string"&&HF.includes(e)?e:null}function Jl(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function jF(e){const t=e[vk]===!0;Jl(e.modules)||(e.modules={});const n=Jl(e.modules.trackChanges),r=Jl(e.trackChanges),o=Jl(e.layoutEngineOptions?.trackedChanges);t||(r&&bk("config.trackChanges","config.modules.trackChanges"),o&&bk("config.layoutEngineOptions.trackedChanges","config.modules.trackChanges"));const i=wk(n?.visible,r?.visible,!1),s=wk(n?.enabled,o?.enabled,!0),a=VF(n?.replacements)??"paired",l=Jl(n?.authorColors)?n.authorColors:void 0,u=Jl(n?.semanticColors)?n.semanticColors:void 0,c=e.documentMode==="viewing"?i?"review":"original":"review",d=UF(n?.mode,o?.mode,c),h={visible:i,mode:d,enabled:s,replacements:a};return l&&(h.authorColors=l),u&&(h.semanticColors=u),e.modules.trackChanges=h,e.trackChanges={visible:i},Jl(e.layoutEngineOptions)||(e.layoutEngineOptions={}),e.layoutEngineOptions.trackedChanges={mode:d,enabled:s},Object.defineProperty(e,vk,{value:!0,writable:!0,configurable:!0,enumerable:!1}),h}const M0=Object.freeze({id:null,name:"Default SuperDoc user",email:null});function GF(e){return!e||typeof e!="object"?{...M0}:{...M0,...e}}function Sf(...e){const t={};for(const n of e)if(!(typeof n!="object"||n===null))for(const[r,o]of Object.entries(n))o!==void 0&&(t[r]=o);return t}function Ck(...e){for(const t of e)if(t!==void 0)return t}var _k=Object.freeze({toolbar:!0,comments:!0,contextMenu:!0,search:!1,linkPopover:!1,ruler:!1,contentControls:!0}),WF=Object.freeze(["left","center","right"]),kj=Object.freeze(Object.keys(_k)),jp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Sk(e,t){const n=e?.[t];return n===!1?!1:n===void 0?_k[t]:!0}function KF(e,t){const n=e?.[t];return jp(n)?n:{}}function kk(e={}){const t=e.ui,n=t===!1,r=jp(t)?t:void 0,o=w=>!n&&Sk(r,w),i=w=>n?!1:r?.[w]===void 0?void 0:Sk(r,w),s=w=>n?{}:KF(r,w),a=n||i("ruler")===!1,l=s("toolbar"),u=e.modules?.toolbar,c=jp(u)?u:{},d=[l.groups,c.groups],h=d.find(jp),m=Ck(d.find(Array.isArray),c.toolbarGroups,e.toolbarGroups),p=Array.isArray(m)?m:null,g=(w,S)=>Object.prototype.hasOwnProperty.call(w,S),k=h&&p?Object.fromEntries([...p.filter(w=>g(h,w)),...Object.keys(h).filter(w=>!WF.includes(w))].map(w=>[w,h[w]])):h;return{enabled:!n,toolbar:{enabled:o("toolbar"),container:n?null:Ck(l.container,c.selector,e.toolbar)??null,options:n?{}:{...Sf(c,l),groups:k,toolbarGroups:m,icons:Sf(e.toolbarIcons,c.icons,l.icons),texts:Sf(e.toolbarTexts,c.texts,l.texts)}},comments:{enabled:i("comments")??(!n&&e.modules?.comments!==!1),options:s("comments")},contextMenu:{enabled:i("contextMenu")??(!n&&e.disableContextMenu!==!0),suppressed:n||i("contextMenu")===!1,options:s("contextMenu")},search:{enabled:i("search")??(!n&&!!e.modules?.surfaces?.findReplace),options:s("search")},linkPopover:{enabled:i("linkPopover")??(!n&&!!e.modules?.links?.popoverResolver),suppressed:n||i("linkPopover")===!1,options:s("linkPopover")},ruler:{enabled:i("ruler")??(!n&&!!e.rulers),suppressed:a,container:a?null:s("ruler").container??e.rulerContainer??null},contentControls:{enabled:i("contentControls")??(!n&&e.modules?.contentControls?.chrome!=="none"),options:s("contentControls")}}}var L0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ak(e={}){const t=L0(e.interaction)?e.interaction:{},n=L0(t.comments)?t.comments:{},r=L0(e.modules?.comments)?e.modules.comments:{};return{comments:{readOnly:(n.readOnly??r.readOnly??!1)===!0,allowResolve:(n.allowResolve??r.allowResolve??!0)!==!1}}}var Ik=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ek(e={}){const t=Ik(e.surfaces)?e.surfaces:{},n=Ik(e.modules?.surfaces)?e.modules.surfaces:{},r=t.resolver===void 0?n.resolver:t.resolver;return{resolver:typeof r=="function"?r:null,dialog:Sf(n.dialog,t.dialog),floating:Sf(n.floating,t.floating)}}var qF=class{#t=new Map;#n=new Map;#e=null;#i=new Set;register(e){if(this.#t.has(e.id))throw new Error(`EditorRuntimeRegistry: duplicate runtime id "${e.id}"`);const t=e.root,n=t?this.#n.get(t):void 0;if(n!==void 0&&n!==e.id)throw new Error(`EditorRuntimeRegistry: root element already registered to runtime "${n}"`);this.#t.set(e.id,e),t&&this.#n.set(t,e.id)}unregister(e){const t=this.#t.get(e);return t?(this.#t.delete(e),t.root&&this.#n.delete(t.root),this.#e===e&&(this.#e=null,this.#s({previousRuntimeId:e,nextRuntimeId:null,reason:"active-runtime-unregistered",legacyEditorProjection:null})),!0):!1}get(e){return this.#t.get(e)??null}getAll(){return Array.from(this.#t.values())}getAllByDocumentId(e){const t=[];for(const n of this.#t.values())n.documentId===e&&t.push(n);return t}getActive(){return this.#e===null?null:this.#t.get(this.#e)}getActiveId(){return this.#e}setActive(e,t){if(e!==null&&!this.#t.has(e))throw new Error(`EditorRuntimeRegistry: cannot activate unknown runtime "${e}"`);if(e===this.#e)return;const n=this.#e;this.#e=e;let r=null;e!==null&&(r=this.#t.get(e).getLegacyEditorProjection?.()??null),this.#s({previousRuntimeId:n,nextRuntimeId:e,reason:t,legacyEditorProjection:r})}resolveFromEventTarget(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;if(!t)return null;const n=t.closest(`[${_p}]`);if(!n)return null;const r=n.getAttribute(_p),o=r?this.get(r):null;return o&&o.root===n?o:null}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}clear(){this.#t.clear(),this.#n.clear(),this.#e=null,this.#i.clear()}#s(e){for(const t of Array.from(this.#i))try{t(e)}catch{}}};const at={notReady:"not-ready",documentApiUnavailable:"document-api-unavailable",documentReadonly:"document-readonly",selectionRequired:"selection-required",rangeSelectionRequired:"range-selection-required",contextUnavailable:"context-unavailable",geometryUnavailable:"geometry-unavailable",targetUnresolved:"target-unresolved",targetNotVisible:"target-not-visible",commandUnsupported:"command-unsupported",commandDeferred:"command-deferred",tableContextUnavailable:"table-context-unavailable",operationUnavailable:"operation-unavailable",bulkDecisionsDisabled:"bulk-decisions-disabled",hostCapabilityUnavailable:"host-capability-unavailable",historyEmpty:"history-empty",searchUnavailable:"search-unavailable",searchInvalidPattern:"search-invalid-pattern",replaceUnsupported:"replace-unsupported",contentControlLocked:"content-control-locked"},xk={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strikethrough",fontFamily:"font-family",fontSize:"font-size",setFontFamily:"setFontFamily",setFontSize:"setFontSize",undo:"undo",redo:"redo",acceptChange:"acceptChange",rejectChange:"rejectChange",acceptAllChanges:"acceptAllChanges",rejectAllChanges:"rejectAllChanges",bulletList:"bullet-list",numberedList:"numbered-list"};function Tk(e){const t=n=>typeof n=="string"?n.replace(/\s*pt$/i,"").trim():n;if(typeof e=="string")return t(e);if(e&&typeof e=="object"&&"value"in e){const n=e;return{...n,value:t(n.value)}}return e}function YF(e){const t=(n,r)=>!r&&n>0&&n<=5?n*100:n;if(typeof e=="string"){const n=e.includes("%"),r=Number.parseFloat(e.replace("%","").trim());return Number.isFinite(r)?t(r,n):e}return typeof e=="number"&&Number.isFinite(e)?t(e,!1):e}function XF(e){const t=e&&typeof e=="object"&&"value"in e?e.value:e;if(t==="in"||t==="cm")return t;if(typeof t=="string"){const n=t.trim().toLowerCase();if(n==="in"||n==="inch"||n==="inches")return"in";if(n==="cm"||n==="centimeter"||n==="centimeters"||n==="centimetre"||n==="centimetres")return"cm"}return t}function Rk(e){const t=n=>{if(n===null)return null;if(typeof n!="string")return n;const r=n.trim();return r===""?n:/^#[0-9a-fA-F]{6}$/.test(r)?r:/^[0-9a-fA-F]{6}$/.test(r)?`#${r}`:r};if(e&&typeof e=="object"&&"value"in e){const n=e;return{...n,value:t(n.value)}}return t(e)}function D0(e,t){if(e&&typeof e=="object"){const n=e;for(const r of t)if(r in n)return n[r]}return e}function QF(e){const t=D0(e,["alignment","value"]);if(typeof t!="string")return t;const n=t.trim().toLowerCase();return n==="justified"||n==="both"?"justify":n}function ZF(e){const t=D0(e,["line","lineHeight","value"]),n=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t.trim()):NaN;return!Number.isFinite(n)||n<=0?t:n<=10?Math.round(n*240):Math.round(n)}function JF(e){if(e&&typeof e=="object"&&"role"in e)return e;const t=D0(e,["styleId","value","style"]);return typeof t=="string"?t.trim():t}function $F(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e.mode;if(typeof t=="string")return t}return e}var eB=at.commandUnsupported,bs=at.tableContextUnavailable;const Mk=[{id:"bold",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.bold",activeMark:"bold",inline:{key:"bold",kind:"toggle"}},{id:"italic",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.italic",activeMark:"italic",inline:{key:"italic",kind:"toggle"}},{id:"underline",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.underline",activeMark:"underline",inline:{key:"underline",kind:"toggle"}},{id:"strikethrough",family:"inline marks",disposition:"routed",mutates:!0,docRoute:"format.strikethrough",activeMark:"strikethrough",inline:{key:"strike",kind:"toggle"}},{id:"font-family",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontFamily",aliases:["setFontFamily"],inline:{key:"fontFamily",kind:"value-string"}},{id:"font-size",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontSize",aliases:["setFontSize"],normalizePayload:Tk,inline:{key:"fontSize",kind:"value-number"}},{id:"setFontFamily",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontFamily",aliasOf:"font-family",inline:{key:"fontFamily",kind:"value-string"}},{id:"setFontSize",family:"fonts",disposition:"routed",mutates:!0,docRoute:"format.fontSize",aliasOf:"font-size",normalizePayload:Tk,inline:{key:"fontSize",kind:"value-number"}},{id:"undo",family:"history",disposition:"routed",mutates:!0,docRoute:"history.undo"},{id:"redo",family:"history",disposition:"routed",mutates:!0,docRoute:"history.redo"},{id:"acceptChange",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"accept",scope:"id"},aliases:["track-changes-accept-selection"]},{id:"rejectChange",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"reject",scope:"id"},aliases:["track-changes-reject-selection"]},{id:"acceptAllChanges",family:"tracked changes (bulk)",disposition:"routed",mutates:!0,trackDecision:{kind:"accept",scope:"all"}},{id:"rejectAllChanges",family:"tracked changes (bulk)",disposition:"routed",mutates:!0,trackDecision:{kind:"reject",scope:"all"}},{id:"track-changes-accept-selection",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"accept",scope:"id"},aliasOf:"acceptChange"},{id:"track-changes-reject-selection",family:"tracked changes",disposition:"routed",mutates:!0,trackDecision:{kind:"reject",scope:"id"},aliasOf:"rejectChange"},{id:"zoom",family:"zoom",disposition:"routed",mutates:!1,instanceRoute:"setZoom",valueFrom:"zoom",normalizePayload:YF},{id:"zoom-fit-width",family:"zoom",disposition:"routed",mutates:!1,instanceRoute:"setZoomMode",fixedArg:"fit-width",valueFrom:"zoom"},{id:"document-mode",family:"document",disposition:"routed",mutates:!1,instanceRoute:"setDocumentMode",valueFrom:"documentMode",normalizePayload:$F},{id:"measurement-unit",family:"measurement",disposition:"routed",mutates:!1,instanceRoute:"setMeasurementUnit",valueFrom:"measurementUnit",normalizePayload:XF},{id:"text-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.color",inline:{key:"color",kind:"value-string"},normalizePayload:Rk},{id:"highlight-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.highlight",inline:{key:"highlight",kind:"value-string"},normalizePayload:Rk},{id:"link",family:"links",disposition:"routed",mutates:!0,docRoute:"hyperlinks.wrap",activeMark:"link",link:{kind:"link"}},{id:"text-align",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setAlignment",blockParagraph:{kind:"alignment"},normalizePayload:QF},{id:"line-height",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setSpacing",blockParagraph:{kind:"spacing-line"},normalizePayload:ZF},{id:"linked-style",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"styles.paragraph.setStyle",blockParagraph:{kind:"style"},normalizePayload:JF},{id:"bullet-list",family:"lists",disposition:"routed",mutates:!0,docRoute:"lists.apply",list:{mode:"toggle-seed",seed:"bullet"}},{id:"numbered-list",family:"lists",disposition:"routed",mutates:!0,docRoute:"lists.apply",list:{mode:"toggle-seed",seed:"ordered"}},{id:"indent-increase",family:"lists/indent",disposition:"routed",mutates:!0,docRoute:"lists.indent",list:{mode:"indent"}},{id:"indent-decrease",family:"lists/indent",disposition:"routed",mutates:!0,docRoute:"lists.outdent",list:{mode:"outdent"}},{id:"direction-ltr",family:"direction",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setDirection",blockParagraph:{kind:"direction",fixedValue:"ltr"}},{id:"direction-rtl",family:"direction",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setDirection",blockParagraph:{kind:"direction",fixedValue:"rtl"}},{id:"clear-formatting",family:"formatting",disposition:"routed",mutates:!0,docRoute:"format.apply",inline:{key:"*",kind:"clear"}},{id:"image",family:"media",disposition:"routed",mutates:!0,docRoute:"create.image",create:{kind:"image"}},{id:"table-of-contents-insert",family:"TOC",disposition:"routed",mutates:!0,docRoute:"create.tableOfContents",create:{kind:"toc"}},{id:"table-insert",family:"tables",disposition:"routed",mutates:!0,docRoute:"create.table",create:{kind:"table"}},{id:"table-add-row-before",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertRow",table:{action:"insert-row-before",op:"insertRow"},reason:bs},{id:"table-add-row-after",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertRow",table:{action:"insert-row-after",op:"insertRow"},reason:bs},{id:"table-delete-row",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.deleteRow",table:{action:"delete-row",op:"deleteRow"},reason:bs},{id:"table-add-column-before",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertColumn",table:{action:"insert-column-before",op:"insertColumn"},reason:bs},{id:"table-add-column-after",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertColumn",table:{action:"insert-column-after",op:"insertColumn"},reason:bs},{id:"table-delete-column",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.deleteColumn",table:{action:"delete-column",op:"deleteColumn"},reason:bs},{id:"table-delete",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.delete",table:{action:"delete-table",op:"delete"},reason:bs},{id:"table-merge-cells",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.mergeCells",table:{action:"merge-cells",op:"mergeCells"},reason:bs},{id:"table-split-cell",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.splitCell",table:{action:"split-cell",op:"splitCell",requiresCell:!0},reason:bs},{id:"table-remove-borders",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.setBorders",table:{action:"remove-borders",op:"setBorders"},reason:bs},{id:"ruler",family:"UI chrome",disposition:"routed",mutates:!1,instanceRoute:"toggleRuler",valueFrom:"ruler"},{id:"formatting-marks",family:"UI chrome",disposition:"routed",mutates:!1,instanceRoute:"toggleFormattingMarks",valueFrom:"formattingMarks"},{id:"copy-format",family:"formatting",disposition:"routed",mutates:!1},{id:"table-fix",family:"tables",disposition:"unsupported",mutates:!0,reason:eB}];var tB=new Map(Mk.map(e=>[e.id,e]));const nB=Mk.map(e=>e.id);function fu(e){return tB.get(e)??null}var rB=["table-add-row-before","table-add-row-after","table-delete-row","table-add-column-before","table-add-column-after","table-delete-column","table-delete","table-merge-cells","table-split-cell","table-remove-borders"];const Lk=[{name:"bold",commandId:"bold",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"italic",commandId:"italic",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"underline",commandId:"underline",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"strike",commandId:"strikethrough",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"clearFormatting",commandId:"clear-formatting",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"copyFormat",commandId:"copy-format",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"fontFamily",commandId:"font-family",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"fontSize",commandId:"font-size",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"color",commandId:"text-color",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"highlight",commandId:"highlight-color",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"textAlign",commandId:"text-align",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"list",commandId:"bullet-list",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"numberedlist",commandId:"numbered-list",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"indentleft",commandId:"indent-decrease",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"indentright",commandId:"indent-increase",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"lineHeight",commandId:"line-height",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"linkedStyles",commandId:"linked-style",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"link",commandId:"link",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"image",commandId:"image",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"table",commandId:"table-insert",instanceMethod:null,disposition:"controller-routed",group:"center"},{name:"tableActions",commandId:null,instanceMethod:null,disposition:"shell-owned",group:"center",memberCommandIds:rB,note:"table editing dropdown is shell chrome; its member commands are controller-routed through the shared table-context facade (ui.tables / host.getTableContext()) and fail closed with table-context-unavailable when the caret is not in a table"},{name:"undo",commandId:"undo",instanceMethod:null,disposition:"controller-routed",group:"left"},{name:"redo",commandId:"redo",instanceMethod:null,disposition:"controller-routed",group:"left"},{name:"search",commandId:null,instanceMethod:null,disposition:"shell-owned",group:"right",note:"built-in search button; opens the shared find/replace surface (the same one Cmd/Ctrl+F opens) by emitting a `search:open` event on the SuperDoc instance, which the shell handles. The surface reads/drives the controller search surface (ui.search), backed by the single V2 host search session (host.search) which owns query, navigation, reveal, and replace. Find/navigation are always available when the host exposes search; replace/replaceAll mutate through the host session and fail closed (document-readonly) in viewing/read-only mode. If a runtime cannot expose search, the surface fails closed with search-unavailable"},{name:"zoom",commandId:"zoom",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"measurementUnit",commandId:"measurement-unit",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"ruler",commandId:null,instanceMethod:"toggleRuler",disposition:"host-routed",group:"right",note:"built-in shell toggles ruler visibility through the public SuperDoc.toggleRuler() instance method; the controller also routes the ruler command through it so custom UIs drive the same chrome (active state from config.rulers)"},{name:"formattingMarks",commandId:null,instanceMethod:"toggleFormattingMarks",disposition:"host-routed",group:"right",note:"built-in shell toggles nonprinting marks through the public SuperDoc.toggleFormattingMarks()/setShowFormattingMarks() instance methods (not a controller command)"},{name:"documentMode",commandId:"document-mode",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"acceptTrackedChangeBySelection",commandId:"track-changes-accept-selection",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"rejectTrackedChangeOnSelection",commandId:"track-changes-reject-selection",instanceMethod:null,disposition:"controller-routed",group:"right"},{name:"customButtons",commandId:null,instanceMethod:null,disposition:"shell-owned",group:"center",note:"consumer-defined buttons the rendered shell owns; their execution context surface is phase 2"}];var Dk=new Map(Lk.map(e=>[e.name,e]));const Aj=Lk.map(e=>e.name);function P0(e){return Dk.get(e)??null}function oB(e){const t=Dk.get(e);return t?.disposition==="controller-routed"?t.commandId:null}const iB=".png,.jpg,.jpeg,image/png,image/jpeg";var Pk=new Set(["image/png","image/jpeg","image/jpg"]),sB=/\.(png|jpe?g)$/i;function aB(e){if(!e)return!1;const t=typeof e.type=="string"?e.type.toLowerCase():"";return t?Pk.has(t):sB.test(String(e.name??""))}function Ok(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(lB(String(r.result),e)),r.onerror=()=>n(r.error??new Error("image-read-failed")),r.readAsDataURL(e)})}function lB(e,t){const n=/^data:([^;,]*);base64,/.exec(e);if(!n)return e;const r=n[1].toLowerCase();if(Pk.has(r))return e;const o=String(t?.name??""),i=/\.jpe?g$/i.test(o)?"image/jpeg":/\.png$/i.test(o)?"image/png":null;return i?`data:${i};base64,${e.slice(n[0].length)}`:e}async function cB(e,t){if(typeof t=="function"){const n=await t(e);if(typeof n!="string"||n.trim()==="")throw new Error("handleImageUpload returned an empty result");return n.startsWith("data:")?n:uB(n,e)}return Ok(e)}async function uB(e,t){const n=await fetch(e);if(!n.ok)throw new Error(`image fetch failed: ${n.status}`);const r=await n.blob(),o=(/\.(?:png|jpe?g)(?:$|[?#])/i.test(e)?e.split(/[?#]/)[0]:"")||t?.name||"";return Ok(o?Object.assign(r,{name:o}):r)}function dB({ownerDocument:e=document,onPick:t,onError:n}={}){const r=e.createElement("input");return r.type="file",r.accept=iB,r.hidden=!0,r.tabIndex=-1,r.setAttribute("data-superdoc-image-picker","true"),r.setAttribute("aria-hidden","true"),r.addEventListener("change",()=>{const o=r.files&&r.files[0];if(r.value="",!!o){if(!aB(o)){n?.(new Error(`unsupported image type: ${o.type||o.name}`));return}try{const i=t?.(o);i&&typeof i.then=="function"&&i.catch(s=>n?.(s))}catch(i){n?.(i)}}}),e.body?.appendChild(r),{input:r,open(){r.click()},destroy(){r.remove()}}}var fB=(e,t)=>{let n=e.replace(/[^0-9.]/g,"");return n=parseFloat(n),isNaN(n)&&(n=t),n=parseFloat(n),n},hB=(e,t,n)=>{let r,o,i,s=0;n||(n={});const a=()=>{s=n.leading===!1?0:Date.now(),r=null,i=e(...o),r||(o=null)},l=(...u)=>{const c=Date.now();!s&&n.leading===!1&&(s=c);const d=t-(c-s);return o=u,d<=0||d>t?(r&&(clearTimeout(r),r=null),s=c,i=e(...u),r||(o=null)):!r&&n.trailing!==!1&&(r=setTimeout(a,d)),i};return l.cancel=function(){clearTimeout(r),s=0,r=o=null},l};It(),gn();var pB={class:"sd-toolbar-icon"},mB=["innerHTML"],gB={__name:"ToolbarButtonIcon",props:{name:{type:String,required:!0},color:{type:String,default:null},icon:{type:String,default:null}},setup(e){const t=e,n=Se(()=>{if(t.name==="color")return{backgroundColor:t.color||"#111111"};if(t.name==="highlight")return{backgroundColor:t.color||"#D6D6D6"}}),r=Se(()=>["color","highlight"].includes(t.name));return(o,i)=>(me(),_e("div",pB,[Le("div",{class:en(["sd-toolbar-icon__icon",[`sd-toolbar-icon__icon--${t.name}`]]),innerHTML:e.icon},null,10,mB),r.value?(me(),_e("div",{key:0,class:"color-bar",style:vn(n.value)},null,4)):ut("",!0)]))}},Fk=hn(gB,[["__scopeId","data-v-d7d79424"]]);It(),gn();var vB=["role","aria-label"],yB=["data-item"],bB=["data-item"],wB={key:1,class:"sd-button-label"},CB=["data-item","aria-label"],_B=["innerHTML"],SB={key:2},kB=["onKeydown","id"],AB=["placeholder","onKeydown","id","data-item"],IB=["data-item","innerHTML"],EB={"aria-live":"polite",class:"sd-visually-hidden"},xB={__name:"ToolbarButton",props:{iconColor:{type:String,default:null},active:{type:Boolean,default:!1},isNarrow:{type:Boolean,default:!1},isWide:{type:Boolean,default:!1},toolbarItem:{type:Object,required:!0},defaultLabel:{type:String,default:null},isOverflowItem:{type:Boolean,default:!1},allowEnterPropagation:{type:Boolean,default:!1}},emits:["buttonClick","textSubmit","mainClick"],setup(e,{emit:t}){const n=t,{proxy:r}=sr(),o=e,{name:i,active:s,icon:a,label:l,hideLabel:u,iconColor:c,hasCaret:d,splitButton:h,disabled:m,expand:p,inlineTextInputVisible:g,hasInlineTextInput:k,minWidth:w,style:S,attributes:y}=o.toolbarItem,C=Se(()=>!!h?.value&&!!d?.value),T=Se(()=>i?.value??""),R=ne(""),M=ne(null),{isHighContrastMode:H}=zi();Pt(()=>l?.value,Ce=>{document.activeElement!==M.value&&(R.value=Ce==null?"":String(Ce))},{immediate:!0});const B=()=>{k&&_t(()=>{M.value?.focus(),M.value?.select()}),n("buttonClick")},z=Ce=>{m?.value||(Ce?.stopPropagation(),n("mainClick"))},Z=()=>{C.value||B()},P=Ce=>{if(C.value){z(Ce);return}B()},N=Ce=>{o.allowEnterPropagation||Ce.stopPropagation(),P(Ce)},I=Ce=>{const oe=o.toolbarItem?.nestedOptions?.value??[],xe=Ce.trim();if(!xe)return"";const qe=oe.find(et=>typeof et?.label=="string"&&et.label.toLowerCase()===xe.toLowerCase());return qe?.label?qe.label:oe.find(et=>typeof et?.label=="string"&&et.label.toLowerCase().startsWith(xe.toLowerCase()))?.label??xe},L=()=>{const Ce=String(R.value??"").trim();let oe=Ce;if(T.value==="fontSize"){const xe=Number.parseFloat(Ce);oe=Ce.match(/^\d+(\.5)?$/)?Ce:Number.isFinite(xe)?Math.floor(xe).toString():""}else T.value==="fontFamily"&&(oe=I(Ce));return oe?(n("textSubmit",oe),R.value=oe,!0):!1},X=Ce=>{const oe=Ce?.currentTarget;oe instanceof HTMLInputElement&&(oe.focus({preventScroll:!0}),oe.select())},te=Ce=>{requestAnimationFrame(()=>{const oe=document.getElementById(`inlineTextInput-${Ce}`);oe instanceof HTMLInputElement&&(oe.focus({preventScroll:!0}),oe.select())})},le=()=>{const Ce=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return Ce instanceof HTMLElement?(Ce.focus({preventScroll:!0}),!0):!1},fe=()=>{const Ce=r?.$toolbar?.pendingSelectionCapture,oe=()=>{Ce&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(Ce)};if(le()){oe();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),oe())},Fe=()=>{L()&&fe()},he=Ce=>{if(L(),Ce.shiftKey){T.value==="fontSize"&&(Ce.preventDefault(),_t(()=>te("fontFamily")));return}if(Ce.preventDefault(),T.value==="fontFamily"){_t(()=>te("fontSize"));return}T.value==="fontSize"&&_t(fe)},ge=Se(()=>S.value?S.value:{minWidth:o.minWidth}),ae=Se(()=>p?.value?tr.dropdownCaretUp:tr.dropdownCaretDown);return(Ce,oe)=>(me(),_e("div",{class:en(["sd-toolbar-item",Ge(y).className]),style:vn(ge.value),role:e.isOverflowItem?"menuitem":"button","aria-label":Ge(y).ariaLabel,"data-sd-part":"toolbar-item",onClick:Z,onKeydown:oe[9]||(oe[9]=Yo(xe=>N(xe),["enter"])),tabindex:"0"},[Le("div",{class:en(["sd-toolbar-button",{"sd-active":Ge(s),"sd-disabled":Ge(m),narrow:e.isNarrow,wide:e.isWide,split:C.value,"has-inline-text-input":Ge(k),"high-contrast":Ge(H)}]),"data-item":`btn-${Ge(i)||""}`},[C.value?(me(),_e("div",{key:0,class:"sd-toolbar-button__main","data-item":`btn-${Ge(i)||""}-main`,onClick:oe[0]||(oe[0]=xe=>z(xe))},[Ge(a)?(me(),fn(Fk,{key:0,color:Ge(c),class:"sd-toolbar-icon",icon:Ge(a),name:Ge(i)},null,8,["color","icon","name"])):ut("",!0),Ge(l)&&!Ge(u)&&!Ge(g)?(me(),_e("div",wB,Ht(Ge(l)),1)):ut("",!0)],8,bB)):ut("",!0),C.value?(me(),_e("div",{key:1,class:"sd-toolbar-button__caret","data-item":`btn-${Ge(i)||""}-caret`,"aria-label":`${Ge(y).ariaLabel} options`,role:"button"},[Le("div",{class:"sd-dropdown-caret",innerHTML:ae.value,style:vn({opacity:Ge(m)?.6:1})},null,12,_B)],8,CB)):(me(),_e(Wt,{key:2},[Ge(a)?(me(),fn(Fk,{key:0,color:Ge(c),class:"sd-toolbar-icon",icon:Ge(a),name:Ge(i)},null,8,["color","icon","name"])):ut("",!0),Ge(l)&&!Ge(u)&&(!Ge(g)||T.value==="fontFamily")?(me(),_e("div",{key:1,class:en(["sd-button-label",{"sd-visually-hidden":Ge(g)&&T.value==="fontFamily"}])},Ht(Ge(l)),3)):ut("",!0),Ge(g)?(me(),_e("span",SB,[Ge(i)==="fontSize"?Ws((me(),_e("input",{key:0,"onUpdate:modelValue":oe[1]||(oe[1]=xe=>R.value=xe),onKeydown:[Yo(Jt(Fe,["stop","prevent"]),["enter"]),oe[2]||(oe[2]=Yo(xe=>he(xe),["tab"]))],onClick:oe[3]||(oe[3]=Jt(xe=>X(xe),["stop"])),onFocus:oe[4]||(oe[4]=xe=>X(xe)),type:"text",class:en(["button-text-input button-text-input--font-size",{"high-contrast":Ge(H)}]),id:"inlineTextInput-"+Ge(i),autocomplete:"off",ref_key:"inlineInput",ref:M},null,42,kB)),[[ki,R.value]]):Ws((me(),_e("input",{key:1,"onUpdate:modelValue":oe[5]||(oe[5]=xe=>R.value=xe),placeholder:Ge(l),onKeydown:[Yo(Jt(Fe,["stop","prevent"]),["enter"]),oe[6]||(oe[6]=Yo(xe=>he(xe),["tab"]))],onClick:oe[7]||(oe[7]=Jt(xe=>X(xe),["stop"])),onFocus:oe[8]||(oe[8]=xe=>X(xe)),type:"text",class:en(["button-text-input",{"button-text-input--font-family":T.value==="fontFamily","high-contrast":Ge(H)}]),id:"inlineTextInput-"+Ge(i),"data-item":T.value==="fontFamily"?`btn-${Ge(i)}-input`:void 0,autocomplete:"off",ref_key:"inlineInput",ref:M},null,42,AB)),[[ki,R.value]])])):ut("",!0),Ge(d)?(me(),_e("div",{key:3,class:"sd-dropdown-caret","data-item":`btn-${Ge(i)||""}-toggle`,innerHTML:ae.value,style:vn({opacity:Ge(m)?.6:1})},null,12,IB)):ut("",!0)],64)),Le("div",EB,Ht(`${Ge(y).ariaLabel} ${Ge(s)?"selected":"unset"}`),1)],10,yB)],46,vB))}},O0=hn(xB,[["__scopeId","data-v-dbdea151"]]);It(),gn();var TB={class:"toolbar-separator",role:"separator","aria-label":"Toolbar separator"},RB={__name:"ToolbarSeparator",props:{active:{type:Boolean,default:!1}},emits:["command"],setup(e,{emit:t}){const{isHighContrastMode:n}=zi(),r=()=>n.value?"#000":"var(--sd-ui-border, #dbdbdb)";return(o,i)=>(me(),_e("div",TB,[Le("div",{class:"separator-inner",style:vn({backgroundColor:r()})},null,4)]))}},MB=hn(RB,[["__scopeId","data-v-cb82253a"]]);It(),gn();var LB={class:"overflow-menu"},DB={class:"overflow-menu-trigger"},PB={key:0,class:"overflow-menu_items",role:"group"},OB={__name:"OverflowMenu",props:{toolbarItem:{type:Object,required:!0},overflowItems:{type:Array,required:!0}},emits:["buttonClick","close"],setup(e,{emit:t}){const{proxy:n}=sr(),r=t,o=e,i=Se(()=>o.toolbarItem.expand.value),s=ne(!1),a=Se(()=>({...o.toolbarItem,active:i.value})),l=()=>{r("buttonClick",o.toolbarItem)},u=({item:d,argument:h})=>{n.$toolbar.emitCommand({item:d,argument:h})},c=d=>{d.key==="Escape"&&i.value&&!s.value&&(d.preventDefault(),r("close"))};return Rn(()=>{document.addEventListener("keydown",c,!0)}),ir(()=>{document.removeEventListener("keydown",c,!0)}),(d,h)=>(me(),_e("div",LB,[Le("div",DB,[Gt(O0,{"toolbar-item":a.value,onButtonClick:l},null,8,["toolbar-item"])]),i.value?(me(),_e("div",PB,[Gt(qp,{class:"superdoc-toolbar-overflow","toolbar-items":e.overflowItems,"from-overflow":"",onCommand:u,onDropdownUpdateShow:h[0]||(h[0]=m=>s.value=m)},null,8,["toolbar-items"])])):ut("",!0)]))}},FB=hn(OB,[["__scopeId","data-v-504ecd05"]]);It(),gn();var BB={class:"toolbar-dropdown"},NB=["onClick"],zB={key:0,class:"toolbar-dropdown-option__icon"},HB={class:"toolbar-dropdown-option__label"},Gp='button, [href], input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])',UB={__name:"ToolbarDropdown",props:{options:{type:Array,default:()=>[]},show:{type:Boolean,required:!0},placement:{type:String,default:"bottom-start"},disabled:{type:Boolean,default:!1},contentStyle:{type:Object,default:()=>({})},menuProps:{type:Function,default:null},nodeProps:{type:Function,default:null}},emits:["update:show","select"],setup(e,{emit:t}){const n=e,r=t,o=ne(null),i=ne(null),s=ne({top:"0px",left:"0px",maxHeight:"none"}),a=ne([]),l=ne(-1),u=Se(()=>!!n.show),c=Se(()=>n.options.some(oe=>oe?.type==="render")),d=Se(()=>typeof n.menuProps!="function"?{}:n.menuProps()||{}),h=Se(()=>{const{class:oe,style:xe,...qe}=d.value;return qe}),m=Se(()=>{const oe=d.value.class,xe=n.options.length>0&&n.options.every(qe=>qe&&qe.type==="render");return["toolbar-dropdown-menu",oe,{"toolbar-dropdown-menu--render-only":xe}]}),p=Se(()=>{const oe=d.value.style||{};return{...n.contentStyle,...oe}}),g=Se(()=>({...p.value,position:"fixed",top:s.value.top,left:s.value.left,maxHeight:s.value.maxHeight,zIndex:2e3})),k=oe=>{r("update:show",oe)},w=()=>{u.value&&k(!1)},S=()=>{if(!o.value)return;const oe=o.value.getBoundingClientRect(),xe=i.value,qe=xe?.offsetWidth??0,et=xe?.scrollHeight??xe?.offsetHeight??0,kt=window.innerWidth||document.documentElement.clientWidth||0,Ie=window.innerHeight||document.documentElement.clientHeight||0,ze=8,Ve=4,Q=oe.bottom+Ve,_=oe.top-Ve,$=Math.max(0,Ie-Q-ze),F=Math.max(0,_-ze),j=$<et&&F>$,V=j?F:$,G=et?Math.min(et,V):V,J=j?Math.max(ze,_-G):Q;let K=oe.left;n.placement==="bottom-end"&&(K=oe.right-qe);const W=Math.max(ze,kt-qe-ze);K=Math.min(Math.max(ze,K),W),s.value={top:`${J}px`,left:`${K}px`,maxHeight:`${V}px`}},y=()=>{n.disabled||k(!u.value)},C=oe=>typeof n.nodeProps!="function"?{}:n.nodeProps(oe)||{},T=oe=>{oe?.disabled||oe?.type!=="render"&&(r("select",oe?.key,oe),w())},R=oe=>oe?.type==="render",M=oe=>!oe?.disabled&&oe?.type!=="render",H=oe=>typeof oe?.icon=="function"||!!oe?.icon,B=oe=>typeof oe?.icon=="function"?oe.icon(oe):oe?.icon||null,z=oe=>oe?typeof oe=="string"?oe.split(/\s+/).includes("sd-selected"):Array.isArray(oe)?oe.some(z):typeof oe=="object"?!!oe["sd-selected"]:!1:!1,Z=oe=>z(oe?.props?.class)||z(oe?.class),P=()=>n.options.map((oe,xe)=>M(oe)?xe:-1).filter(oe=>oe>=0),N=()=>{const oe=n.options.findIndex(xe=>M(xe)&&Z(xe));return oe>=0?oe:P()[0]??-1},I=(oe,xe)=>{if(!oe){delete a.value[xe];return}a.value[xe]=oe},L=()=>{a.value.forEach((xe,qe)=>{xe&&xe.setAttribute("tabindex",qe===l.value?"0":"-1")});const oe=a.value[l.value];oe&&typeof oe.focus=="function"&&(oe.focus(),oe.scrollIntoView?.({block:"nearest",inline:"nearest"}))},X=oe=>{const xe=P();if(!xe.length){l.value=-1;return}const qe=xe.indexOf(l.value);if(qe<0){l.value=oe>0?xe[0]:xe[xe.length-1];return}l.value=xe[(qe+oe+xe.length)%xe.length]},te=()=>{let oe=n.options[l.value];if(!M(oe)){const xe=P()[0];oe=xe===void 0?null:n.options[xe]}oe&&T(oe)},le=Ll({name:"ToolbarDropdownRenderOption",props:{option:{type:Object,required:!0}},setup(oe){return()=>typeof oe.option.render!="function"?null:oe.option.render()}}),fe=Ll({name:"ToolbarDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(oe){return()=>B(oe.option)}}),Fe=oe=>{if(!u.value)return;const xe=oe.target;if(!(xe instanceof Element))return;const qe=o.value?.contains(xe),et=i.value?.contains(xe);qe||et||w()},he=ne(null),ge=()=>{const oe=o.value,xe=document.activeElement;if(oe&&xe instanceof HTMLElement&&oe.contains(xe)){he.value=xe;return}he.value=oe?.matches?.(Gp)?oe:oe?.querySelector(Gp)},ae=()=>{const oe=he.value;if(oe instanceof HTMLElement&&document.contains(oe)){oe.focus();return}const xe=o.value;if(!xe)return;const qe=xe.matches?.(Gp)?xe:xe.querySelector(Gp);if(qe instanceof HTMLElement){qe.focus();return}xe.setAttribute("tabindex","-1"),xe.focus()},Ce=oe=>{if(!u.value)return;const{key:xe}=oe;if(["Escape","ArrowDown","ArrowUp","Enter"].includes(xe)){if(xe==="Escape"){oe.preventDefault(),w(),_t(()=>{requestAnimationFrame(ae)});return}if(!c.value){if(oe.preventDefault(),xe==="ArrowDown"){X(1),L();return}if(xe==="ArrowUp"){X(-1),L();return}xe==="Enter"&&te()}}};return Pt(u,async oe=>{if(!oe){l.value=-1,a.value=[];return}ge(),await _t(),S(),!c.value&&(l.value=N(),await _t(),L())},{immediate:!0}),Pt(u,oe=>{oe?(document.addEventListener("pointerdown",Fe,!0),document.addEventListener("keydown",Ce,!0),window.addEventListener("resize",S),window.addEventListener("scroll",S,!0)):(document.removeEventListener("pointerdown",Fe,!0),document.removeEventListener("keydown",Ce,!0),window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0))},{immediate:!0}),ir(()=>{document.removeEventListener("pointerdown",Fe,!0),document.removeEventListener("keydown",Ce,!0),window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0)}),(oe,xe)=>(me(),_e("div",BB,[Le("div",{ref_key:"triggerRef",ref:o,class:"toolbar-dropdown-trigger","data-sd-part":"dropdown-trigger",onClick:y},[hd(oe.$slots,"trigger",{},void 0,!0)],512),(me(),fn(Oa,{to:"body"},[Gt(Mh,{name:"fade-in-scale-up-transition"},{default:ko(()=>[u.value?(me(),_e("div",cs({key:0,ref_key:"menuRef",ref:i,"data-sd-part":"dropdown-menu",class:m.value,style:g.value},h.value),[(me(!0),_e(Wt,null,or(e.options,(qe,et)=>(me(),_e("div",cs({key:qe.key,ref_for:!0,ref:kt=>I(kt,et),class:["toolbar-dropdown-option",[qe.class,qe.props?.class,{"sd-disabled":qe.disabled,"sd-render":R(qe)}]],tabindex:"-1",onClick:kt=>T(qe)},{ref_for:!0},{...qe.props,...C(qe)}),[R(qe)?(me(),fn(Ge(le),{key:0,option:qe},null,8,["option"])):(me(),_e(Wt,{key:1},[H(qe)?(me(),_e("span",zB,[Gt(Ge(fe),{option:qe},null,8,["option"])])):ut("",!0),Le("span",HB,Ht(qe.label),1)],64))],16,NB))),128))],16)):ut("",!0)]),_:1})]))]))}},VB=hn(UB,[["__scopeId","data-v-fef410f7"]]),Bk=e=>String(e??"").trim().toLowerCase();const Wp=(e,t)=>{const n=Bk(e);if(!n)return-1;for(let r=0;r<t.length;r+=1)if(Bk(t[r]).startsWith(n))return r;return-1},jB=(e,t,{autocomplete:n=!0}={})=>{const r=String(e??""),o=Wp(r,t),i=o>=0?String(t[o]??""):"";return n&&o>=0&&i.length>r.length?{matchIndex:o,display:i,selectionStart:r.length,selectionEnd:i.length}:{matchIndex:o,display:r,selectionStart:r.length,selectionEnd:r.length}};var GB=e=>{let t=String(e??"").trim();for(;t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"));)t=t.slice(1,-1).trim();return t},WB=e=>e<=31||e===127,KB=e=>e===32||e===160||e===65279,qB=e=>Array.from(String(e)).filter(t=>!WB(t.charCodeAt(0))).join(""),YB=e=>{let t="",n=!1;for(const r of String(e)){if(KB(r.charCodeAt(0))){n=t.length>0;continue}n&&(t+=" "),n=!1,t+=r}return t};const XB=e=>YB(GB(qB(String(e??"").split(",")[0]??""))).trim();var QB=1,ZB=1638;const JB=e=>{const t=String(e??"").replace(/[^0-9.-]/g,""),n=Number.parseFloat(t);if(!Number.isFinite(n))return"";const r=Math.round(n*2)/2;return r<QB?"":String(Math.min(r,ZB))};It(),gn();var $B=["data-item"],eN=["id","value","disabled","aria-label","aria-expanded","aria-controls","aria-activedescendant","data-item"],tN=["data-item","aria-label","disabled"],nN=["innerHTML"],rN=["id","aria-label"],oN=["id","aria-selected","aria-label","onMousedown","onMouseenter"],iN={class:"toolbar-dropdown-option__label"},sN={class:"sd-button-label sd-font-combobox__legacy-label","aria-hidden":"true"},aN={__name:"ToolbarComboBox",props:{item:{type:Object,required:!0},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"},showPreview:{type:Boolean,default:!1},normalizeValue:{type:Function,default:e=>String(e??"").trim()}},emits:["command","item-clicked","tab-out","editor-handoff"],setup(e,{emit:t}){const n=e,r=t,{isHighContrastMode:o}=zi(),i=ne(null),s=ne(null),a=ne(null),l=ne([]),u=ne(!1),c=ne(!1),d=ne(-1),h=ne(""),m=ne(""),p=ne(!1),g=ne({top:"0px",left:"0px",minWidth:"0px",maxHeight:"none"}),k=Se(()=>n.item.nestedOptions?.value??[]),w=Se(()=>k.value.map(K=>String(K?.label??""))),S=Se(()=>String(n.item.label?.value??"")),y=Se(()=>!!n.item.disabled?.value),C=Se(()=>String(n.item.name?.value??"")),T=Se(()=>n.item.attributes?.value?.ariaLabel??"Font family"),R=Se(()=>u.value?m.value:S.value),M=Se(()=>`sd-${C.value||"combobox"}-listbox-${n.item.id?.value??"default"}`),H=K=>`${M.value}-option-${K}`,B=Se(()=>c.value&&d.value>=0?H(d.value):void 0),z=Se(()=>c.value?tr.dropdownCaretUp:tr.dropdownCaretDown),Z=K=>{const W=String(K??"").trim().toLowerCase();return k.value.find(ue=>String(ue?.label??"").trim().toLowerCase()===W)?.props?.style?.fontFamily||K||n.uiFontFamily},P=Se(()=>n.showPreview?{fontFamily:Z(u.value?m.value:S.value)}:{fontFamily:n.uiFontFamily}),N=()=>{const K=n.item.selectedValue?.value;if(K){const W=k.value.findIndex(ue=>ue?.key===K);if(W>=0)return W}return w.value.findIndex(W=>W.toLowerCase()===S.value.toLowerCase())},I=(K,W)=>{const ue=i.value;if(!(!ue||typeof ue.setSelectionRange!="function"))try{ue.setSelectionRange(K,W)}catch{}},L=()=>{l.value[d.value]?.scrollIntoView?.({block:"nearest",inline:"nearest"})},X=()=>{l.value[d.value]?.focus?.()},te=()=>{const K=s.value;if(!K)return;const W=K.getBoundingClientRect(),ue=a.value,be=ue?.scrollHeight??ue?.offsetHeight??0,we=window.innerHeight||document.documentElement.clientHeight||0,Te=window.innerWidth||document.documentElement.clientWidth||0,rt=8,nt=4,wt=W.bottom+nt,Zt=W.top-nt,Ct=Math.max(0,we-wt-rt),Ot=Math.max(0,Zt-rt),Bt=Ct<be&&Ot>Ct,on=Bt?Ot:Ct,Fn=be?Math.min(be,on):on,Vt=Bt?Math.max(rt,Zt-Fn):wt,We=Math.min(Math.max(rt,W.left),Math.max(rt,Te-W.width-rt));g.value={top:`${Vt}px`,left:`${We}px`,minWidth:`${W.width}px`,maxHeight:`${on}px`}},le=Se(()=>({position:"fixed",top:g.value.top,left:g.value.left,minWidth:g.value.minWidth,maxHeight:g.value.maxHeight,fontFamily:n.uiFontFamily,zIndex:2e3})),fe=K=>{n.item.expand&&typeof n.item.expand=="object"&&"value"in n.item.expand&&(n.item.expand.value=K)},Fe=(K,{focusInput:W=!1,focusOption:ue=!1}={})=>{if(y.value||!k.value.length){fe(!1);return}c.value=!0,fe(!0),d.value=K??-1,W&&(u.value=!0,m.value=S.value,i.value?.focus()),_t(()=>{te(),L(),ue&&X()})},he=({syncItem:K=!0}={})=>{c.value=!1,d.value=-1,K&&fe(!1)},ge=()=>{he(),u.value=!1,h.value="",m.value=S.value},ae=()=>{y.value||(c.value||r("item-clicked"),u.value=!0,h.value="",m.value=S.value,_t(()=>I(0,m.value.length)))},Ce=K=>{if(y.value)return;const W=document.activeElement===i.value;if(r("item-clicked"),u.value=!0,W||(h.value="",m.value=S.value,K.preventDefault(),i.value?.focus({preventScroll:!0}),I(0,S.value.length)),!c.value){const ue=N();Fe(ue>=0?ue:0)}},oe=K=>{const W=K.relatedTarget;W instanceof Node&&s.value?.contains(W)||W instanceof Node&&a.value?.contains(W)||ge()},xe=K=>{if(p.value)return;const W=K.target,ue=W.value,be=typeof W.selectionStart=="number"?W.selectionStart:ue.length,we=typeof W.selectionEnd=="number"?W.selectionEnd:be,Te=typeof K.inputType=="string"&&K.inputType.startsWith("delete"),rt=be===ue.length&&we===ue.length;h.value=ue;const nt=jB(ue,w.value,{autocomplete:!Te&&rt});m.value=nt.display,W.value=nt.display,nt.display===ue&&!rt?I(be,we):I(nt.selectionStart,nt.selectionEnd),c.value&&(d.value=nt.matchIndex,_t(L))},qe=K=>{p.value=!1,xe(K)},et=K=>{if(!k.value.length)return;const W=k.value.length;d.value=((d.value<0?K>0?-1:0:d.value)+K+W)%W,_t(L)},kt=(K,W)=>{r("item-clicked"),r("command",{item:n.item,argument:K,option:W}),W&&(n.item.selectedValue.value=W.key)},Ie=K=>{K&&(kt(K.label,K),u.value=!1,h.value="",m.value=K.label,he())},ze=()=>{if(c.value&&d.value>=0)return Ie(k.value[d.value]),!0;const K=Wp(h.value,w.value);if(K>=0)return Ie(k.value[K]),!0;const W=n.normalizeValue(h.value);return W?(kt(W,null),u.value=!1,h.value="",m.value=W,he(),!0):!1},Ve=K=>{if(!(K.isComposing||p.value||K.keyCode===229)&&!(K.ctrlKey||K.metaKey||K.altKey))switch(K.key){case"ArrowDown":if(K.preventDefault(),c.value)X();else{const W=Wp(h.value,w.value),ue=W>=0?W:N();Fe(ue>=0?ue:0,{focusOption:!0})}break;case"ArrowUp":if(K.preventDefault(),c.value)X();else{const W=Wp(h.value,w.value),ue=W>=0?W:N();Fe(ue>=0?ue:k.value.length-1,{focusOption:!0})}break;case"Enter":K.preventDefault(),ze()&&r("editor-handoff"),i.value?.blur();break;case"Tab":K.preventDefault(),ze(),he(),i.value?.blur(),r("tab-out",K);break;case"Escape":K.preventDefault(),ge(),_t(()=>i.value?.focus());break;default:break}},Q=K=>{if(K.preventDefault(),!y.value)if(r("item-clicked"),c.value)he(),i.value?.focus();else{const W=N();Fe(W>=0?W:0,{focusOption:!0})}},_=(K,W)=>{K.preventDefault(),Ie(W),r("editor-handoff"),i.value?.blur()},$=K=>{d.value=K},F=K=>{if(!(K.ctrlKey||K.metaKey||K.altKey))switch(K.key){case"ArrowDown":K.preventDefault(),et(1),X();break;case"ArrowUp":K.preventDefault(),et(-1),X();break;case"Enter":K.preventDefault(),d.value>=0&&(Ie(k.value[d.value]),r("editor-handoff"));break;case"Escape":K.preventDefault(),ge(),_t(()=>i.value?.focus());break;case"Tab":K.preventDefault(),d.value>=0?Ie(k.value[d.value]):he(),r("tab-out",{shiftKey:K.shiftKey,target:i.value});break;default:break}},j=K=>{if(!c.value)return;const W=K.target;W instanceof Element&&(s.value?.contains(W)||a.value?.contains(W)||ge())};Pt(c,K=>{K?(document.addEventListener("pointerdown",j,!0),window.addEventListener("resize",te),window.addEventListener("scroll",te,!0)):(document.removeEventListener("pointerdown",j,!0),window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),l.value=[])},{immediate:!0}),ir(()=>{document.removeEventListener("pointerdown",j,!0),window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0)});const V=(K,W)=>{if(!K){delete l.value[W];return}l.value[W]=K},G=K=>K===d.value,J=K=>K?.key&&K.key===n.item.selectedValue?.value;return Pt(S,K=>{u.value||(m.value=K)}),Pt(()=>!!n.item.expand?.value,K=>{if(K&&!c.value){const W=N();Fe(W>=0?W:0,{focusInput:!0});return}!K&&c.value&&he({syncItem:!1})}),(K,W)=>(me(),_e("div",{ref_key:"rootRef",ref:s,class:en(["sd-font-combobox sd-toolbar-split-field",{"sd-disabled":y.value,"high-contrast":Ge(o)}]),style:vn(n.item.style?.value),"data-item":`btn-${C.value}`},[Le("span",{class:"sd-font-combobox__field sd-toolbar-split-field__main",onMousedown:Ce},[Le("input",{ref_key:"inputRef",ref:i,id:`inlineTextInput-${C.value}`,class:"button-text-input sd-font-combobox__input",type:"text",role:"combobox",autocomplete:"off",spellcheck:"false",value:R.value,style:vn(P.value),disabled:y.value,"aria-label":T.value,"aria-expanded":c.value?"true":"false","aria-controls":M.value,"aria-activedescendant":B.value,"aria-haspopup":"listbox","aria-autocomplete":"both","data-item":`btn-${C.value}-input`,onFocus:ae,onBlur:oe,onInput:xe,onKeydown:Ve,onCompositionstart:W[0]||(W[0]=ue=>p.value=!0),onCompositionend:qe},null,44,eN)],32),Le("button",{type:"button",class:"sd-font-combobox__caret sd-toolbar-split-field__caret","data-item":`btn-${C.value}-toggle`,tabindex:"-1","aria-label":`${T.value} options`,disabled:y.value,onMousedown:Q},[Le("span",{class:"sd-dropdown-caret",innerHTML:z.value},null,8,nN)],40,tN),(me(),fn(Oa,{to:"body"},[c.value?(me(),_e("div",{key:0,ref_key:"popupRef",ref:a,role:"listbox",id:M.value,"aria-label":T.value,class:en(["sd-font-combobox__listbox",{"high-contrast":Ge(o)}]),style:vn(le.value)},[(me(!0),_e(Wt,null,or(k.value,(ue,be)=>(me(),_e("div",cs({key:ue.key,ref_for:!0,ref:we=>V(we,be),id:H(be),role:"option",tabindex:"-1",class:["toolbar-dropdown-option sd-font-combobox__option",{"sd-active":G(be),"sd-selected":J(ue)}],"aria-selected":J(ue)?"true":"false","aria-label":`${T.value} - ${ue.label}`},{ref_for:!0},ue.props,{onMousedown:we=>_(we,ue),onMouseenter:we=>$(be),onKeydown:F}),[Le("span",iN,Ht(ue.label),1)],16,oN))),128))],14,rN)):ut("",!0)])),Le("span",sN,Ht(S.value),1)],14,$B))}},Nk=hn(aN,[["__scopeId","data-v-99070b63"]]);It();var lN={__name:"FontFamilyCombobox",props:{item:{type:Object,required:!0},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"}},emits:["command","item-clicked","tab-out","editor-handoff"],setup(e,{emit:t}){const n=e,r=t;return(o,i)=>(me(),fn(Nk,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!0,"normalize-value":Ge(XB),onCommand:i[0]||(i[0]=s=>r("command",s)),onItemClicked:i[1]||(i[1]=s=>r("item-clicked")),onTabOut:i[2]||(i[2]=s=>r("tab-out",s)),onEditorHandoff:i[3]||(i[3]=s=>r("editor-handoff"))},null,8,["item","ui-font-family","normalize-value"]))}},cN=lN;It();var uN={__name:"FontSizeCombobox",props:{item:{type:Object,required:!0},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"}},emits:["command","item-clicked","tab-out","editor-handoff"],setup(e,{emit:t}){const n=e,r=t;return(o,i)=>(me(),fn(Nk,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!1,"normalize-value":Ge(JB),onCommand:i[0]||(i[0]=s=>r("command",s)),onItemClicked:i[1]||(i[1]=s=>r("item-clicked")),onTabOut:i[2]||(i[2]=s=>r("tab-out",s)),onEditorHandoff:i[3]||(i[3]=s=>r("editor-handoff"))},null,8,["item","ui-font-family","normalize-value"]))}},dN=uN;It(),gn();var fN=2500,hN=Object.assign({inheritAttrs:!1},{__name:"SdTooltip",props:{trigger:{type:String,default:"hover"},delay:{type:Number,default:100},duration:{type:Number,default:100},disabled:{type:Boolean,default:!1},contentStyle:{type:Object,default:()=>({})}},setup(e){const t=e,n=O2(),r=ne(!1),o=ne(null),i=ne(null),s=ne({top:"0px",left:"0px"});let a=null,l=null,u=null;const c=Se(()=>["sd-tooltip-content",n.class]),d=Se(()=>({...t.contentStyle,...n.style||{},position:"fixed",top:s.value.top,left:s.value.left,zIndex:2100})),h=()=>{a&&(window.clearTimeout(a),a=null)},m=()=>{l&&(window.clearTimeout(l),l=null)},p=()=>{u&&(window.clearTimeout(u),u=null)},g=()=>{p(),u=window.setTimeout(()=>{u=null,S()},fN)},k=()=>{if(!o.value||!i.value)return;const z=o.value.getBoundingClientRect(),Z=i.value.offsetWidth,P=i.value.offsetHeight,N=window.innerWidth||document.documentElement.clientWidth||0,I=8;let L=z.left+z.width/2-Z/2;L=Math.max(I,Math.min(L,N-Z-I)),s.value={top:`${z.top-P-10}px`,left:`${L}px`}},w=async()=>{t.disabled||(h(),m(),!r.value&&(r.value=!0,g(),await _t(),k()))},S=()=>{m(),h(),p(),r.value&&(r.value=!1)},y=()=>{if(h(),m(),!r.value){if(t.delay===0){w();return}l=window.setTimeout(()=>{l=null,w()},t.delay)}},C=()=>{if(m(),h(),!!r.value){if(t.duration===0){S();return}a=window.setTimeout(()=>{a=null,S()},t.duration)}},T=()=>{t.trigger==="hover"&&y()},R=()=>{t.trigger==="hover"&&C()},M=()=>{m(),h()},H=()=>{C()},B=z=>{z.key==="Escape"&&S()};return Pt(()=>t.disabled,z=>{z&&S()}),Pt(r,z=>{z?(window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),document.addEventListener("keydown",B,!0)):(window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),document.removeEventListener("keydown",B,!0))}),ir(()=>{m(),h(),p(),window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),document.removeEventListener("keydown",B,!0)}),(z,Z)=>(me(),_e(Wt,null,[Le("span",{ref_key:"triggerRef",ref:o,class:"sd-tooltip-trigger",onMouseenter:T,onMouseleave:R,onFocusin:T,onFocusout:R},[hd(z.$slots,"trigger",{},void 0,!0)],544),(me(),fn(Oa,{to:"body"},[Gt(Mh,{name:"fade-in-scale-up-transition"},{default:ko(()=>[r.value&&!e.disabled?(me(),_e("div",{key:0,ref_key:"contentRef",ref:i,class:en(c.value),style:vn(d.value),onMouseenter:M,onMouseleave:H},[Z[0]||(Z[0]=Le("span",{class:"sd-tooltip-arrow","aria-hidden":"true"},null,-1)),hd(z.$slots,"default",{},void 0,!0)],38)):ut("",!0)]),_:3})]))],64))}}),Kp=hn(hN,[["__scopeId","data-v-2a872eae"]]);It(),gn();var pN=["onKeydown","tabindex","data-item-id"],mN={key:0},gN={key:0},vN={key:0},yN={key:0},bN={key:0},wN={__name:"ButtonGroup",props:{toolbarItems:{type:Array,required:!0},overflowItems:{type:Array,default:()=>[]},uiFontFamily:{type:String,default:"Arial, Helvetica, sans-serif"},position:{type:String,default:"left"},fromOverflow:{type:Boolean,default:!1},compactSideGroups:{type:Boolean,default:!1}},emits:["command","item-clicked","dropdown-update-show"],setup(e,{emit:t}){const n=t,{proxy:r}=sr(),o=ne([]),i=ne(null),s=e,a=ne(null),{isHighContrastMode:l}=zi(),u=window.matchMedia("(max-width: 768px)").matches,c=Se(()=>s.position==="left"?{minWidth:s.compactSideGroups?"auto":"120px",justifyContent:"flex-start"}:s.position==="right"?{minWidth:s.compactSideGroups?"auto":"120px",justifyContent:"flex-end"}:{flexGrow:u?0:1,justifyContent:"center"}),d=Ie=>Ie.type==="button",h=Ie=>Ie.type==="dropdown",m=Ie=>Ie.type==="dropdown"&&Ie.name?.value==="fontFamily",p=Ie=>Ie.type==="dropdown"&&Ie.name?.value==="fontSize",g=Ie=>Ie.type==="separator",k=Ie=>Ie.type==="overflow",w=Ie=>!!Ie.nestedOptions?.value?.length,S=Ie=>{if(!Ie)return!1;const ze=Ie.expand;return typeof ze=="object"&&ze!==null&&"value"in ze?!!ze.value:!!ze},y=(Ie,ze)=>{Ie?.expand&&(Ie.expand.value=ze)},C=(Ie,ze=void 0)=>{if(Ie.disabled.value)return;if(k(Ie)){const Q=!S(Ie);Q&&M(),y(Ie,Q),a.value=Q?Ie:null,n("item-clicked");return}if(h(Ie))return;a.value&&h(a.value)&&S(a.value)&&M(),n("item-clicked");const Ve=ze!==void 0?ze:Ie.argument?.value;n("command",Ve===void 0?{item:Ie}:{item:Ie,argument:Ve})},T=(Ie,ze)=>{Ie.disabled.value||(a.value=null,n("command",{item:Ie,argument:ze}))},R=Ie=>{if(Ie.disabled.value)return;M();const ze=Ie.splitButtonCommand,Ve=Ie.command,Q=ze||Ve;if(!Q)return;const _={...Ie,command:Q};n("item-clicked"),n("command",{item:_})},M=()=>{const Ie=r?.$toolbar?.toolbarItems||[],ze=r?.$toolbar?.overflowItems||[],Ve=[...Ie,...ze];(Ve.length?Ve:s.toolbarItems).forEach(Q=>{const _=k(Q)&&!s.fromOverflow;(h(Q)||_)&&y(Q,!1)}),a.value=null},H=(Ie,ze)=>{M(),n("command",{item:Ie,argument:Ie.dropdownValueKey.value?ze[Ie.dropdownValueKey.value]:ze.label,option:ze}),Ie.selectedValue.value=ze.key},B=Ie=>{n("command",Ie)},z=()=>{M(),n("item-clicked")},Z=()=>{const Ie=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return Ie instanceof HTMLElement?(Ie.focus({preventScroll:!0}),!0):!1},P=()=>{const Ie=r?.$toolbar?.pendingSelectionCapture,ze=()=>{Ie&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(Ie)};if(Z()){ze();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),ze())},N=Ie=>!(Ie instanceof HTMLElement)||Ie.classList.contains("sd-disabled")?null:Ie.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")||Ie.querySelector('button:not([disabled]), [role="button"]:not(.sd-disabled), [tabindex]:not([tabindex="-1"])'),I=(Ie,ze)=>{const Ve=Ie?.target?.closest?.(".sd-toolbar-item-ctn");if(!(Ve instanceof HTMLElement))return!1;let Q=ze>0?Ve.nextElementSibling:Ve.previousElementSibling;for(;Q;){const _=N(Q);if(_ instanceof HTMLElement)return Ve.setAttribute("tabindex","-1"),Q.setAttribute("tabindex","0"),_.focus(),!0;Q=ze>0?Q.nextElementSibling:Q.previousElementSibling}return!1},L=Ie=>{M(),I(Ie,Ie?.shiftKey?-1:1)||P()},X=Ie=>{if(M(),Ie?.shiftKey){I(Ie,-1)||P();return}P()},te=()=>{P()},le=Ie=>Ie.nestedOptions?.value?.length?Ie.nestedOptions.value.map(ze=>{const Ve=ze?.type!=="render"&&Ie.selectedValue.value===ze.key;return{...ze,props:{...ze.props,class:Ve?"sd-selected":""}}}):[],fe=(Ie,ze)=>({role:"menuitem",ariaLabel:`${ze.attributes.value.ariaLabel} - ${Ie.label}`}),Fe=Ie=>{const ze=Ie.target,Ve=Ie.target.closest(".sd-toolbar-item-ctn").nextElementSibling;Ve&&(ze.setAttribute("tabindex","-1"),Ve.setAttribute("tabindex","0"),Ve.focus())},he=Ie=>{const ze=Ie.target,Ve=Ie.target.closest(".sd-toolbar-item-ctn").previousElementSibling;Ve&&(ze.setAttribute("tabindex","-1"),Ve.setAttribute("tabindex","0"),Ve.focus())},ge=Ie=>{const ze=Ie.target.closest(".button-group").nextElementSibling;if(ze)ze.setAttribute("tabindex","0"),ze.focus();else{const Ve=document.querySelector(".ProseMirror");Ve&&Ve.focus()}},ae=Ie=>{const ze=Ie.target.closest(".button-group").previousElementSibling;ze&&(ze.setAttribute("tabindex","0"),ze.focus())},Ce=Ie=>{if(!Ie.disabled.value){if(h(Ie)){qe(!S(Ie),Ie);return}C(Ie)}},oe=(Ie,ze)=>{const Ve=Ie.target.nodeName==="INPUT"||Ie.target.nodeName==="TEXTAREA",Q=ze.name.value==="fontSize"||ze.name.value==="fontFamily";if(!(Ve&&Q)&&["Enter"," ","Spacebar","Escape","ArrowRight","ArrowLeft","Tab"].includes(Ie.key))switch(Ie.preventDefault(),Ie.key){case"Enter":case" ":case"Spacebar":Ce(ze);break;case"Escape":M();break;case"ArrowRight":M(),Fe(Ie);break;case"ArrowLeft":M(),he(Ie);break;case"Tab":Ie.shiftKey?ae(Ie):ge(Ie);break;default:break}},xe=Ie=>{const ze=o.value.find(Ve=>!Ve.classList.contains("sd-disabled"));ze&&(ze.setAttribute("tabindex","0"),ze.focus())},qe=(Ie,ze)=>{if(n("item-clicked"),!Ie){M(),n("dropdown-update-show",!1);return}M(),a.value=ze,y(ze,!0),n("dropdown-update-show",!0)},et=Ie=>{if(!a.value)return;const ze=Ie.target;ze instanceof Element&&(ze.closest(".sd-toolbar-dropdown-menu")||i.value?.contains(ze)||M())};return Pt(()=>S(a.value),Ie=>{Ie?document.addEventListener("pointerdown",et,!0):document.removeEventListener("pointerdown",et,!0)},{immediate:!0}),ir(()=>{document.removeEventListener("pointerdown",et,!0)}),(Ie,ze)=>(me(),_e("div",{style:vn(c.value),class:"button-group",role:"group",onFocus:xe,ref_key:"buttonGroupRef",ref:i},[(me(!0),_e(Wt,null,or(e.toolbarItems,(Ve,Q)=>(me(),_e("div",{key:Ve.id.value,class:en([{narrow:Ve.isNarrow.value,wide:Ve.isWide.value,"sd-disabled":Ve.disabled.value},"sd-toolbar-item-ctn"]),onKeydown:_=>oe(_,Ve),ref_for:!0,ref_key:"toolbarItemRefs",ref:o,tabindex:Q===0?0:-1,"data-item-id":Ve.id.value},[g(Ve)?(me(),fn(MB,{key:0,style:{width:"20px"}})):ut("",!0),m(Ve)&&w(Ve)?(me(),fn(Kp,{key:1,trigger:"hover",disabled:!Ve.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(cN,{item:Ve,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:B,onItemClicked:z,onTabOut:ze[0]||(ze[0]=_=>L(_)),onEditorHandoff:te},null,8,["item","ui-font-family"])]),default:ko(()=>[Le("div",null,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",mN,"(disabled)")):ut("",!0)])]),_:2},1032,["disabled","content-style"])):p(Ve)&&w(Ve)?(me(),fn(Kp,{key:2,trigger:"hover",disabled:!Ve.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(dN,{item:Ve,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:B,onItemClicked:z,onTabOut:ze[1]||(ze[1]=_=>X(_)),onEditorHandoff:te},null,8,["item","ui-font-family"])]),default:ko(()=>[Le("div",null,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",gN,"(disabled)")):ut("",!0)])]),_:2},1032,["disabled","content-style"])):h(Ve)&&Ve.nestedOptions?.value?.length?(me(),fn(VB,{key:3,options:le(Ve),disabled:Ve.disabled.value,show:S(Ve),"content-style":{fontFamily:s.uiFontFamily},placement:"bottom-start",class:"sd-toolbar-button sd-editor-toolbar-dropdown",onSelect:(_,$)=>H(Ve,$),"onUpdate:show":_=>qe(_,Ve),style:vn(Ve.dropdownStyles.value),"menu-props":()=>({role:"menu",style:{fontFamily:s.uiFontFamily},class:["sd-toolbar-dropdown-menu",{"high-contrast":Ge(l)}]}),"node-props":_=>fe(_,Ve)},{trigger:ko(()=>[Gt(Kp,{trigger:"hover",disabled:!Ve.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(O0,{"toolbar-item":Ve,disabled:Ve.disabled.value,"allow-enter-propagation":!0,onTextSubmit:_=>T(Ve,_),onMainClick:_=>R(Ve)},null,8,["toolbar-item","disabled","onTextSubmit","onMainClick"])]),default:ko(()=>[Le("div",null,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",vN,"(disabled)")):ut("",!0)])]),_:2},1032,["disabled","content-style"])]),_:2},1032,["options","disabled","show","content-style","onSelect","onUpdate:show","style","menu-props","node-props"])):d(Ve)?(me(),fn(Kp,{key:4,trigger:"hover",class:"sd-editor-toolbar-tooltip","content-style":{fontFamily:s.uiFontFamily}},{trigger:ko(()=>[Gt(O0,{"toolbar-item":Ve,"is-overflow-item":e.fromOverflow,onTextSubmit:_=>T(Ve,_),onButtonClick:_=>C(Ve)},null,8,["toolbar-item","is-overflow-item","onTextSubmit","onButtonClick"])]),default:ko(()=>[Ve.tooltip?(me(),_e("div",yN,[Oi(Ht(Ve.tooltip)+" ",1),Ve.disabled.value?(me(),_e("span",bN,"(disabled)")):ut("",!0)])):ut("",!0)]),_:2},1032,["content-style"])):ut("",!0),k(Ve)&&e.overflowItems.length?(me(),fn(FB,{key:5,"toolbar-item":Ve,onButtonClick:_=>C(Ve),"overflow-items":e.overflowItems,onClose:M},null,8,["toolbar-item","onButtonClick","overflow-items"])):ut("",!0)],42,pN))),128))],36))}},qp=hn(wN,[["__scopeId","data-v-590293ab"]]),CN=[["Arial","sans-serif"],["Arial Black","sans-serif"],["Arial Narrow","sans-serif"],["Baskerville Old Face","serif"],["Bookman Old Style","serif"],["Brush Script MT","cursive"],["Calibri","sans-serif"],["Century","serif"],["Century Gothic","sans-serif"],["Comic Sans MS","sans-serif"],["Cooper Black","serif"],["Courier New","monospace"],["Garamond","serif"],["Georgia","serif"],["Gill Sans MT Condensed","sans-serif"],["Helvetica","sans-serif"],["Lucida Console","monospace"],["Segoe UI","sans-serif"],["Tahoma","sans-serif"],["Times New Roman","serif"],["Trebuchet MS","sans-serif"],["Verdana","sans-serif"]];const _N=CN.map(([e,t])=>({label:e,key:e,fontWeight:400,props:{style:{fontFamily:`${e}, ${t}`},"data-item":"btn-fontFamily-option"}}));function SN(e){if(e?.length)return e.map(t=>({label:t.label,key:t.value,fontWeight:400,props:{style:{fontFamily:t.previewFamily||t.label},"data-item":"btn-fontFamily-option"}}))}const kN=[{label:"8",key:"8pt",props:{"data-item":"btn-fontSize-option"}},{label:"9",key:"9pt",props:{"data-item":"btn-fontSize-option"}},{label:"10",key:"10pt",props:{"data-item":"btn-fontSize-option"}},{label:"11",key:"11pt",props:{"data-item":"btn-fontSize-option"}},{label:"12",key:"12pt",props:{"data-item":"btn-fontSize-option"}},{label:"14",key:"14pt",props:{"data-item":"btn-fontSize-option"}},{label:"18",key:"18pt",props:{"data-item":"btn-fontSize-option"}},{label:"24",key:"24pt",props:{"data-item":"btn-fontSize-option"}},{label:"30",key:"30pt",props:{"data-item":"btn-fontSize-option"}},{label:"36",key:"36pt",props:{"data-item":"btn-fontSize-option"}},{label:"48",key:"48pt",props:{"data-item":"btn-fontSize-option"}},{label:"60",key:"60pt",props:{"data-item":"btn-fontSize-option"}},{label:"72",key:"72pt",props:{"data-item":"btn-fontSize-option"}},{label:"96",key:"96pt",props:{"data-item":"btn-fontSize-option"}}],kf={sm:768,md:1024,lg:1280,xl:1410},F0={undo:"undo",redo:"redo",bold:"bold",italic:"italic",underline:"underline",strike:"strikethrough",acceptTrackedChangeBySelection:"track-changes-accept-selection",rejectTrackedChangeOnSelection:"track-changes-reject-selection",ruler:"ruler",formattingMarks:"formatting-marks",zoom:"zoom",measurementUnit:"measurement-unit",documentMode:"document-mode",link:"link",fontFamily:"font-family",fontSize:"font-size",list:"bullet-list",numberedlist:"numbered-list",table:"table-insert",image:"image",tableOfContents:"table-of-contents-insert",color:"text-color",highlight:"highlight-color",textAlign:"text-align",lineHeight:"line-height",linkedStyles:"linked-style",indentleft:"indent-decrease",indentright:"indent-increase",directionLtr:"direction-ltr",directionRtl:"direction-rtl",clearFormatting:"clear-formatting",copyFormat:"copy-format"},zk={addRowBefore:"table-add-row-before",addRowAfter:"table-add-row-after",deleteRow:"table-delete-row",addColumnBefore:"table-add-column-before",addColumnAfter:"table-add-column-after",deleteColumn:"table-delete-column",deleteTable:"table-delete",deleteCellAndTableBorders:"table-remove-borders",mergeCells:"table-merge-cells",splitCell:"table-split-cell",fixTables:"table-fix"},Hk=Object.values(zk),Ij=[...new Set([...Object.values(F0),...Hk])];var AN=new Set(["link"]);const Ej=new Set(Object.keys(F0).filter(e=>!AN.has(e)));It(),gn();var IN="Arial, Helvetica, sans-serif",EN={__name:"Toolbar",emits:["command","toggle","select"],setup(e,{emit:t}){const{proxy:n}=sr();let r=ne(1);const o=ne(0),i=ne(!1);let s=null,a=null;const l=Se(()=>{const H=n?.$toolbar?.config?.uiDisplayFallbackFont;return typeof H=="string"&&H.trim()?H.trim():IN}),u=n.$toolbar.config?.toolbarGroups?.includes("left"),c=n.$toolbar.config?.toolbarGroups?.includes("right"),d=n.$toolbar.config?.toolbarButtonsExclude||[],h=H=>(o.value,n.$toolbar.getToolbarItemByGroup(H).filter(B=>!d.includes(B.name.value))),m=()=>{i.value=n.$toolbar.getAvailableWidth()<=kf.lg},g=hB(async()=>{await n.$toolbar.onToolbarResize(),m(),r.value+=1},300),k=()=>{r.value+=1},w=()=>{o.value+=1};function S(){window.removeEventListener("resize",g),n.$toolbar.off?.("toolbar-items-changed",k),n.$toolbar.off?.("toolbar-state-change",w),s?.disconnect(),s=null}function y(){S(),window.addEventListener("resize",g),n.$toolbar.on?.("toolbar-items-changed",k),n.$toolbar.on?.("toolbar-state-change",w),typeof ResizeObserver<"u"&&n.$toolbar.config?.responsiveToContainer&&n.$toolbar.toolbarContainer&&(s=new ResizeObserver(()=>{g()}),s.observe(n.$toolbar.toolbarContainer)),m()}Rn(y),mg(y),gg(S),ir(S);const C=()=>{if(!n.$toolbar.activeEditor){a=null,n.$toolbar.pendingSelectionCapture=null;return}a=n.$toolbar.ui?.selection?.capture?.()??null,n.$toolbar.pendingSelectionCapture=a},T=({item:H,argument:B,option:z})=>{R(),n.$toolbar.emitCommand({item:H,argument:B,option:z})},R=()=>{const H=n.$toolbar.activeEditor;if(!H)return;const B=n.$toolbar.pendingSelectionCapture??a;if(B&&typeof n.$toolbar.ui?.selection?.restore=="function"){n.$toolbar.ui.selection.restore(B);return}H.commands?.restoreSelection?.()},M=H=>{C(),!H.target.closest('input, textarea, [contenteditable="true"]')&&H.preventDefault()};return(H,B)=>(me(),_e("div",{class:"superdoc-toolbar",key:Ge(r),role:"toolbar","aria-label":"Toolbar","data-sd-part":"toolbar","data-editor-ui-surface":"",onMousedown:M},[Ge(u)?(me(),fn(qp,{key:0,tabindex:"0","toolbar-items":h("left"),"overflow-items":Ge(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"left",onCommand:T,class:"superdoc-toolbar-group-side"},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"])):ut("",!0),Gt(qp,{tabindex:"0","toolbar-items":h("center"),"overflow-items":Ge(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"center",onCommand:T},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"]),Ge(c)?(me(),fn(qp,{key:1,tabindex:"0","toolbar-items":h("right"),"overflow-items":Ge(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"right",onCommand:T,class:"superdoc-toolbar-group-side"},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"])):ut("",!0)],32))}},xN=hn(EN,[["__scopeId","data-v-55b5af7a"]]);const TN=e=>{if(!e)return e;const t=e.props?.style?.fontFamily??e.label??e.key;return{...e,props:{...e.props,style:{...e.props?.style,fontFamily:t},"data-item":e.props?.["data-item"]??"btn-fontFamily-option"}}};It();const Cn=e=>{if(!["button","options","separator","dropdown","overflow"].includes(e.type))throw new Error("Invalid toolbar item type - "+e.type);if(e.type==="button"&&!e.defaultLabel&&!e.icon)throw new Error("Toolbar button item needs either icon or label - "+e.name);if(!e.name)throw new Error("Invalid toolbar item name - "+e.name);const t=ne(os()),n=e.type,r=ne(e.name),o=e.command,i=e.noArgumentCommand,s=ne(e.icon),a=ne(e.group||"center"),l=ne(e.allowWithoutEditor),u=ne(e.attributes||{}),c=e.disabled||!1,d=ne(e.disabled),h=ne(!1),m=ne(!1),p=ne(e.style),g=ne(e.isNarrow),k=ne(e.isWide),w=ne(e.minWidth),S=ne(e.suppressActiveHighlight||!1),y=ne(e.argument),C=ne(null),T=ne(null),R=ne(e.iconColor),M=ne(e.hasCaret),H=ne(!!e.splitButton),B=e.splitButtonCommand,z=!!e.restoreEditorFocus,Z=ne(e.dropdownStyles),P=ne(e.tooltip),N=ne(e.tooltipVisible),I=ne(e.tooltipTimeout),L=ne(e.defaultLabel),X=ne(e.label),te=ne(e.hideLabel),le=ne(e.inlineTextInputVisible),fe=ne(e.hasInlineTextInput),Fe=ne(e.markName),he=ne(e.labelAttr),ge=ne(e.selectedValue),ae=ne(e.dropdownValueKey),Ce=ne(e.inputRef||null),oe=ne([]);if(e.options){if(!Array.isArray(e.options))throw new Error("Invalid toolbar item options - "+e.options);oe.value?.push(...e.options)}const xe=(_={},...$)=>{Ie(_,...$),!S.value&&(h.value=!0)},qe=()=>{ze(),h.value=!1},et=_=>{d.value=_},kt=()=>{d.value=c},Ie=e.onActivate||(()=>null),ze=e.onDeactivate||(()=>null),Ve=()=>{const _={};return Object.keys(Q).forEach($=>{Q[$].value!==void 0&&(_[$]=Q[$].value)}),_},Q={id:t,name:r,type:n,command:o,noArgumentCommand:i,icon:s,tooltip:P,group:a,attributes:u,disabled:d,active:h,expand:m,nestedOptions:oe,style:p,isNarrow:g,isWide:k,minWidth:w,argument:y,parentItem:T,iconColor:R,hasCaret:M,splitButton:H,splitButtonCommand:B,dropdownStyles:Z,tooltipVisible:N,tooltipTimeout:I,defaultLabel:L,label:X,hideLabel:te,inlineTextInputVisible:le,hasInlineTextInput:fe,restoreEditorFocus:z,markName:Fe,labelAttr:he,childItem:C,allowWithoutEditor:l,dropdownValueKey:ae,selectedValue:ge,inputRef:Ce};return{...Q,unref:Ve,activate:xe,deactivate:qe,setDisabled:et,resetDisabled:kt,onActivate:Ie,onDeactivate:ze}};It(),gn();var RN=["onClick","innerHTML","aria-label","onKeydown"],MN={__name:"AlignmentButtons",emits:["select"],setup(e,{emit:t}){const{isHighContrastMode:n}=zi(),r=t,o=ne([]),i=[{key:"left",ariaLabel:"Align left",icon:tr.alignLeft},{key:"center",ariaLabel:"Align center",icon:tr.alignCenter},{key:"right",ariaLabel:"Align right",icon:tr.alignRight},{key:"justify",ariaLabel:"Justify",icon:tr.alignJustify}],s=c=>{r("select",c)},a=c=>{if(c===o.value.length-1)return;const d=o.value[c+1];d&&(d.setAttribute("tabindex","0"),d.focus())},l=c=>{if(c===0)return;const d=o.value[c-1];d&&(d.setAttribute("tabindex","0"),d.focus())},u=(c,d)=>{switch(c.key){case"ArrowLeft":l(d);break;case"ArrowRight":a(d);break;case"Enter":s(i[d].key);break;default:break}};return Rn(()=>{const c=o.value[0];c&&(c.setAttribute("tabindex","0"),c.focus())}),(c,d)=>(me(),_e("div",{class:en(["alignment-buttons",{"high-contrast":Ge(n)}])},[(me(),_e(Wt,null,or(i,(h,m)=>Le("div",{key:h.key,class:"sd-button-icon",onClick:p=>s(h.key),innerHTML:h.icon,"data-item":"btn-textAlign-option",role:"menuitem","aria-label":h.ariaLabel,ref_for:!0,ref_key:"alignmentButtonsRefs",ref:o,onKeydown:Jt(p=>u(p,m),["prevent"])},null,40,RN)),64))],2))}},LN=hn(MN,[["__scopeId","data-v-13e5f7a4"]]);It(),gn();var DN=["onClick","innerHTML","aria-label","onKeydown"],PN={__name:"StyleButtonsList",props:{buttons:{type:Array,required:!0},selectedStyle:{type:String,default:null},iconSize:{type:Number,default:25}},emits:["select"],setup(e,{emit:t}){const{isHighContrastMode:n}=zi(),r=t,o=e,i=ne([]),s=Se(()=>({width:`${o.iconSize}px`,height:`${o.iconSize}px`})),a=d=>{r("select",d)},l=d=>{if(d===i.value.length-1)return;const h=i.value[d+1];h&&(h.setAttribute("tabindex","0"),h.focus())},u=d=>{if(d===0)return;const h=i.value[d-1];h&&(h.setAttribute("tabindex","0"),h.focus())},c=(d,h)=>{switch(d.key){case"ArrowLeft":u(h);break;case"ArrowRight":l(h);break;case"Enter":a(o.buttons[h].key);break;default:break}};return Rn(()=>{const d=i.value[0];d&&(d.setAttribute("tabindex","0"),d.focus())}),(d,h)=>(me(),_e("div",{class:en(["style-buttons-list",{"high-contrast":Ge(n)}])},[(me(!0),_e(Wt,null,or(o.buttons,(m,p)=>(me(),_e("div",{key:m.key,class:en(["sd-button-icon",{"sd-selected":o.selectedStyle===m.key}]),style:vn(s.value),onClick:g=>a(m.key),innerHTML:m.icon,role:"menuitem","aria-label":m.ariaLabel,ref_for:!0,ref_key:"buttonRefs",ref:i,onKeydown:Jt(g=>c(g,p),["prevent"])},null,46,DN))),128))],2))}},Uk=hn(PN,[["__scopeId","data-v-44f37ff6"]]);const ON=[{key:"disc",icon:tr.bulletListDisc,ariaLabel:"Opaque circle"},{key:"circle",icon:tr.bulletListCircle,ariaLabel:"Outline circle"},{key:"square",icon:tr.bulletListSquare,ariaLabel:"Opaque square"}],FN=[{key:"decimal",icon:tr.numberedListDecimal,ariaLabel:"1. 2. 3."},{key:"decimal-paren",icon:tr.numberedListDecimalParen,ariaLabel:"1) 2) 3)"},{key:"upper-roman",icon:tr.numberedListUpperRoman,ariaLabel:"I. II. III."},{key:"lower-roman",icon:tr.numberedListLowerRoman,ariaLabel:"i. ii. iii."},{key:"upper-alpha",icon:tr.numberedListUpperAlpha,ariaLabel:"A. B. C."},{key:"upper-alpha-paren",icon:tr.numberedListUpperAlphaParen,ariaLabel:"A) B) C)"},{key:"lower-alpha",icon:tr.numberedListLowerAlpha,ariaLabel:"a. b. c."},{key:"lower-alpha-paren",icon:tr.numberedListLowerAlphaParen,ariaLabel:"a) b) c)"}];It(),gn();var BN=["onClick","onKeydown"],NN={class:"document-mode-column icon-column"},zN=["innerHTML"],HN={class:"document-mode-column text-column"},UN={class:"document-mode-type"},VN={class:"document-mode-description"},jN={__name:"DocumentMode",props:{options:{type:Array}},emits:["select"],setup(e,{emit:t}){const n=t,r=ne([]),{isHighContrastMode:o}=zi(),i=e,s=c=>{n("select",c)},a=c=>{if(c===r.value.length-1)return;const d=r.value[c+1];d&&(d.setAttribute("tabindex","0"),d.focus())},l=c=>{if(c===0)return;const d=r.value[c-1];d&&(d.setAttribute("tabindex","0"),d.focus())},u=(c,d)=>{switch(c.key){case"ArrowDown":a(d);break;case"ArrowUp":l(d);break;case"Enter":s(i.options[d]);break;default:break}};return Rn(()=>{r.value[0].setAttribute("tabindex","0"),r.value[0].focus()}),(c,d)=>(me(),_e("div",{class:en(["document-mode",{"high-contrast":Ge(o)}])},[(me(!0),_e(Wt,null,or(e.options,(h,m)=>(me(),_e("div",{class:en(["sd-option-item",{"sd-disabled":h.disabled}]),onClick:p=>s(h),"data-item":"btn-documentMode-option",role:"menuitem",ref_for:!0,ref_key:"documentModeRefs",ref:r,onKeydown:Jt(p=>u(p,m),["prevent"])},[Le("div",NN,[Le("div",{class:"icon-column__icon",innerHTML:h.icon},null,8,zN)]),Le("div",HN,[Le("div",UN,Ht(h.label),1),Le("div",VN,Ht(h.description),1)])],42,BN))),256))],2))}},GN=hn(jN,[["__scopeId","data-v-bee14d7a"]]);It(),gn();var WN={class:"linked-style-buttons","data-editor-ui-surface":""},KN=["onClick","onKeydown","aria-label"],qN={__name:"LinkedStyle",props:{styles:{type:Array,default:()=>[]},selectedOption:{type:String,default:null}},emits:["select"],setup(e,{emit:t}){const n=t,r=ne([]),o=e,i=d=>{n("select",d)},s=d=>{if(d===r.value.length-1)return;const h=r.value[d+1];h.setAttribute("tabindex","0"),h.focus()},a=d=>{if(d===0)return;const h=r.value[d-1];h.setAttribute("tabindex","0"),h.focus()},l=(d,h,m)=>{switch(d.key){case"ArrowDown":s(h);break;case"ArrowUp":a(h);break;case"Enter":d.preventDefault(),i(m);break;default:break}},u=d=>d?.name??d?.id??"",c=d=>{const h=d?.preview?.css;return h&&typeof h=="object"?h:void 0};return Rn(()=>{r.value[0]&&(r.value[0].setAttribute("tabindex","0"),r.value[0].focus())}),(d,h)=>(me(),_e("div",WN,[(me(!0),_e(Wt,null,or(o.styles,(m,p)=>(me(),_e("div",{key:m.id??p,class:en(["style-item",{selected:e.selectedOption===m.id}]),onClick:g=>i(m),onKeydown:g=>l(g,p,m),"aria-label":`Linked style - ${m.id??u(m)}`,ref_for:!0,ref_key:"styleRefs",ref:r},[Le("div",{class:"style-name","data-item":"btn-linkedStyles-option",style:vn(c(m))},Ht(u(m)),5)],42,KN))),128))]))}},YN=hn(qN,[["__scopeId","data-v-43b5dcca"]]);It(),gn();var XN=["placeholder"],QN={class:"sd-ai-writer__footer"},ZN={key:0,class:"sd-ai-writer__error",role:"alert"},JN=["disabled"],$N="https://sd-dev-express-gateway-i6xtm.ondigitalocean.app/insights",ez="You are an expert copywriter and you are immersed in a document editor. Only write what is asked for.",tz={__name:"AIWriter",props:{selectedText:{type:String,default:""},target:{type:Object,default:null},doc:{type:Object,default:null},apiKey:{type:String,default:""},endpoint:{type:String,default:""},restoreSelection:{type:Function,default:null},handleClose:{type:Function,required:!0}},setup(e){const t=e,n=ne(""),r=ne(!1),o=ne(""),i=ne(null),s=Se(()=>t.selectedText?"Insert prompt to update text":"Insert prompt to generate text"),a=Se(()=>n.value.trim().length>0&&!r.value);Rn(()=>{_t(()=>{i.value?.focus()})});function l(p){if(typeof p=="string")return p;if(!p||typeof p!="object")return"";const g=p.custom_prompt;if(Array.isArray(g)){const k=g[0];if(k&&typeof k.value=="string")return k.value}return g&&typeof g=="object"&&typeof g.value=="string"?g.value:typeof p.value=="string"?p.value:typeof p.text=="string"?p.text:""}async function u(p){const g={"Content-Type":"application/json"};t.apiKey&&(g["x-api-key"]=t.apiKey);const k=t.selectedText.trim(),w=k?`Rewrite the following text: "${k}" using these instructions: ${p}`:`Generate text based on the following prompt: ${p}`,S=await fetch(t.endpoint||$N,{method:"POST",headers:g,body:JSON.stringify({stream:!1,context:ez,insights:[{type:"custom_prompt",name:k?"text_rewrite":"text_generation",message:w,format:[{value:""}]}]})});if(!S.ok){const C=await S.text().catch(()=>"");throw new Error(C||`AI request failed with ${S.status}`)}const y=l((S.headers.get("content-type")||"").includes("application/json")?await S.json():await S.text()).trim();if(!y)throw new Error("AI returned no text.");return y}function c(p){return!p||typeof p!="object"?!0:!(p.success===!1||p.ok===!1)}function d(p){const g=t.doc;if(!g)throw new Error("Document API is unavailable.");t.restoreSelection?.();let k=null,w=!1;if(t.selectedText&&t.target&&typeof g.replace=="function"?(k=g.replace({target:t.target,text:p}),w=!0):t.target&&typeof g.insert=="function"?(k=g.insert({target:t.target,value:p,type:"text"}),w=!0):typeof g.insert=="function"&&(k=g.insert({value:p,type:"text"}),w=!0),!w)throw new Error("Document text insertion is unavailable.");if(!c(k))throw new Error("Unable to insert generated text.")}async function h(){if(a.value){o.value="",r.value=!0;try{d(await u(n.value.trim())),t.handleClose()}catch(p){o.value=p instanceof Error?p.message:String(p)}finally{r.value=!1}}}function m(p){p.key!=="Enter"||p.shiftKey||(p.preventDefault(),h())}return(p,g)=>(me(),_e("form",{class:"sd-ai-writer","data-item":"ai-writer",onSubmit:Jt(h,["prevent"])},[Ws(Le("textarea",{ref_key:"textareaRef",ref:i,"onUpdate:modelValue":g[0]||(g[0]=k=>n.value=k),class:"sd-ai-writer__input",placeholder:s.value,rows:"4",onKeydown:m},null,40,XN),[[ki,n.value]]),Le("div",QN,[o.value?(me(),_e("p",ZN,Ht(o.value),1)):ut("",!0),Le("button",{class:"sd-ai-writer__submit",type:"submit",disabled:!a.value},Ht(r.value?"Generating":"Generate"),9,JN)])],32))}},nz=hn(tz,[["__scopeId","data-v-67f6c6f7"]]);It(),gn();var rz=["aria-label","onClick","onKeydown"],oz=["innerHTML"],iz=["innerHTML"],Yp=7,sz={__name:"IconGridRow",props:{icons:{type:Array,required:!0},activeColor:{type:Object,required:!1}},emits:["select","clickoutside"],setup(e,{emit:t}){const n=t,r=e,o=Se(()=>p=>r.activeColor.value?r.activeColor.value.toUpperCase()===p.value:!1),i=(p,g)=>g===5||["#FFFFFF","#FAFF09"].includes(p)?{color:"#000"}:{color:"#FFF"},s=p=>{n("select",p.value)},a=ne([]),l=ne([]);Rn(()=>{if(!r.icons.every(g=>Array.isArray(g)))throw new Error("icon props must be 2d array");const p=l.value[0];p&&(p.setAttribute("tabindex","0"),p.focus({preventScroll:!0}))});const u=(p,g)=>{const k=Yp*p+g+1,w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},c=(p,g)=>{const k=Yp*p+g-1,w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},d=(p,g)=>{const k=g+Yp*(p+1),w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},h=(p,g)=>{const k=g+Yp*(p-1),w=l.value[k];w&&(w.setAttribute("tabindex","0"),w.focus({preventScroll:!0}))},m=(p,g,k,w)=>{switch(p.key){case"ArrowRight":u(g,k);break;case"ArrowLeft":c(g,k);break;case"ArrowDown":d(g,k);break;case"ArrowUp":h(g,k);break;case"Enter":s(w);break;case"Escape":n("clickoutside");break;default:break}};return(p,g)=>(me(!0),_e(Wt,null,or(e.icons,(k,w)=>(me(),_e("div",{class:"sd-option-row",key:w,role:"group",ref_for:!0,ref_key:"rowRefs",ref:a},[(me(!0),_e(Wt,null,or(k,(S,y)=>(me(),_e("div",{class:"sd-option",key:y,"aria-label":S.label,role:"menuitem",ref_for:!0,ref_key:"iconRefs",ref:l,onClick:Jt(C=>s(S),["stop","prevent"]),onKeydown:Jt(C=>m(C,w,y,S),["prevent"])},[Le("div",{class:"sd-option__icon",innerHTML:S.icon,style:vn(S.style)},null,12,oz),o.value(S)?(me(),_e("div",{key:0,class:"sd-option__check",innerHTML:Ge(tr).colorOptionCheck,style:vn(i(S.value,y))},null,12,iz)):ut("",!0)],40,rz))),128))]))),128))}},Vk=hn(sz,[["__scopeId","data-v-05eb02fc"]]),az=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M320 512c53.2 0 101.4-21.6 136.1-56.6l-298.3-235C140 257.1 128 292.3 128 320c0 106 86 192 192 192zM505.2 370.7c4.4-16.2 6.8-33.1 6.8-50.7c0-91.2-130.2-262.3-166.6-308.3C339.4 4.2 330.5 0 320.9 0l-1.8 0c-9.6 0-18.5 4.2-24.5 11.7C277.8 33 240.7 81.3 205.8 136L38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L505.2 370.7zM224 336c0 44.2 35.8 80 80 80c8.8 0 16 7.2 16 16s-7.2 16-16 16c-61.9 0-112-50.1-112-112c0-8.8 7.2-16 16-16s16 7.2 16 16z"/></svg>
|
|
101
101
|
`;It(),gn();var lz={class:"options-grid-wrap"},cz=["innerHTML"],uz={class:"option-grid-ctn"},dz={__name:"IconGrid",props:{icons:{type:Array,required:!0},customIcons:{type:Array,required:!1},activeColor:{type:Object,required:!1},hasNoneIcon:{type:Boolean,required:!1}},emits:["select","clickoutside"],setup(e,{emit:t}){const n=t,r=o=>{n("select",o)};return(o,i)=>(me(),_e("div",lz,[e.hasNoneIcon?(me(),_e("div",{key:0,class:"none-option",role:"menuitem","aria-label":"Clear color selection",onClick:i[0]||(i[0]=s=>r("none"))},[Le("span",{innerHTML:Ge(az),class:"none-icon"},null,8,cz),i[1]||(i[1]=Oi(" None ",-1))])):ut("",!0),Le("div",uz,[Gt(Vk,{icons:e.icons,"active-color":e.activeColor,onSelect:r},null,8,["icons","active-color"]),e.customIcons.flat().length?(me(),_e(Wt,{key:0},[i[2]||(i[2]=Le("span",{class:"option-grid-ctn__subtitle"},"Custom colors",-1)),Gt(Vk,{icons:e.customIcons,"active-color":e.activeColor,onSelect:r},null,8,["icons","active-color"])],64)):ut("",!0)])]))}},fz=hn(dz,[["__scopeId","data-v-52b0283a"]]);const B0=(e,t=null)=>{if(typeof t?.focus=="function"){t.focus();return}const n=e?.superdoc?.focus??e?.activeEditor?.focus;if(typeof n=="function"){n.call(e?.superdoc??e?.activeEditor,{preventScroll:!0});return}const r=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');r instanceof HTMLElement&&r.focus({preventScroll:!0})};It();var hz=e=>{e.expand.value=!1};const Ut=(e,t=null)=>({label:t,icon:tr.colorOption,value:e,style:{color:e,boxShadow:"0 0 5px 1px rgba(0, 0, 0, 0.1)",borderRadius:"50%"}}),N0=(e,t,n=[],r=!1)=>{const o=i=>{t.iconColor.value=i,e.emitCommand({item:t,argument:i}),hz(t),B0(e)};return Dr("div",{},[Dr(fz,{icons:pz,customIcons:n,activeColor:t.iconColor,hasNoneIcon:r,onSelect:o})])},pz=[[Ut("#111111","black"),Ut("#333333","dark gray"),Ut("#5C5C5C","medium gray"),Ut("#858585","light gray"),Ut("#ADADAD","very light gray"),Ut("#D6D6D6","transparent gray"),Ut("#FFFFFF","white")],[Ut("#860028","dark red"),Ut("#D2003F","red"),Ut("#DB3365","coral red"),Ut("#E4668C","light red"),Ut("#ED99B2","pale pink"),Ut("#F6CCD9","transparent pink"),Ut("#FF004D","bright pink")],[Ut("#83015E","dark purple"),Ut("#CD0194","purple"),Ut("#D734A9","orchid"),Ut("#E167BF","light purple"),Ut("#EB99D4","lavender"),Ut("#F5CCEA","transparent pink"),Ut("#FF00A8","neon pink")],[Ut("#8E220A","maroon"),Ut("#DD340F","red-orange"),Ut("#E45C3F","burnt orange"),Ut("#EB856F","peach"),Ut("#F1AE9F","pale peach"),Ut("#F8D6CF","transparent peach"),Ut("#FF7A00","orange")],[Ut("#947D02","olive"),Ut("#E7C302","mustard yellow"),Ut("#ECCF35","yellow"),Ut("#F1DB67","light yellow"),Ut("#F5E79A","very pale yellow"),Ut("#FAF3CC","transparent yellow"),Ut("#FAFF09","neon yellow")],[Ut("#055432","forest green"),Ut("#07834F","green"),Ut("#399C72","medium green"),Ut("#6AB595","light green"),Ut("#9CCDB9","mint"),Ut("#CDE6DC","transparent mint"),Ut("#05F38F","bright teal")],[Ut("#063E7E","navy blue"),Ut("#0A60C5","blue"),Ut("#3B80D1","sky blue"),Ut("#6CA0DC","cornflower blue"),Ut("#9DBFE8","light blue"),Ut("#CEDFF3","very light blue"),Ut("#21c8ce","cyan")],[Ut("#3E027A","deep purple"),Ut("#6103BF","indigo"),Ut("#8136CC","violet"),Ut("#A068D9","lavender pink"),Ut("#C09AE6","light lilac"),Ut("#DFCDF2","transparent lilac"),Ut("#A91DFF","neon purple")]];It(),gn();var mz=["data-cols","data-rows","onKeydown","onClick"],gz=["aria-valuetext"],Xp=5,vz={__name:"TableGrid",emits:["select","clickoutside"],setup(e,{emit:t}){const n=t,r=ne(0),o=ne(0),{isHighContrastMode:i}=zi(),s=ne([]),a=d=>{let h=d.target;h.dataset.grid||l([...h.parentElement.querySelectorAll("[data-item]")],parseInt(h.dataset.cols,10),parseInt(h.dataset.rows,10))},l=(d,h,m)=>{o.value=h,r.value=m;for(let p=0;p<d.length;p++){let g=d[p],k=parseInt(g.dataset.cols,10),w=parseInt(g.dataset.rows,10);k<=h&&w<=m?g.classList.add("sd-selected"):g.classList.remove("sd-selected")}},u=({cols:d,rows:h})=>{n("select",{cols:d,rows:h})},c=(d,h,m)=>{let p=h-1,g=m-1;switch(d.key){case"ArrowRight":{if(p>=4)return;const k=g*Xp;s.value[k+p+1].setAttribute("tabindex","0"),s.value[k+p+1].focus(),l(s.value,h+1,m);break}case"ArrowLeft":{if(p<=0)return;const k=g*Xp;s.value[k+p-1].setAttribute("tabindex","0"),s.value[k+p-1].focus(),l(s.value,h-1,m);break}case"ArrowDown":{if(g>=4)return;const k=(g+1)*Xp;s.value[k+p].setAttribute("tabindex","0"),s.value[k+p].focus(),l(s.value,h,m+1);break}case"ArrowUp":{if(g<=0)return;const k=(g-1)*Xp;s.value[k+p].setAttribute("tabindex","0"),s.value[k+p].focus(),l(s.value,h,m-1);break}case"Enter":u({cols:h,rows:m});break;default:break}};return Rn(()=>{s.value[0].setAttribute("tabindex","0"),s.value[0].focus(),l(s.value,1,1)}),(d,h)=>(me(),_e("div",{class:en(["toolbar-table-grid-wrapper",{"high-contrast":Ge(i)}])},[Le("div",{class:"toolbar-table-grid",onMouseover:a,"data-grid":"true"},[(me(),_e(Wt,null,or(5,m=>(me(),_e(Wt,{key:m},[(me(),_e(Wt,null,or(5,p=>Le("div",{class:"toolbar-table-grid__item",key:`${m}_${p}`,"data-cols":p,"data-rows":m,"data-item":"true",ref_for:!0,ref_key:"tableGridItems",ref:s,onKeydown:Jt(g=>c(g,p,m),["prevent"]),onClick:Jt(g=>u({cols:p,rows:m}),["stop","prevent"])},null,40,mz)),64))],64))),64))],32),Le("div",{class:"toolbar-table-grid-value","aria-valuetext":`${r.value} x ${o.value}`},Ht(r.value)+" x "+Ht(o.value),9,gz)],2))}},yz=hn(vz,[["__scopeId","data-v-b87d6ca2"]]);It(),gn();var bz={class:"toolbar-table-actions"},wz=["onClick","data-item","ariaLabel"],Cz={class:"toolbar-table-actions__icon"},_z=["innerHTML"],Sz={class:"toolbar-table-actions__label"},kz={__name:"TableActions",props:{options:{type:Array}},emits:["select"],setup(e,{emit:t}){const n=t,r=o=>{n("select",{command:o.command})};return(o,i)=>(me(),_e("div",bz,[(me(!0),_e(Wt,null,or(e.options,s=>(me(),_e("div",{class:en(["toolbar-table-actions__item",{"toolbar-table-actions__item--border":s.bottomBorder}]),onClick:a=>r(s),"data-item":s.props?.["data-item"]||"",ariaLabel:s.props?.ariaLabel,role:"menuitem"},[Le("div",Cz,[Le("div",{class:"toolbar-table-actions__icon-wrapper",innerHTML:s.icon},null,8,_z)]),Le("div",Sz,Ht(s.label),1)],10,wz))),256))]))}},Az=hn(kz,[["__scopeId","data-v-0cdad084"]]),Iz=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"/></svg>
|
|
102
|
-
`;It();var ws=e=>{e.expand.value=!1};function z0(e,t){const n={...e??{}};return t?n.href=t:delete n.href,n}function jk(e){const t=Array.isArray(e?.segments)?e.segments:[];if(e?.kind!=="text"||!t.length)return null;const n=t[0],r=t[t.length-1];if(!n?.blockId||!r?.blockId||!n.range||!r.range)return null;const o=e.story;return{kind:"selection",start:{kind:"text",blockId:n.blockId,offset:n.range.start??0,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end??0,...o?{story:o}:{}},...o?{story:o}:{}}}function Ez(e){return typeof e?.quotedText=="string"?e.quotedText:typeof e?.text=="string"?e.text:""}function Gk(e){return e.ui?.selection?.get?.()??e.ui?.selection?.current?.()??null}function xz(e){return!!(e.config?.superdoc?.config?.modules?.ai||e.superdoc?.config?.modules?.ai)}function Tz(e){return e.config?.superdoc?.config?.modules?.ai??e.superdoc?.config?.modules?.ai??{}}const Rz=({superToolbar:e,toolbarIcons:t,toolbarTexts:n,toolbarFonts:r,hideButtons:o,availableWidth:i,role:s,isDev:a=!1}={})=>{const l=Cn({type:"button",name:"bold",command:"toggleBold",icon:t.bold,tooltip:n.bold,attributes:{ariaLabel:"Bold"}}),u=(r??_N).map(TN),c=Cn({type:"dropdown",name:"fontFamily",tooltip:n.fontFamily,command:"setFontFamily",defaultLabel:"Arial",label:"Arial",markName:"textStyle",labelAttr:"fontFamily",hasCaret:!0,hasInlineTextInput:!0,inlineTextInputVisible:!0,isWide:!0,style:{width:"116px"},suppressActiveHighlight:!0,attributes:{ariaLabel:"Font family"},options:u,onActivate:({fontFamily:We}={},St=!1)=>{if(St){c.label.value="",c.selectedValue.value="";return}if(!We)return;We=We.split(",")[0],c.label.value=We;const Nt=u.find(Dt=>Dt.label===c.defaultLabel.value),cn=u.find(Dt=>Dt.label===We);cn?c.selectedValue.value=cn.key:Nt?c.selectedValue.value=Nt.key:c.selectedValue.value=""},onDeactivate:()=>{c.label.value=c.defaultLabel.value;const We=u.find(St=>St.label===c.defaultLabel.value);We?c.selectedValue.value=We.key:c.selectedValue.value=""}}),d=Cn({type:"dropdown",name:"ai",dropdownStyles:{padding:0,outline:"none"},tooltip:n.ai,icon:t.ai,hideLabel:!0,hasCaret:!1,isWide:!0,suppressActiveHighlight:!0,attributes:{ariaLabel:"AI"},options:[{type:"render",key:"ai",render:()=>h(d)}]});function h(We){const St=Gk(e),Nt=St?.selectionTarget??jk(St?.target),cn=St?.empty?"":Ez(St),Dt=Tz(e),un=()=>ws(We),Ft=()=>{const Me=e.pendingSelectionCapture;Me&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Me)};return Dr("div",{},[Dr(nz,{handleClose:un,selectedText:cn,target:Nt,doc:e.superdoc?.activeEditor?.doc??null,apiKey:Dt?.apiKey||e.config?.aiApiKey||"",endpoint:Dt?.endpoint||e.config?.aiEndpoint||"",restoreSelection:Ft})])}const m=kN,p=Cn({type:"dropdown",name:"fontSize",defaultLabel:"12",label:"12",style:{width:"56px"},markName:"textStyle",labelAttr:"fontSize",tooltip:n.fontSize,hasCaret:!0,hasInlineTextInput:!0,inlineTextInputVisible:!0,suppressActiveHighlight:!0,isWide:!0,command:"setFontSize",attributes:{ariaLabel:"Font size"},options:m,onActivate:({fontSize:We},St=!1)=>{if(St){p.label.value="",p.selectedValue.value="";return}const Nt=m.find(Ft=>Ft.label===String(p.defaultLabel.value));if(!We){p.label.value=p.defaultLabel.value,Nt?p.selectedValue.value=Nt.key:p.selectedValue.value="";return}let cn=fB(We,12);cn<8&&(cn=8),cn>96&&(cn=96);let Dt=String(cn);const un=m.find(Ft=>Ft.label===Dt||Ft.key===Dt);un?p.selectedValue.value=un.key:p.selectedValue.value="",p.label.value=Dt},onDeactivate:()=>{p.label.value=p.defaultLabel.value;const We=m.find(St=>St.label===String(p.defaultLabel.value));We?p.selectedValue.value=We.key:p.selectedValue.value=""}}),g=Cn({type:"separator",name:"separator",isNarrow:!0}),k=Cn({type:"button",name:"italic",command:"toggleItalic",icon:t.italic,active:!1,tooltip:n.italic,attributes:{ariaLabel:"Italic"}}),w=Cn({type:"button",name:"underline",command:"toggleUnderline",icon:t.underline,active:!1,tooltip:n.underline,attributes:{ariaLabel:"Underline"}}),S=Cn({type:"button",name:"strike",command:"toggleStrike",icon:t.strikethrough,active:!1,tooltip:n.strikethrough,attributes:{ariaLabel:"Strikethrough"}}),y=Cn({type:"dropdown",name:"highlight",icon:t.highlight,hideLabel:!0,markName:"highlight",labelAttr:"color",active:!1,tooltip:n.highlight,command:"setHighlight",noArgumentCommand:"unsetHighlight",suppressActiveHighlight:!0,attributes:{ariaLabel:"Highlight"},options:[{key:"color",type:"render",render:()=>N0(e,y,[],!0)}],onActivate:({color:We})=>{y.iconColor.value=We||""},onDeactivate:()=>y.iconColor.value=""}),C=Cn({type:"dropdown",name:"color",icon:t.color,hideLabel:!0,markName:"textStyle",labelAttr:"color",active:!1,tooltip:n.color,command:"setColor",suppressActiveHighlight:!0,attributes:{ariaLabel:"Color"},options:[{key:"color",type:"render",render:()=>N0(e,C)}],onActivate:({color:We})=>{C.iconColor.value=We},onDeactivate:()=>C.iconColor.value="#000"}),T=Cn({type:"button",name:"search",allowWithoutEditor:!0,active:!1,icon:t.search,tooltip:n.search,group:"right",attributes:{ariaLabel:"Search"}}),R=Cn({type:"dropdown",name:"link",markName:"link",icon:t.link,active:!1,tooltip:n.link,attributes:{ariaLabel:"Link dropdown"},options:[{type:"render",key:"linkDropdown",render:()=>M(R)}],onActivate:({href:We})=>{R.attributes.value=z0(R.attributes.value,We)},onDeactivate:()=>{R.attributes.value=z0(R.attributes.value,null),R.expand.value=!1}});function M(We){const St=Gk(e),Nt=St?.selectionTarget??jk(St?.target),cn=()=>{const Dt=e.pendingSelectionCapture;Dt&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Dt)};return Dr("div",{},[Dr(pS,{ui:e.ui,linkItem:We,textTarget:Nt,restoreSelection:cn,closePopover:()=>ws(We),goToAnchor:()=>{ws(We);const Dt=We.attributes.value?.href;if(!Dt)return;const un=Dt.slice(1),Ft=(e.ui?.viewport?.getHost?.()??null)?.querySelector?.(`a[name='${un}']`);Ft&&tf(Ft)}})])}const H=Cn({type:"options",name:"linkInput",command:"toggleLink",active:!1});R.childItem=H,H.parentItem=R;const B=Cn({type:"button",name:"image",command:"startImageUpload",icon:t.image,active:!1,tooltip:n.image,disabled:!1,attributes:{ariaLabel:"Image"}}),z=Cn({type:"button",name:"tableOfContents",command:"insertTableOfContents",icon:t.tableOfContents,active:!1,tooltip:n.tableOfContents,disabled:!1,attributes:{ariaLabel:"Table of contents"}}),Z=Cn({type:"dropdown",name:"table",icon:t.table,hideLabel:!0,labelAttr:"table",active:!1,tooltip:n.table,command:"insertTable",suppressActiveHighlight:!0,attributes:{ariaLabel:"Table"},options:[{key:"table",type:"render",render:()=>P(Z)}]});function P(We){return Dr("div",{},[Dr(yz,{onSelect:Nt=>{e.emitCommand({item:We,argument:Nt}),ws(We),B0(e)}})])}const N=Cn({type:"dropdown",name:"tableActions",command:"executeTableCommand",tooltip:n.tableActions,icon:t.tableActions,hideLabel:!0,disabled:!0,attributes:{ariaLabel:"Table actions"},options:[{type:"render",render:()=>L(N)}]}),I=[{label:n.addRowBefore,command:"addRowBefore",icon:t.addRowBefore,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add row before"}},{label:n.addRowAfter,command:"addRowAfter",icon:t.addRowAfter,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add row after"}},{label:n.addColumnBefore,command:"addColumnBefore",icon:t.addColumnBefore,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add column before"}},{label:n.addColumnAfter,command:"addColumnAfter",icon:t.addColumnAfter,bottomBorder:!0,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add column after"}},{label:n.deleteRow,command:"deleteRow",icon:t.deleteRow,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete row"}},{label:n.deleteColumn,command:"deleteColumn",icon:t.deleteColumn,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete column"}},{label:n.deleteTable,command:"deleteTable",icon:t.deleteTable,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete table"}},{label:n.removeBorders,command:"deleteCellAndTableBorders",icon:t.deleteBorders,bottomBorder:!0,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete cell and table borders"}},{label:n.mergeCells,command:"mergeCells",icon:t.mergeCells,props:{"data-item":"btn-tableActions-option",ariaLabel:"Merge cells"}},{label:n.splitCell,command:"splitCell",icon:t.splitCell,props:{"data-item":"btn-tableActions-option",ariaLabel:"Split cells"}},{label:n.fixTables,command:"fixTables",icon:t.fixTables,props:{"data-item":"btn-tableActions-option",ariaLabel:"Fix tables"}}];function L(We){return Dr(Az,{options:I,onSelect:St=>{ws(We);const{command:Nt}=St;e.emitCommand({item:We,argument:{command:Nt}})}})}const X=Cn({type:"dropdown",name:"textAlign",tooltip:n.textAlign,icon:t.alignLeft,command:"setTextAlign",hasCaret:!0,markName:"textAlign",labelAttr:"textAlign",suppressActiveHighlight:!0,attributes:{ariaLabel:"Text align"},options:[{type:"render",render:()=>Dr("div",{},[Dr(LN,{onSelect:St=>{ws(X);const Nt={...X,command:"setTextAlign"};Nt.command="setTextAlign",e.emitCommand({item:Nt,argument:St}),te(X,St)}})]),key:"alignment"}],onActivate:({textAlign:We})=>{te(X,We)},onDeactivate:()=>{te(X,"left")}}),te=(We,St)=>{let Nt=St==="both"?"justify":St,cn={left:t.alignLeft,right:t.alignRight,center:t.alignCenter,justify:t.alignJustify},Dt=cn[Nt]??cn.left;We.icon.value=Dt},le=Cn({type:"dropdown",name:"list",command:"toggleBulletListStyle",splitButton:!0,splitButtonCommand:"toggleBulletList",icon:t.bulletList,hasCaret:!0,tooltip:n.bulletList,restoreEditorFocus:!0,attributes:{ariaLabel:"Bullet list"},options:[{type:"render",key:"bullet-style-buttons",render:()=>{const We=St=>{ws(le);const Nt={...le,command:"toggleBulletListStyle"};e.emitCommand({item:Nt,argument:St})};return Dr(Uk,{buttons:ON,iconSize:25,selectedStyle:le.selectedValue.value,onSelect:We})}}]}),fe=Cn({type:"dropdown",name:"numberedlist",command:"toggleOrderedListStyle",splitButton:!0,splitButtonCommand:"toggleOrderedList",icon:t.numberedList,hasCaret:!0,tooltip:n.numberedList,restoreEditorFocus:!0,attributes:{ariaLabel:"Numbered list"},options:[{type:"render",key:"numbered-style-buttons",render:()=>{const We=St=>{ws(fe);const Nt={...fe,command:"toggleOrderedListStyle"};e.emitCommand({item:Nt,argument:St})};return Dr(Uk,{buttons:FN,iconSize:30,selectedStyle:fe.selectedValue.value,onSelect:We})}}]}),Fe=Cn({type:"button",name:"indentleft",command:"decreaseTextIndent",icon:t.indentLeft,active:!1,tooltip:n.indentLeft,disabled:!1,attributes:{ariaLabel:"Left indent"}}),he=Cn({type:"button",name:"indentright",command:"increaseTextIndent",icon:t.indentRight,active:!1,tooltip:n.indentRight,disabled:!1,attributes:{ariaLabel:"Right indent"}}),ge=Cn({type:"overflow",name:"overflow",command:null,icon:t.overflow,active:!1,disabled:!1,attributes:{ariaLabel:"Overflow items"}}),ae=Cn({type:"dropdown",name:"zoom",allowWithoutEditor:!0,tooltip:n.zoom,defaultLabel:"100%",label:"100%",hasCaret:!0,command:"setZoom",isWide:!0,style:{width:"71px",minWidth:"71px"},inlineTextInputVisible:!1,hasInlineTextInput:!0,attributes:{ariaLabel:"Zoom"},options:[{label:"50%",key:.5,props:{"data-item":"btn-zoom-option"}},{label:"75%",key:.75,props:{"data-item":"btn-zoom-option"}},{label:"90%",key:.9,props:{"data-item":"btn-zoom-option"}},{label:"100%",key:1,props:{"data-item":"btn-zoom-option"}},{label:"125%",key:1.25,props:{"data-item":"btn-zoom-option"}},{label:"150%",key:1.5,props:{"data-item":"btn-zoom-option"}},{label:"200%",key:2,props:{"data-item":"btn-zoom-option"}}],onActivate:({zoom:We})=>{We&&(ae.label.value=We)}}),Ce=Cn({type:"dropdown",name:"measurementUnit",allowWithoutEditor:!0,tooltip:n.measurementUnit,defaultLabel:"in",label:"in",hasCaret:!0,command:"setMeasurementUnit",group:"right",style:{width:"52px",minWidth:"52px"},inlineTextInputVisible:!1,hasInlineTextInput:!1,attributes:{ariaLabel:"Measurement unit"},options:[{label:"Inches",key:"in",props:{"data-item":"btn-measurement-unit-option"}},{label:"Centimeters",key:"cm",props:{"data-item":"btn-measurement-unit-option"}}],onActivate:({measurementUnit:We})=>{We&&(Ce.label.value=We)}}),oe=Cn({type:"button",name:"undo",disabled:!0,tooltip:n.undo,command:"undo",icon:t.undo,group:"left",attributes:{ariaLabel:"Undo"}}),xe=Cn({type:"button",disabled:!0,name:"redo",tooltip:n.redo,command:"redo",icon:t.redo,group:"left",attributes:{ariaLabel:"Redo"}}),qe=Cn({type:"button",disabled:!1,name:"acceptTrackedChangeBySelection",tooltip:n.trackChangesAccept,command:"acceptTrackedChangeFromToolbar",icon:t.trackChangesAccept,group:"left",attributes:{ariaLabel:"Accept tracked changes"}}),et=Cn({type:"button",disabled:!1,name:"rejectTrackedChangeOnSelection",tooltip:n.trackChangesReject,command:"rejectTrackedChangeFromToolbar",icon:t.trackChangesReject,group:"left",attributes:{ariaLabel:"Reject tracked changes"}}),kt=Cn({type:"button",name:"clearFormatting",command:"clearFormat",tooltip:n.clearFormatting,icon:t.clearFormatting,attributes:{ariaLabel:"Clear formatting"}}),Ie=Cn({type:"button",name:"copyFormat",tooltip:n.copyFormat,icon:t.copyFormat,command:"copyFormat",active:!1,attributes:{ariaLabel:"Copy formatting"}}),ze=(We,St)=>We==="editor"?St:We==="suggester"?St.filter(Nt=>Nt.value==="suggesting"):St.filter(Nt=>Nt.value==="viewing"),Ve=We=>We==="editor"?"Editing":We==="suggester"?"Suggesting":"Viewing",Q=Cn({type:"dropdown",name:"documentMode",command:"setDocumentMode",allowWithoutEditor:!0,icon:t.documentMode,defaultLabel:Ve(s),label:Ve(s),hasCaret:s==="editor",isWide:!0,style:{display:"flex",justifyContent:"flex-end"},inlineTextInputVisible:!1,hasInlineTextInput:!1,group:"right",disabled:s!=="editor",attributes:{dropdownPosition:"right",className:"sd-toolbar-item--doc-mode",ariaLabel:"Document mode"},options:[{type:"render",render:()=>$(Q)}]}),_=[{label:n.documentEditingMode,value:"editing",icon:t.documentEditingMode,description:n.documentEditingModeDescription},{label:n.documentSuggestingMode,value:"suggesting",icon:t.documentSuggestingMode,description:n.documentSuggestingModeDescription},{label:n.documentViewingMode,value:"viewing",icon:t.documentViewingMode,description:n.documentViewingModeDescription}];function $(We){return Dr(GN,{options:ze(s,_),onSelect:St=>{const Nt=e.superdoc?.activeEditor??e.activeEditor;ws(We);const{label:cn,icon:Dt,value:un}=St;Q.label.value=cn,Q.icon.value=Dt,e.emitCommand({item:Q,argument:un}),B0(e,Nt)}})}const F=new Map([["separator",20],["zoom",71],["measurementUnit",52],["fontFamily",118],["fontSize",57],["textAlign",40],["linkedStyles",142],["documentMode",47],["default",32]]),j=["search","ruler","undo","overflow","documentMode"],V=Cn({type:"button",name:"ruler",command:"toggleRuler",allowWithoutEditor:!0,icon:t.ruler,active:!1,tooltip:n.ruler,attributes:{ariaLabel:"Ruler"}}),G=Cn({type:"button",name:"formattingMarks",command:"toggleFormattingMarks",allowWithoutEditor:!0,icon:t.formattingMarks,active:!1,tooltip:n.formattingMarks,attributes:{ariaLabel:"Formatting marks"}}),J=Cn({type:"dropdown",name:"linkedStyles",command:"setLinkedStyle",tooltip:n.linkedStyles,icon:t.paintbrush,defaultLabel:n.formatText,label:n.formatText,hasCaret:!0,isWide:!0,style:{width:"140px"},suppressActiveHighlight:!0,disabled:!1,attributes:{className:"sd-toolbar-item--linked-styles",ariaLabel:"Linked styles"},options:[{type:"render",key:"linkedStyle",render:()=>{const We=Nt=>{ws(J);const cn=typeof Nt=="string"?Nt:Nt?.id??null;if(!cn)return;const Dt={...J,command:"setLinkedStyle"};e.emitCommand({item:Dt,argument:cn})},St=e.getActiveLinkedStyleId?.()??null;return Dr("div",{},[Dr(YN,{styles:e.getLinkedStyleOptions?.()??[],onSelect:We,selectedOption:St})])}}],onActivate:({styleId:We,styleName:St})=>{const Nt=St||We;J.label.value=We&&We!=="Normal"?String(Nt):n.formatText,J.disabled.value=!1},onDeactivate:()=>{J.disabled.value=!0,J.label.value=n.formatText}}),K=(We,St)=>{if(St.value==We)return Dr("div",{innerHTML:Iz,class:"dropdown-select-icon"})},W=Cn({type:"dropdown",name:"lineHeight",tooltip:n.lineHeight,icon:t.lineHeight,hasCaret:!1,hasInlineTextInput:!1,hideLabel:!0,inlineTextInputVisible:!1,suppressActiveHighlight:!0,isWide:!1,command:"setLineHeight",dropdownValueKey:"key",selectedValue:"1",attributes:{ariaLabel:"Line height"},options:[1,1.15,1.5,2,2.5,3].map(We=>({label:We.toFixed(2),key:We,icon:()=>K(We,W.selectedValue),props:{"data-item":"btn-lineHeight-option"}}))}),ue=20,be=32,we=j.reduce((We,St)=>We+(F.get(St)||F.get("default")),0),Te=["linkedStyles","clearFormatting","copyFormat","formattingMarks"],rt=["zoom","fontFamily","fontSize","redo"],nt=i<=kf.lg,wt=e.config?.showFormattingMarksButton===!0,Zt=e.config?.showTableOfContentsButton===!0;nt&&(Q.attributes.value={...Q.attributes.value,className:`${Q.attributes.value.className} sd-toolbar-item--doc-mode-compact`}),nt&&(J.attributes.value={...J.attributes.value,className:`${J.attributes.value.className} sd-toolbar-item--linked-styles-compact`});let Ct=[oe,xe,qe,et,T,ae,c,g,p,g,l,k,w,S,C,y,g,R,B,...Zt?[z]:[],Z,N,g,X,le,fe,Fe,he,W,g,J,g,V,Ce,...wt?[G]:[],Ie,kt,...xz(e)?[d]:[],ge,Q];if(i<=kf.md&&o&&(Ct=Ct.filter(We=>We.type!=="separator")),e.config.mode!=="docx"){const We=Ct.findIndex(Nt=>Nt.name.value==="linkedStyles");Ct.splice(We-1,2);const St=["ruler","zoom","undo","redo"];Ct=Ct.filter(Nt=>!St.includes(Nt.name.value))}const Ot=[];a||(s==="viewer"&&Ot.push(qe,et),Ct=Ct.filter(We=>!Ot.includes(We)));const Bt=We=>j.includes(We.name.value),on=[],Fn=[];let Vt=be+we;return Ct.forEach(We=>{const St=F.get(We.name.value)||F.get("default");if(i<kf.xl+ue&&Te.includes(We.name.value)&&o){if(on.push(We),We.name.value==="linkedStyles"){const Nt=Ct.findIndex(cn=>cn.name.value==="linkedStyles");Ct.splice(Nt+1,1)}return}if(i<kf.sm&&rt.includes(We.name.value)&&o){on.push(We);return}if(Bt(We)){Fn.push(We),Vt+=St;return}Vt<i||!o?(Fn.push(We),Vt+=St):on.push(We)}),{defaultItems:Fn,overflowItems:on.filter(We=>We.type!=="separator")}},Wk={bold:"Bold",fontFamily:"Font family",ai:"AI text generation",fontSize:"Font size",italic:"Italic",underline:"Underline",highlight:"Highlight color",strikethrough:"Strikethrough",color:"Text color",search:"Search",link:"Link",image:"Image",tableOfContents:"Table of contents",table:"Insert table",tableActions:"Table options",addRowBefore:"Insert row above",addRowAfter:"Insert row below",addColumnBefore:"Insert column left",addColumnAfter:"Insert column right",deleteRow:"Delete row",deleteColumn:"Delete column",deleteTable:"Delete table",removeBorders:"Remove borders",mergeCells:"Merge cells",splitCell:"Split cell",fixTables:"Fix tables",textAlign:"Alignment",bulletList:"Bullet list",numberedList:"Numbered list",indentLeft:"Left indent",indentRight:"Right indent",directionLtr:"Left-to-right",directionRtl:"Right-to-left",zoom:"Zoom",measurementUnit:"Measurement unit",undo:"Undo",redo:"Redo",trackChanges:"Track Changes",trackChangesAccept:"Accept changes under selection",trackChangesReject:"Reject changes under selection",trackChangesOriginal:"Toggle Show Original",trackChangesFinal:"Toggle Show Final",clearFormatting:"Clear formatting",copyFormat:"Format painter",lineHeight:"Line height",formatText:"Format text",ruler:"Show or hide ruler",formattingMarks:"Show or hide formatting marks",pageBreak:"Insert page break",documentEditingMode:"Editing",documentSuggestingMode:"Suggesting",documentViewingMode:"Viewing",documentEditingModeDescription:"Edit document directly",documentSuggestingModeDescription:"Edits become suggestions",documentViewingModeDescription:"View clean version of document only",linkedStyles:"Linked styles"},Mz=e=>e?typeof e!="string"?e instanceof HTMLElement?e:null:e.startsWith("#")||e.startsWith(".")?document.querySelector(e):document.getElementById(e):null;It();function Kk(e){return oB(e)??F0[e]??null}function Qp(e,t,n,r={}){if(!e?.commands||!t||typeof e.commands.has=="function"&&!e.commands.has(t))return!1;const o=typeof e.commands.executeAsync=="function"?e.commands.executeAsync:e.commands.execute;if(typeof o!="function")return!1;const i=n===void 0?o.call(e.commands,t):o.call(e.commands,t,n);return i&&typeof i.then=="function"&&Promise.resolve(i).then(()=>r.onSettled?.(),s=>{r.onError?.(s),r.onSettled?.()}),!0}var Lz=new Set(["bold","italic","underline","strike","color","highlight","link","clearFormatting","textAlign","list","numberedlist","indentleft","indentright","lineHeight","linkedStyles"]),Dz=new Set(["list","numberedlist"]);function Pz(e,t){if(e==="fontFamily"||e==="fontSize"||Dz.has(e)&&t?.disabled&&t?.supported!==!1&&t?.reason==null)return!0;if(!Lz.has(e))return!1;const n=t?.reason;return n==="range-selection-required"||n==="selection-required"}function qk(e){return!!e?.closest?.("[data-editor-ui-surface], .toolbar-dropdown-menu, .sd-toolbar-dropdown-menu, .sd-tooltip-content")}function Oz(e){return["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)}var Fz=class extends Dm.default{config={selector:null,toolbarGroups:["left","center","right"],role:"editor",icons:{...tr},texts:{...Wk},fonts:null,hideButtons:!0,responsiveToContainer:!1,mode:"docx",excludeItems:[],groups:null,customButtons:[],showFormattingMarksButton:!1,showTableOfContentsButton:!1};toolbarItems=[];overflowItems=[];#t=null;#n=null;isDev=!1;role="editor";superdoc;toolbarContainer=null;toolbar=null;_detachFontsChanged=null;constructor(e={}){if(super(),this.config={...this.config,...e},this.toolbarItems=[],this.overflowItems=[],this.isDev=e.isDev||!1,this.superdoc=e.superdoc,this.role=e.role||"editor",this.toolbarContainer=null,this.config.icons={...tr,...e.icons},this.config.texts={...Wk,...e.texts},this.config.hideButtons=e.hideButtons??!0,this.config.responsiveToContainer=e.responsiveToContainer??!1,this.activeEditor=e.editor??this.superdoc?.activeEditor??null,this.ui=null,this.snapshot=null,this._unsubscribeController=null,this._detachFormatPainterModeChange=null,this._customCommandRegs=new Map,this._lastFontOptionsSignature="",!this.config.selector&&this.config.element&&(this.config.selector=this.config.element),this.toolbarContainer=Mz(this.config.selector),this.toolbarContainer){const t=(this.config?.uiDisplayFallbackFont||"").toString().trim()||"Arial, Helvetica, sans-serif";this.toolbarContainer.style.setProperty("--sd-ui-font-family",t)}try{if(this.#e(),this.#u(),this.#l(),this.#s(),this._lastFontOptionsSignature=this.#o(),!this.toolbarContainer){this.updateToolbarState();return}this.app=Hl(xN),this.app.directive("click-outside",Fv),this.app.config.globalProperties.$toolbar=this,this.toolbar=this.app.mount(this.toolbarContainer),this.updateToolbarState()}catch(t){try{this.destroy()}catch{}throw t}}#e(){this.ui=this.superdoc?.ui??null,this.ui&&(this.snapshot=this.ui.toolbar.getSnapshot(),this._unsubscribeController=this.ui.toolbar.subscribe(()=>{this.snapshot=this.ui.toolbar.getSnapshot(),this.updateToolbarState()}),this._detachFormatPainterModeChange=this.ui.formatPainter.onModeChange(e=>{e==="armed"||e==="persistent"?this.#D():this.#k()}))}#i(){this._unsubscribeController?.(),this._unsubscribeController=null,this._detachFormatPainterModeChange?.(),this._detachFormatPainterModeChange=null,this.#k();for(const e of this._customCommandRegs.values())try{e.unregister?.()}catch{}this._customCommandRegs.clear(),this.ui=null,this.snapshot=null}#s(){if(!this.superdoc||typeof this.superdoc.on!="function"||typeof this.superdoc.off!="function")return;const e=()=>{const t=this.#o();t!==this._lastFontOptionsSignature&&(this._lastFontOptionsSignature=t,this.#m()),this.updateToolbarState()};this.superdoc.on("fonts-changed",e),this._detachFontsChanged=()=>{this.superdoc?.off?.("fonts-changed",e)}}#a(){this._detachFontsChanged?.(),this._detachFontsChanged=null}#u(){if(Array.isArray(this.config.groups)){this.config.toolbarGroups=this.config.groups,this.config.groups=null;return}this.config.groups&&!Array.isArray(this.config.groups)&&Object.keys(this.config.groups).length&&(this.config.toolbarGroups=Object.keys(this.config.groups))}getAvailableWidth(){const e=document.documentElement.clientWidth,t=this.toolbarContainer?.offsetWidth??0;return this.config.responsiveToContainer?t:e}#d(e){return e||SN(this.superdoc?.fonts?.getFontFamilyOptions?.()??[])}#l(){const e=this.getAvailableWidth(),t=this.config.groups&&!Array.isArray(this.config.groups)&&Object.keys(this.config.groups).length>0,{defaultItems:n,overflowItems:r}=Rz({superToolbar:this,toolbarIcons:this.config.icons,toolbarTexts:this.config.texts,toolbarFonts:this.#d(this.config.fonts),hideButtons:this.config.hideButtons,availableWidth:e,role:this.role,isDev:this.isDev}),o=this.config.customButtons||[],i=o.map(l=>this.#f(l));o.length&&n.push(...i);let s=[...n.map(l=>l.name.value),...r.map(l=>l.name.value)];if(t){const l=Object.values(this.config.groups).flatMap(d=>d),u=new Set(Object.keys(this.config.groups)),c=i.filter(d=>u.has(d.group?.value||"center")).map(d=>d.name.value);s=[...new Set([...l,...c])]}const a=n.filter(l=>s.includes(l.name.value)).filter(l=>!this.config.excludeItems.includes(l.name.value));if(t)for(const[l,u]of Object.entries(this.config.groups))for(const c of a)u.includes(c.name.value)&&(c.group.value=l);this.toolbarItems=a,this.overflowItems=r.filter(l=>s.includes(l.name.value))}#f(e){const t=Cn({...e});t.isCustomToolbarItem=!0;const n=e.command;if(typeof n=="function"&&this.ui?.commands?.register){const r=`__builtin_toolbar__${e.name}`;if(!this._customCommandRegs.has(r)){const o=this.ui.commands.register({id:r,execute:i=>{const s=i?.payload&&typeof i.payload=="object"?i.payload:{};return n({...i,item:t,argument:s.argument,option:s.option})}});this._customCommandRegs.set(r,o)}}return t}#m(){this.#l(),this.emit("toolbar-items-changed")}#o(){if(this.config.fonts)return"custom-fonts";const e=this.superdoc?.fonts?.getFontFamilyOptions?.()??[];return JSON.stringify(e.map(t=>[t.label,t.value,t.previewFamily]))}getToolbarItemByGroup(e){return this.toolbarItems.filter(t=>(t.group?.value||"center")===e)}getToolbarItemByName(e){return this.#r().find(t=>t.name.value===e)}#r(){return[...this.toolbarItems,...this.overflowItems]}getLinkedStyleOptions(){return this.ui?.styles?.getQuickGallery?.()??[]}getActiveLinkedStyleId(){return this.ui?.styles?.getActiveParagraphStyle?.()?.styleId??null}setActiveEditor(e){this.activeEditor=e;const t=this.#o();t!==this._lastFontOptionsSignature&&(this._lastFontOptionsSignature=t,this.#m()),this.ui&&(this.snapshot=this.ui.toolbar.getSnapshot()),this.updateToolbarState()}onToolbarResize=()=>{this.#l(),this.updateToolbarState()};#p(e){return e==="ruler"?!!this.superdoc?.config?.rulers:e==="formattingMarks"?!!this.superdoc?.config?.layoutEngineOptions?.showFormattingMarks:!1}#y(e){return e==="ruler"?typeof this.superdoc?.toggleRuler=="function":e==="formattingMarks"?typeof this.superdoc?.toggleFormattingMarks=="function"||typeof this.superdoc?.setShowFormattingMarks=="function":!1}#w(){const e=this.getToolbarItemByName("documentMode");if(!e)return;const t=(this.snapshot?.commands?.["document-mode"]?.value||"editing").toLowerCase(),n=this.config.texts||{},r=this.config.icons||{},o={editing:{label:n.documentEditingMode||"Editing",icon:r.documentEditingMode||r.documentMode},suggesting:{label:n.documentSuggestingMode||"Suggesting",icon:r.documentSuggestingMode||r.documentMode},viewing:{label:n.documentViewingMode||"Viewing",icon:r.documentViewingMode||r.documentMode}},i=o[t]||o.editing;e.label?.value!==void 0&&(e.label.value=i.label),e.defaultLabel?.value!==void 0&&(e.defaultLabel.value=i.label),e.icon?.value!==void 0&&i.icon&&(e.icon.value=i.icon)}#_(){const e=this.toolbarItems.find(n=>n.name.value==="highlight");if(!e)return;const t={key:"color",type:"render",render:()=>N0(this,e,[],!0)};e.nestedOptions.value=[t]}#S(e){return!!e?.active&&e?.value==null}#E(e){return!!e&&e.disabled===!1&&e.value==null}#x(e){const t=e.name.value;if(t==="tableActions"){const i=Hk.map(s=>this.snapshot?.commands?.[s]).some(s=>s&&!s.disabled);return e.setDisabled(!i),!0}if(t==="search")return e.setDisabled(!1),!0;if(P0(t)?.disposition==="host-routed")return e.setDisabled(!this.#y(t)),this.#p(t)?e.activate():e.deactivate(),!0;const n=Kk(t);if(!n)return!1;const r=this.snapshot?.commands?.[n];Pz(t,r)?e.setDisabled(!1):e.setDisabled(!!r?.disabled);const o={textAlign:()=>{r?.value?e.activate({textAlign:r.value}):e.deactivate()},lineHeight:()=>{e.selectedValue.value=r?.value!=null?r.value:""},zoom:()=>{if(r?.value!=null){const i=typeof r.value=="number"?`${r.value}%`:String(r.value);e.onActivate({zoom:i})}},measurementUnit:()=>{r?.value!=null&&e.onActivate({measurementUnit:String(r.value)})},documentMode:()=>{this.#w()},link:()=>{e.active.value=!!r?.active,e.attributes.value=z0(e.attributes.value,r?.value??null)},fontFamily:()=>{if(r?.value!=null){e.activate({fontFamily:r.value});return}if(this.#E(r)){e.activate({},!0);return}e.deactivate()},fontSize:()=>{if(r?.value!=null){e.activate({fontSize:r.value});return}if(this.#S(r)){e.activate({},!0);return}e.deactivate()},color:()=>{r?.value!=null?e.activate({color:r.value}):e.deactivate()},highlight:()=>{r?.value!=null?e.activate({color:r.value}):e.deactivate()},linkedStyles:()=>{const i=r?.value,s=typeof i=="string"?i:i?.styleId,a=i&&typeof i=="object"?i.styleName:null;s?e.activate({styleId:s,styleName:a}):e.label.value=this.config.texts?.formatText||"Format text"},list:()=>{r?.active?(e.activate(),e.selectedValue.value=r.value):(e.deactivate(),e.selectedValue.value=null)},numberedlist:()=>{r?.active?(e.activate(),e.selectedValue.value=r.value):(e.deactivate(),e.selectedValue.value=null)},default:()=>{r?.active?e.activate():e.deactivate()}};return(o[t]??o.default)(),!0}updateToolbarState(){this.#w(),this.#_();const e=this.snapshot?.commands?.["document-mode"]?.value||"editing";!(this.snapshot&&(this.superdoc?.activeEditor??this.activeEditor))||e==="viewing"?(this.#M(),this.#r().forEach(n=>{n.allowWithoutEditor?.value&&this.#x(n)})):this.#r().forEach(n=>{n.resetDisabled(),this.#x(n)});const t=this.getToolbarItemByName("copyFormat");t&&(this.snapshot?.copyFormatActive?t.activate():t.deactivate()),this.emit("toolbar-state-change")}#M(){this.#r().forEach(e=>{const{allowWithoutEditor:t}=e;t?.value||e.setDisabled(!0)})}#c(e,t){const n=this.superdoc;if(e==="ruler")return typeof n?.toggleRuler=="function"?(n.toggleRuler(),!0):!1;if(e==="formattingMarks"){if(typeof t=="boolean"&&typeof n?.setShowFormattingMarks=="function")return n.setShowFormattingMarks(t),!0;if(typeof n?.toggleFormattingMarks=="function")return n.toggleFormattingMarks(),!0}return!1}#L(e,t){const n=e?.name?.value;if(!n)return!1;const r={onSettled:()=>this.updateToolbarState(),onError:i=>this.#g(i,n)};if(n==="image"&&t==null)return this.#T();if(n==="tableActions"){const i=zk[t?.command];return i?Qp(this.ui,i,void 0,r):!1}if(P0(n)?.disposition==="unsupported")return!0;const o=Kk(n);return o?Qp(this.ui,o,t,r):!1}#T(){return this.snapshot?.commands?.image?.disabled||(this.#t||(this.#t=dB({ownerDocument:this.toolbarContainer?.ownerDocument??document,onPick:async e=>{const t=await cB(e,this.superdoc?.config?.handleImageUpload);Qp(this.ui,"image",{src:t},{onSettled:()=>this.updateToolbarState(),onError:n=>this.#g(n,"image")})},onError:e=>this.#g(e,"image")})),this.#t.open()),!0}#D(){if(this.#n)return;const e=this.superdoc?.activeEditor?.container??document,t=i=>{qk(i.target)||this.ui.formatPainter.setPointerSelecting(!0)},n=i=>{this.ui.formatPainter.setPointerSelecting(!1),!qk(i.target)&&this.ui.formatPainter.notifyPointerUp()},r=i=>{if(i.key==="Escape"){this.ui.formatPainter.cancel();return}Oz(i)&&this.ui.formatPainter.setKeyboardSelecting(!0)},o=()=>{this.ui.formatPainter.setKeyboardSelecting(!1),this.ui.formatPainter.notifyKeyUp()};e.addEventListener("pointerdown",t),e.addEventListener("pointerup",n),e.addEventListener("keydown",r),e.addEventListener("keyup",o),this.#n=()=>{e.removeEventListener("pointerdown",t),e.removeEventListener("pointerup",n),e.removeEventListener("keydown",r),e.removeEventListener("keyup",o)}}#k(){this.#n&&(this.#n(),this.#n=null)}#g(e,t){const n=e instanceof Error?e:new Error(String(e));this.emit("exception",{error:n,originalError:e,itemName:t??null,editor:this.superdoc?.activeEditor??this.activeEditor??null})}emitCommand({item:e,argument:t,option:n}){const r=e?.name?.value,{command:o}=e,i=t!=null;if(!(e?.type==="dropdown"&&!i&&(o==="setFontFamily"||o==="setFontSize"))){if(r==="search"){this.superdoc?.emit?.("search:open");return}try{if(P0(r)?.disposition==="host-routed"){this.#c(r,t),this.updateToolbarState();return}if(typeof o=="function"){const s=`__builtin_toolbar__${r}`;this._customCommandRegs.has(s)&&this.ui?.commands?.execute?this.ui.commands.execute(s,{argument:t,option:n}):o({item:e,argument:t,option:n,ui:this.ui,superdoc:this.superdoc}),this.updateToolbarState();return}if(e?.isCustomToolbarItem&&typeof o=="string"){if(!Qp(this.ui,o,t,{onSettled:()=>this.updateToolbarState(),onError:s=>this.#g(s,r)}))throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState();return}if(!this.#L(e,t)&&o)throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState()}catch(s){this.#g(s,r)}}}destroy(){this.#k(),this.#t?.destroy(),this.#t=null,this.#a(),this.#i(),this.app?.unmount(),this.app=null,this.toolbar=null}};function Bz(e){return new Fz(e)}function Nz(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null||Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!Object.prototype.hasOwnProperty.call(t,o)||!Object.is(e[o],t[o]))return!1;return!0}function zz(e){if(!e||typeof e!="object")return{};const t={};e.fonts&&(t.rFonts={ascii:e.fonts.ascii,hAnsi:e.fonts.hAnsi,eastAsia:e.fonts.eastAsia,cs:e.fonts.cs,asciiTheme:e.fonts.asciiTheme,hAnsiTheme:e.fonts.hAnsiTheme,eastAsiaTheme:e.fonts.eastAsiaTheme,csTheme:e.fonts.csTheme,hint:e.fonts.hint}),e.fontFamily!=null&&(t.fontFamily=e.fontFamily),e.lang&&(t.lang={val:e.lang.val,eastAsia:e.lang.eastAsia,bidi:e.lang.bidi}),e.fontSize!=null&&(t.fontSize=e.fontSize),e.fontSizeCs!=null&&(t.fontSizeCs=e.fontSizeCs);const n=Zp(e.color);n!=null&&(t.color=n),e.highlight!=null&&(t.highlight=e.highlight);const r=Uz(e.shading);r&&(t.shading=r),e.cs!=null&&(t.cs=e.cs),e.rtl!=null&&(t.rtl=e.rtl),e.bold!=null&&(t.bold=e.bold),e.boldCs!=null&&(t.bCs=e.boldCs),e.italic!=null&&(t.italic=e.italic),e.italicCs!=null&&(t.iCs=e.italicCs);const o=Hz(e.underline);o!==void 0&&(t.underline=o),e.strikethrough!=null&&(t.strike=e.strikethrough),e.doubleStrikethrough!=null&&(t.dstrike=e.doubleStrikethrough),e.caps!=null&&(t.caps=e.caps),e.smallCaps!=null&&(t.smallCaps=e.smallCaps),e.outline!=null&&(t.outline=e.outline),e.shadow!=null&&(t.shadow=e.shadow),e.emboss!=null&&(t.emboss=e.emboss),e.imprint!=null&&(t.imprint=e.imprint),e.verticalAlign!=null&&(t.vertAlign=e.verticalAlign),e.characterSpacing!=null&&(t.letterSpacing=e.characterSpacing),e.characterScale!=null&&(t.charScale=e.characterScale),e.kern!=null&&(t.kerning=e.kern),e.baselineShift!=null&&(t.position=e.baselineShift),e.fitTextWidth!=null&&(t.fitText={val:e.fitTextWidth}),e.vanish!=null&&(t.vanish=e.vanish),e.webHidden!=null&&(t.webHidden=e.webHidden),e.specVanish!=null&&(t.specVanish=e.specVanish);const i=Vz(e.border);return i&&(t.border=i),t}function Zp(e){if(e){if(typeof e=="string")return e;if(e.model==="rgb")return e.value;if(e.model==="auto")return"auto"}}function Hz(e){if(e==null)return;const t={};return e.style!=null&&(t.style=e.style),e.color?.model==="rgb"&&(t.color=e.color.value),e.color?.model==="theme"&&(t.themeColor=e.color.theme),Object.keys(t).length>0?t:!0}function Uz(e){if(!e)return;const t={},n=Zp(e.fill);n!=null&&(t.fill=n);const r=Zp(e.color);return r!=null&&(t.color=r),e.pattern!=null&&(t.val=e.pattern),Object.keys(t).length>0?t:void 0}function Vz(e){if(!e)return;const t={};e.style!=null&&(t.val=e.style),e.width!=null&&(t.sz=e.width),e.space!=null&&(t.space=e.space);const n=Zp(e.color);return n!=null&&(t.color=n),Object.keys(t).length>0?t:void 0}function $l(e){const t=e?.selectionTarget??e?.target;if(!e||!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function Yk(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function jz(e){const t=[],n=o=>{o&&!t.includes(o)&&t.push(o)};n(e.getAttribute("data-track-change-preferred-target-id"));const r=e.getAttribute("data-track-change-ids");if(r)for(const o of Yk(r))n(o);return n(e.getAttribute("data-track-change-id")),t}function Xk(e,t){if(!e||typeof e.getAttribute!="function")return[];const n=[],r=new Set;let o=[],i=e;for(;i;){const s=i,a=jz(s),l=a.length>0?s.getAttribute("data-story-key"):null;for(const m of a){const p=`trackedChange:${m}`;if(!r.has(p)){r.add(p);const g={type:"trackedChange",id:m};l&&(g.storyKey=l),n.push(g),o.push(g)}}const u=s.getAttribute("data-layout-story");if(u&&o.length>0){for(const m of o)m.story=u;o=[]}const c=s.getAttribute("data-comment-ids");if(c)for(const m of Yk(c)){const p=`comment:${m}`;r.has(p)||(r.add(p),n.push({type:"comment",id:m}))}const d=s.getAttribute("data-sdt-type"),h=s.getAttribute("data-sdt-id");if(h&&d==="structuredContent"){const m=`contentControl:${h}`;if(!r.has(m)){r.add(m);const p=s.getAttribute("data-sdt-scope"),g=s.getAttribute("data-sdt-tag"),k={type:"contentControl",id:h};(p==="block"||p==="inline")&&(k.scope=p),g&&(k.tag=g),n.push(k)}}if(t&&i===t)break;i=i.parentElement}return n}const H0={PAGE:"superdoc-page",FRAGMENT:"superdoc-fragment",LINE:"superdoc-line",INLINE_SDT_WRAPPER:"superdoc-structured-content-inline",INLINE_SDT_LABEL:"superdoc-structured-content-inline__label",BLOCK_SDT:"superdoc-structured-content-block",BLOCK_SDT_LABEL:"superdoc-structured-content__label",TABLE_FRAGMENT:"superdoc-table-fragment",DOCUMENT_SECTION:"superdoc-document-section",SDT_GROUP_HOVER:"sdt-group-hover",TOC_ENTRY:"superdoc-toc-entry",TOC_GROUP_HOVER:"toc-group-hover",IMAGE_FRAGMENT:"superdoc-image-fragment",INLINE_IMAGE:"superdoc-inline-image",LIST_MARKER:"superdoc-list-marker",INLINE_IMAGE_CLIP_WRAPPER:"superdoc-inline-image-clip-wrapper",ANNOTATION:"annotation",ANNOTATION_CONTENT:"annotation-content",ANNOTATION_CARET_ANCHOR:"annotation-caret-anchor"},xj=[H0.INLINE_SDT_LABEL,H0.BLOCK_SDT_LABEL],Qk={PM_START:"data-pm-start",PM_END:"data-pm-end",LAYOUT_EPOCH:"data-layout-epoch",TABLE_BOUNDARIES:"data-table-boundaries",SDT_ID:"data-sdt-id",SDT_TYPE:"data-sdt-type",FIELD_ID:"data-field-id",FIELD_TYPE:"data-field-type",DRAGGABLE:"data-draggable",DISPLAY_LABEL:"data-display-label",VARIANT:"data-variant",TYPE:"data-type",LAYOUT_BOUNDARY_SCHEMA:"data-layout-boundary-schema",LAYOUT_FRAGMENT_ID:"data-layout-fragment-id",LAYOUT_STORY:"data-layout-story",LAYOUT_BLOCK_REF:"data-layout-block-ref"},Gz=e=>{if(!e)return{kind:"unknown"};if(e==="body")return{kind:"body"};const t=e.indexOf(":"),n=t===-1?e:e.slice(0,t),r=t===-1?void 0:e.slice(t+1);switch(n){case"body":case"header":case"footer":case"footnote":case"endnote":case"textbox":return r?{kind:n,id:r}:{kind:n};default:return{kind:"unknown"}}},Tj=`.${H0.BLOCK_SDT}[${Qk.SDT_ID}]`,Rj=`[${Qk.DRAGGABLE}="true"]`;var to=()=>({oneOf:[{type:"boolean"},{type:"null"}]}),nl=()=>({oneOf:[{type:"string",minLength:1},{type:"null"}]}),hu=()=>({oneOf:[{type:"number"},{type:"null"}]}),pu=e=>({oneOf:[{type:"object",properties:e,additionalProperties:!1,minProperties:1},{type:"null"}]}),Wz={type:"object",properties:{style:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},themeColor:{oneOf:[{type:"string",minLength:1},{type:"null"}]}},additionalProperties:!1,minProperties:1},Kz={type:"object",properties:{id:{type:"number"},val:{type:"boolean"}},required:["id"],additionalProperties:!1},qz=()=>({oneOf:[{type:"boolean"},{type:"null"},Wz]}),Yz=()=>({oneOf:[{type:"array",items:Kz,minItems:1},{type:"null"}]});function Jp(e,t){return{storage:"mark",markName:e,textStyleAttr:t}}function Xz(e){return{storage:"runAttribute",nodeName:"run",runPropertyKey:e}}var U0=(e,t,n)=>({key:e,type:"boolean",ooxmlElement:t,storage:"mark",tracked:!0,carrier:Jp(n),schema:to()}),ec=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"mark",tracked:!0,carrier:Jp("textStyle",o??e),schema:r}),Pn=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"runAttribute",tracked:!1,carrier:Xz(o??e),schema:r});const $p=[U0("bold","w:b","bold"),U0("italic","w:i","italic"),U0("strike","w:strike","strike"),{key:"underline",type:"object",ooxmlElement:"w:u",storage:"mark",tracked:!0,carrier:Jp("underline"),schema:qz()},{key:"highlight",type:"string",ooxmlElement:"w:highlight",storage:"mark",tracked:!0,carrier:Jp("highlight"),schema:nl()},ec("color","string","w:color",nl()),ec("fontSize","number","w:sz",hu()),ec("fontFamily","string","w:rFonts",nl()),ec("letterSpacing","number","w:spacing",hu()),ec("vertAlign","string","w:vertAlign",{oneOf:[{enum:["superscript","subscript","baseline"]},{type:"null"}]}),ec("position","number","w:position",hu()),Pn("dstrike","boolean","w:dstrike",to()),Pn("smallCaps","boolean","w:smallCaps",to()),ec("caps","boolean","w:caps",to(),"textTransform"),Pn("shading","object","w:shd",pu({fill:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},val:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Pn("border","object","w:bdr",pu({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},sz:{oneOf:[{type:"number"},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},space:{oneOf:[{type:"number"},{type:"null"}]}}),"borders"),Pn("outline","boolean","w:outline",to()),Pn("shadow","boolean","w:shadow",to()),Pn("emboss","boolean","w:emboss",to()),Pn("imprint","boolean","w:imprint",to()),Pn("charScale","number","w:w",hu(),"w"),Pn("kerning","number","w:kern",hu(),"kern"),Pn("vanish","boolean","w:vanish",to()),Pn("webHidden","boolean","w:webHidden",to()),Pn("specVanish","boolean","w:specVanish",to()),Pn("rtl","boolean","w:rtl",to()),Pn("cs","boolean","w:cs",to()),Pn("bCs","boolean","w:bCs",to(),"boldCs"),Pn("iCs","boolean","w:iCs",to(),"italicCs"),Pn("eastAsianLayout","object","w:eastAsianLayout",pu({id:{oneOf:[{type:"string",minLength:1},{type:"null"}]},combine:{oneOf:[{type:"boolean"},{type:"null"}]},combineBrackets:{oneOf:[{type:"string",minLength:1},{type:"null"}]},vert:{oneOf:[{type:"boolean"},{type:"null"}]},vertCompress:{oneOf:[{type:"boolean"},{type:"null"}]}})),Pn("em","string","w:em",nl()),Pn("fitText","object","w:fitText",pu({val:{oneOf:[{type:"number"},{type:"null"}]},id:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Pn("snapToGrid","boolean","w:snapToGrid",to()),Pn("lang","object","w:lang",pu({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},bidi:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Pn("oMath","boolean","w:oMath",to()),Pn("rStyle","string","w:rStyle",nl(),"styleId"),Pn("rFonts","object","w:rFonts",pu({ascii:{oneOf:[{type:"string",minLength:1},{type:"null"}]},hAnsi:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},cs:{oneOf:[{type:"string",minLength:1},{type:"null"}]},asciiTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},hAnsiTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsiaTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},csTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},hint:{oneOf:[{type:"string",minLength:1},{type:"null"}]}}),"fontFamily"),Pn("fontSizeCs","number","w:szCs",hu()),Pn("ligatures","string","w14:ligatures",nl()),Pn("numForm","string","w14:numForm",nl()),Pn("numSpacing","string","w14:numSpacing",nl()),Pn("stylisticSets","array","w14:stylisticSets",Yz()),Pn("contextualAlternates","boolean","w14:cntxtAlts",to())],Mj=new Set($p.map(e=>e.key)),Qz=Object.fromEntries($p.map(e=>[e.key,e])),Lj={mark:$p.filter(e=>e.storage==="mark").map(e=>e.key),runAttribute:$p.filter(e=>e.storage==="runAttribute").map(e=>e.key)};var Zz=new Set(Object.values(at));function V0(e,t){return typeof e=="string"&&Zz.has(e)?e:t}function Zk(e){if(e&&typeof e=="object"&&e.ok===!1){const t=e.reason;return t==="host-not-ready"||t==="host-disposed"||t==="editing-mount-required"?{ok:!1,reason:at.notReady}:{ok:!1,reason:V0(t,at.targetUnresolved)}}return{ok:!0}}var Jz=["document-replaced","editorCreate","active-editor-change","document-mode-change","zoomChange","measurement-unit-change","viewport-change","fonts-changed"],$z={[xk.bulletList]:"bullet",[xk.numberedList]:"ordered"};function Jk(e){return $z[e]??null}var eH={disc:"disc",circle:"circle",square:"square",decimal:"decimal","decimal-paren":"decimalParenthesis","upper-roman":"upperRoman","lower-roman":"lowerRoman","upper-alpha":"upperLetter","upper-alpha-paren":"upperLetterParenthesis","lower-alpha":"lowerLetter","lower-alpha-paren":"lowerLetterParenthesis"};function tH(e){const t=eH[e];return t?{preset:t,behavior:"toggleStyle"}:{}}var nH={status:"ready",empty:!0,target:null,selectionTarget:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[],quotedText:""};const rH=[{key:"contentControls",match:"exact",note:"full-document SDT catalog parse (the measured during-load cliff)"},{key:"contentControls:inRange:",match:"prefix",note:"same adapter load() as the catalog, issued per settled selection"},{key:"hyperlinks:",match:"prefix",note:"per-block hyperlink list over the loading story"},{key:"styles:catalog:",match:"prefix",note:"WordStyleModel recompile from package bytes"},{key:"comments",match:"exact",note:"audited: full comments list; stale-served during load"},{key:"trackChanges",match:"exact",note:"audited: body tracked-changes list; stale-served during load"},{key:"trackChanges:all",match:"exact",note:"audited: all-story tracked-changes list; consumers already fail closed on non-ready"},{key:"tables",match:"exact",note:"reserved: full tables catalog"},{key:"sections",match:"exact",note:"reserved: full sections list"}];var oH=new Set(["/word/comments.xml","/word/commentsExtended.xml","/word/commentsIds.xml"]);function iH(e){return rH.some(t=>t.match==="exact"?t.key===e:e.startsWith(t.key))}var $k={ready:0,stale:1,pending:2};function mu(...e){let t="ready";for(const n of e)$k[n]>$k[t]&&(t=n);return t}function xt(e,t){if(typeof e!="function")return t;try{const n=e();return n===void 0?t:n}catch{return t}}function Or(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function gr(e,t){if(!e)return null;const n=t.split(".");let r=e;for(const o of n){if(r==null)return null;r=r[o]}return typeof r=="function"?r:null}function cr(e,t="CAPABILITY_UNAVAILABLE"){return{success:!1,failure:{code:t,message:e}}}function Af(e,t){return{success:!1,failure:{code:"PARTIAL_LINK_EDIT",message:"Hyperlink target was updated, but display text replacement failed."},applied:{href:!0,text:!1},hyperlinkResult:e,textResult:t}}function If(e){if(!e||typeof e!="object")return null;const t=e.target;return t&&typeof t=="object"?t:null}function j0(e){if(!e||typeof e!="object")return!1;const t=e,n=i=>{if(!i||typeof i!="object")return!1;const s=i;return s.kind==="text"&&typeof s.blockId=="string"&&typeof s.offset=="number"},r=i=>{if(!i||typeof i!="object")return!1;const s=i,a=s.range;return typeof s.blockId=="string"&&typeof a?.start=="number"&&typeof a.end=="number"};if(Array.isArray(t.segments)){const i=t.segments[0],s=t.segments[t.segments.length-1];return r(i)&&r(s)}if(t.kind==="selection")return n(t.start)&&n(t.end);if(t.kind!=="text"||typeof t.blockId!="string")return!1;const o=t.range;return typeof o?.start=="number"&&typeof o.end=="number"}function sH(e){if(!e||typeof e!="object")return null;const t=If(e);if(j0(t))return t;const n=e,r=n.navigationTarget&&typeof n.navigationTarget=="object"?n.navigationTarget:null;return r?.kind==="block"&&typeof r.blockId=="string"&&r.blockId.length>0?{kind:"text",blockId:r.blockId,range:{start:0,end:0},...r.story&&typeof r.story=="object"?{story:r.story}:{},...n.address&&typeof n.address=="object"?{address:n.address}:{}}:t}function no(e){if(!e||typeof e!="object")return"story:body";const t=e,n=typeof t.storyType=="string"?t.storyType:"body";switch(n){case"body":return"story:body";case"headerFooterPart":return`story:headerFooterPart:${typeof t.refId=="string"?t.refId:""}`;case"headerFooterSlot":return JSON.stringify({storyType:n,section:t.section??null,headerFooterKind:t.headerFooterKind??null,variant:t.variant??null,resolution:t.resolution??"effective",onWrite:t.onWrite??"materializeIfInherited"});case"footnote":return`story:footnote:${typeof t.noteId=="string"?t.noteId:""}`;case"endnote":return`story:endnote:${typeof t.noteId=="string"?t.noteId:""}`;case"textbox":return`story:textbox:${typeof t.textboxId=="string"?t.textboxId:""}`;default:return JSON.stringify(t)}}function em(e){if(!e||typeof e!="object")return null;const t=e,n=t.address&&typeof t.address=="object"?t.address:null;if(n?.story&&typeof n.story=="object")return n.story;if(t.storyLocator&&typeof t.storyLocator=="object")return t.storyLocator;if(t.trackedChangeStory&&typeof t.trackedChangeStory=="object")return t.trackedChangeStory;const r=If(e);if(!r||typeof r!="object")return null;const o=r;if(o.story&&typeof o.story=="object")return o.story;const i=o.address&&typeof o.address=="object"?o.address:null;return i?.story&&typeof i.story=="object"?i.story:null}function rl(e,t,n){return Un(e)!==t?!1:n?no(em(e))===no(n):!0}function eA(e){const t=em(e);if(!(!t||no(t)===no(null)))return t}function aH(e){if(typeof e!="string"||e.length===0)return;const t=Gz(e);switch(t.kind){case"body":return;case"footnote":return t.id?{kind:"story",storyType:"footnote",noteId:t.id}:void 0;case"endnote":return t.id?{kind:"story",storyType:"endnote",noteId:t.id}:void 0;case"header":case"footer":return t.id?{kind:"story",storyType:"headerFooterPart",refId:t.id}:void 0;default:return}}function lH(e){if(!(typeof e!="string"||e.length===0||e==="body")){if(e.startsWith("hf:part:")){const t=e.slice(8);return t?{kind:"story",storyType:"headerFooterPart",refId:t}:void 0}if(e.startsWith("fn:")){const t=e.slice(3);return t?{kind:"story",storyType:"footnote",noteId:t}:void 0}if(e.startsWith("en:")){const t=e.slice(3);return t?{kind:"story",storyType:"endnote",noteId:t}:void 0}}}function G0(e){if(!e||typeof e!="object")return null;const t=e.selectionTarget;return t&&typeof t=="object"?t:null}function tm(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function cH(e){if(!e||typeof e!="object")return null;const t=e;if(t.kind!=="selection")return e;const n=t.start;return!n||typeof n!="object"?null:{...t,end:n}}function Un(e){if(!e||typeof e!="object")return null;const t=e,n=t.id??t.commentId??t.changeId;return typeof n=="string"&&n.length>0?n:null}function uH(e){if(!e||typeof e!="object")return null;const t=e,n=t.anchor,r=t.focus,o=n?.visualCaret,i=r?.visualCaret,s=o?.trackChangeId,a=i?.trackChangeId;return typeof s=="string"&&s.length>0&&s===a?s:null}var tA=new WeakMap;function dH(e){const t=[],n=i=>{typeof i=="string"&&i.length>0&&!t.includes(i)&&t.push(i)},r=i=>{if(!i||typeof i!="object")return;const s=i,a=s.sourceIds;if(a&&typeof a=="object"&&(n(a.wordIdInsert),n(a.wordIdDelete),Array.isArray(a.wordIdOther)))for(const d of a.wordIdOther)n(d);const l=s.wordRevisionIds;l&&typeof l=="object"&&(n(l.insert),n(l.delete),n(l.format));const u=s.replacement;if(u&&typeof u=="object")for(const d of[u.inserted,u.deleted])d&&typeof d=="object"&&(n(d.id),n(d.wordId));const c=s.move;if(c&&typeof c=="object")for(const d of[c.source,c.destination])d&&typeof d=="object"&&(n(d.id),n(d.wordId))};r(e);const o=e?.change;return o&&o!==e&&r(o),t}function Ef(e){const t=tA.get(e);if(t)return t;const n=new Set,r=new Map;for(const i of e){const s=Un(i);if(s){n.add(s);for(const a of dH(i)){r.has(a)||r.set(a,s);const l=`imported:${a}`;r.has(l)||r.set(l,s)}}}const o={toPublicId(i){if(n.has(i))return i;const s=r.get(i);return s!=null&&n.has(s)?s:null},aliasesFor(i){const s=[i];for(const[a,l]of r)l===i&&!s.includes(a)&&s.push(a);return s}};return tA.set(e,o),o}var nA=new WeakMap;function rA(e,t){const n=no(t);let r=nA.get(e);r||(r=new Map,nA.set(e,r));const o=r.get(n);if(o)return o;const i=Ef(e.filter(s=>no(em(s))===n));return r.set(n,i),i}function fH(e,t){const n=e.find(r=>Un(r)===t||r.importedId===t);return n?n.rootCommentId??n.parentCommentId??Un(n)??t:null}function hH(e){const t=e.selectionTarget;if(t){const s=t.start,a=t.end,l=typeof s?.blockId=="string"?s.blockId:void 0,u=typeof a?.blockId=="string"?a.blockId:l;if(l)return{startBlockId:l,endBlockId:u??l}}const n=e.target,r=n&&Array.isArray(n.segments)?n.segments:[],o=r[0]?.blockId,i=r[r.length-1]?.blockId;return typeof o=="string"?{startBlockId:o,endBlockId:typeof i=="string"?i:o}:null}function Rr(e){const t=[],n=s=>{typeof s=="string"&&s.length>0&&!t.includes(s)&&t.push(s)},r=e.target,o=r&&Array.isArray(r.segments)?r.segments:[];for(const s of o)n(s?.blockId);const i=e.selectionTarget;return i&&(n(i.start?.blockId),n(i.end?.blockId)),t}var pH=64;function tc(e){return e.length<=pH}function ga(e){const t=e.target,n=e.selectionTarget,r=n?.start,o=n?.end,i=t?.story??n?.story??r?.story??o?.story;return i&&typeof i=="object"?i:{kind:"story",storyType:"body"}}function ho(e,t){return{kind:"block",nodeType:"paragraph",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}function va(e){return{kind:"block",nodeType:"paragraph",nodeId:e}}function oA(e,t){return{kind:"block",nodeType:"listItem",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}var iA=720;function Cs(e){return Math.round(e*20)}function gu(e){return typeof e=="number"&&Number.isFinite(e)}function mH(e){if(!e||typeof e!="object")return null;const t=e.node;if(!t||typeof t!="object")return null;const n=t.kind==="heading"?t.heading??null:t.kind==="paragraph"?t.paragraph??null:null;if(!n)return null;const r=n.resolved,o=n.props,i=r?.indent??o?.indent;if(!i||typeof i!="object")return null;const s=gu(i.left)?Cs(i.left):gu(i.start)?Cs(i.start):void 0,a=gu(i.right)?Cs(i.right):gu(i.end)?Cs(i.end):void 0,l=gu(i.firstLine)?Cs(i.firstLine):void 0,u=gu(i.hanging)?Cs(i.hanging):void 0;return s==null&&a==null&&l==null&&u==null?null:{...s!=null?{left:s}:{},...a!=null?{right:a}:{},...l!=null?{firstLine:l}:{},...u!=null?{hanging:u}:{}}}function W0(e){const t=e.target,n=t&&Array.isArray(t.segments)?t.segments:[],r=t?.story,o=[];for(const i of n){if(!i||typeof i.blockId!="string")continue;const s=i.range;!s||typeof s.start!="number"||typeof s.end!="number"||s.start===s.end||o.push({kind:"text",blockId:i.blockId,range:{start:s.start,end:s.end},...r?{story:r}:{}})}return o}function gH(e){if(!e||typeof e!="object")return[];const t=e,n=t.story,r=[];if(t.kind==="text"&&t.range&&typeof t.blockId=="string"){const o=t.range;return typeof o.start=="number"&&typeof o.end=="number"&&o.start!==o.end&&r.push({kind:"text",blockId:t.blockId,range:{start:Math.min(o.start,o.end),end:Math.max(o.start,o.end)},...n?{story:n}:{}}),r}if(t.kind==="text"&&Array.isArray(t.segments)){for(const o of t.segments){const i=o?.range;typeof o?.blockId=="string"&&typeof i?.start=="number"&&typeof i?.end=="number"&&i.start!==i.end&&r.push({kind:"text",blockId:o.blockId,range:{start:Math.min(i.start,i.end),end:Math.max(i.start,i.end)},...n?{story:n}:{}})}return r}if(t.kind==="selection"){const o=t.start,i=t.end,s=typeof o?.blockId=="string"&&i?.blockId===o.blockId?o.blockId:null;o?.kind==="text"&&i?.kind==="text"&&s&&typeof o.offset=="number"&&typeof i.offset=="number"&&o.offset!==i.offset&&r.push({kind:"text",blockId:s,range:{start:Math.min(o.offset,i.offset),end:Math.max(o.offset,i.offset)},...t.story??o.story?{story:t.story??o.story}:{}})}return r}function xf(e){if(!e||typeof e!="object")return null;const t=e,n=t.story;if(t.kind==="text"&&t.range&&typeof t.blockId=="string"){const r=t.range;if(typeof r.start=="number"&&typeof r.end=="number"&&r.start===r.end)return{kind:"text",blockId:t.blockId,range:{start:r.start,end:r.end},...n?{story:n}:{}}}if(t.kind==="text"&&Array.isArray(t.segments)){const r=t.segments[0],o=r?.range;if(typeof r?.blockId=="string"&&typeof o?.start=="number"&&typeof o?.end=="number"&&o.start===o.end)return{kind:"text",blockId:r.blockId,range:{start:o.start,end:o.end},...n?{story:n}:{}}}if(t.kind==="selection"){const r=t.start,o=t.end,i=typeof r?.blockId=="string"&&o?.blockId===r.blockId?r.blockId:null;if(r?.kind==="text"&&o?.kind==="text"&&i&&typeof r.offset=="number"&&typeof o.offset=="number"&&r.offset===o.offset)return{kind:"text",blockId:i,range:{start:r.offset,end:r.offset},...t.story??r.story?{story:t.story??r.story}:{}}}return null}function ol(e){return xf(e.target)??xf(e.selectionTarget)}var sA=["fontFamily","fontSize","color","highlight"],vH={undo:"history.undo",redo:"history.redo"},Tf=["bold","italic","underline","strikethrough"];function K0(e){return sA.includes(e)}function vu(e){const t=e.target,n=t&&Array.isArray(t.segments)?t.segments:[],r=[],o=(l,u,c)=>{typeof l!="string"||typeof u!="number"||typeof c!="number"||r.push({blockId:l,start:Math.min(u,c),end:Math.max(u,c)})};for(const l of n){const u=l?.range;o(l?.blockId,u?.start,u?.end)}if(r.length>0)return r;const i=e.selectionTarget,s=i?.start,a=i?.end;return!s||!a||s.blockId!==a.blockId||o(s.blockId,s.offset,a.offset),r}function _s(e){const t=e.target,n=e.selectionTarget,r=n?.start,o=n?.end,i=t?.story??n?.story??r?.story??o?.story;return i&&typeof i=="object"?i:void 0}function yH(e){const t=_s(e);if(!t||typeof t!="object")return"body";const n=t;return JSON.stringify({storyType:typeof n.storyType=="string"?n.storyType:"body",refId:typeof n.refId=="string"?n.refId:null,noteId:typeof n.noteId=="string"?n.noteId:null,textboxId:typeof n.textboxId=="string"?n.textboxId:null})}function ya(e){const t=vu(e);return t.length===0?null:[yH(e),...t.map(n=>`${n.blockId}:${n.start}-${n.end}`)].join("|")}function aA(e){const t=e.selectionTarget;return!t||typeof t!="object"?null:$l({selectionTarget:t})}function bH(e,t){if(e==="fontSize"){const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)&&r>0?String(r):null}if(typeof t!="string")return null;const n=t.trim();return n.length===0?null:e==="color"||e==="highlight"?n.toUpperCase():n}function wH(e,t){return Math.max(e.start,t.start)<Math.min(e.end,t.end)}function CH(e){if(!e)return[];const t=Array.isArray(e.blocks)?e.blocks:[],n=[];for(const r of t){const o=r?.range,i=r?.blockId;typeof i!="string"||typeof o?.start!="number"||typeof o?.end!="number"||n.push({blockId:i,start:Math.min(o.start,o.end),end:Math.max(o.start,o.end)})}return n}function _H(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return o?.blockId===n.blockId&&o?.start===n.start&&o?.end===n.end})}function lA(e,t){const n=vu(t);if(n.length===0)return null;const r=e&&Array.isArray(e.items)?e.items:[];if(r.length===0)return null;const o=r.find(i=>_H(n,CH(i)));if(o)return o;if(n.length===1){const i=r.find(s=>{const a=s?.address;return a?.kind==="block"&&a.nodeId===n[0].blockId});if(i)return i}return r[0]??null}function SH(e,t){const n=t==="fontSize"?e?.fontSizePt??e?.fontSize:t==="highlight"?e?.highlight??e?.backgroundColor:e?.[t];if(typeof n=="number")return Number.isFinite(n)?String(n):void 0;if(typeof n!="string")return;const r=n.trim();if(r.length!==0)return t==="color"||t==="highlight"?r.toUpperCase():r}function q0(e){if(typeof e!="string")return;const t=e.split(",")[0]?.trim().replace(/^['"]+|['"]+$/g,"").trim();if(!t)return;const n=t.toLowerCase();if(!(n==="serif"||n==="sans-serif"||n==="monospace"||n==="cursive"||n==="fantasy"))return t}function kH(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return;const t=Math.round(e*.75*2)/2;if(!(t<=0))return String(t)}function AH(e,t){return e==="fontFamily"?t.toLowerCase():e==="color"||e==="highlight"?t.toUpperCase():t}function cA(e,t){if(!e)return{};const n=new Map;for(const i of vu(t)){const s=n.get(i.blockId)??[];s.push({start:i.start,end:i.end}),n.set(i.blockId,s)}if(n.size===0)return{};const r=Array.isArray(e.blocks)?e.blocks:[],o={};for(const i of sA){const s=new Map;let a=!1,l=!1;for(const u of r){const c=typeof u?.blockId=="string"?u.blockId:null;if(!c)continue;const d=n.get(c);if(!d?.length)continue;const h=Array.isArray(u?.runs)?u.runs:[];for(const m of h){const p=m?.range,g=typeof p?.start=="number"?p.start:null,k=typeof p?.end=="number"?p.end:null;if(g==null||k==null||!d.some(y=>wH(y,{start:g,end:k})))continue;a=!0;const w=SH(m?.styles,i);if(w===void 0){l=!0;continue}const S=AH(i,w);if(s.has(S)||s.set(S,w),s.size>1)break}if(s.size>1)break}a&&!l&&s.size===1&&(o[i]=[...s.values()][0])}return o}function Y0(e,t){const n=Rr(e)[0];return n?t==="nodeId"?{kind:"after",nodeId:n}:{kind:"after",target:ho(n)}:{kind:"documentEnd"}}function tn(e,t){const n=e.supported??t!=="unsupported",r=e.enabled??(e.disabled!==void 0?!e.disabled:n);return{enabled:r,disabled:!r,active:e.active??!1,supported:n,value:e.value,source:t,reason:r?void 0:e.reason}}function nc(e){if(!e||typeof e!="object")return null;const t=e,n=t.change,r=n&&typeof n=="object"?n:t;return{...t,id:t.id??r.id,change:r}}function X0(e){const t=e,n=t.change;return n&&typeof n=="object"?n:t}function il(e){if(Or(e))return!0;if(e===!1)return!1;if(e===!0||e==null||typeof e!="object")return!0;const t=e;return"success"in t||"failure"in t||"effects"in t?e:t.status!=="rejected"}function nm(e){return!!e&&typeof e=="object"&&e.success===!0}function zo(e){return!(e===!1||e&&typeof e=="object"&&e.success===!1)}function yu(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Q0(e){const t=[],n=r=>{if(!r||typeof r!="object")return;const o=r;if(Array.isArray(o.runs)&&t.push(o),Array.isArray(o.rows))for(const i of o.rows){const s=i?.cells;if(Array.isArray(s))for(const a of s){const l=a;if(Array.isArray(l?.blocks))for(const u of l.blocks)n(u);l?.paragraph&&n(l.paragraph)}}};if(Array.isArray(e))for(const r of e)n(r);return t}function rc(e,t){return e.sourceAnchor?.sourceNodeId===t?!0:e.id===t}function hi(e){let t=!1,n=null,r=null,o=null;for(const i of e)t=i,!zo(i)&&n===null&&(n=i),nm(i)&&(o=i),i!==!1&&(r=i);return n??o??r??t}function IH(e){const t=e?.anchor,n=t?.start,r=t?.end;return typeof n?.blockId!="string"||typeof r?.blockId!="string"||n.blockId!==r.blockId||typeof n.offset!="number"||typeof r.offset!="number"?null:{kind:"selection",start:{kind:"text",blockId:n.blockId,offset:n.offset},end:{kind:"text",blockId:r.blockId,offset:r.offset}}}function EH(e){return e.startsWith("#")?{kind:"anchor",anchor:e.slice(1)}:{kind:"external",url:e}}function rm(e){return fu(e)?.trackDecision??null}function xH(e){return{found:e.length>0,success:e.length>0,rects:e,rect:e[0]}}function sl(e){return{found:!1,success:!1,rects:[],reason:e}}function TH(e,t){if(!t||typeof t.getBoundingClientRect!="function"||e.rects.length===0)return e;let n;try{const o=t.getBoundingClientRect();n={left:o.left,top:o.top}}catch{return e}const r=e.rects.map(o=>({...o,left:o.left-n.left,right:o.right-n.left,top:o.top-n.top,bottom:o.bottom-n.top}));return{...e,rects:r,rect:r[0]}}function RH(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.blockId!="string"||!t.range||typeof t.range!="object")return!1;const n=t.range;return Number.isInteger(n.start)&&Number.isInteger(n.end)&&n.start>=0&&n.start<=n.end}function uA(e){if(!e||e.kind!=="text"||!Array.isArray(e.segments)||e.segments.length===0)return null;const t=Array.from(e.segments);if(!t.every(RH))return null;const n=t[0],r=t[t.length-1],o=e.story;return{kind:"selection",start:{kind:"text",blockId:n.blockId,offset:n.range.start,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end,...o?{story:o}:{}},...o?{story:o}:{}}}function MH(e){return e.selectionTarget?e.selectionTarget:uA(e.target)}function bu(e){if(e.empty)return null;if(e.selectionTarget)return e.selectionTarget;const t=uA(e.target);return t&&t.start.kind==="text"&&t.end.kind==="text"&&t.start.blockId!==t.end.blockId?null:t}function Z0(e){return!e.inline||typeof e.docRoute!="string"?null:e.docRoute.startsWith("format.")?e.docRoute.slice(7):null}var J0={bold:null,italic:null,underline:null,strike:null,color:null,highlight:null,fontFamily:null,fontSize:null,vertAlign:null,smallCaps:null,caps:null,letterSpacing:null,dstrike:null},LH=Object.fromEntries(Object.entries(J0).filter(([e])=>Qz[e]?.tracked===!0));function DH(e,t,n,r){switch(e.kind){case"toggle":{const o=typeof n=="object"&&n!==null&&"value"in n?n.value:n;return typeof o=="boolean"||o===null?{target:t,value:o}:{target:t,value:!r}}case"value-string":{const o=typeof n=="object"&&n!==null&&"value"in n?n.value:n;return o===null?{target:t,value:null}:typeof o!="string"||o.trim()===""?null:{target:t,value:o}}case"value-number":{const o=typeof n=="object"&&n!==null&&"value"in n?n.value:n,i=typeof o=="number"?o:Number(o);return!Number.isFinite(i)||i<=0?null:{target:t,value:i}}case"clear":return{target:t,inline:{...J0}};default:return null}}function PH(e){const t=o=>{if(!o||typeof o!="object")return null;const i=o,s=i.rowIndex,a=i.columnIndex;return typeof s!="number"||!Number.isInteger(s)||typeof a!="number"||!Number.isInteger(a)?null:{rowIndex:s,columnIndex:a}};if(!e)return null;const n=t(e.start),r=t(e.end);return!n||!r?null:{start:n,end:r}}function OH(e,t){const{tableNodeId:n,rowIndex:r,columnIndex:o,cellNodeId:i,mergeRange:s}=t;switch(e){case"insert-row-before":return{nodeId:n,rowIndex:r,position:"above"};case"insert-row-after":return{nodeId:n,rowIndex:r,position:"below"};case"delete-row":return{nodeId:n,rowIndex:r};case"insert-column-before":return{nodeId:n,columnIndex:o,position:"left"};case"insert-column-after":return{nodeId:n,columnIndex:o,position:"right"};case"delete-column":return{nodeId:n,columnIndex:o};case"delete-table":return{nodeId:n};case"merge-cells":{const a=s??{start:{rowIndex:r,columnIndex:o},end:{rowIndex:r,columnIndex:o}};return{nodeId:n,start:a.start,end:a.end}}case"split-cell":return i?{nodeId:i,rows:1,columns:2}:null;case"remove-borders":return{nodeId:n,mode:"applyTo",applyTo:"all",border:null};default:return null}}function FH(e){const t=e.superdoc,n=new Map,r=new Map;let o=null,i=0;const s=[];let a=null,l=0,u=!1,c=Promise.resolve(),d=null,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:0,pointerSelecting:!1,keyboardSelecting:!1},m=0;const p=new Set;let g={},k="",w=null;const S=()=>{const f=t?.activeEditor;return f&&typeof f=="object"?f:null},y=()=>{const f=S()?.doc;return f&&typeof f=="object"?f:null},C=()=>{const f=S()?.v2TrackedChanges;return f&&typeof f=="object"?f:null},T=()=>{const f=S()?.host;return f&&typeof f=="object"?f:null},R=f=>{if(f.storyType!=="headerFooterPart"||typeof f.refId!="string")return null;const v=S(),b=T(),A=v?.pageLayout??b?.pageLayout;if(!A||typeof A!="object")return null;const E=A.getActiveRulerContext,U=b?.resolveHeaderFooterEditTarget;if(typeof E!="function"||typeof U!="function")return null;const Y=xt(()=>E.call(A),null);if(!Y||typeof Y.pageIndex!="number")return null;for(const re of["header","footer"]){const ye=xt(()=>U.call(b,{pageIndex:Y.pageIndex,kind:re}),null);if(!(ye?.status!=="ready"||ye.refId!==f.refId||typeof ye.sectionId!="string"||!["default","first","even"].includes(String(ye.slotVariant))))return{kind:"story",storyType:"headerFooterSlot",section:{kind:"section",sectionId:ye.sectionId},headerFooterKind:re,variant:ye.slotVariant}}return null},M=()=>{const f=T(),v=f?.getPendingInlineFormat;if(typeof v!="function")return null;const b=xt(()=>v.call(f),null);return b&&typeof b=="object"?b:null},H=f=>{const v=Z0(f);if(!v)return null;const b=M();if(!b||!(v in b))return null;const A=b[v];return f.inline?.kind==="toggle"?A===!0:A!=null&&A!==""},B=f=>{const v=Z0(f);if(!v)return;const b=M();if(!b||!(v in b))return;const A=b[v];if(typeof A=="string"&&A!=="")return A;if(typeof A=="number"&&Number.isFinite(A))return String(A)},z=(f,v)=>{const b=T(),A=b?.setPendingInlineFormat;typeof A=="function"&&xt(()=>A.call(b,f,v),void 0)},Z=f=>{const v=T(),b=v?.clearPendingInlineFormat;typeof b=="function"&&xt(()=>b.call(v,f),void 0)},P=new Set(["bold","italic","underline","strikethrough"]),N=f=>{const v=M();if(!v)return;const b=Array.isArray(f.activeMarks)?f.activeMarks:[];let A=null;for(const E of Object.keys(v)){const U=v[E];let Y;if(P.has(E))Y=b.includes(E)===(U===!0);else if(K0(E)){if(U==null)continue;A||(A=Ms(f)),Y=A[E]===U}else Y=!1;Y&&Z(E)}},I=()=>{const f=S()?.editCommands;return f&&typeof f=="object"?f:null},L=f=>{const v=I();if(!v||typeof v.getSnapshot!="function")return null;const b=xt(()=>v.getSnapshot(),null)?.commands?.[f];return b&&typeof b=="object"?b:null},X=()=>L("lists.apply"),te=f=>{const v=f?.value?.seed;return v==="bullet"||v==="ordered"?v:null},le=f=>{const v=vH[f];return v?L(v):null},fe=()=>{const f=T();if(!f||typeof f.getTableContext!="function")return null;const v=xt(()=>f.getTableContext(),null);return v&&typeof v=="object"?v:null},Fe=()=>{const f=fe();if(!f||f.inTable!==!0)return null;const v=f.table,b=typeof v?.nodeId=="string"&&v.nodeId.length>0?v.nodeId:null;if(!b)return null;const A=f.row,E=f.column,U=f.cell,Y=typeof A?.index=="number"&&Number.isInteger(A.index)?A.index:null,re=typeof E?.index=="number"&&Number.isInteger(E.index)?E.index:null;if(Y==null||re==null)return null;const ye=typeof U?.nodeId=="string"&&U.nodeId.length>0?U.nodeId:null,Re=f.cellRange;return{tableNodeId:b,rowIndex:Y,columnIndex:re,cellNodeId:ye,mergeRange:PH(Re)}},he=new Map;let ge=null,ae=null,Ce=0,oe=0,xe=0;const qe=new Set,et=(f,v)=>f===v?!0:!f||!v?!1:f.id===v.id&&f.paintedEntityId===v.paintedEntityId&&no(f.story)===no(v.story),kt=f=>Array.from(qe).some(v=>et(v,f)),Ie=f=>{const v=T();if(typeof v?.getHandles!="function")return;const b=xt(()=>v.getHandles(),null),A=b?.review;if(A){if(f){if(typeof A.setActiveReviewTarget!="function")return;const E=b?.layout;xt(()=>A.setActiveReviewTarget({entityType:"trackedChange",entityId:f.id,...f.paintedEntityId?{paintedEntityId:f.paintedEntityId}:{},origin:"panel",layoutEpoch:typeof E?.generation=="number"?E.generation:0,story:f.story??{kind:"story",storyType:"body"}}),null);return}typeof A.getActiveReviewTarget!="function"||typeof A.clearActiveReviewTarget!="function"||xt(()=>A.getActiveReviewTarget(),null)?.entityType==="trackedChange"&&xt(()=>A.clearActiveReviewTarget(),void 0)}},ze=(f,v)=>{ae=f,Ce+=1,xe+=1,v?.invalidateQueuedNavigation!==!1&&(oe+=1)},Ve=new Set;let Q=!1,_=null;const $=new Map,F=new Set;let j=null,V=null,G=!1,J=null,K=0,W=null,ue=null,be=null;const we=()=>{if(G||Q)return;G=!0;const f=()=>{G=!1,Q||qt()};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Te=250,rt=5e3,nt=f=>{Q||J&&K<=f||(J&&clearTimeout(J),K=f,J=setTimeout(()=>{J=null,K=0,Q||qt()},Math.max(0,f-Date.now())))},wt=new WeakMap;let Zt=0;const Ct=f=>{if(!f)return"none";let v=wt.get(f);return v==null&&(v=Zt+=1,wt.set(f,v)),`e${v}`};let Ot=0,Bt={},on=null,Fn=null,Vt=0;const We=()=>{Fn&&clearTimeout(Fn),Fn=null,Vt=0};let St=f=>{},Nt=null,cn=new Set,Dt=0,un=null;const Ft=()=>`${Ct(S())}|m${Ot}`,Me=()=>{Nt=null,cn=new Set},Pe=f=>{for(const v of["trackChanges","trackChanges:all"]){const b=$.get(v);if(!b?.hasSettled||!Array.isArray(b.value))continue;const A=b.value.filter(E=>{const U=Un(E);return!U||!f.has(U)});A.length!==b.value.length&&$.set(v,{...b,value:A})}},Ze=f=>{const v=()=>{if(!Q)for(const U of[...Ve])U(dt)},b=yu(f)?f:null,A=S()?.documentMutationReadiness,E=()=>{const U=globalThis.requestAnimationFrame;return typeof U!="function"?Promise.resolve():new Promise(Y=>{let re=!1;const ye=()=>{re||(re=!0,clearTimeout(Re),Y())},Re=setTimeout(ye,250);U(()=>U(()=>setTimeout(ye,0)))})};if(b?.success===!0&&typeof b.txId=="string"&&b.txId.length>0&&typeof A?.whenPainted=="function")try{Promise.resolve(A.whenPainted.call(A,b)).then(E,()=>{}).then(v,v);return}catch{}v()},ot=(f,v)=>{const b=dt.trackChanges,A=b.items.filter(Y=>{const re=Un(Y);return!re||!f.has(re)});if(A.length===b.items.length)return;ae&&f.has(ae.id)&&ze(null);const E=new Set;for(const Y of A){const re=X0(Y),ye=Y,Re=re.author??re.authorEmail??ye.author??ye.authorEmail;typeof Re=="string"&&E.add(Re)}const U=b.items.length-A.length;dt={...dt,trackChanges:{...b,items:A,total:Math.max(A.length,b.total-U),activeId:b.activeId&&f.has(b.activeId)?null:b.activeId,authors:[...E]}},Ze(v)},Mt=(f,v)=>{if(f.size===0)return;const b=Ft(),A=Nt===b?cn:new Set,E=new Set([...f].filter(U=>!A.has(U)));E.size!==0&&(Nt=b,cn=new Set([...A,...E]),Pe(cn),ot(E,v))},Et=f=>Nt===f&&cn.size>0?cn:null,sn=(f,v=[])=>{const b=f.map(nc).filter(E=>E!=null&&Un(E)!=null);if(b.length===0)return;const A=v.map(nc).map(E=>E==null?null:Un(E)).filter(E=>E!=null);for(const E of["trackChanges","trackChanges:all"]){const U=$.get(E),Y=U?.hasSettled&&Array.isArray(U.value)?[...U.value]:[],re=new Set;let ye=!1;for(const Re of b){const Ue=Un(Re);if(!Ue)continue;const Ye=Y.findIndex(De=>Un(De)===Ue);if(Ye<0)Y.push(Re),re.add(Ue);else{const De=Y[Ye];Y[Ye]=yu(De)?{...De,...Re}:Re}ye=!0}if(E==="trackChanges"&&re.size>0&&A.length>0){const Re=new Set(A.filter(De=>re.has(De))),Ue=new Map(Y.filter(De=>Re.has(Un(De)??"")).map(De=>[Un(De),De])),Ye=Y.filter(De=>!Re.has(Un(De)??""));for(const[De,Ke]of A.entries()){if(!Re.has(Ke))continue;const Be=Ue.get(Ke);if(!Be)continue;const He=A.slice(De+1).map($e=>Ye.findIndex(Je=>Un(Je)===$e)).find($e=>$e>=0);if(He!=null){Ye.splice(He,0,Be);continue}const je=A.slice(0,De).reverse().map($e=>Ye.findIndex(Je=>Un(Je)===$e)).find($e=>$e>=0);Ye.splice(je==null?Ye.length:je+1,0,Be)}Y.splice(0,Y.length,...Ye)}ye&&$.set(E,{token:U?.token??null,value:Y,hasSettled:!0,inflightToken:null})}},Tt=f=>{const v=Ft(),b=Et(v),A=f.map(nc).filter(E=>{if(E==null)return!1;const U=Un(E);return U!=null&&!b?.has(U)});for(const E of["trackChanges","trackChanges:all"])$.set(E,{token:v,value:[...A],hasSettled:!0,inflightToken:null})},ur=async(f,v)=>{try{const b=f.v2TrackedChanges?.listTrackedChanges;if(typeof b=="function"){const U=await Promise.resolve(b.call(f.v2TrackedChanges,{mode:v.trackedChangesListMode,refreshReason:v.refreshReason,blocking:v.blocking,...v.targetIds?.length?{targetIds:v.targetIds}:{}})),Y=v.trackedChangesListMode==="all"&&v.refreshReason==="mutation-history-render-reconcile"?U?.ok===!0:U?.ok!==!1;return{ok:Y,items:Y&&Array.isArray(U?.items)?U.items:[],...typeof U?.complete=="boolean"?{complete:U.complete}:{},...typeof U?.sourceCoverageComplete=="boolean"?{sourceCoverageComplete:U.sourceCoverageComplete}:{}}}const A=f.docTrackChanges?.list;if(typeof A!="function")return{ok:!1,items:[]};const E=await Promise.resolve(A.call(f.docTrackChanges));return{ok:!0,items:Array.isArray(E?.items)?E.items:[]}}catch(b){return{ok:!1,items:[],failures:[b]}}},dr=k_({getContext:()=>{const f=S();if(!f)return null;const v=C(),b=y()?.trackChanges??null,A=v??b;if(!A)return null;const E=f.documentId??v?.documentId;return{editor:f,adapter:A,documentId:E==null?null:String(E),reconcileToken:Bt,v2TrackedChanges:v,docTrackChanges:b}},reconcile:async(f,v)=>{v.removedIds.size>0&&Mt(new Set(v.removedIds));const b=[...new Set(v.upsertIds)];if(b.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};const A=$.get("trackChanges"),E=A?.hasSettled&&Array.isArray(A.value)?A.value:null,U=new Set(E?E.map(Un).filter(je=>je!=null):[]),Y=E?.length===0&&po()==="complete",re=new Set(b.filter(je=>!U.has(je))),ye=f.v2TrackedChanges?.getTrackedChange,Re=f.docTrackChanges?.get;if(typeof ye!="function"&&typeof Re!="function")return{ok:!1,items:[],resolvedIds:[],unresolvedIds:b};const Ue=await Promise.all(b.map(async je=>{try{if(typeof ye=="function"){const Je=await Promise.resolve(ye.call(f.v2TrackedChanges,je));return{id:je,ok:Je?.ok!==!1,items:Je?.ok!==!1&&Array.isArray(Je?.items)?Je.items:[],result:Je}}const $e=await Promise.resolve(Re.call(f.docTrackChanges,{id:je}));return{id:je,ok:!0,items:$e&&typeof $e=="object"?[$e]:[],result:$e}}catch($e){return{id:je,ok:!1,items:[],result:$e}}})),Ye=[],De=[],Ke=[];for(const je of Ue){const $e=je.items.filter(Je=>{const Lt=nc(Je);return Lt!=null&&Un(Lt)===je.id});je.ok&&$e.length>0?(Ye.push(...$e),De.push(je.id)):Ke.push(je.id)}let Be;const He=De.filter(je=>re.has(je));if(He.length>0&&!Y){const je=await ur(f,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1,targetIds:He});je.ok&&(Be=je.items)}return{ok:Ke.length===0,items:Ye,orderedItems:Be,resolvedIds:De,unresolvedIds:Ke,failures:Ue.filter(je=>!je.ok).map(je=>je.result)}},hydrate:ur,onReconciled:(f,v,b)=>{if(b?.reconcileMode==="authoritative"){if(f.reconcileToken!==Bt)return;b.ok===!0&&b.complete===!0&&b.sourceCoverageComplete===!0?(We(),Tt(b.items??[]),on=null):b.ok===!0?(We(),sn(b.items??[])):St(f.reconcileToken),qt();return}sn((b?.items??[]).filter(A=>{const E=nc(A),U=E==null?null:Un(E);return U!=null&&v.has(U)}),b?.orderedItems??b?.items??[]),qt()}});St=f=>{if(Q||Fn)return;const v=Math.min(Te*2**Vt,rt);Vt+=1,Fn=setTimeout(()=>{Fn=null,!(Q||on===null||f!==Bt)&&dr.onRender(!0)},v)};const jr=()=>`${Ft()}|m${jn()}|s${Dt}`,$t=f=>JSON.stringify({t:f.target??null,s:f.selectionTarget??null}),Vn=["contentControls:inRange:","query:","effInline:"],Mr=120,_r=180,po=()=>{const f=T(),v=f?.getDocumentLoadingSnapshot;if(typeof v!="function")return"unknown";const b=xt(()=>v.call(f),null)?.sourceStage;return b==="opening"||b==="ready-window"||b==="source-loading"?"loading":b==="source-complete"||b==="source-failed"||b==="source-cancelled"?"complete":"unknown"},Kt=new Map,yn=f=>{const v=Ft();Kt.get(f)!==v&&(Kt.set(f,v),we())},xo=()=>{const f=$.get("comments");return f?.hasSettled?Array.isArray(f.value)&&f.value.length>0:f?.inflightToken!=null},Zo=(f,v)=>Kt.get(f)===v,Ei=f=>{yn("contentControls")},pi=()=>{const f=$.get("trackChanges");f?.hasSettled||f?.inflightToken!=null||yn("trackChanges")},Ss=6500,ks=8e3,As=250;let al=0,Wi=0,ro=!1,ke=0,Oe=!1,ht=null;const lt=()=>{if(Q||ht)return;const f=ke||Date.now(),v=()=>{if(ht=null,Q)return;const b=Date.now()-al,A=go()||b<Ss;if(A&&Date.now()-f<ks){ht=setTimeout(v,As);return}ro=!1,Oe=A;try{qt()}finally{Oe=!1,ke=0}};ht=setTimeout(v,0)};let bn=null,an=null;const Fr=()=>{const f=T();if(!f||bn===f)return;an&&(an(),an=null),bn=f;const v=f.subscribeDocumentLoading;if(typeof v!="function"){bn=null,To(Ss);return}try{const b=U=>{const Y=U?.sourceStage;(Y==="source-complete"||Y==="source-failed"||Y==="source-cancelled")&<()},A=v.call(f,b);typeof A=="function"&&(an=A);const E=f.getDocumentLoadingSnapshot;typeof E=="function"&&b(xt(()=>E.call(f),null))}catch{bn=null,To(Ss)}},mo=()=>{const f=S()?.host,v=f?.getForegroundMutationState;if(typeof v!="function")return null;const b=xt(()=>v.call(f),null);return{active:typeof b?.active=="number"?b.active:0,pending:typeof b?.pending=="number"?b.pending:0}},go=()=>{const f=mo();return!!(f&&(f.active>0||f.pending>0))},To=(f=Mr)=>{Q||W||(W=setTimeout(()=>{if(W=null,Q)return;if(ue&&go()){To(),qt();return}const v=ue;ue=null,v===jr()&&oc("selection",v,fl,Yi),qt()},f))},Is=(f,v)=>{if(!mo())return!1;const b=`${f}\0${v}`;return F.has(b)?!1:(F.add(b),To(_r),!0)},Jo=f=>{if(j==null||f===j)return V?.timer&&clearTimeout(V.timer),V=null,j=f,!1;if(V?.key===f)return V.ready?(V=null,j=f,!1):!0;V?.timer&&clearTimeout(V.timer);const v={key:f,ready:!1,timer:null};return v.timer=setTimeout(()=>{Q||V!==v||(v.timer=null,v.ready=!0,qt())},_r),V=v,!0},Ro=f=>A_(f),Ki=()=>{mi(),qt()};let Gr=null,Sr=!1,Mo=0;const Ho=()=>{Gr=null,Sr=!1,Mo+=1},$o=()=>{const f=S(),v=f?.documentMutationReadiness;if(!f||typeof v?.whenPainted!="function"||(Gr={editor:f,readiness:v,afterEpoch:typeof v.getRenderEpoch=="function"?xt(()=>v.getRenderEpoch.call(v),null):null},Sr))return;Sr=!0;const b=Mo;(async()=>{for(;!Q&&b===Mo;){const E=Gr;if(Gr=null,!E){Sr=!1;return}let U=!1;try{await E.readiness.whenPainted.call(E.readiness,typeof E.afterEpoch=="number"?{afterEpoch:E.afterEpoch}:void 0),U=!0}catch{}if(Q||b!==Mo)return;if(S()!==E.editor){Ho();return}U&&Ki()}})()},ll=()=>{be&&clearTimeout(be),be=setTimeout(()=>{be=null,Q||Ki()},500)},oc=(f,v,b,A)=>{let E;try{E=b()}catch{E=void 0}if(!Or(E)){const re={token:v,value:A(E),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0};return $.set(f,re),re}const U=$.get(f),Y=U?.failedToken===v;return $.set(f,{token:U?.token??null,value:U?.value??null,hasSettled:U?.hasSettled??!1,inflightToken:v,failedToken:Y?v:null,failureCount:Y?U.failureCount??0:0,retryAtMs:0}),Promise.resolve(E).then(re=>{const ye=$.get(f);!ye||ye.inflightToken!==v||($.set(f,{token:v,value:A(re),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0}),we())},()=>{const re=$.get(f);if(!re||re.inflightToken!==v)return;const ye=re.failedToken===v?(re.failureCount??0)+1:1,Re=Math.min(rt,Te*2**Math.min(ye-1,8)),Ue=Date.now()+Re;$.set(f,{...re,inflightToken:null,failedToken:v,failureCount:ye,retryAtMs:Ue}),nt(Ue)}),null},kr=(f,v,b,A)=>{const E=$.get(f);if(E&&E.token===v&&E.hasSettled)return{value:E.value,status:"ready"};if(iH(f)&&!Zo(f,v)){if(po()==="loading")return ro=!0,Fr(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(ro&&!Oe)return lt(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!Oe){const Y=Date.now();if(Y-Wi<Ss&&(!ke||Y-ke<ks))return ke||(ke=Y),ro=!0,lt(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};ke=0}}if(go())return To(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(E?.failedToken===v&&E.inflightToken==null&&(E.retryAtMs??0)>Date.now())return nt(E.retryAtMs),E.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!E&&f.startsWith("effInline:")&&Jo(f))return{value:null,status:"pending"};if(!E&&Is(f,v))return{value:null,status:"pending"};if(!E||E.inflightToken!==v){const Y=oc(f,v,b,A);if(Y)return{value:Y.value,status:"ready"}}const U=$.get(f);return U?.hasSettled?{value:U.value,status:"stale"}:{value:null,status:"pending"}},Uo=f=>{for(const v of $.keys())f(v)&&$.delete(v)},xi=f=>{const v=$t(f),b=aA(f);return new Set([`contentControls:inRange:${v}`,`query:${v}`,...b?[`effInline:${b}`]:[]])},cl=f=>{const v=xi(f);Uo(b=>Vn.some(A=>b.startsWith(A))&&!v.has(b));for(const b of F){const A=b.split("\0",1)[0];Vn.some(E=>A.startsWith(E))&&!v.has(A)&&F.delete(b)}},qi=()=>{const f=S();f!==un&&(Ho(),dr.reset(),Bt={},un=f,$.clear(),on=null,We(),J&&clearTimeout(J),J=null,K=0,V?.timer&&clearTimeout(V.timer),V=null,j=null,w=null,o=null,ue=null,F.clear(),Kt.clear(),ro=!1,ke=0,an&&an(),an=null,bn=null,Me())},mi=()=>{const f=on!==null;Ot+=1,f&&(on=Ft()),Me()},Rf=f=>{if(typeof f!="string"||f.length===0)return cr("insertText requires a non-empty string.","INVALID_INPUT");if(jn()==="viewing")return cr("The document is read-only.","DOCUMENT_READONLY");const v=y(),b=v?.insert;if(!v||typeof b!="function")return cr("insert is unavailable.");const A=v.selection?.current;if(typeof A!="function")return cr("selection.current is unavailable.");const E=Y=>{const re=Y&&typeof Y=="object"?Y:null,ye=re?.selectionTarget??re?.target??null;return!ye||typeof ye!="object"?cr("insertText requires a live selection target.","PRECONDITION_FAILED"):xt(()=>Aa(b.call(v,{type:"text",value:f,target:ye}),cr("insert failed.")),cr("insert failed."))};let U;try{U=A.call(v.selection)}catch{return cr("insertText could not resolve the live selection.","PRECONDITION_FAILED")}return Or(U)?Promise.resolve(U).then(E,()=>cr("insertText could not resolve the live selection.","PRECONDITION_FAILED")):E(U)},ei=(f,v)=>({payload:f,state:dt,editor:S(),superdoc:t,context:v,ui:_,execute:(b,A)=>gc(b,A),executeAsync:(b,A)=>mm(b,A),doc:y(),selection:dt.selection,documentMode:jn(),insertText:Rf}),ul=f=>f==="editing"||f==="suggesting"||f==="viewing"?f:null,jn=()=>{const f=S(),v=t&&typeof t=="object"?t:null,b=ul(v?.config?.documentMode),A=ul(xt(typeof v?.getActiveRuntime=="function"?()=>{const U=v.getActiveRuntime();return typeof U?.getSnapshot=="function"?U.getSnapshot():null}:void 0,null)?.documentMode),E=ul(f?.options?.documentMode);return b&&A&&b!==A?b:A??b??E},ic=()=>{const f=t&&typeof t=="object"?t:null,v=f?.interactionConfig?.comments;if(v&&typeof v.readOnly=="boolean")return v.readOnly===!0;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.readOnly===!0},wu=()=>{const f=t&&typeof t=="object"?t:null,v=f?.interactionConfig?.comments;if(v&&typeof v.allowResolve=="boolean")return v.allowResolve===!1;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.allowResolve===!1},ba=()=>jn()==="viewing"||ic(),Yi=f=>f&&typeof f=="object"?f:null,Es=(f,v)=>{if(!f)return{...nH,status:v};const b=f.target??null,A=typeof f.text=="string"?f.text:"";return{status:v,empty:f.empty===!0,target:b,selectionTarget:f.selectionTarget??null,activeMarks:Array.isArray(f.activeMarks)?f.activeMarks:[],activeCommentIds:Array.isArray(f.activeCommentIds)?f.activeCommentIds:[],activeChangeIds:Array.isArray(f.activeChangeIds)?f.activeChangeIds:[],quotedText:A}},dl=()=>{const f=y()?.selection;return kr("selection",jr(),()=>f?.current?f.current({includeText:!0}):void 0,Yi)},Cu=()=>{const{value:f,status:v}=dl();return Es(f,v)},fl=()=>{const f=y()?.selection;return f?.current?f.current({includeText:!0}):void 0},_u=f=>{if(f.empty!==!0)return!1;const v=f.selectionTarget,b=v?.start,A=v?.end;return b?.kind==="text"&&A?.kind==="text"&&typeof b.blockId=="string"&&b.blockId===A.blockId&&typeof b.offset=="number"&&b.offset===A.offset},Ti=f=>{const v=T(),b=v?.readLiveSelectionSyncSnapshot;if(typeof b!="function")return;const A=Yi(xt(()=>b.call(v),null));if(!A||!_u(A))return;const E=jr(),U=mo(),Y=!!(U&&(U.active>0||U.pending>0));if(Y)ue=E,To();else if(ue=null,oc("selection",E,fl,Yi))return;const re=$.get("selection"),ye=Array.isArray(A.activeMarks)&&A.activeMarks.length>0?A.activeMarks:Array.isArray(dt.selection.activeMarks)?dt.selection.activeMarks:[],Re=Array.isArray(A.activeCommentIds)?A.activeCommentIds:[],Ue=uH(f),Ye=ol(dt.selection),De=xf(A.selectionTarget)??xf(A.target),Ke=Ye?.range,Be=De?.range,He=!!(U&&U.active>0&&Ye&&De&&Ye.blockId===De.blockId&&no(Ye.story)===no(De.story)&&typeof Ke?.start=="number"&&typeof Be?.start=="number"&&Math.abs(Be.start-Ke.start)<=2),je=Ue!=null||He?dt.selection.activeChangeIds.filter(Je=>Ue==null||Ef(dt.trackChanges.items).aliasesFor(Je).includes(Ue)):[],$e=Array.isArray(A.activeChangeIds)&&A.activeChangeIds.length>0?A.activeChangeIds:je;$.set("selection",{token:E,value:{...A,activeMarks:ye,activeCommentIds:Re,activeChangeIds:$e},hasSettled:!0,inflightToken:Y?null:re?.inflightToken??null})},xs=async(f=0)=>{const v=y()?.selection,b=v?.current,A=jr();if(typeof b!="function")return $.set("selection",{token:A,value:null,hasSettled:!0,inflightToken:null}),qt(),dt.selection;let E;try{E=b.call(v,{includeText:!0}),Or(E)&&(E=await Promise.resolve(E))}catch{E=null}return Q?Es(null,"pending"):jr()!==A?f<1?xs(f+1):dt.selection:($.set("selection",{token:A,value:Yi(E),hasSettled:!0,inflightToken:null}),qt(),dt.selection)},Mf=f=>{const v=y()?.comments,{value:b,status:A}=kr("comments",Ft(),()=>v?.list?v.list():void 0,re=>re&&Array.isArray(re.items)?re.items:[]),E=b??[],U=f.activeCommentIds;ge&&!E.some(re=>Un(re)===ge)&&(ge=null);const Y=ge??U[0]??null;return{status:mu(A,f.status),listStatus:A,items:E,total:E.length,activeIds:U,activeId:Y}},Ts=()=>{const f=y()?.trackChanges,v=Ft(),b=$.get("trackChanges:all"),{value:A,status:E}=on===v?{value:b?.hasSettled?b.value:null,status:b?.hasSettled?"stale":"pending"}:kr("trackChanges:all",v,()=>f?.list?f.list({in:"all"}):void 0,U=>(U&&Array.isArray(U.items)?U.items:[]).map(nc).filter(Y=>Y!=null));return E==="ready"?A:null},hl=f=>{const v=y()?.trackChanges,b=C(),A=typeof b?.listTrackedChanges=="function"?b.listTrackedChanges:null,E=Ft(),U=Et(E),Y=$.get("trackChanges"),{value:re,status:ye}=on===E?{value:Y?.hasSettled?Y.value:null,status:Y?.hasSettled?"stale":"pending"}:kr("trackChanges",E,()=>A?A.call(b):v?.list?v.list():void 0,He=>He&&Array.isArray(He.items)?He.items.filter(je=>!A||no(em(je))==="story:body"):[]),Re=(re??[]).map(nc).filter(He=>He!=null).filter(He=>{const je=Un(He);return!je||!U?.has(je)}),Ue=new Set;for(const He of Re){const je=X0(He),$e=He,Je=je.author??je.authorEmail??$e.author??$e.authorEmail;typeof Je=="string"&&Ue.add(Je)}const Ye=v?.list?Ts():null,De=ae;De&&(De.story?Ye&&!Ye.some(He=>rl(He,De.id,De.story))&&ze(null):Re.some(He=>Un(He)===De.id)||ze(null));const Ke=U?f.activeChangeIds.filter(He=>!U.has(He)):f.activeChangeIds,Be=ae?.id??Ke[0]??null;return{status:mu(ye,f.status),items:Re,total:Re.length,activeId:Be,authors:[...Ue]}},Lo=f=>{const v=y()?.contentControls,{value:b,status:A}=kr("contentControls",Ft(),()=>v?.list?v.list():void 0,re=>re&&Array.isArray(re.items)?re.items:[]),E=b??[],{ids:U,status:Y}=Su(v,f);return{status:mu(A,Y,f.status),items:E,total:E.length,activeId:U[0]??null,activeIds:U}},ti=(f,v)=>{if(!f||typeof f.listInRange!="function")return{lockModesById:new Map,status:"ready"};const b=hH(v);if(!b)return{lockModesById:new Map,status:"ready"};const{value:A,status:E}=kr(`contentControls:inRange:${$t(v)}`,Ft(),()=>f.listInRange(b),re=>re&&Array.isArray(re.items)?re.items:[]),U=A??[],Y=new Map;for(const re of U)typeof re?.id=="string"&&Y.set(re.id,typeof re.lockMode=="string"?re.lockMode:"unlocked");return{lockModesById:Y,status:E}},Su=(f,v)=>{const{lockModesById:b,status:A}=ti(f,v);return{ids:[...b.keys()],status:A}},ku=()=>{const f=t?.fonts;return{options:UH(zH(xt(f?.getDocumentFontOptions?()=>f.getDocumentFontOptions():void 0,[])),HH(xt(f?.getFontFamilyOptions?()=>f.getFontFamilyOptions():void 0,[]))),sizeOptions:VH}},ni=()=>{const f=xt(t?.getZoomState?()=>t.getZoomState():void 0,null),v=typeof f?.value=="number"?f.value:100,b=f?.mode;return{mode:b==="manual"||b==="fit-width"?b:b==="fixed"?"manual":null,value:v,min:typeof f?.min=="number"?f.min:10,max:typeof f?.max=="number"?f.max:100}},Rs=()=>xt(t?.getMeasurementUnit?()=>t.getMeasurementUnit():void 0,"in")==="cm"?"cm":"in",pl=()=>{const f=S();return{ready:f!=null,mode:jn(),dirty:f?!!f.isDirty:!1}},wa=f=>{const v=f.quotedText;if(typeof v!="string"||v.length===0)return null;const b=vu(f);if(b.length===0||!tc(b.map(U=>U.blockId)))return null;const A=f.target,E=b.length===1?ho(b[0].blockId,A?.story):void 0;return{select:{type:"text",pattern:v,mode:"contains",caseSensitive:!0},...E?{within:E}:{},require:"any"}},ml=f=>{const v=y()?.query;if(typeof v?.match!="function")return null;const b=wa(f);if(!b)return null;const{value:A}=kr(`query:${$t(f)}`,Ft(),()=>v.match(b),E=>E&&typeof E=="object"?E:null);return lA(A,f)},Xi=f=>{const v=T(),b=new Set(Rr(f));if(b.size===0)return{};const A=v?.readMountedProjectionBlocksByIds,E=v?.readMountedProjectionBlocks;if(typeof A!="function"&&typeof E!="function")return{};const U=xt(()=>{if(typeof A!="function")return E.call(v);const He=_s(f);return He?A.call(v,[...b],He):A.call(v,[...b])},null);if(!Array.isArray(U))return{};const Y=Q0(U),re=He=>{const je={},$e=q0(He.fontFamily);$e&&(je.fontFamily=$e);const Je=kH(He.fontSize);return Je&&(je.fontSize=Je),typeof He.color=="string"&&He.color.trim()!==""&&(je.color=He.color.trim().toUpperCase()),typeof He.highlight=="string"&&He.highlight.trim()!==""&&(je.highlight=He.highlight.trim().toUpperCase()),je},ye=ol(f),Re=ye&&typeof ye.range?.start=="number"?ye.range.start:null;if(ye&&Re!==null&&b.has(ye.blockId)){const He=Y.find($e=>rc($e,ye.blockId)),je=He&&Array.isArray(He.runs)?He.runs:null;if(je&&je.length>0&&je.every($e=>$e?.kind==="text"||$e?.kind==="tab")){let $e=0,Je=null;for(const Lt of je){const Yt=typeof Lt.text=="string"?Lt.text.length:0;if(Re>=$e&&Re<$e+Yt){Je=Lt;break}$e+=Yt}if(!Je){for(let Lt=je.length-1;Lt>=0&&!Je;Lt-=1)je[Lt]?.kind==="text"&&(Je=je[Lt]);Je??=je[je.length-1]??null}return Je?re(Je):{}}}const Ue=vu(f);if(Ue.length>0){const He=new Set,je=new Set;let $e=!1,Je=!0;for(const Lt of Ue){const Yt=Y.find(Yr=>rc(Yr,Lt.blockId));if(!Yt)return{};const zn=Array.isArray(Yt.runs)?Yt.runs:[];if(zn.length===0)continue;if(!zn.every(Yr=>Yr?.kind==="text"||Yr?.kind==="tab")){Je=!1;break}let qn=0;for(const Yr of zn){const Nr=typeof Yr.text=="string"?Yr.text.length:0,Lr=qn,Ar=qn+Nr;if(Lr<Lt.end&&Ar>Lt.start){$e=!0;const jo=re(Yr);jo.fontFamily&&He.add(jo.fontFamily),jo.fontSize&&je.add(jo.fontSize)}qn=Ar}}if(Je&&$e){const Lt={};return He.size===1&&(Lt.fontFamily=[...He][0]),je.size===1&&(Lt.fontSize=[...je][0]),Lt}}const Ye=new Set,De=new Set;let Ke=!1;for(const He of Y){if(![...b].some($e=>rc(He,$e)))continue;const je=Array.isArray(He.runs)?He.runs:[];for(const $e of je){if($e?.kind!=="text")continue;Ke=!0;const Je=re($e);Je.fontFamily&&Ye.add(Je.fontFamily),Je.fontSize&&De.add(Je.fontSize)}}if(!Ke)return{};const Be={};return Ye.size===1&&(Be.fontFamily=[...Ye][0]),De.size===1&&(Be.fontSize=[...De][0]),Be},sc=f=>{const v=T(),b=new Set(Rr(f));if(b.size===0)return{};const A=v?.readMountedProjectionBlocksByIds,E=v?.readMountedProjectionBlocks;if(typeof A!="function"&&typeof E!="function")return{};const U=xt(()=>{if(typeof A!="function")return E.call(v);const Be=_s(f);return Be?A.call(v,[...b],Be):A.call(v,[...b])},null);if(!Array.isArray(U))return{};const Y=Q0(U),re=Be=>({bold:Be.bold===!0,italic:Be.italic===!0,underline:Be.underline!=null,strikethrough:Be.strike===!0}),ye=Be=>{const He={};for(const je of Tf){const $e=Be[je];$e.size===1&&(He[je]=[...$e][0])}return He},Re=ol(f),Ue=Re&&typeof Re.range?.start=="number"?Re.range.start:null;if(Re&&Ue!==null&&b.has(Re.blockId)){const Be=Y.find(je=>rc(je,Re.blockId)),He=Be&&Array.isArray(Be.runs)?Be.runs:null;if(He&&He.length>0&&He.every(je=>je?.kind==="text"||je?.kind==="tab")){let je=0,$e=null;for(const Je of He){const Lt=typeof Je.text=="string"?Je.text.length:0;if(Ue>=je&&Ue<je+Lt){$e=Je;break}je+=Lt}if(!$e){for(let Je=He.length-1;Je>=0&&!$e;Je-=1)He[Je]?.kind==="text"&&($e=He[Je]);$e??=He[He.length-1]??null}return $e?re($e):{}}}const Ye=vu(f);if(Ye.length>0){const Be={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let He=!1,je=!0;for(const $e of Ye){const Je=Y.find(zn=>rc(zn,$e.blockId));if(!Je)return{};const Lt=Array.isArray(Je.runs)?Je.runs:[];if(Lt.length===0)continue;if(!Lt.every(zn=>zn?.kind==="text"||zn?.kind==="tab")){je=!1;break}let Yt=0;for(const zn of Lt){const qn=typeof zn.text=="string"?zn.text.length:0,Yr=Yt,Nr=Yt+qn;if(Yr<$e.end&&Nr>$e.start){He=!0;const Lr=re(zn);for(const Ar of Tf)Be[Ar].add(Lr[Ar])}Yt=Nr}}if(je&&He)return ye(Be)}const De={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Ke=!1;for(const Be of Y){if(![...b].some(je=>rc(Be,je)))continue;const He=Array.isArray(Be.runs)?Be.runs:[];for(const je of He){if(je?.kind!=="text")continue;Ke=!0;const $e=re(je);for(const Je of Tf)De[Je].add($e[Je])}}return Ke?ye(De):{}},ac=(f,v)=>{if(v.fontFamily!==void 0&&v.fontSize!==void 0&&v.color!==void 0&&v.highlight!==void 0)return{values:v,effectiveUniformityStatus:"ready"};const b=Xi(f),A={...b.fontFamily!==void 0?{fontFamily:b.fontFamily}:{},...b.fontSize!==void 0?{fontSize:b.fontSize}:{},...b.color!==void 0?{color:b.color}:{},...b.highlight!==void 0?{highlight:b.highlight}:{},...v};if(!f.empty&&(A.fontFamily===void 0||A.fontSize===void 0)){const E=Lf(f);return E.values&&(A.fontFamily===void 0&&E.values.fontFamily!==void 0&&(A.fontFamily=E.values.fontFamily),A.fontSize===void 0&&E.values.fontSize!==void 0&&(A.fontSize=E.values.fontSize)),{values:A,effectiveUniformityStatus:E.status}}return{values:A,effectiveUniformityStatus:"ready"}},lc=["fontFamily","fontSize","bold","italic","underline","strikethrough"],Au=f=>{const v=f.selectionTarget;if(!v)return{value:null,status:"ready"};const b=gr(y(),"format.readEffectiveInlineUniformity");return b?kr(`effInline:${aA(f)??$t(f)}`,Ft(),()=>b({target:v,offsetSpace:"selection",keys:lc}),A=>A&&typeof A=="object"?A:null):{value:null,status:"ready"}},Lf=f=>{const{value:v,status:b}=Au(f);if(!v||v.success!==!0)return{values:null,status:b};const A=v.values,E=U=>{const Y=A?.[U];if(!(!Y||Y.state!=="uniform"||typeof Y.value!="string"))return U==="fontFamily"?q0(Y.value):Y.value};return{values:{fontFamily:E("fontFamily"),fontSize:E("fontSize")},status:b}},cc=f=>{const{value:v,status:b}=Au(f);if(!v||v.success!==!0)return{values:null,status:b};const A=v.values,E={};for(const U of Tf){const Y=A?.[U];Y?.state==="uniform"&&(Y.value==="true"||Y.value==="false")&&(E[U]=Y.value==="true")}return{values:E,status:b}},Ca=(f,v)=>{const b=f.activeMark;if(!b||!Tf.includes(b))return null;const A=b,E=sc(v)[A];if(E!==void 0)return E;const{values:U}=cc(v),Y=U?.[A];return Y!==void 0?Y:null},Df=async f=>{const v=f.selectionTarget;if(!v)return null;const b=gr(y(),"format.readEffectiveInlineUniformity");if(!b)return null;try{const A=await Promise.resolve(b({target:v,offsetSpace:"selection"}));return A&&typeof A=="object"&&A.success===!0?A:null}catch{return null}},Iu=(f,v,b)=>{const A=b.values;for(const E of["fontFamily","fontSize"]){if(v[E]!==void 0)continue;const U=A?.[E];U?.state==="uniform"&&typeof U.value=="string"?f[E]=E==="fontFamily"?q0(U.value):U.value:delete f[E]}},uc=f=>ac(f,cA(ml(f),f)),Ms=f=>uc(f).values,Eu=async f=>{const v=y()?.query,b=wa(f);if(typeof v?.match!="function"||!b)return Ms(f);try{const A=await Promise.resolve(v.match(b)),E=cA(lA(A&&typeof A=="object"?A:null,f),f),U=ac(f,E);if(U.effectiveUniformityStatus!=="ready"&&(E.fontFamily===void 0||E.fontSize===void 0)){const Y=await Df(f);Y&&Iu(U.values,E,Y)}return U.values}catch{return Ms(f)}},Ls=async f=>{const v=y();if(v)return typeof v.getNode=="function"?await Promise.resolve(v.getNode(f)):await Promise.resolve(v.getNodeById?.({nodeId:f.nodeId,nodeType:f.nodeType}))},dc=f=>{const v=y()?.query;if(typeof v?.match!="function")return"ready";const b=wa(f);if(!b)return"ready";const{status:A}=kr(`query:${$t(f)}`,Ft(),()=>v.match(b),E=>E&&typeof E=="object"?E:null);return A},xu=f=>{const v=uc(f),b=v.values;if(f.empty)return v;const A=ya(f);return A?f.status==="ready"&&dc(f)==="ready"&&v.effectiveUniformityStatus==="ready"?(w={key:A,values:b},v):w&&w.key===A?{...v,values:{...w.values,...b}}:v:v},Tu=f=>{const v=y(),b=xu(f),A=b.values;f.status==="ready"&&!f.empty&&dc(f)==="ready"&&b.effectiveUniformityStatus==="ready"&&(g=A,k=`${$l(f)}:${Ft()}`);const E=v?.contentControls,{lockModesById:U}=ti(E,f),Y={};for(const re of Bn())Y[re]=fc(re,v,f,A,U);return Y},Qi=f=>f?at.operationUnavailable:S()?at.documentApiUnavailable:at.notReady,Ru=f=>f==="contentLocked"||f==="sdtContentLocked",Zi=f=>{for(const v of f.values())if(Ru(v))return at.contentControlLocked},Pf=(f,v,b,A,E)=>{if(!v)return f.scope==="all"?at.bulkDecisionsDisabled:Qi(E);if(b)return at.documentReadonly;if(f.scope!=="all"&&A.activeChangeIds.length===0)return at.selectionRequired},Mu=f=>{const v=T(),b=xt(typeof v?.getCapabilities=="function"?()=>v.getCapabilities():void 0,null)?.editableSubset?.commands;if(Array.isArray(b))return b.find(A=>A?.command===f||A?.id===f)??null;if(b&&typeof b=="object"){const A=b[f];return A&&typeof A=="object"?A:null}return null},gl=(f,v)=>{if(f.scope!=="all"||typeof v?.[`${f.kind}All`]=="function")return;const b=Mu(`trackedChanges.${f.kind}All`);if(!(b&&(b.status==="supported"||b.enabled===!0)))return at.bulkDecisionsDisabled},fc=(f,v,b,A,E=new Map)=>{if(he.has(f))return tn({supported:!0,enabled:!0,...xt(he.get(f).getState?()=>he.get(f).getState(ei(void 0)):void 0,{})},"custom");const U=jn()==="viewing",Y=Jk(f);if(Y&&typeof I()?.lists?.apply=="function"){const Ke=X(),Be=typeof Ke?.shippedStatus=="string"?Ke.shippedStatus:null,He=Be!=="not-shipped"&&Be!=="disabled";return tn({enabled:He&&(typeof Ke?.enabled=="boolean"?Ke.enabled:!0),active:(He?te(Ke):null)===Y,supported:He,value:Ke?.value},"builtin")}const re=rm(f);if(re){const Ke=v?.trackChanges,Be=typeof Ke?.decide=="function"||typeof Ke?.[re.kind]=="function",He=typeof Ke?.decide=="function"||typeof Ke?.[`${re.kind}All`]=="function",je=re.scope==="all"?He:Be,$e=gl(re,Ke)??Pf(re,je,ba(),b,v);return tn({enabled:$e==null,active:!1,supported:je,reason:$e},"builtin")}if(f==="copy-format")return jn()==="viewing"?tn({supported:!0,enabled:!1,active:!1},"builtin"):S()?tn({supported:!0,enabled:!0,active:h.mode!=="idle"},"builtin"):tn({supported:!0,enabled:!1,active:!1,reason:at.notReady},"builtin");const ye=fu(f);if(!ye)return tn({enabled:!1,active:!1,supported:!1,reason:at.commandUnsupported},"unsupported");if(ye.disposition!=="routed")return tn({enabled:!1,active:!1,supported:!1,reason:ye.reason??at.commandUnsupported},ye.disposition==="unsupported"?"unsupported":"builtin");if(ye.instanceRoute)return vt(ye);if(ye.table)return it(ye,v,U);if(ye.inline?.kind==="clear"){if(ye.mutates&&U)return tn({enabled:!1,active:!1,supported:!0,reason:at.documentReadonly},"builtin");const Ke=Zi(E);if(Ke)return tn({enabled:!1,active:!1,supported:!0,reason:Ke},"builtin");const Be=Rr(b).length>0||bu(b)!=null;return tn({enabled:Be,active:!1,supported:!0,reason:Be?void 0:at.selectionRequired},"builtin")}const Re=ye.docRoute;if(!Re)return tn({enabled:!1,active:!1,supported:!1,reason:at.commandUnsupported},"unsupported");if(gr(v,Re)==null)return tn({enabled:!1,active:!1,supported:!1,reason:Qi(v)},"builtin");const Ue=le(f);if(Ue){const Ke=Ue.shippedStatus,Be=Ke!=="not-shipped"&&Ke!=="disabled",He=typeof Ue.enabled=="boolean"?Ue.enabled:!0,je=f==="undo"||f==="redo",$e=je&&Ue.historyResolved===!1,Je=je&&Be&&He===!1&&Ue.reason===null&&!$e,Lt=Ue.reason===void 0?void 0:Je?at.historyEmpty:$e?at.notReady:V0(Ue.reason,at.commandUnsupported);return ye.mutates&&U?tn({enabled:!1,active:!1,supported:Be,reason:at.documentReadonly},"builtin"):tn({enabled:Be&&He,active:!1,supported:Be,reason:Lt},"builtin")}const Ye=yl(ye,v,b),De=Du(ye,v,b,A);if(ye.list?.mode==="indent"||ye.list?.mode==="outdent")return Qe(ye,v,U,b,Ye,De);if(ye.list?.mode==="toggle-seed")return tt(ye,v,U,b,Ye,De);if(ye.mutates&&U)return tn({enabled:!1,active:Ye,supported:!0,value:De,reason:at.documentReadonly},"builtin");if(ye.inline&&!bu(b)){const Ke=Zi(E);return tn(Ke?{enabled:!1,active:Ye,supported:!0,value:De,reason:Ke}:Rr(b).length>0&&typeof T()?.setPendingInlineFormat=="function"?{enabled:!0,active:Ye,supported:!0,value:De}:{enabled:!1,active:Ye,supported:!0,value:De,reason:at.rangeSelectionRequired},"builtin")}if((ye.blockParagraph||ye.list)&&Rr(b).length===0)return tn({enabled:!1,active:Ye,supported:!0,value:De,reason:at.selectionRequired},"builtin");if(ye.link&&!Ye&&W0(b).length===0&&!ol(b))return tn({enabled:!1,active:Ye,supported:!0,reason:at.rangeSelectionRequired},"builtin");if(ye.inline){const Ke=Zi(E);if(Ke)return tn({enabled:!1,active:Ye,supported:!0,value:De,reason:Ke},"builtin")}return tn({enabled:!0,active:Ye,supported:!0,value:De},"builtin")};function Lu(f,v){const b=f.address?.anchor,A=b?.start,E=b?.end,U=typeof A?.blockId=="string"?A.blockId:null,Y=typeof E?.blockId=="string"?E.blockId:null;if(!U||!Y)return!1;const re=typeof A?.offset=="number"?A.offset:null,ye=typeof E?.offset=="number"?E.offset:null;if(re==null||ye==null)return!1;const Re=v.target,Ue=Re&&Array.isArray(Re.segments)?Re.segments:[];for(const Ye of Ue){const De=typeof Ye?.blockId=="string"?Ye.blockId:null;if(!De)continue;const Ke=Ye.range,Be=typeof Ke?.start=="number"?Ke.start:null,He=typeof Ke?.end=="number"?Ke.end:null;if(!(Be==null||He==null)){if(U!==Y){if(De===U&&He>re||De===Y&&Be<ye)return!0;continue}if(De===U){if(Be===He){if(Be>=re&&Be<=ye)return!0;continue}if(Math.max(Be,re)<Math.min(He,ye))return!0}}}return!1}const vl=(f,v)=>{const b=f?.hyperlinks;if(!b||typeof b.list!="function")return null;const A=Rr(v);if(!tc(A))return null;for(const E of A){const U={kind:"block",nodeType:"paragraph",nodeId:E},{value:Y}=kr(`hyperlinks:${E}`,Ft(),()=>b.list({within:U}),ye=>ye&&typeof ye=="object"?ye:null),re=(Y&&Array.isArray(Y.items)?Y.items:[]).find(ye=>Lu(ye,v));if(re)return re}return null},yl=(f,v,b)=>{if(f.link)return vl(v,b)!=null;if(f.list?.mode==="toggle-seed"&&f.list.seed)return Of(v,b)===f.list.seed;const A=H(f);if(A!==null)return A;const E=r.get(f.id),U=ya(b);if(U&&E?.selectionSignature===U)return E.active;const Y=Ca(f,b);return Y!==null?Y:jH(f,b)},Du=(f,v,b,A)=>{if(f.inline&&K0(f.inline.key)){const E=B(f);if(E!==void 0)return E;const U=A[f.inline.key];if(U!==void 0)return U;const Y=ya(b),re=Y?n.get(f.inline.key):void 0;if(Y&&re?.selectionSignature===Y)return re.value}if(f.id==="linked-style"){const{style:E}=Zn(b,Hn().cache);return!E.styleId||E.mixed?void 0:{styleId:E.styleId,styleName:E.styleName}}if(f.id==="text-align")return ie(v,b);if(f.id==="link")return st(v,b)??void 0},bl=(f,v,b)=>{const A=f?.lists;if(!A)return{value:null,status:"ready"};const E=b.storyType==="body",U=typeof A.getStateInStory=="function"?()=>A.getStateInStory({target:va(v),story:b}):E&&typeof A.getState=="function"?()=>A.getState({target:va(v)}):null;if(!U)return{value:null,status:"ready"};const{value:Y,status:re}=kr(`lists:${no(b)}:${v}`,Ft(),U,ye=>ye&&typeof ye=="object"?ye:null);return{value:Y?.success===!0?Y:null,status:re}},ri=(f,v,b)=>bl(f,v,b).value,Ji=(f,v,b)=>{const A=ri(f,v,b);return!A||A.isListItem!==!0?null:A.seed==="bullet"||A.seed==="ordered"?A.seed:null},Wr=(f,v,b)=>{const A=bl(f,v,b),E=A.value;return{value:E&&typeof E.isListItem=="boolean"?E.isListItem:null,status:A.status}},Of=(f,v)=>{const b=Rr(v);if(b.length===0||!tc(b))return null;const A=ga(v),E=Ji(f,b[0],A);if(E!=="bullet"&&E!=="ordered")return null;for(const U of b.slice(1))if(Ji(f,U,A)!==E)return null;return E},Pu=(f,v,b)=>{if(!f)return{value:null,status:"ready",refreshing:!1};const A=no(b),E=A==="story:body";if(E&&typeof f.getNodeById!="function")return{value:null,status:"ready",refreshing:!1};if(!E&&typeof f.getNode!="function")return{value:null,status:"ready",refreshing:!1};const U=`node:${A}:${v}`,Y=Ft(),re=kr(U,Y,()=>E?f.getNodeById({nodeId:v,nodeType:"paragraph"}):f.getNode(ho(v,b)),Re=>Re&&typeof Re=="object"?Re:null),ye=$.get(U);return{...re,refreshing:re.status==="stale"&&ye?.inflightToken===Y&&ye.failedToken!==Y}},Ds=f=>f==="left"||f==="center"||f==="right"||f==="justify"?f:void 0,hc=f=>f==="start"||f==="end"||f==="distributed"||f==="numTab"||f==="lowKashida"||f==="mediumKashida"||f==="highKashida"||f==="thaiDistribute",Ff=(f,v)=>{const b=T(),A=b?.readMountedProjectionBlocksByIds;if(typeof A!="function")return null;const E=_s(f),U=xt(()=>E?A.call(b,[...v],E):A.call(b,[...v]),null);if(!Array.isArray(U))return new Map;const Y=Q0(U),re=new Map;for(const ye of v){const Re=Y.find(Ke=>rc(Ke,ye));if(!Re)continue;const Ue=Re.attrs,Ye=Ds(Ue?.alignment),De=a9(Ue);re.set(ye,Ye??(De==="rtl"?"right":"left"))}return re},x=(f,v,b,A)=>{const{value:E,status:U,refreshing:Y}=Pu(f,v,b),re=A?.get(v);if(U==="pending")return re?{status:"uniform",value:re}:{status:"pending"};if(U==="stale"&&!Y)return{status:"pending"};if(U==="stale"&&re)return{status:"uniform",value:re};if(U==="stale"&&A&&!re)return{status:"unavailable"};if(!E)return{status:"unavailable"};const ye=E.node;if(!ye)return{status:"unavailable"};const Re=ye.kind;if(Re!=="paragraph"&&Re!=="heading")return{status:"unavailable"};const Ue=ye[Re];if(!Ue||typeof Ue!="object")return{status:"unavailable"};const Ye=Ue.props?.alignment;if(Ye==null)return re?{status:"uniform",value:re}:{status:"unavailable"};const De=Ds(Ye);return De?{status:"uniform",value:De}:hc(Ye)&&re?{status:"uniform",value:re}:{status:"unavailable"}},D=(f,v)=>{const b=Rr(v);if(b.length===0||!tc(b))return{status:"unavailable"};const A=ga(v),E=Ff(v,b),U=x(f,b[0],A,E);if(U.status!=="uniform")return U;for(const Y of b.slice(1)){const re=x(f,Y,A,E);if(re.status!=="uniform")return re;if(re.value!==U.value)return{status:"mixed"}}return U},ee=f=>{const v=Rr(f);return v.length===0?null:`${no(ga(f))}:${v.join(",")}`},ie=(f,v)=>{const b=D(f,v),A=b.status==="uniform"?b.value:void 0,E=o;if(!E)return A;const U=ee(v);return U&&U!==E.selectionSignature?(o=null,A):!U||!E.settled?E.value:b.status!=="pending"?(o=null,A):E.value},se=(f,v)=>{const b=Ds(v),A=ee(f),E=Rr(f);if(!b||!A||E.length===0)return null;const U=++i;return o={selectionSignature:A,value:b,generation:U,settled:!1,canReconcile:tc(E)},qt(),U},de=(f,v)=>{if(f==null)return;const b=o;if(!(!b||b.generation!==f)){if(!zo(v)){o=null;return}if(!b.canReconcile){o=null;return}b.settled=!0}},pe=async(f,v,b)=>{const A=f?.lists;if(!A)return null;try{const E=b.storyType==="body",U=typeof A.getStateInStory=="function"?await A.getStateInStory({target:va(v),story:b}):E&&typeof A.getState=="function"?await A.getState({target:va(v)}):null,Y=U&&typeof U=="object"?U:null;return!Y||Y.success!==!0||typeof Y.isListItem!="boolean"?null:Y.isListItem}catch{return null}},ve=(f,v,b)=>{const A={resolved:!1,seed:null},E=f?.lists;if(!E)return A;const U=b.storyType==="body",Y=typeof E.getStateInStory=="function"?()=>E.getStateInStory({target:va(v),story:b}):U&&typeof E.getState=="function"?()=>E.getState({target:va(v)}):null;if(!Y)return A;const re=ye=>{const Re=ye&&typeof ye=="object"?ye:null;return!Re||Re.success!==!0||typeof Re.isListItem!="boolean"?A:{resolved:!0,seed:Re.isListItem===!0&&(Re.seed==="bullet"||Re.seed==="ordered")?Re.seed:null}};try{const ye=Y();return Or(ye)?Promise.resolve(ye).then(re,()=>A):re(ye)}catch{return A}},Xe=async(f,v,b)=>{if(!f)return null;try{const A=!b||b.storyType==="body",E=b&&typeof f.getNode=="function"?await f.getNode(ho(v,b)):A&&typeof f.getNodeById=="function"?await f.getNodeById({nodeId:v,nodeType:"paragraph"}):null;return mH(E&&typeof E=="object"?E:null)}catch{return null}},Qe=(f,v,b,A,E,U)=>{if(f.mutates&&b)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.documentReadonly},"builtin");const Y=Rr(A);if(Y.length===0)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.selectionRequired},"builtin");const re=f.docRoute?gr(v,f.docRoute):null,ye=gr(v,"format.paragraph.setIndentation"),Re=gr(v,"format.paragraph.clearIndentation"),Ue=f.list?.mode,Ye=Ue==="indent"?ye!=null:ye!=null||Re!=null,De=ga(A);let Ke=null;if(De.storyType!=="body"){Ke=[];for(const Be of Y){const{value:He,status:je}=Wr(v,Be,De);if(He===null)return je!=="ready"&&(re!=null||Ye)?tn({enabled:!0,active:E,supported:!0,value:U},"builtin"):tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin");Ke.push(He)}}if(Ke?.some(Be=>Be===!0)){const Be=Ue==="indent"?"lists.indentRange":"lists.outdentRange",He=jn()!=="suggesting"&&Ke.every($e=>$e===!0)&&gr(v,Be)!=null,je=Ue==="outdent"&&gr(v,"lists.outdentInStory")!=null;if(!He&&!je)return tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin")}for(const[Be,He]of Y.entries()){const je=Ke?{value:Ke[Be]??null,status:"ready"}:Wr(v,He,De),$e=je.value;if($e===!0){if(re!=null)return tn({enabled:!0,active:E,supported:!0,value:U},"builtin");continue}if($e===!1&&Ye){if(De.storyType!=="body"&&typeof v?.getNode!="function")continue;return tn({enabled:!0,active:E,supported:!0,value:U},"builtin")}if($e===null)return je.status!=="ready"&&(re!=null||Ye)?tn({enabled:!0,active:E,supported:!0,value:U},"builtin"):tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin")}return tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin")},tt=(f,v,b,A,E,U)=>{if(f.mutates&&b)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.documentReadonly},"builtin");const Y=Rr(A);if(Y.length===0)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.selectionRequired},"builtin");const re=ga(A),ye=v?.lists;if(!(typeof ye?.getStateInStory=="function"||re.storyType==="body"&&typeof ye?.getState=="function"))return tn({enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");if(!tc(Y))return tn(re.storyType==="body"&&gr(v,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:U}:{enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");const Re=Y.map(Ke=>bl(v,Ke,re));if(Re.some(({status:Ke})=>Ke!=="ready"))return tn({enabled:!0,active:E,supported:!0,value:U},"builtin");if(Re.some(({value:Ke})=>Ke===null))return tn({enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");const Ue=f.list?.seed,Ye=Re.every(({value:Ke})=>Ke?.isListItem===!0&&Ke.seed===Ue);if(re.storyType==="body")return tn(!Ye||gr(v,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:U}:{enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");const De=gr(v,"lists.removeInStory");return tn(Ye&&De?{enabled:!0,active:E,supported:!0,value:U}:{enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin")},st=(f,v)=>{const b=vl(f,v)?.properties?.href;return typeof b=="string"?b:null},vt=f=>{if(!S())return tn({enabled:!1,active:!1,supported:!1,reason:at.notReady},"builtin");const v=f.instanceRoute;return typeof t?.[v]!="function"?tn({enabled:!1,active:!1,supported:!1,reason:at.operationUnavailable},"builtin"):tn({enabled:!0,active:pt(f),supported:!0,value:dn(f)},"builtin")},pt=f=>{const v=t?.config??void 0;return f.valueFrom==="ruler"?!!v?.rulers:f.valueFrom==="formattingMarks"?!!v?.layoutEngineOptions?.showFormattingMarks:!1},it=(f,v,b)=>{if(b)return tn({enabled:!1,active:!1,supported:!0,reason:at.documentReadonly},"builtin");const A=Fe();return A!=null&&(!f.table.requiresCell||A.cellNodeId!=null)?(f.docRoute?gr(v,f.docRoute):null)==null?tn({enabled:!1,active:!1,supported:!1,reason:Qi(v)},"builtin"):tn({enabled:!0,active:!1,supported:!0},"builtin"):tn({enabled:!1,active:!1,supported:!0,reason:at.tableContextUnavailable},"builtin")},dn=f=>{if(f.valueFrom==="zoom")return ni().value;if(f.valueFrom==="documentMode")return jn();if(f.valueFrom==="measurementUnit")return Rs();if(f.valueFrom==="ruler"||f.valueFrom==="formattingMarks")return pt(f)},rn=(f,v)=>f.id==="zoom"?typeof v=="number"&&Number.isFinite(v)&&v>0:f.id==="document-mode"?v==="editing"||v==="suggesting"||v==="viewing":f.id==="measurement-unit"?v==="in"||v==="cm":!0,Bn=()=>[...new Set([...nB,...he.keys()])],Gn="Normal",Wn={ready:!1,status:"ready",catalogRevision:null,quickGallery:[],activeParagraphStyleId:null,activeParagraphStyleName:null,mixedSelection:!1,sourceStatus:null,diagnostics:[]},vo=f=>{const v=y()?.styles;return!v||typeof v.getCatalog!="function"?{value:null,status:"ready"}:kr(`styles:catalog:${JSON.stringify(f??{})}`,Ft(),()=>v.getCatalog(f),b=>b&&typeof b=="object"?b:null)},Hn=()=>{const f=vo({includePreview:!0});if(!f.value)return{cache:null,status:f.status};const v=vo({view:"quickGallery",includePreview:!0}),b=v.value?v.value.items:f.value.styles.filter(E=>E.visibility.quickGallery),A=new Map;for(const E of f.value.styles)A.set(E.id,E);return{cache:{full:f.value,quickGallery:b,byId:A},status:mu(f.status,v.status)}},Mn=(f,v,b)=>{const{value:A,status:E}=Pu(f,v,b);if(!A)return{ok:!1,styleRef:null,status:E};const U=A.node;if(!U||typeof U!="object")return{ok:!1,styleRef:null,status:E};const Y=U.kind,re=typeof Y=="string"?U[Y]:void 0,ye=re&&typeof re=="object"?re.styleRef:void 0;return{ok:!0,styleRef:typeof ye=="string"&&ye.length>0?ye:null,status:E}},Zn=(f,v)=>{const b=[],A=y();if(!A)return b.push({severity:"warning",code:"active-style-unavailable",message:"Active paragraph style is unavailable: the Document API is not reachable."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:"ready"};const E=Rr(f);if(E.length===0)return b.push({severity:"info",code:"active-style-no-selection",message:"No paragraph block is resolvable from the current selection; active paragraph style is unavailable."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:"ready"};if(!tc(E))return b.push({severity:"info",code:"active-style-selection-too-large",message:"Active paragraph style is unavailable for a large multi-paragraph selection."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:"ready"};const U=v?.full.defaults.paragraphStyleId??(v?Gn:null),Y=new Set;let re=0,ye=0,Re=0,Ue="ready";const Ye=ga(f);for(const Be of E){const He=Mn(A,Be,Ye);if(Ue=mu(Ue,He.status),!He.ok){ye+=1;continue}if(!He.styleRef&&!U){Re+=1;continue}const je=He.styleRef??U;if(!je){Re+=1;continue}re+=1,Y.add(je)}if(re===0){const Be=Re>0&&ye===0;return b.push({severity:"warning",code:Be?"active-style-default-unavailable":"active-style-read-failed",message:Be?"Selected paragraphs have no explicit style and the style catalogue is unavailable, so the document default cannot be resolved.":"Could not read the paragraph style of any selected block; active paragraph style is unavailable."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:Ue}}const De=ye+Re;if(De>0)return b.push({severity:"warning",code:"active-style-partial",message:`Active paragraph style resolved from ${re} of ${re+De} selected blocks; ${De} could not be read, so the active style is unavailable.`}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:Ue};if(Y.size>1)return{style:{styleId:null,styleName:null,mixed:!0,diagnostics:b},status:Ue};const Ke=[...Y][0];return{style:{styleId:Ke,styleName:v?.byId.get(Ke)?.name??null,mixed:!1,diagnostics:b},status:Ue}},bt=f=>{if(!S())return Wn;const{cache:v,status:b}=Hn(),{style:A,status:E}=Zn(f,v);let U;return v?U=A.diagnostics.length===0?v.full.diagnostics:[...v.full.diagnostics,...A.diagnostics]:U=[{severity:"warning",code:"catalog-unavailable",message:"The style catalogue is unavailable: the Document API styles surface is not reachable (e.g. viewing mode or a worker-backed editor)."},...A.diagnostics],{ready:!0,status:mu(b,E,f.status),catalogRevision:v?.full.revision??null,quickGallery:v?.quickGallery??[],activeParagraphStyleId:A.styleId,activeParagraphStyleName:A.styleName,mixedSelection:A.mixed,sourceStatus:v?.full.sourceStatus??null,diagnostics:U}},zt=()=>{const f=jn(),v=Cu();v.status==="ready"&&cl(v),N(v);const b=ya(v);for(const[A,E]of r)(!b||E.selectionSignature!==b||E.settled&&v.status==="ready")&&r.delete(A);return{ready:S()!=null,documentMode:f,document:pl(),selection:v,toolbar:{context:f,commands:Tu(v),copyFormatActive:h.mode!=="idle"},comments:Mf(v),trackChanges:hl(v),contentControls:Lo(v),zoom:ni(),fonts:ku(),styles:bt(v)}},Kn=f=>{const v=ya(f);v&&a&&v!==a&&(n.clear(),r.clear()),v&&(a=v)};let oo=null,fr=null,$i=null,gi=null,yo=!1;const wl=()=>{if(Q||yo)return;yo=!0;const f=()=>{yo&&(yo=!1,!Q&&qt())};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Ps=()=>{const f=I();if(f!==$i&&(gi&&(gi(),gi=null),$i=f,!(!f||typeof f.subscribe!="function")))try{const v=f.subscribe(()=>wl());typeof v=="function"&&(gi=v)}catch{$i=null}};let oi=null,vi=null,io=null,Do=null,yi=null,Vo=null;const Cl=()=>{const f=S()?.host,v=xt(f?.getHandles?()=>f.getHandles():void 0,null)?.editing?.selection;return v&&typeof v.subscribe=="function"?v:null},es=()=>{const f=Cl();if(f!==oo&&(fr&&(fr(),fr=null),oo=f,!!f))try{const v=f.subscribe(b=>{Dt+=1,Ti(b),qt()});typeof v=="function"&&(fr=v)}catch{oo=null}},Ri=()=>{const f=S()?.host,v=xt(f?.getHandles?()=>f.getHandles():void 0,null)?.review;return v&&typeof v.subscribe=="function"?v:null},Os=f=>f?typeof f.getActiveReviewTarget=="function"?xt(()=>f.getActiveReviewTarget(),null):typeof f.getSnapshot=="function"?xt(()=>f.getSnapshot(),null)?.activeReviewTarget??null:null:null;let bo=0;const ts=(f,v)=>{const b=(v&&typeof v=="object"?v:null)?.lastInteractionRejection;if(bo>0&&f==null&&b&&typeof b=="object"&&b.code==="review-target-invalidated"&&b.detail==="not-painted")return!1;const A=f&&typeof f=="object"?f:null;let E=null;if(A?.entityType==="trackedChange"&&typeof A.entityId=="string"&&A.entityId.length>0){const U=A.story&&no(A.story)!==no(null)?A.story:void 0;E={id:A.entityId,...U?{story:U}:{},...typeof A.paintedEntityId=="string"&&A.paintedEntityId.length>0?{paintedEntityId:A.paintedEntityId}:{}}}return f==null&&E==null&&ae!=null&&kt(ae)||et(ae,E)?!1:(ze(E),!0)},Ou=()=>{const f=Ri();if(f===oi)return;if(vi&&(vi(),vi=null),oi=f,!f){ts(null);return}let v=!0;try{const b=f.subscribe(A=>{const E=A&&typeof A=="object"?A:null;!ts(E&&Object.prototype.hasOwnProperty.call(E,"activeReviewTarget")?E.activeReviewTarget:Os(f),A)||v||qt()});typeof b=="function"&&(vi=b),ts(Os(f))}catch{oi=null}finally{v=!1}},_l=()=>{if(oo||jn()!=="viewing")return null;const f=S()?.mount?.container,v=(f&&typeof f=="object"&&"ownerDocument"in f?f.ownerDocument??null:null)??globalThis.document??null;return v&&typeof v.addEventListener=="function"?v:null},_a=()=>{const f=_l();if(f===yi||(Vo&&(Vo(),Vo=null),yi=f,!f))return;const v=()=>{Dt+=1,qt()};f.addEventListener("selectionchange",v),f.addEventListener("pointerup",v,!0),f.addEventListener("mouseup",v,!0),Vo=()=>{f.removeEventListener("selectionchange",v),f.removeEventListener("pointerup",v,!0),f.removeEventListener("mouseup",v,!0)}};qi(),ts(Os(Ri()));let dt=zt();a=ya(dt.selection);const Fu=()=>{const f=S()?.host?.events,v=f&&typeof f.subscribe=="function"?f:null;if(v!==io&&(Do&&(Do(),Do=null),io=v,!!v))try{const b=v.subscribe(A=>{const E=A?.type;if(E==="source:complete"||E==="source:signals-complete"){on!==null&&(We(),dr.onRender(!0));return}if((E==="mutation:committed"||E==="collaboration:remote-changed")&&(al=Date.now()),E==="mutation:committed"&&(We(),Bt={}),E==="mutation:committed"||E==="save:completed"||E==="collaboration:remote-changed"){const U=E==="mutation:committed"?S_(A):null,Y=E==="mutation:committed"&&dr.getPendingIds().size>0;U?.removedIds.size&&Mt(new Set(U.removedIds),A.receipt);const re=U?.reconcileMode==="authoritative"&&U.upsertIds.size>0;if(re&&(mi(),We(),on=Ft(),qt()),U?.upsertIds.size||Y){const Ye=A.origin==="history"?null:A.receipt,De=S()?.documentMutationReadiness,Ke=typeof Ye?.txId=="string"&&Ye.txId.length>0&&typeof De?.whenPainted=="function",Be=A.origin==="history"&&typeof De?.getRenderEpoch=="function"?xt(()=>De.getRenderEpoch.call(De),null):null,He=A.origin==="history"&&typeof De?.whenPainted=="function",je={upsertIds:U?.upsertIds??new Set,removedIds:new Set,reconcileMode:U?.reconcileMode==="authoritative"?"authoritative":"targeted"};Ke?dr.enqueueAfterPaint(je,()=>De.whenPainted.call(De,Ye)):He?dr.enqueueAfterPaint(je,()=>De.whenPainted.call(De,typeof Be=="number"?{afterEpoch:Be}:void 0)):(dr.enqueue(je),dr.onRender(Y))}if(re)return;const ye=E==="mutation:committed"&&Ro(A)||E==="collaboration:remote-changed"&&Array.isArray(A.changedStoryIds)&&A.changedStoryIds.length>0;if(ye&&(Wi=Date.now()),E==="mutation:committed"&&ye){ll();return}if(U?.removedIds.size&&U.upsertIds.size===0)return;(E==="collaboration:remote-changed"||E==="mutation:committed"&&!ye)&&$o();const Re=E==="collaboration:remote-changed"&&Array.isArray(A.changedPartUris)&&A.changedPartUris.some(Ye=>typeof Ye=="string"&&oH.has(Ye)),Ue=E==="collaboration:remote-changed"&&Array.isArray(A.changedStoryIds)&&A.changedStoryIds.length>0&&xo();Re&&!ye&&(ro=!0),mi(),(Re||Ue)&&yn("comments"),qt()}});typeof b=="function"&&(Do=b)}catch{io=null}},qt=()=>{if(Q)return;yo=!1,qi(),es(),Ps(),Ou(),_a(),Fu();const f=zt();Kn(f.selection),dt=f;for(const v of[...Ve])v(dt)},pc=[],Qt=[],Ln=f=>{for(const v of f)try{v()}catch{}},Nn=()=>Ln(pc),Mi=()=>Ln(Qt),ns=[];((f,v)=>{if(!(!f||typeof f.on!="function"))for(const b of v){const A=b==="active-editor-change"?()=>{Nn(),Mi(),qt()}:b==="document-replaced"?E=>{const U=E&&typeof E=="object"?E:null,Y=U?.editor,re=U?.host,ye=!!Y&&Y===S(),Re=!!re&&re===T();!ye&&!Re||(Mi(),$.clear(),mi(),qt())}:()=>qt();try{f.on(b,A),ns.push(()=>{try{typeof f.off=="function"&&f.off(b,A)}catch{}})}catch{}}})(t,Jz),es(),Ps(),Ou(),_a(),Fu();const Li=(f,v=Nz)=>({get:()=>f(dt),subscribe:b=>{let A=f(dt);const E=U=>{const Y=f(U);v(A,Y)||(A=Y,b(Y))};return Ve.add(E),()=>Ve.delete(E)}}),Po=f=>Li(f),Di=f=>{const v=b=>{const A=U=>{try{b(U)}catch{}},E=f.subscribe(A);return A(f.get()),E};return{get:()=>f.get(),getSnapshot:()=>f.get(),observe:v,subscribe:b=>v(A=>b({snapshot:A}))}};function tb(f){return f&&typeof f=="object"&&typeof f.id=="string"?String(f.id):null}function O(f){if(f.empty)return null;const v=f.selectionTarget,b=v?.start,A=v?.end;if(v?.kind!=="selection"||b?.kind!=="text"||A?.kind!=="text"||typeof b.blockId!="string"||b.blockId!==A.blockId||!Number.isInteger(b.offset)||!Number.isInteger(A.offset)||b.offset<0||A.offset<0||b.offset===A.offset)return null;const E=Math.min(b.offset,A.offset),U=Math.max(b.offset,A.offset),Y=_s(f);return{kind:"range",coordinateSpace:v.coordinateSpace==="tracked"?"tracked":"visible",range:{kind:"text",...Y?{story:Y}:{},segments:[{blockId:b.blockId,range:{start:E,end:U}}]}}}function q(){const f=dt.selection.activeChangeIds[0];if(!f)return"unavailable";const v=Ts();if(!v)return"unavailable";const b=_s(dt.selection),A=v.find(re=>rl(re,f,b));if(!A)return"unavailable";const E=X0(A),U=E.type,Y=E.grouping;return U==="replacement"&&Y==="replacement-pair"?typeof E.insertedText=="string"&&dt.selection.quotedText===E.insertedText?"id":"range":(U==="insertion"||U==="deletion"||U==="insert"||U==="delete")&&Y==="standalone"?"range":"id"}function Ee(f,v){if(f.scope==="all")return{target:{scope:"all"},changeId:null};if(typeof v=="string"&&v.length>0)return{target:{kind:"id",id:v},changeId:v};if(v&&typeof v=="object"){const A=v;if(A.target&&typeof A.target=="object")return{target:A.target,changeId:tb(A.target)};const E=typeof A.changeId=="string"?A.changeId:A.id;if(typeof E=="string"&&E.length>0)return{target:{kind:"id",id:E},changeId:E}}const b=dt.selection.activeChangeIds[0];return b?{target:{kind:"id",id:b},changeId:b}:null}function Ne(f,v){if(f.scope==="id"&&v==null){if(dt.selection.activeChangeIds.length>1)return Hu(f.kind,{kind:"ids",ids:dt.selection.activeChangeIds},null);if(dt.selection.activeChangeIds.length===1&&!dt.selection.empty&&dt.selection.selectionTarget){const A=q();if(A==="unavailable")return!1;if(A==="range"){const E=O(dt.selection);return E?Hu(f.kind,E,null):!1}if(A==="id"){const E=dt.selection.activeChangeIds[0],U=_s(dt.selection),Y=U&&no(U)!==no(null)?U:void 0;return lb(f.kind,Y?{id:E,story:Y}:E)}}}const b=Ee(f,v);return b?Hu(f.kind,b.target,b.changeId):!1}function mt(f,v){const b=I()?.lists,A=b?.apply;if(typeof A!="function")return!1;const{behavior:E,preset:U,continuity:Y}=typeof v=="string"?tH(v):v&&typeof v=="object"?v:{},re={kind:f,behavior:E??"toggle"};U!==void 0&&(re.preset=U),Y!==void 0&&(re.continuity=Y);try{return Kr(A.call(b,re))}catch{return!1}}let nn=Promise.resolve(!1),pn=null,Jn=Promise.resolve(!1);const Dn=async f=>{if(!nm(f))return f;const v=S()?.documentMutationReadiness,b=v?.whenPainted;if(typeof b!="function")return f;const A=typeof f.txId=="string"?f.txId:void 0;try{await b.call(v,A?{txId:A}:void 0)}catch{}return f},_n=f=>{if(Or(f)){const b=Promise.resolve(f);return{immediate:!0,committed:b.then(A=>il(A),()=>!1),settled:b.then(A=>Dn(il(A)),()=>!1)}}const v=il(f);return{immediate:v,committed:Promise.resolve(v),settled:Dn(v)}},An=()=>{const f=s.shift();if(!f){u=!1,d?.(),d=null;return}try{f.resolve(Q?!1:f.mutate())}catch{f.resolve(!1)}},so=()=>{let f=!1;return()=>{f||(f=!0,An())}},ao=(f,v)=>{if(!u){u=!0,c=new Promise(U=>{d=U});try{return{result:v(),release:so()}}catch(U){throw u=!1,d?.(),d=null,U}}const b=s.find(U=>U.key===f);if(b)return b.mutate=v,{result:b.result,release:()=>{}};let A;const E=new Promise(U=>{A=U});return s.push({key:f,mutate:v,result:E,resolve:A}),{result:E,release:so()}},ka=new Set(["create.tableOfContents"]),Sl=f=>cr(`Tracked authoring is not supported for ${f}.`),Oo=f=>{if(jn()==="suggesting")return ka.has(f)?Sl(f):{changeMode:"tracked"}},kl=()=>jn()==="suggesting"?LH:J0,hr=(f,v,b)=>{const A=Oo(f);return A&&A.success===!1?A:A?v(b,A):v(b)},nb=(f,v,b,A)=>{const E=f.inline;if(!E)return;const U=il(A);if(U===!1||typeof U=="object"&&U&&U.success===!1)return;if(E.kind==="clear"){n.clear();return}if(E.kind==="toggle"||!K0(E.key))return;const Y=ya(v);if(!Y)return;const re=bH(E.key,b.value);if(re==null){n.delete(E.key);return}n.set(E.key,{selectionSignature:Y,value:re})},sm=(f,v,b,A)=>!f.inline||f.inline.kind==="toggle"?A:Or(A)?Promise.resolve(A).then(E=>(nb(f,v,b,E),E)):A,am=(f,v,b,A)=>{if(f.inline?.kind!=="toggle"||!zo(il(A))||typeof b.value!="boolean"&&b.value!==null)return null;const E=ya(v);if(!E)return null;const U=++l;return r.set(f.id,{selectionSignature:E,active:b.value===!0,generation:U,settled:!1}),qt(),U},rb=(f,v,b)=>{if(v==null)return;const A=r.get(f.id);if(!(!A||A.generation!==v)){if(!zo(b)){r.delete(f.id);return}A.settled=!0}},Bu=(f,v)=>f.then(b=>(v?.(b),mi(),qt(),b),()=>(v?.(!1),mi(),qt(),!1)),Kr=(f,v)=>{const b=pn;if(pn=null,b)return nn=Bu(b,v),il(f);if(Or(f))return nn=Bu(_n(f).settled,v),!0;const A=il(f);return nm(A)&&typeof S()?.documentMutationReadiness?.whenPainted=="function"?(nn=Bu(Dn(A),v),A):(v?.(A),nn=Promise.resolve(A),mi(),qt(),A)},$n=(f,v)=>!f||typeof f!="object"?v:f,Aa=(f,v=cr("Document API operation failed."))=>{if(Or(f))return Promise.resolve(f).then(A=>Aa(A,v),()=>v);const b=$n(f,v);return mi(),nm(b)&&typeof S()?.documentMutationReadiness?.whenPainted=="function"?(Bu(Dn(b)),qt(),b):(qt(),b)},lm=(f,v,b,A)=>{const E=[],U=[];for(const Y of b){const re=A(Y);if(re)try{const ye=_n(hr(f,v,re));E.push(ye.immediate),U.push(ye.settled)}catch{E.push(!1),U.push(Promise.resolve(!1))}}return pn=U.length?Promise.all(U).then(Y=>hi(Y)):null,hi(E)},cm=(f,v,b,A)=>{const E=[],U=[];for(const Y of b){const re=A(Y);if(re)try{const ye=_n(hr(f,v,re));E.push(ye.immediate),U.push(ye.settled)}catch{E.push(!1),U.push(Promise.resolve(!1))}}return pn=U.length?Promise.all(U).then(Y=>hi(Y)):null,hi(E)},Bf=(f,v,b,A=dt.selection)=>{const E=Oo(f);return E&&E.success===!1?E:A.selectionTarget?v(b,{...E??{},offsetSpace:"selection"}):E?v(b,E):v(b)},um=(f,v,b,A)=>{const E=ho(v,A);switch(f.kind){case"alignment":{const U=b;return U!=="left"&&U!=="center"&&U!=="right"&&U!=="justify"?null:{target:E,alignment:U}}case"spacing-line":{const U=typeof b=="number"?b:Number(b);return!Number.isFinite(U)||U<=0?null:{target:E,line:U,lineRule:"auto"}}case"style":if(b&&typeof b=="object"){const U=b.role;if(U&&typeof U=="object")return{target:E,role:U}}return typeof b!="string"||b.trim()===""?null:{target:E,styleId:b};case"direction":{const U=f.fixedValue;return U!=="ltr"&&U!=="rtl"?null:{target:E,direction:U}}default:return null}},dm=(f,v)=>{const b=f.inline,A=Z0(f),E=T();if(!b||typeof E?.setPendingInlineFormat!="function")return!1;if(b.kind==="clear")return Z(),!0;if(!A)return!1;let U;if(b.kind==="toggle")U=!yl(f,y(),dt.selection);else{const Y=v&&typeof v=="object"&&"value"in v?v.value:v;if(b.kind==="value-number"){const re=typeof Y=="number"?Y:Number(Y);U=Number.isFinite(re)&&re>0?re:null}else U=typeof Y=="string"&&Y.trim()!==""?Y:null;if(U===null)return z(A,null),!0}return z(A,U),!0},fm=()=>{const f=y(),{lockModesById:v}=ti(f?.contentControls,dt.selection);if(Zi(v))return!1;const b=[],A=[],E=Ke=>{const Be=_n(Ke);b.push(Be.immediate),A.push(Be.settled)},U=(Ke,Be,He)=>{try{E(He?Ke(Be,He):Ke(Be))}catch{b.push(!1),A.push(Promise.resolve(!1))}},Y=Hn().cache?.full.defaults.paragraphStyleId??Gn,re=bu(dt.selection);if(re){const Ke=gr(f,"format.apply");if(Ke)try{E(Bf("format.apply",Ke,{target:re,inline:{...kl()}}))}catch{b.push(!1),A.push(Promise.resolve(!1))}}const ye=gr(f,"format.paragraph.resetDirectFormatting"),Re=gr(f,"styles.paragraph.setStyleRef"),Ue=_s(dt.selection),Ye=!Ue||Ue.storyType==="body",De=gr(f,Ye?"lists.remove":"lists.removeInStory");for(const Ke of Rr(dt.selection)){const Be=ho(Ke,Ue);if(ye&&U(ye,{target:Be}),De)try{const He=va(Ke),je=_n(De(Ye?{target:He}:{target:He,story:Ue}));A.push(je.settled.then($e=>zo($e)?$e:!0))}catch{}Re&&U(Re,{target:Be,styleId:Y})}if(!re&&jn()!=="suggesting"){const Ke=gr(f,"format.paragraph.setMarkRunProps");if(Ke)for(const Be of Rr(dt.selection))U(Ke,{target:ho(Be,Ue),markRunProps:{bold:!1,italic:!1,strikethrough:!1,doubleStrikethrough:!1,smallCaps:!1,caps:!1,verticalAlign:"baseline"}})}return pn=A.length?Promise.all(A).then(Ke=>hi(Ke)):null,hi(b.length?b:[!1])},ob=(f,v,b)=>{const A=Rr(dt.selection);if(A.length===0)return!1;const E=_s(dt.selection);return lm(f.docRoute,v,A,U=>um(f.blockParagraph,U,b,E))},hm=(f,v,b)=>{const A=y(),E=gr(A,"format.paragraph.setIndentation"),U=gr(A,"format.paragraph.clearIndentation"),Y=f.list?.mode,re=ga(dt.selection),ye=_s(dt.selection),Re=async Ue=>{const Ye=await pe(A,Ue,re);if(Ye===!0)return{kind:"list",routeToCall:f.docRoute,opToCall:v,input:{target:oA(Ue)}};if(Ye===null||ye&&ye.storyType!=="body"&&typeof A?.getNode!="function")return null;const De=await Xe(A,Ue,ye),Ke={};if(De?.right!=null&&(Ke.right=De.right),De?.firstLine!=null&&(Ke.firstLine=De.firstLine),De?.hanging!=null&&(Ke.hanging=De.hanging),Y==="indent")return E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:ho(Ue,ye),left:Math.max(0,De?.left??0)+iA,...Ke}}:null;const Be=Math.max(0,(De?.left??0)-iA);return Be>0&&(Ke.left=Be),Object.keys(Ke).length===0?U?{kind:"paragraph",routeToCall:"format.paragraph.clearIndentation",opToCall:U,input:{target:ho(Ue,ye)}}:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:ho(Ue,ye),left:0}}:null:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:ho(Ue,ye),...Ke}}:null};return pn=(async()=>{const Ue=await Promise.all(b.map(Be=>Re(Be).catch(()=>null)));if(Ue.length===b.length&&Ue.every(Be=>Be?.kind==="list")&&jn()!=="suggesting"){const Be=Y==="indent"?"lists.indentRange":"lists.outdentRange",He=gr(A,Be);if(He)try{return await _n(hr(Be,He,{paraIds:b,story:re})).settled}catch{return!1}}const Ye=re.storyType!=="body"&&Ue.some(Be=>Be?.kind==="list"),De=Ye&&Y==="outdent"?gr(A,"lists.outdentInStory"):null;if(Ye&&!De)return!1;const Ke=Ue.map(Be=>{if(!Be)return Promise.resolve(!1);try{return Be.kind==="list"&&De?_n(hr("lists.outdentInStory",De,{target:Be.input.target,story:re})).settled:_n(hr(Be.routeToCall,Be.opToCall,Be.input)).settled}catch{return Promise.resolve(!1)}});return hi(await Promise.all(Ke))})(),!0},mc=(f,v)=>{const b=f.list,A=y(),E=Rr(dt.selection);if(E.length===0)return!1;const U=ga(dt.selection),Y=U.storyType==="body";if(b.mode==="indent"||b.mode==="outdent")return hm(f,v,E);const re=b.seed,ye=Ye=>{if(Ye.some($e=>!$e.resolved))return{immediate:!1,settled:null};const De=Ye.every($e=>$e.seed===re);if(!De&&!Y)return{immediate:!1,settled:null};const Ke=De?Y?"lists.remove":"lists.removeInStory":f.docRoute,Be=De?gr(A,Ke):v;if(!Be)return{immediate:!1,settled:null};const He=[],je=[];return E.forEach(($e,Je)=>{if(!De&&Ye[Je]?.seed===re)return;const Lt=De?{target:va($e),...Y?{}:{story:U}}:{target:va($e),seed:re};try{const Yt=_n(hr(Ke,Be,Lt));He.push(Yt.immediate),je.push(Yt.settled)}catch{He.push(!1),je.push(Promise.resolve(!1))}}),{immediate:hi(He),settled:je.length?Promise.all(je).then($e=>hi($e)):null}},Re=E.map(Ye=>ve(A,Ye,U));if(Re.some(Or))return pn=Promise.all(Re).then(async Ye=>{const De=ye(Ye);return De.settled?await De.settled:De.immediate}),!0;const Ue=ye(Re);return pn=Ue.settled,Ue.immediate};function Fs(f){return f&&typeof f=="object"?f:{}}function Nf(f){if(typeof f=="string")return f;const v=Fs(f);if(Object.prototype.hasOwnProperty.call(v,"href"))return v.href;if(Object.prototype.hasOwnProperty.call(v,"value"))return v.value}function At(f,v){const b=Fs(f).text;return typeof b=="string"&&b.trim()!==""?b:v}function jt(f){const v=Fs(f),b=v.capture&&typeof v.capture=="object"?v.capture:null;return v.target??b?.target??b?.selectionTarget??v.selectionTarget??v.textTarget??null}const wn=f=>{const v=y(),b=v?.hyperlinks;if(!b)return!1;const A=Fs(f),E=Nf(f),U=jt(f),Y=typeof A.text=="string"?A.text:void 0,re=typeof A.currentText=="string"?A.currentText:void 0,ye=yu(A.hyperlinkTarget)?A.hyperlinkTarget:null,Re=yu(A.textTarget)?A.textTarget:null,Ue=vl(v,dt.selection),Ye=typeof ye?.storyId=="string"&&typeof ye?.hyperlinkNodeId=="string";if(Ye&&E===null){const De=b.remove;if(typeof De!="function")return!1;try{return hr("hyperlinks.remove",De,{storyId:ye.storyId,hyperlinkNodeId:ye.hyperlinkNodeId,keepText:!0})}catch{return!1}}if(Ue&&E===null){const De=b.remove;if(typeof De!="function")return!1;try{return hr("hyperlinks.remove",De,{target:Ue.address,mode:"unwrap"})}catch{return!1}}if((Ue||ye)&&typeof E=="string"&&E.trim()!==""){const De=b.patch,Ke=b.updateTarget;if(!(!Ye&&Ue&&typeof De=="function")&&!(Ye&&typeof Ke=="function"))return!1;const Be=typeof Y=="string"&&Y!==(Ye?re:Ue?.text??re),He=v?.text?.replace,je=Be?Ye?Re:IH(Ue?.address):null,$e=Be&&!!je&&typeof He=="function";if(Be&&!$e)return!1;const Je=[],Lt=[];let Yt=null,zn=null,qn=null,Yr=!1;try{if(Ye){if(typeof Ke!="function")return!1;const Nr=hr("hyperlinks.updateTarget",Ke,{storyId:ye.storyId,hyperlinkNodeId:ye.hyperlinkNodeId,newTarget:EH(E)});Yr=Or(Nr);const Lr=_n(Nr);if(!zo(Lr.immediate))return!1;Je.push(Lr.immediate),Lt.push(Lr.settled),Yt=Lr.immediate,zn=Lr.committed,qn=Lr.settled}else if(Ue){if(typeof De!="function")return!1;const Nr=hr("hyperlinks.patch",De,{target:Ue.address,patch:{href:E}});Yr=Or(Nr);const Lr=_n(Nr);if(!zo(Lr.immediate))return!1;Je.push(Lr.immediate),Lt.push(Lr.settled),Yt=Lr.immediate,zn=Lr.committed,qn=Lr.settled}}catch{return!1}if($e){const Nr=(Ar,jo)=>zo(jo)?hi([Ar,jo]):zo(Ar)?Af(Ar,jo):jo,Lr=Ar=>{if(!zo(Ar))return Ar;try{const jo=_n(hr("text.replace",He,{target:je,text:Y}));return zo(jo.immediate)?Promise.all([qn??Promise.resolve(Ar),jo.settled]).then(([hb,HU])=>Nr(hb,HU)):Af(Ar,jo.immediate)}catch{return Af(Ar,!1)}};if(Yr)return pn=(zn??Promise.resolve(Yt??!1)).then(Lr),hi(Je);try{const Ar=_n(hr("text.replace",He,{target:je,text:Y}));if(!zo(Ar.immediate))return Yt?Af(Yt,Ar.immediate):Ar.immediate;Je.push(Ar.immediate),Lt.push(Ar.settled),pn=Promise.all([qn??Promise.resolve(Yt??!1),Ar.settled]).then(([jo,hb])=>Nr(jo,hb))}catch{return Yt?Af(Yt,!1):!1}}return!$e&&Lt.length>0&&(pn=Promise.all(Lt).then(Nr=>hi(Nr))),hi(Je)}if(typeof E=="string"&&E.trim()!==""){const De=E.trim(),Ke=b.wrap,Be=gH(U),He=Be.length>0?Be:W0(dt.selection);if(He.length>0){if(typeof Ke!="function")return!1;try{return cm("hyperlinks.wrap",Ke,He,Lt=>({target:Lt,link:{destination:{href:De}}}))}catch{return!1}}const je=b.insert,$e=At(f,De);if(typeof je!="function"||$e.trim()==="")return!1;const Je=xf(U)??ol(dt.selection);if(!Je)return!1;try{return hr("hyperlinks.insert",je,{target:Je,text:$e,link:{destination:{href:De}}})}catch{return!1}}return!1},yr=(f,v,b)=>{const A=f.create.kind,E=b&&typeof b=="object"?b:{};if(A==="table"){const Y=Number(E.rows??E.rowCount),re=Number(E.columns??E.cols??E.colCount);if(!Number.isInteger(Y)||Y<1||!Number.isInteger(re)||re<1)return!1;const ye=ol(dt.selection),Re=ye&&typeof ye.blockId=="string"?{kind:"inParagraph",target:ho(ye.blockId),offset:ye.range?.start??0}:Y0(dt.selection,"nodeId");try{return hr(f.docRoute,v,{rows:Y,columns:re,at:Re})}catch{return!1}}if(A==="image"){const Y=E.src??E.value;if(typeof Y!="string"||Y.trim()==="")return!1;const re=ol(dt.selection),ye=ga(dt.selection),Re=ye.storyType==="body"?null:ye;let Ue;re&&typeof re.blockId=="string"?Ue={kind:"inParagraph",target:ho(re.blockId,Re),offset:re.range?.start??0}:(Ue=Y0(dt.selection,"target"),Re&&Ue.kind==="after"&&(Ue={...Ue,target:{...Ue.target,story:Re}}));const Ye={src:Y,at:Ue};Re&&(Ye.in=Ue.kind==="inParagraph"?R(Re)??Re:Re),typeof E.alt=="string"&&(Ye.alt=E.alt),typeof E.title=="string"&&(Ye.title=E.title),E.size&&typeof E.size=="object"&&(Ye.size=E.size);try{return hr(f.docRoute,v,Ye)}catch{return!1}}const U={at:Y0(dt.selection,"target")};typeof E.instruction=="string"&&(U.instruction=E.instruction),E.config&&typeof E.config=="object"&&(U.config=E.config);try{return hr(f.docRoute,v,U)}catch{return!1}},Br=(f,v)=>{const b=f.table,A=Fe();if(!A||b.requiresCell&&!A.cellNodeId)return!1;const E=OH(b.action,A);if(!E)return!1;try{if(b.action==="insert-row-before"||b.action==="insert-row-after"){const U=T(),Y=(typeof U?.getHandles=="function"?U.getHandles():null)?.editing?.tables;if(typeof Y?.insertRow!="function")return!1;const re=Oo(f.docRoute);return re&&re.success===!1?re:re?Y.insertRow(E,re):Y.insertRow(E)}return hr(f.docRoute,v,E)}catch{return!1}},lo=f=>!f||f.disposition!=="routed"?!1:!!(f.inline||f.blockParagraph||f.list||f.link||f.create),bi=f=>{const v=Fs(f);return!!(jt(f)||yu(v.hyperlinkTarget)||yu(v.textTarget))},Al=(f,v,b)=>dt.selection.status!=="ready"?!1:rm(f)?.scope==="id"||!v||v.disposition!=="routed"?!0:v.inline?.kind==="clear"?Rr(dt.selection).length>0||bu(dt.selection)!=null:v.inline?bu(dt.selection)!=null||Rr(dt.selection).length>0:v.blockParagraph||v.list?Rr(dt.selection).length>0:v.link?bi(b)||W0(dt.selection).length>0||ol(dt.selection)!=null||yl(v,y(),dt.selection):!0,Nu=(f,v)=>{const b=rm(f),A=fu(f);return b?.scope!=="id"&&!lo(A)?!1:!Al(f,A,v)},uU=(f,v)=>Nu(f,v)?xs().then(()=>{}):null,gc=(f,v,b)=>{if(pn=null,nn=Promise.resolve(!1),Q)return!1;const A=he.get(f);if(A)try{return Kr(A.execute(ei(v,b)))}catch{return!1}const E=Jk(f);if(E&&typeof I()?.lists?.apply=="function")return mt(E,v);const U=rm(f);if(U)return Ne(U,v);if(f==="copy-format")return Kr(dU());const Y=fu(f);if(!Y||Y.disposition!=="routed")return!1;const re=Y.normalizePayload?Y.normalizePayload(v):v;if(Y.instanceRoute){if(!S()||!rn(Y,re))return!1;const Ye=t?.[Y.instanceRoute];if(typeof Ye!="function")return!1;try{const De=Y.fixedArg!==void 0?Y.fixedArg:re;return Kr(Ye.call(t,De))}catch{return!1}}if(Y.inline?.kind==="clear")return Y.mutates&&jn()==="viewing"?!1:Kr(fm());const ye=Y.docRoute;if(!ye||Y.mutates&&jn()==="viewing")return!1;const Re=y(),Ue=gr(Re,ye);if(!Ue)return!1;if(Y.inline){const{lockModesById:Ye}=ti(Re?.contentControls,dt.selection);if(Zi(Ye))return!1;const De=bu(dt.selection);if(!De)return dt.selection.empty===!1?Kr(!1):Kr(dm(Y,re));const Ke=yl(Y,Re,dt.selection),Be=DH(Y.inline,De,re,Ke);if(!Be)return!1;let He=null;try{const je=S(),$e=jn(),Je=()=>S()!==je||y()!==Re||jn()!==$e?!1:Bf(ye,Ue,Be),Lt=ya(dt.selection)??$l(dt.selection),Yt=Y.inline.kind==="toggle"?ao(`${Y.id}:${Lt}`,Je):null;He=Yt?.release??null;const zn=Yt?Yt.result:Je(),qn=am(Y,dt.selection,Be,zn),Yr=Kr(sm(Y,dt.selection,Be,zn),Nr=>{rb(Y,qn,Nr),He?.(),He=null});return Y.inline.kind==="toggle"&&(Jn=nn),Yr}catch{return He?.(),!1}}if(Y.blockParagraph){const Ye=ob(Y,Ue,re),De=Y.blockParagraph.kind==="alignment"&&zo(Ye)?se(dt.selection,re):null;return Kr(Ye,Ke=>{de(De,Ke)})}if(Y.list)return Kr(mc(Y,Ue));if(Y.link)return Kr(wn(re));if(Y.create)return Kr(yr(Y,Ue,re));if(Y.table)return Kr(Br(Y,Ue));try{return Kr(Y.mutates?hr(ye,Ue,re):Ue(re))}catch{return!1}},pm=()=>{m+=1,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:h.lastClickAt,pointerSelecting:!1,keyboardSelecting:!1};for(const f of p)f("idle");qt()},dU=async()=>{const f=["bold","italic","underline","strikethrough"].filter(Ue=>dt.toolbar.commands[Ue]?.active===!0),v=await Jn;await c;const b=zo(v)?f:[],A=500,E=Date.now();if(h.mode!=="idle"){if(h.mode==="armed"&&E-h.lastClickAt<A){h={...h,mode:"persistent",lastClickAt:E};for(const Ue of p)Ue("persistent");return qt(),!0}return pm(),!1}const U=E-h.lastClickAt<A,Y=++m;h={...h,lastClickAt:E};const re=await xs(),ye=`${$l(re)}:${Ft()}`,Re=await fU(null,re,ye&&ye===k?g:void 0,b);if(Y!==m)return!0;h={...h,mode:U?"persistent":"armed",snapshot:Re,sourceSelectionKey:$l(re),lastClickAt:E};for(const Ue of p)Ue(h.mode);return qt(),!0},fU=async(f,v,b,A=[])=>{const E=v?.target??f?.target;if(!E||E.kind!=="text")return null;const U=Array.isArray(E.segments)?E.segments:[];if(U.length===0)return null;const Y=y();if(!Y)return null;const re=E.story;let ye=null;for(const Be of U){const He=(await Ls(ho(Be.blockId,re)))?.node??null;if(!He)continue;const je=ib(He),$e=hU(Array.isArray(je?.inlines)?je.inlines:[],Be.range);ye?ye=gA(ye,$e):ye=$e}const Re=ye?zz(ye):{},Ue={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strike"},Ye=new Set([...v?.activeMarks??(Array.isArray(f?.activeMarks)?f.activeMarks:[]),...A]);for(const[Be,He]of Object.entries(Ue))Ye.has(Be)&&(Re[He]=!0);const De=b??await Eu(v??Es(f,"ready"));if(De.fontFamily&&(Re.fontFamily=De.fontFamily),De.color&&(Re.color=De.color),De.highlight&&(Re.highlight=De.highlight),De.fontSize){const Be=Number.parseFloat(De.fontSize);Number.isNaN(Be)||(Re.fontSize=Be)}let Ke=null;if(U.length===1){const Be=U[0],He=(await Ls(ho(Be.blockId,re)))?.node??null;He&&ib(He)&&(Ke=await pU(He,Be.blockId,Y,re))}return{story:re??null,inline:Re,paragraph:Ke}},ib=f=>f?f.kind==="paragraph"?f.paragraph??null:f.kind==="heading"?f.heading??null:null:null,hU=(f,v)=>{const b=Y=>{const re=Y.run;return typeof re?.text=="string"?re.text:""},A=Y=>Y.run?.props;if(v.start===v.end){let Y=0;for(const re of f){const ye=b(re),Re=Y,Ue=Y+ye.length;if(Y=Ue,v.start>=Re&&v.start<=Ue){const Ye=A(re);return Ye?{...Ye}:{}}}return{}}let E=0;const U=[];for(const Y of f){const re=b(Y),ye=E,Re=E+re.length;if(E=Re,Re<=v.start||ye>=v.end)continue;const Ue=A(Y);Ue&&U.push(Ue)}return U.length===0?{}:U.length===1?{...U[0]}:gA(U[0],...U.slice(1))},gA=(f,...v)=>{const b={...f};for(const A of v)for(const E of Object.keys(b)){if(!(E in A)){delete b[E];continue}const U=b[E],Y=A[E];(typeof U!=typeof Y||JSON.stringify(U)!==JSON.stringify(Y))&&delete b[E]}return b},pU=async(f,v,b,A)=>{const E=ib(f),U=E.props??{},Y=E.styleRef??null,re=U.alignment??null,ye=U.spacing??null,Re=U.indent??null,Ue=Re?{...Re.left!=null?{left:Re.left}:{},...Re.right!=null?{right:Re.right}:{},...Re.firstLine!=null?{firstLine:Re.firstLine}:{},...Re.hanging!=null?{hanging:Re.hanging}:{}}:null,Ye=U.markRunProps??null,De=U.numbering?.numId,Ke=typeof De=="string"?parseInt(De,10):typeof De=="number"?De:NaN,Be=U.numbering?.level,He=isNaN(Ke)?null:{numId:Ke,...Be!=null?{level:Be}:{}};let je=null;if(He&&typeof b.lists?.getState=="function")try{const $e=await b.lists.getState({target:ho(v,A)});$e&&typeof b.lists?.getStyle=="function"&&(je=await b.lists.getStyle($e)??null)}catch{}return{styleId:Y,alignment:re,spacing:ye,indentation:Ue,markRunProps:Ye,numbering:He,listStyle:je}},vA=async()=>{if(h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;const f=y()?.selection,v=async()=>Yi(typeof f?.current=="function"?await Promise.resolve(f.current({includeText:!0})):dl().value),b=()=>new Promise(Y=>setTimeout(Y,16)),A=8;let E=null,U="";for(let Y=0;Y<A;Y+=1){if(Y>0&&await b(),h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;if(E=await v(),!(!E||E.empty)&&(U=$l(E),U!==h.sourceSelectionKey))break}if(E&&!E.empty&&U!==h.sourceSelectionKey){await yA(E);return}if(h.snapshot?.paragraph){const Y=await v();if(!Y||$l(Y)===h.sourceSelectionKey)return;await yA(Y)}},yA=async f=>{const v=h.snapshot;if(!v){h.mode==="armed"&&pm();return}const b=y();if(!b)return;const A=Es(f,"ready"),{lockModesById:E}=ti(b.contentControls,A);if(Zi(E)){qt();return}const U=f.target,Y=f.selectionTarget;if(f.empty!==!0&&Object.keys(v.inline).length>0){const re=gr(b,"format.apply");if(re&&Y)try{if(!zo(il(await Promise.resolve(Bf("format.apply",re,{target:Y,inline:v.inline},f))))){qt();return}}catch{qt();return}}if(v.paragraph){const re=Array.isArray(U?.segments)?U.segments:[],ye=U?.story;for(const Re of re){const Ue=ho(Re.blockId,ye),Ye=await Ls(Ue),De=Ye?.node??null,Ke=Ye?.address??null;if(!De)continue;const Be={kind:"block",nodeType:Ke?.nodeType??De.kind??"paragraph",nodeId:Re.blockId,...ye&&typeof ye=="object"?{story:ye}:{}},{styleId:He,alignment:je,spacing:$e,indentation:Je,markRunProps:Lt,numbering:Yt,listStyle:zn}=v.paragraph;if(He&&await b.styles?.paragraph?.setStyle?.({target:Be,styleId:He}),je&&await b.format?.paragraph?.setAlignment?.({target:Be,alignment:je}),$e){const qn=$e,Yr=qn.lineRule??"auto",Nr=new Set(["auto","exact","atLeast"]).has(Yr)?Yr:"auto",Lr={...qn.before!=null?{before:Math.round(qn.before*20)}:{},...qn.after!=null?{after:Math.round(qn.after*20)}:{},...qn.line!=null?{line:Math.round(Nr==="auto"?qn.line*240:qn.line*20),lineRule:Nr}:{}};await b.format?.paragraph?.setSpacing?.({target:Be,...Lr})}if(Je){const qn={...Je.left!=null?{left:Cs(Je.left)}:{},...Je.right!=null?{right:Cs(Je.right)}:{},...Je.firstLine!=null?{firstLine:Cs(Je.firstLine)}:{},...Je.hanging!=null?{hanging:Cs(Je.hanging)}:{}};await b.format?.paragraph?.setIndentation?.({target:Be,...qn})}Lt&&await b.format?.paragraph?.setMarkRunProps?.({target:Be,markRunProps:Lt}),Yt&&await b.format?.paragraph?.setNumbering?.({target:Be,...Yt}),zn&&((await Ls(Ue))?.address?.nodeType==="listItem"?await b.lists?.applyStyle?.({target:oA(Re.blockId,ye),style:zn}):Yt&&await b.format?.paragraph?.setNumbering?.({target:Be,...Yt}))}}h.mode==="armed"&&pm(),qt()},mm=(f,v,b)=>{const A=uU(f,v),E=A?A.then(()=>(gc(f,v,b),nn)):(gc(f,v,b),nn);return fu(f)?.inline?.kind==="toggle"&&(Jn=E),E},bA=f=>({id:f,getState:()=>dt.toolbar.commands[f]??fc(f,y(),dt.selection,Ms(dt.selection)),observe:v=>Li(b=>b.toolbar.commands[f]??{enabled:!1,active:!1,supported:!1,source:"unsupported",reason:at.commandUnsupported}).subscribe(v),execute:v=>gc(f,v),executeAsync:v=>mm(f,v)}),mU=f=>{he.set(f.id,f),qt();const v=()=>{he.delete(f.id),qt()};return Object.assign(v,{handle:bA(f.id),unregister:v})},gm=Po(f=>f.selection),vm=Di(gm),wA=()=>{const f=T();if(typeof f?.getHandles!="function")return{reason:at.hostCapabilityUnavailable};let v=null;try{v=f.getHandles()}catch(A){const E=A?.reason;return{reason:E==="host-not-ready"||E==="host-disposed"||E==="editing-mount-required"?at.notReady:at.hostCapabilityUnavailable}}const b=v?.editing?.selectionTargets;return typeof b?.apply!="function"?{reason:at.hostCapabilityUnavailable}:{helper:b}},CA={get:vm.get,getSnapshot:vm.getSnapshot,subscribe:vm.subscribe,observe:vm.observe,current:()=>dl().value,capture:()=>{const f=gm.get();return f.empty||!f.target&&!f.selectionTarget?null:{...f,capturedAt:Date.now()}},restore:f=>{const v=E=>(qt(),{...E,success:E.ok});if(!f||typeof f!="object")return v({ok:!1,reason:at.targetUnresolved});if(!S())return v({ok:!1,reason:at.notReady});const b=MH(f);if(!b)return v({ok:!1,reason:at.targetUnresolved});const A=wA();if(!("helper"in A))return v({ok:!1,reason:A.reason});try{return v(Zk(A.helper.apply(b)))}catch{return v({ok:!1,reason:at.hostCapabilityUnavailable})}},apply:f=>{if(!S())return{ok:!1,reason:at.notReady};const v=wA();if(!("helper"in v))return{ok:!1,reason:v.reason};try{const b=v.helper.apply(f);return qt(),Zk(b)}catch{return{ok:!1,reason:at.hostCapabilityUnavailable}}},getAnchorRect:f=>{const v=T();if(typeof v?.getSelectionAnchorRect=="function"){const b=xt(()=>v.getSelectionAnchorRect(f),null);return b&&typeof b=="object"&&(Number(b.width)>0||Number(b.height)>0)?b:null}return null},getRects:f=>{const v=gm.get(),b=v.selectionTarget??v.target;if(v.empty||!b)return[];const A=Em.getRect({target:b,relativeTo:f?.relativeTo});return A.found?A.rects:[]}},gU={get ids(){return Bn()},has:f=>fu(f)!=null||he.has(f),get:f=>bA(f),execute:gc,executeAsync:mm,register:mU,getContextMenuItems:f=>{const v=[];for(const b of he.values()){const A=b.contextMenu;A&&xt(A.when?()=>A.when(f):void 0,!0)&&v.push({id:b.id,label:A.label,group:A.group,order:A.order,invoke:()=>gc(b.id,void 0,f)})}return v.sort((b,A)=>(b.order??0)-(A.order??0)||b.label.localeCompare(A.label))}},sb=Di(Po(f=>f.toolbar)),vU={get:sb.get,getSnapshot:()=>dt.toolbar,subscribe:sb.subscribe,observe:sb.observe,execute:gc,executeAsync:mm},vc=async(f,v)=>{if(!S())return{success:!1,ok:!1,reason:at.notReady};if(!f)return{success:!1,ok:!1,reason:at.targetUnresolved};const b=T(),A=b?.scrollTargetIntoView;if(typeof A!="function")return{success:!1,ok:!1,reason:at.hostCapabilityUnavailable};try{const E={target:f,block:v?.block??"center",behavior:v?.behavior??"smooth"},U=await Promise.resolve(v?.shouldContinue?A.call(b,E,v.shouldContinue):A.call(b,E));return U&&typeof U=="object"&&U.success===!1?{success:!1,ok:!1,reason:V0(U.reason,at.targetUnresolved)}:{success:!0,ok:!0}}catch{return{success:!1,ok:!1,reason:at.hostCapabilityUnavailable}}},ym=async(f,v,b,A)=>{const E=f==="trackChanges"?A?.story:void 0,U=$e=>{if(!E||!$e||typeof $e!="object")return $e;const Je=$e,Lt=Je.address&&typeof Je.address=="object"?Je.address:null;return Je.story||Lt?.story?$e:{...Je,story:E}},Y=f==="trackChanges"?sH:If,re=b.find($e=>rl($e,v,E)),ye=re&&typeof re=="object"?re:null,Re=f==="trackChanges"&&ye?.type==="move"&&(ye.subtype==="move-to"||ye.subtype==="move-from")?ye.subtype:null,Ue=Re&&typeof ye?.trackedChangeCanonicalId=="string"?ye.trackedChangeCanonicalId:v,Ye=$e=>{if(!Re)return Y($e);const Je=If($e);if(Je?.kind!=="move")return null;const Lt=Re==="move-to"?Je.destination:Je.source;return j0(Lt)?Lt:null},De=Y(re),Ke=f!=="trackChanges"||!Re&&j0(If(re));if(De&&Ke)return U(De);const Be=y()?.[f],He=f==="comments"?{commentId:v}:{id:Ue,...E?{story:E}:{}},je=Be?.get;if(typeof je!="function")return U(De);try{return U(Ye(await Promise.resolve(je.call(Be,He)))??De)}catch{return U(De)}};function _A(f,v){if(ba())return cr("Comments are read-only.","DOCUMENT_READONLY");if(wu())return cr("Resolving comments is disabled.","DOCUMENT_READONLY");const b=y()?.comments,A=b?.patch;if(typeof A!="function")return cr("comments.patch is unavailable.");const E=cr("comments.patch failed.");return xt(()=>Aa(A.call(b,{commentId:f,status:v}),E),E)}const bm=()=>ba()?cr("Comments are read-only.","DOCUMENT_READONLY"):null,SA=(f,v)=>{const b=v&&typeof v=="object"?v:null;let A=Array.from(f);b?.includeResolved===!1&&(A=A.filter(ye=>ye.status!=="resolved"));const E=Number(b?.offset),U=Number.isInteger(E)&&E>0?E:0,Y=Number(b?.limit),re=Number.isInteger(Y)&&Y>=0?U+Y:void 0;return A.slice(U,re)},zu=Po(f=>f.comments),wm=Di(zu),yU={get:wm.get,getSnapshot:wm.getSnapshot,subscribe:wm.subscribe,observe:wm.observe,list:f=>{const v=zu.get();if(v.status!=="pending")return SA(v.items,f);const b=y()?.comments,A=xt(b?.list?()=>b.list(f):void 0,null);return Or(A)?[]:SA(Array.isArray(A?.items)?A.items:[],f)},getById:f=>{const v=zu.get().items.find(E=>Un(E)===f)??null;if(v)return v;const b=y()?.comments,A=xt(b?.get?()=>b.get({commentId:f}):void 0,null);return Or(A)?null:A},createFromCapture:(f,v)=>{const b=bm();if(b)return b;const A=y()?.comments,E=A?.create;if(typeof E!="function")return cr("comments.create is unavailable.");const U=cr("comments.create failed.");return xt(()=>Aa(E.call(A,{target:f.target??f.selectionTarget,text:v.text}),U),U)},createFromSelection:f=>{const v=bm();if(v)return v;const b=y()?.comments,A=b?.create;if(typeof A!="function")return cr("comments.create is unavailable.");const E=gm.get(),U=E.target??E.selectionTarget;if(E.empty||!U)return cr("A range selection is required to comment.","NO_SELECTION");const Y=cr("comments.create failed.");return xt(()=>Aa(A.call(b,{target:U,text:f.text}),Y),Y)},reply:(f,v)=>{const b=bm();if(b)return b;const A=y()?.comments,E=A?.reply??A?.create;if(typeof E!="function")return cr("comments.reply is unavailable.");const U=cr("comments.reply failed.");return xt(()=>Aa(E===A?.reply?E.call(A,{parentCommentId:f,text:v.text}):E.call(A,{parentCommentId:f,text:v.text}),U),U)},resolve:f=>_A(f,"resolved"),reopen:f=>_A(f,"active"),delete:f=>{const v=bm();if(v)return v;const b=y()?.comments,A=b?.delete??b?.remove;if(typeof A!="function")return cr("comments.delete is unavailable.");const E=cr("comments.delete failed.");return xt(()=>Aa(A.call(b,{commentId:f}),E),E)},setActive:f=>{if(f==null)return ge=null,qt(),!0;if(!S())return!1;const v=zu.get();if(v.listStatus!=="ready")return!1;const b=fH(v.items,f);return!b||!v.items.some(A=>Un(A)===b)?!1:(ge=b,qt(),!0)},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:S()?at.documentApiUnavailable:at.notReady};const v=await ym("comments",f,zu.get().items);return v?vc(v):{success:!1,ok:!1,reason:at.targetUnresolved}}},Ia=Po(f=>f.trackChanges),ab=(f,v)=>{const b=Ia.get().items.filter(Re=>Un(Re)!==null);if(b.length===0)return null;const A=dt.trackChanges.activeId,E=ae?.id===A?ae.story:void 0;let U=A?b.findIndex(Re=>rl(Re,A,E)):-1;U===-1&&A&&E&&(U=b.findIndex(Re=>rl(Re,A)));const Y=b[U===-1?f>0?0:b.length-1:(U+f+b.length)%b.length],re=Un(Y),ye=eA(Y);return ze(ye?{id:re,story:ye}:{id:re},v),qt(),re};let kA=Promise.resolve();const bU=f=>{const v=oe;return kA.catch(()=>{}).then(()=>wU(f,v))},wU=async(f,v)=>{if(oe!==v)return{success:!1};const b=ae,A=ab(f,{invalidateQueuedNavigation:!1});if(A==null)return{success:!1};const E=ae,U=Ce,Y=()=>oe===v&&ae===E&&Ce===U,re=()=>{Y()&&(ze(b,{invalidateQueuedNavigation:!1}),qt())};E&&qe.add(E);try{const ye=await ym("trackChanges",A,Ia.get().items,E?.story?{story:E.story}:void 0);if(!Y())return{success:!1};if(!ye)return re(),{success:!1};bo+=1;try{const Re=await vc(ye,{behavior:"auto",shouldContinue:Y});return Y()?(!Re.ok&&Re.reason!==at.targetNotVisible?(re(),Ie(b)):Ie(E),{success:Re.ok}):{success:!1}}finally{bo=Math.max(0,bo-1),bo===0&&(Y()?oi&&ts(Os(oi)):Ie(ae))}}finally{E&&qe.delete(E)}},AA=f=>{const v=bU(f);return kA=v.then(()=>{},()=>{}),v},Cm=Di(Ia),CU={get:()=>(pi(),Cm.get()),getSnapshot:()=>(pi(),Cm.getSnapshot()),subscribe:f=>(pi(),Cm.subscribe(f)),observe:f=>(pi(),Cm.observe(f)),list:()=>(pi(),Ia.get().items),accept:f=>lb("accept",f),reject:f=>lb("reject",f),acceptAll:()=>Hu("accept",{scope:"all"},null),rejectAll:()=>Hu("reject",{scope:"all"},null),next:()=>ab(1),previous:()=>ab(-1),navigateNext:()=>AA(1),navigatePrevious:()=>AA(-1),getAt:f=>{if(!f||typeof f!="object"||typeof f.x!="number"||typeof f.y!="number")return null;const v=ub(f);if(v.length===0)return null;const b=Ia.get().items;let A;for(const E of v){if(E.type!=="trackedChange")continue;let U;if(E.story){if(A===void 0&&(A=Ts()),!A)continue;U=A}else U=b;const Y=U.find(re=>rl(re,E.id,E.story));if(Y)return E.story?{id:Y.id,item:Y,story:E.story}:{id:Y.id,item:Y}}return null},setActive:f=>{if(f==null)return ze(null),Ie(null),qt(),!0;if(!S())return!1;const v=typeof f=="string"?{id:f}:{id:f.id,story:f.story};if(typeof v.id!="string"||v.id.length===0)return!1;const b=v.id;if(v.story){const A=Ts();if(!A)return!1;const E=rA(A,v.story).toPublicId(v.id)??v.id;if(!A.some(U=>rl(U,E,v.story)))return!1;v.id=E}else{const A=Ia.get().items,E=Ef(A).toPublicId(v.id)??v.id;if(!A.some(U=>Un(U)===E))return!1;v.id=E}return b!==v.id&&(v.paintedEntityId=b),ze(v),Ie(v),qt(),!0},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:S()?at.documentApiUnavailable:at.notReady};oe+=1,xe+=1;const v=xe,b=Ia.get().items,A=Ef(b).toPublicId(f)??f,E=eA(b.find(re=>Un(re)===A)),U=ae,Y={id:A,...E?{story:E}:{},...A!==f?{paintedEntityId:f}:{}};qe.add(Y);try{const re=await ym("trackChanges",A,b,E?{story:E}:void 0);if(xe!==v)return{success:!1,ok:!1};if(!re)return{success:!1,ok:!1,reason:at.targetUnresolved};ze(Y);const ye=xe,Re=ae,Ue=Ce,Ye=()=>xe===ye&&ae===Re&&Ce===Ue,De=()=>{Ye()&&(ze(U,{invalidateQueuedNavigation:!1}),qt())};qt(),bo+=1;try{const Ke=await vc(re,{behavior:"auto",shouldContinue:Ye});return Ye()?(!Ke.ok&&Ke.reason!==at.targetNotVisible?(De(),Ie(U)):Ie(Y),Ke):{success:!1,ok:!1}}finally{bo=Math.max(0,bo-1),bo===0&&(Ye()?oi&&ts(Os(oi)):Ie(ae))}}finally{qe.delete(Y)}}},lb=(f,v)=>{const{id:b,story:A}=typeof v=="string"?{id:v,story:void 0}:v;return Hu(f,{kind:"id",id:b,...A?{story:A}:{}},b,A)},Hu=(f,v,b,A)=>{try{return Kr(_U(f,v,b,A))}catch{return!1}},_U=(f,v,b,A)=>{if(ba())return!1;const E=y()?.trackChanges,U=v.scope==="all",Y=v.kind==="range",re=v.kind==="ids";if(gl({kind:f,scope:U?"all":"id"},E))return!1;const ye=U?`${f}All`:f,Re=!Y&&!re&&!A&&E&&typeof E[ye]=="function"?E[ye]:null,Ue=E&&typeof E.decide=="function"?E.decide:null;return!Re&&!Ue?!1:Re?Re.call(E,b??{}):Ue.call(E,{decision:f,target:v})},cb=Po(f=>f.contentControls),zf=f=>cb.get().items.find(v=>v?.id===f)??null,_m=Di(cb),SU=(f=>{if(f===void 0)return _m.get();const v=tm(f);return v?zf(v):null}),kU={get:(f=>(f!==void 0&&Ei("api"),SU(f))),getSnapshot:_m.getSnapshot,subscribe:_m.subscribe,observe:_m.observe,list:()=>(Ei("api"),cb.get().items),getById:f=>(Ei("api"),zf(f)),getRect:f=>{const v=tm(f);if(!v)return sl("unresolved");Ei("panel");const b=zf(v);if(!b)return sl("unresolved");const A=G0(b);return A?Em.getRect({target:A}):sl("unavailable")},scrollIntoView:async f=>{const v=tm(f);if(!v)return{success:!1};Ei("panel");const b=zf(v);if(!b)return{success:!1};const A=G0(b);return A?{success:(await vc(A,{block:f.block,behavior:f.behavior})).ok}:{success:!1}},focus:async f=>{const v=tm(f);if(!v)return{success:!1,reason:"invalid-id"};if(!S())return{success:!1,reason:"not-ready"};Ei("panel");const b=zf(v);if(!b)return{success:!1,reason:"not-found"};const A=G0(b);if(!A)return{success:!1,reason:"not-reachable"};if(!(await vc(A,{block:f.block,behavior:f.behavior})).ok)return{success:!1,reason:"not-reachable"};const E=cH(A);if(!E)return{success:!1,reason:"not-reachable"};const U=CA.apply(E);return!U.ok&&U.reason!==at.hostCapabilityUnavailable?{success:!1,reason:"not-reachable"}:{success:!0}}},Sm=Di(Po(f=>f.fonts)),AU={get:Sm.get,getSnapshot:Sm.getSnapshot,subscribe:Sm.subscribe,observe:Sm.observe,getFamilyOptions:()=>dt.fonts.options,getSizeOptions:()=>dt.fonts.sizeOptions},km=Di(Po(f=>f.zoom)),IU={get:km.get,getSnapshot:km.getSnapshot,subscribe:km.subscribe,observe:km.observe,set:f=>{if(typeof t?.setZoom=="function")try{t.setZoom(f),qt()}catch{}},setMode:f=>{if(typeof t?.setZoomMode=="function")try{t.setZoomMode(f),qt()}catch{}}},Am=Di(Po(f=>f.document)),EU={get:Am.get,getSnapshot:Am.getSnapshot,subscribe:Am.subscribe,observe:Am.observe,setMode:f=>{if(typeof t?.setDocumentMode=="function")try{t.setDocumentMode(f),qt()}catch{}},export:f=>{if(typeof t?.export=="function")try{return Promise.resolve(t.export(f))}catch{return}},getText:()=>{const f=y(),v=xt(f?.getText?()=>f.getText({}):void 0,null);return typeof v=="string"?v:v&&typeof v=="object"&&typeof v.text=="string"?v.text:null},replaceFile:f=>{const v=t?.replaceFile??t?.loadDocument??t?.reload;if(typeof v=="function")try{return Promise.resolve(v.call(t,f))}catch{return}}},IA=()=>{if(typeof HTMLElement>"u")return null;const f=S()?.mount?.container;if(f instanceof HTMLElement)return f;const v=t?.element;return v instanceof HTMLElement?v:null},xU=(f,v)=>{if(typeof f!="number"||typeof v!="number"||!Number.isFinite(f)||!Number.isFinite(v))return[];const b=globalThis.document;if(!b||typeof b.elementFromPoint!="function")return[];const A=IA();if(!A)return[];const E=b.elementFromPoint(f,v);if(!E||!A.contains(E))return[];const U=[E],Y=Je=>{Je&&A.contains(Je)&&!U.includes(Je)&&U.push(Je)},re=b.elementsFromPoint;if(typeof re=="function"){let Je=[];try{Je=re.call(b,f,v)??[]}catch{Je=[]}for(const Lt of Je)Y(Lt)}const ye=[],Re=Je=>{Je&&A.contains(Je)&&!ye.includes(Je)&&!U.includes(Je)&&ye.push(Je)},Ue=Je=>{const Lt=Je.getBoundingClientRect;if(typeof Lt!="function")return!1;let Yt;try{Yt=Lt.call(Je)}catch{return!1}return Yt!=null&&f>=Yt.left&&f<=Yt.right&&v>=Yt.top&&v<=Yt.bottom};for(const Je of U){const Lt=Je.querySelectorAll;if(typeof Lt!="function")continue;let Yt;try{Yt=Lt.call(Je,"[data-track-change-marker]")}catch{continue}for(let zn=0;zn<Yt.length;zn+=1)Ue(Yt[zn])&&Re(Yt[zn])}ye.reverse();const Ye=[...ye,...U],De=Xk(Ye[0],A);for(let Je=1;Je<Ye.length;Je+=1)for(const Lt of Xk(Ye[Je],A))De.push(Lt);if(De.length===0)return De;const Ke=Ia.get().items,Be=Ef(Ke);let He;const je=new Set,$e=[];for(const Je of De){if(Je.type!=="trackedChange"){const qn=`${Je.type}:${Je.id}`;if(je.has(qn))continue;je.add(qn),$e.push(Je);continue}const Lt=lH(Je.storyKey)??aH(Je.story);let Yt;if(Lt){if(He===void 0&&(He=Ts()),!He||(Yt=rA(He,Lt).toPublicId(Je.id),!Yt||!He.some(qn=>rl(qn,Yt,Lt))))continue}else if(Yt=Be.toPublicId(Je.id),!Yt)continue;const zn=`trackedChange:${Yt}`;je.has(zn)||(je.add(zn),$e.push(Lt?{type:"trackedChange",id:Yt,story:Lt}:{type:"trackedChange",id:Yt}))}return $e};function ub(f,v){return typeof f=="object"?xU(f?.x,f?.y):null}const Uu=new Set;let db=!1;const EA=f=>{const v=T();if(typeof v?.observeGeometry!="function")return;let b=!1;const A=xt(()=>{const E=v.observeGeometry(()=>f.schedule());return b=!0,E},null);f.detach=typeof A=="function"?A:null,f.boundHost=b?v:null},Im=f=>{if(f.detach){try{f.detach()}catch{}f.detach=null}f.boundHost=null},xA=()=>{if(db=!1,!(Q||T()))for(const f of Uu)Im(f)},TU=()=>{if(!db){if(db=!0,typeof queueMicrotask=="function"){queueMicrotask(xA);return}Promise.resolve().then(xA)}},RU=()=>{const f=T();if(!f){TU();return}for(const v of Uu)v.boundHost&&v.boundHost===f||(Im(v),EA(v),v.schedule())};pc.push(RU);const Em={getRect:f=>{const v=T(),b=v?.getTargetRects;if(typeof b=="function"){const A=xt(()=>b.call(v,{target:f.target}),null);return A&&typeof A=="object"?A.success===!0&&Array.isArray(A.rects)?TH(xH(A.rects.filter(E=>E!=null&&typeof E=="object")),f.relativeTo):sl(typeof A.reason=="string"?A.reason:"unresolved"):sl("unresolved")}return sl("unavailable")},observe:f=>{const v=[];let b=0;const A=typeof requestAnimationFrame=="function",E=()=>{if(!A){f();return}b||(b=requestAnimationFrame(()=>{b=0,f()}))},U=Li(re=>({ready:re.ready,selection:re.selection,zoom:re.zoom}));v.push(U.subscribe(()=>E()));const Y={schedule:E,detach:null,boundHost:null};return EA(Y),Uu.add(Y),()=>{Uu.delete(Y),Im(Y),b&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(b);for(const re of v.splice(0))try{re()}catch{}}},getHost:()=>IA(),entityAt:ub,contextAt:f=>{const v=!!f&&typeof f.x=="number"&&typeof f.y=="number",b=v?f.x:0,A=v?f.y:0;return{point:{x:b,y:A},entities:v?ub({x:b,y:A}):[],selection:dt.selection,position:null,insideSelection:!1}},scrollIntoView:async f=>{const v=f?.target;if(!v)return{success:!1};let b=null;if(v.kind==="entity"){const A=v.entityType==="comment"?"comments":"trackChanges",E=A==="comments"?zu.get().items:Ia.get().items,U=v.entityType==="trackedChange"&&v.story?{story:v.story}:void 0;b=await ym(A,v.entityId,E,U)}else{const A=v,E=v,U=Array.isArray(A.segments)&&A.segments.length>0?A.segments:E.blockId&&E.range?[{blockId:E.blockId,range:E.range}]:null;if(U){const Y=v.story;b={kind:"text",segments:U,...Y?{story:Y}:{}}}}return b?{success:(await vc(b,{block:f.block??"center",behavior:f.behavior??"smooth"})).ok}:{success:!1}}},TA=f=>{const v=(f&&typeof f=="object"?f:null)?.target;return v&&typeof v=="object"?v:null},RA=f=>`metadata:resolve:${f}`,MU=f=>{const v=y()?.metadata;if(!v||typeof v.resolve!="function")return null;const{value:b}=kr(RA(f),Ft(),()=>v.resolve({id:f}),TA);return b},LU=async f=>{const v=y()?.metadata;if(!v||typeof v.resolve!="function")return null;try{const b=Ft(),A=await Promise.resolve(v.resolve({id:f}));if(b!==Ft())return null;const E=TA(A);return $.set(RA(f),{token:b,value:E,hasSettled:!0,inflightToken:null}),E}catch{return null}},DU={getRect:f=>{const v=y()?.metadata;if(!v||typeof v.resolve!="function")return sl("unavailable");const b=MU(f.id);return b?Em.getRect({target:b}):sl("unresolved")},scrollIntoView:async f=>{const v=await LU(f.id);return v?{success:(await vc(v,{block:f.block,behavior:f.behavior})).ok}:{success:!1}}},PU={inTable:!1,tableNodeId:null,rowIndex:null,columnIndex:null,cellNodeId:null,rows:null,columns:null},OU={getContext:()=>{const f=Fe();if(!f)return{...PU};const v=fe()?.table;return{inTable:!0,tableNodeId:f.tableNodeId,rowIndex:f.rowIndex,columnIndex:f.columnIndex,cellNodeId:f.cellNodeId,rows:typeof v?.rows=="number"?v.rows:null,columns:typeof v?.columns=="number"?v.columns:null}},isInTable:()=>Fe()!=null},xm={query:"",total:0,activeIndex:-1,open:!1,available:!1,caseSensitive:!1,includeDeletedText:!1,regex:!1,canReplace:!1,reason:at.searchUnavailable};let xn={...xm};const Tm=new Set,Ea=()=>{const f=T()?.search;return f&&typeof f=="object"?f:null},Bs=()=>{const f=I()?.search;return f&&typeof f=="object"?f:null},Hf=()=>{const f=Ea();if(f&&typeof f.setSession=="function")return!0;const v=Bs();return!!v&&typeof v.query=="function"&&typeof v.getState=="function"},rs=()=>{for(const f of[...Tm])try{f(xn)}catch{}},ii=f=>(xn={...xn,...f},rs(),xn);let qr=0,yc=null;const MA=()=>{const f=yc;yc=null,f&&xt(()=>(f(),null),null)},FU=()=>{qr+=1,MA();const f=Hf();xn={...xm,available:f,reason:f?void 0:at.searchUnavailable},rs()};Qt.push(FU);const BU=f=>{if(!f)return!1;const v=f.queryError;if(v&&typeof v=="object"&&v.code==="invalid-pattern")return!0;const b=f.rejection;return f.status==="rejected"&&!!b&&typeof b=="object"&&b.code==="invalid-pattern"},fb=(f,v=!1)=>{const b=f&&typeof f=="object"?f:null;if(!b)return null;const A=Array.isArray(b.matches)?b.matches:[],E=typeof b.total=="number"&&Number.isFinite(b.total)?b.total:A.length,U=typeof b.activeMatchIndex=="number"?b.activeMatchIndex:typeof b.activeIndex=="number"?b.activeIndex:-1;return{...typeof b.query=="string"?{query:b.query}:{},total:E,activeIndex:U,canReplace:b.canReplace===!0||v,...b.includeDeletedText===!0?{includeDeletedText:!0}:{},...b.regex===!0?{regex:!0}:{},...BU(b)?{invalidPattern:!0}:{}}},wo=()=>{const f=L("find.replace"),v=L("find.replaceAll");return f?.enabled===!0||v?.enabled===!0},Co=(f,v=!1)=>{const b=fb(f,v);if(!b){ii({total:0,activeIndex:-1,canReplace:!1,reason:void 0});return}ii({...b.query!==void 0?{query:b.query}:{},total:b.total,activeIndex:b.activeIndex,canReplace:b.canReplace,...b.includeDeletedText!==void 0?{includeDeletedText:b.includeDeletedText}:{},...b.regex!==void 0?{regex:b.regex}:{},reason:b.invalidPattern?at.searchInvalidPattern:void 0})},xa=()=>{const f=Ea();if(f&&typeof f.getState!="function")return xn={...xn,available:Hf(),reason:Hf()?void 0:at.searchUnavailable},xn;if(!f){const b=Bs();if(b&&typeof b.getState=="function"){const A=fb(xt(()=>b.getState(),null),wo());if(A)return xn={...xn,...A.query!==void 0?{query:A.query}:{},total:A.total,activeIndex:A.activeIndex,canReplace:A.canReplace,available:!0,reason:A.invalidPattern?at.searchInvalidPattern:void 0,open:xn.open||!!A.query},xn}return xn={...xm,query:xn.query,caseSensitive:xn.caseSensitive,includeDeletedText:xn.includeDeletedText},xn}const v=fb(xt(()=>f.getState(),null));return v&&(xn={...xn,...v.query!==void 0?{query:v.query}:{},total:v.total,activeIndex:v.activeIndex,canReplace:v.canReplace,...v.includeDeletedText!==void 0?{includeDeletedText:v.includeDeletedText}:{},...v.regex!==void 0?{regex:v.regex}:{},available:!0,reason:v.invalidPattern?at.searchInvalidPattern:void 0,open:xn.open||!!v.query}),xn},Vu=f=>{const v=f&&typeof f=="object"?f:null;if(v?.status==="committed")return{ok:!0};if(v?.status==="rejected"&&v.reason==="read-only")return{ok:!1,reason:at.documentReadonly};const b=v?.rejection;return v?.status==="rejected"&&b&&typeof b=="object"&&b.code==="read-only-document"?{ok:!1,reason:at.documentReadonly}:{ok:!1,reason:at.operationUnavailable}},Rm=Di({get:()=>xa(),subscribe:f=>(Tm.add(f),()=>Tm.delete(f))}),NU={get:Rm.get,getSnapshot:Rm.getSnapshot,subscribe:Rm.subscribe,observe:Rm.observe,open:()=>Hf()?(ii({available:!0,open:!0,reason:void 0}),{ok:!0}):(ii({available:!1,open:!1,reason:at.searchUnavailable}),{ok:!1,reason:at.searchUnavailable}),close:()=>{if(qr+=1,yc)MA();else{const f=Ea();if(f&&typeof f.clear=="function")xt(()=>f.clear(),null);else{const v=Bs();v&&typeof v.query=="function"&&xt(()=>v.query({query:""}),null)}}xn={...xm,available:Hf(),reason:void 0},xn.available||(xn.reason=at.searchUnavailable),rs()},search:(f,v)=>{const b=Ea(),A=!!v?.caseSensitive,E=v?.includeDeletedText===!0,U=v?.regex===!0,Y=++qr;if(!b||typeof b.setSession!="function"){const re=Bs();if(re&&typeof re.query=="function"&&typeof re.getState=="function"){ii({query:f,caseSensitive:A,includeDeletedText:E,regex:U,available:!0,open:!0,reason:void 0}),yc=()=>{re.query({query:""})};const ye=xt(()=>re.query({query:f,caseSensitive:A,includeDeletedText:E,regex:U}),null);return Or(ye)?Promise.resolve(ye).then(Re=>{Y===qr&&Co(Re,wo())},()=>{Y===qr&&ii({available:!1,reason:at.searchUnavailable})}):Co(ye,wo()),Co(xt(()=>re.getState(),null),wo()),xn}return ii({query:f,total:0,activeIndex:-1,available:!1,caseSensitive:A,includeDeletedText:E,regex:U,reason:at.searchUnavailable})}if(ii({query:f,caseSensitive:A,includeDeletedText:E,regex:U,available:!0,open:!0,reason:void 0}),yc=()=>{typeof b.clear=="function"&&b.clear()},Co(xt(()=>b.setSession(f,{caseSensitive:A,includeDeletedText:E,...U?{regex:!0}:{},highlight:!0}),null)),f.length>0&&xn.total===0&&xn.reason!==at.searchInvalidPattern){const re=Bs();if(re&&typeof re.query=="function"&&typeof re.getState=="function"){const ye=yc;yc=()=>{ye?.(),re.query({query:""})};const Re=xt(()=>re.query({query:f,caseSensitive:A,includeDeletedText:E,regex:U}),null);Or(Re)?Promise.resolve(Re).then(Ue=>{Y===qr&&Co(Ue,wo())},()=>{Y===qr&&ii({available:!1,reason:at.searchUnavailable})}):Co(Re,wo()),Co(xt(()=>re.getState(),null),wo())}}return xn},next:()=>{const f=Ea();if(!f||typeof f.next!="function"){const v=Bs();if(!v||typeof v.next!="function"||typeof v.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(xn.total===0)return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.next(),null);if(Or(b)){const A=qr;Promise.resolve(b).then(E=>{A===qr&&Co(E,wo())}).catch(()=>{A===qr&&ii({available:!1,reason:at.searchUnavailable})})}else Co(b,wo());return Co(xt(()=>v.getState(),null),wo()),{ok:!0}}return xn.total===0?{ok:!1,reason:at.operationUnavailable}:(Co(xt(()=>f.next(),null)),{ok:!0})},previous:()=>{const f=Ea();if(!f||typeof f.previous!="function"){const v=Bs();if(!v||typeof v.previous!="function"||typeof v.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(xn.total===0)return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.previous(),null);if(Or(b)){const A=qr;Promise.resolve(b).then(E=>{A===qr&&Co(E,wo())}).catch(()=>{A===qr&&ii({available:!1,reason:at.searchUnavailable})})}else Co(b,wo());return Co(xt(()=>v.getState(),null),wo()),{ok:!0}}return xn.total===0?{ok:!1,reason:at.operationUnavailable}:(Co(xt(()=>f.previous(),null)),{ok:!0})},clear:()=>{qr+=1;const f=Ea();if(f&&typeof f.clear=="function"&&xt(()=>f.clear(),null),!f||typeof f.clear!="function"){const v=Bs();v&&typeof v.query=="function"&&xt(()=>v.query({query:""}),null)}ii({query:"",total:0,activeIndex:-1,canReplace:!1})},replace:f=>{const v=Ea();if(!v){const A=Bs();if(!A||typeof A.replace!="function"||typeof A.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(!wo())return{ok:!1,reason:at.operationUnavailable};const E=xt(()=>A.replace({replacement:typeof f=="string"?f:""}),null);if(Or(E)){const U=qr;xa(),rs();const Y=()=>U===qr;return Promise.resolve(E).then(re=>(Y()&&(Co(re,wo()),xa(),rs()),Vu(re)),()=>(Y()&&ii({available:!1,reason:at.searchUnavailable}),{ok:!1,reason:at.searchUnavailable}))}return xa(),rs(),Vu(E)}if(typeof v.replaceCurrent!="function")return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.replaceCurrent(typeof f=="string"?f:""),null);return xa(),rs(),Vu(b)},replaceAll:f=>{const v=Ea();if(!v){const A=Bs();if(!A||typeof A.replaceAll!="function"||typeof A.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(!wo())return{ok:!1,reason:at.operationUnavailable};const E=xt(()=>A.replaceAll({replacement:typeof f=="string"?f:""}),null);if(Or(E)){const U=qr;xa(),rs();const Y=()=>U===qr;return Promise.resolve(E).then(re=>(Y()&&(Co(re,wo()),xa(),rs()),Vu(re)),()=>(Y()&&ii({available:!1,reason:at.searchUnavailable}),{ok:!1,reason:at.searchUnavailable}))}return xa(),rs(),Vu(E)}if(typeof v.replaceAll!="function")return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.replaceAll(typeof f=="string"?f:""),null);return xa(),rs(),Vu(b)}},LA=Po(f=>f.styles),Mm=Di(LA),zU={get:Mm.get,getSnapshot:Mm.getSnapshot,subscribe:Mm.subscribe,observe:Mm.observe,getCatalog:f=>vo(f).value,getQuickGallery:()=>LA.get().quickGallery,getActiveParagraphStyle:()=>Zn(dt.selection,Hn().cache).style},DA={select:Li,get state(){return dt},selection:CA,commands:gU,toolbar:vU,comments:yU,trackChanges:CU,contentControls:kU,fonts:AU,zoom:IU,document:EU,viewport:Em,metadata:DU,tables:OU,search:NU,styles:zU,formatPainter:{setPointerSelecting(f){Q||(h={...h,pointerSelecting:f})},notifyPointerUp(){Q||(h={...h,pointerSelecting:!1},vA())},setKeyboardSelecting(f){Q||(h={...h,keyboardSelecting:f})},notifyKeyUp(){Q||(h={...h,keyboardSelecting:!1},vA())},cancel(){Q||pm()},onModeChange(f){return Q?()=>{}:(p.add(f),()=>p.delete(f))}},createScope:()=>{const f=[];return{select:(v,b)=>{const A=Li(v,b);return{get:A.get,subscribe:E=>{const U=A.subscribe(E);return f.push(U),U}}},dispose:()=>{for(const v of f.splice(0))v()}}},destroy:()=>{if(!Q){Q=!0,dr.reset(),We(),W&&(clearTimeout(W),W=null),J&&(clearTimeout(J),J=null,K=0),V?.timer&&(clearTimeout(V.timer),V.timer=null),V=null,be&&(clearTimeout(be),be=null),ht&&(clearTimeout(ht),ht=null),an&&an(),an=null,bn=null,Kt.clear(),F.clear();for(const f of ns.splice(0))f();fr&&fr(),fr=null,oo=null,gi&&gi(),gi=null,$i=null,vi&&vi(),vi=null,oi=null,Do&&Do(),Do=null,io=null,Vo&&Vo(),Vo=null,yi=null;for(const f of Uu)Im(f);Uu.clear(),Ve.clear(),Tm.clear(),m+=1,p.clear(),qr+=1,he.clear()}}};return _=DA,DA}var BH=[{value:"Arial",label:"Arial",previewFamily:"Arial, sans-serif"},{value:"Calibri",label:"Calibri",previewFamily:"Calibri, sans-serif"},{value:"Courier New",label:"Courier New",previewFamily:'"Courier New", monospace'},{value:"Georgia",label:"Georgia",previewFamily:"Georgia, serif"},{value:"Times New Roman",label:"Times New Roman",previewFamily:'"Times New Roman", serif'},{value:"Verdana",label:"Verdana",previewFamily:"Verdana, sans-serif"}];function NH(e){const t=e.trim(),n=t[0];if(n==='"'||n==="'"){const o=t.indexOf(n,1);if(o>0)return t.slice(1,o).trim()}const r=t.indexOf(",");return(r===-1?t:t.slice(0,r)).trim().replace(/^["']|["']$/g,"")}function zH(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n||typeof n!="object")continue;const r=n,o=typeof r.logicalFamily=="string"?NH(r.logicalFamily):"";if(!o)continue;const i=typeof r.previewFamily=="string"&&r.previewFamily.trim()?r.previewFamily.trim():o;t.push({value:o,label:o,previewFamily:i})}return t}function HH(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n||typeof n!="object")continue;const r=n,o=typeof r.value=="string"?r.value.trim():"";if(!o)continue;const i=typeof r.label=="string"&&r.label.trim()?r.label.trim():o,s=typeof r.previewFamily=="string"&&r.previewFamily.trim()?r.previewFamily.trim():o;t.push({value:o,label:i,previewFamily:s})}return t}function UH(e,t=[]){const n=[],r=new Set,o=s=>{const a=String(s.value).trim().toLowerCase();!a||r.has(a)||(r.add(a),n.push(s))};for(const s of e)o(s);const i=t.length?t:BH;for(const s of i)o(s);return n}var VH=[{value:"8",label:"8"},{value:"9",label:"9"},{value:"10",label:"10"},{value:"11",label:"11"},{value:"12",label:"12"},{value:"14",label:"14"},{value:"16",label:"16"},{value:"18",label:"18"},{value:"24",label:"24"},{value:"36",label:"36"}];function jH(e,t){return e.activeMark?t.activeMarks.includes(e.activeMark):!1}It();var GH=Object.freeze(["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#F1948A","#82E0AA","#F8C471","#AED6F1","#D7BDE2","#A3E4D7","#F0B27A","#AEB6BF","#E74C3C","#2ECC71","#3498DB","#E67E22","#1ABC9C","#9B59B6","#34495E","#F39C12"]);async function WH(e,t){const n=new e6.default;return e.forEach((r,o)=>{n.file(t[o],r)}),n.generateAsync({type:"blob",compression:"DEFLATE"})}function $0(e){return!!(e&&(e.synced===!0||e.isSynced===!0))}function dA(e){try{e.synced=!0}catch{}try{e.isSynced=!0}catch{}}function KH(e,t){if(!e)return()=>{};if($0(e))return t(),()=>{};const n=typeof e.on=="function"?e.on.bind(e):null,r=typeof e.off=="function"?e.off.bind(e):null;if(!n)return t(),()=>{};let o=!1;const i=()=>{o||(o=!0,r?.("synced",a),r?.("sync",l))},s=()=>{o||(i(),t())},a=()=>{dA(e),s()},l=u=>{u!==!1&&(u===!0||$0(e))&&(dA(e),s())};return n("synced",a),n("sync",l),$0(e)&&s(),i}function Qo(e){return!!(e&&typeof e=="object"&&e.editorVersion===2)}function qH(e){const t=e&&typeof e=="object"?e.code:null;return t==="comment-export-missing-story-reference"||t==="v2-worker-comment-export-mode-unsupported"}function fA(e){return typeof e=="string"&&e.length>0?e:null}function eb(e){return e?Qo(e)?fA(e.documentId??e.options?.documentId??null):fA(typeof e.getDocumentId=="function"?e.getDocumentId():e.options?.documentId):null}function YH(e){if(!e||Qo(e))return null;const t=e;return t.documentRenderer??t.presentationEditor??null}function Gi(e){if(!e)return null;if(Qo(e))return e.fonts??null;const t=YH(e);return t?{getReport:()=>t.getFontReport?.()??[],getMissingFonts:()=>t.getMissingFonts?.()??[],getDocumentFonts:()=>[...new Set((t.getFontReport?.()??[]).map(n=>n.logicalFamily))],getDocumentFontOptions:()=>t.getDocumentFontOptions?.()??[],getFontFamilyOptions:()=>t.getFontFamilyOptions?.()??[],getLastFontsChangedPayload:()=>t.getLastFontsChangedPayload?.()??null,map:n=>t.mapFonts(n),unmap:n=>t.unmapFonts(n),add:n=>t.addFonts(Array.isArray(n)?n:[n]),preload:n=>t.preloadFonts(n)}:null}var om=class extends Dm.default{static{this.allowedTypes=[Tr,Ul,Fh]}#t=!1;#n=!1;#e=null;#i=null;#s=null;#a=null;#u=null;#d=null;#l=kk({});get uiConfig(){return this.#l}#f=Ak({});get interactionConfig(){return this.#f}#m=Ek({});get surfacesConfig(){return this.#m}#o;#r=new qF;#p=null;#y=!1;constructor(e){if(super(),this.version="0.0.0",this.users=[],this.whiteboard=null,this.colors=[],this.readyEditors=0,this.pendingCollaborationSaves=0,this.config={selector:"#superdoc",documentMode:"editing",allowSelectionInViewMode:!1,role:"editor",document:{},documents:[],editorExtensions:[],colors:[],users:[],user:{...M0},layoutEngineOptions:{},modules:{},licenseKey:void 0,telemetry:{enabled:!0},title:"SuperDoc",conversations:[],isInternal:!1,comments:{visible:!1},toolbarGroups:["left","center","right"],toolbarIcons:{},toolbarTexts:{},uiDisplayFallbackFont:"Arial, Helvetica, sans-serif",isDev:!1,disablePiniaDevtools:!1,onEditorBeforeCreate:()=>null,onEditorCreate:()=>null,onEditorDestroy:()=>null,onSourceComplete:()=>null,onSourceSignalsComplete:()=>null,onContentError:()=>null,onReady:()=>null,onCommentsUpdate:()=>null,onContentControlActiveChange:()=>null,onContentControlClick:()=>null,onAwarenessUpdate:()=>null,onLocked:()=>null,onPdfDocumentReady:()=>null,onSidebarToggle:()=>null,onCollaborationReady:()=>null,onEditorUpdate:()=>null,onCommentsListChange:()=>null,onException:()=>null,onListDefinitionsChange:()=>null,onPaginationUpdate:()=>null,onTransaction:()=>null,disableContextMenu:!1,viewOptions:{layout:"print"},useLayoutEngine:!0},!e.selector)throw new Error("SuperDoc: selector is required");const t=typeof e.selector=="string"?document.querySelector(e.selector):e.selector;if(!(t instanceof HTMLElement))throw new Error("SuperDoc: selector must be a valid CSS selector string or DOM element");this.#o=new FF({getModuleConfig:()=>this.#m}),this.#w(e,t)}async#w(e,t){this.config={...this.config,...e},!this.config.comments||typeof this.config.comments!="object"?this.config.comments={visible:!1}:typeof this.config.comments.visible!="boolean"&&(this.config.comments.visible=!1),jF(this.config),this.config.documents=this.config.documents||[],this.config.layoutEngineOptions=this.config.layoutEngineOptions||{};const n=this.config.viewOptions?.layout==="web",r=this.config.layoutEngineOptions?.flowMode==="semantic";if(n&&this.config.useLayoutEngine&&!r&&(console.warn("[SuperDoc] Web layout uses PM fallback unless layoutEngineOptions.flowMode is set to 'semantic'. Automatically disabling layout engine."),this.config.useLayoutEngine=!1),!n&&r&&(console.warn("[SuperDoc] flowMode 'semantic' is only valid with web layout. Coercing to 'paginated'."),this.config.layoutEngineOptions.flowMode="paginated"),this.editorVersion=2,this.#ve(),this.config.user=GF(this.config.user),this.config.layoutEngineOptions.virtualization||(this.config.layoutEngineOptions.virtualization={enabled:!0,window:5,overscan:1}),this.config.modules=this.config.modules||{},Object.prototype.hasOwnProperty.call(this.config.modules,"comments")||(this.config.modules.comments={}),this.config.modules.comments=w9(this.config.modules.comments),this.#l=kk(this.config),this.#f=Ak(this.config),this.#m=Ek(this.config),this.config.disableContextMenu=!this.#l.contextMenu.enabled,this.#l.comments.enabled?this.config.modules.comments===!1&&(this.config.modules.comments={}):this.config.modules.comments=!1,this.#l.comments.enabled){this.config.modules.comments===!0&&(this.config.modules.comments={});const i=this.config.modules.comments;i&&Object.assign(i,this.#f.comments)}if(this.config.colors=l6(this.config.colors),this.userColorMap=new Map,this.colorIndex=0,this.version="2.0.0-next.52",this.#b("🦋 [superdoc] Using SuperDoc version:",this.version),this.superdocId=e.superdocId||os(),this.colors=this.config.colors??[],this.#x(),await hT(),this.#t)return;if(await this.#T(this.config.modules),this.#t){this.#le();return}this.config.cspNonce&&this.#E(),this.user=this.config.user,this.users=this.config.users||[],this.socket=null,this.isDev=this.config.isDev||!1,this.activeEditor=null,this.comments=[],this.#p||(this.#p=this.#r.subscribe(i=>{this.#be(i.nextRuntimeId,i.legacyEditorProjection)})),this.isLocked=this.config.isLocked||!1,this.lockedBy=this.config.lockedBy||null;const o=document.createElement("div");o.style.display="contents",t.appendChild(o),this.#u=o,this.#L(),this.#S(),this.#we(),this.#_()}#_(){if(this.#M(),this.readyEditors=0,!this.app)throw new Error("SuperDoc: #startRuntime called before #initVueApp populated this.app");this.app.mount(this.#u)}#S(){const e=this.config.modules?.whiteboard,t=e!==!1&&(e?.enabled??!1);this.whiteboard=new cP({Renderer:DF,superdoc:this,enabled:t}),this.emit("whiteboard:init",{whiteboard:this.whiteboard})}get requiredNumberOfEditors(){return this.#h("requiredNumberOfEditors").documents.filter(e=>e.type===Tr).length}get ui(){return this.#d||(this.#d=FH({superdoc:this}),this.#t&&this.#d.destroy()),this.#d}get state(){return{documents:this.#h("state").documents,users:this.users}}getDocumentRuntimeForDocument(e){return typeof e!="string"||e.length===0?null:(this.superdocStore?.documents??[]).find(t=>t?.getEditor?.()?.options?.documentId===e)?.getDocumentRuntime?.()??null}getComment(e){return typeof e!="string"||e.length===0?null:this.commentsStore?.getComment?.(e)??null}get element(){return typeof this.config.selector=="string"?document.querySelector(this.config.selector):this.config.selector}#E(){const e=this.config.cspNonce,t=document.createElement;document.createElement=function(n){const r=t.call(this,n);return n.toLowerCase()==="style"&&r.setAttribute("nonce",e),r}}#x(){const e=this.config.document,t=!!e&&typeof e=="object"&&Object.keys(e)?.length,n=!!e&&typeof e=="string"&&e.length>0,r=!!e&&typeof File=="function"&&e instanceof File,o=!!e&&e instanceof Blob&&!(e instanceof File),i=this.config.documents&&this.config.documents?.length;if(t&&i&&console.warn("🦋 [superdoc] You can only provide one of document or documents"),t){const s=Fd(this.config.document);this.config.documents=[{id:os(),...s}]}else if(n)this.config.documents=[{id:os(),type:Tr,url:this.config.document,name:"document.docx"}];else if(r){const s=Fd(this.config.document);this.config.documents=[{id:os(),...s}]}else if(o){const s=Fd(this.config.document);this.config.documents=[{id:os(),...s}]}Array.isArray(this.config.documents)&&this.config.documents.length>0&&(this.config.documents=this.config.documents.map(s=>{const a=Fd(s);if(!a||typeof a!="object")return a;const l=typeof a=="object"&&"id"in a&&a.id||s&&typeof s=="object"&&"id"in s&&s.id;return{...a,id:l||os()}}))}#M(){const{app:e,pinia:t,superdocStore:n,commentsStore:r,highContrastModeStore:o}=ZD({disablePiniaDevtools:!!this.config.disablePiniaDevtools});this.app=e,this.pinia=t,this.app.config.globalProperties.$config=this.config,this.app.config.globalProperties.$documentMode=this.config.documentMode,this.app.config.globalProperties.$superdoc=this,this.app.provide("surfaceManager",this.#o),this.superdocStore=n,this.commentsStore=r,this.highContrastModeStore=o,typeof this.superdocStore.setExceptionHandler=="function"&&this.superdocStore.setExceptionHandler(s=>this.emit("exception",s)),this.superdocStore.init(this.config);const i=this.config.modules.comments;this.commentsStore.init(i||{}),this.isCollaborative&&J8(this),this.#ae()}#c(e,t){t&&this.on(e,t)}#L(){this.#c("editorBeforeCreate",this.config.onEditorBeforeCreate),this.#c("editorCreate",this.config.onEditorCreate),this.#c("editorDestroy",this.config.onEditorDestroy),this.#c("source:complete",this.config.onSourceComplete),this.#c("source:signals-complete",this.config.onSourceSignalsComplete),this.#c("ready",this.config.onReady),this.#c("comments-update",this.config.onCommentsUpdate),this.#c("content-control:active-change",this.config.onContentControlActiveChange),this.#c("content-control:click",this.config.onContentControlClick),this.#c("awareness-update",this.config.onAwarenessUpdate),this.#c("locked",this.config.onLocked),this.#c("pdf:document-ready",this.config.onPdfDocumentReady),this.#c("sidebar-toggle",this.config.onSidebarToggle),this.#c("collaboration-ready",this.config.onCollaborationReady),this.on("collaboration-ready",e=>this.#j(e?.editor??null)),this.#c("editor-update",this.config.onEditorUpdate),this.on("content-error",this.onContentError),this.#c("exception",this.config.onException),this.#c("list-definitions-change",this.config.onListDefinitionsChange),this.#c("pagination-update",this.config.onPaginationUpdate),this.#c("fonts-resolved",this.config.onFontsResolved),this.#c("fonts-changed",this.config.onFontsChanged),this.#c("zoomChange",this.config.onZoomChange),this.#c("viewport-change",this.config.onViewportChange)}async#T({collaboration:e}={}){return e?(this.isCollaborative=!1,this.config.documents.length===0&&(this.config.documents=[{id:os(),type:Tr,name:"document.docx"}]),this.config.v2CollaborationPreflightFailure={code:"collaboration-v1-config-unsupported",message:"SuperDoc v2 cannot use modules.collaboration because it is the SuperDoc v1 collaboration API. SuperDoc did not attach the provider or change the document. Configure Document.v2Collaboration with a v2 room instead."},this.config.documents):this.config.documents}#D(e,t){this.isCollaborative=!0,this._commentsCollabInitialized=!1,this.ydoc=Hr(e),this.provider=Hr(t),this.#W();const n=this.config;this._cleanupAwareness=q8(t,this,n.user),n.documents.forEach(r=>{r.ydoc=e,r.provider=t,r.role=this.config.role})}#k(){this.#a=null,this.#g(),typeof this._cleanupAwareness=="function"&&(this._cleanupAwareness(),this._cleanupAwareness=null),this.isCollaborative=!1,this._commentsCollabInitialized=!1,this.ydoc=void 0,this.provider=void 0;const e=this.config;delete e.modules.collaboration,e.documents.forEach(t=>{delete t.ydoc,delete t.provider})}#g(){if(this.#i){try{this.#i()}catch{}this.#i=null}if(this.#s){try{this.#s()}catch{}this.#s=null}}#j(e){this.#g(),Qo(e)&&(this.#G(e),this.#P(e))}#G(e){const t=e.presence;if(!t||typeof t.subscribe!="function")return;const n=iP(()=>this.user),r=o=>{if(this.#t)return;const i=n.next(o);this.emit("awareness-update",{...i,superdoc:this})};try{const o=t.getSnapshot?.();o&&r(o),this.#i=t.subscribe(r)}catch(o){console.warn("[SuperDoc] v2 awareness bridge failed to subscribe",o)}}#P(e){const t=e.lock;if(!t||typeof t.subscribe!="function")return;const n=r=>{this.#t||this.#C(!!r.isLocked,this.#O(r.lockedBy??null))};try{if(this.#a&&typeof t.setLocked=="function"){const o=this.#a;t.setLocked(o.isLocked,o.isLocked?o.lockedBy:null),this.#a=null}const r=t.getSnapshot?.();r&&n(r),this.#s=t.subscribe(n)}catch(r){console.warn("[SuperDoc] v2 lock bridge failed to subscribe",r)}}#O(e){return!e||typeof e!="object"||Array.isArray(e)?null:{...e}}#F(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}#C(e,t){this.isLocked===e&&this.#F(this.lockedBy,t)||(this.isLocked=e,this.lockedBy=t,this.#b("🦋 [superdoc] Locking superdoc:",e,t,`
|
|
102
|
+
`;It();var ws=e=>{e.expand.value=!1};function z0(e,t){const n={...e??{}};return t?n.href=t:delete n.href,n}function jk(e){const t=Array.isArray(e?.segments)?e.segments:[];if(e?.kind!=="text"||!t.length)return null;const n=t[0],r=t[t.length-1];if(!n?.blockId||!r?.blockId||!n.range||!r.range)return null;const o=e.story;return{kind:"selection",start:{kind:"text",blockId:n.blockId,offset:n.range.start??0,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end??0,...o?{story:o}:{}},...o?{story:o}:{}}}function Ez(e){return typeof e?.quotedText=="string"?e.quotedText:typeof e?.text=="string"?e.text:""}function Gk(e){return e.ui?.selection?.get?.()??e.ui?.selection?.current?.()??null}function xz(e){return!!(e.config?.superdoc?.config?.modules?.ai||e.superdoc?.config?.modules?.ai)}function Tz(e){return e.config?.superdoc?.config?.modules?.ai??e.superdoc?.config?.modules?.ai??{}}const Rz=({superToolbar:e,toolbarIcons:t,toolbarTexts:n,toolbarFonts:r,hideButtons:o,availableWidth:i,role:s,isDev:a=!1}={})=>{const l=Cn({type:"button",name:"bold",command:"toggleBold",icon:t.bold,tooltip:n.bold,attributes:{ariaLabel:"Bold"}}),u=(r??_N).map(TN),c=Cn({type:"dropdown",name:"fontFamily",tooltip:n.fontFamily,command:"setFontFamily",defaultLabel:"Arial",label:"Arial",markName:"textStyle",labelAttr:"fontFamily",hasCaret:!0,hasInlineTextInput:!0,inlineTextInputVisible:!0,isWide:!0,style:{width:"116px"},suppressActiveHighlight:!0,attributes:{ariaLabel:"Font family"},options:u,onActivate:({fontFamily:We}={},St=!1)=>{if(St){c.label.value="",c.selectedValue.value="";return}if(!We)return;We=We.split(",")[0],c.label.value=We;const Nt=u.find(Dt=>Dt.label===c.defaultLabel.value),cn=u.find(Dt=>Dt.label===We);cn?c.selectedValue.value=cn.key:Nt?c.selectedValue.value=Nt.key:c.selectedValue.value=""},onDeactivate:()=>{c.label.value=c.defaultLabel.value;const We=u.find(St=>St.label===c.defaultLabel.value);We?c.selectedValue.value=We.key:c.selectedValue.value=""}}),d=Cn({type:"dropdown",name:"ai",dropdownStyles:{padding:0,outline:"none"},tooltip:n.ai,icon:t.ai,hideLabel:!0,hasCaret:!1,isWide:!0,suppressActiveHighlight:!0,attributes:{ariaLabel:"AI"},options:[{type:"render",key:"ai",render:()=>h(d)}]});function h(We){const St=Gk(e),Nt=St?.selectionTarget??jk(St?.target),cn=St?.empty?"":Ez(St),Dt=Tz(e),un=()=>ws(We),Ft=()=>{const Me=e.pendingSelectionCapture;Me&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Me)};return Dr("div",{},[Dr(nz,{handleClose:un,selectedText:cn,target:Nt,doc:e.superdoc?.activeEditor?.doc??null,apiKey:Dt?.apiKey||e.config?.aiApiKey||"",endpoint:Dt?.endpoint||e.config?.aiEndpoint||"",restoreSelection:Ft})])}const m=kN,p=Cn({type:"dropdown",name:"fontSize",defaultLabel:"12",label:"12",style:{width:"56px"},markName:"textStyle",labelAttr:"fontSize",tooltip:n.fontSize,hasCaret:!0,hasInlineTextInput:!0,inlineTextInputVisible:!0,suppressActiveHighlight:!0,isWide:!0,command:"setFontSize",attributes:{ariaLabel:"Font size"},options:m,onActivate:({fontSize:We},St=!1)=>{if(St){p.label.value="",p.selectedValue.value="";return}const Nt=m.find(Ft=>Ft.label===String(p.defaultLabel.value));if(!We){p.label.value=p.defaultLabel.value,Nt?p.selectedValue.value=Nt.key:p.selectedValue.value="";return}let cn=fB(We,12);cn<8&&(cn=8),cn>96&&(cn=96);let Dt=String(cn);const un=m.find(Ft=>Ft.label===Dt||Ft.key===Dt);un?p.selectedValue.value=un.key:p.selectedValue.value="",p.label.value=Dt},onDeactivate:()=>{p.label.value=p.defaultLabel.value;const We=m.find(St=>St.label===String(p.defaultLabel.value));We?p.selectedValue.value=We.key:p.selectedValue.value=""}}),g=Cn({type:"separator",name:"separator",isNarrow:!0}),k=Cn({type:"button",name:"italic",command:"toggleItalic",icon:t.italic,active:!1,tooltip:n.italic,attributes:{ariaLabel:"Italic"}}),w=Cn({type:"button",name:"underline",command:"toggleUnderline",icon:t.underline,active:!1,tooltip:n.underline,attributes:{ariaLabel:"Underline"}}),S=Cn({type:"button",name:"strike",command:"toggleStrike",icon:t.strikethrough,active:!1,tooltip:n.strikethrough,attributes:{ariaLabel:"Strikethrough"}}),y=Cn({type:"dropdown",name:"highlight",icon:t.highlight,hideLabel:!0,markName:"highlight",labelAttr:"color",active:!1,tooltip:n.highlight,command:"setHighlight",noArgumentCommand:"unsetHighlight",suppressActiveHighlight:!0,attributes:{ariaLabel:"Highlight"},options:[{key:"color",type:"render",render:()=>N0(e,y,[],!0)}],onActivate:({color:We})=>{y.iconColor.value=We||""},onDeactivate:()=>y.iconColor.value=""}),C=Cn({type:"dropdown",name:"color",icon:t.color,hideLabel:!0,markName:"textStyle",labelAttr:"color",active:!1,tooltip:n.color,command:"setColor",suppressActiveHighlight:!0,attributes:{ariaLabel:"Color"},options:[{key:"color",type:"render",render:()=>N0(e,C)}],onActivate:({color:We})=>{C.iconColor.value=We},onDeactivate:()=>C.iconColor.value="#000"}),T=Cn({type:"button",name:"search",allowWithoutEditor:!0,active:!1,icon:t.search,tooltip:n.search,group:"right",attributes:{ariaLabel:"Search"}}),R=Cn({type:"dropdown",name:"link",markName:"link",icon:t.link,active:!1,tooltip:n.link,attributes:{ariaLabel:"Link dropdown"},options:[{type:"render",key:"linkDropdown",render:()=>M(R)}],onActivate:({href:We})=>{R.attributes.value=z0(R.attributes.value,We)},onDeactivate:()=>{R.attributes.value=z0(R.attributes.value,null),R.expand.value=!1}});function M(We){const St=Gk(e),Nt=St?.selectionTarget??jk(St?.target),cn=()=>{const Dt=e.pendingSelectionCapture;Dt&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Dt)};return Dr("div",{},[Dr(pS,{ui:e.ui,linkItem:We,textTarget:Nt,restoreSelection:cn,closePopover:()=>ws(We),goToAnchor:()=>{ws(We);const Dt=We.attributes.value?.href;if(!Dt)return;const un=Dt.slice(1),Ft=(e.ui?.viewport?.getHost?.()??null)?.querySelector?.(`a[name='${un}']`);Ft&&tf(Ft)}})])}const H=Cn({type:"options",name:"linkInput",command:"toggleLink",active:!1});R.childItem=H,H.parentItem=R;const B=Cn({type:"button",name:"image",command:"startImageUpload",icon:t.image,active:!1,tooltip:n.image,disabled:!1,attributes:{ariaLabel:"Image"}}),z=Cn({type:"button",name:"tableOfContents",command:"insertTableOfContents",icon:t.tableOfContents,active:!1,tooltip:n.tableOfContents,disabled:!1,attributes:{ariaLabel:"Table of contents"}}),Z=Cn({type:"dropdown",name:"table",icon:t.table,hideLabel:!0,labelAttr:"table",active:!1,tooltip:n.table,command:"insertTable",suppressActiveHighlight:!0,attributes:{ariaLabel:"Table"},options:[{key:"table",type:"render",render:()=>P(Z)}]});function P(We){return Dr("div",{},[Dr(yz,{onSelect:Nt=>{e.emitCommand({item:We,argument:Nt}),ws(We),B0(e)}})])}const N=Cn({type:"dropdown",name:"tableActions",command:"executeTableCommand",tooltip:n.tableActions,icon:t.tableActions,hideLabel:!0,disabled:!0,attributes:{ariaLabel:"Table actions"},options:[{type:"render",render:()=>L(N)}]}),I=[{label:n.addRowBefore,command:"addRowBefore",icon:t.addRowBefore,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add row before"}},{label:n.addRowAfter,command:"addRowAfter",icon:t.addRowAfter,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add row after"}},{label:n.addColumnBefore,command:"addColumnBefore",icon:t.addColumnBefore,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add column before"}},{label:n.addColumnAfter,command:"addColumnAfter",icon:t.addColumnAfter,bottomBorder:!0,props:{"data-item":"btn-tableActions-option",ariaLabel:"Add column after"}},{label:n.deleteRow,command:"deleteRow",icon:t.deleteRow,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete row"}},{label:n.deleteColumn,command:"deleteColumn",icon:t.deleteColumn,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete column"}},{label:n.deleteTable,command:"deleteTable",icon:t.deleteTable,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete table"}},{label:n.removeBorders,command:"deleteCellAndTableBorders",icon:t.deleteBorders,bottomBorder:!0,props:{"data-item":"btn-tableActions-option",ariaLabel:"Delete cell and table borders"}},{label:n.mergeCells,command:"mergeCells",icon:t.mergeCells,props:{"data-item":"btn-tableActions-option",ariaLabel:"Merge cells"}},{label:n.splitCell,command:"splitCell",icon:t.splitCell,props:{"data-item":"btn-tableActions-option",ariaLabel:"Split cells"}},{label:n.fixTables,command:"fixTables",icon:t.fixTables,props:{"data-item":"btn-tableActions-option",ariaLabel:"Fix tables"}}];function L(We){return Dr(Az,{options:I,onSelect:St=>{ws(We);const{command:Nt}=St;e.emitCommand({item:We,argument:{command:Nt}})}})}const X=Cn({type:"dropdown",name:"textAlign",tooltip:n.textAlign,icon:t.alignLeft,command:"setTextAlign",hasCaret:!0,markName:"textAlign",labelAttr:"textAlign",suppressActiveHighlight:!0,attributes:{ariaLabel:"Text align"},options:[{type:"render",render:()=>Dr("div",{},[Dr(LN,{onSelect:St=>{ws(X);const Nt={...X,command:"setTextAlign"};Nt.command="setTextAlign",e.emitCommand({item:Nt,argument:St}),te(X,St)}})]),key:"alignment"}],onActivate:({textAlign:We})=>{te(X,We)},onDeactivate:()=>{te(X,"left")}}),te=(We,St)=>{let Nt=St==="both"?"justify":St,cn={left:t.alignLeft,right:t.alignRight,center:t.alignCenter,justify:t.alignJustify},Dt=cn[Nt]??cn.left;We.icon.value=Dt},le=Cn({type:"dropdown",name:"list",command:"toggleBulletListStyle",splitButton:!0,splitButtonCommand:"toggleBulletList",icon:t.bulletList,hasCaret:!0,tooltip:n.bulletList,restoreEditorFocus:!0,attributes:{ariaLabel:"Bullet list"},options:[{type:"render",key:"bullet-style-buttons",render:()=>{const We=St=>{ws(le);const Nt={...le,command:"toggleBulletListStyle"};e.emitCommand({item:Nt,argument:St})};return Dr(Uk,{buttons:ON,iconSize:25,selectedStyle:le.selectedValue.value,onSelect:We})}}]}),fe=Cn({type:"dropdown",name:"numberedlist",command:"toggleOrderedListStyle",splitButton:!0,splitButtonCommand:"toggleOrderedList",icon:t.numberedList,hasCaret:!0,tooltip:n.numberedList,restoreEditorFocus:!0,attributes:{ariaLabel:"Numbered list"},options:[{type:"render",key:"numbered-style-buttons",render:()=>{const We=St=>{ws(fe);const Nt={...fe,command:"toggleOrderedListStyle"};e.emitCommand({item:Nt,argument:St})};return Dr(Uk,{buttons:FN,iconSize:30,selectedStyle:fe.selectedValue.value,onSelect:We})}}]}),Fe=Cn({type:"button",name:"indentleft",command:"decreaseTextIndent",icon:t.indentLeft,active:!1,tooltip:n.indentLeft,disabled:!1,attributes:{ariaLabel:"Left indent"}}),he=Cn({type:"button",name:"indentright",command:"increaseTextIndent",icon:t.indentRight,active:!1,tooltip:n.indentRight,disabled:!1,attributes:{ariaLabel:"Right indent"}}),ge=Cn({type:"overflow",name:"overflow",command:null,icon:t.overflow,active:!1,disabled:!1,attributes:{ariaLabel:"Overflow items"}}),ae=Cn({type:"dropdown",name:"zoom",allowWithoutEditor:!0,tooltip:n.zoom,defaultLabel:"100%",label:"100%",hasCaret:!0,command:"setZoom",isWide:!0,style:{width:"71px",minWidth:"71px"},inlineTextInputVisible:!1,hasInlineTextInput:!0,attributes:{ariaLabel:"Zoom"},options:[{label:"50%",key:.5,props:{"data-item":"btn-zoom-option"}},{label:"75%",key:.75,props:{"data-item":"btn-zoom-option"}},{label:"90%",key:.9,props:{"data-item":"btn-zoom-option"}},{label:"100%",key:1,props:{"data-item":"btn-zoom-option"}},{label:"125%",key:1.25,props:{"data-item":"btn-zoom-option"}},{label:"150%",key:1.5,props:{"data-item":"btn-zoom-option"}},{label:"200%",key:2,props:{"data-item":"btn-zoom-option"}}],onActivate:({zoom:We})=>{We&&(ae.label.value=We)}}),Ce=Cn({type:"dropdown",name:"measurementUnit",allowWithoutEditor:!0,tooltip:n.measurementUnit,defaultLabel:"in",label:"in",hasCaret:!0,command:"setMeasurementUnit",group:"right",style:{width:"52px",minWidth:"52px"},inlineTextInputVisible:!1,hasInlineTextInput:!1,attributes:{ariaLabel:"Measurement unit"},options:[{label:"Inches",key:"in",props:{"data-item":"btn-measurement-unit-option"}},{label:"Centimeters",key:"cm",props:{"data-item":"btn-measurement-unit-option"}}],onActivate:({measurementUnit:We})=>{We&&(Ce.label.value=We)}}),oe=Cn({type:"button",name:"undo",disabled:!0,tooltip:n.undo,command:"undo",icon:t.undo,group:"left",attributes:{ariaLabel:"Undo"}}),xe=Cn({type:"button",disabled:!0,name:"redo",tooltip:n.redo,command:"redo",icon:t.redo,group:"left",attributes:{ariaLabel:"Redo"}}),qe=Cn({type:"button",disabled:!1,name:"acceptTrackedChangeBySelection",tooltip:n.trackChangesAccept,command:"acceptTrackedChangeFromToolbar",icon:t.trackChangesAccept,group:"left",attributes:{ariaLabel:"Accept tracked changes"}}),et=Cn({type:"button",disabled:!1,name:"rejectTrackedChangeOnSelection",tooltip:n.trackChangesReject,command:"rejectTrackedChangeFromToolbar",icon:t.trackChangesReject,group:"left",attributes:{ariaLabel:"Reject tracked changes"}}),kt=Cn({type:"button",name:"clearFormatting",command:"clearFormat",tooltip:n.clearFormatting,icon:t.clearFormatting,attributes:{ariaLabel:"Clear formatting"}}),Ie=Cn({type:"button",name:"copyFormat",tooltip:n.copyFormat,icon:t.copyFormat,command:"copyFormat",active:!1,attributes:{ariaLabel:"Copy formatting"}}),ze=(We,St)=>We==="editor"?St:We==="suggester"?St.filter(Nt=>Nt.value==="suggesting"):St.filter(Nt=>Nt.value==="viewing"),Ve=We=>We==="editor"?"Editing":We==="suggester"?"Suggesting":"Viewing",Q=Cn({type:"dropdown",name:"documentMode",command:"setDocumentMode",allowWithoutEditor:!0,icon:t.documentMode,defaultLabel:Ve(s),label:Ve(s),hasCaret:s==="editor",isWide:!0,style:{display:"flex",justifyContent:"flex-end"},inlineTextInputVisible:!1,hasInlineTextInput:!1,group:"right",disabled:s!=="editor",attributes:{dropdownPosition:"right",className:"sd-toolbar-item--doc-mode",ariaLabel:"Document mode"},options:[{type:"render",render:()=>$(Q)}]}),_=[{label:n.documentEditingMode,value:"editing",icon:t.documentEditingMode,description:n.documentEditingModeDescription},{label:n.documentSuggestingMode,value:"suggesting",icon:t.documentSuggestingMode,description:n.documentSuggestingModeDescription},{label:n.documentViewingMode,value:"viewing",icon:t.documentViewingMode,description:n.documentViewingModeDescription}];function $(We){return Dr(GN,{options:ze(s,_),onSelect:St=>{const Nt=e.superdoc?.activeEditor??e.activeEditor;ws(We);const{label:cn,icon:Dt,value:un}=St;Q.label.value=cn,Q.icon.value=Dt,e.emitCommand({item:Q,argument:un}),B0(e,Nt)}})}const F=new Map([["separator",20],["zoom",71],["measurementUnit",52],["fontFamily",118],["fontSize",57],["textAlign",40],["linkedStyles",142],["documentMode",47],["default",32]]),j=["search","ruler","undo","overflow","documentMode"],V=Cn({type:"button",name:"ruler",command:"toggleRuler",allowWithoutEditor:!0,icon:t.ruler,active:!1,tooltip:n.ruler,attributes:{ariaLabel:"Ruler"}}),G=Cn({type:"button",name:"formattingMarks",command:"toggleFormattingMarks",allowWithoutEditor:!0,icon:t.formattingMarks,active:!1,tooltip:n.formattingMarks,attributes:{ariaLabel:"Formatting marks"}}),J=Cn({type:"dropdown",name:"linkedStyles",command:"setLinkedStyle",tooltip:n.linkedStyles,icon:t.paintbrush,defaultLabel:n.formatText,label:n.formatText,hasCaret:!0,isWide:!0,style:{width:"140px"},suppressActiveHighlight:!0,disabled:!1,attributes:{className:"sd-toolbar-item--linked-styles",ariaLabel:"Linked styles"},options:[{type:"render",key:"linkedStyle",render:()=>{const We=Nt=>{ws(J);const cn=typeof Nt=="string"?Nt:Nt?.id??null;if(!cn)return;const Dt={...J,command:"setLinkedStyle"};e.emitCommand({item:Dt,argument:cn})},St=e.getActiveLinkedStyleId?.()??null;return Dr("div",{},[Dr(YN,{styles:e.getLinkedStyleOptions?.()??[],onSelect:We,selectedOption:St})])}}],onActivate:({styleId:We,styleName:St})=>{const Nt=St||We;J.label.value=We&&We!=="Normal"?String(Nt):n.formatText,J.disabled.value=!1},onDeactivate:()=>{J.disabled.value=!0,J.label.value=n.formatText}}),K=(We,St)=>{if(St.value==We)return Dr("div",{innerHTML:Iz,class:"dropdown-select-icon"})},W=Cn({type:"dropdown",name:"lineHeight",tooltip:n.lineHeight,icon:t.lineHeight,hasCaret:!1,hasInlineTextInput:!1,hideLabel:!0,inlineTextInputVisible:!1,suppressActiveHighlight:!0,isWide:!1,command:"setLineHeight",dropdownValueKey:"key",selectedValue:"1",attributes:{ariaLabel:"Line height"},options:[1,1.15,1.5,2,2.5,3].map(We=>({label:We.toFixed(2),key:We,icon:()=>K(We,W.selectedValue),props:{"data-item":"btn-lineHeight-option"}}))}),ue=20,be=32,we=j.reduce((We,St)=>We+(F.get(St)||F.get("default")),0),Te=["linkedStyles","clearFormatting","copyFormat","formattingMarks"],rt=["zoom","fontFamily","fontSize","redo"],nt=i<=kf.lg,wt=e.config?.showFormattingMarksButton===!0,Zt=e.config?.showTableOfContentsButton===!0;nt&&(Q.attributes.value={...Q.attributes.value,className:`${Q.attributes.value.className} sd-toolbar-item--doc-mode-compact`}),nt&&(J.attributes.value={...J.attributes.value,className:`${J.attributes.value.className} sd-toolbar-item--linked-styles-compact`});let Ct=[oe,xe,qe,et,T,ae,c,g,p,g,l,k,w,S,C,y,g,R,B,...Zt?[z]:[],Z,N,g,X,le,fe,Fe,he,W,g,J,g,V,Ce,...wt?[G]:[],Ie,kt,...xz(e)?[d]:[],ge,Q];if(i<=kf.md&&o&&(Ct=Ct.filter(We=>We.type!=="separator")),e.config.mode!=="docx"){const We=Ct.findIndex(Nt=>Nt.name.value==="linkedStyles");Ct.splice(We-1,2);const St=["ruler","zoom","undo","redo"];Ct=Ct.filter(Nt=>!St.includes(Nt.name.value))}const Ot=[];a||(s==="viewer"&&Ot.push(qe,et),Ct=Ct.filter(We=>!Ot.includes(We)));const Bt=We=>j.includes(We.name.value),on=[],Fn=[];let Vt=be+we;return Ct.forEach(We=>{const St=F.get(We.name.value)||F.get("default");if(i<kf.xl+ue&&Te.includes(We.name.value)&&o){if(on.push(We),We.name.value==="linkedStyles"){const Nt=Ct.findIndex(cn=>cn.name.value==="linkedStyles");Ct.splice(Nt+1,1)}return}if(i<kf.sm&&rt.includes(We.name.value)&&o){on.push(We);return}if(Bt(We)){Fn.push(We),Vt+=St;return}Vt<i||!o?(Fn.push(We),Vt+=St):on.push(We)}),{defaultItems:Fn,overflowItems:on.filter(We=>We.type!=="separator")}},Wk={bold:"Bold",fontFamily:"Font family",ai:"AI text generation",fontSize:"Font size",italic:"Italic",underline:"Underline",highlight:"Highlight color",strikethrough:"Strikethrough",color:"Text color",search:"Search",link:"Link",image:"Image",tableOfContents:"Table of contents",table:"Insert table",tableActions:"Table options",addRowBefore:"Insert row above",addRowAfter:"Insert row below",addColumnBefore:"Insert column left",addColumnAfter:"Insert column right",deleteRow:"Delete row",deleteColumn:"Delete column",deleteTable:"Delete table",removeBorders:"Remove borders",mergeCells:"Merge cells",splitCell:"Split cell",fixTables:"Fix tables",textAlign:"Alignment",bulletList:"Bullet list",numberedList:"Numbered list",indentLeft:"Left indent",indentRight:"Right indent",directionLtr:"Left-to-right",directionRtl:"Right-to-left",zoom:"Zoom",measurementUnit:"Measurement unit",undo:"Undo",redo:"Redo",trackChanges:"Track Changes",trackChangesAccept:"Accept changes under selection",trackChangesReject:"Reject changes under selection",trackChangesOriginal:"Toggle Show Original",trackChangesFinal:"Toggle Show Final",clearFormatting:"Clear formatting",copyFormat:"Format painter",lineHeight:"Line height",formatText:"Format text",ruler:"Show or hide ruler",formattingMarks:"Show or hide formatting marks",pageBreak:"Insert page break",documentEditingMode:"Editing",documentSuggestingMode:"Suggesting",documentViewingMode:"Viewing",documentEditingModeDescription:"Edit document directly",documentSuggestingModeDescription:"Edits become suggestions",documentViewingModeDescription:"View clean version of document only",linkedStyles:"Linked styles"},Mz=e=>e?typeof e!="string"?e instanceof HTMLElement?e:null:e.startsWith("#")||e.startsWith(".")?document.querySelector(e):document.getElementById(e):null;It();function Kk(e){return oB(e)??F0[e]??null}function Qp(e,t,n,r={}){if(!e?.commands||!t||typeof e.commands.has=="function"&&!e.commands.has(t))return!1;const o=typeof e.commands.executeAsync=="function"?e.commands.executeAsync:e.commands.execute;if(typeof o!="function")return!1;const i=n===void 0?o.call(e.commands,t):o.call(e.commands,t,n);return i&&typeof i.then=="function"&&Promise.resolve(i).then(()=>r.onSettled?.(),s=>{r.onError?.(s),r.onSettled?.()}),!0}var Lz=new Set(["bold","italic","underline","strike","color","highlight","link","clearFormatting","textAlign","list","numberedlist","indentleft","indentright","lineHeight","linkedStyles"]),Dz=new Set(["list","numberedlist"]);function Pz(e,t){if(e==="fontFamily"||e==="fontSize"||Dz.has(e)&&t?.disabled&&t?.supported!==!1&&t?.reason==null)return!0;if(!Lz.has(e))return!1;const n=t?.reason;return n==="range-selection-required"||n==="selection-required"}function qk(e){return!!e?.closest?.("[data-editor-ui-surface], .toolbar-dropdown-menu, .sd-toolbar-dropdown-menu, .sd-tooltip-content")}function Oz(e){return["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)}var Fz=class extends Dm.default{config={selector:null,toolbarGroups:["left","center","right"],role:"editor",icons:{...tr},texts:{...Wk},fonts:null,hideButtons:!0,responsiveToContainer:!1,mode:"docx",excludeItems:[],groups:null,customButtons:[],showFormattingMarksButton:!1,showTableOfContentsButton:!1};toolbarItems=[];overflowItems=[];#t=null;#n=null;isDev=!1;role="editor";superdoc;toolbarContainer=null;toolbar=null;_detachFontsChanged=null;constructor(e={}){if(super(),this.config={...this.config,...e},this.toolbarItems=[],this.overflowItems=[],this.isDev=e.isDev||!1,this.superdoc=e.superdoc,this.role=e.role||"editor",this.toolbarContainer=null,this.config.icons={...tr,...e.icons},this.config.texts={...Wk,...e.texts},this.config.hideButtons=e.hideButtons??!0,this.config.responsiveToContainer=e.responsiveToContainer??!1,this.activeEditor=e.editor??this.superdoc?.activeEditor??null,this.ui=null,this.snapshot=null,this._unsubscribeController=null,this._detachFormatPainterModeChange=null,this._customCommandRegs=new Map,this._lastFontOptionsSignature="",!this.config.selector&&this.config.element&&(this.config.selector=this.config.element),this.toolbarContainer=Mz(this.config.selector),this.toolbarContainer){const t=(this.config?.uiDisplayFallbackFont||"").toString().trim()||"Arial, Helvetica, sans-serif";this.toolbarContainer.style.setProperty("--sd-ui-font-family",t)}try{if(this.#e(),this.#u(),this.#l(),this.#s(),this._lastFontOptionsSignature=this.#o(),!this.toolbarContainer){this.updateToolbarState();return}this.app=Hl(xN),this.app.directive("click-outside",Fv),this.app.config.globalProperties.$toolbar=this,this.toolbar=this.app.mount(this.toolbarContainer),this.updateToolbarState()}catch(t){try{this.destroy()}catch{}throw t}}#e(){this.ui=this.superdoc?.ui??null,this.ui&&(this.snapshot=this.ui.toolbar.getSnapshot(),this._unsubscribeController=this.ui.toolbar.subscribe(()=>{this.snapshot=this.ui.toolbar.getSnapshot(),this.updateToolbarState()}),this._detachFormatPainterModeChange=this.ui.formatPainter.onModeChange(e=>{e==="armed"||e==="persistent"?this.#D():this.#k()}))}#i(){this._unsubscribeController?.(),this._unsubscribeController=null,this._detachFormatPainterModeChange?.(),this._detachFormatPainterModeChange=null,this.#k();for(const e of this._customCommandRegs.values())try{e.unregister?.()}catch{}this._customCommandRegs.clear(),this.ui=null,this.snapshot=null}#s(){if(!this.superdoc||typeof this.superdoc.on!="function"||typeof this.superdoc.off!="function")return;const e=()=>{const t=this.#o();t!==this._lastFontOptionsSignature&&(this._lastFontOptionsSignature=t,this.#m()),this.updateToolbarState()};this.superdoc.on("fonts-changed",e),this._detachFontsChanged=()=>{this.superdoc?.off?.("fonts-changed",e)}}#a(){this._detachFontsChanged?.(),this._detachFontsChanged=null}#u(){if(Array.isArray(this.config.groups)){this.config.toolbarGroups=this.config.groups,this.config.groups=null;return}this.config.groups&&!Array.isArray(this.config.groups)&&Object.keys(this.config.groups).length&&(this.config.toolbarGroups=Object.keys(this.config.groups))}getAvailableWidth(){const e=document.documentElement.clientWidth,t=this.toolbarContainer?.offsetWidth??0;return this.config.responsiveToContainer?t:e}#d(e){return e||SN(this.superdoc?.fonts?.getFontFamilyOptions?.()??[])}#l(){const e=this.getAvailableWidth(),t=this.config.groups&&!Array.isArray(this.config.groups)&&Object.keys(this.config.groups).length>0,{defaultItems:n,overflowItems:r}=Rz({superToolbar:this,toolbarIcons:this.config.icons,toolbarTexts:this.config.texts,toolbarFonts:this.#d(this.config.fonts),hideButtons:this.config.hideButtons,availableWidth:e,role:this.role,isDev:this.isDev}),o=this.config.customButtons||[],i=o.map(l=>this.#f(l));o.length&&n.push(...i);let s=[...n.map(l=>l.name.value),...r.map(l=>l.name.value)];if(t){const l=Object.values(this.config.groups).flatMap(d=>d),u=new Set(Object.keys(this.config.groups)),c=i.filter(d=>u.has(d.group?.value||"center")).map(d=>d.name.value);s=[...new Set([...l,...c])]}const a=n.filter(l=>s.includes(l.name.value)).filter(l=>!this.config.excludeItems.includes(l.name.value));if(t)for(const[l,u]of Object.entries(this.config.groups))for(const c of a)u.includes(c.name.value)&&(c.group.value=l);this.toolbarItems=a,this.overflowItems=r.filter(l=>s.includes(l.name.value))}#f(e){const t=Cn({...e});t.isCustomToolbarItem=!0;const n=e.command;if(typeof n=="function"&&this.ui?.commands?.register){const r=`__builtin_toolbar__${e.name}`;if(!this._customCommandRegs.has(r)){const o=this.ui.commands.register({id:r,execute:i=>{const s=i?.payload&&typeof i.payload=="object"?i.payload:{};return n({...i,item:t,argument:s.argument,option:s.option})}});this._customCommandRegs.set(r,o)}}return t}#m(){this.#l(),this.emit("toolbar-items-changed")}#o(){if(this.config.fonts)return"custom-fonts";const e=this.superdoc?.fonts?.getFontFamilyOptions?.()??[];return JSON.stringify(e.map(t=>[t.label,t.value,t.previewFamily]))}getToolbarItemByGroup(e){return this.toolbarItems.filter(t=>(t.group?.value||"center")===e)}getToolbarItemByName(e){return this.#r().find(t=>t.name.value===e)}#r(){return[...this.toolbarItems,...this.overflowItems]}getLinkedStyleOptions(){return this.ui?.styles?.getQuickGallery?.()??[]}getActiveLinkedStyleId(){return this.ui?.styles?.getActiveParagraphStyle?.()?.styleId??null}setActiveEditor(e){this.activeEditor=e;const t=this.#o();t!==this._lastFontOptionsSignature&&(this._lastFontOptionsSignature=t,this.#m()),this.ui&&(this.snapshot=this.ui.toolbar.getSnapshot()),this.updateToolbarState()}onToolbarResize=()=>{this.#l(),this.updateToolbarState()};#p(e){return e==="ruler"?!!this.superdoc?.config?.rulers:e==="formattingMarks"?!!this.superdoc?.config?.layoutEngineOptions?.showFormattingMarks:!1}#y(e){return e==="ruler"?typeof this.superdoc?.toggleRuler=="function":e==="formattingMarks"?typeof this.superdoc?.toggleFormattingMarks=="function"||typeof this.superdoc?.setShowFormattingMarks=="function":!1}#w(){const e=this.getToolbarItemByName("documentMode");if(!e)return;const t=(this.snapshot?.commands?.["document-mode"]?.value||"editing").toLowerCase(),n=this.config.texts||{},r=this.config.icons||{},o={editing:{label:n.documentEditingMode||"Editing",icon:r.documentEditingMode||r.documentMode},suggesting:{label:n.documentSuggestingMode||"Suggesting",icon:r.documentSuggestingMode||r.documentMode},viewing:{label:n.documentViewingMode||"Viewing",icon:r.documentViewingMode||r.documentMode}},i=o[t]||o.editing;e.label?.value!==void 0&&(e.label.value=i.label),e.defaultLabel?.value!==void 0&&(e.defaultLabel.value=i.label),e.icon?.value!==void 0&&i.icon&&(e.icon.value=i.icon)}#_(){const e=this.toolbarItems.find(n=>n.name.value==="highlight");if(!e)return;const t={key:"color",type:"render",render:()=>N0(this,e,[],!0)};e.nestedOptions.value=[t]}#S(e){return!!e?.active&&e?.value==null}#E(e){return!!e&&e.disabled===!1&&e.value==null}#x(e){const t=e.name.value;if(t==="tableActions"){const i=Hk.map(s=>this.snapshot?.commands?.[s]).some(s=>s&&!s.disabled);return e.setDisabled(!i),!0}if(t==="search")return e.setDisabled(!1),!0;if(P0(t)?.disposition==="host-routed")return e.setDisabled(!this.#y(t)),this.#p(t)?e.activate():e.deactivate(),!0;const n=Kk(t);if(!n)return!1;const r=this.snapshot?.commands?.[n];Pz(t,r)?e.setDisabled(!1):e.setDisabled(!!r?.disabled);const o={textAlign:()=>{r?.value?e.activate({textAlign:r.value}):e.deactivate()},lineHeight:()=>{e.selectedValue.value=r?.value!=null?r.value:""},zoom:()=>{if(r?.value!=null){const i=typeof r.value=="number"?`${r.value}%`:String(r.value);e.onActivate({zoom:i})}},measurementUnit:()=>{r?.value!=null&&e.onActivate({measurementUnit:String(r.value)})},documentMode:()=>{this.#w()},link:()=>{e.active.value=!!r?.active,e.attributes.value=z0(e.attributes.value,r?.value??null)},fontFamily:()=>{if(r?.value!=null){e.activate({fontFamily:r.value});return}if(this.#E(r)){e.activate({},!0);return}e.deactivate()},fontSize:()=>{if(r?.value!=null){e.activate({fontSize:r.value});return}if(this.#S(r)){e.activate({},!0);return}e.deactivate()},color:()=>{r?.value!=null?e.activate({color:r.value}):e.deactivate()},highlight:()=>{r?.value!=null?e.activate({color:r.value}):e.deactivate()},linkedStyles:()=>{const i=r?.value,s=typeof i=="string"?i:i?.styleId,a=i&&typeof i=="object"?i.styleName:null;s?e.activate({styleId:s,styleName:a}):e.label.value=this.config.texts?.formatText||"Format text"},list:()=>{r?.active?(e.activate(),e.selectedValue.value=r.value):(e.deactivate(),e.selectedValue.value=null)},numberedlist:()=>{r?.active?(e.activate(),e.selectedValue.value=r.value):(e.deactivate(),e.selectedValue.value=null)},default:()=>{r?.active?e.activate():e.deactivate()}};return(o[t]??o.default)(),!0}updateToolbarState(){this.#w(),this.#_();const e=this.snapshot?.commands?.["document-mode"]?.value||"editing";!(this.snapshot&&(this.superdoc?.activeEditor??this.activeEditor))||e==="viewing"?(this.#M(),this.#r().forEach(n=>{n.allowWithoutEditor?.value&&this.#x(n)})):this.#r().forEach(n=>{n.resetDisabled(),this.#x(n)});const t=this.getToolbarItemByName("copyFormat");t&&(this.snapshot?.copyFormatActive?t.activate():t.deactivate()),this.emit("toolbar-state-change")}#M(){this.#r().forEach(e=>{const{allowWithoutEditor:t}=e;t?.value||e.setDisabled(!0)})}#c(e,t){const n=this.superdoc;if(e==="ruler")return typeof n?.toggleRuler=="function"?(n.toggleRuler(),!0):!1;if(e==="formattingMarks"){if(typeof t=="boolean"&&typeof n?.setShowFormattingMarks=="function")return n.setShowFormattingMarks(t),!0;if(typeof n?.toggleFormattingMarks=="function")return n.toggleFormattingMarks(),!0}return!1}#L(e,t){const n=e?.name?.value;if(!n)return!1;const r={onSettled:()=>this.updateToolbarState(),onError:i=>this.#g(i,n)};if(n==="image"&&t==null)return this.#T();if(n==="tableActions"){const i=zk[t?.command];return i?Qp(this.ui,i,void 0,r):!1}if(P0(n)?.disposition==="unsupported")return!0;const o=Kk(n);return o?Qp(this.ui,o,t,r):!1}#T(){return this.snapshot?.commands?.image?.disabled||(this.#t||(this.#t=dB({ownerDocument:this.toolbarContainer?.ownerDocument??document,onPick:async e=>{const t=await cB(e,this.superdoc?.config?.handleImageUpload);Qp(this.ui,"image",{src:t},{onSettled:()=>this.updateToolbarState(),onError:n=>this.#g(n,"image")})},onError:e=>this.#g(e,"image")})),this.#t.open()),!0}#D(){if(this.#n)return;const e=this.superdoc?.activeEditor?.container??document,t=i=>{qk(i.target)||this.ui.formatPainter.setPointerSelecting(!0)},n=i=>{this.ui.formatPainter.setPointerSelecting(!1),!qk(i.target)&&this.ui.formatPainter.notifyPointerUp()},r=i=>{if(i.key==="Escape"){this.ui.formatPainter.cancel();return}Oz(i)&&this.ui.formatPainter.setKeyboardSelecting(!0)},o=()=>{this.ui.formatPainter.setKeyboardSelecting(!1),this.ui.formatPainter.notifyKeyUp()};e.addEventListener("pointerdown",t),e.addEventListener("pointerup",n),e.addEventListener("keydown",r),e.addEventListener("keyup",o),this.#n=()=>{e.removeEventListener("pointerdown",t),e.removeEventListener("pointerup",n),e.removeEventListener("keydown",r),e.removeEventListener("keyup",o)}}#k(){this.#n&&(this.#n(),this.#n=null)}#g(e,t){const n=e instanceof Error?e:new Error(String(e));this.emit("exception",{error:n,originalError:e,itemName:t??null,editor:this.superdoc?.activeEditor??this.activeEditor??null})}emitCommand({item:e,argument:t,option:n}){const r=e?.name?.value,{command:o}=e,i=t!=null;if(!(e?.type==="dropdown"&&!i&&(o==="setFontFamily"||o==="setFontSize"))){if(r==="search"){this.superdoc?.emit?.("search:open");return}try{if(P0(r)?.disposition==="host-routed"){this.#c(r,t),this.updateToolbarState();return}if(typeof o=="function"){const s=`__builtin_toolbar__${r}`;this._customCommandRegs.has(s)&&this.ui?.commands?.execute?this.ui.commands.execute(s,{argument:t,option:n}):o({item:e,argument:t,option:n,ui:this.ui,superdoc:this.superdoc}),this.updateToolbarState();return}if(e?.isCustomToolbarItem&&typeof o=="string"){if(!Qp(this.ui,o,t,{onSettled:()=>this.updateToolbarState(),onError:s=>this.#g(s,r)}))throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState();return}if(!this.#L(e,t)&&o)throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState()}catch(s){this.#g(s,r)}}}destroy(){this.#k(),this.#t?.destroy(),this.#t=null,this.#a(),this.#i(),this.app?.unmount(),this.app=null,this.toolbar=null}};function Bz(e){return new Fz(e)}function Nz(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null||Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!Object.prototype.hasOwnProperty.call(t,o)||!Object.is(e[o],t[o]))return!1;return!0}function zz(e){if(!e||typeof e!="object")return{};const t={};e.fonts&&(t.rFonts={ascii:e.fonts.ascii,hAnsi:e.fonts.hAnsi,eastAsia:e.fonts.eastAsia,cs:e.fonts.cs,asciiTheme:e.fonts.asciiTheme,hAnsiTheme:e.fonts.hAnsiTheme,eastAsiaTheme:e.fonts.eastAsiaTheme,csTheme:e.fonts.csTheme,hint:e.fonts.hint}),e.fontFamily!=null&&(t.fontFamily=e.fontFamily),e.lang&&(t.lang={val:e.lang.val,eastAsia:e.lang.eastAsia,bidi:e.lang.bidi}),e.fontSize!=null&&(t.fontSize=e.fontSize),e.fontSizeCs!=null&&(t.fontSizeCs=e.fontSizeCs);const n=Zp(e.color);n!=null&&(t.color=n),e.highlight!=null&&(t.highlight=e.highlight);const r=Uz(e.shading);r&&(t.shading=r),e.cs!=null&&(t.cs=e.cs),e.rtl!=null&&(t.rtl=e.rtl),e.bold!=null&&(t.bold=e.bold),e.boldCs!=null&&(t.bCs=e.boldCs),e.italic!=null&&(t.italic=e.italic),e.italicCs!=null&&(t.iCs=e.italicCs);const o=Hz(e.underline);o!==void 0&&(t.underline=o),e.strikethrough!=null&&(t.strike=e.strikethrough),e.doubleStrikethrough!=null&&(t.dstrike=e.doubleStrikethrough),e.caps!=null&&(t.caps=e.caps),e.smallCaps!=null&&(t.smallCaps=e.smallCaps),e.outline!=null&&(t.outline=e.outline),e.shadow!=null&&(t.shadow=e.shadow),e.emboss!=null&&(t.emboss=e.emboss),e.imprint!=null&&(t.imprint=e.imprint),e.verticalAlign!=null&&(t.vertAlign=e.verticalAlign),e.characterSpacing!=null&&(t.letterSpacing=e.characterSpacing),e.characterScale!=null&&(t.charScale=e.characterScale),e.kern!=null&&(t.kerning=e.kern),e.baselineShift!=null&&(t.position=e.baselineShift),e.fitTextWidth!=null&&(t.fitText={val:e.fitTextWidth}),e.vanish!=null&&(t.vanish=e.vanish),e.webHidden!=null&&(t.webHidden=e.webHidden),e.specVanish!=null&&(t.specVanish=e.specVanish);const i=Vz(e.border);return i&&(t.border=i),t}function Zp(e){if(e){if(typeof e=="string")return e;if(e.model==="rgb")return e.value;if(e.model==="auto")return"auto"}}function Hz(e){if(e==null)return;const t={};return e.style!=null&&(t.style=e.style),e.color?.model==="rgb"&&(t.color=e.color.value),e.color?.model==="theme"&&(t.themeColor=e.color.theme),Object.keys(t).length>0?t:!0}function Uz(e){if(!e)return;const t={},n=Zp(e.fill);n!=null&&(t.fill=n);const r=Zp(e.color);return r!=null&&(t.color=r),e.pattern!=null&&(t.val=e.pattern),Object.keys(t).length>0?t:void 0}function Vz(e){if(!e)return;const t={};e.style!=null&&(t.val=e.style),e.width!=null&&(t.sz=e.width),e.space!=null&&(t.space=e.space);const n=Zp(e.color);return n!=null&&(t.color=n),Object.keys(t).length>0?t:void 0}function $l(e){const t=e?.selectionTarget??e?.target;if(!e||!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function Yk(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function jz(e){const t=[],n=o=>{o&&!t.includes(o)&&t.push(o)};n(e.getAttribute("data-track-change-preferred-target-id"));const r=e.getAttribute("data-track-change-ids");if(r)for(const o of Yk(r))n(o);return n(e.getAttribute("data-track-change-id")),t}function Xk(e,t){if(!e||typeof e.getAttribute!="function")return[];const n=[],r=new Set;let o=[],i=e;for(;i;){const s=i,a=jz(s),l=a.length>0?s.getAttribute("data-story-key"):null;for(const m of a){const p=`trackedChange:${m}`;if(!r.has(p)){r.add(p);const g={type:"trackedChange",id:m};l&&(g.storyKey=l),n.push(g),o.push(g)}}const u=s.getAttribute("data-layout-story");if(u&&o.length>0){for(const m of o)m.story=u;o=[]}const c=s.getAttribute("data-comment-ids");if(c)for(const m of Yk(c)){const p=`comment:${m}`;r.has(p)||(r.add(p),n.push({type:"comment",id:m}))}const d=s.getAttribute("data-sdt-type"),h=s.getAttribute("data-sdt-id");if(h&&d==="structuredContent"){const m=`contentControl:${h}`;if(!r.has(m)){r.add(m);const p=s.getAttribute("data-sdt-scope"),g=s.getAttribute("data-sdt-tag"),k={type:"contentControl",id:h};(p==="block"||p==="inline")&&(k.scope=p),g&&(k.tag=g),n.push(k)}}if(t&&i===t)break;i=i.parentElement}return n}const H0={PAGE:"superdoc-page",FRAGMENT:"superdoc-fragment",LINE:"superdoc-line",INLINE_SDT_WRAPPER:"superdoc-structured-content-inline",INLINE_SDT_LABEL:"superdoc-structured-content-inline__label",BLOCK_SDT:"superdoc-structured-content-block",BLOCK_SDT_LABEL:"superdoc-structured-content__label",TABLE_FRAGMENT:"superdoc-table-fragment",DOCUMENT_SECTION:"superdoc-document-section",SDT_GROUP_HOVER:"sdt-group-hover",TOC_ENTRY:"superdoc-toc-entry",TOC_GROUP_HOVER:"toc-group-hover",IMAGE_FRAGMENT:"superdoc-image-fragment",INLINE_IMAGE:"superdoc-inline-image",LIST_MARKER:"superdoc-list-marker",INLINE_IMAGE_CLIP_WRAPPER:"superdoc-inline-image-clip-wrapper",ANNOTATION:"annotation",ANNOTATION_CONTENT:"annotation-content",ANNOTATION_CARET_ANCHOR:"annotation-caret-anchor"},xj=[H0.INLINE_SDT_LABEL,H0.BLOCK_SDT_LABEL],Qk={PM_START:"data-pm-start",PM_END:"data-pm-end",LAYOUT_EPOCH:"data-layout-epoch",TABLE_BOUNDARIES:"data-table-boundaries",SDT_ID:"data-sdt-id",SDT_TYPE:"data-sdt-type",FIELD_ID:"data-field-id",FIELD_TYPE:"data-field-type",DRAGGABLE:"data-draggable",DISPLAY_LABEL:"data-display-label",VARIANT:"data-variant",TYPE:"data-type",LAYOUT_BOUNDARY_SCHEMA:"data-layout-boundary-schema",LAYOUT_FRAGMENT_ID:"data-layout-fragment-id",LAYOUT_STORY:"data-layout-story",LAYOUT_BLOCK_REF:"data-layout-block-ref"},Gz=e=>{if(!e)return{kind:"unknown"};if(e==="body")return{kind:"body"};const t=e.indexOf(":"),n=t===-1?e:e.slice(0,t),r=t===-1?void 0:e.slice(t+1);switch(n){case"body":case"header":case"footer":case"footnote":case"endnote":case"textbox":return r?{kind:n,id:r}:{kind:n};default:return{kind:"unknown"}}},Tj=`.${H0.BLOCK_SDT}[${Qk.SDT_ID}]`,Rj=`[${Qk.DRAGGABLE}="true"]`;var to=()=>({oneOf:[{type:"boolean"},{type:"null"}]}),nl=()=>({oneOf:[{type:"string",minLength:1},{type:"null"}]}),hu=()=>({oneOf:[{type:"number"},{type:"null"}]}),pu=e=>({oneOf:[{type:"object",properties:e,additionalProperties:!1,minProperties:1},{type:"null"}]}),Wz={type:"object",properties:{style:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},themeColor:{oneOf:[{type:"string",minLength:1},{type:"null"}]}},additionalProperties:!1,minProperties:1},Kz={type:"object",properties:{id:{type:"number"},val:{type:"boolean"}},required:["id"],additionalProperties:!1},qz=()=>({oneOf:[{type:"boolean"},{type:"null"},Wz]}),Yz=()=>({oneOf:[{type:"array",items:Kz,minItems:1},{type:"null"}]});function Jp(e,t){return{storage:"mark",markName:e,textStyleAttr:t}}function Xz(e){return{storage:"runAttribute",nodeName:"run",runPropertyKey:e}}var U0=(e,t,n)=>({key:e,type:"boolean",ooxmlElement:t,storage:"mark",tracked:!0,carrier:Jp(n),schema:to()}),ec=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"mark",tracked:!0,carrier:Jp("textStyle",o??e),schema:r}),Pn=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"runAttribute",tracked:!1,carrier:Xz(o??e),schema:r});const $p=[U0("bold","w:b","bold"),U0("italic","w:i","italic"),U0("strike","w:strike","strike"),{key:"underline",type:"object",ooxmlElement:"w:u",storage:"mark",tracked:!0,carrier:Jp("underline"),schema:qz()},{key:"highlight",type:"string",ooxmlElement:"w:highlight",storage:"mark",tracked:!0,carrier:Jp("highlight"),schema:nl()},ec("color","string","w:color",nl()),ec("fontSize","number","w:sz",hu()),ec("fontFamily","string","w:rFonts",nl()),ec("letterSpacing","number","w:spacing",hu()),ec("vertAlign","string","w:vertAlign",{oneOf:[{enum:["superscript","subscript","baseline"]},{type:"null"}]}),ec("position","number","w:position",hu()),Pn("dstrike","boolean","w:dstrike",to()),Pn("smallCaps","boolean","w:smallCaps",to()),ec("caps","boolean","w:caps",to(),"textTransform"),Pn("shading","object","w:shd",pu({fill:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},val:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Pn("border","object","w:bdr",pu({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},sz:{oneOf:[{type:"number"},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},space:{oneOf:[{type:"number"},{type:"null"}]}}),"borders"),Pn("outline","boolean","w:outline",to()),Pn("shadow","boolean","w:shadow",to()),Pn("emboss","boolean","w:emboss",to()),Pn("imprint","boolean","w:imprint",to()),Pn("charScale","number","w:w",hu(),"w"),Pn("kerning","number","w:kern",hu(),"kern"),Pn("vanish","boolean","w:vanish",to()),Pn("webHidden","boolean","w:webHidden",to()),Pn("specVanish","boolean","w:specVanish",to()),Pn("rtl","boolean","w:rtl",to()),Pn("cs","boolean","w:cs",to()),Pn("bCs","boolean","w:bCs",to(),"boldCs"),Pn("iCs","boolean","w:iCs",to(),"italicCs"),Pn("eastAsianLayout","object","w:eastAsianLayout",pu({id:{oneOf:[{type:"string",minLength:1},{type:"null"}]},combine:{oneOf:[{type:"boolean"},{type:"null"}]},combineBrackets:{oneOf:[{type:"string",minLength:1},{type:"null"}]},vert:{oneOf:[{type:"boolean"},{type:"null"}]},vertCompress:{oneOf:[{type:"boolean"},{type:"null"}]}})),Pn("em","string","w:em",nl()),Pn("fitText","object","w:fitText",pu({val:{oneOf:[{type:"number"},{type:"null"}]},id:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Pn("snapToGrid","boolean","w:snapToGrid",to()),Pn("lang","object","w:lang",pu({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},bidi:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Pn("oMath","boolean","w:oMath",to()),Pn("rStyle","string","w:rStyle",nl(),"styleId"),Pn("rFonts","object","w:rFonts",pu({ascii:{oneOf:[{type:"string",minLength:1},{type:"null"}]},hAnsi:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},cs:{oneOf:[{type:"string",minLength:1},{type:"null"}]},asciiTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},hAnsiTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsiaTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},csTheme:{oneOf:[{type:"string",minLength:1},{type:"null"}]},hint:{oneOf:[{type:"string",minLength:1},{type:"null"}]}}),"fontFamily"),Pn("fontSizeCs","number","w:szCs",hu()),Pn("ligatures","string","w14:ligatures",nl()),Pn("numForm","string","w14:numForm",nl()),Pn("numSpacing","string","w14:numSpacing",nl()),Pn("stylisticSets","array","w14:stylisticSets",Yz()),Pn("contextualAlternates","boolean","w14:cntxtAlts",to())],Mj=new Set($p.map(e=>e.key)),Qz=Object.fromEntries($p.map(e=>[e.key,e])),Lj={mark:$p.filter(e=>e.storage==="mark").map(e=>e.key),runAttribute:$p.filter(e=>e.storage==="runAttribute").map(e=>e.key)};var Zz=new Set(Object.values(at));function V0(e,t){return typeof e=="string"&&Zz.has(e)?e:t}function Zk(e){if(e&&typeof e=="object"&&e.ok===!1){const t=e.reason;return t==="host-not-ready"||t==="host-disposed"||t==="editing-mount-required"?{ok:!1,reason:at.notReady}:{ok:!1,reason:V0(t,at.targetUnresolved)}}return{ok:!0}}var Jz=["document-replaced","editorCreate","active-editor-change","document-mode-change","zoomChange","measurement-unit-change","viewport-change","fonts-changed"],$z={[xk.bulletList]:"bullet",[xk.numberedList]:"ordered"};function Jk(e){return $z[e]??null}var eH={disc:"disc",circle:"circle",square:"square",decimal:"decimal","decimal-paren":"decimalParenthesis","upper-roman":"upperRoman","lower-roman":"lowerRoman","upper-alpha":"upperLetter","upper-alpha-paren":"upperLetterParenthesis","lower-alpha":"lowerLetter","lower-alpha-paren":"lowerLetterParenthesis"};function tH(e){const t=eH[e];return t?{preset:t,behavior:"toggleStyle"}:{}}var nH={status:"ready",empty:!0,target:null,selectionTarget:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[],quotedText:""};const rH=[{key:"contentControls",match:"exact",note:"full-document SDT catalog parse (the measured during-load cliff)"},{key:"contentControls:inRange:",match:"prefix",note:"same adapter load() as the catalog, issued per settled selection"},{key:"hyperlinks:",match:"prefix",note:"per-block hyperlink list over the loading story"},{key:"styles:catalog:",match:"prefix",note:"WordStyleModel recompile from package bytes"},{key:"comments",match:"exact",note:"audited: full comments list; stale-served during load"},{key:"trackChanges",match:"exact",note:"audited: body tracked-changes list; stale-served during load"},{key:"trackChanges:all",match:"exact",note:"audited: all-story tracked-changes list; consumers already fail closed on non-ready"},{key:"tables",match:"exact",note:"reserved: full tables catalog"},{key:"sections",match:"exact",note:"reserved: full sections list"}];var oH=new Set(["/word/comments.xml","/word/commentsExtended.xml","/word/commentsIds.xml"]);function iH(e){return rH.some(t=>t.match==="exact"?t.key===e:e.startsWith(t.key))}var $k={ready:0,stale:1,pending:2};function mu(...e){let t="ready";for(const n of e)$k[n]>$k[t]&&(t=n);return t}function xt(e,t){if(typeof e!="function")return t;try{const n=e();return n===void 0?t:n}catch{return t}}function Or(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function gr(e,t){if(!e)return null;const n=t.split(".");let r=e;for(const o of n){if(r==null)return null;r=r[o]}return typeof r=="function"?r:null}function cr(e,t="CAPABILITY_UNAVAILABLE"){return{success:!1,failure:{code:t,message:e}}}function Af(e,t){return{success:!1,failure:{code:"PARTIAL_LINK_EDIT",message:"Hyperlink target was updated, but display text replacement failed."},applied:{href:!0,text:!1},hyperlinkResult:e,textResult:t}}function If(e){if(!e||typeof e!="object")return null;const t=e.target;return t&&typeof t=="object"?t:null}function j0(e){if(!e||typeof e!="object")return!1;const t=e,n=i=>{if(!i||typeof i!="object")return!1;const s=i;return s.kind==="text"&&typeof s.blockId=="string"&&typeof s.offset=="number"},r=i=>{if(!i||typeof i!="object")return!1;const s=i,a=s.range;return typeof s.blockId=="string"&&typeof a?.start=="number"&&typeof a.end=="number"};if(Array.isArray(t.segments)){const i=t.segments[0],s=t.segments[t.segments.length-1];return r(i)&&r(s)}if(t.kind==="selection")return n(t.start)&&n(t.end);if(t.kind!=="text"||typeof t.blockId!="string")return!1;const o=t.range;return typeof o?.start=="number"&&typeof o.end=="number"}function sH(e){if(!e||typeof e!="object")return null;const t=If(e);if(j0(t))return t;const n=e,r=n.navigationTarget&&typeof n.navigationTarget=="object"?n.navigationTarget:null;return r?.kind==="block"&&typeof r.blockId=="string"&&r.blockId.length>0?{kind:"text",blockId:r.blockId,range:{start:0,end:0},...r.story&&typeof r.story=="object"?{story:r.story}:{},...n.address&&typeof n.address=="object"?{address:n.address}:{}}:t}function no(e){if(!e||typeof e!="object")return"story:body";const t=e,n=typeof t.storyType=="string"?t.storyType:"body";switch(n){case"body":return"story:body";case"headerFooterPart":return`story:headerFooterPart:${typeof t.refId=="string"?t.refId:""}`;case"headerFooterSlot":return JSON.stringify({storyType:n,section:t.section??null,headerFooterKind:t.headerFooterKind??null,variant:t.variant??null,resolution:t.resolution??"effective",onWrite:t.onWrite??"materializeIfInherited"});case"footnote":return`story:footnote:${typeof t.noteId=="string"?t.noteId:""}`;case"endnote":return`story:endnote:${typeof t.noteId=="string"?t.noteId:""}`;case"textbox":return`story:textbox:${typeof t.textboxId=="string"?t.textboxId:""}`;default:return JSON.stringify(t)}}function em(e){if(!e||typeof e!="object")return null;const t=e,n=t.address&&typeof t.address=="object"?t.address:null;if(n?.story&&typeof n.story=="object")return n.story;if(t.storyLocator&&typeof t.storyLocator=="object")return t.storyLocator;if(t.trackedChangeStory&&typeof t.trackedChangeStory=="object")return t.trackedChangeStory;const r=If(e);if(!r||typeof r!="object")return null;const o=r;if(o.story&&typeof o.story=="object")return o.story;const i=o.address&&typeof o.address=="object"?o.address:null;return i?.story&&typeof i.story=="object"?i.story:null}function rl(e,t,n){return Un(e)!==t?!1:n?no(em(e))===no(n):!0}function eA(e){const t=em(e);if(!(!t||no(t)===no(null)))return t}function aH(e){if(typeof e!="string"||e.length===0)return;const t=Gz(e);switch(t.kind){case"body":return;case"footnote":return t.id?{kind:"story",storyType:"footnote",noteId:t.id}:void 0;case"endnote":return t.id?{kind:"story",storyType:"endnote",noteId:t.id}:void 0;case"header":case"footer":return t.id?{kind:"story",storyType:"headerFooterPart",refId:t.id}:void 0;default:return}}function lH(e){if(!(typeof e!="string"||e.length===0||e==="body")){if(e.startsWith("hf:part:")){const t=e.slice(8);return t?{kind:"story",storyType:"headerFooterPart",refId:t}:void 0}if(e.startsWith("fn:")){const t=e.slice(3);return t?{kind:"story",storyType:"footnote",noteId:t}:void 0}if(e.startsWith("en:")){const t=e.slice(3);return t?{kind:"story",storyType:"endnote",noteId:t}:void 0}}}function G0(e){if(!e||typeof e!="object")return null;const t=e.selectionTarget;return t&&typeof t=="object"?t:null}function tm(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function cH(e){if(!e||typeof e!="object")return null;const t=e;if(t.kind!=="selection")return e;const n=t.start;return!n||typeof n!="object"?null:{...t,end:n}}function Un(e){if(!e||typeof e!="object")return null;const t=e,n=t.id??t.commentId??t.changeId;return typeof n=="string"&&n.length>0?n:null}function uH(e){if(!e||typeof e!="object")return null;const t=e,n=t.anchor,r=t.focus,o=n?.visualCaret,i=r?.visualCaret,s=o?.trackChangeId,a=i?.trackChangeId;return typeof s=="string"&&s.length>0&&s===a?s:null}var tA=new WeakMap;function dH(e){const t=[],n=i=>{typeof i=="string"&&i.length>0&&!t.includes(i)&&t.push(i)},r=i=>{if(!i||typeof i!="object")return;const s=i,a=s.sourceIds;if(a&&typeof a=="object"&&(n(a.wordIdInsert),n(a.wordIdDelete),Array.isArray(a.wordIdOther)))for(const d of a.wordIdOther)n(d);const l=s.wordRevisionIds;l&&typeof l=="object"&&(n(l.insert),n(l.delete),n(l.format));const u=s.replacement;if(u&&typeof u=="object")for(const d of[u.inserted,u.deleted])d&&typeof d=="object"&&(n(d.id),n(d.wordId));const c=s.move;if(c&&typeof c=="object")for(const d of[c.source,c.destination])d&&typeof d=="object"&&(n(d.id),n(d.wordId))};r(e);const o=e?.change;return o&&o!==e&&r(o),t}function Ef(e){const t=tA.get(e);if(t)return t;const n=new Set,r=new Map;for(const i of e){const s=Un(i);if(s){n.add(s);for(const a of dH(i)){r.has(a)||r.set(a,s);const l=`imported:${a}`;r.has(l)||r.set(l,s)}}}const o={toPublicId(i){if(n.has(i))return i;const s=r.get(i);return s!=null&&n.has(s)?s:null},aliasesFor(i){const s=[i];for(const[a,l]of r)l===i&&!s.includes(a)&&s.push(a);return s}};return tA.set(e,o),o}var nA=new WeakMap;function rA(e,t){const n=no(t);let r=nA.get(e);r||(r=new Map,nA.set(e,r));const o=r.get(n);if(o)return o;const i=Ef(e.filter(s=>no(em(s))===n));return r.set(n,i),i}function fH(e,t){const n=e.find(r=>Un(r)===t||r.importedId===t);return n?n.rootCommentId??n.parentCommentId??Un(n)??t:null}function hH(e){const t=e.selectionTarget;if(t){const s=t.start,a=t.end,l=typeof s?.blockId=="string"?s.blockId:void 0,u=typeof a?.blockId=="string"?a.blockId:l;if(l)return{startBlockId:l,endBlockId:u??l}}const n=e.target,r=n&&Array.isArray(n.segments)?n.segments:[],o=r[0]?.blockId,i=r[r.length-1]?.blockId;return typeof o=="string"?{startBlockId:o,endBlockId:typeof i=="string"?i:o}:null}function Rr(e){const t=[],n=s=>{typeof s=="string"&&s.length>0&&!t.includes(s)&&t.push(s)},r=e.target,o=r&&Array.isArray(r.segments)?r.segments:[];for(const s of o)n(s?.blockId);const i=e.selectionTarget;return i&&(n(i.start?.blockId),n(i.end?.blockId)),t}var pH=64;function tc(e){return e.length<=pH}function ga(e){const t=e.target,n=e.selectionTarget,r=n?.start,o=n?.end,i=t?.story??n?.story??r?.story??o?.story;return i&&typeof i=="object"?i:{kind:"story",storyType:"body"}}function ho(e,t){return{kind:"block",nodeType:"paragraph",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}function va(e){return{kind:"block",nodeType:"paragraph",nodeId:e}}function oA(e,t){return{kind:"block",nodeType:"listItem",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}var iA=720;function Cs(e){return Math.round(e*20)}function gu(e){return typeof e=="number"&&Number.isFinite(e)}function mH(e){if(!e||typeof e!="object")return null;const t=e.node;if(!t||typeof t!="object")return null;const n=t.kind==="heading"?t.heading??null:t.kind==="paragraph"?t.paragraph??null:null;if(!n)return null;const r=n.resolved,o=n.props,i=r?.indent??o?.indent;if(!i||typeof i!="object")return null;const s=gu(i.left)?Cs(i.left):gu(i.start)?Cs(i.start):void 0,a=gu(i.right)?Cs(i.right):gu(i.end)?Cs(i.end):void 0,l=gu(i.firstLine)?Cs(i.firstLine):void 0,u=gu(i.hanging)?Cs(i.hanging):void 0;return s==null&&a==null&&l==null&&u==null?null:{...s!=null?{left:s}:{},...a!=null?{right:a}:{},...l!=null?{firstLine:l}:{},...u!=null?{hanging:u}:{}}}function W0(e){const t=e.target,n=t&&Array.isArray(t.segments)?t.segments:[],r=t?.story,o=[];for(const i of n){if(!i||typeof i.blockId!="string")continue;const s=i.range;!s||typeof s.start!="number"||typeof s.end!="number"||s.start===s.end||o.push({kind:"text",blockId:i.blockId,range:{start:s.start,end:s.end},...r?{story:r}:{}})}return o}function gH(e){if(!e||typeof e!="object")return[];const t=e,n=t.story,r=[];if(t.kind==="text"&&t.range&&typeof t.blockId=="string"){const o=t.range;return typeof o.start=="number"&&typeof o.end=="number"&&o.start!==o.end&&r.push({kind:"text",blockId:t.blockId,range:{start:Math.min(o.start,o.end),end:Math.max(o.start,o.end)},...n?{story:n}:{}}),r}if(t.kind==="text"&&Array.isArray(t.segments)){for(const o of t.segments){const i=o?.range;typeof o?.blockId=="string"&&typeof i?.start=="number"&&typeof i?.end=="number"&&i.start!==i.end&&r.push({kind:"text",blockId:o.blockId,range:{start:Math.min(i.start,i.end),end:Math.max(i.start,i.end)},...n?{story:n}:{}})}return r}if(t.kind==="selection"){const o=t.start,i=t.end,s=typeof o?.blockId=="string"&&i?.blockId===o.blockId?o.blockId:null;o?.kind==="text"&&i?.kind==="text"&&s&&typeof o.offset=="number"&&typeof i.offset=="number"&&o.offset!==i.offset&&r.push({kind:"text",blockId:s,range:{start:Math.min(o.offset,i.offset),end:Math.max(o.offset,i.offset)},...t.story??o.story?{story:t.story??o.story}:{}})}return r}function xf(e){if(!e||typeof e!="object")return null;const t=e,n=t.story;if(t.kind==="text"&&t.range&&typeof t.blockId=="string"){const r=t.range;if(typeof r.start=="number"&&typeof r.end=="number"&&r.start===r.end)return{kind:"text",blockId:t.blockId,range:{start:r.start,end:r.end},...n?{story:n}:{}}}if(t.kind==="text"&&Array.isArray(t.segments)){const r=t.segments[0],o=r?.range;if(typeof r?.blockId=="string"&&typeof o?.start=="number"&&typeof o?.end=="number"&&o.start===o.end)return{kind:"text",blockId:r.blockId,range:{start:o.start,end:o.end},...n?{story:n}:{}}}if(t.kind==="selection"){const r=t.start,o=t.end,i=typeof r?.blockId=="string"&&o?.blockId===r.blockId?r.blockId:null;if(r?.kind==="text"&&o?.kind==="text"&&i&&typeof r.offset=="number"&&typeof o.offset=="number"&&r.offset===o.offset)return{kind:"text",blockId:i,range:{start:r.offset,end:r.offset},...t.story??r.story?{story:t.story??r.story}:{}}}return null}function ol(e){return xf(e.target)??xf(e.selectionTarget)}var sA=["fontFamily","fontSize","color","highlight"],vH={undo:"history.undo",redo:"history.redo"},Tf=["bold","italic","underline","strikethrough"];function K0(e){return sA.includes(e)}function vu(e){const t=e.target,n=t&&Array.isArray(t.segments)?t.segments:[],r=[],o=(l,u,c)=>{typeof l!="string"||typeof u!="number"||typeof c!="number"||r.push({blockId:l,start:Math.min(u,c),end:Math.max(u,c)})};for(const l of n){const u=l?.range;o(l?.blockId,u?.start,u?.end)}if(r.length>0)return r;const i=e.selectionTarget,s=i?.start,a=i?.end;return!s||!a||s.blockId!==a.blockId||o(s.blockId,s.offset,a.offset),r}function _s(e){const t=e.target,n=e.selectionTarget,r=n?.start,o=n?.end,i=t?.story??n?.story??r?.story??o?.story;return i&&typeof i=="object"?i:void 0}function yH(e){const t=_s(e);if(!t||typeof t!="object")return"body";const n=t;return JSON.stringify({storyType:typeof n.storyType=="string"?n.storyType:"body",refId:typeof n.refId=="string"?n.refId:null,noteId:typeof n.noteId=="string"?n.noteId:null,textboxId:typeof n.textboxId=="string"?n.textboxId:null})}function ya(e){const t=vu(e);return t.length===0?null:[yH(e),...t.map(n=>`${n.blockId}:${n.start}-${n.end}`)].join("|")}function aA(e){const t=e.selectionTarget;return!t||typeof t!="object"?null:$l({selectionTarget:t})}function bH(e,t){if(e==="fontSize"){const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)&&r>0?String(r):null}if(typeof t!="string")return null;const n=t.trim();return n.length===0?null:e==="color"||e==="highlight"?n.toUpperCase():n}function wH(e,t){return Math.max(e.start,t.start)<Math.min(e.end,t.end)}function CH(e){if(!e)return[];const t=Array.isArray(e.blocks)?e.blocks:[],n=[];for(const r of t){const o=r?.range,i=r?.blockId;typeof i!="string"||typeof o?.start!="number"||typeof o?.end!="number"||n.push({blockId:i,start:Math.min(o.start,o.end),end:Math.max(o.start,o.end)})}return n}function _H(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return o?.blockId===n.blockId&&o?.start===n.start&&o?.end===n.end})}function lA(e,t){const n=vu(t);if(n.length===0)return null;const r=e&&Array.isArray(e.items)?e.items:[];if(r.length===0)return null;const o=r.find(i=>_H(n,CH(i)));if(o)return o;if(n.length===1){const i=r.find(s=>{const a=s?.address;return a?.kind==="block"&&a.nodeId===n[0].blockId});if(i)return i}return r[0]??null}function SH(e,t){const n=t==="fontSize"?e?.fontSizePt??e?.fontSize:t==="highlight"?e?.highlight??e?.backgroundColor:e?.[t];if(typeof n=="number")return Number.isFinite(n)?String(n):void 0;if(typeof n!="string")return;const r=n.trim();if(r.length!==0)return t==="color"||t==="highlight"?r.toUpperCase():r}function q0(e){if(typeof e!="string")return;const t=e.split(",")[0]?.trim().replace(/^['"]+|['"]+$/g,"").trim();if(!t)return;const n=t.toLowerCase();if(!(n==="serif"||n==="sans-serif"||n==="monospace"||n==="cursive"||n==="fantasy"))return t}function kH(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return;const t=Math.round(e*.75*2)/2;if(!(t<=0))return String(t)}function AH(e,t){return e==="fontFamily"?t.toLowerCase():e==="color"||e==="highlight"?t.toUpperCase():t}function cA(e,t){if(!e)return{};const n=new Map;for(const i of vu(t)){const s=n.get(i.blockId)??[];s.push({start:i.start,end:i.end}),n.set(i.blockId,s)}if(n.size===0)return{};const r=Array.isArray(e.blocks)?e.blocks:[],o={};for(const i of sA){const s=new Map;let a=!1,l=!1;for(const u of r){const c=typeof u?.blockId=="string"?u.blockId:null;if(!c)continue;const d=n.get(c);if(!d?.length)continue;const h=Array.isArray(u?.runs)?u.runs:[];for(const m of h){const p=m?.range,g=typeof p?.start=="number"?p.start:null,k=typeof p?.end=="number"?p.end:null;if(g==null||k==null||!d.some(y=>wH(y,{start:g,end:k})))continue;a=!0;const w=SH(m?.styles,i);if(w===void 0){l=!0;continue}const S=AH(i,w);if(s.has(S)||s.set(S,w),s.size>1)break}if(s.size>1)break}a&&!l&&s.size===1&&(o[i]=[...s.values()][0])}return o}function Y0(e,t){const n=Rr(e)[0];return n?t==="nodeId"?{kind:"after",nodeId:n}:{kind:"after",target:ho(n)}:{kind:"documentEnd"}}function tn(e,t){const n=e.supported??t!=="unsupported",r=e.enabled??(e.disabled!==void 0?!e.disabled:n);return{enabled:r,disabled:!r,active:e.active??!1,supported:n,value:e.value,source:t,reason:r?void 0:e.reason}}function nc(e){if(!e||typeof e!="object")return null;const t=e,n=t.change,r=n&&typeof n=="object"?n:t;return{...t,id:t.id??r.id,change:r}}function X0(e){const t=e,n=t.change;return n&&typeof n=="object"?n:t}function il(e){if(Or(e))return!0;if(e===!1)return!1;if(e===!0||e==null||typeof e!="object")return!0;const t=e;return"success"in t||"failure"in t||"effects"in t?e:t.status!=="rejected"}function nm(e){return!!e&&typeof e=="object"&&e.success===!0}function zo(e){return!(e===!1||e&&typeof e=="object"&&e.success===!1)}function yu(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Q0(e){const t=[],n=r=>{if(!r||typeof r!="object")return;const o=r;if(Array.isArray(o.runs)&&t.push(o),Array.isArray(o.rows))for(const i of o.rows){const s=i?.cells;if(Array.isArray(s))for(const a of s){const l=a;if(Array.isArray(l?.blocks))for(const u of l.blocks)n(u);l?.paragraph&&n(l.paragraph)}}};if(Array.isArray(e))for(const r of e)n(r);return t}function rc(e,t){return e.sourceAnchor?.sourceNodeId===t?!0:e.id===t}function hi(e){let t=!1,n=null,r=null,o=null;for(const i of e)t=i,!zo(i)&&n===null&&(n=i),nm(i)&&(o=i),i!==!1&&(r=i);return n??o??r??t}function IH(e){const t=e?.anchor,n=t?.start,r=t?.end;return typeof n?.blockId!="string"||typeof r?.blockId!="string"||n.blockId!==r.blockId||typeof n.offset!="number"||typeof r.offset!="number"?null:{kind:"selection",start:{kind:"text",blockId:n.blockId,offset:n.offset},end:{kind:"text",blockId:r.blockId,offset:r.offset}}}function EH(e){return e.startsWith("#")?{kind:"anchor",anchor:e.slice(1)}:{kind:"external",url:e}}function rm(e){return fu(e)?.trackDecision??null}function xH(e){return{found:e.length>0,success:e.length>0,rects:e,rect:e[0]}}function sl(e){return{found:!1,success:!1,rects:[],reason:e}}function TH(e,t){if(!t||typeof t.getBoundingClientRect!="function"||e.rects.length===0)return e;let n;try{const o=t.getBoundingClientRect();n={left:o.left,top:o.top}}catch{return e}const r=e.rects.map(o=>({...o,left:o.left-n.left,right:o.right-n.left,top:o.top-n.top,bottom:o.bottom-n.top}));return{...e,rects:r,rect:r[0]}}function RH(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.blockId!="string"||!t.range||typeof t.range!="object")return!1;const n=t.range;return Number.isInteger(n.start)&&Number.isInteger(n.end)&&n.start>=0&&n.start<=n.end}function uA(e){if(!e||e.kind!=="text"||!Array.isArray(e.segments)||e.segments.length===0)return null;const t=Array.from(e.segments);if(!t.every(RH))return null;const n=t[0],r=t[t.length-1],o=e.story;return{kind:"selection",start:{kind:"text",blockId:n.blockId,offset:n.range.start,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end,...o?{story:o}:{}},...o?{story:o}:{}}}function MH(e){return e.selectionTarget?e.selectionTarget:uA(e.target)}function bu(e){if(e.empty)return null;if(e.selectionTarget)return e.selectionTarget;const t=uA(e.target);return t&&t.start.kind==="text"&&t.end.kind==="text"&&t.start.blockId!==t.end.blockId?null:t}function Z0(e){return!e.inline||typeof e.docRoute!="string"?null:e.docRoute.startsWith("format.")?e.docRoute.slice(7):null}var J0={bold:null,italic:null,underline:null,strike:null,color:null,highlight:null,fontFamily:null,fontSize:null,vertAlign:null,smallCaps:null,caps:null,letterSpacing:null,dstrike:null},LH=Object.fromEntries(Object.entries(J0).filter(([e])=>Qz[e]?.tracked===!0));function DH(e,t,n,r){switch(e.kind){case"toggle":{const o=typeof n=="object"&&n!==null&&"value"in n?n.value:n;return typeof o=="boolean"||o===null?{target:t,value:o}:{target:t,value:!r}}case"value-string":{const o=typeof n=="object"&&n!==null&&"value"in n?n.value:n;return o===null?{target:t,value:null}:typeof o!="string"||o.trim()===""?null:{target:t,value:o}}case"value-number":{const o=typeof n=="object"&&n!==null&&"value"in n?n.value:n,i=typeof o=="number"?o:Number(o);return!Number.isFinite(i)||i<=0?null:{target:t,value:i}}case"clear":return{target:t,inline:{...J0}};default:return null}}function PH(e){const t=o=>{if(!o||typeof o!="object")return null;const i=o,s=i.rowIndex,a=i.columnIndex;return typeof s!="number"||!Number.isInteger(s)||typeof a!="number"||!Number.isInteger(a)?null:{rowIndex:s,columnIndex:a}};if(!e)return null;const n=t(e.start),r=t(e.end);return!n||!r?null:{start:n,end:r}}function OH(e,t){const{tableNodeId:n,rowIndex:r,columnIndex:o,cellNodeId:i,mergeRange:s}=t;switch(e){case"insert-row-before":return{nodeId:n,rowIndex:r,position:"above"};case"insert-row-after":return{nodeId:n,rowIndex:r,position:"below"};case"delete-row":return{nodeId:n,rowIndex:r};case"insert-column-before":return{nodeId:n,columnIndex:o,position:"left"};case"insert-column-after":return{nodeId:n,columnIndex:o,position:"right"};case"delete-column":return{nodeId:n,columnIndex:o};case"delete-table":return{nodeId:n};case"merge-cells":{const a=s??{start:{rowIndex:r,columnIndex:o},end:{rowIndex:r,columnIndex:o}};return{nodeId:n,start:a.start,end:a.end}}case"split-cell":return i?{nodeId:i,rows:1,columns:2}:null;case"remove-borders":return{nodeId:n,mode:"applyTo",applyTo:"all",border:null};default:return null}}function FH(e){const t=e.superdoc,n=new Map,r=new Map;let o=null,i=0;const s=[];let a=null,l=0,u=!1,c=Promise.resolve(),d=null,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:0,pointerSelecting:!1,keyboardSelecting:!1},m=0;const p=new Set;let g={},k="",w=null;const S=()=>{const f=t?.activeEditor;return f&&typeof f=="object"?f:null},y=()=>{const f=S()?.doc;return f&&typeof f=="object"?f:null},C=()=>{const f=S()?.v2TrackedChanges;return f&&typeof f=="object"?f:null},T=()=>{const f=S()?.host;return f&&typeof f=="object"?f:null},R=f=>{if(f.storyType!=="headerFooterPart"||typeof f.refId!="string")return null;const v=S(),b=T(),A=v?.pageLayout??b?.pageLayout;if(!A||typeof A!="object")return null;const E=A.getActiveRulerContext,U=b?.resolveHeaderFooterEditTarget;if(typeof E!="function"||typeof U!="function")return null;const Y=xt(()=>E.call(A),null);if(!Y||typeof Y.pageIndex!="number")return null;for(const re of["header","footer"]){const ye=xt(()=>U.call(b,{pageIndex:Y.pageIndex,kind:re}),null);if(!(ye?.status!=="ready"||ye.refId!==f.refId||typeof ye.sectionId!="string"||!["default","first","even"].includes(String(ye.slotVariant))))return{kind:"story",storyType:"headerFooterSlot",section:{kind:"section",sectionId:ye.sectionId},headerFooterKind:re,variant:ye.slotVariant}}return null},M=()=>{const f=T(),v=f?.getPendingInlineFormat;if(typeof v!="function")return null;const b=xt(()=>v.call(f),null);return b&&typeof b=="object"?b:null},H=f=>{const v=Z0(f);if(!v)return null;const b=M();if(!b||!(v in b))return null;const A=b[v];return f.inline?.kind==="toggle"?A===!0:A!=null&&A!==""},B=f=>{const v=Z0(f);if(!v)return;const b=M();if(!b||!(v in b))return;const A=b[v];if(typeof A=="string"&&A!=="")return A;if(typeof A=="number"&&Number.isFinite(A))return String(A)},z=(f,v)=>{const b=T(),A=b?.setPendingInlineFormat;typeof A=="function"&&xt(()=>A.call(b,f,v),void 0)},Z=f=>{const v=T(),b=v?.clearPendingInlineFormat;typeof b=="function"&&xt(()=>b.call(v,f),void 0)},P=new Set(["bold","italic","underline","strikethrough"]),N=f=>{const v=M();if(!v)return;const b=Array.isArray(f.activeMarks)?f.activeMarks:[];let A=null;for(const E of Object.keys(v)){const U=v[E];let Y;if(P.has(E))Y=b.includes(E)===(U===!0);else if(K0(E)){if(U==null)continue;A||(A=Ms(f)),Y=A[E]===U}else Y=!1;Y&&Z(E)}},I=()=>{const f=S()?.editCommands;return f&&typeof f=="object"?f:null},L=f=>{const v=I();if(!v||typeof v.getSnapshot!="function")return null;const b=xt(()=>v.getSnapshot(),null)?.commands?.[f];return b&&typeof b=="object"?b:null},X=()=>L("lists.apply"),te=f=>{const v=f?.value?.seed;return v==="bullet"||v==="ordered"?v:null},le=f=>{const v=vH[f];return v?L(v):null},fe=()=>{const f=T();if(!f||typeof f.getTableContext!="function")return null;const v=xt(()=>f.getTableContext(),null);return v&&typeof v=="object"?v:null},Fe=()=>{const f=fe();if(!f||f.inTable!==!0)return null;const v=f.table,b=typeof v?.nodeId=="string"&&v.nodeId.length>0?v.nodeId:null;if(!b)return null;const A=f.row,E=f.column,U=f.cell,Y=typeof A?.index=="number"&&Number.isInteger(A.index)?A.index:null,re=typeof E?.index=="number"&&Number.isInteger(E.index)?E.index:null;if(Y==null||re==null)return null;const ye=typeof U?.nodeId=="string"&&U.nodeId.length>0?U.nodeId:null,Re=f.cellRange;return{tableNodeId:b,rowIndex:Y,columnIndex:re,cellNodeId:ye,mergeRange:PH(Re)}},he=new Map;let ge=null,ae=null,Ce=0,oe=0,xe=0;const qe=new Set,et=(f,v)=>f===v?!0:!f||!v?!1:f.id===v.id&&f.paintedEntityId===v.paintedEntityId&&no(f.story)===no(v.story),kt=f=>Array.from(qe).some(v=>et(v,f)),Ie=f=>{const v=T();if(typeof v?.getHandles!="function")return;const b=xt(()=>v.getHandles(),null),A=b?.review;if(A){if(f){if(typeof A.setActiveReviewTarget!="function")return;const E=b?.layout;xt(()=>A.setActiveReviewTarget({entityType:"trackedChange",entityId:f.id,...f.paintedEntityId?{paintedEntityId:f.paintedEntityId}:{},origin:"panel",layoutEpoch:typeof E?.generation=="number"?E.generation:0,story:f.story??{kind:"story",storyType:"body"}}),null);return}typeof A.getActiveReviewTarget!="function"||typeof A.clearActiveReviewTarget!="function"||xt(()=>A.getActiveReviewTarget(),null)?.entityType==="trackedChange"&&xt(()=>A.clearActiveReviewTarget(),void 0)}},ze=(f,v)=>{ae=f,Ce+=1,xe+=1,v?.invalidateQueuedNavigation!==!1&&(oe+=1)},Ve=new Set;let Q=!1,_=null;const $=new Map,F=new Set;let j=null,V=null,G=!1,J=null,K=0,W=null,ue=null,be=null;const we=()=>{if(G||Q)return;G=!0;const f=()=>{G=!1,Q||qt()};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Te=250,rt=5e3,nt=f=>{Q||J&&K<=f||(J&&clearTimeout(J),K=f,J=setTimeout(()=>{J=null,K=0,Q||qt()},Math.max(0,f-Date.now())))},wt=new WeakMap;let Zt=0;const Ct=f=>{if(!f)return"none";let v=wt.get(f);return v==null&&(v=Zt+=1,wt.set(f,v)),`e${v}`};let Ot=0,Bt={},on=null,Fn=null,Vt=0;const We=()=>{Fn&&clearTimeout(Fn),Fn=null,Vt=0};let St=f=>{},Nt=null,cn=new Set,Dt=0,un=null;const Ft=()=>`${Ct(S())}|m${Ot}`,Me=()=>{Nt=null,cn=new Set},Pe=f=>{for(const v of["trackChanges","trackChanges:all"]){const b=$.get(v);if(!b?.hasSettled||!Array.isArray(b.value))continue;const A=b.value.filter(E=>{const U=Un(E);return!U||!f.has(U)});A.length!==b.value.length&&$.set(v,{...b,value:A})}},Ze=f=>{const v=()=>{if(!Q)for(const U of[...Ve])U(ht)},b=yu(f)?f:null,A=S()?.documentMutationReadiness,E=()=>{const U=globalThis.requestAnimationFrame;return typeof U!="function"?Promise.resolve():new Promise(Y=>{let re=!1;const ye=()=>{re||(re=!0,clearTimeout(Re),Y())},Re=setTimeout(ye,250);U(()=>U(()=>setTimeout(ye,0)))})};if(b?.success===!0&&typeof b.txId=="string"&&b.txId.length>0&&typeof A?.whenPainted=="function")try{Promise.resolve(A.whenPainted.call(A,b)).then(E,()=>{}).then(v,v);return}catch{}v()},ot=(f,v)=>{const b=ht.trackChanges,A=b.items.filter(Y=>{const re=Un(Y);return!re||!f.has(re)});if(A.length===b.items.length)return;ae&&f.has(ae.id)&&ze(null);const E=new Set;for(const Y of A){const re=X0(Y),ye=Y,Re=re.author??re.authorEmail??ye.author??ye.authorEmail;typeof Re=="string"&&E.add(Re)}const U=b.items.length-A.length;ht={...ht,trackChanges:{...b,items:A,total:Math.max(A.length,b.total-U),activeId:b.activeId&&f.has(b.activeId)?null:b.activeId,authors:[...E]}},Ze(v)},Mt=(f,v)=>{if(f.size===0)return;const b=Ft(),A=Nt===b?cn:new Set,E=new Set([...f].filter(U=>!A.has(U)));E.size!==0&&(Nt=b,cn=new Set([...A,...E]),Pe(cn),ot(E,v))},Et=f=>Nt===f&&cn.size>0?cn:null,sn=(f,v=[])=>{const b=f.map(nc).filter(E=>E!=null&&Un(E)!=null);if(b.length===0)return;const A=v.map(nc).map(E=>E==null?null:Un(E)).filter(E=>E!=null);for(const E of["trackChanges","trackChanges:all"]){const U=$.get(E),Y=U?.hasSettled&&Array.isArray(U.value)?[...U.value]:[],re=new Set;let ye=!1;for(const Re of b){const Ue=Un(Re);if(!Ue)continue;const Ye=Y.findIndex(De=>Un(De)===Ue);if(Ye<0)Y.push(Re),re.add(Ue);else{const De=Y[Ye];Y[Ye]=yu(De)?{...De,...Re}:Re}ye=!0}if(E==="trackChanges"&&re.size>0&&A.length>0){const Re=new Set(A.filter(De=>re.has(De))),Ue=new Map(Y.filter(De=>Re.has(Un(De)??"")).map(De=>[Un(De),De])),Ye=Y.filter(De=>!Re.has(Un(De)??""));for(const[De,Ke]of A.entries()){if(!Re.has(Ke))continue;const Be=Ue.get(Ke);if(!Be)continue;const He=A.slice(De+1).map($e=>Ye.findIndex(Je=>Un(Je)===$e)).find($e=>$e>=0);if(He!=null){Ye.splice(He,0,Be);continue}const je=A.slice(0,De).reverse().map($e=>Ye.findIndex(Je=>Un(Je)===$e)).find($e=>$e>=0);Ye.splice(je==null?Ye.length:je+1,0,Be)}Y.splice(0,Y.length,...Ye)}ye&&$.set(E,{token:U?.token??null,value:Y,hasSettled:!0,inflightToken:null})}},Tt=f=>{const v=Ft(),b=Et(v),A=f.map(nc).filter(E=>{if(E==null)return!1;const U=Un(E);return U!=null&&!b?.has(U)});for(const E of["trackChanges","trackChanges:all"])$.set(E,{token:v,value:[...A],hasSettled:!0,inflightToken:null})},ur=async(f,v)=>{try{const b=f.v2TrackedChanges?.listTrackedChanges;if(typeof b=="function"){const U=await Promise.resolve(b.call(f.v2TrackedChanges,{mode:v.trackedChangesListMode,refreshReason:v.refreshReason,blocking:v.blocking,...v.targetIds?.length?{targetIds:v.targetIds}:{}})),Y=v.trackedChangesListMode==="all"&&v.refreshReason==="mutation-history-render-reconcile"?U?.ok===!0:U?.ok!==!1;return{ok:Y,items:Y&&Array.isArray(U?.items)?U.items:[],...typeof U?.complete=="boolean"?{complete:U.complete}:{},...typeof U?.sourceCoverageComplete=="boolean"?{sourceCoverageComplete:U.sourceCoverageComplete}:{}}}const A=f.docTrackChanges?.list;if(typeof A!="function")return{ok:!1,items:[]};const E=await Promise.resolve(A.call(f.docTrackChanges));return{ok:!0,items:Array.isArray(E?.items)?E.items:[]}}catch(b){return{ok:!1,items:[],failures:[b]}}},dr=k_({getContext:()=>{const f=S();if(!f)return null;const v=C(),b=y()?.trackChanges??null,A=v??b;if(!A)return null;const E=f.documentId??v?.documentId;return{editor:f,adapter:A,documentId:E==null?null:String(E),reconcileToken:Bt,v2TrackedChanges:v,docTrackChanges:b}},reconcile:async(f,v)=>{v.removedIds.size>0&&Mt(new Set(v.removedIds));const b=[...new Set(v.upsertIds)];if(b.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};const A=$.get("trackChanges"),E=A?.hasSettled&&Array.isArray(A.value)?A.value:null,U=new Set(E?E.map(Un).filter(je=>je!=null):[]),Y=E?.length===0&&po()==="complete",re=new Set(b.filter(je=>!U.has(je))),ye=f.v2TrackedChanges?.getTrackedChange,Re=f.docTrackChanges?.get;if(typeof ye!="function"&&typeof Re!="function")return{ok:!1,items:[],resolvedIds:[],unresolvedIds:b};const Ue=await Promise.all(b.map(async je=>{try{if(typeof ye=="function"){const Je=await Promise.resolve(ye.call(f.v2TrackedChanges,je));return{id:je,ok:Je?.ok!==!1,items:Je?.ok!==!1&&Array.isArray(Je?.items)?Je.items:[],result:Je}}const $e=await Promise.resolve(Re.call(f.docTrackChanges,{id:je}));return{id:je,ok:!0,items:$e&&typeof $e=="object"?[$e]:[],result:$e}}catch($e){return{id:je,ok:!1,items:[],result:$e}}})),Ye=[],De=[],Ke=[];for(const je of Ue){const $e=je.items.filter(Je=>{const Lt=nc(Je);return Lt!=null&&Un(Lt)===je.id});je.ok&&$e.length>0?(Ye.push(...$e),De.push(je.id)):Ke.push(je.id)}let Be;const He=De.filter(je=>re.has(je));if(He.length>0&&!Y){const je=await ur(f,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1,targetIds:He});je.ok&&(Be=je.items)}return{ok:Ke.length===0,items:Ye,orderedItems:Be,resolvedIds:De,unresolvedIds:Ke,failures:Ue.filter(je=>!je.ok).map(je=>je.result)}},hydrate:ur,onReconciled:(f,v,b)=>{if(b?.reconcileMode==="authoritative"){if(f.reconcileToken!==Bt)return;b.ok===!0&&b.complete===!0&&b.sourceCoverageComplete===!0?(We(),Tt(b.items??[]),on=null):b.ok===!0?(We(),sn(b.items??[])):St(f.reconcileToken),qt();return}sn((b?.items??[]).filter(A=>{const E=nc(A),U=E==null?null:Un(E);return U!=null&&v.has(U)}),b?.orderedItems??b?.items??[]),qt()}});St=f=>{if(Q||Fn)return;const v=Math.min(Te*2**Vt,rt);Vt+=1,Fn=setTimeout(()=>{Fn=null,!(Q||on===null||f!==Bt)&&dr.onRender(!0)},v)};const jr=()=>`${Ft()}|m${jn()}|s${Dt}`,$t=f=>JSON.stringify({t:f.target??null,s:f.selectionTarget??null}),Vn=["contentControls:inRange:","query:","effInline:"],Mr=120,_r=180,po=()=>{const f=T(),v=f?.getDocumentLoadingSnapshot;if(typeof v!="function")return"unknown";const b=xt(()=>v.call(f),null)?.sourceStage;return b==="opening"||b==="ready-window"||b==="source-loading"?"loading":b==="source-complete"||b==="source-failed"||b==="source-cancelled"?"complete":"unknown"},Kt=new Map,yn=f=>{const v=Ft();Kt.get(f)!==v&&(Kt.set(f,v),we())},xo=()=>{const f=$.get("comments");return f?.hasSettled?Array.isArray(f.value)&&f.value.length>0:f?.inflightToken!=null},Zo=(f,v)=>Kt.get(f)===v,Ei=f=>{yn("contentControls")},pi=()=>{const f=$.get("trackChanges");f?.hasSettled||f?.inflightToken!=null||yn("trackChanges")},Ss=6500,ks=8e3,As=250;let al=0,Wi=0,ro=!1,ke=0,Oe=!1,ft=null;const lt=()=>{if(Q||ft)return;const f=ke||Date.now(),v=()=>{if(ft=null,Q)return;const b=Date.now()-al,A=go()||b<Ss;if(A&&Date.now()-f<ks){ft=setTimeout(v,As);return}ro=!1,Oe=A;try{qt()}finally{Oe=!1,ke=0}};ft=setTimeout(v,0)};let bn=null,an=null;const Fr=()=>{const f=T();if(!f||bn===f)return;an&&(an(),an=null),bn=f;const v=f.subscribeDocumentLoading;if(typeof v!="function"){bn=null,To(Ss);return}try{const b=U=>{const Y=U?.sourceStage;(Y==="source-complete"||Y==="source-failed"||Y==="source-cancelled")&<()},A=v.call(f,b);typeof A=="function"&&(an=A);const E=f.getDocumentLoadingSnapshot;typeof E=="function"&&b(xt(()=>E.call(f),null))}catch{bn=null,To(Ss)}},mo=()=>{const f=S()?.host,v=f?.getForegroundMutationState;if(typeof v!="function")return null;const b=xt(()=>v.call(f),null);return{active:typeof b?.active=="number"?b.active:0,pending:typeof b?.pending=="number"?b.pending:0}},go=()=>{const f=mo();return!!(f&&(f.active>0||f.pending>0))},To=(f=Mr)=>{Q||W||(W=setTimeout(()=>{if(W=null,Q)return;if(ue&&go()){To(),qt();return}const v=ue;ue=null,v===jr()&&oc("selection",v,fl,Yi),qt()},f))},Is=(f,v)=>{if(!mo())return!1;const b=`${f}\0${v}`;return F.has(b)?!1:(F.add(b),To(_r),!0)},Jo=f=>{if(j==null||f===j)return V?.timer&&clearTimeout(V.timer),V=null,j=f,!1;if(V?.key===f)return V.ready?(V=null,j=f,!1):!0;V?.timer&&clearTimeout(V.timer);const v={key:f,ready:!1,timer:null};return v.timer=setTimeout(()=>{Q||V!==v||(v.timer=null,v.ready=!0,qt())},_r),V=v,!0},Ro=f=>A_(f),Ki=()=>{mi(),qt()};let Gr=null,Sr=!1,Mo=0;const Ho=()=>{Gr=null,Sr=!1,Mo+=1},$o=()=>{const f=S(),v=f?.documentMutationReadiness;if(!f||typeof v?.whenPainted!="function"||(Gr={editor:f,readiness:v,afterEpoch:typeof v.getRenderEpoch=="function"?xt(()=>v.getRenderEpoch.call(v),null):null},Sr))return;Sr=!0;const b=Mo;(async()=>{for(;!Q&&b===Mo;){const E=Gr;if(Gr=null,!E){Sr=!1;return}let U=!1;try{await E.readiness.whenPainted.call(E.readiness,typeof E.afterEpoch=="number"?{afterEpoch:E.afterEpoch}:void 0),U=!0}catch{}if(Q||b!==Mo)return;if(S()!==E.editor){Ho();return}U&&Ki()}})()},ll=()=>{be&&clearTimeout(be),be=setTimeout(()=>{be=null,Q||Ki()},500)},oc=(f,v,b,A)=>{let E;try{E=b()}catch{E=void 0}if(!Or(E)){const re={token:v,value:A(E),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0};return $.set(f,re),re}const U=$.get(f),Y=U?.failedToken===v;return $.set(f,{token:U?.token??null,value:U?.value??null,hasSettled:U?.hasSettled??!1,inflightToken:v,failedToken:Y?v:null,failureCount:Y?U.failureCount??0:0,retryAtMs:0}),Promise.resolve(E).then(re=>{const ye=$.get(f);!ye||ye.inflightToken!==v||($.set(f,{token:v,value:A(re),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0}),we())},()=>{const re=$.get(f);if(!re||re.inflightToken!==v)return;const ye=re.failedToken===v?(re.failureCount??0)+1:1,Re=Math.min(rt,Te*2**Math.min(ye-1,8)),Ue=Date.now()+Re;$.set(f,{...re,inflightToken:null,failedToken:v,failureCount:ye,retryAtMs:Ue}),nt(Ue)}),null},kr=(f,v,b,A)=>{const E=$.get(f);if(E&&E.token===v&&E.hasSettled)return{value:E.value,status:"ready"};if(iH(f)&&!Zo(f,v)){if(po()==="loading")return ro=!0,Fr(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(ro&&!Oe)return lt(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!Oe){const Y=Date.now();if(Y-Wi<Ss&&(!ke||Y-ke<ks))return ke||(ke=Y),ro=!0,lt(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};ke=0}}if(go())return To(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(E?.failedToken===v&&E.inflightToken==null&&(E.retryAtMs??0)>Date.now())return nt(E.retryAtMs),E.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!E&&f.startsWith("effInline:")&&Jo(f))return{value:null,status:"pending"};if(!E&&Is(f,v))return{value:null,status:"pending"};if(!E||E.inflightToken!==v){const Y=oc(f,v,b,A);if(Y)return{value:Y.value,status:"ready"}}const U=$.get(f);return U?.hasSettled?{value:U.value,status:"stale"}:{value:null,status:"pending"}},Uo=f=>{for(const v of $.keys())f(v)&&$.delete(v)},xi=f=>{const v=$t(f),b=aA(f);return new Set([`contentControls:inRange:${v}`,`query:${v}`,...b?[`effInline:${b}`]:[]])},cl=f=>{const v=xi(f);Uo(b=>Vn.some(A=>b.startsWith(A))&&!v.has(b));for(const b of F){const A=b.split("\0",1)[0];Vn.some(E=>A.startsWith(E))&&!v.has(A)&&F.delete(b)}},qi=()=>{const f=S();f!==un&&(Ho(),dr.reset(),Bt={},un=f,$.clear(),on=null,We(),J&&clearTimeout(J),J=null,K=0,V?.timer&&clearTimeout(V.timer),V=null,j=null,w=null,o=null,ue=null,F.clear(),Kt.clear(),ro=!1,ke=0,an&&an(),an=null,bn=null,Me())},mi=()=>{const f=on!==null;Ot+=1,f&&(on=Ft()),Me()},Rf=f=>{if(typeof f!="string"||f.length===0)return cr("insertText requires a non-empty string.","INVALID_INPUT");if(jn()==="viewing")return cr("The document is read-only.","DOCUMENT_READONLY");const v=y(),b=v?.insert;if(!v||typeof b!="function")return cr("insert is unavailable.");const A=v.selection?.current;if(typeof A!="function")return cr("selection.current is unavailable.");const E=Y=>{const re=Y&&typeof Y=="object"?Y:null,ye=re?.selectionTarget??re?.target??null;return!ye||typeof ye!="object"?cr("insertText requires a live selection target.","PRECONDITION_FAILED"):xt(()=>Aa(b.call(v,{type:"text",value:f,target:ye}),cr("insert failed.")),cr("insert failed."))};let U;try{U=A.call(v.selection)}catch{return cr("insertText could not resolve the live selection.","PRECONDITION_FAILED")}return Or(U)?Promise.resolve(U).then(E,()=>cr("insertText could not resolve the live selection.","PRECONDITION_FAILED")):E(U)},ei=(f,v)=>({payload:f,state:ht,editor:S(),superdoc:t,context:v,ui:_,execute:(b,A)=>gc(b,A),executeAsync:(b,A)=>mm(b,A),doc:y(),selection:ht.selection,documentMode:jn(),insertText:Rf}),ul=f=>f==="editing"||f==="suggesting"||f==="viewing"?f:null,jn=()=>{const f=S(),v=t&&typeof t=="object"?t:null,b=ul(v?.config?.documentMode),A=ul(xt(typeof v?.getActiveRuntime=="function"?()=>{const U=v.getActiveRuntime();return typeof U?.getSnapshot=="function"?U.getSnapshot():null}:void 0,null)?.documentMode),E=ul(f?.options?.documentMode);return b&&A&&b!==A?b:A??b??E},ic=()=>{const f=t&&typeof t=="object"?t:null,v=f?.interactionConfig?.comments;if(v&&typeof v.readOnly=="boolean")return v.readOnly===!0;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.readOnly===!0},wu=()=>{const f=t&&typeof t=="object"?t:null,v=f?.interactionConfig?.comments;if(v&&typeof v.allowResolve=="boolean")return v.allowResolve===!1;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.allowResolve===!1},ba=()=>jn()==="viewing"||ic(),Yi=f=>f&&typeof f=="object"?f:null,Es=(f,v)=>{if(!f)return{...nH,status:v};const b=f.target??null,A=typeof f.text=="string"?f.text:"";return{status:v,empty:f.empty===!0,target:b,selectionTarget:f.selectionTarget??null,activeMarks:Array.isArray(f.activeMarks)?f.activeMarks:[],activeCommentIds:Array.isArray(f.activeCommentIds)?f.activeCommentIds:[],activeChangeIds:Array.isArray(f.activeChangeIds)?f.activeChangeIds:[],quotedText:A}},dl=()=>{const f=y()?.selection;return kr("selection",jr(),()=>f?.current?f.current({includeText:!0}):void 0,Yi)},Cu=()=>{const{value:f,status:v}=dl();return Es(f,v)},fl=()=>{const f=y()?.selection;return f?.current?f.current({includeText:!0}):void 0},_u=f=>{if(f.empty!==!0)return!1;const v=f.selectionTarget,b=v?.start,A=v?.end;return b?.kind==="text"&&A?.kind==="text"&&typeof b.blockId=="string"&&b.blockId===A.blockId&&typeof b.offset=="number"&&b.offset===A.offset},Ti=f=>{const v=T(),b=v?.readLiveSelectionSyncSnapshot;if(typeof b!="function")return;const A=Yi(xt(()=>b.call(v),null));if(!A||!_u(A))return;const E=jr(),U=mo(),Y=!!(U&&(U.active>0||U.pending>0));if(Y)ue=E,To();else if(ue=null,oc("selection",E,fl,Yi))return;const re=$.get("selection"),ye=Array.isArray(A.activeMarks)&&A.activeMarks.length>0?A.activeMarks:Array.isArray(ht.selection.activeMarks)?ht.selection.activeMarks:[],Re=Array.isArray(A.activeCommentIds)?A.activeCommentIds:[],Ue=uH(f),Ye=ol(ht.selection),De=xf(A.selectionTarget)??xf(A.target),Ke=Ye?.range,Be=De?.range,He=!!(U&&U.active>0&&Ye&&De&&Ye.blockId===De.blockId&&no(Ye.story)===no(De.story)&&typeof Ke?.start=="number"&&typeof Be?.start=="number"&&Math.abs(Be.start-Ke.start)<=2),je=Ue!=null||He?ht.selection.activeChangeIds.filter(Je=>Ue==null||Ef(ht.trackChanges.items).aliasesFor(Je).includes(Ue)):[],$e=Array.isArray(A.activeChangeIds)&&A.activeChangeIds.length>0?A.activeChangeIds:je;$.set("selection",{token:E,value:{...A,activeMarks:ye,activeCommentIds:Re,activeChangeIds:$e},hasSettled:!0,inflightToken:Y?null:re?.inflightToken??null})},xs=async(f=0)=>{const v=y()?.selection,b=v?.current,A=jr();if(typeof b!="function")return $.set("selection",{token:A,value:null,hasSettled:!0,inflightToken:null}),qt(),ht.selection;let E;try{E=b.call(v,{includeText:!0}),Or(E)&&(E=await Promise.resolve(E))}catch{E=null}return Q?Es(null,"pending"):jr()!==A?f<1?xs(f+1):ht.selection:($.set("selection",{token:A,value:Yi(E),hasSettled:!0,inflightToken:null}),qt(),ht.selection)},Mf=f=>{const v=y()?.comments,{value:b,status:A}=kr("comments",Ft(),()=>v?.list?v.list():void 0,re=>re&&Array.isArray(re.items)?re.items:[]),E=b??[],U=f.activeCommentIds;ge&&!E.some(re=>Un(re)===ge)&&(ge=null);const Y=ge??U[0]??null;return{status:mu(A,f.status),listStatus:A,items:E,total:E.length,activeIds:U,activeId:Y}},Ts=()=>{const f=y()?.trackChanges,v=Ft(),b=$.get("trackChanges:all"),{value:A,status:E}=on===v?{value:b?.hasSettled?b.value:null,status:b?.hasSettled?"stale":"pending"}:kr("trackChanges:all",v,()=>f?.list?f.list({in:"all"}):void 0,U=>(U&&Array.isArray(U.items)?U.items:[]).map(nc).filter(Y=>Y!=null));return E==="ready"?A:null},hl=f=>{const v=y()?.trackChanges,b=C(),A=typeof b?.listTrackedChanges=="function"?b.listTrackedChanges:null,E=Ft(),U=Et(E),Y=$.get("trackChanges"),{value:re,status:ye}=on===E?{value:Y?.hasSettled?Y.value:null,status:Y?.hasSettled?"stale":"pending"}:kr("trackChanges",E,()=>A?A.call(b):v?.list?v.list():void 0,He=>He&&Array.isArray(He.items)?He.items.filter(je=>!A||no(em(je))==="story:body"):[]),Re=(re??[]).map(nc).filter(He=>He!=null).filter(He=>{const je=Un(He);return!je||!U?.has(je)}),Ue=new Set;for(const He of Re){const je=X0(He),$e=He,Je=je.author??je.authorEmail??$e.author??$e.authorEmail;typeof Je=="string"&&Ue.add(Je)}const Ye=v?.list?Ts():null,De=ae;De&&(De.story?Ye&&!Ye.some(He=>rl(He,De.id,De.story))&&ze(null):Re.some(He=>Un(He)===De.id)||ze(null));const Ke=U?f.activeChangeIds.filter(He=>!U.has(He)):f.activeChangeIds,Be=ae?.id??Ke[0]??null;return{status:mu(ye,f.status),items:Re,total:Re.length,activeId:Be,authors:[...Ue]}},Lo=f=>{const v=y()?.contentControls,{value:b,status:A}=kr("contentControls",Ft(),()=>v?.list?v.list():void 0,re=>re&&Array.isArray(re.items)?re.items:[]),E=b??[],{ids:U,status:Y}=Su(v,f);return{status:mu(A,Y,f.status),items:E,total:E.length,activeId:U[0]??null,activeIds:U}},ti=(f,v)=>{if(!f||typeof f.listInRange!="function")return{lockModesById:new Map,status:"ready"};const b=hH(v);if(!b)return{lockModesById:new Map,status:"ready"};const{value:A,status:E}=kr(`contentControls:inRange:${$t(v)}`,Ft(),()=>f.listInRange(b),re=>re&&Array.isArray(re.items)?re.items:[]),U=A??[],Y=new Map;for(const re of U)typeof re?.id=="string"&&Y.set(re.id,typeof re.lockMode=="string"?re.lockMode:"unlocked");return{lockModesById:Y,status:E}},Su=(f,v)=>{const{lockModesById:b,status:A}=ti(f,v);return{ids:[...b.keys()],status:A}},ku=()=>{const f=t?.fonts;return{options:UH(zH(xt(f?.getDocumentFontOptions?()=>f.getDocumentFontOptions():void 0,[])),HH(xt(f?.getFontFamilyOptions?()=>f.getFontFamilyOptions():void 0,[]))),sizeOptions:VH}},ni=()=>{const f=xt(t?.getZoomState?()=>t.getZoomState():void 0,null),v=typeof f?.value=="number"?f.value:100,b=f?.mode;return{mode:b==="manual"||b==="fit-width"?b:b==="fixed"?"manual":null,value:v,min:typeof f?.min=="number"?f.min:10,max:typeof f?.max=="number"?f.max:100}},Rs=()=>xt(t?.getMeasurementUnit?()=>t.getMeasurementUnit():void 0,"in")==="cm"?"cm":"in",pl=()=>{const f=S();return{ready:f!=null,mode:jn(),dirty:f?!!f.isDirty:!1}},wa=f=>{const v=f.quotedText;if(typeof v!="string"||v.length===0)return null;const b=vu(f);if(b.length===0||!tc(b.map(U=>U.blockId)))return null;const A=f.target,E=b.length===1?ho(b[0].blockId,A?.story):void 0;return{select:{type:"text",pattern:v,mode:"contains",caseSensitive:!0},...E?{within:E}:{},require:"any"}},ml=f=>{const v=y()?.query;if(typeof v?.match!="function")return null;const b=wa(f);if(!b)return null;const{value:A}=kr(`query:${$t(f)}`,Ft(),()=>v.match(b),E=>E&&typeof E=="object"?E:null);return lA(A,f)},Xi=f=>{const v=T(),b=new Set(Rr(f));if(b.size===0)return{};const A=v?.readMountedProjectionBlocksByIds,E=v?.readMountedProjectionBlocks;if(typeof A!="function"&&typeof E!="function")return{};const U=xt(()=>{if(typeof A!="function")return E.call(v);const He=_s(f);return He?A.call(v,[...b],He):A.call(v,[...b])},null);if(!Array.isArray(U))return{};const Y=Q0(U),re=He=>{const je={},$e=q0(He.fontFamily);$e&&(je.fontFamily=$e);const Je=kH(He.fontSize);return Je&&(je.fontSize=Je),typeof He.color=="string"&&He.color.trim()!==""&&(je.color=He.color.trim().toUpperCase()),typeof He.highlight=="string"&&He.highlight.trim()!==""&&(je.highlight=He.highlight.trim().toUpperCase()),je},ye=ol(f),Re=ye&&typeof ye.range?.start=="number"?ye.range.start:null;if(ye&&Re!==null&&b.has(ye.blockId)){const He=Y.find($e=>rc($e,ye.blockId)),je=He&&Array.isArray(He.runs)?He.runs:null;if(je&&je.length>0&&je.every($e=>$e?.kind==="text"||$e?.kind==="tab")){let $e=0,Je=null;for(const Lt of je){const Yt=typeof Lt.text=="string"?Lt.text.length:0;if(Re>=$e&&Re<$e+Yt){Je=Lt;break}$e+=Yt}if(!Je){for(let Lt=je.length-1;Lt>=0&&!Je;Lt-=1)je[Lt]?.kind==="text"&&(Je=je[Lt]);Je??=je[je.length-1]??null}return Je?re(Je):{}}}const Ue=vu(f);if(Ue.length>0){const He=new Set,je=new Set;let $e=!1,Je=!0;for(const Lt of Ue){const Yt=Y.find(Yr=>rc(Yr,Lt.blockId));if(!Yt)return{};const zn=Array.isArray(Yt.runs)?Yt.runs:[];if(zn.length===0)continue;if(!zn.every(Yr=>Yr?.kind==="text"||Yr?.kind==="tab")){Je=!1;break}let qn=0;for(const Yr of zn){const Nr=typeof Yr.text=="string"?Yr.text.length:0,Lr=qn,Ar=qn+Nr;if(Lr<Lt.end&&Ar>Lt.start){$e=!0;const jo=re(Yr);jo.fontFamily&&He.add(jo.fontFamily),jo.fontSize&&je.add(jo.fontSize)}qn=Ar}}if(Je&&$e){const Lt={};return He.size===1&&(Lt.fontFamily=[...He][0]),je.size===1&&(Lt.fontSize=[...je][0]),Lt}}const Ye=new Set,De=new Set;let Ke=!1;for(const He of Y){if(![...b].some($e=>rc(He,$e)))continue;const je=Array.isArray(He.runs)?He.runs:[];for(const $e of je){if($e?.kind!=="text")continue;Ke=!0;const Je=re($e);Je.fontFamily&&Ye.add(Je.fontFamily),Je.fontSize&&De.add(Je.fontSize)}}if(!Ke)return{};const Be={};return Ye.size===1&&(Be.fontFamily=[...Ye][0]),De.size===1&&(Be.fontSize=[...De][0]),Be},sc=f=>{const v=T(),b=new Set(Rr(f));if(b.size===0)return{};const A=v?.readMountedProjectionBlocksByIds,E=v?.readMountedProjectionBlocks;if(typeof A!="function"&&typeof E!="function")return{};const U=xt(()=>{if(typeof A!="function")return E.call(v);const Be=_s(f);return Be?A.call(v,[...b],Be):A.call(v,[...b])},null);if(!Array.isArray(U))return{};const Y=Q0(U),re=Be=>({bold:Be.bold===!0,italic:Be.italic===!0,underline:Be.underline!=null,strikethrough:Be.strike===!0}),ye=Be=>{const He={};for(const je of Tf){const $e=Be[je];$e.size===1&&(He[je]=[...$e][0])}return He},Re=ol(f),Ue=Re&&typeof Re.range?.start=="number"?Re.range.start:null;if(Re&&Ue!==null&&b.has(Re.blockId)){const Be=Y.find(je=>rc(je,Re.blockId)),He=Be&&Array.isArray(Be.runs)?Be.runs:null;if(He&&He.length>0&&He.every(je=>je?.kind==="text"||je?.kind==="tab")){let je=0,$e=null;for(const Je of He){const Lt=typeof Je.text=="string"?Je.text.length:0;if(Ue>=je&&Ue<je+Lt){$e=Je;break}je+=Lt}if(!$e){for(let Je=He.length-1;Je>=0&&!$e;Je-=1)He[Je]?.kind==="text"&&($e=He[Je]);$e??=He[He.length-1]??null}return $e?re($e):{}}}const Ye=vu(f);if(Ye.length>0){const Be={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let He=!1,je=!0;for(const $e of Ye){const Je=Y.find(zn=>rc(zn,$e.blockId));if(!Je)return{};const Lt=Array.isArray(Je.runs)?Je.runs:[];if(Lt.length===0)continue;if(!Lt.every(zn=>zn?.kind==="text"||zn?.kind==="tab")){je=!1;break}let Yt=0;for(const zn of Lt){const qn=typeof zn.text=="string"?zn.text.length:0,Yr=Yt,Nr=Yt+qn;if(Yr<$e.end&&Nr>$e.start){He=!0;const Lr=re(zn);for(const Ar of Tf)Be[Ar].add(Lr[Ar])}Yt=Nr}}if(je&&He)return ye(Be)}const De={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Ke=!1;for(const Be of Y){if(![...b].some(je=>rc(Be,je)))continue;const He=Array.isArray(Be.runs)?Be.runs:[];for(const je of He){if(je?.kind!=="text")continue;Ke=!0;const $e=re(je);for(const Je of Tf)De[Je].add($e[Je])}}return Ke?ye(De):{}},ac=(f,v)=>{if(v.fontFamily!==void 0&&v.fontSize!==void 0&&v.color!==void 0&&v.highlight!==void 0)return{values:v,effectiveUniformityStatus:"ready"};const b=Xi(f),A={...b.fontFamily!==void 0?{fontFamily:b.fontFamily}:{},...b.fontSize!==void 0?{fontSize:b.fontSize}:{},...b.color!==void 0?{color:b.color}:{},...b.highlight!==void 0?{highlight:b.highlight}:{},...v};if(!f.empty&&(A.fontFamily===void 0||A.fontSize===void 0)){const E=Lf(f);return E.values&&(A.fontFamily===void 0&&E.values.fontFamily!==void 0&&(A.fontFamily=E.values.fontFamily),A.fontSize===void 0&&E.values.fontSize!==void 0&&(A.fontSize=E.values.fontSize)),{values:A,effectiveUniformityStatus:E.status}}return{values:A,effectiveUniformityStatus:"ready"}},lc=["fontFamily","fontSize","bold","italic","underline","strikethrough"],Au=f=>{const v=f.selectionTarget;if(!v)return{value:null,status:"ready"};const b=gr(y(),"format.readEffectiveInlineUniformity");return b?kr(`effInline:${aA(f)??$t(f)}`,Ft(),()=>b({target:v,offsetSpace:"selection",keys:lc}),A=>A&&typeof A=="object"?A:null):{value:null,status:"ready"}},Lf=f=>{const{value:v,status:b}=Au(f);if(!v||v.success!==!0)return{values:null,status:b};const A=v.values,E=U=>{const Y=A?.[U];if(!(!Y||Y.state!=="uniform"||typeof Y.value!="string"))return U==="fontFamily"?q0(Y.value):Y.value};return{values:{fontFamily:E("fontFamily"),fontSize:E("fontSize")},status:b}},cc=f=>{const{value:v,status:b}=Au(f);if(!v||v.success!==!0)return{values:null,status:b};const A=v.values,E={};for(const U of Tf){const Y=A?.[U];Y?.state==="uniform"&&(Y.value==="true"||Y.value==="false")&&(E[U]=Y.value==="true")}return{values:E,status:b}},Ca=(f,v)=>{const b=f.activeMark;if(!b||!Tf.includes(b))return null;const A=b,E=sc(v)[A];if(E!==void 0)return E;const{values:U}=cc(v),Y=U?.[A];return Y!==void 0?Y:null},Df=async f=>{const v=f.selectionTarget;if(!v)return null;const b=gr(y(),"format.readEffectiveInlineUniformity");if(!b)return null;try{const A=await Promise.resolve(b({target:v,offsetSpace:"selection"}));return A&&typeof A=="object"&&A.success===!0?A:null}catch{return null}},Iu=(f,v,b)=>{const A=b.values;for(const E of["fontFamily","fontSize"]){if(v[E]!==void 0)continue;const U=A?.[E];U?.state==="uniform"&&typeof U.value=="string"?f[E]=E==="fontFamily"?q0(U.value):U.value:delete f[E]}},uc=f=>ac(f,cA(ml(f),f)),Ms=f=>uc(f).values,Eu=async f=>{const v=y()?.query,b=wa(f);if(typeof v?.match!="function"||!b)return Ms(f);try{const A=await Promise.resolve(v.match(b)),E=cA(lA(A&&typeof A=="object"?A:null,f),f),U=ac(f,E);if(U.effectiveUniformityStatus!=="ready"&&(E.fontFamily===void 0||E.fontSize===void 0)){const Y=await Df(f);Y&&Iu(U.values,E,Y)}return U.values}catch{return Ms(f)}},Ls=async f=>{const v=y();if(v)return typeof v.getNode=="function"?await Promise.resolve(v.getNode(f)):await Promise.resolve(v.getNodeById?.({nodeId:f.nodeId,nodeType:f.nodeType}))},dc=f=>{const v=y()?.query;if(typeof v?.match!="function")return"ready";const b=wa(f);if(!b)return"ready";const{status:A}=kr(`query:${$t(f)}`,Ft(),()=>v.match(b),E=>E&&typeof E=="object"?E:null);return A},xu=f=>{const v=uc(f),b=v.values;if(f.empty)return v;const A=ya(f);return A?f.status==="ready"&&dc(f)==="ready"&&v.effectiveUniformityStatus==="ready"?(w={key:A,values:b},v):w&&w.key===A?{...v,values:{...w.values,...b}}:v:v},Tu=f=>{const v=y(),b=xu(f),A=b.values;f.status==="ready"&&!f.empty&&dc(f)==="ready"&&b.effectiveUniformityStatus==="ready"&&(g=A,k=`${$l(f)}:${Ft()}`);const E=v?.contentControls,{lockModesById:U}=ti(E,f),Y={};for(const re of Bn())Y[re]=fc(re,v,f,A,U);return Y},Qi=f=>f?at.operationUnavailable:S()?at.documentApiUnavailable:at.notReady,Ru=f=>f==="contentLocked"||f==="sdtContentLocked",Zi=f=>{for(const v of f.values())if(Ru(v))return at.contentControlLocked},Pf=(f,v,b,A,E)=>{if(!v)return f.scope==="all"?at.bulkDecisionsDisabled:Qi(E);if(b)return at.documentReadonly;if(f.scope!=="all"&&A.activeChangeIds.length===0)return at.selectionRequired},Mu=f=>{const v=T(),b=xt(typeof v?.getCapabilities=="function"?()=>v.getCapabilities():void 0,null)?.editableSubset?.commands;if(Array.isArray(b))return b.find(A=>A?.command===f||A?.id===f)??null;if(b&&typeof b=="object"){const A=b[f];return A&&typeof A=="object"?A:null}return null},gl=(f,v)=>{if(f.scope!=="all"||typeof v?.[`${f.kind}All`]=="function")return;const b=Mu(`trackedChanges.${f.kind}All`);if(!(b&&(b.status==="supported"||b.enabled===!0)))return at.bulkDecisionsDisabled},fc=(f,v,b,A,E=new Map)=>{if(he.has(f))return tn({supported:!0,enabled:!0,...xt(he.get(f).getState?()=>he.get(f).getState(ei(void 0)):void 0,{})},"custom");const U=jn()==="viewing",Y=Jk(f);if(Y&&typeof I()?.lists?.apply=="function"){const Ke=X(),Be=typeof Ke?.shippedStatus=="string"?Ke.shippedStatus:null,He=Be!=="not-shipped"&&Be!=="disabled";return tn({enabled:He&&(typeof Ke?.enabled=="boolean"?Ke.enabled:!0),active:(He?te(Ke):null)===Y,supported:He,value:Ke?.value},"builtin")}const re=rm(f);if(re){const Ke=v?.trackChanges,Be=typeof Ke?.decide=="function"||typeof Ke?.[re.kind]=="function",He=typeof Ke?.decide=="function"||typeof Ke?.[`${re.kind}All`]=="function",je=re.scope==="all"?He:Be,$e=gl(re,Ke)??Pf(re,je,ba(),b,v);return tn({enabled:$e==null,active:!1,supported:je,reason:$e},"builtin")}if(f==="copy-format")return jn()==="viewing"?tn({supported:!0,enabled:!1,active:!1},"builtin"):S()?tn({supported:!0,enabled:!0,active:h.mode!=="idle"},"builtin"):tn({supported:!0,enabled:!1,active:!1,reason:at.notReady},"builtin");const ye=fu(f);if(!ye)return tn({enabled:!1,active:!1,supported:!1,reason:at.commandUnsupported},"unsupported");if(ye.disposition!=="routed")return tn({enabled:!1,active:!1,supported:!1,reason:ye.reason??at.commandUnsupported},ye.disposition==="unsupported"?"unsupported":"builtin");if(ye.instanceRoute)return vt(ye);if(ye.table)return it(ye,v,U);if(ye.inline?.kind==="clear"){if(ye.mutates&&U)return tn({enabled:!1,active:!1,supported:!0,reason:at.documentReadonly},"builtin");const Ke=Zi(E);if(Ke)return tn({enabled:!1,active:!1,supported:!0,reason:Ke},"builtin");const Be=Rr(b).length>0||bu(b)!=null;return tn({enabled:Be,active:!1,supported:!0,reason:Be?void 0:at.selectionRequired},"builtin")}const Re=ye.docRoute;if(!Re)return tn({enabled:!1,active:!1,supported:!1,reason:at.commandUnsupported},"unsupported");if(gr(v,Re)==null)return tn({enabled:!1,active:!1,supported:!1,reason:Qi(v)},"builtin");const Ue=le(f);if(Ue){const Ke=Ue.shippedStatus,Be=Ke!=="not-shipped"&&Ke!=="disabled",He=typeof Ue.enabled=="boolean"?Ue.enabled:!0,je=f==="undo"||f==="redo",$e=je&&Ue.historyResolved===!1,Je=je&&Be&&He===!1&&Ue.reason===null&&!$e,Lt=Ue.reason===void 0?void 0:Je?at.historyEmpty:$e?at.notReady:V0(Ue.reason,at.commandUnsupported);return ye.mutates&&U?tn({enabled:!1,active:!1,supported:Be,reason:at.documentReadonly},"builtin"):tn({enabled:Be&&He,active:!1,supported:Be,reason:Lt},"builtin")}const Ye=yl(ye,v,b),De=Du(ye,v,b,A);if(ye.list?.mode==="indent"||ye.list?.mode==="outdent")return Qe(ye,v,U,b,Ye,De);if(ye.list?.mode==="toggle-seed")return tt(ye,v,U,b,Ye,De);if(ye.mutates&&U)return tn({enabled:!1,active:Ye,supported:!0,value:De,reason:at.documentReadonly},"builtin");if(ye.inline&&!bu(b)){const Ke=Zi(E);return tn(Ke?{enabled:!1,active:Ye,supported:!0,value:De,reason:Ke}:Rr(b).length>0&&typeof T()?.setPendingInlineFormat=="function"?{enabled:!0,active:Ye,supported:!0,value:De}:{enabled:!1,active:Ye,supported:!0,value:De,reason:at.rangeSelectionRequired},"builtin")}if((ye.blockParagraph||ye.list)&&Rr(b).length===0)return tn({enabled:!1,active:Ye,supported:!0,value:De,reason:at.selectionRequired},"builtin");if(ye.link&&!Ye&&W0(b).length===0&&!ol(b))return tn({enabled:!1,active:Ye,supported:!0,reason:at.rangeSelectionRequired},"builtin");if(ye.inline){const Ke=Zi(E);if(Ke)return tn({enabled:!1,active:Ye,supported:!0,value:De,reason:Ke},"builtin")}return tn({enabled:!0,active:Ye,supported:!0,value:De},"builtin")};function Lu(f,v){const b=f.address?.anchor,A=b?.start,E=b?.end,U=typeof A?.blockId=="string"?A.blockId:null,Y=typeof E?.blockId=="string"?E.blockId:null;if(!U||!Y)return!1;const re=typeof A?.offset=="number"?A.offset:null,ye=typeof E?.offset=="number"?E.offset:null;if(re==null||ye==null)return!1;const Re=v.target,Ue=Re&&Array.isArray(Re.segments)?Re.segments:[];for(const Ye of Ue){const De=typeof Ye?.blockId=="string"?Ye.blockId:null;if(!De)continue;const Ke=Ye.range,Be=typeof Ke?.start=="number"?Ke.start:null,He=typeof Ke?.end=="number"?Ke.end:null;if(!(Be==null||He==null)){if(U!==Y){if(De===U&&He>re||De===Y&&Be<ye)return!0;continue}if(De===U){if(Be===He){if(Be>=re&&Be<=ye)return!0;continue}if(Math.max(Be,re)<Math.min(He,ye))return!0}}}return!1}const vl=(f,v)=>{const b=f?.hyperlinks;if(!b||typeof b.list!="function")return null;const A=Rr(v);if(!tc(A))return null;for(const E of A){const U={kind:"block",nodeType:"paragraph",nodeId:E},{value:Y}=kr(`hyperlinks:${E}`,Ft(),()=>b.list({within:U}),ye=>ye&&typeof ye=="object"?ye:null),re=(Y&&Array.isArray(Y.items)?Y.items:[]).find(ye=>Lu(ye,v));if(re)return re}return null},yl=(f,v,b)=>{if(f.link)return vl(v,b)!=null;if(f.list?.mode==="toggle-seed"&&f.list.seed)return Of(v,b)===f.list.seed;const A=H(f);if(A!==null)return A;const E=r.get(f.id),U=ya(b);if(U&&E?.selectionSignature===U)return E.active;const Y=Ca(f,b);return Y!==null?Y:jH(f,b)},Du=(f,v,b,A)=>{if(f.inline&&K0(f.inline.key)){const E=B(f);if(E!==void 0)return E;const U=A[f.inline.key];if(U!==void 0)return U;const Y=ya(b),re=Y?n.get(f.inline.key):void 0;if(Y&&re?.selectionSignature===Y)return re.value}if(f.id==="linked-style"){const{style:E}=Zn(b,Hn().cache);return!E.styleId||E.mixed?void 0:{styleId:E.styleId,styleName:E.styleName}}if(f.id==="text-align")return ie(v,b);if(f.id==="link")return st(v,b)??void 0},bl=(f,v,b)=>{const A=f?.lists;if(!A)return{value:null,status:"ready"};const E=b.storyType==="body",U=typeof A.getStateInStory=="function"?()=>A.getStateInStory({target:va(v),story:b}):E&&typeof A.getState=="function"?()=>A.getState({target:va(v)}):null;if(!U)return{value:null,status:"ready"};const{value:Y,status:re}=kr(`lists:${no(b)}:${v}`,Ft(),U,ye=>ye&&typeof ye=="object"?ye:null);return{value:Y?.success===!0?Y:null,status:re}},ri=(f,v,b)=>bl(f,v,b).value,Ji=(f,v,b)=>{const A=ri(f,v,b);return!A||A.isListItem!==!0?null:A.seed==="bullet"||A.seed==="ordered"?A.seed:null},Wr=(f,v,b)=>{const A=bl(f,v,b),E=A.value;return{value:E&&typeof E.isListItem=="boolean"?E.isListItem:null,status:A.status}},Of=(f,v)=>{const b=Rr(v);if(b.length===0||!tc(b))return null;const A=ga(v),E=Ji(f,b[0],A);if(E!=="bullet"&&E!=="ordered")return null;for(const U of b.slice(1))if(Ji(f,U,A)!==E)return null;return E},Pu=(f,v,b)=>{if(!f)return{value:null,status:"ready",refreshing:!1};const A=no(b),E=A==="story:body";if(E&&typeof f.getNodeById!="function")return{value:null,status:"ready",refreshing:!1};if(!E&&typeof f.getNode!="function")return{value:null,status:"ready",refreshing:!1};const U=`node:${A}:${v}`,Y=Ft(),re=kr(U,Y,()=>E?f.getNodeById({nodeId:v,nodeType:"paragraph"}):f.getNode(ho(v,b)),Re=>Re&&typeof Re=="object"?Re:null),ye=$.get(U);return{...re,refreshing:re.status==="stale"&&ye?.inflightToken===Y&&ye.failedToken!==Y}},Ds=f=>f==="left"||f==="center"||f==="right"||f==="justify"?f:void 0,hc=f=>f==="start"||f==="end"||f==="distributed"||f==="numTab"||f==="lowKashida"||f==="mediumKashida"||f==="highKashida"||f==="thaiDistribute",Ff=(f,v)=>{const b=T(),A=b?.readMountedProjectionBlocksByIds;if(typeof A!="function")return null;const E=_s(f),U=xt(()=>E?A.call(b,[...v],E):A.call(b,[...v]),null);if(!Array.isArray(U))return new Map;const Y=Q0(U),re=new Map;for(const ye of v){const Re=Y.find(Ke=>rc(Ke,ye));if(!Re)continue;const Ue=Re.attrs,Ye=Ds(Ue?.alignment),De=a9(Ue);re.set(ye,Ye??(De==="rtl"?"right":"left"))}return re},x=(f,v,b,A)=>{const{value:E,status:U,refreshing:Y}=Pu(f,v,b),re=A?.get(v);if(U==="pending")return re?{status:"uniform",value:re}:{status:"pending"};if(U==="stale"&&!Y)return{status:"pending"};if(U==="stale"&&re)return{status:"uniform",value:re};if(U==="stale"&&A&&!re)return{status:"unavailable"};if(!E)return{status:"unavailable"};const ye=E.node;if(!ye)return{status:"unavailable"};const Re=ye.kind;if(Re!=="paragraph"&&Re!=="heading")return{status:"unavailable"};const Ue=ye[Re];if(!Ue||typeof Ue!="object")return{status:"unavailable"};const Ye=Ue.props?.alignment;if(Ye==null)return re?{status:"uniform",value:re}:{status:"unavailable"};const De=Ds(Ye);return De?{status:"uniform",value:De}:hc(Ye)&&re?{status:"uniform",value:re}:{status:"unavailable"}},D=(f,v)=>{const b=Rr(v);if(b.length===0||!tc(b))return{status:"unavailable"};const A=ga(v),E=Ff(v,b),U=x(f,b[0],A,E);if(U.status!=="uniform")return U;for(const Y of b.slice(1)){const re=x(f,Y,A,E);if(re.status!=="uniform")return re;if(re.value!==U.value)return{status:"mixed"}}return U},ee=f=>{const v=Rr(f);return v.length===0?null:`${no(ga(f))}:${v.join(",")}`},ie=(f,v)=>{const b=D(f,v),A=b.status==="uniform"?b.value:void 0,E=o;if(!E)return A;const U=ee(v);return U&&U!==E.selectionSignature?(o=null,A):!U||!E.settled?E.value:b.status!=="pending"?(o=null,A):E.value},se=(f,v)=>{const b=Ds(v),A=ee(f),E=Rr(f);if(!b||!A||E.length===0)return null;const U=++i;return o={selectionSignature:A,value:b,generation:U,settled:!1,canReconcile:tc(E)},qt(),U},de=(f,v)=>{if(f==null)return;const b=o;if(!(!b||b.generation!==f)){if(!zo(v)){o=null;return}if(!b.canReconcile){o=null;return}b.settled=!0}},pe=async(f,v,b)=>{const A=f?.lists;if(!A)return null;try{const E=b.storyType==="body",U=typeof A.getStateInStory=="function"?await A.getStateInStory({target:va(v),story:b}):E&&typeof A.getState=="function"?await A.getState({target:va(v)}):null,Y=U&&typeof U=="object"?U:null;return!Y||Y.success!==!0||typeof Y.isListItem!="boolean"?null:Y.isListItem}catch{return null}},ve=(f,v,b)=>{const A={resolved:!1,seed:null},E=f?.lists;if(!E)return A;const U=b.storyType==="body",Y=typeof E.getStateInStory=="function"?()=>E.getStateInStory({target:va(v),story:b}):U&&typeof E.getState=="function"?()=>E.getState({target:va(v)}):null;if(!Y)return A;const re=ye=>{const Re=ye&&typeof ye=="object"?ye:null;return!Re||Re.success!==!0||typeof Re.isListItem!="boolean"?A:{resolved:!0,seed:Re.isListItem===!0&&(Re.seed==="bullet"||Re.seed==="ordered")?Re.seed:null}};try{const ye=Y();return Or(ye)?Promise.resolve(ye).then(re,()=>A):re(ye)}catch{return A}},Xe=async(f,v,b)=>{if(!f)return null;try{const A=!b||b.storyType==="body",E=b&&typeof f.getNode=="function"?await f.getNode(ho(v,b)):A&&typeof f.getNodeById=="function"?await f.getNodeById({nodeId:v,nodeType:"paragraph"}):null;return mH(E&&typeof E=="object"?E:null)}catch{return null}},Qe=(f,v,b,A,E,U)=>{if(f.mutates&&b)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.documentReadonly},"builtin");const Y=Rr(A);if(Y.length===0)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.selectionRequired},"builtin");const re=f.docRoute?gr(v,f.docRoute):null,ye=gr(v,"format.paragraph.setIndentation"),Re=gr(v,"format.paragraph.clearIndentation"),Ue=f.list?.mode,Ye=Ue==="indent"?ye!=null:ye!=null||Re!=null,De=ga(A);let Ke=null;if(De.storyType!=="body"){Ke=[];for(const Be of Y){const{value:He,status:je}=Wr(v,Be,De);if(He===null)return je!=="ready"&&(re!=null||Ye)?tn({enabled:!0,active:E,supported:!0,value:U},"builtin"):tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin");Ke.push(He)}}if(Ke?.some(Be=>Be===!0)){const Be=Ue==="indent"?"lists.indentRange":"lists.outdentRange",He=jn()!=="suggesting"&&Ke.every($e=>$e===!0)&&gr(v,Be)!=null,je=Ue==="outdent"&&gr(v,"lists.outdentInStory")!=null;if(!He&&!je)return tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin")}for(const[Be,He]of Y.entries()){const je=Ke?{value:Ke[Be]??null,status:"ready"}:Wr(v,He,De),$e=je.value;if($e===!0){if(re!=null)return tn({enabled:!0,active:E,supported:!0,value:U},"builtin");continue}if($e===!1&&Ye){if(De.storyType!=="body"&&typeof v?.getNode!="function")continue;return tn({enabled:!0,active:E,supported:!0,value:U},"builtin")}if($e===null)return je.status!=="ready"&&(re!=null||Ye)?tn({enabled:!0,active:E,supported:!0,value:U},"builtin"):tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin")}return tn({enabled:!1,active:E,supported:!1,value:U,reason:Qi(v)},"builtin")},tt=(f,v,b,A,E,U)=>{if(f.mutates&&b)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.documentReadonly},"builtin");const Y=Rr(A);if(Y.length===0)return tn({enabled:!1,active:E,supported:!0,value:U,reason:at.selectionRequired},"builtin");const re=ga(A),ye=v?.lists;if(!(typeof ye?.getStateInStory=="function"||re.storyType==="body"&&typeof ye?.getState=="function"))return tn({enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");if(!tc(Y))return tn(re.storyType==="body"&&gr(v,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:U}:{enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");const Re=Y.map(Ke=>bl(v,Ke,re));if(Re.some(({status:Ke})=>Ke!=="ready"))return tn({enabled:!0,active:E,supported:!0,value:U},"builtin");if(Re.some(({value:Ke})=>Ke===null))return tn({enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");const Ue=f.list?.seed,Ye=Re.every(({value:Ke})=>Ke?.isListItem===!0&&Ke.seed===Ue);if(re.storyType==="body")return tn(!Ye||gr(v,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:U}:{enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin");const De=gr(v,"lists.removeInStory");return tn(Ye&&De?{enabled:!0,active:E,supported:!0,value:U}:{enabled:!1,active:E,supported:!1,value:U,reason:at.operationUnavailable},"builtin")},st=(f,v)=>{const b=vl(f,v)?.properties?.href;return typeof b=="string"?b:null},vt=f=>{if(!S())return tn({enabled:!1,active:!1,supported:!1,reason:at.notReady},"builtin");const v=f.instanceRoute;return typeof t?.[v]!="function"?tn({enabled:!1,active:!1,supported:!1,reason:at.operationUnavailable},"builtin"):tn({enabled:!0,active:pt(f),supported:!0,value:dn(f)},"builtin")},pt=f=>{const v=t?.config??void 0;return f.valueFrom==="ruler"?!!v?.rulers:f.valueFrom==="formattingMarks"?!!v?.layoutEngineOptions?.showFormattingMarks:!1},it=(f,v,b)=>{if(b)return tn({enabled:!1,active:!1,supported:!0,reason:at.documentReadonly},"builtin");const A=Fe();return A!=null&&(!f.table.requiresCell||A.cellNodeId!=null)?(f.docRoute?gr(v,f.docRoute):null)==null?tn({enabled:!1,active:!1,supported:!1,reason:Qi(v)},"builtin"):tn({enabled:!0,active:!1,supported:!0},"builtin"):tn({enabled:!1,active:!1,supported:!0,reason:at.tableContextUnavailable},"builtin")},dn=f=>{if(f.valueFrom==="zoom")return ni().value;if(f.valueFrom==="documentMode")return jn();if(f.valueFrom==="measurementUnit")return Rs();if(f.valueFrom==="ruler"||f.valueFrom==="formattingMarks")return pt(f)},rn=(f,v)=>f.id==="zoom"?typeof v=="number"&&Number.isFinite(v)&&v>0:f.id==="document-mode"?v==="editing"||v==="suggesting"||v==="viewing":f.id==="measurement-unit"?v==="in"||v==="cm":!0,Bn=()=>[...new Set([...nB,...he.keys()])],Gn="Normal",Wn={ready:!1,status:"ready",catalogRevision:null,quickGallery:[],activeParagraphStyleId:null,activeParagraphStyleName:null,mixedSelection:!1,sourceStatus:null,diagnostics:[]},vo=f=>{const v=y()?.styles;return!v||typeof v.getCatalog!="function"?{value:null,status:"ready"}:kr(`styles:catalog:${JSON.stringify(f??{})}`,Ft(),()=>v.getCatalog(f),b=>b&&typeof b=="object"?b:null)},Hn=()=>{const f=vo({includePreview:!0});if(!f.value)return{cache:null,status:f.status};const v=vo({view:"quickGallery",includePreview:!0}),b=v.value?v.value.items:f.value.styles.filter(E=>E.visibility.quickGallery),A=new Map;for(const E of f.value.styles)A.set(E.id,E);return{cache:{full:f.value,quickGallery:b,byId:A},status:mu(f.status,v.status)}},Mn=(f,v,b)=>{const{value:A,status:E}=Pu(f,v,b);if(!A)return{ok:!1,styleRef:null,status:E};const U=A.node;if(!U||typeof U!="object")return{ok:!1,styleRef:null,status:E};const Y=U.kind,re=typeof Y=="string"?U[Y]:void 0,ye=re&&typeof re=="object"?re.styleRef:void 0;return{ok:!0,styleRef:typeof ye=="string"&&ye.length>0?ye:null,status:E}},Zn=(f,v)=>{const b=[],A=y();if(!A)return b.push({severity:"warning",code:"active-style-unavailable",message:"Active paragraph style is unavailable: the Document API is not reachable."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:"ready"};const E=Rr(f);if(E.length===0)return b.push({severity:"info",code:"active-style-no-selection",message:"No paragraph block is resolvable from the current selection; active paragraph style is unavailable."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:"ready"};if(!tc(E))return b.push({severity:"info",code:"active-style-selection-too-large",message:"Active paragraph style is unavailable for a large multi-paragraph selection."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:"ready"};const U=v?.full.defaults.paragraphStyleId??(v?Gn:null),Y=new Set;let re=0,ye=0,Re=0,Ue="ready";const Ye=ga(f);for(const Be of E){const He=Mn(A,Be,Ye);if(Ue=mu(Ue,He.status),!He.ok){ye+=1;continue}if(!He.styleRef&&!U){Re+=1;continue}const je=He.styleRef??U;if(!je){Re+=1;continue}re+=1,Y.add(je)}if(re===0){const Be=Re>0&&ye===0;return b.push({severity:"warning",code:Be?"active-style-default-unavailable":"active-style-read-failed",message:Be?"Selected paragraphs have no explicit style and the style catalogue is unavailable, so the document default cannot be resolved.":"Could not read the paragraph style of any selected block; active paragraph style is unavailable."}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:Ue}}const De=ye+Re;if(De>0)return b.push({severity:"warning",code:"active-style-partial",message:`Active paragraph style resolved from ${re} of ${re+De} selected blocks; ${De} could not be read, so the active style is unavailable.`}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:Ue};if(Y.size>1)return{style:{styleId:null,styleName:null,mixed:!0,diagnostics:b},status:Ue};const Ke=[...Y][0];return{style:{styleId:Ke,styleName:v?.byId.get(Ke)?.name??null,mixed:!1,diagnostics:b},status:Ue}},bt=f=>{if(!S())return Wn;const{cache:v,status:b}=Hn(),{style:A,status:E}=Zn(f,v);let U;return v?U=A.diagnostics.length===0?v.full.diagnostics:[...v.full.diagnostics,...A.diagnostics]:U=[{severity:"warning",code:"catalog-unavailable",message:"The style catalogue is unavailable: the Document API styles surface is not reachable (e.g. viewing mode or a worker-backed editor)."},...A.diagnostics],{ready:!0,status:mu(b,E,f.status),catalogRevision:v?.full.revision??null,quickGallery:v?.quickGallery??[],activeParagraphStyleId:A.styleId,activeParagraphStyleName:A.styleName,mixedSelection:A.mixed,sourceStatus:v?.full.sourceStatus??null,diagnostics:U}},zt=()=>{const f=jn(),v=Cu();v.status==="ready"&&cl(v),N(v);const b=ya(v);for(const[A,E]of r)(!b||E.selectionSignature!==b||E.settled&&v.status==="ready")&&r.delete(A);return{ready:S()!=null,documentMode:f,document:pl(),selection:v,toolbar:{context:f,commands:Tu(v),copyFormatActive:h.mode!=="idle"},comments:Mf(v),trackChanges:hl(v),contentControls:Lo(v),zoom:ni(),fonts:ku(),styles:bt(v)}},Kn=f=>{const v=ya(f);v&&a&&v!==a&&(n.clear(),r.clear()),v&&(a=v)};let oo=null,fr=null,$i=null,gi=null,yo=!1;const wl=()=>{if(Q||yo)return;yo=!0;const f=()=>{yo&&(yo=!1,!Q&&qt())};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Ps=()=>{const f=I();if(f!==$i&&(gi&&(gi(),gi=null),$i=f,!(!f||typeof f.subscribe!="function")))try{const v=f.subscribe(()=>wl());typeof v=="function"&&(gi=v)}catch{$i=null}};let oi=null,vi=null,io=null,Do=null,yi=null,Vo=null;const Cl=()=>{const f=S()?.host,v=xt(f?.getHandles?()=>f.getHandles():void 0,null)?.editing?.selection;return v&&typeof v.subscribe=="function"?v:null},es=()=>{const f=Cl();if(f!==oo&&(fr&&(fr(),fr=null),oo=f,!!f))try{const v=f.subscribe(b=>{Dt+=1,Ti(b),qt()});typeof v=="function"&&(fr=v)}catch{oo=null}},Ri=()=>{const f=S()?.host,v=xt(f?.getHandles?()=>f.getHandles():void 0,null)?.review;return v&&typeof v.subscribe=="function"?v:null},Os=f=>f?typeof f.getActiveReviewTarget=="function"?xt(()=>f.getActiveReviewTarget(),null):typeof f.getSnapshot=="function"?xt(()=>f.getSnapshot(),null)?.activeReviewTarget??null:null:null;let bo=0;const ts=(f,v)=>{const b=(v&&typeof v=="object"?v:null)?.lastInteractionRejection;if(bo>0&&f==null&&b&&typeof b=="object"&&b.code==="review-target-invalidated"&&b.detail==="not-painted")return!1;const A=f&&typeof f=="object"?f:null;let E=null;if(A?.entityType==="trackedChange"&&typeof A.entityId=="string"&&A.entityId.length>0){const U=A.story&&no(A.story)!==no(null)?A.story:void 0;E={id:A.entityId,...U?{story:U}:{},...typeof A.paintedEntityId=="string"&&A.paintedEntityId.length>0?{paintedEntityId:A.paintedEntityId}:{}}}return f==null&&E==null&&ae!=null&&kt(ae)||et(ae,E)?!1:(ze(E),!0)},Ou=()=>{const f=Ri();if(f===oi)return;if(vi&&(vi(),vi=null),oi=f,!f){ts(null);return}let v=!0;try{const b=f.subscribe(A=>{const E=A&&typeof A=="object"?A:null;!ts(E&&Object.prototype.hasOwnProperty.call(E,"activeReviewTarget")?E.activeReviewTarget:Os(f),A)||v||qt()});typeof b=="function"&&(vi=b),ts(Os(f))}catch{oi=null}finally{v=!1}},_l=()=>{if(oo||jn()!=="viewing")return null;const f=S()?.mount?.container,v=(f&&typeof f=="object"&&"ownerDocument"in f?f.ownerDocument??null:null)??globalThis.document??null;return v&&typeof v.addEventListener=="function"?v:null},_a=()=>{const f=_l();if(f===yi||(Vo&&(Vo(),Vo=null),yi=f,!f))return;const v=()=>{Dt+=1,qt()};f.addEventListener("selectionchange",v),f.addEventListener("pointerup",v,!0),f.addEventListener("mouseup",v,!0),Vo=()=>{f.removeEventListener("selectionchange",v),f.removeEventListener("pointerup",v,!0),f.removeEventListener("mouseup",v,!0)}};qi(),ts(Os(Ri()));let ht=zt();a=ya(ht.selection);const Fu=()=>{const f=S()?.host?.events,v=f&&typeof f.subscribe=="function"?f:null;if(v!==io&&(Do&&(Do(),Do=null),io=v,!!v))try{const b=v.subscribe(A=>{const E=A?.type;if(E==="source:complete"||E==="source:signals-complete"){on!==null&&(We(),dr.onRender(!0));return}if((E==="mutation:committed"||E==="collaboration:remote-changed")&&(al=Date.now()),E==="mutation:committed"&&(We(),Bt={}),E==="mutation:committed"||E==="save:completed"||E==="collaboration:remote-changed"){const U=E==="mutation:committed"?S_(A):null,Y=E==="mutation:committed"&&dr.getPendingIds().size>0;U?.removedIds.size&&Mt(new Set(U.removedIds),A.receipt);const re=U?.reconcileMode==="authoritative"&&U.upsertIds.size>0;if(re&&(mi(),We(),on=Ft(),qt()),U?.upsertIds.size||Y){const Ye=A.origin==="history"?null:A.receipt,De=S()?.documentMutationReadiness,Ke=typeof Ye?.txId=="string"&&Ye.txId.length>0&&typeof De?.whenPainted=="function",Be=A.origin==="history"&&typeof De?.getRenderEpoch=="function"?xt(()=>De.getRenderEpoch.call(De),null):null,He=A.origin==="history"&&typeof De?.whenPainted=="function",je={upsertIds:U?.upsertIds??new Set,removedIds:new Set,reconcileMode:U?.reconcileMode==="authoritative"?"authoritative":"targeted"};Ke?dr.enqueueAfterPaint(je,()=>De.whenPainted.call(De,Ye)):He?dr.enqueueAfterPaint(je,()=>De.whenPainted.call(De,typeof Be=="number"?{afterEpoch:Be}:void 0)):(dr.enqueue(je),dr.onRender(Y))}if(re)return;const ye=E==="mutation:committed"&&Ro(A)||E==="collaboration:remote-changed"&&Array.isArray(A.changedStoryIds)&&A.changedStoryIds.length>0;if(ye&&(Wi=Date.now()),E==="mutation:committed"&&ye){ll();return}if(U?.removedIds.size&&U.upsertIds.size===0)return;(E==="collaboration:remote-changed"||E==="mutation:committed"&&!ye)&&$o();const Re=E==="collaboration:remote-changed"&&Array.isArray(A.changedPartUris)&&A.changedPartUris.some(Ye=>typeof Ye=="string"&&oH.has(Ye)),Ue=E==="collaboration:remote-changed"&&Array.isArray(A.changedStoryIds)&&A.changedStoryIds.length>0&&xo();Re&&!ye&&(ro=!0),mi(),(Re||Ue)&&yn("comments"),qt()}});typeof b=="function"&&(Do=b)}catch{io=null}},qt=()=>{if(Q)return;yo=!1,qi(),es(),Ps(),Ou(),_a(),Fu();const f=zt();Kn(f.selection),ht=f;for(const v of[...Ve])v(ht)},pc=[],Qt=[],Ln=f=>{for(const v of f)try{v()}catch{}},Nn=()=>Ln(pc),Mi=()=>Ln(Qt),ns=[];((f,v)=>{if(!(!f||typeof f.on!="function"))for(const b of v){const A=b==="active-editor-change"?()=>{Nn(),Mi(),qt()}:b==="document-replaced"?E=>{const U=E&&typeof E=="object"?E:null,Y=U?.editor,re=U?.host,ye=!!Y&&Y===S(),Re=!!re&&re===T();!ye&&!Re||(Mi(),$.clear(),mi(),qt())}:()=>qt();try{f.on(b,A),ns.push(()=>{try{typeof f.off=="function"&&f.off(b,A)}catch{}})}catch{}}})(t,Jz),es(),Ps(),Ou(),_a(),Fu();const Li=(f,v=Nz)=>({get:()=>f(ht),subscribe:b=>{let A=f(ht);const E=U=>{const Y=f(U);v(A,Y)||(A=Y,b(Y))};return Ve.add(E),()=>Ve.delete(E)}}),Po=f=>Li(f),Di=f=>{const v=b=>{const A=U=>{try{b(U)}catch{}},E=f.subscribe(A);return A(f.get()),E};return{get:()=>f.get(),getSnapshot:()=>f.get(),observe:v,subscribe:b=>v(A=>b({snapshot:A}))}};function tb(f){return f&&typeof f=="object"&&typeof f.id=="string"?String(f.id):null}function O(f){if(f.empty)return null;const v=f.selectionTarget,b=v?.start,A=v?.end;if(v?.kind!=="selection"||b?.kind!=="text"||A?.kind!=="text"||typeof b.blockId!="string"||b.blockId!==A.blockId||!Number.isInteger(b.offset)||!Number.isInteger(A.offset)||b.offset<0||A.offset<0||b.offset===A.offset)return null;const E=Math.min(b.offset,A.offset),U=Math.max(b.offset,A.offset),Y=_s(f);return{kind:"range",coordinateSpace:v.coordinateSpace==="tracked"?"tracked":"visible",range:{kind:"text",...Y?{story:Y}:{},segments:[{blockId:b.blockId,range:{start:E,end:U}}]}}}function q(){const f=ht.selection.activeChangeIds[0];if(!f)return"unavailable";const v=Ts();if(!v)return"unavailable";const b=_s(ht.selection),A=v.find(re=>rl(re,f,b));if(!A)return"unavailable";const E=X0(A),U=E.type,Y=E.grouping;return U==="replacement"&&Y==="replacement-pair"||(U==="insertion"||U==="deletion"||U==="insert"||U==="delete")&&Y==="standalone"?"range":"id"}function Ee(f,v){if(f.scope==="all")return{target:{scope:"all"},changeId:null};if(typeof v=="string"&&v.length>0)return{target:{kind:"id",id:v},changeId:v};if(v&&typeof v=="object"){const A=v;if(A.target&&typeof A.target=="object")return{target:A.target,changeId:tb(A.target)};const E=typeof A.changeId=="string"?A.changeId:A.id;if(typeof E=="string"&&E.length>0)return{target:{kind:"id",id:E},changeId:E}}const b=ht.selection.activeChangeIds[0];return b?{target:{kind:"id",id:b},changeId:b}:null}function Ne(f,v){if(f.scope==="id"&&v==null){if(ht.selection.activeChangeIds.length>1)return Hu(f.kind,{kind:"ids",ids:ht.selection.activeChangeIds},null);if(ht.selection.activeChangeIds.length===1&&!ht.selection.empty&&ht.selection.selectionTarget){const A=q();if(A==="unavailable")return!1;if(A==="range"){const E=O(ht.selection);return E?Hu(f.kind,E,null):!1}if(A==="id"){const E=ht.selection.activeChangeIds[0],U=_s(ht.selection),Y=U&&no(U)!==no(null)?U:void 0;return lb(f.kind,Y?{id:E,story:Y}:E)}}}const b=Ee(f,v);return b?Hu(f.kind,b.target,b.changeId):!1}function mt(f,v){const b=I()?.lists,A=b?.apply;if(typeof A!="function")return!1;const{behavior:E,preset:U,continuity:Y}=typeof v=="string"?tH(v):v&&typeof v=="object"?v:{},re={kind:f,behavior:E??"toggle"};U!==void 0&&(re.preset=U),Y!==void 0&&(re.continuity=Y);try{return Kr(A.call(b,re))}catch{return!1}}let nn=Promise.resolve(!1),pn=null,Jn=Promise.resolve(!1);const Dn=async f=>{if(!nm(f))return f;const v=S()?.documentMutationReadiness,b=v?.whenPainted;if(typeof b!="function")return f;const A=typeof f.txId=="string"?f.txId:void 0;try{await b.call(v,A?{txId:A}:void 0)}catch{}return f},_n=f=>{if(Or(f)){const b=Promise.resolve(f);return{immediate:!0,committed:b.then(A=>il(A),()=>!1),settled:b.then(A=>Dn(il(A)),()=>!1)}}const v=il(f);return{immediate:v,committed:Promise.resolve(v),settled:Dn(v)}},An=()=>{const f=s.shift();if(!f){u=!1,d?.(),d=null;return}try{f.resolve(Q?!1:f.mutate())}catch{f.resolve(!1)}},so=()=>{let f=!1;return()=>{f||(f=!0,An())}},ao=(f,v)=>{if(!u){u=!0,c=new Promise(U=>{d=U});try{return{result:v(),release:so()}}catch(U){throw u=!1,d?.(),d=null,U}}const b=s.find(U=>U.key===f);if(b)return b.mutate=v,{result:b.result,release:()=>{}};let A;const E=new Promise(U=>{A=U});return s.push({key:f,mutate:v,result:E,resolve:A}),{result:E,release:so()}},ka=new Set(["create.tableOfContents"]),Sl=f=>cr(`Tracked authoring is not supported for ${f}.`),Oo=f=>{if(jn()==="suggesting")return ka.has(f)?Sl(f):{changeMode:"tracked"}},kl=()=>jn()==="suggesting"?LH:J0,hr=(f,v,b)=>{const A=Oo(f);return A&&A.success===!1?A:A?v(b,A):v(b)},nb=(f,v,b,A)=>{const E=f.inline;if(!E)return;const U=il(A);if(U===!1||typeof U=="object"&&U&&U.success===!1)return;if(E.kind==="clear"){n.clear();return}if(E.kind==="toggle"||!K0(E.key))return;const Y=ya(v);if(!Y)return;const re=bH(E.key,b.value);if(re==null){n.delete(E.key);return}n.set(E.key,{selectionSignature:Y,value:re})},sm=(f,v,b,A)=>!f.inline||f.inline.kind==="toggle"?A:Or(A)?Promise.resolve(A).then(E=>(nb(f,v,b,E),E)):A,am=(f,v,b,A)=>{if(f.inline?.kind!=="toggle"||!zo(il(A))||typeof b.value!="boolean"&&b.value!==null)return null;const E=ya(v);if(!E)return null;const U=++l;return r.set(f.id,{selectionSignature:E,active:b.value===!0,generation:U,settled:!1}),qt(),U},rb=(f,v,b)=>{if(v==null)return;const A=r.get(f.id);if(!(!A||A.generation!==v)){if(!zo(b)){r.delete(f.id);return}A.settled=!0}},Bu=(f,v)=>f.then(b=>(v?.(b),mi(),qt(),b),()=>(v?.(!1),mi(),qt(),!1)),Kr=(f,v)=>{const b=pn;if(pn=null,b)return nn=Bu(b,v),il(f);if(Or(f))return nn=Bu(_n(f).settled,v),!0;const A=il(f);return nm(A)&&typeof S()?.documentMutationReadiness?.whenPainted=="function"?(nn=Bu(Dn(A),v),A):(v?.(A),nn=Promise.resolve(A),mi(),qt(),A)},$n=(f,v)=>!f||typeof f!="object"?v:f,Aa=(f,v=cr("Document API operation failed."))=>{if(Or(f))return Promise.resolve(f).then(A=>Aa(A,v),()=>v);const b=$n(f,v);return mi(),nm(b)&&typeof S()?.documentMutationReadiness?.whenPainted=="function"?(Bu(Dn(b)),qt(),b):(qt(),b)},lm=(f,v,b,A)=>{const E=[],U=[];for(const Y of b){const re=A(Y);if(re)try{const ye=_n(hr(f,v,re));E.push(ye.immediate),U.push(ye.settled)}catch{E.push(!1),U.push(Promise.resolve(!1))}}return pn=U.length?Promise.all(U).then(Y=>hi(Y)):null,hi(E)},cm=(f,v,b,A)=>{const E=[],U=[];for(const Y of b){const re=A(Y);if(re)try{const ye=_n(hr(f,v,re));E.push(ye.immediate),U.push(ye.settled)}catch{E.push(!1),U.push(Promise.resolve(!1))}}return pn=U.length?Promise.all(U).then(Y=>hi(Y)):null,hi(E)},Bf=(f,v,b,A=ht.selection)=>{const E=Oo(f);return E&&E.success===!1?E:A.selectionTarget?v(b,{...E??{},offsetSpace:"selection"}):E?v(b,E):v(b)},um=(f,v,b,A)=>{const E=ho(v,A);switch(f.kind){case"alignment":{const U=b;return U!=="left"&&U!=="center"&&U!=="right"&&U!=="justify"?null:{target:E,alignment:U}}case"spacing-line":{const U=typeof b=="number"?b:Number(b);return!Number.isFinite(U)||U<=0?null:{target:E,line:U,lineRule:"auto"}}case"style":if(b&&typeof b=="object"){const U=b.role;if(U&&typeof U=="object")return{target:E,role:U}}return typeof b!="string"||b.trim()===""?null:{target:E,styleId:b};case"direction":{const U=f.fixedValue;return U!=="ltr"&&U!=="rtl"?null:{target:E,direction:U}}default:return null}},dm=(f,v)=>{const b=f.inline,A=Z0(f),E=T();if(!b||typeof E?.setPendingInlineFormat!="function")return!1;if(b.kind==="clear")return Z(),!0;if(!A)return!1;let U;if(b.kind==="toggle")U=!yl(f,y(),ht.selection);else{const Y=v&&typeof v=="object"&&"value"in v?v.value:v;if(b.kind==="value-number"){const re=typeof Y=="number"?Y:Number(Y);U=Number.isFinite(re)&&re>0?re:null}else U=typeof Y=="string"&&Y.trim()!==""?Y:null;if(U===null)return z(A,null),!0}return z(A,U),!0},fm=()=>{const f=y(),{lockModesById:v}=ti(f?.contentControls,ht.selection);if(Zi(v))return!1;const b=[],A=[],E=Ke=>{const Be=_n(Ke);b.push(Be.immediate),A.push(Be.settled)},U=(Ke,Be,He)=>{try{E(He?Ke(Be,He):Ke(Be))}catch{b.push(!1),A.push(Promise.resolve(!1))}},Y=Hn().cache?.full.defaults.paragraphStyleId??Gn,re=bu(ht.selection);if(re){const Ke=gr(f,"format.apply");if(Ke)try{E(Bf("format.apply",Ke,{target:re,inline:{...kl()}}))}catch{b.push(!1),A.push(Promise.resolve(!1))}}const ye=gr(f,"format.paragraph.resetDirectFormatting"),Re=gr(f,"styles.paragraph.setStyleRef"),Ue=_s(ht.selection),Ye=!Ue||Ue.storyType==="body",De=gr(f,Ye?"lists.remove":"lists.removeInStory");for(const Ke of Rr(ht.selection)){const Be=ho(Ke,Ue);if(ye&&U(ye,{target:Be}),De)try{const He=va(Ke),je=_n(De(Ye?{target:He}:{target:He,story:Ue}));A.push(je.settled.then($e=>zo($e)?$e:!0))}catch{}Re&&U(Re,{target:Be,styleId:Y})}if(!re&&jn()!=="suggesting"){const Ke=gr(f,"format.paragraph.setMarkRunProps");if(Ke)for(const Be of Rr(ht.selection))U(Ke,{target:ho(Be,Ue),markRunProps:{bold:!1,italic:!1,strikethrough:!1,doubleStrikethrough:!1,smallCaps:!1,caps:!1,verticalAlign:"baseline"}})}return pn=A.length?Promise.all(A).then(Ke=>hi(Ke)):null,hi(b.length?b:[!1])},ob=(f,v,b)=>{const A=Rr(ht.selection);if(A.length===0)return!1;const E=_s(ht.selection);return lm(f.docRoute,v,A,U=>um(f.blockParagraph,U,b,E))},hm=(f,v,b)=>{const A=y(),E=gr(A,"format.paragraph.setIndentation"),U=gr(A,"format.paragraph.clearIndentation"),Y=f.list?.mode,re=ga(ht.selection),ye=_s(ht.selection),Re=async Ue=>{const Ye=await pe(A,Ue,re);if(Ye===!0)return{kind:"list",routeToCall:f.docRoute,opToCall:v,input:{target:oA(Ue)}};if(Ye===null||ye&&ye.storyType!=="body"&&typeof A?.getNode!="function")return null;const De=await Xe(A,Ue,ye),Ke={};if(De?.right!=null&&(Ke.right=De.right),De?.firstLine!=null&&(Ke.firstLine=De.firstLine),De?.hanging!=null&&(Ke.hanging=De.hanging),Y==="indent")return E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:ho(Ue,ye),left:Math.max(0,De?.left??0)+iA,...Ke}}:null;const Be=Math.max(0,(De?.left??0)-iA);return Be>0&&(Ke.left=Be),Object.keys(Ke).length===0?U?{kind:"paragraph",routeToCall:"format.paragraph.clearIndentation",opToCall:U,input:{target:ho(Ue,ye)}}:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:ho(Ue,ye),left:0}}:null:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:ho(Ue,ye),...Ke}}:null};return pn=(async()=>{const Ue=await Promise.all(b.map(Be=>Re(Be).catch(()=>null)));if(Ue.length===b.length&&Ue.every(Be=>Be?.kind==="list")&&jn()!=="suggesting"){const Be=Y==="indent"?"lists.indentRange":"lists.outdentRange",He=gr(A,Be);if(He)try{return await _n(hr(Be,He,{paraIds:b,story:re})).settled}catch{return!1}}const Ye=re.storyType!=="body"&&Ue.some(Be=>Be?.kind==="list"),De=Ye&&Y==="outdent"?gr(A,"lists.outdentInStory"):null;if(Ye&&!De)return!1;const Ke=Ue.map(Be=>{if(!Be)return Promise.resolve(!1);try{return Be.kind==="list"&&De?_n(hr("lists.outdentInStory",De,{target:Be.input.target,story:re})).settled:_n(hr(Be.routeToCall,Be.opToCall,Be.input)).settled}catch{return Promise.resolve(!1)}});return hi(await Promise.all(Ke))})(),!0},mc=(f,v)=>{const b=f.list,A=y(),E=Rr(ht.selection);if(E.length===0)return!1;const U=ga(ht.selection),Y=U.storyType==="body";if(b.mode==="indent"||b.mode==="outdent")return hm(f,v,E);const re=b.seed,ye=Ye=>{if(Ye.some($e=>!$e.resolved))return{immediate:!1,settled:null};const De=Ye.every($e=>$e.seed===re);if(!De&&!Y)return{immediate:!1,settled:null};const Ke=De?Y?"lists.remove":"lists.removeInStory":f.docRoute,Be=De?gr(A,Ke):v;if(!Be)return{immediate:!1,settled:null};const He=[],je=[];return E.forEach(($e,Je)=>{if(!De&&Ye[Je]?.seed===re)return;const Lt=De?{target:va($e),...Y?{}:{story:U}}:{target:va($e),seed:re};try{const Yt=_n(hr(Ke,Be,Lt));He.push(Yt.immediate),je.push(Yt.settled)}catch{He.push(!1),je.push(Promise.resolve(!1))}}),{immediate:hi(He),settled:je.length?Promise.all(je).then($e=>hi($e)):null}},Re=E.map(Ye=>ve(A,Ye,U));if(Re.some(Or))return pn=Promise.all(Re).then(async Ye=>{const De=ye(Ye);return De.settled?await De.settled:De.immediate}),!0;const Ue=ye(Re);return pn=Ue.settled,Ue.immediate};function Fs(f){return f&&typeof f=="object"?f:{}}function Nf(f){if(typeof f=="string")return f;const v=Fs(f);if(Object.prototype.hasOwnProperty.call(v,"href"))return v.href;if(Object.prototype.hasOwnProperty.call(v,"value"))return v.value}function At(f,v){const b=Fs(f).text;return typeof b=="string"&&b.trim()!==""?b:v}function jt(f){const v=Fs(f),b=v.capture&&typeof v.capture=="object"?v.capture:null;return v.target??b?.target??b?.selectionTarget??v.selectionTarget??v.textTarget??null}const wn=f=>{const v=y(),b=v?.hyperlinks;if(!b)return!1;const A=Fs(f),E=Nf(f),U=jt(f),Y=typeof A.text=="string"?A.text:void 0,re=typeof A.currentText=="string"?A.currentText:void 0,ye=yu(A.hyperlinkTarget)?A.hyperlinkTarget:null,Re=yu(A.textTarget)?A.textTarget:null,Ue=vl(v,ht.selection),Ye=typeof ye?.storyId=="string"&&typeof ye?.hyperlinkNodeId=="string";if(Ye&&E===null){const De=b.remove;if(typeof De!="function")return!1;try{return hr("hyperlinks.remove",De,{storyId:ye.storyId,hyperlinkNodeId:ye.hyperlinkNodeId,keepText:!0})}catch{return!1}}if(Ue&&E===null){const De=b.remove;if(typeof De!="function")return!1;try{return hr("hyperlinks.remove",De,{target:Ue.address,mode:"unwrap"})}catch{return!1}}if((Ue||ye)&&typeof E=="string"&&E.trim()!==""){const De=b.patch,Ke=b.updateTarget;if(!(!Ye&&Ue&&typeof De=="function")&&!(Ye&&typeof Ke=="function"))return!1;const Be=typeof Y=="string"&&Y!==(Ye?re:Ue?.text??re),He=v?.text?.replace,je=Be?Ye?Re:IH(Ue?.address):null,$e=Be&&!!je&&typeof He=="function";if(Be&&!$e)return!1;const Je=[],Lt=[];let Yt=null,zn=null,qn=null,Yr=!1;try{if(Ye){if(typeof Ke!="function")return!1;const Nr=hr("hyperlinks.updateTarget",Ke,{storyId:ye.storyId,hyperlinkNodeId:ye.hyperlinkNodeId,newTarget:EH(E)});Yr=Or(Nr);const Lr=_n(Nr);if(!zo(Lr.immediate))return!1;Je.push(Lr.immediate),Lt.push(Lr.settled),Yt=Lr.immediate,zn=Lr.committed,qn=Lr.settled}else if(Ue){if(typeof De!="function")return!1;const Nr=hr("hyperlinks.patch",De,{target:Ue.address,patch:{href:E}});Yr=Or(Nr);const Lr=_n(Nr);if(!zo(Lr.immediate))return!1;Je.push(Lr.immediate),Lt.push(Lr.settled),Yt=Lr.immediate,zn=Lr.committed,qn=Lr.settled}}catch{return!1}if($e){const Nr=(Ar,jo)=>zo(jo)?hi([Ar,jo]):zo(Ar)?Af(Ar,jo):jo,Lr=Ar=>{if(!zo(Ar))return Ar;try{const jo=_n(hr("text.replace",He,{target:je,text:Y}));return zo(jo.immediate)?Promise.all([qn??Promise.resolve(Ar),jo.settled]).then(([hb,HU])=>Nr(hb,HU)):Af(Ar,jo.immediate)}catch{return Af(Ar,!1)}};if(Yr)return pn=(zn??Promise.resolve(Yt??!1)).then(Lr),hi(Je);try{const Ar=_n(hr("text.replace",He,{target:je,text:Y}));if(!zo(Ar.immediate))return Yt?Af(Yt,Ar.immediate):Ar.immediate;Je.push(Ar.immediate),Lt.push(Ar.settled),pn=Promise.all([qn??Promise.resolve(Yt??!1),Ar.settled]).then(([jo,hb])=>Nr(jo,hb))}catch{return Yt?Af(Yt,!1):!1}}return!$e&&Lt.length>0&&(pn=Promise.all(Lt).then(Nr=>hi(Nr))),hi(Je)}if(typeof E=="string"&&E.trim()!==""){const De=E.trim(),Ke=b.wrap,Be=gH(U),He=Be.length>0?Be:W0(ht.selection);if(He.length>0){if(typeof Ke!="function")return!1;try{return cm("hyperlinks.wrap",Ke,He,Lt=>({target:Lt,link:{destination:{href:De}}}))}catch{return!1}}const je=b.insert,$e=At(f,De);if(typeof je!="function"||$e.trim()==="")return!1;const Je=xf(U)??ol(ht.selection);if(!Je)return!1;try{return hr("hyperlinks.insert",je,{target:Je,text:$e,link:{destination:{href:De}}})}catch{return!1}}return!1},yr=(f,v,b)=>{const A=f.create.kind,E=b&&typeof b=="object"?b:{};if(A==="table"){const Y=Number(E.rows??E.rowCount),re=Number(E.columns??E.cols??E.colCount);if(!Number.isInteger(Y)||Y<1||!Number.isInteger(re)||re<1)return!1;const ye=ol(ht.selection),Re=ye&&typeof ye.blockId=="string"?{kind:"inParagraph",target:ho(ye.blockId),offset:ye.range?.start??0}:Y0(ht.selection,"nodeId");try{return hr(f.docRoute,v,{rows:Y,columns:re,at:Re})}catch{return!1}}if(A==="image"){const Y=E.src??E.value;if(typeof Y!="string"||Y.trim()==="")return!1;const re=ol(ht.selection),ye=ga(ht.selection),Re=ye.storyType==="body"?null:ye;let Ue;re&&typeof re.blockId=="string"?Ue={kind:"inParagraph",target:ho(re.blockId,Re),offset:re.range?.start??0}:(Ue=Y0(ht.selection,"target"),Re&&Ue.kind==="after"&&(Ue={...Ue,target:{...Ue.target,story:Re}}));const Ye={src:Y,at:Ue};Re&&(Ye.in=Ue.kind==="inParagraph"?R(Re)??Re:Re),typeof E.alt=="string"&&(Ye.alt=E.alt),typeof E.title=="string"&&(Ye.title=E.title),E.size&&typeof E.size=="object"&&(Ye.size=E.size);try{return hr(f.docRoute,v,Ye)}catch{return!1}}const U={at:Y0(ht.selection,"target")};typeof E.instruction=="string"&&(U.instruction=E.instruction),E.config&&typeof E.config=="object"&&(U.config=E.config);try{return hr(f.docRoute,v,U)}catch{return!1}},Br=(f,v)=>{const b=f.table,A=Fe();if(!A||b.requiresCell&&!A.cellNodeId)return!1;const E=OH(b.action,A);if(!E)return!1;try{if(b.action==="insert-row-before"||b.action==="insert-row-after"){const U=T(),Y=(typeof U?.getHandles=="function"?U.getHandles():null)?.editing?.tables;if(typeof Y?.insertRow!="function")return!1;const re=Oo(f.docRoute);return re&&re.success===!1?re:re?Y.insertRow(E,re):Y.insertRow(E)}return hr(f.docRoute,v,E)}catch{return!1}},lo=f=>!f||f.disposition!=="routed"?!1:!!(f.inline||f.blockParagraph||f.list||f.link||f.create),bi=f=>{const v=Fs(f);return!!(jt(f)||yu(v.hyperlinkTarget)||yu(v.textTarget))},Al=(f,v,b)=>ht.selection.status!=="ready"?!1:rm(f)?.scope==="id"||!v||v.disposition!=="routed"?!0:v.inline?.kind==="clear"?Rr(ht.selection).length>0||bu(ht.selection)!=null:v.inline?bu(ht.selection)!=null||Rr(ht.selection).length>0:v.blockParagraph||v.list?Rr(ht.selection).length>0:v.link?bi(b)||W0(ht.selection).length>0||ol(ht.selection)!=null||yl(v,y(),ht.selection):!0,Nu=(f,v)=>{const b=rm(f),A=fu(f);return b?.scope!=="id"&&!lo(A)?!1:!Al(f,A,v)},uU=(f,v)=>Nu(f,v)?xs().then(()=>{}):null,gc=(f,v,b)=>{if(pn=null,nn=Promise.resolve(!1),Q)return!1;const A=he.get(f);if(A)try{return Kr(A.execute(ei(v,b)))}catch{return!1}const E=Jk(f);if(E&&typeof I()?.lists?.apply=="function")return mt(E,v);const U=rm(f);if(U)return Ne(U,v);if(f==="copy-format")return Kr(dU());const Y=fu(f);if(!Y||Y.disposition!=="routed")return!1;const re=Y.normalizePayload?Y.normalizePayload(v):v;if(Y.instanceRoute){if(!S()||!rn(Y,re))return!1;const Ye=t?.[Y.instanceRoute];if(typeof Ye!="function")return!1;try{const De=Y.fixedArg!==void 0?Y.fixedArg:re;return Kr(Ye.call(t,De))}catch{return!1}}if(Y.inline?.kind==="clear")return Y.mutates&&jn()==="viewing"?!1:Kr(fm());const ye=Y.docRoute;if(!ye||Y.mutates&&jn()==="viewing")return!1;const Re=y(),Ue=gr(Re,ye);if(!Ue)return!1;if(Y.inline){const{lockModesById:Ye}=ti(Re?.contentControls,ht.selection);if(Zi(Ye))return!1;const De=bu(ht.selection);if(!De)return ht.selection.empty===!1?Kr(!1):Kr(dm(Y,re));const Ke=yl(Y,Re,ht.selection),Be=DH(Y.inline,De,re,Ke);if(!Be)return!1;let He=null;try{const je=S(),$e=jn(),Je=()=>S()!==je||y()!==Re||jn()!==$e?!1:Bf(ye,Ue,Be),Lt=ya(ht.selection)??$l(ht.selection),Yt=Y.inline.kind==="toggle"?ao(`${Y.id}:${Lt}`,Je):null;He=Yt?.release??null;const zn=Yt?Yt.result:Je(),qn=am(Y,ht.selection,Be,zn),Yr=Kr(sm(Y,ht.selection,Be,zn),Nr=>{rb(Y,qn,Nr),He?.(),He=null});return Y.inline.kind==="toggle"&&(Jn=nn),Yr}catch{return He?.(),!1}}if(Y.blockParagraph){const Ye=ob(Y,Ue,re),De=Y.blockParagraph.kind==="alignment"&&zo(Ye)?se(ht.selection,re):null;return Kr(Ye,Ke=>{de(De,Ke)})}if(Y.list)return Kr(mc(Y,Ue));if(Y.link)return Kr(wn(re));if(Y.create)return Kr(yr(Y,Ue,re));if(Y.table)return Kr(Br(Y,Ue));try{return Kr(Y.mutates?hr(ye,Ue,re):Ue(re))}catch{return!1}},pm=()=>{m+=1,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:h.lastClickAt,pointerSelecting:!1,keyboardSelecting:!1};for(const f of p)f("idle");qt()},dU=async()=>{const f=["bold","italic","underline","strikethrough"].filter(Ue=>ht.toolbar.commands[Ue]?.active===!0),v=await Jn;await c;const b=zo(v)?f:[],A=500,E=Date.now();if(h.mode!=="idle"){if(h.mode==="armed"&&E-h.lastClickAt<A){h={...h,mode:"persistent",lastClickAt:E};for(const Ue of p)Ue("persistent");return qt(),!0}return pm(),!1}const U=E-h.lastClickAt<A,Y=++m;h={...h,lastClickAt:E};const re=await xs(),ye=`${$l(re)}:${Ft()}`,Re=await fU(null,re,ye&&ye===k?g:void 0,b);if(Y!==m)return!0;h={...h,mode:U?"persistent":"armed",snapshot:Re,sourceSelectionKey:$l(re),lastClickAt:E};for(const Ue of p)Ue(h.mode);return qt(),!0},fU=async(f,v,b,A=[])=>{const E=v?.target??f?.target;if(!E||E.kind!=="text")return null;const U=Array.isArray(E.segments)?E.segments:[];if(U.length===0)return null;const Y=y();if(!Y)return null;const re=E.story;let ye=null;for(const Be of U){const He=(await Ls(ho(Be.blockId,re)))?.node??null;if(!He)continue;const je=ib(He),$e=hU(Array.isArray(je?.inlines)?je.inlines:[],Be.range);ye?ye=gA(ye,$e):ye=$e}const Re=ye?zz(ye):{},Ue={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strike"},Ye=new Set([...v?.activeMarks??(Array.isArray(f?.activeMarks)?f.activeMarks:[]),...A]);for(const[Be,He]of Object.entries(Ue))Ye.has(Be)&&(Re[He]=!0);const De=b??await Eu(v??Es(f,"ready"));if(De.fontFamily&&(Re.fontFamily=De.fontFamily),De.color&&(Re.color=De.color),De.highlight&&(Re.highlight=De.highlight),De.fontSize){const Be=Number.parseFloat(De.fontSize);Number.isNaN(Be)||(Re.fontSize=Be)}let Ke=null;if(U.length===1){const Be=U[0],He=(await Ls(ho(Be.blockId,re)))?.node??null;He&&ib(He)&&(Ke=await pU(He,Be.blockId,Y,re))}return{story:re??null,inline:Re,paragraph:Ke}},ib=f=>f?f.kind==="paragraph"?f.paragraph??null:f.kind==="heading"?f.heading??null:null:null,hU=(f,v)=>{const b=Y=>{const re=Y.run;return typeof re?.text=="string"?re.text:""},A=Y=>Y.run?.props;if(v.start===v.end){let Y=0;for(const re of f){const ye=b(re),Re=Y,Ue=Y+ye.length;if(Y=Ue,v.start>=Re&&v.start<=Ue){const Ye=A(re);return Ye?{...Ye}:{}}}return{}}let E=0;const U=[];for(const Y of f){const re=b(Y),ye=E,Re=E+re.length;if(E=Re,Re<=v.start||ye>=v.end)continue;const Ue=A(Y);Ue&&U.push(Ue)}return U.length===0?{}:U.length===1?{...U[0]}:gA(U[0],...U.slice(1))},gA=(f,...v)=>{const b={...f};for(const A of v)for(const E of Object.keys(b)){if(!(E in A)){delete b[E];continue}const U=b[E],Y=A[E];(typeof U!=typeof Y||JSON.stringify(U)!==JSON.stringify(Y))&&delete b[E]}return b},pU=async(f,v,b,A)=>{const E=ib(f),U=E.props??{},Y=E.styleRef??null,re=U.alignment??null,ye=U.spacing??null,Re=U.indent??null,Ue=Re?{...Re.left!=null?{left:Re.left}:{},...Re.right!=null?{right:Re.right}:{},...Re.firstLine!=null?{firstLine:Re.firstLine}:{},...Re.hanging!=null?{hanging:Re.hanging}:{}}:null,Ye=U.markRunProps??null,De=U.numbering?.numId,Ke=typeof De=="string"?parseInt(De,10):typeof De=="number"?De:NaN,Be=U.numbering?.level,He=isNaN(Ke)?null:{numId:Ke,...Be!=null?{level:Be}:{}};let je=null;if(He&&typeof b.lists?.getState=="function")try{const $e=await b.lists.getState({target:ho(v,A)});$e&&typeof b.lists?.getStyle=="function"&&(je=await b.lists.getStyle($e)??null)}catch{}return{styleId:Y,alignment:re,spacing:ye,indentation:Ue,markRunProps:Ye,numbering:He,listStyle:je}},vA=async()=>{if(h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;const f=y()?.selection,v=async()=>Yi(typeof f?.current=="function"?await Promise.resolve(f.current({includeText:!0})):dl().value),b=()=>new Promise(Y=>setTimeout(Y,16)),A=8;let E=null,U="";for(let Y=0;Y<A;Y+=1){if(Y>0&&await b(),h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;if(E=await v(),!(!E||E.empty)&&(U=$l(E),U!==h.sourceSelectionKey))break}if(E&&!E.empty&&U!==h.sourceSelectionKey){await yA(E);return}if(h.snapshot?.paragraph){const Y=await v();if(!Y||$l(Y)===h.sourceSelectionKey)return;await yA(Y)}},yA=async f=>{const v=h.snapshot;if(!v){h.mode==="armed"&&pm();return}const b=y();if(!b)return;const A=Es(f,"ready"),{lockModesById:E}=ti(b.contentControls,A);if(Zi(E)){qt();return}const U=f.target,Y=f.selectionTarget;if(f.empty!==!0&&Object.keys(v.inline).length>0){const re=gr(b,"format.apply");if(re&&Y)try{if(!zo(il(await Promise.resolve(Bf("format.apply",re,{target:Y,inline:v.inline},f))))){qt();return}}catch{qt();return}}if(v.paragraph){const re=Array.isArray(U?.segments)?U.segments:[],ye=U?.story;for(const Re of re){const Ue=ho(Re.blockId,ye),Ye=await Ls(Ue),De=Ye?.node??null,Ke=Ye?.address??null;if(!De)continue;const Be={kind:"block",nodeType:Ke?.nodeType??De.kind??"paragraph",nodeId:Re.blockId,...ye&&typeof ye=="object"?{story:ye}:{}},{styleId:He,alignment:je,spacing:$e,indentation:Je,markRunProps:Lt,numbering:Yt,listStyle:zn}=v.paragraph;if(He&&await b.styles?.paragraph?.setStyle?.({target:Be,styleId:He}),je&&await b.format?.paragraph?.setAlignment?.({target:Be,alignment:je}),$e){const qn=$e,Yr=qn.lineRule??"auto",Nr=new Set(["auto","exact","atLeast"]).has(Yr)?Yr:"auto",Lr={...qn.before!=null?{before:Math.round(qn.before*20)}:{},...qn.after!=null?{after:Math.round(qn.after*20)}:{},...qn.line!=null?{line:Math.round(Nr==="auto"?qn.line*240:qn.line*20),lineRule:Nr}:{}};await b.format?.paragraph?.setSpacing?.({target:Be,...Lr})}if(Je){const qn={...Je.left!=null?{left:Cs(Je.left)}:{},...Je.right!=null?{right:Cs(Je.right)}:{},...Je.firstLine!=null?{firstLine:Cs(Je.firstLine)}:{},...Je.hanging!=null?{hanging:Cs(Je.hanging)}:{}};await b.format?.paragraph?.setIndentation?.({target:Be,...qn})}Lt&&await b.format?.paragraph?.setMarkRunProps?.({target:Be,markRunProps:Lt}),Yt&&await b.format?.paragraph?.setNumbering?.({target:Be,...Yt}),zn&&((await Ls(Ue))?.address?.nodeType==="listItem"?await b.lists?.applyStyle?.({target:oA(Re.blockId,ye),style:zn}):Yt&&await b.format?.paragraph?.setNumbering?.({target:Be,...Yt}))}}h.mode==="armed"&&pm(),qt()},mm=(f,v,b)=>{const A=uU(f,v),E=A?A.then(()=>(gc(f,v,b),nn)):(gc(f,v,b),nn);return fu(f)?.inline?.kind==="toggle"&&(Jn=E),E},bA=f=>({id:f,getState:()=>ht.toolbar.commands[f]??fc(f,y(),ht.selection,Ms(ht.selection)),observe:v=>Li(b=>b.toolbar.commands[f]??{enabled:!1,active:!1,supported:!1,source:"unsupported",reason:at.commandUnsupported}).subscribe(v),execute:v=>gc(f,v),executeAsync:v=>mm(f,v)}),mU=f=>{he.set(f.id,f),qt();const v=()=>{he.delete(f.id),qt()};return Object.assign(v,{handle:bA(f.id),unregister:v})},gm=Po(f=>f.selection),vm=Di(gm),wA=()=>{const f=T();if(typeof f?.getHandles!="function")return{reason:at.hostCapabilityUnavailable};let v=null;try{v=f.getHandles()}catch(A){const E=A?.reason;return{reason:E==="host-not-ready"||E==="host-disposed"||E==="editing-mount-required"?at.notReady:at.hostCapabilityUnavailable}}const b=v?.editing?.selectionTargets;return typeof b?.apply!="function"?{reason:at.hostCapabilityUnavailable}:{helper:b}},CA={get:vm.get,getSnapshot:vm.getSnapshot,subscribe:vm.subscribe,observe:vm.observe,current:()=>dl().value,capture:()=>{const f=gm.get();return f.empty||!f.target&&!f.selectionTarget?null:{...f,capturedAt:Date.now()}},restore:f=>{const v=E=>(qt(),{...E,success:E.ok});if(!f||typeof f!="object")return v({ok:!1,reason:at.targetUnresolved});if(!S())return v({ok:!1,reason:at.notReady});const b=MH(f);if(!b)return v({ok:!1,reason:at.targetUnresolved});const A=wA();if(!("helper"in A))return v({ok:!1,reason:A.reason});try{return v(Zk(A.helper.apply(b)))}catch{return v({ok:!1,reason:at.hostCapabilityUnavailable})}},apply:f=>{if(!S())return{ok:!1,reason:at.notReady};const v=wA();if(!("helper"in v))return{ok:!1,reason:v.reason};try{const b=v.helper.apply(f);return qt(),Zk(b)}catch{return{ok:!1,reason:at.hostCapabilityUnavailable}}},getAnchorRect:f=>{const v=T();if(typeof v?.getSelectionAnchorRect=="function"){const b=xt(()=>v.getSelectionAnchorRect(f),null);return b&&typeof b=="object"&&(Number(b.width)>0||Number(b.height)>0)?b:null}return null},getRects:f=>{const v=gm.get(),b=v.selectionTarget??v.target;if(v.empty||!b)return[];const A=Em.getRect({target:b,relativeTo:f?.relativeTo});return A.found?A.rects:[]}},gU={get ids(){return Bn()},has:f=>fu(f)!=null||he.has(f),get:f=>bA(f),execute:gc,executeAsync:mm,register:mU,getContextMenuItems:f=>{const v=[];for(const b of he.values()){const A=b.contextMenu;A&&xt(A.when?()=>A.when(f):void 0,!0)&&v.push({id:b.id,label:A.label,group:A.group,order:A.order,invoke:()=>gc(b.id,void 0,f)})}return v.sort((b,A)=>(b.order??0)-(A.order??0)||b.label.localeCompare(A.label))}},sb=Di(Po(f=>f.toolbar)),vU={get:sb.get,getSnapshot:()=>ht.toolbar,subscribe:sb.subscribe,observe:sb.observe,execute:gc,executeAsync:mm},vc=async(f,v)=>{if(!S())return{success:!1,ok:!1,reason:at.notReady};if(!f)return{success:!1,ok:!1,reason:at.targetUnresolved};const b=T(),A=b?.scrollTargetIntoView;if(typeof A!="function")return{success:!1,ok:!1,reason:at.hostCapabilityUnavailable};try{const E={target:f,block:v?.block??"center",behavior:v?.behavior??"smooth"},U=await Promise.resolve(v?.shouldContinue?A.call(b,E,v.shouldContinue):A.call(b,E));return U&&typeof U=="object"&&U.success===!1?{success:!1,ok:!1,reason:V0(U.reason,at.targetUnresolved)}:{success:!0,ok:!0}}catch{return{success:!1,ok:!1,reason:at.hostCapabilityUnavailable}}},ym=async(f,v,b,A)=>{const E=f==="trackChanges"?A?.story:void 0,U=$e=>{if(!E||!$e||typeof $e!="object")return $e;const Je=$e,Lt=Je.address&&typeof Je.address=="object"?Je.address:null;return Je.story||Lt?.story?$e:{...Je,story:E}},Y=f==="trackChanges"?sH:If,re=b.find($e=>rl($e,v,E)),ye=re&&typeof re=="object"?re:null,Re=f==="trackChanges"&&ye?.type==="move"&&(ye.subtype==="move-to"||ye.subtype==="move-from")?ye.subtype:null,Ue=Re&&typeof ye?.trackedChangeCanonicalId=="string"?ye.trackedChangeCanonicalId:v,Ye=$e=>{if(!Re)return Y($e);const Je=If($e);if(Je?.kind!=="move")return null;const Lt=Re==="move-to"?Je.destination:Je.source;return j0(Lt)?Lt:null},De=Y(re),Ke=f!=="trackChanges"||!Re&&j0(If(re));if(De&&Ke)return U(De);const Be=y()?.[f],He=f==="comments"?{commentId:v}:{id:Ue,...E?{story:E}:{}},je=Be?.get;if(typeof je!="function")return U(De);try{return U(Ye(await Promise.resolve(je.call(Be,He)))??De)}catch{return U(De)}};function _A(f,v){if(ba())return cr("Comments are read-only.","DOCUMENT_READONLY");if(wu())return cr("Resolving comments is disabled.","DOCUMENT_READONLY");const b=y()?.comments,A=b?.patch;if(typeof A!="function")return cr("comments.patch is unavailable.");const E=cr("comments.patch failed.");return xt(()=>Aa(A.call(b,{commentId:f,status:v}),E),E)}const bm=()=>ba()?cr("Comments are read-only.","DOCUMENT_READONLY"):null,SA=(f,v)=>{const b=v&&typeof v=="object"?v:null;let A=Array.from(f);b?.includeResolved===!1&&(A=A.filter(ye=>ye.status!=="resolved"));const E=Number(b?.offset),U=Number.isInteger(E)&&E>0?E:0,Y=Number(b?.limit),re=Number.isInteger(Y)&&Y>=0?U+Y:void 0;return A.slice(U,re)},zu=Po(f=>f.comments),wm=Di(zu),yU={get:wm.get,getSnapshot:wm.getSnapshot,subscribe:wm.subscribe,observe:wm.observe,list:f=>{const v=zu.get();if(v.status!=="pending")return SA(v.items,f);const b=y()?.comments,A=xt(b?.list?()=>b.list(f):void 0,null);return Or(A)?[]:SA(Array.isArray(A?.items)?A.items:[],f)},getById:f=>{const v=zu.get().items.find(E=>Un(E)===f)??null;if(v)return v;const b=y()?.comments,A=xt(b?.get?()=>b.get({commentId:f}):void 0,null);return Or(A)?null:A},createFromCapture:(f,v)=>{const b=bm();if(b)return b;const A=y()?.comments,E=A?.create;if(typeof E!="function")return cr("comments.create is unavailable.");const U=cr("comments.create failed.");return xt(()=>Aa(E.call(A,{target:f.target??f.selectionTarget,text:v.text}),U),U)},createFromSelection:f=>{const v=bm();if(v)return v;const b=y()?.comments,A=b?.create;if(typeof A!="function")return cr("comments.create is unavailable.");const E=gm.get(),U=E.target??E.selectionTarget;if(E.empty||!U)return cr("A range selection is required to comment.","NO_SELECTION");const Y=cr("comments.create failed.");return xt(()=>Aa(A.call(b,{target:U,text:f.text}),Y),Y)},reply:(f,v)=>{const b=bm();if(b)return b;const A=y()?.comments,E=A?.reply??A?.create;if(typeof E!="function")return cr("comments.reply is unavailable.");const U=cr("comments.reply failed.");return xt(()=>Aa(E===A?.reply?E.call(A,{parentCommentId:f,text:v.text}):E.call(A,{parentCommentId:f,text:v.text}),U),U)},resolve:f=>_A(f,"resolved"),reopen:f=>_A(f,"active"),delete:f=>{const v=bm();if(v)return v;const b=y()?.comments,A=b?.delete??b?.remove;if(typeof A!="function")return cr("comments.delete is unavailable.");const E=cr("comments.delete failed.");return xt(()=>Aa(A.call(b,{commentId:f}),E),E)},setActive:f=>{if(f==null)return ge=null,qt(),!0;if(!S())return!1;const v=zu.get();if(v.listStatus!=="ready")return!1;const b=fH(v.items,f);return!b||!v.items.some(A=>Un(A)===b)?!1:(ge=b,qt(),!0)},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:S()?at.documentApiUnavailable:at.notReady};const v=await ym("comments",f,zu.get().items);return v?vc(v):{success:!1,ok:!1,reason:at.targetUnresolved}}},Ia=Po(f=>f.trackChanges),ab=(f,v)=>{const b=Ia.get().items.filter(Re=>Un(Re)!==null);if(b.length===0)return null;const A=ht.trackChanges.activeId,E=ae?.id===A?ae.story:void 0;let U=A?b.findIndex(Re=>rl(Re,A,E)):-1;U===-1&&A&&E&&(U=b.findIndex(Re=>rl(Re,A)));const Y=b[U===-1?f>0?0:b.length-1:(U+f+b.length)%b.length],re=Un(Y),ye=eA(Y);return ze(ye?{id:re,story:ye}:{id:re},v),qt(),re};let kA=Promise.resolve();const bU=f=>{const v=oe;return kA.catch(()=>{}).then(()=>wU(f,v))},wU=async(f,v)=>{if(oe!==v)return{success:!1};const b=ae,A=ab(f,{invalidateQueuedNavigation:!1});if(A==null)return{success:!1};const E=ae,U=Ce,Y=()=>oe===v&&ae===E&&Ce===U,re=()=>{Y()&&(ze(b,{invalidateQueuedNavigation:!1}),qt())};E&&qe.add(E);try{const ye=await ym("trackChanges",A,Ia.get().items,E?.story?{story:E.story}:void 0);if(!Y())return{success:!1};if(!ye)return re(),{success:!1};bo+=1;try{const Re=await vc(ye,{behavior:"auto",shouldContinue:Y});return Y()?(!Re.ok&&Re.reason!==at.targetNotVisible?(re(),Ie(b)):Ie(E),{success:Re.ok}):{success:!1}}finally{bo=Math.max(0,bo-1),bo===0&&(Y()?oi&&ts(Os(oi)):Ie(ae))}}finally{E&&qe.delete(E)}},AA=f=>{const v=bU(f);return kA=v.then(()=>{},()=>{}),v},Cm=Di(Ia),CU={get:()=>(pi(),Cm.get()),getSnapshot:()=>(pi(),Cm.getSnapshot()),subscribe:f=>(pi(),Cm.subscribe(f)),observe:f=>(pi(),Cm.observe(f)),list:()=>(pi(),Ia.get().items),accept:f=>lb("accept",f),reject:f=>lb("reject",f),acceptAll:()=>Hu("accept",{scope:"all"},null),rejectAll:()=>Hu("reject",{scope:"all"},null),next:()=>ab(1),previous:()=>ab(-1),navigateNext:()=>AA(1),navigatePrevious:()=>AA(-1),getAt:f=>{if(!f||typeof f!="object"||typeof f.x!="number"||typeof f.y!="number")return null;const v=ub(f);if(v.length===0)return null;const b=Ia.get().items;let A;for(const E of v){if(E.type!=="trackedChange")continue;let U;if(E.story){if(A===void 0&&(A=Ts()),!A)continue;U=A}else U=b;const Y=U.find(re=>rl(re,E.id,E.story));if(Y)return E.story?{id:Y.id,item:Y,story:E.story}:{id:Y.id,item:Y}}return null},setActive:f=>{if(f==null)return ze(null),Ie(null),qt(),!0;if(!S())return!1;const v=typeof f=="string"?{id:f}:{id:f.id,story:f.story};if(typeof v.id!="string"||v.id.length===0)return!1;const b=v.id;if(v.story){const A=Ts();if(!A)return!1;const E=rA(A,v.story).toPublicId(v.id)??v.id;if(!A.some(U=>rl(U,E,v.story)))return!1;v.id=E}else{const A=Ia.get().items,E=Ef(A).toPublicId(v.id)??v.id;if(!A.some(U=>Un(U)===E))return!1;v.id=E}return b!==v.id&&(v.paintedEntityId=b),ze(v),Ie(v),qt(),!0},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:S()?at.documentApiUnavailable:at.notReady};oe+=1,xe+=1;const v=xe,b=Ia.get().items,A=Ef(b).toPublicId(f)??f,E=eA(b.find(re=>Un(re)===A)),U=ae,Y={id:A,...E?{story:E}:{},...A!==f?{paintedEntityId:f}:{}};qe.add(Y);try{const re=await ym("trackChanges",A,b,E?{story:E}:void 0);if(xe!==v)return{success:!1,ok:!1};if(!re)return{success:!1,ok:!1,reason:at.targetUnresolved};ze(Y);const ye=xe,Re=ae,Ue=Ce,Ye=()=>xe===ye&&ae===Re&&Ce===Ue,De=()=>{Ye()&&(ze(U,{invalidateQueuedNavigation:!1}),qt())};qt(),bo+=1;try{const Ke=await vc(re,{behavior:"auto",shouldContinue:Ye});return Ye()?(!Ke.ok&&Ke.reason!==at.targetNotVisible?(De(),Ie(U)):Ie(Y),Ke):{success:!1,ok:!1}}finally{bo=Math.max(0,bo-1),bo===0&&(Ye()?oi&&ts(Os(oi)):Ie(ae))}}finally{qe.delete(Y)}}},lb=(f,v)=>{const{id:b,story:A}=typeof v=="string"?{id:v,story:void 0}:v;return Hu(f,{kind:"id",id:b,...A?{story:A}:{}},b,A)},Hu=(f,v,b,A)=>{try{return Kr(_U(f,v,b,A))}catch{return!1}},_U=(f,v,b,A)=>{if(ba())return!1;const E=y()?.trackChanges,U=v.scope==="all",Y=v.kind==="range",re=v.kind==="ids";if(gl({kind:f,scope:U?"all":"id"},E))return!1;const ye=U?`${f}All`:f,Re=!Y&&!re&&!A&&E&&typeof E[ye]=="function"?E[ye]:null,Ue=E&&typeof E.decide=="function"?E.decide:null;return!Re&&!Ue?!1:Re?Re.call(E,b??{}):Ue.call(E,{decision:f,target:v})},cb=Po(f=>f.contentControls),zf=f=>cb.get().items.find(v=>v?.id===f)??null,_m=Di(cb),SU=(f=>{if(f===void 0)return _m.get();const v=tm(f);return v?zf(v):null}),kU={get:(f=>(f!==void 0&&Ei("api"),SU(f))),getSnapshot:_m.getSnapshot,subscribe:_m.subscribe,observe:_m.observe,list:()=>(Ei("api"),cb.get().items),getById:f=>(Ei("api"),zf(f)),getRect:f=>{const v=tm(f);if(!v)return sl("unresolved");Ei("panel");const b=zf(v);if(!b)return sl("unresolved");const A=G0(b);return A?Em.getRect({target:A}):sl("unavailable")},scrollIntoView:async f=>{const v=tm(f);if(!v)return{success:!1};Ei("panel");const b=zf(v);if(!b)return{success:!1};const A=G0(b);return A?{success:(await vc(A,{block:f.block,behavior:f.behavior})).ok}:{success:!1}},focus:async f=>{const v=tm(f);if(!v)return{success:!1,reason:"invalid-id"};if(!S())return{success:!1,reason:"not-ready"};Ei("panel");const b=zf(v);if(!b)return{success:!1,reason:"not-found"};const A=G0(b);if(!A)return{success:!1,reason:"not-reachable"};if(!(await vc(A,{block:f.block,behavior:f.behavior})).ok)return{success:!1,reason:"not-reachable"};const E=cH(A);if(!E)return{success:!1,reason:"not-reachable"};const U=CA.apply(E);return!U.ok&&U.reason!==at.hostCapabilityUnavailable?{success:!1,reason:"not-reachable"}:{success:!0}}},Sm=Di(Po(f=>f.fonts)),AU={get:Sm.get,getSnapshot:Sm.getSnapshot,subscribe:Sm.subscribe,observe:Sm.observe,getFamilyOptions:()=>ht.fonts.options,getSizeOptions:()=>ht.fonts.sizeOptions},km=Di(Po(f=>f.zoom)),IU={get:km.get,getSnapshot:km.getSnapshot,subscribe:km.subscribe,observe:km.observe,set:f=>{if(typeof t?.setZoom=="function")try{t.setZoom(f),qt()}catch{}},setMode:f=>{if(typeof t?.setZoomMode=="function")try{t.setZoomMode(f),qt()}catch{}}},Am=Di(Po(f=>f.document)),EU={get:Am.get,getSnapshot:Am.getSnapshot,subscribe:Am.subscribe,observe:Am.observe,setMode:f=>{if(typeof t?.setDocumentMode=="function")try{t.setDocumentMode(f),qt()}catch{}},export:f=>{if(typeof t?.export=="function")try{return Promise.resolve(t.export(f))}catch{return}},getText:()=>{const f=y(),v=xt(f?.getText?()=>f.getText({}):void 0,null);return typeof v=="string"?v:v&&typeof v=="object"&&typeof v.text=="string"?v.text:null},replaceFile:f=>{const v=t?.replaceFile??t?.loadDocument??t?.reload;if(typeof v=="function")try{return Promise.resolve(v.call(t,f))}catch{return}}},IA=()=>{if(typeof HTMLElement>"u")return null;const f=S()?.mount?.container;if(f instanceof HTMLElement)return f;const v=t?.element;return v instanceof HTMLElement?v:null},xU=(f,v)=>{if(typeof f!="number"||typeof v!="number"||!Number.isFinite(f)||!Number.isFinite(v))return[];const b=globalThis.document;if(!b||typeof b.elementFromPoint!="function")return[];const A=IA();if(!A)return[];const E=b.elementFromPoint(f,v);if(!E||!A.contains(E))return[];const U=[E],Y=Je=>{Je&&A.contains(Je)&&!U.includes(Je)&&U.push(Je)},re=b.elementsFromPoint;if(typeof re=="function"){let Je=[];try{Je=re.call(b,f,v)??[]}catch{Je=[]}for(const Lt of Je)Y(Lt)}const ye=[],Re=Je=>{Je&&A.contains(Je)&&!ye.includes(Je)&&!U.includes(Je)&&ye.push(Je)},Ue=Je=>{const Lt=Je.getBoundingClientRect;if(typeof Lt!="function")return!1;let Yt;try{Yt=Lt.call(Je)}catch{return!1}return Yt!=null&&f>=Yt.left&&f<=Yt.right&&v>=Yt.top&&v<=Yt.bottom};for(const Je of U){const Lt=Je.querySelectorAll;if(typeof Lt!="function")continue;let Yt;try{Yt=Lt.call(Je,"[data-track-change-marker]")}catch{continue}for(let zn=0;zn<Yt.length;zn+=1)Ue(Yt[zn])&&Re(Yt[zn])}ye.reverse();const Ye=[...ye,...U],De=Xk(Ye[0],A);for(let Je=1;Je<Ye.length;Je+=1)for(const Lt of Xk(Ye[Je],A))De.push(Lt);if(De.length===0)return De;const Ke=Ia.get().items,Be=Ef(Ke);let He;const je=new Set,$e=[];for(const Je of De){if(Je.type!=="trackedChange"){const qn=`${Je.type}:${Je.id}`;if(je.has(qn))continue;je.add(qn),$e.push(Je);continue}const Lt=lH(Je.storyKey)??aH(Je.story);let Yt;if(Lt){if(He===void 0&&(He=Ts()),!He||(Yt=rA(He,Lt).toPublicId(Je.id),!Yt||!He.some(qn=>rl(qn,Yt,Lt))))continue}else if(Yt=Be.toPublicId(Je.id),!Yt)continue;const zn=`trackedChange:${Yt}`;je.has(zn)||(je.add(zn),$e.push(Lt?{type:"trackedChange",id:Yt,story:Lt}:{type:"trackedChange",id:Yt}))}return $e};function ub(f,v){return typeof f=="object"?xU(f?.x,f?.y):null}const Uu=new Set;let db=!1;const EA=f=>{const v=T();if(typeof v?.observeGeometry!="function")return;let b=!1;const A=xt(()=>{const E=v.observeGeometry(()=>f.schedule());return b=!0,E},null);f.detach=typeof A=="function"?A:null,f.boundHost=b?v:null},Im=f=>{if(f.detach){try{f.detach()}catch{}f.detach=null}f.boundHost=null},xA=()=>{if(db=!1,!(Q||T()))for(const f of Uu)Im(f)},TU=()=>{if(!db){if(db=!0,typeof queueMicrotask=="function"){queueMicrotask(xA);return}Promise.resolve().then(xA)}},RU=()=>{const f=T();if(!f){TU();return}for(const v of Uu)v.boundHost&&v.boundHost===f||(Im(v),EA(v),v.schedule())};pc.push(RU);const Em={getRect:f=>{const v=T(),b=v?.getTargetRects;if(typeof b=="function"){const A=xt(()=>b.call(v,{target:f.target}),null);return A&&typeof A=="object"?A.success===!0&&Array.isArray(A.rects)?TH(xH(A.rects.filter(E=>E!=null&&typeof E=="object")),f.relativeTo):sl(typeof A.reason=="string"?A.reason:"unresolved"):sl("unresolved")}return sl("unavailable")},observe:f=>{const v=[];let b=0;const A=typeof requestAnimationFrame=="function",E=()=>{if(!A){f();return}b||(b=requestAnimationFrame(()=>{b=0,f()}))},U=Li(re=>({ready:re.ready,selection:re.selection,zoom:re.zoom}));v.push(U.subscribe(()=>E()));const Y={schedule:E,detach:null,boundHost:null};return EA(Y),Uu.add(Y),()=>{Uu.delete(Y),Im(Y),b&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(b);for(const re of v.splice(0))try{re()}catch{}}},getHost:()=>IA(),entityAt:ub,contextAt:f=>{const v=!!f&&typeof f.x=="number"&&typeof f.y=="number",b=v?f.x:0,A=v?f.y:0;return{point:{x:b,y:A},entities:v?ub({x:b,y:A}):[],selection:ht.selection,position:null,insideSelection:!1}},scrollIntoView:async f=>{const v=f?.target;if(!v)return{success:!1};let b=null;if(v.kind==="entity"){const A=v.entityType==="comment"?"comments":"trackChanges",E=A==="comments"?zu.get().items:Ia.get().items,U=v.entityType==="trackedChange"&&v.story?{story:v.story}:void 0;b=await ym(A,v.entityId,E,U)}else{const A=v,E=v,U=Array.isArray(A.segments)&&A.segments.length>0?A.segments:E.blockId&&E.range?[{blockId:E.blockId,range:E.range}]:null;if(U){const Y=v.story;b={kind:"text",segments:U,...Y?{story:Y}:{}}}}return b?{success:(await vc(b,{block:f.block??"center",behavior:f.behavior??"smooth"})).ok}:{success:!1}}},TA=f=>{const v=(f&&typeof f=="object"?f:null)?.target;return v&&typeof v=="object"?v:null},RA=f=>`metadata:resolve:${f}`,MU=f=>{const v=y()?.metadata;if(!v||typeof v.resolve!="function")return null;const{value:b}=kr(RA(f),Ft(),()=>v.resolve({id:f}),TA);return b},LU=async f=>{const v=y()?.metadata;if(!v||typeof v.resolve!="function")return null;try{const b=Ft(),A=await Promise.resolve(v.resolve({id:f}));if(b!==Ft())return null;const E=TA(A);return $.set(RA(f),{token:b,value:E,hasSettled:!0,inflightToken:null}),E}catch{return null}},DU={getRect:f=>{const v=y()?.metadata;if(!v||typeof v.resolve!="function")return sl("unavailable");const b=MU(f.id);return b?Em.getRect({target:b}):sl("unresolved")},scrollIntoView:async f=>{const v=await LU(f.id);return v?{success:(await vc(v,{block:f.block,behavior:f.behavior})).ok}:{success:!1}}},PU={inTable:!1,tableNodeId:null,rowIndex:null,columnIndex:null,cellNodeId:null,rows:null,columns:null},OU={getContext:()=>{const f=Fe();if(!f)return{...PU};const v=fe()?.table;return{inTable:!0,tableNodeId:f.tableNodeId,rowIndex:f.rowIndex,columnIndex:f.columnIndex,cellNodeId:f.cellNodeId,rows:typeof v?.rows=="number"?v.rows:null,columns:typeof v?.columns=="number"?v.columns:null}},isInTable:()=>Fe()!=null},xm={query:"",total:0,activeIndex:-1,open:!1,available:!1,caseSensitive:!1,includeDeletedText:!1,regex:!1,canReplace:!1,reason:at.searchUnavailable};let xn={...xm};const Tm=new Set,Ea=()=>{const f=T()?.search;return f&&typeof f=="object"?f:null},Bs=()=>{const f=I()?.search;return f&&typeof f=="object"?f:null},Hf=()=>{const f=Ea();if(f&&typeof f.setSession=="function")return!0;const v=Bs();return!!v&&typeof v.query=="function"&&typeof v.getState=="function"},rs=()=>{for(const f of[...Tm])try{f(xn)}catch{}},ii=f=>(xn={...xn,...f},rs(),xn);let qr=0,yc=null;const MA=()=>{const f=yc;yc=null,f&&xt(()=>(f(),null),null)},FU=()=>{qr+=1,MA();const f=Hf();xn={...xm,available:f,reason:f?void 0:at.searchUnavailable},rs()};Qt.push(FU);const BU=f=>{if(!f)return!1;const v=f.queryError;if(v&&typeof v=="object"&&v.code==="invalid-pattern")return!0;const b=f.rejection;return f.status==="rejected"&&!!b&&typeof b=="object"&&b.code==="invalid-pattern"},fb=(f,v=!1)=>{const b=f&&typeof f=="object"?f:null;if(!b)return null;const A=Array.isArray(b.matches)?b.matches:[],E=typeof b.total=="number"&&Number.isFinite(b.total)?b.total:A.length,U=typeof b.activeMatchIndex=="number"?b.activeMatchIndex:typeof b.activeIndex=="number"?b.activeIndex:-1;return{...typeof b.query=="string"?{query:b.query}:{},total:E,activeIndex:U,canReplace:b.canReplace===!0||v,...b.includeDeletedText===!0?{includeDeletedText:!0}:{},...b.regex===!0?{regex:!0}:{},...BU(b)?{invalidPattern:!0}:{}}},wo=()=>{const f=L("find.replace"),v=L("find.replaceAll");return f?.enabled===!0||v?.enabled===!0},Co=(f,v=!1)=>{const b=fb(f,v);if(!b){ii({total:0,activeIndex:-1,canReplace:!1,reason:void 0});return}ii({...b.query!==void 0?{query:b.query}:{},total:b.total,activeIndex:b.activeIndex,canReplace:b.canReplace,...b.includeDeletedText!==void 0?{includeDeletedText:b.includeDeletedText}:{},...b.regex!==void 0?{regex:b.regex}:{},reason:b.invalidPattern?at.searchInvalidPattern:void 0})},xa=()=>{const f=Ea();if(f&&typeof f.getState!="function")return xn={...xn,available:Hf(),reason:Hf()?void 0:at.searchUnavailable},xn;if(!f){const b=Bs();if(b&&typeof b.getState=="function"){const A=fb(xt(()=>b.getState(),null),wo());if(A)return xn={...xn,...A.query!==void 0?{query:A.query}:{},total:A.total,activeIndex:A.activeIndex,canReplace:A.canReplace,available:!0,reason:A.invalidPattern?at.searchInvalidPattern:void 0,open:xn.open||!!A.query},xn}return xn={...xm,query:xn.query,caseSensitive:xn.caseSensitive,includeDeletedText:xn.includeDeletedText},xn}const v=fb(xt(()=>f.getState(),null));return v&&(xn={...xn,...v.query!==void 0?{query:v.query}:{},total:v.total,activeIndex:v.activeIndex,canReplace:v.canReplace,...v.includeDeletedText!==void 0?{includeDeletedText:v.includeDeletedText}:{},...v.regex!==void 0?{regex:v.regex}:{},available:!0,reason:v.invalidPattern?at.searchInvalidPattern:void 0,open:xn.open||!!v.query}),xn},Vu=f=>{const v=f&&typeof f=="object"?f:null;if(v?.status==="committed")return{ok:!0};if(v?.status==="rejected"&&v.reason==="read-only")return{ok:!1,reason:at.documentReadonly};const b=v?.rejection;return v?.status==="rejected"&&b&&typeof b=="object"&&b.code==="read-only-document"?{ok:!1,reason:at.documentReadonly}:{ok:!1,reason:at.operationUnavailable}},Rm=Di({get:()=>xa(),subscribe:f=>(Tm.add(f),()=>Tm.delete(f))}),NU={get:Rm.get,getSnapshot:Rm.getSnapshot,subscribe:Rm.subscribe,observe:Rm.observe,open:()=>Hf()?(ii({available:!0,open:!0,reason:void 0}),{ok:!0}):(ii({available:!1,open:!1,reason:at.searchUnavailable}),{ok:!1,reason:at.searchUnavailable}),close:()=>{if(qr+=1,yc)MA();else{const f=Ea();if(f&&typeof f.clear=="function")xt(()=>f.clear(),null);else{const v=Bs();v&&typeof v.query=="function"&&xt(()=>v.query({query:""}),null)}}xn={...xm,available:Hf(),reason:void 0},xn.available||(xn.reason=at.searchUnavailable),rs()},search:(f,v)=>{const b=Ea(),A=!!v?.caseSensitive,E=v?.includeDeletedText===!0,U=v?.regex===!0,Y=++qr;if(!b||typeof b.setSession!="function"){const re=Bs();if(re&&typeof re.query=="function"&&typeof re.getState=="function"){ii({query:f,caseSensitive:A,includeDeletedText:E,regex:U,available:!0,open:!0,reason:void 0}),yc=()=>{re.query({query:""})};const ye=xt(()=>re.query({query:f,caseSensitive:A,includeDeletedText:E,regex:U}),null);return Or(ye)?Promise.resolve(ye).then(Re=>{Y===qr&&Co(Re,wo())},()=>{Y===qr&&ii({available:!1,reason:at.searchUnavailable})}):Co(ye,wo()),Co(xt(()=>re.getState(),null),wo()),xn}return ii({query:f,total:0,activeIndex:-1,available:!1,caseSensitive:A,includeDeletedText:E,regex:U,reason:at.searchUnavailable})}if(ii({query:f,caseSensitive:A,includeDeletedText:E,regex:U,available:!0,open:!0,reason:void 0}),yc=()=>{typeof b.clear=="function"&&b.clear()},Co(xt(()=>b.setSession(f,{caseSensitive:A,includeDeletedText:E,...U?{regex:!0}:{},highlight:!0}),null)),f.length>0&&xn.total===0&&xn.reason!==at.searchInvalidPattern){const re=Bs();if(re&&typeof re.query=="function"&&typeof re.getState=="function"){const ye=yc;yc=()=>{ye?.(),re.query({query:""})};const Re=xt(()=>re.query({query:f,caseSensitive:A,includeDeletedText:E,regex:U}),null);Or(Re)?Promise.resolve(Re).then(Ue=>{Y===qr&&Co(Ue,wo())},()=>{Y===qr&&ii({available:!1,reason:at.searchUnavailable})}):Co(Re,wo()),Co(xt(()=>re.getState(),null),wo())}}return xn},next:()=>{const f=Ea();if(!f||typeof f.next!="function"){const v=Bs();if(!v||typeof v.next!="function"||typeof v.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(xn.total===0)return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.next(),null);if(Or(b)){const A=qr;Promise.resolve(b).then(E=>{A===qr&&Co(E,wo())}).catch(()=>{A===qr&&ii({available:!1,reason:at.searchUnavailable})})}else Co(b,wo());return Co(xt(()=>v.getState(),null),wo()),{ok:!0}}return xn.total===0?{ok:!1,reason:at.operationUnavailable}:(Co(xt(()=>f.next(),null)),{ok:!0})},previous:()=>{const f=Ea();if(!f||typeof f.previous!="function"){const v=Bs();if(!v||typeof v.previous!="function"||typeof v.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(xn.total===0)return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.previous(),null);if(Or(b)){const A=qr;Promise.resolve(b).then(E=>{A===qr&&Co(E,wo())}).catch(()=>{A===qr&&ii({available:!1,reason:at.searchUnavailable})})}else Co(b,wo());return Co(xt(()=>v.getState(),null),wo()),{ok:!0}}return xn.total===0?{ok:!1,reason:at.operationUnavailable}:(Co(xt(()=>f.previous(),null)),{ok:!0})},clear:()=>{qr+=1;const f=Ea();if(f&&typeof f.clear=="function"&&xt(()=>f.clear(),null),!f||typeof f.clear!="function"){const v=Bs();v&&typeof v.query=="function"&&xt(()=>v.query({query:""}),null)}ii({query:"",total:0,activeIndex:-1,canReplace:!1})},replace:f=>{const v=Ea();if(!v){const A=Bs();if(!A||typeof A.replace!="function"||typeof A.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(!wo())return{ok:!1,reason:at.operationUnavailable};const E=xt(()=>A.replace({replacement:typeof f=="string"?f:""}),null);if(Or(E)){const U=qr;xa(),rs();const Y=()=>U===qr;return Promise.resolve(E).then(re=>(Y()&&(Co(re,wo()),xa(),rs()),Vu(re)),()=>(Y()&&ii({available:!1,reason:at.searchUnavailable}),{ok:!1,reason:at.searchUnavailable}))}return xa(),rs(),Vu(E)}if(typeof v.replaceCurrent!="function")return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.replaceCurrent(typeof f=="string"?f:""),null);return xa(),rs(),Vu(b)},replaceAll:f=>{const v=Ea();if(!v){const A=Bs();if(!A||typeof A.replaceAll!="function"||typeof A.getState!="function")return{ok:!1,reason:at.searchUnavailable};if(!wo())return{ok:!1,reason:at.operationUnavailable};const E=xt(()=>A.replaceAll({replacement:typeof f=="string"?f:""}),null);if(Or(E)){const U=qr;xa(),rs();const Y=()=>U===qr;return Promise.resolve(E).then(re=>(Y()&&(Co(re,wo()),xa(),rs()),Vu(re)),()=>(Y()&&ii({available:!1,reason:at.searchUnavailable}),{ok:!1,reason:at.searchUnavailable}))}return xa(),rs(),Vu(E)}if(typeof v.replaceAll!="function")return{ok:!1,reason:at.operationUnavailable};const b=xt(()=>v.replaceAll(typeof f=="string"?f:""),null);return xa(),rs(),Vu(b)}},LA=Po(f=>f.styles),Mm=Di(LA),zU={get:Mm.get,getSnapshot:Mm.getSnapshot,subscribe:Mm.subscribe,observe:Mm.observe,getCatalog:f=>vo(f).value,getQuickGallery:()=>LA.get().quickGallery,getActiveParagraphStyle:()=>Zn(ht.selection,Hn().cache).style},DA={select:Li,get state(){return ht},selection:CA,commands:gU,toolbar:vU,comments:yU,trackChanges:CU,contentControls:kU,fonts:AU,zoom:IU,document:EU,viewport:Em,metadata:DU,tables:OU,search:NU,styles:zU,formatPainter:{setPointerSelecting(f){Q||(h={...h,pointerSelecting:f})},notifyPointerUp(){Q||(h={...h,pointerSelecting:!1},vA())},setKeyboardSelecting(f){Q||(h={...h,keyboardSelecting:f})},notifyKeyUp(){Q||(h={...h,keyboardSelecting:!1},vA())},cancel(){Q||pm()},onModeChange(f){return Q?()=>{}:(p.add(f),()=>p.delete(f))}},createScope:()=>{const f=[];return{select:(v,b)=>{const A=Li(v,b);return{get:A.get,subscribe:E=>{const U=A.subscribe(E);return f.push(U),U}}},dispose:()=>{for(const v of f.splice(0))v()}}},destroy:()=>{if(!Q){Q=!0,dr.reset(),We(),W&&(clearTimeout(W),W=null),J&&(clearTimeout(J),J=null,K=0),V?.timer&&(clearTimeout(V.timer),V.timer=null),V=null,be&&(clearTimeout(be),be=null),ft&&(clearTimeout(ft),ft=null),an&&an(),an=null,bn=null,Kt.clear(),F.clear();for(const f of ns.splice(0))f();fr&&fr(),fr=null,oo=null,gi&&gi(),gi=null,$i=null,vi&&vi(),vi=null,oi=null,Do&&Do(),Do=null,io=null,Vo&&Vo(),Vo=null,yi=null;for(const f of Uu)Im(f);Uu.clear(),Ve.clear(),Tm.clear(),m+=1,p.clear(),qr+=1,he.clear()}}};return _=DA,DA}var BH=[{value:"Arial",label:"Arial",previewFamily:"Arial, sans-serif"},{value:"Calibri",label:"Calibri",previewFamily:"Calibri, sans-serif"},{value:"Courier New",label:"Courier New",previewFamily:'"Courier New", monospace'},{value:"Georgia",label:"Georgia",previewFamily:"Georgia, serif"},{value:"Times New Roman",label:"Times New Roman",previewFamily:'"Times New Roman", serif'},{value:"Verdana",label:"Verdana",previewFamily:"Verdana, sans-serif"}];function NH(e){const t=e.trim(),n=t[0];if(n==='"'||n==="'"){const o=t.indexOf(n,1);if(o>0)return t.slice(1,o).trim()}const r=t.indexOf(",");return(r===-1?t:t.slice(0,r)).trim().replace(/^["']|["']$/g,"")}function zH(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n||typeof n!="object")continue;const r=n,o=typeof r.logicalFamily=="string"?NH(r.logicalFamily):"";if(!o)continue;const i=typeof r.previewFamily=="string"&&r.previewFamily.trim()?r.previewFamily.trim():o;t.push({value:o,label:o,previewFamily:i})}return t}function HH(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n||typeof n!="object")continue;const r=n,o=typeof r.value=="string"?r.value.trim():"";if(!o)continue;const i=typeof r.label=="string"&&r.label.trim()?r.label.trim():o,s=typeof r.previewFamily=="string"&&r.previewFamily.trim()?r.previewFamily.trim():o;t.push({value:o,label:i,previewFamily:s})}return t}function UH(e,t=[]){const n=[],r=new Set,o=s=>{const a=String(s.value).trim().toLowerCase();!a||r.has(a)||(r.add(a),n.push(s))};for(const s of e)o(s);const i=t.length?t:BH;for(const s of i)o(s);return n}var VH=[{value:"8",label:"8"},{value:"9",label:"9"},{value:"10",label:"10"},{value:"11",label:"11"},{value:"12",label:"12"},{value:"14",label:"14"},{value:"16",label:"16"},{value:"18",label:"18"},{value:"24",label:"24"},{value:"36",label:"36"}];function jH(e,t){return e.activeMark?t.activeMarks.includes(e.activeMark):!1}It();var GH=Object.freeze(["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#F1948A","#82E0AA","#F8C471","#AED6F1","#D7BDE2","#A3E4D7","#F0B27A","#AEB6BF","#E74C3C","#2ECC71","#3498DB","#E67E22","#1ABC9C","#9B59B6","#34495E","#F39C12"]);async function WH(e,t){const n=new e6.default;return e.forEach((r,o)=>{n.file(t[o],r)}),n.generateAsync({type:"blob",compression:"DEFLATE"})}function $0(e){return!!(e&&(e.synced===!0||e.isSynced===!0))}function dA(e){try{e.synced=!0}catch{}try{e.isSynced=!0}catch{}}function KH(e,t){if(!e)return()=>{};if($0(e))return t(),()=>{};const n=typeof e.on=="function"?e.on.bind(e):null,r=typeof e.off=="function"?e.off.bind(e):null;if(!n)return t(),()=>{};let o=!1;const i=()=>{o||(o=!0,r?.("synced",a),r?.("sync",l))},s=()=>{o||(i(),t())},a=()=>{dA(e),s()},l=u=>{u!==!1&&(u===!0||$0(e))&&(dA(e),s())};return n("synced",a),n("sync",l),$0(e)&&s(),i}function Qo(e){return!!(e&&typeof e=="object"&&e.editorVersion===2)}function qH(e){const t=e&&typeof e=="object"?e.code:null;return t==="comment-export-missing-story-reference"||t==="v2-worker-comment-export-mode-unsupported"}function fA(e){return typeof e=="string"&&e.length>0?e:null}function eb(e){return e?Qo(e)?fA(e.documentId??e.options?.documentId??null):fA(typeof e.getDocumentId=="function"?e.getDocumentId():e.options?.documentId):null}function YH(e){if(!e||Qo(e))return null;const t=e;return t.documentRenderer??t.presentationEditor??null}function Gi(e){if(!e)return null;if(Qo(e))return e.fonts??null;const t=YH(e);return t?{getReport:()=>t.getFontReport?.()??[],getMissingFonts:()=>t.getMissingFonts?.()??[],getDocumentFonts:()=>[...new Set((t.getFontReport?.()??[]).map(n=>n.logicalFamily))],getDocumentFontOptions:()=>t.getDocumentFontOptions?.()??[],getFontFamilyOptions:()=>t.getFontFamilyOptions?.()??[],getLastFontsChangedPayload:()=>t.getLastFontsChangedPayload?.()??null,map:n=>t.mapFonts(n),unmap:n=>t.unmapFonts(n),add:n=>t.addFonts(Array.isArray(n)?n:[n]),preload:n=>t.preloadFonts(n)}:null}var om=class extends Dm.default{static{this.allowedTypes=[Tr,Ul,Fh]}#t=!1;#n=!1;#e=null;#i=null;#s=null;#a=null;#u=null;#d=null;#l=kk({});get uiConfig(){return this.#l}#f=Ak({});get interactionConfig(){return this.#f}#m=Ek({});get surfacesConfig(){return this.#m}#o;#r=new qF;#p=null;#y=!1;constructor(e){if(super(),this.version="0.0.0",this.users=[],this.whiteboard=null,this.colors=[],this.readyEditors=0,this.pendingCollaborationSaves=0,this.config={selector:"#superdoc",documentMode:"editing",allowSelectionInViewMode:!1,role:"editor",document:{},documents:[],editorExtensions:[],colors:[],users:[],user:{...M0},layoutEngineOptions:{},modules:{},licenseKey:void 0,telemetry:{enabled:!0},title:"SuperDoc",conversations:[],isInternal:!1,comments:{visible:!1},toolbarGroups:["left","center","right"],toolbarIcons:{},toolbarTexts:{},uiDisplayFallbackFont:"Arial, Helvetica, sans-serif",isDev:!1,disablePiniaDevtools:!1,onEditorBeforeCreate:()=>null,onEditorCreate:()=>null,onEditorDestroy:()=>null,onSourceComplete:()=>null,onSourceSignalsComplete:()=>null,onContentError:()=>null,onReady:()=>null,onCommentsUpdate:()=>null,onContentControlActiveChange:()=>null,onContentControlClick:()=>null,onAwarenessUpdate:()=>null,onLocked:()=>null,onPdfDocumentReady:()=>null,onSidebarToggle:()=>null,onCollaborationReady:()=>null,onEditorUpdate:()=>null,onCommentsListChange:()=>null,onException:()=>null,onListDefinitionsChange:()=>null,onPaginationUpdate:()=>null,onTransaction:()=>null,disableContextMenu:!1,viewOptions:{layout:"print"},useLayoutEngine:!0},!e.selector)throw new Error("SuperDoc: selector is required");const t=typeof e.selector=="string"?document.querySelector(e.selector):e.selector;if(!(t instanceof HTMLElement))throw new Error("SuperDoc: selector must be a valid CSS selector string or DOM element");this.#o=new FF({getModuleConfig:()=>this.#m}),this.#w(e,t)}async#w(e,t){this.config={...this.config,...e},!this.config.comments||typeof this.config.comments!="object"?this.config.comments={visible:!1}:typeof this.config.comments.visible!="boolean"&&(this.config.comments.visible=!1),jF(this.config),this.config.documents=this.config.documents||[],this.config.layoutEngineOptions=this.config.layoutEngineOptions||{};const n=this.config.viewOptions?.layout==="web",r=this.config.layoutEngineOptions?.flowMode==="semantic";if(n&&this.config.useLayoutEngine&&!r&&(console.warn("[SuperDoc] Web layout uses PM fallback unless layoutEngineOptions.flowMode is set to 'semantic'. Automatically disabling layout engine."),this.config.useLayoutEngine=!1),!n&&r&&(console.warn("[SuperDoc] flowMode 'semantic' is only valid with web layout. Coercing to 'paginated'."),this.config.layoutEngineOptions.flowMode="paginated"),this.editorVersion=2,this.#ve(),this.config.user=GF(this.config.user),this.config.layoutEngineOptions.virtualization||(this.config.layoutEngineOptions.virtualization={enabled:!0,window:5,overscan:1}),this.config.modules=this.config.modules||{},Object.prototype.hasOwnProperty.call(this.config.modules,"comments")||(this.config.modules.comments={}),this.config.modules.comments=w9(this.config.modules.comments),this.#l=kk(this.config),this.#f=Ak(this.config),this.#m=Ek(this.config),this.config.disableContextMenu=!this.#l.contextMenu.enabled,this.#l.comments.enabled?this.config.modules.comments===!1&&(this.config.modules.comments={}):this.config.modules.comments=!1,this.#l.comments.enabled){this.config.modules.comments===!0&&(this.config.modules.comments={});const i=this.config.modules.comments;i&&Object.assign(i,this.#f.comments)}if(this.config.colors=l6(this.config.colors),this.userColorMap=new Map,this.colorIndex=0,this.version="2.0.0-next.53",this.#b("🦋 [superdoc] Using SuperDoc version:",this.version),this.superdocId=e.superdocId||os(),this.colors=this.config.colors??[],this.#x(),await hT(),this.#t)return;if(await this.#T(this.config.modules),this.#t){this.#le();return}this.config.cspNonce&&this.#E(),this.user=this.config.user,this.users=this.config.users||[],this.socket=null,this.isDev=this.config.isDev||!1,this.activeEditor=null,this.comments=[],this.#p||(this.#p=this.#r.subscribe(i=>{this.#be(i.nextRuntimeId,i.legacyEditorProjection)})),this.isLocked=this.config.isLocked||!1,this.lockedBy=this.config.lockedBy||null;const o=document.createElement("div");o.style.display="contents",t.appendChild(o),this.#u=o,this.#L(),this.#S(),this.#we(),this.#_()}#_(){if(this.#M(),this.readyEditors=0,!this.app)throw new Error("SuperDoc: #startRuntime called before #initVueApp populated this.app");this.app.mount(this.#u)}#S(){const e=this.config.modules?.whiteboard,t=e!==!1&&(e?.enabled??!1);this.whiteboard=new cP({Renderer:DF,superdoc:this,enabled:t}),this.emit("whiteboard:init",{whiteboard:this.whiteboard})}get requiredNumberOfEditors(){return this.#h("requiredNumberOfEditors").documents.filter(e=>e.type===Tr).length}get ui(){return this.#d||(this.#d=FH({superdoc:this}),this.#t&&this.#d.destroy()),this.#d}get state(){return{documents:this.#h("state").documents,users:this.users}}getDocumentRuntimeForDocument(e){return typeof e!="string"||e.length===0?null:(this.superdocStore?.documents??[]).find(t=>t?.getEditor?.()?.options?.documentId===e)?.getDocumentRuntime?.()??null}getComment(e){return typeof e!="string"||e.length===0?null:this.commentsStore?.getComment?.(e)??null}get element(){return typeof this.config.selector=="string"?document.querySelector(this.config.selector):this.config.selector}#E(){const e=this.config.cspNonce,t=document.createElement;document.createElement=function(n){const r=t.call(this,n);return n.toLowerCase()==="style"&&r.setAttribute("nonce",e),r}}#x(){const e=this.config.document,t=!!e&&typeof e=="object"&&Object.keys(e)?.length,n=!!e&&typeof e=="string"&&e.length>0,r=!!e&&typeof File=="function"&&e instanceof File,o=!!e&&e instanceof Blob&&!(e instanceof File),i=this.config.documents&&this.config.documents?.length;if(t&&i&&console.warn("🦋 [superdoc] You can only provide one of document or documents"),t){const s=Fd(this.config.document);this.config.documents=[{id:os(),...s}]}else if(n)this.config.documents=[{id:os(),type:Tr,url:this.config.document,name:"document.docx"}];else if(r){const s=Fd(this.config.document);this.config.documents=[{id:os(),...s}]}else if(o){const s=Fd(this.config.document);this.config.documents=[{id:os(),...s}]}Array.isArray(this.config.documents)&&this.config.documents.length>0&&(this.config.documents=this.config.documents.map(s=>{const a=Fd(s);if(!a||typeof a!="object")return a;const l=typeof a=="object"&&"id"in a&&a.id||s&&typeof s=="object"&&"id"in s&&s.id;return{...a,id:l||os()}}))}#M(){const{app:e,pinia:t,superdocStore:n,commentsStore:r,highContrastModeStore:o}=ZD({disablePiniaDevtools:!!this.config.disablePiniaDevtools});this.app=e,this.pinia=t,this.app.config.globalProperties.$config=this.config,this.app.config.globalProperties.$documentMode=this.config.documentMode,this.app.config.globalProperties.$superdoc=this,this.app.provide("surfaceManager",this.#o),this.superdocStore=n,this.commentsStore=r,this.highContrastModeStore=o,typeof this.superdocStore.setExceptionHandler=="function"&&this.superdocStore.setExceptionHandler(s=>this.emit("exception",s)),this.superdocStore.init(this.config);const i=this.config.modules.comments;this.commentsStore.init(i||{}),this.isCollaborative&&J8(this),this.#ae()}#c(e,t){t&&this.on(e,t)}#L(){this.#c("editorBeforeCreate",this.config.onEditorBeforeCreate),this.#c("editorCreate",this.config.onEditorCreate),this.#c("editorDestroy",this.config.onEditorDestroy),this.#c("source:complete",this.config.onSourceComplete),this.#c("source:signals-complete",this.config.onSourceSignalsComplete),this.#c("ready",this.config.onReady),this.#c("comments-update",this.config.onCommentsUpdate),this.#c("content-control:active-change",this.config.onContentControlActiveChange),this.#c("content-control:click",this.config.onContentControlClick),this.#c("awareness-update",this.config.onAwarenessUpdate),this.#c("locked",this.config.onLocked),this.#c("pdf:document-ready",this.config.onPdfDocumentReady),this.#c("sidebar-toggle",this.config.onSidebarToggle),this.#c("collaboration-ready",this.config.onCollaborationReady),this.on("collaboration-ready",e=>this.#j(e?.editor??null)),this.#c("editor-update",this.config.onEditorUpdate),this.on("content-error",this.onContentError),this.#c("exception",this.config.onException),this.#c("list-definitions-change",this.config.onListDefinitionsChange),this.#c("pagination-update",this.config.onPaginationUpdate),this.#c("fonts-resolved",this.config.onFontsResolved),this.#c("fonts-changed",this.config.onFontsChanged),this.#c("zoomChange",this.config.onZoomChange),this.#c("viewport-change",this.config.onViewportChange)}async#T({collaboration:e}={}){return e?(this.isCollaborative=!1,this.config.documents.length===0&&(this.config.documents=[{id:os(),type:Tr,name:"document.docx"}]),this.config.v2CollaborationPreflightFailure={code:"collaboration-v1-config-unsupported",message:"SuperDoc v2 cannot use modules.collaboration because it is the SuperDoc v1 collaboration API. SuperDoc did not attach the provider or change the document. Configure Document.v2Collaboration with a v2 room instead."},this.config.documents):this.config.documents}#D(e,t){this.isCollaborative=!0,this._commentsCollabInitialized=!1,this.ydoc=Hr(e),this.provider=Hr(t),this.#W();const n=this.config;this._cleanupAwareness=q8(t,this,n.user),n.documents.forEach(r=>{r.ydoc=e,r.provider=t,r.role=this.config.role})}#k(){this.#a=null,this.#g(),typeof this._cleanupAwareness=="function"&&(this._cleanupAwareness(),this._cleanupAwareness=null),this.isCollaborative=!1,this._commentsCollabInitialized=!1,this.ydoc=void 0,this.provider=void 0;const e=this.config;delete e.modules.collaboration,e.documents.forEach(t=>{delete t.ydoc,delete t.provider})}#g(){if(this.#i){try{this.#i()}catch{}this.#i=null}if(this.#s){try{this.#s()}catch{}this.#s=null}}#j(e){this.#g(),Qo(e)&&(this.#G(e),this.#P(e))}#G(e){const t=e.presence;if(!t||typeof t.subscribe!="function")return;const n=iP(()=>this.user),r=o=>{if(this.#t)return;const i=n.next(o);this.emit("awareness-update",{...i,superdoc:this})};try{const o=t.getSnapshot?.();o&&r(o),this.#i=t.subscribe(r)}catch(o){console.warn("[SuperDoc] v2 awareness bridge failed to subscribe",o)}}#P(e){const t=e.lock;if(!t||typeof t.subscribe!="function")return;const n=r=>{this.#t||this.#C(!!r.isLocked,this.#O(r.lockedBy??null))};try{if(this.#a&&typeof t.setLocked=="function"){const o=this.#a;t.setLocked(o.isLocked,o.isLocked?o.lockedBy:null),this.#a=null}const r=t.getSnapshot?.();r&&n(r),this.#s=t.subscribe(n)}catch(r){console.warn("[SuperDoc] v2 lock bridge failed to subscribe",r)}}#O(e){return!e||typeof e!="object"||Array.isArray(e)?null:{...e}}#F(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}#C(e,t){this.isLocked===e&&this.#F(this.lockedBy,t)||(this.isLocked=e,this.lockedBy=t,this.#b("🦋 [superdoc] Locking superdoc:",e,t,`
|
|
103
103
|
|
|
104
104
|
|
|
105
105
|
`),this.emit("locked",{isLocked:e,lockedBy:t}))}#W(){const e=this.config.user;if(!e||e.color)return;const t=this.colors.length>0?this.colors:GH,n=e.id||e.email||e.name||"";let r=5381;for(let o=0;o<n.length;o++)r=(r<<5)+r^n.charCodeAt(o);e.color=t[Math.abs(r)%t.length]}async upgradeToCollaboration(e){const{target:t,mountedDocumentId:n}=this.#he(e);this.#n=!0;try{const r=await this.#de(),o=this.#v(),i=this.#K();this.#B();let s=null;try{this.#a=i,s=this.#fe(n);const a=this.#ce(t,r);await s,this.#ue(a,t),this.#a=null}catch(a){if(s&&this.#e){const l=this.#e;this.#e=null,l(),await s.catch(()=>{})}throw this.#A(o),a}}finally{this.#e=null,this.#n=!1}}#K(){return{isLocked:this.isLocked,lockedBy:this.lockedBy?{...this.lockedBy}:null}}#v(){const e=this.config.documents.find(r=>r.type===Tr),t=this.superdocStore?.documents.find(r=>r.id===e.id)??null,n=t?mn(t):null;return{isCollaborative:this.isCollaborative,configV2Collaboration:e.v2Collaboration??null,configData:e.data,storeDoc:t,storeV2Collaboration:this.#X(n),storeData:t?.data}}#A(e){this.#a=null;const t=this.config.documents.find(n=>n.type===Tr);t.v2Collaboration=e.configV2Collaboration,t.data=e.configData,this.isCollaborative=e.isCollaborative,e.storeDoc&&(e.storeDoc.data=e.storeData,this.#I(e.storeDoc,e.storeV2Collaboration),this.#N(e.storeDoc))}#B(){if(this.#t)throw new Error("SuperDoc: instance was destroyed during upgrade")}#h(e){if(!this.superdocStore)throw new Error(`SuperDoc: ${e} requires the instance to be ready; wait for the "ready" event before calling.`);return this.superdocStore}#q(e){if(!this.commentsStore)throw new Error(`SuperDoc: ${e} requires the instance to be ready; wait for the "ready" event before calling.`);return this.commentsStore}#R(e){if(!this.superdocStore)throw new Error(`SuperDoc: ${e} requires the instance to be ready; wait for the "ready" event before calling.`)}#Y(e,t){const n=this.superdocStore?.documents;if(Array.isArray(n))for(const r of n){const o=mn(r);o.ydoc&&typeof o.ydoc=="object"&&"value"in o.ydoc&&(o.ydoc.value=e),o.provider&&typeof o.provider=="object"&&"value"in o.provider&&(o.provider.value=t)}}#X(e){if(!e)return null;const t=e.v2Collaboration;return t&&typeof t=="object"&&"value"in t?t.value:t??null}#I(e,t){const n=mn(e).v2Collaboration;if(n&&typeof n=="object"&&"value"in n){n.value=t;return}e.v2Collaboration=t}#N(e){const t=mn(e).editorMountNonce;if(t&&typeof t=="object"&&"value"in t&&typeof t.value=="number"){t.value+=1;return}const n=e;n.editorMountNonce=(typeof n.editorMountNonce=="number"?n.editorMountNonce:0)+1}#z(e){return e.providerFamily==="liveblocks"?{providerType:"liveblocks",documentId:e.documentId,roomMode:e.roomMode,...e.publicApiKey?{publicApiKey:e.publicApiKey}:{},...e.authEndpoint?{authEndpoint:e.authEndpoint}:{}}:e.providerFamily==="hocuspocus"?{providerType:"hocuspocus",documentId:e.documentId,roomMode:e.roomMode,...e.serverUrl?{serverUrl:e.serverUrl}:{},...e.params?{params:e.params}:{},...e.token?{token:e.token}:{}}:{providerType:"y-websocket",documentId:e.documentId,roomMode:e.roomMode,...e.serverUrl?{serverUrl:e.serverUrl}:{},...e.params?{params:e.params}:{}}}#ce(e,t){const n=this.config.documents.find(i=>i.type===Tr),r=this.#h("upgradeToCollaboration").documents.find(i=>i.id===n.id);if(!r)throw new Error("SuperDoc: source document store entry is not available for upgrade");const o=this.#z({...e,roomMode:"create"});return n.data=t,n.v2Collaboration=o,r.data=t,this.#I(r,o),this.isCollaborative=!0,this.readyEditors=0,this.#N(r),{configDoc:n,storeDoc:r}}#ue(e,t){const n=this.#z({...t,roomMode:"join"});e.configDoc.v2Collaboration=n,this.#I(e.storeDoc,n)}async#de(){const e=this.activeEditor;if(Qo(e)&&typeof e.save=="function"){const r=await e.save();return this.#Q(r)}const t=this.config.documents.find(r=>r.type===Tr),n=(this.superdocStore?.documents.find(r=>r.id===t.id)??null)?.data??t.data;if(n instanceof Blob)return n;if(n instanceof Uint8Array||n instanceof ArrayBuffer)return this.#Q(n);throw new Error("SuperDoc: upgradeToCollaboration() requires a live v2 editor save or DOCX Blob source")}#Q(e){if(e instanceof Blob)return e;if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),new Blob([t],{type:Tr})}if(e instanceof ArrayBuffer)return new Blob([e],{type:Tr});throw new Error("SuperDoc: active v2 editor returned an unsupported DOCX save payload")}#$(e,t){const n=eb(e),r=(n?this.config.documents.find(a=>a.id===n):null)??this.config.documents.find(a=>a.type==="application/vnd.openxmlformats-officedocument.wordprocessingml.document");if(!r)return;const o=this.#Q(t),i=r.v2Collaboration&&typeof r.v2Collaboration=="object"&&r.v2Collaboration.roomMode==="create"?{...r.v2Collaboration,roomMode:"join"}:null;r.data=o,i&&(r.v2Collaboration=i);const s=this.superdocStore?.documents.find(a=>a.id===r.id)??null;s&&(s.data=o,i&&this.#I(s,i))}#ke(){const e=this.superdocStore?.documents;if(!e?.length)throw new Error("SuperDoc: no store documents available for upgrade");const t=e[0].getDocumentRuntime?.()||e[0].getEditor?.();if(!t?.attachCollaboration)throw new Error("SuperDoc: editor does not support attachCollaboration");return t}#Ae(){this.#k(),this.#Y(null,null)}#Ie(e){const n=e.editor??e;return n.options?.collaborationIsReady?Promise.resolve():new Promise(r=>{let o=!1;const i=()=>{o||(o=!0,clearTimeout(s),typeof n.off=="function"&&n.off("collaborationReady",a))},s=setTimeout(()=>{i(),console.warn("[SuperDoc] collaborationReady did not fire within 10 s after collaboration attach. Continuing — collaboration is active but cursor/presence setup may be delayed."),r(void 0)},1e4),a=()=>{i(),r(void 0)};this.#e=()=>{i(),r(void 0)},typeof n.on=="function"?n.on("collaborationReady",a):(i(),r(void 0))})}#fe(e){return new Promise((n,r)=>{let o=!1;const i=()=>{o||(o=!0,clearTimeout(a),this.off("collaboration-ready",s))},s=l=>{const u=l?.editor;Qo(u)&&eb(u)===e&&(!u.presence&&!u.lock||(i(),n()))},a=setTimeout(()=>{i(),r(new Error(`SuperDoc: v2 collaboration runtime did not become ready within 20000 ms for mounted document "${e}".`))},2e4);this.on("collaboration-ready",s),this.#e=()=>{i(),r(new Error("SuperDoc: instance was destroyed during upgrade"))}})}#Ee(e){return new Promise((n,r)=>{let o,i=!1,s=()=>{};const a=()=>{i=!0,clearTimeout(o),s()};s=KH(e,()=>{i||(a(),n())}),i||(o=setTimeout(()=>{a(),r(new Error("SuperDoc: collaboration provider did not sync within 10000 ms. The provider exposes on/off but never emitted sync(true) or synced."))},1e4)),this.#e=()=>{i||(a(),r(new Error("SuperDoc: instance was destroyed during upgrade")))}})}#he(e){if(this.#t)throw new Error("SuperDoc: cannot upgrade a destroyed instance");if(this.#n)throw new Error("SuperDoc: upgrade already in progress");if(this.isCollaborative)throw new Error("SuperDoc: instance is already collaborative");const t=this.config,n=t.documents.filter(l=>l.type===Tr);if(n.length===0)throw new Error("SuperDoc: no DOCX document found for upgrade");if(n.length>1)throw new Error("SuperDoc: upgradeToCollaboration() only supports a single DOCX document");if(t.documents.length!==n.length)throw new Error("SuperDoc: upgradeToCollaboration() only supports single-DOCX instances");if(!Qo(this.#me()))throw new Error("SuperDoc: upgradeToCollaboration() requires a ready v2 DOCX editor");const r=n[0],o=r.id;if(typeof o!="string"||o.length===0)throw new Error("SuperDoc: source document is missing its mounted document identity");const i=t.modules?.collaboration,s=e.ydoc||e.provider?{ydoc:e.ydoc,provider:e.provider}:i?{...i}:null,a=DS({v2Collaboration:e.v2Collaboration??this.#pe(r.v2Collaboration)??i?.v2Collaboration??i?.v2??null,legacyCollaboration:s,documentType:Tr,documentCount:t.documents.length,...typeof window<"u"?{authEndpointBaseUrl:window.location.href}:{}});if(!a.ok)throw new Error(`SuperDoc: upgradeToCollaboration() ${a.reason}: ${a.message}`);return{target:a.target,mountedDocumentId:o}}#pe(e){return e&&typeof e=="object"&&"value"in e?e.value:e}#me(){const e=this.config.documents.find(n=>n.type===Tr),t=this.#h("upgradeToCollaboration").documents.find(n=>n.id===e.id)?.getEditor?.();if(!t)throw new Error("SuperDoc: source editor not yet created — wait for the ready event before upgrading");return t}addSharedUser(e){this.#R("addSharedUser");const t=Hc({actor:e});t&&this.users.some(n=>Hc({actor:n})===t)||this.users.push(e)}removeSharedUser(e){this.#R("removeSharedUser");const t=typeof e=="string"?Pv(e):"",n=typeof e=="string"?`email:${t}`:Hc({actor:e});this.users=this.users.filter(r=>{const o=Hc({actor:r});return n?o!==n:t?Pv(r.email)!==t:!0})}onContentError({error:e,editor:t}){const n=t.options?.documentId,r=this.#h("onContentError").documents.find(i=>i.id===n),o=typeof r?.id=="string"?r.id:typeof n=="string"?n:"";this.config.onContentError?.({error:e,editor:t,documentId:o,file:r?.data})}broadcastPdfDocumentReady(){this.emit("pdf:document-ready")}broadcastReady(){this.readyEditors===this.requiredNumberOfEditors&&this.emit("ready",{superdoc:this})}broadcastEditorBeforeCreate(e){this.emit("editorBeforeCreate",{editor:mk(e)})}broadcastEditorCreate(e){this.readyEditors++,this.broadcastReady(),this.#ge(e),this.emit("editorCreate",{editor:mk(e)})}broadcastSourceComplete(){this.emit("source:complete")}broadcastSourceSignalsComplete(){this.emit("source:signals-complete")}#ee=new WeakSet;#ge(e){if(!e||typeof e.on!="function"||this.#ee.has(e))return;this.#ee.add(e),e.on("fonts-changed",n=>{this.#te(e)&&this.#H(n)});const t=(e.documentRenderer??e.presentationEditor)?.getLastFontsChangedPayload?.();t&&this.#te(e)&&this.#H(t)}#te(e){return!this.activeEditor||e===this.activeEditor}#ne=null;#H(e){this.#ne=e,this.emit("fonts-changed",e)}broadcastEditorDestroy(){this.emit("editorDestroy")}broadcastSidebarToggle(e){this.emit("sidebar-toggle",e)}#ve(){Array.isArray(this.config.editorExtensions)&&this.config.editorExtensions.length>0&&console.warn("[SuperDoc] `editorExtensions` is a legacy ProseMirror concept and is ignored by superdoc@2. Use `extensions` with `defineSuperDocExtension`; legacy ProseMirror extensions (Node.create, Mark.create, addPmPlugins, custom schema) do not run in v2.")}#b(...e){(console.debug?console.debug:console.log)("🦋 🦸♀️ [superdoc]",...e)}#Z=null;get fonts(){return this.#Z||(this.#Z={getReport:()=>Gi(this.activeEditor)?.getReport()??[],getMissingFonts:()=>Gi(this.activeEditor)?.getMissingFonts()??[],getDocumentFontOptions:()=>Gi(this.activeEditor)?.getDocumentFontOptions()??[],getFontFamilyOptions:()=>Gi(this.activeEditor)?.getFontFamilyOptions()??[],getDocumentFonts:()=>Gi(this.activeEditor)?.getDocumentFonts()??[],onReport:e=>{const t=this.activeEditor,n=t?Gi(t)?.getLastFontsChangedPayload?.()??null:this.#ne??null;return n&&e(n),this.on("fonts-changed",e),()=>this.off("fonts-changed",e)},map:e=>{const t=Gi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.map requires an active editor");t.map(e)},unmap:e=>{const t=Gi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.unmap requires an active editor");t.unmap(e)},add:e=>{const t=Gi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.add requires an active editor");t.add(e)},preload:e=>{const t=Gi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.preload requires an active editor");return t.preload(e)}}),this.#Z}#U(){const e=this.activeEditor!==null;this.#re(),this.activeEditor=null,this.toolbar?.setActiveEditor?this.toolbar.setActiveEditor(null):this.toolbar&&(this.toolbar.activeEditor=null),e&&this.emit("active-editor-change")}#V=null;#re(){if(this.#V){try{this.#V()}catch{}this.#V=null}}#ye(e){this.#re();const t=Gi(e);if(!t?.onChanged)return;const n=t.getLastFontsChangedPayload?.();n&&this.#H(n),this.#V=t.onChanged(r=>this.#H(r))}#be(e,t){this.#y=!0;try{if(e===null){this.#U();return}this.#r.get(e)?.kind==="v2"&&Qo(t)?this.#oe(t):this.#U()}finally{this.#y=!1}}#oe(e){if(Qo(e)){!this.#y&&this.#r.getActive()&&this.#r.setActive(null,"set-active-v2-facade");const t=this.activeEditor;this.activeEditor=e,this.#ye(e),this.toolbar?.setActiveEditor?.(e),t!==this.activeEditor&&this.emit("active-editor-change");return}this.#U()}setActiveEditor(e){this.#oe(e)}getV2FeatureMatrix(){return[{feature:"source.docx-bytes",status:"supported",reason:"SuperDoc normalizes File/Blob/ArrayBuffer/Uint8Array DOCX inputs for the separate DOCX Engine dependency"},{feature:"source.url",status:"supported",reason:"shell-owned source normalization resolves URL-backed DOCX inputs before opening the injected v2 editor"},{feature:"source.blank",status:"supported",reason:"shell-owned blank-document seeding resolves to DOCX bytes before mounting the injected v2 editor"},{feature:"execution.browser-worker",status:"supported",reason:"the shipped public v2 shell opens DOCX documents through the browser-worker path by default when collaboration is not active"},{feature:"distribution.cdn-iife",status:"supported",reason:"the CDN/IIFE distribution ships the public bundle plus the emitted v2 browser-worker asset and opens DOCX documents through the worker-backed v2 runtime"},{feature:"docx.open-render",status:"supported",reason:"superdoc@2 opens and renders DOCX documents through its DOCX Engine dependency"},{feature:"docx.review-handles",status:"supported",reason:"Comment/tracked-change list + decide via v2 host handles"},{feature:"shell.toolbar",status:"supported",reason:"new SuperDoc({ toolbar }) mounts the rendered built-in toolbar shell and the superdoc.toolbar handle, both backed by the V2 command controller and the internal compatibility catalog. Explicit item-level limits stay fail-closed in the shared command matrix (for example search replace and copyFormat)."},{feature:"shell.rich-formatting",status:"supported",reason:"Rich inline, paragraph, and list formatting route through the V2 command controller and public Document API (format.* / styles.* / lists.*): bold, italic, underline, strikethrough, font family/size, text/highlight color, alignment, line spacing, linked styles, bullet/numbered lists, indent, and clear formatting."},{feature:"shell.comments-sidebar",status:"supported",reason:"ui-phase3-002: v2 comments adapter routes create/reply/edit/resolve/delete through V2EditorHost.dispatch"},{feature:"shell.comments-sidebar.reopen",status:"supported",reason:'ui-phase3-002: v2 comments sidebar reopens resolved threads through the v2 comments adapter (activeEditor.doc.comments.patch({ status: "active" }))'},{feature:"shell.tracked-change-sidebar",status:"supported",reason:"SD-3722: v2 tracked-change adapter lists and decides exact body, header/footer-part, and note targets"},{feature:"shell.tracked-change-sidebar.bulk",status:"not-shipped",reason:"bulk-tracked-change-decisions-omitted: acceptAll/rejectAll are matrix-disabled by default in the v2 host"},{feature:"shell.tracked-change-sidebar.non-body",status:"supported",reason:"SD-3722: public v2 shell hydrates and targets header/footer-part and note tracked changes"},{feature:"shell.comments-sidebar.persistence",status:"supported",reason:"ui-phase3-004: comment create/reply/edit/resolve/delete persist through SuperDoc.export() → re-mount via the v2 host save bridge"},{feature:"shell.tracked-change-sidebar.persistence",status:"supported",reason:"ui-phase3-004: tracked-change accept/reject persist through SuperDoc.export() → re-mount via the v2 host save bridge"},{feature:"shell.comments-sidebar.author-required",status:"supported",reason:"ui-phase3-004: v2 comments adapter surfaces commentCommandsReason=author-required from the host capability matrix; write controls disable and forced dispatch reports ok:false"},{feature:"shell.find-replace",status:"supported",reason:"Ctrl/Cmd+F opens the SuperDoc find/replace surface in v2; find/navigation/replace/replaceAll route through the single host search session (host.search) via ui.search, with replace failing closed in viewing/read-only mode"},{feature:"shell.ai-writer",status:"supported",reason:"built-in toolbar renders the modules.ai-gated AI writer and applies generated text through the public Document API facade"},{feature:"shell.collaboration",status:"supported",reason:"v2 single-doc y-websocket collaboration is wired through document.v2Collaboration, including collaboration-ready, awareness-update, and locked event bridges; arbitrary external { ydoc, provider } adapters remain unsupported"},{feature:"shell.context-menu",status:"not-shipped",reason:"context-menu-omitted: public v2 shell disables the legacy context menu"},{feature:"shell.page-metrics",status:"supported",reason:"ui-phase4-001: v2 page metrics snapshot (editorVersion: 2, documentId, renderEpoch, layoutGeneration, zoom, pages[], capabilities) available via superdoc.activeEditor.pageMetrics.{ getSnapshot, subscribe, setZoom, scrollToPage, revealBodyTarget, pageIndexForBodyTarget }"},{feature:"shell.zoom",status:"supported",reason:"ui-phase4-001: SuperDoc.setZoom routes to V2EditorHost.setZoom in v2 mode; single CSS-transform wrapper applies scale to the painted document, page metrics viewport coords scale with the same zoom value"},{feature:"shell.ruler-page-margins",status:"supported",reason:"ui-phase4-002: v2 ruler renders against the V2PageMetricsSnapshot and dispatches margin drags through a narrow v2 page-layout bridge (`activeEditor.pageLayout.setMargins(...)`) backed by `doc.sections.setPageMargins(...)`. The v2 page metrics snapshot now reports `capabilities.marginEdit = { supported: true }`"},{feature:"shell.custom-extensions",status:"supported",reason:"superdoc@2 supports customer extensions through `extensions` + `defineSuperDocExtension`; command execution and diagnostics are exposed through the narrow `activeEditor.extensions` facet. Legacy ProseMirror `editorExtensions` are ignored in v2."},{feature:"pdf.viewer",status:"supported",reason:"editorVersion ignored for PDF documents"},{feature:"html.viewer",status:"supported",reason:"editorVersion ignored for HTML documents"}]}get v2(){return this.editorVersion!==2?null:{version:2,featureMatrix:this.getV2FeatureMatrix()}}registerEditorRuntime(e){this.#r.register(e)}unregisterEditorRuntime(e){return this.#r.unregister(e)}getActiveRuntime(){return this.#r.getActive()}setActiveRuntime(e,t){this.#r.setActive(e,t)}resolveRuntimeFromEventTarget(e){return this.#r.resolveFromEventTarget(e)}activateRuntimeFromEventTarget(e,t){const n=this.#r.resolveFromEventTarget(e);return n?(this.#r.setActive(n.id,t),!0):!1}toggleRuler(){const e=this.#h("toggleRuler");this.config.rulers=!this.config.rulers,e.documents.forEach(t=>{t.rulers=this.config.rulers}),this.toolbar?.updateToolbarState?.()}canPerformPermission({permission:e,role:t=this.config.role,isInternal:n=this.config.isInternal,comment:r=null,trackedChange:o=null}={}){if(!e)return!1;let i=r??o?.comment??null;const s=o?.commentId||o?.id;if(!i&&s&&this.commentsStore?.getComment){const a=this.commentsStore.getComment(s),l=a?.getValues;i=typeof l=="function"?l.call(a):a}return da(e,t,n,{superdoc:this,currentUser:this.config.user,comment:i??null,trackedChange:o??null})}#we(){const e=this.config.modules?.toolbar,t=e&&typeof e=="object"?e:{},n=this.#l.toolbar;this.toolbarElement=n.container??void 0;const r=this.config.ui,o=typeof r=="object"&&r!==null&&r.toolbar!==void 0;if(!(n.enabled&&(n.container||e===!0||e!=null&&typeof e=="object"||o))){this.toolbar=null;return}try{this.toolbar=Bz({...t,...n.options,selector:this.toolbarElement,superdoc:this,editor:this.activeEditor,role:this.config.role,isDev:this.isDev,documentMode:this.config.documentMode,groups:n.options.groups,toolbarGroups:n.options.toolbarGroups,icons:n.options.icons,texts:n.options.texts,uiDisplayFallbackFont:this.config.uiDisplayFallbackFont})}catch(i){console.warn("[SuperDoc] built-in toolbar mount failed",i),this.toolbar=null}}addCommentsList(e){!this.config?.modules?.comments||this.config.role==="viewer"||(e&&(this.config.modules.comments.element=e),this.commentsList=new MR(this.config.modules?.comments,this),this.config.onCommentsListChange&&this.config.onCommentsListChange({isRendered:!0}))}removeCommentsList(){this.commentsList&&(this.commentsList.close(),this.commentsList=null,this.config.onCommentsListChange&&this.config.onCommentsListChange({isRendered:!1}))}scrollToComment(e,t={}){if(!this.config?.modules?.comments||!e||typeof e!="string")return!1;const n=this.element||document,r=globalThis.CSS?.escape?globalThis.CSS.escape(e):e.replace(/"/g,'\\"'),o=n.querySelector(`[data-comment-ids*="${r}"]`);if(!o)return!1;const{behavior:i="smooth",block:s="start"}=t??{};return o.scrollIntoView({behavior:i,block:s}),this.commentsStore?.setActiveComment?.(this,e),!0}async navigateTo(e){const t=this.superdocStore?.documents;if(!t?.length)return!1;const n=t[0].getDocumentRuntime?.();return n?.navigateTo?n.navigateTo(e):!1}async scrollToElement(e){const t=this.superdocStore?.documents;if(!t?.length)return!1;const n=t[0].getDocumentRuntime?.();return n?.scrollToElement?n.scrollToElement(e):!1}setDisableContextMenu(e=!0){if(!e&&this.#l.contextMenu.suppressed)return;const t=!!e;this.config.disableContextMenu!==t&&(this.config.disableContextMenu=t,this.superdocStore?.documents?.forEach(n=>{const r=n.getDocumentRuntime?.();r?.setContextMenuDisabled&&r.setContextMenuDisabled(t);const o=n.getEditor?.();o?.setOptions&&o.setOptions({disableContextMenu:t})}))}setShowBookmarks(e=!0){const t=!!e,n=this.config.layoutEngineOptions=this.config.layoutEngineOptions||{};n.showBookmarks!==t&&(n.showBookmarks=t,this.superdocStore?.documents?.forEach(r=>{r.getDocumentRuntime?.()?.setShowBookmarks?.(t)}))}setShowFormattingMarks(e=!0){const t=!!e,n=this.config.layoutEngineOptions=this.config.layoutEngineOptions||{};n.showFormattingMarks!==t&&(n.showFormattingMarks=t,this.superdocStore?.documents?.forEach(r=>{r.getDocumentRuntime?.()?.setShowFormattingMarks?.(t)}),this.emit("formatting-marks-change",{showFormattingMarks:t,superdoc:this}),this.toolbar?.updateToolbarState?.())}toggleFormattingMarks(){const e=!!this.config.layoutEngineOptions?.showFormattingMarks;this.setShowFormattingMarks(!e)}setDocumentMode(e){if(!e)return;this.#R("setDocumentMode"),e=e.toLowerCase(),this.config.documentMode=e,this.#ae();const t={viewing:()=>this.#se(),editing:()=>this.#Ce(),suggesting:()=>this.#ie()};t[e]&&(t[e](),this.emit("document-mode-change",{documentMode:e}))}#J(e,t){const n=typeof e.id=="string"&&e.id.length>0?e.id:null;if(n){const i=this.#r.getAllByDocumentId(n);if(i.length>0){for(const s of i)s.setDocumentMode(t);return}}const r=typeof e.getDocumentRuntime=="function"?e.getDocumentRuntime():null;if(typeof r?.setDocumentMode=="function"){r.setDocumentMode(t);return}const o=typeof e.getEditor=="function"?e.getEditor():null;o&&typeof o.setDocumentMode=="function"&&o.setDocumentMode(t)}setTrackedChangesPreferences(e){const t=e&&Object.keys(e).length?{...e}:void 0;this.config.layoutEngineOptions||(this.config.layoutEngineOptions={}),this.config.layoutEngineOptions.trackedChanges=t,this.superdocStore?.documents?.forEach(n=>{const r=typeof n.getDocumentRuntime=="function"?n.getDocumentRuntime():null;r?.setTrackedChangesOverrides&&r.setTrackedChangesOverrides(t)})}#Ce(){if(this.config.role!=="editor")return this.#ie();const e=this.#h("setDocumentMode");if(e.documents.length>0){const t=e.documents[0]?.getEditor();t&&this.setActiveEditor(t)}this.setTrackedChangesPreferences({mode:"review",enabled:!0}),e.documents.forEach(t=>{t.restoreComments?.(),this.#J(t,"editing")})}#ie(){if(!["editor","suggester"].includes(this.config.role??""))return this.#se();const e=this.#h("setDocumentMode");if(e.documents.length>0){const t=e.documents[0]?.getEditor();t&&this.setActiveEditor(t)}this.setTrackedChangesPreferences({mode:"review",enabled:!0}),e.documents.forEach(t=>{t.restoreComments?.(),this.#J(t,"suggesting")})}#se(){const e=this.#h("setDocumentMode");this.toolbar?.setActiveEditor?this.toolbar.setActiveEditor(null):this.toolbar&&(this.toolbar.activeEditor=null);const t=this.config.comments?.visible===!0,n=this.config.trackChanges?.visible===!0;this.setTrackedChangesPreferences(n?{mode:"review",enabled:!0}:{mode:"original",enabled:!0}),!t&&!n&&this.commentsStore?.clearEditorCommentPositions?.(),e.documents.forEach(r=>{t||n?r.restoreComments?.():r.removeComments?.(),this.#J(r,"viewing")})}#ae(){const e=this.config.comments?.visible===!0,t=this.config.trackChanges?.visible===!0,n=this.config.documentMode==="viewing",r=e||t;this.commentsStore?.setViewingVisibility&&this.commentsStore.setViewingVisibility({documentMode:this.config.documentMode,commentsVisible:e,trackChangesVisible:t});const o=this.superdocStore?.documents;Array.isArray(o)&&o.length>0&&o.forEach(i=>{const s=typeof i.getDocumentRuntime=="function"?i.getDocumentRuntime():null;s?.setViewingCommentOptions&&s.setViewingCommentOptions({emitCommentPositionsInViewing:n&&r,enableCommentsInViewing:n&&e})})}search(e){const t=this.activeEditor?.commands,n=t?.search;if(typeof n=="function")return n.call(t,e,{searchModel:"visible"})}goToSearchResult(e){const t=this.activeEditor?.commands,n=t?.goToSearchResult;if(typeof n=="function")return!!n.call(t,e)}getZoom(){return this.superdocStore?.activeZoom??100}setZoom(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0){console.warn("[SuperDoc] setZoom expects a positive number representing percentage");return}if(!this.superdocStore){console.warn("[SuperDoc] setZoom called before initialization; use config.zoom.initial for the starting zoom");return}this.superdocStore.activeZoom=e,this.superdocStore.zoomMode="manual",this.emit("zoomChange",{zoom:e,mode:"manual"})}setZoomMode(e){if(e!=="manual"&&e!=="fit-width"){console.warn("[SuperDoc] setZoomMode expects 'manual' or 'fit-width'");return}if(!this.superdocStore){console.warn("[SuperDoc] setZoomMode called before initialization; use config.zoom.mode for the starting mode");return}this.superdocStore.zoomMode!==e&&(this.superdocStore.zoomMode=e,this.emit("zoomChange",{zoom:this.getZoom(),mode:e}))}getZoomState(){const e=h_(this.config.zoom?.fitWidth);return{mode:this.superdocStore?.zoomMode??"manual",value:this.superdocStore?.activeZoom??100,fitZoom:this.superdocStore?.viewportMetrics?.fitZoom??null,min:e.min,max:e.max}}getViewportMetrics(){return this.superdocStore?.viewportMetrics??null}getMeasurementUnit(){return this.superdocStore?.measurementUnit??"in"}setMeasurementUnit(e){if(e!=="in"&&e!=="cm"){console.warn("[SuperDoc] setMeasurementUnit expects 'in' or 'cm'");return}if(!this.superdocStore){console.warn("[SuperDoc] setMeasurementUnit called before initialization; use config.measurementUnit for the starting unit");return}this.superdocStore.measurementUnit!==e&&(this.superdocStore.measurementUnit=e,this.emit("measurement-unit-change",{unit:e}))}setLocked(e=!0){const t=this.activeEditor;if(Qo(t)&&typeof t.lock?.setLocked=="function"){t.lock.setLocked(e,e?{...this.user}:null);const n=t.lock.getSnapshot?.();n&&this.#C(!!n.isLocked,this.#O(n.lockedBy??null));return}this.config.documents.forEach(n=>{const r=n.ydoc;if(!r)return;const o=r.getMap("meta");r.transact(()=>{o.set("locked",e),e?o.set("lockedBy",this.user):o.delete("lockedBy")})}),this.#C(e,e?this.user:null)}getHTML(e={}){const t=[];return this.#h("getHTML").documents.forEach(n=>{const r=n.getEditor?.();r&&t.push(r)}),t.map(n=>n.getHTML(e))}lockSuperdoc(e=!1,t=null){this.#C(e,t)}async export({exportType:e=["docx"],commentsType:t="external",exportedName:n,additionalFiles:r=[],additionalFileNames:o=[],isFinalDoc:i=!1,triggerDownload:s=!0,fieldsHighlightColor:a=null}={}){const l=n4(n||this.config.title),u=await this.exportEditorsToDOCX({commentsType:t,isFinalDoc:i,fieldsHighlightColor:a}),c=[...r],d=[...o];if(e.includes("docx")&&u.forEach(m=>{c.push(m),d.push(`${l}.docx`)}),c.length===1)return s?t4(c[0],l,e[0]):c[0];const h=await WH(c,d);return s?t4(h,l,"zip"):h}async replaceFile(e){const t=this.activeEditor;if(Qo(t)&&typeof t.replaceFile=="function"){const r=await t.replaceFile(e),o=r&&typeof r=="object"?r.state:null;return(o===null||o==="review-ready"||o==="editing-ready")&&(this.#$(t,e),this.emit("document-replaced",{editor:t,host:t?.host})),r}const n=t&&!Qo(t)?t.replaceFile:null;if(typeof n=="function"){const r=await n.call(t,e),o=r&&typeof r=="object"?r.state:void 0;return(o==null||o==="review-ready"||o==="editing-ready")&&(this.#$(t,e),this.emit("document-replaced",{editor:t,host:t?.host})),r}throw new Error("SuperDoc: replaceFile is unavailable for the active editor")}async exportEditorsToDOCX({commentsType:e,isFinalDoc:t,fieldsHighlightColor:n}={}){const r=this.config?.modules?.comments!==!1;let o,i=!1;const s=()=>(i||(i=!0,e==="clean"?o=[]:r&&this.commentsStore&&typeof this.commentsStore.translateCommentsForExport=="function"&&(o=this.commentsStore.translateCommentsForExport(),Array.isArray(o)||(o=[]))),o),a=new WeakSet,l=u=>{"editor"in u&&u.error&&typeof u.error=="object"&&a.add(u.error)};this.on("exception",l);try{const u=this.#h("exportEditorsToDOCX").documents.map(async c=>{if(!c||c.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")return null;const d=typeof c.getEditor=="function"?c.getEditor():null,h=()=>!c.data||c.data.type&&c.data.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document"?null:c.data;if(!d||typeof d.exportDocx!="function")return h();const m=d.editorVersion===2;try{const p=await d.exportDocx(m?{isFinalDoc:t,commentsType:e,fieldsHighlightColor:n}:{isFinalDoc:t,comments:s(),commentsType:e,fieldsHighlightColor:n});if(p)return p}catch(p){if((!p||typeof p!="object"||!a.has(p))&&this.emit("exception",{error:p,document:c}),m&&(e==="clean"||qH(p)))throw p}return h()});return(await Promise.all(u)).filter(c=>c!=null)}finally{this.off("exception",l)}}async#_e(){this.#b("🦋 [superdoc] Triggering collaboration saves");const e=this.#h("save");return new Promise(t=>{e.documents.forEach((n,r)=>{if(this.#b(`Before reset - Doc ${r}: pending = ${this.pendingCollaborationSaves}`),this.pendingCollaborationSaves=0,n.ydoc){this.pendingCollaborationSaves++,this.#b(`After increment - Doc ${r}: pending = ${this.pendingCollaborationSaves}`);const o=n.ydoc.getMap("meta");o.observe(i=>{i.changes.keys.has("immediate-save-finished")&&(this.pendingCollaborationSaves--,this.pendingCollaborationSaves<=0&&t())}),o.set("immediate-save",!0)}}),this.#b(`FINAL pending = ${this.pendingCollaborationSaves}, but we have ${e.documents.filter(n=>n.ydoc).length} docs!`)})}async save(){const e=[this.#_e()];this.#b("🦋 [superdoc] Saving superdoc"),await Promise.all(e),this.#b("🦋 [superdoc] Save complete")}#Se(e,t){const n=e.provider;n&&n!==this.provider&&!t.some(o=>o.provider===n)&&(n.disconnect?.(),n.destroy?.());const r=e.ydoc;r&&r!==this.ydoc&&!t.some(o=>o.ydoc===r)&&r.destroy?.()}#le(){this.#a=null,this.#g(),typeof this._cleanupAwareness=="function"&&(this._cleanupAwareness(),this._cleanupAwareness=null);const e=this.config;e.socket?.cancelWebsocketRetry?.(),e.socket?.disconnect(),e.socket?.destroy(),this.ydoc?.destroy(),this.provider?.disconnect?.(),this.provider?.destroy?.(),e.documents.forEach(t=>{t.provider?.disconnect?.(),t.provider?.destroy?.(),t.ydoc?.destroy()})}openSurface(e){return this.#o.open(e)}closeSurface(e){this.#o.close(e)}async removeDocument(e){const t=typeof e=="string"?e:String(e??"");if(!t)return!1;const n=this.#h("removeDocument"),r=this.activeEditor,o=eb(r);for(const s of this.#r.getAllByDocumentId(t))this.#r.unregister(s.id);o===t&&r!==null&&this.#U();const i=n.removeDocument(t);return i?(this.#Se(i,n.documents),await _t(),!0):!1}destroy(){this.#t=!0,this.#e&&(this.#e(),this.#e=null),this.#o&&this.#o.destroy(),this.toolbar?.destroy?.(),this.app&&(this.#b("[superdoc] Unmounting app"),this.superdocStore?.reset(),this.app.unmount(),this.removeAllListeners(),delete this.app.config.globalProperties.$config,delete this.app.config.globalProperties.$superdoc),this.#d?.destroy(),this.#le(),this.#p?.(),this.#p=null,this.#r.clear(),this.#u&&(this.#u.remove(),this.#u=null)}focus(e={}){const t=this.getActiveRuntime();if(t?.getCapabilities().lifecycle.canFocus){t.focus(e).catch(n=>{console.warn("[SuperDoc] active editor runtime focus failed",n)});return}this.activeEditor?Qo(this.activeEditor)?this.activeEditor.focus?.(e):this.activeEditor.focus?.():this.#h("focus").documents.find(n=>{const r=n.getEditor?.();return r?(Qo(r)?r.focus?.(e):r.focus?.(),!0):!1})}setHighContrastMode(e){this.activeEditor&&(this.activeEditor.setHighContrastMode?.(e),this.highContrastModeStore?.setHighContrastMode(e))}};It();const hA="__SUPERDOC_V2_BROWSER_RUNTIME__";function XH(e=globalThis){const t=e[hA];return t&&typeof t=="object"?t:null}function QH(e={},t=globalThis){const n=XH(t)??{},r={...n,...e,vue:e.vue??n.vue??Z5};return t[hA]=r,r}QH();var ZH={action:"--sd-ui-action",actionHover:"--sd-ui-action-hover",actionText:"--sd-ui-action-text",bg:"--sd-ui-bg",hoverBg:"--sd-ui-hover-bg",activeBg:"--sd-ui-active-bg",disabledBg:"--sd-ui-disabled-bg",text:"--sd-ui-text",textMuted:"--sd-ui-text-muted",textDisabled:"--sd-ui-text-disabled",border:"--sd-ui-border"},JH=0;function pA(e){const{name:t,font:n,radius:r,shadow:o,colors:i,vars:s}=e,a=`sd-theme-${(t?t.replace(/[^a-zA-Z0-9-_]/g,"-"):null)||`custom-${++JH}`}`,l=[];if(i)for(const[u,c]of Object.entries(i)){if(c==null)continue;const d=ZH[u];d&&l.push(` ${d}: ${c};`)}if(n!=null&&l.push(` --sd-ui-font-family: ${n};`),r!=null&&l.push(` --sd-ui-radius: ${r};`),o!=null&&l.push(` --sd-ui-shadow: ${o};`),s)for(const[u,c]of Object.entries(s))c!=null&&l.push(` ${u}: ${c};`);return{className:a,css:l.length>0?`.${a} {
|
|
106
106
|
${l.join(`
|
|
107
107
|
`)}
|
|
108
|
-
}`:""}}function $H(e,t){if(typeof document>"u"||!t)return;let n=document.querySelector(`[data-sd-theme="${e}"]`);n||(n=document.createElement("style"),n.setAttribute("data-sd-theme",e),document.head.appendChild(n)),n.textContent=t}function eU(e){const{className:t,css:n}=pA(e);return $H(t,n),t}function tU(e){return pA(e)}function nU(e){if(!e||typeof e!="object")throw new Error("defineSuperDocExtension requires an extension object.");if(typeof e.id!="string"||e.id.length===0)throw new Error("defineSuperDocExtension requires a non-empty string `id`.");if(typeof e.activate!="function")throw new Error(`defineSuperDocExtension("${e.id}") requires an \`activate(ctx)\` function.`);if(e.storage!==void 0&&typeof e.storage!="function")throw new Error(`defineSuperDocExtension("${e.id}") \`storage\` must be a function returning the initial storage object.`);return e}var rU=Gu({BlankDOCX:()=>GC,DOCX:()=>Tr,HTML:()=>Fh,PDF:()=>Ul,SuperDoc:()=>om,buildTheme:()=>tU,compareVersions:()=>i6,createTheme:()=>eU,defineSuperDocExtension:()=>nU,getFileObject:()=>Ov},1),oU="SUPERDOC_ENGINE_CDN_BASE_URL",mA=Symbol.for("superdoc.docx-engine.cdn-load-state"),im="superdocDocxEngineStatus";function iU(e,t,n=null){const r=e?.[oU],o=typeof r=="string"&&r.trim()?r:n;if(typeof o=="string"&&o.trim())return sU(o);if(!t)throw new Error("SuperDoc: the CDN build is missing its exact DOCX Engine version");return`https://cdn.jsdelivr.net/npm/@superdoc/docx-engine@${t}`}function sU(e){const t=e.trim().replace(/\/+$/,""),n=t.match(/^([a-z][a-z\d+.-]*):/iu)?.[1]?.toLowerCase();if(n&&n!=="http"&&n!=="https")throw new TypeError(`SuperDoc: unsupported DOCX Engine CDN URL scheme ${n}:`);return t}function aU({engineVersion:e,buildBaseUrl:t}){dT(()=>{const n=iU(globalThis,e,t),r=globalThis[mA],o=r instanceof Map?r:new Map;if(globalThis[mA]=o,!o.has(n)){const i=Promise.all([import(`${n}/dist-cdn/docx-engine.es.js`),lU(`${n}/dist-cdn/style.css`)]).then(([s])=>s);o.set(n,i),i.catch(()=>{o.get(n)===i&&o.delete(n)})}return o.get(n)})}function lU(e){if(typeof document>"u")return Promise.resolve();const t=new URL(e,document.baseURI).href,n=Array.from(document.querySelectorAll('link[rel~="stylesheet"]')).find(o=>o.href===t);if(n?.sheet||n?.dataset[im]==="loaded")return Promise.resolve();const r=n?.dataset[im]==="loading";return n&&!r&&n.remove(),new Promise((o,i)=>{const s=r?n:document.createElement("link");let a=!1,l;const u=(m,p)=>{a||(a=!0,l?.disconnect(),s.dataset[im]=m,p())},c=()=>u("loaded",o),d=()=>u("error",()=>i(new Error(`SuperDoc: failed to load DOCX Engine styles from ${t}`))),h=()=>{s.isConnected||u("error",()=>i(new Error(`SuperDoc: DOCX Engine stylesheet was removed while loading from ${t}`)))};s.addEventListener("load",c,{once:!0}),s.addEventListener("error",d,{once:!0}),typeof globalThis.MutationObserver=="function"&&(l=new globalThis.MutationObserver(h),l.observe(document.head,{childList:!0})),r||(s.rel="stylesheet",s.href=t,s.dataset.superdocDocxEngine="true",s.dataset[im]="loading",document.head.appendChild(s))})}aU({engineVersion:"0.2.0-next.
|
|
108
|
+
}`:""}}function $H(e,t){if(typeof document>"u"||!t)return;let n=document.querySelector(`[data-sd-theme="${e}"]`);n||(n=document.createElement("style"),n.setAttribute("data-sd-theme",e),document.head.appendChild(n)),n.textContent=t}function eU(e){const{className:t,css:n}=pA(e);return $H(t,n),t}function tU(e){return pA(e)}function nU(e){if(!e||typeof e!="object")throw new Error("defineSuperDocExtension requires an extension object.");if(typeof e.id!="string"||e.id.length===0)throw new Error("defineSuperDocExtension requires a non-empty string `id`.");if(typeof e.activate!="function")throw new Error(`defineSuperDocExtension("${e.id}") requires an \`activate(ctx)\` function.`);if(e.storage!==void 0&&typeof e.storage!="function")throw new Error(`defineSuperDocExtension("${e.id}") \`storage\` must be a function returning the initial storage object.`);return e}var rU=Gu({BlankDOCX:()=>GC,DOCX:()=>Tr,HTML:()=>Fh,PDF:()=>Ul,SuperDoc:()=>om,buildTheme:()=>tU,compareVersions:()=>i6,createTheme:()=>eU,defineSuperDocExtension:()=>nU,getFileObject:()=>Ov},1),oU="SUPERDOC_ENGINE_CDN_BASE_URL",mA=Symbol.for("superdoc.docx-engine.cdn-load-state"),im="superdocDocxEngineStatus";function iU(e,t,n=null){const r=e?.[oU],o=typeof r=="string"&&r.trim()?r:n;if(typeof o=="string"&&o.trim())return sU(o);if(!t)throw new Error("SuperDoc: the CDN build is missing its exact DOCX Engine version");return`https://cdn.jsdelivr.net/npm/@superdoc/docx-engine@${t}`}function sU(e){const t=e.trim().replace(/\/+$/,""),n=t.match(/^([a-z][a-z\d+.-]*):/iu)?.[1]?.toLowerCase();if(n&&n!=="http"&&n!=="https")throw new TypeError(`SuperDoc: unsupported DOCX Engine CDN URL scheme ${n}:`);return t}function aU({engineVersion:e,buildBaseUrl:t}){dT(()=>{const n=iU(globalThis,e,t),r=globalThis[mA],o=r instanceof Map?r:new Map;if(globalThis[mA]=o,!o.has(n)){const i=Promise.all([import(`${n}/dist-cdn/docx-engine.es.js`),lU(`${n}/dist-cdn/style.css`)]).then(([s])=>s);o.set(n,i),i.catch(()=>{o.get(n)===i&&o.delete(n)})}return o.get(n)})}function lU(e){if(typeof document>"u")return Promise.resolve();const t=new URL(e,document.baseURI).href,n=Array.from(document.querySelectorAll('link[rel~="stylesheet"]')).find(o=>o.href===t);if(n?.sheet||n?.dataset[im]==="loaded")return Promise.resolve();const r=n?.dataset[im]==="loading";return n&&!r&&n.remove(),new Promise((o,i)=>{const s=r?n:document.createElement("link");let a=!1,l;const u=(m,p)=>{a||(a=!0,l?.disconnect(),s.dataset[im]=m,p())},c=()=>u("loaded",o),d=()=>u("error",()=>i(new Error(`SuperDoc: failed to load DOCX Engine styles from ${t}`))),h=()=>{s.isConnected||u("error",()=>i(new Error(`SuperDoc: DOCX Engine stylesheet was removed while loading from ${t}`)))};s.addEventListener("load",c,{once:!0}),s.addEventListener("error",d,{once:!0}),typeof globalThis.MutationObserver=="function"&&(l=new globalThis.MutationObserver(h),l.observe(document.head,{childList:!0})),r||(s.rel="stylesheet",s.href=t,s.dataset.superdocDocxEngine="true",s.dataset[im]="loading",document.head.appendChild(s))})}aU({engineVersion:"0.2.0-next.24",buildBaseUrl:null});for(const[e,t]of Object.entries(rU))e==="SuperDoc"||e==="default"||Object.prototype.hasOwnProperty.call(om,e)||(om[e]=t);var cU=om;return cU})();
|