superdoc 2.4.0-next.7 → 2.4.0-next.8
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/{FindReplaceSurface-C-I4GcRE.cjs → FindReplaceSurface-9VkPw_-X.cjs} +1 -2
- package/dist/chunks/{FindReplaceSurface-B_1Ksbr0.es.js → FindReplaceSurface-BuvaIrQ5.es.js} +1 -2
- package/dist/collaboration-upgrade-engine.cjs +1 -1
- package/dist/collaboration-upgrade-engine.es.js +1 -1
- package/dist/style.css +40 -40
- package/dist/style.layered.css +40 -40
- package/dist/superdoc/src/core/types/index.d.ts +105 -3
- package/dist/superdoc/src/public/index.d.cts +6 -0
- package/dist/superdoc/src/public/index.d.ts +3 -0
- package/dist/superdoc.cjs +2 -2
- package/dist/superdoc.es.js +2 -2
- package/dist-cdn/style.layered.css +1 -1
- package/dist-cdn/superdoc.min.css +1 -1
- package/dist-cdn/superdoc.min.js +3 -3
- package/package.json +2 -2
package/dist-cdn/superdoc.min.js
CHANGED
|
@@ -11,7 +11,7 @@ ${n.toString()}`)};var AT=class{constructor(e){this.patterns=[],this.$state=e}if
|
|
|
11
11
|
|
|
12
12
|
`).replace(/^\n+/,"").replace(/\n+$/,"")};const ca=vC("comments",()=>{const e={kind:"story",storyType:"body"},t=A=>{if(!A?.trackedChange)return!1;const M=A?.trackedChangeStory?.storyType;return M==null||M==="body"?!0:A?.trackedChangeAnchorKey?.startsWith?.("tc::body::")===!0},n=A=>A==null?null:a0({storyKey:"body",rawId:String(A)}),r=A=>{const M=bt(A);if(!M?.startsWith("tc::"))return null;const Q=M.indexOf("::",4);if(Q<=4)return null;const re=M.slice(4,Q),ae=M.slice(Q+2);return!re||!ae?null:{storyKey:re,rawId:ae}},o=(A,M)=>M==null?null:a0({storyKey:A||"body",rawId:String(M)}),i=A=>{if(!A)return null;const M=A.sourceId?String(A.sourceId):"";return M?`word:structural:${M}`:A.id?String(A.id):null},s=vu(),a=Yr({name:"comments",readOnly:!1,allowResolve:!0,showResolved:!1}),l=()=>({ok:!1,reason:"read-only-document"}),u=()=>({ok:!1,reason:"resolve-disabled"}),c=()=>a.allowResolve===!1,d=()=>a.readOnly===!0,h=Yr({documentMode:"editing",commentsVisible:!1,trackChangesVisible:!1}),g=!1,p={},v=new WeakMap,k=new Map;let C=0;const _=()=>typeof window>"u"?!1:"__labsSuperDocV2PreviewDebug"in window,y=(A,M=null)=>{if(_()){if(M!==null){console.debug("[SuperDoc][comments-store]",A,M);return}console.debug("[SuperDoc][comments-store]",A)}},w=op,x=ne(!1),P=ne(!1),N=ne(null),G=ne(!1),R=ne(null),F=ne(null),Z=ne(null),D=ne([]),B=ne([]),T=new Set([]),V=ne(!0),J=ne(""),q=ne([]);let se=new Map;const pe=_e(()=>{const A=j8(q.value,se);return se=A,A}),Ne=A=>{const M=A?.commentId??null;return(M!=null?pe.value.get(M):null)??[A].filter(Boolean)};let he=new Map;const ye=_e(()=>{const A=G8(q.value,he);return he=A,A}),ce=ne(!1),ke=ne([]),ie=ne({}),xe=ne(!1),Je=ne(0),st=ne([]),Tt=ne([]),Te=ne(!1),je=ne(!1),Ye=ne([]),$=ne(null),S=ne(null),ee=ne(null),O=ne(null),j=Zr(null),U=_e(()=>h.documentMode==="viewing"),W=_e(()=>U.value?h.commentsVisible||h.trackChangesVisible:!0),te=Zr(null),Y=new WeakMap,X=A=>Y.get(A)??0,be=A=>{if(!A||typeof A!="object"&&typeof A!="function")return 0;const M=X(A)+1;return Y.set(A,M),M},ve=A=>{te.value=A??null,A&&!Y.has(A)&&Y.set(A,0)},we=A=>{const M=A?.activeEditor?.v2Comments??null;return M||te.value},Be=A=>A?.activeEditor?.editorVersion===2||te.value!==null,rt=Zr(null),at=new WeakMap,Ct=A=>at.get(A)??0,en=A=>{if(!A||typeof A!="object"&&typeof A!="function")return 0;const M=Ct(A)+1;return at.set(A,M),M},Et=A=>{rt.value=A??null,A&&!at.has(A)&&at.set(A,0)},Ut=A=>{const M=A?.activeEditor?.v2TrackedChanges??null;return M||rt.value},Wt=({commentsAdapter:A,trackedChangesAdapter:M}={})=>({commentsGeneration:be(A??te.value),trackedChangesGeneration:en(M??rt.value)}),In=(A={})=>{const M={...a,...A};Object.assign(a,M),V.value=a.suppressInternalExternal||!1,A.comments&&A.comments.length&&(q.value=A.comments?.map(Q=>aa(Q))||[])},bt=A=>A==null?null:String(A),nn=A=>Array.isArray(A)?[...new Set(A.map(M=>bt(M)).filter(Boolean))]:[],et=A=>bt(A?.id??A?.changeId??A?.address?.entityId),Pt=A=>nn([et(A),A?.changeId,A?.address?.entityId,A?.trackedChangeAnchorKey,A?.anchorKey,A?.address?.anchorKey,...Array.isArray(A?.trackedChangePositionAliases)?A.trackedChangePositionAliases:[],...Array.isArray(A?.sourceIds?.rsids)?A.sourceIds.rsids:[],A?.sourceIds?.wordIdDelete,A?.sourceIds?.wordIdInsert,...Array.isArray(A?.sourceIds?.wordIdOther)?A.sourceIds.wordIdOther:[]]),Kt=A=>new Set(Pt(A).flatMap(M=>{const Q=r(M);return Q?.rawId?[M,Q.rawId]:[M]})),Rn=A=>{const M=new Set,Q=[];for(const re of A){const ae=et(re);if(ae){if(M.has(ae))continue;M.add(ae)}Q.push(re)}return Q},Nt=A=>{if(!A?.trackedChange)return null;const M=r(A.trackedChangeAnchorKey);if(M?.storyKey)return M.storyKey;const Q=A.trackedChangeStory;switch(Q?.storyType){case"body":return"body";case"headerFooterPart":return Q.refId?`hf:${Q.refId}`:null;case"footnote":return Q.noteId?`fn:${Q.noteId}`:null;case"endnote":return Q.noteId?`en:${Q.noteId}`:null;case"textbox":return Q.textboxId?`textbox:${Q.textboxId}`:null;default:return null}},un=A=>A?.startsWith("hf:part:")?`hf:${A.slice(8)}`:A?.startsWith("headerFooterPart:")?`hf:${A.slice(17)}`:A,Mn=(A,M)=>{const Q=un(A),re=un(M);return!Q||!re||Q===re},Pe=(A,M)=>Mn(un(Nt(M)),un(bt(A?.storyKey))),Ge=A=>{const M=bt(A);return M?M.startsWith("imported:")?M:`imported:${M}`:null},We=A=>{const M=bt(A);if(!M)return{key:null,entry:null};const Q=ie.value||{};if(Q[M]!==void 0)return{key:M,entry:Q[M]};for(const[re,ae]of Object.entries(Q)){const de=bt(ae?.key),fe=bt(ae?.threadId);if(de===M||fe===M)return{key:re,entry:ae}}return{key:null,entry:null}},ft=(A,M)=>{if(!A||!M)return!1;const Q=Math.max(Number(A.left),Number(M.left)),re=Math.min(Number(A.right),Number(M.right)),ae=Math.max(Number(A.top),Number(M.top)),de=Math.min(Number(A.bottom),Number(M.bottom));return[Q,re,ae,de].every(Number.isFinite)&&re>Q&&de>ae},Vt=(A,M)=>{if(!A||!M||A.kind!=="trackedChange"||M.kind!=="trackedChange"||A.storyKey&&M.storyKey&&A.storyKey!==M.storyKey)return!1;const Q=Number(A.pageIndex),re=Number(M.pageIndex);if(Number.isFinite(Q)&&Number.isFinite(re)&&Q!==re)return!1;if(ft(A.bounds,M.bounds))return!0;const ae=Number(A.start),de=Number(A.end),fe=Number(M.start),le=Number(M.end);return[ae,de,fe,le].every(Number.isFinite)&&ae===fe&&de===le},yt=A=>{const{entry:M}=We(A);if(!M)return null;const Q=q.value.filter(re=>re?.trackedChange?Ht(re).some(ae=>{const{entry:de}=We(ae);return Vt(M,de)}):!1);return Q.length===1?Q[0]:null},$t=A=>A==null?null:q.value.find(M=>M.commentId==A||M.importedId==A||M.trackedChangeAnchorKey==A||M?.trackedChange&&Ge(M.importedId)==A)||yt(A),At=A=>A?.parentCommentId?$t(A.parentCommentId):A,kn=A=>A?.trackedChangeThreadParentId?A.trackedChangeThreadParentId:mf(A)&&A?.trackedChange===!0?null:Op(A),Nn=A=>{const M=kn(A);return M?!!$t(M)?.trackedChange:!1},Uo=A=>{if(!A)return null;const M=ie.value||{};if(typeof A=="string"){if(M[A])return A;const fe=$t(A);if(!fe)return A;const le=fe.commentId??null,Ae=fe.importedId??null,Le=fe.trackedChange?Ge(Ae):null,Me=fe.trackedChangeAnchorKey??null;return Me&&M[Me]?Me:le&&M[le]?le:Ae&&M[Ae]?Ae:Le&&M[Le]?Le:Me??le??Le??Ae??null}const Q=A.commentId??null,re=A.importedId??null,ae=A.trackedChange?Ge(re):null,de=A.trackedChangeAnchorKey??null;return de&&M[de]?de:Q&&M[Q]?Q:re&&M[re]?re:ae&&M[ae]?ae:de??Q??ae??re??null},Ht=A=>{if(A==null)return[];const M=typeof A=="object"?null:A,Q=typeof A=="object"?A:$t(A),re=Q?.trackedChange?nn(Q?.trackedChangePositionAliases):[],ae=un(Nt(Q)),de=new Set;return[M,Uo(Q),Q?.trackedChangeAnchorKey,Q?.commentId,Q?.importedId,Q?.trackedChange?Ge(Q?.importedId):null,...re.flatMap(fe=>[ae&&!fe.startsWith("tc::")?a0({storyKey:ae,rawId:fe}):null,fe])].map(fe=>bt(fe)).filter(fe=>!fe||de.has(fe)?!1:(de.add(fe),!0))},Pn=(A,M)=>{const Q=ie.value||{},re=typeof A=="object"?A:$t(A),ae=new Set;for(const de of[M,...Ht(A)].map(fe=>bt(fe)).filter(Boolean)){if(ae.has(de))continue;ae.add(de);const fe=Q[de];if(fe!==void 0&&Pe(fe,re))return{key:de,entry:fe}}return{key:null,entry:null}},br=A=>{A&&((A.resolvedTime!=null||A.resolvedById!=null||A.resolvedByEmail!=null||A.resolvedByName!=null)&&v.set(A,{resolvedTime:A.resolvedTime??null,resolvedById:A.resolvedById??null,resolvedByEmail:A.resolvedByEmail??null,resolvedByName:A.resolvedByName??null,trackedChangeDecision:A.trackedChangeDecision??null}),A.resolvedTime=null,A.resolvedById=null,A.resolvedByEmail=null,A.resolvedByName=null,A.trackedChangeDecision=null)},Do=A=>{if(!A)return!1;const M=v.get(A);return M?(A.resolvedTime=M.resolvedTime??Date.now(),A.resolvedById=M.resolvedById??null,A.resolvedByEmail=M.resolvedByEmail??null,A.resolvedByName=M.resolvedByName??null,A.trackedChangeDecision=M.trackedChangeDecision??null,!0):!1},er=A=>typeof A?.getValues=="function"?A.getValues():{...A},cn=A=>{const M=A?.selection?.source;return M==null?!0:M===gu},Gn=A=>!!A?.trackedChange||!!kn(A),Br=({documentId:A,editor:M}={})=>{if(!M?.state||!q.value?.length)return 0;const Q=ie.value||{};if(!Object.keys(Q).length)return 0;const re=qe=>qe.find(Dt=>Q[Dt]!==void 0)??null,ae=new Set,de=new Map;if(q.value.forEach(qe=>{if(!qe?.trackedChange)return;if(A){const Bt=qe?.fileId??null;if(Bt&&Bt!==A)return}const Dt=Ht(qe),gt=re(Dt);gt&&(ae.add(gt),de.set(gt,new Set(Dt)))}),!ae.size)return 0;const fe=new Set(la.getTrackChanges(M.state).map(({mark:qe})=>qe?.attrs?.id).filter(qe=>qe!=null).map(qe=>String(qe))),le=typeof wu=="function"?wu(M):null;let Ae=[];try{Ae=le?.getAll?.()??[]}catch{}const Le=new Set(Ae.map(qe=>qe?.anchorKey).filter(qe=>typeof qe=="string"&&qe.length>0)),Me=new Set(Array.from(ae).filter(qe=>{const Dt=de.get(qe)??new Set([qe]);return Array.from(Dt).some(gt=>Le.has(gt))?!1:!Array.from(Dt).some(gt=>fe.has(gt))}));if(!Me.size)return 0;const ze=new Set;Me.forEach(qe=>{(de.get(qe)??new Set([qe])).forEach(Dt=>ze.add(Dt))});const tt=new Set(Me);q.value.forEach(qe=>{const Dt=re(Ht(qe));Dt&&[kn(qe),qe?.threadingParentCommentId,qe?.parentCommentId].map(gt=>bt(gt)).filter(Boolean).some(gt=>ze.has(gt))&&tt.add(Dt)});const ct={...Q};if(tt.forEach(qe=>{delete ct[qe]}),ie.value=ct,R.value!==void 0&&R.value!==null){const qe=$t(R.value),Dt=new Set(Ht(qe??R.value)),gt=[kn(qe),qe?.threadingParentCommentId,qe?.parentCommentId].map(Bt=>bt(Bt)).filter(Boolean);(Array.from(Dt).some(Bt=>ze.has(Bt))||gt.some(Bt=>ze.has(Bt)))&&fo()}return tt.size},ei=A=>{const M=A?.state?.doc;if(!M||typeof M.descendants!="function")return null;const Q=new Set,re=new Set;return M.descendants(ae=>{ae.marks?.filter(le=>le?.type?.name==="commentMark").forEach(le=>{[le.attrs?.commentId,le.attrs?.importedId].map(Ae=>bt(Ae)).filter(Boolean).forEach(Ae=>Q.add(Ae))});const de=ae.type?.name;if(de!=="commentRangeStart"&&de!=="commentRangeEnd")return;const fe=bt(ae.attrs?.["w:id"]);fe&&re.add(fe)}),{liveMarkIds:Q,resolvedAnchorIds:re}},bo=()=>{const A=s.documents;if(!Array.isArray(A))return null;for(const M of A){const Q=typeof M?.getEditor=="function"?M.getEditor():null;if(Q?.state?.doc)return Q}return null},Jr=({editor:A}={})=>{if(te.value)return 0;const M=ei(A??bo()),Q=ie.value||{},re=new Set(Object.keys(Q));if(!M&&!re.size)return 0;let ae=0;return q.value.forEach(de=>{if(!cn(de)||Gn(de))return;if(M){const le=Ht(de),Ae=le.some(Me=>M.liveMarkIds.has(Me)),Le=le.some(Me=>M.resolvedAnchorIds.has(Me));if(Ae&&de.resolvedTime!=null){br(de),ae+=1;return}!Ae&&Le&&de.resolvedTime==null&&Do(de)&&(ae+=1);return}const{key:fe}=Pn(de);fe&&re.has(String(fe))&&de.resolvedTime!=null&&(br(de),ae+=1)}),ae};zt(ie,()=>{Jr()}),zt(q,()=>{Jr()},{deep:!1});const Xi=A=>{if(!A)return null;const M=A.start??A.pos??A.from,Q=A.end??A.to??M;return!Number.isFinite(M)||!Number.isFinite(Q)?null:{start:M,end:Q}},Ri=A=>Pn(A).entry??null,ba=(A,M={})=>{const Q=typeof A=="object"?A:$t(A);if(!Q)return null;const re=Xi(Pn(A).entry??null);if(!re)return null;const ae=s.getDocument(Q.fileId)?.getEditor?.()?.state?.doc;if(!ae?.textBetween)return null;const de=M.separator??" ",fe=ae.textBetween(re.start,re.end,de,de);return M.trim===!1?fe:fe?.trim()},ti=(A,M={})=>{const Q=Ri(A);return Q?{position:Q,anchoredText:ba(A,M)}:null},wa=A=>{if(!U.value)return!0;const M=At(A);return!M&&A?.parentCommentId?!1:M?.trackedChange||kn(A)?h.trackChangesVisible:h.commentsVisible},uc=(A,M)=>{const Q=A?.activeEditor,re=we(A);if(M==null){if(fo(),re){re.setActiveComment(null);return}Q?.commands?.setActiveComment({commentId:null});return}const ae=$t(M);if(ae){if(R.value=ae.commentId,Ps(ae.commentId),re){re.setActiveComment(ae.commentId);return}Q?.commands?.setActiveComment({commentId:R.value})}},Oo=({superdoc:A,params:M,broadcastChanges:Q=!0,documentState:re=void 0,trackedChangeIdentityIndex:ae=null})=>{const de=i0("store.trackedChanges.handleUpdate","store-reconciliation",{event:M?.event??null,changeId:M?.changeId??null,documentId:M?.documentId??null});try{const{event:fe,changeId:le,trackedChangeText:Ae,trackedChangeType:Le,trackedChangeDisplayType:Me,semanticColorKey:ze,semanticColor:tt,deletedText:ct,trackedChangeLabel:qe,trackedChangeDetailLines:Dt,trackedChangeImagePreview:gt,authorId:Bt,authorEmail:xt,authorImage:St,date:Zn,author:rn,importedAuthor:hn,documentId:mr,coords:xr,trackedChangeStory:tr,trackedChangeStoryKind:No,trackedChangeStoryLabel:$r,trackedChangeAnchorKey:it,trackedChangeCanonicalId:dn,trackedChangePositionAliases:eo,importedId:wi}=M,So=le!=null?String(le):null,Ci=dn!=null?String(dn):null,_o=Object.prototype.hasOwnProperty.call(M,"trackedChangePositionAliases"),Bo=_o?nn(eo):void 0,Il=Object.prototype.hasOwnProperty.call(M,"importedId"),$i=Il?wi!=null?String(wi):null:void 0,Ds=mr!=null?String(mr):null;if(!(Me==="tableInsert"||Me==="tableDelete")&&So){const jt=Ds??(A?.activeEditor?.options?.documentId!=null?String(A.activeEditor.options.documentId):null),qn=jt?s.getDocument(jt)?.getEditor?.():null,L=re!==void 0?re:qn?.state??A?.activeEditor?.state??null;if(L){const{ranges:H,ids:Ce}=Ta(L),De=la.getTrackChanges(L,So),pt=H.length>0&&De.length>0&&$f(De,H),fn=De.length===0&&Ce.has(So);if(pt||fn){Aa({suppressedIds:new Set([So]),activeDocumentId:jt,superdoc:A,broadcastChanges:Q});return}}}const dt=tr!==void 0||No!==void 0||$r!==void 0||it!==void 0,Os=dt?tr??null:e,Xt=dt?No??null:"body",xa=dt&&$r!==void 0?$r:"",es=it!==void 0?it??null:dt?null:n(So),Ic=typeof qe=="string"&&qe.length>0?qe:null,El=e7(Dt),Ec=n7(gt),Tl=ko({documentId:mr,commentId:le,trackedChange:!0,trackedChangeText:Ae,trackedChangeType:Le,trackedChangeDisplayType:Me,semanticColorKey:ze,semanticColor:tt,deletedText:ct,trackedChangeLabel:Ic,trackedChangeDetailLines:El,trackedChangeImagePreview:Ec,createdTime:Zn,creatorId:Bt??null,creatorName:rn,creatorEmail:xt,creatorImage:St,isInternal:!1,importedAuthor:hn,...Il?{importedId:$i}:{},trackedChangeStory:Os,trackedChangeStoryKind:Xt,trackedChangeStoryLabel:xa,trackedChangeAnchorKey:es,trackedChangeCanonicalId:Ci,..._o?{trackedChangePositionAliases:Bo}:{},selection:{source:gu,selectionBounds:xr}}),Tc=()=>{const jt=es!=null?String(es):null;if(!So)return null;const qn=Nt(Tl),L=H=>{if(!H)return!1;const Ce=H.trackedChangeAnchorKey!=null?String(H.trackedChangeAnchorKey):null,De=H.commentId!=null?String(H.commentId):null,pt=H.importedId!=null?String(H.importedId):null,fn=H.trackedChangeCanonicalId!=null?String(H.trackedChangeCanonicalId):null,xn=Ht(H),Yn=Mn(Nt(H),qn);if(Yn&&xn.includes(So))return!0;const pn=new Set(Bo??[]);if(Yn&&pn.size>0&&[De,pt,fn,Ce,...xn].filter(Boolean).some(bn=>pn.has(bn)))return!0;const gn=Ci&&Ci!==So||fn&&fn!==De;return De===So||!gn&&(pt===So||$i!==void 0&&$i!=null&&pt===$i)?!0:gn?!1:jt&&Ce?Ce===jt:!1};if(ae){const H=ae.candidates({changeId:So,importedId:$i,anchorKey:jt,canonicalId:Ci,positionAliases:Bo});for(const Ce of H)if(L(Ce)&&(!Ds||Kr(Ce,Ds)))return Ce;return null}return Ds?q.value.find(H=>L(H)&&Kr(H,Ds)):q.value.find(L)},Fs=jt=>{Q&&(Xl(A,jt),Ln(le,jt,A))},Ao=(jt,qn,L)=>jt?.[qn]==null&&L==null||!jt||Ck(jt[qn],L)?!1:(jt[qn]=L,!0),oi=jt=>{if(!jt)return!1;let qn=!1;return Os!=null&&(qn=Ao(jt,"trackedChangeStory",Os)||qn),Xt!=null&&(qn=Ao(jt,"trackedChangeStoryKind",Xt)||qn),xa!==void 0&&xa!==""&&(qn=Ao(jt,"trackedChangeStoryLabel",xa)||qn),es!=null&&(qn=Ao(jt,"trackedChangeAnchorKey",es)||qn),qn},th=jt=>{const qn={trackedChangeText:Ae??null,trackedChangeType:Le??null,trackedChangeDisplayType:Me??null,semanticColorKey:ze??null,semanticColor:tt??null,deletedText:ct??null,trackedChangeLabel:Ic,trackedChangeImagePreview:Ec,trackedChangeCanonicalId:Ci,creatorId:Bt??null,creatorName:rn??null,creatorEmail:xt??null,creatorImage:St??null,createdTime:Zn??null};if(Il&&(qn.importedId=$i),_o){const H=new Set([jt?.commentId,jt?.importedId,jt?.trackedChangeCanonicalId,jt?.trackedChangeAnchorKey,...Ht(jt)].map(Ce=>bt(Ce)).filter(Boolean));qn.trackedChangePositionAliases=Bo.some(Ce=>H.has(Ce))?nn([...Array.isArray(jt?.trackedChangePositionAliases)?jt.trackedChangePositionAliases:[],...Bo]):Bo}let L=!1;for(const[H,Ce]of Object.entries(qn))L=Ao(jt,H,Ce)||L;return jt&&!(jt.trackedChangeDetailLines==null&&El==null)&&!t7(jt.trackedChangeDetailLines,El)&&(jt.trackedChangeDetailLines=El,L=!0),oi(jt)||L},xc=jt=>{const qn=!!(jt.resolvedTime||jt.resolvedById||jt.resolvedByEmail||jt.resolvedByName);return qn&&br(jt),th(jt)||qn};if(fe==="add"){const jt=Tc();if(jt){if(!xc(jt))return;ae?.add(jt),Fs({type:w.UPDATE,comment:er(jt)});return}ri({superdoc:A,comment:Tl,broadcastChanges:Q}),ae?.add(Tl)}else if(fe==="update"){const jt=Tc();if(!jt||!xc(jt))return;ae?.add(jt),Fs({type:w.UPDATE,comment:er(jt)})}else if(fe==="resolve"){const jt=Tc(),qn={id:M.resolvedById??A?.user?.id??null,email:M.resolvedByEmail??A?.user?.email??null,name:M.resolvedByName??A?.user?.name??null,decision:M.decision??null,superdoc:A};jt&&!jt.resolvedTime&&jt.resolveComment({...qn,reconciliationToken:dk})}}finally{bu(de)}},jo=(A=[])=>({insertedMark:A.find(({mark:M})=>M?.type?.name==="trackInsert")?.mark??null,deletionMark:A.find(({mark:M})=>M?.type?.name==="trackDelete")?.mark??null,formatMark:A.find(({mark:M})=>M?.type?.name==="trackFormat")?.mark??null}),Se=({superdoc:A,editor:M,changeIds:Q,broadcastChanges:re=!0})=>{if(!A||!M?.state||!Array.isArray(Q)||!Q.length)return;const ae=M?.options?.documentId!=null?String(M.options.documentId):null;if(ae)for(const de of new Set(Q.map(fe=>fe!=null?String(fe):null).filter(Boolean))){const fe=la.getTrackChanges(M.state,de);if(!fe.length)continue;const le=s0({event:"update",marks:jo(fe),nodes:[],newEditorState:M.state,documentId:ae,trackedChangesForId:fe});le&&(le.trackedChangeStory=e,le.trackedChangeStoryKind="body",le.trackedChangeStoryLabel="",le.trackedChangeAnchorKey=n(le.changeId??de),Oo({superdoc:A,params:le,broadcastChanges:re}))}},Ve=(A=null,M=null,Q=null)=>{const re=Number.isFinite(A);$.value=re?A:null,S.value=re&&M!=null?String(M):null;const ae=Q??M;ee.value=re&&ae!=null?String(ae):null},_t=()=>{const A=$.value;return Number.isFinite(A)?A:null},lt=()=>{$.value=null,S.value=null,ee.value=null},Ln=(A,M,Q,re=1e3)=>{p[A]&&clearTimeout(p[A]),p[A]=setTimeout(()=>{Q&&Q.emit("comments-update",M),delete p[A]},re)},Bn=(A,M)=>{if(M?.source!=="document-editor")return null;const Q=M?.documentId??null,re=A?.activeEditor?.options?.documentId??null;if(!Q||!re||Q!==re)return null;let ae;try{ae=A?.activeEditor?.doc?.selection?.current}catch{return null}if(typeof ae!="function")return null;try{return ae()}catch{return null}},sr=(A,M=null)=>{const Q=we(A),re=Bn(A,s.activeSelection),ae={type:w.PENDING,pendingSelection:re};if(A.emit("comments-update",ae),Q){const fe=Q.getCapabilityState?.();return fe&&fe.canWrite===!1?{ok:!1,reason:fe.reason}:Promise.resolve(Q.captureCurrentSelection?.()).then(le=>{if(!le?.ok)return{ok:!1,reason:le?.reason??"editing-range-required",detail:le?.detail};j.value=le.target??null;const Ae=Q.documentId??A?.activeEditor?.options?.documentId??null;return O.value=ko({selection:{source:gu,documentId:Ae,page:1,selectionBounds:{}},documentId:Ae,parentCommentId:null}),A.config.isInternal||(O.value.isInternal=!1),Ve(M,"pending"),Ls(null),R.value=O.value.commentId,{ok:!0}}).catch(le=>({ok:!1,reason:"selection-capture-failed",detail:le?.message??String(le)}))}const de={...s.activeSelection};return de.selectionBounds={...de.selectionBounds},s.selectionPosition?.source&&s.selectionPosition.source!=="pdf"&&(s.selectionPosition.source=null),O.value=ko({selection:de,documentId:de.documentId,parentCommentId:null}),A.config.isInternal||(O.value.isInternal=!1),A.activeEditor?.commands&&A.activeEditor.commands.insertComment({...O.value.getValues(),commentId:"pending",skipEmit:!0}),O.value.selection.source==="document-editor"&&s.selectionPosition&&(s.selectionPosition.source=gu),Ve(M,"pending"),Ls(null),R.value=O.value.commentId,{ok:!0}},Sr=A=>{const M=Pn(A).entry;return M?Number.isFinite(M.start)?M.start:Number.isFinite(M.pos)?M.pos:Number.isFinite(M.from)?M.from:Number.isFinite(M.to)?M.to:Number.isFinite(M.pageIndex)&&Number.isFinite(M?.bounds?.top)?M.pageIndex*1e6+M.bounds.top:null:null},wo=(A,M)=>(A.createdTime??0)-(M.createdTime??0),Co=(A,M)=>{const Q=Sr(A),re=Sr(M),ae=Number.isFinite(Q),de=Number.isFinite(re);return ae&&de&&Q!==re?Q-re:ae&&!de?-1:!ae&&de?1:wo(A,M)},mi=A=>{const M=[],Q=[],re=new Map;return q.value.forEach(ae=>{if(!wa(ae))return;const de=Nn(ae)?kn(ae):null,fe=ae.trackedChange?null:ae.parentCommentId||de;ae.resolvedTime?Q.push(ae):!fe&&!ae.resolvedTime?M.push({...ae}):fe&&(re.has(fe)||re.set(fe,[]),re.get(fe).push(ae))}),{parentComments:M.sort(A),resolvedComments:Q.sort(A)}},co=_e(()=>mi(wo)),pr=_e(()=>co.value?.parentComments.some(A=>A.trackedChange&&!A.resolvedTime)??!1),hl=_e(()=>mi(Co)),Ca=A=>T.includes(A),gi=_e(()=>s.documents),zr=_e(()=>a),ni=(A,M)=>{const Q=A.getContainerLocation(M);return{top:Q.top+A.selectionBounds.top,left:Q.left+A.selectionBounds.left}},ko=({selection:A,documentId:M,parentCommentId:Q,...re})=>Mi({selection:A,documentId:M,parentCommentId:Q,...re}),Mi=({selection:A,documentId:M,parentCommentId:Q,...re})=>{let ae;return M?ae=s.getDocument(M):A&&(ae=s.getDocument(A.documentId)),ae||(ae=s.documents[0]),aa({fileId:ae.id,fileType:ae.type,parentCommentId:Q,creatorId:s.user.id,creatorEmail:s.user.email,creatorName:s.user.name,creatorImage:s.user.image,commentText:J.value,selection:A,...re})},vi=A=>{const M=!!O.value;J.value="",O.value=null,j.value=null,s.selectionPosition=null,M&&fo(),!Be(A)&&A?.activeEditor?.commands?.removeComment({commentId:"pending"})},ka=({superdoc:A,comment:M,skipEditorUpdate:Q=!1,broadcastChanges:re=!0,isHydration:ae=!1})=>{if(d()&&!ae)return l();const de=!Q&&!ae?we(A):null;if(de&&!M.trackedChange){const Le=c0(O.value?J.value:M.commentText),Me=O.value?j.value:null,ze=M.parentCommentId?String(M.parentCommentId):(O.value,null);return(async()=>{try{return await(ze?de.reply({parentCommentId:ze,text:Le}):de.commitPendingComment({text:Le,target:Me}))}catch(tt){return{ok:!1,reason:"adapter-threw",detail:tt?.message??String(tt)}}})().then(tt=>{if(!Go(de))return{ok:!1,reason:"adapter-stale"};if(!tt?.ok)return re&&A.emit("comments-update",{type:w.PENDING,rejected:!0,reason:tt?.reason??"v2-create-failed",...tt?.committed?{committed:!0}:{}}),tt;const ct=Xn({superdoc:A,adapter:de,documentId:de.documentId,items:tt.items});return O.value&&vi(A),re&&A.emit("comments-update",{type:w.ADD,comment:ct?.added?.getValues?.()??null}),{ok:!0,comment:ct?.added??null}})}let fe=q.value.find(Le=>Le.commentId===R.value);fe||(fe=M);const le=aa(M.getValues());O.value?le.setText({text:J.value,suppressUpdate:!0}):le.setText({text:M.commentText,suppressUpdate:!0}),le.selection.source=O.value?.selection?.source??le.selection.source,fe&&(le.isInternal=fe.isInternal),A.config.isInternal||(le.isInternal=!1),q.value.push(le),vi(A),!Q&&!M.trackedChange&&A.activeEditor?.commands&&!M.parentCommentId&&A.activeEditor.commands.insertComment({...le.getValues(),skipEmit:!0});const Ae={type:w.ADD,comment:le.getValues()};return re&&(Xl(A,Ae),A.emit("comments-update",Ae)),{ok:!0,comment:le}},pl=({superdoc:A,comment:M,skipEditorUpdate:Q=!1,broadcastChanges:re=!0})=>ka({superdoc:A,comment:M,skipEditorUpdate:Q,broadcastChanges:re}),ri=({superdoc:A,comment:M,skipEditorUpdate:Q=!1,broadcastChanges:re=!0})=>ka({superdoc:A,comment:M,skipEditorUpdate:Q,broadcastChanges:re,isHydration:!0}),Ss=({commentId:A,superdoc:M})=>{if(d())return Promise.resolve(l());const Q=q.value.findIndex(Me=>Me.commentId===A),re=q.value[Q];if(!re)return Promise.resolve({ok:!1,reason:"comment-not-found"});const{commentId:ae,importedId:de}=re,{fileId:fe}=re,le=we(M);if(le&&!re.trackedChange)return(async()=>{try{return await le.delete({commentId:ae})}catch(Me){return{ok:!1,reason:"adapter-threw",detail:Me?.message??String(Me)}}})().then(Me=>Go(le)?Me?.ok?(Xn({superdoc:M,adapter:le,documentId:le.documentId??fe,items:Me.items}),M.emit("comments-update",{type:w.DELETED,comment:re.getValues(),changes:[{key:"deleted",commentId:ae,fileId:fe}]}),{ok:!0}):(M.emit("comments-update",{type:w.DELETED,rejected:!0,comment:re.getValues(),reason:Me?.reason??"v2-delete-failed",...Me?.committed?{committed:!0}:{}}),Me):{ok:!1,reason:"adapter-stale"});M.activeEditor?.commands?.removeComment({commentId:ae,importedId:de}),q.value.splice(Q,1);const Ae=q.value.filter(Me=>Me.parentCommentId===ae).map(Me=>Me.commentId||Me.importedId);q.value=q.value.filter(Me=>!Ae.includes(Me.commentId)),(R.value===ae||Ae.includes(R.value))&&fo();const Le={type:w.DELETED,comment:re.getValues(),changes:[{key:"deleted",commentId:ae,fileId:fe}]};return M.emit("comments-update",Le),Xl(M,Le),Promise.resolve({ok:!0})},_s=async({superdoc:A,adapter:M,fileId:Q,operation:re,eventType:ae,rejectionFallbackReason:de,rejectionEventExtras:fe={},validateOutcome:le,successEventBuilder:Ae})=>{let Le;try{Le=await re()}catch(ct){Le={ok:!1,reason:"adapter-threw",detail:ct?.message??String(ct)}}if(!Go(M))return{ok:!1,reason:"adapter-stale"};if(!Le?.ok){const ct={type:ae,rejected:!0,reason:Le?.reason??de,...Le?.committed?{committed:!0}:{},...Le?.code!==void 0?{code:Le.code}:{},...Le?.detail!==void 0?{detail:Le.detail}:{},...fe};return A?.emit?.("comments-update",ct),Le}const Me=le?.({outcome:Le});if(Me?.ok===!1){const ct={ok:!1,committed:Me.committed??!0,reason:Me.reason??de,...Me.code!==void 0?{code:Me.code}:{},...Me.detail!==void 0?{detail:Me.detail}:{}},qe={type:ae,rejected:!0,reason:ct.reason,...ct.committed?{committed:!0}:{},...ct.code!==void 0?{code:ct.code}:{},...ct.detail!==void 0?{detail:ct.detail}:{},...fe};return A?.emit?.("comments-update",qe),ct}const ze=Xn({superdoc:A,adapter:M,documentId:M.documentId??Q,items:Le.items??[]}),tt=Ae?.({outcome:Le,reconciled:ze})??null;return tt&&A?.emit?.("comments-update",tt),{ok:!0,items:Le.items??[],reconciled:ze}},ml=({outcome:A,adapter:M,fileId:Q})=>(A.items??[]).map(re=>M.mapV2CommentToUseCommentInput(re,{fileId:Q,fileType:null})).filter(Boolean),As=A=>{const M=A?.commentId??A?.importedId;return M!=null?String(M):null},Vr=A=>A?.parentCommentId!=null?String(A.parentCommentId):null,Nu=({outcome:A,adapter:M,fileId:Q,commentId:re,expectedResolved:ae,operation:de})=>{const fe=re!=null?String(re):null,le=ml({outcome:A,adapter:M,fileId:Q}),Ae=le.find(qe=>As(qe)===fe)??null,Le=Ae?.parentCommentId?le.find(qe=>As(qe)===Vr(Ae))??null:Ae,Me=As(Le);if(!Le||!Me)return{ok:!1,reason:`v2-${de}-refresh-missing`,detail:`comment ${fe} was absent from the refreshed v2 comment list after ${de}`};const ze=[Le,...le.filter(qe=>Vr(qe)===Me)],tt=qe=>!!qe?.resolvedTime;if(ze.filter(qe=>tt(qe)!==ae).length===0)return{ok:!0};const ct=tt(Le);return ze.some(qe=>tt(qe)!==ct)?{ok:!1,reason:`v2-${de}-refresh-split-thread`,detail:{rootId:Me,expected:ae?"resolved":"open",observed:ze.map(qe=>({commentId:As(qe),parentCommentId:Vr(qe),status:tt(qe)?"resolved":"open"}))}}:{ok:!1,reason:ae?`v2-${de}-refresh-still-open`:`v2-${de}-refresh-still-resolved`,detail:`comment ${Me} remained ${ct?"resolved":"open"} after ${de}`}},Is=async({superdoc:A,parentCommentId:M,text:Q}={})=>{if(d())return l();const re=we(A);if(!re)return{ok:!1,reason:"v2-comments-adapter-missing"};const ae=M!=null?String(M):null;if(!ae)return{ok:!1,reason:"parent-comment-id-missing"};const de=c0(Q);if(de.length===0)return{ok:!1,reason:"comment-text-empty"};const fe=q.value.find(le=>String(le.commentId)===ae);return _s({superdoc:A,adapter:re,fileId:fe?.fileId??re.documentId??null,operation:()=>re.reply({parentCommentId:ae,text:de}),eventType:w.ADD,rejectionFallbackReason:"v2-reply-failed",rejectionEventExtras:fe?{comment:er(fe)}:{},successEventBuilder:({reconciled:le})=>({type:w.ADD,comment:le?.added?.getValues?.()??null})})},Wf=async({superdoc:A,commentId:M,text:Q}={})=>{if(d())return l();const re=we(A);if(!re)return{ok:!1,reason:"v2-comments-adapter-missing"};const ae=M!=null?String(M):null;if(!ae)return{ok:!1,reason:"comment-id-missing"};const de=c0(Q);if(de.length===0)return{ok:!1,reason:"comment-text-empty"};const fe=q.value.find(le=>String(le.commentId)===ae);return _s({superdoc:A,adapter:re,fileId:fe?.fileId??re.documentId??null,operation:()=>re.edit({commentId:ae,text:de}),eventType:w.UPDATE,rejectionFallbackReason:"v2-edit-failed",rejectionEventExtras:fe?{comment:er(fe),changes:[{key:"text",value:de}]}:{},successEventBuilder:()=>{const le=q.value.find(Ae=>String(Ae.commentId)===ae)??fe;return le?{type:w.UPDATE,comment:er(le),changes:[{key:"text",value:le.commentText??de}]}:null}})},Sa=async({superdoc:A,commentId:M}={})=>{if(d())return l();if(c())return u();const Q=we(A);if(!Q)return{ok:!1,reason:"v2-comments-adapter-missing"};const re=M!=null?String(M):null;if(!re)return{ok:!1,reason:"comment-id-missing"};const ae=q.value.find(le=>String(le.commentId)===re),de=ae?.fileId??Q.documentId??null,fe=await _s({superdoc:A,adapter:Q,fileId:de,operation:()=>Q.resolve({commentId:re}),eventType:w.RESOLVED,rejectionFallbackReason:"v2-resolve-failed",rejectionEventExtras:ae?{comment:er(ae)}:{},validateOutcome:({outcome:le})=>Nu({outcome:le,adapter:Q,fileId:de,commentId:re,expectedResolved:!0,operation:"resolve"}),successEventBuilder:()=>{const le=q.value.find(Ae=>String(Ae.commentId)===re)??ae;return le?{type:w.RESOLVED,comment:er(le)}:null}});if(fe?.ok){const Ae=!!q.value.find(Me=>String(Me.commentId)===re)?.resolvedTime,Le=R.value!=null?String(R.value):null;Ae&&Le===re&&fo()}return fe},Es=async({superdoc:A,commentId:M}={})=>{if(d())return l();if(c())return u();const Q=we(A);if(!Q)return{ok:!1,reason:"v2-comments-adapter-missing"};const re=M!=null?String(M):null;if(!re)return{ok:!1,reason:"comment-id-missing"};const ae=q.value.find(fe=>String(fe.commentId)===re),de=ae?.fileId??Q.documentId??null;return _s({superdoc:A,adapter:Q,fileId:de,operation:()=>Q.reopen({commentId:re}),eventType:w.UPDATE,rejectionFallbackReason:"v2-reopen-failed",rejectionEventExtras:ae?{comment:er(ae),changes:[{key:"resolvedTime",value:null}]}:{},validateOutcome:({outcome:fe})=>Nu({outcome:fe,adapter:Q,fileId:de,commentId:re,expectedResolved:!1,operation:"reopen"}),successEventBuilder:()=>{const fe=q.value.find(le=>String(le.commentId)===re);return!fe||fe.resolvedTime?null:{type:w.UPDATE,comment:er(fe),changes:[{key:"resolvedTime",value:null}]}}})},Go=A=>A?te.value===A:!1,Li=A=>A?rt.value===A:!1,Bu=({superdoc:A,commentsAdapter:M,trackedChangesAdapter:Q,documentId:re,commentItems:ae,trackedChangeItems:de,trackedList:fe,sourceCoverageRevision:le,evaluatedRevision:Ae,patch:Le}={})=>ms("store.reviewSnapshot.apply","store-reconciliation",{commentItemCount:Array.isArray(ae)?ae.length:null,trackedItemCount:Array.isArray(de)?de.length:null},()=>{if(!Go(M))return{ok:!1,reason:"comments-adapter-stale"};if(!Li(Q))return{ok:!1,reason:"tracked-changes-adapter-stale"};const Me=re!=null?String(re):null,ze=A?.activeEditor?.documentId??A?.activeEditor?.options?.documentId??null;if(!Me)return{ok:!1,reason:"document-mismatch"};for(const Bt of[M.documentId,Q.documentId,ze])if(Bt==null||String(Bt)!==Me)return{ok:!1,reason:"document-mismatch"};if(!Array.isArray(ae)||!Array.isArray(de))return{ok:!1,reason:"items-invalid"};if(fe?.complete!==!1||!["review-snapshot","visible-window"].includes(fe?.visibleWindowSource))return{ok:!1,reason:"tracked-list-not-partial-visible-window"};if(typeof M.mapV2CommentToUseCommentInput!="function"||typeof Q.mapV2TrackedChangeToCommentParams!="function")return{ok:!1,reason:"adapter-mapper-missing"};let tt=ae,ct=!1;if(typeof M.seedReviewCatalog=="function"){const Bt=M.seedReviewCatalog(ae,{sourceCoverageRevision:le,evaluatedRevision:Ae});if(Bt?.ok!==!0)return{ok:!1,reason:Bt?.reason??"comment-catalog-seed-failed"};const xt=M.selectVisibleReviewComments?.();xt?.ok===!0&&Array.isArray(xt.items)&&(!Array.isArray(xt.unresolvedIds)||xt.unresolvedIds.length===0)&&(tt=xt.items,ct=!0)}const qe=(Me?s.getDocument(Me):null)?.type??null;let Dt,gt;try{Dt=tt.filter(Bt=>!r0(Bt)).map(Bt=>M.mapV2CommentToUseCommentInput(Bt,{fileId:Me,fileType:qe})).filter(Boolean),gt=de.map(Bt=>Q.mapV2TrackedChangeToCommentParams(Bt)).filter(Boolean)}catch(Bt){return{ok:!1,reason:"mapper-failed",detail:Bt?.message??String(Bt)}}return typeof Le!="function"?{ok:!1,reason:"patch-missing"}:(Le(()=>{Pi({superdoc:A,adapter:Q,documentId:Me,items:de,preparedParams:gt,pruneStale:!1}),Xn({superdoc:A,adapter:M,documentId:Me,items:tt,preparedInputs:Dt,pruneStale:!ct})}),{ok:!0,commentItems:Dt.length,trackedItems:gt.length})}),gl=async({superdoc:A,adapter:M,documentId:Q,trackedChangesListMode:re="all",isCurrent:ae,signal:de,hydrationGeneration:fe}={})=>ms("store.comments.hydrateFromV2","comments-list",{documentId:Q??null},async()=>{const le=M??we(A),Ae=re==="visible-window",Le=Ae?le?.selectVisibleReviewComments:le?.refresh;if(!le||typeof Le!="function")return{ok:!1,reason:"adapter-missing"};const Me=()=>ae?.()!==!1&&Go(le);if(!Me())return{ok:!1,reason:"adapter-stale"};if(de?.aborted)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!1};const ze=X(le);let tt;try{const ct={};de&&(ct.signal=de),typeof fe=="number"&&(ct.hydrationGeneration=fe),tt=Object.keys(ct).length>0?await Le.call(le,ct):await Le.call(le)}catch(ct){return{ok:!1,reason:"adapter-threw",detail:ct?.message??String(ct)}}return Me()?de?.aborted||X(le)!==ze?{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0}:tt?.ok?de?.aborted||X(le)!==ze?{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0}:(Xn({superdoc:A,adapter:le,documentId:Q,items:tt.items??[],pruneStale:!Ae,hydrationGeneration:fe}),{ok:!0,items:tt.items??[],reconciled:!0,...typeof fe=="number"?{hydrationGeneration:fe}:{},...tt.visibleWindowSource!=null?{visibleWindowSource:tt.visibleWindowSource}:{}}):tt:{ok:!1,reason:"adapter-stale"}}),Xn=({superdoc:A,adapter:M,documentId:Q,items:re,preparedInputs:ae=null,pruneStale:de=!0,hydrationGeneration:fe}={})=>ms("store.comments.reconcile","store-reconciliation",{documentId:Q??null,itemCount:Array.isArray(re)?re.length:null,hydrationGeneration:fe??null},()=>{if(!M||!Array.isArray(re))return{added:null};if(!Go(M))return{added:null,dropped:"adapter-stale"};const le=Q??M.documentId??null,Ae=le!=null?String(le):null,Le=(le?s.getDocument(le):null)?.type??null,Me=it=>typeof it!="string"?!0:it.replace(/<[^>]*>/g,"").replace(/ /gi," ").trim().length===0,ze=it=>!it||it.trackedChange===!0||!it.trackedChangeThreadParentId||it.parentCommentId?!1:Me(it.commentText),tt=R.value!=null?String(R.value):null,ct=tt?q.value.find(it=>String(it.commentId)===tt)??null:null,qe=ct!=null&&O.value!=null&&(ct===O.value||O.value.commentId!=null&&String(ct.commentId??"")===String(O.value.commentId)),Dt=ct!=null&&!qe&&ct.trackedChange!==!0&&!mf(ct)&&(Ae==null||ct.fileId==null||String(ct.fileId)===Ae),gt=new Map,Bt=new Map,xt=[],St=Array.isArray(ae)?ae:re.filter(it=>!r0(it)).map(it=>M.mapV2CommentToUseCommentInput(it,{fileId:le,fileType:Le})).filter(Boolean);for(const it of St){if(ze(it)){Bt.set(String(it.commentId),String(it.trackedChangeThreadParentId)),y("hydrate:drop-v2-sidecar-comment",{commentId:it.commentId??null,importedId:it.importedId??null,parentCommentId:it.parentCommentId??null,trackedChangeParentId:it.trackedChangeParentId??null,trackedChangeThreadParentId:it.trackedChangeThreadParentId??null,trackedChangeSide:it.trackedChangeSide??null,commentText:it.commentText??null});continue}xt.push(it)}for(const it of xt){const dn=it.parentCommentId!=null?String(it.parentCommentId):null,eo=dn?Bt.get(dn):null;eo&&(it.threadingParentCommentId=eo,it.trackedChangeThreadParentId==null&&(it.trackedChangeThreadParentId=eo));const wi=it.commentId!=null?String(it.commentId):null;wi&>.set(wi,it)}const Zn=it=>{if(Ae==null)return!0;const dn=it?.fileId!=null?String(it.fileId):null;return dn==null?!0:dn===Ae},rn=O.value?.commentId!=null?String(O.value.commentId):null,hn=it=>!it||!O.value?!1:it===O.value||rn!=null&&String(it.commentId??"")===rn,mr=it=>!it||hn(it)||it.trackedChange===!0||mf(it)?!1:it.commentId!=null,xr=(it,dn)=>{it.commentText=dn.commentText??it.commentText,it.isInternal=typeof dn.isInternal=="boolean"?dn.isInternal:it.isInternal,typeof dn.resolvedTime=="number"?(it.resolvedTime=dn.resolvedTimeWasSynthesized===!0&&typeof it.resolvedTime=="number"?it.resolvedTime:dn.resolvedTime,it.resolvedByEmail=dn.resolvedByEmail??null,it.resolvedByName=dn.resolvedByName??null):(it.resolvedTime=null,it.resolvedByEmail=null,it.resolvedByName=null),dn.parentCommentId!==void 0?it.parentCommentId=dn.parentCommentId:delete it.parentCommentId,dn.trackedChangeParentId!==void 0?it.trackedChangeParentId=dn.trackedChangeParentId:delete it.trackedChangeParentId,dn.trackedChangeThreadParentId!==void 0?it.trackedChangeThreadParentId=dn.trackedChangeThreadParentId:it.trackedChangeThreadParentId=void 0,dn.trackedChangeSide!==void 0?it.trackedChangeSide=dn.trackedChangeSide:delete it.trackedChangeSide,dn.threadingParentCommentId!==void 0?it.threadingParentCommentId=dn.threadingParentCommentId:delete it.threadingParentCommentId},tr=[],No=new Set,$r=[];for(const it of q.value){if(!mr(it)||!Zn(it)){tr.push(it);continue}const dn=String(it.commentId),eo=gt.get(dn);eo&&(xr(it,eo),No.add(dn),tr.push(it)),!eo&&!de&&tr.push(it)}for(const[it,dn]of gt.entries()){if(No.has(it))continue;const eo=aa(dn);tr.push(eo),$r.push(eo)}return q.value=tr,Dt&&tt&&!tr.some(it=>String(it.commentId)===tt)&&fo(),{added:$r[$r.length-1]??null}}),zu=A=>{vi(A)},dc=A=>typeof A!="string"?null:A.replace(/\s*\(imported\)\s*$/u,"").trim()||null,Zi=A=>{if(!A)return null;try{if(A.isDestroyed===!0)return null;const M=A.view;if(!M||M.isDestroyed===!0||M.destroyed===!0)return null;const Q=M.state;return Q?{view:M,state:Q}:null}catch{return null}},uo=A=>A!=null&&String(A).length>0?String(A):null,Ts=A=>{const M=uo(A),Q=M?[[M,k.get(M)]]:Array.from(k.entries());let re=0;for(const[ae,de]of Q)de&&(k.delete(ae),de.timeoutHandle!==null&&de.timeoutHandle!==void 0&&clearTimeout(de.timeoutHandle),re+=1);return re},_a=A=>{const M=Zi(A);if(!M)return null;let Q=[];try{Q=la.getTrackChanges(M.state)??[]}catch{return null}const re=la?.enumerateStructuralRowChanges;let ae=[];if(typeof re=="function")try{ae=re(M.state)??[]}catch{ae=[]}let de=[];if(typeof wu=="function")try{de=wu(A)?.getAll?.()??[]}catch{de=[]}return{...M,trackedChanges:Q,structuralChanges:ae,storySnapshots:de}},Kf=(A,M,Q=null)=>{if(!A||!M)return!1;const re=Q??_a(A);return re?(bl(A,M,re.trackedChanges,{editorState:re.state,editorView:re.view}),yc({superdoc:M,editor:A,snapshots:re.storySnapshots,documentState:re.state,resolveFromEditor:!1}),Ji({superdoc:M,editor:A,structuralChanges:re.structuralChanges}),!0):!1},fc=A=>{if(!A||k.get(A.documentId)!==A)return!1;try{const M=A.editor?.options?.documentId;if(M!=null&&String(M)!==A.documentId)return!1;const Q=s.getDocument(A.documentId);if(!Q||Q.getEditor?.()!==A.editor)return!1}catch{return!1}return!0},hc=A=>{if(!fc(A))return k.get(A?.documentId)===A&&k.delete(A.documentId),!1;const M=_a(A.editor);if(!M||!fc(A))return k.get(A.documentId)===A&&k.delete(A.documentId),!1;try{return Kf(A.editor,A.superdoc,M)}finally{k.get(A.documentId)===A&&k.delete(A.documentId)}},vl=({editor:A,superdoc:M,documentId:Q,defer:re=!0})=>{const ae=uo(Q);if(!ae||!A||!M)return!1;Ts(ae);const de={documentId:ae,editor:A,superdoc:M,generation:++C,timeoutHandle:null};return k.set(ae,de),re?(de.timeoutHandle=setTimeout(()=>{de.timeoutHandle=null,hc(de)},0),!0):hc(de)};function yl(A){const M=A!=null?String(A):null;if(!M)return;Ts(M);const Q=q.value.filter(de=>bi(de,M,{allowSingleDocumentMismatch:!0}));if(!Q.length)return;const re=new Set;if(Q.forEach(de=>{Ht(de).forEach(fe=>re.add(fe))}),q.value=q.value.filter(de=>!Q.includes(de)),re.size){const de={...ie.value||{}};re.forEach(fe=>{delete de[fe]}),ie.value=de}const ae=R.value!=null?String(R.value):null;ae&&re.has(ae)&&fo()}function qf(A){yl(A)}const Qi=async({superdoc:A,editor:M,comments:Q,documentId:re,replacedFile:ae=!1})=>{const de=s.getDocument(re);if(de?.commentThreadingProfile&&(de.commentThreadingProfile.value=M?.converter?.commentThreadingProfile||null),ae&&qf(re),Q.forEach(fe=>{const le=Array.isArray(fe.elements)?fe.elements:[],Ae=eh(le);if(!Ae&&!fe.trackedChange)return;const Le=dc(fe.creatorName),Me=Le?`${Le} (imported)`:null;ri({superdoc:A,comment:aa({fileId:re,fileType:de.type,docxCommentJSON:le.length?le:null,commentId:fe.commentId,isInternal:!1,parentCommentId:fe.parentCommentId,trackedChangeParentId:fe.trackedChangeParentId,trackedChangeThreadParentId:fe.trackedChangeThreadParentId,creatorId:null,creatorName:Le,createdTime:fe.createdTime,creatorEmail:fe.creatorEmail,importedAuthor:{...Me?{name:Me}:{},email:fe.creatorEmail},commentText:Ae,resolvedTime:fe.isDone?Date.now():null,resolvedById:null,resolvedByEmail:fe.isDone?fe.creatorEmail:null,resolvedByName:fe.isDone?Me||"(Imported)":null,trackedChange:fe.trackedChange||!1,trackedChangeText:fe.trackedChangeText,trackedChangeType:fe.trackedChangeType,trackedChangeDisplayType:fe.trackedChangeDisplayType,deletedText:fe.trackedDeletedText,origin:fe.origin||"word",threadingMethod:fe.threadingMethod,threadingStyleOverride:fe.threadingStyleOverride,threadingParentCommentId:fe.threadingParentCommentId,originalXmlStructure:fe.originalXmlStructure})})}),ae){vl({editor:M,superdoc:A,documentId:re,defer:!1});return}vl({editor:M,superdoc:A,documentId:re})},bl=(A,M,Q=null,re={})=>{const{reopenResolved:ae=!1,refreshExisting:de=!1,broadcastChanges:fe=!0,editorState:le=null,editorView:Ae=null}=re,Le=le?{state:le,view:Ae}:Zi(A);if(!Le?.state)return;const Me=Le.state,ze=Q??la.getTrackChanges(Me),tt=k8(ze),ct=A?.options?.documentId!=null?String(A.options.documentId):null;if(!ct)return;const qe=new Set,Dt=new Map;q.value.forEach(rn=>{if(!rn?.trackedChange||!Kr(rn,ct)||!t(rn))return;const hn=[rn.commentId,rn.importedId].map(mr=>mr!=null?String(mr):null).filter(Boolean);if(rn.resolvedTime){ae||hn.forEach(mr=>qe.add(mr));return}hn.forEach(mr=>{Dt.set(mr,rn),de||qe.add(mr)})});const gt=new Map;for(const rn of ze){const hn=rn.mark.attrs.id;gt.has(hn)||gt.set(hn,[]),gt.get(hn).push(rn)}const Bt=ct,xt=new Set;tt.forEach(({insertedMark:rn,deletionMark:hn,formatMark:mr})=>{const xr=rn?.mark.attrs.id||hn?.mark.attrs.id||mr?.mark.attrs.id;if(xr==null)return;const tr=String(xr);if(xt.has(tr)||(xt.add(tr),!de&&qe.has(tr)))return;const No=Dt.get(tr),$r={...rn&&{insertedMark:rn.mark},...hn&&{deletionMark:hn.mark},...mr&&{formatMark:mr.mark}},it=s0({event:No?"update":"add",marks:$r,nodes:[],newEditorState:Me,documentId:Bt,trackedChangesForId:gt.get(xr)||[]});if(it){const dn=n(it.changeId??xr);it.trackedChangeStory=e,it.trackedChangeStoryKind="body",it.trackedChangeStoryLabel="",it.trackedChangeAnchorKey=dn,Oo({superdoc:M,params:it,broadcastChanges:fe,documentState:Me}),No||(qe.add(tr),it.changeId!=null&&qe.add(String(it.changeId)),it.importedId!=null&&qe.add(String(it.importedId)))}});const St=Le.view;try{if(!St||A.view!==St||St.isDestroyed===!0||St.destroyed===!0)return}catch{return}const{tr:Zn}=Me;Zn.setMeta(W8,{type:"force"}),St.dispatch(Zn)},Aa=({suppressedIds:A,activeDocumentId:M,superdoc:Q=null,broadcastChanges:re=!0})=>{if(!(A instanceof Set)||!A.size||!M)return;const ae=[];if(q.value=q.value.filter(le=>{if(!le?.trackedChange||!t(le)||Fo(le)||!Kr(le,M))return!0;const Ae=le.commentId!=null?String(le.commentId):null,Le=le.importedId!=null?String(le.importedId):null;return Ae&&A.has(Ae)||Le&&A.has(Le)?(ae.push(le),!1):!0}),!ae.length)return;const de=new Set;ae.forEach(le=>{le.commentId!=null&&de.add(String(le.commentId)),le.importedId!=null&&de.add(String(le.importedId));const Ae=er(le),Le={type:w.DELETED,comment:Ae,changes:[{key:"deleted",commentId:Ae.commentId,fileId:Ae.fileId}]};re&&(Xl(Q,Le),Q?.emit?.("comments-update",Le))});const fe=R.value!=null?String(R.value):null;fe&&de.has(fe)&&fo()},xs=A=>A?A.fileId!=null?String(A.fileId):A.documentId!=null?String(A.documentId):A.selection?.documentId!=null?String(A.selection.documentId):null:null,Yf=()=>{const A=Array.isArray(s.documents)?s.documents:s.documents?.value;return Array.isArray(A)?A:[]},yi=()=>{const A=Yf();return A.length!==1?null:A[0]?.id!=null?String(A[0].id):null},bi=(A,M,Q={})=>{const{allowSingleDocumentMismatch:re=!1}=Q;if(!M)return!1;const ae=xs(A);if(ae){if(ae===M)return!0;const de=yi();return re&&de===M}return yi()===M},Kr=(A,M)=>bi(A,M,{allowSingleDocumentMismatch:!0}),pc=A=>{const M=typeof A=="string"?A.toLowerCase():"";return M?M==="insert"||M==="insertion"||M==="trackinsert"||M==="tableinsert"||M==="paragraphsplit"?"insertion":M==="delete"||M==="deletion"||M==="trackdelete"||M==="tabledelete"?"deletion":M:null},wl=({comment:A,decision:M}={})=>{const Q=M==="accept"||M==="reject"?M:null;if(!Q)return!1;const re=pc(A?.trackedChangeDisplayType)??pc(A?.trackedChangeType);return Q==="accept"&&re==="insertion"||Q==="reject"&&re==="deletion"},Rs=(A,M,Q,re=null,{broadcastChanges:ae=!0}={})=>ms("store.trackedChanges.pruneStaleComments","store-reconciliation",{activeDocumentId:Q??null,liveIdCount:A instanceof Set?A.size:null,liveAnchorKeyCount:M instanceof Set?M.size:null},()=>{if(!(A instanceof Set)||!Q)return;const de=new Set,fe=[],le=[...q.value];if(q.value=q.value.filter(ze=>{if(!ze?.trackedChange||!Kr(ze,Q))return!0;const tt=ze.commentId!=null?String(ze.commentId):null,ct=ze.importedId!=null?String(ze.importedId):null,qe=ze.trackedChangeAnchorKey!=null?String(ze.trackedChangeAnchorKey):null,Dt=!!(tt&&A.has(tt)),gt=!!(ct&&A.has(ct)),Bt=!!(qe&&M?.has(qe));if(!tt&&!ct&&!qe||Dt||gt||Bt||ze.resolvedTime)return!0;const xt=v.get(ze);return xt?(ze.resolvedTime=xt.resolvedTime??Date.now(),ze.resolvedById=xt.resolvedById??null,ze.resolvedByEmail=xt.resolvedByEmail??null,ze.resolvedByName=xt.resolvedByName??null,ze.trackedChangeDecision=xt.trackedChangeDecision??null,fe.push(ze),!0):(tt&&de.add(tt),ct&&de.add(ct),!1)}),fe.forEach(ze=>{const tt=er(ze),ct={type:w.UPDATE,comment:tt};ae&&(Xl(re,ct),re?.emit?.("comments-update",ct))}),!de.size)return;let Ae=!0;for(;Ae;)Ae=!1,q.value=q.value.filter(ze=>{if(!Kr(ze,Q))return!0;const tt=ze.parentCommentId!=null?String(ze.parentCommentId):null,ct=kn(ze)!=null?String(kn(ze)):null;if(!(tt&&de.has(tt)||ct&&de.has(ct))||ze.resolvedTime)return!0;const qe=ze.commentId!=null?String(ze.commentId):null,Dt=ze.importedId!=null?String(ze.importedId):null;return qe&&de.add(qe),Dt&&de.add(Dt),Ae=!0,!1});le.filter(ze=>{if(!Kr(ze,Q))return!1;const tt=ze.commentId!=null?String(ze.commentId):null,ct=ze.importedId!=null?String(ze.importedId):null;return tt&&de.has(tt)||ct&&de.has(ct)}).forEach(ze=>{const tt=er(ze),ct={type:w.DELETED,comment:tt,changes:[{key:"deleted",commentId:tt.commentId,fileId:tt.fileId}]};ae&&(Xl(re,ct),re?.emit?.("comments-update",ct))});const Le=R.value!=null?String(R.value):null,Me=le.some(ze=>{const tt=ze.commentId!=null?String(ze.commentId):null,ct=ze.importedId!=null?String(ze.importedId):null;return Kr(ze,Q)&&(tt&&tt===Le||ct&&ct===Le)});Le&&de.has(Le)&&Me&&fo()}),Ia=({superdoc:A,comment:M,decision:Q}={})=>{if(!M?.trackedChange||wl({comment:M,decision:Q}))return 0;const re=Wo(M);if(!re.size)return 0;const ae={email:A?.user?.email??null,name:A?.user?.name??null,superdoc:A};let de=0;return Cl(M).forEach(fe=>{!fe||fe===M||fe.resolvedTime||[kn(fe),fe.threadingParentCommentId,fe.parentCommentId].map(le=>bt(le)).filter(Boolean).some(le=>re.has(le))&&typeof fe.resolveComment=="function"&&(fe.resolveComment(ae),de+=1)}),de},Wo=A=>{const M=new Set(Ht(A));A?.trackedChangeCanonicalId!=null&&M.add(String(A.trackedChangeCanonicalId));const Q=A?.trackedChangeAnchorKey!=null?String(A.trackedChangeAnchorKey):null;if(Q&&(M.add(Q),Q.startsWith("tc::"))){const re=Q.slice(Q.lastIndexOf("::")+2);re&&M.add(re)}return M},Cl=A=>{const M=[],Q=new Set;for(const re of Wo(A))for(const ae of ye.value.get(String(re))??[])Q.has(ae)||(Q.add(ae),M.push(ae));return M},Xf=A=>{const M=A&&typeof A=="object"?A:null;if(!M?.success)return new Set;const Q=new Set,re=ae=>{const de=ae&&typeof ae=="object"?ae:null;de?.kind!=="entity"||de.entityType!=="trackedChange"||de.entityId!=null&&String(de.entityId).length>0&&Q.add(String(de.entityId))};return Array.isArray(M.removed)&&M.removed.forEach(re),Array.isArray(M.invalidatedRefs)&&M.invalidatedRefs.forEach(re),Q},Vu=A=>{const M=new Set;return A?.decidedId!=null&&String(A.decidedId).length>0&&M.add(String(A.decidedId)),Array.isArray(A?.decidedIds)&&A.decidedIds.forEach(Q=>{Q!=null&&String(Q).length>0&&M.add(String(Q))}),Xf(A?.receipt).forEach(Q=>M.add(Q)),M},kl=({comment:A,decision:M}={})=>{if(!A?.trackedChange||!wl({comment:A,decision:M}))return 0;const Q=Wo(A);if(!Q.size)return 0;let re=0;return Cl(A).forEach(ae=>{if(!ae||ae===A)return;const de=bt(ae.trackedChangeParentId),fe=bt(ae.trackedChangeThreadParentId),le=bt(ae.threadingParentCommentId),Ae=bt(ae.parentCommentId);(de&&Q.has(de)||fe&&Q.has(fe)||le&&Q.has(le)||Ae&&Q.has(Ae))&&(delete ae.trackedChangeParentId,ae.trackedChangeThreadParentId=void 0,delete ae.trackedChangeSide,delete ae.threadingParentCommentId,Ae&&Q.has(Ae)&&delete ae.parentCommentId,re+=1)}),re},Zf=(A=[],{documentId:M}={})=>{const Q=bt(M);if(!Array.isArray(A)||A.length===0||!Q)return;const re=ie.value||{};let ae=!1;const de=(le,Ae,Le,Me)=>bt(le?.[Ae])!==Le?!1:(le[Ae]=Me,!0),fe=(le,Ae)=>le?.trackedChange&&Kr(le,Q)&&[le.commentId,le.importedId,le.trackedChangeCanonicalId,...Ht(le)].map(Le=>bt(Le)).includes(Ae);for(const le of A){const Ae=bt(le?.from),Le=bt(le?.to);if(!Ae||!Le||Ae===Le)continue;const Me=q.value.find(xt=>fe(xt,Ae));if(!Me)continue;const ze={};for(const xt of["commentId","importedId"])de(Me,xt,Ae,Le)&&(ze[xt]=Le);de(Me,"trackedChangeCanonicalId",Ae,Le)&&(ze.trackedChangeCanonicalId=Le);const tt=n(Ae),ct=r(Me.trackedChangeAnchorKey)?.storyKey??un(Nt(Me)),qe=o(ct,Ae),Dt=o(ct,Le);(bt(Me.trackedChangeAnchorKey)===tt||Me.trackedChangeAnchorKey==null||bt(Me.trackedChangeAnchorKey)===qe)&&(Me.trackedChangeAnchorKey=Dt),Array.isArray(Me.trackedChangePositionAliases)&&(Me.trackedChangePositionAliases=Me.trackedChangePositionAliases.map(xt=>bt(xt)===Ae?Le:xt)),q.value.forEach(xt=>{if(xt===Me||!Kr(xt,Q))return;const St={};for(const Zn of["trackedChangeThreadParentId","trackedChangeParentId","threadingParentCommentId","parentCommentId"])de(xt,Zn,Ae,Le)&&(St[Zn]=Le);Object.keys(St).length&&typeof xt.updateIdentityValues=="function"&&xt.updateIdentityValues(St)}),Object.keys(ze).length&&typeof Me.updateIdentityValues=="function"&&Me.updateIdentityValues(ze);const gt=[re[Ae],re[tt]],Bt=re[qe]??gt.find(xt=>xt&&Pe(xt,Me));if(Bt)for(const xt of[Le,Dt])re[xt]===void 0&&(re[xt]=Bt,ae=!0);bt(R.value)===Ae&&(R.value=Le),bt(F.value)===Ae&&(F.value=Le)}ae&&(ie.value={...re})},Hu=({superdoc:A,comment:M,decidedId:Q,decidedIds:re,documentId:ae}={})=>{const de=new Set((Array.isArray(re)||re instanceof Set?Array.from(re):[Q]).map(tt=>bt(tt)).filter(Boolean)),fe=bt(ae);if(!de.size||!fe)return{removed:!1,removedIds:new Set};const le=new Set;let Ae=!1;const Le=M?q.value.indexOf(M):-1,Me=M?.trackedChange?Wo(M):new Set;if(Le>=0&&Kr(M,fe)&&Array.from(Me).some(tt=>de.has(tt))?(Me.forEach(tt=>le.add(tt)),q.value.splice(Le,1),Ae=!0):q.value=q.value.filter(tt=>{if(!tt?.trackedChange||!Kr(tt,fe))return!0;const ct=Wo(tt);return Array.from(ct).some(qe=>de.has(qe))?(Ae=!0,ct.forEach(qe=>le.add(qe)),!1):!0}),!Ae)return{removed:!1,removedIds:le};const ze=R.value!=null?String(R.value):null;return ze&&le.has(ze)&&fo(),{removed:!0,removedIds:le}},mc=({adapter:A,documentId:M}={})=>{const Q=bt(M);if(!A||!Q)return{removed:0,removedIds:new Set};en(A);const re=new Set,ae=bt(R.value);let de=!1;const fe=q.value.filter(Ae=>{if(!Ae?.trackedChange||!Kr(Ae,Q))return!0;const Le=Wo(Ae);return Le.forEach(Me=>re.add(Me)),ae&&Le.has(ae)&&(de=!0),!1}),le=q.value.length-fe.length;return le>0&&(q.value=fe),de&&fo(),{removed:le,removedIds:re}},gc=(A,M)=>{if(!(!M||typeof A?.clearActiveTrackedChangeTargetIfMatches!="function"))try{A.clearActiveTrackedChangeTargetIfMatches(M)}catch{}},Uu=async({superdoc:A,receipt:M}={})=>{const Q=A?.activeEditor?.documentMutationReadiness;if(!(M?.success!==!0||typeof M?.txId!="string"||!M.txId||typeof Q?.whenPainted!="function"))try{await Q.whenPainted(M);const re=globalThis.requestAnimationFrame;typeof re=="function"&&await new Promise(ae=>{let de=!1;const fe=()=>{de||(de=!0,clearTimeout(le),ae())},le=setTimeout(fe,250);re(()=>re(()=>setTimeout(fe,0)))})}catch{}},Sl=({superdoc:A,comment:M,decision:Q})=>{if(d())return{ok:!1,reason:"read-only-document"};if(!M?.trackedChange)return{ok:!1};const re=Ut(A);if(re){if(Q!=="accept"&&Q!=="reject")return Promise.resolve({ok:!1,reason:"decision-invalid"});const Me=M?.trackedChangeCanonicalId!=null?String(M.trackedChangeCanonicalId):M?.commentId!=null?String(M.commentId):M?.trackedChangeAnchorKey?.startsWith?.("tc::body::")?M.trackedChangeAnchorKey.slice(10):null,ze=Me!=null&&String(R.value??"")===Me;return ms("store.trackedChanges.sidebarDecision","command",{decision:Q,decidedId:Me},()=>(async()=>{try{return await(Q==="accept"?re.accept(M):re.reject(M))}catch(tt){return{ok:!1,reason:"adapter-threw",detail:tt?.message??String(tt)}}})().then(async tt=>{if(!Li(re))return{ok:!1,reason:"adapter-stale"};if(!tt?.ok)return{ok:!1,reason:tt?.reason,detail:tt?.detail};const ct=Vu(tt),qe=tt?.documentId??re.documentId??A?.activeEditor?.documentId??A?.activeEditor?.options?.documentId??null,Dt=async()=>{let gt;try{gt=await re.listTrackedChanges({mode:"all",refreshReason:"post-decision-blocking",blocking:!0})}catch(St){return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:St?.message??String(St)}}if(!Li(re))return{ok:!1,committed:!0,reason:"adapter-stale"};if(!gt?.ok)return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:gt?.reason??gt?.detail??null};Ia({superdoc:A,comment:M,decision:Q}),kl({comment:M,decision:Q}),Pi({superdoc:A,adapter:re,documentId:qe,items:gt.items??[],pruneStale:gt.complete===!0&>.sourceCoverageComplete===!0});const Bt=new Set((gt.items??[]).map(St=>St&&St.id!=null?String(St.id):null).filter(Boolean));Me!=null&&Bt.has(Me)||(ze&&fo(),gc(re,Me));const xt=we(A);if(xt&&typeof xt.refresh=="function"&&Go(xt)){let St;try{St=await xt.refresh()}catch(Zn){return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:Zn?.message??String(Zn)}}if(!Go(xt))return{ok:!1,committed:!0,reason:"comments-adapter-stale"};if(!St?.ok)return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:St?.reason??St?.detail??null};Xn({superdoc:A,adapter:xt,documentId:xt.documentId??qe,items:St.items??[]})}return{ok:!0,success:!0}};return!ct.size||!qe?Dt():(ct.forEach(gt=>gc(re,gt)),await Uu({superdoc:A,receipt:tt.receipt}),Ia({superdoc:A,comment:M,decision:Q}),kl({comment:M,decision:Q}),Hu({superdoc:A,comment:M,decidedIds:ct,documentId:qe}),ze&&fo(),{ok:!0,success:!0})}))}const ae=A?.activeEditor;if(!ae)return{ok:!1};const de=M.commentId??M.importedId;if(!de)return{ok:!1};const fe=M.trackedChangeStory??void 0,le=typeof ae.doc=="object"?ae.doc:null;if(le?.trackChanges?.decide)try{const Me=fe?{id:de,story:fe}:{id:de};return Promise.resolve(le.trackChanges.decide({decision:Q,target:Me})).then(ze=>({ok:!0,success:!!ze?.success}))}catch(Me){if(fe)return{ok:!1,error:Me}}const Ae=Q==="accept"?"acceptTrackedChangeById":"rejectTrackedChangeById",Le=ae.commands?.[Ae];return typeof Le!="function"?{ok:!1}:{ok:!0,success:!!Le(de)}},Qf=async({superdoc:A,adapter:M,documentId:Q,trackedChangesListMode:re="all",refreshReason:ae,blocking:de,isCurrent:fe,targetIds:le,reconciliationBatchSize:Ae=l0,signal:Le,hydrationGeneration:Me}={})=>ms("store.trackedChanges.hydrateFromV2","tracked-change-list",{documentId:Q??null,trackedChangesListMode:re,refreshReason:ae??null,blocking:de??null},async()=>{const ze=M??Ut(A);if(!ze||typeof ze.listTrackedChanges!="function")return{ok:!1,reason:"adapter-missing"};const tt=()=>fe?.()!==!1&&Li(ze);if(!tt())return{ok:!1,reason:"adapter-stale"};const ct=Ct(ze),qe=()=>tt()&&!Le?.aborted&&Ct(ze)===ct;if(Le?.aborted)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!1};const Dt=new Set,gt=new Set;let Bt=0,xt=0,St;try{const hn={mode:re};Array.isArray(le)&&(hn.targetIds=le),ae!=null&&(hn.refreshReason=ae),typeof de=="boolean"&&(hn.blocking=de),Le&&(hn.signal=Le),typeof Me=="number"&&(hn.hydrationGeneration=Me),re==="background-reconcile"&&(hn.shouldContinue=qe,hn.onPage=async mr=>{if(!qe())return;const xr=Array.isArray(mr?.items)?mr.items:[];!Pi({superdoc:A,adapter:ze,documentId:Q,items:xr,pruneStale:!1,liveIds:Dt,liveAnchorKeys:gt,hydrationGeneration:Me})||!qe()||(Bt+=1,xt+=xr.length)}),St=await ze.listTrackedChanges(hn)}catch(hn){return{ok:!1,reason:"adapter-threw",detail:hn?.message??String(hn)}}if(!tt())return{ok:!1,reason:"adapter-stale"};if(Ct(ze)!==ct)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0};if(Le?.aborted)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0};if(!St?.ok)return St;const Zn=!(re==="startup-page"||re==="interaction-prime"||re==="visible-window")&&St.visibleWindowSource==null&&St.complete===!0&&St.sourceCoverageComplete===!0;if(Le?.aborted||Ct(ze)!==ct)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0};if(re==="background-reconcile")if(Bt>0){if(!qe())return{ok:!1,reason:"reconciliation-stale"};const hn=Q??ze.documentId??A?.activeEditor?.documentId??null;Zn&&hn&&ms("store.trackedChanges.reconcile.finalPrune","store-reconciliation",{documentId:hn,liveIds:Dt.size,liveAnchorKeys:gt.size},()=>{qe()&&Rs(Dt,gt,String(hn),A,{broadcastChanges:!1})})}else{const hn=await ju({superdoc:A,adapter:ze,documentId:Q,items:St.items??[],pruneStale:Zn,isCurrent:tt,batchSize:Ae,hydrationGeneration:Me});if(!hn.ok)return hn;xt=hn.appliedItems}else Pi({superdoc:A,adapter:ze,documentId:Q,items:St.items??[],pruneStale:Zn,hydrationGeneration:Me});const rn={ok:!0,items:St.items??[],reconciled:!0,...typeof Me=="number"?{hydrationGeneration:Me}:{}};typeof St.complete=="boolean"&&(rn.complete=St.complete),typeof St.sourceCoverageComplete=="boolean"&&(rn.sourceCoverageComplete=St.sourceCoverageComplete),St.visibleWindowSource!=null&&(rn.visibleWindowSource=St.visibleWindowSource),St.visibleWindowFallbackReason!=null&&(rn.visibleWindowFallbackReason=St.visibleWindowFallbackReason),typeof St.visibleTrackedChangeExpectedRows=="number"&&(rn.visibleTrackedChangeExpectedRows=St.visibleTrackedChangeExpectedRows),typeof St.visibleTrackedChangeObservedRows=="number"&&(rn.visibleTrackedChangeObservedRows=St.visibleTrackedChangeObservedRows);for(const hn of["visibleTrackedChangeRequestedIds","visibleTrackedChangeSucceededIds","visibleTrackedChangeFailedIds"])Array.isArray(St[hn])&&(rn[hn]=[...St[hn]]);return Array.isArray(St.visibleWindowGetFailures)&&(rn.visibleWindowGetFailures=St.visibleWindowGetFailures.map(hn=>({...hn}))),typeof St.refreshReason=="string"&&(rn.refreshReason=St.refreshReason),typeof St.blocking=="boolean"&&(rn.blocking=St.blocking),typeof St.pageCount=="number"&&(rn.pageCount=St.pageCount),typeof St.pagesStarted=="number"&&(rn.pagesStarted=St.pagesStarted),typeof St.pagesCompleted=="number"&&(rn.pagesCompleted=St.pagesCompleted),typeof St.pagesSkippedAfterAbort=="number"&&(rn.pagesSkippedAfterAbort=St.pagesSkippedAfterAbort),typeof St.totalItems=="number"&&(rn.totalItems=St.totalItems),typeof St.coalesced=="boolean"&&(rn.coalesced=St.coalesced),typeof St.evaluatedRevision=="string"&&(rn.evaluatedRevision=St.evaluatedRevision),re==="background-reconcile"&&(rn.incrementalPagesApplied=Bt,rn.incrementalItemsApplied=xt),rn}),Ms=async({superdoc:A,adapter:M,documentId:Q,upsertIds:re=[],removedIds:ae=[],allResolved:de}={})=>{const fe=M??Ut(A);if(!fe)return{ok:!1,reason:"adapter-missing"};if(!Li(fe))return{ok:!1,reason:"adapter-stale"};const le=Q??fe.documentId??A?.activeEditor?.documentId??null;if(de&&le==null)return{ok:!1,reason:"document-id-missing"};if(de)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[],allResolved:!0,removedRows:ms("store.trackedChanges.allResolved","store-reconciliation",{documentId:String(le),logicalTargetCount:de.logicalTargetCount??null,physicalCarrierCount:de.physicalCarrierCount??null},()=>mc({adapter:fe,documentId:le})).removed};const Ae=Ct(fe),Le=new Set(Array.from(ae??[]).map(gt=>bt(gt)).filter(Boolean)),Me=[...new Set(Array.from(re??[]).map(gt=>bt(gt)).filter(Boolean))];if(Le.size>0&&Me.length===0&&le!=null&&Hu({superdoc:A,decidedIds:Le,documentId:le}),Me.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};if(typeof fe.getTrackedChange!="function")return{ok:!1,reason:"adapter-get-missing"};const ze=await Promise.all(Me.map(async gt=>{try{return{id:gt,result:await fe.getTrackedChange(gt)}}catch(Bt){return{id:gt,result:{ok:!1,reason:"adapter-threw",detail:Bt?.message??String(Bt)}}}}));if(!Li(fe))return{ok:!1,reason:"adapter-stale"};if(Ct(fe)!==Ae)return{ok:!1,reason:"generation-stale"};const tt=[],ct=[],qe=[];for(const{id:gt,result:Bt}of ze){const xt=(Bt?.ok&&Array.isArray(Bt.items)?Bt.items:[]).filter(St=>Kt(St).has(gt));xt.length>0?(tt.push(gt),qe.push(...xt)):ct.push(gt)}const Dt=Rn(qe);return qe.length>0&&Pi({superdoc:A,adapter:fe,documentId:le,items:Dt,pruneStale:!1}),{ok:ct.length===0,items:Dt,resolvedIds:tt,unresolvedIds:ct,failures:ze.map(({result:gt})=>gt).filter(gt=>!gt?.ok)}},vc=A=>{const M=new Map,Q=new Set;let re=0,ae=0;const de=(le,Ae,Le)=>{const Me=bt(Ae);if(!Me)return;const ze=le.get(Me)??new Set;ze.add(Le),le.set(Me,ze)},fe=le=>{le?.trackedChange&&(A&&!Kr(le,A)||(Q.add(le),de(M,le.commentId,le),de(M,le.importedId,le),de(M,le.trackedChangeCanonicalId,le),de(M,le.trackedChangeAnchorKey,le),Ht(le).forEach(Ae=>de(M,Ae,le))))};return q.value.forEach(fe),{add:fe,work:()=>({trackedRowsIndexed:Q.size,invalidatedIdMembershipChecks:0,incomingAliasLookups:re,candidateVisits:ae}),candidates({changeId:le,importedId:Ae,anchorKey:Le,canonicalId:Me,positionAliases:ze=[]}={}){const tt=new Set,ct=qe=>{const Dt=bt(qe);if(!Dt)return;re+=1;const gt=M.get(Dt);gt&&(ae+=gt.size,gt.forEach(Bt=>tt.add(Bt)))};return new Set([le,Ae,Me,Le,...ze]).forEach(ct),tt}}},Pi=({superdoc:A,adapter:M,documentId:Q,items:re,pruneStale:ae=!0,preparedParams:de=null,liveIds:fe=null,liveAnchorKeys:le=null,hydrationGeneration:Ae}={})=>ms("store.trackedChanges.reconcile","store-reconciliation",{documentId:Q??null,itemCount:Array.isArray(re)?re.length:null,pruneStale:ae,hydrationGeneration:Ae??null},()=>{if(!M||!Array.isArray(re)||!Li(M))return;const Le=Q??M.documentId??A?.activeEditor?.documentId??null,Me=le instanceof Set?le:new Set,ze=fe instanceof Set?fe:new Set;let tt=0;const ct=vc(Le==null?null:String(Le)),qe=i0("store.trackedChanges.batchIdentity","store-reconciliation",{itemCount:re.length}),Dt=Array.isArray(de)?de:re.map(gt=>M.mapV2TrackedChangeToCommentParams(gt));try{for(const gt of Dt)if(gt){if(gt.event==="omit"){gt.changeId!=null&&ze.add(String(gt.changeId));continue}Le&>.documentId==null&&(gt.documentId=Le),gt.changeId!=null&&ze.add(String(gt.changeId)),gt.trackedChangeAnchorKey!=null&&Me.add(String(gt.trackedChangeAnchorKey)),Oo({superdoc:A,params:gt,broadcastChanges:!1,trackedChangeIdentityIndex:ct}),tt+=1}}finally{bu(qe,ct.work())}return!Le||!ae?{liveIds:ze,liveAnchorKeys:Me,appliedCount:tt}:(Rs(ze,Me,String(Le),A,{broadcastChanges:!1}),{liveIds:ze,liveAnchorKeys:Me,appliedCount:tt})}),ju=async({superdoc:A,adapter:M,documentId:Q,items:re,pruneStale:ae,isCurrent:de,batchSize:fe=l0,hydrationGeneration:le}={})=>{if(!M||!Array.isArray(re))return{ok:!1,reason:"reconcile-input-invalid"};const Ae=()=>de?.()!==!1&&Li(M);if(!Ae())return{ok:!1,reason:"reconciliation-stale"};const Le=Math.max(1,Math.floor(Number(fe)||l0)),Me=Q??M.documentId??A?.activeEditor?.documentId??null,ze=new Set,tt=new Set;let ct=0,qe=0;for(let Dt=0;Dt<re.length;Dt+=Le){if(!Ae())return{ok:!1,reason:"reconciliation-stale",appliedItems:ct,batchCount:qe};const gt=re.slice(Dt,Dt+Le);if(!Pi({superdoc:A,adapter:M,documentId:Me,items:gt,pruneStale:!1,liveIds:ze,liveAnchorKeys:tt,hydrationGeneration:le})||!Ae())return{ok:!1,reason:"reconciliation-stale",appliedItems:ct,batchCount:qe};ct+=gt.length,qe+=1,Dt+Le<re.length&&await $8()}return Ae()?ae&&Me&&(ms("store.trackedChanges.reconcile.finalPrune","store-reconciliation",{documentId:Me,liveIds:ze.size,liveAnchorKeys:tt.size},()=>{Ae()&&Rs(ze,tt,String(Me),A,{broadcastChanges:!1})}),!Ae())?{ok:!1,reason:"reconciliation-stale",appliedItems:ct,batchCount:qe}:{ok:!0,appliedItems:ct,batchCount:qe,pruned:!!(ae&&Me)}:{ok:!1,reason:"reconciliation-stale",appliedItems:ct,batchCount:qe}},Di=(A=null)=>{const M=A==null?null:String(A);return q.value.filter(Q=>{if(Q?.trackedChange!==!0)return!1;if(M==null)return!0;const re=Q?.documentId??Q?.fileId??null;return re!=null&&String(re)===M}).length},Gu=({superdoc:A,editor:M,broadcastChanges:Q=!0})=>{if(!A||!M)return;const re=M?.options?.documentId!=null?String(M.options.documentId):null;if(!re)return;const ae=_a(M);if(!ae)return;const de=ae.trackedChanges,fe=new Set;de.forEach(Ae=>{const Le=Ae?.mark?.attrs?.id;Le!=null&&fe.add(String(Le))});const le=ae.storySnapshots;Rs(fe,new Set(le.map(Ae=>Ae?.anchorKey).filter(Ae=>typeof Ae=="string"&&Ae.length>0)),re,A,{broadcastChanges:Q}),bl(M,A,de,{reopenResolved:!0,refreshExisting:!0,broadcastChanges:Q,editorState:ae.state,editorView:ae.view}),yc({superdoc:A,editor:M,broadcastChanges:Q,snapshots:le,documentState:ae.state}),Ji({superdoc:A,editor:M,broadcastChanges:Q,structuralChanges:ae.structuralChanges})},Ji=({superdoc:A,editor:M,broadcastChanges:Q=!0,structuralChanges:re=null})=>{const ae=M?.options?.documentId!=null?String(M.options.documentId):null;if(!ae)return;const de=la?.enumerateStructuralRowChanges;if(typeof de!="function")return;let fe=re;if(!Array.isArray(fe)){const le=Zi(M);if(!le)return;try{fe=de(le.state)??[]}catch{fe=[]}}for(const le of fe){if(!le?.decidable||!le?.wholeTable)continue;const Ae=i(le);if(!Ae)continue;const Le=n(Ae),Me=le.subtype==="table-insert"?"tableInsert":"tableDelete",ze=le.side==="insertion"?"trackInsert":"trackDelete",tt=String(Ae),ct=Le!=null?String(Le):null;Oo({superdoc:A,params:{event:q.value.find(qe=>{if(!qe?.trackedChange||!Kr(qe,ae))return!1;const Dt=qe.trackedChangeAnchorKey!=null?String(qe.trackedChangeAnchorKey):null;if(ct&&Dt)return Dt===ct;const gt=qe.commentId!=null?String(qe.commentId):null,Bt=qe.importedId!=null?String(qe.importedId):null;return gt===tt||Bt===tt})?"update":"add",changeId:Ae,trackedChangeText:"",trackedChangeType:ze,trackedChangeDisplayType:Me,deletedText:null,authorId:null,authorEmail:le.authorEmail||null,authorImage:le.authorImage||null,date:le.date||null,author:le.author||null,importedAuthor:le.importedAuthor?{name:le.importedAuthor}:null,semanticColorKey:le.semanticColorKey??null,semanticColor:le.semanticColor??null,documentId:ae,coords:null,trackedChangeStory:e,trackedChangeStoryKind:"body",trackedChangeStoryLabel:"",trackedChangeAnchorKey:Le},broadcastChanges:Q})}},yc=({superdoc:A,editor:M,broadcastChanges:Q=!0,snapshots:re=null,documentState:ae=void 0,resolveFromEditor:de=!0})=>{const fe=M?.options?.documentId!=null?String(M.options.documentId):null;if(!fe)return;let le=re;if(!Array.isArray(le)){if(typeof wu!="function"||!Zi(M))return;let Ae=null;try{Ae=wu(M)}catch{return}if(!Ae)return;try{le=Ae.getAll()}catch{return}}for(const Ae of le)Ae.storyKind!=="body"&&wc({superdoc:A,editor:M,snapshot:Ae,documentId:fe,broadcastChanges:Q,documentState:ae,resolveFromEditor:de})},Wu=A=>A?.type!=="structural"?A?.type??null:A?.subtype==="table-delete"?"tableDelete":"tableInsert",Ku=A=>A?.type!=="structural"?A?.type??null:A?.subtype==="table-delete"?"trackDelete":"trackInsert",bc=A=>A?A.type==="delete"?!0:A.type==="structural"&&A.subtype==="table-delete":!1,qu=({editor:A,snapshot:M,documentId:Q,event:re,resolveFromEditor:ae=!0})=>{const de=Ku(M),fe=Wu(M),le={event:re,changeId:M.runtimeRef.rawId,trackedChangeText:bc(M)?"":M.excerpt??"",trackedChangeType:de,trackedChangeDisplayType:fe,semanticColorKey:M.semanticColorKey??null,semanticColor:M.semanticColor??null,deletedText:bc(M)?M.excerpt??"":null,authorId:M.authorId,authorEmail:M.authorEmail,authorImage:M.authorImage,date:M.date,author:M.author,documentId:Q,coords:null,trackedChangeStory:M.story,trackedChangeStoryKind:M.storyKind,trackedChangeStoryLabel:M.storyLabel,trackedChangeAnchorKey:M.anchorKey};if(!ae||typeof wk!="function")return le;let Ae=null;try{Ae=wk(A,{kind:"entity",entityType:"trackedChange",entityId:M.runtimeRef.rawId,story:M.story})}catch{Ae=null}const Le=Ae?.editor?.state??null;if(!Le)return le;let Me=[];try{Me=la.getTrackChanges(Le,Ae.change.rawId)??[]}catch{Me=[]}const ze=s0({event:re,marks:jo(Me),nodes:[],newEditorState:Le,documentId:Q,trackedChangesForId:Me});return ze?(ze.semanticColorKey==null&&M.semanticColorKey!=null&&(ze.semanticColorKey=M.semanticColorKey),ze.semanticColor==null&&M.semanticColor!=null&&(ze.semanticColor=M.semanticColor),ze.trackedChangeStory=M.story,ze.trackedChangeStoryKind=M.storyKind,ze.trackedChangeStoryLabel=M.storyLabel,ze.trackedChangeAnchorKey=M.anchorKey,ze):le},wc=({superdoc:A,editor:M,snapshot:Q,documentId:re,broadcastChanges:ae,documentState:de,resolveFromEditor:fe})=>{if(!Q?.runtimeRef?.rawId)return;const le=q.value.find(Ae=>{if(!Ae?.trackedChange)return!1;const Le=Ae.trackedChangeAnchorKey!=null?String(Ae.trackedChangeAnchorKey):null;return Le&&Q.anchorKey?Le===Q.anchorKey:Le||Q.anchorKey?!1:Ae.commentId===Q.runtimeRef.rawId||Ae.importedId===Q.runtimeRef.rawId});Oo({superdoc:A,params:qu({editor:M,snapshot:Q,documentId:re,event:le?"update":"add",resolveFromEditor:fe}),broadcastChanges:ae,documentState:de}),le&&(le.trackedChangeStory=Q.story,le.trackedChangeStoryKind=Q.storyKind,le.trackedChangeStoryLabel=Q.storyLabel,le.trackedChangeAnchorKey=Q.anchorKey)},Ea=A=>A?(Array.isArray(A)?A:[A]).filter(Boolean):[],Yu=()=>{const A=[];return q.value.forEach(M=>{const Q=M.getValues(),re=Q.commentText,ae=Ea(Q.docxCommentJSON),de=ae.length?ae:Cc(re);A.push({...Q,commentJSON:de})}),A},Cc=A=>{const M=new yk({mode:"text",isHeadless:!0,content:A,extensions:bk()}).getJSON();return Array.isArray(M?.content)?M.content.filter(Boolean):[]},Jf=(A,M={})=>{if(A==null)return;const Q=M?.retainMissingTrackedChangeGeometry===!0,re=Q&&M?.retainedTrackedChangeIds!=null?new Set(Array.from(M.retainedTrackedChangeIds,Ae=>bt(Ae)).filter(Boolean)):null,ae=ie.value||{},de={};Object.entries(A).forEach(([Ae,Le])=>{de[Ae]=Le;const Me=Le?.kind==="trackedChange"&&Le?.storyKey==="body"&&Le?.threadId!=null?String(Le.threadId):null;Me&&de[Me]===void 0&&(de[Me]=Le);const ze=typeof Le?.key=="string"?Le.key:null;ze&&de[ze]===void 0&&(de[ze]=Le)});const fe=(Ae,Le)=>{for(const Me of Ht(Ae)){const ze=Le[Me];if(ze!==void 0&&Pe(ze,Ae))return ze}return null},le=(Ae,Le,Me=[])=>{const ze=[...Ht(Le),...Me.map(tt=>bt(tt)).filter(Boolean)];for(const tt of new Set(ze))de[tt]===void 0&&(de[tt]=Ae)};q.value.forEach(Ae=>{if(!Ae?.trackedChange||Ae.resolvedTime)return;const Le=fe(Ae,de);if(Le){le(Le,Ae);return}if(!Q||re&&!Ht(Ae).some(ze=>re.has(ze)))return;const Me=fe(Ae,ae);Me&&le(Me,Ae,[Me.key,Me.threadId])}),ie.value=de},Xu=()=>{ie.value={}},Fo=A=>{if(!A?.trackedChange)return!1;const M=A?.trackedChangeDisplayType;return M==="tableInsert"||M==="tableDelete"?!0:[A?.commentId,A?.importedId,A?.trackedChangeAnchorKey].map(Q=>Q!=null?String(Q):"").filter(Boolean).some(Q=>Q.includes("word:structural:"))},kc=new WeakMap,Ta=A=>{if(!A)return{ranges:[],ids:new Set};const M=kc.get(A);if(M)return M;const Q=[],re=new Set,ae=le=>{le!=null&&le!==""&&re.add(String(le))},de=la?.enumerateStructuralRowChanges;if(typeof de=="function"){let le=[];try{le=de(A)??[]}catch{le=[]}for(const Ae of le){if(!Ae?.decidable||!Ae?.wholeTable)continue;const Le=Number(Ae.tableFrom),Me=Number(Ae.tableTo);Number.isFinite(Le)&&Number.isFinite(Me)&&Q.push({from:Le,to:Me}),ae(Ae.id),ae(Ae.revisionId),ae(Ae.revisionGroupId),ae(Ae.sourceId);for(const ze of Ae.rows||[]){const tt=ze?.node?.attrs?.trackChange;ae(tt?.id),ae(tt?.sourceId)}}}const fe={ranges:Q,ids:re};return kc.set(A,fe),fe},Sc=A=>{const M=s.getDocument(A)?.getEditor?.();return Ta(M?.state).ranges},$f=(A,M)=>!M?.length||!A?.length?!1:A.every(Q=>{const re=Number(Q?.from),ae=Number(Q?.to);return!Number.isFinite(re)||!Number.isFinite(ae)?!1:M.some(de=>re>=de.from&&ae<=de.to)}),_l=A=>{if(!A?.trackedChange||Fo(A))return!1;const M=Sc(A?.fileId);if(!M.length)return!1;const Q=Pn(A).entry,re=Xi(Q);return re?M.some(ae=>re.start>=ae.from&&re.end<=ae.to):!1},_c=_e(()=>co.value?.parentComments.filter(A=>!A.resolvedTime).filter(A=>!cn(A)||Gn(A)?!0:!!Pn(A).entry).filter(A=>!_l(A))),Zu=_e(()=>_c.value.flatMap(A=>{const{key:M,entry:Q}=Pn(A);return M8({comment:A,positionKey:M,positionEntry:Q,fallbackId:bt(A?.commentId)??Ht(A)[0]??null})})),Qu=A=>A==null?null:String(A),Ls=(A=null)=>{F.value=Qu(A)},fo=()=>{R.value=null,Ls(null)},Ju=(A,M)=>A==null||M==null?!1:Zu.value.some(Q=>String(Q.id)===String(A)&&String(Q.comment?.commentId??Q.threadId??"")===String(M)),Ps=A=>{Ju(F.value,A)||Ls(null)},Al=({documentMode:A,commentsVisible:M,trackChangesVisible:Q}={})=>{typeof A=="string"&&(h.documentMode=A),typeof M=="boolean"&&(h.commentsVisible=M),typeof Q=="boolean"&&(h.trackChangesVisible=Q)},Ac=A=>{if(Array.isArray(A))return A.map(fe=>Ac(fe)).flat().filter(Boolean);if(!A||typeof A!="object")return A;const M=fe=>{if(!fe)return fe;const le={...fe};return delete le.fontSize,delete le.fontFamily,delete le.eastAsiaFontFamily,Object.keys(le).length?le:void 0},Q=fe=>{if(!fe)return fe;const le=typeof fe.type=="string"?fe.type:fe.type?.name,Ae=fe?.attrs?{...fe.attrs}:void 0;return le==="textStyle"&&Ae?{...fe,attrs:M(Ae)}:{...fe,attrs:Ae}},re=fe=>Array.isArray(fe)?fe.filter(Boolean).map(le=>Q(le)):void 0,ae=fe=>fe&&typeof fe=="object"?{...fe}:void 0;if(!Array.isArray(A.content))return{type:A.type,...A.text!==void 0?{text:A.text}:{},...A.attrs?{attrs:ae(A.attrs)}:{},...A.marks?{marks:re(A.marks)}:{}};const de=A.content.map(fe=>Ac(fe)).flat().filter(Boolean);return A.type==="run"?de:{type:A.type,...A.attrs?{attrs:ae(A.attrs)}:{},...A.marks?{marks:re(A.marks)}:{},content:de}},eh=A=>{const M=Array.isArray(A)?A:A?[A]:[];if(M.some(Q=>Q?.content?.length))try{const Q=Ac(M),re=Array.isArray(Q)?Q:Q?[Q]:[];return re.length?new yk({mode:"text",isHeadless:!0,content:{type:"doc",content:re},loadFromSchema:!0,extensions:bk()}).getHTML():null}catch(Q){console.warn("Failed to convert comment",Q);return}};return{COMMENT_EVENTS:w,isDebugging:g,hasInitializedComments:x,hasSyncedCollaborationComments:P,editingCommentId:Z,activeComment:R,activeFloatingCommentInstanceId:F,commentDialogs:D,overlappingComments:B,overlappedIds:T,suppressInternalExternal:V,pendingComment:O,currentCommentText:J,commentsList:q,isCommentsListVisible:ce,generalCommentIds:Ye,editorCommentIds:ke,commentsParentElement:N,editorCommentPositions:ie,hasInitializedLocations:G,isCommentHighlighted:xe,floatingCommentsOffset:Je,sortedConversations:st,visibleConversations:Tt,skipSelectionUpdate:Te,isFloatingCommentsReady:je,instantSidebarAlignmentTargetY:$,instantSidebarAlignmentThreadId:S,instantSidebarAlignmentInstanceId:ee,getConfig:zr,documentsWithConverations:gi,getGroupedComments:co,hasOpenTrackedChanges:pr,getCommentsByPosition:hl,getFloatingComments:_c,getFloatingCommentInstances:Zu,getCommentAliasIds:Ht,getTrackedChangeThread:Ne,getCommentPositionKey:Uo,getCommentPosition:Ri,getCommentAnchoredText:ba,getCommentAnchorData:ti,resolveCommentPositionEntry:Pn,getCommentDocumentId:xs,belongsToDocument:bi,viewingVisibility:h,isViewingMode:U,shouldRenderReviewInViewing:W,init:In,setViewingVisibility:Al,getComment:$t,setActiveComment:uc,getCommentLocation:ni,hasOverlapId:Ca,getPendingComment:ko,showAddComment:sr,addComment:pl,addHydratedComment:ri,cancelComment:zu,deleteComment:Ss,removePendingComment:vi,cancelImportedTrackedChangeBootstrap:Ts,removeCommentsForDocument:yl,processLoadedDocxComments:Qi,translateCommentsForExport:Yu,handleEditorLocationsUpdate:Jf,clearEditorCommentPositions:Xu,handleTrackedChangeUpdate:Oo,refreshTrackedChangeCommentsByIds:Se,syncResolvedCommentsWithDocument:Jr,syncTrackedChangePositionsWithDocument:Br,setActiveFloatingCommentInstance:Ls,requestInstantSidebarAlignment:Ve,peekInstantSidebarAlignment:_t,clearInstantSidebarAlignment:lt,syncTrackedChangeComments:Gu,decideTrackedChangeFromSidebar:Sl,v2CommentsAdapter:te,setV2CommentsAdapter:ve,getV2CommentsAdapter:we,hydrateCommentsFromV2:gl,applyReviewSnapshotFromV2:Bu,supersedeV2ReviewHydration:Wt,reconcileCommentsFromV2:Xn,isV2EditorActive:Be,replyCommentV2:Is,editCommentV2:Wf,resolveCommentV2:Sa,reopenCommentV2:Es,v2TrackedChangesAdapter:rt,setV2TrackedChangesAdapter:Et,getV2TrackedChangesAdapter:Ut,getV2TrackedChangeRowCount:Di,hydrateTrackedChangesFromV2:Qf,reconcileTrackedChangeMutationFromV2:Ms,reconcileTrackedChangesFromV2:Pi,remapTrackedChangeIdentities:Zf}});var kk='<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>',Sk='<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>',i7='<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>',s7='<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>',u0='<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>',_k='<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>',Ak='<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>',Ik='<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:kk,caretDown:Sk,internal:i7,external:s7,markDone:u0,acceptChange:u0,rejectChange:_k,overflow:Ak,reopen:Ik};var a7=.38,l7=".superdoc-comment-highlight",c7=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},u7=e=>e?e.split(",").map(t=>t.trim()).filter(Boolean):[],d7=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 f7=()=>Math.round(window.innerHeight*a7),Ek=(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},h7=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(l7);for(const o of r){const i=new Set([...u7(o.getAttribute("data-comment-ids")),...d7(o.getAttribute("data-comment-imported-ids"))]);if(![...t].some(a=>i.has(a))||!c7(o))continue;const s=o.getBoundingClientRect().top;Number.isFinite(s)&&(n=n==null?s:Math.min(n,s))}return n},p7=(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)};Mt();const m7="Arial, Helvetica, sans-serif";function d0(){const e=ur();return{uiFontFamily:_e(()=>{const t=e?.proxy?.$superdoc?.config?.uiDisplayFallbackFont;return typeof t=="string"&&t.trim()?t.trim():m7})}}var yn,Cn=Ir((()=>{yn=(e,t)=>{const n=e.__vccOpts||e;for(const[r,o]of t)n[r]=o;return n}}));Mt(),Cn();var g7={class:"comments-dropdown"},v7=["onClick"],y7={key:0,class:"comments-dropdown__option-icon"},b7=["innerHTML"],w7={class:"comments-dropdown__option-label"},C7={__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=_e(()=>({...n.contentStyle,position:"fixed",top:a.value.top,left:a.value.left,zIndex:1200})),u=w=>{n.disabled&&w||(o.value=w)},c=()=>{n.disabled||u(!o.value)},d=()=>{o.value&&u(!1)},h=()=>{if(!i.value)return;const w=i.value.getBoundingClientRect(),x=s.value?.offsetWidth??0,P=window.innerWidth||document.documentElement.clientWidth||0,N=8;let G=w.left;const R=Math.max(N,P-x-N);G=Math.min(Math.max(N,G),R),a.value={top:`${w.bottom+4}px`,left:`${G}px`}},g=w=>{w.stopPropagation(),c()},p=w=>{w?.disabled||(r("select",w?.key,w),d())},v=w=>!!w?.iconString||!!w?.icon,k=w=>w?.iconString?w.iconString:typeof w?.icon=="function"?w.icon(w):w?.icon||null,C=Bl({name:"CommentsDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(w){return()=>k(w.option)}}),_=w=>{if(!o.value)return;const x=w.target;if(!(x instanceof Element))return;const P=i.value?.contains(x),N=s.value?.contains(x);P||N||d()},y=w=>{w.key==="Escape"&&d()};return zt(o,async w=>{w&&(await It(),h())}),zt(o,w=>{w?(document.addEventListener("pointerdown",_,!0),document.addEventListener("keydown",y,!0),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0)):(document.removeEventListener("pointerdown",_,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0))}),cr(()=>{document.removeEventListener("pointerdown",_,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0)}),(w,x)=>(ge(),Ie("div",g7,[Oe("div",{ref_key:"triggerRef",ref:i,class:"comments-dropdown__trigger",onClick:g},[Rd(w.$slots,"default",{},void 0,!0)],512),(ge(),vn(Ua,{to:"body"},[o.value?(ge(),Ie("div",{key:0,ref_key:"menuRef",ref:s,class:"comments-dropdown__menu",style:Sn(l.value)},[(ge(!0),Ie(Jt,null,lr(e.options,P=>(ge(),Ie("div",{key:P.key,class:an(["comments-dropdown__option",{"sd-disabled":P.disabled}]),onClick:N=>p(P)},[v(P)?(ge(),Ie("span",y7,[P.iconString?(ge(),Ie("span",{key:0,innerHTML:P.iconString},null,8,b7)):(ge(),vn($e(C),{key:1,option:P},null,8,["option"]))])):mt("",!0),Oe("span",w7,qt(P.label),1)],10,v7))),128))],4)):mt("",!0)]))]))}},Tk=yn(C7,[["__scopeId","data-v-7eced80a"]]);Mt(),Cn();var k7={class:"sd-comment-option"},S7=["innerHTML"],_7={class:"sd-option-state"},A7=["innerHTML"],I7={__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}=d0(),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=_e(()=>i.find(d=>d.key===u.value)?.label),a=_e(()=>{if(!r.state)return{};const d=i.find(g=>g.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(g=>g.key===d)?.iconString,!h&&n("select",d)},u=ne(r.state),c=ne(null);return zt(()=>r.state,d=>{l(d)}),Un(()=>{l(r.state,!0)}),(d,h)=>(ge(),Ie("div",{class:"sd-internal-dropdown",style:Sn(a.value),"data-sd-part":"dropdown-trigger"},[Zt(Tk,{options:i,onSelect:h[0]||(h[0]=g=>l(g)),disabled:e.isDisabled,"content-style":{fontFamily:$e(o)}},{default:Ro(()=>[Oe("div",k7,[Oe("div",{class:"sd-active-icon",innerHTML:c.value},null,8,S7),Oe("div",_7,qt(s.value),1),Oe("div",{class:"sd-dropdown-caret",innerHTML:$e(ua).caretDown},null,8,A7)])]),_:1},8,["disabled","content-style"])],4))}},xk=yn(I7,[["__scopeId","data-v-138d641e"]]);function E7(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 ao=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 gr=Object.freeze({EDITOR:"editor",SUGGESTER:"suggester",VIEWER:"viewer"}),T7=Object.freeze({[ao.RESOLVE_OWN]:{internal:[gr.EDITOR],external:[gr.EDITOR]},[ao.RESOLVE_OTHER]:{internal:[gr.EDITOR],external:[gr.EDITOR]},[ao.REJECT_OWN]:{internal:[gr.EDITOR,gr.SUGGESTER],external:[gr.EDITOR,gr.SUGGESTER]},[ao.REJECT_OTHER]:{internal:[gr.EDITOR],external:[gr.EDITOR]},[ao.COMMENTS_OVERFLOW_OWN]:{internal:[gr.EDITOR,gr.SUGGESTER],external:[gr.EDITOR,gr.SUGGESTER]},[ao.COMMENTS_OVERFLOW_OTHER]:{internal:[gr.EDITOR],external:[gr.EDITOR]},[ao.COMMENTS_DELETE_OWN]:{internal:[gr.EDITOR,gr.SUGGESTER],external:[gr.EDITOR,gr.SUGGESTER]},[ao.COMMENTS_DELETE_OTHER]:{internal:[gr.EDITOR],external:[gr.EDITOR]},[ao.UPLOAD_VERSION]:{internal:[gr.EDITOR],external:[]},[ao.VERSION_HISTORY]:{internal:[gr.EDITOR],external:[]}}),x7=(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},R7=(e,t,n)=>{const r=n?"internal":"external";return T7[e]?.[r]?.includes(t)??!1};const da=(e,t,n,r={})=>{const o=R7(e,t,n),i=x7(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};Mt(),Cn();var M7={class:"user-container"},L7=["src"],P7={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)=>(ge(),Ie("div",M7,[e.user.image?(ge(),Ie("img",{key:0,class:"user-bg",src:e.user.image.startsWith("http")?e.user.image:`data:image/png;base64,${e.user.image}`},null,8,L7)):(ge(),Ie("span",P7,qt(t(e.user.name,e.user.email)),1))]))}},Rk=yn(D7,[["__scopeId","data-v-c95b2073"]]);Mt(),Cn();var O7={class:"card-section comment-header"},F7={class:"comment-header-left"},N7={class:"user-info"},B7={class:"user-name"},z7={key:0,class:"imported-tag"},V7={key:0,class:"user-timestamp"},H7=["data-disabled-reason","aria-disabled","innerHTML"],U7=["data-disabled-reason","aria-disabled","innerHTML"],j7=["data-disabled-reason","aria-disabled","innerHTML"],G7={class:"overflow-menu__icon"},W7=["innerHTML"],K7={__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}=ur(),s=i.$superdoc.config.role,a=i.$superdoc.config.isInternal,l=F=>{const Z=i.$superdoc.config.user,D={id:F?.creatorId,email:F?.creatorEmail};if(rC({current:Z,other:D}))return!0;const B=Xd(Z),T=Xd(D);if(B.hasId||B.hasEmail||T.hasId||T.hasEmail||F?.origin!=null||F?.importedAuthor?.name)return!1;const V=nC(Z?.name),J=nC(F?.creatorName);return!!(V&&J&&V===J)},u=_e(()=>l(o.comment)),c=_e(()=>Op(o.comment)),{uiFontFamily:d}=d0(),h=Object.freeze({edit:{label:"Edit",key:"edit"},delete:{label:"Delete",key:"delete"}}),g=_e(()=>o.config.readOnly!==!0),p=_e(()=>!(!g.value||!o.comment||o.comment.resolvedTime||r.pendingComment||o.isPendingInput)),v=_e(()=>{if(!p.value||!o.comment.trackedChange&&o.config.allowResolve===!1||o.comment.parentCommentId||c.value)return!1;const F={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value||o.comment.trackedChange?da(ao.RESOLVE_OWN,s,a,F):da(ao.RESOLVE_OTHER,s,a,F)}),k=_e(()=>{if(!p.value||!o.comment.trackedChange)return!1;const F={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value||o.comment.trackedChange?da(ao.REJECT_OWN,s,a,F):da(ao.REJECT_OTHER,s,a,F)}),C=_e(()=>{if(!g.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 F={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return u.value?da(ao.RESOLVE_OWN,s,a,F):da(ao.RESOLVE_OTHER,s,a,F)}),_=_e(()=>!(!p.value||o.comment.trackedChange||o.isPendingInput||y.value.length===0)),y=_e(()=>{if(!g.value)return[];if(!p.value)return[];if(o.writeDisabledReason)return[];const F=[],Z=new Set;l(o.comment)&&Z.add("edit");const D=l(o.comment),B={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return(D&&da(ao.COMMENTS_DELETE_OWN,s,a,B)||!D&&da(ao.COMMENTS_DELETE_OTHER,s,a,B))&&Z.add("delete"),Z.forEach(T=>F.push(h[T])),F}),w=()=>{g.value&&(!o.comment?.trackedChange&&o.config.allowResolve===!1||o.resolveDisabledReason||n("resolve"))},x=()=>{g.value&&(o.rejectDisabledReason||n("reject"))},P=()=>{!g.value||o.config.allowResolve===!1||o.reopenDisabledReason||n("reopen")},N=F=>{g.value&&n("overflow-select",F)},G=_e(()=>!(!(o.comment.origin!=null||o.comment.importedAuthor?.name)||l(o.comment))),R=_e(()=>{if(o.isPendingInput)return i.$superdoc.config.user;const F=o.comment.getCommentUser();if(F?.name){const Z=F.name.replace(/\s*\(imported\)\s*/gi,"").trim();if(Z)return{...F,name:Z}}return F});return(F,Z)=>(ge(),Ie("div",O7,[Oe("div",F7,[Zt(Rk,{user:R.value,class:"avatar"},null,8,["user"]),Oe("div",N7,[Oe("div",B7,[Fi(qt(R.value.name),1),G.value?(ge(),Ie("span",z7,"IMPORTED")):mt("",!0)]),o.comment.createdTime?(ge(),Ie("div",V7,qt($e(E7)(o.comment.createdTime)),1)):mt("",!0)])]),Oe("div",{class:an(["overflow-menu",{"is-visible":o.isActive}])},[v.value?(ge(),Ie("div",{key:0,class:an(["overflow-menu__icon",{"sd-is-disabled":!!e.resolveDisabledReason}]),"data-comment-action":"resolve","data-disabled-reason":e.resolveDisabledReason||null,"aria-disabled":!!e.resolveDisabledReason,innerHTML:$e(ua).markDone,onClick:sn(w,["stop","prevent"])},null,10,H7)):mt("",!0),k.value?(ge(),Ie("div",{key:1,class:an(["overflow-menu__icon",{"sd-is-disabled":!!e.rejectDisabledReason}]),"data-comment-action":"reject","data-disabled-reason":e.rejectDisabledReason||null,"aria-disabled":!!e.rejectDisabledReason,innerHTML:$e(ua).rejectChange,onClick:sn(x,["stop","prevent"])},null,10,U7)):mt("",!0),C.value?(ge(),Ie("div",{key:2,class:an(["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:$e(ua).reopen,onClick:sn(P,["stop","prevent"])},null,10,j7)):mt("",!0),_.value?(ge(),vn(Tk,{key:3,"data-comment-action":"overflow",options:y.value,onSelect:N,"content-style":{fontFamily:$e(d)}},{default:Ro(()=>[Oe("div",G7,[Oe("div",{class:"overflow-icon",innerHTML:$e(ua).overflow},null,8,W7)])]),_:1},8,["options","content-style"])):mt("",!0)],2)]))}},f0=yn(K7,[["__scopeId","data-v-ca6050aa"]]);Mt(),Cn();var q7={class:"input-section"},h0=28,Mk=132,Y7={__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=`${h0}px`;const v=p.scrollHeight||h0,k=Math.min(Math.max(v,h0),Mk);p.style.height=`${k}px`,p.style.overflowY=v>Mk?"auto":"hidden"},u=()=>{It(l)},c=p=>String(p??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),d=p=>{const v=String(p??"");if(!v||v==="<p></p>")return"";if(typeof document>"u")return v.replace(/<br\s*\/?>/gi,`
|
|
13
13
|
`).replace(/<[^>]+>/g,"");const k=document.createElement("div");return k.innerHTML=v,k.innerText||k.textContent||""},h=p=>{const v=String(p??"").replace(/\r\n/g,`
|
|
14
|
-
`).trim();return v?v.split(/\n{2,}/).map(k=>`<p>${c(k).replace(/\n/g,"<br>")}</p>`).join(""):"<p></p>"},g=_e({get:()=>d(o.value),set:p=>{o.value=h(p)}});return Un(u),zt(o,u),t({focus:a}),(p,v)=>(ge(),Ie("div",q7,[e.includeHeader?(ge(),vn(f0,{key:0,config:e.config,comment:e.comment,"is-pending-input":!0},null,8,["config","comment"])):mt("",!0),Oe("div",{class:an(["comment-entry",{"sd-input-active":e.isFocused}])},[Ws(Oe("textarea",{ref_key:"inputRef",ref:i,class:"superdoc-field",placeholder:"Add a comment","onUpdate:modelValue":v[0]||(v[0]=k=>g.value=k),rows:"1",onInput:l,onFocus:v[1]||(v[1]=k=>s(!0)),onBlur:v[2]||(v[2]=k=>s(!1))},null,544),[[Ei,g.value]])],2)]))}},p0=yn(Y7,[["__scopeId","data-v-cc54b489"]]);Mt(),Cn();var X7=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Z7={key:0,class:"existing-internal-input"},Q7={class:"new-comment-input-wrapper"},J7={class:"reply-actions"},$7=["disabled"],eR={key:0,class:"resolved-badge"},tR=["innerHTML"],nR={key:1,class:"existing-internal-input"},rR={key:0,class:"card-section comment-body"},oR=["data-track-change-semantic-color-key"],iR={key:0},sR={class:"change-type tracked-change-label"},aR={key:0,class:"tracked-change-detail-lines"},lR={key:0,class:"tracked-change-text"},cR={key:1,class:"change-type"},uR={class:"change-type"},dR={key:1},fR={class:"tracked-change-text is-inserted"},hR={key:2},pR={class:"tracked-change-text is-inserted"},mR={key:3},gR={key:4},vR={key:5},yR={key:6},bR={class:"tracked-change-text"},wR={key:7},CR={class:"tracked-change-text is-deleted"},kR={class:"tracked-change-text is-inserted"},SR={key:8},_R={class:"tracked-change-text is-deleted"},AR={key:9},IR={class:"tracked-change-text is-inserted"},ER=["data-track-change-image-preview-role"],TR=["src","alt"],xR={key:1,class:"card-section comment-body"},RR=["innerHTML"],MR={key:1,class:"comment"},LR={key:2,class:"reply-expanded"},PR={class:"reply-input-wrapper"},DR={class:"reply-actions"},OR=["onClick"],FR=["onClick","disabled","data-disabled-reason"],NR={class:"collapsed-avatars"},BR={key:3,class:"comment-separator"},zR={key:2,class:"tracked-change-decision-alert",role:"alert"},VR={class:"tracked-change-decision-alert__message"},HR=["disabled","data-disabled-reason"],UR={key:1,class:"reply-expanded"},jR={class:"reply-input-wrapper"},GR={class:"reply-actions"},WR=["disabled","data-disabled-reason"],Fp=3,Lk=90,KR={__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}=ur(),i=vu(),s=ca(),{addComment:a,cancelComment:l,deleteComment:u,getCommentAliasIds:c,removePendingComment:d,getCommentDocumentId:h,requestInstantSidebarAlignment:g,resolveCommentPositionEntry:p,clearInstantSidebarAlignment:v,setActiveFloatingCommentInstance:k}=s,{suppressInternalExternal:C,getConfig:_,activeComment:y,activeFloatingCommentInstanceId:w,floatingCommentsOffset:x,pendingComment:P,currentCommentText:N,isDebugging:G,editingCommentId:R,editorCommentPositions:F,isCommentHighlighted:Z}=ea(s),D=ne(!0),B=ne(null),T=ne(new Map),V=ne(null),J=[[0,0],[-Fp,0],[Fp,0],[0,-Fp],[0,Fp]],q=Se=>{const Ve=typeof Se?.width=="number"&&Number.isFinite(Se.width)?Se.width:null,_t=typeof Se?.height=="number"&&Number.isFinite(Se.height)?Se.height:null;if(!Ve||!_t||Ve<=0||_t<=0)return{};const lt=Math.min(Lk/Ve,Lk/_t,1);return{width:`${Math.max(1,Math.round(Ve*lt))}px`,height:`${Math.max(1,Math.round(_t*lt))}px`}},se=[".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(","),pe=Se=>Ve=>{Se&&(Ve?(T.value.set(Se,Ve),R.value===Se&&It(()=>{ye(Se)})):T.value.delete(Se))},Ne=(Se,Ve,_t)=>{const lt=Se?.getBoundingClientRect?.();return!lt||![lt.left,lt.top,lt.right,lt.bottom].every(Number.isFinite)||lt.width<=0||lt.height<=0?!1:J.some(([Ln,Bn])=>{const sr=Ve+Ln,Sr=_t+Bn;return sr>=lt.left&&sr<=lt.right&&Sr>=lt.top&&Sr<=lt.bottom})},he=(Se,Ve)=>{if(!Number.isFinite(Se)||!Number.isFinite(Ve))return null;const _t=document.querySelectorAll(se);for(const lt of _t)if(lt instanceof HTMLElement&&Ne(lt,Se,Ve))return lt;return null},ye=Se=>{T.value.get(Se)?.focus?.()},ce=ne(null),ke=Se=>Se.resolvedTime?Se.commentId:Se.importedId||Se.commentId,ie=Se=>Se?Se.trackedChange&&Se.importedId!=null?String(Se.importedId):Se.commentId!=null?String(Se.commentId):null:null,xe=(Se,Ve)=>{const _t=Se?.bounds?.[Ve];return Number.isFinite(_t)?_t:null},Je=(Se,Ve)=>{if(!Se||!Ve||Se.pageIndex!==Ve.pageIndex)return!1;const _t=xe(Se,"top"),lt=xe(Ve,"top");return _t!=null&<!=null&&Math.abs(_t-lt)<.5},st=(Se,Ve)=>{const _t=xe(Se,"left"),lt=xe(Ve,"left"),Ln=xe(Se,"right"),Bn=xe(Ve,"right");return[_t,lt,Ln,Bn].some(sr=>sr==null)?!1:lt<Ln&&_t<Bn},Tt=(Se,Ve)=>{const _t=Se?.start,lt=Se?.end,Ln=Ve?.start,Bn=Ve?.end;return[_t,lt,Ln,Bn].every(Number.isFinite)?Ln<=lt&&_t<=Bn:!1},Te=(Se,Ve)=>!Se||!Ve||Se.kind&&Ve.kind&&Se.kind!==Ve.kind||Se.storyKey&&Ve.storyKey&&Se.storyKey!==Ve.storyKey?!1:Ve.start===Se.start&&Ve.end===Se.end?!0:Je(Se,Ve)&&st(Se,Ve)&&Tt(Se,Ve),je=Se=>{const Ve=new Set(c(Se)),{key:_t,entry:lt}=p(Se);return _t&&Ve.add(_t),lt?(Object.entries(F.value??{}).forEach(([Ln,Bn])=>{Te(lt,Bn)&&Ve.add(Ln)}),[...Ve]):[...Ve]},Ye=(Se,Ve,_t=24)=>{if(!Number.isFinite(Ve)||typeof Se?.getBoundingClientRect!="function")return!1;const lt=Se.getBoundingClientRect().top;return Number.isFinite(lt)&&Math.abs(lt-Ve)<=_t},$=_e(()=>r.floatingInstanceId??r.comment.commentId??null),S=_e(()=>typeof r.isFloatingInstanceActive=="boolean"?r.isFloatingInstanceActive:y.value!==r.comment.commentId?!1:r.floatingInstanceId==null?!0:w.value===r.floatingInstanceId),ee=_e(()=>r.comment.resolvedTime?r.comment.trackedChange?r.comment.trackedChangeDecision==="reject"?"Rejected":"Accepted":"Resolved":null),O=_e(()=>P.value&&P.value.commentId===r.comment.commentId),j=_e(()=>Se=>{const Ve=et.value;return U.value&&Se===Ve.length-1?!0:Ve.length>1&&Se!==Ve.length-1}),U=_e(()=>!_.readOnly&&S.value&&!r.comment.resolvedTime&&!Mn.value),W=()=>({ok:!1,reason:"read-only-document"}),te=()=>_.value?.readOnly===!0,Y=ne(!1),X=ne(!1),be=()=>{if(te())return W();if(Nn.value)return{ok:!1,reason:kn.value?.reason??"v2-write-unavailable"};Y.value=!0,It(()=>{B.value?.focus?.(),n("resize")})},ve=_e(()=>{const Se=r.comment;return Se.trackedChange?s.getTrackedChangeThread(Se):s.commentsList.filter(Ve=>{const _t=Ve.parentCommentId===Se.commentId,lt=Ve.commentId===Se.commentId;return _t||lt}).sort((Ve,_t)=>Ve.commentId===Se.commentId?-1:_t.commentId===Se.commentId?1:Ve.createdTime-_t.createdTime)}),we=ne(!1),Be=ne(null),rt=ne(!1),at=_e(()=>!we.value),Ct=_e(()=>({"is-truncated":at.value,"is-scrollable":we.value&&rt.value})),en=()=>{we.value=!we.value,It(()=>n("resize"))},Et=Se=>{Be.value=Se??null},Ut=()=>{if(we.value)return;const Se=Be.value;if(!Se){rt.value=!1;return}rt.value=Se.scrollHeight>Se.clientHeight+1};zt(Be,()=>{It(Ut)});const Wt=()=>R.value?ve.value.some(Se=>Se.commentId===R.value):!1;zt(S,Se=>{Se||((Y.value||Wt())&&(N.value="",R.value=null),we.value=!1,In.value=!1,Y.value=!1,It(()=>n("resize")))});const In=ne(!1),bt=_e(()=>ve.value.slice(1)),nn=_e(()=>In.value?!1:bt.value.length>=2),et=_e(()=>nn.value?[ve.value[0],bt.value[bt.value.length-1]].filter(Boolean):ve.value);zt(_e(()=>{const Se=et.value[0];return Se?JSON.stringify({commentId:Se.commentId,commentText:Se.commentText,trackedChange:Se.trackedChange,trackedChangeText:Se.trackedChangeText,deletedText:Se.deletedText,trackedChangeLabel:Se.trackedChangeLabel,trackedChangeDisplayType:Se.trackedChangeDisplayType,trackedChangeDetailLines:Se.trackedChangeDetailLines}):""}),()=>{It(Ut)});const Pt=_e(()=>nn.value?bt.value.length-1:0),Kt=_e(()=>{if(!nn.value)return[];const Se=bt.value.slice(0,-1),Ve=new Set;return Se.map(_t=>typeof _t.getCommentUser=="function"?_t.getCommentUser():{name:_t.creatorName,email:_t.creatorEmail||_t.email}).filter(_t=>{if(!_t)return!1;const lt=_t.email||_t.name;return Ve.has(lt)?!1:(Ve.add(lt),!0)}).slice(0,3)}),Rn=()=>{In.value=!0,We(),It(()=>n("resize"))},Nt=_e(()=>r.comment.resolvedTime?!0:_.value.readOnly),un=_e(()=>Se=>S.value&&R.value===Se.commentId),Mn=_e(()=>!R.value||!S.value?!1:ve.value.some(Se=>Se.commentId===R.value)),Pe=_e(()=>_.value.readOnly||!o.$superdoc.config.isInternal||yt.value?!1:!C.value&&!r.comment.trackedChange),Ge=_e(()=>N.value&&N.value!=="<p></p>"),We=async()=>{const Se=o.$superdoc.activeEditor,Ve=Se?.editorVersion===2?Se?.v2Comments??null:null,_t=!!r.comment?.trackedChange,lt=f7(),Ln=r.floatingInstanceId!=null,Bn=ce.value?.getBoundingClientRect?.().top,sr=!r.comment.resolvedTime&&(y.value!==r.comment.commentId||Ln&&$.value!==w.value);let Sr=lt;if(Ve){const wo=!_t&&!r.comment.resolvedTime&&String(r.comment?.trackedChangeParentId??"").trim()?r.comment.trackedChangeParentId:null,Co=Se?.editorVersion===2&&(_t||wo!=null)?Se?.v2TrackedChanges??null:null,mi=wo!=null?s.getComment(wo):null,co=_t?r.comment:mi?.trackedChange?mi:wo;let pr=await(Co?Co.focusTrackedChange(co):Ve.focusComment(r.comment));return!_t&&pr?.reason==="tracked-change-anchor-not-found"&&(pr=await Ve.focusComment(r.comment)),pr?.ok?(r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId)),sr&&!Ln?g(lt,r.comment.commentId,r.floatingInstanceId??null):sr&&Number.isFinite(Bn)?g(Bn,r.comment.commentId,r.floatingInstanceId):v(),pr):(v(),pr)}if(Se){const{entry:wo}=p(r.comment),Co=r.floatingPositionEntry??wo,mi=Number.isFinite(r.floatingPageIndex)&&r.comment?.trackedChangeStory?.storyType==="headerFooterPart",co=Ek(r.parent,Co),pr=mi?null:h7(je(r.comment)),hl=Number.isFinite(pr)?pr:co,Ca=Ye(ce.value,hl),gi=ke(r.comment),zr=null;let ni=null;if(_t)if(r.comment.trackedChangeStory&&(r.comment.trackedChangeStory,{...Number.isFinite(r.floatingPageIndex)?{pageIndex:r.floatingPageIndex}:{}}),r.comment.resolvedTime)Se.commands?.setCursorById(gi);else{const ko=r.comment.commentId;Se.commands?.setCursorById(gi,{activeCommentId:ko})||Se.commands?.setActiveComment({commentId:ko})}else{if(r.comment.resolvedTime)Se.commands?.setCursorById(gi);else{const Mi=r.comment.commentId;Se.commands?.setCursorById(gi,{activeCommentId:Mi})||Se.commands?.setActiveComment({commentId:Mi})}const ko=r.comment.commentId;ni=Ca?null:p7(zr,gi,ko,lt)}Number.isFinite(pr)?Sr=pr:Number.isFinite(co)?Sr=co:Number.isFinite(ni)&&(Sr=ni)}sr&&!Ln?r.floatingInstanceId?g(Sr,r.comment.commentId,r.floatingInstanceId):g(Sr,r.comment.commentId):v(),r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId))},ft=Se=>{const Ve=Se.target instanceof Element?Se.target:Se.target?.parentElement,_t=document.elementFromPoint(Se.clientX,Se.clientY);if(!(Ve?.closest?.(se)||_t?.closest?.(se)||he(Se.clientX,Se.clientY)||Z.value)&&!(Se.target.closest?.(".comments-dialog")&&!ce.value?.contains(Se.target))){if(O.value){l(o.$superdoc);return}S.value&&(x.value=0,n("dialog-exit"),y.value=null,s.setActiveComment(o.$superdoc,y.value),Z.value=!1)}},Vt=async()=>{if(te())return W();if(Nn.value)return{ok:!1,reason:kn.value?.reason??"v2-write-unavailable"};if(yt.value&&$t.value&&!O.value){if(X.value)return{ok:!1,reason:"reply-submit-in-flight"};X.value=!0;try{const _t=await s.replyCommentV2({superdoc:o.$superdoc,parentCommentId:ie(r.comment),text:N.value});return _t?.ok?(Y.value=!1,N.value="",It(()=>n("resize")),_t):(It(()=>n("resize")),_t)}finally{X.value=!1}}const Se={documentId:r.comment.fileId,isInternal:P.value?P.value.isInternal:D.value,parentCommentId:P.value?null:r.comment.commentId};P.value&&(Se.selection=P.value.selection.getValues());const Ve=s.getPendingComment(Se);!P.value&&N.value&&Ve.setText({text:N.value,suppressUpdate:!0}),Promise.resolve(a({superdoc:o.$superdoc,comment:Ve})).finally(()=>{Y.value=!1,It(()=>n("resize"))})},yt=_e(()=>o.$superdoc?.activeEditor?.editorVersion===2),$t=_e(()=>yt.value?o.$superdoc?.activeEditor?.v2Comments??null:null),At=_e(()=>yt.value?o.$superdoc?.activeEditor?.v2TrackedChanges??null:null),kn=_e(()=>{if(!$t.value)return null;const Se=s.viewingVisibility.documentMode,Ve=$t.value.getCapabilityState?.()??null;return Se==="viewing"?{...Ve??{},canWrite:!1,reason:"review-surface-read-only"}:Ve}),Nn=_e(()=>{if(!yt.value)return!1;const Se=kn.value;return Se?Se.canWrite===!1:!1}),Uo=_e(()=>X.value?"reply-submit-in-flight":Nn.value?kn.value?.reason??"v2-write-unavailable":null),Ht=_e(()=>{if(!At.value)return null;const Se=s.viewingVisibility.documentMode,Ve=At.value.getCapabilityState?.()??null;return Se==="viewing"&&Ve?.canDecide!==!1?{canDecide:!1,reason:"review-surface-read-only"}:Ve}),Pn=Se=>{if(yt.value&&Se?.trackedChange){if(!At.value)return"v2-tracked-change-adapter-missing";const Ve=Ht.value;return Ve&&Ve.canDecide===!1?Ve.reason??"v2-tracked-change-unavailable":null}return Nn.value?kn.value?.reason??"v2-write-unavailable":null},br=Se=>{if(yt.value&&Se?.trackedChange){if(!At.value)return"v2-tracked-change-adapter-missing";const Ve=Ht.value;return Ve&&Ve.canDecide===!1?Ve.reason??"v2-tracked-change-unavailable":null}return Nn.value?kn.value?.reason??"v2-write-unavailable":null},Do=()=>yt.value?$t.value?_.value?.readOnly?"read-only-document":Nn.value?kn.value?.reason??"v2-write-unavailable":null:"v2-comments-adapter-missing":null,er=_e(()=>!yt.value||!Nn.value?null:kn.value?.reason??"v2-write-unavailable"),cn=(Se,Ve)=>{V.value={decision:Se,reason:Ve?.reason??null},It(()=>n("resize"))},Gn=()=>{V.value&&(V.value=null,It(()=>n("resize")))},Br=_e(()=>{const Se=V.value;if(!Se)return null;const Ve=Se.decision==="reject"?"reject":"accept";return Se.reason==="stale-catalog"?`Couldn't ${Ve} this change because the review list is stale.`:`Couldn't ${Ve} this change.`}),ei=()=>{const Se=V.value;if(Se){if(V.value=null,Se.decision==="reject"){bo();return}Jr()}},bo=async()=>{if(te())return W();const Se=o.$superdoc.config.onTrackedChangeBubbleReject;if(r.comment.trackedChange){if(yt.value){const _t=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});if(!_t?.ok||_t.success===!1){cn("reject",_t);return}Gn(),typeof Se=="function"&&Se(r.comment,o.$superdoc.activeEditor),It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Ve=!0;if(typeof Se=="function")Se(r.comment,o.$superdoc.activeEditor);else{const _t=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});Ve=!!_t?.ok&&_t.success!==!1}Ve&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"reject"})}else if(yt.value&&$t.value){if(!(await s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId});It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Jr=async()=>{if(te())return W();if(!r.comment.trackedChange&&_.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};const Se=o.$superdoc.config.onTrackedChangeBubbleAccept;if(r.comment.trackedChange&&yt.value){const _t=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});if(!_t?.ok||_t.success===!1){cn("accept",_t);return}Gn(),typeof Se=="function"&&Se(r.comment,o.$superdoc.activeEditor),It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Ve=!0;if(r.comment.trackedChange&&typeof Se=="function")Se(r.comment,o.$superdoc.activeEditor);else if(r.comment.trackedChange){const _t=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});Ve=!!_t?.ok&&_t.success!==!1}else if(yt.value&&$t.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&&!yt.value&&Ve&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"accept"}),It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Xi=async()=>{if(te())return W();if(_.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};!yt.value||!$t.value||(await s.reopenCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok&&It(()=>{s.lastUpdate=new Date,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Ri=(Se,Ve)=>{if(te())return W();switch(Se){case"edit":N.value=Ve?.commentText?.value??Ve?.commentText??"",y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId),R.value=Ve.commentId,s.setActiveComment(o.$superdoc,y.value),It(()=>{ye(Ve.commentId)});break;case"delete":u({superdoc:o.$superdoc,commentId:Ve.commentId});break}},ba=async Se=>{if(te())return W();if(yt.value&&$t.value){const Ve=await s.editCommentV2({superdoc:o.$superdoc,commentId:Se.commentId,text:N.value});return Ve?.ok&&(R.value=null,d(o.$superdoc)),Ve}R.value=null,Se.setText({text:N.value,superdoc:o.$superdoc}),d(o.$superdoc)},ti=Se=>{if(te())return W();const Ve=!!P.value,_t=Se.toLowerCase()==="internal";Ve?P.value.isInternal=_t:r.comment.setIsInternal({isInternal:_t,superdoc:o.$superdoc})},wa=_e(()=>{const Se={};return(S.value||O.value||Mn.value)&&(Se.zIndex=50),Se}),uc=Se=>typeof Se=="string"?new Date(Se).getTime():Se,Oo=Se=>{R.value=null,Y.value=!1,l(o.$superdoc)},jo=_e(()=>{const Se=o.$superdoc.users;return r.comment.isInternal===!0?Se.filter(Ve=>Ve.access?.role==="internal"):Se});return Un(()=>{r.autoFocus&&It(()=>We()),O.value&&It(()=>{B.value?.focus?.()}),It(()=>{n("ready",{commentId:r.floatingInstanceId??(r.comment.importedId!==void 0?r.comment.importedId:r.comment.commentId),elementRef:ce}),Ut()})}),zt(U,Se=>{Se&&It(()=>{B.value?.focus?.()})},{immediate:!0}),zt(R,Se=>{if(!Se||!S.value)return;const Ve=ve.value.find(_t=>_t.commentId===Se);!Ve||Ve.trackedChange||It(()=>{ye(Se)})}),zt(()=>_.value?.readOnly===!0,Se=>{Se&&(Y.value=!1,ve.value.some(Ve=>Ve.commentId===R.value)&&(R.value=null),O.value&&l(o.$superdoc),It(()=>n("resize")))},{immediate:!0}),zt(Nn,Se=>{Se&&(Y.value=!1,It(()=>n("resize")))}),(Se,Ve)=>{const _t=t1("click-outside");return Ws((ge(),Ie("div",{class:an(["comments-dialog",{"is-active":S.value||O.value,"is-resolved":r.comment.resolvedTime}]),onClick:sn(We,["stop","prevent"]),style:Sn(wa.value),ref_key:"commentDialogElement",ref:ce,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:""},[O.value?(ge(),Ie(Jt,{key:0},[Pe.value?(ge(),Ie("div",Z7,[Zt(xk,{onClick:Ve[0]||(Ve[0]=sn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":!1,state:$e(P).isInternal?"internal":"external",onSelect:ti},null,8,["state"])])):mt("",!0),Zt(f0,{config:$e(_),comment:r.comment,"is-pending-input":!0},null,8,["config","comment"]),Oe("div",Q7,[Zt(p0,{ref_key:"commentInput",ref:B,users:jo.value,config:$e(_),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Oe("div",J7,[Oe("button",{class:"sd-button reply-btn-cancel",onClick:sn(Oo,["stop","prevent"])},"Cancel"),Oe("button",{class:an(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ge.value}]),onClick:sn(Vt,["stop","prevent"]),disabled:!Ge.value}," Comment ",10,$7)])],64)):(ge(),Ie(Jt,{key:1},[ee.value?(ge(),Ie("div",eR,[Oe("span",{class:"resolved-badge__icon",innerHTML:$e(ua).markDone},null,8,tR),Fi(" "+qt(ee.value),1)])):mt("",!0),Pe.value?(ge(),Ie("div",nR,[Zt(xk,{onClick:Ve[1]||(Ve[1]=sn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":Nt.value,state:e.comment.isInternal?"internal":"external",onSelect:ti},null,8,["is-disabled","state"])])):mt("",!0),(ge(!0),Ie(Jt,null,lr(et.value,(lt,Ln)=>(ge(),Ie("div",{key:lt.commentId,class:"conversation-item"},[Zt(f0,{config:$e(_),timestamp:uc(lt.createdTime),comment:lt,"is-active":S.value,"resolve-disabled-reason":Pn(lt),"reject-disabled-reason":br(lt),"reopen-supported":yt.value&&!!$t.value,"reopen-disabled-reason":Do(),"write-disabled-reason":er.value,onResolve:Jr,onReject:bo,onReopen:Xi,onOverflowSelect:Bn=>Ri(Bn,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?(ge(),Ie("div",rR,[Oe("div",{class:an(["tracked-change",Ln===0?Ct.value:void 0]),"data-track-change-semantic-color-key":lt.semanticColorKey??void 0,ref_for:!0,ref:Ln===0?Et:void 0},[lt.trackedChangeLabel?(ge(),Ie("div",iR,[Oe("span",sR,qt(lt.trackedChangeLabel),1),lt.trackedChangeDetailLines&<.trackedChangeDetailLines.length?(ge(),Ie("div",aR,[(ge(!0),Ie(Jt,null,lr(lt.trackedChangeDetailLines,(Bn,sr)=>(ge(),Ie("div",{key:sr,class:"tracked-change-detail-line"},[Bn.excerpt?(ge(),Ie("span",lR,'"'+qt(Bn.excerpt)+'"',1)):mt("",!0),Bn.excerpt?(ge(),Ie("span",cR," — ")):mt("",!0),Oe("span",uR,qt(Bn.label),1)]))),128))])):mt("",!0)])):lt.trackedChangeDisplayType==="hyperlinkAdded"?(ge(),Ie("div",dR,[Ve[2]||(Ve[2]=Oe("span",{class:"change-type"},"Added hyperlink ",-1)),Oe("span",fR,'"'+qt(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="hyperlinkModified"?(ge(),Ie("div",hR,[Ve[3]||(Ve[3]=Oe("span",{class:"change-type"},"Changed hyperlink to ",-1)),Oe("span",pR,'"'+qt(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="paragraphSplit"?(ge(),Ie("div",mR,[...Ve[4]||(Ve[4]=[Oe("span",{class:"change-type"},"Added new line",-1)])])):lt.trackedChangeDisplayType==="tableInsert"?(ge(),Ie("div",gR,[...Ve[5]||(Ve[5]=[Oe("span",{class:"change-type"},"Added table",-1)])])):lt.trackedChangeDisplayType==="tableDelete"?(ge(),Ie("div",vR,[...Ve[6]||(Ve[6]=[Oe("span",{class:"change-type"},"Deleted table",-1)])])):lt.trackedChangeType==="trackFormat"?(ge(),Ie("div",yR,[Ve[7]||(Ve[7]=Oe("span",{class:"change-type"},"Format: ",-1)),Oe("span",bR,qt(lt.trackedChangeText),1)])):lt.trackedChangeType==="both"?(ge(),Ie("div",wR,[Ve[8]||(Ve[8]=Oe("span",{class:"change-type"},"Replaced ",-1)),Oe("span",CR,'"'+qt(lt.deletedText)+'"',1),Ve[9]||(Ve[9]=Oe("span",{class:"change-type"}," with ",-1)),Oe("span",kR,'"'+qt(lt.trackedChangeText)+'"',1)])):lt.deletedText?(ge(),Ie("div",SR,[Ve[10]||(Ve[10]=Oe("span",{class:"change-type"},"Deleted ",-1)),Oe("span",_R,'"'+qt(lt.deletedText)+'"',1)])):lt.trackedChangeText?(ge(),Ie("div",AR,[Ve[11]||(Ve[11]=Oe("span",{class:"change-type"},"Added ",-1)),Oe("span",IR,'"'+qt(lt.trackedChangeText)+'"',1)])):mt("",!0),lt.trackedChangeImagePreview?.src?(ge(),Ie("div",{key:10,class:"tracked-change-image-preview","data-track-change-image-preview-role":lt.trackedChangeImagePreview.role??void 0},[Oe("img",{class:"tracked-change-image-preview__image",src:lt.trackedChangeImagePreview.src,alt:lt.trackedChangeImagePreview.alt||"Tracked image preview",style:Sn(q(lt.trackedChangeImagePreview)),loading:"lazy",decoding:"async"},null,12,TR)],8,ER)):mt("",!0)],10,oR),at.value&&rt.value&&Ln===0?(ge(),Ie("div",{key:0,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show more ")):mt("",!0),we.value&&rt.value&&Ln===0?(ge(),Ie("div",{key:1,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show less ")):mt("",!0)])):mt("",!0),lt.trackedChange?mt("",!0):(ge(),Ie("div",xR,[!$e(G)&&!un.value(lt)?(ge(),Ie("div",{key:0,class:an(["comment",Ln===0?Ct.value:void 0]),ref_for:!0,ref:Ln===0?Et:void 0,innerHTML:lt.commentText},null,10,RR)):$e(G)&&!un.value(lt)?(ge(),Ie("div",MR,qt($e(F)[lt.importedId!==void 0?lt.importedId:lt.commentId]?.bounds),1)):(ge(),Ie("div",LR,[Oe("div",PR,[Zt(p0,{ref_for:!0,ref:pe(lt.commentId),users:jo.value,config:$e(_),"include-header":!1,comment:lt},null,8,["users","config","comment"])]),Oe("div",DR,[Oe("button",{class:"sd-button reply-btn-cancel",onClick:sn(Bn=>Oo(lt),["stop","prevent"])},"Cancel",8,OR),Oe("button",{class:an(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ge.value||Nn.value}]),onClick:sn(Bn=>ba(lt),["stop","prevent"]),disabled:!Ge.value||Nn.value,"data-disabled-reason":Nn.value?kn.value?.reason??null:null}," Update ",10,FR)])])),at.value&&rt.value&&Ln===0&&!un.value(lt)?(ge(),Ie("div",{key:3,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show more ")):mt("",!0),we.value&&rt.value&&Ln===0&&!un.value(lt)?(ge(),Ie("div",{key:4,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show less ")):mt("",!0)])),nn.value&&Ln===0?(ge(),Ie(Jt,{key:2},[Ve[12]||(Ve[12]=Oe("div",{class:"comment-separator"},null,-1)),Oe("div",{class:"collapsed-replies",onClick:sn(Rn,["stop","prevent"])},[Oe("div",NR,[(ge(!0),Ie(Jt,null,lr(Kt.value,Bn=>(ge(),vn(Rk,{key:Bn.email||Bn.name,user:Bn,class:"mini-avatar"},null,8,["user"]))),128))]),Oe("span",null,qt(Pt.value)+" more "+qt(Pt.value===1?"reply":"replies"),1)])],64)):mt("",!0),j.value(Ln)?(ge(),Ie("div",BR)):mt("",!0)]))),128)),V.value?(ge(),Ie("div",zR,[Oe("span",VR,qt(Br.value),1),Oe("button",{type:"button",class:"sd-button tracked-change-decision-alert__retry",onClick:sn(ei,["stop","prevent"])}," Retry ")])):mt("",!0),U.value&&!$e(_).readOnly?(ge(),Ie(Jt,{key:3},[Y.value?(ge(),Ie("div",UR,[Oe("div",jR,[Zt(p0,{ref_key:"commentInput",ref:B,users:jo.value,config:$e(_),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Oe("div",GR,[Oe("button",{class:"sd-button reply-btn-cancel",onClick:sn(Oo,["stop","prevent"])},"Cancel"),Oe("button",{class:an(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ge.value||Nn.value||X.value}]),onClick:sn(Vt,["stop","prevent"]),disabled:!Ge.value||Nn.value||X.value,"data-disabled-reason":Uo.value}," Reply ",10,WR)])])):(ge(),Ie("button",{key:0,type:"button",class:an(["reply-pill",{"sd-is-disabled":Nn.value}]),onClick:sn(be,["stop","prevent"]),disabled:Nn.value,"data-disabled-reason":Nn.value?kn.value?.reason??null:null}," Reply or add others with @ ",10,HR))],64)):mt("",!0)],64))],14,X7)),[[_t,ft]])}}},Np=yn(KR,[["__scopeId","data-v-f26decd0"]]);Mt(),Cn();var qR={class:"comments-list"},YR={key:0},XR=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],ZR={key:1},QR="headerFooterPart",JR={__name:"commentsList",props:{showMainComments:{type:Boolean,default:!0},showResolvedComments:{type:Boolean,default:!0}},setup(e){const t=e,n=ca(),r=vg(n,"isCommentsListVisible"),o=_e(()=>n.getGroupedComments),i=_e(()=>n.getFloatingCommentInstances),{activeComment:s,activeFloatingCommentInstanceId:a}=ea(n),l=g=>{const p=i.value.filter(v=>v?.comment?.commentId===g?.commentId);return p.length<2?[]:g?.trackedChange?g?.trackedChangeStory?.storyType!==QR?[]:p:[]},u=g=>!g?.comment?.commentId||s.value!==g.comment.commentId?!1:a.value==null?g.isPrimary===!0:String(a.value)===String(g.id),c=g=>{const p=l(g);return p.length?p.map(v=>({id:v.id,comment:g,floatingInstanceId:String(v.id),floatingPageIndex:v.pageIndex,floatingPositionEntry:v.positionEntry??null,isFloatingInstanceActive:u(v)})):[{id:g.commentId,comment:g,floatingInstanceId:null,floatingPageIndex:null,floatingPositionEntry:null,isFloatingInstanceActive:void 0}]},d=_e(()=>o.value.parentComments.flatMap(g=>c(g))),h=_e(()=>t.showResolvedComments&&o.value?.resolvedComments?.length>0);return Un(()=>{r.value=!0}),cr(()=>{r.value=!1}),(g,p)=>(ge(),Ie("div",qR,[e.showMainComments?(ge(),Ie("div",YR,[(ge(!0),Ie(Jt,null,lr(d.value,v=>(ge(),Ie("div",{key:v.id,class:"comment-item","data-comment-instance-id":v.floatingInstanceId??"","data-comment-thread-id":v.comment.commentId??"","data-comment-position-key":v.comment.trackedChangeAnchorKey??"","data-comment-page-index":Number.isFinite(v.floatingPageIndex)?v.floatingPageIndex:""},[Zt(Np,{comment:v.comment,"floating-instance-id":v.floatingInstanceId,"floating-page-index":v.floatingPageIndex,"floating-position-entry":v.floatingPositionEntry,"is-floating-instance-active":v.isFloatingInstanceActive},null,8,["comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])],8,XR))),128))])):mt("",!0),h.value?(ge(),Ie("div",ZR,[p[0]||(p[0]=Oe("div",{class:"comment-title"},"Resolved",-1)),(ge(!0),Ie(Jt,null,lr(o.value.resolvedComments,v=>(ge(),Ie("div",{key:v.commentId,class:"comment-item"},[Zt(Np,{comment:v},null,8,["comment"])]))),128))])):mt("",!0)]))}},$R=yn(JR,[["__scopeId","data-v-e89dbc33"]]);Mt();var e9=class extends Qm.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=Kl($R);const e=this.superdoc?.app?._context?.provides;e&&this.app?._context?.provides&&Object.setPrototypeOf(this.app._context.provides,e),this.superdoc?.pinia&&(Zd(this.superdoc.pinia),this.app.use(this.superdoc.pinia),this.app.config.globalProperties.$pinia=this.superdoc.pinia),this.app.directive("click-outside",ey),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()}},t9,el,m0=Ir((()=>{t9=2,el=96/72}));Mt(),m0();var n9=96,r9=".superdoc__right-sidebar",o9=".sd-pdf-viewer-page";const g0=Object.freeze({min:10,max:100,padding:0}),Pk=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,g0.min),o=n(t.max,g0.max),i=typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding>=0?t.padding:g0.padding;return{min:Math.min(r,o),max:Math.max(r,o),padding:i}},Dk=(e,t)=>!(e>0)||!(t>0)?null:Math.round(e/t*100),i9=(e,t,n)=>{const r=Dk(e-n.padding,t);return r===null?null:Math.max(1,Math.round(Math.min(n.max,Math.max(n.min,r))))},s9=(e,t,n)=>e>0?Number.isFinite(t)&&t>0?e/t*el:n>0?e/n:e:null;function a9({getSuperdoc:e,superdocContainerWidth:t,isReady:n,activeZoom:r,zoomMode:o,viewportMetrics:i,showCommentsSidebar:s,rightSidebarRef:a,superdocRoot:l,documents:u}){const c=w=>{if(!w)return null;let x=0;try{const G=w.getPages?.();if(Array.isArray(G))for(const R of G){const F=R?.size?.w;typeof F=="number"&&Number.isFinite(F)&&F>x&&(x=F)}}catch{x=0}if(x>0)return x;let P=null;try{P=w.getPageStyles?.()??null}catch{P=null}const N=P?.pageSize?.width;return typeof N=="number"&&Number.isFinite(N)&&N>0?N*n9:null},d=()=>{if(!(u?.value??[]).some(P=>P?.type==="application/pdf"))return null;const w=l.value;if(!w?.querySelectorAll)return null;let x=0;for(const P of w.querySelectorAll(o9)){const N=Number(P.clientWidth)||Number(P.getBoundingClientRect?.().width)||0;let G=NaN;typeof window<"u"&&typeof window.getComputedStyle=="function"&&(G=Number.parseFloat(window.getComputedStyle(P).getPropertyValue("--scale-factor")));const R=(r.value??100)/100,F=s9(N,G,R);F!==null&&F>x&&(x=F)}return x>0?x:null},h=()=>{const w=e();if(!w)return null;const x=[],P=u?.value??[];for(const G of P){if(G?.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")continue;const R=c(G.getEditor?.());R!==null&&x.push(R)}if(x.length===0){const G=c(w.activeEditor);G!==null&&x.push(G)}const N=d();if(N!==null&&x.push(N),x.length>0)return Math.max(...x);if(w.activeEditor){const G=l.value?.querySelector?.(".superdoc__document"),R=Number(G?.clientWidth)||Number(G?.getBoundingClientRect?.().width)||0;if(R>0){const F=(r.value??100)/100;return F>0?R/F:R}}return null},g=()=>{if(!s?.value)return 0;const w=a?.value??l.value?.querySelector?.(r9),x=Number(w?.offsetWidth)||Number(w?.getBoundingClientRect?.().width)||0;return x>0?x:0},p=(w,x)=>{const P=Pk(w.config?.zoom?.fitWidth),N=i9(x.availableWidth,x.documentWidth,P);N!==null&&N!==r.value&&(r.value=N,w.emit("zoomChange",{zoom:N,mode:"fit-width"}))},v=()=>{const w=e();if(!w)return;const x=t.value;if(!(x>0)||!n.value)return;const P=h();if(P===null)return;const N=x-g(),G=Dk(N,P);if(G===null)return;const R=Object.freeze({availableWidth:N,documentWidth:P,fitZoom:G}),F=i.value;(!F||F.availableWidth!==N||F.documentWidth!==P||F.fitZoom!==G)&&(i.value=R),(!F||F.fitZoom!==G||Math.round(F.documentWidth)!==Math.round(P))&&w.emit("viewport-change",R),o.value==="fit-width"&&p(w,R)};zt(t,()=>{It(()=>v())}),zt(n,w=>{w&&v()}),zt(o,w=>{w==="fit-width"&&v()}),s&&zt(s,()=>{It(()=>v())});const k=()=>{It(()=>v())},C=()=>{It(()=>v())},_=()=>{It(()=>v())},y=e();return y?.on?.("editorCreate",k),y?.on?.("pagination-update",C),y?.on?.("pdf:document-ready",_),cr(()=>{y?.off?.("editorCreate",k),y?.off?.("pagination-update",C),y?.off?.("pdf:document-ready",_)}),{evaluateViewport:v}}const l9=e=>!!e?.trackedChange,c9=e=>e,u9=(e,t,n,r=e)=>!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?!1:(Number.isFinite(r)?r:e)<t||e>n,d9=({comment:e,anchorTop:t,anchorBottom:n,viewportTop:r,viewportBottom:o})=>l9(e)&&u9(t,r,o,n),f9=({comment:e,anchorTop:t,anchorBottom:n,cardHeight:r,viewportTop:o,viewportBottom:i})=>!d9({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,h9=({id:e,visibleIds:t,activeCommentInstanceId:n})=>e?!!(e==="pending"||n!=null&&String(e)===String(n)||t?.has?.(e)):!1,Ok=({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};Mt(),Cn();var p9=["data-comment-id","data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Zl={},m9={__name:"FloatingComments",props:{currentDocument:{type:Object,required:!0},parent:{type:Object,required:!0}},setup(e){const r=(Pe,Ge,We)=>{if(Ge>=0){Pe[Ge].top=Pe[Ge].anchorTop;let ft=Pe[Ge].top+Pe[Ge].height+We;for(let yt=Ge+1;yt<Pe.length;yt++)Pe[yt].top=Math.max(Pe[yt].anchorTop,ft),ft=Pe[yt].top+Pe[yt].height+We;ft=Pe[Ge].top-We;for(let yt=Ge-1;yt>=0;yt--){const $t=ft-Pe[yt].height;Pe[yt].top=Math.min(Pe[yt].anchorTop,$t),ft=Pe[yt].top-We}const Vt=Math.min(...Pe.map(yt=>yt.top));if(Vt<0){const yt=Math.abs(Vt);for(const $t of Pe)$t.top+=yt}}else for(let ft=1;ft<Pe.length;ft++){const Vt=Pe[ft-1],yt=Vt.top+Vt.height+We;Pe[ft].top<yt&&(Pe[ft].top=yt)}},o=e,i=vu(),s=ca(),{clearInstantSidebarAlignment:a}=s,{activeComment:l,activeFloatingCommentInstanceId:u,editorCommentPositions:c,pendingComment:d,editingCommentId:h,instantSidebarAlignmentTargetY:g,instantSidebarAlignmentThreadId:p,instantSidebarAlignmentInstanceId:v}=ea(s),{activeZoom:k}=ea(i),C=_e(()=>{const Pe=s.getFloatingCommentInstances;if(!Array.isArray(Pe))return[];const Ge=o.currentDocument?.id;return Ge==null?Pe:Pe.filter(We=>s.belongsToDocument(We.comment,String(Ge),{allowSingleDocumentMismatch:!0}))}),_=ne(null),y=ne(0),w=ne(0),x=ne(!1),P=ne(null),N=ne(0),G=Pe=>{const Ge=d.value?.commentId;return Ge?typeof Pe=="object"?Pe?.commentId===Ge:Pe===Ge||Pe==="pending":!1},R=Pe=>Pe?.commentId??Pe?.importedId??null,F=_e(()=>{const Pe=new Map,Ge=new Map;for(const We of C.value){We?.id!=null&&Pe.set(String(We.id),We);const ft=R(We?.comment);if(ft==null)continue;const Vt=String(ft),yt=Ge.get(Vt)??[];yt.push(We),Ge.set(Vt,yt)}return{byId:Pe,byThreadId:Ge}}),Z=(Pe,Ge=null)=>{if(Pe==null)return null;const We=String(Pe),ft=F.value.byThreadId.get(We)??[];if(!ft.length)return null;if(Ge!=null){const Vt=ft.find(yt=>String(yt.id)===String(Ge));if(Vt)return Vt.id}return ft.find(Vt=>Vt.isPrimary)?.id??ft[0]?.id??null},D=_e(()=>l.value?Z(l.value,u.value):null),B=Pe=>{if(typeof Pe=="number")return Number.isFinite(Pe)?Pe:null;if(typeof Pe!="string"||Pe.trim()==="")return null;const Ge=Number(Pe);return Number.isFinite(Ge)?Ge:null},T=ne({...Zl}),V=ne(new Set),J=ne({});let q=null;const se=new Set;let pe=null;const Ne=()=>{pe==null&&(pe=requestAnimationFrame(()=>{pe=null,N.value+=1}))},he=Pe=>{if(o.currentDocument.type==="application/pdf"){const Ge=(k.value??100)/100,We=B(Pe?.comment?.selection?.selectionBounds?.top);return We==null?null:We*Ge}return Pe?.positionEntry?.bounds?.top},ye=(Pe,Ge)=>{if(o.currentDocument.type==="application/pdf"){const ft=(k.value??100)/100,Vt=B(Pe?.comment?.selection?.selectionBounds?.bottom);return Vt!=null?Vt*ft:Ge}const We=Pe?.positionEntry?.bounds?.bottom;return Number.isFinite(We)?We:Ge},ce=_e(()=>{const Pe=[];for(const Ge of C.value){const We=Ge?.id,ft=R(Ge?.comment),Vt=he(Ge);if(We==null||ft==null||!Number.isFinite(Vt))continue;const yt=c9(Vt,Ge.comment);Pe.push({id:We,threadId:ft,instance:Ge,top:yt,anchorBottom:ye(Ge,yt)})}return Pe}),ke=()=>{const Pe=c.value.pending;if(typeof Pe?.bounds?.top=="number"&&!isNaN(Pe.bounds.top))return Pe.bounds.top;const Ge=o.currentDocument.type==="application/pdf"?(k.value??100)/100:1,We=B(d.value?.selection?.selectionBounds?.top);return We==null?null:We*Ge},ie=Pe=>h9({id:Pe?.id,visibleIds:V.value,activeCommentInstanceId:D.value,comment:Pe?.commentRef}),xe=()=>{const Pe=_.value;if(!Pe)return null;const Ge=Pe.getBoundingClientRect();if(!Number.isFinite(Ge.top)||!Number.isFinite(window.innerHeight))return null;let We=0,ft=window.innerHeight;for(let yt=Pe.parentElement;yt;yt=yt.parentElement){const $t=window.getComputedStyle(yt).overflowY;if(!["auto","scroll","hidden","clip"].includes($t))continue;const At=yt.getBoundingClientRect();!Number.isFinite(At.top)||!Number.isFinite(At.bottom)||(We=Math.max(We,At.top),ft=Math.min(ft,At.bottom))}if(ft<=We)return null;const Vt=o.parent?.getBoundingClientRect?.();if(Vt&&Number.isFinite(Vt.top)&&Number.isFinite(Vt.bottom)){const yt=Math.max(We,Vt.top),$t=Math.min(ft,Vt.bottom);$t>yt&&(We=yt,ft=$t)}return{top:We-Ge.top,bottom:ft-Ge.top}},Je=_e(()=>p.value?Z(p.value,v.value):null),st=_e(()=>{N.value;const Pe=ce.value,Ge=d.value&&d.value.fileId===o.currentDocument.id;if(!Pe.length&&!C.value.length&&!Ge)return[];const We=[],ft=xe()??{top:0,bottom:Math.max(0,o.parent?.clientHeight||window.innerHeight||0)},Vt=ft.top-600,yt=ft.bottom+600,$t=Ge?"pending":D.value,At=new Set,kn=({id:Ht,threadId:Pn,instance:br,top:Do,anchorBottom:er,hasAnchorGeometry:cn})=>{const Gn=String(Ht);At.has(Gn)||(At.add(Gn),We.push({id:Ht,threadId:Pn,pageIndex:br?.pageIndex??null,anchorTop:Do,anchorBottom:er,hasAnchorGeometry:cn,top:Do,height:T.value[Ht]||110,commentRef:br.comment,instanceRef:br}))};for(const Ht of Pe){const{id:Pn,threadId:br,instance:Do,top:er,anchorBottom:cn}=Ht,Gn=$t!=null&&String(Pn)===String($t),Br=h.value!=null&&String(br)===String(h.value);!Gn&&!Br&&(cn<Vt||er>yt)||kn({id:Pn,threadId:br,instance:Do,top:er,anchorBottom:cn,hasAnchorGeometry:!0})}const Nn=[];if($t&&$t!=="pending"){const Ht=F.value.byId.get(String($t));Ht&&Nn.push(Ht)}if(h.value!=null){const Ht=F.value.byThreadId.get(String(h.value))??[],Pn=Ht.find(br=>br.isPrimary)??Ht[0];Pn&&Nn.push(Pn)}for(const Ht of Nn){const Pn=Ht.id,br=R(Ht.comment);Pn==null||br==null||At.has(String(Pn))||kn({id:Pn,threadId:br,instance:Ht,top:ft.top,anchorBottom:ft.top,hasAnchorGeometry:!1})}if(Ge){const Ht=ke();typeof Ht=="number"&&!isNaN(Ht)&&We.push({id:"pending",anchorTop:Ht,anchorBottom:Ht,hasAnchorGeometry:!0,top:Ht,height:T.value.pending||110,commentRef:d.value})}We.sort((Ht,Pn)=>Ht.anchorTop-Pn.anchorTop);const Uo=[];for(const Ht of We){const Pn=Ht.hasAnchorGeometry?f9({comment:Ht.commentRef,anchorTop:Ht.anchorTop,anchorBottom:Ht.anchorBottom,cardHeight:Ht.height,viewportTop:ft.top,viewportBottom:ft.bottom}):null;Pn==null?Uo.push(Ht):Ht.top=Pn}return r(Uo,$t?Uo.findIndex(Ht=>Ht.id===$t):-1,15),We}),Tt=_e(()=>(N.value,Math.max(0,o.parent?.clientHeight||0,o.parent?.scrollHeight||0))),Te=()=>{q&&q.disconnect(),q=new IntersectionObserver(Pe=>{const Ge=new Set(V.value);for(const We of Pe){const ft=We.target.dataset.commentId;ft&&(We.isIntersecting?Ge.add(ft):Ge.delete(ft))}V.value=Ge},{rootMargin:"600px 0px 600px 0px"})},je=()=>{if(!q)return;const Pe=new Set;for(const Ge of st.value){const We=J.value[Ge.id];We&&(Pe.add(We),se.has(We)||(q.observe(We),se.add(We)))}for(const Ge of se)Pe.has(Ge)||(q.unobserve(Ge),se.delete(Ge))},Ye=(Pe,Ge)=>{Ge<=0||Ge===T.value[Pe]||(Zl[Pe]=Ge,T.value={...T.value,[Pe]:Ge})},$=Pe=>{if(!Pe)return;const{elementRef:Ge,commentId:We}=Pe;Ge&&It(()=>{const ft=Ge.value?.getBoundingClientRect();!ft||ft.height<=0||We&&Ye(We,ft.height)})},S=Pe=>{const Ge=Pe?.id;Ge&&It(()=>{const We=J.value[Ge];if(!We)return;const ft=We.querySelector(".comments-dialog");if(!ft)return;Ye(Ge,ft.getBoundingClientRect().height);const Vt=Ge===D.value,yt=Ge==="pending",$t=!!h.value&&!!l.value&&Pe?.threadId!=null&&String(Pe.threadId)===String(l.value);!Vt&&!yt&&!$t||(Et(st.value.map(At=>At.id)),In(()=>st.value.map(At=>At.id)))})},ee=Pe=>{!Pe&&P.value!=null||(x.value=Pe)},O=(Pe,Ge,We)=>{if(!Number.isFinite(Ge)){We?.(!1);return}const ft=J.value[Pe];if(!ft){We?.(!1);return}const Vt=ft.getBoundingClientRect().top;w.value+=Ge-Vt,We?.(!0)},j=(Pe,Ge)=>{if(Ge)J.value[Pe]=Ge,q&&!se.has(Ge)&&(q.observe(Ge),se.add(Ge));else{const We=J.value[Pe];We&&q&&(q.unobserve(We),se.delete(We)),delete J.value[Pe]}};let U=[],W=null,te=[],Y=null,X=!1,be=0,ve=null,we=null,Be=null,rt=null;const at=()=>{Be=null,rt=null,P.value=null,ee(!1)},Ct=Pe=>{if(!Be)return;const Ge=(Pe?.target instanceof Element?Pe.target:null)?.closest?.("[data-comment-action]"),We=Ge?.getAttribute?.("data-comment-action");(We==="resolve"||We==="reject")&&_.value?.contains?.(Ge)||at()},en=()=>{U.forEach(clearTimeout),U=[]},Et=Pe=>{for(const Ge of Pe.filter(Boolean)){const We=J.value[Ge];if(!We)continue;const ft=We.querySelector(".comments-dialog");ft&&Ye(Ge,ft.getBoundingClientRect().height)}},Ut=50,Wt=350,In=Pe=>{en();const Ge=typeof Pe=="function"?Pe:()=>Pe;U.push(setTimeout(()=>Et(Ge()),Ut)),U.push(setTimeout(()=>Et(Ge()),Wt))},bt=()=>{a(),requestAnimationFrame(()=>{ee(!1)})},nn=(Pe,Ge)=>{!Pe||!Number.isFinite(Ge)||(ee(!0),It(()=>{Et([Pe]),O(Pe,Ge,()=>{bt()})}))},et=()=>{Y=null,be+=1,ve!=null&&(cancelAnimationFrame(ve),ve=null),ee(!1)},Pt=()=>{if(!Y||X)return;X=!0;const Pe=be;ve!=null&&(cancelAnimationFrame(ve),ve=null),ee(!0),It(()=>{if(X=!1,Pe!==be){Pt();return}const{key:Ge,targetClientY:We}=Y;Et([Ge]),O(Ge,We,ft=>{if(Pe===be){if(!ft){ee(!1);return}ve=requestAnimationFrame(()=>{ve=null,Pe===be&&ee(!1)})}})})},Kt=(Pe,Ge)=>{const We=Ok({previousIds:te,currentIds:Ge,removedId:Pe}),ft=(We?J.value[We]:null)?.getBoundingClientRect?.().top;return!We||!Number.isFinite(ft)?(et(),!1):(Y={key:We,targetClientY:ft},be+=1,Pt(),!0)},Rn=Pe=>{const Ge=Pe?.target?.closest?.("[data-comment-action]"),We=Ge?.getAttribute?.("data-comment-action");if(We!=="resolve"&&We!=="reject"||(at(),Ge.getAttribute?.("aria-disabled")==="true"))return;const ft=Ge.closest?.("[data-comment-id]")?.getAttribute?.("data-comment-id");if(!ft||String(D.value??"")===String(ft))return;const Vt=st.value.filter(At=>At.commentRef?.trackedChange).map((At,kn)=>({id:At.id,index:kn,top:At.top})).filter(At=>Number.isFinite(At.top)).sort((At,kn)=>At.top-kn.top||At.index-kn.index).map(At=>At.id),yt=Ok({previousIds:Vt,currentIds:new Set(Vt),removedId:ft}),$t=(yt?J.value[yt]:null)?.getBoundingClientRect?.().top;!yt||!Number.isFinite($t)||(Be={removedKey:ft,targetKey:yt,targetClientY:$t,applied:!1},rt=ft,P.value=yt,ee(!0))};zt(D,(Pe,Ge)=>{if(en(),!(Be!=null&&rt!=null&&[Pe,Ge].some(Vt=>Vt!=null&&String(Vt)===String(rt)))){if(rt=null,Pe)at(),et();else if(Ge){const Vt=new Set(st.value.map(yt=>yt.id));Vt.has(Ge)?et():Kt(Ge,Vt)}}const We=[Pe,Ge],ft=Pe&&Pe===Je.value&&Number.isFinite(g.value);It(()=>{if(ft){Et(We);return}In(We)})}),zt([D,Je,g],([Pe,Ge,We])=>{!Pe||!Ge||Pe!==Ge||!Number.isFinite(We)||nn(Pe,We)}),zt(h,()=>{en(),It(()=>{In(()=>st.value.map(Pe=>Pe.id))})}),zt(l,()=>{if(W&&clearTimeout(W),!l.value){if(a(),Y){Pt();return}ee(!1),w.value=0;return}if(!(G(l.value)?d.value:s.getComment(l.value)))return;const Pe=G(l.value)?"pending":D.value;if(Pe){if(Pe===Je.value&&Number.isFinite(g.value)){ee(!0);return}It(()=>{W=setTimeout(()=>{const We=J.value[Pe];if(!We)return;const ft=o.parent?.getBoundingClientRect?.();if(!ft)return;const Vt=st.value.find(kn=>kn.id===Pe),yt=Pe==="pending"?ke():Vt?.anchorTop;if(typeof yt!="number"||isNaN(yt))return;const $t=We.getBoundingClientRect().top,At=ft.top+yt;w.value+=At-$t},400)})}}),zt(k,()=>{if(o.currentDocument.type==="application/pdf"){for(const Pe in Zl)delete Zl[Pe];T.value={},y.value+=1}});let Nt=new Set,un=null,Mn=null;return zt(st,Pe=>{const Ge=D.value?Pe.find(cn=>cn.id===D.value):null,We=typeof Ge?.anchorTop=="number"&&Number.isFinite(Ge.anchorTop)?Ge.anchorTop:null,ft=We!=null&&un!=null&&Math.abs(We-un)>1,Vt=typeof Ge?.top=="number"&&Number.isFinite(Ge.top)?Ge.top:null,yt=Vt!=null&&Mn!=null&&Math.abs(Vt-Mn)>1;ft&&w.value!==0&&!Number.isFinite(g.value)?(w.value=0,ee(!1)):yt&&w.value!==0&&!Number.isFinite(g.value)&&!Y&&(ee(!0),w.value+=Mn-Vt,we!=null&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{we=null,!Y&&!Number.isFinite(g.value)&&ee(!1)})),un=We,Mn=Vt;const $t=Pe.map(cn=>cn.id),At=new Set($t);if(Be&&!Be.applied&&!At.has(Be.removedKey)){const{targetKey:cn,targetClientY:Gn}=Be;Be.applied=!0,At.has(cn)&&Number.isFinite(Gn)?(Y={key:cn,targetClientY:Gn},be+=1,Pt()):at()}if(Be?.applied&&!At.has(Be.targetKey)&&at(),Y&&!At.has(Y.key)){const cn=Y.key;Kt(cn,At)||(ee(!1),w.value=0)}const kn=new Set(V.value);let Nn=!1,Uo=-1/0,Ht=1/0;const Pn=_.value;if(Pn){const cn=Pn.getBoundingClientRect();Uo=-cn.top-600,Ht=-cn.top+window.innerHeight+600}const br=new Map(Pe.map(cn=>[cn.id,cn]));for(const cn of At)if(!kn.has(cn)){const Gn=br.get(cn);(!Gn||Gn.top>=Uo&&Gn.top<=Ht)&&(kn.add(cn),Nn=!0)}for(const cn of kn)At.has(cn)||(kn.delete(cn),Nn=!0);Nn&&(V.value=kn);for(const cn of Nt)At.has(cn)||delete Zl[cn];const Do=Nt.size!==At.size||[...Nt].some(cn=>!At.has(cn)),er=te.length!==$t.length||te.some((cn,Gn)=>cn!==$t[Gn]);if(Do){const cn={};for(const Gn of At)Zl[Gn]&&(cn[Gn]=Zl[Gn]);T.value=cn,It(()=>{for(const Gn of Pe){const Br=J.value[Gn.id];if(!Br)continue;const ei=Br.querySelector(".comments-dialog");ei&&Ye(Gn.id,ei.getBoundingClientRect().height)}})}Y&&(Do||er)&&Pt(),Nt=At,It(()=>{te=$t,je()})}),Un(()=>{Te(),o.parent?.addEventListener?.("scroll",Ne,{passive:!0}),window.addEventListener("resize",Ne,{passive:!0}),document.addEventListener("pointerdown",Ct,!0),It(je)}),cr(()=>{en(),W&&clearTimeout(W),at(),et(),we!=null&&(cancelAnimationFrame(we),we=null),o.parent?.removeEventListener?.("scroll",Ne),window.removeEventListener("resize",Ne),document.removeEventListener("pointerdown",Ct,!0),pe!=null&&(cancelAnimationFrame(pe),pe=null),q&&(q.disconnect(),q=null,se.clear())}),(Pe,Ge)=>(ge(),Ie("div",{class:"section-wrapper",ref_key:"floatingCommentsContainer",ref:_,onClickCapture:Rn,style:Sn({minHeight:Tt.value+"px",transition:x.value?"none":void 0})},[Oe("div",{class:"sidebar-container",style:Sn({transform:`translateY(${w.value}px)`,transition:x.value?"none":void 0})},[(ge(!0),Ie(Jt,null,lr(st.value,We=>(ge(),Ie("div",{key:We.id,ref_for:!0,ref:ft=>j(We.id,ft),"data-comment-id":We.id,"data-comment-instance-id":We.id,"data-comment-thread-id":We.threadId,"data-comment-position-key":We.instanceRef?.positionKey??"","data-comment-page-index":We.pageIndex??"",class:an([{"is-direct-decision-continuity-target":We.id===P.value},"comment-placeholder"]),style:Sn({top:We.top+"px",height:We.height+"px",transition:x.value?"none":void 0})},[ie(We)?(ge(),vn(Np,{key:We.id+y.value,onReady:$,onResize:ft=>S(We),class:"floating-comment",parent:e.parent,comment:We.commentRef,"floating-instance-id":We.id,"floating-page-index":We.pageIndex,"floating-position-entry":We.instanceRef?.positionEntry??null,"is-floating-instance-active":We.id===D.value},null,8,["onResize","parent","comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])):mt("",!0)],14,p9))),128))],4)],36))}},g9=yn(m9,[["__scopeId","data-v-a0a841ce"]]);Mt(),Cn();var v9={class:"superdoc__pdf-comments-layer pdf-comments-layer","aria-hidden":"false"},y9=["data-id","data-comment-id","data-page-number","onClick","onKeydown"],b9="pdf",w9="#078383",C9="#B1124B",k9={__name:"PdfCommentsLayer",emits:["anchor-activate"],setup(e,{emit:t}){const n=t,r=ca(),o=vu(),{activeComment:i}=ea(r),{documents:s,activeZoom:a}=ea(o),{proxy:l}=ur(),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=_e(()=>{const y=Array.isArray(s.value)?s.value:[];return new Set(y.filter(w=>w?.type===ql).map(w=>String(w.id)))}),h=y=>{const w=y?.fileId??y?.documentId??y?.selection?.documentId;return w!=null?String(w):null},g=y=>{const w=y?.commentId??y?.importedId;return w!=null&&String(w)!==""?String(w):null},p=y=>{const w=d.value;if(!w.size)return!1;const x=h(y);return x?w.has(x):w.size===1},v=y=>{const w=Math.min(Number(y.top),Number(y.bottom)),x=Math.max(Number(y.top),Number(y.bottom));return{top:w,left:Math.min(Number(y.left),Number(y.right)),right:Math.max(Number(y.left),Number(y.right)),bottom:x}},k=_e(()=>{const y=r.getFloatingComments;return Array.isArray(y)?y.filter(w=>w?.selection?.source===b9).filter(w=>!w.resolvedTime).filter(w=>g(w)!==null).filter(w=>c(w.selection?.selectionBounds)).filter(w=>p(w)).map(w=>{const x=g(w),P=v(w.selection.selectionBounds);return{commentId:x,page:w.selection?.page??null,isInternal:w.isInternal!==!1,bounds:P}}):[]}),C=y=>{const w=(a.value??100)/100,{top:x,left:P,right:N,bottom:G}=y.bounds,R=i.value===y.commentId,F=(y.isInternal?w9:C9)+(R?"66":"33");return{position:"absolute",top:x*w+"px",left:P*w+"px",width:(N-P)*w+"px",height:(G-x)*w+"px",backgroundColor:F}},_=y=>{r.setActiveComment(l.$superdoc,y.commentId),n("anchor-activate",y.commentId)};return(y,w)=>(ge(),Ie("div",v9,[(ge(!0),Ie(Jt,null,lr(k.value,x=>(ge(),Ie("div",{key:x.commentId,class:"sd-comment-anchor sd-highlight",role:"button",tabindex:"0","data-id":x.commentId,"data-comment-id":x.commentId,"data-page-number":x.page,style:Sn(C(x)),onClick:sn(P=>_(x),["stop","prevent"]),onKeydown:[Qo(sn(P=>_(x),["stop","prevent"]),["enter"]),Qo(sn(P=>_(x),["stop","prevent"]),["space"])]},null,44,y9))),128))]))}},S9=yn(k9,[["__scopeId","data-v-b5ad4c58"]]);Mt();const _9=({proxy:e,layers:t,documents:n,modules:r})=>{const o=_e(()=>{const F=r.value?.whiteboard??r.whiteboard;return F===!1||F==null?null:F}),i=e?.$superdoc?.whiteboard,s=Zr([]),a=Yr({}),l=Yr({}),u=ne(!1),c=ne(0),d=ne(0),h=ne(1),g=ne(o.value?.enabled??!1),p=()=>{if(u.value)return;c.value+=1;const F=d.value||s.value.length;F&&c.value>=F&&(u.value=!0,e?.$superdoc?.emit("whiteboard:ready",{whiteboard:i}))},v=F=>{if(!F)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&k(F)},k=F=>{const{pageIndex:Z,width:D,height:B,originalWidth:T,originalHeight:V}=F,J={width:D,height:B,originalWidth:T,originalHeight:V};i?.setPageSize(Z,J),a[Z]=J;const q=i?.getPage(Z);q&&q.setSize(J),i&&(s.value=i.getPages().sort((se,pe)=>se.pageIndex-pe.pageIndex).map(se=>Xr(se)),d.value=s.value.length),It(()=>{G(),p()})},C=F=>{e?.$superdoc?.emit("whiteboard:change",F)},_=F=>{F.forEach(Z=>{const D=a[Z.pageIndex];D&&Z.setSize(D)}),s.value=F.map(Z=>Xr(Z)),d.value=s.value.length,It(()=>G())},y=F=>{g.value=F,e?.$superdoc?.emit("whiteboard:enabled",F)},w=F=>{h.value=F},x=F=>{e?.$superdoc?.emit("whiteboard:tool",F)},P=()=>{const F=n.value?.[0];F&&F.type==="application/pdf"&&N({doc:F})},N=({doc:F})=>{s.value.forEach(Z=>{const D=`${F.id}-page-${Z.pageIndex+1}`,B=document.querySelector(`[data-page-id="${D}"]`);if(!B)return;const T=B.getBoundingClientRect(),V=a[Z.pageIndex]||{},J=V.originalWidth??Z.size?.originalWidth??T.width,q=V.originalHeight??Z.size?.originalHeight??T.height,se={width:T.width,height:T.height,originalWidth:J,originalHeight:q};a[Z.pageIndex]=se,Z.setSize(se)})},G=()=>{const F=t.value?.getBoundingClientRect?.();if(!F)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&R({doc:Z,layerBounds:F})},R=({doc:F,layerBounds:Z})=>{s.value.forEach(D=>{const B=`${F.id}-page-${D.pageIndex+1}`,T=document.querySelector(`[data-page-id="${B}"]`);if(!T)return;const V=T.getBoundingClientRect();l[D.pageIndex]={top:V.top-Z.top,left:V.left-Z.left}})};return i&&(i.on("change",C),i.on("setData",_),i.on("enabled",y),i.on("opacity",w),i.on("tool",x)),cr(()=>{i&&(i.off("change",C),i.off("setData",_),i.off("opacity",w),i.off("enabled",y),i.off("tool",x))}),{whiteboard:i,whiteboardModuleConfig:o,whiteboardPages:s,whiteboardPageSizes:a,whiteboardPageOffsets:l,whiteboardEnabled:g,whiteboardOpacity:h,whiteboardReady:u,handleWhiteboardPageReady:v,updateWhiteboardPageSizes:P,updateWhiteboardPageOffsets:G}};Mt(),Cn();var A9=["data-page-index"],I9={__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,g=u.clientY-d.top,p=t.pageSize?.width,v=t.pageSize?.originalWidth??p,k=Number.isFinite(p)&&Number.isFinite(v)&&v?p/v:1;i(u,h,g,k)||s(u,h,g,k)||a(u,h,g)||l(u,h,g)},i=(u,c,d,h)=>{const g=u.dataTransfer.getData("application/sticker");if(!g)return!1;const p=(t.whiteboard.getType("stickers")||[]).find(v=>v.id===g);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 g=Array.from(u.dataTransfer.files||[]).find(v=>v.type.startsWith("image/"));if(!g)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(g),!0},a=(u,c,d)=>{const h=u.dataTransfer.getData("application/comment");if(!h)return!1;const g=(t.whiteboard.getType("comments")||[]).find(p=>p.id===h);return g?.text?(t.page.addText({x:c,y:d,content:g.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 zt(()=>[t.page,t.pageSize?.width,t.pageSize?.height],()=>{It(r)}),Un(()=>{r()}),cr(()=>{t.page?.destroy()}),(u,c)=>(ge(),Ie("div",{ref_key:"containerRef",ref:n,class:"whiteboard-page","data-page-index":e.page.pageIndex,onDragover:c[0]||(c[0]=sn(()=>{},["prevent"])),onDrop:sn(o,["prevent"]),style:Sn({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,A9))}},E9=yn(I9,[["__scopeId","data-v-c876c9b5"]]);Mt(),Cn();var T9={__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=_e(()=>t.interactive==null?t.enabled:t.interactive);return(r,o)=>(ge(),Ie("div",{class:"whiteboard-layer","aria-hidden":"true",style:Sn({opacity:e.opacity,pointerEvents:n.value?"auto":"none"})},[(ge(!0),Ie(Jt,null,lr(e.pages,i=>(ge(),vn(E9,{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))}},x9=yn(T9,[["__scopeId","data-v-54546c3d"]]);function R9(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 Fk=["#1f6feb","#d1242f","#8250df","#bf3989","#1a7f37","#9a6700","#bc4c00","#0969da","#cf222e","#6639ba","#116329","#7d4e00"];const M9=e=>e?`${typeof e.name=="string"?e.name:""} ${typeof e.email=="string"?e.email:""}`:"";var L9=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 P9=e=>Fk[L9(M9(e))%Fk.length];var gf=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(gf(o.email)&&gf(t[o.email]))return t[o.email];if(gf(o.name)&&gf(t[o.name]))return t[o.name]}if(n)try{const i=n(o);if(gf(i))return i}catch{}return P9(o)}},O9=["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 Zj=new Set(O9);const vr={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"},Qj={"render.media.missing-relationship":vr.missingRelationship,"render.media.wrong-relationship-type":vr.unsupportedRelationshipType,"render.media.unsupported-target":vr.unsupportedRelationshipType,"render.media.invalid-image-size":vr.imageTooLarge,"render.media-resolver-unavailable":vr.missingMediaPart,"render.chart-not-supported":vr.unsupportedObject,"render.textbox.vml-unsupported":vr.vmlUnsupported},F9={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:vr.externalImageDeferred},missingRelationship:{family:"missingRelationship",support:"fail-closed",description:"Drawing references a relationship id absent from the owner part .rels.",contract:"none",diagnostic:vr.missingRelationship},missingMediaPart:{family:"missingMediaPart",support:"fail-closed",description:"Relationship resolves but the target media part bytes are missing or empty.",contract:"none",diagnostic:vr.missingMediaPart},wrongRelationshipType:{family:"wrongRelationshipType",support:"fail-closed",description:"Relationship exists but is not an image relationship type.",contract:"none",diagnostic:vr.unsupportedRelationshipType},unsupportedMime:{family:"unsupportedMime",support:"fail-closed",description:"Media MIME outside the supported allowlist (incl. GIF/BMP/ICO).",contract:"none",diagnostic:vr.unsupportedMime},oversizedMediaPart:{family:"oversizedMediaPart",support:"fail-closed",description:"Media part exceeds the host byte-size policy before bytes are materialized.",contract:"none",diagnostic:vr.imageTooLarge},unsafeSvg:{family:"unsafeSvg",support:"fail-closed",description:"SVG content rejected by the SVG safety policy.",contract:"none",diagnostic:vr.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:vr.unsupportedFormat},embeddedObject:{family:"embeddedObject",support:"fail-closed",description:"OLE / ActiveX / embedded package object.",contract:"none",diagnostic:vr.embeddedObjectNotSupported},smartArtOrDiagram:{family:"smartArtOrDiagram",support:"fail-closed",description:"SmartArt / diagram / unknown external graphic-data object.",contract:"none",diagnostic:vr.unsupportedObject},vml:{family:"vml",support:"fail-closed",description:"VML structure outside any supported image-like subset (default fail-closed policy).",contract:"none",diagnostic:vr.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:vr.vmlImageUnsupported},unsupportedGeometryCommand:{family:"unsupportedGeometryCommand",support:"fail-closed",description:"Custom geometry command the extractor does not implement, e.g. arcTo.",contract:"none",diagnostic:vr.unsupportedGeometryCommand},unsupportedAnchorFields:{family:"unsupportedAnchorFields",support:"fail-closed",description:"Anchor fields required for honest placement are unsupported (char-relative, alignment modes, etc.).",contract:"none",diagnostic:vr.anchorUnsupported},unsupportedWrapFields:{family:"unsupportedWrapFields",support:"fail-closed",description:"Wrap fields required for honest placement are unsupported (arbitrary wrap polygons, etc.).",contract:"none",diagnostic:vr.wrapUnsupported},alternateContentNoSupportedChoice:{family:"alternateContentNoSupportedChoice",support:"fail-closed",description:"mc:AlternateContent with no supported choice and no usable fallback.",contract:"none",diagnostic:vr.altContentNoSupportedChoice},groupChildUnsupported:{family:"groupChildUnsupported",support:"fail-closed",description:"Unsupported child inside an otherwise-supported group. Supported siblings are not dropped.",contract:"none",diagnostic:vr.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"}},Jj=Object.keys(F9),$j=Object.freeze(["multiple-sections","furniture-page-tokens","non-balanceable-multi-column-sections","body-anchored-objects","footnotes","page-references","keep-constraints","tables","furniture-anchored-objects"]);Mt(),Cn();var N9={class:"superdoc-html-viewer"},B9={class:"superdoc-html-viewer__document"},z9=["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 g=h.target.result;u(g)},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 Un(()=>{a()}),(l,u)=>(ge(),Ie("div",N9,[Oe("div",B9,[Oe("div",{class:"superdoc-html-viewer__content",innerHTML:r.value,onMouseup:i},null,40,z9)])]))}},H9=yn(V9,[["__scopeId","data-v-da3494ba"]]);const U9=(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=Op(s),d=c!=null?String(c):null,h=a&&o.has(a)||l&&o.has(l),g=u&&o.has(u)||d&&o.has(d);if(!h&&!g)return;const p=o.size;a&&o.add(a),l&&o.add(l),o.size>p&&(i=!0)});return o};Mt();var Nk=ne(!1);function Vi(){return{isHighContrastMode:Nk,setHighContrastMode:t=>{Nk.value=t}}}const eG="[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor",tG=320,nG=24,rG=816,oG=250,iG="sidebar",Bk=new Set(["auto","sidebar","inline"]);function zk(e){if(!e||e===!1||typeof e!="object")return e;const t={...e},n=t.displayMode;Bk.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}Mt();var j9=".superdoc__document",G9=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,W9=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=g=>{if(!(g instanceof HTMLElement)||(typeof window<"u"?window.getComputedStyle(g):null)?.display==="contents")return!1;const p=Number(g.clientWidth??0),v=Number(g.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0||Number.isFinite(v)&&v>0},l=()=>{const g=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 v=g?.parentElement??null;for(;v;){if(a(v))return v;v=v.parentElement}return a(g)||g instanceof HTMLElement?g:null},u=()=>{const g=typeof window<"u"?window.ResizeObserver:void 0;if(typeof g>"u")return;const p=l();p!==s&&(i&&(i.disconnect(),i=null),s=p,s&&(i=new g(()=>{h()}),i.observe(s)))},c=()=>{u();const g=Number(s?.clientWidth??0);if(Number.isFinite(g)&&g>0)return g;const p=Number(s?.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0?p:0},d=()=>{const g=t.value?.querySelector?.(j9),p=n.value,v=Number(g?.clientWidth??g?.getBoundingClientRect?.().width??0);if(Number.isFinite(v)&&v>0)return v;const k=Number(p?.clientWidth??p?.getBoundingClientRect?.().width??0);return Number.isFinite(k)&&k>0?k:816},h=()=>{const g=c(),p=e.value,v=p?.displayMode??"sidebar";if(v==="sidebar"){r.value=g,o.value=!1;return}if(v==="inline"){r.value=g,o.value=!0;return}if(!(Number.isFinite(g)&&g>0))return;r.value=g;const k=p?.compactBreakpointPx;if(G9(k)){o.value=g<k;return}o.value=g<W9(d())};return cr(()=>{i&&(i.disconnect(),i=null),s=null}),{superdocContainerWidth:r,isCompactCommentsMode:o,recalculateCompactCommentsMode:h,ensureCompactMeasurementObserver:u}}Mt();var Vk=320,tl=12,q9=220,Y9=16,X9=500,Hk=".superdoc-comment-highlight[data-comment-ids]",Uk="data-comment-ids",Z9=".sd-comment-anchor",v0=(e,t,n)=>Math.min(Math.max(e,t),n),gs=e=>Number(e),Hi=e=>Number.isFinite(e),y0=e=>e?.commentId??e?.importedId??null,jk=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),Q9=e=>{const t=e?.value;if(!t)return null;const n=gs(t.ts);if(!Hi(n)||Date.now()-n>X9)return null;const r=gs(t.x),o=gs(t.anchorRect?.bottom),i=Hi(o)?o:gs(t.y);return!Hi(r)||!Hi(i)?null:{x:r,y:i}},J9=({rootEl:e,comment:t,pendingComment:n})=>{if(n?.value&&t?.commentId===n.value?.commentId){const a=e.querySelectorAll(Hk);for(const l of a)if(jk(l.getAttribute(Uk)).includes("pending")&&typeof l.getBoundingClientRect=="function")return l.getBoundingClientRect()}const r=y0(t);if(!r)return null;const o=String(r),i=e.querySelectorAll(Hk);for(const a of i)if(jk(a.getAttribute(Uk)).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},$9=(e,t)=>{const{entry:n}=e(y0(t)),r=gs(n?.bounds?.bottom);return Hi(r)?r:gs(n?.bounds?.top)},eM=({selectionPosition:e,comment:t,pendingComment:n})=>e.value?.source==="pdf"||t?.selection?.source==="pdf"||n.value?.selection?.source==="pdf",tM=({rootEl:e,layersRect:t,comment:n})=>{const r=y0(n);if(r==null)return NaN;const o=e.querySelector(`${Z9}[data-id="${String(r)}"]`);return!o||typeof o.getBoundingClientRect!="function"?NaN:gs(o.getBoundingClientRect().bottom)-gs(t.top)},nM=({comment:e,pendingComment:t,selectionPosition:n,activeZoom:r})=>{if(!t.value||e?.commentId!==t.value?.commentId)return NaN;const o=gs(n.value?.bottom);if(Hi(o))return o*(n.value?.source==="pdf"?(r.value??100)/100:1);const i=gs(n.value?.top);return Hi(i)?i*(n.value?.source==="pdf"?(r.value??100)/100:1):NaN},rM=({top:e,left:t})=>({top:`${Math.round(e)}px`,left:`${Math.round(t)}px`,right:"auto"}),oM=({rootRect:e,layersRect:t,anchorBottom:n,anchorClientX:r=NaN})=>{const o=v0(t.top-e.top+n+Y9,tl,Math.max(tl,e.height-q9)),i=Math.max(tl,e.width-Vk-tl);let s;if(Hi(r))s=v0(r-e.left+tl,tl,i);else{const a=e.width-(t.left-e.left+t.width)+tl;s=v0(e.width-a-Vk,tl,i)}return{top:o,left:s}};function iM({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"},g=ne(0),p=ne({x:null,y:null,ts:0,anchorRect:null});let v=null,k=null;const C=()=>{p.value={x:null,y:null,ts:0,anchorRect:null}},_=(P,N,G)=>{if(!l.value?.some(F=>F.type==="application/pdf"))return!1;const R=P.querySelector(".superdoc__compact-comment-popover");return!n.value||!R||R.contains(N)||G?!1:(t.value&&d(),c(),C(),!0)},y=P=>{const N=s.value;if(!N||!a.value?.contains(P.target))return;const G=(typeof document.elementsFromPoint=="function"?document.elementsFromPoint(P.clientX,P.clientY):[]).find(F=>F?.nodeType===1&&N.contains(F)&&F.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"))?.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor")??(P.target?.nodeType===1?P.target.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"):null);if(_(N,P.target,G)||P.button!==0||P.pointerType!=="mouse")return;const R=G&&typeof G.getBoundingClientRect=="function"?G.getBoundingClientRect():null;R&&(p.value={x:P.clientX,y:R.bottom,ts:Date.now(),anchorRect:{left:R.left,right:R.right,top:R.top,bottom:R.bottom}})},w=_e(()=>{g.value;const P=n.value;if(!P)return h;const N=s.value,G=a.value;if(!N||!G)return h;const R=N.getBoundingClientRect(),F=G.getBoundingClientRect(),Z=Q9(p),D=Z?null:J9({rootEl:N,comment:P,pendingComment:t});let B=NaN,T=NaN;return Z?(B=Z.y-F.top,T=Z.x):D?(B=D.bottom-F.top,T=D.left):B=$9(u,P),!Hi(B)&&eM({selectionPosition:o,comment:P,pendingComment:t})&&(B=tM({rootEl:N,layersRect:F,comment:P})),Hi(B)||(B=nM({comment:P,pendingComment:t,selectionPosition:o,activeZoom:i})),Hi(B)?rM(oM({rootRect:R,layersRect:F,anchorBottom:B,anchorClientX:T})):h});return zt([e,t,o,i,r,p],()=>{const P=typeof window<"u"?window.requestAnimationFrame:null,N=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&N?.(v),P&&(v=P(()=>{g.value+=1,v=null}))},{deep:!1}),zt(n,(P,N)=>{if(!N&&P){const G=document.activeElement;G instanceof HTMLElement&&(k=G)}},{deep:!1}),zt(t,(P,N)=>{!N&&P&&C()}),Un(()=>{document.addEventListener("pointerdown",y,!0)}),cr(()=>{document.removeEventListener("pointerdown",y,!0);const P=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&(P?.(v),v=null),k=null}),{compactCommentPopoverStyle:w,closeCompactCommentPopover:()=>{n.value&&(t.value&&d(),c(),k&&typeof k.focus=="function"&&k.focus(),k=null)},resetClickAnchor:C}}function vs(...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 b0(...e){for(const t of e)if(t!==void 0)return t}function Gk(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=(l,u)=>{l?.kind!=="entity"||l.entityType!=="trackedChange"||typeof l.entityId=="string"&&l.entityId.length>0&&u.add(l.entityId)},s=l=>l?.kind!=="entity"||l.entityType!=="trackedChange"?null:typeof l.entityId=="string"&&l.entityId.length>0?l.entityId:null;if(Array.isArray(t.inserted)&&t.inserted.forEach(l=>i(l,n)),Array.isArray(t.updated)&&t.updated.forEach(l=>i(l,n)),Array.isArray(t.trackedChangeRefs)&&t.trackedChangeRefs.forEach(l=>i(l,n)),Array.isArray(t.removed)&&t.removed.forEach(l=>i(l,r)),Array.isArray(t.invalidatedRefs)&&t.invalidatedRefs.forEach(l=>i(l,r)),Array.isArray(t.remappedRefs))for(const l of t.remappedRefs){const u=s(l?.from),c=s(l?.to);u&&r.add(u),c&&n.add(c),u&&c&&u!==c&&o.push({from:u,to:c})}for(const l of r)n.delete(l);const a=sM(e,t);return n.size===0&&r.size===0&&!a?null:{upsertIds:n,removedIds:r,remappedPairs:o,reconcileMode:e.origin==="history"?"authoritative":"targeted",...a?{allResolved:a}:{}}}function sM(e,t){const n=e?.trackedChangeAllResolved;return e?.origin==="history"||!n||n.schemaVersion!==1||n.targetKind!=="all"||n.decision!=="accept"&&n.decision!=="reject"||n.remainingLogicalCount!==0||typeof n.catalogRevision!="string"||!n.catalogRevision||typeof n.sourceCoverageRevision!="string"||!n.sourceCoverageRevision||!Number.isSafeInteger(n.logicalTargetCount)||n.logicalTargetCount<=0||!Number.isSafeInteger(n.physicalCarrierCount)||n.physicalCarrierCount<n.logicalTargetCount||typeof n.txId!="string"||n.txId!==t.txId||typeof n.documentEpoch!="string"||!Number.isSafeInteger(n.commitSequence)||typeof n.packagePreviousRevision!="string"||typeof n.packageNextRevision!="string"||n.packagePreviousRevision===n.packageNextRevision?null:n}var vf=e=>new Set(Array.from(e??[]).filter(t=>typeof t=="string"&&t.length>0)),aM=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,lM=(e,t)=>e?.adapter===t?.adapter&&e?.documentId===t?.documentId&&e?.editor===t?.editor&&e?.reconcileToken===t?.reconcileToken;function Wk({getContext:e,reconcile:t,hydrate:n,onReconciled:r}){const o=new Map;let i=null,s=0,a=0,l=null,u=!1;const c=[],d=(R,F)=>{for(let Z=c.length-1;Z>=0;Z-=1){const D=c[Z];D.generation!==a||D.version>R||(c.splice(Z,1),D.resolve(F===!0&&D.requiresAllResolved?i==null:F))}},h=(R,F)=>a===R&&lM(F,e()),g=(R,F)=>{const Z=new Set;for(const D of R)o.get(D)===F.get(D)&&(o.delete(D),Z.add(D));return Z},p=R=>new Map([...o].filter(([,F])=>F.ready===!0&&F.reconcileMode===R)),v=()=>{let R=!1;i?.gate==="render"&&!i.ready&&(i.ready=!0,R=!0);for(const F of o.values())F.gate!=="render"||F.ready||(F.ready=!0,R=!0);return R},k=R=>{let F=!1;i&&i.version<=R&&!i.ready&&(i.ready=!0,F=!0);for(const Z of o.values())Z.version>R||Z.ready||(Z.ready=!0,F=!0);return F},C=async(R,F,Z,D=!1)=>{if(!(!D&&F.size===0||typeof r!="function"))try{await r(R,F,Z)}catch{}},_=R=>vf(R?.resolvedIds??(R?.items??[]).map(aM).filter(Boolean)),y=async(R,F,Z)=>{const D=await t(R,{upsertIds:new Set(F.keys()),removedIds:new Set,reconcileMode:"targeted"});if(!h(Z,R)||(await C(R,g(_(D),F),D),new Set([...F].filter(([T,V])=>o.get(T)===V).map(([T])=>T)).size===0))return;const B=await n(R,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1});h(Z,R)&&await C(R,g(_(B),F),B)},w=async(R,F,Z)=>{const D=await n(R,{trackedChangesListMode:"all",refreshReason:"mutation-history-render-reconcile",blocking:!0});if(!h(Z,R)||![...F].some(([q,se])=>o.get(q)===se))return;const B=D?.ok===!0,T=B&&D?.complete===!0&&D?.sourceCoverageComplete===!0,V=B?_(D):new Set,J=T?g(new Set(F.keys()),F):new Set;await C(R,T?J:V,{...D,reconcileMode:"authoritative"},!0)},x=()=>{if(l)return l;const R=i?.ready?i:null,F=p("targeted"),Z=p("authoritative");if(!R&&F.size===0&&Z.size===0)return null;const D=e();if(!D?.adapter)return null;u=!1;const B=a;return l=Promise.resolve().then(async()=>{if(R){let T=null;try{T=await t(D,{upsertIds:new Set,removedIds:new Set,allResolved:R.fact,reconcileMode:"targeted"})}catch{}if(!h(B,D))return;T?.ok===!0&&(i===R&&(i=null),await C(D,new Set,T,!0))}Z.size>0&&await w(D,Z,B).catch(()=>{}),F.size>0&&await y(D,F,B).catch(()=>{})}).catch(()=>{}).finally(()=>{l=null,u&&x()}),l},P=(R,F)=>{if(!R)return;R.allResolved&&(o.clear(),i={fact:R.allResolved,version:++s,gate:F,ready:!1});const Z=R.reconcileMode==="authoritative"?"authoritative":"targeted",D=vf(R.removedIds),B=vf(R.upsertIds);for(const V of D){const J=o.get(V);J?.reconcileMode==="authoritative"?o.set(V,{...J,version:++s,gate:F,ready:!1}):o.delete(V)}const T=e();if(D.size>0&&B.size===0&&T?.adapter&&!R.allResolved)try{Promise.resolve(t(T,{upsertIds:new Set,removedIds:D})).catch(()=>{})}catch{}for(const V of B)if(!D.has(V)){const J=o.get(V);o.set(V,{version:++s,gate:F,ready:!1,reconcileMode:Z==="authoritative"||J?.reconcileMode==="authoritative"?"authoritative":"targeted"})}},N=R=>P(R,"render");return{enqueue:N,enqueueAfterPaint(R,F){if(!R||typeof F!="function")return N(R),Promise.resolve(!1);P(R,"exact-paint");const Z=e(),D=a,B=s;if(!Z?.adapter)return k(B),Promise.resolve(!1);const T=new Promise(q=>{c.push({generation:D,version:B,requiresAllResolved:!!R.allResolved,resolve:q})}),V=new Set([...vf(R.upsertIds),...vf(R.removedIds)]),J=new Map([...V].flatMap(q=>{const se=o.get(q);return se?[[q,se]]:[]}));return Promise.resolve().then(()=>F()).then(async()=>{if(!h(D,Z)){d(B,!1);return}let q=v();k(B)&&(q=!0);for(const[Ne,he]of J)o.get(Ne)===he&&(he.ready||(q=!0),he.ready=!0);l&&(q||B>0)&&(u=!0);const se=l,pe=x();if(pe&&await pe,se){const Ne=l;Ne&&Ne!==se&&await Ne}if(!h(D,Z)){d(B,!1);return}d(B,!0)}).catch(()=>{if(!h(D,Z)){d(B,!1);return}for(const[q,se]of J)o.get(q)===se&&(se.gate="render");i?.gate==="exact-paint"&&(i.gate="render"),d(B,!1)}),T},onRender:(R=!1)=>{const F=v();l&&(F||R)&&(u=!0),x()},reset(){for(const R of c.splice(0))R.resolve(!1);a+=1,o.clear(),i=null,u=!1},getPendingIds(){return new Set(o.keys())}}}function cM(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 uM=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 Kk=e=>e?.type!=="mutation:committed"||e.origin!=="command"?!1:uM.has(e.editableCommandKind);function qk(e){return e==null?null:String(e)}function dM({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=g=>qk(t())===g,d=()=>{a!=null&&s(a),a=null,l=null,u=null};return{schedule:g=>{const p=qk(g);if(!c(p))return!1;u!==p&&d();const v=o();u=p,l??=v,a!=null&&s(a);const k=Math.max(0,r-(v-l));return a=i(()=>{const C=u;a=null,l=null,u=null,c(C)&&e()},Math.min(n,k)),!0},clear:d}}var fM="no-author-configured";const hM="author-required",Yk="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 Xk(e){return typeof e=="string"&&e.includes(fM)}function pM(e){if(!e||e.type!=="mutation:rejected")return!1;if(e.failureSource==="receipt"){const t=e.failure;return t?t.code==="PRECONDITION_FAILED"&&Xk(t.message):!1}return e.failureSource==="shell"?e.reason==="author-required"?!0:e.reason==="PRECONDITION_FAILED"&&Xk(e.message):!1}function mM(){const e=new Set,t=n=>typeof n=="string"&&n.length>0?n:"__default__";return{shouldNotify(n,r){if(!pM(r))return!1;const o=t(n);return e.has(o)?!1:(e.add(o),!0)},clear(n){e.delete(t(n))}}}const gM=e=>!!(e?.anchor&&e?.focus&&(e.anchor.blockId!==e.focus.blockId||e.anchor.blockOffset!==e.focus.blockOffset)),vM=(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)},yM=(e,t)=>e!=="editing"&&e!=="suggesting"?!1:gM(t);var bM=Ir((()=>{})),wM=ad({default:()=>sS},1),Zk,Qk,Jk,$k,eS,tS,nS,rS,oS,iS,sS,CM=Ir((()=>{Mt(),bM(),Cn(),Zk=["onKeydown"],Qk=["id"],Jk={class:"sd-password-prompt__description"},$k={class:"sd-password-prompt__field"},eS=["placeholder","disabled","aria-label"],tS={key:0,class:"sd-password-prompt__error",role:"alert"},nS={class:"sd-password-prompt__actions"},rS=["disabled"],oS=["disabled"],iS={__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=_e(()=>o.value?t.passwordPrompt.texts.invalidTitle:t.passwordPrompt.texts.title),a=_e(()=>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)=>(ge(),Ie("div",{class:"sd-password-prompt",onKeydown:Qo(sn(l,["prevent"]),["enter"])},[Oe("h3",{id:`sd-password-prompt-heading-${e.surfaceId}`,class:"sd-password-prompt__heading"},qt(s.value),9,Qk),Oe("p",Jk,qt(e.passwordPrompt.texts.description),1),Oe("div",$k,[Ws(Oe("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,eS),[[Ei,n.value]])]),i.value?(ge(),Ie("p",tS,qt(i.value),1)):mt("",!0),Oe("div",nS,[Oe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--cancel",disabled:r.value,onClick:u},qt(e.passwordPrompt.texts.cancelLabel),9,rS),Oe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--submit",disabled:!a.value,onClick:l},qt(r.value?e.passwordPrompt.texts.busyLabel:e.passwordPrompt.texts.submitLabel),9,oS)])],40,Zk))}},sS=yn(iS,[["__scopeId","data-v-ecf7f6fb"]])}));Mt();var kM=["DOCX_PASSWORD_REQUIRED","DOCX_PASSWORD_INVALID"],SM=3e4,Ti={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 _M({getSurfaceManager:e,getPasswordPromptConfig:t,onUnhandled:n}){const r=[],o=Zr(null),i=new Map;let s=!1;function a(p,v,k){if(!p||!kM.includes(v)||t()===!1||!e())return!1;const C=i.get(p.id);if(C)return clearTimeout(C.timer),C.resolve({success:!1,errorCode:v}),i.delete(p.id),!0;const _=r.find(y=>y.doc.id===p.id);return _?(_.errorCode=v,_.originalException=k,!0):(o.value?.doc.id===p.id||(r.push({doc:p,errorCode:v,originalException:k}),c()),!0)}function l(p){if(!p)return;const v=i.get(p.id);v&&(clearTimeout(v.timer),v.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(v=>{o.value=null,console.error("[SuperDoc] Password prompt error:",v),n?.(p.doc,p.errorCode,p.originalException),c()})}async function d({doc:p,errorCode:v,originalException:k}){const C=e();if(!C||s)return;const _=h(),y=N=>(p.password=N,p.editorMountNonce++,new Promise(G=>{const R=setTimeout(()=>{i.delete(p.id),G({success:!1,errorCode:"timeout"})},SM);i.set(p.id,{resolve:G,timer:R})})),w={documentId:p.id,errorCode:v,texts:_.texts,attemptPassword:y},x=g(_,{documentId:p.id,errorCode:v,texts:_.texts});if(x.suppressed){n?.(p,v,k),c();return}o.value={doc:p,surfaceHandle:null};let P;if(x.component)P=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:_.texts.title,component:Xr(x.component),props:{...x.props,passwordPrompt:w}});else if(x.render){const N=x.render;P=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:_.texts.title,render:G=>N({container:G.container,passwordPrompt:w,resolve:G.resolve,close:G.close,surfaceId:G.surfaceId,mode:G.mode})})}else{const N=(await Promise.resolve().then(()=>(CM(),wM))).default,G=`password-prompt-${p.id}`;P=C.open({id:G,mode:"dialog",closeOnBackdrop:!1,ariaLabelledBy:`sd-password-prompt-heading-${G}`,component:Xr(N),props:{passwordPrompt:w}})}o.value={doc:p,surfaceHandle:P},await P.result,o.value=null,c()}function h(){const p=t();if(p===!1)return{enabled:!1,texts:Ti};const v=typeof p=="object"&&p!==null?p:{};if(v.component!=null&&typeof v.render=="function")throw new Error('modules.surfaces.passwordPrompt cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{title:v.title??Ti.title,invalidTitle:v.invalidTitle??Ti.invalidTitle,description:v.description??Ti.description,placeholder:v.placeholder??Ti.placeholder,inputAriaLabel:v.inputAriaLabel??Ti.inputAriaLabel,submitLabel:v.submitLabel??Ti.submitLabel,cancelLabel:v.cancelLabel??Ti.cancelLabel,busyLabel:v.busyLabel??Ti.busyLabel,invalidMessage:v.invalidMessage??Ti.invalidMessage,timeoutMessage:v.timeoutMessage??Ti.timeoutMessage,genericErrorMessage:v.genericErrorMessage??Ti.genericErrorMessage},component:v.component,props:v.props,render:v.render,resolver:v.resolver}}function g(p,v){if(typeof p.resolver=="function"){const k=p.resolver(v);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 aS(e,{getCurrentSession:t,applySlice:n,onSettled:r}){return()=>{if(e===t())try{n(e.getSnapshot())}catch{}r()}}var AM=Ir((()=>{})),IM=ad({default:()=>RS},1),lS,cS,uS,dS,fS,hS,pS,mS,gS,vS,yS,bS,wS,CS,kS,SS,_S,AS,IS,ES,TS,xS,RS,EM=Ir((()=>{Mt(),AM(),Cn(),lS=["onKeydown"],cS={class:"sd-find-replace__row"},uS=["title","aria-label","aria-expanded"],dS=["value","placeholder","aria-label"],fS={key:0,class:"sd-find-replace__count"},hS=["title","aria-label","aria-pressed"],pS=["title","aria-label","aria-pressed"],mS=["title","aria-label","aria-pressed"],gS={class:"sd-find-replace__nav"},vS=["disabled","title","aria-label"],yS=["disabled","title","aria-label"],bS=["title","aria-label"],wS={key:0,class:"sd-find-replace__row"},CS={class:"sd-find-replace__field"},kS=["value","placeholder","aria-label"],SS={class:"sd-find-replace__nav sd-find-replace__nav--actions"},_S=["disabled","title"],AS=["disabled","title"],IS={key:1,class:"sd-find-replace__error",role:"alert"},ES={key:0,class:"sd-find-replace__row-indent","aria-hidden":"true"},TS={class:"sd-find-replace__error-text"},xS={__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=_e(()=>{const p=t.findReplace;return!!(!p.hasMatches?.value||p.replacePending?.value===!0||p.canReplace&&p.canReplace.value===!1)}),o=_e(()=>t.findReplace.ignoreDiacriticsSupported?.value!==!1),i=_e(()=>t.findReplace.replaceEnabled&&t.findReplace.replaceCanMutate?.value!==!1),s=_e(()=>t.findReplace.regexSupported?.value===!0),a=_e(()=>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(),g()}function c(){t.findReplace.goPrev(),g()}function d(){t.findReplace.close("user-closed")}function h(p){const v=[];let k=p?.parentElement??null;for(;k;){const _=k.ownerDocument?.defaultView?.getComputedStyle?.(k);if(_){const y=`${_.overflowY} ${_.overflowX}`;(y.includes("auto")||y.includes("scroll"))&&v.push(k)}k=k.parentElement}const C=p?.ownerDocument?.scrollingElement;return C&&!v.includes(C)&&v.push(C),v}function g(){const p=n.value;if(!p)return;const v=h(p).map(k=>({el:k,top:k.scrollTop,left:k.scrollLeft}));p.focus({preventScroll:!0});for(const{el:k,top:C,left:_}of v)k.scrollTop!==C&&(k.scrollTop=C),k.scrollLeft!==_&&(k.scrollLeft=_)}return Un(()=>{n.value?.focus(),t.findReplace.registerFocusFn(g)}),(p,v)=>(ge(),Ie("div",{class:"sd-find-replace",onKeydown:Qo(sn(d,["stop"]),["esc"])},[Oe("div",cS,[i.value?(ge(),Ie("button",{key:0,type:"button",class:an(["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:v[0]||(v[0]=k=>e.findReplace.showReplace.value=!e.findReplace.showReplace.value)},[...v[14]||(v[14]=[Oe("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true"},[Oe("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,uS)):mt("",!0),Oe("div",{class:an(["sd-find-replace__field",{"sd-find-replace__field--error":a.value}])},[v[15]||(v[15]=Oe("svg",{class:"sd-find-replace__search-icon",viewBox:"0 0 16 16",width:"15",height:"15","aria-hidden":"true"},[Oe("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)),Oe("input",{ref_key:"findInputRef",ref:n,value:e.findReplace.findQuery.value,onInput:v[1]||(v[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,dS),e.findReplace.findQuery.value&&!a.value?(ge(),Ie("span",fS,qt(e.findReplace.matchLabel.value),1)):mt("",!0),Oe("button",{type:"button",class:an(["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:v[2]||(v[2]=sn(()=>{},["prevent"])),onClick:v[3]||(v[3]=k=>e.findReplace.caseSensitive.value=!e.findReplace.caseSensitive.value)},qt(e.findReplace.texts.matchCaseLabel),43,hS),o.value?(ge(),Ie("button",{key:1,type:"button",class:an(["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:v[4]||(v[4]=sn(()=>{},["prevent"])),onClick:v[5]||(v[5]=k=>e.findReplace.ignoreDiacritics.value=!e.findReplace.ignoreDiacritics.value)},qt(e.findReplace.texts.ignoreDiacriticsLabel),43,pS)):mt("",!0),s.value?(ge(),Ie("button",{key:2,type:"button",class:an(["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:v[6]||(v[6]=sn(()=>{},["prevent"])),onClick:v[7]||(v[7]=k=>e.findReplace.regex.value=!e.findReplace.regex.value)},qt(e.findReplace.texts.regexLabel),43,mS)):mt("",!0)],2),Oe("div",gS,[Oe("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:v[8]||(v[8]=k=>c())},[...v[16]||(v[16]=[Oe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Oe("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,vS),Oe("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:v[9]||(v[9]=k=>u())},[...v[17]||(v[17]=[Oe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Oe("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,yS),v[19]||(v[19]=Oe("span",{class:"sd-find-replace__divider","aria-hidden":"true"},null,-1)),Oe("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},[...v[18]||(v[18]=[Oe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Oe("path",{d:"m4.5 4.5 7 7m0-7-7 7",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,bS)])]),e.findReplace.showReplace.value&&i.value?(ge(),Ie("div",wS,[v[20]||(v[20]=Oe("span",{class:"sd-find-replace__row-indent","aria-hidden":"true"},null,-1)),Oe("div",CS,[Oe("input",{value:e.findReplace.replaceText.value,onInput:v[10]||(v[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:v[11]||(v[11]=Qo(sn(k=>e.findReplace.replaceCurrent(),["prevent"]),["enter"]))},null,40,kS)]),Oe("div",SS,[Oe("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceLabel,onClick:v[12]||(v[12]=k=>e.findReplace.replaceCurrent())},qt(e.findReplace.texts.replaceLabel),9,_S),Oe("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceAllLabel,onClick:v[13]||(v[13]=k=>e.findReplace.replaceAll())},qt(e.findReplace.texts.replaceAllLabel),9,AS)])])):mt("",!0),a.value?(ge(),Ie("div",IS,[i.value?(ge(),Ie("span",ES)):mt("",!0),Oe("span",TS,qt(a.value),1)])):mt("",!0)],40,lS))}},RS=yn(xS,[["__scopeId","data-v-fed15bd3"]])}));Mt();var fr={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 TM(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 xM({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(""),g=ne(""),p=ne(!1),v=ne(!1),k=ne(!1),C=ne(!1),_=ne(0),y=ne(-1),w=ne(!0),x=ne(!1),P=ne(!0),N=ne(!1),G=ne(null);let R=fr;const F=_e(()=>h.value?_.value===0?R.noResultsLabel:`${y.value+1} of ${_.value}`:""),Z=_e(()=>_.value>0),D=_e(()=>Z.value&&!x.value&&w.value);let B=null,T=null;function V(W){return typeof W?.commands?.setSearchSession=="function"}function J(){try{const W=(typeof o=="function"?o():null)?.search;return W&&typeof W.search=="function"?W:null}catch{return null}}function q(W){W&&(_.value=typeof W.total=="number"?W.total:0,y.value=typeof W.activeIndex=="number"?W.activeIndex:-1,w.value=W.canReplace===!0,G.value=W.reason==="search-invalid-pattern"?R.invalidPatternLabel:null)}function se(){if(a){pe();return}if(s){if(!h.value){try{s.commands.clearSearchSession()}catch{}_.value=0,y.value=-1;return}try{const W=s.commands.setSearchSession(h.value,{caseSensitive:p.value,ignoreDiacritics:v.value,highlight:!0,searchModel:Te().includeDeletedText?"raw":"visible"});_.value=W.matches.length,y.value=W.activeMatchIndex}catch{}}}function pe(){const W=a;if(W){if(!h.value){try{W.clear()}catch{}_.value=0,y.value=-1,G.value=null;return}try{q(W.search(h.value,{caseSensitive:p.value,includeDeletedText:Te().includeDeletedText===!0,regex:k.value}))}catch{}}}function Ne(){B&&clearTimeout(B),B=setTimeout(se,150)}zt(h,()=>{c.value&&Ne()}),zt(p,()=>{c.value&&se()}),zt(v,()=>{c.value&&se()}),zt(k,()=>{c.value&&se()});let he=!0;function ye(){if(Z.value){if(a){try{a.next(),q(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.nextSearchMatch().activeMatchIndex}catch{}}}function ce(){if(Z.value){if(a){try{a.previous(),q(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.previousSearchMatch().activeMatchIndex}catch{}}}function ke(){if(he&&!x.value&&Z.value){if(a){if(!w.value)return;const W=a;x.value=!0;const te=aS(W,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let Y=null;try{Y=W.replace(g.value)}catch{}Y&&typeof Y.then=="function"?Promise.resolve(Y).then(te,te):te();return}if(s)try{const W=s.commands.replaceSearchMatch(g.value);_.value=W.matches.length,y.value=W.activeMatchIndex}catch{}}}function ie(){if(he&&!x.value&&Z.value){if(a){if(!w.value)return;const W=a;x.value=!0;const te=aS(W,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let Y=null;try{Y=W.replaceAll(g.value)}catch{}Y&&typeof Y.then=="function"?Promise.resolve(Y).then(te,te):te();return}if(s)try{s.commands.replaceAllSearchMatches(g.value),_.value=0,y.value=-1}catch{}}}function xe(){if(a){try{q(a.getSnapshot())}catch{}return}const W=TM(s);if(!W)return;const te=W.searchResults,Y=Array.isArray(te)?te.length:0,X=W.activeMatchIndex??-1;Y!==_.value&&(_.value=Y),X!==y.value&&(y.value=X)}function Je(){st(),T=setInterval(xe,200)}function st(){B&&clearTimeout(B),B=null,T&&clearInterval(T),T=null}function Tt(){h.value="",g.value="",p.value=!1,v.value=!1,k.value=!1,G.value=null,C.value=!1,_.value=0,y.value=-1,w.value=!0,x.value=!1}function Te(){const W=typeof r=="function"?r():void 0;if(W===!1||W==null)return{enabled:!1,texts:fr,replaceEnabled:!0};if(W===!0)return{enabled:!0,texts:fr,replaceEnabled:!0};const te=typeof W=="object"?W:{};if(te.component!=null&&typeof te.render=="function")throw new Error('modules.surfaces.findReplace cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{findPlaceholder:te.findPlaceholder??fr.findPlaceholder,findAriaLabel:te.findAriaLabel??fr.findAriaLabel,replacePlaceholder:te.replacePlaceholder??fr.replacePlaceholder,replaceAriaLabel:te.replaceAriaLabel??fr.replaceAriaLabel,noResultsLabel:te.noResultsLabel??fr.noResultsLabel,previousMatchLabel:te.previousMatchLabel??fr.previousMatchLabel,previousMatchAriaLabel:te.previousMatchAriaLabel??fr.previousMatchAriaLabel,nextMatchLabel:te.nextMatchLabel??fr.nextMatchLabel,nextMatchAriaLabel:te.nextMatchAriaLabel??fr.nextMatchAriaLabel,closeLabel:te.closeLabel??fr.closeLabel,closeAriaLabel:te.closeAriaLabel??fr.closeAriaLabel,replaceLabel:te.replaceLabel??fr.replaceLabel,replaceAllLabel:te.replaceAllLabel??fr.replaceAllLabel,toggleReplaceLabel:te.toggleReplaceLabel??fr.toggleReplaceLabel,toggleReplaceAriaLabel:te.toggleReplaceAriaLabel??fr.toggleReplaceAriaLabel,matchCaseLabel:te.matchCaseLabel??fr.matchCaseLabel,matchCaseAriaLabel:te.matchCaseAriaLabel??fr.matchCaseAriaLabel,regexLabel:te.regexLabel??fr.regexLabel,regexAriaLabel:te.regexAriaLabel??fr.regexAriaLabel,invalidPatternLabel:te.invalidPatternLabel??fr.invalidPatternLabel,ignoreDiacriticsLabel:te.ignoreDiacriticsLabel??fr.ignoreDiacriticsLabel,ignoreDiacriticsAriaLabel:te.ignoreDiacriticsAriaLabel??fr.ignoreDiacriticsAriaLabel},replaceEnabled:te.replaceEnabled??!0,includeDeletedText:te.includeDeletedText??!1,component:te.component,props:te.props,render:te.render,resolver:te.resolver,floating:te.floating&&typeof te.floating=="object"?te.floating:void 0}}function je(W,te){if(typeof W.resolver=="function"){const Y=W.resolver(te);if(Y!=null&&Y.type!=="default"){if(Y.type==="none")return{suppressed:!0};if(Y.type==="custom")return{component:Y.component,props:Y.props};if(Y.type==="external")return{render:Y.render}}}return W.component!=null?{component:W.component,props:W.props}:typeof W.render=="function"?{render:W.render}:{builtin:!0}}function Ye(W,te){return{findQuery:h,replaceText:g,caseSensitive:p,ignoreDiacritics:v,regex:k,showReplace:C,matchCount:_,activeMatchIndex:y,matchLabel:F,hasMatches:Z,canReplace:D,replaceCanMutate:w,replacePending:x,ignoreDiacriticsSupported:P,regexSupported:N,searchError:G,replaceEnabled:W.replaceEnabled??!0,texts:W.texts,goNext:ye,goPrev:ce,replaceCurrent:ke,replaceAll:ie,registerFocusFn:Y=>{d=Y},close:Y=>te(Y)}}function $(W){return{get findQuery(){return W.findQuery.value},set findQuery(te){W.findQuery.value=te},get replaceText(){return W.replaceText.value},set replaceText(te){W.replaceText.value=te},get caseSensitive(){return W.caseSensitive.value},set caseSensitive(te){W.caseSensitive.value=te},get ignoreDiacritics(){return W.ignoreDiacritics.value},set ignoreDiacritics(te){W.ignoreDiacritics.value=te},get regex(){return W.regex.value},set regex(te){W.regex.value=te},get regexSupported(){return W.regexSupported.value},get searchError(){return W.searchError.value},get replaceCanMutate(){return W.replaceCanMutate.value},get showReplace(){return W.showReplace.value},set showReplace(te){W.showReplace.value=te},get matchCount(){return W.matchCount.value},get activeMatchIndex(){return W.activeMatchIndex.value},get matchLabel(){return W.matchLabel.value},get hasMatches(){return W.hasMatches.value},get canReplace(){return W.canReplace.value},get replacePending(){return W.replacePending.value},get ignoreDiacriticsSupported(){return W.ignoreDiacriticsSupported.value},replaceEnabled:W.replaceEnabled,texts:W.texts,goNext:W.goNext,goPrev:W.goPrev,replaceCurrent:W.replaceCurrent,replaceAll:W.replaceAll,registerFocusFn:W.registerFocusFn,close:W.close}}function S(W){if(W){if(typeof W?.commands?.clearSearchSession=="function"){try{W.commands.clearSearchSession()}catch{}return}if(a&&W===s)try{a.clear()}catch{}}}function ee(){try{if(l||!e()||!t())return!1;if(i&&c.value)return!0;const W=Te();if(!W.enabled||je(W,{texts:W.texts,replaceEnabled:W.replaceEnabled??!0}).suppressed)return!1;if(!V(t())){const te=J();if(!te)return!1;try{if(te.getSnapshot?.().available!==!0)return!1}catch{return!1}}return!0}catch{return!1}}async function O(){if(l)return;const W=e();if(W){if(i&&c.value){d?.();return}if(!u){u=!0;try{const te=t();if(!te){u=!1;return}const Y=Te();if(!Y.enabled){u=!1;return}const X=je(Y,{texts:Y.texts,replaceEnabled:Y.replaceEnabled??!0});if(X.suppressed){u=!1;return}Tt(),R=Y.texts,he=Y.replaceEnabled??!0;const be={placement:"top-right",autoFocus:!0,width:420,...Y.floating??{}};if(s&&s!==te&&S(s),s=te,a=V(te)?null:J(),P.value=!a,N.value=!!a,a)try{q(a.getSnapshot())}catch{}d=null;let ve=()=>{};const we=Ye(Y,at=>ve(at));let Be;if(X.component)Be=W.open({mode:"floating",ariaLabel:Y.texts.findAriaLabel,closeOnEscape:!0,floating:be,component:Xr(X.component),props:{...X.props,findReplace:we}});else if(X.render){const at=X.render;Be=W.open({mode:"floating",ariaLabel:Y.texts.findAriaLabel,closeOnEscape:!0,floating:be,render:Ct=>at({container:Ct.container,findReplace:$(we),resolve:Ct.resolve,close:Ct.close,surfaceId:Ct.surfaceId,mode:Ct.mode})})}else{let at;try{at=(await Promise.resolve().then(()=>(EM(),IM))).default}catch{u=!1;return}if(l||i&&c.value){u=!1;return}const Ct=t()||te;s!==Ct&&(S(s),s=Ct,a=V(Ct)?null:J(),P.value=!a),Be=W.open({mode:"floating",ariaLabel:Y.texts.findAriaLabel,component:Xr(at),closeOnEscape:!0,floating:be,props:{findReplace:we}})}ve=at=>Be.close(at??"programmatic"),i=Be,c.value=!0,u=!1,Je();const rt=Be.id;Be.result.then(()=>{i?.id===rt?(st(),S(s),i=null,c.value=!1,d=null):S(te!==s?te:null)})}catch(te){throw u=!1,te}}}}function j(){i&&i.close("programmatic")}n&&zt(n,(W,te)=>{!c.value||!i||W!==te&&(S(te),j())});function U(){l=!0,st(),j(),s=null,a=null,d=null}return{open:O,close:j,isOpen:c,wouldOpen:ee,destroy:U}}var yf=null;function w0(e){e!=null&&(yf=e)}function RM(e){yf===e&&(yf=null)}function MM(e){return yf===null||yf===e}function LM(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)&&MM(n)}var PM=/^(https?|mailto|tel):/i,DM=/^(javascript|data|vbscript):/i,OM=/^[a-z][a-z0-9+.-]*:/i;function FM(e){if(typeof e!="string")return null;const t=e.trim();return t?t.startsWith("#")?{href:t}:DM.test(t)?null:OM.test(t)?PM.test(t)?{href:t}:null:{href:t}:null}var NM='<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>',BM='<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>',zM='<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>',MS='<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 v?v.split(/\n{2,}/).map(k=>`<p>${c(k).replace(/\n/g,"<br>")}</p>`).join(""):"<p></p>"},g=_e({get:()=>d(o.value),set:p=>{o.value=h(p)}});return Un(u),zt(o,u),t({focus:a}),(p,v)=>(ge(),Ie("div",q7,[e.includeHeader?(ge(),vn(f0,{key:0,config:e.config,comment:e.comment,"is-pending-input":!0},null,8,["config","comment"])):mt("",!0),Oe("div",{class:an(["comment-entry",{"sd-input-active":e.isFocused}])},[Ws(Oe("textarea",{ref_key:"inputRef",ref:i,class:"superdoc-field",placeholder:"Add a comment","onUpdate:modelValue":v[0]||(v[0]=k=>g.value=k),rows:"1",onInput:l,onFocus:v[1]||(v[1]=k=>s(!0)),onBlur:v[2]||(v[2]=k=>s(!1))},null,544),[[Ei,g.value]])],2)]))}},p0=yn(Y7,[["__scopeId","data-v-cc54b489"]]);Mt(),Cn();var X7=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Z7={key:0,class:"existing-internal-input"},Q7={class:"new-comment-input-wrapper"},J7={class:"reply-actions"},$7=["disabled"],eR={key:0,class:"resolved-badge"},tR=["innerHTML"],nR={key:1,class:"existing-internal-input"},rR={key:0,class:"card-section comment-body"},oR=["data-track-change-semantic-color-key"],iR={key:0},sR={class:"change-type tracked-change-label"},aR={key:0,class:"tracked-change-detail-lines"},lR={key:0,class:"tracked-change-text"},cR={key:1,class:"change-type"},uR={class:"change-type"},dR={key:1},fR={class:"tracked-change-text is-inserted"},hR={key:2},pR={class:"tracked-change-text is-inserted"},mR={key:3},gR={key:4},vR={key:5},yR={key:6},bR={class:"tracked-change-text"},wR={key:7},CR={class:"tracked-change-text is-deleted"},kR={class:"tracked-change-text is-inserted"},SR={key:8},_R={class:"tracked-change-text is-deleted"},AR={key:9},IR={class:"tracked-change-text is-inserted"},ER=["data-track-change-image-preview-role"],TR=["src","alt"],xR={key:1,class:"card-section comment-body"},RR=["innerHTML"],MR={key:1,class:"comment"},LR={key:2,class:"reply-expanded"},PR={class:"reply-input-wrapper"},DR={class:"reply-actions"},OR=["onClick"],FR=["onClick","disabled","data-disabled-reason"],NR={class:"collapsed-avatars"},BR={key:3,class:"comment-separator"},zR={key:2,class:"tracked-change-decision-alert",role:"alert"},VR={class:"tracked-change-decision-alert__message"},HR=["disabled","data-disabled-reason"],UR={key:1,class:"reply-expanded"},jR={class:"reply-input-wrapper"},GR={class:"reply-actions"},WR=["disabled","data-disabled-reason"],Fp=3,Lk=90,KR={__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}=ur(),i=vu(),s=ca(),{addComment:a,cancelComment:l,deleteComment:u,getCommentAliasIds:c,removePendingComment:d,getCommentDocumentId:h,requestInstantSidebarAlignment:g,resolveCommentPositionEntry:p,clearInstantSidebarAlignment:v,setActiveFloatingCommentInstance:k}=s,{suppressInternalExternal:C,getConfig:_,activeComment:y,activeFloatingCommentInstanceId:w,floatingCommentsOffset:x,pendingComment:P,currentCommentText:N,isDebugging:G,editingCommentId:R,editorCommentPositions:F,isCommentHighlighted:Z}=ea(s),D=ne(!0),B=ne(null),T=ne(new Map),V=ne(null),J=[[0,0],[-Fp,0],[Fp,0],[0,-Fp],[0,Fp]],q=Se=>{const Ve=typeof Se?.width=="number"&&Number.isFinite(Se.width)?Se.width:null,_t=typeof Se?.height=="number"&&Number.isFinite(Se.height)?Se.height:null;if(!Ve||!_t||Ve<=0||_t<=0)return{};const lt=Math.min(Lk/Ve,Lk/_t,1);return{width:`${Math.max(1,Math.round(Ve*lt))}px`,height:`${Math.max(1,Math.round(_t*lt))}px`}},se=[".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(","),pe=Se=>Ve=>{Se&&(Ve?(T.value.set(Se,Ve),R.value===Se&&It(()=>{ye(Se)})):T.value.delete(Se))},Ne=(Se,Ve,_t)=>{const lt=Se?.getBoundingClientRect?.();return!lt||![lt.left,lt.top,lt.right,lt.bottom].every(Number.isFinite)||lt.width<=0||lt.height<=0?!1:J.some(([Ln,Bn])=>{const sr=Ve+Ln,Sr=_t+Bn;return sr>=lt.left&&sr<=lt.right&&Sr>=lt.top&&Sr<=lt.bottom})},he=(Se,Ve)=>{if(!Number.isFinite(Se)||!Number.isFinite(Ve))return null;const _t=document.querySelectorAll(se);for(const lt of _t)if(lt instanceof HTMLElement&&Ne(lt,Se,Ve))return lt;return null},ye=Se=>{T.value.get(Se)?.focus?.()},ce=ne(null),ke=Se=>Se.resolvedTime?Se.commentId:Se.importedId||Se.commentId,ie=Se=>Se?Se.trackedChange&&Se.importedId!=null?String(Se.importedId):Se.commentId!=null?String(Se.commentId):null:null,xe=(Se,Ve)=>{const _t=Se?.bounds?.[Ve];return Number.isFinite(_t)?_t:null},Je=(Se,Ve)=>{if(!Se||!Ve||Se.pageIndex!==Ve.pageIndex)return!1;const _t=xe(Se,"top"),lt=xe(Ve,"top");return _t!=null&<!=null&&Math.abs(_t-lt)<.5},st=(Se,Ve)=>{const _t=xe(Se,"left"),lt=xe(Ve,"left"),Ln=xe(Se,"right"),Bn=xe(Ve,"right");return[_t,lt,Ln,Bn].some(sr=>sr==null)?!1:lt<Ln&&_t<Bn},Tt=(Se,Ve)=>{const _t=Se?.start,lt=Se?.end,Ln=Ve?.start,Bn=Ve?.end;return[_t,lt,Ln,Bn].every(Number.isFinite)?Ln<=lt&&_t<=Bn:!1},Te=(Se,Ve)=>!Se||!Ve||Se.kind&&Ve.kind&&Se.kind!==Ve.kind||Se.storyKey&&Ve.storyKey&&Se.storyKey!==Ve.storyKey?!1:Ve.start===Se.start&&Ve.end===Se.end?!0:Je(Se,Ve)&&st(Se,Ve)&&Tt(Se,Ve),je=Se=>{const Ve=new Set(c(Se)),{key:_t,entry:lt}=p(Se);return _t&&Ve.add(_t),lt?(Object.entries(F.value??{}).forEach(([Ln,Bn])=>{Te(lt,Bn)&&Ve.add(Ln)}),[...Ve]):[...Ve]},Ye=(Se,Ve,_t=24)=>{if(!Number.isFinite(Ve)||typeof Se?.getBoundingClientRect!="function")return!1;const lt=Se.getBoundingClientRect().top;return Number.isFinite(lt)&&Math.abs(lt-Ve)<=_t},$=_e(()=>r.floatingInstanceId??r.comment.commentId??null),S=_e(()=>typeof r.isFloatingInstanceActive=="boolean"?r.isFloatingInstanceActive:y.value!==r.comment.commentId?!1:r.floatingInstanceId==null?!0:w.value===r.floatingInstanceId),ee=_e(()=>r.comment.resolvedTime?r.comment.trackedChange?r.comment.trackedChangeDecision==="reject"?"Rejected":"Accepted":"Resolved":null),O=_e(()=>P.value&&P.value.commentId===r.comment.commentId),j=_e(()=>Se=>{const Ve=et.value;return U.value&&Se===Ve.length-1?!0:Ve.length>1&&Se!==Ve.length-1}),U=_e(()=>!_.readOnly&&S.value&&!r.comment.resolvedTime&&!Mn.value),W=()=>({ok:!1,reason:"read-only-document"}),te=()=>_.value?.readOnly===!0,Y=ne(!1),X=ne(!1),be=()=>{if(te())return W();if(Nn.value)return{ok:!1,reason:kn.value?.reason??"v2-write-unavailable"};Y.value=!0,It(()=>{B.value?.focus?.(),n("resize")})},ve=_e(()=>{const Se=r.comment;return Se.trackedChange?s.getTrackedChangeThread(Se):s.commentsList.filter(Ve=>{const _t=Ve.parentCommentId===Se.commentId,lt=Ve.commentId===Se.commentId;return _t||lt}).sort((Ve,_t)=>Ve.commentId===Se.commentId?-1:_t.commentId===Se.commentId?1:Ve.createdTime-_t.createdTime)}),we=ne(!1),Be=ne(null),rt=ne(!1),at=_e(()=>!we.value),Ct=_e(()=>({"is-truncated":at.value,"is-scrollable":we.value&&rt.value})),en=()=>{we.value=!we.value,It(()=>n("resize"))},Et=Se=>{Be.value=Se??null},Ut=()=>{if(we.value)return;const Se=Be.value;if(!Se){rt.value=!1;return}rt.value=Se.scrollHeight>Se.clientHeight+1};zt(Be,()=>{It(Ut)});const Wt=()=>R.value?ve.value.some(Se=>Se.commentId===R.value):!1;zt(S,Se=>{Se||((Y.value||Wt())&&(N.value="",R.value=null),we.value=!1,In.value=!1,Y.value=!1,It(()=>n("resize")))});const In=ne(!1),bt=_e(()=>ve.value.slice(1)),nn=_e(()=>In.value?!1:bt.value.length>=2),et=_e(()=>nn.value?[ve.value[0],bt.value[bt.value.length-1]].filter(Boolean):ve.value);zt(_e(()=>{const Se=et.value[0];return Se?JSON.stringify({commentId:Se.commentId,commentText:Se.commentText,trackedChange:Se.trackedChange,trackedChangeText:Se.trackedChangeText,deletedText:Se.deletedText,trackedChangeLabel:Se.trackedChangeLabel,trackedChangeDisplayType:Se.trackedChangeDisplayType,trackedChangeDetailLines:Se.trackedChangeDetailLines}):""}),()=>{It(Ut)});const Pt=_e(()=>nn.value?bt.value.length-1:0),Kt=_e(()=>{if(!nn.value)return[];const Se=bt.value.slice(0,-1),Ve=new Set;return Se.map(_t=>typeof _t.getCommentUser=="function"?_t.getCommentUser():{name:_t.creatorName,email:_t.creatorEmail||_t.email}).filter(_t=>{if(!_t)return!1;const lt=_t.email||_t.name;return Ve.has(lt)?!1:(Ve.add(lt),!0)}).slice(0,3)}),Rn=()=>{In.value=!0,We(),It(()=>n("resize"))},Nt=_e(()=>r.comment.resolvedTime?!0:_.value.readOnly),un=_e(()=>Se=>S.value&&R.value===Se.commentId),Mn=_e(()=>!R.value||!S.value?!1:ve.value.some(Se=>Se.commentId===R.value)),Pe=_e(()=>_.value.readOnly||!o.$superdoc.config.isInternal||yt.value?!1:!C.value&&!r.comment.trackedChange),Ge=_e(()=>N.value&&N.value!=="<p></p>"),We=async()=>{const Se=o.$superdoc.activeEditor,Ve=Se?.editorVersion===2?Se?.v2Comments??null:null,_t=!!r.comment?.trackedChange,lt=f7(),Ln=r.floatingInstanceId!=null,Bn=ce.value?.getBoundingClientRect?.().top,sr=!r.comment.resolvedTime&&(y.value!==r.comment.commentId||Ln&&$.value!==w.value);let Sr=lt;if(Ve){const wo=!_t&&!r.comment.resolvedTime&&String(r.comment?.trackedChangeParentId??"").trim()?r.comment.trackedChangeParentId:null,Co=Se?.editorVersion===2&&(_t||wo!=null)?Se?.v2TrackedChanges??null:null,mi=wo!=null?s.getComment(wo):null,co=_t?r.comment:mi?.trackedChange?mi:wo;let pr=await(Co?Co.focusTrackedChange(co):Ve.focusComment(r.comment));return!_t&&pr?.reason==="tracked-change-anchor-not-found"&&(pr=await Ve.focusComment(r.comment)),pr?.ok?(r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId)),sr&&!Ln?g(lt,r.comment.commentId,r.floatingInstanceId??null):sr&&Number.isFinite(Bn)?g(Bn,r.comment.commentId,r.floatingInstanceId):v(),pr):(v(),pr)}if(Se){const{entry:wo}=p(r.comment),Co=r.floatingPositionEntry??wo,mi=Number.isFinite(r.floatingPageIndex)&&r.comment?.trackedChangeStory?.storyType==="headerFooterPart",co=Ek(r.parent,Co),pr=mi?null:h7(je(r.comment)),hl=Number.isFinite(pr)?pr:co,Ca=Ye(ce.value,hl),gi=ke(r.comment),zr=null;let ni=null;if(_t)if(r.comment.trackedChangeStory&&(r.comment.trackedChangeStory,{...Number.isFinite(r.floatingPageIndex)?{pageIndex:r.floatingPageIndex}:{}}),r.comment.resolvedTime)Se.commands?.setCursorById(gi);else{const ko=r.comment.commentId;Se.commands?.setCursorById(gi,{activeCommentId:ko})||Se.commands?.setActiveComment({commentId:ko})}else{if(r.comment.resolvedTime)Se.commands?.setCursorById(gi);else{const Mi=r.comment.commentId;Se.commands?.setCursorById(gi,{activeCommentId:Mi})||Se.commands?.setActiveComment({commentId:Mi})}const ko=r.comment.commentId;ni=Ca?null:p7(zr,gi,ko,lt)}Number.isFinite(pr)?Sr=pr:Number.isFinite(co)?Sr=co:Number.isFinite(ni)&&(Sr=ni)}sr&&!Ln?r.floatingInstanceId?g(Sr,r.comment.commentId,r.floatingInstanceId):g(Sr,r.comment.commentId):v(),r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId))},ft=Se=>{const Ve=Se.target instanceof Element?Se.target:Se.target?.parentElement,_t=document.elementFromPoint(Se.clientX,Se.clientY);if(!(Ve?.closest?.(se)||_t?.closest?.(se)||he(Se.clientX,Se.clientY)||Z.value)&&!(Se.target.closest?.(".comments-dialog")&&!ce.value?.contains(Se.target))){if(O.value){l(o.$superdoc);return}S.value&&(x.value=0,n("dialog-exit"),y.value=null,s.setActiveComment(o.$superdoc,y.value),Z.value=!1)}},Vt=async()=>{if(te())return W();if(Nn.value)return{ok:!1,reason:kn.value?.reason??"v2-write-unavailable"};if(yt.value&&$t.value&&!O.value){if(X.value)return{ok:!1,reason:"reply-submit-in-flight"};X.value=!0;try{const _t=await s.replyCommentV2({superdoc:o.$superdoc,parentCommentId:ie(r.comment),text:N.value});return _t?.ok?(Y.value=!1,N.value="",It(()=>n("resize")),_t):(It(()=>n("resize")),_t)}finally{X.value=!1}}const Se={documentId:r.comment.fileId,isInternal:P.value?P.value.isInternal:D.value,parentCommentId:P.value?null:r.comment.commentId};P.value&&(Se.selection=P.value.selection.getValues());const Ve=s.getPendingComment(Se);!P.value&&N.value&&Ve.setText({text:N.value,suppressUpdate:!0}),Promise.resolve(a({superdoc:o.$superdoc,comment:Ve})).finally(()=>{Y.value=!1,It(()=>n("resize"))})},yt=_e(()=>o.$superdoc?.activeEditor?.editorVersion===2),$t=_e(()=>yt.value?o.$superdoc?.activeEditor?.v2Comments??null:null),At=_e(()=>yt.value?o.$superdoc?.activeEditor?.v2TrackedChanges??null:null),kn=_e(()=>{if(!$t.value)return null;const Se=s.viewingVisibility.documentMode,Ve=$t.value.getCapabilityState?.()??null;return Se==="viewing"?{...Ve??{},canWrite:!1,reason:"review-surface-read-only"}:Ve}),Nn=_e(()=>{if(!yt.value)return!1;const Se=kn.value;return Se?Se.canWrite===!1:!1}),Uo=_e(()=>X.value?"reply-submit-in-flight":Nn.value?kn.value?.reason??"v2-write-unavailable":null),Ht=_e(()=>{if(!At.value)return null;const Se=s.viewingVisibility.documentMode,Ve=At.value.getCapabilityState?.()??null;return Se==="viewing"&&Ve?.canDecide!==!1?{canDecide:!1,reason:"review-surface-read-only"}:Ve}),Pn=Se=>{if(yt.value&&Se?.trackedChange){if(!At.value)return"v2-tracked-change-adapter-missing";const Ve=Ht.value;return Ve&&Ve.canDecide===!1?Ve.reason??"v2-tracked-change-unavailable":null}return Nn.value?kn.value?.reason??"v2-write-unavailable":null},br=Se=>{if(yt.value&&Se?.trackedChange){if(!At.value)return"v2-tracked-change-adapter-missing";const Ve=Ht.value;return Ve&&Ve.canDecide===!1?Ve.reason??"v2-tracked-change-unavailable":null}return Nn.value?kn.value?.reason??"v2-write-unavailable":null},Do=()=>yt.value?$t.value?_.value?.readOnly?"read-only-document":Nn.value?kn.value?.reason??"v2-write-unavailable":null:"v2-comments-adapter-missing":null,er=_e(()=>!yt.value||!Nn.value?null:kn.value?.reason??"v2-write-unavailable"),cn=(Se,Ve)=>{V.value={decision:Se,reason:Ve?.reason??null},It(()=>n("resize"))},Gn=()=>{V.value&&(V.value=null,It(()=>n("resize")))},Br=_e(()=>{const Se=V.value;if(!Se)return null;const Ve=Se.decision==="reject"?"reject":"accept";return Se.reason==="stale-catalog"?`Couldn't ${Ve} this change because the review list is stale.`:`Couldn't ${Ve} this change.`}),ei=()=>{const Se=V.value;if(Se){if(V.value=null,Se.decision==="reject"){bo();return}Jr()}},bo=async()=>{if(te())return W();const Se=o.$superdoc.config.onTrackedChangeBubbleReject;if(r.comment.trackedChange){if(yt.value){const _t=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});if(!_t?.ok||_t.success===!1){cn("reject",_t);return}Gn(),typeof Se=="function"&&Se(r.comment,o.$superdoc.activeEditor),It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Ve=!0;if(typeof Se=="function")Se(r.comment,o.$superdoc.activeEditor);else{const _t=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});Ve=!!_t?.ok&&_t.success!==!1}Ve&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"reject"})}else if(yt.value&&$t.value){if(!(await s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId});It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Jr=async()=>{if(te())return W();if(!r.comment.trackedChange&&_.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};const Se=o.$superdoc.config.onTrackedChangeBubbleAccept;if(r.comment.trackedChange&&yt.value){const _t=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});if(!_t?.ok||_t.success===!1){cn("accept",_t);return}Gn(),typeof Se=="function"&&Se(r.comment,o.$superdoc.activeEditor),It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let Ve=!0;if(r.comment.trackedChange&&typeof Se=="function")Se(r.comment,o.$superdoc.activeEditor);else if(r.comment.trackedChange){const _t=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});Ve=!!_t?.ok&&_t.success!==!1}else if(yt.value&&$t.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&&!yt.value&&Ve&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"accept"}),It(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Xi=async()=>{if(te())return W();if(_.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};!yt.value||!$t.value||(await s.reopenCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok&&It(()=>{s.lastUpdate=new Date,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Ri=(Se,Ve)=>{if(te())return W();switch(Se){case"edit":N.value=Ve?.commentText?.value??Ve?.commentText??"",y.value=r.comment.commentId,r.floatingInstanceId&&k(r.floatingInstanceId),R.value=Ve.commentId,s.setActiveComment(o.$superdoc,y.value),It(()=>{ye(Ve.commentId)});break;case"delete":u({superdoc:o.$superdoc,commentId:Ve.commentId});break}},ba=async Se=>{if(te())return W();if(yt.value&&$t.value){const Ve=await s.editCommentV2({superdoc:o.$superdoc,commentId:Se.commentId,text:N.value});return Ve?.ok&&(R.value=null,d(o.$superdoc)),Ve}R.value=null,Se.setText({text:N.value,superdoc:o.$superdoc}),d(o.$superdoc)},ti=Se=>{if(te())return W();const Ve=!!P.value,_t=Se.toLowerCase()==="internal";Ve?P.value.isInternal=_t:r.comment.setIsInternal({isInternal:_t,superdoc:o.$superdoc})},wa=_e(()=>{const Se={};return(S.value||O.value||Mn.value)&&(Se.zIndex=50),Se}),uc=Se=>typeof Se=="string"?new Date(Se).getTime():Se,Oo=Se=>{R.value=null,Y.value=!1,l(o.$superdoc)},jo=_e(()=>{const Se=o.$superdoc.users;return r.comment.isInternal===!0?Se.filter(Ve=>Ve.access?.role==="internal"):Se});return Un(()=>{r.autoFocus&&It(()=>We()),O.value&&It(()=>{B.value?.focus?.()}),It(()=>{n("ready",{commentId:r.floatingInstanceId??(r.comment.importedId!==void 0?r.comment.importedId:r.comment.commentId),elementRef:ce}),Ut()})}),zt(U,Se=>{Se&&It(()=>{B.value?.focus?.()})},{immediate:!0}),zt(R,Se=>{if(!Se||!S.value)return;const Ve=ve.value.find(_t=>_t.commentId===Se);!Ve||Ve.trackedChange||It(()=>{ye(Se)})}),zt(()=>_.value?.readOnly===!0,Se=>{Se&&(Y.value=!1,ve.value.some(Ve=>Ve.commentId===R.value)&&(R.value=null),O.value&&l(o.$superdoc),It(()=>n("resize")))},{immediate:!0}),zt(Nn,Se=>{Se&&(Y.value=!1,It(()=>n("resize")))}),(Se,Ve)=>{const _t=t1("click-outside");return Ws((ge(),Ie("div",{class:an(["comments-dialog",{"is-active":S.value||O.value,"is-resolved":r.comment.resolvedTime}]),onClick:sn(We,["stop","prevent"]),style:Sn(wa.value),ref_key:"commentDialogElement",ref:ce,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:""},[O.value?(ge(),Ie(Jt,{key:0},[Pe.value?(ge(),Ie("div",Z7,[Zt(xk,{onClick:Ve[0]||(Ve[0]=sn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":!1,state:$e(P).isInternal?"internal":"external",onSelect:ti},null,8,["state"])])):mt("",!0),Zt(f0,{config:$e(_),comment:r.comment,"is-pending-input":!0},null,8,["config","comment"]),Oe("div",Q7,[Zt(p0,{ref_key:"commentInput",ref:B,users:jo.value,config:$e(_),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Oe("div",J7,[Oe("button",{class:"sd-button reply-btn-cancel",onClick:sn(Oo,["stop","prevent"])},"Cancel"),Oe("button",{class:an(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ge.value}]),onClick:sn(Vt,["stop","prevent"]),disabled:!Ge.value}," Comment ",10,$7)])],64)):(ge(),Ie(Jt,{key:1},[ee.value?(ge(),Ie("div",eR,[Oe("span",{class:"resolved-badge__icon",innerHTML:$e(ua).markDone},null,8,tR),Fi(" "+qt(ee.value),1)])):mt("",!0),Pe.value?(ge(),Ie("div",nR,[Zt(xk,{onClick:Ve[1]||(Ve[1]=sn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":Nt.value,state:e.comment.isInternal?"internal":"external",onSelect:ti},null,8,["is-disabled","state"])])):mt("",!0),(ge(!0),Ie(Jt,null,lr(et.value,(lt,Ln)=>(ge(),Ie("div",{key:lt.commentId,class:"conversation-item"},[Zt(f0,{config:$e(_),timestamp:uc(lt.createdTime),comment:lt,"is-active":S.value,"resolve-disabled-reason":Pn(lt),"reject-disabled-reason":br(lt),"reopen-supported":yt.value&&!!$t.value,"reopen-disabled-reason":Do(),"write-disabled-reason":er.value,onResolve:Jr,onReject:bo,onReopen:Xi,onOverflowSelect:Bn=>Ri(Bn,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?(ge(),Ie("div",rR,[Oe("div",{class:an(["tracked-change",Ln===0?Ct.value:void 0]),"data-track-change-semantic-color-key":lt.semanticColorKey??void 0,ref_for:!0,ref:Ln===0?Et:void 0},[lt.trackedChangeLabel?(ge(),Ie("div",iR,[Oe("span",sR,qt(lt.trackedChangeLabel),1),lt.trackedChangeDetailLines&<.trackedChangeDetailLines.length?(ge(),Ie("div",aR,[(ge(!0),Ie(Jt,null,lr(lt.trackedChangeDetailLines,(Bn,sr)=>(ge(),Ie("div",{key:sr,class:"tracked-change-detail-line"},[Bn.excerpt?(ge(),Ie("span",lR,'"'+qt(Bn.excerpt)+'"',1)):mt("",!0),Bn.excerpt?(ge(),Ie("span",cR," — ")):mt("",!0),Oe("span",uR,qt(Bn.label),1)]))),128))])):mt("",!0)])):lt.trackedChangeDisplayType==="hyperlinkAdded"?(ge(),Ie("div",dR,[Ve[2]||(Ve[2]=Oe("span",{class:"change-type"},"Added hyperlink ",-1)),Oe("span",fR,'"'+qt(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="hyperlinkModified"?(ge(),Ie("div",hR,[Ve[3]||(Ve[3]=Oe("span",{class:"change-type"},"Changed hyperlink to ",-1)),Oe("span",pR,'"'+qt(lt.trackedChangeText)+'"',1)])):lt.trackedChangeDisplayType==="paragraphSplit"?(ge(),Ie("div",mR,[...Ve[4]||(Ve[4]=[Oe("span",{class:"change-type"},"Added new line",-1)])])):lt.trackedChangeDisplayType==="tableInsert"?(ge(),Ie("div",gR,[...Ve[5]||(Ve[5]=[Oe("span",{class:"change-type"},"Added table",-1)])])):lt.trackedChangeDisplayType==="tableDelete"?(ge(),Ie("div",vR,[...Ve[6]||(Ve[6]=[Oe("span",{class:"change-type"},"Deleted table",-1)])])):lt.trackedChangeType==="trackFormat"?(ge(),Ie("div",yR,[Ve[7]||(Ve[7]=Oe("span",{class:"change-type"},"Format: ",-1)),Oe("span",bR,qt(lt.trackedChangeText),1)])):lt.trackedChangeType==="both"?(ge(),Ie("div",wR,[Ve[8]||(Ve[8]=Oe("span",{class:"change-type"},"Replaced ",-1)),Oe("span",CR,'"'+qt(lt.deletedText)+'"',1),Ve[9]||(Ve[9]=Oe("span",{class:"change-type"}," with ",-1)),Oe("span",kR,'"'+qt(lt.trackedChangeText)+'"',1)])):lt.deletedText?(ge(),Ie("div",SR,[Ve[10]||(Ve[10]=Oe("span",{class:"change-type"},"Deleted ",-1)),Oe("span",_R,'"'+qt(lt.deletedText)+'"',1)])):lt.trackedChangeText?(ge(),Ie("div",AR,[Ve[11]||(Ve[11]=Oe("span",{class:"change-type"},"Added ",-1)),Oe("span",IR,'"'+qt(lt.trackedChangeText)+'"',1)])):mt("",!0),lt.trackedChangeImagePreview?.src?(ge(),Ie("div",{key:10,class:"tracked-change-image-preview","data-track-change-image-preview-role":lt.trackedChangeImagePreview.role??void 0},[Oe("img",{class:"tracked-change-image-preview__image",src:lt.trackedChangeImagePreview.src,alt:lt.trackedChangeImagePreview.alt||"Tracked image preview",style:Sn(q(lt.trackedChangeImagePreview)),loading:"lazy",decoding:"async"},null,12,TR)],8,ER)):mt("",!0)],10,oR),at.value&&rt.value&&Ln===0?(ge(),Ie("div",{key:0,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show more ")):mt("",!0),we.value&&rt.value&&Ln===0?(ge(),Ie("div",{key:1,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show less ")):mt("",!0)])):mt("",!0),lt.trackedChange?mt("",!0):(ge(),Ie("div",xR,[!$e(G)&&!un.value(lt)?(ge(),Ie("div",{key:0,class:an(["comment",Ln===0?Ct.value:void 0]),ref_for:!0,ref:Ln===0?Et:void 0,innerHTML:lt.commentText},null,10,RR)):$e(G)&&!un.value(lt)?(ge(),Ie("div",MR,qt($e(F)[lt.importedId!==void 0?lt.importedId:lt.commentId]?.bounds),1)):(ge(),Ie("div",LR,[Oe("div",PR,[Zt(p0,{ref_for:!0,ref:pe(lt.commentId),users:jo.value,config:$e(_),"include-header":!1,comment:lt},null,8,["users","config","comment"])]),Oe("div",DR,[Oe("button",{class:"sd-button reply-btn-cancel",onClick:sn(Bn=>Oo(lt),["stop","prevent"])},"Cancel",8,OR),Oe("button",{class:an(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ge.value||Nn.value}]),onClick:sn(Bn=>ba(lt),["stop","prevent"]),disabled:!Ge.value||Nn.value,"data-disabled-reason":Nn.value?kn.value?.reason??null:null}," Update ",10,FR)])])),at.value&&rt.value&&Ln===0&&!un.value(lt)?(ge(),Ie("div",{key:3,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show more ")):mt("",!0),we.value&&rt.value&&Ln===0&&!un.value(lt)?(ge(),Ie("div",{key:4,class:"show-more-toggle",onClick:sn(en,["stop","prevent"])}," Show less ")):mt("",!0)])),nn.value&&Ln===0?(ge(),Ie(Jt,{key:2},[Ve[12]||(Ve[12]=Oe("div",{class:"comment-separator"},null,-1)),Oe("div",{class:"collapsed-replies",onClick:sn(Rn,["stop","prevent"])},[Oe("div",NR,[(ge(!0),Ie(Jt,null,lr(Kt.value,Bn=>(ge(),vn(Rk,{key:Bn.email||Bn.name,user:Bn,class:"mini-avatar"},null,8,["user"]))),128))]),Oe("span",null,qt(Pt.value)+" more "+qt(Pt.value===1?"reply":"replies"),1)])],64)):mt("",!0),j.value(Ln)?(ge(),Ie("div",BR)):mt("",!0)]))),128)),V.value?(ge(),Ie("div",zR,[Oe("span",VR,qt(Br.value),1),Oe("button",{type:"button",class:"sd-button tracked-change-decision-alert__retry",onClick:sn(ei,["stop","prevent"])}," Retry ")])):mt("",!0),U.value&&!$e(_).readOnly?(ge(),Ie(Jt,{key:3},[Y.value?(ge(),Ie("div",UR,[Oe("div",jR,[Zt(p0,{ref_key:"commentInput",ref:B,users:jo.value,config:$e(_),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Oe("div",GR,[Oe("button",{class:"sd-button reply-btn-cancel",onClick:sn(Oo,["stop","prevent"])},"Cancel"),Oe("button",{class:an(["sd-button primary reply-btn-primary",{"sd-is-disabled":!Ge.value||Nn.value||X.value}]),onClick:sn(Vt,["stop","prevent"]),disabled:!Ge.value||Nn.value||X.value,"data-disabled-reason":Uo.value}," Reply ",10,WR)])])):(ge(),Ie("button",{key:0,type:"button",class:an(["reply-pill",{"sd-is-disabled":Nn.value}]),onClick:sn(be,["stop","prevent"]),disabled:Nn.value,"data-disabled-reason":Nn.value?kn.value?.reason??null:null}," Reply or add others with @ ",10,HR))],64)):mt("",!0)],64))],14,X7)),[[_t,ft]])}}},Np=yn(KR,[["__scopeId","data-v-f26decd0"]]);Mt(),Cn();var qR={class:"comments-list"},YR={key:0},XR=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],ZR={key:1},QR="headerFooterPart",JR={__name:"commentsList",props:{showMainComments:{type:Boolean,default:!0},showResolvedComments:{type:Boolean,default:!0}},setup(e){const t=e,n=ca(),r=vg(n,"isCommentsListVisible"),o=_e(()=>n.getGroupedComments),i=_e(()=>n.getFloatingCommentInstances),{activeComment:s,activeFloatingCommentInstanceId:a}=ea(n),l=g=>{const p=i.value.filter(v=>v?.comment?.commentId===g?.commentId);return p.length<2?[]:g?.trackedChange?g?.trackedChangeStory?.storyType!==QR?[]:p:[]},u=g=>!g?.comment?.commentId||s.value!==g.comment.commentId?!1:a.value==null?g.isPrimary===!0:String(a.value)===String(g.id),c=g=>{const p=l(g);return p.length?p.map(v=>({id:v.id,comment:g,floatingInstanceId:String(v.id),floatingPageIndex:v.pageIndex,floatingPositionEntry:v.positionEntry??null,isFloatingInstanceActive:u(v)})):[{id:g.commentId,comment:g,floatingInstanceId:null,floatingPageIndex:null,floatingPositionEntry:null,isFloatingInstanceActive:void 0}]},d=_e(()=>o.value.parentComments.flatMap(g=>c(g))),h=_e(()=>t.showResolvedComments&&o.value?.resolvedComments?.length>0);return Un(()=>{r.value=!0}),cr(()=>{r.value=!1}),(g,p)=>(ge(),Ie("div",qR,[e.showMainComments?(ge(),Ie("div",YR,[(ge(!0),Ie(Jt,null,lr(d.value,v=>(ge(),Ie("div",{key:v.id,class:"comment-item","data-comment-instance-id":v.floatingInstanceId??"","data-comment-thread-id":v.comment.commentId??"","data-comment-position-key":v.comment.trackedChangeAnchorKey??"","data-comment-page-index":Number.isFinite(v.floatingPageIndex)?v.floatingPageIndex:""},[Zt(Np,{comment:v.comment,"floating-instance-id":v.floatingInstanceId,"floating-page-index":v.floatingPageIndex,"floating-position-entry":v.floatingPositionEntry,"is-floating-instance-active":v.isFloatingInstanceActive},null,8,["comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])],8,XR))),128))])):mt("",!0),h.value?(ge(),Ie("div",ZR,[p[0]||(p[0]=Oe("div",{class:"comment-title"},"Resolved",-1)),(ge(!0),Ie(Jt,null,lr(o.value.resolvedComments,v=>(ge(),Ie("div",{key:v.commentId,class:"comment-item"},[Zt(Np,{comment:v},null,8,["comment"])]))),128))])):mt("",!0)]))}},$R=yn(JR,[["__scopeId","data-v-e89dbc33"]]);Mt();var e9=class extends Qm.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=Kl($R);const e=this.superdoc?.app?._context?.provides;e&&this.app?._context?.provides&&Object.setPrototypeOf(this.app._context.provides,e),this.superdoc?.pinia&&(Zd(this.superdoc.pinia),this.app.use(this.superdoc.pinia),this.app.config.globalProperties.$pinia=this.superdoc.pinia),this.app.directive("click-outside",ey),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()}},t9,el,m0=Ir((()=>{t9=2,el=96/72}));Mt(),m0();var n9=96,r9=".superdoc__right-sidebar",o9=".sd-pdf-viewer-page";const g0=Object.freeze({min:10,max:100,padding:0}),Pk=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,g0.min),o=n(t.max,g0.max),i=typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding>=0?t.padding:g0.padding;return{min:Math.min(r,o),max:Math.max(r,o),padding:i}},Dk=(e,t)=>!(e>0)||!(t>0)?null:Math.round(e/t*100),i9=(e,t,n)=>{const r=Dk(e-n.padding,t);return r===null?null:Math.max(1,Math.round(Math.min(n.max,Math.max(n.min,r))))},s9=(e,t,n)=>e>0?Number.isFinite(t)&&t>0?e/t*el:n>0?e/n:e:null;function a9({getSuperdoc:e,superdocContainerWidth:t,isReady:n,activeZoom:r,zoomMode:o,viewportMetrics:i,showCommentsSidebar:s,rightSidebarRef:a,superdocRoot:l,documents:u}){const c=w=>{if(!w)return null;let x=0;try{const G=w.getPages?.();if(Array.isArray(G))for(const R of G){const F=R?.size?.w;typeof F=="number"&&Number.isFinite(F)&&F>x&&(x=F)}}catch{x=0}if(x>0)return x;let P=null;try{P=w.getPageStyles?.()??null}catch{P=null}const N=P?.pageSize?.width;return typeof N=="number"&&Number.isFinite(N)&&N>0?N*n9:null},d=()=>{if(!(u?.value??[]).some(P=>P?.type==="application/pdf"))return null;const w=l.value;if(!w?.querySelectorAll)return null;let x=0;for(const P of w.querySelectorAll(o9)){const N=Number(P.clientWidth)||Number(P.getBoundingClientRect?.().width)||0;let G=NaN;typeof window<"u"&&typeof window.getComputedStyle=="function"&&(G=Number.parseFloat(window.getComputedStyle(P).getPropertyValue("--scale-factor")));const R=(r.value??100)/100,F=s9(N,G,R);F!==null&&F>x&&(x=F)}return x>0?x:null},h=()=>{const w=e();if(!w)return null;const x=[],P=u?.value??[];for(const G of P){if(G?.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")continue;const R=c(G.getEditor?.());R!==null&&x.push(R)}if(x.length===0){const G=c(w.activeEditor);G!==null&&x.push(G)}const N=d();if(N!==null&&x.push(N),x.length>0)return Math.max(...x);if(w.activeEditor){const G=l.value?.querySelector?.(".superdoc__document"),R=Number(G?.clientWidth)||Number(G?.getBoundingClientRect?.().width)||0;if(R>0){const F=(r.value??100)/100;return F>0?R/F:R}}return null},g=()=>{if(!s?.value)return 0;const w=a?.value??l.value?.querySelector?.(r9),x=Number(w?.offsetWidth)||Number(w?.getBoundingClientRect?.().width)||0;return x>0?x:0},p=(w,x)=>{const P=Pk(w.config?.zoom?.fitWidth),N=i9(x.availableWidth,x.documentWidth,P);N!==null&&N!==r.value&&(r.value=N,w.emit("zoomChange",{zoom:N,mode:"fit-width"}))},v=()=>{const w=e();if(!w)return;const x=t.value;if(!(x>0)||!n.value)return;const P=h();if(P===null)return;const N=x-g(),G=Dk(N,P);if(G===null)return;const R=Object.freeze({availableWidth:N,documentWidth:P,fitZoom:G}),F=i.value;(!F||F.availableWidth!==N||F.documentWidth!==P||F.fitZoom!==G)&&(i.value=R),(!F||F.fitZoom!==G||Math.round(F.documentWidth)!==Math.round(P))&&w.emit("viewport-change",R),o.value==="fit-width"&&p(w,R)};zt(t,()=>{It(()=>v())}),zt(n,w=>{w&&v()}),zt(o,w=>{w==="fit-width"&&v()}),s&&zt(s,()=>{It(()=>v())});const k=()=>{It(()=>v())},C=()=>{It(()=>v())},_=()=>{It(()=>v())},y=e();return y?.on?.("editorCreate",k),y?.on?.("pagination-update",C),y?.on?.("pdf:document-ready",_),cr(()=>{y?.off?.("editorCreate",k),y?.off?.("pagination-update",C),y?.off?.("pdf:document-ready",_)}),{evaluateViewport:v}}const l9=e=>!!e?.trackedChange,c9=e=>e,u9=(e,t,n,r=e)=>!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?!1:(Number.isFinite(r)?r:e)<t||e>n,d9=({comment:e,anchorTop:t,anchorBottom:n,viewportTop:r,viewportBottom:o})=>l9(e)&&u9(t,r,o,n),f9=({comment:e,anchorTop:t,anchorBottom:n,cardHeight:r,viewportTop:o,viewportBottom:i})=>!d9({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,h9=({id:e,visibleIds:t,activeCommentInstanceId:n})=>e?!!(e==="pending"||n!=null&&String(e)===String(n)||t?.has?.(e)):!1,Ok=({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};Mt(),Cn();var p9=["data-comment-id","data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Zl={},m9={__name:"FloatingComments",props:{currentDocument:{type:Object,required:!0},parent:{type:Object,required:!0}},setup(e){const r=(Pe,Ge,We)=>{if(Ge>=0){Pe[Ge].top=Pe[Ge].anchorTop;let ft=Pe[Ge].top+Pe[Ge].height+We;for(let yt=Ge+1;yt<Pe.length;yt++)Pe[yt].top=Math.max(Pe[yt].anchorTop,ft),ft=Pe[yt].top+Pe[yt].height+We;ft=Pe[Ge].top-We;for(let yt=Ge-1;yt>=0;yt--){const $t=ft-Pe[yt].height;Pe[yt].top=Math.min(Pe[yt].anchorTop,$t),ft=Pe[yt].top-We}const Vt=Math.min(...Pe.map(yt=>yt.top));if(Vt<0){const yt=Math.abs(Vt);for(const $t of Pe)$t.top+=yt}}else for(let ft=1;ft<Pe.length;ft++){const Vt=Pe[ft-1],yt=Vt.top+Vt.height+We;Pe[ft].top<yt&&(Pe[ft].top=yt)}},o=e,i=vu(),s=ca(),{clearInstantSidebarAlignment:a}=s,{activeComment:l,activeFloatingCommentInstanceId:u,editorCommentPositions:c,pendingComment:d,editingCommentId:h,instantSidebarAlignmentTargetY:g,instantSidebarAlignmentThreadId:p,instantSidebarAlignmentInstanceId:v}=ea(s),{activeZoom:k}=ea(i),C=_e(()=>{const Pe=s.getFloatingCommentInstances;if(!Array.isArray(Pe))return[];const Ge=o.currentDocument?.id;return Ge==null?Pe:Pe.filter(We=>s.belongsToDocument(We.comment,String(Ge),{allowSingleDocumentMismatch:!0}))}),_=ne(null),y=ne(0),w=ne(0),x=ne(!1),P=ne(null),N=ne(0),G=Pe=>{const Ge=d.value?.commentId;return Ge?typeof Pe=="object"?Pe?.commentId===Ge:Pe===Ge||Pe==="pending":!1},R=Pe=>Pe?.commentId??Pe?.importedId??null,F=_e(()=>{const Pe=new Map,Ge=new Map;for(const We of C.value){We?.id!=null&&Pe.set(String(We.id),We);const ft=R(We?.comment);if(ft==null)continue;const Vt=String(ft),yt=Ge.get(Vt)??[];yt.push(We),Ge.set(Vt,yt)}return{byId:Pe,byThreadId:Ge}}),Z=(Pe,Ge=null)=>{if(Pe==null)return null;const We=String(Pe),ft=F.value.byThreadId.get(We)??[];if(!ft.length)return null;if(Ge!=null){const Vt=ft.find(yt=>String(yt.id)===String(Ge));if(Vt)return Vt.id}return ft.find(Vt=>Vt.isPrimary)?.id??ft[0]?.id??null},D=_e(()=>l.value?Z(l.value,u.value):null),B=Pe=>{if(typeof Pe=="number")return Number.isFinite(Pe)?Pe:null;if(typeof Pe!="string"||Pe.trim()==="")return null;const Ge=Number(Pe);return Number.isFinite(Ge)?Ge:null},T=ne({...Zl}),V=ne(new Set),J=ne({});let q=null;const se=new Set;let pe=null;const Ne=()=>{pe==null&&(pe=requestAnimationFrame(()=>{pe=null,N.value+=1}))},he=Pe=>{if(o.currentDocument.type==="application/pdf"){const Ge=(k.value??100)/100,We=B(Pe?.comment?.selection?.selectionBounds?.top);return We==null?null:We*Ge}return Pe?.positionEntry?.bounds?.top},ye=(Pe,Ge)=>{if(o.currentDocument.type==="application/pdf"){const ft=(k.value??100)/100,Vt=B(Pe?.comment?.selection?.selectionBounds?.bottom);return Vt!=null?Vt*ft:Ge}const We=Pe?.positionEntry?.bounds?.bottom;return Number.isFinite(We)?We:Ge},ce=_e(()=>{const Pe=[];for(const Ge of C.value){const We=Ge?.id,ft=R(Ge?.comment),Vt=he(Ge);if(We==null||ft==null||!Number.isFinite(Vt))continue;const yt=c9(Vt,Ge.comment);Pe.push({id:We,threadId:ft,instance:Ge,top:yt,anchorBottom:ye(Ge,yt)})}return Pe}),ke=()=>{const Pe=c.value.pending;if(typeof Pe?.bounds?.top=="number"&&!isNaN(Pe.bounds.top))return Pe.bounds.top;const Ge=o.currentDocument.type==="application/pdf"?(k.value??100)/100:1,We=B(d.value?.selection?.selectionBounds?.top);return We==null?null:We*Ge},ie=Pe=>h9({id:Pe?.id,visibleIds:V.value,activeCommentInstanceId:D.value,comment:Pe?.commentRef}),xe=()=>{const Pe=_.value;if(!Pe)return null;const Ge=Pe.getBoundingClientRect();if(!Number.isFinite(Ge.top)||!Number.isFinite(window.innerHeight))return null;let We=0,ft=window.innerHeight;for(let yt=Pe.parentElement;yt;yt=yt.parentElement){const $t=window.getComputedStyle(yt).overflowY;if(!["auto","scroll","hidden","clip"].includes($t))continue;const At=yt.getBoundingClientRect();!Number.isFinite(At.top)||!Number.isFinite(At.bottom)||(We=Math.max(We,At.top),ft=Math.min(ft,At.bottom))}if(ft<=We)return null;const Vt=o.parent?.getBoundingClientRect?.();if(Vt&&Number.isFinite(Vt.top)&&Number.isFinite(Vt.bottom)){const yt=Math.max(We,Vt.top),$t=Math.min(ft,Vt.bottom);$t>yt&&(We=yt,ft=$t)}return{top:We-Ge.top,bottom:ft-Ge.top}},Je=_e(()=>p.value?Z(p.value,v.value):null),st=_e(()=>{N.value;const Pe=ce.value,Ge=d.value&&d.value.fileId===o.currentDocument.id;if(!Pe.length&&!C.value.length&&!Ge)return[];const We=[],ft=xe()??{top:0,bottom:Math.max(0,o.parent?.clientHeight||window.innerHeight||0)},Vt=ft.top-600,yt=ft.bottom+600,$t=Ge?"pending":D.value,At=new Set,kn=({id:Ht,threadId:Pn,instance:br,top:Do,anchorBottom:er,hasAnchorGeometry:cn})=>{const Gn=String(Ht);At.has(Gn)||(At.add(Gn),We.push({id:Ht,threadId:Pn,pageIndex:br?.pageIndex??null,anchorTop:Do,anchorBottom:er,hasAnchorGeometry:cn,top:Do,height:T.value[Ht]||110,commentRef:br.comment,instanceRef:br}))};for(const Ht of Pe){const{id:Pn,threadId:br,instance:Do,top:er,anchorBottom:cn}=Ht,Gn=$t!=null&&String(Pn)===String($t),Br=h.value!=null&&String(br)===String(h.value);!Gn&&!Br&&(cn<Vt||er>yt)||kn({id:Pn,threadId:br,instance:Do,top:er,anchorBottom:cn,hasAnchorGeometry:!0})}const Nn=[];if($t&&$t!=="pending"){const Ht=F.value.byId.get(String($t));Ht&&Nn.push(Ht)}if(h.value!=null){const Ht=F.value.byThreadId.get(String(h.value))??[],Pn=Ht.find(br=>br.isPrimary)??Ht[0];Pn&&Nn.push(Pn)}for(const Ht of Nn){const Pn=Ht.id,br=R(Ht.comment);Pn==null||br==null||At.has(String(Pn))||kn({id:Pn,threadId:br,instance:Ht,top:ft.top,anchorBottom:ft.top,hasAnchorGeometry:!1})}if(Ge){const Ht=ke();typeof Ht=="number"&&!isNaN(Ht)&&We.push({id:"pending",anchorTop:Ht,anchorBottom:Ht,hasAnchorGeometry:!0,top:Ht,height:T.value.pending||110,commentRef:d.value})}We.sort((Ht,Pn)=>Ht.anchorTop-Pn.anchorTop);const Uo=[];for(const Ht of We){const Pn=Ht.hasAnchorGeometry?f9({comment:Ht.commentRef,anchorTop:Ht.anchorTop,anchorBottom:Ht.anchorBottom,cardHeight:Ht.height,viewportTop:ft.top,viewportBottom:ft.bottom}):null;Pn==null?Uo.push(Ht):Ht.top=Pn}return r(Uo,$t?Uo.findIndex(Ht=>Ht.id===$t):-1,15),We}),Tt=_e(()=>(N.value,Math.max(0,o.parent?.clientHeight||0,o.parent?.scrollHeight||0))),Te=()=>{q&&q.disconnect(),q=new IntersectionObserver(Pe=>{const Ge=new Set(V.value);for(const We of Pe){const ft=We.target.dataset.commentId;ft&&(We.isIntersecting?Ge.add(ft):Ge.delete(ft))}V.value=Ge},{rootMargin:"600px 0px 600px 0px"})},je=()=>{if(!q)return;const Pe=new Set;for(const Ge of st.value){const We=J.value[Ge.id];We&&(Pe.add(We),se.has(We)||(q.observe(We),se.add(We)))}for(const Ge of se)Pe.has(Ge)||(q.unobserve(Ge),se.delete(Ge))},Ye=(Pe,Ge)=>{Ge<=0||Ge===T.value[Pe]||(Zl[Pe]=Ge,T.value={...T.value,[Pe]:Ge})},$=Pe=>{if(!Pe)return;const{elementRef:Ge,commentId:We}=Pe;Ge&&It(()=>{const ft=Ge.value?.getBoundingClientRect();!ft||ft.height<=0||We&&Ye(We,ft.height)})},S=Pe=>{const Ge=Pe?.id;Ge&&It(()=>{const We=J.value[Ge];if(!We)return;const ft=We.querySelector(".comments-dialog");if(!ft)return;Ye(Ge,ft.getBoundingClientRect().height);const Vt=Ge===D.value,yt=Ge==="pending",$t=!!h.value&&!!l.value&&Pe?.threadId!=null&&String(Pe.threadId)===String(l.value);!Vt&&!yt&&!$t||(Et(st.value.map(At=>At.id)),In(()=>st.value.map(At=>At.id)))})},ee=Pe=>{!Pe&&P.value!=null||(x.value=Pe)},O=(Pe,Ge,We)=>{if(!Number.isFinite(Ge)){We?.(!1);return}const ft=J.value[Pe];if(!ft){We?.(!1);return}const Vt=ft.getBoundingClientRect().top;w.value+=Ge-Vt,We?.(!0)},j=(Pe,Ge)=>{if(Ge)J.value[Pe]=Ge,q&&!se.has(Ge)&&(q.observe(Ge),se.add(Ge));else{const We=J.value[Pe];We&&q&&(q.unobserve(We),se.delete(We)),delete J.value[Pe]}};let U=[],W=null,te=[],Y=null,X=!1,be=0,ve=null,we=null,Be=null,rt=null;const at=()=>{Be=null,rt=null,P.value=null,ee(!1)},Ct=Pe=>{if(!Be)return;const Ge=(Pe?.target instanceof Element?Pe.target:null)?.closest?.("[data-comment-action]"),We=Ge?.getAttribute?.("data-comment-action");(We==="resolve"||We==="reject")&&_.value?.contains?.(Ge)||at()},en=()=>{U.forEach(clearTimeout),U=[]},Et=Pe=>{for(const Ge of Pe.filter(Boolean)){const We=J.value[Ge];if(!We)continue;const ft=We.querySelector(".comments-dialog");ft&&Ye(Ge,ft.getBoundingClientRect().height)}},Ut=50,Wt=350,In=Pe=>{en();const Ge=typeof Pe=="function"?Pe:()=>Pe;U.push(setTimeout(()=>Et(Ge()),Ut)),U.push(setTimeout(()=>Et(Ge()),Wt))},bt=()=>{a(),requestAnimationFrame(()=>{ee(!1)})},nn=(Pe,Ge)=>{!Pe||!Number.isFinite(Ge)||(ee(!0),It(()=>{Et([Pe]),O(Pe,Ge,()=>{bt()})}))},et=()=>{Y=null,be+=1,ve!=null&&(cancelAnimationFrame(ve),ve=null),ee(!1)},Pt=()=>{if(!Y||X)return;X=!0;const Pe=be;ve!=null&&(cancelAnimationFrame(ve),ve=null),ee(!0),It(()=>{if(X=!1,Pe!==be){Pt();return}const{key:Ge,targetClientY:We}=Y;Et([Ge]),O(Ge,We,ft=>{if(Pe===be){if(!ft){ee(!1);return}ve=requestAnimationFrame(()=>{ve=null,Pe===be&&ee(!1)})}})})},Kt=(Pe,Ge)=>{const We=Ok({previousIds:te,currentIds:Ge,removedId:Pe}),ft=(We?J.value[We]:null)?.getBoundingClientRect?.().top;return!We||!Number.isFinite(ft)?(et(),!1):(Y={key:We,targetClientY:ft},be+=1,Pt(),!0)},Rn=Pe=>{const Ge=Pe?.target?.closest?.("[data-comment-action]"),We=Ge?.getAttribute?.("data-comment-action");if(We!=="resolve"&&We!=="reject"||(at(),Ge.getAttribute?.("aria-disabled")==="true"))return;const ft=Ge.closest?.("[data-comment-id]")?.getAttribute?.("data-comment-id");if(!ft||String(D.value??"")===String(ft))return;const Vt=st.value.filter(At=>At.commentRef?.trackedChange).map((At,kn)=>({id:At.id,index:kn,top:At.top})).filter(At=>Number.isFinite(At.top)).sort((At,kn)=>At.top-kn.top||At.index-kn.index).map(At=>At.id),yt=Ok({previousIds:Vt,currentIds:new Set(Vt),removedId:ft}),$t=(yt?J.value[yt]:null)?.getBoundingClientRect?.().top;!yt||!Number.isFinite($t)||(Be={removedKey:ft,targetKey:yt,targetClientY:$t,applied:!1},rt=ft,P.value=yt,ee(!0))};zt(D,(Pe,Ge)=>{if(en(),!(Be!=null&&rt!=null&&[Pe,Ge].some(Vt=>Vt!=null&&String(Vt)===String(rt)))){if(rt=null,Pe)at(),et();else if(Ge){const Vt=new Set(st.value.map(yt=>yt.id));Vt.has(Ge)?et():Kt(Ge,Vt)}}const We=[Pe,Ge],ft=Pe&&Pe===Je.value&&Number.isFinite(g.value);It(()=>{if(ft){Et(We);return}In(We)})}),zt([D,Je,g],([Pe,Ge,We])=>{!Pe||!Ge||Pe!==Ge||!Number.isFinite(We)||nn(Pe,We)}),zt(h,()=>{en(),It(()=>{In(()=>st.value.map(Pe=>Pe.id))})}),zt(l,()=>{if(W&&clearTimeout(W),!l.value){if(a(),Y){Pt();return}ee(!1),w.value=0;return}if(!(G(l.value)?d.value:s.getComment(l.value)))return;const Pe=G(l.value)?"pending":D.value;if(Pe){if(Pe===Je.value&&Number.isFinite(g.value)){ee(!0);return}It(()=>{W=setTimeout(()=>{const We=J.value[Pe];if(!We)return;const ft=o.parent?.getBoundingClientRect?.();if(!ft)return;const Vt=st.value.find(kn=>kn.id===Pe),yt=Pe==="pending"?ke():Vt?.anchorTop;if(typeof yt!="number"||isNaN(yt))return;const $t=We.getBoundingClientRect().top,At=ft.top+yt;w.value+=At-$t},400)})}}),zt(k,()=>{if(o.currentDocument.type==="application/pdf"){for(const Pe in Zl)delete Zl[Pe];T.value={},y.value+=1}});let Nt=new Set,un=null,Mn=null;return zt(st,Pe=>{const Ge=D.value?Pe.find(cn=>cn.id===D.value):null,We=typeof Ge?.anchorTop=="number"&&Number.isFinite(Ge.anchorTop)?Ge.anchorTop:null,ft=We!=null&&un!=null&&Math.abs(We-un)>1,Vt=typeof Ge?.top=="number"&&Number.isFinite(Ge.top)?Ge.top:null,yt=Vt!=null&&Mn!=null&&Math.abs(Vt-Mn)>1;ft&&w.value!==0&&!Number.isFinite(g.value)?(w.value=0,ee(!1)):yt&&w.value!==0&&!Number.isFinite(g.value)&&!Y&&(ee(!0),w.value+=Mn-Vt,we!=null&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{we=null,!Y&&!Number.isFinite(g.value)&&ee(!1)})),un=We,Mn=Vt;const $t=Pe.map(cn=>cn.id),At=new Set($t);if(Be&&!Be.applied&&!At.has(Be.removedKey)){const{targetKey:cn,targetClientY:Gn}=Be;Be.applied=!0,At.has(cn)&&Number.isFinite(Gn)?(Y={key:cn,targetClientY:Gn},be+=1,Pt()):at()}if(Be?.applied&&!At.has(Be.targetKey)&&at(),Y&&!At.has(Y.key)){const cn=Y.key;Kt(cn,At)||(ee(!1),w.value=0)}const kn=new Set(V.value);let Nn=!1,Uo=-1/0,Ht=1/0;const Pn=_.value;if(Pn){const cn=Pn.getBoundingClientRect();Uo=-cn.top-600,Ht=-cn.top+window.innerHeight+600}const br=new Map(Pe.map(cn=>[cn.id,cn]));for(const cn of At)if(!kn.has(cn)){const Gn=br.get(cn);(!Gn||Gn.top>=Uo&&Gn.top<=Ht)&&(kn.add(cn),Nn=!0)}for(const cn of kn)At.has(cn)||(kn.delete(cn),Nn=!0);Nn&&(V.value=kn);for(const cn of Nt)At.has(cn)||delete Zl[cn];const Do=Nt.size!==At.size||[...Nt].some(cn=>!At.has(cn)),er=te.length!==$t.length||te.some((cn,Gn)=>cn!==$t[Gn]);if(Do){const cn={};for(const Gn of At)Zl[Gn]&&(cn[Gn]=Zl[Gn]);T.value=cn,It(()=>{for(const Gn of Pe){const Br=J.value[Gn.id];if(!Br)continue;const ei=Br.querySelector(".comments-dialog");ei&&Ye(Gn.id,ei.getBoundingClientRect().height)}})}Y&&(Do||er)&&Pt(),Nt=At,It(()=>{te=$t,je()})}),Un(()=>{Te(),o.parent?.addEventListener?.("scroll",Ne,{passive:!0}),window.addEventListener("resize",Ne,{passive:!0}),document.addEventListener("pointerdown",Ct,!0),It(je)}),cr(()=>{en(),W&&clearTimeout(W),at(),et(),we!=null&&(cancelAnimationFrame(we),we=null),o.parent?.removeEventListener?.("scroll",Ne),window.removeEventListener("resize",Ne),document.removeEventListener("pointerdown",Ct,!0),pe!=null&&(cancelAnimationFrame(pe),pe=null),q&&(q.disconnect(),q=null,se.clear())}),(Pe,Ge)=>(ge(),Ie("div",{class:"section-wrapper",ref_key:"floatingCommentsContainer",ref:_,onClickCapture:Rn,style:Sn({minHeight:Tt.value+"px",transition:x.value?"none":void 0})},[Oe("div",{class:"sidebar-container",style:Sn({transform:`translateY(${w.value}px)`,transition:x.value?"none":void 0})},[(ge(!0),Ie(Jt,null,lr(st.value,We=>(ge(),Ie("div",{key:We.id,ref_for:!0,ref:ft=>j(We.id,ft),"data-comment-id":We.id,"data-comment-instance-id":We.id,"data-comment-thread-id":We.threadId,"data-comment-position-key":We.instanceRef?.positionKey??"","data-comment-page-index":We.pageIndex??"",class:an([{"is-direct-decision-continuity-target":We.id===P.value},"comment-placeholder"]),style:Sn({top:We.top+"px",height:We.height+"px",transition:x.value?"none":void 0})},[ie(We)?(ge(),vn(Np,{key:We.id+y.value,onReady:$,onResize:ft=>S(We),class:"floating-comment",parent:e.parent,comment:We.commentRef,"floating-instance-id":We.id,"floating-page-index":We.pageIndex,"floating-position-entry":We.instanceRef?.positionEntry??null,"is-floating-instance-active":We.id===D.value},null,8,["onResize","parent","comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])):mt("",!0)],14,p9))),128))],4)],36))}},g9=yn(m9,[["__scopeId","data-v-a0a841ce"]]);Mt(),Cn();var v9={class:"superdoc__pdf-comments-layer pdf-comments-layer","aria-hidden":"false"},y9=["data-id","data-comment-id","data-page-number","onClick","onKeydown"],b9="pdf",w9="#078383",C9="#B1124B",k9={__name:"PdfCommentsLayer",emits:["anchor-activate"],setup(e,{emit:t}){const n=t,r=ca(),o=vu(),{activeComment:i}=ea(r),{documents:s,activeZoom:a}=ea(o),{proxy:l}=ur(),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=_e(()=>{const y=Array.isArray(s.value)?s.value:[];return new Set(y.filter(w=>w?.type===ql).map(w=>String(w.id)))}),h=y=>{const w=y?.fileId??y?.documentId??y?.selection?.documentId;return w!=null?String(w):null},g=y=>{const w=y?.commentId??y?.importedId;return w!=null&&String(w)!==""?String(w):null},p=y=>{const w=d.value;if(!w.size)return!1;const x=h(y);return x?w.has(x):w.size===1},v=y=>{const w=Math.min(Number(y.top),Number(y.bottom)),x=Math.max(Number(y.top),Number(y.bottom));return{top:w,left:Math.min(Number(y.left),Number(y.right)),right:Math.max(Number(y.left),Number(y.right)),bottom:x}},k=_e(()=>{const y=r.getFloatingComments;return Array.isArray(y)?y.filter(w=>w?.selection?.source===b9).filter(w=>!w.resolvedTime).filter(w=>g(w)!==null).filter(w=>c(w.selection?.selectionBounds)).filter(w=>p(w)).map(w=>{const x=g(w),P=v(w.selection.selectionBounds);return{commentId:x,page:w.selection?.page??null,isInternal:w.isInternal!==!1,bounds:P}}):[]}),C=y=>{const w=(a.value??100)/100,{top:x,left:P,right:N,bottom:G}=y.bounds,R=i.value===y.commentId,F=(y.isInternal?w9:C9)+(R?"66":"33");return{position:"absolute",top:x*w+"px",left:P*w+"px",width:(N-P)*w+"px",height:(G-x)*w+"px",backgroundColor:F}},_=y=>{r.setActiveComment(l.$superdoc,y.commentId),n("anchor-activate",y.commentId)};return(y,w)=>(ge(),Ie("div",v9,[(ge(!0),Ie(Jt,null,lr(k.value,x=>(ge(),Ie("div",{key:x.commentId,class:"sd-comment-anchor sd-highlight",role:"button",tabindex:"0","data-id":x.commentId,"data-comment-id":x.commentId,"data-page-number":x.page,style:Sn(C(x)),onClick:sn(P=>_(x),["stop","prevent"]),onKeydown:[Qo(sn(P=>_(x),["stop","prevent"]),["enter"]),Qo(sn(P=>_(x),["stop","prevent"]),["space"])]},null,44,y9))),128))]))}},S9=yn(k9,[["__scopeId","data-v-b5ad4c58"]]);Mt();const _9=({proxy:e,layers:t,documents:n,modules:r})=>{const o=_e(()=>{const F=r.value?.whiteboard??r.whiteboard;return F===!1||F==null?null:F}),i=e?.$superdoc?.whiteboard,s=Zr([]),a=Yr({}),l=Yr({}),u=ne(!1),c=ne(0),d=ne(0),h=ne(1),g=ne(o.value?.enabled??!1),p=()=>{if(u.value)return;c.value+=1;const F=d.value||s.value.length;F&&c.value>=F&&(u.value=!0,e?.$superdoc?.emit("whiteboard:ready",{whiteboard:i}))},v=F=>{if(!F)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&k(F)},k=F=>{const{pageIndex:Z,width:D,height:B,originalWidth:T,originalHeight:V}=F,J={width:D,height:B,originalWidth:T,originalHeight:V};i?.setPageSize(Z,J),a[Z]=J;const q=i?.getPage(Z);q&&q.setSize(J),i&&(s.value=i.getPages().sort((se,pe)=>se.pageIndex-pe.pageIndex).map(se=>Xr(se)),d.value=s.value.length),It(()=>{G(),p()})},C=F=>{e?.$superdoc?.emit("whiteboard:change",F)},_=F=>{F.forEach(Z=>{const D=a[Z.pageIndex];D&&Z.setSize(D)}),s.value=F.map(Z=>Xr(Z)),d.value=s.value.length,It(()=>G())},y=F=>{g.value=F,e?.$superdoc?.emit("whiteboard:enabled",F)},w=F=>{h.value=F},x=F=>{e?.$superdoc?.emit("whiteboard:tool",F)},P=()=>{const F=n.value?.[0];F&&F.type==="application/pdf"&&N({doc:F})},N=({doc:F})=>{s.value.forEach(Z=>{const D=`${F.id}-page-${Z.pageIndex+1}`,B=document.querySelector(`[data-page-id="${D}"]`);if(!B)return;const T=B.getBoundingClientRect(),V=a[Z.pageIndex]||{},J=V.originalWidth??Z.size?.originalWidth??T.width,q=V.originalHeight??Z.size?.originalHeight??T.height,se={width:T.width,height:T.height,originalWidth:J,originalHeight:q};a[Z.pageIndex]=se,Z.setSize(se)})},G=()=>{const F=t.value?.getBoundingClientRect?.();if(!F)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&R({doc:Z,layerBounds:F})},R=({doc:F,layerBounds:Z})=>{s.value.forEach(D=>{const B=`${F.id}-page-${D.pageIndex+1}`,T=document.querySelector(`[data-page-id="${B}"]`);if(!T)return;const V=T.getBoundingClientRect();l[D.pageIndex]={top:V.top-Z.top,left:V.left-Z.left}})};return i&&(i.on("change",C),i.on("setData",_),i.on("enabled",y),i.on("opacity",w),i.on("tool",x)),cr(()=>{i&&(i.off("change",C),i.off("setData",_),i.off("opacity",w),i.off("enabled",y),i.off("tool",x))}),{whiteboard:i,whiteboardModuleConfig:o,whiteboardPages:s,whiteboardPageSizes:a,whiteboardPageOffsets:l,whiteboardEnabled:g,whiteboardOpacity:h,whiteboardReady:u,handleWhiteboardPageReady:v,updateWhiteboardPageSizes:P,updateWhiteboardPageOffsets:G}};Mt(),Cn();var A9=["data-page-index"],I9={__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,g=u.clientY-d.top,p=t.pageSize?.width,v=t.pageSize?.originalWidth??p,k=Number.isFinite(p)&&Number.isFinite(v)&&v?p/v:1;i(u,h,g,k)||s(u,h,g,k)||a(u,h,g)||l(u,h,g)},i=(u,c,d,h)=>{const g=u.dataTransfer.getData("application/sticker");if(!g)return!1;const p=(t.whiteboard.getType("stickers")||[]).find(v=>v.id===g);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 g=Array.from(u.dataTransfer.files||[]).find(v=>v.type.startsWith("image/"));if(!g)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(g),!0},a=(u,c,d)=>{const h=u.dataTransfer.getData("application/comment");if(!h)return!1;const g=(t.whiteboard.getType("comments")||[]).find(p=>p.id===h);return g?.text?(t.page.addText({x:c,y:d,content:g.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 zt(()=>[t.page,t.pageSize?.width,t.pageSize?.height],()=>{It(r)}),Un(()=>{r()}),cr(()=>{t.page?.destroy()}),(u,c)=>(ge(),Ie("div",{ref_key:"containerRef",ref:n,class:"whiteboard-page","data-page-index":e.page.pageIndex,onDragover:c[0]||(c[0]=sn(()=>{},["prevent"])),onDrop:sn(o,["prevent"]),style:Sn({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,A9))}},E9=yn(I9,[["__scopeId","data-v-c876c9b5"]]);Mt(),Cn();var T9={__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=_e(()=>t.interactive==null?t.enabled:t.interactive);return(r,o)=>(ge(),Ie("div",{class:"whiteboard-layer","aria-hidden":"true",style:Sn({opacity:e.opacity,pointerEvents:n.value?"auto":"none"})},[(ge(!0),Ie(Jt,null,lr(e.pages,i=>(ge(),vn(E9,{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))}},x9=yn(T9,[["__scopeId","data-v-54546c3d"]]);function R9(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 Fk=["#1f6feb","#d1242f","#8250df","#bf3989","#1a7f37","#9a6700","#bc4c00","#0969da","#cf222e","#6639ba","#116329","#7d4e00"];const M9=e=>e?`${typeof e.name=="string"?e.name:""} ${typeof e.email=="string"?e.email:""}`:"";var L9=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 P9=e=>Fk[L9(M9(e))%Fk.length];var gf=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(gf(o.email)&&gf(t[o.email]))return t[o.email];if(gf(o.name)&&gf(t[o.name]))return t[o.name]}if(n)try{const i=n(o);if(gf(i))return i}catch{}return P9(o)}},O9=["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 Zj=new Set(O9);const vr={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"},Qj={"render.media.missing-relationship":vr.missingRelationship,"render.media.wrong-relationship-type":vr.unsupportedRelationshipType,"render.media.unsupported-target":vr.unsupportedRelationshipType,"render.media.invalid-image-size":vr.imageTooLarge,"render.media-resolver-unavailable":vr.missingMediaPart,"render.chart-not-supported":vr.unsupportedObject,"render.textbox.vml-unsupported":vr.vmlUnsupported},F9={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:vr.externalImageDeferred},missingRelationship:{family:"missingRelationship",support:"fail-closed",description:"Drawing references a relationship id absent from the owner part .rels.",contract:"none",diagnostic:vr.missingRelationship},missingMediaPart:{family:"missingMediaPart",support:"fail-closed",description:"Relationship resolves but the target media part bytes are missing or empty.",contract:"none",diagnostic:vr.missingMediaPart},wrongRelationshipType:{family:"wrongRelationshipType",support:"fail-closed",description:"Relationship exists but is not an image relationship type.",contract:"none",diagnostic:vr.unsupportedRelationshipType},unsupportedMime:{family:"unsupportedMime",support:"fail-closed",description:"Media MIME outside the supported allowlist (incl. GIF/BMP/ICO).",contract:"none",diagnostic:vr.unsupportedMime},oversizedMediaPart:{family:"oversizedMediaPart",support:"fail-closed",description:"Media part exceeds the host byte-size policy before bytes are materialized.",contract:"none",diagnostic:vr.imageTooLarge},unsafeSvg:{family:"unsafeSvg",support:"fail-closed",description:"SVG content rejected by the SVG safety policy.",contract:"none",diagnostic:vr.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:vr.unsupportedFormat},embeddedObject:{family:"embeddedObject",support:"fail-closed",description:"OLE / ActiveX / embedded package object.",contract:"none",diagnostic:vr.embeddedObjectNotSupported},smartArtOrDiagram:{family:"smartArtOrDiagram",support:"fail-closed",description:"SmartArt / diagram / unknown external graphic-data object.",contract:"none",diagnostic:vr.unsupportedObject},vml:{family:"vml",support:"fail-closed",description:"VML structure outside any supported image-like subset (default fail-closed policy).",contract:"none",diagnostic:vr.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:vr.vmlImageUnsupported},unsupportedGeometryCommand:{family:"unsupportedGeometryCommand",support:"fail-closed",description:"Custom geometry command the extractor does not implement, e.g. arcTo.",contract:"none",diagnostic:vr.unsupportedGeometryCommand},unsupportedAnchorFields:{family:"unsupportedAnchorFields",support:"fail-closed",description:"Anchor fields required for honest placement are unsupported (char-relative, alignment modes, etc.).",contract:"none",diagnostic:vr.anchorUnsupported},unsupportedWrapFields:{family:"unsupportedWrapFields",support:"fail-closed",description:"Wrap fields required for honest placement are unsupported (arbitrary wrap polygons, etc.).",contract:"none",diagnostic:vr.wrapUnsupported},alternateContentNoSupportedChoice:{family:"alternateContentNoSupportedChoice",support:"fail-closed",description:"mc:AlternateContent with no supported choice and no usable fallback.",contract:"none",diagnostic:vr.altContentNoSupportedChoice},groupChildUnsupported:{family:"groupChildUnsupported",support:"fail-closed",description:"Unsupported child inside an otherwise-supported group. Supported siblings are not dropped.",contract:"none",diagnostic:vr.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"}},Jj=Object.keys(F9),$j=Object.freeze(["multiple-sections","furniture-page-tokens","non-balanceable-multi-column-sections","body-anchored-objects","footnotes","page-references","keep-constraints","tables","furniture-anchored-objects"]);Mt(),Cn();var N9={class:"superdoc-html-viewer"},B9={class:"superdoc-html-viewer__document"},z9=["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 g=h.target.result;u(g)},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 Un(()=>{a()}),(l,u)=>(ge(),Ie("div",N9,[Oe("div",B9,[Oe("div",{class:"superdoc-html-viewer__content",innerHTML:r.value,onMouseup:i},null,40,z9)])]))}},H9=yn(V9,[["__scopeId","data-v-da3494ba"]]);const U9=(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=Op(s),d=c!=null?String(c):null,h=a&&o.has(a)||l&&o.has(l),g=u&&o.has(u)||d&&o.has(d);if(!h&&!g)return;const p=o.size;a&&o.add(a),l&&o.add(l),o.size>p&&(i=!0)});return o};Mt();var Nk=ne(!1);function Vi(){return{isHighContrastMode:Nk,setHighContrastMode:t=>{Nk.value=t}}}const eG="[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor",tG=320,nG=24,rG=816,oG=250,iG="sidebar",Bk=new Set(["auto","sidebar","inline"]);function zk(e){if(!e||e===!1||typeof e!="object")return e;const t={...e},n=t.displayMode;Bk.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}Mt();var j9=".superdoc__document",G9=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,W9=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=g=>{if(!(g instanceof HTMLElement)||(typeof window<"u"?window.getComputedStyle(g):null)?.display==="contents")return!1;const p=Number(g.clientWidth??0),v=Number(g.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0||Number.isFinite(v)&&v>0},l=()=>{const g=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 v=g?.parentElement??null;for(;v;){if(a(v))return v;v=v.parentElement}return a(g)||g instanceof HTMLElement?g:null},u=()=>{const g=typeof window<"u"?window.ResizeObserver:void 0;if(typeof g>"u")return;const p=l();p!==s&&(i&&(i.disconnect(),i=null),s=p,s&&(i=new g(()=>{h()}),i.observe(s)))},c=()=>{u();const g=Number(s?.clientWidth??0);if(Number.isFinite(g)&&g>0)return g;const p=Number(s?.getBoundingClientRect?.().width??0);return Number.isFinite(p)&&p>0?p:0},d=()=>{const g=t.value?.querySelector?.(j9),p=n.value,v=Number(g?.clientWidth??g?.getBoundingClientRect?.().width??0);if(Number.isFinite(v)&&v>0)return v;const k=Number(p?.clientWidth??p?.getBoundingClientRect?.().width??0);return Number.isFinite(k)&&k>0?k:816},h=()=>{const g=c(),p=e.value,v=p?.displayMode??"sidebar";if(v==="sidebar"){r.value=g,o.value=!1;return}if(v==="inline"){r.value=g,o.value=!0;return}if(!(Number.isFinite(g)&&g>0))return;r.value=g;const k=p?.compactBreakpointPx;if(G9(k)){o.value=g<k;return}o.value=g<W9(d())};return cr(()=>{i&&(i.disconnect(),i=null),s=null}),{superdocContainerWidth:r,isCompactCommentsMode:o,recalculateCompactCommentsMode:h,ensureCompactMeasurementObserver:u}}Mt();var Vk=320,tl=12,q9=220,Y9=16,X9=500,Hk=".superdoc-comment-highlight[data-comment-ids]",Uk="data-comment-ids",Z9=".sd-comment-anchor",v0=(e,t,n)=>Math.min(Math.max(e,t),n),gs=e=>Number(e),Hi=e=>Number.isFinite(e),y0=e=>e?.commentId??e?.importedId??null,jk=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),Q9=e=>{const t=e?.value;if(!t)return null;const n=gs(t.ts);if(!Hi(n)||Date.now()-n>X9)return null;const r=gs(t.x),o=gs(t.anchorRect?.bottom),i=Hi(o)?o:gs(t.y);return!Hi(r)||!Hi(i)?null:{x:r,y:i}},J9=({rootEl:e,comment:t,pendingComment:n})=>{if(n?.value&&t?.commentId===n.value?.commentId){const a=e.querySelectorAll(Hk);for(const l of a)if(jk(l.getAttribute(Uk)).includes("pending")&&typeof l.getBoundingClientRect=="function")return l.getBoundingClientRect()}const r=y0(t);if(!r)return null;const o=String(r),i=e.querySelectorAll(Hk);for(const a of i)if(jk(a.getAttribute(Uk)).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},$9=(e,t)=>{const{entry:n}=e(y0(t)),r=gs(n?.bounds?.bottom);return Hi(r)?r:gs(n?.bounds?.top)},eM=({selectionPosition:e,comment:t,pendingComment:n})=>e.value?.source==="pdf"||t?.selection?.source==="pdf"||n.value?.selection?.source==="pdf",tM=({rootEl:e,layersRect:t,comment:n})=>{const r=y0(n);if(r==null)return NaN;const o=e.querySelector(`${Z9}[data-id="${String(r)}"]`);return!o||typeof o.getBoundingClientRect!="function"?NaN:gs(o.getBoundingClientRect().bottom)-gs(t.top)},nM=({comment:e,pendingComment:t,selectionPosition:n,activeZoom:r})=>{if(!t.value||e?.commentId!==t.value?.commentId)return NaN;const o=gs(n.value?.bottom);if(Hi(o))return o*(n.value?.source==="pdf"?(r.value??100)/100:1);const i=gs(n.value?.top);return Hi(i)?i*(n.value?.source==="pdf"?(r.value??100)/100:1):NaN},rM=({top:e,left:t})=>({top:`${Math.round(e)}px`,left:`${Math.round(t)}px`,right:"auto"}),oM=({rootRect:e,layersRect:t,anchorBottom:n,anchorClientX:r=NaN})=>{const o=v0(t.top-e.top+n+Y9,tl,Math.max(tl,e.height-q9)),i=Math.max(tl,e.width-Vk-tl);let s;if(Hi(r))s=v0(r-e.left+tl,tl,i);else{const a=e.width-(t.left-e.left+t.width)+tl;s=v0(e.width-a-Vk,tl,i)}return{top:o,left:s}};function iM({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"},g=ne(0),p=ne({x:null,y:null,ts:0,anchorRect:null});let v=null,k=null;const C=()=>{p.value={x:null,y:null,ts:0,anchorRect:null}},_=(P,N,G)=>{if(!l.value?.some(F=>F.type==="application/pdf"))return!1;const R=P.querySelector(".superdoc__compact-comment-popover");return!n.value||!R||R.contains(N)||G?!1:(t.value&&d(),c(),C(),!0)},y=P=>{const N=s.value;if(!N||!a.value?.contains(P.target))return;const G=(typeof document.elementsFromPoint=="function"?document.elementsFromPoint(P.clientX,P.clientY):[]).find(F=>F?.nodeType===1&&N.contains(F)&&F.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"))?.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor")??(P.target?.nodeType===1?P.target.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"):null);if(_(N,P.target,G)||P.button!==0||P.pointerType!=="mouse")return;const R=G&&typeof G.getBoundingClientRect=="function"?G.getBoundingClientRect():null;R&&(p.value={x:P.clientX,y:R.bottom,ts:Date.now(),anchorRect:{left:R.left,right:R.right,top:R.top,bottom:R.bottom}})},w=_e(()=>{g.value;const P=n.value;if(!P)return h;const N=s.value,G=a.value;if(!N||!G)return h;const R=N.getBoundingClientRect(),F=G.getBoundingClientRect(),Z=Q9(p),D=Z?null:J9({rootEl:N,comment:P,pendingComment:t});let B=NaN,T=NaN;return Z?(B=Z.y-F.top,T=Z.x):D?(B=D.bottom-F.top,T=D.left):B=$9(u,P),!Hi(B)&&eM({selectionPosition:o,comment:P,pendingComment:t})&&(B=tM({rootEl:N,layersRect:F,comment:P})),Hi(B)||(B=nM({comment:P,pendingComment:t,selectionPosition:o,activeZoom:i})),Hi(B)?rM(oM({rootRect:R,layersRect:F,anchorBottom:B,anchorClientX:T})):h});return zt([e,t,o,i,r,p],()=>{const P=typeof window<"u"?window.requestAnimationFrame:null,N=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&N?.(v),P&&(v=P(()=>{g.value+=1,v=null}))},{deep:!1}),zt(n,(P,N)=>{if(!N&&P){const G=document.activeElement;G instanceof HTMLElement&&(k=G)}},{deep:!1}),zt(t,(P,N)=>{!N&&P&&C()}),Un(()=>{document.addEventListener("pointerdown",y,!0)}),cr(()=>{document.removeEventListener("pointerdown",y,!0);const P=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&(P?.(v),v=null),k=null}),{compactCommentPopoverStyle:w,closeCompactCommentPopover:()=>{n.value&&(t.value&&d(),c(),k&&typeof k.focus=="function"&&k.focus(),k=null)},resetClickAnchor:C}}function vs(...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 b0(...e){for(const t of e)if(t!==void 0)return t}function Gk(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=(l,u)=>{l?.kind!=="entity"||l.entityType!=="trackedChange"||typeof l.entityId=="string"&&l.entityId.length>0&&u.add(l.entityId)},s=l=>l?.kind!=="entity"||l.entityType!=="trackedChange"?null:typeof l.entityId=="string"&&l.entityId.length>0?l.entityId:null;if(Array.isArray(t.inserted)&&t.inserted.forEach(l=>i(l,n)),Array.isArray(t.updated)&&t.updated.forEach(l=>i(l,n)),Array.isArray(t.trackedChangeRefs)&&t.trackedChangeRefs.forEach(l=>i(l,n)),Array.isArray(t.removed)&&t.removed.forEach(l=>i(l,r)),Array.isArray(t.invalidatedRefs)&&t.invalidatedRefs.forEach(l=>i(l,r)),Array.isArray(t.remappedRefs))for(const l of t.remappedRefs){const u=s(l?.from),c=s(l?.to);u&&r.add(u),c&&n.add(c),u&&c&&u!==c&&o.push({from:u,to:c})}for(const l of r)n.delete(l);const a=sM(e,t);return n.size===0&&r.size===0&&!a?null:{upsertIds:n,removedIds:r,remappedPairs:o,reconcileMode:e.origin==="history"?"authoritative":"targeted",...a?{allResolved:a}:{}}}function sM(e,t){const n=e?.trackedChangeAllResolved;return e?.origin==="history"||!n||n.schemaVersion!==1||n.targetKind!=="all"||n.decision!=="accept"&&n.decision!=="reject"||n.remainingLogicalCount!==0||typeof n.catalogRevision!="string"||!n.catalogRevision||typeof n.sourceCoverageRevision!="string"||!n.sourceCoverageRevision||!Number.isSafeInteger(n.logicalTargetCount)||n.logicalTargetCount<=0||!Number.isSafeInteger(n.physicalCarrierCount)||n.physicalCarrierCount<n.logicalTargetCount||typeof n.txId!="string"||n.txId!==t.txId||typeof n.documentEpoch!="string"||!Number.isSafeInteger(n.commitSequence)||typeof n.packagePreviousRevision!="string"||typeof n.packageNextRevision!="string"||n.packagePreviousRevision===n.packageNextRevision?null:n}var vf=e=>new Set(Array.from(e??[]).filter(t=>typeof t=="string"&&t.length>0)),aM=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,lM=(e,t)=>e?.adapter===t?.adapter&&e?.documentId===t?.documentId&&e?.editor===t?.editor&&e?.reconcileToken===t?.reconcileToken;function Wk({getContext:e,reconcile:t,hydrate:n,onReconciled:r}){const o=new Map;let i=null,s=0,a=0,l=null,u=!1;const c=[],d=(R,F)=>{for(let Z=c.length-1;Z>=0;Z-=1){const D=c[Z];D.generation!==a||D.version>R||(c.splice(Z,1),D.resolve(F===!0&&D.requiresAllResolved?i==null:F))}},h=(R,F)=>a===R&&lM(F,e()),g=(R,F)=>{const Z=new Set;for(const D of R)o.get(D)===F.get(D)&&(o.delete(D),Z.add(D));return Z},p=R=>new Map([...o].filter(([,F])=>F.ready===!0&&F.reconcileMode===R)),v=()=>{let R=!1;i?.gate==="render"&&!i.ready&&(i.ready=!0,R=!0);for(const F of o.values())F.gate!=="render"||F.ready||(F.ready=!0,R=!0);return R},k=R=>{let F=!1;i&&i.version<=R&&!i.ready&&(i.ready=!0,F=!0);for(const Z of o.values())Z.version>R||Z.ready||(Z.ready=!0,F=!0);return F},C=async(R,F,Z,D=!1)=>{if(!(!D&&F.size===0||typeof r!="function"))try{await r(R,F,Z)}catch{}},_=R=>vf(R?.resolvedIds??(R?.items??[]).map(aM).filter(Boolean)),y=async(R,F,Z)=>{const D=await t(R,{upsertIds:new Set(F.keys()),removedIds:new Set,reconcileMode:"targeted"});if(!h(Z,R)||(await C(R,g(_(D),F),D),new Set([...F].filter(([T,V])=>o.get(T)===V).map(([T])=>T)).size===0))return;const B=await n(R,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1});h(Z,R)&&await C(R,g(_(B),F),B)},w=async(R,F,Z)=>{const D=await n(R,{trackedChangesListMode:"all",refreshReason:"mutation-history-render-reconcile",blocking:!0});if(!h(Z,R)||![...F].some(([q,se])=>o.get(q)===se))return;const B=D?.ok===!0,T=B&&D?.complete===!0&&D?.sourceCoverageComplete===!0,V=B?_(D):new Set,J=T?g(new Set(F.keys()),F):new Set;await C(R,T?J:V,{...D,reconcileMode:"authoritative"},!0)},x=()=>{if(l)return l;const R=i?.ready?i:null,F=p("targeted"),Z=p("authoritative");if(!R&&F.size===0&&Z.size===0)return null;const D=e();if(!D?.adapter)return null;u=!1;const B=a;return l=Promise.resolve().then(async()=>{if(R){let T=null;try{T=await t(D,{upsertIds:new Set,removedIds:new Set,allResolved:R.fact,reconcileMode:"targeted"})}catch{}if(!h(B,D))return;T?.ok===!0&&(i===R&&(i=null),await C(D,new Set,T,!0))}Z.size>0&&await w(D,Z,B).catch(()=>{}),F.size>0&&await y(D,F,B).catch(()=>{})}).catch(()=>{}).finally(()=>{l=null,u&&x()}),l},P=(R,F)=>{if(!R)return;R.allResolved&&(o.clear(),i={fact:R.allResolved,version:++s,gate:F,ready:!1});const Z=R.reconcileMode==="authoritative"?"authoritative":"targeted",D=vf(R.removedIds),B=vf(R.upsertIds);for(const V of D){const J=o.get(V);J?.reconcileMode==="authoritative"?o.set(V,{...J,version:++s,gate:F,ready:!1}):o.delete(V)}const T=e();if(D.size>0&&B.size===0&&T?.adapter&&!R.allResolved)try{Promise.resolve(t(T,{upsertIds:new Set,removedIds:D})).catch(()=>{})}catch{}for(const V of B)if(!D.has(V)){const J=o.get(V);o.set(V,{version:++s,gate:F,ready:!1,reconcileMode:Z==="authoritative"||J?.reconcileMode==="authoritative"?"authoritative":"targeted"})}},N=R=>P(R,"render");return{enqueue:N,enqueueAfterPaint(R,F){if(!R||typeof F!="function")return N(R),Promise.resolve(!1);P(R,"exact-paint");const Z=e(),D=a,B=s;if(!Z?.adapter)return k(B),Promise.resolve(!1);const T=new Promise(q=>{c.push({generation:D,version:B,requiresAllResolved:!!R.allResolved,resolve:q})}),V=new Set([...vf(R.upsertIds),...vf(R.removedIds)]),J=new Map([...V].flatMap(q=>{const se=o.get(q);return se?[[q,se]]:[]}));return Promise.resolve().then(()=>F()).then(async()=>{if(!h(D,Z)){d(B,!1);return}let q=v();k(B)&&(q=!0);for(const[Ne,he]of J)o.get(Ne)===he&&(he.ready||(q=!0),he.ready=!0);l&&(q||B>0)&&(u=!0);const se=l,pe=x();if(pe&&await pe,se){const Ne=l;Ne&&Ne!==se&&await Ne}if(!h(D,Z)){d(B,!1);return}d(B,!0)}).catch(()=>{if(!h(D,Z)){d(B,!1);return}for(const[q,se]of J)o.get(q)===se&&(se.gate="render");i?.gate==="exact-paint"&&(i.gate="render"),d(B,!1)}),T},onRender:(R=!1)=>{const F=v();l&&(F||R)&&(u=!0),x()},reset(){for(const R of c.splice(0))R.resolve(!1);a+=1,o.clear(),i=null,u=!1},getPendingIds(){return new Set(o.keys())}}}function cM(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 uM=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 Kk=e=>e?.type!=="mutation:committed"||e.origin!=="command"?!1:uM.has(e.editableCommandKind);function qk(e){return e==null?null:String(e)}function dM({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=g=>qk(t())===g,d=()=>{a!=null&&s(a),a=null,l=null,u=null};return{schedule:g=>{const p=qk(g);if(!c(p))return!1;u!==p&&d();const v=o();u=p,l??=v,a!=null&&s(a);const k=Math.max(0,r-(v-l));return a=i(()=>{const C=u;a=null,l=null,u=null,c(C)&&e()},Math.min(n,k)),!0},clear:d}}var fM="no-author-configured";const hM="author-required",Yk="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 Xk(e){return typeof e=="string"&&e.includes(fM)}function pM(e){if(!e||e.type!=="mutation:rejected")return!1;if(e.failureSource==="receipt"){const t=e.failure;return t?t.code==="PRECONDITION_FAILED"&&Xk(t.message):!1}return e.failureSource==="shell"?e.reason==="author-required"?!0:e.reason==="PRECONDITION_FAILED"&&Xk(e.message):!1}function mM(){const e=new Set,t=n=>typeof n=="string"&&n.length>0?n:"__default__";return{shouldNotify(n,r){if(!pM(r))return!1;const o=t(n);return e.has(o)?!1:(e.add(o),!0)},clear(n){e.delete(t(n))}}}const gM=e=>!!(e?.anchor&&e?.focus&&(e.anchor.blockId!==e.focus.blockId||e.anchor.blockOffset!==e.focus.blockOffset)),vM=(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)},yM=(e,t)=>e!=="editing"&&e!=="suggesting"?!1:gM(t);var bM=Ir((()=>{})),wM=ad({default:()=>sS},1),Zk,Qk,Jk,$k,eS,tS,nS,rS,oS,iS,sS,CM=Ir((()=>{Mt(),bM(),Cn(),Zk=["onKeydown"],Qk=["id"],Jk={class:"sd-password-prompt__description"},$k={class:"sd-password-prompt__field"},eS=["placeholder","disabled","aria-label"],tS={key:0,class:"sd-password-prompt__error",role:"alert"},nS={class:"sd-password-prompt__actions"},rS=["disabled"],oS=["disabled"],iS={__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=_e(()=>o.value?t.passwordPrompt.texts.invalidTitle:t.passwordPrompt.texts.title),a=_e(()=>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)=>(ge(),Ie("div",{class:"sd-password-prompt",onKeydown:Qo(sn(l,["prevent"]),["enter"])},[Oe("h3",{id:`sd-password-prompt-heading-${e.surfaceId}`,class:"sd-password-prompt__heading"},qt(s.value),9,Qk),Oe("p",Jk,qt(e.passwordPrompt.texts.description),1),Oe("div",$k,[Ws(Oe("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,eS),[[Ei,n.value]])]),i.value?(ge(),Ie("p",tS,qt(i.value),1)):mt("",!0),Oe("div",nS,[Oe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--cancel",disabled:r.value,onClick:u},qt(e.passwordPrompt.texts.cancelLabel),9,rS),Oe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--submit",disabled:!a.value,onClick:l},qt(r.value?e.passwordPrompt.texts.busyLabel:e.passwordPrompt.texts.submitLabel),9,oS)])],40,Zk))}},sS=yn(iS,[["__scopeId","data-v-ecf7f6fb"]])}));Mt();var kM=["DOCX_PASSWORD_REQUIRED","DOCX_PASSWORD_INVALID"],SM=3e4,Ti={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 _M({getSurfaceManager:e,getPasswordPromptConfig:t,onUnhandled:n}){const r=[],o=Zr(null),i=new Map;let s=!1;function a(p,v,k){if(!p||!kM.includes(v)||t()===!1||!e())return!1;const C=i.get(p.id);if(C)return clearTimeout(C.timer),C.resolve({success:!1,errorCode:v}),i.delete(p.id),!0;const _=r.find(y=>y.doc.id===p.id);return _?(_.errorCode=v,_.originalException=k,!0):(o.value?.doc.id===p.id||(r.push({doc:p,errorCode:v,originalException:k}),c()),!0)}function l(p){if(!p)return;const v=i.get(p.id);v&&(clearTimeout(v.timer),v.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(v=>{o.value=null,console.error("[SuperDoc] Password prompt error:",v),n?.(p.doc,p.errorCode,p.originalException),c()})}async function d({doc:p,errorCode:v,originalException:k}){const C=e();if(!C||s)return;const _=h(),y=N=>(p.password=N,p.editorMountNonce++,new Promise(G=>{const R=setTimeout(()=>{i.delete(p.id),G({success:!1,errorCode:"timeout"})},SM);i.set(p.id,{resolve:G,timer:R})})),w={documentId:p.id,errorCode:v,texts:_.texts,attemptPassword:y},x=g(_,{documentId:p.id,errorCode:v,texts:_.texts});if(x.suppressed){n?.(p,v,k),c();return}o.value={doc:p,surfaceHandle:null};let P;if(x.component)P=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:_.texts.title,component:Xr(x.component),props:{...x.props,passwordPrompt:w}});else if(x.render){const N=x.render;P=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:_.texts.title,render:G=>N({container:G.container,passwordPrompt:w,resolve:G.resolve,close:G.close,surfaceId:G.surfaceId,mode:G.mode})})}else{const N=(await Promise.resolve().then(()=>(CM(),wM))).default,G=`password-prompt-${p.id}`;P=C.open({id:G,mode:"dialog",closeOnBackdrop:!1,ariaLabelledBy:`sd-password-prompt-heading-${G}`,component:Xr(N),props:{passwordPrompt:w}})}o.value={doc:p,surfaceHandle:P},await P.result,o.value=null,c()}function h(){const p=t();if(p===!1)return{enabled:!1,texts:Ti};const v=typeof p=="object"&&p!==null?p:{};if(v.component!=null&&typeof v.render=="function")throw new Error('modules.surfaces.passwordPrompt cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{title:v.title??Ti.title,invalidTitle:v.invalidTitle??Ti.invalidTitle,description:v.description??Ti.description,placeholder:v.placeholder??Ti.placeholder,inputAriaLabel:v.inputAriaLabel??Ti.inputAriaLabel,submitLabel:v.submitLabel??Ti.submitLabel,cancelLabel:v.cancelLabel??Ti.cancelLabel,busyLabel:v.busyLabel??Ti.busyLabel,invalidMessage:v.invalidMessage??Ti.invalidMessage,timeoutMessage:v.timeoutMessage??Ti.timeoutMessage,genericErrorMessage:v.genericErrorMessage??Ti.genericErrorMessage},component:v.component,props:v.props,render:v.render,resolver:v.resolver}}function g(p,v){if(typeof p.resolver=="function"){const k=p.resolver(v);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 aS(e,{getCurrentSession:t,applySlice:n,onSettled:r}){return()=>{if(e===t())try{n(e.getSnapshot())}catch{}r()}}var AM=Ir((()=>{})),IM=ad({default:()=>RS},1),lS,cS,uS,dS,fS,hS,pS,mS,gS,vS,yS,bS,wS,CS,kS,SS,_S,AS,IS,ES,TS,xS,RS,EM=Ir((()=>{Mt(),AM(),Cn(),lS=["onKeydown"],cS={class:"sd-find-replace__row"},uS=["title","aria-label","aria-expanded"],dS=["value","placeholder","aria-label"],fS={key:0,class:"sd-find-replace__count"},hS=["title","aria-label","aria-pressed"],pS=["title","aria-label","aria-pressed"],mS=["title","aria-label","aria-pressed"],gS={class:"sd-find-replace__nav"},vS=["disabled","title","aria-label"],yS=["disabled","title","aria-label"],bS=["title","aria-label"],wS={key:0,class:"sd-find-replace__row"},CS={class:"sd-find-replace__field"},kS=["value","placeholder","aria-label"],SS={class:"sd-find-replace__nav sd-find-replace__nav--actions"},_S=["disabled","title"],AS=["disabled","title"],IS={key:1,class:"sd-find-replace__error",role:"alert"},ES={key:0,class:"sd-find-replace__row-indent","aria-hidden":"true"},TS={class:"sd-find-replace__error-text"},xS={__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=_e(()=>{const p=t.findReplace;return!!(!p.hasMatches?.value||p.replacePending?.value===!0||p.canReplace&&p.canReplace.value===!1)}),o=_e(()=>t.findReplace.ignoreDiacriticsSupported?.value!==!1),i=_e(()=>t.findReplace.replaceEnabled&&t.findReplace.replaceCanMutate?.value!==!1),s=_e(()=>t.findReplace.regexSupported?.value===!0),a=_e(()=>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(),g()}function c(){t.findReplace.goPrev(),g()}function d(){t.findReplace.close("user-closed")}function h(p){const v=[];let k=p?.parentElement??null;for(;k;){const _=k.ownerDocument?.defaultView?.getComputedStyle?.(k);if(_){const y=`${_.overflowY} ${_.overflowX}`;(y.includes("auto")||y.includes("scroll"))&&v.push(k)}k=k.parentElement}const C=p?.ownerDocument?.scrollingElement;return C&&!v.includes(C)&&v.push(C),v}function g(){const p=n.value;if(!p)return;const v=h(p).map(k=>({el:k,top:k.scrollTop,left:k.scrollLeft}));p.focus({preventScroll:!0});for(const{el:k,top:C,left:_}of v)k.scrollTop!==C&&(k.scrollTop=C),k.scrollLeft!==_&&(k.scrollLeft=_)}return Un(()=>{t.findReplace.registerFocusFn(g)}),(p,v)=>(ge(),Ie("div",{class:"sd-find-replace",onKeydown:Qo(sn(d,["stop"]),["esc"])},[Oe("div",cS,[i.value?(ge(),Ie("button",{key:0,type:"button",class:an(["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:v[0]||(v[0]=k=>e.findReplace.showReplace.value=!e.findReplace.showReplace.value)},[...v[14]||(v[14]=[Oe("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true"},[Oe("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,uS)):mt("",!0),Oe("div",{class:an(["sd-find-replace__field",{"sd-find-replace__field--error":a.value}])},[v[15]||(v[15]=Oe("svg",{class:"sd-find-replace__search-icon",viewBox:"0 0 16 16",width:"15",height:"15","aria-hidden":"true"},[Oe("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)),Oe("input",{ref_key:"findInputRef",ref:n,value:e.findReplace.findQuery.value,onInput:v[1]||(v[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,dS),e.findReplace.findQuery.value&&!a.value?(ge(),Ie("span",fS,qt(e.findReplace.matchLabel.value),1)):mt("",!0),Oe("button",{type:"button",class:an(["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:v[2]||(v[2]=sn(()=>{},["prevent"])),onClick:v[3]||(v[3]=k=>e.findReplace.caseSensitive.value=!e.findReplace.caseSensitive.value)},qt(e.findReplace.texts.matchCaseLabel),43,hS),o.value?(ge(),Ie("button",{key:1,type:"button",class:an(["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:v[4]||(v[4]=sn(()=>{},["prevent"])),onClick:v[5]||(v[5]=k=>e.findReplace.ignoreDiacritics.value=!e.findReplace.ignoreDiacritics.value)},qt(e.findReplace.texts.ignoreDiacriticsLabel),43,pS)):mt("",!0),s.value?(ge(),Ie("button",{key:2,type:"button",class:an(["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:v[6]||(v[6]=sn(()=>{},["prevent"])),onClick:v[7]||(v[7]=k=>e.findReplace.regex.value=!e.findReplace.regex.value)},qt(e.findReplace.texts.regexLabel),43,mS)):mt("",!0)],2),Oe("div",gS,[Oe("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:v[8]||(v[8]=k=>c())},[...v[16]||(v[16]=[Oe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Oe("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,vS),Oe("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:v[9]||(v[9]=k=>u())},[...v[17]||(v[17]=[Oe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Oe("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,yS),v[19]||(v[19]=Oe("span",{class:"sd-find-replace__divider","aria-hidden":"true"},null,-1)),Oe("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},[...v[18]||(v[18]=[Oe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Oe("path",{d:"m4.5 4.5 7 7m0-7-7 7",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,bS)])]),e.findReplace.showReplace.value&&i.value?(ge(),Ie("div",wS,[v[20]||(v[20]=Oe("span",{class:"sd-find-replace__row-indent","aria-hidden":"true"},null,-1)),Oe("div",CS,[Oe("input",{value:e.findReplace.replaceText.value,onInput:v[10]||(v[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:v[11]||(v[11]=Qo(sn(k=>e.findReplace.replaceCurrent(),["prevent"]),["enter"]))},null,40,kS)]),Oe("div",SS,[Oe("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceLabel,onClick:v[12]||(v[12]=k=>e.findReplace.replaceCurrent())},qt(e.findReplace.texts.replaceLabel),9,_S),Oe("button",{type:"button",class:"sd-find-replace__btn sd-find-replace__btn--action",disabled:r.value,title:e.findReplace.texts.replaceAllLabel,onClick:v[13]||(v[13]=k=>e.findReplace.replaceAll())},qt(e.findReplace.texts.replaceAllLabel),9,AS)])])):mt("",!0),a.value?(ge(),Ie("div",IS,[i.value?(ge(),Ie("span",ES)):mt("",!0),Oe("span",TS,qt(a.value),1)])):mt("",!0)],40,lS))}},RS=yn(xS,[["__scopeId","data-v-41f37c29"]])}));Mt();var fr={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 TM(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 xM({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(""),g=ne(""),p=ne(!1),v=ne(!1),k=ne(!1),C=ne(!1),_=ne(0),y=ne(-1),w=ne(!0),x=ne(!1),P=ne(!0),N=ne(!1),G=ne(null);let R=fr;const F=_e(()=>h.value?_.value===0?R.noResultsLabel:`${y.value+1} of ${_.value}`:""),Z=_e(()=>_.value>0),D=_e(()=>Z.value&&!x.value&&w.value);let B=null,T=null;function V(W){return typeof W?.commands?.setSearchSession=="function"}function J(){try{const W=(typeof o=="function"?o():null)?.search;return W&&typeof W.search=="function"?W:null}catch{return null}}function q(W){W&&(_.value=typeof W.total=="number"?W.total:0,y.value=typeof W.activeIndex=="number"?W.activeIndex:-1,w.value=W.canReplace===!0,G.value=W.reason==="search-invalid-pattern"?R.invalidPatternLabel:null)}function se(){if(a){pe();return}if(s){if(!h.value){try{s.commands.clearSearchSession()}catch{}_.value=0,y.value=-1;return}try{const W=s.commands.setSearchSession(h.value,{caseSensitive:p.value,ignoreDiacritics:v.value,highlight:!0,searchModel:Te().includeDeletedText?"raw":"visible"});_.value=W.matches.length,y.value=W.activeMatchIndex}catch{}}}function pe(){const W=a;if(W){if(!h.value){try{W.clear()}catch{}_.value=0,y.value=-1,G.value=null;return}try{q(W.search(h.value,{caseSensitive:p.value,includeDeletedText:Te().includeDeletedText===!0,regex:k.value}))}catch{}}}function Ne(){B&&clearTimeout(B),B=setTimeout(se,150)}zt(h,()=>{c.value&&Ne()}),zt(p,()=>{c.value&&se()}),zt(v,()=>{c.value&&se()}),zt(k,()=>{c.value&&se()});let he=!0;function ye(){if(Z.value){if(a){try{a.next(),q(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.nextSearchMatch().activeMatchIndex}catch{}}}function ce(){if(Z.value){if(a){try{a.previous(),q(a.getSnapshot())}catch{}return}if(s)try{y.value=s.commands.previousSearchMatch().activeMatchIndex}catch{}}}function ke(){if(he&&!x.value&&Z.value){if(a){if(!w.value)return;const W=a;x.value=!0;const te=aS(W,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let Y=null;try{Y=W.replace(g.value)}catch{}Y&&typeof Y.then=="function"?Promise.resolve(Y).then(te,te):te();return}if(s)try{const W=s.commands.replaceSearchMatch(g.value);_.value=W.matches.length,y.value=W.activeMatchIndex}catch{}}}function ie(){if(he&&!x.value&&Z.value){if(a){if(!w.value)return;const W=a;x.value=!0;const te=aS(W,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let Y=null;try{Y=W.replaceAll(g.value)}catch{}Y&&typeof Y.then=="function"?Promise.resolve(Y).then(te,te):te();return}if(s)try{s.commands.replaceAllSearchMatches(g.value),_.value=0,y.value=-1}catch{}}}function xe(){if(a){try{q(a.getSnapshot())}catch{}return}const W=TM(s);if(!W)return;const te=W.searchResults,Y=Array.isArray(te)?te.length:0,X=W.activeMatchIndex??-1;Y!==_.value&&(_.value=Y),X!==y.value&&(y.value=X)}function Je(){st(),T=setInterval(xe,200)}function st(){B&&clearTimeout(B),B=null,T&&clearInterval(T),T=null}function Tt(){h.value="",g.value="",p.value=!1,v.value=!1,k.value=!1,G.value=null,C.value=!1,_.value=0,y.value=-1,w.value=!0,x.value=!1}function Te(){const W=typeof r=="function"?r():void 0;if(W===!1||W==null)return{enabled:!1,texts:fr,replaceEnabled:!0};if(W===!0)return{enabled:!0,texts:fr,replaceEnabled:!0};const te=typeof W=="object"?W:{};if(te.component!=null&&typeof te.render=="function")throw new Error('modules.surfaces.findReplace cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{findPlaceholder:te.findPlaceholder??fr.findPlaceholder,findAriaLabel:te.findAriaLabel??fr.findAriaLabel,replacePlaceholder:te.replacePlaceholder??fr.replacePlaceholder,replaceAriaLabel:te.replaceAriaLabel??fr.replaceAriaLabel,noResultsLabel:te.noResultsLabel??fr.noResultsLabel,previousMatchLabel:te.previousMatchLabel??fr.previousMatchLabel,previousMatchAriaLabel:te.previousMatchAriaLabel??fr.previousMatchAriaLabel,nextMatchLabel:te.nextMatchLabel??fr.nextMatchLabel,nextMatchAriaLabel:te.nextMatchAriaLabel??fr.nextMatchAriaLabel,closeLabel:te.closeLabel??fr.closeLabel,closeAriaLabel:te.closeAriaLabel??fr.closeAriaLabel,replaceLabel:te.replaceLabel??fr.replaceLabel,replaceAllLabel:te.replaceAllLabel??fr.replaceAllLabel,toggleReplaceLabel:te.toggleReplaceLabel??fr.toggleReplaceLabel,toggleReplaceAriaLabel:te.toggleReplaceAriaLabel??fr.toggleReplaceAriaLabel,matchCaseLabel:te.matchCaseLabel??fr.matchCaseLabel,matchCaseAriaLabel:te.matchCaseAriaLabel??fr.matchCaseAriaLabel,regexLabel:te.regexLabel??fr.regexLabel,regexAriaLabel:te.regexAriaLabel??fr.regexAriaLabel,invalidPatternLabel:te.invalidPatternLabel??fr.invalidPatternLabel,ignoreDiacriticsLabel:te.ignoreDiacriticsLabel??fr.ignoreDiacriticsLabel,ignoreDiacriticsAriaLabel:te.ignoreDiacriticsAriaLabel??fr.ignoreDiacriticsAriaLabel},replaceEnabled:te.replaceEnabled??!0,includeDeletedText:te.includeDeletedText??!1,component:te.component,props:te.props,render:te.render,resolver:te.resolver,floating:te.floating&&typeof te.floating=="object"?te.floating:void 0}}function je(W,te){if(typeof W.resolver=="function"){const Y=W.resolver(te);if(Y!=null&&Y.type!=="default"){if(Y.type==="none")return{suppressed:!0};if(Y.type==="custom")return{component:Y.component,props:Y.props};if(Y.type==="external")return{render:Y.render}}}return W.component!=null?{component:W.component,props:W.props}:typeof W.render=="function"?{render:W.render}:{builtin:!0}}function Ye(W,te){return{findQuery:h,replaceText:g,caseSensitive:p,ignoreDiacritics:v,regex:k,showReplace:C,matchCount:_,activeMatchIndex:y,matchLabel:F,hasMatches:Z,canReplace:D,replaceCanMutate:w,replacePending:x,ignoreDiacriticsSupported:P,regexSupported:N,searchError:G,replaceEnabled:W.replaceEnabled??!0,texts:W.texts,goNext:ye,goPrev:ce,replaceCurrent:ke,replaceAll:ie,registerFocusFn:Y=>{d=Y},close:Y=>te(Y)}}function $(W){return{get findQuery(){return W.findQuery.value},set findQuery(te){W.findQuery.value=te},get replaceText(){return W.replaceText.value},set replaceText(te){W.replaceText.value=te},get caseSensitive(){return W.caseSensitive.value},set caseSensitive(te){W.caseSensitive.value=te},get ignoreDiacritics(){return W.ignoreDiacritics.value},set ignoreDiacritics(te){W.ignoreDiacritics.value=te},get regex(){return W.regex.value},set regex(te){W.regex.value=te},get regexSupported(){return W.regexSupported.value},get searchError(){return W.searchError.value},get replaceCanMutate(){return W.replaceCanMutate.value},get showReplace(){return W.showReplace.value},set showReplace(te){W.showReplace.value=te},get matchCount(){return W.matchCount.value},get activeMatchIndex(){return W.activeMatchIndex.value},get matchLabel(){return W.matchLabel.value},get hasMatches(){return W.hasMatches.value},get canReplace(){return W.canReplace.value},get replacePending(){return W.replacePending.value},get ignoreDiacriticsSupported(){return W.ignoreDiacriticsSupported.value},replaceEnabled:W.replaceEnabled,texts:W.texts,goNext:W.goNext,goPrev:W.goPrev,replaceCurrent:W.replaceCurrent,replaceAll:W.replaceAll,registerFocusFn:W.registerFocusFn,close:W.close}}function S(W){if(W){if(typeof W?.commands?.clearSearchSession=="function"){try{W.commands.clearSearchSession()}catch{}return}if(a&&W===s)try{a.clear()}catch{}}}function ee(){try{if(l||!e()||!t())return!1;if(i&&c.value)return!0;const W=Te();if(!W.enabled||je(W,{texts:W.texts,replaceEnabled:W.replaceEnabled??!0}).suppressed)return!1;if(!V(t())){const te=J();if(!te)return!1;try{if(te.getSnapshot?.().available!==!0)return!1}catch{return!1}}return!0}catch{return!1}}async function O(){if(l)return;const W=e();if(W){if(i&&c.value){d?.();return}if(!u){u=!0;try{const te=t();if(!te){u=!1;return}const Y=Te();if(!Y.enabled){u=!1;return}const X=je(Y,{texts:Y.texts,replaceEnabled:Y.replaceEnabled??!0});if(X.suppressed){u=!1;return}Tt(),R=Y.texts,he=Y.replaceEnabled??!0;const be={placement:"top-right",autoFocus:!0,width:420,...Y.floating??{}};if(s&&s!==te&&S(s),s=te,a=V(te)?null:J(),P.value=!a,N.value=!!a,a)try{q(a.getSnapshot())}catch{}d=null;let ve=()=>{};const we=Ye(Y,at=>ve(at));let Be;if(X.component)Be=W.open({mode:"floating",ariaLabel:Y.texts.findAriaLabel,closeOnEscape:!0,floating:be,component:Xr(X.component),props:{...X.props,findReplace:we}});else if(X.render){const at=X.render;Be=W.open({mode:"floating",ariaLabel:Y.texts.findAriaLabel,closeOnEscape:!0,floating:be,render:Ct=>at({container:Ct.container,findReplace:$(we),resolve:Ct.resolve,close:Ct.close,surfaceId:Ct.surfaceId,mode:Ct.mode})})}else{let at;try{at=(await Promise.resolve().then(()=>(EM(),IM))).default}catch{u=!1;return}if(l||i&&c.value){u=!1;return}const Ct=t()||te;s!==Ct&&(S(s),s=Ct,a=V(Ct)?null:J(),P.value=!a),Be=W.open({mode:"floating",ariaLabel:Y.texts.findAriaLabel,component:Xr(at),closeOnEscape:!0,floating:be,props:{findReplace:we}})}ve=at=>Be.close(at??"programmatic"),i=Be,c.value=!0,u=!1,Je();const rt=Be.id;Be.result.then(()=>{i?.id===rt?(st(),S(s),i=null,c.value=!1,d=null):S(te!==s?te:null)})}catch(te){throw u=!1,te}}}}function j(){i&&i.close("programmatic")}n&&zt(n,(W,te)=>{!c.value||!i||W!==te&&(S(te),j())});function U(){l=!0,st(),j(),s=null,a=null,d=null}return{open:O,close:j,isOpen:c,wouldOpen:ee,destroy:U}}var yf=null;function w0(e){e!=null&&(yf=e)}function RM(e){yf===e&&(yf=null)}function MM(e){return yf===null||yf===e}function LM(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)&&MM(n)}var PM=/^(https?|mailto|tel):/i,DM=/^(javascript|data|vbscript):/i,OM=/^[a-z][a-z0-9+.-]*:/i;function FM(e){if(typeof e!="string")return null;const t=e.trim();return t?t.startsWith("#")?{href:t}:DM.test(t)?null:OM.test(t)?PM.test(t)?{href:t}:null:{href:t}:null}var NM='<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>',BM='<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>',zM='<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>',MS='<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
|
`,HM=`<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
|
`,UM='<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>',jM=`<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)">
|
|
@@ -99,10 +99,10 @@ js: import "konva/skia-backend";
|
|
|
99
99
|
`,I_=()=>{if(typeof document>"u")throw new Error(FD)},Ui=class cI{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 cI(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=Ee._getRotation(l.rotation),l}},ND="[object Array]",BD="[object Number]",zD="[object String]",VD="[object Boolean]",HD=Math.PI/180,UD=180/Math.PI,kf="#",jD="",GD="0",WD="Konva warning: ",E_="Konva error: ",KD="rgb(",x0={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]},qD=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,qp=[],Sf=null,YD=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(e){setTimeout(e,16)};const Ee={_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)===ND},_isNumber(e){return Object.prototype.toString.call(e)===BD&&!isNaN(e)&&isFinite(e)},_isString(e){return Object.prototype.toString.call(e)===zD},_isBoolean(e){return Object.prototype.toString.call(e)===VD},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){qp.push(e),qp.length===1&&YD(function(){const t=qp;qp=[],t.forEach(function(n){n()})})},createCanvasElement(){I_();const e=document.createElement("canvas");try{e.style=e.style||{}}catch{}return e},createImageElement(){return I_(),document.createElement("img")},_isInDocument(e){for(;e=e.parentNode;)if(e==document)return!0;return!1},_urlToImage(e,t){const n=Ee.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(kf,jD);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=GD+e;return kf+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),kf+this._rgbToHex(e,t,n)},getSnappedHexColor(e){const t=this._hexToRgb(e);return kf+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 x0?(t=x0[e],{r:t[0],g:t[1],b:t[2]}):e[0]===kf?this._hexToRgb(e.substring(1)):e.substr(0,4)===KD?(t=qD.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",Ee._namedColorToRBA(e)||Ee._hex3ColorToRGBA(e)||Ee._hex4ColorToRGBA(e)||Ee._hex6ColorToRGBA(e)||Ee._hex8ColorToRGBA(e)||Ee._rgbColorToRGBA(e)||Ee._rgbaColorToRGBA(e)||Ee._hslColorToRGBA(e)},_namedColorToRBA(e){const t=x0[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*HD},radToDeg(e){return e*UD},_degToRad(e){return Ee.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),Ee.degToRad(e)},_radToDeg(e){return Ee.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),Ee.radToDeg(e)},_getRotation(e){return wt.angleDeg?Ee.radToDeg(e):e},_capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)},throw(e){throw new Error(E_+e)},error(e){console.error(E_+e)},warn(e){wt.showWarnings&&console.warn(WD+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=Ee.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=Ee._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=Ee._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||Ee._isElement(e[n]))if(t.configurable)delete e[n];else return null;else if(Ee._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){wt.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 g;typeof o=="number"?g=o:g=i<o.length?o[i]:0,g=r*Math.cos(Math.PI/n)*Math.min(1,g/r*2);const p={x:u.x/d,y:u.y/d},v={x:c.x/h,y:c.y/h},k={x:a.x-p.x*g,y:a.y-p.y*g},C={x:a.x+v.x*g,y:a.y+v.y*g};i===0?e.moveTo(k.x,k.y):e.lineTo(k.x,k.y),e.arcTo(a.x,a.y,C.x,C.y,g)}}};function XD(e){const t=[],n=e.length,r=Ee;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 T_=",",ZD="(",QD=")",JD="([",$D="])",eO=";",tO="()",nO="=",x_=["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"],rO=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],oO=100,Yp=null;function R_(){if(Yp!==null)return Yp;try{const e=Ee.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(Yp=!1,!1)}catch{return Yp=!1,!1}}var Xp=class{constructor(e){this.canvas=e,wt.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+=tO:Ee._isArray(l[0])?o+=JD+l.join(T_)+$D:(t&&(l=l.map(u=>typeof u=="number"?Math.floor(u):u)),o+=ZD+l.join(T_)+QD)):(o+=s.property,e||(o+=nO+s.val)),o+=eO;return o}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,n;t.push(e),n=t.length,n>=oO&&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=x_.length,n=this.setAttr,r,o;const i=function(s){let a=e[s],l;e[s]=function(){return o=XD(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(x_[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)}};rO.forEach(function(e){Object.defineProperty(Xp.prototype,e,{get(){return this._context[e]},set(t){this._context[e]=t}})});var iO=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)}},sO=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()}}},Zp;function aO(){if(Zp)return Zp;const e=Ee.createCanvasElement(),t=e.getContext("2d");return Zp=(function(){return(wt._global.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)})(),Ee.releaseCanvas(e),Zp}var R0=class{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1,this.pixelRatio=(e||{}).pixelRatio||wt.pixelRatio||aO(),this._canvas=Ee.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 Ee.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}},nl=class extends R0{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new iO(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}},M0=class extends R0{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new sO(this),this.setSize(e.width,e.height)}};const Fn={get isDragging(){let e=!1;return Fn._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(e=!0)}),e},justDragged:!1,get node(){let e;return Fn._dragElements.forEach(t=>{e=t.node}),e},_dragElements:new Map,_drag(e){const t=[];Fn._dragElements.forEach((n,r)=>{const{node:o}=n,i=o.getStage();i.setPointersPositions(e),n.pointerId===void 0&&(n.pointerId=Ee._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=[];Fn._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")&&(Fn.justDragged=!0,wt._mouseListenClick=!1,wt._touchListenClick=!1,wt._pointerListenClick=!1,n.dragStatus="stopped");const i=n.node.getLayer()||n.node instanceof wt.Stage&&n.node;i&&t.indexOf(i)===-1&&t.push(i)}),t.forEach(n=>{n.draw()})},_endDragAfter(e){Fn._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:e},!0),t.dragStatus!=="dragging"&&Fn._dragElements.delete(n)})}};wt.isBrowser&&(window.addEventListener("mouseup",Fn._endDragBefore,!0),window.addEventListener("touchend",Fn._endDragBefore,!0),window.addEventListener("touchcancel",Fn._endDragBefore,!0),window.addEventListener("mousemove",Fn._drag),window.addEventListener("touchmove",Fn._drag),window.addEventListener("mouseup",Fn._endDragAfter,!1),window.addEventListener("touchend",Fn._endDragAfter,!1),window.addEventListener("touchcancel",Fn._endDragAfter,!1));function rl(e){return Ee._isString(e)?'"'+e+'"':Object.prototype.toString.call(e)==="[object Number]"||Ee._isBoolean(e)?e:Object.prototype.toString.call(e)}function M_(e){return e>255?255:e<0?0:Math.round(e)}function vt(){if(wt.isUnminified)return function(e,t){return Ee._isNumber(e)||Ee.warn(rl(e)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),e}}function Qp(e){if(wt.isUnminified)return function(t,n){let r=Ee._isNumber(t),o=Ee._isArray(t)&&t.length==e;return!r&&!o&&Ee.warn(rl(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array<number>('+e+")"),t}}function L0(){if(wt.isUnminified)return function(e,t){return Ee._isNumber(e)||e==="auto"||Ee.warn(rl(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),e}}function Jl(){if(wt.isUnminified)return function(e,t){return Ee._isString(e)||Ee.warn(rl(e)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),e}}function L_(){if(wt.isUnminified)return function(e,t){const n=Ee._isString(e),r=Object.prototype.toString.call(e)==="[object CanvasGradient]"||e&&e.addColorStop;return n||r||Ee.warn(rl(e)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),e}}function lO(){if(wt.isUnminified)return function(e,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&e instanceof n||(Ee._isArray(e)?e.forEach(function(r){Ee._isNumber(r)||Ee.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):Ee.warn(rl(e)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),e}}function ji(){if(wt.isUnminified)return function(e,t){return e===!0||e===!1||Ee.warn(rl(e)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),e}}function cO(e){if(wt.isUnminified)return function(t,n){return t==null||Ee.isObject(t)||Ee.warn(rl(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+e),t}}var _f="get",Af="set";const ue={addGetterSetter(e,t,n,r,o){ue.addGetter(e,t,n),ue.addSetter(e,t,r,o),ue.addOverloadedGetterSetter(e,t)},addGetter(e,t,n){const r=_f+Ee._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=Af+Ee._capitalize(t);e.prototype[o]||ue.overWriteSetter(e,t,n,r)},overWriteSetter(e,t,n,r){const o=Af+Ee._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=Ee._capitalize,a=_f+s(t),l=Af+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=cO(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},ue.addOverloadedGetterSetter(e,t)},addOverloadedGetterSetter(e,t){const n=Ee._capitalize(t),r=Af+n,o=_f+n;e.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[o]()}},addDeprecatedGetterSetter(e,t,n,r){Ee.error("Adding deprecated "+t);const o=_f+Ee._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";e.prototype[o]=function(){Ee.error(i);const s=this.attrs[t];return s===void 0?n:s},ue.addSetter(e,t,r,function(){Ee.error(i)}),ue.addOverloadedGetterSetter(e,t)},backCompat(e,t){Ee.each(t,function(n,r){const o=e.prototype[r],i=_f+Ee._capitalize(n),s=Af+Ee._capitalize(n);function a(){o.apply(this,arguments),Ee.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 uO(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=wt.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=wt.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=wt.Filters;l&&l.Contrast&&l.Contrast.call(this,s)}}case"grayscale":return function(i){const s=wt.Filters;s&&s.Grayscale&&s.Grayscale.call(this,i)};case"sepia":return function(i){const s=wt.Filters;s&&s.Sepia&&s.Sepia.call(this,i)};case"invert":return function(i){const s=wt.Filters;s&&s.Invert&&s.Invert.call(this,i)};default:Ee.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}var Jp="absoluteOpacity",P_="allEventListeners",fa="absoluteTransform",D_="absoluteScale",$l="canvas",dO="Change",fO="children",hO="konva",P0="listening",pO="mouseenter",mO="mouseleave",gO="pointerenter",vO="pointerleave",yO="touchenter",bO="touchleave",O_="set",F_="Shape",$p=" ",N_="stage",ol="transform",wO="Stage",D0="visible",CO=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join($p),kO=1,kt=class lh{constructor(t){this._id=kO++,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===ol||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===ol||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($p);this.on(o,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get($l)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===fa&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has($l)){const{scene:t,filter:n,hit:r}=this._cache.get($l);Ee.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete($l)}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){Ee.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,g=Math.abs(Math.round(r.y)-l)>.5?1:0;o+=u*2+h,i+=u*2+g,a-=u,l-=u;const p=new nl({pixelRatio:s,width:o,height:i}),v=new nl({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),k=new M0({pixelRatio:d,width:o,height:i}),C=p.getContext(),_=k.getContext(),y=new nl({width:p.width/p.pixelRatio+Math.abs(a),height:p.height/p.pixelRatio+Math.abs(l),pixelRatio:p.pixelRatio}),w=y.getContext();return k.isCache=!0,p.isCache=!0,this._cache.delete($l),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(p.getContext()._context.imageSmoothingEnabled=!1,v.getContext()._context.imageSmoothingEnabled=!1),C.save(),_.save(),w.save(),C.translate(-a,-l),_.translate(-a,-l),w.translate(-a,-l),y.x=a,y.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Jp),this._clearSelfAndDescendantCache(D_),this.drawScene(p,this,y),this.drawHit(k,this),this._isUnderCache=!1,C.restore(),_.restore(),c&&(C.save(),C.beginPath(),C.rect(0,0,o,i),C.closePath(),C.setAttr("strokeStyle","red"),C.setAttr("lineWidth",5),C.stroke(),C.restore()),Ee.releaseCanvas(y._canvas),this._cache.set($l,{scene:p,filter:v,hit:k,x:a,y:l}),this._requestDraw(),this}isCached(){return this._cache.has($l)}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"&&R_(),typeof t[h]!="string"||!R_()){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=uO(u)),u.call(this,a),i.putImageData(a,0,0)}catch(h){Ee.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(P_),t.length===3)return this._delegate.apply(this,t);const o=n.split($p);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($p),o=r.length,i,s,a,l,u,c;if(this._cache&&this._cache.delete(P_),!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=Ee.cloneObject(i),i.currentTarget=s[a],r.call(s[a],i)}),this}remove(){return this.isDragging()&&this.stopDrag(),Fn._dragElements.delete(this._id),Fn._dragElements.forEach((t,n)=>{this.isAncestorOf(t.node)&&Fn._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(fa),this._clearSelfAndDescendantCache(Jp),this._clearSelfAndDescendantCache(D_),this._clearSelfAndDescendantCache(N_),this._clearSelfAndDescendantCache(D0),this._clearSelfAndDescendantCache(P0)}_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"+Ee._capitalize(t);return Ee._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!==fO&&(r=O_+Ee._capitalize(n),Ee._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(P0,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;Fn._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===r)&&(o=!0)});const i=!n&&!wt.hitOnDragEnabled&&(o||wt.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!==F_&&(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!==wO&&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(ol),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(ol);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(ol),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 Ee.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 Ee.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 Ee.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 Ee.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 Ee.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Ee.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(Jp,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=Ee.isObject(r)&&!Ee._isPlainObject(r)&&!Ee._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 Ee._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],Ee.isValidSelector(i)||(Ee.warn('Selector "'+i+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),Ee.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),Ee.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(N_,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(ol,this._getTransform)}_getTransform(){var t,n;const r=this._cache.get(ol)||new Ui;r.reset();const o=this.x(),i=this.y(),s=wt.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=Ee.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(hO)<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 nl({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 nl({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,Ee._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():wt.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+dO,{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[O_+Ee._capitalize(t)];return Ee._isFunction(r)?r.call(this,n):this._setAttr(t,n),this}_requestDraw(){if(wt.autoDrawEnabled){const t=this.getLayer()||this.getStage();t?.batchDraw()}}_setAttr(t,n){const r=this.attrs[t];r===n&&!Ee.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===F_&&(n.target=this);const o=[pO,mO,gO,vO,yO,bO];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=lh.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,lh.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;Fn._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){Fn._dragElements.has(this._id)||this._createDragElement(t);const r=Fn._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:Ee.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=Fn._dragElements.get(this._id);n&&(n.dragStatus="stopped"),Fn._endDragBefore(t),Fn._endDragAfter(t)}setDraggable(t){this._setAttr("draggable",t),this._dragChange()}isDragging(){const t=Fn._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||wt.dragButtons.indexOf(t.evt.button)>=0)||this.isDragging())return;let n=!1;Fn._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=Fn._dragElements.get(this._id),n=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";n?this.stopDrag():r&&Fn._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 Ee.haveIntersection(r,this.getClientRect())}static create(t,n){return Ee._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=lh.prototype.getClassName.call(t),o=t.children,i,s,a;n&&(t.attrs.container=n),wt[r]||(Ee.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const l=wt[r];if(i=new l(t.attrs),o)for(s=o.length,a=0;a<s;a++)i.add(lh._createNode(o[a]));return i}};kt.protoListenerMap=new Map,kt.prototype.nodeType="Node",kt.prototype._attrsAffectingSize=[],kt.prototype.eventListeners={},kt.prototype.on(CO,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(ol),this._clearSelfAndDescendantCache(fa)}),kt.prototype.on("visibleChange.konva",function(){this._clearSelfAndDescendantCache(D0)}),kt.prototype.on("listeningChange.konva",function(){this._clearSelfAndDescendantCache(P0)}),kt.prototype.on("opacityChange.konva",function(){this._clearSelfAndDescendantCache(Jp)});var $n=ue.addGetterSetter;$n(kt,"zIndex"),$n(kt,"absolutePosition"),$n(kt,"position"),$n(kt,"x",0,vt()),$n(kt,"y",0,vt()),$n(kt,"globalCompositeOperation","source-over",Jl()),$n(kt,"opacity",1,vt()),$n(kt,"name","",Jl()),$n(kt,"id","",Jl()),$n(kt,"rotation",0,vt()),ue.addComponentsGetterSetter(kt,"scale",["x","y"]),$n(kt,"scaleX",1,vt()),$n(kt,"scaleY",1,vt()),ue.addComponentsGetterSetter(kt,"skew",["x","y"]),$n(kt,"skewX",0,vt()),$n(kt,"skewY",0,vt()),ue.addComponentsGetterSetter(kt,"offset",["x","y"]),$n(kt,"offsetX",0,vt()),$n(kt,"offsetY",0,vt()),$n(kt,"dragDistance",void 0,vt()),$n(kt,"width",0,vt()),$n(kt,"height",0,vt()),$n(kt,"listening",!0,ji()),$n(kt,"preventDefault",!0,ji()),$n(kt,"filters",void 0,function(e){return this._filterUpToDate=!1,e}),$n(kt,"visible",!0,ji()),$n(kt,"transformsEnabled","all",Jl()),$n(kt,"size"),$n(kt,"dragBoundFunc"),$n(kt,"draggable",!1,ji()),ue.backCompat(kt,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});var hi=class extends kt{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=kt.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=kt.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 g=h.getMatrix();i.transform(g[0],g[1],g[2],g[3],g[4],g[5]),i.beginPath();let p;if(l)p=l.call(this,i,this);else{const v=this.clipX(),k=this.clipY();i.rect(v||0,k||0,s,a)}i.clip.apply(i,p),g=h.copy().invert().getMatrix(),i.transform(g[0],g[1],g[2],g[3],g[4],g[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 g=h.getClientRect({relativeTo:u,skipShadow:e.skipShadow,skipStroke:e.skipStroke});g.width===0&&g.height===0||(o===void 0?(o=g.x,i=g.y,s=g.x+g.width,a=g.y+g.height):(o=Math.min(o,g.x),i=Math.min(i,g.y),s=Math.max(s,g.x+g.width),a=Math.max(a,g.y+g.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)}};ue.addComponentsGetterSetter(hi,"clip",["x","y","width","height"]),ue.addGetterSetter(hi,"clipX",void 0,vt()),ue.addGetterSetter(hi,"clipY",void 0,vt()),ue.addGetterSetter(hi,"clipWidth",void 0,vt()),ue.addGetterSetter(hi,"clipHeight",void 0,vt()),ue.addGetterSetter(hi,"clipFunc");var If=new Map,B_=wt._global.PointerEvent!==void 0;function O0(e){return If.get(e)}function F0(e){return{evt:e,pointerId:e.pointerId}}function z_(e,t){return If.get(e)===t}function V_(e,t){Ef(e),t.getStage()&&(If.set(e,t),B_&&t._fire("gotpointercapture",F0(new PointerEvent("gotpointercapture"))))}function Ef(e,t){const n=If.get(e);if(!n)return;const r=n.getStage();r&&r.content,If.delete(e),B_&&n._fire("lostpointercapture",F0(new PointerEvent("lostpointercapture")))}var SO="Stage",_O="string",H_="px",AO="mouseout",U_="mouseleave",j_="mouseover",G_="mouseenter",W_="mousemove",K_="mousedown",q_="mouseup",Tf="pointermove",xf="pointerdown",Cu="pointerup",Rf="pointercancel",IO="lostpointercapture",em="pointerout",Mf="pointerleave",tm="pointerover",nm="pointerenter",N0="contextmenu",Y_="touchstart",X_="touchend",Z_="touchmove",Q_="touchcancel",B0="wheel",EO=5,TO=[[G_,"_pointerenter"],[K_,"_pointerdown"],[W_,"_pointermove"],[q_,"_pointerup"],[U_,"_pointerleave"],[Y_,"_pointerdown"],[Z_,"_pointermove"],[X_,"_pointerup"],[Q_,"_pointercancel"],[j_,"_pointerover"],[B0,"_wheel"],[N0,"_contextmenu"],[xf,"_pointerdown"],[Tf,"_pointermove"],[Cu,"_pointerup"],[Rf,"_pointercancel"],[Mf,"_pointerleave"],[IO,"_lostpointercapture"]],z0={mouse:{[em]:AO,[Mf]:U_,[tm]:j_,[nm]:G_,[Tf]:W_,[xf]:K_,[Cu]:q_,[Rf]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[em]:"touchout",[Mf]:"touchleave",[tm]:"touchover",[nm]:"touchenter",[Tf]:Z_,[xf]:Y_,[Cu]:X_,[Rf]:Q_,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[em]:em,[Mf]:Mf,[tm]:tm,[nm]:nm,[Tf]:Tf,[xf]:xf,[Cu]:Cu,[Rf]:Rf,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Lf=e=>e.indexOf("pointer")>=0?"pointer":e.indexOf("touch")>=0?"touch":"mouse",ku=e=>{const t=Lf(e);if(t==="pointer")return wt.pointerEventsEnabled&&z0.pointer;if(t==="touch")return z0.touch;if(t==="mouse")return z0.mouse};function J_(e={}){return(e.clipFunc||e.clipWidth||e.clipHeight)&&Ee.warn("Stage does not support clipping. Please use clip for Layers or Groups."),e}var xO="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 Pf=[];var rm=class extends hi{constructor(e){super(J_(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),Pf.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{J_(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",n=e.getType()==="FastLayer";t||n||Ee.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===_O){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"),hi.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&Ee._isInDocument(e)&&this.container().removeChild(e);const t=Pf.indexOf(this);return t>-1&&Pf.splice(t,1),Ee.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}:(Ee.warn(xO),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 nl({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+H_,this.content.style.height=t+H_),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>EO&&Ee.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(),wt.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return z_(e,this)}setPointerCapture(e){V_(e,this)}releaseCapture(e){Ef(e,this)}getLayers(){return this.children}_bindContentEvents(){wt.isBrowser&&TO.forEach(([e,t])=>{this.content.addEventListener(e,n=>{this[t](n)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=ku(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=ku(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=ku(e.type),n=Lf(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(n),o=!(wt.isDragging()||wt.isTransforming())||wt.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=ku(e.type),n=Lf(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(o=>{const i=this.getIntersection(o);if(Fn.justDragged=!1,wt["_"+n+"ListenClick"]=!0,!i||!i.isListening()){this[n+"ClickStartShape"]=void 0;return}wt.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=ku(e.type),n=Lf(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(wt.isDragging()&&Fn.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(wt.isDragging()||wt.isTransforming())||wt.hitOnDragEnabled))return;const o={};let i=!1;const s=this._getTargetShape(n);this._changedPointerPositions.forEach(a=>{const l=O0(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=ku(e.type),n=Lf(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=O0(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;wt["_"+n+"InDblClickWindow"]?(d=!0,clearTimeout(this[n+"DblTimeout"])):Fn.justDragged||(wt["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"])),this[n+"DblTimeout"]=setTimeout(function(){wt["_"+n+"InDblClickWindow"]=!1},wt.dblClickWindow),l&&l.isListening()?(s=!0,this[n+"ClickEndShape"]=l,l._fireAndBubble(t.pointerup,{...c}),wt["_"+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),wt["_"+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}),wt["_"+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(N0,{evt:e}):this._fire(N0,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(B0,{evt:e}):this._fire(B0,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=O0(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(Cu,F0(e)),Ef(e.pointerId)}_lostpointercapture(e){Ef(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:Ee._getFirstPointerId(e)}],this._changedPointerPositions=[{x:n,y:r,id:Ee._getFirstPointerId(e)}])}_setPointerPosition(e){Ee.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 nl({width:this.width(),height:this.height()}),this.bufferHitCanvas=new M0({pixelRatio:1,width:this.width(),height:this.height()}),!wt.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 Ee.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}};rm.prototype.nodeType=SO,wr(rm),ue.addGetterSetter(rm,"container"),wt.isBrowser&&document.addEventListener("visibilitychange",()=>{Pf.forEach(e=>{e.batchDraw()})});var $_="hasShadow",e4="shadowRGBA",t4="patternImage",n4="linearGradient",r4="radialGradient",om;function V0(){return om||(om=Ee.createCanvasElement().getContext("2d"),om)}const Df={};function RO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function MO(e){e.stroke()}function LO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function PO(e){e.stroke()}function DO(){this._clearCache($_)}function OO(){this._clearCache(e4)}function FO(){this._clearCache(t4)}function NO(){this._clearCache(n4)}function BO(){this._clearCache(r4)}var ht=class extends kt{constructor(e){super(e);let t,n=0;for(;t=Ee.getHitColor(),!(t&&!(t in Df));)if(n++,n>=1e4){Ee.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=Ee.getRandomColor();break}this.colorKey=t,Df[t]=this}getContext(){return Ee.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Ee.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($_,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(t4,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(wt.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(n4,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(r4,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(e4,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=Ee.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 kt.prototype.destroy.call(this),delete Df[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){Ee.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),g=l+Math.abs(d),p=u&&this.shadowBlur()||0,v={width:h+p*2,height:g+p*2,x:-(s/2+p)+Math.min(c,0)+i.x,y:-(s/2+p)+Math.min(d,0)+i.y};return r?v:this._transformedRect(v,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 g=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/g,c.height/g)}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||Ee.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=Ee._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){Ee.error("Unable to draw hit graph from cached scene canvas. "+a.message)}return this}hasPointerCapture(e){return z_(e,this)}setPointerCapture(e){V_(e,this)}releaseCapture(e){Ef(e,this)}};ht.prototype._fillFunc=RO,ht.prototype._strokeFunc=MO,ht.prototype._fillFuncHit=LO,ht.prototype._strokeFuncHit=PO,ht.prototype._centroid=!1,ht.prototype.nodeType="Shape",wr(ht),ht.prototype.eventListeners={},ht.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",DO),ht.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",OO),ht.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",FO),ht.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",NO),ht.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",BO),ue.addGetterSetter(ht,"stroke",void 0,L_()),ue.addGetterSetter(ht,"strokeWidth",2,vt()),ue.addGetterSetter(ht,"fillAfterStrokeEnabled",!1),ue.addGetterSetter(ht,"hitStrokeWidth","auto",L0()),ue.addGetterSetter(ht,"strokeHitEnabled",!0,ji()),ue.addGetterSetter(ht,"perfectDrawEnabled",!0,ji()),ue.addGetterSetter(ht,"shadowForStrokeEnabled",!0,ji()),ue.addGetterSetter(ht,"lineJoin"),ue.addGetterSetter(ht,"lineCap"),ue.addGetterSetter(ht,"miterLimit"),ue.addGetterSetter(ht,"sceneFunc"),ue.addGetterSetter(ht,"hitFunc"),ue.addGetterSetter(ht,"dash"),ue.addGetterSetter(ht,"dashOffset",0,vt()),ue.addGetterSetter(ht,"shadowColor",void 0,Jl()),ue.addGetterSetter(ht,"shadowBlur",0,vt()),ue.addGetterSetter(ht,"shadowOpacity",1,vt()),ue.addComponentsGetterSetter(ht,"shadowOffset",["x","y"]),ue.addGetterSetter(ht,"shadowOffsetX",0,vt()),ue.addGetterSetter(ht,"shadowOffsetY",0,vt()),ue.addGetterSetter(ht,"fillPatternImage"),ue.addGetterSetter(ht,"fill",void 0,L_()),ue.addGetterSetter(ht,"fillPatternX",0,vt()),ue.addGetterSetter(ht,"fillPatternY",0,vt()),ue.addGetterSetter(ht,"fillLinearGradientColorStops"),ue.addGetterSetter(ht,"strokeLinearGradientColorStops"),ue.addGetterSetter(ht,"fillRadialGradientStartRadius",0),ue.addGetterSetter(ht,"fillRadialGradientEndRadius",0),ue.addGetterSetter(ht,"fillRadialGradientColorStops"),ue.addGetterSetter(ht,"fillPatternRepeat","repeat"),ue.addGetterSetter(ht,"fillEnabled",!0),ue.addGetterSetter(ht,"strokeEnabled",!0),ue.addGetterSetter(ht,"shadowEnabled",!0),ue.addGetterSetter(ht,"dashEnabled",!0),ue.addGetterSetter(ht,"strokeScaleEnabled",!0),ue.addGetterSetter(ht,"fillPriority","color"),ue.addComponentsGetterSetter(ht,"fillPatternOffset",["x","y"]),ue.addGetterSetter(ht,"fillPatternOffsetX",0,vt()),ue.addGetterSetter(ht,"fillPatternOffsetY",0,vt()),ue.addComponentsGetterSetter(ht,"fillPatternScale",["x","y"]),ue.addGetterSetter(ht,"fillPatternScaleX",1,vt()),ue.addGetterSetter(ht,"fillPatternScaleY",1,vt()),ue.addComponentsGetterSetter(ht,"fillLinearGradientStartPoint",["x","y"]),ue.addComponentsGetterSetter(ht,"strokeLinearGradientStartPoint",["x","y"]),ue.addGetterSetter(ht,"fillLinearGradientStartPointX",0),ue.addGetterSetter(ht,"strokeLinearGradientStartPointX",0),ue.addGetterSetter(ht,"fillLinearGradientStartPointY",0),ue.addGetterSetter(ht,"strokeLinearGradientStartPointY",0),ue.addComponentsGetterSetter(ht,"fillLinearGradientEndPoint",["x","y"]),ue.addComponentsGetterSetter(ht,"strokeLinearGradientEndPoint",["x","y"]),ue.addGetterSetter(ht,"fillLinearGradientEndPointX",0),ue.addGetterSetter(ht,"strokeLinearGradientEndPointX",0),ue.addGetterSetter(ht,"fillLinearGradientEndPointY",0),ue.addGetterSetter(ht,"strokeLinearGradientEndPointY",0),ue.addComponentsGetterSetter(ht,"fillRadialGradientStartPoint",["x","y"]),ue.addGetterSetter(ht,"fillRadialGradientStartPointX",0),ue.addGetterSetter(ht,"fillRadialGradientStartPointY",0),ue.addComponentsGetterSetter(ht,"fillRadialGradientEndPoint",["x","y"]),ue.addGetterSetter(ht,"fillRadialGradientEndPointX",0),ue.addGetterSetter(ht,"fillRadialGradientEndPointY",0),ue.addGetterSetter(ht,"fillPatternRotation",0),ue.addGetterSetter(ht,"fillRule",void 0,Jl()),ue.backCompat(ht,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var zO="beforeDraw",VO="draw",o4=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],HO=o4.length,ec=class extends hi{constructor(e){super(e),this.canvas=new nl,this.hitCanvas=new M0({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(){kt.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(!kt.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(kt.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(kt.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 kt.prototype.remove.call(this),e&&e.parentNode&&Ee._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"&&Ee.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(),kt.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(){Ee.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){Ee.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,Ee.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<HO;r++){const o=o4[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=Df[Ee.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(zO,{node:this}),this.clearBeforeDraw()&&o.getContext().clear(),hi.prototype.drawScene.call(this,o,t,n),this._fire(VO,{node:this}),this}drawHit(e,t){const n=this.getLayer(),r=e||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),hi.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){Ee.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return Ee.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 Ee.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};ec.prototype.nodeType="Layer",wr(ec),ue.addGetterSetter(ec,"imageSmoothingEnabled",!0),ue.addGetterSetter(ec,"clearBeforeDraw",!0),ue.addGetterSetter(ec,"hitGraphEnabled",!0,ji());var H0=class extends ec{constructor(e){super(e),this.listening(!1),Ee.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}};H0.prototype.nodeType="FastLayer",wr(H0);var Su=class extends hi{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&Ee.throw("You may only add groups and shapes to groups.")}};Su.prototype.nodeType="Group",wr(Su);var U0=(function(){return Ql.performance&&Ql.performance.now?function(){return Ql.performance.now()}:function(){return new Date().getTime()}})(),_u=class sd{constructor(t,n){this.id=sd.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:U0(),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=sd.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=U0(),sd._addAnimation(this),this}stop(){return sd._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(U0());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=sd;t.animations.length?(t._runFrames(),Ee.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,Ee.requestAnimFrame(this._animationLoop))}};_u.animations=[],_u.animIdCounter=0,_u.animRunning=!1;var UO={node:1,duration:1,easing:1,onFinish:1,yoyo:1},jO=1,i4=2,s4=3,a4=["fill","stroke","shadowColor"],GO=0,WO=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=i4,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=s4,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===i4?this.setTime(e):this.state===s4&&this.setTime(this.duration-e)}pause(){this.state=jO,this.fire("onPause")}getTimer(){return new Date().getTime()}},im=class Pr{constructor(t){const n=this,r=t.node,o=r._id,i=t.easing||Of.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=GO++;const u=r.getLayer()||(r instanceof wt.Stage?r.getLayers():null);u||Ee.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new _u(function(){n.tween.onEnterFrame()},u),this.tween=new WO(l,function(c){n._tweenFunc(c)},i,0,1,a*1e3,s),this._addListeners(),Pr.attrs[o]||(Pr.attrs[o]={}),Pr.attrs[o][this._id]||(Pr.attrs[o][this._id]={}),Pr.tweens[o]||(Pr.tweens[o]={});for(l in t)UO[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=Pr.tweens[o][t];c&&delete Pr.attrs[o][c][t];let d=r.getAttr(t);if(Ee._isArray(n))if(i=[],s=Math.max(n.length,d.length),t==="points"&&n.length!==d.length&&(n.length>d.length?(l=d,d=Ee._prepareArrayForTween(d,n,r.closed())):(a=n,n=Ee._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 g=Ee.colorToRGBA(d[h]);u=Ee.colorToRGBA(n[h]),d[h]=g,i.push({r:u.r-g.r,g:u.g-g.g,b:u.b-g.b,a:u.a-g.a})}else for(let h=0;h<s;h++)i.push(n[h]-d[h]);else a4.indexOf(t)!==-1?(d=Ee.colorToRGBA(d),u=Ee.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;Pr.attrs[o][this._id][t]={start:d,diff:i,end:n,trueEnd:a,trueStart:l},Pr.tweens[o][t]=this._id}_tweenFunc(t){const n=this.node,r=Pr.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,Ee._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 a4.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=Pr.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=Pr.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=Pr.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const o in r)delete Pr.tweens[t][o];delete Pr.attrs[t][n],Pr.tweens[t]&&(Object.keys(Pr.tweens[t]).length===0&&delete Pr.tweens[t],Object.keys(Pr.attrs[t]).length===0&&delete Pr.attrs[t])}};im.attrs={},im.tweens={},kt.prototype.to=function(e){const t=e.onFinish;e.node=this,e.onFinish=function(){this.destroy(),t&&t()},new im(e).play()};const Of={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-Of.BounceEaseOut(r-e,0,n,r)+t},BounceEaseInOut(e,t,n,r){return e<r/2?Of.BounceEaseIn(e*2,0,n,r)*.5+t:Of.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}},l4=Ee._assign(wt,{Util:Ee,Transform:Ui,Node:kt,Container:hi,Stage:rm,stages:Pf,Layer:ec,FastLayer:H0,Group:Su,DD:Fn,Shape:ht,shapes:Df,Animation:_u,Tween:im,Easings:Of,Context:Xp,Canvas:R0});var ha=class extends ht{_sceneFunc(e){const t=wt.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=wt.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"],wr(ha),ue.addGetterSetter(ha,"innerRadius",0,vt()),ue.addGetterSetter(ha,"outerRadius",0,vt()),ue.addGetterSetter(ha,"angle",0,vt()),ue.addGetterSetter(ha,"clockwise",!1,ji());function j0(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 c4(e,t){const n=e.length,r=[];for(let o=2;o<n-2;o+=2){const i=j0(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 KO(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 ht{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():c4(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,n=this.tension(),r=j0(e[t-2],e[t-1],e[0],e[1],e[2],e[3],n),o=j0(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],n),i=c4(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],...KO(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"],wr(pa),ue.addGetterSetter(pa,"closed",!1),ue.addGetterSetter(pa,"bezier",!1),ue.addGetterSetter(pa,"tension",0,vt()),ue.addGetterSetter(pa,"points",[],lO());const qO=[[],[],[-.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]],YO=[[],[],[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]],XO=[[1],[1,1],[1,2,1],[1,3,3,1]],u4=(e,t,n)=>{let r,o;const s=n/2;r=0;for(let a=0;a<20;a++)o=s*qO[20][a]+s,r+=YO[20][a]*ZO(e,t,o);return s*r},d4=(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,g=d-c*c,p=h*h+g>0?Math.sqrt(h*h+g):0,v=c*c+g>0?Math.sqrt(c*c+g):0,k=c+Math.sqrt(c*c+g)!==0?g*Math.log(Math.abs((h+p)/(c+v))):0;return Math.sqrt(a)/2*(h*p-c*v+k)};function ZO(e,t,n){const r=G0(1,n,e),o=G0(1,n,t),i=r*r+o*o;return Math.sqrt(i)}var G0=(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+=XO[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 G0(e-1,t,o)}};const f4=(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 xi=class ai extends ht{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ai.parsePathData(this.data()),this.pathLength=ai.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],g=s[6],p=s[7],v=u>c?u:c,k=u>c?1:u/c,C=u>c?c/u:1;t.translate(a,l),t.rotate(g),t.scale(k,C),t.arc(0,0,v,d,d+h,1-p),t.scale(1/k,1/C),t.rotate(-g),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 g=u-h;g>d;g-=h){const p=ai.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);t.push(p.x,p.y)}else for(let g=u+h;g<d;g+=h){const p=ai.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);t.push(p.x,p.y)}}else if(l.command==="C")for(let u=0;u<=1;u+=.01){const c=ai.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 ai.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 ai.getPointOnLine(t,s.start.x,s.start.y,a[0],a[1]);case"C":return ai.getPointOnCubicBezier(f4(t,ai.getPathLength(n),v=>u4([s.start.x,a[0],a[2],a[4]],[s.start.y,a[1],a[3],a[5]],v)),s.start.x,s.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return ai.getPointOnQuadraticBezier(f4(t,ai.getPathLength(n),v=>d4([s.start.x,a[0],a[2]],[s.start.y,a[1],a[3]],v)),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],g=a[6];let p=a[4];return p+=h*t/s.pathLength,ai.getPointOnEllipticalArc(l,u,c,d,p,g)}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),g=n+h*(o-n),p=r+h*(i-r),v=this.getLineLength(s,a,g,p),k=Math.sqrt(t*t-v*v),C=Math.sqrt(k*k/(1+u*u))*(o<n?-1:1),_=u*C;return{x:g+C,y:p+_}}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 g(p){return(1-p)*(1-p)*(1-p)}return{x:l*c(t)+s*d(t)+o*h(t)+n*g(t),y:u*c(t)+a*d(t)+i*h(t)+r*g(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],g=h.charAt(0);for(h=h.slice(1),s.length=0;c=u.exec(h);)s.push(c[0]);let p=[],v=g==="A"||g==="a"?0:-1;for(let k=0,C=s.length;k<C;k++){const _=s[k];if(_==="00"){p.push(0,0),v>=0&&(v+=2,v>=7&&(v-=7));continue}if(v>=0){if(v===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(_)){p.push(parseInt(_[0],10)),p.push(parseInt(_[1],10)),p.push(parseFloat(_.slice(2))),v+=3,v>=7&&(v-=7);continue}if(_==="11"||_==="10"||_==="01"){p.push(parseInt(_[0],10)),p.push(parseInt(_[1],10)),v+=2,v>=7&&(v-=7);continue}if(_==="0"||_==="1"){p.push(parseInt(_,10)),v+=1,v>=7&&(v-=7);continue}}else if(v===4){if(/^[01]\d+(?:\.\d+)?$/.test(_)){p.push(parseInt(_[0],10)),p.push(parseFloat(_.slice(1))),v+=2,v>=7&&(v-=7);continue}if(_==="0"||_==="1"){p.push(parseInt(_,10)),v+=1,v>=7&&(v-=7);continue}}const y=parseFloat(_);isNaN(y)?p.push(0):p.push(y),v+=1,v>=7&&(v-=7)}else{const y=parseFloat(_);isNaN(y)?p.push(0):p.push(y)}}for(;p.length>0&&!isNaN(p[0]);){let k="",C=[];const _=a,y=l;let w,x,P,N,G,R,F,Z,D,B;switch(g){case"l":a+=p.shift(),l+=p.shift(),k="L",C.push(a,l);break;case"L":a=p.shift(),l=p.shift(),C.push(a,l);break;case"m":const T=p.shift(),V=p.shift();if(a+=T,l+=V,k="M",i.length>2&&i[i.length-1].command==="z"){for(let J=i.length-2;J>=0;J--)if(i[J].command==="M"){a=i[J].points[0]+T,l=i[J].points[1]+V;break}}C.push(a,l),g="l";break;case"M":a=p.shift(),l=p.shift(),k="M",C.push(a,l),g="L";break;case"h":a+=p.shift(),k="L",C.push(a,l);break;case"H":a=p.shift(),k="L",C.push(a,l);break;case"v":l+=p.shift(),k="L",C.push(a,l);break;case"V":l=p.shift(),k="L",C.push(a,l);break;case"C":C.push(p.shift(),p.shift(),p.shift(),p.shift()),a=p.shift(),l=p.shift(),C.push(a,l);break;case"c":C.push(a+p.shift(),l+p.shift(),a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="C",C.push(a,l);break;case"S":x=a,P=l,w=i[i.length-1],w.command==="C"&&(x=a+(a-w.points[2]),P=l+(l-w.points[3])),C.push(x,P,p.shift(),p.shift()),a=p.shift(),l=p.shift(),k="C",C.push(a,l);break;case"s":x=a,P=l,w=i[i.length-1],w.command==="C"&&(x=a+(a-w.points[2]),P=l+(l-w.points[3])),C.push(x,P,a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="C",C.push(a,l);break;case"Q":C.push(p.shift(),p.shift()),a=p.shift(),l=p.shift(),C.push(a,l);break;case"q":C.push(a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),k="Q",C.push(a,l);break;case"T":x=a,P=l,w=i[i.length-1],w.command==="Q"&&(x=a+(a-w.points[0]),P=l+(l-w.points[1])),a=p.shift(),l=p.shift(),k="Q",C.push(x,P,a,l);break;case"t":x=a,P=l,w=i[i.length-1],w.command==="Q"&&(x=a+(a-w.points[0]),P=l+(l-w.points[1])),a+=p.shift(),l+=p.shift(),k="Q",C.push(x,P,a,l);break;case"A":N=p.shift(),G=p.shift(),R=p.shift(),F=p.shift(),Z=p.shift(),D=a,B=l,a=p.shift(),l=p.shift(),k="A",C=this.convertEndpointToCenterParameterization(D,B,a,l,F,Z,N,G,R);break;case"a":N=p.shift(),G=p.shift(),R=p.shift(),F=p.shift(),Z=p.shift(),D=a,B=l,a+=p.shift(),l+=p.shift(),k="A",C=this.convertEndpointToCenterParameterization(D,B,a,l,F,Z,N,G,R);break}i.push({command:k||g,points:C,start:{x:_,y},pathLength:this.calcLength(_,y,k||g,C)})}(g==="z"||g==="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=ai;switch(r){case"L":return u.getLineLength(t,n,o[0],o[1]);case"C":return u4([t,o[0],o[2],o[4]],[n,o[1],o[3],o[5]],1);case"Q":return d4([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 g=Math.PI/180;if(Math.abs(c-h)<g&&(g=Math.abs(c-h)),s=u.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],c,0),d<0)for(l=c-g;l>h;l-=g)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+g;l<h;l+=g)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,g=d*d/(a*a)+h*h/(l*l);g>1&&(a*=Math.sqrt(g),l*=Math.sqrt(g));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 v=p*a*h/l,k=p*-l*d/a,C=(t+r)/2+Math.cos(c)*v-Math.sin(c)*k,_=(n+o)/2+Math.sin(c)*v+Math.cos(c)*k,y=function(F){return Math.sqrt(F[0]*F[0]+F[1]*F[1])},w=function(F,Z){return(F[0]*Z[0]+F[1]*Z[1])/(y(F)*y(Z))},x=function(F,Z){return(F[0]*Z[1]<F[1]*Z[0]?-1:1)*Math.acos(w(F,Z))},P=x([1,0],[(d-v)/a,(h-k)/l]),N=[(d-v)/a,(h-k)/l],G=[(-1*d-v)/a,(-1*h-k)/l];let R=x(N,G);return w(N,G)<=-1&&(R=Math.PI),w(N,G)>=1&&(R=0),s===0&&R>0&&(R=R-2*Math.PI),s===1&&R<0&&(R=R+2*Math.PI),[C,_,a,l,P,R,c,s]}};xi.prototype.className="Path",xi.prototype._attrsAffectingSize=["data"],wr(xi),ue.addGetterSetter(xi,"data");var tc=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=xi.calcLength(r[r.length-4],r[r.length-3],"C",d),g=xi.getPointOnQuadraticBezier(Math.min(1,1-i/h),d[0],d[1],d[2],d[3],d[4],d[5]);a=n[s-2]-g.x,l=n[s-1]-g.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}}};tc.prototype.className="Arrow",wr(tc),ue.addGetterSetter(tc,"pointerLength",10,vt()),ue.addGetterSetter(tc,"pointerWidth",10,vt()),ue.addGetterSetter(tc,"pointerAtBeginning",!1),ue.addGetterSetter(tc,"pointerAtEnding",!0);var Au=class extends ht{_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)}};Au.prototype._centroid=!0,Au.prototype.className="Circle",Au.prototype._attrsAffectingSize=["radius"],wr(Au),ue.addGetterSetter(Au,"radius",0,vt());var il=class extends ht{_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)}};il.prototype.className="Ellipse",il.prototype._centroid=!0,il.prototype._attrsAffectingSize=["radiusX","radiusY"],wr(il),ue.addComponentsGetterSetter(il,"radius",["x","y"]),ue.addGetterSetter(il,"radiusX",0,vt()),ue.addGetterSetter(il,"radiusY",0,vt());var Gi=class uI extends ht{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?Ee.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?Ee.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=Ee.createImageElement();o.onload=function(){n(new uI({image:o}))},o.onerror=r,o.crossOrigin="Anonymous",o.src=t}};Gi.prototype.className="Image",Gi.prototype._attrsAffectingSize=["image"],wr(Gi),ue.addGetterSetter(Gi,"cornerRadius",0,Qp(4)),ue.addGetterSetter(Gi,"image"),ue.addComponentsGetterSetter(Gi,"crop",["x","y","width","height"]),ue.addGetterSetter(Gi,"cropX",0,vt()),ue.addGetterSetter(Gi,"cropY",0,vt()),ue.addGetterSetter(Gi,"cropWidth",0,vt()),ue.addGetterSetter(Gi,"cropHeight",0,vt());var h4=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],QO="Change.konva",JO="none",W0="up",K0="right",q0="down",Y0="left",$O=h4.length,X0=class extends Su{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<$O;n++)e.on(h4[n]+QO,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 W0:s=n/2,a=-1*l;break;case K0:s=n+i,a=r/2;break;case q0:s=n/2,a=r+l;break;case Y0: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})}}};X0.prototype.className="Label",wr(X0);var nc=class extends ht{_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===W0&&(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===K0&&(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===q0&&(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===Y0&&(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===W0?(t-=r,s+=r):o===q0?s+=r:o===Y0?(e-=n*1.5,i+=n):o===K0&&(i+=n*1.5),{x:e,y:t,width:i,height:s}}};nc.prototype.className="Tag",wr(nc),ue.addGetterSetter(nc,"pointerDirection",JO),ue.addGetterSetter(nc,"pointerWidth",0,vt()),ue.addGetterSetter(nc,"pointerHeight",0,vt()),ue.addGetterSetter(nc,"cornerRadius",0,Qp(4));var Ff=class extends ht{_sceneFunc(e){const t=this.cornerRadius(),n=this.width(),r=this.height();e.beginPath(),t?Ee.drawRoundedRectPath(e,n,r,t):e.rect(0,0,n,r),e.closePath(),e.fillStrokeShape(this)}};Ff.prototype.className="Rect",wr(Ff),ue.addGetterSetter(Ff,"cornerRadius",0,Qp(4));var sl=class extends ht{_sceneFunc(e){const t=this._getPoints(),n=this.radius(),r=this.sides(),o=this.cornerRadius();if(e.beginPath(),o)Ee.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)}};sl.prototype.className="RegularPolygon",sl.prototype._centroid=!0,sl.prototype._attrsAffectingSize=["radius"],wr(sl),ue.addGetterSetter(sl,"radius",0,vt()),ue.addGetterSetter(sl,"sides",0,vt()),ue.addGetterSetter(sl,"cornerRadius",0,Qp(4));var p4=Math.PI*2,rc=class extends ht{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,p4,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),p4,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)}};rc.prototype.className="Ring",rc.prototype._centroid=!0,rc.prototype._attrsAffectingSize=["innerRadius","outerRadius"],wr(rc),ue.addGetterSetter(rc,"innerRadius",0,vt()),ue.addGetterSetter(rc,"outerRadius",0,vt());var ys=class extends ht{constructor(e){super(e),this._updated=!0,this.anim=new _u(()=>{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",wr(ys),ue.addGetterSetter(ys,"animation"),ue.addGetterSetter(ys,"animations"),ue.addGetterSetter(ys,"frameOffsets"),ue.addGetterSetter(ys,"image"),ue.addGetterSetter(ys,"frameIndex",0,vt()),ue.addGetterSetter(ys,"frameRate",17,vt()),ue.backCompat(ys,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});var al=class extends ht{_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)}};al.prototype.className="Star",al.prototype._centroid=!0,al.prototype._attrsAffectingSize=["innerRadius","outerRadius"],wr(al),ue.addGetterSetter(al,"numPoints",5,vt()),ue.addGetterSetter(al,"innerRadius",0,vt()),ue.addGetterSetter(al,"outerRadius",0,vt());function ll(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 Iu="auto",eF="center",m4="inherit",Nf="justify",tF="Change.konva",g4="2d",v4="-",y4="left",nF="text",rF="Text",oF="top",iF="bottom",b4="middle",w4="normal",sF="px ",sm=" ",aF="right",C4="rtl",lF="word",cF="char",k4="none",Z0="…",S4=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],uF=S4.length,Bf=null;function dF(){if(Bf!==null)return Bf;Bf=!1;try{const e=document.createElement("canvas");e.width=10,e.height=10;const t=e.getContext(g4);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){Bf=!0;break}}}catch{}return Bf}function fF(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 am;function Q0(){return am||(am=Ee.createCanvasElement().getContext(g4),am)}function hF(e){e.fillText(this._partialText,this._partialTextX,this._partialTextY)}function pF(e){e.setAttr("miterLimit",2),e.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function mF(e){return e=e||{},!e.fillLinearGradientColorStops&&!e.fillRadialGradientColorStops&&!e.fillPatternImage&&(e.fill=e.fill||"black"),e}var ir=class extends ht{constructor(e){super(mF(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<uF;t++)this.on(S4[t]+tF,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(),g=this.letterSpacing(),p=this.charRenderFunc(),v=this.fill(),k=this.textDecoration(),C=this.underlineOffset(),_=k.indexOf("underline")!==-1,y=k.indexOf("line-through")!==-1,w;u=u===m4?e.direction:u;let x=a/2,P=b4;if(!wt.legacyTextRendering){const N=this.measureSize("M");P="alphabetic",x=(((t=N.fontBoundingBoxAscent)!==null&&t!==void 0?t:N.actualBoundingBoxAscent)-((n=N.fontBoundingBoxDescent)!==null&&n!==void 0?n:N.actualBoundingBoxDescent))/2+a/2}for(u===C4&&e.setAttr("direction",u),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",P),e.setAttr("textAlign",y4),l===b4?c=(this.getHeight()-o*a-i*2)/2:l===iF&&(c=this.getHeight()-o*a-i*2),e.translate(i,c+i),w=0;w<o;w++){let N=0,G=0;const R=r[w],F=R.text,Z=R.width,D=R.lastInParagraph;if(e.save(),d===aF?N+=h-Z-i*2:d===eF&&(N+=(h-Z-i*2)/2),_){e.save(),e.beginPath();const T=C??(wt.legacyTextRendering?Math.round(s/2):Math.round(s/4)),V=N,J=x+G+T;e.moveTo(V,J);const q=d===Nf&&!D?h-i*2:Z;e.lineTo(V+Math.round(q),J),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||v,e.stroke(),e.restore()}const B=N;if(u!==C4&&(g!==0||d===Nf||p)){const T=F.split(" ").length-1,V=ll(F);for(let J=0;J<V.length;J++){const q=V[J];if(q===" "&&!D&&d===Nf&&(N+=(h-i*2-Z)/T),this._partialTextX=N,this._partialTextY=x+G,this._partialText=q,p){e.save();const se=r.slice(0,w).reduce((pe,Ne)=>pe+ll(Ne.text).length,0);p({char:q,index:J+se,x:N,y:x+G,lineIndex:w,column:J,isLastInLine:D,width:this.measureSize(q).width,context:e})}e.fillStrokeShape(this),p&&e.restore(),N+=this.measureSize(q).width+g}}else g!==0&&e.setAttr("letterSpacing",`${g}px`),this._partialTextX=N,this._partialTextY=x+G,this._partialText=F,e.fillStrokeShape(this);if(y){e.save(),e.beginPath();const T=wt.legacyTextRendering?0:-Math.round(s/4),V=B;e.moveTo(V,x+G+T);const J=d===Nf&&!D?h-i*2:Z;e.lineTo(V+Math.round(J),x+G+T),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||v,e.stroke(),e.restore()}e.restore(),o>1&&(x+=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=Ee._isString(e)?e:e==null?"":e+"";return this._setAttr(nF,t),this}getWidth(){return this.attrs.width===Iu||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===Iu||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Ee.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=Q0(),g=this.fontSize(),p;h.save(),h.font=this._getContextFont(),p=h.measureText(e),h.restore();const v=g/100;return{actualBoundingBoxAscent:(t=p.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*v,actualBoundingBoxDescent:(n=p.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(r=p.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*v,actualBoundingBoxRight:(o=p.actualBoundingBoxRight)!==null&&o!==void 0?o:75.732421875*v,alphabeticBaseline:(i=p.alphabeticBaseline)!==null&&i!==void 0?i:0,emHeightAscent:(s=p.emHeightAscent)!==null&&s!==void 0?s:100*v,emHeightDescent:(a=p.emHeightDescent)!==null&&a!==void 0?a:-20*v,fontBoundingBoxAscent:(l=p.fontBoundingBoxAscent)!==null&&l!==void 0?l:91*v,fontBoundingBoxDescent:(u=p.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(c=p.hangingBaseline)!==null&&c!==void 0?c:72.80000305175781*v,ideographicBaseline:(d=p.ideographicBaseline)!==null&&d!==void 0?d:-21*v,width:p.width,height:g}}_getContextFont(){return this.fontStyle()+sm+this.fontVariant()+sm+(this.fontSize()+sF)+fF(this.fontFamily())}_addTextLine(e){this.align()===Nf&&(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 Q0().measureText(e).width+t*n}_setTextData(){let e=this.text().split(`
|
|
100
100
|
`),t=+this.fontSize(),n=0,r=this.lineHeight()*t,o=this.attrs.width,i=this.attrs.height,s=o!==Iu&&o!==void 0,a=i!==Iu&&i!==void 0,l=this.padding(),u=o-l*2,c=i-l*2,d=0,h=this.wrap(),g=h!==cF&&h!==k4,p=this.ellipsis();this.textArr=[],Q0().font=this._getContextFont();const v=p?this._getTextWidth(Z0):0;for(let k=0,C=e.length;k<C;++k){let _=e[k],y=this._getTextWidth(_);if(s&&y>u)for(;_.length>0;){let w=0,x=ll(_).length,P="",N=0;for(;w<x;){const G=w+x>>>1,R=ll(_).slice(0,G+1).join(""),F=this._getTextWidth(R);(p&&a&&d+r>c?F+v:F)<=u?(w=G+1,P=R,N=F):x=G}if(P){if(g){const G=ll(_),R=ll(P),F=G[R.length],Z=F===sm||F===v4;let D;if(Z&&N<=u)D=R.length;else{const B=R.lastIndexOf(sm),T=R.lastIndexOf(v4);D=Math.max(B,T)+1}D>0&&(w=D,P=G.slice(0,w).join(""),N=this._getTextWidth(P))}if(P=P.trimRight(),this._addTextLine(P),n=Math.max(n,N),d+=r,this._shouldHandleEllipsis(d)){this._tryToAddEllipsisToLastLine();break}if(_=ll(_).slice(w).join("").trimLeft(),_.length>0&&(y=this._getTextWidth(_),y<=u)){this._addTextLine(_),d+=r,n=Math.max(n,y);break}}else break}else this._addTextLine(_),d+=r,n=Math.max(n,y),this._shouldHandleEllipsis(d)&&k<C-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!==Iu&&r!==void 0,i=r-this.padding()*2;return this.wrap()===k4||o&&e+n>i}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==Iu&&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+Z0)<n||(o.text=o.text.slice(0,o.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(o.text+Z0))}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&&dF()?!0:super._useBufferCanvas()}};ir.prototype._fillFunc=hF,ir.prototype._strokeFunc=pF,ir.prototype.className=rF,ir.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],wr(ir),ue.overWriteSetter(ir,"width",L0()),ue.overWriteSetter(ir,"height",L0()),ue.addGetterSetter(ir,"direction",m4),ue.addGetterSetter(ir,"fontFamily","Arial"),ue.addGetterSetter(ir,"fontSize",12,vt()),ue.addGetterSetter(ir,"fontStyle",w4),ue.addGetterSetter(ir,"fontVariant",w4),ue.addGetterSetter(ir,"padding",0,vt()),ue.addGetterSetter(ir,"align",y4),ue.addGetterSetter(ir,"verticalAlign",oF),ue.addGetterSetter(ir,"lineHeight",1,vt()),ue.addGetterSetter(ir,"wrap",lF),ue.addGetterSetter(ir,"ellipsis",!1,ji()),ue.addGetterSetter(ir,"letterSpacing",0,vt()),ue.addGetterSetter(ir,"text","",Jl()),ue.addGetterSetter(ir,"textDecoration",""),ue.addGetterSetter(ir,"underlineOffset",void 0,vt()),ue.addGetterSetter(ir,"charRenderFunc",void 0);var gF="",_4="normal";function A4(e){e.fillText(this.partialText,0,0)}function I4(e){e.strokeText(this.partialText,0,0)}var Qr=class extends ht{constructor(e){super(e),this.dummyCanvas=Ee.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 xi.getPathLength(this.dataArray)}_getPointAtLength(e){return!this.attrs.data||e>this.pathLength?null:xi.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=xi.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 Ee.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return ir.prototype.setText.call(this,e)}_getContextFont(){return ir.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=ll(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 g=this._getPointAtLength(d);if(!g)return;const p=t[h].char;let v=t[h].width+i;if(p===" "&&s==="justify"){const P=this.text().split(" ").length-1;v+=(this.pathLength-u)/P}const k=d+v,C=this._getPointAtLength(k>this.pathLength&&k-this.pathLength<=l?this.pathLength:k);if(!C)return;const _=xi.getLineLength(g.x,g.y,C.x,C.y);let y=0;if(a)try{y=a(t[h-1].char,p)*this.fontSize()}catch{y=0}g.x+=y,C.x+=y,this.textWidth+=y;const w=xi.getPointOnLine(y+_/2,g.x,g.y,C.x,C.y),x=Math.atan2(C.y-g.y,C.x-g.x);this.glyphInfo.push({transposeX:w.x,transposeY:w.y,text:e[h],rotation:x,p0:g,p1:C,width:_}),d+=v}}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 Ee.releaseCanvas(this.dummyCanvas),super.destroy()}};Qr.prototype._fillFunc=A4,Qr.prototype._strokeFunc=I4,Qr.prototype._fillFuncHit=A4,Qr.prototype._strokeFuncHit=I4,Qr.prototype.className="TextPath",Qr.prototype._attrsAffectingSize=["text","fontSize","data"],wr(Qr),ue.addGetterSetter(Qr,"data"),ue.addGetterSetter(Qr,"fontFamily","Arial"),ue.addGetterSetter(Qr,"fontSize",12,vt()),ue.addGetterSetter(Qr,"fontStyle",_4),ue.addGetterSetter(Qr,"align","left"),ue.addGetterSetter(Qr,"letterSpacing",0,vt()),ue.addGetterSetter(Qr,"textBaseline","middle"),ue.addGetterSetter(Qr,"fontVariant",_4),ue.addGetterSetter(Qr,"text",gF),ue.addGetterSetter(Qr,"textDecoration",""),ue.addGetterSetter(Qr,"kerningFunc",void 0);var E4="tr-konva",vF=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(e=>e+`.${E4}`).join(" "),T4="nodesRect",yF=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],bF={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},wF="ontouchstart"in wt._global;function CF(e,t,n){if(e==="rotater")return n;t+=Ee.degToRad(bF[e]||0);const r=(Ee.radToDeg(t)%360+360)%360;return Ee._inRange(r,337.5,360)||Ee._inRange(r,0,22.5)?"ns-resize":Ee._inRange(r,22.5,67.5)?"nesw-resize":Ee._inRange(r,67.5,112.5)?"ew-resize":Ee._inRange(r,112.5,157.5)?"nwse-resize":Ee._inRange(r,157.5,202.5)?"ns-resize":Ee._inRange(r,202.5,247.5)?"nesw-resize":Ee._inRange(r,247.5,292.5)?"ew-resize":Ee._inRange(r,292.5,337.5)?"nwse-resize":(Ee.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}var lm=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],x4=1e8;function kF(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 R4(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 SF(e,t){return R4(e,t,kF(e))}function _F(e,t,n){let r=t;for(let o=0;o<e.length;o++){const i=wt.getAngle(e[o]),s=Math.abs(i-t)%(Math.PI*2);Math.min(s,Math.PI*2-s)<n&&(r=i)}return r}var J0=0,Tn=class extends Su{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(vF,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return Ee.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 E4+this._id}setNodes(e=[]){return this._nodes&&this._nodes.length&&this.detach(),this._nodes=e=e.filter(t=>t.isAncestorOf(this)?(Ee.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(yF.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(T4),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(T4,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=(wt.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2);return R4({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},-wt.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-x4,y:-x4,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(-wt.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:wt.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(),lm.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(e){const t=new Ff({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:wF?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=CF(e,wt.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 ht({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=Ee.degToRad(a),c=Math.sin(u),d=-Math.cos(u),h=i/2,g=s/2;let p=1/0;d<0?p=Math.min(p,-g/d):d>0&&(p=Math.min(p,(s-g)/d)),c<0?p=Math.min(p,-h/c):c>0&&(p=Math.min(p,(i-h)/c));const v=h+c*p,k=g+d*p,C=Ee._sign(s),_=v+c*l*C,y=k+d*l*C;t.moveTo(v,k),t.lineTo(_,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},J0++,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 C=this._getNodeRect();t=o.x()-C.width/2,n=-o.y()+C.height/2;const _=wt.getAngle(this.rotateAnchorAngle());let y=Math.atan2(-n,t)+Math.PI/2-_;C.height<0&&(y-=Math.PI);const w=wt.getAngle(this.rotation())+y,x=wt.getAngle(this.rotationSnapTolerance()),P=SF(C,_F(this.rotationSnaps(),w,x)-C.rotation);this._fitNodesInto(P,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 C=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(C.x-o.x(),2)+Math.pow(C.y-o.y(),2));const _=this.findOne(".top-left").x()>C.x?-1:1,y=this.findOne(".top-left").y()>C.y?-1:1;t=r*this.cos*_,n=r*this.sin*y,this.findOne(".top-left").x(C.x-t),this.findOne(".top-left").y(C.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(o.y());else if(this._movingAnchorName==="top-right"){if(d){const C=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()-C.x,2)+Math.pow(C.y-o.y(),2));const _=this.findOne(".top-right").x()<C.x?-1:1,y=this.findOne(".top-right").y()>C.y?-1:1;t=r*this.cos*_,n=r*this.sin*y,this.findOne(".top-right").x(C.x+t),this.findOne(".top-right").y(C.y-n)}var g=o.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.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 C=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(C.x-o.x(),2)+Math.pow(o.y()-C.y,2));const _=C.x<o.x()?-1:1,y=o.y()<C.y?-1:1;t=r*this.cos*_,n=r*this.sin*y,o.x(C.x-t),o.y(C.y+n)}g=o.position(),this.findOne(".top-left").x(g.x),this.findOne(".bottom-right").y(g.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(o.y());else if(this._movingAnchorName==="bottom-right"){if(d){const C=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()-C.x,2)+Math.pow(o.y()-C.y,2));const _=this.findOne(".bottom-right").x()<C.x?-1:1,y=this.findOne(".bottom-right").y()<C.y?-1:1;t=r*this.cos*_,n=r*this.sin*y,this.findOne(".bottom-right").x(C.x+t),this.findOne(".bottom-right").y(C.y+n)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(h=this.centeredScaling()||e.altKey,h){const C=this.findOne(".top-left"),_=this.findOne(".bottom-right"),y=C.x(),w=C.y(),x=this.getWidth()-_.x(),P=this.getHeight()-_.y();_.move({x:-y,y:-w}),C.move({x,y:P})}const p=this.findOne(".top-left").getAbsolutePosition();t=p.x,n=p.y;const v=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:v,height:k,rotation:wt.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();J0--,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(Ee._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(Ee._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const o=new Ui;if(o.rotate(wt.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:Ee.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 g=d.getParent().getAbsoluteTransform(),p=d.getTransform().copy();p.translate(d.offsetX(),d.offsetY());const v=new Ui;v.multiply(g.copy().invert()).multiply(c).multiply(g).multiply(p);const k=v.decompose();d.setAttrs(k),(h=d.getLayer())===null||h===void 0||h.batchDraw()}),this.rotation(Ee._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(Ee._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(x=>{x.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=Ee.degToRad(u),h=Math.sin(d),g=-Math.cos(d),p=n/2,v=r/2;let k=1/0;g<0?k=Math.min(k,-v/g):g>0&&(k=Math.min(k,(r-v)/g)),h<0?k=Math.min(k,-p/h):h>0&&(k=Math.min(k,(n-p)/h));const C=p+h*k,_=v+g*k,y=Ee._sign(r);this._batchChangeChild(".rotater",{x:C+h*c*y,y:_+g*c*y-s*g,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(x=>x.draggable()),x:0,y:0});const w=this.anchorStyleFunc();w&&l.forEach(x=>{w(x)}),(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=""),Su.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...e){return this._elementsCreated?(Ee.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...e)}toObject(){return kt.prototype.toObject.call(this)}clone(e){return kt.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};Tn.isTransforming=()=>J0>0;function AF(e){return e instanceof Array||Ee.warn("enabledAnchors value should be an array"),e instanceof Array&&e.forEach(function(t){lm.indexOf(t)===-1&&Ee.warn("Unknown anchor name: "+t+". Available names are: "+lm.join(", "))}),e||[]}Tn.prototype.className="Transformer",wr(Tn),ue.addGetterSetter(Tn,"enabledAnchors",lm,AF),ue.addGetterSetter(Tn,"flipEnabled",!0,ji()),ue.addGetterSetter(Tn,"resizeEnabled",!0),ue.addGetterSetter(Tn,"anchorSize",10,vt()),ue.addGetterSetter(Tn,"rotateEnabled",!0),ue.addGetterSetter(Tn,"rotateLineVisible",!0),ue.addGetterSetter(Tn,"rotationSnaps",[]),ue.addGetterSetter(Tn,"rotateAnchorOffset",50,vt()),ue.addGetterSetter(Tn,"rotateAnchorAngle",0,vt()),ue.addGetterSetter(Tn,"rotateAnchorCursor","crosshair"),ue.addGetterSetter(Tn,"rotationSnapTolerance",5,vt()),ue.addGetterSetter(Tn,"borderEnabled",!0),ue.addGetterSetter(Tn,"anchorStroke","rgb(0, 161, 255)"),ue.addGetterSetter(Tn,"anchorStrokeWidth",1,vt()),ue.addGetterSetter(Tn,"anchorFill","white"),ue.addGetterSetter(Tn,"anchorCornerRadius",0,vt()),ue.addGetterSetter(Tn,"borderStroke","rgb(0, 161, 255)"),ue.addGetterSetter(Tn,"borderStrokeWidth",1,vt()),ue.addGetterSetter(Tn,"borderDash"),ue.addGetterSetter(Tn,"keepRatio",!0),ue.addGetterSetter(Tn,"shiftBehavior","default"),ue.addGetterSetter(Tn,"centeredScaling",!1),ue.addGetterSetter(Tn,"ignoreStroke",!1),ue.addGetterSetter(Tn,"padding",0,vt()),ue.addGetterSetter(Tn,"nodes"),ue.addGetterSetter(Tn,"node"),ue.addGetterSetter(Tn,"boundBoxFunc"),ue.addGetterSetter(Tn,"anchorDragBoundFunc"),ue.addGetterSetter(Tn,"anchorStyleFunc"),ue.addGetterSetter(Tn,"shouldOverdrawWholeArea",!1),ue.addGetterSetter(Tn,"useSingleNodeRotation",!0),ue.backCompat(Tn,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var ma=class extends ht{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,wt.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"],wr(ma),ue.addGetterSetter(ma,"radius",0,vt()),ue.addGetterSetter(ma,"angle",0,vt()),ue.addGetterSetter(ma,"clockwise",!1),ue.backCompat(ma,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function M4(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}var IF=[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],EF=[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 TF(e,t){const n=e.data,r=e.width,o=e.height;let i,s,a,l,u,c,d,h,g,p,v,k,C,_,y,w,x,P,N,G;const R=t+t+1,F=r-1,Z=o-1,D=t+1,B=D*(D+1)/2,T=new M4,V=IF[t],J=EF[t];let q=null,se=T,pe=null,Ne=null;for(let he=1;he<R;he++)se=se.next=new M4,he===D&&(q=se);se.next=T,a=s=0;for(let he=0;he<o;he++){k=C=_=y=l=u=c=d=0,h=D*(w=n[s]),g=D*(x=n[s+1]),p=D*(P=n[s+2]),v=D*(N=n[s+3]),l+=B*w,u+=B*x,c+=B*P,d+=B*N,se=T;for(let ye=0;ye<D;ye++)se.r=w,se.g=x,se.b=P,se.a=N,se=se.next;for(let ye=1;ye<D;ye++)i=s+((F<ye?F:ye)<<2),l+=(se.r=w=n[i])*(G=D-ye),u+=(se.g=x=n[i+1])*G,c+=(se.b=P=n[i+2])*G,d+=(se.a=N=n[i+3])*G,k+=w,C+=x,_+=P,y+=N,se=se.next;pe=T,Ne=q;for(let ye=0;ye<r;ye++)n[s+3]=N=d*V>>J,N!==0?(N=255/N,n[s]=(l*V>>J)*N,n[s+1]=(u*V>>J)*N,n[s+2]=(c*V>>J)*N):n[s]=n[s+1]=n[s+2]=0,l-=h,u-=g,c-=p,d-=v,h-=pe.r,g-=pe.g,p-=pe.b,v-=pe.a,i=a+((i=ye+t+1)<F?i:F)<<2,k+=pe.r=n[i],C+=pe.g=n[i+1],_+=pe.b=n[i+2],y+=pe.a=n[i+3],l+=k,u+=C,c+=_,d+=y,pe=pe.next,h+=w=Ne.r,g+=x=Ne.g,p+=P=Ne.b,v+=N=Ne.a,k-=w,C-=x,_-=P,y-=N,Ne=Ne.next,s+=4;a+=r}for(let he=0;he<r;he++){C=_=y=k=u=c=d=l=0,s=he<<2,h=D*(w=n[s]),g=D*(x=n[s+1]),p=D*(P=n[s+2]),v=D*(N=n[s+3]),l+=B*w,u+=B*x,c+=B*P,d+=B*N,se=T;for(let ce=0;ce<D;ce++)se.r=w,se.g=x,se.b=P,se.a=N,se=se.next;let ye=r;for(let ce=1;ce<=t;ce++)s=ye+he<<2,l+=(se.r=w=n[s])*(G=D-ce),u+=(se.g=x=n[s+1])*G,c+=(se.b=P=n[s+2])*G,d+=(se.a=N=n[s+3])*G,k+=w,C+=x,_+=P,y+=N,se=se.next,ce<Z&&(ye+=r);s=he,pe=T,Ne=q;for(let ce=0;ce<o;ce++)i=s<<2,n[i+3]=N=d*V>>J,N>0?(N=255/N,n[i]=(l*V>>J)*N,n[i+1]=(u*V>>J)*N,n[i+2]=(c*V>>J)*N):n[i]=n[i+1]=n[i+2]=0,l-=h,u-=g,c-=p,d-=v,h-=pe.r,g-=pe.g,p-=pe.b,v-=pe.a,i=he+((i=ce+D)<Z?i:Z)*r<<2,l+=k+=pe.r=n[i],u+=C+=pe.g=n[i+1],c+=_+=pe.b=n[i+2],d+=y+=pe.a=n[i+3],pe=pe.next,h+=w=Ne.r,g+=x=Ne.g,p+=P=Ne.b,v+=N=Ne.a,k-=w,C-=x,_-=P,y-=N,Ne=Ne.next,s+=r}}const xF=function(t){const n=Math.round(this.blurRadius());n>0&&TF(t,n)};ue.addGetterSetter(kt,"blurRadius",0,vt(),ue.afterSetFilter);const RF=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};ue.addGetterSetter(kt,"brightness",0,vt(),ue.afterSetFilter);const MF=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};ue.addGetterSetter(kt,"contrast",0,vt(),ue.afterSetFilter);const PF=function(e){var t,n,r,o,i,s,a,l,u;const c=e.data,d=e.width,h=e.height,g=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)),v=(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),C=g*10,_=p*255,y=v*Math.PI/180,w=Math.cos(y),x=Math.sin(y),P=128/1020*C,N=new Uint8ClampedArray(c),G=new Float32Array(d*h);for(let B=0,T=0;T<c.length;T+=4,B++)G[B]=.2126*N[T]+.7152*N[T+1]+.0722*N[T+2];const R=[-1,0,1,-2,0,2,-1,0,1],F=[-1,-2,-1,0,0,0,1,2,1],Z=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],D=B=>B<0?0:B>255?255:B;for(let B=1;B<h-1;B++)for(let T=1;T<d-1;T++){const V=B*d+T;let J=0,q=0;J+=G[V+Z[0]]*R[0],q+=G[V+Z[0]]*F[0],J+=G[V+Z[1]]*R[1],q+=G[V+Z[1]]*F[1],J+=G[V+Z[2]]*R[2],q+=G[V+Z[2]]*F[2],J+=G[V+Z[3]]*R[3],q+=G[V+Z[3]]*F[3],J+=G[V+Z[5]]*R[5],q+=G[V+Z[5]]*F[5],J+=G[V+Z[6]]*R[6],q+=G[V+Z[6]]*F[6],J+=G[V+Z[7]]*R[7],q+=G[V+Z[7]]*F[7],J+=G[V+Z[8]]*R[8],q+=G[V+Z[8]]*F[8];const se=D(_+(w*J+x*q)*P),pe=V*4;if(k){const Ne=se-_;c[pe]=D(N[pe]+Ne),c[pe+1]=D(N[pe+1]+Ne),c[pe+2]=D(N[pe+2]+Ne),c[pe+3]=N[pe+3]}else c[pe]=c[pe+1]=c[pe+2]=se,c[pe+3]=N[pe+3]}for(let B=0;B<d;B++){let T=B*4,V=((h-1)*d+B)*4;c[T]=N[T],c[T+1]=N[T+1],c[T+2]=N[T+2],c[T+3]=N[T+3],c[V]=N[V],c[V+1]=N[V+1],c[V+2]=N[V+2],c[V+3]=N[V+3]}for(let B=1;B<h-1;B++){let T=B*d*4,V=(B*d+(d-1))*4;c[T]=N[T],c[T+1]=N[T+1],c[T+2]=N[T+2],c[T+3]=N[T+3],c[V]=N[V],c[V+1]=N[V+1],c[V+2]=N[V+2],c[V+3]=N[V+3]}return e};ue.addGetterSetter(kt,"embossStrength",.5,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"embossWhiteLevel",.5,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"embossDirection","top-left",void 0,ue.afterSetFilter),ue.addGetterSetter(kt,"embossBlend",!1,void 0,ue.afterSetFilter);function $0(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 DF=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 g,p,v,k,C,_;if(h>0)g=o+h*(255-o),p=r-h*(r-0),v=a+h*(255-a),k=s-h*(s-0),C=c+h*(255-c),_=u-h*(u-0);else{const y=(o+r)*.5;g=o+h*(o-y),p=r+h*(r-y);const w=(a+s)*.5;v=a+h*(a-w),k=s+h*(s-w);const x=(c+u)*.5;C=c+h*(c-x),_=u+h*(u-x)}for(let y=0;y<n;y+=4)t[y+0]=$0(t[y+0],r,o,p,g),t[y+1]=$0(t[y+1],s,a,k,v),t[y+2]=$0(t[y+2],u,c,_,C)};ue.addGetterSetter(kt,"enhance",0,vt(),ue.afterSetFilter);const OF=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}};ue.addGetterSetter(kt,"hue",0,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"saturation",0,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"luminance",0,vt(),ue.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,g=.587*r+.413*a+.035*l,p=.114*r-.114*a+.293*l,v=.299*r-.3*a+1.25*l,k=.587*r-.586*a-1.05*l,C=.114*r+.886*a-.2*l;let _,y,w,x;for(let P=0;P<n;P+=4)_=t[P+0],y=t[P+1],w=t[P+2],x=t[P+3],t[P+0]=u*_+c*y+d*w+s,t[P+1]=h*_+g*y+p*w+s,t[P+2]=v*_+k*y+C*w+s,t[P+3]=x},NF=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,g=.114*r-.114*s+.293*a,p=.299*r-.3*s+1.25*a,v=.587*r-.586*s-1.05*a,k=.114*r+.886*s-.2*a;for(let C=0;C<n;C+=4){const _=t[C+0],y=t[C+1],w=t[C+2],x=t[C+3];t[C+0]=l*_+u*y+c*w,t[C+1]=d*_+h*y+g*w,t[C+2]=p*_+v*y+k*w,t[C+3]=x}};ue.addGetterSetter(kt,"hue",0,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"saturation",0,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"value",0,vt(),ue.afterSetFilter);const BF=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 zF=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 g=s,p=i,v=360/p*Math.PI/180;for(let k=0;k<p;k+=1){const C=Math.sin(k*v),_=Math.cos(k*v);for(let y=0;y<g;y+=1){c=Math.floor(a+u*y/g*_),d=Math.floor(l+u*y/g*C);let w=(d*i+c)*4;const x=r[w+0],P=r[w+1],N=r[w+2],G=r[w+3];w=(k+y*i)*4,o[w+0]=x,o[w+1]=P,o[w+2]=N,o[w+3]=G}}},VF=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 g=s,p=i,v=n.polarRotation||0;let k,C;for(c=0;c<i;c+=1)for(d=0;d<s;d+=1){const _=c-a,y=d-l,w=Math.sqrt(_*_+y*y)*g/u;let x=(Math.atan2(y,_)*180/Math.PI+360+v)%360;x=x*p/360,k=Math.floor(x),C=Math.floor(w);let P=(C*i+k)*4;const N=r[P+0],G=r[P+1],R=r[P+2],F=r[P+3];P=(d*i+c)*4,o[P+0]=N,o[P+1]=G,o[P+2]=R,o[P+3]=F}};const HF=function(e){const t=e.width,n=e.height;let r,o,i,s,a,l,u,c,d,h,g=Math.round(this.kaleidoscopePower());const p=Math.round(this.kaleidoscopeAngle()),v=Math.floor(t*(p%360)/360);if(g<1)return;const k=Ee.createCanvasElement();k.width=t,k.height=n;const C=k.getContext("2d").getImageData(0,0,t,n);Ee.releaseCanvas(k),zF(e,C,{polarCenterX:t/2,polarCenterY:n/2});let _=t/Math.pow(2,g);for(;_<=8;)_=_*2,g-=1;_=Math.ceil(_);let y=_,w=0,x=y,P=1;for(v+_>t&&(w=y,x=0,P=-1),o=0;o<n;o+=1)for(r=w;r!==x;r+=P)i=Math.round(r+v)%t,d=(t*o+i)*4,a=C.data[d+0],l=C.data[d+1],u=C.data[d+2],c=C.data[d+3],h=(t*o+r)*4,C.data[h+0]=a,C.data[h+1]=l,C.data[h+2]=u,C.data[h+3]=c;for(o=0;o<n;o+=1)for(y=Math.floor(_),s=0;s<g;s+=1){for(r=0;r<y+1;r+=1)d=(t*o+r)*4,a=C.data[d+0],l=C.data[d+1],u=C.data[d+2],c=C.data[d+3],h=(t*o+y*2-r-1)*4,C.data[h+0]=a,C.data[h+1]=l,C.data[h+2]=u,C.data[h+3]=c;y*=2}VF(C,e,{polarRotation:0})};ue.addGetterSetter(kt,"kaleidoscopePower",2,vt(),ue.afterSetFilter),ue.addGetterSetter(kt,"kaleidoscopeAngle",0,vt(),ue.afterSetFilter);function cm(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 zf(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 UF(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 jF(e,t){const n=cm(e,0,0),r=cm(e,e.width-1,0),o=cm(e,0,e.height-1),i=cm(e,e.width-1,e.height-1),s=t||10;if(zf(n,r)<s&&zf(r,i)<s&&zf(i,o)<s&&zf(o,n)<s){const a=UF([r,n,i,o]),l=[];for(let u=0;u<e.width*e.height;u++)l[u]=zf(a,[e.data[u*4],e.data[u*4+1],e.data[u*4+2]])<s?0:255;return l}}function GF(e,t){for(let n=0;n<e.width*e.height;n++)e.data[4*n+3]=t[n]}function WF(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 g=a+d-i,p=l+h-i;if(g>=0&&g<n&&p>=0&&p<t){const v=g*t+p,k=r[d*o+h];c+=e[v]*k}}s[u]=c===2040?255:0}return s}function KF(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 g=a+d-i,p=l+h-i;if(g>=0&&g<n&&p>=0&&p<t){const v=g*t+p,k=r[d*o+h];c+=e[v]*k}}s[u]=c>=1020?255:0}return s}function qF(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 g=a+d-i,p=l+h-i;if(g>=0&&g<n&&p>=0&&p<t){const v=g*t+p,k=r[d*o+h];c+=e[v]*k}}s[u]=c}return s}const YF=function(e){let t=jF(e,this.threshold());return t&&(t=WF(t,e.width,e.height),t=KF(t,e.width,e.height),t=qF(t,e.width,e.height),GF(e,t)),e};ue.addGetterSetter(kt,"threshold",0,vt(),ue.afterSetFilter);const XF=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()};ue.addGetterSetter(kt,"noise",.2,vt(),ue.afterSetFilter);const ZF=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){Ee.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 g=a*t,p=g+t,v=l*t,k=v+t;let C=0;for(let _=g;_<p;_+=1)if(!(_>=n))for(let y=v;y<k;y+=1){if(y>=r)continue;const w=(n*y+_)*4;u+=s[w+0],c+=s[w+1],d+=s[w+2],h+=s[w+3],C+=1}u=u/C,c=c/C,d=d/C,h=h/C;for(let _=g;_<p;_+=1)if(!(_>=n))for(let y=v;y<k;y+=1){if(y>=r)continue;const w=(n*y+_)*4;s[w+0]=u,s[w+1]=c,s[w+2]=d,s[w+3]=h}}};ue.addGetterSetter(kt,"pixelSize",8,vt(),ue.afterSetFilter);const QF=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};ue.addGetterSetter(kt,"levels",.5,vt(),ue.afterSetFilter);const JF=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]}};ue.addGetterSetter(kt,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ue.addGetterSetter(kt,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ue.addGetterSetter(kt,"blue",0,M_,ue.afterSetFilter);const $F=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}};ue.addGetterSetter(kt,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ue.addGetterSetter(kt,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),ue.addGetterSetter(kt,"blue",0,M_,ue.afterSetFilter),ue.addGetterSetter(kt,"alpha",1,function(e){return this._filterUpToDate=!1,e>1?1:e<0?0:e});const eN=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)}},tN=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},nN=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};ue.addGetterSetter(kt,"threshold",.5,vt(),ue.afterSetFilter);var rN=l4.Util._assign(l4,{Arc:ha,Arrow:tc,Circle:Au,Ellipse:il,Image:Gi,Label:X0,Tag:nc,Line:pa,Path:xi,Rect:Ff,RegularPolygon:sl,Ring:rc,Sprite:ys,Star:al,Text:ir,TextPath:Qr,Transformer:Tn,Wedge:ma,Filters:{Blur:xF,Brightness:MF,Brighten:RF,Contrast:LF,Emboss:PF,Enhance:DF,Grayscale:OF,HSL:FF,HSV:NF,Invert:BF,Kaleidoscope:HF,Mask:YF,Noise:XF,Pixelate:ZF,Posterize:QF,RGB:JF,RGBA:$F,Sepia:eN,Solarize:tN,Threshold:nN}});Mt();var oN=["dialog","floating"],L4=["top-right","top-left","bottom-right","bottom-left","top-center","bottom-center"];function iN(e){if(!e||typeof e!="object")throw new Error("SurfaceManager: request must be a non-null object.");if(!oN.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&&!L4.includes(e.floating.placement))throw new Error(`SurfaceManager: floating.placement must be one of ${L4.join(", ")}, got "${e.floating.placement}".`)}var sN=class{activeDialog=Zr(null);activeFloating=Zr(null);#t=!1;#n=1;#e;constructor({getModuleConfig:e}){this.#e=e}open(e){if(this.#t)return this.#f(e);iN(e);const t=this.#d(e),{component:n,props:r,render:o}=this.#h(t);let i,s=!1;const a=new Promise(g=>{i=p=>s?!1:(s=!0,g(p),!0)});let l;const u=g=>{i({status:"submitted",data:g})&&this.#i(l)},c=g=>{i({status:"closed",reason:g})&&this.#i(l)};l={id:t.id,mode:t.mode,request:t,component:n,props:r,render:o,resolve:u,close:c,settle:g=>i(g),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:g=>this.#r(l,g),result:a}}close(e,t){if(e!=null){const o=this.#s(e);o&&this.#r(o,t);return}const n=this.activeDialog.value;if(n&&!n.settled){this.#r(n,t);return}const r=this.activeFloating.value;r&&!r.settled&&this.#r(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"})}#r(e,t){e.settled||(e.settle({status:"closed",reason:t}),this.#i(e))}#i(e){const t=e.mode==="dialog"?this.activeDialog:this.activeFloating;t.value===e&&(t.value=null)}#s(e){return this.activeDialog.value?.id===e?this.activeDialog.value:this.activeFloating.value?.id===e?this.activeFloating.value:null}#d(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}}#h(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.`)}#f(e){return{id:e?.id??`surface-${this.#n++}`,mode:e?.mode??"dialog",close:()=>{},result:Promise.resolve({status:"destroyed"})}}},aN="https://docs.superdoc.dev/guides/migration/document-api",P4=new Set;function lN(e,t){P4.has(e)||(P4.add(e),console.warn(t))}var cN={state:"editor.state",view:"editor.view",schema:"editor.schema",commands:"editor.commands",chain:"editor.chain()",can:"editor.can()",dispatch:"editor.dispatch()"},D4=Symbol.for("superdoc:rawEditor"),O4=new WeakMap;function F4(e){return!e||e[D4]?e:new Proxy(e,{get(t,n){if(n===D4)return t;const r=cN[n];r&&lN(`deprecated:${String(n)}`,`[SuperDoc] ${r} is deprecated and will be removed in a future version. Use the Document API (editor.doc) instead. See ${aN}`);const o=Reflect.get(t,n,t);if(typeof o=="function"){let i=O4.get(t);return i||(i=new Map,O4.set(t,i)),i.has(n)||i.set(n,o.bind(t)),i.get(n)}return o}})}var N4=["review","original","final","off"],uN=["paired","independent"],B4=Symbol.for("@superdoc/trackChanges:normalized"),z4=new Set;function V4(e,t){z4.has(e)||(z4.add(e),console.warn(`[SuperDoc] ${e} is deprecated — use ${t} instead.`))}function H4(e,t,n){return typeof e=="boolean"?e:typeof t=="boolean"?t:n}function dN(e,t,n){return typeof e=="string"&&N4.includes(e)?e:typeof t=="string"&&N4.includes(t)?t:n}function fN(e){return typeof e=="string"&&uN.includes(e)?e:null}function oc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function hN(e){const t=e[B4]===!0;oc(e.modules)||(e.modules={});const n=oc(e.modules.trackChanges),r=oc(e.trackChanges),o=oc(e.layoutEngineOptions?.trackedChanges);t||(r&&V4("config.trackChanges","config.modules.trackChanges"),o&&V4("config.layoutEngineOptions.trackedChanges","config.modules.trackChanges"));const i=H4(n?.visible,r?.visible,!1),s=H4(n?.enabled,o?.enabled,!0),a=fN(n?.replacements)??"paired",l=oc(n?.authorColors)?n.authorColors:void 0,u=oc(n?.semanticColors)?n.semanticColors:void 0,c=e.documentMode==="viewing"?i?"review":"original":"review",d=dN(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},oc(e.layoutEngineOptions)||(e.layoutEngineOptions={}),e.layoutEngineOptions.trackedChanges={mode:d,enabled:s},Object.defineProperty(e,B4,{value:!0,writable:!0,configurable:!0,enumerable:!1}),h}const eb=Object.freeze({id:null,name:"Default SuperDoc user",email:null});function pN(e){return!e||typeof e!="object"?{...eb}:{...eb,...e}}var U4=Object.freeze({toolbar:!0,comments:!0,contextMenu:!0,search:!1,linkPopover:!1,ruler:!1,contentControls:!0}),mN=Object.freeze(["left","center","right"]),aG=Object.freeze(Object.keys(U4)),Eu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function j4(e,t){const n=e?.[t];return n===!1?!1:n===void 0?U4[t]:!0}function gN(e,t){const n=e?.[t];return Eu(n)?n:{}}var G4=Object.freeze(["readOnly","allowResolve","permissionResolver"]);function vN(e){if(!G4.some(n=>n in e))return e;const t={...e};for(const n of G4)delete t[n];return t}function W4(e={}){const t=e.ui,n=t===!1,r=Eu(t)?t:void 0,o=R=>!n&&j4(r,R),i=R=>n?!1:r?.[R]===void 0?void 0:j4(r,R),s=R=>n?{}:gN(r,R),a=n||i("ruler")===!1,l=n||i("linkPopover")===!1,u=l?void 0:b0(s("linkPopover").popoverResolver,e.modules?.links?.popoverResolver),c=i("contentControls")??(!n&&e.modules?.contentControls?.chrome!=="none"),d=e.modules?.contentControls?.chrome==="none"?void 0:e.modules?.contentControls?.chrome,h=s("toolbar"),g=e.modules?.toolbar,p=Eu(g)?g:{},v=e.modules?.contextMenu??e.modules?.slashMenu,k=Eu(v)?v:{},C=e.modules?.surfaces?.findReplace,_=Eu(C)?C:{},y=[h.groups,p.groups],w=y.find(Eu),x=b0(y.find(Array.isArray),p.toolbarGroups,e.toolbarGroups),P=Array.isArray(x)?x:null,N=(R,F)=>Object.prototype.hasOwnProperty.call(R,F),G=w&&P?Object.fromEntries([...P.filter(R=>N(w,R)),...Object.keys(w).filter(R=>!mN.includes(R))].map(R=>[R,w[R]])):w;return{enabled:!n,toolbar:{enabled:o("toolbar"),container:n?null:b0(h.container,p.selector,e.toolbar)??null,options:n?{}:{...vs(p,h),groups:G,toolbarGroups:x,icons:vs(e.toolbarIcons,p.icons,h.icons),texts:vs(e.toolbarTexts,p.texts,h.texts)}},comments:{enabled:i("comments")??(!n&&e.modules?.comments!==!1),options:n?{}:zk(vN(s("comments")))},contextMenu:{enabled:i("contextMenu")??(!n&&e.disableContextMenu!==!0),suppressed:n||i("contextMenu")===!1,options:n?{}:vs(k,s("contextMenu"))},search:{enabled:i("search")??(!n&&!!e.modules?.surfaces?.findReplace),options:n?{}:vs(_,s("search"))},linkPopover:{enabled:typeof u=="function",suppressed:l,options:vs(s("linkPopover"),{popoverResolver:u})},ruler:{enabled:i("ruler")??(!n&&!!e.rulers),suppressed:a,container:a?null:s("ruler").container??e.rulerContainer??null},contentControls:{enabled:c,options:c?vs({chrome:d},s("contentControls")):{chrome:"none"}}}}var tb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function K4(e={}){const t=tb(e.interaction)?e.interaction:{},n=tb(t.comments)?t.comments:{},r=tb(e.modules?.comments)?e.modules.comments:{};return{comments:{readOnly:(n.readOnly??r.readOnly??!1)===!0,allowResolve:(n.allowResolve??r.allowResolve??!0)!==!1}}}var q4=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Y4(e={}){const t=q4(e.surfaces)?e.surfaces:{},n=q4(e.modules?.surfaces)?e.modules.surfaces:{},r=t.resolver===void 0?n.resolver:t.resolver;return{resolver:typeof r=="function"?r:null,dialog:vs(n.dialog,t.dialog),floating:vs(n.floating,t.floating)}}var yN=class{#t=new Map;#n=new Map;#e=null;#r=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.#i({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.#i({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(`[${jp}]`);if(!n)return null;const r=n.getAttribute(jp),o=r?this.get(r):null;return o&&o.root===n?o:null}subscribe(e){return this.#r.add(e),()=>{this.#r.delete(e)}}clear(){this.#t.clear(),this.#n.clear(),this.#e=null,this.#r.clear()}#i(e){for(const t of Array.from(this.#r))try{t(e)}catch{}}};const ut={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"},X4={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 Z4(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 bN(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 wN(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 Q4(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 nb(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 CN(e){const t=nb(e,["alignment","value"]);if(typeof t!="string")return t;const n=t.trim().toLowerCase();return n==="justified"||n==="both"?"justify":n}function kN(e){const t=nb(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 SN(e){if(e&&typeof e=="object"&&"role"in e)return e;const t=nb(e,["styleId","value","style"]);return typeof t=="string"?t.trim():t}function _N(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 AN=ut.commandUnsupported,bs=ut.tableContextUnavailable;const J4=[{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:Z4,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:Z4,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:bN},{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:_N},{id:"measurement-unit",family:"measurement",disposition:"routed",mutates:!1,instanceRoute:"setMeasurementUnit",valueFrom:"measurementUnit",normalizePayload:wN},{id:"text-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.color",inline:{key:"color",kind:"value-string"},normalizePayload:Q4},{id:"highlight-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.highlight",inline:{key:"highlight",kind:"value-string"},normalizePayload:Q4},{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:CN},{id:"line-height",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setSpacing",blockParagraph:{kind:"spacing-line"},normalizePayload:kN},{id:"linked-style",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"styles.paragraph.setStyle",blockParagraph:{kind:"style"},normalizePayload:SN},{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:AN}];var IN=new Map(J4.map(e=>[e.id,e]));const EN=J4.map(e=>e.id);function Tu(e){return IN.get(e)??null}var TN=["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 $4=[{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:TN,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 eA=new Map($4.map(e=>[e.name,e]));const lG=$4.map(e=>e.name);function rb(e){return eA.get(e)??null}function xN(e){const t=eA.get(e);return t?.disposition==="controller-routed"?t.commandId:null}const RN=".png,.jpg,.jpeg,image/png,image/jpeg";var tA=new Set(["image/png","image/jpeg","image/jpg"]),MN=/\.(png|jpe?g)$/i;function LN(e){if(!e)return!1;const t=typeof e.type=="string"?e.type.toLowerCase():"";return t?tA.has(t):MN.test(String(e.name??""))}function nA(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(PN(String(r.result),e)),r.onerror=()=>n(r.error??new Error("image-read-failed")),r.readAsDataURL(e)})}function PN(e,t){const n=/^data:([^;,]*);base64,/.exec(e);if(!n)return e;const r=n[1].toLowerCase();if(tA.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 DN(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:ON(n,e)}return nA(e)}async function ON(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 nA(o?Object.assign(r,{name:o}):r)}function FN({ownerDocument:e=document,onPick:t,onError:n}={}){const r=e.createElement("input");return r.type="file",r.accept=RN,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(!LN(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 NN=(e,t)=>{let n=e.replace(/[^0-9.]/g,"");return n=parseFloat(n),isNaN(n)&&(n=t),n=parseFloat(n),n},BN=(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};Mt(),Cn();var zN={class:"sd-toolbar-icon"},VN=["innerHTML"],HN={__name:"ToolbarButtonIcon",props:{name:{type:String,required:!0},color:{type:String,default:null},icon:{type:String,default:null}},setup(e){const t=e,n=_e(()=>{if(t.name==="color")return{backgroundColor:t.color||"#111111"};if(t.name==="highlight")return{backgroundColor:t.color||"#D6D6D6"}}),r=_e(()=>["color","highlight"].includes(t.name));return(o,i)=>(ge(),Ie("div",zN,[Oe("div",{class:an(["sd-toolbar-icon__icon",[`sd-toolbar-icon__icon--${t.name}`]]),innerHTML:e.icon},null,10,VN),r.value?(ge(),Ie("div",{key:0,class:"color-bar",style:Sn(n.value)},null,4)):mt("",!0)]))}},rA=yn(HN,[["__scopeId","data-v-d7d79424"]]);Mt(),Cn();var UN=["role","aria-label"],jN=["data-item"],GN=["data-item"],WN={key:1,class:"sd-button-label"},KN=["data-item","aria-label"],qN=["innerHTML"],YN={key:2},XN=["onKeydown","id"],ZN=["placeholder","onKeydown","id","data-item"],QN=["data-item","innerHTML"],JN={"aria-live":"polite",class:"sd-visually-hidden"},$N={__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}=ur(),o=e,{name:i,active:s,icon:a,label:l,hideLabel:u,iconColor:c,hasCaret:d,splitButton:h,disabled:g,expand:p,inlineTextInputVisible:v,hasInlineTextInput:k,minWidth:C,style:_,attributes:y}=o.toolbarItem,w=_e(()=>!!h?.value&&!!d?.value),x=_e(()=>i?.value??""),P=ne(""),N=ne(null),{isHighContrastMode:G}=Vi();zt(()=>l?.value,ke=>{document.activeElement!==N.value&&(P.value=ke==null?"":String(ke))},{immediate:!0});const R=()=>{k&&It(()=>{N.value?.focus(),N.value?.select()}),n("buttonClick")},F=ke=>{g?.value||(ke?.stopPropagation(),n("mainClick"))},Z=()=>{w.value||R()},D=ke=>{if(w.value){F(ke);return}R()},B=ke=>{o.allowEnterPropagation||ke.stopPropagation(),D(ke)},T=ke=>{const ie=o.toolbarItem?.nestedOptions?.value??[],xe=ke.trim();if(!xe)return"";const Je=ie.find(st=>typeof st?.label=="string"&&st.label.toLowerCase()===xe.toLowerCase());return Je?.label?Je.label:ie.find(st=>typeof st?.label=="string"&&st.label.toLowerCase().startsWith(xe.toLowerCase()))?.label??xe},V=()=>{const ke=String(P.value??"").trim();let ie=ke;if(x.value==="fontSize"){const xe=Number.parseFloat(ke);ie=ke.match(/^\d+(\.5)?$/)?ke:Number.isFinite(xe)?Math.floor(xe).toString():""}else x.value==="fontFamily"&&(ie=T(ke));return ie?(n("textSubmit",ie),P.value=ie,!0):!1},J=ke=>{const ie=ke?.currentTarget;ie instanceof HTMLInputElement&&(ie.focus({preventScroll:!0}),ie.select())},q=ke=>{requestAnimationFrame(()=>{const ie=document.getElementById(`inlineTextInput-${ke}`);ie instanceof HTMLInputElement&&(ie.focus({preventScroll:!0}),ie.select())})},se=()=>{const ke=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return ke instanceof HTMLElement?(ke.focus({preventScroll:!0}),!0):!1},pe=()=>{const ke=r?.$toolbar?.pendingSelectionCapture,ie=()=>{ke&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(ke)};if(se()){ie();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),ie())},Ne=()=>{V()&&pe()},he=ke=>{if(V(),ke.shiftKey){x.value==="fontSize"&&(ke.preventDefault(),It(()=>q("fontFamily")));return}if(ke.preventDefault(),x.value==="fontFamily"){It(()=>q("fontSize"));return}x.value==="fontSize"&&It(pe)},ye=_e(()=>_.value?_.value:{minWidth:o.minWidth}),ce=_e(()=>p?.value?or.dropdownCaretUp:or.dropdownCaretDown);return(ke,ie)=>(ge(),Ie("div",{class:an(["sd-toolbar-item",$e(y).className]),style:Sn(ye.value),role:e.isOverflowItem?"menuitem":"button","aria-label":$e(y).ariaLabel,"data-sd-part":"toolbar-item",onClick:Z,onKeydown:ie[9]||(ie[9]=Qo(xe=>B(xe),["enter"])),tabindex:"0"},[Oe("div",{class:an(["sd-toolbar-button",{"sd-active":$e(s),"sd-disabled":$e(g),narrow:e.isNarrow,wide:e.isWide,split:w.value,"has-inline-text-input":$e(k),"high-contrast":$e(G)}]),"data-item":`btn-${$e(i)||""}`},[w.value?(ge(),Ie("div",{key:0,class:"sd-toolbar-button__main","data-item":`btn-${$e(i)||""}-main`,onClick:ie[0]||(ie[0]=xe=>F(xe))},[$e(a)?(ge(),vn(rA,{key:0,color:$e(c),class:"sd-toolbar-icon",icon:$e(a),name:$e(i)},null,8,["color","icon","name"])):mt("",!0),$e(l)&&!$e(u)&&!$e(v)?(ge(),Ie("div",WN,qt($e(l)),1)):mt("",!0)],8,GN)):mt("",!0),w.value?(ge(),Ie("div",{key:1,class:"sd-toolbar-button__caret","data-item":`btn-${$e(i)||""}-caret`,"aria-label":`${$e(y).ariaLabel} options`,role:"button"},[Oe("div",{class:"sd-dropdown-caret",innerHTML:ce.value,style:Sn({opacity:$e(g)?.6:1})},null,12,qN)],8,KN)):(ge(),Ie(Jt,{key:2},[$e(a)?(ge(),vn(rA,{key:0,color:$e(c),class:"sd-toolbar-icon",icon:$e(a),name:$e(i)},null,8,["color","icon","name"])):mt("",!0),$e(l)&&!$e(u)&&(!$e(v)||x.value==="fontFamily")?(ge(),Ie("div",{key:1,class:an(["sd-button-label",{"sd-visually-hidden":$e(v)&&x.value==="fontFamily"}])},qt($e(l)),3)):mt("",!0),$e(v)?(ge(),Ie("span",YN,[$e(i)==="fontSize"?Ws((ge(),Ie("input",{key:0,"onUpdate:modelValue":ie[1]||(ie[1]=xe=>P.value=xe),onKeydown:[Qo(sn(Ne,["stop","prevent"]),["enter"]),ie[2]||(ie[2]=Qo(xe=>he(xe),["tab"]))],onClick:ie[3]||(ie[3]=sn(xe=>J(xe),["stop"])),onFocus:ie[4]||(ie[4]=xe=>J(xe)),type:"text",class:an(["button-text-input button-text-input--font-size",{"high-contrast":$e(G)}]),id:"inlineTextInput-"+$e(i),autocomplete:"off",ref_key:"inlineInput",ref:N},null,42,XN)),[[Ei,P.value]]):Ws((ge(),Ie("input",{key:1,"onUpdate:modelValue":ie[5]||(ie[5]=xe=>P.value=xe),placeholder:$e(l),onKeydown:[Qo(sn(Ne,["stop","prevent"]),["enter"]),ie[6]||(ie[6]=Qo(xe=>he(xe),["tab"]))],onClick:ie[7]||(ie[7]=sn(xe=>J(xe),["stop"])),onFocus:ie[8]||(ie[8]=xe=>J(xe)),type:"text",class:an(["button-text-input",{"button-text-input--font-family":x.value==="fontFamily","high-contrast":$e(G)}]),id:"inlineTextInput-"+$e(i),"data-item":x.value==="fontFamily"?`btn-${$e(i)}-input`:void 0,autocomplete:"off",ref_key:"inlineInput",ref:N},null,42,ZN)),[[Ei,P.value]])])):mt("",!0),$e(d)?(ge(),Ie("div",{key:3,class:"sd-dropdown-caret","data-item":`btn-${$e(i)||""}-toggle`,innerHTML:ce.value,style:Sn({opacity:$e(g)?.6:1})},null,12,QN)):mt("",!0)],64)),Oe("div",JN,qt(`${$e(y).ariaLabel} ${$e(s)?"selected":"unset"}`),1)],10,jN)],46,UN))}},ob=yn($N,[["__scopeId","data-v-dbdea151"]]);Mt(),Cn();var eB={class:"toolbar-separator",role:"separator","aria-label":"Toolbar separator"},tB={__name:"ToolbarSeparator",props:{active:{type:Boolean,default:!1}},emits:["command"],setup(e,{emit:t}){const{isHighContrastMode:n}=Vi(),r=()=>n.value?"#000":"var(--sd-ui-border, #dbdbdb)";return(o,i)=>(ge(),Ie("div",eB,[Oe("div",{class:"separator-inner",style:Sn({backgroundColor:r()})},null,4)]))}},nB=yn(tB,[["__scopeId","data-v-cb82253a"]]);Mt(),Cn();var rB={class:"overflow-menu"},oB={class:"overflow-menu-trigger"},iB={key:0,class:"overflow-menu_items",role:"group"},sB={__name:"OverflowMenu",props:{toolbarItem:{type:Object,required:!0},overflowItems:{type:Array,required:!0}},emits:["buttonClick","close"],setup(e,{emit:t}){const{proxy:n}=ur(),r=t,o=e,i=_e(()=>o.toolbarItem.expand.value),s=ne(!1),a=_e(()=>({...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 Un(()=>{document.addEventListener("keydown",c,!0)}),cr(()=>{document.removeEventListener("keydown",c,!0)}),(d,h)=>(ge(),Ie("div",rB,[Oe("div",oB,[Zt(ob,{"toolbar-item":a.value,onButtonClick:l},null,8,["toolbar-item"])]),i.value?(ge(),Ie("div",iB,[Zt(hm,{class:"superdoc-toolbar-overflow","toolbar-items":e.overflowItems,"from-overflow":"",onCommand:u,onDropdownUpdateShow:h[0]||(h[0]=g=>s.value=g)},null,8,["toolbar-items"])])):mt("",!0)]))}},aB=yn(sB,[["__scopeId","data-v-504ecd05"]]);Mt(),Cn();var lB={class:"toolbar-dropdown"},cB=["onClick"],uB={key:0,class:"toolbar-dropdown-option__icon"},dB={class:"toolbar-dropdown-option__label"},um='button, [href], input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])',fB={__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=_e(()=>!!n.show),c=_e(()=>n.options.some(ie=>ie?.type==="render")),d=_e(()=>typeof n.menuProps!="function"?{}:n.menuProps()||{}),h=_e(()=>{const{class:ie,style:xe,...Je}=d.value;return Je}),g=_e(()=>{const ie=d.value.class,xe=n.options.length>0&&n.options.every(Je=>Je&&Je.type==="render");return["toolbar-dropdown-menu",ie,{"toolbar-dropdown-menu--render-only":xe}]}),p=_e(()=>{const ie=d.value.style||{};return{...n.contentStyle,...ie}}),v=_e(()=>({...p.value,position:"fixed",top:s.value.top,left:s.value.left,maxHeight:s.value.maxHeight,zIndex:2e3})),k=ie=>{r("update:show",ie)},C=()=>{u.value&&k(!1)},_=()=>{if(!o.value)return;const ie=o.value.getBoundingClientRect(),xe=i.value,Je=xe?.offsetWidth??0,st=xe?.scrollHeight??xe?.offsetHeight??0,Tt=window.innerWidth||document.documentElement.clientWidth||0,Te=window.innerHeight||document.documentElement.clientHeight||0,je=8,Ye=4,$=ie.bottom+Ye,S=ie.top-Ye,ee=Math.max(0,Te-$-je),O=Math.max(0,S-je),j=ee<st&&O>ee,U=j?O:ee,W=st?Math.min(st,U):U,te=j?Math.max(je,S-W):$;let Y=ie.left;n.placement==="bottom-end"&&(Y=ie.right-Je);const X=Math.max(je,Tt-Je-je);Y=Math.min(Math.max(je,Y),X),s.value={top:`${te}px`,left:`${Y}px`,maxHeight:`${U}px`}},y=()=>{n.disabled||k(!u.value)},w=ie=>typeof n.nodeProps!="function"?{}:n.nodeProps(ie)||{},x=ie=>{ie?.disabled||ie?.type!=="render"&&(r("select",ie?.key,ie),C())},P=ie=>ie?.type==="render",N=ie=>!ie?.disabled&&ie?.type!=="render",G=ie=>typeof ie?.icon=="function"||!!ie?.icon,R=ie=>typeof ie?.icon=="function"?ie.icon(ie):ie?.icon||null,F=ie=>ie?typeof ie=="string"?ie.split(/\s+/).includes("sd-selected"):Array.isArray(ie)?ie.some(F):typeof ie=="object"?!!ie["sd-selected"]:!1:!1,Z=ie=>F(ie?.props?.class)||F(ie?.class),D=()=>n.options.map((ie,xe)=>N(ie)?xe:-1).filter(ie=>ie>=0),B=()=>{const ie=n.options.findIndex(xe=>N(xe)&&Z(xe));return ie>=0?ie:D()[0]??-1},T=(ie,xe)=>{if(!ie){delete a.value[xe];return}a.value[xe]=ie},V=()=>{a.value.forEach((xe,Je)=>{xe&&xe.setAttribute("tabindex",Je===l.value?"0":"-1")});const ie=a.value[l.value];ie&&typeof ie.focus=="function"&&(ie.focus(),ie.scrollIntoView?.({block:"nearest",inline:"nearest"}))},J=ie=>{const xe=D();if(!xe.length){l.value=-1;return}const Je=xe.indexOf(l.value);if(Je<0){l.value=ie>0?xe[0]:xe[xe.length-1];return}l.value=xe[(Je+ie+xe.length)%xe.length]},q=()=>{let ie=n.options[l.value];if(!N(ie)){const xe=D()[0];ie=xe===void 0?null:n.options[xe]}ie&&x(ie)},se=Bl({name:"ToolbarDropdownRenderOption",props:{option:{type:Object,required:!0}},setup(ie){return()=>typeof ie.option.render!="function"?null:ie.option.render()}}),pe=Bl({name:"ToolbarDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(ie){return()=>R(ie.option)}}),Ne=ie=>{if(!u.value)return;const xe=ie.target;if(!(xe instanceof Element))return;const Je=o.value?.contains(xe),st=i.value?.contains(xe);Je||st||C()},he=ne(null),ye=()=>{const ie=o.value,xe=document.activeElement;if(ie&&xe instanceof HTMLElement&&ie.contains(xe)){he.value=xe;return}he.value=ie?.matches?.(um)?ie:ie?.querySelector(um)},ce=()=>{const ie=he.value;if(ie instanceof HTMLElement&&document.contains(ie)){ie.focus();return}const xe=o.value;if(!xe)return;const Je=xe.matches?.(um)?xe:xe.querySelector(um);if(Je instanceof HTMLElement){Je.focus();return}xe.setAttribute("tabindex","-1"),xe.focus()},ke=ie=>{if(!u.value)return;const{key:xe}=ie;if(["Escape","ArrowDown","ArrowUp","Enter"].includes(xe)){if(xe==="Escape"){ie.preventDefault(),C(),It(()=>{requestAnimationFrame(ce)});return}if(!c.value){if(ie.preventDefault(),xe==="ArrowDown"){J(1),V();return}if(xe==="ArrowUp"){J(-1),V();return}xe==="Enter"&&q()}}};return zt(u,async ie=>{if(!ie){l.value=-1,a.value=[];return}ye(),await It(),_(),!c.value&&(l.value=B(),await It(),V())},{immediate:!0}),zt(u,ie=>{ie?(document.addEventListener("pointerdown",Ne,!0),document.addEventListener("keydown",ke,!0),window.addEventListener("resize",_),window.addEventListener("scroll",_,!0)):(document.removeEventListener("pointerdown",Ne,!0),document.removeEventListener("keydown",ke,!0),window.removeEventListener("resize",_),window.removeEventListener("scroll",_,!0))},{immediate:!0}),cr(()=>{document.removeEventListener("pointerdown",Ne,!0),document.removeEventListener("keydown",ke,!0),window.removeEventListener("resize",_),window.removeEventListener("scroll",_,!0)}),(ie,xe)=>(ge(),Ie("div",lB,[Oe("div",{ref_key:"triggerRef",ref:o,class:"toolbar-dropdown-trigger","data-sd-part":"dropdown-trigger",onClick:y},[Rd(ie.$slots,"trigger",{},void 0,!0)],512),(ge(),vn(Ua,{to:"body"},[Zt(Jh,{name:"fade-in-scale-up-transition"},{default:Ro(()=>[u.value?(ge(),Ie("div",as({key:0,ref_key:"menuRef",ref:i,"data-sd-part":"dropdown-menu",class:g.value,style:v.value},h.value),[(ge(!0),Ie(Jt,null,lr(e.options,(Je,st)=>(ge(),Ie("div",as({key:Je.key,ref_for:!0,ref:Tt=>T(Tt,st),class:["toolbar-dropdown-option",[Je.class,Je.props?.class,{"sd-disabled":Je.disabled,"sd-render":P(Je)}]],tabindex:"-1",onClick:Tt=>x(Je)},{ref_for:!0},{...Je.props,...w(Je)}),[P(Je)?(ge(),vn($e(se),{key:0,option:Je},null,8,["option"])):(ge(),Ie(Jt,{key:1},[G(Je)?(ge(),Ie("span",uB,[Zt($e(pe),{option:Je},null,8,["option"])])):mt("",!0),Oe("span",dB,qt(Je.label),1)],64))],16,cB))),128))],16)):mt("",!0)]),_:1})]))]))}},hB=yn(fB,[["__scopeId","data-v-fef410f7"]]),oA=e=>String(e??"").trim().toLowerCase();const dm=(e,t)=>{const n=oA(e);if(!n)return-1;for(let r=0;r<t.length;r+=1)if(oA(t[r]).startsWith(n))return r;return-1},pB=(e,t,{autocomplete:n=!0}={})=>{const r=String(e??""),o=dm(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 mB=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},gB=e=>e<=31||e===127,vB=e=>e===32||e===160||e===65279,yB=e=>Array.from(String(e)).filter(t=>!gB(t.charCodeAt(0))).join(""),bB=e=>{let t="",n=!1;for(const r of String(e)){if(vB(r.charCodeAt(0))){n=t.length>0;continue}n&&(t+=" "),n=!1,t+=r}return t};const wB=e=>bB(mB(yB(String(e??"").split(",")[0]??""))).trim();var CB=1,kB=1638;const SB=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<CB?"":String(Math.min(r,kB))};Mt(),Cn();var _B=["data-item"],AB=["id","value","disabled","aria-label","aria-expanded","aria-controls","aria-activedescendant","data-item"],IB=["data-item","aria-label","disabled"],EB=["innerHTML"],TB=["id","aria-label"],xB=["id","aria-selected","aria-label","onMousedown","onMouseenter"],RB={class:"toolbar-dropdown-option__label"},MB={class:"sd-button-label sd-font-combobox__legacy-label","aria-hidden":"true"},LB={__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}=Vi(),i=ne(null),s=ne(null),a=ne(null),l=ne([]),u=ne(!1),c=ne(!1),d=ne(-1),h=ne(""),g=ne(""),p=ne(!1),v=ne({top:"0px",left:"0px",minWidth:"0px",maxHeight:"none"}),k=_e(()=>n.item.nestedOptions?.value??[]),C=_e(()=>k.value.map(Y=>String(Y?.label??""))),_=_e(()=>String(n.item.label?.value??"")),y=_e(()=>!!n.item.disabled?.value),w=_e(()=>String(n.item.name?.value??"")),x=_e(()=>n.item.attributes?.value?.ariaLabel??"Font family"),P=_e(()=>u.value?g.value:_.value),N=_e(()=>`sd-${w.value||"combobox"}-listbox-${n.item.id?.value??"default"}`),G=Y=>`${N.value}-option-${Y}`,R=_e(()=>c.value&&d.value>=0?G(d.value):void 0),F=_e(()=>c.value?or.dropdownCaretUp:or.dropdownCaretDown),Z=Y=>{const X=String(Y??"").trim().toLowerCase();return k.value.find(be=>String(be?.label??"").trim().toLowerCase()===X)?.props?.style?.fontFamily||Y||n.uiFontFamily},D=_e(()=>n.showPreview?{fontFamily:Z(u.value?g.value:_.value)}:{fontFamily:n.uiFontFamily}),B=()=>{const Y=n.item.selectedValue?.value;if(Y){const X=k.value.findIndex(be=>be?.key===Y);if(X>=0)return X}return C.value.findIndex(X=>X.toLowerCase()===_.value.toLowerCase())},T=(Y,X)=>{const be=i.value;if(!(!be||typeof be.setSelectionRange!="function"))try{be.setSelectionRange(Y,X)}catch{}},V=()=>{l.value[d.value]?.scrollIntoView?.({block:"nearest",inline:"nearest"})},J=()=>{l.value[d.value]?.focus?.()},q=()=>{const Y=s.value;if(!Y)return;const X=Y.getBoundingClientRect(),be=a.value,ve=be?.scrollHeight??be?.offsetHeight??0,we=window.innerHeight||document.documentElement.clientHeight||0,Be=window.innerWidth||document.documentElement.clientWidth||0,rt=8,at=4,Ct=X.bottom+at,en=X.top-at,Et=Math.max(0,we-Ct-rt),Ut=Math.max(0,en-rt),Wt=Et<ve&&Ut>Et,In=Wt?Ut:Et,bt=ve?Math.min(ve,In):In,nn=Wt?Math.max(rt,en-bt):Ct,et=Math.min(Math.max(rt,X.left),Math.max(rt,Be-X.width-rt));v.value={top:`${nn}px`,left:`${et}px`,minWidth:`${X.width}px`,maxHeight:`${In}px`}},se=_e(()=>({position:"fixed",top:v.value.top,left:v.value.left,minWidth:v.value.minWidth,maxHeight:v.value.maxHeight,fontFamily:n.uiFontFamily,zIndex:2e3})),pe=Y=>{n.item.expand&&typeof n.item.expand=="object"&&"value"in n.item.expand&&(n.item.expand.value=Y)},Ne=(Y,{focusInput:X=!1,focusOption:be=!1}={})=>{if(y.value||!k.value.length){pe(!1);return}c.value=!0,pe(!0),d.value=Y??-1,X&&(u.value=!0,g.value=_.value,i.value?.focus()),It(()=>{q(),V(),be&&J()})},he=({syncItem:Y=!0}={})=>{c.value=!1,d.value=-1,Y&&pe(!1)},ye=()=>{he(),u.value=!1,h.value="",g.value=_.value},ce=()=>{y.value||(c.value||r("item-clicked"),u.value=!0,h.value="",g.value=_.value,It(()=>T(0,g.value.length)))},ke=Y=>{if(y.value)return;const X=document.activeElement===i.value;if(r("item-clicked"),u.value=!0,X||(h.value="",g.value=_.value,Y.preventDefault(),i.value?.focus({preventScroll:!0}),T(0,_.value.length)),!c.value){const be=B();Ne(be>=0?be:0)}},ie=Y=>{const X=Y.relatedTarget;X instanceof Node&&s.value?.contains(X)||X instanceof Node&&a.value?.contains(X)||ye()},xe=Y=>{if(p.value)return;const X=Y.target,be=X.value,ve=typeof X.selectionStart=="number"?X.selectionStart:be.length,we=typeof X.selectionEnd=="number"?X.selectionEnd:ve,Be=typeof Y.inputType=="string"&&Y.inputType.startsWith("delete"),rt=ve===be.length&&we===be.length;h.value=be;const at=pB(be,C.value,{autocomplete:!Be&&rt});g.value=at.display,X.value=at.display,at.display===be&&!rt?T(ve,we):T(at.selectionStart,at.selectionEnd),c.value&&(d.value=at.matchIndex,It(V))},Je=Y=>{p.value=!1,xe(Y)},st=Y=>{if(!k.value.length)return;const X=k.value.length;d.value=((d.value<0?Y>0?-1:0:d.value)+Y+X)%X,It(V)},Tt=(Y,X)=>{r("item-clicked"),r("command",{item:n.item,argument:Y,option:X}),X&&(n.item.selectedValue.value=X.key)},Te=Y=>{Y&&(Tt(Y.label,Y),u.value=!1,h.value="",g.value=Y.label,he())},je=()=>{if(c.value&&d.value>=0)return Te(k.value[d.value]),!0;const Y=dm(h.value,C.value);if(Y>=0)return Te(k.value[Y]),!0;const X=n.normalizeValue(h.value);return X?(Tt(X,null),u.value=!1,h.value="",g.value=X,he(),!0):!1},Ye=Y=>{if(!(Y.isComposing||p.value||Y.keyCode===229)&&!(Y.ctrlKey||Y.metaKey||Y.altKey))switch(Y.key){case"ArrowDown":if(Y.preventDefault(),c.value)J();else{const X=dm(h.value,C.value),be=X>=0?X:B();Ne(be>=0?be:0,{focusOption:!0})}break;case"ArrowUp":if(Y.preventDefault(),c.value)J();else{const X=dm(h.value,C.value),be=X>=0?X:B();Ne(be>=0?be:k.value.length-1,{focusOption:!0})}break;case"Enter":Y.preventDefault(),je()&&r("editor-handoff"),i.value?.blur();break;case"Tab":Y.preventDefault(),je(),he(),i.value?.blur(),r("tab-out",Y);break;case"Escape":Y.preventDefault(),ye(),It(()=>i.value?.focus());break;default:break}},$=Y=>{if(Y.preventDefault(),!y.value)if(r("item-clicked"),c.value)he(),i.value?.focus();else{const X=B();Ne(X>=0?X:0,{focusOption:!0})}},S=(Y,X)=>{Y.preventDefault(),Te(X),r("editor-handoff"),i.value?.blur()},ee=Y=>{d.value=Y},O=Y=>{if(!(Y.ctrlKey||Y.metaKey||Y.altKey))switch(Y.key){case"ArrowDown":Y.preventDefault(),st(1),J();break;case"ArrowUp":Y.preventDefault(),st(-1),J();break;case"Enter":Y.preventDefault(),d.value>=0&&(Te(k.value[d.value]),r("editor-handoff"));break;case"Escape":Y.preventDefault(),ye(),It(()=>i.value?.focus());break;case"Tab":Y.preventDefault(),d.value>=0?Te(k.value[d.value]):he(),r("tab-out",{shiftKey:Y.shiftKey,target:i.value});break;default:break}},j=Y=>{if(!c.value)return;const X=Y.target;X instanceof Element&&(s.value?.contains(X)||a.value?.contains(X)||ye())};zt(c,Y=>{Y?(document.addEventListener("pointerdown",j,!0),window.addEventListener("resize",q),window.addEventListener("scroll",q,!0)):(document.removeEventListener("pointerdown",j,!0),window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),l.value=[])},{immediate:!0}),cr(()=>{document.removeEventListener("pointerdown",j,!0),window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0)});const U=(Y,X)=>{if(!Y){delete l.value[X];return}l.value[X]=Y},W=Y=>Y===d.value,te=Y=>Y?.key&&Y.key===n.item.selectedValue?.value;return zt(_,Y=>{u.value||(g.value=Y)}),zt(()=>!!n.item.expand?.value,Y=>{if(Y&&!c.value){const X=B();Ne(X>=0?X:0,{focusInput:!0});return}!Y&&c.value&&he({syncItem:!1})}),(Y,X)=>(ge(),Ie("div",{ref_key:"rootRef",ref:s,class:an(["sd-font-combobox sd-toolbar-split-field",{"sd-disabled":y.value,"high-contrast":$e(o)}]),style:Sn(n.item.style?.value),"data-item":`btn-${w.value}`},[Oe("span",{class:"sd-font-combobox__field sd-toolbar-split-field__main",onMousedown:ke},[Oe("input",{ref_key:"inputRef",ref:i,id:`inlineTextInput-${w.value}`,class:"button-text-input sd-font-combobox__input",type:"text",role:"combobox",autocomplete:"off",spellcheck:"false",value:P.value,style:Sn(D.value),disabled:y.value,"aria-label":x.value,"aria-expanded":c.value?"true":"false","aria-controls":N.value,"aria-activedescendant":R.value,"aria-haspopup":"listbox","aria-autocomplete":"both","data-item":`btn-${w.value}-input`,onFocus:ce,onBlur:ie,onInput:xe,onKeydown:Ye,onCompositionstart:X[0]||(X[0]=be=>p.value=!0),onCompositionend:Je},null,44,AB)],32),Oe("button",{type:"button",class:"sd-font-combobox__caret sd-toolbar-split-field__caret","data-item":`btn-${w.value}-toggle`,tabindex:"-1","aria-label":`${x.value} options`,disabled:y.value,onMousedown:$},[Oe("span",{class:"sd-dropdown-caret",innerHTML:F.value},null,8,EB)],40,IB),(ge(),vn(Ua,{to:"body"},[c.value?(ge(),Ie("div",{key:0,ref_key:"popupRef",ref:a,role:"listbox",id:N.value,"aria-label":x.value,class:an(["sd-font-combobox__listbox",{"high-contrast":$e(o)}]),style:Sn(se.value)},[(ge(!0),Ie(Jt,null,lr(k.value,(be,ve)=>(ge(),Ie("div",as({key:be.key,ref_for:!0,ref:we=>U(we,ve),id:G(ve),role:"option",tabindex:"-1",class:["toolbar-dropdown-option sd-font-combobox__option",{"sd-active":W(ve),"sd-selected":te(be)}],"aria-selected":te(be)?"true":"false","aria-label":`${x.value} - ${be.label}`},{ref_for:!0},be.props,{onMousedown:we=>S(we,be),onMouseenter:we=>ee(ve),onKeydown:O}),[Oe("span",RB,qt(be.label),1)],16,xB))),128))],14,TB)):mt("",!0)])),Oe("span",MB,qt(_.value),1)],14,_B))}},iA=yn(LB,[["__scopeId","data-v-99070b63"]]);Mt();var PB={__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)=>(ge(),vn(iA,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!0,"normalize-value":$e(wB),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"]))}},DB=PB;Mt();var OB={__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)=>(ge(),vn(iA,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!1,"normalize-value":$e(SB),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"]))}},FB=OB;Mt(),Cn();var NB=2500,BB=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=r1(),r=ne(!1),o=ne(null),i=ne(null),s=ne({top:"0px",left:"0px"});let a=null,l=null,u=null;const c=_e(()=>["sd-tooltip-content",n.class]),d=_e(()=>({...t.contentStyle,...n.style||{},position:"fixed",top:s.value.top,left:s.value.left,zIndex:2100})),h=()=>{a&&(window.clearTimeout(a),a=null)},g=()=>{l&&(window.clearTimeout(l),l=null)},p=()=>{u&&(window.clearTimeout(u),u=null)},v=()=>{p(),u=window.setTimeout(()=>{u=null,_()},NB)},k=()=>{if(!o.value||!i.value)return;const F=o.value.getBoundingClientRect(),Z=i.value.offsetWidth,D=i.value.offsetHeight,B=window.innerWidth||document.documentElement.clientWidth||0,T=8;let V=F.left+F.width/2-Z/2;V=Math.max(T,Math.min(V,B-Z-T)),s.value={top:`${F.top-D-10}px`,left:`${V}px`}},C=async()=>{t.disabled||(h(),g(),!r.value&&(r.value=!0,v(),await It(),k()))},_=()=>{g(),h(),p(),r.value&&(r.value=!1)},y=()=>{if(h(),g(),!r.value){if(t.delay===0){C();return}l=window.setTimeout(()=>{l=null,C()},t.delay)}},w=()=>{if(g(),h(),!!r.value){if(t.duration===0){_();return}a=window.setTimeout(()=>{a=null,_()},t.duration)}},x=()=>{t.trigger==="hover"&&y()},P=()=>{t.trigger==="hover"&&w()},N=()=>{g(),h()},G=()=>{w()},R=F=>{F.key==="Escape"&&_()};return zt(()=>t.disabled,F=>{F&&_()}),zt(r,F=>{F?(window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),document.addEventListener("keydown",R,!0)):(window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),document.removeEventListener("keydown",R,!0))}),cr(()=>{g(),h(),p(),window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),document.removeEventListener("keydown",R,!0)}),(F,Z)=>(ge(),Ie(Jt,null,[Oe("span",{ref_key:"triggerRef",ref:o,class:"sd-tooltip-trigger",onMouseenter:x,onMouseleave:P,onFocusin:x,onFocusout:P},[Rd(F.$slots,"trigger",{},void 0,!0)],544),(ge(),vn(Ua,{to:"body"},[Zt(Jh,{name:"fade-in-scale-up-transition"},{default:Ro(()=>[r.value&&!e.disabled?(ge(),Ie("div",{key:0,ref_key:"contentRef",ref:i,class:an(c.value),style:Sn(d.value),onMouseenter:N,onMouseleave:G},[Z[0]||(Z[0]=Oe("span",{class:"sd-tooltip-arrow","aria-hidden":"true"},null,-1)),Rd(F.$slots,"default",{},void 0,!0)],38)):mt("",!0)]),_:3})]))],64))}}),fm=yn(BB,[["__scopeId","data-v-2a872eae"]]);Mt(),Cn();var zB=["onKeydown","tabindex","data-item-id"],VB={key:0},HB={key:0},UB={key:0},jB={key:0},GB={key:0},WB={__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}=ur(),o=ne([]),i=ne(null),s=e,a=ne(null),{isHighContrastMode:l}=Vi(),u=window.matchMedia("(max-width: 768px)").matches,c=_e(()=>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=Te=>Te.type==="button",h=Te=>Te.type==="dropdown",g=Te=>Te.type==="dropdown"&&Te.name?.value==="fontFamily",p=Te=>Te.type==="dropdown"&&Te.name?.value==="fontSize",v=Te=>Te.type==="separator",k=Te=>Te.type==="overflow",C=Te=>!!Te.nestedOptions?.value?.length,_=Te=>{if(!Te)return!1;const je=Te.expand;return typeof je=="object"&&je!==null&&"value"in je?!!je.value:!!je},y=(Te,je)=>{Te?.expand&&(Te.expand.value=je)},w=(Te,je=void 0)=>{if(Te.disabled.value)return;if(k(Te)){const $=!_(Te);$&&N(),y(Te,$),a.value=$?Te:null,n("item-clicked");return}if(h(Te))return;a.value&&h(a.value)&&_(a.value)&&N(),n("item-clicked");const Ye=je!==void 0?je:Te.argument?.value;n("command",Ye===void 0?{item:Te}:{item:Te,argument:Ye})},x=(Te,je)=>{Te.disabled.value||(a.value=null,n("command",{item:Te,argument:je}))},P=Te=>{if(Te.disabled.value)return;N();const je=Te.splitButtonCommand,Ye=Te.command,$=je||Ye;if(!$)return;const S={...Te,command:$};n("item-clicked"),n("command",{item:S})},N=()=>{const Te=r?.$toolbar?.toolbarItems||[],je=r?.$toolbar?.overflowItems||[],Ye=[...Te,...je];(Ye.length?Ye:s.toolbarItems).forEach($=>{const S=k($)&&!s.fromOverflow;(h($)||S)&&y($,!1)}),a.value=null},G=(Te,je)=>{N(),n("command",{item:Te,argument:Te.dropdownValueKey.value?je[Te.dropdownValueKey.value]:je.label,option:je}),Te.selectedValue.value=je.key},R=Te=>{n("command",Te)},F=()=>{N(),n("item-clicked")},Z=()=>{const Te=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return Te instanceof HTMLElement?(Te.focus({preventScroll:!0}),!0):!1},D=()=>{const Te=r?.$toolbar?.pendingSelectionCapture,je=()=>{Te&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(Te)};if(Z()){je();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),je())},B=Te=>!(Te instanceof HTMLElement)||Te.classList.contains("sd-disabled")?null:Te.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")||Te.querySelector('button:not([disabled]), [role="button"]:not(.sd-disabled), [tabindex]:not([tabindex="-1"])'),T=(Te,je)=>{const Ye=Te?.target?.closest?.(".sd-toolbar-item-ctn");if(!(Ye instanceof HTMLElement))return!1;let $=je>0?Ye.nextElementSibling:Ye.previousElementSibling;for(;$;){const S=B($);if(S instanceof HTMLElement)return Ye.setAttribute("tabindex","-1"),$.setAttribute("tabindex","0"),S.focus(),!0;$=je>0?$.nextElementSibling:$.previousElementSibling}return!1},V=Te=>{N(),T(Te,Te?.shiftKey?-1:1)||D()},J=Te=>{if(N(),Te?.shiftKey){T(Te,-1)||D();return}D()},q=()=>{D()},se=Te=>Te.nestedOptions?.value?.length?Te.nestedOptions.value.map(je=>{const Ye=je?.type!=="render"&&Te.selectedValue.value===je.key;return{...je,props:{...je.props,class:Ye?"sd-selected":""}}}):[],pe=(Te,je)=>({role:"menuitem",ariaLabel:`${je.attributes.value.ariaLabel} - ${Te.label}`}),Ne=Te=>{const je=Te.target,Ye=Te.target.closest(".sd-toolbar-item-ctn").nextElementSibling;Ye&&(je.setAttribute("tabindex","-1"),Ye.setAttribute("tabindex","0"),Ye.focus())},he=Te=>{const je=Te.target,Ye=Te.target.closest(".sd-toolbar-item-ctn").previousElementSibling;Ye&&(je.setAttribute("tabindex","-1"),Ye.setAttribute("tabindex","0"),Ye.focus())},ye=Te=>{const je=Te.target.closest(".button-group").nextElementSibling;if(je)je.setAttribute("tabindex","0"),je.focus();else{const Ye=document.querySelector(".ProseMirror");Ye&&Ye.focus()}},ce=Te=>{const je=Te.target.closest(".button-group").previousElementSibling;je&&(je.setAttribute("tabindex","0"),je.focus())},ke=Te=>{if(!Te.disabled.value){if(h(Te)){Je(!_(Te),Te);return}w(Te)}},ie=(Te,je)=>{const Ye=Te.target.nodeName==="INPUT"||Te.target.nodeName==="TEXTAREA",$=je.name.value==="fontSize"||je.name.value==="fontFamily";if(!(Ye&&$)&&["Enter"," ","Spacebar","Escape","ArrowRight","ArrowLeft","Tab"].includes(Te.key))switch(Te.preventDefault(),Te.key){case"Enter":case" ":case"Spacebar":ke(je);break;case"Escape":N();break;case"ArrowRight":N(),Ne(Te);break;case"ArrowLeft":N(),he(Te);break;case"Tab":Te.shiftKey?ce(Te):ye(Te);break;default:break}},xe=Te=>{const je=o.value.find(Ye=>!Ye.classList.contains("sd-disabled"));je&&(je.setAttribute("tabindex","0"),je.focus())},Je=(Te,je)=>{if(n("item-clicked"),!Te){N(),n("dropdown-update-show",!1);return}N(),a.value=je,y(je,!0),n("dropdown-update-show",!0)},st=Te=>{if(!a.value)return;const je=Te.target;je instanceof Element&&(je.closest(".sd-toolbar-dropdown-menu")||i.value?.contains(je)||N())};return zt(()=>_(a.value),Te=>{Te?document.addEventListener("pointerdown",st,!0):document.removeEventListener("pointerdown",st,!0)},{immediate:!0}),cr(()=>{document.removeEventListener("pointerdown",st,!0)}),(Te,je)=>(ge(),Ie("div",{style:Sn(c.value),class:"button-group",role:"group",onFocus:xe,ref_key:"buttonGroupRef",ref:i},[(ge(!0),Ie(Jt,null,lr(e.toolbarItems,(Ye,$)=>(ge(),Ie("div",{key:Ye.id.value,class:an([{narrow:Ye.isNarrow.value,wide:Ye.isWide.value,"sd-disabled":Ye.disabled.value},"sd-toolbar-item-ctn"]),onKeydown:S=>ie(S,Ye),ref_for:!0,ref_key:"toolbarItemRefs",ref:o,tabindex:$===0?0:-1,"data-item-id":Ye.id.value},[v(Ye)?(ge(),vn(nB,{key:0,style:{width:"20px"}})):mt("",!0),g(Ye)&&C(Ye)?(ge(),vn(fm,{key:1,trigger:"hover",disabled:!Ye.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:Ro(()=>[Zt(DB,{item:Ye,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:R,onItemClicked:F,onTabOut:je[0]||(je[0]=S=>V(S)),onEditorHandoff:q},null,8,["item","ui-font-family"])]),default:Ro(()=>[Oe("div",null,[Fi(qt(Ye.tooltip)+" ",1),Ye.disabled.value?(ge(),Ie("span",VB,"(disabled)")):mt("",!0)])]),_:2},1032,["disabled","content-style"])):p(Ye)&&C(Ye)?(ge(),vn(fm,{key:2,trigger:"hover",disabled:!Ye.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:Ro(()=>[Zt(FB,{item:Ye,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:R,onItemClicked:F,onTabOut:je[1]||(je[1]=S=>J(S)),onEditorHandoff:q},null,8,["item","ui-font-family"])]),default:Ro(()=>[Oe("div",null,[Fi(qt(Ye.tooltip)+" ",1),Ye.disabled.value?(ge(),Ie("span",HB,"(disabled)")):mt("",!0)])]),_:2},1032,["disabled","content-style"])):h(Ye)&&Ye.nestedOptions?.value?.length?(ge(),vn(hB,{key:3,options:se(Ye),disabled:Ye.disabled.value,show:_(Ye),"content-style":{fontFamily:s.uiFontFamily},placement:"bottom-start",class:"sd-toolbar-button sd-editor-toolbar-dropdown",onSelect:(S,ee)=>G(Ye,ee),"onUpdate:show":S=>Je(S,Ye),style:Sn(Ye.dropdownStyles.value),"menu-props":()=>({role:"menu",style:{fontFamily:s.uiFontFamily},class:["sd-toolbar-dropdown-menu",{"high-contrast":$e(l)}]}),"node-props":S=>pe(S,Ye)},{trigger:Ro(()=>[Zt(fm,{trigger:"hover",disabled:!Ye.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:Ro(()=>[Zt(ob,{"toolbar-item":Ye,disabled:Ye.disabled.value,"allow-enter-propagation":!0,onTextSubmit:S=>x(Ye,S),onMainClick:S=>P(Ye)},null,8,["toolbar-item","disabled","onTextSubmit","onMainClick"])]),default:Ro(()=>[Oe("div",null,[Fi(qt(Ye.tooltip)+" ",1),Ye.disabled.value?(ge(),Ie("span",UB,"(disabled)")):mt("",!0)])]),_:2},1032,["disabled","content-style"])]),_:2},1032,["options","disabled","show","content-style","onSelect","onUpdate:show","style","menu-props","node-props"])):d(Ye)?(ge(),vn(fm,{key:4,trigger:"hover",class:"sd-editor-toolbar-tooltip","content-style":{fontFamily:s.uiFontFamily}},{trigger:Ro(()=>[Zt(ob,{"toolbar-item":Ye,"is-overflow-item":e.fromOverflow,onTextSubmit:S=>x(Ye,S),onButtonClick:S=>w(Ye)},null,8,["toolbar-item","is-overflow-item","onTextSubmit","onButtonClick"])]),default:Ro(()=>[Ye.tooltip?(ge(),Ie("div",jB,[Fi(qt(Ye.tooltip)+" ",1),Ye.disabled.value?(ge(),Ie("span",GB,"(disabled)")):mt("",!0)])):mt("",!0)]),_:2},1032,["content-style"])):mt("",!0),k(Ye)&&e.overflowItems.length?(ge(),vn(aB,{key:5,"toolbar-item":Ye,onButtonClick:S=>w(Ye),"overflow-items":e.overflowItems,onClose:N},null,8,["toolbar-item","onButtonClick","overflow-items"])):mt("",!0)],42,zB))),128))],36))}},hm=yn(WB,[["__scopeId","data-v-590293ab"]]),KB=[["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 qB=KB.map(([e,t])=>({label:e,key:e,props:{style:{fontFamily:`${e}, ${t}`},"data-item":"btn-fontFamily-option"}}));function YB(e){if(e?.length)return e.map(t=>({label:t.label,key:t.value,props:{style:{fontFamily:t.previewFamily||t.label},"data-item":"btn-fontFamily-option"}}))}const XB=[{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"}}],Vf={sm:768,md:1024,lg:1280,xl:1410},ib={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"},sA={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"},aA=Object.values(sA),cG=[...new Set([...Object.values(ib),...aA])];var ZB=new Set(["link"]);const uG=new Set(Object.keys(ib).filter(e=>!ZB.has(e)));Mt(),Cn();var QB="Arial, Helvetica, sans-serif",JB={__name:"Toolbar",emits:["command","toggle","select"],setup(e,{emit:t}){const{proxy:n}=ur();let r=ne(1);const o=ne(0),i=ne(!1);let s=null,a=null;const l=_e(()=>{const G=n?.$toolbar?.config?.uiDisplayFallbackFont;return typeof G=="string"&&G.trim()?G.trim():QB}),u=n.$toolbar.config?.toolbarGroups?.includes("left"),c=n.$toolbar.config?.toolbarGroups?.includes("right"),d=n.$toolbar.config?.toolbarButtonsExclude||[],h=G=>(o.value,n.$toolbar.getToolbarItemByGroup(G).filter(R=>!d.includes(R.name.value))),g=()=>{i.value=n.$toolbar.getAvailableWidth()<=Vf.lg},v=BN(async()=>{await n.$toolbar.onToolbarResize(),g(),r.value+=1},300),k=()=>{r.value+=1},C=()=>{o.value+=1};function _(){window.removeEventListener("resize",v),n.$toolbar.off?.("toolbar-items-changed",k),n.$toolbar.off?.("toolbar-state-change",C),s?.disconnect(),s=null}function y(){_(),window.addEventListener("resize",v),n.$toolbar.on?.("toolbar-items-changed",k),n.$toolbar.on?.("toolbar-state-change",C),typeof ResizeObserver<"u"&&n.$toolbar.config?.responsiveToContainer&&n.$toolbar.toolbarContainer&&(s=new ResizeObserver(()=>{v()}),s.observe(n.$toolbar.toolbarContainer)),g()}Un(y),Pg(y),Dg(_),cr(_);const w=()=>{if(!n.$toolbar.activeEditor){a=null,n.$toolbar.pendingSelectionCapture=null;return}a=n.$toolbar.ui?.selection?.capture?.()??null,n.$toolbar.pendingSelectionCapture=a},x=({item:G,argument:R,option:F})=>{P(),n.$toolbar.emitCommand({item:G,argument:R,option:F})},P=()=>{const G=n.$toolbar.activeEditor;if(!G)return;const R=n.$toolbar.pendingSelectionCapture??a;if(R&&typeof n.$toolbar.ui?.selection?.restore=="function"){n.$toolbar.ui.selection.restore(R);return}G.commands?.restoreSelection?.()},N=G=>{w(),!G.target.closest('input, textarea, [contenteditable="true"]')&&G.preventDefault()};return(G,R)=>(ge(),Ie("div",{class:"superdoc-toolbar",key:$e(r),role:"toolbar","aria-label":"Toolbar","data-sd-part":"toolbar","data-editor-ui-surface":"",onMousedown:N},[$e(u)?(ge(),vn(hm,{key:0,tabindex:"0","toolbar-items":h("left"),"overflow-items":$e(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"left",onCommand:x,class:"superdoc-toolbar-group-side"},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"])):mt("",!0),Zt(hm,{tabindex:"0","toolbar-items":h("center"),"overflow-items":$e(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"center",onCommand:x},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"]),$e(c)?(ge(),vn(hm,{key:1,tabindex:"0","toolbar-items":h("right"),"overflow-items":$e(n).$toolbar.overflowItems,"compact-side-groups":i.value,"ui-font-family":l.value,position:"right",onCommand:x,class:"superdoc-toolbar-group-side"},null,8,["toolbar-items","overflow-items","compact-side-groups","ui-font-family"])):mt("",!0)],32))}},$B=yn(JB,[["__scopeId","data-v-55b5af7a"]]);const ez=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"}}};Mt();const An=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(ns()),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),g=ne(!1),p=ne(e.style),v=ne(e.isNarrow),k=ne(e.isWide),C=ne(e.minWidth),_=ne(e.suppressActiveHighlight||!1),y=ne(e.argument),w=ne(null),x=ne(null),P=ne(e.iconColor),N=ne(e.hasCaret),G=ne(!!e.splitButton),R=e.splitButtonCommand,F=!!e.restoreEditorFocus,Z=ne(e.dropdownStyles),D=ne(e.tooltip),B=ne(e.tooltipVisible),T=ne(e.tooltipTimeout),V=ne(e.defaultLabel),J=ne(e.label),q=ne(e.hideLabel),se=ne(e.inlineTextInputVisible),pe=ne(e.hasInlineTextInput),Ne=ne(e.markName),he=ne(e.labelAttr),ye=ne(e.selectedValue),ce=ne(e.dropdownValueKey),ke=ne(e.inputRef||null),ie=ne([]);if(e.options){if(!Array.isArray(e.options))throw new Error("Invalid toolbar item options - "+e.options);ie.value?.push(...e.options)}const xe=(S={},...ee)=>{Te(S,...ee),!_.value&&(h.value=!0)},Je=()=>{je(),h.value=!1},st=S=>{d.value=S},Tt=()=>{d.value=c},Te=e.onActivate||(()=>null),je=e.onDeactivate||(()=>null),Ye=()=>{const S={};return Object.keys($).forEach(ee=>{$[ee].value!==void 0&&(S[ee]=$[ee].value)}),S},$={id:t,name:r,type:n,command:o,noArgumentCommand:i,icon:s,tooltip:D,group:a,attributes:u,disabled:d,active:h,expand:g,nestedOptions:ie,style:p,isNarrow:v,isWide:k,minWidth:C,argument:y,parentItem:x,iconColor:P,hasCaret:N,splitButton:G,splitButtonCommand:R,dropdownStyles:Z,tooltipVisible:B,tooltipTimeout:T,defaultLabel:V,label:J,hideLabel:q,inlineTextInputVisible:se,hasInlineTextInput:pe,restoreEditorFocus:F,markName:Ne,labelAttr:he,childItem:w,allowWithoutEditor:l,dropdownValueKey:ce,selectedValue:ye,inputRef:ke};return{...$,unref:Ye,activate:xe,deactivate:Je,setDisabled:st,resetDisabled:Tt,onActivate:Te,onDeactivate:je}};Mt(),Cn();var tz=["onClick","innerHTML","aria-label","onKeydown"],nz={__name:"AlignmentButtons",emits:["select"],setup(e,{emit:t}){const{isHighContrastMode:n}=Vi(),r=t,o=ne([]),i=[{key:"left",ariaLabel:"Align left",icon:or.alignLeft},{key:"center",ariaLabel:"Align center",icon:or.alignCenter},{key:"right",ariaLabel:"Align right",icon:or.alignRight},{key:"justify",ariaLabel:"Justify",icon:or.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 Un(()=>{const c=o.value[0];c&&(c.setAttribute("tabindex","0"),c.focus())}),(c,d)=>(ge(),Ie("div",{class:an(["alignment-buttons",{"high-contrast":$e(n)}])},[(ge(),Ie(Jt,null,lr(i,(h,g)=>Oe("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:sn(p=>u(p,g),["prevent"])},null,40,tz)),64))],2))}},rz=yn(nz,[["__scopeId","data-v-13e5f7a4"]]);Mt(),Cn();var oz=["onClick","innerHTML","aria-label","onKeydown"],iz={__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}=Vi(),r=t,o=e,i=ne([]),s=_e(()=>({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 Un(()=>{const d=i.value[0];d&&(d.setAttribute("tabindex","0"),d.focus())}),(d,h)=>(ge(),Ie("div",{class:an(["style-buttons-list",{"high-contrast":$e(n)}])},[(ge(!0),Ie(Jt,null,lr(o.buttons,(g,p)=>(ge(),Ie("div",{key:g.key,class:an(["sd-button-icon",{"sd-selected":o.selectedStyle===g.key}]),style:Sn(s.value),onClick:v=>a(g.key),innerHTML:g.icon,role:"menuitem","aria-label":g.ariaLabel,ref_for:!0,ref_key:"buttonRefs",ref:i,onKeydown:sn(v=>c(v,p),["prevent"])},null,46,oz))),128))],2))}},lA=yn(iz,[["__scopeId","data-v-44f37ff6"]]);const sz=[{key:"disc",icon:or.bulletListDisc,ariaLabel:"Opaque circle"},{key:"circle",icon:or.bulletListCircle,ariaLabel:"Outline circle"},{key:"square",icon:or.bulletListSquare,ariaLabel:"Opaque square"}],az=[{key:"decimal",icon:or.numberedListDecimal,ariaLabel:"1. 2. 3."},{key:"decimal-paren",icon:or.numberedListDecimalParen,ariaLabel:"1) 2) 3)"},{key:"upper-roman",icon:or.numberedListUpperRoman,ariaLabel:"I. II. III."},{key:"lower-roman",icon:or.numberedListLowerRoman,ariaLabel:"i. ii. iii."},{key:"upper-alpha",icon:or.numberedListUpperAlpha,ariaLabel:"A. B. C."},{key:"upper-alpha-paren",icon:or.numberedListUpperAlphaParen,ariaLabel:"A) B) C)"},{key:"lower-alpha",icon:or.numberedListLowerAlpha,ariaLabel:"a. b. c."},{key:"lower-alpha-paren",icon:or.numberedListLowerAlphaParen,ariaLabel:"a) b) c)"}];Mt(),Cn();var lz=["onClick","onKeydown"],cz={class:"document-mode-column icon-column"},uz=["innerHTML"],dz={class:"document-mode-column text-column"},fz={class:"document-mode-type"},hz={class:"document-mode-description"},pz={__name:"DocumentMode",props:{options:{type:Array}},emits:["select"],setup(e,{emit:t}){const n=t,r=ne([]),{isHighContrastMode:o}=Vi(),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 Un(()=>{r.value[0].setAttribute("tabindex","0"),r.value[0].focus()}),(c,d)=>(ge(),Ie("div",{class:an(["document-mode",{"high-contrast":$e(o)}])},[(ge(!0),Ie(Jt,null,lr(e.options,(h,g)=>(ge(),Ie("div",{class:an(["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:sn(p=>u(p,g),["prevent"])},[Oe("div",cz,[Oe("div",{class:"icon-column__icon",innerHTML:h.icon},null,8,uz)]),Oe("div",dz,[Oe("div",fz,qt(h.label),1),Oe("div",hz,qt(h.description),1)])],42,lz))),256))],2))}},mz=yn(pz,[["__scopeId","data-v-bee14d7a"]]);Mt(),Cn();var gz={class:"linked-style-buttons","data-editor-ui-surface":""},vz=["onClick","onKeydown","aria-label"],yz={__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,g)=>{switch(d.key){case"ArrowDown":s(h);break;case"ArrowUp":a(h);break;case"Enter":d.preventDefault(),i(g);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 Un(()=>{r.value[0]&&(r.value[0].setAttribute("tabindex","0"),r.value[0].focus())}),(d,h)=>(ge(),Ie("div",gz,[(ge(!0),Ie(Jt,null,lr(o.styles,(g,p)=>(ge(),Ie("div",{key:g.id??p,class:an(["style-item",{selected:e.selectedOption===g.id}]),onClick:v=>i(g),onKeydown:v=>l(v,p,g),"aria-label":`Linked style - ${g.id??u(g)}`,ref_for:!0,ref_key:"styleRefs",ref:r},[Oe("div",{class:"style-name","data-item":"btn-linkedStyles-option",style:Sn(c(g))},qt(u(g)),5)],42,vz))),128))]))}},bz=yn(yz,[["__scopeId","data-v-43b5dcca"]]);Mt(),Cn();var wz=["placeholder"],Cz={class:"sd-ai-writer__footer"},kz={key:0,class:"sd-ai-writer__error",role:"alert"},Sz=["disabled"],_z="https://sd-dev-express-gateway-i6xtm.ondigitalocean.app/insights",Az="You are an expert copywriter and you are immersed in a document editor. Only write what is asked for.",Iz={__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=_e(()=>t.selectedText?"Insert prompt to update text":"Insert prompt to generate text"),a=_e(()=>n.value.trim().length>0&&!r.value);Un(()=>{It(()=>{i.value?.focus()})});function l(p){if(typeof p=="string")return p;if(!p||typeof p!="object")return"";const v=p.custom_prompt;if(Array.isArray(v)){const k=v[0];if(k&&typeof k.value=="string")return k.value}return v&&typeof v=="object"&&typeof v.value=="string"?v.value:typeof p.value=="string"?p.value:typeof p.text=="string"?p.text:""}async function u(p){const v={"Content-Type":"application/json"};t.apiKey&&(v["x-api-key"]=t.apiKey);const k=t.selectedText.trim(),C=k?`Rewrite the following text: "${k}" using these instructions: ${p}`:`Generate text based on the following prompt: ${p}`,_=await fetch(t.endpoint||_z,{method:"POST",headers:v,body:JSON.stringify({stream:!1,context:Az,insights:[{type:"custom_prompt",name:k?"text_rewrite":"text_generation",message:C,format:[{value:""}]}]})});if(!_.ok){const w=await _.text().catch(()=>"");throw new Error(w||`AI request failed with ${_.status}`)}const y=l((_.headers.get("content-type")||"").includes("application/json")?await _.json():await _.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 v=t.doc;if(!v)throw new Error("Document API is unavailable.");t.restoreSelection?.();let k=null,C=!1;if(t.selectedText&&t.target&&typeof v.replace=="function"?(k=v.replace({target:t.target,text:p}),C=!0):t.target&&typeof v.insert=="function"?(k=v.insert({target:t.target,value:p,type:"text"}),C=!0):typeof v.insert=="function"&&(k=v.insert({value:p,type:"text"}),C=!0),!C)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 g(p){p.key!=="Enter"||p.shiftKey||(p.preventDefault(),h())}return(p,v)=>(ge(),Ie("form",{class:"sd-ai-writer","data-item":"ai-writer",onSubmit:sn(h,["prevent"])},[Ws(Oe("textarea",{ref_key:"textareaRef",ref:i,"onUpdate:modelValue":v[0]||(v[0]=k=>n.value=k),class:"sd-ai-writer__input",placeholder:s.value,rows:"4",onKeydown:g},null,40,wz),[[Ei,n.value]]),Oe("div",Cz,[o.value?(ge(),Ie("p",kz,qt(o.value),1)):mt("",!0),Oe("button",{class:"sd-ai-writer__submit",type:"submit",disabled:!a.value},qt(r.value?"Generating":"Generate"),9,Sz)])],32))}},Ez=yn(Iz,[["__scopeId","data-v-67f6c6f7"]]);Mt(),Cn();var Tz=["aria-label","onClick","onKeydown"],xz=["innerHTML"],Rz=["innerHTML"],pm=7,Mz={__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=_e(()=>p=>r.activeColor.value?r.activeColor.value.toUpperCase()===p.value:!1),i=(p,v)=>v===5||["#FFFFFF","#FAFF09"].includes(p)?{color:"#000"}:{color:"#FFF"},s=p=>{n("select",p.value)},a=ne([]),l=ne([]);Un(()=>{if(!r.icons.every(v=>Array.isArray(v)))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,v)=>{const k=pm*p+v+1,C=l.value[k];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},c=(p,v)=>{const k=pm*p+v-1,C=l.value[k];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},d=(p,v)=>{const k=v+pm*(p+1),C=l.value[k];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},h=(p,v)=>{const k=v+pm*(p-1),C=l.value[k];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},g=(p,v,k,C)=>{switch(p.key){case"ArrowRight":u(v,k);break;case"ArrowLeft":c(v,k);break;case"ArrowDown":d(v,k);break;case"ArrowUp":h(v,k);break;case"Enter":s(C);break;case"Escape":n("clickoutside");break;default:break}};return(p,v)=>(ge(!0),Ie(Jt,null,lr(e.icons,(k,C)=>(ge(),Ie("div",{class:"sd-option-row",key:C,role:"group",ref_for:!0,ref_key:"rowRefs",ref:a},[(ge(!0),Ie(Jt,null,lr(k,(_,y)=>(ge(),Ie("div",{class:"sd-option",key:y,"aria-label":_.label,role:"menuitem",ref_for:!0,ref_key:"iconRefs",ref:l,onClick:sn(w=>s(_),["stop","prevent"]),onKeydown:sn(w=>g(w,C,y,_),["prevent"])},[Oe("div",{class:"sd-option__icon",innerHTML:_.icon,style:Sn(_.style)},null,12,xz),o.value(_)?(ge(),Ie("div",{key:0,class:"sd-option__check",innerHTML:$e(or).colorOptionCheck,style:Sn(i(_.value,y))},null,12,Rz)):mt("",!0)],40,Tz))),128))]))),128))}},cA=yn(Mz,[["__scopeId","data-v-05eb02fc"]]),Lz=`<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
|
`;Mt(),Cn();var Pz={class:"options-grid-wrap"},Dz=["innerHTML"],Oz={class:"option-grid-ctn"},Fz={__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)=>(ge(),Ie("div",Pz,[e.hasNoneIcon?(ge(),Ie("div",{key:0,class:"none-option",role:"menuitem","aria-label":"Clear color selection",onClick:i[0]||(i[0]=s=>r("none"))},[Oe("span",{innerHTML:$e(Lz),class:"none-icon"},null,8,Dz),i[1]||(i[1]=Fi(" None ",-1))])):mt("",!0),Oe("div",Oz,[Zt(cA,{icons:e.icons,"active-color":e.activeColor,onSelect:r},null,8,["icons","active-color"]),e.customIcons.flat().length?(ge(),Ie(Jt,{key:0},[i[2]||(i[2]=Oe("span",{class:"option-grid-ctn__subtitle"},"Custom colors",-1)),Zt(cA,{icons:e.customIcons,"active-color":e.activeColor,onSelect:r},null,8,["icons","active-color"])],64)):mt("",!0)])]))}},Nz=yn(Fz,[["__scopeId","data-v-52b0283a"]]);const sb=(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})};Mt();var Bz=e=>{e.expand.value=!1};const Yt=(e,t=null)=>({label:t,icon:or.colorOption,value:e,style:{color:e,boxShadow:"0 0 5px 1px rgba(0, 0, 0, 0.1)",borderRadius:"50%"}}),ab=(e,t,n=[],r=!1)=>{const o=i=>{t.iconColor.value=i,e.emitCommand({item:t,argument:i}),Bz(t),sb(e)};return Gr("div",{},[Gr(Nz,{icons:zz,customIcons:n,activeColor:t.iconColor,hasNoneIcon:r,onSelect:o})])},zz=[[Yt("#111111","black"),Yt("#333333","dark gray"),Yt("#5C5C5C","medium gray"),Yt("#858585","light gray"),Yt("#ADADAD","very light gray"),Yt("#D6D6D6","transparent gray"),Yt("#FFFFFF","white")],[Yt("#860028","dark red"),Yt("#D2003F","red"),Yt("#DB3365","coral red"),Yt("#E4668C","light red"),Yt("#ED99B2","pale pink"),Yt("#F6CCD9","transparent pink"),Yt("#FF004D","bright pink")],[Yt("#83015E","dark purple"),Yt("#CD0194","purple"),Yt("#D734A9","orchid"),Yt("#E167BF","light purple"),Yt("#EB99D4","lavender"),Yt("#F5CCEA","transparent pink"),Yt("#FF00A8","neon pink")],[Yt("#8E220A","maroon"),Yt("#DD340F","red-orange"),Yt("#E45C3F","burnt orange"),Yt("#EB856F","peach"),Yt("#F1AE9F","pale peach"),Yt("#F8D6CF","transparent peach"),Yt("#FF7A00","orange")],[Yt("#947D02","olive"),Yt("#E7C302","mustard yellow"),Yt("#ECCF35","yellow"),Yt("#F1DB67","light yellow"),Yt("#F5E79A","very pale yellow"),Yt("#FAF3CC","transparent yellow"),Yt("#FAFF09","neon yellow")],[Yt("#055432","forest green"),Yt("#07834F","green"),Yt("#399C72","medium green"),Yt("#6AB595","light green"),Yt("#9CCDB9","mint"),Yt("#CDE6DC","transparent mint"),Yt("#05F38F","bright teal")],[Yt("#063E7E","navy blue"),Yt("#0A60C5","blue"),Yt("#3B80D1","sky blue"),Yt("#6CA0DC","cornflower blue"),Yt("#9DBFE8","light blue"),Yt("#CEDFF3","very light blue"),Yt("#21c8ce","cyan")],[Yt("#3E027A","deep purple"),Yt("#6103BF","indigo"),Yt("#8136CC","violet"),Yt("#A068D9","lavender pink"),Yt("#C09AE6","light lilac"),Yt("#DFCDF2","transparent lilac"),Yt("#A91DFF","neon purple")]];Mt(),Cn();var Vz=["data-cols","data-rows","onKeydown","onClick"],Hz=["aria-valuetext"],mm=5,Uz={__name:"TableGrid",emits:["select","clickoutside"],setup(e,{emit:t}){const n=t,r=ne(0),o=ne(0),{isHighContrastMode:i}=Vi(),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,g)=>{o.value=h,r.value=g;for(let p=0;p<d.length;p++){let v=d[p],k=parseInt(v.dataset.cols,10),C=parseInt(v.dataset.rows,10);k<=h&&C<=g?v.classList.add("sd-selected"):v.classList.remove("sd-selected")}},u=({cols:d,rows:h})=>{n("select",{cols:d,rows:h})},c=(d,h,g)=>{let p=h-1,v=g-1;switch(d.key){case"ArrowRight":{if(p>=4)return;const k=v*mm;s.value[k+p+1].setAttribute("tabindex","0"),s.value[k+p+1].focus(),l(s.value,h+1,g);break}case"ArrowLeft":{if(p<=0)return;const k=v*mm;s.value[k+p-1].setAttribute("tabindex","0"),s.value[k+p-1].focus(),l(s.value,h-1,g);break}case"ArrowDown":{if(v>=4)return;const k=(v+1)*mm;s.value[k+p].setAttribute("tabindex","0"),s.value[k+p].focus(),l(s.value,h,g+1);break}case"ArrowUp":{if(v<=0)return;const k=(v-1)*mm;s.value[k+p].setAttribute("tabindex","0"),s.value[k+p].focus(),l(s.value,h,g-1);break}case"Enter":u({cols:h,rows:g});break;default:break}};return Un(()=>{s.value[0].setAttribute("tabindex","0"),s.value[0].focus(),l(s.value,1,1)}),(d,h)=>(ge(),Ie("div",{class:an(["toolbar-table-grid-wrapper",{"high-contrast":$e(i)}])},[Oe("div",{class:"toolbar-table-grid",onMouseover:a,"data-grid":"true"},[(ge(),Ie(Jt,null,lr(5,g=>(ge(),Ie(Jt,{key:g},[(ge(),Ie(Jt,null,lr(5,p=>Oe("div",{class:"toolbar-table-grid__item",key:`${g}_${p}`,"data-cols":p,"data-rows":g,"data-item":"true",ref_for:!0,ref_key:"tableGridItems",ref:s,onKeydown:sn(v=>c(v,p,g),["prevent"]),onClick:sn(v=>u({cols:p,rows:g}),["stop","prevent"])},null,40,Vz)),64))],64))),64))],32),Oe("div",{class:"toolbar-table-grid-value","aria-valuetext":`${r.value} x ${o.value}`},qt(r.value)+" x "+qt(o.value),9,Hz)],2))}},jz=yn(Uz,[["__scopeId","data-v-b87d6ca2"]]);Mt(),Cn();var Gz={class:"toolbar-table-actions"},Wz=["onClick","data-item","ariaLabel"],Kz={class:"toolbar-table-actions__icon"},qz=["innerHTML"],Yz={class:"toolbar-table-actions__label"},Xz={__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)=>(ge(),Ie("div",Gz,[(ge(!0),Ie(Jt,null,lr(e.options,s=>(ge(),Ie("div",{class:an(["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"},[Oe("div",Kz,[Oe("div",{class:"toolbar-table-actions__icon-wrapper",innerHTML:s.icon},null,8,qz)]),Oe("div",Yz,qt(s.label),1)],10,Wz))),256))]))}},Zz=yn(Xz,[["__scopeId","data-v-0cdad084"]]),Qz=`<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
|
-
`;Mt();var ws=e=>{e.expand.value=!1};function lb(e,t){const n={...e??{}};return t?n.href=t:delete n.href,n}function uA(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 Jz(e){return typeof e?.quotedText=="string"?e.quotedText:typeof e?.text=="string"?e.text:""}function dA(e){return e.ui?.selection?.get?.()??e.ui?.selection?.current?.()??null}function $z(e){return!!(e.config?.superdoc?.config?.modules?.ai||e.superdoc?.config?.modules?.ai)}function eV(e){return e.config?.superdoc?.config?.modules?.ai??e.superdoc?.config?.modules?.ai??{}}const tV=({superToolbar:e,toolbarIcons:t,toolbarTexts:n,toolbarFonts:r,hideButtons:o,availableWidth:i,role:s,isDev:a=!1}={})=>{const l=An({type:"button",name:"bold",command:"toggleBold",icon:t.bold,tooltip:n.bold,attributes:{ariaLabel:"Bold"}}),u=(r??qB).map(ez),c=An({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:et}={},Pt=!1)=>{if(Pt){c.label.value="",c.selectedValue.value="";return}if(!et)return;et=et.split(",")[0],c.label.value=et;const Kt=u.find(Nt=>Nt.label===c.defaultLabel.value),Rn=u.find(Nt=>Nt.label===et);Rn?c.selectedValue.value=Rn.key:Kt?c.selectedValue.value=Kt.key:c.selectedValue.value=""},onDeactivate:()=>{c.label.value=c.defaultLabel.value;const et=u.find(Pt=>Pt.label===c.defaultLabel.value);et?c.selectedValue.value=et.key:c.selectedValue.value=""}}),d=An({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(et){const Pt=dA(e),Kt=Pt?.selectionTarget??uA(Pt?.target),Rn=Pt?.empty?"":Jz(Pt),Nt=eV(e),un=()=>ws(et),Mn=()=>{const Pe=e.pendingSelectionCapture;Pe&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Pe)};return Gr("div",{},[Gr(Ez,{handleClose:un,selectedText:Rn,target:Kt,doc:e.superdoc?.activeEditor?.doc??null,apiKey:Nt?.apiKey||e.config?.aiApiKey||"",endpoint:Nt?.endpoint||e.config?.aiEndpoint||"",restoreSelection:Mn})])}const g=XB,p=An({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:g,onActivate:({fontSize:et},Pt=!1)=>{if(Pt){p.label.value="",p.selectedValue.value="";return}const Kt=g.find(Mn=>Mn.label===String(p.defaultLabel.value));if(!et){p.label.value=p.defaultLabel.value,Kt?p.selectedValue.value=Kt.key:p.selectedValue.value="";return}let Rn=NN(et,12);Rn<8&&(Rn=8),Rn>96&&(Rn=96);let Nt=String(Rn);const un=g.find(Mn=>Mn.label===Nt||Mn.key===Nt);un?p.selectedValue.value=un.key:p.selectedValue.value="",p.label.value=Nt},onDeactivate:()=>{p.label.value=p.defaultLabel.value;const et=g.find(Pt=>Pt.label===String(p.defaultLabel.value));et?p.selectedValue.value=et.key:p.selectedValue.value=""}}),v=An({type:"separator",name:"separator",isNarrow:!0}),k=An({type:"button",name:"italic",command:"toggleItalic",icon:t.italic,active:!1,tooltip:n.italic,attributes:{ariaLabel:"Italic"}}),C=An({type:"button",name:"underline",command:"toggleUnderline",icon:t.underline,active:!1,tooltip:n.underline,attributes:{ariaLabel:"Underline"}}),_=An({type:"button",name:"strike",command:"toggleStrike",icon:t.strikethrough,active:!1,tooltip:n.strikethrough,attributes:{ariaLabel:"Strikethrough"}}),y=An({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:()=>ab(e,y,[],!0)}],onActivate:({color:et})=>{y.iconColor.value=et||""},onDeactivate:()=>y.iconColor.value=""}),w=An({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:()=>ab(e,w)}],onActivate:({color:et})=>{w.iconColor.value=et},onDeactivate:()=>w.iconColor.value="#000"}),x=An({type:"button",name:"search",allowWithoutEditor:!0,active:!1,icon:t.search,tooltip:n.search,group:"right",attributes:{ariaLabel:"Search"}}),P=An({type:"dropdown",name:"link",markName:"link",icon:t.link,active:!1,tooltip:n.link,attributes:{ariaLabel:"Link dropdown"},options:[{type:"render",key:"linkDropdown",render:()=>N(P)}],onActivate:({href:et})=>{P.attributes.value=lb(P.attributes.value,et)},onDeactivate:()=>{P.attributes.value=lb(P.attributes.value,null),P.expand.value=!1}});function N(et){const Pt=dA(e),Kt=Pt?.selectionTarget??uA(Pt?.target),Rn=()=>{const Nt=e.pendingSelectionCapture;Nt&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Nt)};return Gr("div",{},[Gr(OS,{ui:e.ui,linkItem:et,textTarget:Kt,restoreSelection:Rn,closePopover:()=>ws(et),goToAnchor:()=>{ws(et);const Nt=et.attributes.value?.href;if(!Nt)return;const un=Nt.slice(1),Mn=(e.ui?.viewport?.getHost?.()??null)?.querySelector?.(`a[name='${un}']`);Mn&&bf(Mn)}})])}const G=An({type:"options",name:"linkInput",command:"toggleLink",active:!1});P.childItem=G,G.parentItem=P;const R=An({type:"button",name:"image",command:"startImageUpload",icon:t.image,active:!1,tooltip:n.image,disabled:!1,attributes:{ariaLabel:"Image"}}),F=An({type:"button",name:"tableOfContents",command:"insertTableOfContents",icon:t.tableOfContents,active:!1,tooltip:n.tableOfContents,disabled:!1,attributes:{ariaLabel:"Table of contents"}}),Z=An({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:()=>D(Z)}]});function D(et){return Gr("div",{},[Gr(jz,{onSelect:Kt=>{e.emitCommand({item:et,argument:Kt}),ws(et),sb(e)}})])}const B=An({type:"dropdown",name:"tableActions",command:"executeTableCommand",tooltip:n.tableActions,icon:t.tableActions,hideLabel:!0,disabled:!0,attributes:{ariaLabel:"Table actions"},options:[{type:"render",render:()=>V(B)}]}),T=[{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 V(et){return Gr(Zz,{options:T,onSelect:Pt=>{ws(et);const{command:Kt}=Pt;e.emitCommand({item:et,argument:{command:Kt}})}})}const J=An({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:()=>Gr("div",{},[Gr(rz,{onSelect:Pt=>{ws(J);const Kt={...J,command:"setTextAlign"};Kt.command="setTextAlign",e.emitCommand({item:Kt,argument:Pt}),q(J,Pt)}})]),key:"alignment"}],onActivate:({textAlign:et})=>{q(J,et)},onDeactivate:()=>{q(J,"left")}}),q=(et,Pt)=>{let Kt=Pt==="both"?"justify":Pt,Rn={left:t.alignLeft,right:t.alignRight,center:t.alignCenter,justify:t.alignJustify},Nt=Rn[Kt]??Rn.left;et.icon.value=Nt},se=An({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 et=Pt=>{ws(se);const Kt={...se,command:"toggleBulletListStyle"};e.emitCommand({item:Kt,argument:Pt})};return Gr(lA,{buttons:sz,iconSize:25,selectedStyle:se.selectedValue.value,onSelect:et})}}]}),pe=An({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 et=Pt=>{ws(pe);const Kt={...pe,command:"toggleOrderedListStyle"};e.emitCommand({item:Kt,argument:Pt})};return Gr(lA,{buttons:az,iconSize:30,selectedStyle:pe.selectedValue.value,onSelect:et})}}]}),Ne=An({type:"button",name:"indentleft",command:"decreaseTextIndent",icon:t.indentLeft,active:!1,tooltip:n.indentLeft,disabled:!1,attributes:{ariaLabel:"Left indent"}}),he=An({type:"button",name:"indentright",command:"increaseTextIndent",icon:t.indentRight,active:!1,tooltip:n.indentRight,disabled:!1,attributes:{ariaLabel:"Right indent"}}),ye=An({type:"overflow",name:"overflow",command:null,icon:t.overflow,active:!1,disabled:!1,attributes:{ariaLabel:"Overflow items"}}),ce=An({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:et})=>{et&&(ce.label.value=et)}}),ke=An({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:et})=>{et&&(ke.label.value=et)}}),ie=An({type:"button",name:"undo",disabled:!0,tooltip:n.undo,command:"undo",icon:t.undo,group:"left",attributes:{ariaLabel:"Undo"}}),xe=An({type:"button",disabled:!0,name:"redo",tooltip:n.redo,command:"redo",icon:t.redo,group:"left",attributes:{ariaLabel:"Redo"}}),Je=An({type:"button",disabled:!1,name:"acceptTrackedChangeBySelection",tooltip:n.trackChangesAccept,command:"acceptTrackedChangeFromToolbar",icon:t.trackChangesAccept,group:"left",attributes:{ariaLabel:"Accept tracked changes"}}),st=An({type:"button",disabled:!1,name:"rejectTrackedChangeOnSelection",tooltip:n.trackChangesReject,command:"rejectTrackedChangeFromToolbar",icon:t.trackChangesReject,group:"left",attributes:{ariaLabel:"Reject tracked changes"}}),Tt=An({type:"button",name:"clearFormatting",command:"clearFormat",tooltip:n.clearFormatting,icon:t.clearFormatting,attributes:{ariaLabel:"Clear formatting"}}),Te=An({type:"button",name:"copyFormat",tooltip:n.copyFormat,icon:t.copyFormat,command:"copyFormat",active:!1,attributes:{ariaLabel:"Copy formatting"}}),je=(et,Pt)=>et==="editor"?Pt:et==="suggester"?Pt.filter(Kt=>Kt.value==="suggesting"):Pt.filter(Kt=>Kt.value==="viewing"),Ye=et=>et==="editor"?"Editing":et==="suggester"?"Suggesting":"Viewing",$=An({type:"dropdown",name:"documentMode",command:"setDocumentMode",allowWithoutEditor:!0,icon:t.documentMode,defaultLabel:Ye(s),label:Ye(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:()=>ee($)}]}),S=[{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 ee(et){return Gr(mz,{options:je(s,S),onSelect:Pt=>{const Kt=e.superdoc?.activeEditor??e.activeEditor;ws(et);const{label:Rn,icon:Nt,value:un}=Pt;$.label.value=Rn,$.icon.value=Nt,e.emitCommand({item:$,argument:un}),sb(e,Kt)}})}const O=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"],U=An({type:"button",name:"ruler",command:"toggleRuler",allowWithoutEditor:!0,icon:t.ruler,active:!1,tooltip:n.ruler,attributes:{ariaLabel:"Ruler"}}),W=An({type:"button",name:"formattingMarks",command:"toggleFormattingMarks",allowWithoutEditor:!0,icon:t.formattingMarks,active:!1,tooltip:n.formattingMarks,attributes:{ariaLabel:"Formatting marks"}}),te=An({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 et=Kt=>{ws(te);const Rn=typeof Kt=="string"?Kt:Kt?.id??null;if(!Rn)return;const Nt={...te,command:"setLinkedStyle"};e.emitCommand({item:Nt,argument:Rn})},Pt=e.getActiveLinkedStyleId?.()??null;return Gr("div",{},[Gr(bz,{styles:e.getLinkedStyleOptions?.()??[],onSelect:et,selectedOption:Pt})])}}],onActivate:({styleId:et,styleName:Pt})=>{const Kt=Pt||et;te.label.value=et&&et!=="Normal"?String(Kt):n.formatText,te.disabled.value=!1},onDeactivate:()=>{te.disabled.value=!0,te.label.value=n.formatText}}),Y=(et,Pt)=>{if(Pt.value==et)return Gr("div",{innerHTML:Qz,class:"dropdown-select-icon"})},X=An({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(et=>({label:et.toFixed(2),key:et,icon:()=>Y(et,X.selectedValue),props:{"data-item":"btn-lineHeight-option"}}))}),be=20,ve=32,we=j.reduce((et,Pt)=>et+(O.get(Pt)||O.get("default")),0),Be=["linkedStyles","clearFormatting","copyFormat","formattingMarks"],rt=["zoom","fontFamily","fontSize","redo"],at=i<=Vf.lg,Ct=e.config?.showFormattingMarksButton===!0,en=e.config?.showTableOfContentsButton===!0;at&&($.attributes.value={...$.attributes.value,className:`${$.attributes.value.className} sd-toolbar-item--doc-mode-compact`}),at&&(te.attributes.value={...te.attributes.value,className:`${te.attributes.value.className} sd-toolbar-item--linked-styles-compact`});let Et=[ie,xe,Je,st,x,ce,c,v,p,v,l,k,C,_,w,y,v,P,R,...en?[F]:[],Z,B,v,J,se,pe,Ne,he,X,v,te,v,U,ke,...Ct?[W]:[],Te,Tt,...$z(e)?[d]:[],ye,$];if(i<=Vf.md&&o&&(Et=Et.filter(et=>et.type!=="separator")),e.config.mode!=="docx"){const et=Et.findIndex(Kt=>Kt.name.value==="linkedStyles");Et.splice(et-1,2);const Pt=["ruler","zoom","undo","redo"];Et=Et.filter(Kt=>!Pt.includes(Kt.name.value))}const Ut=[];a||(s==="viewer"&&Ut.push(Je,st),Et=Et.filter(et=>!Ut.includes(et)));const Wt=et=>j.includes(et.name.value),In=[],bt=[];let nn=ve+we;return Et.forEach(et=>{const Pt=O.get(et.name.value)||O.get("default");if(i<Vf.xl+be&&Be.includes(et.name.value)&&o){if(In.push(et),et.name.value==="linkedStyles"){const Kt=Et.findIndex(Rn=>Rn.name.value==="linkedStyles");Et.splice(Kt+1,1)}return}if(i<Vf.sm&&rt.includes(et.name.value)&&o){In.push(et);return}if(Wt(et)){bt.push(et),nn+=Pt;return}nn<i||!o?(bt.push(et),nn+=Pt):In.push(et)}),{defaultItems:bt,overflowItems:In.filter(et=>et.type!=="separator")}},fA={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"},nV=e=>e?typeof e!="string"?e instanceof HTMLElement?e:null:e.startsWith("#")||e.startsWith(".")?document.querySelector(e):document.getElementById(e):null;Mt();function hA(e){return xN(e)??ib[e]??null}function gm(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 rV=new Set(["bold","italic","underline","strike","color","highlight","link","clearFormatting","textAlign","list","numberedlist","indentleft","indentright","lineHeight","linkedStyles"]),oV=new Set(["list","numberedlist"]);function iV(e,t){if(e==="fontFamily"||e==="fontSize"||oV.has(e)&&t?.disabled&&t?.supported!==!1&&t?.reason==null)return!0;if(!rV.has(e))return!1;const n=t?.reason;return n==="range-selection-required"||n==="selection-required"}function pA(e){return!!e?.closest?.("[data-editor-ui-surface], .toolbar-dropdown-menu, .sd-toolbar-dropdown-menu, .sd-tooltip-content")}function sV(e){return["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)}var aV=class extends Qm.default{config={selector:null,toolbarGroups:["left","center","right"],role:"editor",icons:{...or},texts:{...fA},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={...or,...e.icons},this.config.texts={...fA,...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=nV(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.#d(),this.#f(),this.#i(),this._lastFontOptionsSignature=this.#o(),!this.toolbarContainer){this.updateToolbarState();return}this.app=Kl($B),this.app.directive("click-outside",ey),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.#a():this.#S()}))}#r(){this._unsubscribeController?.(),this._unsubscribeController=null,this._detachFormatPainterModeChange?.(),this._detachFormatPainterModeChange=null,this.#S();for(const e of this._customCommandRegs.values())try{e.unregister?.()}catch{}this._customCommandRegs.clear(),this.ui=null,this.snapshot=null}#i(){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.#p()),this.updateToolbarState()};this.superdoc.on("fonts-changed",e),this._detachFontsChanged=()=>{this.superdoc?.off?.("fonts-changed",e)}}#s(){this._detachFontsChanged?.(),this._detachFontsChanged=null}#d(){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}#h(e){return e||YB(this.superdoc?.fonts?.getFontFamilyOptions?.()??[])}#f(){const e=this.getAvailableWidth(),t=this.config.groups&&!Array.isArray(this.config.groups)&&Object.keys(this.config.groups).length>0,{defaultItems:n,overflowItems:r}=tV({superToolbar:this,toolbarIcons:this.config.icons,toolbarTexts:this.config.texts,toolbarFonts:this.#h(this.config.fonts),hideButtons:this.config.hideButtons,availableWidth:e,role:this.role,isDev:this.isDev}),o=this.config.customButtons||[],i=o.map(l=>this.#c(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))}#c(e){const t=An({...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}#p(){this.#f(),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.#l().find(t=>t.name.value===e)}#l(){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.#p()),this.ui&&(this.snapshot=this.ui.toolbar.getSnapshot()),this.updateToolbarState()}onToolbarResize=()=>{this.#f(),this.updateToolbarState()};#g(e){return e==="ruler"?!!this.superdoc?.config?.rulers:e==="formattingMarks"?!!this.superdoc?.config?.layoutEngineOptions?.showFormattingMarks:!1}#u(e){return e==="ruler"?typeof this.superdoc?.toggleRuler=="function":e==="formattingMarks"?typeof this.superdoc?.toggleFormattingMarks=="function"||typeof this.superdoc?.setShowFormattingMarks=="function":!1}#y(){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)}#w(){const e=this.toolbarItems.find(n=>n.name.value==="highlight");if(!e)return;const t={key:"color",type:"render",render:()=>ab(this,e,[],!0)};e.nestedOptions.value=[t]}#k(e){return!!e?.active&&e?.value==null}#I(e){return!!e&&e.disabled===!1&&e.value==null}#E(e){const t=e.name.value;if(t==="tableActions"){const i=aA.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(rb(t)?.disposition==="host-routed")return e.setDisabled(!this.#u(t)),this.#g(t)?e.activate():e.deactivate(),!0;const n=hA(t);if(!n)return!1;const r=this.snapshot?.commands?.[n];iV(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.#y()},link:()=>{e.active.value=!!r?.active,e.attributes.value=lb(e.attributes.value,r?.value??null)},fontFamily:()=>{if(r?.value!=null){e.activate({fontFamily:r.value});return}if(this.#I(r)){e.activate({},!0);return}e.deactivate()},fontSize:()=>{if(r?.value!=null){e.activate({fontSize:r.value});return}if(this.#k(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.#y(),this.#w();const e=this.snapshot?.commands?.["document-mode"]?.value||"editing";!(this.snapshot&&(this.superdoc?.activeEditor??this.activeEditor))||e==="viewing"?(this.#M(),this.#l().forEach(n=>{n.allowWithoutEditor?.value&&this.#E(n)})):this.#l().forEach(n=>{n.resetDisabled(),this.#E(n)});const t=this.getToolbarItemByName("copyFormat");t&&(this.snapshot?.copyFormatActive?t.activate():t.deactivate()),this.emit("toolbar-state-change")}#M(){this.#l().forEach(e=>{const{allowWithoutEditor:t}=e;t?.value||e.setDisabled(!0)})}#L(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}#P(e,t){const n=e?.name?.value;if(!n)return!1;const r={onSettled:()=>this.updateToolbarState(),onError:i=>this.#b(i,n)};if(n==="image"&&t==null)return this.#T();if(n==="tableActions"){const i=sA[t?.command];return i?gm(this.ui,i,void 0,r):!1}if(rb(n)?.disposition==="unsupported")return!0;const o=hA(n);return o?gm(this.ui,o,t,r):!1}#T(){return this.snapshot?.commands?.image?.disabled||(this.#t||(this.#t=FN({ownerDocument:this.toolbarContainer?.ownerDocument??document,onPick:async e=>{const t=await DN(e,this.superdoc?.config?.handleImageUpload);gm(this.ui,"image",{src:t},{onSettled:()=>this.updateToolbarState(),onError:n=>this.#b(n,"image")})},onError:e=>this.#b(e,"image")})),this.#t.open()),!0}#a(){if(this.#n)return;const e=this.superdoc?.activeEditor?.container??document,t=i=>{pA(i.target)||this.ui.formatPainter.setPointerSelecting(!0)},n=i=>{this.ui.formatPainter.setPointerSelecting(!1),!pA(i.target)&&this.ui.formatPainter.notifyPointerUp()},r=i=>{if(i.key==="Escape"){this.ui.formatPainter.cancel();return}sV(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)}}#S(){this.#n&&(this.#n(),this.#n=null)}#b(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(rb(r)?.disposition==="host-routed"){this.#L(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(!gm(this.ui,o,t,{onSettled:()=>this.updateToolbarState(),onError:s=>this.#b(s,r)}))throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState();return}if(!this.#P(e,t)&&o)throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState()}catch(s){this.#b(s,r)}}}destroy(){this.#S(),this.#t?.destroy(),this.#t=null,this.#s(),this.#r(),this.app?.unmount(),this.app=null,this.toolbar=null}};function lV(e){return new aV(e)}function cV(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 uV(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=vm(e.color);n!=null&&(t.color=n),e.highlight!=null&&(t.highlight=e.highlight);const r=fV(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=dV(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=hV(e.border);return i&&(t.border=i),t}function vm(e){if(e){if(typeof e=="string")return e;if(e.model==="rgb")return e.value;if(e.model==="auto")return"auto"}}function dV(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 fV(e){if(!e)return;const t={},n=vm(e.fill);n!=null&&(t.fill=n);const r=vm(e.color);return r!=null&&(t.color=r),e.pattern!=null&&(t.val=e.pattern),Object.keys(t).length>0?t:void 0}function hV(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=vm(e.color);return n!=null&&(t.color=n),Object.keys(t).length>0?t:void 0}function ic(e){const t=e?.selectionTarget??e?.target;if(!e||!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function mA(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function pV(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 mA(r))n(o);return n(e.getAttribute("data-track-change-id")),t}function gA(e,t){if(!e||typeof e.getAttribute!="function")return[];const n=[],r=new Set;let o=[],i=e;for(;i;){const s=i,a=pV(s),l=a.length>0?s.getAttribute("data-story-key"):null;for(const g of a){const p=`trackedChange:${g}`;if(!r.has(p)){r.add(p);const v={type:"trackedChange",id:g};l&&(v.storyKey=l),n.push(v),o.push(v)}}const u=s.getAttribute("data-layout-story");if(u&&o.length>0){for(const g of o)g.story=u;o=[]}const c=s.getAttribute("data-comment-ids");if(c)for(const g of mA(c)){const p=`comment:${g}`;r.has(p)||(r.add(p),n.push({type:"comment",id:g}))}const d=s.getAttribute("data-sdt-type"),h=s.getAttribute("data-sdt-id");if(h&&d==="structuredContent"){const g=`contentControl:${h}`;if(!r.has(g)){r.add(g);const p=s.getAttribute("data-sdt-scope"),v=s.getAttribute("data-sdt-tag"),k={type:"contentControl",id:h};(p==="block"||p==="inline")&&(k.scope=p),v&&(k.tag=v),n.push(k)}}if(t&&i===t)break;i=i.parentElement}return n}var lo=()=>({oneOf:[{type:"boolean"},{type:"null"}]}),cl=()=>({oneOf:[{type:"string",minLength:1},{type:"null"}]}),xu=()=>({oneOf:[{type:"number"},{type:"null"}]}),Ru=e=>({oneOf:[{type:"object",properties:e,additionalProperties:!1,minProperties:1},{type:"null"}]}),mV={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},gV={type:"object",properties:{id:{type:"number"},val:{type:"boolean"}},required:["id"],additionalProperties:!1},vV=()=>({oneOf:[{type:"boolean"},{type:"null"},mV]}),yV=()=>({oneOf:[{type:"array",items:gV,minItems:1},{type:"null"}]});function ym(e,t){return{storage:"mark",markName:e,textStyleAttr:t}}function bV(e){return{storage:"runAttribute",nodeName:"run",runPropertyKey:e}}var cb=(e,t,n)=>({key:e,type:"boolean",ooxmlElement:t,storage:"mark",tracked:!0,carrier:ym(n),schema:lo()}),sc=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"mark",tracked:!0,carrier:ym("textStyle",o??e),schema:r}),jn=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"runAttribute",tracked:!1,carrier:bV(o??e),schema:r});const bm=[cb("bold","w:b","bold"),cb("italic","w:i","italic"),cb("strike","w:strike","strike"),{key:"underline",type:"object",ooxmlElement:"w:u",storage:"mark",tracked:!0,carrier:ym("underline"),schema:vV()},{key:"highlight",type:"string",ooxmlElement:"w:highlight",storage:"mark",tracked:!0,carrier:ym("highlight"),schema:cl()},sc("color","string","w:color",cl()),sc("fontSize","number","w:sz",xu()),sc("fontFamily","string","w:rFonts",cl()),sc("letterSpacing","number","w:spacing",xu()),sc("vertAlign","string","w:vertAlign",{oneOf:[{enum:["superscript","subscript","baseline"]},{type:"null"}]}),sc("position","number","w:position",xu()),jn("dstrike","boolean","w:dstrike",lo()),jn("smallCaps","boolean","w:smallCaps",lo()),sc("caps","boolean","w:caps",lo(),"textTransform"),jn("shading","object","w:shd",Ru({fill:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},val:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),jn("border","object","w:bdr",Ru({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"),jn("outline","boolean","w:outline",lo()),jn("shadow","boolean","w:shadow",lo()),jn("emboss","boolean","w:emboss",lo()),jn("imprint","boolean","w:imprint",lo()),jn("charScale","number","w:w",xu(),"w"),jn("kerning","number","w:kern",xu(),"kern"),jn("vanish","boolean","w:vanish",lo()),jn("webHidden","boolean","w:webHidden",lo()),jn("specVanish","boolean","w:specVanish",lo()),jn("rtl","boolean","w:rtl",lo()),jn("cs","boolean","w:cs",lo()),jn("bCs","boolean","w:bCs",lo(),"boldCs"),jn("iCs","boolean","w:iCs",lo(),"italicCs"),jn("eastAsianLayout","object","w:eastAsianLayout",Ru({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"}]}})),jn("em","string","w:em",cl()),jn("fitText","object","w:fitText",Ru({val:{oneOf:[{type:"number"},{type:"null"}]},id:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),jn("snapToGrid","boolean","w:snapToGrid",lo()),jn("lang","object","w:lang",Ru({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},bidi:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),jn("oMath","boolean","w:oMath",lo()),jn("rStyle","string","w:rStyle",cl(),"styleId"),jn("rFonts","object","w:rFonts",Ru({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"),jn("fontSizeCs","number","w:szCs",xu()),jn("ligatures","string","w14:ligatures",cl()),jn("numForm","string","w14:numForm",cl()),jn("numSpacing","string","w14:numSpacing",cl()),jn("stylisticSets","array","w14:stylisticSets",yV()),jn("contextualAlternates","boolean","w14:cntxtAlts",lo())],dG=new Set(bm.map(e=>e.key)),wV=Object.fromEntries(bm.map(e=>[e.key,e])),fG={mark:bm.filter(e=>e.storage==="mark").map(e=>e.key),runAttribute:bm.filter(e=>e.storage==="runAttribute").map(e=>e.key)};var ub=new WeakMap;function CV(e){let t=ub.get(e);return t||(t={refCount:0,generation:0,abortController:new AbortController,inFlight:null,activeMutationTokens:new Set},ub.set(e,t)),t.refCount+=1,t}function kV(e,t){t.refCount=Math.max(0,t.refCount-1),!(t.refCount>0)&&(t.abortController.abort("ui-controller-destroyed"),t.inFlight=null,t.activeMutationTokens.clear(),ub.delete(e))}var SV=new Set(Object.values(ut));function db(e,t){return typeof e=="string"&&SV.has(e)?e:t}function vA(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:ut.notReady}:{ok:!1,reason:db(t,ut.targetUnresolved)}}return{ok:!0}}var _V=["document-replaced","editorCreate","active-editor-change","document-mode-change","zoomChange","measurement-unit-change","viewport-change","fonts-changed"],AV={[X4.bulletList]:"bullet",[X4.numberedList]:"ordered"};function yA(e){return AV[e]??null}var IV={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 EV(e){const t=IV[e];return t?{preset:t,behavior:"toggleStyle"}:{}}var TV={status:"ready",empty:!0,target:null,selectionTarget:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[],quotedText:""};const xV=[{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: shared all-story tracked-changes catalog; stale-served during load"},{key:"trackChanges:all",match:"exact",note:"audited: current-token validation over the shared all-story catalog; consumers fail closed on non-ready"},{key:"tables",match:"exact",note:"reserved: full tables catalog"},{key:"sections",match:"exact",note:"reserved: full sections list"}];var RV=new Set(["/word/comments.xml","/word/commentsExtended.xml","/word/commentsIds.xml"]);function MV(e){return xV.some(t=>t.match==="exact"?t.key===e:e.startsWith(t.key))}var bA={ready:0,stale:1,pending:2};function Mu(...e){let t="ready";for(const n of e)bA[n]>bA[t]&&(t=n);return t}function Lt(e,t){if(typeof e!="function")return t;try{const n=e();return n===void 0?t:n}catch{return t}}function Cr(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function yr(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 hr(e,t="CAPABILITY_UNAVAILABLE"){return{success:!1,failure:{code:t,message:e}}}function Hf(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 Uf(e){if(!e||typeof e!="object")return null;const t=e.target;return t&&typeof t=="object"?t:null}function fb(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 LV(e){if(!e||typeof e!="object")return null;const t=Uf(e);if(fb(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 kr(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 Lu(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=Uf(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 Wi(e,t,n){return Kn(e)!==t?!1:n?kr(Lu(e))===kr(n):!0}function wm(e){const t=Lu(e);if(!(!t||kr(t)===kr(null)))return t}function PV(e){if(typeof e!="string"||e.length===0)return;const t=x6(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 DV(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 hb(e){if(!e||typeof e!="object")return null;const t=e.selectionTarget;return t&&typeof t=="object"?t:null}function Cm(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function OV(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 Kn(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 FV(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 wA=new WeakMap;function CA(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 ga(e){const t=wA.get(e);if(t)return t;const n=new Set,r=new Map;for(const i of e){const s=Kn(i);if(s){n.add(s);for(const a of CA(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 wA.set(e,o),o}var kA=new WeakMap,SA=new WeakMap;function Pu(e,t){const n=kr(t);let r=kA.get(e);r||(r=new Map,kA.set(e,r));const o=r.get(n);if(o)return o;const i=ga(e.filter(s=>kr(Lu(s))===n));return r.set(n,i),i}function NV(e){return!!e&&typeof e=="object"&&e.storyType==="textbox"}function BV(e,t){const n=t.filter(o=>e.some(i=>Kn(i)===o&&Lu(i)==null));if(n.length===0)return null;if(n.length===1)return n[0];const r=new Set;for(const o of n){const i=e.find(s=>Kn(s)===o);if(i)for(const s of CA(i)){if(r.has(s))return null;r.add(s)}}return n[0]}function zV(e){const t=SA.get(e);if(t)return t;const n=e.filter(o=>Lu(o)!=null),r=n.length===e.length?e:n;return SA.set(e,r),r}function VV(e){const{selectionIds:t,publicIds:n,selection:r,bodyItems:o,allStoryItems:i}=e;if(t.length===0)return null;const s=u=>{for(const c of t){const d=u.toPublicId(c);if(d)return d}return null},a=Ki(r),l=kr(a)===kr(null);if(i){const u=l?zV(i):i,c=s(Pu(u,a));if(c)return c;const d=n?.find(h=>u.some(g=>Wi(g,h,a)));return d||(l?s(ga(o)):NV(a)?BV(i,t):null)}return l?s(ga(o))??t[0]??null:null}function HV(e,t){const n=e.find(r=>Kn(r)===t||r.importedId===t);return n?n.rootCommentId??n.parentCommentId??Kn(n)??t:null}function UV(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 Nr(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 jV=64;function ac(e){return e.length<=jV}function Ki(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 vo(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 _A(e,t){return{kind:"block",nodeType:"listItem",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}var AA=720;function Cs(e){return Math.round(e*20)}function Du(e){return typeof e=="number"&&Number.isFinite(e)}function GV(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=Du(i.left)?Cs(i.left):Du(i.start)?Cs(i.start):void 0,a=Du(i.right)?Cs(i.right):Du(i.end)?Cs(i.end):void 0,l=Du(i.firstLine)?Cs(i.firstLine):void 0,u=Du(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 pb(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 WV(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 jf(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 ul(e){return jf(e.target)??jf(e.selectionTarget)}var IA=["fontFamily","fontSize","color","highlight"],KV={undo:"history.undo",redo:"history.redo"},Gf=["bold","italic","underline","strikethrough"];function mb(e){return IA.includes(e)}function Ou(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 qi(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 qV(e){const t=qi(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=Ou(e);return t.length===0?null:[qV(e),...t.map(n=>`${n.blockId}:${n.start}-${n.end}`)].join("|")}function EA(e){const t=e.selectionTarget;return!t||typeof t!="object"?null:ic({selectionTarget:t})}function YV(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 XV(e,t){return Math.max(e.start,t.start)<Math.min(e.end,t.end)}function ZV(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 QV(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 TA(e,t){const n=Ou(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=>QV(n,ZV(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 JV(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 gb(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 $V(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 eH(e,t){return e==="fontFamily"?t.toLowerCase():e==="color"||e==="highlight"?t.toUpperCase():t}function xA(e,t){if(!e)return{};const n=new Map;for(const i of Ou(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 IA){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 g of h){const p=g?.range,v=typeof p?.start=="number"?p.start:null,k=typeof p?.end=="number"?p.end:null;if(v==null||k==null||!d.some(y=>XV(y,{start:v,end:k})))continue;a=!0;const C=JV(g?.styles,i);if(C===void 0){l=!0;continue}const _=eH(i,C);if(s.has(_)||s.set(_,C),s.size>1)break}if(s.size>1)break}a&&!l&&s.size===1&&(o[i]=[...s.values()][0])}return o}function vb(e,t){const n=Nr(e)[0];return n?t==="nodeId"?{kind:"after",nodeId:n}:{kind:"after",target:vo(n)}:{kind:"documentEnd"}}function ln(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 dl(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 km(e){const t=e,n=t.change;return n&&typeof n=="object"?n:t}function ks(e){if(Cr(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 Sm(e){return!!e&&typeof e=="object"&&e.success===!0}function yo(e){return!(e===!1||e&&typeof e=="object"&&e.success===!1)}function lc(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function yb(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 cc(e,t){return e.sourceAnchor?.sourceNodeId===t?!0:e.id===t}function pi(e){let t=!1,n=null,r=null,o=null;for(const i of e)t=i,!yo(i)&&n===null&&(n=i),Sm(i)&&(o=i),i!==!1&&(r=i);return n??o??r??t}function tH(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 nH(e){return e.startsWith("#")?{kind:"anchor",anchor:e.slice(1)}:{kind:"external",url:e}}function _m(e){return Tu(e)?.trackDecision??null}function rH(e){return{found:e.length>0,success:e.length>0,rects:e,rect:e[0]}}function fl(e){return{found:!1,success:!1,rects:[],reason:e}}function oH(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 iH(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 RA(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(iH))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 sH(e){return e.selectionTarget?e.selectionTarget:RA(e.target)}function Fu(e){if(e.empty)return null;if(e.selectionTarget)return e.selectionTarget;const t=RA(e.target);return t&&t.start.kind==="text"&&t.end.kind==="text"&&t.start.blockId!==t.end.blockId?null:t}function bb(e){return!e.inline||typeof e.docRoute!="string"?null:e.docRoute.startsWith("format.")?e.docRoute.slice(7):null}var wb={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},aH=Object.fromEntries(Object.entries(wb).filter(([e])=>wV[e]?.tracked===!0));function lH(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:{...wb}};default:return null}}function cH(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 uH(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 dH(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},g=0;const p=new Set;let v={},k="",C=null;const _=()=>{const f=t?.activeEditor;return f&&typeof f=="object"?f:null},y=()=>{const f=_()?.doc;return f&&typeof f=="object"?f:null},w=()=>{const f=_()?.v2TrackedChanges;return f&&typeof f=="object"?f:null},x=()=>{const f=_()?.host;return f&&typeof f=="object"?f:null},P=f=>{if(f.storyType!=="headerFooterPart"||typeof f.refId!="string")return null;const m=_(),b=x(),I=m?.pageLayout??b?.pageLayout;if(!I||typeof I!="object")return null;const E=I.getActiveRulerContext,z=b?.resolveHeaderFooterEditTarget;if(typeof E!="function"||typeof z!="function")return null;const K=Lt(()=>E.call(I),null);if(!K||typeof K.pageIndex!="number")return null;for(const oe of["header","footer"]){const me=Lt(()=>z.call(b,{pageIndex:K.pageIndex,kind:oe}),null);if(!(me?.status!=="ready"||me.refId!==f.refId||typeof me.sectionId!="string"||!["default","first","even"].includes(String(me.slotVariant))))return{kind:"story",storyType:"headerFooterSlot",section:{kind:"section",sectionId:me.sectionId},headerFooterKind:oe,variant:me.slotVariant}}return null},N=()=>{const f=x(),m=f?.getPendingInlineFormat;if(typeof m!="function")return null;const b=Lt(()=>m.call(f),null);return b&&typeof b=="object"?b:null},G=f=>{const m=bb(f);if(!m)return null;const b=N();if(!b||!(m in b))return null;const I=b[m];return f.inline?.kind==="toggle"?I===!0:I!=null&&I!==""},R=f=>{const m=bb(f);if(!m)return;const b=N();if(!b||!(m in b))return;const I=b[m];if(typeof I=="string"&&I!=="")return I;if(typeof I=="number"&&Number.isFinite(I))return String(I)},F=(f,m)=>{const b=x(),I=b?.setPendingInlineFormat;typeof I=="function"&&Lt(()=>I.call(b,f,m),void 0)},Z=f=>{const m=x(),b=m?.clearPendingInlineFormat;typeof b=="function"&&Lt(()=>b.call(m,f),void 0)},D=new Set(["bold","italic","underline","strikethrough"]),B=f=>{const m=N();if(!m)return;const b=Array.isArray(f.activeMarks)?f.activeMarks:[];let I=null;for(const E of Object.keys(m)){const z=m[E];let K;if(D.has(E))K=b.includes(E)===(z===!0);else if(mb(E)){if(z==null)continue;I||(I=Sl(f)),K=I[E]===z}else K=!1;K&&Z(E)}},T=()=>{const f=_()?.editCommands;return f&&typeof f=="object"?f:null},V=f=>{const m=T();if(!m||typeof m.getSnapshot!="function")return null;const b=Lt(()=>m.getSnapshot(),null)?.commands?.[f];return b&&typeof b=="object"?b:null},J=()=>V("lists.apply"),q=f=>{const m=f?.value?.seed;return m==="bullet"||m==="ordered"?m:null},se=f=>{const m=KV[f];return m?V(m):null},pe=()=>{const f=x();if(!f||typeof f.getTableContext!="function")return null;const m=Lt(()=>f.getTableContext(),null);return m&&typeof m=="object"?m:null},Ne=()=>{const f=pe();if(!f||f.inTable!==!0)return null;const m=f.table,b=typeof m?.nodeId=="string"&&m.nodeId.length>0?m.nodeId:null;if(!b)return null;const I=f.row,E=f.column,z=f.cell,K=typeof I?.index=="number"&&Number.isInteger(I.index)?I.index:null,oe=typeof E?.index=="number"&&Number.isInteger(E.index)?E.index:null;if(K==null||oe==null)return null;const me=typeof z?.nodeId=="string"&&z.nodeId.length>0?z.nodeId:null,Re=f.cellRange;return{tableNodeId:b,rowIndex:K,columnIndex:oe,cellNodeId:me,mergeRange:cH(Re)}},he=new Map;let ye=null,ce=null,ke=0,ie=0,xe=0;const Je=new Set,st=(f,m)=>f===m?!0:!f||!m?!1:f.id===m.id&&f.paintedEntityId===m.paintedEntityId&&kr(f.story)===kr(m.story),Tt=f=>Array.from(Je).some(m=>st(m,f)),Te=f=>{const m=x();if(typeof m?.getHandles!="function")return;const b=Lt(()=>m.getHandles(),null),I=b?.review;if(I){if(f){if(typeof I.setActiveReviewTarget!="function")return;const E=b?.layout;Lt(()=>I.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 I.getActiveReviewTarget!="function"||typeof I.clearActiveReviewTarget!="function"||Lt(()=>I.getActiveReviewTarget(),null)?.entityType==="trackedChange"&&Lt(()=>I.clearActiveReviewTarget(),void 0)}},je=(f,m)=>{ce=f,ke+=1,xe+=1,m?.invalidateQueuedNavigation!==!1&&(ie+=1)},Ye=new Set;let $=!1,S=null;const ee=new Map,O=new Set;let j=null,U=null,W=!1,te=null,Y=0,X=null,be=null,ve=null;const we=()=>{if(W||$)return;W=!0;const f=()=>{W=!1,$||Xt()};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Be=250,rt=5e3,at=f=>{$||te&&Y<=f||(te&&clearTimeout(te),Y=f,te=setTimeout(()=>{te=null,Y=0,$||Xt()},Math.max(0,f-Date.now())))},Ct=new WeakMap;let en=0;const Et=f=>{if(!f)return"none";let m=Ct.get(f);return m==null&&(m=en+=1,Ct.set(f,m)),`e${m}`};let Ut=0,Wt={};const In=e.superdoc,bt=CV(In),nn=()=>{bt.abortController.abort("review-mutation-started"),bt.inFlight=null},et=()=>{bt.generation+=1,bt.abortController=new AbortController,bt.inFlight=null},Pt=f=>{const m=bt.activeMutationTokens;if(typeof f!="string"||f.length===0||m.has(f))return;const b=m.size===0;m.add(f),b&&nn()},Kt=f=>{const m=bt.activeMutationTokens;typeof f!="string"||!m.delete(f)||m.size===0&&et()},Rn=f=>{const m=w(),b=m?.listTrackedChanges;if(typeof b!="function")return _()?.editorVersion===2?Promise.reject(new Error("v2-tracked-changes-bridge-pending")):f();if(bt.activeMutationTokens.size>0)return Promise.reject(new Error("ui-review-catalog-superseded"));if(_()?.reviewHydration?.getDiagnostics?.()?.inFlight===!0)return Promise.reject(new Error("shell-review-hydration-in-flight"));const I=bt.generation,E=bt.inFlight;if(E?.generation===I)return E.promise;const z=bt.abortController.signal,K=Re=>{if(z.aborted||I!==bt.generation||Re?.reason==="review-hydration-superseded")throw new Error("ui-review-catalog-superseded");return Re},oe=b.call(m,{blocking:!1,signal:z});if(!Cr(oe))return K(oe);const me=Promise.resolve(oe).then(K);return bt.inFlight={generation:I,promise:me},me.then(()=>{bt.inFlight?.promise===me&&(bt.inFlight=null)},()=>{bt.inFlight?.promise===me&&(bt.inFlight=null)}),me};let Nt=null,un=null,Mn=0;const Pe=()=>{un&&clearTimeout(un),un=null,Mn=0};let Ge=f=>{},We=null,ft=new Set,Vt=null,yt=0,$t=null;const At=()=>`${Et(_())}|m${Ut}`,kn=()=>{We=null,ft=new Set},Nn=f=>{for(const m of["trackChanges","trackChanges:all"]){const b=ee.get(m);if(!b?.hasSettled||!Array.isArray(b.value))continue;const I=b.value.filter(E=>{const z=Kn(E);return!z||!f.has(z)});I.length!==b.value.length&&ee.set(m,{...b,value:I})}},Uo=f=>{const m=()=>{if(!$)for(const z of[...Ye])z(dt)},b=lc(f)?f:null,I=_()?.documentMutationReadiness,E=()=>{const z=globalThis.requestAnimationFrame;return typeof z!="function"?Promise.resolve():new Promise(K=>{let oe=!1;const me=()=>{oe||(oe=!0,clearTimeout(Re),K())},Re=setTimeout(me,250);z(()=>z(()=>setTimeout(me,0)))})};if(b?.success===!0&&typeof b.txId=="string"&&b.txId.length>0&&typeof I?.whenPainted=="function")try{Promise.resolve(I.whenPainted.call(I,b)).then(E,()=>{}).then(m,m);return}catch{}m()},Ht=(f,m)=>{const b=dt.trackChanges,I=b.items.filter(K=>{const oe=Kn(K);return!oe||!f.has(oe)});if(I.length===b.items.length)return;ce&&f.has(ce.id)&&je(null);const E=new Set;for(const K of I){const oe=km(K),me=K,Re=oe.author??oe.authorEmail??me.author??me.authorEmail;typeof Re=="string"&&E.add(Re)}const z=b.items.length-I.length;dt={...dt,trackChanges:{...b,items:I,total:Math.max(I.length,b.total-z),activeId:b.activeId&&f.has(b.activeId)?null:b.activeId,authors:[...E]}},Uo(m)},Pn=f=>{const m=dt.trackChanges,b=m.items.length>0||m.total!==0||m.activeId!==null||m.authors.length>0;Vt=At(),ce!==null&&je(null),dt={...dt,trackChanges:{...m,items:[],total:0,activeId:null,authors:[]}},b&&Uo(f)},br=(f,m)=>{if(f.size===0)return;const b=At(),I=We===b?ft:new Set,E=new Set([...f].filter(z=>!I.has(z)));E.size!==0&&(We=b,ft=new Set([...I,...E]),Nn(ft),Ht(E,m))},Do=f=>We===f&&ft.size>0?ft:null,er=(f,m=[])=>{const b=f.map(dl).filter(E=>E!=null&&Kn(E)!=null);if(b.length===0)return;const I=m.map(dl).map(E=>E==null?null:Kn(E)).filter(E=>E!=null);for(const E of["trackChanges","trackChanges:all"]){const z=ee.get(E),K=z?.hasSettled&&Array.isArray(z.value)?[...z.value]:[],oe=new Set;let me=!1;for(const Re of b){const Ue=Kn(Re);if(!Ue)continue;const Ke=K.findIndex(Fe=>Kn(Fe)===Ue);if(Ke<0)K.push(Re),oe.add(Ue);else{const Fe=K[Ke];K[Ke]=lc(Fe)?{...Fe,...Re}:Re}me=!0}if(E==="trackChanges"&&oe.size>0&&I.length>0){const Re=new Set(I.filter(Fe=>oe.has(Fe))),Ue=new Map(K.filter(Fe=>Re.has(Kn(Fe)??"")).map(Fe=>[Kn(Fe),Fe])),Ke=K.filter(Fe=>!Re.has(Kn(Fe)??""));for(const[Fe,Xe]of I.entries()){if(!Re.has(Xe))continue;const He=Ue.get(Xe);if(!He)continue;const Ze=I.slice(Fe+1).map(ot=>Ke.findIndex(nt=>Kn(nt)===ot)).find(ot=>ot>=0);if(Ze!=null){Ke.splice(Ze,0,He);continue}const Qe=I.slice(0,Fe).reverse().map(ot=>Ke.findIndex(nt=>Kn(nt)===ot)).find(ot=>ot>=0);Ke.splice(Qe==null?Ke.length:Qe+1,0,He)}K.splice(0,K.length,...Ke)}me&&ee.set(E,{token:z?.token??null,value:K,hasSettled:!0,inflightToken:null})}},cn=f=>{const m=At(),b=Do(m),I=f.map(dl).filter(E=>{if(E==null)return!1;const z=Kn(E);return z!=null&&!b?.has(z)});for(const E of["trackChanges","trackChanges:all"])ee.set(E,{token:m,value:[...I],hasSettled:!0,inflightToken:null})},Gn=async(f,m)=>{try{const b=f.v2TrackedChanges?.listTrackedChanges;if(typeof b=="function"){const z=await Promise.resolve(b.call(f.v2TrackedChanges,{mode:m.trackedChangesListMode,refreshReason:m.refreshReason,blocking:m.blocking,...m.targetIds?.length?{targetIds:m.targetIds}:{}})),K=m.trackedChangesListMode==="all"&&m.refreshReason==="mutation-history-render-reconcile"?z?.ok===!0:z?.ok!==!1;return{ok:K,items:K&&Array.isArray(z?.items)?z.items:[],...typeof z?.complete=="boolean"?{complete:z.complete}:{},...typeof z?.sourceCoverageComplete=="boolean"?{sourceCoverageComplete:z.sourceCoverageComplete}:{}}}const I=f.docTrackChanges?.list;if(typeof I!="function")return{ok:!1,items:[]};const E=await Promise.resolve(I.call(f.docTrackChanges));return{ok:!0,items:Array.isArray(E?.items)?E.items:[]}}catch(b){return{ok:!1,items:[],failures:[b]}}},Br=Wk({getContext:()=>{const f=_();if(!f)return null;const m=w(),b=y()?.trackChanges??null,I=m??b;if(!I)return null;const E=f.documentId??m?.documentId;return{editor:f,adapter:I,documentId:E==null?null:String(E),reconcileToken:Wt,v2TrackedChanges:m,docTrackChanges:b}},reconcile:async(f,m)=>{m.removedIds.size>0&&br(new Set(m.removedIds));const b=[...new Set(m.upsertIds)];if(b.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};const I=ee.get("trackChanges"),E=I?.hasSettled&&Array.isArray(I.value)?I.value:null,z=new Set(E?E.map(Kn).filter(Qe=>Qe!=null):[]),K=E?.length===0&&ba()==="complete",oe=new Set(b.filter(Qe=>!z.has(Qe))),me=f.v2TrackedChanges?.getTrackedChange,Re=f.docTrackChanges?.get;if(typeof me!="function"&&typeof Re!="function")return{ok:!1,items:[],resolvedIds:[],unresolvedIds:b};const Ue=await Promise.all(b.map(async Qe=>{try{if(typeof me=="function"){const nt=await Promise.resolve(me.call(f.v2TrackedChanges,Qe));return{id:Qe,ok:nt?.ok!==!1,items:nt?.ok!==!1&&Array.isArray(nt?.items)?nt.items:[],result:nt}}const ot=await Promise.resolve(Re.call(f.docTrackChanges,{id:Qe}));return{id:Qe,ok:!0,items:ot&&typeof ot=="object"?[ot]:[],result:ot}}catch(ot){return{id:Qe,ok:!1,items:[],result:ot}}})),Ke=[],Fe=[],Xe=[];for(const Qe of Ue){const ot=Qe.items.filter(nt=>{const Ot=dl(nt);return Ot!=null&&Kn(Ot)===Qe.id});Qe.ok&&ot.length>0?(Ke.push(...ot),Fe.push(Qe.id)):Xe.push(Qe.id)}let He;const Ze=Fe.filter(Qe=>oe.has(Qe));if(Ze.length>0&&!K){const Qe=await Gn(f,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1,targetIds:Ze});Qe.ok&&(He=Qe.items)}return{ok:Xe.length===0,items:Ke,orderedItems:He,resolvedIds:Fe,unresolvedIds:Xe,failures:Ue.filter(Qe=>!Qe.ok).map(Qe=>Qe.result)}},hydrate:Gn,onReconciled:(f,m,b)=>{if(b?.reconcileMode==="authoritative"){if(f.reconcileToken!==Wt)return;b.ok===!0&&b.complete===!0&&b.sourceCoverageComplete===!0?(Pe(),cn(b.items??[]),Nt=null):b.ok===!0?(Pe(),er(b.items??[])):Ge(f.reconcileToken),Xt();return}er((b?.items??[]).filter(I=>{const E=dl(I),z=E==null?null:Kn(E);return z!=null&&m.has(z)}),b?.orderedItems??b?.items??[]),Xt()}});Ge=f=>{if($||un)return;const m=Math.min(Be*2**Mn,rt);Mn+=1,un=setTimeout(()=>{un=null,!($||Nt===null||f!==Wt)&&Br.onRender(!0)},m)};const ei=()=>`${At()}|m${Xn()}|s${yt}`,bo=f=>JSON.stringify({t:f.target??null,s:f.selectionTarget??null}),Jr=["contentControls:inRange:","query:","effInline:"],Xi=120,Ri=180,ba=()=>{const f=x(),m=f?.getDocumentLoadingSnapshot;if(typeof m!="function")return"unknown";const b=Lt(()=>m.call(f),null)?.sourceStage;return b==="opening"||b==="bootstrap-ready"||b==="source-loading"?"loading":b==="source-complete"||b==="source-failed"||b==="source-cancelled"?"complete":"unknown"},ti=new Map,wa=f=>{const m=At();ti.get(f)!==m&&(ti.set(f,m),we())},uc=()=>{const f=ee.get("comments");return f?.hasSettled?Array.isArray(f.value)&&f.value.length>0:f?.inflightToken!=null},Oo=(f,m)=>ti.get(f)===m,jo=f=>{wa("contentControls")},Se=()=>{const f=ee.get("trackChanges");f?.hasSettled||f?.inflightToken!=null||wa("trackChanges")},Ve=6500,_t=8e3,lt=250;let Ln=0,Bn=0,sr=!1,Sr=0,wo=!1,Co=null;const mi=()=>{if($||Co)return;const f=Sr||Date.now(),m=()=>{if(Co=null,$)return;const b=Date.now()-Ln,I=gi()||b<Ve;if(I&&Date.now()-f<_t){Co=setTimeout(m,lt);return}sr=!1,wo=I;try{Xt()}finally{wo=!1,Sr=0}};Co=setTimeout(m,0)};let co=null,pr=null;const hl=()=>{const f=x();if(!f||co===f)return;pr&&(pr(),pr=null),co=f;const m=f.subscribeDocumentLoading;if(typeof m!="function"){co=null,zr(Ve);return}try{const b=z=>{const K=z?.sourceStage;(K==="source-complete"||K==="source-failed"||K==="source-cancelled")&&mi()},I=m.call(f,b);typeof I=="function"&&(pr=I);const E=f.getDocumentLoadingSnapshot;typeof E=="function"&&b(Lt(()=>E.call(f),null))}catch{co=null,zr(Ve)}},Ca=()=>{const f=_()?.host,m=f?.getForegroundMutationState;if(typeof m!="function")return null;const b=Lt(()=>m.call(f),null);return{active:typeof b?.active=="number"?b.active:0,pending:typeof b?.pending=="number"?b.pending:0}},gi=()=>{const f=Ca();return!!(f&&(f.active>0||f.pending>0))},zr=(f=Xi)=>{$||X||(X=setTimeout(()=>{if(X=null,$)return;if(be&&gi()){zr(),Xt();return}const m=be;be=null,m===ei()&&As("selection",m,fc,uo),Xt()},f))},ni=(f,m)=>{if(!Ca())return!1;const b=`${f}\0${m}`;return O.has(b)?!1:(O.add(b),zr(Ri),!0)},ko=f=>{if(j==null||f===j)return U?.timer&&clearTimeout(U.timer),U=null,j=f,!1;if(U?.key===f)return U.ready?(U=null,j=f,!1):!0;U?.timer&&clearTimeout(U.timer);const m={key:f,ready:!1,timer:null};return m.timer=setTimeout(()=>{$||U!==m||(m.timer=null,m.ready=!0,Xt())},Ri),U=m,!0},Mi=f=>Kk(f),vi=()=>{Es(),Xt()};let ka=null,pl=!1,ri=0;const Ss=()=>{ka=null,pl=!1,ri+=1},_s=()=>{const f=_(),m=f?.documentMutationReadiness;if(!f||typeof m?.whenPainted!="function"||(ka={editor:f,readiness:m,afterEpoch:typeof m.getRenderEpoch=="function"?Lt(()=>m.getRenderEpoch.call(m),null):null},pl))return;pl=!0;const b=ri;(async()=>{for(;!$&&b===ri;){const E=ka;if(ka=null,!E){pl=!1;return}let z=!1;try{await E.readiness.whenPainted.call(E.readiness,typeof E.afterEpoch=="number"?{afterEpoch:E.afterEpoch}:void 0),z=!0}catch{}if($||b!==ri)return;if(_()!==E.editor){Ss();return}z&&vi()}})()},ml=()=>{ve&&clearTimeout(ve),ve=setTimeout(()=>{ve=null,$||vi()},500)},As=(f,m,b,I)=>{let E;try{E=b()}catch{E=void 0}if(!Cr(E)){const oe={token:m,value:I(E),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0};return ee.set(f,oe),oe}const z=ee.get(f),K=z?.failedToken===m;return ee.set(f,{token:z?.token??null,value:z?.value??null,hasSettled:z?.hasSettled??!1,inflightToken:m,failedToken:K?m:null,failureCount:K?z.failureCount??0:0,retryAtMs:0}),Promise.resolve(E).then(oe=>{const me=ee.get(f);!me||me.inflightToken!==m||(ee.set(f,{token:m,value:I(oe),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0}),we())},()=>{const oe=ee.get(f);if(!oe||oe.inflightToken!==m)return;const me=oe.failedToken===m?(oe.failureCount??0)+1:1,Re=Math.min(rt,Be*2**Math.min(me-1,8)),Ue=Date.now()+Re;ee.set(f,{...oe,inflightToken:null,failedToken:m,failureCount:me,retryAtMs:Ue}),at(Ue)}),null},Vr=(f,m,b,I)=>{const E=ee.get(f);if(E&&E.token===m&&E.hasSettled)return{value:E.value,status:"ready"};if(MV(f)&&!Oo(f,m)){if(ba()==="loading")return sr=!0,hl(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(sr&&!wo)return mi(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!wo){const K=Date.now();if(K-Bn<Ve&&(!Sr||K-Sr<_t))return Sr||(Sr=K),sr=!0,mi(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};Sr=0}}if(gi())return zr(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(E?.failedToken===m&&E.inflightToken==null&&(E.retryAtMs??0)>Date.now())return at(E.retryAtMs),E.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!E&&f.startsWith("effInline:")&&ko(f))return{value:null,status:"pending"};if(!E&&ni(f,m))return{value:null,status:"pending"};if(!E||E.inflightToken!==m){const K=As(f,m,b,I);if(K)return{value:K.value,status:"ready"}}const z=ee.get(f);return z?.hasSettled?{value:z.value,status:"stale"}:{value:null,status:"pending"}},Nu=f=>{for(const m of ee.keys())f(m)&&ee.delete(m)},Is=f=>{const m=bo(f),b=EA(f);return new Set([`contentControls:inRange:${m}`,`query:${m}`,...b?[`effInline:${b}`]:[]])},Wf=f=>{const m=Is(f);Nu(b=>Jr.some(I=>b.startsWith(I))&&!m.has(b));for(const b of O){const I=b.split("\0",1)[0];Jr.some(E=>I.startsWith(E))&&!m.has(I)&&O.delete(b)}},Sa=()=>{const f=_();f!==$t&&(Ss(),Br.reset(),Wt={},$t=f,ee.clear(),Nt=null,Pe(),te&&clearTimeout(te),te=null,Y=0,U?.timer&&clearTimeout(U.timer),U=null,j=null,C=null,o=null,be=null,O.clear(),ti.clear(),sr=!1,Sr=0,pr&&pr(),pr=null,co=null,kn(),Vt=null)},Es=()=>{const f=Nt!==null;Ut+=1,f&&(Nt=At()),kn()},Go=()=>{const f=Vt===At();Es(),f&&(cn([]),Vt=At()),Xt()},Li=f=>{if(typeof f!="string"||f.length===0)return hr("insertText requires a non-empty string.","INVALID_INPUT");if(Xn()==="viewing")return hr("The document is read-only.","DOCUMENT_READONLY");const m=y(),b=m?.insert;if(!m||typeof b!="function")return hr("insert is unavailable.");const I=m.selection?.current;if(typeof I!="function")return hr("selection.current is unavailable.");const E=K=>{const oe=K&&typeof K=="object"?K:null,me=oe?.selectionTarget??oe?.target??null;return!me||typeof me!="object"?hr("insertText requires a live selection target.","PRECONDITION_FAILED"):Lt(()=>La(b.call(m,{type:"text",value:f,target:me}),hr("insert failed.")),hr("insert failed."))};let z;try{z=I.call(m.selection)}catch{return hr("insertText could not resolve the live selection.","PRECONDITION_FAILED")}return Cr(z)?Promise.resolve(z).then(E,()=>hr("insertText could not resolve the live selection.","PRECONDITION_FAILED")):E(z)},Bu=(f,m)=>({payload:f,state:dt,editor:_(),superdoc:t,context:m,ui:S,execute:(b,I)=>Mc(b,I),executeAsync:(b,I)=>Pm(b,I),doc:y(),selection:dt.selection,documentMode:Xn(),insertText:Li}),gl=f=>f==="editing"||f==="suggesting"||f==="viewing"?f:null,Xn=()=>{const f=_(),m=t&&typeof t=="object"?t:null,b=gl(m?.config?.documentMode),I=gl(Lt(typeof m?.getActiveRuntime=="function"?()=>{const z=m.getActiveRuntime();return typeof z?.getSnapshot=="function"?z.getSnapshot():null}:void 0,null)?.documentMode),E=gl(f?.options?.documentMode);return b&&I&&b!==I?b:I??b??E},zu=()=>{const f=t&&typeof t=="object"?t:null,m=f?.interactionConfig?.comments;if(m&&typeof m.readOnly=="boolean")return m.readOnly===!0;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.readOnly===!0},dc=()=>{const f=t&&typeof t=="object"?t:null,m=f?.interactionConfig?.comments;if(m&&typeof m.allowResolve=="boolean")return m.allowResolve===!1;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.allowResolve===!1},Zi=()=>Xn()==="viewing"||zu(),uo=f=>f&&typeof f=="object"?f:null,Ts=(f,m)=>{if(!f)return{...TV,status:m};const b=f.target??null,I=typeof f.text=="string"?f.text:"";return{status:m,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:I}},_a=()=>{const f=y()?.selection;return Vr("selection",ei(),()=>f?.current?f.current({includeText:!0}):void 0,uo)},Kf=()=>{const{value:f,status:m}=_a();return Ts(f,m)},fc=()=>{const f=y()?.selection;return f?.current?f.current({includeText:!0}):void 0},hc=f=>{if(f.empty!==!0)return!1;const m=f.selectionTarget,b=m?.start,I=m?.end;return b?.kind==="text"&&I?.kind==="text"&&typeof b.blockId=="string"&&b.blockId===I.blockId&&typeof b.offset=="number"&&b.offset===I.offset},vl=f=>{const m=x(),b=m?.readLiveSelectionSyncSnapshot;if(typeof b!="function")return;const I=uo(Lt(()=>b.call(m),null));if(!I||!hc(I))return;const E=ei(),z=Ca(),K=!!(z&&(z.active>0||z.pending>0));if(K)be=E,zr();else if(be=null,As("selection",E,fc,uo))return;const oe=ee.get("selection"),me=Array.isArray(I.activeMarks)&&I.activeMarks.length>0?I.activeMarks:Array.isArray(dt.selection.activeMarks)?dt.selection.activeMarks:[],Re=Array.isArray(I.activeCommentIds)?I.activeCommentIds:[],Ue=FV(f),Ke=ul(dt.selection),Fe=jf(I.selectionTarget)??jf(I.target),Xe=Ke?.range,He=Fe?.range,Ze=!!(z&&z.active>0&&Ke&&Fe&&Ke.blockId===Fe.blockId&&kr(Ke.story)===kr(Fe.story)&&typeof Xe?.start=="number"&&typeof He?.start=="number"&&Math.abs(He.start-Xe.start)<=2),Qe=Ue!=null||Ze?dt.selection.activeChangeIds.filter(nt=>Ue==null||ga(dt.trackChanges.items).aliasesFor(nt).includes(Ue)):[],ot=Array.isArray(I.activeChangeIds)&&I.activeChangeIds.length>0?I.activeChangeIds:Qe;ee.set("selection",{token:E,value:{...I,activeMarks:me,activeCommentIds:Re,activeChangeIds:ot},hasSettled:!0,inflightToken:K?null:oe?.inflightToken??null})},yl=async(f=0)=>{const m=y()?.selection,b=m?.current,I=ei();if(typeof b!="function")return ee.set("selection",{token:I,value:null,hasSettled:!0,inflightToken:null}),Xt(),dt.selection;let E;try{E=b.call(m,{includeText:!0}),Cr(E)&&(E=await Promise.resolve(E))}catch{E=null}return $?Ts(null,"pending"):ei()!==I?f<1?yl(f+1):dt.selection:(ee.set("selection",{token:I,value:uo(E),hasSettled:!0,inflightToken:null}),Xt(),dt.selection)},qf=f=>{const m=y()?.comments,{value:b,status:I}=Vr("comments",At(),()=>m?.list?m.list():void 0,oe=>oe&&Array.isArray(oe.items)?oe.items:[]),E=b??[],z=f.activeCommentIds;ye&&!E.some(oe=>Kn(oe)===ye)&&(ye=null);const K=ye??z[0]??null;return{status:Mu(I,f.status),listStatus:I,items:E,total:E.length,activeIds:z,activeId:K}},Qi=()=>{const f=y()?.trackChanges,m=At(),b=ee.get("trackChanges:all"),{value:I,status:E}=Nt===m?{value:b?.hasSettled?b.value:null,status:b?.hasSettled?"stale":"pending"}:Vr("trackChanges:all",m,()=>{if(!f?.list)return;const z=()=>f.list({in:"all"}),K=typeof w()?.listTrackedChanges=="function",oe=Rn(z);return K?Promise.resolve(oe).then(me=>{const Re=lc(me)?me:null;return(Array.isArray(Re?.items)?Re.items:[]).some(Ue=>Lu(Ue)==null)?z():me}):oe},z=>(z&&Array.isArray(z.items)?z.items:[]).map(dl).filter(K=>K!=null));return E==="ready"?I:null},bl=f=>{const m=y()?.trackChanges,b=w(),I=typeof b?.listTrackedChanges=="function"?b.listTrackedChanges:null,E=At(),z=Do(E),K=ee.get("trackChanges"),{value:oe,status:me}=Nt===E?{value:K?.hasSettled?K.value:null,status:K?.hasSettled?"stale":"pending"}:Vr("trackChanges",E,()=>I?Rn(()=>m?.list?.()):m?.list?m.list({in:"all"}):void 0,on=>on&&Array.isArray(on.items)?on.items:[]),Re=(oe??[]).map(dl).filter(on=>on!=null).filter(on=>{const Dn=Kn(on);return!Dn||!z?.has(Dn)}),Ue=new Set;for(const on of Re){const Dn=km(on),Mr=on,Ar=Dn.author??Dn.authorEmail??Mr.author??Mr.authorEmail;typeof Ar=="string"&&Ue.add(Ar)}const Ke=m?.list?Qi():null,Fe=ce;Fe&&(Fe.story?Ke&&!Ke.some(on=>Wi(on,Fe.id,Fe.story))&&je(null):Re.some(on=>Kn(on)===Fe.id)||je(null));const Xe=Ke??Re,He=Pu(Xe,Ki(f)),Ze=Vt===E?[]:z?f.activeChangeIds.filter(on=>!z.has(on)):f.activeChangeIds,Qe=Ze.map(on=>He.toPublicId(on)??on),ot=ce?.story?Pu(Xe,ce.story):ga(Xe),nt=ce?ot.toPublicId(ce.id)??ce.id:null,Ot=VV({selectionIds:Ze,publicIds:Qe,selection:f,bodyItems:Re,allStoryItems:Ke}),Qt=nt??Ot;return{status:Mu(me,f.status),items:Re,total:Re.length,activeId:Qt,authors:[...Ue]}},Aa=f=>{const m=y()?.contentControls,{value:b,status:I}=Vr("contentControls",At(),()=>m?.list?m.list():void 0,oe=>oe&&Array.isArray(oe.items)?oe.items:[]),E=b??[],{ids:z,status:K}=Yf(m,f);return{status:Mu(I,K,f.status),items:E,total:E.length,activeId:z[0]??null,activeIds:z}},xs=(f,m)=>{if(!f||typeof f.listInRange!="function")return{lockModesById:new Map,status:"ready"};const b=UV(m);if(!b)return{lockModesById:new Map,status:"ready"};const{value:I,status:E}=Vr(`contentControls:inRange:${bo(m)}`,At(),()=>f.listInRange(b),oe=>oe&&Array.isArray(oe.items)?oe.items:[]),z=I??[],K=new Map;for(const oe of z)typeof oe?.id=="string"&&K.set(oe.id,typeof oe.lockMode=="string"?oe.lockMode:"unlocked");return{lockModesById:K,status:E}},Yf=(f,m)=>{const{lockModesById:b,status:I}=xs(f,m);return{ids:[...b.keys()],status:I}},yi=()=>{const f=t?.fonts;return{options:gH(pH(Lt(f?.getDocumentFontOptions?()=>f.getDocumentFontOptions():void 0,[])),mH(Lt(f?.getFontFamilyOptions?()=>f.getFontFamilyOptions():void 0,[]))),sizeOptions:vH}},bi=()=>{const f=Lt(t?.getZoomState?()=>t.getZoomState():void 0,null),m=typeof f?.value=="number"?f.value:100,b=f?.mode;return{mode:b==="manual"||b==="fit-width"?b:b==="fixed"?"manual":null,value:m,min:typeof f?.min=="number"?f.min:10,max:typeof f?.max=="number"?f.max:100}},Kr=()=>Lt(t?.getMeasurementUnit?()=>t.getMeasurementUnit():void 0,"in")==="cm"?"cm":"in",pc=()=>{const f=_();return{ready:f!=null,mode:Xn(),dirty:f?!!f.isDirty:!1}},wl=f=>{const m=f.quotedText;if(typeof m!="string"||m.length===0)return null;const b=Ou(f);if(b.length===0||!ac(b.map(z=>z.blockId)))return null;const I=f.target,E=b.length===1?vo(b[0].blockId,I?.story):void 0;return{select:{type:"text",pattern:m,mode:"contains",caseSensitive:!0},...E?{within:E}:{},require:"any"}},Rs=f=>{const m=y()?.query;if(typeof m?.match!="function")return null;const b=wl(f);if(!b)return null;const{value:I}=Vr(`query:${bo(f)}`,At(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return TA(I,f)},Ia=f=>{const m=x(),b=new Set(Nr(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Lt(()=>{if(typeof I!="function")return E.call(m);const Ze=qi(f);return Ze?I.call(m,[...b],Ze):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=yb(z),oe=Ze=>{const Qe={},ot=gb(Ze.fontFamily);ot&&(Qe.fontFamily=ot);const nt=$V(Ze.fontSize);return nt&&(Qe.fontSize=nt),typeof Ze.color=="string"&&Ze.color.trim()!==""&&(Qe.color=Ze.color.trim().toUpperCase()),typeof Ze.highlight=="string"&&Ze.highlight.trim()!==""&&(Qe.highlight=Ze.highlight.trim().toUpperCase()),Qe},me=ul(f),Re=me&&typeof me.range?.start=="number"?me.range.start:null;if(me&&Re!==null&&b.has(me.blockId)){const Ze=K.find(ot=>cc(ot,me.blockId)),Qe=Ze&&Array.isArray(Ze.runs)?Ze.runs:null;if(Qe&&Qe.length>0&&Qe.every(ot=>ot?.kind==="text"||ot?.kind==="tab")){let ot=0,nt=null;for(const Ot of Qe){const Qt=typeof Ot.text=="string"?Ot.text.length:0;if(Re>=ot&&Re<ot+Qt){nt=Ot;break}ot+=Qt}if(!nt){for(let Ot=Qe.length-1;Ot>=0&&!nt;Ot-=1)Qe[Ot]?.kind==="text"&&(nt=Qe[Ot]);nt??=Qe[Qe.length-1]??null}return nt?oe(nt):{}}}const Ue=Ou(f);if(Ue.length>0){const Ze=new Set,Qe=new Set;let ot=!1,nt=!0;for(const Ot of Ue){const Qt=K.find(Mr=>cc(Mr,Ot.blockId));if(!Qt)return{};const on=Array.isArray(Qt.runs)?Qt.runs:[];if(on.length===0)continue;if(!on.every(Mr=>Mr?.kind==="text"||Mr?.kind==="tab")){nt=!1;break}let Dn=0;for(const Mr of on){const Ar=typeof Mr.text=="string"?Mr.text.length:0,jr=Dn,Lr=Dn+Ar;if(jr<Ot.end&&Lr>Ot.start){ot=!0;const Ko=oe(Mr);Ko.fontFamily&&Ze.add(Ko.fontFamily),Ko.fontSize&&Qe.add(Ko.fontSize)}Dn=Lr}}if(nt&&ot){const Ot={};return Ze.size===1&&(Ot.fontFamily=[...Ze][0]),Qe.size===1&&(Ot.fontSize=[...Qe][0]),Ot}}const Ke=new Set,Fe=new Set;let Xe=!1;for(const Ze of K){if(![...b].some(ot=>cc(Ze,ot)))continue;const Qe=Array.isArray(Ze.runs)?Ze.runs:[];for(const ot of Qe){if(ot?.kind!=="text")continue;Xe=!0;const nt=oe(ot);nt.fontFamily&&Ke.add(nt.fontFamily),nt.fontSize&&Fe.add(nt.fontSize)}}if(!Xe)return{};const He={};return Ke.size===1&&(He.fontFamily=[...Ke][0]),Fe.size===1&&(He.fontSize=[...Fe][0]),He},Wo=f=>{const m=x(),b=new Set(Nr(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Lt(()=>{if(typeof I!="function")return E.call(m);const He=qi(f);return He?I.call(m,[...b],He):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=yb(z),oe=He=>({bold:He.bold===!0,italic:He.italic===!0,underline:He.underline!=null,strikethrough:He.strike===!0}),me=He=>{const Ze={};for(const Qe of Gf){const ot=He[Qe];ot.size===1&&(Ze[Qe]=[...ot][0])}return Ze},Re=ul(f),Ue=Re&&typeof Re.range?.start=="number"?Re.range.start:null;if(Re&&Ue!==null&&b.has(Re.blockId)){const He=K.find(Qe=>cc(Qe,Re.blockId)),Ze=He&&Array.isArray(He.runs)?He.runs:null;if(Ze&&Ze.length>0&&Ze.every(Qe=>Qe?.kind==="text"||Qe?.kind==="tab")){let Qe=0,ot=null;for(const nt of Ze){const Ot=typeof nt.text=="string"?nt.text.length:0;if(Ue>=Qe&&Ue<Qe+Ot){ot=nt;break}Qe+=Ot}if(!ot){for(let nt=Ze.length-1;nt>=0&&!ot;nt-=1)Ze[nt]?.kind==="text"&&(ot=Ze[nt]);ot??=Ze[Ze.length-1]??null}return ot?oe(ot):{}}}const Ke=Ou(f);if(Ke.length>0){const He={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Ze=!1,Qe=!0;for(const ot of Ke){const nt=K.find(on=>cc(on,ot.blockId));if(!nt)return{};const Ot=Array.isArray(nt.runs)?nt.runs:[];if(Ot.length===0)continue;if(!Ot.every(on=>on?.kind==="text"||on?.kind==="tab")){Qe=!1;break}let Qt=0;for(const on of Ot){const Dn=typeof on.text=="string"?on.text.length:0,Mr=Qt,Ar=Qt+Dn;if(Mr<ot.end&&Ar>ot.start){Ze=!0;const jr=oe(on);for(const Lr of Gf)He[Lr].add(jr[Lr])}Qt=Ar}}if(Qe&&Ze)return me(He)}const Fe={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Xe=!1;for(const He of K){if(![...b].some(Qe=>cc(He,Qe)))continue;const Ze=Array.isArray(He.runs)?He.runs:[];for(const Qe of Ze){if(Qe?.kind!=="text")continue;Xe=!0;const ot=oe(Qe);for(const nt of Gf)Fe[nt].add(ot[nt])}}return Xe?me(Fe):{}},Cl=(f,m)=>{if(m.fontFamily!==void 0&&m.fontSize!==void 0&&m.color!==void 0&&m.highlight!==void 0)return{values:m,effectiveUniformityStatus:"ready"};const b=Ia(f),I={...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}:{},...m};if(!f.empty&&(I.fontFamily===void 0||I.fontSize===void 0)){const E=kl(f);return E.values&&(I.fontFamily===void 0&&E.values.fontFamily!==void 0&&(I.fontFamily=E.values.fontFamily),I.fontSize===void 0&&E.values.fontSize!==void 0&&(I.fontSize=E.values.fontSize)),{values:I,effectiveUniformityStatus:E.status}}return{values:I,effectiveUniformityStatus:"ready"}},Xf=["fontFamily","fontSize","bold","italic","underline","strikethrough"],Vu=f=>{const m=f.selectionTarget;if(!m)return{value:null,status:"ready"};const b=yr(y(),"format.readEffectiveInlineUniformity");return b?Vr(`effInline:${EA(f)??bo(f)}`,At(),()=>b({target:m,offsetSpace:"selection",keys:Xf}),I=>I&&typeof I=="object"?I:null):{value:null,status:"ready"}},kl=f=>{const{value:m,status:b}=Vu(f);if(!m||m.success!==!0)return{values:null,status:b};const I=m.values,E=z=>{const K=I?.[z];if(!(!K||K.state!=="uniform"||typeof K.value!="string"))return z==="fontFamily"?gb(K.value):K.value};return{values:{fontFamily:E("fontFamily"),fontSize:E("fontSize")},status:b}},Zf=f=>{const{value:m,status:b}=Vu(f);if(!m||m.success!==!0)return{values:null,status:b};const I=m.values,E={};for(const z of Gf){const K=I?.[z];K?.state==="uniform"&&(K.value==="true"||K.value==="false")&&(E[z]=K.value==="true")}return{values:E,status:b}},Hu=(f,m)=>{const b=f.activeMark;if(!b||!Gf.includes(b))return null;const I=b,E=Wo(m)[I];if(E!==void 0)return E;const{values:z}=Zf(m),K=z?.[I];return K!==void 0?K:null},mc=async f=>{const m=f.selectionTarget;if(!m)return null;const b=yr(y(),"format.readEffectiveInlineUniformity");if(!b)return null;try{const I=await Promise.resolve(b({target:m,offsetSpace:"selection"}));return I&&typeof I=="object"&&I.success===!0?I:null}catch{return null}},gc=(f,m,b)=>{const I=b.values;for(const E of["fontFamily","fontSize"]){if(m[E]!==void 0)continue;const z=I?.[E];z?.state==="uniform"&&typeof z.value=="string"?f[E]=E==="fontFamily"?gb(z.value):z.value:delete f[E]}},Uu=f=>Cl(f,xA(Rs(f),f)),Sl=f=>Uu(f).values,Qf=async f=>{const m=y()?.query,b=wl(f);if(typeof m?.match!="function"||!b)return Sl(f);try{const I=await Promise.resolve(m.match(b)),E=xA(TA(I&&typeof I=="object"?I:null,f),f),z=Cl(f,E);if(z.effectiveUniformityStatus!=="ready"&&(E.fontFamily===void 0||E.fontSize===void 0)){const K=await mc(f);K&&gc(z.values,E,K)}return z.values}catch{return Sl(f)}},Ms=async f=>{const m=y();if(m)return typeof m.getNode=="function"?await Promise.resolve(m.getNode(f)):await Promise.resolve(m.getNodeById?.({nodeId:f.nodeId,nodeType:f.nodeType}))},vc=f=>{const m=y()?.query;if(typeof m?.match!="function")return"ready";const b=wl(f);if(!b)return"ready";const{status:I}=Vr(`query:${bo(f)}`,At(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return I},Pi=f=>{const m=Uu(f),b=m.values;if(f.empty)return m;const I=ya(f);return I?f.status==="ready"&&vc(f)==="ready"&&m.effectiveUniformityStatus==="ready"?(C={key:I,values:b},m):C&&C.key===I?{...m,values:{...C.values,...b}}:m:m},ju=f=>{const m=y(),b=Pi(f),I=b.values;f.status==="ready"&&!f.empty&&vc(f)==="ready"&&b.effectiveUniformityStatus==="ready"&&(v=I,k=`${ic(f)}:${At()}`);const E=m?.contentControls,{lockModesById:z}=xs(E,f),K={};for(const oe of le())K[oe]=bc(oe,m,f,I,z);return K},Di=f=>f?ut.operationUnavailable:_()?ut.documentApiUnavailable:ut.notReady,Gu=f=>f==="contentLocked"||f==="sdtContentLocked",Ji=f=>{for(const m of f.values())if(Gu(m))return ut.contentControlLocked},yc=(f,m,b,I,E)=>{if(!m)return f.scope==="all"?ut.bulkDecisionsDisabled:Di(E);if(b)return ut.documentReadonly;if(f.scope!=="all"&&I.activeChangeIds.length===0)return ut.selectionRequired},Wu=f=>{const m=x(),b=Lt(typeof m?.getCapabilities=="function"?()=>m.getCapabilities():void 0,null)?.editableSubset?.commands;if(Array.isArray(b))return b.find(I=>I?.command===f||I?.id===f)??null;if(b&&typeof b=="object"){const I=b[f];return I&&typeof I=="object"?I:null}return null},Ku=(f,m)=>{if(f.scope!=="all"||typeof m?.[`${f.kind}All`]=="function")return;const b=Wu(`trackedChanges.${f.kind}All`);if(!(b&&(b.status==="supported"||b.enabled===!0)))return ut.bulkDecisionsDisabled},bc=(f,m,b,I,E=new Map)=>{if(he.has(f))return ln({supported:!0,enabled:!0,...Lt(he.get(f).getState?()=>he.get(f).getState(Bu(void 0)):void 0,{})},"custom");const z=Xn()==="viewing",K=yA(f);if(K&&typeof T()?.lists?.apply=="function"){const Xe=J(),He=typeof Xe?.shippedStatus=="string"?Xe.shippedStatus:null,Ze=He!=="not-shipped"&&He!=="disabled";return ln({enabled:Ze&&(typeof Xe?.enabled=="boolean"?Xe.enabled:!0),active:(Ze?q(Xe):null)===K,supported:Ze,value:Xe?.value},"builtin")}const oe=_m(f);if(oe){const Xe=m?.trackChanges,He=typeof Xe?.decide=="function"||typeof Xe?.[oe.kind]=="function",Ze=typeof Xe?.decide=="function"||typeof Xe?.[`${oe.kind}All`]=="function",Qe=oe.scope==="all"?Ze:He,ot=Ku(oe,Xe)??yc(oe,Qe,Zi(),b,m);return ln({enabled:ot==null,active:!1,supported:Qe,reason:ot},"builtin")}if(f==="copy-format")return Xn()==="viewing"?ln({supported:!0,enabled:!1,active:!1},"builtin"):_()?ln({supported:!0,enabled:!0,active:h.mode!=="idle"},"builtin"):ln({supported:!0,enabled:!1,active:!1,reason:ut.notReady},"builtin");const me=Tu(f);if(!me)return ln({enabled:!1,active:!1,supported:!1,reason:ut.commandUnsupported},"unsupported");if(me.disposition!=="routed")return ln({enabled:!1,active:!1,supported:!1,reason:me.reason??ut.commandUnsupported},me.disposition==="unsupported"?"unsupported":"builtin");if(me.instanceRoute)return Q(me);if(me.table)return ae(me,m,z);if(me.inline?.kind==="clear"){if(me.mutates&&z)return ln({enabled:!1,active:!1,supported:!0,reason:ut.documentReadonly},"builtin");const Xe=Ji(E);if(Xe)return ln({enabled:!1,active:!1,supported:!0,reason:Xe},"builtin");const He=Nr(b).length>0||Fu(b)!=null;return ln({enabled:He,active:!1,supported:!0,reason:He?void 0:ut.selectionRequired},"builtin")}const Re=me.docRoute;if(!Re)return ln({enabled:!1,active:!1,supported:!1,reason:ut.commandUnsupported},"unsupported");if(yr(m,Re)==null)return ln({enabled:!1,active:!1,supported:!1,reason:Di(m)},"builtin");const Ue=se(f);if(Ue){const Xe=Ue.shippedStatus,He=Xe!=="not-shipped"&&Xe!=="disabled",Ze=typeof Ue.enabled=="boolean"?Ue.enabled:!0,Qe=f==="undo"||f==="redo",ot=Qe&&Ue.historyResolved===!1,nt=Qe&&He&&Ze===!1&&Ue.reason===null&&!ot,Ot=Ue.reason===void 0?void 0:nt?ut.historyEmpty:ot?ut.notReady:db(Ue.reason,ut.commandUnsupported);return me.mutates&&z?ln({enabled:!1,active:!1,supported:He,reason:ut.documentReadonly},"builtin"):ln({enabled:He&&Ze,active:!1,supported:He,reason:Ot},"builtin")}const Ke=Ea(me,m,b),Fe=Yu(me,m,b,I);if(me.list?.mode==="indent"||me.list?.mode==="outdent")return eh(me,m,z,b,Ke,Fe);if(me.list?.mode==="toggle-seed")return A(me,m,z,b,Ke,Fe);if(me.mutates&&z)return ln({enabled:!1,active:Ke,supported:!0,value:Fe,reason:ut.documentReadonly},"builtin");if(me.inline&&!Fu(b)){const Xe=Ji(E);return ln(Xe?{enabled:!1,active:Ke,supported:!0,value:Fe,reason:Xe}:Nr(b).length>0&&typeof x()?.setPendingInlineFormat=="function"?{enabled:!0,active:Ke,supported:!0,value:Fe}:{enabled:!1,active:Ke,supported:!0,value:Fe,reason:ut.rangeSelectionRequired},"builtin")}if((me.blockParagraph||me.list)&&Nr(b).length===0)return ln({enabled:!1,active:Ke,supported:!0,value:Fe,reason:ut.selectionRequired},"builtin");if(me.link&&!Ke&&pb(b).length===0&&!ul(b))return ln({enabled:!1,active:Ke,supported:!0,reason:ut.rangeSelectionRequired},"builtin");if(me.inline){const Xe=Ji(E);if(Xe)return ln({enabled:!1,active:Ke,supported:!0,value:Fe,reason:Xe},"builtin")}return ln({enabled:!0,active:Ke,supported:!0,value:Fe},"builtin")};function qu(f,m){const b=f.address?.anchor,I=b?.start,E=b?.end,z=typeof I?.blockId=="string"?I.blockId:null,K=typeof E?.blockId=="string"?E.blockId:null;if(!z||!K)return!1;const oe=typeof I?.offset=="number"?I.offset:null,me=typeof E?.offset=="number"?E.offset:null;if(oe==null||me==null)return!1;const Re=m.target,Ue=Re&&Array.isArray(Re.segments)?Re.segments:[];for(const Ke of Ue){const Fe=typeof Ke?.blockId=="string"?Ke.blockId:null;if(!Fe)continue;const Xe=Ke.range,He=typeof Xe?.start=="number"?Xe.start:null,Ze=typeof Xe?.end=="number"?Xe.end:null;if(!(He==null||Ze==null)){if(z!==K){if(Fe===z&&Ze>oe||Fe===K&&He<me)return!0;continue}if(Fe===z){if(He===Ze){if(He>=oe&&He<=me)return!0;continue}if(Math.max(He,oe)<Math.min(Ze,me))return!0}}}return!1}const wc=(f,m)=>{const b=f?.hyperlinks;if(!b||typeof b.list!="function")return null;const I=Nr(m);if(!ac(I))return null;for(const E of I){const z={kind:"block",nodeType:"paragraph",nodeId:E},{value:K}=Vr(`hyperlinks:${E}`,At(),()=>b.list({within:z}),me=>me&&typeof me=="object"?me:null),oe=(K&&Array.isArray(K.items)?K.items:[]).find(me=>qu(me,m));if(oe)return oe}return null},Ea=(f,m,b)=>{if(f.link)return wc(m,b)!=null;if(f.list?.mode==="toggle-seed"&&f.list.seed)return kc(m,b)===f.list.seed;const I=G(f);if(I!==null)return I;const E=r.get(f.id),z=ya(b);if(z&&E?.selectionSignature===z)return E.active;const K=Hu(f,b);return K!==null?K:yH(f,b)},Yu=(f,m,b,I)=>{if(f.inline&&mb(f.inline.key)){const E=R(f);if(E!==void 0)return E;const z=I[f.inline.key];if(z!==void 0)return z;const K=ya(b),oe=K?n.get(f.inline.key):void 0;if(K&&oe?.selectionSignature===K)return oe.value}if(f.id==="linked-style"){const{style:E}=ct(b,ze().cache);return!E.styleId||E.mixed?void 0:{styleId:E.styleId,styleName:E.styleName}}if(f.id==="text-align")return Ls(m,b);if(f.id==="link")return M(m,b)??void 0},Cc=(f,m,b)=>{const I=f?.lists;if(!I)return{value:null,status:"ready"};const E=b.storyType==="body",z=typeof I.getStateInStory=="function"?()=>I.getStateInStory({target:va(m),story:b}):E&&typeof I.getState=="function"?()=>I.getState({target:va(m)}):null;if(!z)return{value:null,status:"ready"};const{value:K,status:oe}=Vr(`lists:${kr(b)}:${m}`,At(),z,me=>me&&typeof me=="object"?me:null);return{value:K?.success===!0?K:null,status:oe}},Jf=(f,m,b)=>Cc(f,m,b).value,Xu=(f,m,b)=>{const I=Jf(f,m,b);return!I||I.isListItem!==!0?null:I.seed==="bullet"||I.seed==="ordered"?I.seed:null},Fo=(f,m,b)=>{const I=Cc(f,m,b),E=I.value;return{value:E&&typeof E.isListItem=="boolean"?E.isListItem:null,status:I.status}},kc=(f,m)=>{const b=Nr(m);if(b.length===0||!ac(b))return null;const I=Ki(m),E=Xu(f,b[0],I);if(E!=="bullet"&&E!=="ordered")return null;for(const z of b.slice(1))if(Xu(f,z,I)!==E)return null;return E},Ta=(f,m,b)=>{if(!f)return{value:null,status:"ready",refreshing:!1};const I=kr(b),E=I==="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 z=`node:${I}:${m}`,K=At(),oe=Vr(z,K,()=>E?f.getNodeById({nodeId:m,nodeType:"paragraph"}):f.getNode(vo(m,b)),Re=>Re&&typeof Re=="object"?Re:null),me=ee.get(z);return{...oe,refreshing:oe.status==="stale"&&me?.inflightToken===K&&me.failedToken!==K}},Sc=f=>f==="left"||f==="center"||f==="right"||f==="justify"?f:void 0,$f=f=>f==="start"||f==="end"||f==="distributed"||f==="numTab"||f==="lowKashida"||f==="mediumKashida"||f==="highKashida"||f==="thaiDistribute",_l=(f,m)=>{const b=x(),I=b?.readMountedProjectionBlocksByIds;if(typeof I!="function")return null;const E=qi(f),z=Lt(()=>E?I.call(b,[...m],E):I.call(b,[...m]),null);if(!Array.isArray(z))return new Map;const K=yb(z),oe=new Map;for(const me of m){const Re=K.find(Xe=>cc(Xe,me));if(!Re)continue;const Ue=Re.attrs,Ke=Sc(Ue?.alignment),Fe=R9(Ue);oe.set(me,Ke??(Fe==="rtl"?"right":"left"))}return oe},_c=(f,m,b,I)=>{const{value:E,status:z,refreshing:K}=Ta(f,m,b),oe=I?.get(m);if(z==="pending")return oe?{status:"uniform",value:oe}:{status:"pending"};if(z==="stale"&&!K)return{status:"pending"};if(z==="stale"&&oe)return{status:"uniform",value:oe};if(z==="stale"&&I&&!oe)return{status:"unavailable"};if(!E)return{status:"unavailable"};const me=E.node;if(!me)return{status:"unavailable"};const Re=me.kind;if(Re!=="paragraph"&&Re!=="heading")return{status:"unavailable"};const Ue=me[Re];if(!Ue||typeof Ue!="object")return{status:"unavailable"};const Ke=Ue.props?.alignment;if(Ke==null)return oe?{status:"uniform",value:oe}:{status:"unavailable"};const Fe=Sc(Ke);return Fe?{status:"uniform",value:Fe}:$f(Ke)&&oe?{status:"uniform",value:oe}:{status:"unavailable"}},Zu=(f,m)=>{const b=Nr(m);if(b.length===0||!ac(b))return{status:"unavailable"};const I=Ki(m),E=_l(m,b),z=_c(f,b[0],I,E);if(z.status!=="uniform")return z;for(const K of b.slice(1)){const oe=_c(f,K,I,E);if(oe.status!=="uniform")return oe;if(oe.value!==z.value)return{status:"mixed"}}return z},Qu=f=>{const m=Nr(f);return m.length===0?null:`${kr(Ki(f))}:${m.join(",")}`},Ls=(f,m)=>{const b=Zu(f,m),I=b.status==="uniform"?b.value:void 0,E=o;if(!E)return I;const z=Qu(m);return z&&z!==E.selectionSignature?(o=null,I):!z||!E.settled?E.value:b.status!=="pending"?(o=null,I):E.value},fo=(f,m)=>{const b=Sc(m),I=Qu(f),E=Nr(f);if(!b||!I||E.length===0)return null;const z=++i;return o={selectionSignature:I,value:b,generation:z,settled:!1,canReconcile:ac(E)},Xt(),z},Ju=(f,m)=>{if(f==null)return;const b=o;if(!(!b||b.generation!==f)){if(!yo(m)){o=null;return}if(!b.canReconcile){o=null;return}b.settled=!0}},Ps=async(f,m,b)=>{const I=f?.lists;if(!I)return null;try{const E=b.storyType==="body",z=typeof I.getStateInStory=="function"?await I.getStateInStory({target:va(m),story:b}):E&&typeof I.getState=="function"?await I.getState({target:va(m)}):null,K=z&&typeof z=="object"?z:null;return!K||K.success!==!0||typeof K.isListItem!="boolean"?null:K.isListItem}catch{return null}},Al=(f,m,b)=>{const I={resolved:!1,seed:null},E=f?.lists;if(!E)return I;const z=b.storyType==="body",K=typeof E.getStateInStory=="function"?()=>E.getStateInStory({target:va(m),story:b}):z&&typeof E.getState=="function"?()=>E.getState({target:va(m)}):null;if(!K)return I;const oe=me=>{const Re=me&&typeof me=="object"?me:null;return!Re||Re.success!==!0||typeof Re.isListItem!="boolean"?I:{resolved:!0,seed:Re.isListItem===!0&&(Re.seed==="bullet"||Re.seed==="ordered")?Re.seed:null}};try{const me=K();return Cr(me)?Promise.resolve(me).then(oe,()=>I):oe(me)}catch{return I}},Ac=async(f,m,b)=>{if(!f)return null;try{const I=!b||b.storyType==="body",E=b&&typeof f.getNode=="function"?await f.getNode(vo(m,b)):I&&typeof f.getNodeById=="function"?await f.getNodeById({nodeId:m,nodeType:"paragraph"}):null;return GV(E&&typeof E=="object"?E:null)}catch{return null}},eh=(f,m,b,I,E,z)=>{if(f.mutates&&b)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.documentReadonly},"builtin");const K=Nr(I);if(K.length===0)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.selectionRequired},"builtin");const oe=f.docRoute?yr(m,f.docRoute):null,me=yr(m,"format.paragraph.setIndentation"),Re=yr(m,"format.paragraph.clearIndentation"),Ue=f.list?.mode,Ke=Ue==="indent"?me!=null:me!=null||Re!=null,Fe=Ki(I);let Xe=null;if(Fe.storyType!=="body"){Xe=[];for(const He of K){const{value:Ze,status:Qe}=Fo(m,He,Fe);if(Ze===null)return Qe!=="ready"&&(oe!=null||Ke)?ln({enabled:!0,active:E,supported:!0,value:z},"builtin"):ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin");Xe.push(Ze)}}if(Xe?.some(He=>He===!0)){const He=Ue==="indent"?"lists.indentRange":"lists.outdentRange",Ze=Xn()!=="suggesting"&&Xe.every(ot=>ot===!0)&&yr(m,He)!=null,Qe=Ue==="outdent"&&yr(m,"lists.outdentInStory")!=null;if(!Ze&&!Qe)return ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin")}for(const[He,Ze]of K.entries()){const Qe=Xe?{value:Xe[He]??null,status:"ready"}:Fo(m,Ze,Fe),ot=Qe.value;if(ot===!0){if(oe!=null)return ln({enabled:!0,active:E,supported:!0,value:z},"builtin");continue}if(ot===!1&&Ke){if(Fe.storyType!=="body"&&typeof m?.getNode!="function")continue;return ln({enabled:!0,active:E,supported:!0,value:z},"builtin")}if(ot===null)return Qe.status!=="ready"&&(oe!=null||Ke)?ln({enabled:!0,active:E,supported:!0,value:z},"builtin"):ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin")}return ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin")},A=(f,m,b,I,E,z)=>{if(f.mutates&&b)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.documentReadonly},"builtin");const K=Nr(I);if(K.length===0)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.selectionRequired},"builtin");const oe=Ki(I),me=m?.lists;if(!(typeof me?.getStateInStory=="function"||oe.storyType==="body"&&typeof me?.getState=="function"))return ln({enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");if(!ac(K))return ln(oe.storyType==="body"&&yr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");const Re=K.map(Xe=>Cc(m,Xe,oe));if(Re.some(({status:Xe})=>Xe!=="ready"))return ln({enabled:!0,active:E,supported:!0,value:z},"builtin");if(Re.some(({value:Xe})=>Xe===null))return ln({enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");const Ue=f.list?.seed,Ke=Re.every(({value:Xe})=>Xe?.isListItem===!0&&Xe.seed===Ue);if(oe.storyType==="body")return ln(!Ke||yr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");const Fe=yr(m,"lists.removeInStory");return ln(Ke&&Fe?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin")},M=(f,m)=>{const b=wc(f,m)?.properties?.href;return typeof b=="string"?b:null},Q=f=>{if(!_())return ln({enabled:!1,active:!1,supported:!1,reason:ut.notReady},"builtin");const m=f.instanceRoute;return typeof t?.[m]!="function"?ln({enabled:!1,active:!1,supported:!1,reason:ut.operationUnavailable},"builtin"):ln({enabled:!0,active:re(f),supported:!0,value:de(f)},"builtin")},re=f=>{const m=t?.config??void 0;return f.valueFrom==="ruler"?!!m?.rulers:f.valueFrom==="formattingMarks"?!!m?.layoutEngineOptions?.showFormattingMarks:!1},ae=(f,m,b)=>{if(b)return ln({enabled:!1,active:!1,supported:!0,reason:ut.documentReadonly},"builtin");const I=Ne();return I!=null&&(!f.table.requiresCell||I.cellNodeId!=null)?(f.docRoute?yr(m,f.docRoute):null)==null?ln({enabled:!1,active:!1,supported:!1,reason:Di(m)},"builtin"):ln({enabled:!0,active:!1,supported:!0},"builtin"):ln({enabled:!1,active:!1,supported:!0,reason:ut.tableContextUnavailable},"builtin")},de=f=>{if(f.valueFrom==="zoom")return bi().value;if(f.valueFrom==="documentMode")return Xn();if(f.valueFrom==="measurementUnit")return Kr();if(f.valueFrom==="ruler"||f.valueFrom==="formattingMarks")return re(f)},fe=(f,m)=>f.id==="zoom"?typeof m=="number"&&Number.isFinite(m)&&m>0:f.id==="document-mode"?m==="editing"||m==="suggesting"||m==="viewing":f.id==="measurement-unit"?m==="in"||m==="cm":!0,le=()=>[...new Set([...EN,...he.keys()])],Ae="Normal",Le={ready:!1,status:"ready",catalogRevision:null,quickGallery:[],activeParagraphStyleId:null,activeParagraphStyleName:null,mixedSelection:!1,sourceStatus:null,diagnostics:[]},Me=f=>{const m=y()?.styles;return!m||typeof m.getCatalog!="function"?{value:null,status:"ready"}:Vr(`styles:catalog:${JSON.stringify(f??{})}`,At(),()=>m.getCatalog(f),b=>b&&typeof b=="object"?b:null)},ze=()=>{const f=Me({includePreview:!0});if(!f.value)return{cache:null,status:f.status};const m=Me({view:"quickGallery",includePreview:!0}),b=m.value?m.value.items:f.value.styles.filter(E=>E.visibility.quickGallery),I=new Map;for(const E of f.value.styles)I.set(E.id,E);return{cache:{full:f.value,quickGallery:b,byId:I},status:Mu(f.status,m.status)}},tt=(f,m,b)=>{const{value:I,status:E}=Ta(f,m,b);if(!I)return{ok:!1,styleRef:null,status:E};const z=I.node;if(!z||typeof z!="object")return{ok:!1,styleRef:null,status:E};const K=z.kind,oe=typeof K=="string"?z[K]:void 0,me=oe&&typeof oe=="object"?oe.styleRef:void 0;return{ok:!0,styleRef:typeof me=="string"&&me.length>0?me:null,status:E}},ct=(f,m)=>{const b=[],I=y();if(!I)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=Nr(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(!ac(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 z=m?.full.defaults.paragraphStyleId??(m?Ae:null),K=new Set;let oe=0,me=0,Re=0,Ue="ready";const Ke=Ki(f);for(const He of E){const Ze=tt(I,He,Ke);if(Ue=Mu(Ue,Ze.status),!Ze.ok){me+=1;continue}if(!Ze.styleRef&&!z){Re+=1;continue}const Qe=Ze.styleRef??z;if(!Qe){Re+=1;continue}oe+=1,K.add(Qe)}if(oe===0){const He=Re>0&&me===0;return b.push({severity:"warning",code:He?"active-style-default-unavailable":"active-style-read-failed",message:He?"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 Fe=me+Re;if(Fe>0)return b.push({severity:"warning",code:"active-style-partial",message:`Active paragraph style resolved from ${oe} of ${oe+Fe} selected blocks; ${Fe} could not be read, so the active style is unavailable.`}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:Ue};if(K.size>1)return{style:{styleId:null,styleName:null,mixed:!0,diagnostics:b},status:Ue};const Xe=[...K][0];return{style:{styleId:Xe,styleName:m?.byId.get(Xe)?.name??null,mixed:!1,diagnostics:b},status:Ue}},qe=f=>{if(!_())return Le;const{cache:m,status:b}=ze(),{style:I,status:E}=ct(f,m);let z;return m?z=I.diagnostics.length===0?m.full.diagnostics:[...m.full.diagnostics,...I.diagnostics]:z=[{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)."},...I.diagnostics],{ready:!0,status:Mu(b,E,f.status),catalogRevision:m?.full.revision??null,quickGallery:m?.quickGallery??[],activeParagraphStyleId:I.styleId,activeParagraphStyleName:I.styleName,mixedSelection:I.mixed,sourceStatus:m?.full.sourceStatus??null,diagnostics:z}},Dt=()=>{const f=Xn(),m=Kf();m.status==="ready"&&Wf(m),B(m);const b=ya(m);for(const[I,E]of r)(!b||E.selectionSignature!==b||E.settled&&m.status==="ready")&&r.delete(I);return{ready:_()!=null,documentMode:f,document:pc(),selection:m,toolbar:{context:f,commands:ju(m),copyFormatActive:h.mode!=="idle"},comments:qf(m),trackChanges:bl(m),contentControls:Aa(m),zoom:bi(),fonts:yi(),styles:qe(m)}},gt=f=>{const m=ya(f);m&&a&&m!==a&&(n.clear(),r.clear()),m&&(a=m)};let Bt=null,xt=null,St=null,Zn=null,rn=!1;const hn=()=>{if($||rn)return;rn=!0;const f=()=>{rn&&(rn=!1,!$&&Xt())};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},mr=()=>{const f=T();if(f!==St&&(Zn&&(Zn(),Zn=null),St=f,!(!f||typeof f.subscribe!="function")))try{const m=f.subscribe(()=>hn());typeof m=="function"&&(Zn=m)}catch{St=null}};let xr=null,tr=null,No=null,$r=null,it=null,dn=null;const eo=()=>{const f=_()?.host,m=Lt(f?.getHandles?()=>f.getHandles():void 0,null)?.editing?.selection;return m&&typeof m.subscribe=="function"?m:null},wi=()=>{const f=eo();if(f!==Bt&&(xt&&(xt(),xt=null),Bt=f,!!f))try{const m=f.subscribe(b=>{yt+=1,vl(b),Xt()});typeof m=="function"&&(xt=m)}catch{Bt=null}},So=()=>{const f=_()?.host,m=Lt(f?.getHandles?()=>f.getHandles():void 0,null)?.review;return m&&typeof m.subscribe=="function"?m:null},Ci=f=>f?typeof f.getActiveReviewTarget=="function"?Lt(()=>f.getActiveReviewTarget(),null):typeof f.getSnapshot=="function"?Lt(()=>f.getSnapshot(),null)?.activeReviewTarget??null:null:null;let _o=0;const Bo=(f,m)=>{const b=(m&&typeof m=="object"?m:null)?.lastInteractionRejection;if(_o>0&&f==null&&b&&typeof b=="object"&&b.code==="review-target-invalidated"&&b.detail==="not-painted")return!1;const I=f&&typeof f=="object"?f:null;let E=null;if(I?.entityType==="trackedChange"&&typeof I.entityId=="string"&&I.entityId.length>0){const z=I.entityId,K=I.story&&typeof I.story=="object"?I.story:void 0,oe=Qi(),me=(oe?K?Pu(oe,K).toPublicId(z):ga(oe).toPublicId(z):null)??z,Re=K&&kr(K)!==kr(null)?K:void 0;E={id:me,...Re?{story:Re}:{},...typeof I.paintedEntityId=="string"&&I.paintedEntityId.length>0?{paintedEntityId:I.paintedEntityId}:me!==z?{paintedEntityId:z}:{}}}return f==null&&E==null&&ce!=null&&Tt(ce)||st(ce,E)?!1:(je(E),!0)},Il=()=>{const f=So();if(f===xr)return;if(tr&&(tr(),tr=null),xr=f,!f){Bo(null);return}let m=!0;try{const b=f.subscribe(I=>{const E=I&&typeof I=="object"?I:null;!Bo(E&&Object.prototype.hasOwnProperty.call(E,"activeReviewTarget")?E.activeReviewTarget:Ci(f),I)||m||Xt()});typeof b=="function"&&(tr=b),Bo(Ci(f))}catch{xr=null}finally{m=!1}},$i=()=>{if(Bt||Xn()!=="viewing")return null;const f=_()?.mount?.container,m=(f&&typeof f=="object"&&"ownerDocument"in f?f.ownerDocument??null:null)??globalThis.document??null;return m&&typeof m.addEventListener=="function"?m:null},Ds=()=>{const f=$i();if(f===it||(dn&&(dn(),dn=null),it=f,!f))return;const m=()=>{yt+=1,Xt()};f.addEventListener("selectionchange",m),f.addEventListener("pointerup",m,!0),f.addEventListener("mouseup",m,!0),dn=()=>{f.removeEventListener("selectionchange",m),f.removeEventListener("pointerup",m,!0),f.removeEventListener("mouseup",m,!0)}};Sa(),Bo(Ci(So()));let dt=Dt();a=ya(dt.selection);const Os=()=>{const f=_()?.host?.events,m=f&&typeof f.subscribe=="function"?f:null;if(m!==No&&($r&&($r(),$r=null),No=m,!!m))try{const b=m.subscribe(I=>{const E=I?.type;if(E==="review-mutation:started"){Pt(I.reviewMutation?.token);return}if(E==="review-mutation:aborted"){Kt(I.reviewMutation?.token),we();return}if(E==="mutation:rejected"&&I.reviewMutation&&(Kt(I.reviewMutation.token),we()),E==="mutation:committed"&&I.reviewMutation&&Kt(I.reviewMutation.token),E==="source:complete"||E==="source:signals-complete"){Nt!==null&&(Pe(),Br.onRender(!0));return}if((E==="mutation:committed"||E==="collaboration:remote-changed")&&(Ln=Date.now()),E==="mutation:committed"&&(Pe(),Wt={}),E==="mutation:committed"||E==="save:completed"||E==="collaboration:remote-changed"){const z=E==="mutation:committed"?Gk(I):null,K=E==="mutation:committed"&&Br.getPendingIds().size>0;if(z?.allResolved){Br.reset(),cn([]),Nt=null,Pn(I.receipt);return}z?.removedIds.size&&br(new Set(z.removedIds),I.receipt);const oe=z?.reconcileMode==="authoritative"&&z.upsertIds.size>0;if(oe&&(Es(),Pe(),Nt=At(),Xt()),z?.upsertIds.size||K){const Ke=I.origin==="history"?null:I.receipt,Fe=_()?.documentMutationReadiness,Xe=typeof Ke?.txId=="string"&&Ke.txId.length>0&&typeof Fe?.whenPainted=="function",He=I.origin==="history"&&typeof Fe?.getRenderEpoch=="function"?Lt(()=>Fe.getRenderEpoch.call(Fe),null):null,Ze=I.origin==="history"&&typeof Fe?.whenPainted=="function",Qe={upsertIds:z?.upsertIds??new Set,removedIds:new Set,reconcileMode:z?.reconcileMode==="authoritative"?"authoritative":"targeted"};Xe?Br.enqueueAfterPaint(Qe,()=>Fe.whenPainted.call(Fe,Ke)):Ze?Br.enqueueAfterPaint(Qe,()=>Fe.whenPainted.call(Fe,typeof He=="number"?{afterEpoch:He}:void 0)):(Br.enqueue(Qe),Br.onRender(K))}if(oe)return;const me=E==="mutation:committed"&&Mi(I)||E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0;if(me&&(Bn=Date.now()),E==="mutation:committed"&&me){ml();return}if(z?.removedIds.size&&z.upsertIds.size===0)return;(E==="collaboration:remote-changed"||E==="mutation:committed"&&!me)&&_s();const Re=E==="collaboration:remote-changed"&&Array.isArray(I.changedPartUris)&&I.changedPartUris.some(Ke=>typeof Ke=="string"&&RV.has(Ke)),Ue=E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0&&uc();Re&&!me&&(sr=!0),Es(),(Re||Ue)&&wa("comments"),Xt()}});typeof b=="function"&&($r=b)}catch{No=null}},Xt=()=>{if($)return;rn=!1,Sa(),wi(),mr(),Il(),Ds(),Os();const f=Dt();gt(f.selection),dt=f;for(const m of[...Ye])m(dt)},xa=[],es=[],Ic=f=>{for(const m of f)try{m()}catch{}},El=()=>Ic(xa),Ec=()=>Ic(es),Tl=[];((f,m)=>{if(!(!f||typeof f.on!="function"))for(const b of m){const I=b==="active-editor-change"?()=>{El(),Ec(),Xt()}:b==="document-replaced"?E=>{const z=E&&typeof E=="object"?E:null,K=z?.editor,oe=z?.host,me=!!K&&K===_(),Re=!!oe&&oe===x();!me&&!Re||(Ec(),ee.clear(),Es(),Xt())}:()=>Xt();try{f.on(b,I),Tl.push(()=>{try{typeof f.off=="function"&&f.off(b,I)}catch{}})}catch{}}})(t,_V),wi(),mr(),Il(),Ds(),Os();const Fs=(f,m=cV)=>({get:()=>f(dt),subscribe:b=>{let I=f(dt);const E=z=>{const K=f(z);m(I,K)||(I=K,b(K))};return Ye.add(E),()=>Ye.delete(E)}}),Ao=f=>Fs(f),oi=f=>{const m=b=>{const I=z=>{try{b(z)}catch{}},E=f.subscribe(I);return I(f.get()),E};return{get:()=>f.get(),getSnapshot:()=>f.get(),observe:m,subscribe:b=>m(I=>b({snapshot:I}))}};function th(f){return f&&typeof f=="object"&&typeof f.id=="string"?String(f.id):null}function xc(f){const m=qi(f);return m&&kr(m)!==kr(null)?m:void 0}function jt(f,m){return{kind:"id",id:f,...m?{story:m}:{}}}function qn(f){if(f.empty)return null;const m=f.selectionTarget,b=m?.start,I=m?.end;if(m?.kind!=="selection"||b?.kind!=="text"||I?.kind!=="text"||typeof b.blockId!="string"||b.blockId!==I.blockId||!Number.isInteger(b.offset)||!Number.isInteger(I.offset)||b.offset<0||I.offset<0||b.offset===I.offset)return null;const E=Math.min(b.offset,I.offset),z=Math.max(b.offset,I.offset),K=qi(f);return{kind:"range",coordinateSpace:m.coordinateSpace==="tracked"?"tracked":"visible",range:{kind:"text",...K?{story:K}:{},segments:[{blockId:b.blockId,range:{start:E,end:z}}]}}}function L(f,m){if(kr(m)!==kr(null))return;const b=y()?.trackChanges,I=b?.list;if(typeof I!="function")return;const E=Lt(()=>I.call(b),null);if(Cr(E)||!E||typeof E!="object")return;const z=E.items;if(Array.isArray(z))return z.map(dl).find(K=>K!=null&&Wi(K,f,m))}function H(f,m){const b=Ce(f.quotedText);if(!b)return!1;const I=km(m);return[I.insertedText,I.deletedText,I.excerpt].some(E=>Ce(E)===b)}function Ce(f){return typeof f=="string"?f.replace(/\s+/g," ").trim():""}function De(){const f=dt.selection.activeChangeIds[0];if(!f)return"unavailable";const m=qi(dt.selection),b=(dt.trackChanges.status==="ready"?dt.trackChanges.items.find(K=>Wi(K,f,m)):void 0)??L(f,m)??Qi()?.find(K=>Wi(K,f,m));if(!b)return"unavailable";const I=km(b),E=I.type,z=I.grouping;return H(dt.selection,b)?"id":E==="replacement"&&z==="replacement-pair"||(E==="insertion"||E==="deletion"||E==="insert"||E==="delete")&&z==="standalone"?"range":"id"}function pt(f,m,b,I){const E=()=>Rb(f,jt(b,I),b,I);try{const z=Rb(f,m,null);return Cr(z)?qr(Promise.resolve(z).then(K=>yo(ks(K))?K:E())):qr(yo(ks(z))?z:E())}catch{return!1}}function fn(f,m){if(f.scope==="all")return{target:{kind:"all"},changeId:null};if(typeof m=="string"&&m.length>0)return{target:{kind:"id",id:m},changeId:m};if(m&&typeof m=="object"){const E=m;if(E.target&&typeof E.target=="object"){const K=E.target;return{target:K,changeId:th(K),story:K.story}}const z=typeof E.changeId=="string"?E.changeId:E.id;if(typeof z=="string"&&z.length>0)return{target:jt(z,E.story),changeId:z,story:E.story}}const b=dt.selection.activeChangeIds[0],I=xc(dt.selection);return b?{target:jt(b,I),changeId:b,story:I}:null}function xn(f,m){if(f.scope==="id"&&m==null){if(dt.selection.activeChangeIds.length>1)return ih(f.kind,{kind:"ids",ids:dt.selection.activeChangeIds},null);if(dt.selection.activeChangeIds.length===1&&!dt.selection.empty&&dt.selection.selectionTarget){const I=De();if(I==="unavailable")return!1;if(I==="range"){const E=qn(dt.selection),z=xc(dt.selection);return E?pt(f.kind,E,dt.selection.activeChangeIds[0],z):!1}if(I==="id"){const E=dt.selection.activeChangeIds[0],z=qi(dt.selection),K=z&&kr(z)!==kr(null)?z:void 0;return xb(f.kind,K?{id:E,story:K}:E)}}}const b=fn(f,m);return b?ih(f.kind,b.target,b.changeId,b.story):!1}function Yn(f,m){const b=T()?.lists,I=b?.apply;if(typeof I!="function")return!1;const{behavior:E,preset:z,continuity:K}=typeof m=="string"?EV(m):m&&typeof m=="object"?m:{},oe={kind:f,behavior:E??"toggle"};z!==void 0&&(oe.preset=z),K!==void 0&&(oe.continuity=K);try{return qr(I.call(b,oe))}catch{return!1}}let pn=Promise.resolve(!1),gn=null,bn=Promise.resolve(!1);const Rr=async f=>{if(!Sm(f))return f;const m=_()?.documentMutationReadiness,b=m?.whenPainted;if(typeof b!="function")return f;const I=typeof f.txId=="string"?f.txId:void 0;try{await b.call(m,I?{txId:I}:void 0)}catch{}return f},zn=f=>{if(Cr(f)){const b=Promise.resolve(f);return{immediate:!0,committed:b.then(I=>ks(I),()=>!1),settled:b.then(I=>Rr(ks(I)),()=>!1)}}const m=ks(f);return{immediate:m,committed:Promise.resolve(m),settled:Rr(m)}},Ra=()=>{const f=s.shift();if(!f){u=!1,d?.(),d=null;return}try{f.resolve($?!1:f.mutate())}catch{f.resolve(!1)}},Ma=()=>{let f=!1;return()=>{f||(f=!0,Ra())}},ii=(f,m)=>{if(!u){u=!0,c=new Promise(z=>{d=z});try{return{result:m(),release:Ma()}}catch(z){throw u=!1,d?.(),d=null,z}}const b=s.find(z=>z.key===f);if(b)return b.mutate=m,{result:b.result,release:()=>{}};let I;const E=new Promise(z=>{I=z});return s.push({key:f,mutate:m,result:E,resolve:I}),{result:E,release:Ma()}},xl=new Set(["create.tableOfContents"]),Rl=f=>hr(`Tracked authoring is not supported for ${f}.`),nh=f=>{if(Xn()==="suggesting")return xl.has(f)?Rl(f):{changeMode:"tracked"}},Em=()=>Xn()==="suggesting"?aH:wb,Hr=(f,m,b)=>{const I=nh(f);return I&&I.success===!1?I:I?m(b,I):m(b)},Sb=(f,m,b,I)=>{const E=f.inline;if(!E)return;const z=ks(I);if(z===!1||typeof z=="object"&&z&&z.success===!1)return;if(E.kind==="clear"){n.clear();return}if(E.kind==="toggle"||!mb(E.key))return;const K=ya(m);if(!K)return;const oe=YV(E.key,b.value);if(oe==null){n.delete(E.key);return}n.set(E.key,{selectionSignature:K,value:oe})},_b=(f,m,b,I)=>!f.inline||f.inline.kind==="toggle"?I:Cr(I)?Promise.resolve(I).then(E=>(Sb(f,m,b,E),E)):I,rh=(f,m,b,I)=>{if(f.inline?.kind!=="toggle"||!yo(ks(I))||typeof b.value!="boolean"&&b.value!==null)return null;const E=ya(m);if(!E)return null;const z=++l;return r.set(f.id,{selectionSignature:E,active:b.value===!0,generation:z,settled:!1}),Xt(),z},nr=(f,m,b)=>{if(m==null)return;const I=r.get(f.id);if(!(!I||I.generation!==m)){if(!yo(b)){r.delete(f.id);return}I.settled=!0}},$u=(f,m)=>f.then(b=>(m?.(b),Go(),b),()=>(m?.(!1),Go(),!1)),qr=(f,m)=>{const b=gn;if(gn=null,b)return pn=$u(b,m),ks(f);if(Cr(f))return pn=$u(zn(f).settled,m),!0;const I=ks(f);return Sm(I)&&typeof _()?.documentMutationReadiness?.whenPainted=="function"?(pn=$u(Rr(I),m),I):(m?.(I),pn=Promise.resolve(I),Go(),I)},Tm=(f,m)=>!f||typeof f!="object"?m:f,La=(f,m=hr("Document API operation failed."))=>{if(Cr(f))return Promise.resolve(f).then(I=>La(I,m),()=>m);const b=Tm(f,m);return Es(),Sm(b)&&typeof _()?.documentMutationReadiness?.whenPainted=="function"?($u(Rr(b)),Xt(),b):(Xt(),b)},xm=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const oe=I(K);if(oe)try{const me=zn(Hr(f,m,oe));E.push(me.immediate),z.push(me.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return gn=z.length?Promise.all(z).then(K=>pi(K)):null,pi(E)},Rm=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const oe=I(K);if(oe)try{const me=zn(Hr(f,m,oe));E.push(me.immediate),z.push(me.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return gn=z.length?Promise.all(z).then(K=>pi(K)):null,pi(E)},ed=(f,m,b,I=dt.selection)=>{const E=nh(f);return E&&E.success===!1?E:I.selectionTarget?m(b,{...E??{},offsetSpace:"selection"}):E?m(b,E):m(b)},Ab=(f,m,b,I)=>{const E=vo(m,I);switch(f.kind){case"alignment":{const z=b;return z!=="left"&&z!=="center"&&z!=="right"&&z!=="justify"?null:{target:E,alignment:z}}case"spacing-line":{const z=typeof b=="number"?b:Number(b);return!Number.isFinite(z)||z<=0?null:{target:E,line:z,lineRule:"auto"}}case"style":if(b&&typeof b=="object"){const z=b.role;if(z&&typeof z=="object")return{target:E,role:z}}return typeof b!="string"||b.trim()===""?null:{target:E,styleId:b};case"direction":{const z=f.fixedValue;return z!=="ltr"&&z!=="rtl"?null:{target:E,direction:z}}default:return null}},Mm=(f,m)=>{const b=f.inline,I=bb(f),E=x();if(!b||typeof E?.setPendingInlineFormat!="function")return!1;if(b.kind==="clear")return Z(),!0;if(!I)return!1;let z;if(b.kind==="toggle")z=!Ea(f,y(),dt.selection);else{const K=m&&typeof m=="object"&&"value"in m?m.value:m;if(b.kind==="value-number"){const oe=typeof K=="number"?K:Number(K);z=Number.isFinite(oe)&&oe>0?oe:null}else z=typeof K=="string"&&K.trim()!==""?K:null;if(z===null)return F(I,null),!0}return F(I,z),!0},Rc=()=>{const f=y(),{lockModesById:m}=xs(f?.contentControls,dt.selection);if(Ji(m))return!1;const b=[],I=[],E=Xe=>{const He=zn(Xe);b.push(He.immediate),I.push(He.settled)},z=(Xe,He,Ze)=>{try{E(Ze?Xe(He,Ze):Xe(He))}catch{b.push(!1),I.push(Promise.resolve(!1))}},K=ze().cache?.full.defaults.paragraphStyleId??Ae,oe=Fu(dt.selection);if(oe){const Xe=yr(f,"format.apply");if(Xe)try{E(ed("format.apply",Xe,{target:oe,inline:{...Em()}}))}catch{b.push(!1),I.push(Promise.resolve(!1))}}const me=yr(f,"format.paragraph.resetDirectFormatting"),Re=yr(f,"styles.paragraph.setStyleRef"),Ue=qi(dt.selection),Ke=!Ue||Ue.storyType==="body",Fe=yr(f,Ke?"lists.remove":"lists.removeInStory");for(const Xe of Nr(dt.selection)){const He=vo(Xe,Ue);if(me&&z(me,{target:He}),Fe)try{const Ze=va(Xe),Qe=zn(Fe(Ke?{target:Ze}:{target:Ze,story:Ue}));I.push(Qe.settled.then(ot=>yo(ot)?ot:!0))}catch{}Re&&z(Re,{target:He,styleId:K})}if(!oe&&Xn()!=="suggesting"){const Xe=yr(f,"format.paragraph.setMarkRunProps");if(Xe)for(const He of Nr(dt.selection))z(Xe,{target:vo(He,Ue),markRunProps:{bold:!1,italic:!1,strikethrough:!1,doubleStrikethrough:!1,smallCaps:!1,caps:!1,verticalAlign:"baseline"}})}return gn=I.length?Promise.all(I).then(Xe=>pi(Xe)):null,pi(b.length?b:[!1])},td=(f,m,b)=>{const I=Nr(dt.selection);if(I.length===0)return!1;const E=qi(dt.selection);return xm(f.docRoute,m,I,z=>Ab(f.blockParagraph,z,b,E))},oh=(f,m,b)=>{const I=y(),E=yr(I,"format.paragraph.setIndentation"),z=yr(I,"format.paragraph.clearIndentation"),K=f.list?.mode,oe=Ki(dt.selection),me=qi(dt.selection),Re=async Ue=>{const Ke=await Ps(I,Ue,oe);if(Ke===!0)return{kind:"list",routeToCall:f.docRoute,opToCall:m,input:{target:_A(Ue)}};if(Ke===null||me&&me.storyType!=="body"&&typeof I?.getNode!="function")return null;const Fe=await Ac(I,Ue,me),Xe={};if(Fe?.right!=null&&(Xe.right=Fe.right),Fe?.firstLine!=null&&(Xe.firstLine=Fe.firstLine),Fe?.hanging!=null&&(Xe.hanging=Fe.hanging),K==="indent")return E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:vo(Ue,me),left:Math.max(0,Fe?.left??0)+AA,...Xe}}:null;const He=Math.max(0,(Fe?.left??0)-AA);return He>0&&(Xe.left=He),Object.keys(Xe).length===0?z?{kind:"paragraph",routeToCall:"format.paragraph.clearIndentation",opToCall:z,input:{target:vo(Ue,me)}}:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:vo(Ue,me),left:0}}:null:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:vo(Ue,me),...Xe}}:null};return gn=(async()=>{const Ue=await Promise.all(b.map(He=>Re(He).catch(()=>null)));if(Ue.length===b.length&&Ue.every(He=>He?.kind==="list")&&Xn()!=="suggesting"){const He=K==="indent"?"lists.indentRange":"lists.outdentRange",Ze=yr(I,He);if(Ze)try{return await zn(Hr(He,Ze,{paraIds:b,story:oe})).settled}catch{return!1}}const Ke=oe.storyType!=="body"&&Ue.some(He=>He?.kind==="list"),Fe=Ke&&K==="outdent"?yr(I,"lists.outdentInStory"):null;if(Ke&&!Fe)return!1;const Xe=Ue.map(He=>{if(!He)return Promise.resolve(!1);try{return He.kind==="list"&&Fe?zn(Hr("lists.outdentInStory",Fe,{target:He.input.target,story:oe})).settled:zn(Hr(He.routeToCall,He.opToCall,He.input)).settled}catch{return Promise.resolve(!1)}});return pi(await Promise.all(Xe))})(),!0},Rt=(f,m)=>{const b=f.list,I=y(),E=Nr(dt.selection);if(E.length===0)return!1;const z=Ki(dt.selection),K=z.storyType==="body";if(b.mode==="indent"||b.mode==="outdent")return oh(f,m,E);const oe=b.seed,me=Ke=>{if(Ke.some(ot=>!ot.resolved))return{immediate:!1,settled:null};const Fe=Ke.every(ot=>ot.seed===oe);if(!Fe&&!K)return{immediate:!1,settled:null};const Xe=Fe?K?"lists.remove":"lists.removeInStory":f.docRoute,He=Fe?yr(I,Xe):m;if(!He)return{immediate:!1,settled:null};const Ze=[],Qe=[];return E.forEach((ot,nt)=>{if(!Fe&&Ke[nt]?.seed===oe)return;const Ot=Fe?{target:va(ot),...K?{}:{story:z}}:{target:va(ot),seed:oe};try{const Qt=zn(Hr(Xe,He,Ot));Ze.push(Qt.immediate),Qe.push(Qt.settled)}catch{Ze.push(!1),Qe.push(Promise.resolve(!1))}}),{immediate:pi(Ze),settled:Qe.length?Promise.all(Qe).then(ot=>pi(ot)):null}},Re=E.map(Ke=>Al(I,Ke,z));if(Re.some(Cr))return gn=Promise.all(Re).then(async Ke=>{const Fe=me(Ke);return Fe.settled?await Fe.settled:Fe.immediate}),!0;const Ue=me(Re);return gn=Ue.settled,Ue.immediate};function Gt(f){return f&&typeof f=="object"?f:{}}function _n(f){if(typeof f=="string")return f;const m=Gt(f);if(Object.prototype.hasOwnProperty.call(m,"href"))return m.href;if(Object.prototype.hasOwnProperty.call(m,"value"))return m.value}function _r(f,m){const b=Gt(f).text;return typeof b=="string"&&b.trim()!==""?b:m}function Ur(f){const m=Gt(f),b=m.capture&&typeof m.capture=="object"?m.capture:null;return m.target??b?.target??b?.selectionTarget??m.selectionTarget??m.textTarget??null}const ho=f=>{const m=y(),b=m?.hyperlinks;if(!b)return!1;const I=Gt(f),E=_n(f),z=Ur(f),K=typeof I.text=="string"?I.text:void 0,oe=typeof I.currentText=="string"?I.currentText:void 0,me=lc(I.hyperlinkTarget)?I.hyperlinkTarget:null,Re=lc(I.textTarget)?I.textTarget:null,Ue=wc(m,dt.selection),Ke=typeof me?.storyId=="string"&&typeof me?.hyperlinkNodeId=="string";if(Ke&&E===null){const Fe=b.remove;if(typeof Fe!="function")return!1;try{return Hr("hyperlinks.remove",Fe,{storyId:me.storyId,hyperlinkNodeId:me.hyperlinkNodeId,keepText:!0})}catch{return!1}}if(Ue&&E===null){const Fe=b.remove;if(typeof Fe!="function")return!1;try{return Hr("hyperlinks.remove",Fe,{target:Ue.address,mode:"unwrap"})}catch{return!1}}if((Ue||me)&&typeof E=="string"&&E.trim()!==""){const Fe=b.patch,Xe=b.updateTarget;if(!(!Ke&&Ue&&typeof Fe=="function")&&!(Ke&&typeof Xe=="function"))return!1;const He=typeof K=="string"&&K!==(Ke?oe:Ue?.text??oe),Ze=m?.text?.replace,Qe=He?Ke?Re:tH(Ue?.address):null,ot=He&&!!Qe&&typeof Ze=="function";if(He&&!ot)return!1;const nt=[],Ot=[];let Qt=null,on=null,Dn=null,Mr=!1;try{if(Ke){if(typeof Xe!="function")return!1;const Ar=Hr("hyperlinks.updateTarget",Xe,{storyId:me.storyId,hyperlinkNodeId:me.hyperlinkNodeId,newTarget:nH(E)});Mr=Cr(Ar);const jr=zn(Ar);if(!yo(jr.immediate))return!1;nt.push(jr.immediate),Ot.push(jr.settled),Qt=jr.immediate,on=jr.committed,Dn=jr.settled}else if(Ue){if(typeof Fe!="function")return!1;const Ar=Hr("hyperlinks.patch",Fe,{target:Ue.address,patch:{href:E}});Mr=Cr(Ar);const jr=zn(Ar);if(!yo(jr.immediate))return!1;nt.push(jr.immediate),Ot.push(jr.settled),Qt=jr.immediate,on=jr.committed,Dn=jr.settled}}catch{return!1}if(ot){const Ar=(Lr,Ko)=>yo(Ko)?pi([Lr,Ko]):yo(Lr)?Hf(Lr,Ko):Ko,jr=Lr=>{if(!yo(Lr))return Lr;try{const Ko=zn(Hr("text.replace",Ze,{target:Qe,text:K}));return yo(Ko.immediate)?Promise.all([Dn??Promise.resolve(Lr),Ko.settled]).then(([Ob,kU])=>Ar(Ob,kU)):Hf(Lr,Ko.immediate)}catch{return Hf(Lr,!1)}};if(Mr)return gn=(on??Promise.resolve(Qt??!1)).then(jr),pi(nt);try{const Lr=zn(Hr("text.replace",Ze,{target:Qe,text:K}));if(!yo(Lr.immediate))return Qt?Hf(Qt,Lr.immediate):Lr.immediate;nt.push(Lr.immediate),Ot.push(Lr.settled),gn=Promise.all([Dn??Promise.resolve(Qt??!1),Lr.settled]).then(([Ko,Ob])=>Ar(Ko,Ob))}catch{return Qt?Hf(Qt,!1):!1}}return!ot&&Ot.length>0&&(gn=Promise.all(Ot).then(Ar=>pi(Ar))),pi(nt)}if(typeof E=="string"&&E.trim()!==""){const Fe=E.trim(),Xe=b.wrap,He=WV(z),Ze=He.length>0?He:pb(dt.selection);if(Ze.length>0){if(typeof Xe!="function")return!1;try{return Rm("hyperlinks.wrap",Xe,Ze,Ot=>({target:Ot,link:{destination:{href:Fe}}}))}catch{return!1}}const Qe=b.insert,ot=_r(f,Fe);if(typeof Qe!="function"||ot.trim()==="")return!1;const nt=jf(z)??ul(dt.selection);if(!nt)return!1;try{return Hr("hyperlinks.insert",Qe,{target:nt,text:ot,link:{destination:{href:Fe}}})}catch{return!1}}return!1},ki=(f,m,b)=>{const I=f.create.kind,E=b&&typeof b=="object"?b:{};if(I==="table"){const K=Number(E.rows??E.rowCount),oe=Number(E.columns??E.cols??E.colCount);if(!Number.isInteger(K)||K<1||!Number.isInteger(oe)||oe<1)return!1;const me=ul(dt.selection),Re=me&&typeof me.blockId=="string"?{kind:"inParagraph",target:vo(me.blockId),offset:me.range?.start??0}:vb(dt.selection,"nodeId");try{return Hr(f.docRoute,m,{rows:K,columns:oe,at:Re})}catch{return!1}}if(I==="image"){const K=E.src??E.value;if(typeof K!="string"||K.trim()==="")return!1;const oe=ul(dt.selection),me=Ki(dt.selection),Re=me.storyType==="body"?null:me;let Ue;oe&&typeof oe.blockId=="string"?Ue={kind:"inParagraph",target:vo(oe.blockId,Re),offset:oe.range?.start??0}:(Ue=vb(dt.selection,"target"),Re&&Ue.kind==="after"&&(Ue={...Ue,target:{...Ue.target,story:Re}}));const Ke={src:K,at:Ue};Re&&(Ke.in=Ue.kind==="inParagraph"?P(Re)??Re:Re),typeof E.alt=="string"&&(Ke.alt=E.alt),typeof E.title=="string"&&(Ke.title=E.title),E.size&&typeof E.size=="object"&&(Ke.size=E.size);try{return Hr(f.docRoute,m,Ke)}catch{return!1}}const z={at:vb(dt.selection,"target")};typeof E.instruction=="string"&&(z.instruction=E.instruction),E.config&&typeof E.config=="object"&&(z.config=E.config);try{return Hr(f.docRoute,m,z)}catch{return!1}},Ml=(f,m)=>{const b=f.table,I=Ne();if(!I||b.requiresCell&&!I.cellNodeId)return!1;const E=uH(b.action,I);if(!E)return!1;try{if(b.action==="insert-row-before"||b.action==="insert-row-after"){const z=x(),K=(typeof z?.getHandles=="function"?z.getHandles():null)?.editing?.tables;if(typeof K?.insertRow!="function")return!1;const oe=nh(f.docRoute);return oe&&oe.success===!1?oe:oe?K.insertRow(E,oe):K.insertRow(E)}return Hr(f.docRoute,m,E)}catch{return!1}},nd=f=>!f||f.disposition!=="routed"?!1:!!(f.inline||f.blockParagraph||f.list||f.link||f.create),jH=f=>{const m=Gt(f);return!!(Ur(f)||lc(m.hyperlinkTarget)||lc(m.textTarget))},GH=(f,m,b)=>dt.selection.status!=="ready"?!1:_m(f)?.scope==="id"||!m||m.disposition!=="routed"?!0:m.inline?.kind==="clear"?Nr(dt.selection).length>0||Fu(dt.selection)!=null:m.inline?Fu(dt.selection)!=null||Nr(dt.selection).length>0:m.blockParagraph||m.list?Nr(dt.selection).length>0:m.link?jH(b)||pb(dt.selection).length>0||ul(dt.selection)!=null||Ea(m,y(),dt.selection):!0,WH=(f,m)=>{const b=_m(f),I=Tu(f);return b?.scope!=="id"&&!nd(I)?!1:!GH(f,I,m)},KH=(f,m)=>WH(f,m)?yl().then(()=>{}):null,Mc=(f,m,b)=>{if(gn=null,pn=Promise.resolve(!1),$)return!1;const I=he.get(f);if(I)try{return qr(I.execute(Bu(m,b)))}catch{return!1}const E=yA(f);if(E&&typeof T()?.lists?.apply=="function")return Yn(E,m);const z=_m(f);if(z)return xn(z,m);if(f==="copy-format")return qr(qH());const K=Tu(f);if(!K||K.disposition!=="routed")return!1;const oe=K.normalizePayload?K.normalizePayload(m):m;if(K.instanceRoute){if(!_()||!fe(K,oe))return!1;const Ke=t?.[K.instanceRoute];if(typeof Ke!="function")return!1;try{const Fe=K.fixedArg!==void 0?K.fixedArg:oe;return qr(Ke.call(t,Fe))}catch{return!1}}if(K.inline?.kind==="clear")return K.mutates&&Xn()==="viewing"?!1:qr(Rc());const me=K.docRoute;if(!me||K.mutates&&Xn()==="viewing")return!1;const Re=y(),Ue=yr(Re,me);if(!Ue)return!1;if(K.inline){const{lockModesById:Ke}=xs(Re?.contentControls,dt.selection);if(Ji(Ke))return!1;const Fe=Fu(dt.selection);if(!Fe)return dt.selection.empty===!1?qr(!1):qr(Mm(K,oe));const Xe=Ea(K,Re,dt.selection),He=lH(K.inline,Fe,oe,Xe);if(!He)return!1;let Ze=null;try{const Qe=_(),ot=Xn(),nt=()=>_()!==Qe||y()!==Re||Xn()!==ot?!1:ed(me,Ue,He),Ot=ya(dt.selection)??ic(dt.selection),Qt=K.inline.kind==="toggle"?ii(`${K.id}:${Ot}`,nt):null;Ze=Qt?.release??null;const on=Qt?Qt.result:nt(),Dn=rh(K,dt.selection,He,on),Mr=qr(_b(K,dt.selection,He,on),Ar=>{nr(K,Dn,Ar),Ze?.(),Ze=null});return K.inline.kind==="toggle"&&(bn=pn),Mr}catch{return Ze?.(),!1}}if(K.blockParagraph){const Ke=td(K,Ue,oe),Fe=K.blockParagraph.kind==="alignment"&&yo(Ke)?fo(dt.selection,oe):null;return qr(Ke,Xe=>{Ju(Fe,Xe)})}if(K.list)return qr(Rt(K,Ue));if(K.link)return qr(ho(oe));if(K.create)return qr(ki(K,Ue,oe));if(K.table)return qr(Ml(K,Ue));try{return qr(K.mutates?Hr(me,Ue,oe):Ue(oe))}catch{return!1}},Lm=()=>{g+=1,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:h.lastClickAt,pointerSelecting:!1,keyboardSelecting:!1};for(const f of p)f("idle");Xt()},qH=async()=>{const f=["bold","italic","underline","strikethrough"].filter(Ue=>dt.toolbar.commands[Ue]?.active===!0),m=await bn;await c;const b=yo(m)?f:[],I=500,E=Date.now();if(h.mode!=="idle"){if(h.mode==="armed"&&E-h.lastClickAt<I){h={...h,mode:"persistent",lastClickAt:E};for(const Ue of p)Ue("persistent");return Xt(),!0}return Lm(),!1}const z=E-h.lastClickAt<I,K=++g;h={...h,lastClickAt:E};const oe=await yl(),me=`${ic(oe)}:${At()}`,Re=await YH(null,oe,me&&me===k?v:void 0,b);if(K!==g)return!0;h={...h,mode:z?"persistent":"armed",snapshot:Re,sourceSelectionKey:ic(oe),lastClickAt:E};for(const Ue of p)Ue(h.mode);return Xt(),!0},YH=async(f,m,b,I=[])=>{const E=m?.target??f?.target;if(!E||E.kind!=="text")return null;const z=Array.isArray(E.segments)?E.segments:[];if(z.length===0)return null;const K=y();if(!K)return null;const oe=E.story;let me=null;for(const He of z){const Ze=(await Ms(vo(He.blockId,oe)))?.node??null;if(!Ze)continue;const Qe=Ib(Ze),ot=XH(Array.isArray(Qe?.inlines)?Qe.inlines:[],He.range);me?me=FA(me,ot):me=ot}const Re=me?uV(me):{},Ue={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strike"},Ke=new Set([...m?.activeMarks??(Array.isArray(f?.activeMarks)?f.activeMarks:[]),...I]);for(const[He,Ze]of Object.entries(Ue))Ke.has(He)&&(Re[Ze]=!0);const Fe=b??await Qf(m??Ts(f,"ready"));if(Fe.fontFamily&&(Re.fontFamily=Fe.fontFamily),Fe.color&&(Re.color=Fe.color),Fe.highlight&&(Re.highlight=Fe.highlight),Fe.fontSize){const He=Number.parseFloat(Fe.fontSize);Number.isNaN(He)||(Re.fontSize=He)}let Xe=null;if(z.length===1){const He=z[0],Ze=(await Ms(vo(He.blockId,oe)))?.node??null;Ze&&Ib(Ze)&&(Xe=await ZH(Ze,He.blockId,K,oe))}return{story:oe??null,inline:Re,paragraph:Xe}},Ib=f=>f?f.kind==="paragraph"?f.paragraph??null:f.kind==="heading"?f.heading??null:null:null,XH=(f,m)=>{const b=K=>{const oe=K.run;return typeof oe?.text=="string"?oe.text:""},I=K=>K.run?.props;if(m.start===m.end){let K=0;for(const oe of f){const me=b(oe),Re=K,Ue=K+me.length;if(K=Ue,m.start>=Re&&m.start<=Ue){const Ke=I(oe);return Ke?{...Ke}:{}}}return{}}let E=0;const z=[];for(const K of f){const oe=b(K),me=E,Re=E+oe.length;if(E=Re,Re<=m.start||me>=m.end)continue;const Ue=I(K);Ue&&z.push(Ue)}return z.length===0?{}:z.length===1?{...z[0]}:FA(z[0],...z.slice(1))},FA=(f,...m)=>{const b={...f};for(const I of m)for(const E of Object.keys(b)){if(!(E in I)){delete b[E];continue}const z=b[E],K=I[E];(typeof z!=typeof K||JSON.stringify(z)!==JSON.stringify(K))&&delete b[E]}return b},ZH=async(f,m,b,I)=>{const E=Ib(f),z=E.props??{},K=E.styleRef??null,oe=z.alignment??null,me=z.spacing??null,Re=z.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,Ke=z.markRunProps??null,Fe=z.numbering?.numId,Xe=typeof Fe=="string"?parseInt(Fe,10):typeof Fe=="number"?Fe:NaN,He=z.numbering?.level,Ze=isNaN(Xe)?null:{numId:Xe,...He!=null?{level:He}:{}};let Qe=null;if(Ze&&typeof b.lists?.getState=="function")try{const ot=await b.lists.getState({target:vo(m,I)});ot&&typeof b.lists?.getStyle=="function"&&(Qe=await b.lists.getStyle(ot)??null)}catch{}return{styleId:K,alignment:oe,spacing:me,indentation:Ue,markRunProps:Ke,numbering:Ze,listStyle:Qe}},NA=async()=>{if(h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;const f=y()?.selection,m=async()=>uo(typeof f?.current=="function"?await Promise.resolve(f.current({includeText:!0})):_a().value),b=()=>new Promise(K=>setTimeout(K,16)),I=8;let E=null,z="";for(let K=0;K<I;K+=1){if(K>0&&await b(),h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;if(E=await m(),!(!E||E.empty)&&(z=ic(E),z!==h.sourceSelectionKey))break}if(E&&!E.empty&&z!==h.sourceSelectionKey){await BA(E);return}if(h.snapshot?.paragraph){const K=await m();if(!K||ic(K)===h.sourceSelectionKey)return;await BA(K)}},BA=async f=>{const m=h.snapshot;if(!m){h.mode==="armed"&&Lm();return}const b=y();if(!b)return;const I=Ts(f,"ready"),{lockModesById:E}=xs(b.contentControls,I);if(Ji(E)){Xt();return}const z=f.target,K=f.selectionTarget;if(f.empty!==!0&&Object.keys(m.inline).length>0){const oe=yr(b,"format.apply");if(oe&&K)try{if(!yo(ks(await Promise.resolve(ed("format.apply",oe,{target:K,inline:m.inline},f))))){Xt();return}}catch{Xt();return}}if(m.paragraph){const oe=Array.isArray(z?.segments)?z.segments:[],me=z?.story;for(const Re of oe){const Ue=vo(Re.blockId,me),Ke=await Ms(Ue),Fe=Ke?.node??null,Xe=Ke?.address??null;if(!Fe)continue;const He={kind:"block",nodeType:Xe?.nodeType??Fe.kind??"paragraph",nodeId:Re.blockId,...me&&typeof me=="object"?{story:me}:{}},{styleId:Ze,alignment:Qe,spacing:ot,indentation:nt,markRunProps:Ot,numbering:Qt,listStyle:on}=m.paragraph;if(Ze&&await b.styles?.paragraph?.setStyle?.({target:He,styleId:Ze}),Qe&&await b.format?.paragraph?.setAlignment?.({target:He,alignment:Qe}),ot){const Dn=ot,Mr=Dn.lineRule??"auto",Ar=new Set(["auto","exact","atLeast"]).has(Mr)?Mr:"auto",jr={...Dn.before!=null?{before:Math.round(Dn.before*20)}:{},...Dn.after!=null?{after:Math.round(Dn.after*20)}:{},...Dn.line!=null?{line:Math.round(Ar==="auto"?Dn.line*240:Dn.line*20),lineRule:Ar}:{}};await b.format?.paragraph?.setSpacing?.({target:He,...jr})}if(nt){const Dn={...nt.left!=null?{left:Cs(nt.left)}:{},...nt.right!=null?{right:Cs(nt.right)}:{},...nt.firstLine!=null?{firstLine:Cs(nt.firstLine)}:{},...nt.hanging!=null?{hanging:Cs(nt.hanging)}:{}};await b.format?.paragraph?.setIndentation?.({target:He,...Dn})}Ot&&await b.format?.paragraph?.setMarkRunProps?.({target:He,markRunProps:Ot}),Qt&&await b.format?.paragraph?.setNumbering?.({target:He,...Qt}),on&&((await Ms(Ue))?.address?.nodeType==="listItem"?await b.lists?.applyStyle?.({target:_A(Re.blockId,me),style:on}):Qt&&await b.format?.paragraph?.setNumbering?.({target:He,...Qt}))}}h.mode==="armed"&&Lm(),Xt()},Pm=(f,m,b)=>{const I=KH(f,m),E=I?I.then(()=>(Mc(f,m,b),pn)):(Mc(f,m,b),pn);return Tu(f)?.inline?.kind==="toggle"&&(bn=E),E},zA=f=>({id:f,getState:()=>dt.toolbar.commands[f]??bc(f,y(),dt.selection,Sl(dt.selection)),observe:m=>Fs(b=>b.toolbar.commands[f]??{enabled:!1,active:!1,supported:!1,source:"unsupported",reason:ut.commandUnsupported}).subscribe(m),execute:m=>Mc(f,m),executeAsync:m=>Pm(f,m)}),QH=f=>{he.set(f.id,f),Xt();const m=()=>{he.delete(f.id),Xt()};return Object.assign(m,{handle:zA(f.id),unregister:m})},Dm=Ao(f=>f.selection),Om=oi(Dm),VA=()=>{const f=x();if(typeof f?.getHandles!="function")return{reason:ut.hostCapabilityUnavailable};let m=null;try{m=f.getHandles()}catch(I){const E=I?.reason;return{reason:E==="host-not-ready"||E==="host-disposed"||E==="editing-mount-required"?ut.notReady:ut.hostCapabilityUnavailable}}const b=m?.editing?.selectionTargets;return typeof b?.apply!="function"?{reason:ut.hostCapabilityUnavailable}:{helper:b}},JH=f=>{const m=x();if(typeof m?.getHandles=="function")try{const b=m.getHandles()?.editing?.contentControls;typeof b?.activate=="function"&&b.activate({id:f})}catch{}},HA={get:Om.get,getSnapshot:Om.getSnapshot,subscribe:Om.subscribe,observe:Om.observe,current:()=>_a().value,capture:()=>{const f=Dm.get();return f.empty||!f.target&&!f.selectionTarget?null:{...f,capturedAt:Date.now()}},restore:f=>{const m=E=>(Xt(),{...E,success:E.ok});if(!f||typeof f!="object")return m({ok:!1,reason:ut.targetUnresolved});if(!_())return m({ok:!1,reason:ut.notReady});const b=sH(f);if(!b)return m({ok:!1,reason:ut.targetUnresolved});const I=VA();if(!("helper"in I))return m({ok:!1,reason:I.reason});try{return m(vA(I.helper.apply(b)))}catch{return m({ok:!1,reason:ut.hostCapabilityUnavailable})}},apply:f=>{if(!_())return{ok:!1,reason:ut.notReady};const m=VA();if(!("helper"in m))return{ok:!1,reason:m.reason};try{const b=m.helper.apply(f);return Xt(),vA(b)}catch{return{ok:!1,reason:ut.hostCapabilityUnavailable}}},getAnchorRect:f=>{const m=x();if(typeof m?.getSelectionAnchorRect=="function"){const b=Lt(()=>m.getSelectionAnchorRect(f),null);return b&&typeof b=="object"&&(Number(b.width)>0||Number(b.height)>0)?b:null}return null},getRects:f=>{const m=Dm.get(),b=m.selectionTarget??m.target;if(m.empty||!b)return[];const I=Wm.getRect({target:b,relativeTo:f?.relativeTo});return I.found?I.rects:[]}},$H={get ids(){return le()},has:f=>Tu(f)!=null||he.has(f),get:f=>zA(f),execute:Mc,executeAsync:Pm,register:QH,getContextMenuItems:f=>{const m=[];for(const b of he.values()){const I=b.contextMenu;I&&Lt(I.when?()=>I.when(f):void 0,!0)&&m.push({id:b.id,label:I.label,group:I.group,order:I.order,invoke:()=>Mc(b.id,void 0,f)})}return m.sort((b,I)=>(b.order??0)-(I.order??0)||b.label.localeCompare(I.label))}},Eb=oi(Ao(f=>f.toolbar)),eU={get:Eb.get,getSnapshot:()=>dt.toolbar,subscribe:Eb.subscribe,observe:Eb.observe,execute:Mc,executeAsync:Pm},Lc=async(f,m)=>{if(!_())return{success:!1,ok:!1,reason:ut.notReady};if(!f)return{success:!1,ok:!1,reason:ut.targetUnresolved};const b=x(),I=b?.scrollTargetIntoView;if(typeof I!="function")return{success:!1,ok:!1,reason:ut.hostCapabilityUnavailable};try{const E={target:f,block:m?.block??"center",behavior:m?.behavior??"smooth"},z=await Promise.resolve(m?.shouldContinue?I.call(b,E,m.shouldContinue):I.call(b,E));return z&&typeof z=="object"&&z.success===!1?{success:!1,ok:!1,reason:db(z.reason,ut.targetUnresolved)}:{success:!0,ok:!0}}catch{return{success:!1,ok:!1,reason:ut.hostCapabilityUnavailable}}},Fm=async(f,m,b,I)=>{const E=f==="trackChanges"?I?.story:void 0,z=ot=>{if(!E||!ot||typeof ot!="object")return ot;const nt=ot,Ot=nt.address&&typeof nt.address=="object"?nt.address:null;return nt.story||Ot?.story?ot:{...nt,story:E}},K=f==="trackChanges"?LV:Uf,oe=b.find(ot=>Wi(ot,m,E)),me=oe&&typeof oe=="object"?oe:null,Re=f==="trackChanges"&&me?.type==="move"&&(me.subtype==="move-to"||me.subtype==="move-from")?me.subtype:null,Ue=Re&&typeof me?.trackedChangeCanonicalId=="string"?me.trackedChangeCanonicalId:m,Ke=ot=>{if(!Re)return K(ot);const nt=Uf(ot);if(nt?.kind!=="move")return null;const Ot=Re==="move-to"?nt.destination:nt.source;return fb(Ot)?Ot:null},Fe=K(oe),Xe=f!=="trackChanges"||!Re&&fb(Uf(oe));if(Fe&&Xe)return z(Fe);const He=y()?.[f],Ze=f==="comments"?{commentId:m}:{id:Ue,...E?{story:E}:{}},Qe=He?.get;if(typeof Qe!="function")return z(Fe);try{return z(Ke(await Promise.resolve(Qe.call(He,Ze)))??Fe)}catch{return z(Fe)}};function UA(f,m){if(Zi())return hr("Comments are read-only.","DOCUMENT_READONLY");if(dc())return hr("Resolving comments is disabled.","DOCUMENT_READONLY");const b=y()?.comments,I=b?.patch;if(typeof I!="function")return hr("comments.patch is unavailable.");const E=hr("comments.patch failed.");return Lt(()=>La(I.call(b,{commentId:f,status:m}),E),E)}const Nm=()=>Zi()?hr("Comments are read-only.","DOCUMENT_READONLY"):null,jA=(f,m)=>{const b=m&&typeof m=="object"?m:null;let I=Array.from(f);b?.includeResolved===!1&&(I=I.filter(me=>me.status!=="resolved"));const E=Number(b?.offset),z=Number.isInteger(E)&&E>0?E:0,K=Number(b?.limit),oe=Number.isInteger(K)&&K>=0?z+K:void 0;return I.slice(z,oe)},rd=Ao(f=>f.comments),Bm=oi(rd),tU={get:Bm.get,getSnapshot:Bm.getSnapshot,subscribe:Bm.subscribe,observe:Bm.observe,list:f=>{const m=rd.get();if(m.status!=="pending")return jA(m.items,f);const b=y()?.comments,I=Lt(b?.list?()=>b.list(f):void 0,null);return Cr(I)?[]:jA(Array.isArray(I?.items)?I.items:[],f)},getById:f=>{const m=rd.get().items.find(E=>Kn(E)===f)??null;if(m)return m;const b=y()?.comments,I=Lt(b?.get?()=>b.get({commentId:f}):void 0,null);return Cr(I)?null:I},createFromCapture:(f,m)=>{const b=Nm();if(b)return b;const I=y()?.comments,E=I?.create;if(typeof E!="function")return hr("comments.create is unavailable.");const z=hr("comments.create failed.");return Lt(()=>La(E.call(I,{target:f.target??f.selectionTarget,text:m.text}),z),z)},createFromSelection:f=>{const m=Nm();if(m)return m;const b=y()?.comments,I=b?.create;if(typeof I!="function")return hr("comments.create is unavailable.");const E=Dm.get(),z=E.target??E.selectionTarget;if(E.empty||!z)return hr("A range selection is required to comment.","NO_SELECTION");const K=hr("comments.create failed.");return Lt(()=>La(I.call(b,{target:z,text:f.text}),K),K)},reply:(f,m)=>{const b=Nm();if(b)return b;const I=y()?.comments,E=I?.reply??I?.create;if(typeof E!="function")return hr("comments.reply is unavailable.");const z=hr("comments.reply failed.");return Lt(()=>La(E===I?.reply?E.call(I,{parentCommentId:f,text:m.text}):E.call(I,{parentCommentId:f,text:m.text}),z),z)},resolve:f=>UA(f,"resolved"),reopen:f=>UA(f,"active"),delete:f=>{const m=Nm();if(m)return m;const b=y()?.comments,I=b?.delete??b?.remove;if(typeof I!="function")return hr("comments.delete is unavailable.");const E=hr("comments.delete failed.");return Lt(()=>La(I.call(b,{commentId:f}),E),E)},setActive:f=>{if(f==null)return ye=null,Xt(),!0;if(!_())return!1;const m=rd.get();if(m.listStatus!=="ready")return!1;const b=HV(m.items,f);return!b||!m.items.some(I=>Kn(I)===b)?!1:(ye=b,Xt(),!0)},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:_()?ut.documentApiUnavailable:ut.notReady};const m=await Fm("comments",f,rd.get().items);return m?Lc(m):{success:!1,ok:!1,reason:ut.targetUnresolved}}},Pa=Ao(f=>f.trackChanges),Tb=(f,m)=>{const b=Pa.get().items.filter(Ke=>Kn(Ke)!==null);if(b.length===0)return null;const I=dt.trackChanges.activeId,E=ce?.id===I?ce.story:void 0,z=b.filter(Ke=>wm(Ke)==null),K=E||z.length===0?b:z;let oe=I?K.findIndex(Ke=>Wi(Ke,I,E)):-1;oe===-1&&I&&E&&(oe=K.findIndex(Ke=>Wi(Ke,I)));const me=K[oe===-1?f>0?0:K.length-1:(oe+f+K.length)%K.length],Re=Kn(me),Ue=wm(me);return je(Ue?{id:Re,story:Ue}:{id:Re},m),Xt(),Re};let GA=Promise.resolve();const nU=f=>{const m=ie;return GA.catch(()=>{}).then(()=>rU(f,m))},rU=async(f,m)=>{if(ie!==m)return{success:!1};const b=ce,I=Tb(f,{invalidateQueuedNavigation:!1});if(I==null)return{success:!1};const E=ce,z=ke,K=()=>ie===m&&ce===E&&ke===z,oe=()=>{K()&&(je(b,{invalidateQueuedNavigation:!1}),Xt())};E&&Je.add(E);try{const me=await Fm("trackChanges",I,Pa.get().items,E?.story?{story:E.story}:void 0);if(!K())return{success:!1};if(!me)return oe(),{success:!1};_o+=1;try{const Re=await Lc(me,{behavior:"auto",shouldContinue:K});return K()?(!Re.ok&&Re.reason!==ut.targetNotVisible?(oe(),Te(b)):Te(E),{success:Re.ok}):{success:!1}}finally{_o=Math.max(0,_o-1),_o===0&&(K()?xr&&Bo(Ci(xr)):Te(ce))}}finally{E&&Je.delete(E)}},WA=f=>{const m=nU(f);return GA=m.then(()=>{},()=>{}),m},zm=oi(Pa),oU={get:()=>(Se(),zm.get()),getSnapshot:()=>(Se(),zm.getSnapshot()),subscribe:f=>(Se(),zm.subscribe(f)),observe:f=>(Se(),zm.observe(f)),list:()=>(Se(),Pa.get().items),accept:f=>xb("accept",f),reject:f=>xb("reject",f),acceptAll:()=>ih("accept",{kind:"all"},null),rejectAll:()=>ih("reject",{kind:"all"},null),next:()=>Tb(1),previous:()=>Tb(-1),navigateNext:()=>WA(1),navigatePrevious:()=>WA(-1),getAt:f=>{if(!f||typeof f!="object"||typeof f.x!="number"||typeof f.y!="number")return null;const m=Lb(f);if(m.length===0)return null;const b=Pa.get().items;let I;for(const E of m){if(E.type!=="trackedChange")continue;let z;if(E.story){if(I===void 0&&(I=Qi()),!I)continue;z=I}else z=b;const K=z.find(oe=>Wi(oe,E.id,E.story));if(K)return E.story?{id:K.id,item:K,story:E.story}:{id:K.id,item:K}}return null},setActive:f=>{if(f==null)return je(null),Te(null),Xt(),!0;if(!_())return!1;const m=typeof f=="string"?{id:f}:{id:f.id,story:f.story};if(typeof m.id!="string"||m.id.length===0)return!1;const b=m.id;if(m.story){const I=Qi();if(!I)return!1;const E=Pu(I,m.story).toPublicId(m.id)??m.id;if(!I.some(z=>Wi(z,E,m.story)))return!1;m.id=E}else{const I=Pa.get().items,E=ga(I).toPublicId(m.id)??m.id,z=I.find(K=>Kn(K)===E);if(!z)return!1;m.id=E,m.story=wm(z)}return b!==m.id&&(m.paintedEntityId=b),je(m),Te(m),Xt(),!0},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:_()?ut.documentApiUnavailable:ut.notReady};ie+=1,xe+=1;const m=xe,b=Pa.get().items,I=ga(b).toPublicId(f)??f,E=wm(b.find(oe=>Kn(oe)===I)),z=ce,K={id:I,...E?{story:E}:{},...I!==f?{paintedEntityId:f}:{}};Je.add(K);try{const oe=await Fm("trackChanges",I,b,E?{story:E}:void 0);if(xe!==m)return{success:!1,ok:!1};if(!oe)return{success:!1,ok:!1,reason:ut.targetUnresolved};je(K);const me=xe,Re=ce,Ue=ke,Ke=()=>xe===me&&ce===Re&&ke===Ue,Fe=()=>{Ke()&&(je(z,{invalidateQueuedNavigation:!1}),Xt())};Xt(),_o+=1;try{const Xe=await Lc(oe,{behavior:"auto",shouldContinue:Ke});return Ke()?(!Xe.ok&&Xe.reason!==ut.targetNotVisible?(Fe(),Te(z)):Te(K),Xe):{success:!1,ok:!1}}finally{_o=Math.max(0,_o-1),_o===0&&(Ke()?xr&&Bo(Ci(xr)):Te(ce))}}finally{Je.delete(K)}}},xb=(f,m)=>{const{id:b,story:I}=typeof m=="string"?{id:m,story:void 0}:m;return ih(f,{kind:"id",id:b,...I?{story:I}:{}},b,I)},ih=(f,m,b,I)=>{try{return qr(Rb(f,m,b,I))}catch{return!1}},Rb=(f,m,b,I)=>{if(Zi())return!1;const E=y()?.trackChanges,z=m.kind==="all"||m.scope==="all",K=m.kind==="range",oe=m.kind==="ids";if(Ku({kind:f,scope:z?"all":"id"},E))return!1;const me=z?`${f}All`:f,Re=!K&&!oe&&!I&&E&&typeof E[me]=="function"?E[me]: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:m})},Mb=Ao(f=>f.contentControls),sh=f=>Mb.get().items.find(m=>m?.id===f)??null,Vm=oi(Mb),iU=(f=>{if(f===void 0)return Vm.get();const m=Cm(f);return m?sh(m):null}),sU={get:(f=>(f!==void 0&&jo("api"),iU(f))),getSnapshot:Vm.getSnapshot,subscribe:Vm.subscribe,observe:Vm.observe,list:()=>(jo("api"),Mb.get().items),getById:f=>(jo("api"),sh(f)),getRect:f=>{const m=Cm(f);if(!m)return fl("unresolved");jo("panel");const b=sh(m);if(!b)return fl("unresolved");const I=hb(b);return I?Wm.getRect({target:I}):fl("unavailable")},scrollIntoView:async f=>{const m=Cm(f);if(!m)return{success:!1};jo("panel");const b=sh(m);if(!b)return{success:!1};const I=hb(b);return I?{success:(await Lc(I,{block:f.block,behavior:f.behavior})).ok}:{success:!1}},focus:async f=>{const m=Cm(f);if(!m)return{success:!1,reason:"invalid-id"};if(!_())return{success:!1,reason:"not-ready"};jo("panel");const b=sh(m);if(!b)return{success:!1,reason:"not-found"};const I=hb(b);if(!I)return{success:!1,reason:"not-reachable"};if(!(await Lc(I,{block:f.block,behavior:f.behavior})).ok)return{success:!1,reason:"not-reachable"};const E=OV(I);if(!E)return{success:!1,reason:"not-reachable"};const z=HA.apply(E);return!z.ok&&z.reason!==ut.hostCapabilityUnavailable?{success:!1,reason:"not-reachable"}:(JH(m),{success:!0})}},Hm=oi(Ao(f=>f.fonts)),aU={get:Hm.get,getSnapshot:Hm.getSnapshot,subscribe:Hm.subscribe,observe:Hm.observe,getFamilyOptions:()=>dt.fonts.options,getSizeOptions:()=>dt.fonts.sizeOptions},Um=oi(Ao(f=>f.zoom)),lU={get:Um.get,getSnapshot:Um.getSnapshot,subscribe:Um.subscribe,observe:Um.observe,set:f=>{if(typeof t?.setZoom=="function")try{t.setZoom(f),Xt()}catch{}},setMode:f=>{if(typeof t?.setZoomMode=="function")try{t.setZoomMode(f),Xt()}catch{}}},jm=oi(Ao(f=>f.document)),cU={get:jm.get,getSnapshot:jm.getSnapshot,subscribe:jm.subscribe,observe:jm.observe,setMode:f=>{if(typeof t?.setDocumentMode=="function")try{t.setDocumentMode(f),Xt()}catch{}},export:f=>{if(typeof t?.export=="function")try{return Promise.resolve(t.export(f))}catch{return}},getText:()=>{const f=y(),m=Lt(f?.getText?()=>f.getText({}):void 0,null);return typeof m=="string"?m:m&&typeof m=="object"&&typeof m.text=="string"?m.text:null},replaceFile:f=>{const m=t?.replaceFile??t?.loadDocument??t?.reload;if(typeof m=="function")try{return Promise.resolve(m.call(t,f))}catch{return}}},KA=()=>{if(typeof HTMLElement>"u")return null;const f=_()?.mount?.container;if(f instanceof HTMLElement)return f;const m=t?.element;return m instanceof HTMLElement?m:null},uU=(f,m)=>{if(typeof f!="number"||typeof m!="number"||!Number.isFinite(f)||!Number.isFinite(m))return[];const b=globalThis.document;if(!b||typeof b.elementFromPoint!="function")return[];const I=KA();if(!I)return[];const E=b.elementFromPoint(f,m);if(!E||!I.contains(E))return[];const z=[E],K=nt=>{nt&&I.contains(nt)&&!z.includes(nt)&&z.push(nt)},oe=b.elementsFromPoint;if(typeof oe=="function"){let nt=[];try{nt=oe.call(b,f,m)??[]}catch{nt=[]}for(const Ot of nt)K(Ot)}const me=[],Re=nt=>{nt&&I.contains(nt)&&!me.includes(nt)&&!z.includes(nt)&&me.push(nt)},Ue=nt=>{const Ot=nt.getBoundingClientRect;if(typeof Ot!="function")return!1;let Qt;try{Qt=Ot.call(nt)}catch{return!1}return Qt!=null&&f>=Qt.left&&f<=Qt.right&&m>=Qt.top&&m<=Qt.bottom};for(const nt of z){const Ot=nt.querySelectorAll;if(typeof Ot!="function")continue;let Qt;try{Qt=Ot.call(nt,"[data-track-change-marker]")}catch{continue}for(let on=0;on<Qt.length;on+=1)Ue(Qt[on])&&Re(Qt[on])}me.reverse();const Ke=[...me,...z],Fe=gA(Ke[0],I);for(let nt=1;nt<Ke.length;nt+=1)for(const Ot of gA(Ke[nt],I))Fe.push(Ot);if(Fe.length===0)return Fe;const Xe=Pa.get().items,He=ga(Xe);let Ze;const Qe=new Set,ot=[];for(const nt of Fe){if(nt.type!=="trackedChange"){const Dn=`${nt.type}:${nt.id}`;if(Qe.has(Dn))continue;Qe.add(Dn),ot.push(nt);continue}const Ot=DV(nt.storyKey)??PV(nt.story);let Qt;if(Ot){if(Ze===void 0&&(Ze=Qi()),!Ze||(Qt=Pu(Ze,Ot).toPublicId(nt.id),!Qt||!Ze.some(Dn=>Wi(Dn,Qt,Ot))))continue}else if(Qt=He.toPublicId(nt.id),!Qt)continue;const on=`trackedChange:${Qt}`;Qe.has(on)||(Qe.add(on),ot.push(Ot?{type:"trackedChange",id:Qt,story:Ot}:{type:"trackedChange",id:Qt}))}return ot};function Lb(f,m){return typeof f=="object"?uU(f?.x,f?.y):null}const od=new Set;let Pb=!1;const qA=f=>{const m=x();if(typeof m?.observeGeometry!="function")return;let b=!1;const I=Lt(()=>{const E=m.observeGeometry(()=>f.schedule());return b=!0,E},null);f.detach=typeof I=="function"?I:null,f.boundHost=b?m:null},Gm=f=>{if(f.detach){try{f.detach()}catch{}f.detach=null}f.boundHost=null},YA=()=>{if(Pb=!1,!($||x()))for(const f of od)Gm(f)},dU=()=>{if(!Pb){if(Pb=!0,typeof queueMicrotask=="function"){queueMicrotask(YA);return}Promise.resolve().then(YA)}},fU=()=>{const f=x();if(!f){dU();return}for(const m of od)m.boundHost&&m.boundHost===f||(Gm(m),qA(m),m.schedule())};xa.push(fU);const Wm={getRect:f=>{const m=x(),b=m?.getTargetRects;if(typeof b=="function"){const I=Lt(()=>b.call(m,{target:f.target}),null);return I&&typeof I=="object"?I.success===!0&&Array.isArray(I.rects)?oH(rH(I.rects.filter(E=>E!=null&&typeof E=="object")),f.relativeTo):fl(typeof I.reason=="string"?I.reason:"unresolved"):fl("unresolved")}return fl("unavailable")},observe:f=>{const m=[];let b=0;const I=typeof requestAnimationFrame=="function",E=()=>{if(!I){f();return}b||(b=requestAnimationFrame(()=>{b=0,f()}))},z=Fs(oe=>({ready:oe.ready,selection:oe.selection,zoom:oe.zoom}));m.push(z.subscribe(()=>E()));const K={schedule:E,detach:null,boundHost:null};return qA(K),od.add(K),()=>{od.delete(K),Gm(K),b&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(b);for(const oe of m.splice(0))try{oe()}catch{}}},getHost:()=>KA(),entityAt:Lb,contextAt:f=>{const m=!!f&&typeof f.x=="number"&&typeof f.y=="number",b=m?f.x:0,I=m?f.y:0;return{point:{x:b,y:I},entities:m?Lb({x:b,y:I}):[],selection:dt.selection,position:null,insideSelection:!1}},scrollIntoView:async f=>{const m=f?.target;if(!m)return{success:!1};let b=null;if(m.kind==="entity"){const I=m.entityType==="comment"?"comments":"trackChanges",E=I==="comments"?rd.get().items:Pa.get().items,z=m.entityType==="trackedChange"&&m.story?{story:m.story}:void 0;b=await Fm(I,m.entityId,E,z)}else{const I=m,E=m,z=Array.isArray(I.segments)&&I.segments.length>0?I.segments:E.blockId&&E.range?[{blockId:E.blockId,range:E.range}]:null;if(z){const K=m.story;b={kind:"text",segments:z,...K?{story:K}:{}}}}return b?{success:(await Lc(b,{block:f.block??"center",behavior:f.behavior??"smooth"})).ok}:{success:!1}}},XA=f=>{const m=(f&&typeof f=="object"?f:null)?.target;return m&&typeof m=="object"?m:null},ZA=f=>`metadata:resolve:${f}`,hU=f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;const{value:b}=Vr(ZA(f),At(),()=>m.resolve({id:f}),XA);return b},pU=async f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;try{const b=At(),I=await Promise.resolve(m.resolve({id:f}));if(b!==At())return null;const E=XA(I);return ee.set(ZA(f),{token:b,value:E,hasSettled:!0,inflightToken:null}),E}catch{return null}},mU={getRect:f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return fl("unavailable");const b=hU(f.id);return b?Wm.getRect({target:b}):fl("unresolved")},scrollIntoView:async f=>{const m=await pU(f.id);return m?{success:(await Lc(m,{block:f.block,behavior:f.behavior})).ok}:{success:!1}}},gU={inTable:!1,tableNodeId:null,rowIndex:null,columnIndex:null,cellNodeId:null,rows:null,columns:null},vU={getContext:()=>{const f=Ne();if(!f)return{...gU};const m=pe()?.table;return{inTable:!0,tableNodeId:f.tableNodeId,rowIndex:f.rowIndex,columnIndex:f.columnIndex,cellNodeId:f.cellNodeId,rows:typeof m?.rows=="number"?m.rows:null,columns:typeof m?.columns=="number"?m.columns:null}},isInTable:()=>Ne()!=null},Km={query:"",total:0,activeIndex:-1,open:!1,available:!1,caseSensitive:!1,includeDeletedText:!1,regex:!1,canReplace:!1,reason:ut.searchUnavailable};let Vn={...Km};const qm=new Set,Da=()=>{const f=x()?.search;return f&&typeof f=="object"?f:null},Ns=()=>{const f=T()?.search;return f&&typeof f=="object"?f:null},ah=()=>{const f=Da();if(f&&typeof f.setSession=="function")return!0;const m=Ns();return!!m&&typeof m.query=="function"&&typeof m.getState=="function"},ts=()=>{for(const f of[...qm])try{f(Vn)}catch{}},si=f=>(Vn={...Vn,...f},ts(),Vn);let to=0,Pc=null;const QA=()=>{const f=Pc;Pc=null,f&&Lt(()=>(f(),null),null)},yU=()=>{to+=1,QA();const f=ah();Vn={...Km,available:f,reason:f?void 0:ut.searchUnavailable},ts()};es.push(yU);const bU=f=>{if(!f)return!1;const m=f.queryError;if(m&&typeof m=="object"&&m.code==="invalid-pattern")return!0;const b=f.rejection;return f.status==="rejected"&&!!b&&typeof b=="object"&&b.code==="invalid-pattern"},Db=(f,m=!1)=>{const b=f&&typeof f=="object"?f:null;if(!b)return null;const I=Array.isArray(b.matches)?b.matches:[],E=typeof b.total=="number"&&Number.isFinite(b.total)?b.total:I.length,z=typeof b.activeMatchIndex=="number"?b.activeMatchIndex:typeof b.activeIndex=="number"?b.activeIndex:-1;return{...typeof b.query=="string"?{query:b.query}:{},total:E,activeIndex:z,canReplace:b.canReplace===!0||m,...b.includeDeletedText===!0?{includeDeletedText:!0}:{},...b.regex===!0?{regex:!0}:{},...bU(b)?{invalidPattern:!0}:{}}},Io=()=>{const f=V("find.replace"),m=V("find.replaceAll");return f?.enabled===!0||m?.enabled===!0},Eo=(f,m=!1)=>{const b=Db(f,m);if(!b){si({total:0,activeIndex:-1,canReplace:!1,reason:void 0});return}si({...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?ut.searchInvalidPattern:void 0})},Oa=()=>{const f=Da();if(f&&typeof f.getState!="function")return Vn={...Vn,available:ah(),reason:ah()?void 0:ut.searchUnavailable},Vn;if(!f){const b=Ns();if(b&&typeof b.getState=="function"){const I=Db(Lt(()=>b.getState(),null),Io());if(I)return Vn={...Vn,...I.query!==void 0?{query:I.query}:{},total:I.total,activeIndex:I.activeIndex,canReplace:I.canReplace,available:!0,reason:I.invalidPattern?ut.searchInvalidPattern:void 0,open:Vn.open||!!I.query},Vn}return Vn={...Km,query:Vn.query,caseSensitive:Vn.caseSensitive,includeDeletedText:Vn.includeDeletedText},Vn}const m=Db(Lt(()=>f.getState(),null));return m&&(Vn={...Vn,...m.query!==void 0?{query:m.query}:{},total:m.total,activeIndex:m.activeIndex,canReplace:m.canReplace,...m.includeDeletedText!==void 0?{includeDeletedText:m.includeDeletedText}:{},...m.regex!==void 0?{regex:m.regex}:{},available:!0,reason:m.invalidPattern?ut.searchInvalidPattern:void 0,open:Vn.open||!!m.query}),Vn},id=f=>{const m=f&&typeof f=="object"?f:null;if(m?.status==="committed")return{ok:!0};if(m?.status==="rejected"&&m.reason==="read-only")return{ok:!1,reason:ut.documentReadonly};const b=m?.rejection;return m?.status==="rejected"&&b&&typeof b=="object"&&b.code==="read-only-document"?{ok:!1,reason:ut.documentReadonly}:{ok:!1,reason:ut.operationUnavailable}},Ym=oi({get:()=>Oa(),subscribe:f=>(qm.add(f),()=>qm.delete(f))}),wU={get:Ym.get,getSnapshot:Ym.getSnapshot,subscribe:Ym.subscribe,observe:Ym.observe,open:()=>ah()?(si({available:!0,open:!0,reason:void 0}),{ok:!0}):(si({available:!1,open:!1,reason:ut.searchUnavailable}),{ok:!1,reason:ut.searchUnavailable}),close:()=>{if(to+=1,Pc)QA();else{const f=Da();if(f&&typeof f.clear=="function")Lt(()=>f.clear(),null);else{const m=Ns();m&&typeof m.query=="function"&&Lt(()=>m.query({query:""}),null)}}Vn={...Km,available:ah(),reason:void 0},Vn.available||(Vn.reason=ut.searchUnavailable),ts()},search:(f,m)=>{const b=Da(),I=!!m?.caseSensitive,E=m?.includeDeletedText===!0,z=m?.regex===!0,K=++to;if(!b||typeof b.setSession!="function"){const oe=Ns();if(oe&&typeof oe.query=="function"&&typeof oe.getState=="function"){si({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),Pc=()=>{oe.query({query:""})};const me=Lt(()=>oe.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);return Cr(me)?Promise.resolve(me).then(Re=>{K===to&&Eo(Re,Io())},()=>{K===to&&si({available:!1,reason:ut.searchUnavailable})}):Eo(me,Io()),Eo(Lt(()=>oe.getState(),null),Io()),Vn}return si({query:f,total:0,activeIndex:-1,available:!1,caseSensitive:I,includeDeletedText:E,regex:z,reason:ut.searchUnavailable})}if(si({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),Pc=()=>{typeof b.clear=="function"&&b.clear()},Eo(Lt(()=>b.setSession(f,{caseSensitive:I,includeDeletedText:E,...z?{regex:!0}:{},highlight:!0}),null)),f.length>0&&Vn.total===0&&Vn.reason!==ut.searchInvalidPattern){const oe=Ns();if(oe&&typeof oe.query=="function"&&typeof oe.getState=="function"){const me=Pc;Pc=()=>{me?.(),oe.query({query:""})};const Re=Lt(()=>oe.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);Cr(Re)?Promise.resolve(Re).then(Ue=>{K===to&&Eo(Ue,Io())},()=>{K===to&&si({available:!1,reason:ut.searchUnavailable})}):Eo(Re,Io()),Eo(Lt(()=>oe.getState(),null),Io())}}return Vn},next:()=>{const f=Da();if(!f||typeof f.next!="function"){const m=Ns();if(!m||typeof m.next!="function"||typeof m.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(Vn.total===0)return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.next(),null);if(Cr(b)){const I=to;Promise.resolve(b).then(E=>{I===to&&Eo(E,Io())}).catch(()=>{I===to&&si({available:!1,reason:ut.searchUnavailable})})}else Eo(b,Io());return Eo(Lt(()=>m.getState(),null),Io()),{ok:!0}}return Vn.total===0?{ok:!1,reason:ut.operationUnavailable}:(Eo(Lt(()=>f.next(),null)),{ok:!0})},previous:()=>{const f=Da();if(!f||typeof f.previous!="function"){const m=Ns();if(!m||typeof m.previous!="function"||typeof m.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(Vn.total===0)return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.previous(),null);if(Cr(b)){const I=to;Promise.resolve(b).then(E=>{I===to&&Eo(E,Io())}).catch(()=>{I===to&&si({available:!1,reason:ut.searchUnavailable})})}else Eo(b,Io());return Eo(Lt(()=>m.getState(),null),Io()),{ok:!0}}return Vn.total===0?{ok:!1,reason:ut.operationUnavailable}:(Eo(Lt(()=>f.previous(),null)),{ok:!0})},clear:()=>{to+=1;const f=Da();if(f&&typeof f.clear=="function"&&Lt(()=>f.clear(),null),!f||typeof f.clear!="function"){const m=Ns();m&&typeof m.query=="function"&&Lt(()=>m.query({query:""}),null)}si({query:"",total:0,activeIndex:-1,canReplace:!1})},replace:f=>{const m=Da();if(!m){const I=Ns();if(!I||typeof I.replace!="function"||typeof I.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(!Io())return{ok:!1,reason:ut.operationUnavailable};const E=Lt(()=>I.replace({replacement:typeof f=="string"?f:""}),null);if(Cr(E)){const z=to;Oa(),ts();const K=()=>z===to;return Promise.resolve(E).then(oe=>(K()&&(Eo(oe,Io()),Oa(),ts()),id(oe)),()=>(K()&&si({available:!1,reason:ut.searchUnavailable}),{ok:!1,reason:ut.searchUnavailable}))}return Oa(),ts(),id(E)}if(typeof m.replaceCurrent!="function")return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.replaceCurrent(typeof f=="string"?f:""),null);return Oa(),ts(),id(b)},replaceAll:f=>{const m=Da();if(!m){const I=Ns();if(!I||typeof I.replaceAll!="function"||typeof I.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(!Io())return{ok:!1,reason:ut.operationUnavailable};const E=Lt(()=>I.replaceAll({replacement:typeof f=="string"?f:""}),null);if(Cr(E)){const z=to;Oa(),ts();const K=()=>z===to;return Promise.resolve(E).then(oe=>(K()&&(Eo(oe,Io()),Oa(),ts()),id(oe)),()=>(K()&&si({available:!1,reason:ut.searchUnavailable}),{ok:!1,reason:ut.searchUnavailable}))}return Oa(),ts(),id(E)}if(typeof m.replaceAll!="function")return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.replaceAll(typeof f=="string"?f:""),null);return Oa(),ts(),id(b)}},JA=Ao(f=>f.styles),Xm=oi(JA),CU={get:Xm.get,getSnapshot:Xm.getSnapshot,subscribe:Xm.subscribe,observe:Xm.observe,getCatalog:f=>Me(f).value,getQuickGallery:()=>JA.get().quickGallery,getActiveParagraphStyle:()=>ct(dt.selection,ze().cache).style},$A={select:Fs,get state(){return dt},selection:HA,commands:$H,toolbar:eU,comments:tU,trackChanges:oU,contentControls:sU,fonts:aU,zoom:lU,document:cU,viewport:Wm,metadata:mU,tables:vU,search:wU,styles:CU,formatPainter:{setPointerSelecting(f){$||(h={...h,pointerSelecting:f})},notifyPointerUp(){$||(h={...h,pointerSelecting:!1},NA())},setKeyboardSelecting(f){$||(h={...h,keyboardSelecting:f})},notifyKeyUp(){$||(h={...h,keyboardSelecting:!1},NA())},cancel(){$||Lm()},onModeChange(f){return $?()=>{}:(p.add(f),()=>p.delete(f))}},createScope:()=>{const f=[];return{select:(m,b)=>{const I=Fs(m,b);return{get:I.get,subscribe:E=>{const z=I.subscribe(E);return f.push(z),z}}},dispose:()=>{for(const m of f.splice(0))m()}}},destroy:()=>{if(!$){$=!0,kV(In,bt),Br.reset(),Pe(),X&&(clearTimeout(X),X=null),te&&(clearTimeout(te),te=null,Y=0),U?.timer&&(clearTimeout(U.timer),U.timer=null),U=null,ve&&(clearTimeout(ve),ve=null),Co&&(clearTimeout(Co),Co=null),pr&&pr(),pr=null,co=null,ti.clear(),O.clear();for(const f of Tl.splice(0))f();xt&&xt(),xt=null,Bt=null,Zn&&Zn(),Zn=null,St=null,tr&&tr(),tr=null,xr=null,$r&&$r(),$r=null,No=null,dn&&dn(),dn=null,it=null;for(const f of od)Gm(f);od.clear(),Ye.clear(),qm.clear(),g+=1,p.clear(),to+=1,he.clear()}}};return S=$A,$A}var fH=[{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 hH(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 pH(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"?hH(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 mH(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 gH(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:fH;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 yH(e,t){return e.activeMark?t.activeMarks.includes(e.activeMark):!1}Mt();var bH=['[data-sdt-type="structuredContent"][data-sdt-id]','[data-sdt-type="structuredContent"][data-sdt-container-id]','[data-sdt-container-type="structuredContent"][data-sdt-container-id]'].join(", "),wH=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 CH(e,t){const n=new w6.default;return e.forEach((r,o)=>{n.file(t[o],r)}),n.generateAsync({type:"blob",compression:"DEFLATE"})}function Cb(e){return!!(e&&(e.synced===!0||e.isSynced===!0))}function MA(e){try{e.synced=!0}catch{}try{e.isSynced=!0}catch{}}function kH(e,t){if(!e)return()=>{};if(Cb(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=()=>{MA(e),s()},l=u=>{u!==!1&&(u===!0||Cb(e))&&(MA(e),s())};return n("synced",a),n("sync",l),Cb(e)&&s(),i}function SH(e,t){const n=e.composedPath();if(!n.includes(t))return null;const r=n.find(a=>a instanceof HTMLElement&&a.matches(bH));if(!r)return null;const o=n.some(a=>a instanceof HTMLElement&&a.classList.contains(ap.BLOCK_SDT_LABEL)),i=r.getAttribute("data-sdt-container-id")?.trim()||null,s=r.getAttribute("data-sdt-id")?.trim()||null;return o?i??s:s??i}function _H(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function AH(e){if(!e||typeof e.id!="string"||e.kind!=="inline"&&e.kind!=="block"||typeof e.controlType!="string")return null;const t=e.properties?.tag,n=e.properties?.alias;return{id:e.id,controlType:e.controlType,scope:e.kind,...typeof t=="string"&&t?{tag:t}:{},...typeof n=="string"&&n?{alias:n}:{}}}function $o(e){return!!(e&&typeof e=="object"&&e.editorVersion===2)}function IH(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 LA(e){return typeof e=="string"&&e.length>0?e:null}function kb(e){return e?$o(e)?LA(e.documentId??e.options?.documentId??null):LA(typeof e.getDocumentId=="function"?e.getDocumentId():e.options?.documentId):null}function EH(e){if(!e||$o(e))return null;const t=e;return t.documentRenderer??t.presentationEditor??null}function Yi(e){if(!e)return null;if($o(e))return e.fonts??null;const t=EH(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 Am=class extends Qm.default{static{this.allowedTypes=[Fr,ql,rp]}#t=!1;#n=!1;#e=null;#r=null;#i=null;#s=null;#d=null;#h=null;#f=e=>{this.#k(e)};#c=null;#p=W4({});get uiConfig(){return this.#p}#o=K4({});get interactionConfig(){return this.#o}#l=Y4({});get surfacesConfig(){return this.#l}#g;#u=new yN;#y=null;#w=!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:{...eb},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.#g=new sN({getModuleConfig:()=>this.#l}),this.#h=t,t.addEventListener("click",this.#f,!0),this.#I(e,t)}async#k(e){const t=this.#h;if(!t)return;const n=SH(e,t),r=this.activeEditor?.doc?.contentControls?.list;if(!(!n||typeof r!="function"))try{const o=await r();if(this.#t)return;const i=AH(_H(o).find(s=>s.id===n));i&&this.emit("content-control:click",{target:i,source:"pointer"})}catch{return}}async#I(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),hN(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.#we(),this.config.user=pN(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=zk(this.config.modules.comments),this.#p=W4(this.config),this.#o=K4(this.config),this.#l=Y4(this.config),this.config.disableContextMenu=!this.#p.contextMenu.enabled,this.config.rulers=this.#p.ruler.enabled,this.#p.comments.enabled?this.config.modules.comments===!1&&(this.config.modules.comments={}):this.config.modules.comments=!1,this.#p.comments.enabled){this.config.modules.comments===!0&&(this.config.modules.comments={});const i=this.config.modules.comments;i&&Object.assign(i,this.#o.comments)}if(this.config.colors=T6(this.config.colors),this.userColorMap=new Map,this.colorIndex=0,this.version="2.4.0-next.7",this.#C("🦋 [superdoc] Using SuperDoc version:",this.version),this.superdocId=e.superdocId||ns(),this.colors=this.config.colors??[],this.#P(),await D8(),this.#t)return;if(await this.#b(this.config.modules),this.#t){this.#de();return}this.config.cspNonce&&this.#L(),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.#y||(this.#y=this.#u.subscribe(i=>{this.#ke(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.#d=o,this.#S(),this.#M(),this.#Se(),this.#E()}#E(){if(this.#T(),this.readyEditors=0,!this.app)throw new Error("SuperDoc: #startRuntime called before #initVueApp populated this.app");this.app.mount(this.#d)}#M(){const e=this.config.modules?.whiteboard,t=e!==!1&&(e?.enabled??!1);this.whiteboard=new PD({Renderer:rN,superdoc:this,enabled:t}),this.emit("whiteboard:init",{whiteboard:this.whiteboard})}get requiredNumberOfEditors(){return this.#m("requiredNumberOfEditors").documents.filter(e=>e.type===Fr).length}get ui(){return this.#c||(this.#c=dH({superdoc:this}),this.#t&&this.#c.destroy()),this.#c}get state(){return{documents:this.#m("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}#L(){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}}#P(){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=$d(this.config.document);this.config.documents=[{id:ns(),...s}]}else if(n)this.config.documents=[{id:ns(),type:Fr,url:this.config.document,name:"document.docx"}];else if(r){const s=$d(this.config.document);this.config.documents=[{id:ns(),...s}]}else if(o){const s=$d(this.config.document);this.config.documents=[{id:ns(),...s}]}Array.isArray(this.config.documents)&&this.config.documents.length>0&&(this.config.documents=this.config.documents.map(s=>{const a=$d(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||ns()}}))}#T(){const{app:e,pinia:t,superdocStore:n,commentsStore:r,highContrastModeStore:o}=CD({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.#g),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&&b8(this),this.#ue()}#a(e,t){t&&this.on(e,t)}#S(){this.#a("editorBeforeCreate",this.config.onEditorBeforeCreate),this.#a("editorCreate",this.config.onEditorCreate),this.#a("editorDestroy",this.config.onEditorDestroy),this.#a("source:complete",this.config.onSourceComplete),this.#a("source:signals-complete",this.config.onSourceSignalsComplete),this.#a("ready",this.config.onReady),this.#a("comments-update",this.config.onCommentsUpdate),this.#a("content-control:active-change",this.config.onContentControlActiveChange),this.#a("content-control:click",this.config.onContentControlClick),this.#a("awareness-update",this.config.onAwarenessUpdate),this.#a("locked",this.config.onLocked),this.#a("pdf:document-ready",this.config.onPdfDocumentReady),this.#a("sidebar-toggle",this.config.onSidebarToggle),this.#a("collaboration-ready",this.config.onCollaborationReady),this.on("collaboration-ready",e=>this.#j(e?.editor??null)),this.#a("editor-update",this.config.onEditorUpdate),this.on("content-error",this.onContentError),this.#a("exception",this.config.onException),this.#a("list-definitions-change",this.config.onListDefinitionsChange),this.#a("pagination-update",this.config.onPaginationUpdate),this.#a("fonts-resolved",this.config.onFontsResolved),this.#a("fonts-changed",this.config.onFontsChanged),this.#a("zoomChange",this.config.onZoomChange),this.#a("viewport-change",this.config.onViewportChange)}async#b({collaboration:e}={}){return e?(this.isCollaborative=!1,this.config.documents.length===0&&(this.config.documents=[{id:ns(),type:Fr,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}#J(e,t){this.isCollaborative=!0,this._commentsCollabInitialized=!1,this.ydoc=Xr(e),this.provider=Xr(t),this.#_();const n=this.config;this._cleanupAwareness=p8(t,this,n.user),n.documents.forEach(r=>{r.ydoc=e,r.provider=t,r.role=this.config.role})}#U(){this.#s=null,this.#A(),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})}#A(){if(this.#r){try{this.#r()}catch{}this.#r=null}if(this.#i){try{this.#i()}catch{}this.#i=null}}#j(e){this.#A(),$o(e)&&(this.#D(e),this.#x(e))}#D(e){const t=e.presence;if(!t||typeof t.subscribe!="function")return;const n=xD(()=>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.#r=t.subscribe(r)}catch(o){console.warn("[SuperDoc] v2 awareness bridge failed to subscribe",o)}}#x(e){const t=e.lock;if(!t||typeof t.subscribe!="function")return;const n=r=>{this.#t||this.#v(!!r.isLocked,this.#O(r.lockedBy??null))};try{if(this.#s&&typeof t.setLocked=="function"){const o=this.#s;t.setLocked(o.isLocked,o.isLocked?o.lockedBy:null),this.#s=null}const r=t.getSnapshot?.();r&&n(r),this.#i=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}}#G(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}#v(e,t){this.isLocked===e&&this.#G(this.lockedBy,t)||(this.isLocked=e,this.lockedBy=t,this.#C("🦋 [superdoc] Locking superdoc:",e,t,`
|
|
102
|
+
`;Mt();var ws=e=>{e.expand.value=!1};function lb(e,t){const n={...e??{}};return t?n.href=t:delete n.href,n}function uA(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 Jz(e){return typeof e?.quotedText=="string"?e.quotedText:typeof e?.text=="string"?e.text:""}function dA(e){return e.ui?.selection?.get?.()??e.ui?.selection?.current?.()??null}function $z(e){return!!(e.config?.superdoc?.config?.modules?.ai||e.superdoc?.config?.modules?.ai)}function eV(e){return e.config?.superdoc?.config?.modules?.ai??e.superdoc?.config?.modules?.ai??{}}const tV=({superToolbar:e,toolbarIcons:t,toolbarTexts:n,toolbarFonts:r,hideButtons:o,availableWidth:i,role:s,isDev:a=!1}={})=>{const l=An({type:"button",name:"bold",command:"toggleBold",icon:t.bold,tooltip:n.bold,attributes:{ariaLabel:"Bold"}}),u=(r??qB).map(ez),c=An({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:et}={},Pt=!1)=>{if(Pt){c.label.value="",c.selectedValue.value="";return}if(!et)return;et=et.split(",")[0],c.label.value=et;const Kt=u.find(Nt=>Nt.label===c.defaultLabel.value),Rn=u.find(Nt=>Nt.label===et);Rn?c.selectedValue.value=Rn.key:Kt?c.selectedValue.value=Kt.key:c.selectedValue.value=""},onDeactivate:()=>{c.label.value=c.defaultLabel.value;const et=u.find(Pt=>Pt.label===c.defaultLabel.value);et?c.selectedValue.value=et.key:c.selectedValue.value=""}}),d=An({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(et){const Pt=dA(e),Kt=Pt?.selectionTarget??uA(Pt?.target),Rn=Pt?.empty?"":Jz(Pt),Nt=eV(e),un=()=>ws(et),Mn=()=>{const Pe=e.pendingSelectionCapture;Pe&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Pe)};return Gr("div",{},[Gr(Ez,{handleClose:un,selectedText:Rn,target:Kt,doc:e.superdoc?.activeEditor?.doc??null,apiKey:Nt?.apiKey||e.config?.aiApiKey||"",endpoint:Nt?.endpoint||e.config?.aiEndpoint||"",restoreSelection:Mn})])}const g=XB,p=An({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:g,onActivate:({fontSize:et},Pt=!1)=>{if(Pt){p.label.value="",p.selectedValue.value="";return}const Kt=g.find(Mn=>Mn.label===String(p.defaultLabel.value));if(!et){p.label.value=p.defaultLabel.value,Kt?p.selectedValue.value=Kt.key:p.selectedValue.value="";return}let Rn=NN(et,12);Rn<8&&(Rn=8),Rn>96&&(Rn=96);let Nt=String(Rn);const un=g.find(Mn=>Mn.label===Nt||Mn.key===Nt);un?p.selectedValue.value=un.key:p.selectedValue.value="",p.label.value=Nt},onDeactivate:()=>{p.label.value=p.defaultLabel.value;const et=g.find(Pt=>Pt.label===String(p.defaultLabel.value));et?p.selectedValue.value=et.key:p.selectedValue.value=""}}),v=An({type:"separator",name:"separator",isNarrow:!0}),k=An({type:"button",name:"italic",command:"toggleItalic",icon:t.italic,active:!1,tooltip:n.italic,attributes:{ariaLabel:"Italic"}}),C=An({type:"button",name:"underline",command:"toggleUnderline",icon:t.underline,active:!1,tooltip:n.underline,attributes:{ariaLabel:"Underline"}}),_=An({type:"button",name:"strike",command:"toggleStrike",icon:t.strikethrough,active:!1,tooltip:n.strikethrough,attributes:{ariaLabel:"Strikethrough"}}),y=An({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:()=>ab(e,y,[],!0)}],onActivate:({color:et})=>{y.iconColor.value=et||""},onDeactivate:()=>y.iconColor.value=""}),w=An({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:()=>ab(e,w)}],onActivate:({color:et})=>{w.iconColor.value=et},onDeactivate:()=>w.iconColor.value="#000"}),x=An({type:"button",name:"search",allowWithoutEditor:!0,active:!1,icon:t.search,tooltip:n.search,group:"right",attributes:{ariaLabel:"Search"}}),P=An({type:"dropdown",name:"link",markName:"link",icon:t.link,active:!1,tooltip:n.link,attributes:{ariaLabel:"Link dropdown"},options:[{type:"render",key:"linkDropdown",render:()=>N(P)}],onActivate:({href:et})=>{P.attributes.value=lb(P.attributes.value,et)},onDeactivate:()=>{P.attributes.value=lb(P.attributes.value,null),P.expand.value=!1}});function N(et){const Pt=dA(e),Kt=Pt?.selectionTarget??uA(Pt?.target),Rn=()=>{const Nt=e.pendingSelectionCapture;Nt&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Nt)};return Gr("div",{},[Gr(OS,{ui:e.ui,linkItem:et,textTarget:Kt,restoreSelection:Rn,closePopover:()=>ws(et),goToAnchor:()=>{ws(et);const Nt=et.attributes.value?.href;if(!Nt)return;const un=Nt.slice(1),Mn=(e.ui?.viewport?.getHost?.()??null)?.querySelector?.(`a[name='${un}']`);Mn&&bf(Mn)}})])}const G=An({type:"options",name:"linkInput",command:"toggleLink",active:!1});P.childItem=G,G.parentItem=P;const R=An({type:"button",name:"image",command:"startImageUpload",icon:t.image,active:!1,tooltip:n.image,disabled:!1,attributes:{ariaLabel:"Image"}}),F=An({type:"button",name:"tableOfContents",command:"insertTableOfContents",icon:t.tableOfContents,active:!1,tooltip:n.tableOfContents,disabled:!1,attributes:{ariaLabel:"Table of contents"}}),Z=An({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:()=>D(Z)}]});function D(et){return Gr("div",{},[Gr(jz,{onSelect:Kt=>{e.emitCommand({item:et,argument:Kt}),ws(et),sb(e)}})])}const B=An({type:"dropdown",name:"tableActions",command:"executeTableCommand",tooltip:n.tableActions,icon:t.tableActions,hideLabel:!0,disabled:!0,attributes:{ariaLabel:"Table actions"},options:[{type:"render",render:()=>V(B)}]}),T=[{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 V(et){return Gr(Zz,{options:T,onSelect:Pt=>{ws(et);const{command:Kt}=Pt;e.emitCommand({item:et,argument:{command:Kt}})}})}const J=An({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:()=>Gr("div",{},[Gr(rz,{onSelect:Pt=>{ws(J);const Kt={...J,command:"setTextAlign"};Kt.command="setTextAlign",e.emitCommand({item:Kt,argument:Pt}),q(J,Pt)}})]),key:"alignment"}],onActivate:({textAlign:et})=>{q(J,et)},onDeactivate:()=>{q(J,"left")}}),q=(et,Pt)=>{let Kt=Pt==="both"?"justify":Pt,Rn={left:t.alignLeft,right:t.alignRight,center:t.alignCenter,justify:t.alignJustify},Nt=Rn[Kt]??Rn.left;et.icon.value=Nt},se=An({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 et=Pt=>{ws(se);const Kt={...se,command:"toggleBulletListStyle"};e.emitCommand({item:Kt,argument:Pt})};return Gr(lA,{buttons:sz,iconSize:25,selectedStyle:se.selectedValue.value,onSelect:et})}}]}),pe=An({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 et=Pt=>{ws(pe);const Kt={...pe,command:"toggleOrderedListStyle"};e.emitCommand({item:Kt,argument:Pt})};return Gr(lA,{buttons:az,iconSize:30,selectedStyle:pe.selectedValue.value,onSelect:et})}}]}),Ne=An({type:"button",name:"indentleft",command:"decreaseTextIndent",icon:t.indentLeft,active:!1,tooltip:n.indentLeft,disabled:!1,attributes:{ariaLabel:"Left indent"}}),he=An({type:"button",name:"indentright",command:"increaseTextIndent",icon:t.indentRight,active:!1,tooltip:n.indentRight,disabled:!1,attributes:{ariaLabel:"Right indent"}}),ye=An({type:"overflow",name:"overflow",command:null,icon:t.overflow,active:!1,disabled:!1,attributes:{ariaLabel:"Overflow items"}}),ce=An({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:et})=>{et&&(ce.label.value=et)}}),ke=An({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:et})=>{et&&(ke.label.value=et)}}),ie=An({type:"button",name:"undo",disabled:!0,tooltip:n.undo,command:"undo",icon:t.undo,group:"left",attributes:{ariaLabel:"Undo"}}),xe=An({type:"button",disabled:!0,name:"redo",tooltip:n.redo,command:"redo",icon:t.redo,group:"left",attributes:{ariaLabel:"Redo"}}),Je=An({type:"button",disabled:!1,name:"acceptTrackedChangeBySelection",tooltip:n.trackChangesAccept,command:"acceptTrackedChangeFromToolbar",icon:t.trackChangesAccept,group:"left",attributes:{ariaLabel:"Accept tracked changes"}}),st=An({type:"button",disabled:!1,name:"rejectTrackedChangeOnSelection",tooltip:n.trackChangesReject,command:"rejectTrackedChangeFromToolbar",icon:t.trackChangesReject,group:"left",attributes:{ariaLabel:"Reject tracked changes"}}),Tt=An({type:"button",name:"clearFormatting",command:"clearFormat",tooltip:n.clearFormatting,icon:t.clearFormatting,attributes:{ariaLabel:"Clear formatting"}}),Te=An({type:"button",name:"copyFormat",tooltip:n.copyFormat,icon:t.copyFormat,command:"copyFormat",active:!1,attributes:{ariaLabel:"Copy formatting"}}),je=(et,Pt)=>et==="editor"?Pt:et==="suggester"?Pt.filter(Kt=>Kt.value==="suggesting"):Pt.filter(Kt=>Kt.value==="viewing"),Ye=et=>et==="editor"?"Editing":et==="suggester"?"Suggesting":"Viewing",$=An({type:"dropdown",name:"documentMode",command:"setDocumentMode",allowWithoutEditor:!0,icon:t.documentMode,defaultLabel:Ye(s),label:Ye(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:()=>ee($)}]}),S=[{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 ee(et){return Gr(mz,{options:je(s,S),onSelect:Pt=>{const Kt=e.superdoc?.activeEditor??e.activeEditor;ws(et);const{label:Rn,icon:Nt,value:un}=Pt;$.label.value=Rn,$.icon.value=Nt,e.emitCommand({item:$,argument:un}),sb(e,Kt)}})}const O=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"],U=An({type:"button",name:"ruler",command:"toggleRuler",allowWithoutEditor:!0,icon:t.ruler,active:!1,tooltip:n.ruler,attributes:{ariaLabel:"Ruler"}}),W=An({type:"button",name:"formattingMarks",command:"toggleFormattingMarks",allowWithoutEditor:!0,icon:t.formattingMarks,active:!1,tooltip:n.formattingMarks,attributes:{ariaLabel:"Formatting marks"}}),te=An({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 et=Kt=>{ws(te);const Rn=typeof Kt=="string"?Kt:Kt?.id??null;if(!Rn)return;const Nt={...te,command:"setLinkedStyle"};e.emitCommand({item:Nt,argument:Rn})},Pt=e.getActiveLinkedStyleId?.()??null;return Gr("div",{},[Gr(bz,{styles:e.getLinkedStyleOptions?.()??[],onSelect:et,selectedOption:Pt})])}}],onActivate:({styleId:et,styleName:Pt})=>{const Kt=Pt||et;te.label.value=et&&et!=="Normal"?String(Kt):n.formatText,te.disabled.value=!1},onDeactivate:()=>{te.disabled.value=!0,te.label.value=n.formatText}}),Y=(et,Pt)=>{if(Pt.value==et)return Gr("div",{innerHTML:Qz,class:"dropdown-select-icon"})},X=An({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(et=>({label:et.toFixed(2),key:et,icon:()=>Y(et,X.selectedValue),props:{"data-item":"btn-lineHeight-option"}}))}),be=20,ve=32,we=j.reduce((et,Pt)=>et+(O.get(Pt)||O.get("default")),0),Be=["linkedStyles","clearFormatting","copyFormat","formattingMarks"],rt=["zoom","fontFamily","fontSize","redo"],at=i<=Vf.lg,Ct=e.config?.showFormattingMarksButton===!0,en=e.config?.showTableOfContentsButton===!0;at&&($.attributes.value={...$.attributes.value,className:`${$.attributes.value.className} sd-toolbar-item--doc-mode-compact`}),at&&(te.attributes.value={...te.attributes.value,className:`${te.attributes.value.className} sd-toolbar-item--linked-styles-compact`});let Et=[ie,xe,Je,st,x,ce,c,v,p,v,l,k,C,_,w,y,v,P,R,...en?[F]:[],Z,B,v,J,se,pe,Ne,he,X,v,te,v,U,ke,...Ct?[W]:[],Te,Tt,...$z(e)?[d]:[],ye,$];if(i<=Vf.md&&o&&(Et=Et.filter(et=>et.type!=="separator")),e.config.mode!=="docx"){const et=Et.findIndex(Kt=>Kt.name.value==="linkedStyles");Et.splice(et-1,2);const Pt=["ruler","zoom","undo","redo"];Et=Et.filter(Kt=>!Pt.includes(Kt.name.value))}const Ut=[];a||(s==="viewer"&&Ut.push(Je,st),Et=Et.filter(et=>!Ut.includes(et)));const Wt=et=>j.includes(et.name.value),In=[],bt=[];let nn=ve+we;return Et.forEach(et=>{const Pt=O.get(et.name.value)||O.get("default");if(i<Vf.xl+be&&Be.includes(et.name.value)&&o){if(In.push(et),et.name.value==="linkedStyles"){const Kt=Et.findIndex(Rn=>Rn.name.value==="linkedStyles");Et.splice(Kt+1,1)}return}if(i<Vf.sm&&rt.includes(et.name.value)&&o){In.push(et);return}if(Wt(et)){bt.push(et),nn+=Pt;return}nn<i||!o?(bt.push(et),nn+=Pt):In.push(et)}),{defaultItems:bt,overflowItems:In.filter(et=>et.type!=="separator")}},fA={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"},nV=e=>e?typeof e!="string"?e instanceof HTMLElement?e:null:e.startsWith("#")||e.startsWith(".")?document.querySelector(e):document.getElementById(e):null;Mt();function hA(e){return xN(e)??ib[e]??null}function gm(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 rV=new Set(["bold","italic","underline","strike","color","highlight","link","clearFormatting","textAlign","list","numberedlist","indentleft","indentright","lineHeight","linkedStyles"]),oV=new Set(["list","numberedlist"]);function iV(e,t){if(e==="fontFamily"||e==="fontSize"||oV.has(e)&&t?.disabled&&t?.supported!==!1&&t?.reason==null)return!0;if(!rV.has(e))return!1;const n=t?.reason;return n==="range-selection-required"||n==="selection-required"}function pA(e){return!!e?.closest?.("[data-editor-ui-surface], .toolbar-dropdown-menu, .sd-toolbar-dropdown-menu, .sd-tooltip-content")}function sV(e){return["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)}var aV=class extends Qm.default{config={selector:null,toolbarGroups:["left","center","right"],role:"editor",icons:{...or},texts:{...fA},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={...or,...e.icons},this.config.texts={...fA,...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=nV(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.#d(),this.#f(),this.#i(),this._lastFontOptionsSignature=this.#o(),!this.toolbarContainer){this.updateToolbarState();return}this.app=Kl($B),this.app.directive("click-outside",ey),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.#a():this.#S()}))}#r(){this._unsubscribeController?.(),this._unsubscribeController=null,this._detachFormatPainterModeChange?.(),this._detachFormatPainterModeChange=null,this.#S();for(const e of this._customCommandRegs.values())try{e.unregister?.()}catch{}this._customCommandRegs.clear(),this.ui=null,this.snapshot=null}#i(){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.#p()),this.updateToolbarState()};this.superdoc.on("fonts-changed",e),this._detachFontsChanged=()=>{this.superdoc?.off?.("fonts-changed",e)}}#s(){this._detachFontsChanged?.(),this._detachFontsChanged=null}#d(){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}#h(e){return e||YB(this.superdoc?.fonts?.getFontFamilyOptions?.()??[])}#f(){const e=this.getAvailableWidth(),t=this.config.groups&&!Array.isArray(this.config.groups)&&Object.keys(this.config.groups).length>0,{defaultItems:n,overflowItems:r}=tV({superToolbar:this,toolbarIcons:this.config.icons,toolbarTexts:this.config.texts,toolbarFonts:this.#h(this.config.fonts),hideButtons:this.config.hideButtons,availableWidth:e,role:this.role,isDev:this.isDev}),o=this.config.customButtons||[],i=o.map(l=>this.#c(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))}#c(e){const t=An({...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}#p(){this.#f(),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.#l().find(t=>t.name.value===e)}#l(){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.#p()),this.ui&&(this.snapshot=this.ui.toolbar.getSnapshot()),this.updateToolbarState()}onToolbarResize=()=>{this.#f(),this.updateToolbarState()};#g(e){return e==="ruler"?!!this.superdoc?.config?.rulers:e==="formattingMarks"?!!this.superdoc?.config?.layoutEngineOptions?.showFormattingMarks:!1}#u(e){return e==="ruler"?typeof this.superdoc?.toggleRuler=="function":e==="formattingMarks"?typeof this.superdoc?.toggleFormattingMarks=="function"||typeof this.superdoc?.setShowFormattingMarks=="function":!1}#y(){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)}#w(){const e=this.toolbarItems.find(n=>n.name.value==="highlight");if(!e)return;const t={key:"color",type:"render",render:()=>ab(this,e,[],!0)};e.nestedOptions.value=[t]}#k(e){return!!e?.active&&e?.value==null}#I(e){return!!e&&e.disabled===!1&&e.value==null}#E(e){const t=e.name.value;if(t==="tableActions"){const i=aA.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(rb(t)?.disposition==="host-routed")return e.setDisabled(!this.#u(t)),this.#g(t)?e.activate():e.deactivate(),!0;const n=hA(t);if(!n)return!1;const r=this.snapshot?.commands?.[n];iV(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.#y()},link:()=>{e.active.value=!!r?.active,e.attributes.value=lb(e.attributes.value,r?.value??null)},fontFamily:()=>{if(r?.value!=null){e.activate({fontFamily:r.value});return}if(this.#I(r)){e.activate({},!0);return}e.deactivate()},fontSize:()=>{if(r?.value!=null){e.activate({fontSize:r.value});return}if(this.#k(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.#y(),this.#w();const e=this.snapshot?.commands?.["document-mode"]?.value||"editing";!(this.snapshot&&(this.superdoc?.activeEditor??this.activeEditor))||e==="viewing"?(this.#M(),this.#l().forEach(n=>{n.allowWithoutEditor?.value&&this.#E(n)})):this.#l().forEach(n=>{n.resetDisabled(),this.#E(n)});const t=this.getToolbarItemByName("copyFormat");t&&(this.snapshot?.copyFormatActive?t.activate():t.deactivate()),this.emit("toolbar-state-change")}#M(){this.#l().forEach(e=>{const{allowWithoutEditor:t}=e;t?.value||e.setDisabled(!0)})}#L(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}#P(e,t){const n=e?.name?.value;if(!n)return!1;const r={onSettled:()=>this.updateToolbarState(),onError:i=>this.#b(i,n)};if(n==="image"&&t==null)return this.#T();if(n==="tableActions"){const i=sA[t?.command];return i?gm(this.ui,i,void 0,r):!1}if(rb(n)?.disposition==="unsupported")return!0;const o=hA(n);return o?gm(this.ui,o,t,r):!1}#T(){return this.snapshot?.commands?.image?.disabled||(this.#t||(this.#t=FN({ownerDocument:this.toolbarContainer?.ownerDocument??document,onPick:async e=>{const t=await DN(e,this.superdoc?.config?.handleImageUpload);gm(this.ui,"image",{src:t},{onSettled:()=>this.updateToolbarState(),onError:n=>this.#b(n,"image")})},onError:e=>this.#b(e,"image")})),this.#t.open()),!0}#a(){if(this.#n)return;const e=this.superdoc?.activeEditor?.container??document,t=i=>{pA(i.target)||this.ui.formatPainter.setPointerSelecting(!0)},n=i=>{this.ui.formatPainter.setPointerSelecting(!1),!pA(i.target)&&this.ui.formatPainter.notifyPointerUp()},r=i=>{if(i.key==="Escape"){this.ui.formatPainter.cancel();return}sV(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)}}#S(){this.#n&&(this.#n(),this.#n=null)}#b(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(rb(r)?.disposition==="host-routed"){this.#L(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(!gm(this.ui,o,t,{onSettled:()=>this.updateToolbarState(),onError:s=>this.#b(s,r)}))throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState();return}if(!this.#P(e,t)&&o)throw new Error(`[superdoc toolbar] Command not handled: ${String(o)}`);this.updateToolbarState()}catch(s){this.#b(s,r)}}}destroy(){this.#S(),this.#t?.destroy(),this.#t=null,this.#s(),this.#r(),this.app?.unmount(),this.app=null,this.toolbar=null}};function lV(e){return new aV(e)}function cV(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 uV(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=vm(e.color);n!=null&&(t.color=n),e.highlight!=null&&(t.highlight=e.highlight);const r=fV(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=dV(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=hV(e.border);return i&&(t.border=i),t}function vm(e){if(e){if(typeof e=="string")return e;if(e.model==="rgb")return e.value;if(e.model==="auto")return"auto"}}function dV(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 fV(e){if(!e)return;const t={},n=vm(e.fill);n!=null&&(t.fill=n);const r=vm(e.color);return r!=null&&(t.color=r),e.pattern!=null&&(t.val=e.pattern),Object.keys(t).length>0?t:void 0}function hV(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=vm(e.color);return n!=null&&(t.color=n),Object.keys(t).length>0?t:void 0}function ic(e){const t=e?.selectionTarget??e?.target;if(!e||!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function mA(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function pV(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 mA(r))n(o);return n(e.getAttribute("data-track-change-id")),t}function gA(e,t){if(!e||typeof e.getAttribute!="function")return[];const n=[],r=new Set;let o=[],i=e;for(;i;){const s=i,a=pV(s),l=a.length>0?s.getAttribute("data-story-key"):null;for(const g of a){const p=`trackedChange:${g}`;if(!r.has(p)){r.add(p);const v={type:"trackedChange",id:g};l&&(v.storyKey=l),n.push(v),o.push(v)}}const u=s.getAttribute("data-layout-story");if(u&&o.length>0){for(const g of o)g.story=u;o=[]}const c=s.getAttribute("data-comment-ids");if(c)for(const g of mA(c)){const p=`comment:${g}`;r.has(p)||(r.add(p),n.push({type:"comment",id:g}))}const d=s.getAttribute("data-sdt-type"),h=s.getAttribute("data-sdt-id");if(h&&d==="structuredContent"){const g=`contentControl:${h}`;if(!r.has(g)){r.add(g);const p=s.getAttribute("data-sdt-scope"),v=s.getAttribute("data-sdt-tag"),k={type:"contentControl",id:h};(p==="block"||p==="inline")&&(k.scope=p),v&&(k.tag=v),n.push(k)}}if(t&&i===t)break;i=i.parentElement}return n}var lo=()=>({oneOf:[{type:"boolean"},{type:"null"}]}),cl=()=>({oneOf:[{type:"string",minLength:1},{type:"null"}]}),xu=()=>({oneOf:[{type:"number"},{type:"null"}]}),Ru=e=>({oneOf:[{type:"object",properties:e,additionalProperties:!1,minProperties:1},{type:"null"}]}),mV={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},gV={type:"object",properties:{id:{type:"number"},val:{type:"boolean"}},required:["id"],additionalProperties:!1},vV=()=>({oneOf:[{type:"boolean"},{type:"null"},mV]}),yV=()=>({oneOf:[{type:"array",items:gV,minItems:1},{type:"null"}]});function ym(e,t){return{storage:"mark",markName:e,textStyleAttr:t}}function bV(e){return{storage:"runAttribute",nodeName:"run",runPropertyKey:e}}var cb=(e,t,n)=>({key:e,type:"boolean",ooxmlElement:t,storage:"mark",tracked:!0,carrier:ym(n),schema:lo()}),sc=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"mark",tracked:!0,carrier:ym("textStyle",o??e),schema:r}),jn=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"runAttribute",tracked:!1,carrier:bV(o??e),schema:r});const bm=[cb("bold","w:b","bold"),cb("italic","w:i","italic"),cb("strike","w:strike","strike"),{key:"underline",type:"object",ooxmlElement:"w:u",storage:"mark",tracked:!0,carrier:ym("underline"),schema:vV()},{key:"highlight",type:"string",ooxmlElement:"w:highlight",storage:"mark",tracked:!0,carrier:ym("highlight"),schema:cl()},sc("color","string","w:color",cl()),sc("fontSize","number","w:sz",xu()),sc("fontFamily","string","w:rFonts",cl()),sc("letterSpacing","number","w:spacing",xu()),sc("vertAlign","string","w:vertAlign",{oneOf:[{enum:["superscript","subscript","baseline"]},{type:"null"}]}),sc("position","number","w:position",xu()),jn("dstrike","boolean","w:dstrike",lo()),jn("smallCaps","boolean","w:smallCaps",lo()),sc("caps","boolean","w:caps",lo(),"textTransform"),jn("shading","object","w:shd",Ru({fill:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},val:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),jn("border","object","w:bdr",Ru({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"),jn("outline","boolean","w:outline",lo()),jn("shadow","boolean","w:shadow",lo()),jn("emboss","boolean","w:emboss",lo()),jn("imprint","boolean","w:imprint",lo()),jn("charScale","number","w:w",xu(),"w"),jn("kerning","number","w:kern",xu(),"kern"),jn("vanish","boolean","w:vanish",lo()),jn("webHidden","boolean","w:webHidden",lo()),jn("specVanish","boolean","w:specVanish",lo()),jn("rtl","boolean","w:rtl",lo()),jn("cs","boolean","w:cs",lo()),jn("bCs","boolean","w:bCs",lo(),"boldCs"),jn("iCs","boolean","w:iCs",lo(),"italicCs"),jn("eastAsianLayout","object","w:eastAsianLayout",Ru({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"}]}})),jn("em","string","w:em",cl()),jn("fitText","object","w:fitText",Ru({val:{oneOf:[{type:"number"},{type:"null"}]},id:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),jn("snapToGrid","boolean","w:snapToGrid",lo()),jn("lang","object","w:lang",Ru({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},bidi:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),jn("oMath","boolean","w:oMath",lo()),jn("rStyle","string","w:rStyle",cl(),"styleId"),jn("rFonts","object","w:rFonts",Ru({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"),jn("fontSizeCs","number","w:szCs",xu()),jn("ligatures","string","w14:ligatures",cl()),jn("numForm","string","w14:numForm",cl()),jn("numSpacing","string","w14:numSpacing",cl()),jn("stylisticSets","array","w14:stylisticSets",yV()),jn("contextualAlternates","boolean","w14:cntxtAlts",lo())],dG=new Set(bm.map(e=>e.key)),wV=Object.fromEntries(bm.map(e=>[e.key,e])),fG={mark:bm.filter(e=>e.storage==="mark").map(e=>e.key),runAttribute:bm.filter(e=>e.storage==="runAttribute").map(e=>e.key)};var ub=new WeakMap;function CV(e){let t=ub.get(e);return t||(t={refCount:0,generation:0,abortController:new AbortController,inFlight:null,activeMutationTokens:new Set},ub.set(e,t)),t.refCount+=1,t}function kV(e,t){t.refCount=Math.max(0,t.refCount-1),!(t.refCount>0)&&(t.abortController.abort("ui-controller-destroyed"),t.inFlight=null,t.activeMutationTokens.clear(),ub.delete(e))}var SV=new Set(Object.values(ut));function db(e,t){return typeof e=="string"&&SV.has(e)?e:t}function vA(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:ut.notReady}:{ok:!1,reason:db(t,ut.targetUnresolved)}}return{ok:!0}}var _V=["document-replaced","editorCreate","active-editor-change","document-mode-change","zoomChange","measurement-unit-change","viewport-change","fonts-changed"],AV={[X4.bulletList]:"bullet",[X4.numberedList]:"ordered"};function yA(e){return AV[e]??null}var IV={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 EV(e){const t=IV[e];return t?{preset:t,behavior:"toggleStyle"}:{}}var TV={status:"ready",empty:!0,target:null,selectionTarget:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[],quotedText:""};const xV=[{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: shared all-story tracked-changes catalog; stale-served during load"},{key:"trackChanges:all",match:"exact",note:"audited: current-token validation over the shared all-story catalog; consumers fail closed on non-ready"},{key:"tables",match:"exact",note:"reserved: full tables catalog"},{key:"sections",match:"exact",note:"reserved: full sections list"}];var RV=new Set(["/word/comments.xml","/word/commentsExtended.xml","/word/commentsIds.xml"]);function MV(e){return xV.some(t=>t.match==="exact"?t.key===e:e.startsWith(t.key))}var bA={ready:0,stale:1,pending:2};function Mu(...e){let t="ready";for(const n of e)bA[n]>bA[t]&&(t=n);return t}function Lt(e,t){if(typeof e!="function")return t;try{const n=e();return n===void 0?t:n}catch{return t}}function Cr(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function yr(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 hr(e,t="CAPABILITY_UNAVAILABLE"){return{success:!1,failure:{code:t,message:e}}}function Hf(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 Uf(e){if(!e||typeof e!="object")return null;const t=e.target;return t&&typeof t=="object"?t:null}function fb(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 LV(e){if(!e||typeof e!="object")return null;const t=Uf(e);if(fb(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 kr(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 Lu(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=Uf(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 Wi(e,t,n){return Kn(e)!==t?!1:n?kr(Lu(e))===kr(n):!0}function wm(e){const t=Lu(e);if(!(!t||kr(t)===kr(null)))return t}function PV(e){if(typeof e!="string"||e.length===0)return;const t=x6(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 DV(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 hb(e){if(!e||typeof e!="object")return null;const t=e.selectionTarget;return t&&typeof t=="object"?t:null}function Cm(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function OV(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 Kn(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 FV(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 wA=new WeakMap;function CA(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 ga(e){const t=wA.get(e);if(t)return t;const n=new Set,r=new Map;for(const i of e){const s=Kn(i);if(s){n.add(s);for(const a of CA(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 wA.set(e,o),o}var kA=new WeakMap,SA=new WeakMap;function Pu(e,t){const n=kr(t);let r=kA.get(e);r||(r=new Map,kA.set(e,r));const o=r.get(n);if(o)return o;const i=ga(e.filter(s=>kr(Lu(s))===n));return r.set(n,i),i}function NV(e){return!!e&&typeof e=="object"&&e.storyType==="textbox"}function BV(e,t){const n=t.filter(o=>e.some(i=>Kn(i)===o&&Lu(i)==null));if(n.length===0)return null;if(n.length===1)return n[0];const r=new Set;for(const o of n){const i=e.find(s=>Kn(s)===o);if(i)for(const s of CA(i)){if(r.has(s))return null;r.add(s)}}return n[0]}function zV(e){const t=SA.get(e);if(t)return t;const n=e.filter(o=>Lu(o)!=null),r=n.length===e.length?e:n;return SA.set(e,r),r}function VV(e){const{selectionIds:t,publicIds:n,selection:r,bodyItems:o,allStoryItems:i}=e;if(t.length===0)return null;const s=u=>{for(const c of t){const d=u.toPublicId(c);if(d)return d}return null},a=Ki(r),l=kr(a)===kr(null);if(i){const u=l?zV(i):i,c=s(Pu(u,a));if(c)return c;const d=n?.find(h=>u.some(g=>Wi(g,h,a)));return d||(l?s(ga(o)):NV(a)?BV(i,t):null)}return l?s(ga(o))??t[0]??null:null}function HV(e,t){const n=e.find(r=>Kn(r)===t||r.importedId===t);return n?n.rootCommentId??n.parentCommentId??Kn(n)??t:null}function UV(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 Nr(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 jV=64;function ac(e){return e.length<=jV}function Ki(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 vo(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 _A(e,t){return{kind:"block",nodeType:"listItem",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}var AA=720;function Cs(e){return Math.round(e*20)}function Du(e){return typeof e=="number"&&Number.isFinite(e)}function GV(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=Du(i.left)?Cs(i.left):Du(i.start)?Cs(i.start):void 0,a=Du(i.right)?Cs(i.right):Du(i.end)?Cs(i.end):void 0,l=Du(i.firstLine)?Cs(i.firstLine):void 0,u=Du(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 pb(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 WV(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 jf(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 ul(e){return jf(e.target)??jf(e.selectionTarget)}var IA=["fontFamily","fontSize","color","highlight"],KV={undo:"history.undo",redo:"history.redo"},Gf=["bold","italic","underline","strikethrough"];function mb(e){return IA.includes(e)}function Ou(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 qi(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 qV(e){const t=qi(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=Ou(e);return t.length===0?null:[qV(e),...t.map(n=>`${n.blockId}:${n.start}-${n.end}`)].join("|")}function EA(e){const t=e.selectionTarget;return!t||typeof t!="object"?null:ic({selectionTarget:t})}function YV(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 XV(e,t){return Math.max(e.start,t.start)<Math.min(e.end,t.end)}function ZV(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 QV(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 TA(e,t){const n=Ou(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=>QV(n,ZV(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 JV(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 gb(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 $V(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 eH(e,t){return e==="fontFamily"?t.toLowerCase():e==="color"||e==="highlight"?t.toUpperCase():t}function xA(e,t){if(!e)return{};const n=new Map;for(const i of Ou(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 IA){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 g of h){const p=g?.range,v=typeof p?.start=="number"?p.start:null,k=typeof p?.end=="number"?p.end:null;if(v==null||k==null||!d.some(y=>XV(y,{start:v,end:k})))continue;a=!0;const C=JV(g?.styles,i);if(C===void 0){l=!0;continue}const _=eH(i,C);if(s.has(_)||s.set(_,C),s.size>1)break}if(s.size>1)break}a&&!l&&s.size===1&&(o[i]=[...s.values()][0])}return o}function vb(e,t){const n=Nr(e)[0];return n?t==="nodeId"?{kind:"after",nodeId:n}:{kind:"after",target:vo(n)}:{kind:"documentEnd"}}function ln(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 dl(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 km(e){const t=e,n=t.change;return n&&typeof n=="object"?n:t}function ks(e){if(Cr(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 Sm(e){return!!e&&typeof e=="object"&&e.success===!0}function yo(e){return!(e===!1||e&&typeof e=="object"&&e.success===!1)}function lc(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function yb(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 cc(e,t){return e.sourceAnchor?.sourceNodeId===t?!0:e.id===t}function pi(e){let t=!1,n=null,r=null,o=null;for(const i of e)t=i,!yo(i)&&n===null&&(n=i),Sm(i)&&(o=i),i!==!1&&(r=i);return n??o??r??t}function tH(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 nH(e){return e.startsWith("#")?{kind:"anchor",anchor:e.slice(1)}:{kind:"external",url:e}}function _m(e){return Tu(e)?.trackDecision??null}function rH(e){return{found:e.length>0,success:e.length>0,rects:e,rect:e[0]}}function fl(e){return{found:!1,success:!1,rects:[],reason:e}}function oH(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 iH(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 RA(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(iH))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 sH(e){return e.selectionTarget?e.selectionTarget:RA(e.target)}function Fu(e){if(e.empty)return null;if(e.selectionTarget)return e.selectionTarget;const t=RA(e.target);return t&&t.start.kind==="text"&&t.end.kind==="text"&&t.start.blockId!==t.end.blockId?null:t}function bb(e){return!e.inline||typeof e.docRoute!="string"?null:e.docRoute.startsWith("format.")?e.docRoute.slice(7):null}var wb={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},aH=Object.fromEntries(Object.entries(wb).filter(([e])=>wV[e]?.tracked===!0));function lH(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:{...wb}};default:return null}}function cH(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 uH(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 dH(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},g=0;const p=new Set;let v={},k="",C=null;const _=()=>{const f=t?.activeEditor;return f&&typeof f=="object"?f:null},y=()=>{const f=_()?.doc;return f&&typeof f=="object"?f:null},w=()=>{const f=_()?.v2TrackedChanges;return f&&typeof f=="object"?f:null},x=()=>{const f=_()?.host;return f&&typeof f=="object"?f:null},P=f=>{if(f.storyType!=="headerFooterPart"||typeof f.refId!="string")return null;const m=_(),b=x(),I=m?.pageLayout??b?.pageLayout;if(!I||typeof I!="object")return null;const E=I.getActiveRulerContext,z=b?.resolveHeaderFooterEditTarget;if(typeof E!="function"||typeof z!="function")return null;const K=Lt(()=>E.call(I),null);if(!K||typeof K.pageIndex!="number")return null;for(const oe of["header","footer"]){const me=Lt(()=>z.call(b,{pageIndex:K.pageIndex,kind:oe}),null);if(!(me?.status!=="ready"||me.refId!==f.refId||typeof me.sectionId!="string"||!["default","first","even"].includes(String(me.slotVariant))))return{kind:"story",storyType:"headerFooterSlot",section:{kind:"section",sectionId:me.sectionId},headerFooterKind:oe,variant:me.slotVariant}}return null},N=()=>{const f=x(),m=f?.getPendingInlineFormat;if(typeof m!="function")return null;const b=Lt(()=>m.call(f),null);return b&&typeof b=="object"?b:null},G=f=>{const m=bb(f);if(!m)return null;const b=N();if(!b||!(m in b))return null;const I=b[m];return f.inline?.kind==="toggle"?I===!0:I!=null&&I!==""},R=f=>{const m=bb(f);if(!m)return;const b=N();if(!b||!(m in b))return;const I=b[m];if(typeof I=="string"&&I!=="")return I;if(typeof I=="number"&&Number.isFinite(I))return String(I)},F=(f,m)=>{const b=x(),I=b?.setPendingInlineFormat;typeof I=="function"&&Lt(()=>I.call(b,f,m),void 0)},Z=f=>{const m=x(),b=m?.clearPendingInlineFormat;typeof b=="function"&&Lt(()=>b.call(m,f),void 0)},D=new Set(["bold","italic","underline","strikethrough"]),B=f=>{const m=N();if(!m)return;const b=Array.isArray(f.activeMarks)?f.activeMarks:[];let I=null;for(const E of Object.keys(m)){const z=m[E];let K;if(D.has(E))K=b.includes(E)===(z===!0);else if(mb(E)){if(z==null)continue;I||(I=Sl(f)),K=I[E]===z}else K=!1;K&&Z(E)}},T=()=>{const f=_()?.editCommands;return f&&typeof f=="object"?f:null},V=f=>{const m=T();if(!m||typeof m.getSnapshot!="function")return null;const b=Lt(()=>m.getSnapshot(),null)?.commands?.[f];return b&&typeof b=="object"?b:null},J=()=>V("lists.apply"),q=f=>{const m=f?.value?.seed;return m==="bullet"||m==="ordered"?m:null},se=f=>{const m=KV[f];return m?V(m):null},pe=()=>{const f=x();if(!f||typeof f.getTableContext!="function")return null;const m=Lt(()=>f.getTableContext(),null);return m&&typeof m=="object"?m:null},Ne=()=>{const f=pe();if(!f||f.inTable!==!0)return null;const m=f.table,b=typeof m?.nodeId=="string"&&m.nodeId.length>0?m.nodeId:null;if(!b)return null;const I=f.row,E=f.column,z=f.cell,K=typeof I?.index=="number"&&Number.isInteger(I.index)?I.index:null,oe=typeof E?.index=="number"&&Number.isInteger(E.index)?E.index:null;if(K==null||oe==null)return null;const me=typeof z?.nodeId=="string"&&z.nodeId.length>0?z.nodeId:null,Re=f.cellRange;return{tableNodeId:b,rowIndex:K,columnIndex:oe,cellNodeId:me,mergeRange:cH(Re)}},he=new Map;let ye=null,ce=null,ke=0,ie=0,xe=0;const Je=new Set,st=(f,m)=>f===m?!0:!f||!m?!1:f.id===m.id&&f.paintedEntityId===m.paintedEntityId&&kr(f.story)===kr(m.story),Tt=f=>Array.from(Je).some(m=>st(m,f)),Te=f=>{const m=x();if(typeof m?.getHandles!="function")return;const b=Lt(()=>m.getHandles(),null),I=b?.review;if(I){if(f){if(typeof I.setActiveReviewTarget!="function")return;const E=b?.layout;Lt(()=>I.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 I.getActiveReviewTarget!="function"||typeof I.clearActiveReviewTarget!="function"||Lt(()=>I.getActiveReviewTarget(),null)?.entityType==="trackedChange"&&Lt(()=>I.clearActiveReviewTarget(),void 0)}},je=(f,m)=>{ce=f,ke+=1,xe+=1,m?.invalidateQueuedNavigation!==!1&&(ie+=1)},Ye=new Set;let $=!1,S=null;const ee=new Map,O=new Set;let j=null,U=null,W=!1,te=null,Y=0,X=null,be=null,ve=null;const we=()=>{if(W||$)return;W=!0;const f=()=>{W=!1,$||Xt()};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Be=250,rt=5e3,at=f=>{$||te&&Y<=f||(te&&clearTimeout(te),Y=f,te=setTimeout(()=>{te=null,Y=0,$||Xt()},Math.max(0,f-Date.now())))},Ct=new WeakMap;let en=0;const Et=f=>{if(!f)return"none";let m=Ct.get(f);return m==null&&(m=en+=1,Ct.set(f,m)),`e${m}`};let Ut=0,Wt={};const In=e.superdoc,bt=CV(In),nn=()=>{bt.abortController.abort("review-mutation-started"),bt.inFlight=null},et=()=>{bt.generation+=1,bt.abortController=new AbortController,bt.inFlight=null},Pt=f=>{const m=bt.activeMutationTokens;if(typeof f!="string"||f.length===0||m.has(f))return;const b=m.size===0;m.add(f),b&&nn()},Kt=f=>{const m=bt.activeMutationTokens;typeof f!="string"||!m.delete(f)||m.size===0&&et()},Rn=f=>{const m=w(),b=m?.listTrackedChanges;if(typeof b!="function")return _()?.editorVersion===2?Promise.reject(new Error("v2-tracked-changes-bridge-pending")):f();if(bt.activeMutationTokens.size>0)return Promise.reject(new Error("ui-review-catalog-superseded"));if(_()?.reviewHydration?.getDiagnostics?.()?.inFlight===!0)return Promise.reject(new Error("shell-review-hydration-in-flight"));const I=bt.generation,E=bt.inFlight;if(E?.generation===I)return E.promise;const z=bt.abortController.signal,K=Re=>{if(z.aborted||I!==bt.generation||Re?.reason==="review-hydration-superseded")throw new Error("ui-review-catalog-superseded");return Re},oe=b.call(m,{blocking:!1,signal:z});if(!Cr(oe))return K(oe);const me=Promise.resolve(oe).then(K);return bt.inFlight={generation:I,promise:me},me.then(()=>{bt.inFlight?.promise===me&&(bt.inFlight=null)},()=>{bt.inFlight?.promise===me&&(bt.inFlight=null)}),me};let Nt=null,un=null,Mn=0;const Pe=()=>{un&&clearTimeout(un),un=null,Mn=0};let Ge=f=>{},We=null,ft=new Set,Vt=null,yt=0,$t=null;const At=()=>`${Et(_())}|m${Ut}`,kn=()=>{We=null,ft=new Set},Nn=f=>{for(const m of["trackChanges","trackChanges:all"]){const b=ee.get(m);if(!b?.hasSettled||!Array.isArray(b.value))continue;const I=b.value.filter(E=>{const z=Kn(E);return!z||!f.has(z)});I.length!==b.value.length&&ee.set(m,{...b,value:I})}},Uo=f=>{const m=()=>{if(!$)for(const z of[...Ye])z(dt)},b=lc(f)?f:null,I=_()?.documentMutationReadiness,E=()=>{const z=globalThis.requestAnimationFrame;return typeof z!="function"?Promise.resolve():new Promise(K=>{let oe=!1;const me=()=>{oe||(oe=!0,clearTimeout(Re),K())},Re=setTimeout(me,250);z(()=>z(()=>setTimeout(me,0)))})};if(b?.success===!0&&typeof b.txId=="string"&&b.txId.length>0&&typeof I?.whenPainted=="function")try{Promise.resolve(I.whenPainted.call(I,b)).then(E,()=>{}).then(m,m);return}catch{}m()},Ht=(f,m)=>{const b=dt.trackChanges,I=b.items.filter(K=>{const oe=Kn(K);return!oe||!f.has(oe)});if(I.length===b.items.length)return;ce&&f.has(ce.id)&&je(null);const E=new Set;for(const K of I){const oe=km(K),me=K,Re=oe.author??oe.authorEmail??me.author??me.authorEmail;typeof Re=="string"&&E.add(Re)}const z=b.items.length-I.length;dt={...dt,trackChanges:{...b,items:I,total:Math.max(I.length,b.total-z),activeId:b.activeId&&f.has(b.activeId)?null:b.activeId,authors:[...E]}},Uo(m)},Pn=f=>{const m=dt.trackChanges,b=m.items.length>0||m.total!==0||m.activeId!==null||m.authors.length>0;Vt=At(),ce!==null&&je(null),dt={...dt,trackChanges:{...m,items:[],total:0,activeId:null,authors:[]}},b&&Uo(f)},br=(f,m)=>{if(f.size===0)return;const b=At(),I=We===b?ft:new Set,E=new Set([...f].filter(z=>!I.has(z)));E.size!==0&&(We=b,ft=new Set([...I,...E]),Nn(ft),Ht(E,m))},Do=f=>We===f&&ft.size>0?ft:null,er=(f,m=[])=>{const b=f.map(dl).filter(E=>E!=null&&Kn(E)!=null);if(b.length===0)return;const I=m.map(dl).map(E=>E==null?null:Kn(E)).filter(E=>E!=null);for(const E of["trackChanges","trackChanges:all"]){const z=ee.get(E),K=z?.hasSettled&&Array.isArray(z.value)?[...z.value]:[],oe=new Set;let me=!1;for(const Re of b){const Ue=Kn(Re);if(!Ue)continue;const Ke=K.findIndex(Fe=>Kn(Fe)===Ue);if(Ke<0)K.push(Re),oe.add(Ue);else{const Fe=K[Ke];K[Ke]=lc(Fe)?{...Fe,...Re}:Re}me=!0}if(E==="trackChanges"&&oe.size>0&&I.length>0){const Re=new Set(I.filter(Fe=>oe.has(Fe))),Ue=new Map(K.filter(Fe=>Re.has(Kn(Fe)??"")).map(Fe=>[Kn(Fe),Fe])),Ke=K.filter(Fe=>!Re.has(Kn(Fe)??""));for(const[Fe,Xe]of I.entries()){if(!Re.has(Xe))continue;const He=Ue.get(Xe);if(!He)continue;const Ze=I.slice(Fe+1).map(ot=>Ke.findIndex(nt=>Kn(nt)===ot)).find(ot=>ot>=0);if(Ze!=null){Ke.splice(Ze,0,He);continue}const Qe=I.slice(0,Fe).reverse().map(ot=>Ke.findIndex(nt=>Kn(nt)===ot)).find(ot=>ot>=0);Ke.splice(Qe==null?Ke.length:Qe+1,0,He)}K.splice(0,K.length,...Ke)}me&&ee.set(E,{token:z?.token??null,value:K,hasSettled:!0,inflightToken:null})}},cn=f=>{const m=At(),b=Do(m),I=f.map(dl).filter(E=>{if(E==null)return!1;const z=Kn(E);return z!=null&&!b?.has(z)});for(const E of["trackChanges","trackChanges:all"])ee.set(E,{token:m,value:[...I],hasSettled:!0,inflightToken:null})},Gn=async(f,m)=>{try{const b=f.v2TrackedChanges?.listTrackedChanges;if(typeof b=="function"){const z=await Promise.resolve(b.call(f.v2TrackedChanges,{mode:m.trackedChangesListMode,refreshReason:m.refreshReason,blocking:m.blocking,...m.targetIds?.length?{targetIds:m.targetIds}:{}})),K=m.trackedChangesListMode==="all"&&m.refreshReason==="mutation-history-render-reconcile"?z?.ok===!0:z?.ok!==!1;return{ok:K,items:K&&Array.isArray(z?.items)?z.items:[],...typeof z?.complete=="boolean"?{complete:z.complete}:{},...typeof z?.sourceCoverageComplete=="boolean"?{sourceCoverageComplete:z.sourceCoverageComplete}:{}}}const I=f.docTrackChanges?.list;if(typeof I!="function")return{ok:!1,items:[]};const E=await Promise.resolve(I.call(f.docTrackChanges));return{ok:!0,items:Array.isArray(E?.items)?E.items:[]}}catch(b){return{ok:!1,items:[],failures:[b]}}},Br=Wk({getContext:()=>{const f=_();if(!f)return null;const m=w(),b=y()?.trackChanges??null,I=m??b;if(!I)return null;const E=f.documentId??m?.documentId;return{editor:f,adapter:I,documentId:E==null?null:String(E),reconcileToken:Wt,v2TrackedChanges:m,docTrackChanges:b}},reconcile:async(f,m)=>{m.removedIds.size>0&&br(new Set(m.removedIds));const b=[...new Set(m.upsertIds)];if(b.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};const I=ee.get("trackChanges"),E=I?.hasSettled&&Array.isArray(I.value)?I.value:null,z=new Set(E?E.map(Kn).filter(Qe=>Qe!=null):[]),K=E?.length===0&&ba()==="complete",oe=new Set(b.filter(Qe=>!z.has(Qe))),me=f.v2TrackedChanges?.getTrackedChange,Re=f.docTrackChanges?.get;if(typeof me!="function"&&typeof Re!="function")return{ok:!1,items:[],resolvedIds:[],unresolvedIds:b};const Ue=await Promise.all(b.map(async Qe=>{try{if(typeof me=="function"){const nt=await Promise.resolve(me.call(f.v2TrackedChanges,Qe));return{id:Qe,ok:nt?.ok!==!1,items:nt?.ok!==!1&&Array.isArray(nt?.items)?nt.items:[],result:nt}}const ot=await Promise.resolve(Re.call(f.docTrackChanges,{id:Qe}));return{id:Qe,ok:!0,items:ot&&typeof ot=="object"?[ot]:[],result:ot}}catch(ot){return{id:Qe,ok:!1,items:[],result:ot}}})),Ke=[],Fe=[],Xe=[];for(const Qe of Ue){const ot=Qe.items.filter(nt=>{const Ot=dl(nt);return Ot!=null&&Kn(Ot)===Qe.id});Qe.ok&&ot.length>0?(Ke.push(...ot),Fe.push(Qe.id)):Xe.push(Qe.id)}let He;const Ze=Fe.filter(Qe=>oe.has(Qe));if(Ze.length>0&&!K){const Qe=await Gn(f,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1,targetIds:Ze});Qe.ok&&(He=Qe.items)}return{ok:Xe.length===0,items:Ke,orderedItems:He,resolvedIds:Fe,unresolvedIds:Xe,failures:Ue.filter(Qe=>!Qe.ok).map(Qe=>Qe.result)}},hydrate:Gn,onReconciled:(f,m,b)=>{if(b?.reconcileMode==="authoritative"){if(f.reconcileToken!==Wt)return;b.ok===!0&&b.complete===!0&&b.sourceCoverageComplete===!0?(Pe(),cn(b.items??[]),Nt=null):b.ok===!0?(Pe(),er(b.items??[])):Ge(f.reconcileToken),Xt();return}er((b?.items??[]).filter(I=>{const E=dl(I),z=E==null?null:Kn(E);return z!=null&&m.has(z)}),b?.orderedItems??b?.items??[]),Xt()}});Ge=f=>{if($||un)return;const m=Math.min(Be*2**Mn,rt);Mn+=1,un=setTimeout(()=>{un=null,!($||Nt===null||f!==Wt)&&Br.onRender(!0)},m)};const ei=()=>`${At()}|m${Xn()}|s${yt}`,bo=f=>JSON.stringify({t:f.target??null,s:f.selectionTarget??null}),Jr=["contentControls:inRange:","query:","effInline:"],Xi=120,Ri=180,ba=()=>{const f=x(),m=f?.getDocumentLoadingSnapshot;if(typeof m!="function")return"unknown";const b=Lt(()=>m.call(f),null)?.sourceStage;return b==="opening"||b==="bootstrap-ready"||b==="source-loading"?"loading":b==="source-complete"||b==="source-failed"||b==="source-cancelled"?"complete":"unknown"},ti=new Map,wa=f=>{const m=At();ti.get(f)!==m&&(ti.set(f,m),we())},uc=()=>{const f=ee.get("comments");return f?.hasSettled?Array.isArray(f.value)&&f.value.length>0:f?.inflightToken!=null},Oo=(f,m)=>ti.get(f)===m,jo=f=>{wa("contentControls")},Se=()=>{const f=ee.get("trackChanges");f?.hasSettled||f?.inflightToken!=null||wa("trackChanges")},Ve=6500,_t=8e3,lt=250;let Ln=0,Bn=0,sr=!1,Sr=0,wo=!1,Co=null;const mi=()=>{if($||Co)return;const f=Sr||Date.now(),m=()=>{if(Co=null,$)return;const b=Date.now()-Ln,I=gi()||b<Ve;if(I&&Date.now()-f<_t){Co=setTimeout(m,lt);return}sr=!1,wo=I;try{Xt()}finally{wo=!1,Sr=0}};Co=setTimeout(m,0)};let co=null,pr=null;const hl=()=>{const f=x();if(!f||co===f)return;pr&&(pr(),pr=null),co=f;const m=f.subscribeDocumentLoading;if(typeof m!="function"){co=null,zr(Ve);return}try{const b=z=>{const K=z?.sourceStage;(K==="source-complete"||K==="source-failed"||K==="source-cancelled")&&mi()},I=m.call(f,b);typeof I=="function"&&(pr=I);const E=f.getDocumentLoadingSnapshot;typeof E=="function"&&b(Lt(()=>E.call(f),null))}catch{co=null,zr(Ve)}},Ca=()=>{const f=_()?.host,m=f?.getForegroundMutationState;if(typeof m!="function")return null;const b=Lt(()=>m.call(f),null);return{active:typeof b?.active=="number"?b.active:0,pending:typeof b?.pending=="number"?b.pending:0}},gi=()=>{const f=Ca();return!!(f&&(f.active>0||f.pending>0))},zr=(f=Xi)=>{$||X||(X=setTimeout(()=>{if(X=null,$)return;if(be&&gi()){zr(),Xt();return}const m=be;be=null,m===ei()&&As("selection",m,fc,uo),Xt()},f))},ni=(f,m)=>{if(!Ca())return!1;const b=`${f}\0${m}`;return O.has(b)?!1:(O.add(b),zr(Ri),!0)},ko=f=>{if(j==null||f===j)return U?.timer&&clearTimeout(U.timer),U=null,j=f,!1;if(U?.key===f)return U.ready?(U=null,j=f,!1):!0;U?.timer&&clearTimeout(U.timer);const m={key:f,ready:!1,timer:null};return m.timer=setTimeout(()=>{$||U!==m||(m.timer=null,m.ready=!0,Xt())},Ri),U=m,!0},Mi=f=>Kk(f),vi=()=>{Es(),Xt()};let ka=null,pl=!1,ri=0;const Ss=()=>{ka=null,pl=!1,ri+=1},_s=()=>{const f=_(),m=f?.documentMutationReadiness;if(!f||typeof m?.whenPainted!="function"||(ka={editor:f,readiness:m,afterEpoch:typeof m.getRenderEpoch=="function"?Lt(()=>m.getRenderEpoch.call(m),null):null},pl))return;pl=!0;const b=ri;(async()=>{for(;!$&&b===ri;){const E=ka;if(ka=null,!E){pl=!1;return}let z=!1;try{await E.readiness.whenPainted.call(E.readiness,typeof E.afterEpoch=="number"?{afterEpoch:E.afterEpoch}:void 0),z=!0}catch{}if($||b!==ri)return;if(_()!==E.editor){Ss();return}z&&vi()}})()},ml=()=>{ve&&clearTimeout(ve),ve=setTimeout(()=>{ve=null,$||vi()},500)},As=(f,m,b,I)=>{let E;try{E=b()}catch{E=void 0}if(!Cr(E)){const oe={token:m,value:I(E),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0};return ee.set(f,oe),oe}const z=ee.get(f),K=z?.failedToken===m;return ee.set(f,{token:z?.token??null,value:z?.value??null,hasSettled:z?.hasSettled??!1,inflightToken:m,failedToken:K?m:null,failureCount:K?z.failureCount??0:0,retryAtMs:0}),Promise.resolve(E).then(oe=>{const me=ee.get(f);!me||me.inflightToken!==m||(ee.set(f,{token:m,value:I(oe),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0}),we())},()=>{const oe=ee.get(f);if(!oe||oe.inflightToken!==m)return;const me=oe.failedToken===m?(oe.failureCount??0)+1:1,Re=Math.min(rt,Be*2**Math.min(me-1,8)),Ue=Date.now()+Re;ee.set(f,{...oe,inflightToken:null,failedToken:m,failureCount:me,retryAtMs:Ue}),at(Ue)}),null},Vr=(f,m,b,I)=>{const E=ee.get(f);if(E&&E.token===m&&E.hasSettled)return{value:E.value,status:"ready"};if(MV(f)&&!Oo(f,m)){if(ba()==="loading")return sr=!0,hl(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(sr&&!wo)return mi(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!wo){const K=Date.now();if(K-Bn<Ve&&(!Sr||K-Sr<_t))return Sr||(Sr=K),sr=!0,mi(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};Sr=0}}if(gi())return zr(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(E?.failedToken===m&&E.inflightToken==null&&(E.retryAtMs??0)>Date.now())return at(E.retryAtMs),E.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!E&&f.startsWith("effInline:")&&ko(f))return{value:null,status:"pending"};if(!E&&ni(f,m))return{value:null,status:"pending"};if(!E||E.inflightToken!==m){const K=As(f,m,b,I);if(K)return{value:K.value,status:"ready"}}const z=ee.get(f);return z?.hasSettled?{value:z.value,status:"stale"}:{value:null,status:"pending"}},Nu=f=>{for(const m of ee.keys())f(m)&&ee.delete(m)},Is=f=>{const m=bo(f),b=EA(f);return new Set([`contentControls:inRange:${m}`,`query:${m}`,...b?[`effInline:${b}`]:[]])},Wf=f=>{const m=Is(f);Nu(b=>Jr.some(I=>b.startsWith(I))&&!m.has(b));for(const b of O){const I=b.split("\0",1)[0];Jr.some(E=>I.startsWith(E))&&!m.has(I)&&O.delete(b)}},Sa=()=>{const f=_();f!==$t&&(Ss(),Br.reset(),Wt={},$t=f,ee.clear(),Nt=null,Pe(),te&&clearTimeout(te),te=null,Y=0,U?.timer&&clearTimeout(U.timer),U=null,j=null,C=null,o=null,be=null,O.clear(),ti.clear(),sr=!1,Sr=0,pr&&pr(),pr=null,co=null,kn(),Vt=null)},Es=()=>{const f=Nt!==null;Ut+=1,f&&(Nt=At()),kn()},Go=()=>{const f=Vt===At();Es(),f&&(cn([]),Vt=At()),Xt()},Li=f=>{if(typeof f!="string"||f.length===0)return hr("insertText requires a non-empty string.","INVALID_INPUT");if(Xn()==="viewing")return hr("The document is read-only.","DOCUMENT_READONLY");const m=y(),b=m?.insert;if(!m||typeof b!="function")return hr("insert is unavailable.");const I=m.selection?.current;if(typeof I!="function")return hr("selection.current is unavailable.");const E=K=>{const oe=K&&typeof K=="object"?K:null,me=oe?.selectionTarget??oe?.target??null;return!me||typeof me!="object"?hr("insertText requires a live selection target.","PRECONDITION_FAILED"):Lt(()=>La(b.call(m,{type:"text",value:f,target:me}),hr("insert failed.")),hr("insert failed."))};let z;try{z=I.call(m.selection)}catch{return hr("insertText could not resolve the live selection.","PRECONDITION_FAILED")}return Cr(z)?Promise.resolve(z).then(E,()=>hr("insertText could not resolve the live selection.","PRECONDITION_FAILED")):E(z)},Bu=(f,m)=>({payload:f,state:dt,editor:_(),superdoc:t,context:m,ui:S,execute:(b,I)=>Mc(b,I),executeAsync:(b,I)=>Pm(b,I),doc:y(),selection:dt.selection,documentMode:Xn(),insertText:Li}),gl=f=>f==="editing"||f==="suggesting"||f==="viewing"?f:null,Xn=()=>{const f=_(),m=t&&typeof t=="object"?t:null,b=gl(m?.config?.documentMode),I=gl(Lt(typeof m?.getActiveRuntime=="function"?()=>{const z=m.getActiveRuntime();return typeof z?.getSnapshot=="function"?z.getSnapshot():null}:void 0,null)?.documentMode),E=gl(f?.options?.documentMode);return b&&I&&b!==I?b:I??b??E},zu=()=>{const f=t&&typeof t=="object"?t:null,m=f?.interactionConfig?.comments;if(m&&typeof m.readOnly=="boolean")return m.readOnly===!0;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.readOnly===!0},dc=()=>{const f=t&&typeof t=="object"?t:null,m=f?.interactionConfig?.comments;if(m&&typeof m.allowResolve=="boolean")return m.allowResolve===!1;const b=f?.config?.modules?.comments;return!!b&&typeof b=="object"&&b.allowResolve===!1},Zi=()=>Xn()==="viewing"||zu(),uo=f=>f&&typeof f=="object"?f:null,Ts=(f,m)=>{if(!f)return{...TV,status:m};const b=f.target??null,I=typeof f.text=="string"?f.text:"";return{status:m,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:I}},_a=()=>{const f=y()?.selection;return Vr("selection",ei(),()=>f?.current?f.current({includeText:!0}):void 0,uo)},Kf=()=>{const{value:f,status:m}=_a();return Ts(f,m)},fc=()=>{const f=y()?.selection;return f?.current?f.current({includeText:!0}):void 0},hc=f=>{if(f.empty!==!0)return!1;const m=f.selectionTarget,b=m?.start,I=m?.end;return b?.kind==="text"&&I?.kind==="text"&&typeof b.blockId=="string"&&b.blockId===I.blockId&&typeof b.offset=="number"&&b.offset===I.offset},vl=f=>{const m=x(),b=m?.readLiveSelectionSyncSnapshot;if(typeof b!="function")return;const I=uo(Lt(()=>b.call(m),null));if(!I||!hc(I))return;const E=ei(),z=Ca(),K=!!(z&&(z.active>0||z.pending>0));if(K)be=E,zr();else if(be=null,As("selection",E,fc,uo))return;const oe=ee.get("selection"),me=Array.isArray(I.activeMarks)&&I.activeMarks.length>0?I.activeMarks:Array.isArray(dt.selection.activeMarks)?dt.selection.activeMarks:[],Re=Array.isArray(I.activeCommentIds)?I.activeCommentIds:[],Ue=FV(f),Ke=ul(dt.selection),Fe=jf(I.selectionTarget)??jf(I.target),Xe=Ke?.range,He=Fe?.range,Ze=!!(z&&z.active>0&&Ke&&Fe&&Ke.blockId===Fe.blockId&&kr(Ke.story)===kr(Fe.story)&&typeof Xe?.start=="number"&&typeof He?.start=="number"&&Math.abs(He.start-Xe.start)<=2),Qe=Ue!=null||Ze?dt.selection.activeChangeIds.filter(nt=>Ue==null||ga(dt.trackChanges.items).aliasesFor(nt).includes(Ue)):[],ot=Array.isArray(I.activeChangeIds)&&I.activeChangeIds.length>0?I.activeChangeIds:Qe;ee.set("selection",{token:E,value:{...I,activeMarks:me,activeCommentIds:Re,activeChangeIds:ot},hasSettled:!0,inflightToken:K?null:oe?.inflightToken??null})},yl=async(f=0)=>{const m=y()?.selection,b=m?.current,I=ei();if(typeof b!="function")return ee.set("selection",{token:I,value:null,hasSettled:!0,inflightToken:null}),Xt(),dt.selection;let E;try{E=b.call(m,{includeText:!0}),Cr(E)&&(E=await Promise.resolve(E))}catch{E=null}return $?Ts(null,"pending"):ei()!==I?f<1?yl(f+1):dt.selection:(ee.set("selection",{token:I,value:uo(E),hasSettled:!0,inflightToken:null}),Xt(),dt.selection)},qf=f=>{const m=y()?.comments,{value:b,status:I}=Vr("comments",At(),()=>m?.list?m.list():void 0,oe=>oe&&Array.isArray(oe.items)?oe.items:[]),E=b??[],z=f.activeCommentIds;ye&&!E.some(oe=>Kn(oe)===ye)&&(ye=null);const K=ye??z[0]??null;return{status:Mu(I,f.status),listStatus:I,items:E,total:E.length,activeIds:z,activeId:K}},Qi=()=>{const f=y()?.trackChanges,m=At(),b=ee.get("trackChanges:all"),{value:I,status:E}=Nt===m?{value:b?.hasSettled?b.value:null,status:b?.hasSettled?"stale":"pending"}:Vr("trackChanges:all",m,()=>{if(!f?.list)return;const z=()=>f.list({in:"all"}),K=typeof w()?.listTrackedChanges=="function",oe=Rn(z);return K?Promise.resolve(oe).then(me=>{const Re=lc(me)?me:null;return(Array.isArray(Re?.items)?Re.items:[]).some(Ue=>Lu(Ue)==null)?z():me}):oe},z=>(z&&Array.isArray(z.items)?z.items:[]).map(dl).filter(K=>K!=null));return E==="ready"?I:null},bl=f=>{const m=y()?.trackChanges,b=w(),I=typeof b?.listTrackedChanges=="function"?b.listTrackedChanges:null,E=At(),z=Do(E),K=ee.get("trackChanges"),{value:oe,status:me}=Nt===E?{value:K?.hasSettled?K.value:null,status:K?.hasSettled?"stale":"pending"}:Vr("trackChanges",E,()=>I?Rn(()=>m?.list?.()):m?.list?m.list({in:"all"}):void 0,on=>on&&Array.isArray(on.items)?on.items:[]),Re=(oe??[]).map(dl).filter(on=>on!=null).filter(on=>{const Dn=Kn(on);return!Dn||!z?.has(Dn)}),Ue=new Set;for(const on of Re){const Dn=km(on),Mr=on,Ar=Dn.author??Dn.authorEmail??Mr.author??Mr.authorEmail;typeof Ar=="string"&&Ue.add(Ar)}const Ke=m?.list?Qi():null,Fe=ce;Fe&&(Fe.story?Ke&&!Ke.some(on=>Wi(on,Fe.id,Fe.story))&&je(null):Re.some(on=>Kn(on)===Fe.id)||je(null));const Xe=Ke??Re,He=Pu(Xe,Ki(f)),Ze=Vt===E?[]:z?f.activeChangeIds.filter(on=>!z.has(on)):f.activeChangeIds,Qe=Ze.map(on=>He.toPublicId(on)??on),ot=ce?.story?Pu(Xe,ce.story):ga(Xe),nt=ce?ot.toPublicId(ce.id)??ce.id:null,Ot=VV({selectionIds:Ze,publicIds:Qe,selection:f,bodyItems:Re,allStoryItems:Ke}),Qt=nt??Ot;return{status:Mu(me,f.status),items:Re,total:Re.length,activeId:Qt,authors:[...Ue]}},Aa=f=>{const m=y()?.contentControls,{value:b,status:I}=Vr("contentControls",At(),()=>m?.list?m.list():void 0,oe=>oe&&Array.isArray(oe.items)?oe.items:[]),E=b??[],{ids:z,status:K}=Yf(m,f);return{status:Mu(I,K,f.status),items:E,total:E.length,activeId:z[0]??null,activeIds:z}},xs=(f,m)=>{if(!f||typeof f.listInRange!="function")return{lockModesById:new Map,status:"ready"};const b=UV(m);if(!b)return{lockModesById:new Map,status:"ready"};const{value:I,status:E}=Vr(`contentControls:inRange:${bo(m)}`,At(),()=>f.listInRange(b),oe=>oe&&Array.isArray(oe.items)?oe.items:[]),z=I??[],K=new Map;for(const oe of z)typeof oe?.id=="string"&&K.set(oe.id,typeof oe.lockMode=="string"?oe.lockMode:"unlocked");return{lockModesById:K,status:E}},Yf=(f,m)=>{const{lockModesById:b,status:I}=xs(f,m);return{ids:[...b.keys()],status:I}},yi=()=>{const f=t?.fonts;return{options:gH(pH(Lt(f?.getDocumentFontOptions?()=>f.getDocumentFontOptions():void 0,[])),mH(Lt(f?.getFontFamilyOptions?()=>f.getFontFamilyOptions():void 0,[]))),sizeOptions:vH}},bi=()=>{const f=Lt(t?.getZoomState?()=>t.getZoomState():void 0,null),m=typeof f?.value=="number"?f.value:100,b=f?.mode;return{mode:b==="manual"||b==="fit-width"?b:b==="fixed"?"manual":null,value:m,min:typeof f?.min=="number"?f.min:10,max:typeof f?.max=="number"?f.max:100}},Kr=()=>Lt(t?.getMeasurementUnit?()=>t.getMeasurementUnit():void 0,"in")==="cm"?"cm":"in",pc=()=>{const f=_();return{ready:f!=null,mode:Xn(),dirty:f?!!f.isDirty:!1}},wl=f=>{const m=f.quotedText;if(typeof m!="string"||m.length===0)return null;const b=Ou(f);if(b.length===0||!ac(b.map(z=>z.blockId)))return null;const I=f.target,E=b.length===1?vo(b[0].blockId,I?.story):void 0;return{select:{type:"text",pattern:m,mode:"contains",caseSensitive:!0},...E?{within:E}:{},require:"any"}},Rs=f=>{const m=y()?.query;if(typeof m?.match!="function")return null;const b=wl(f);if(!b)return null;const{value:I}=Vr(`query:${bo(f)}`,At(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return TA(I,f)},Ia=f=>{const m=x(),b=new Set(Nr(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Lt(()=>{if(typeof I!="function")return E.call(m);const Ze=qi(f);return Ze?I.call(m,[...b],Ze):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=yb(z),oe=Ze=>{const Qe={},ot=gb(Ze.fontFamily);ot&&(Qe.fontFamily=ot);const nt=$V(Ze.fontSize);return nt&&(Qe.fontSize=nt),typeof Ze.color=="string"&&Ze.color.trim()!==""&&(Qe.color=Ze.color.trim().toUpperCase()),typeof Ze.highlight=="string"&&Ze.highlight.trim()!==""&&(Qe.highlight=Ze.highlight.trim().toUpperCase()),Qe},me=ul(f),Re=me&&typeof me.range?.start=="number"?me.range.start:null;if(me&&Re!==null&&b.has(me.blockId)){const Ze=K.find(ot=>cc(ot,me.blockId)),Qe=Ze&&Array.isArray(Ze.runs)?Ze.runs:null;if(Qe&&Qe.length>0&&Qe.every(ot=>ot?.kind==="text"||ot?.kind==="tab")){let ot=0,nt=null;for(const Ot of Qe){const Qt=typeof Ot.text=="string"?Ot.text.length:0;if(Re>=ot&&Re<ot+Qt){nt=Ot;break}ot+=Qt}if(!nt){for(let Ot=Qe.length-1;Ot>=0&&!nt;Ot-=1)Qe[Ot]?.kind==="text"&&(nt=Qe[Ot]);nt??=Qe[Qe.length-1]??null}return nt?oe(nt):{}}}const Ue=Ou(f);if(Ue.length>0){const Ze=new Set,Qe=new Set;let ot=!1,nt=!0;for(const Ot of Ue){const Qt=K.find(Mr=>cc(Mr,Ot.blockId));if(!Qt)return{};const on=Array.isArray(Qt.runs)?Qt.runs:[];if(on.length===0)continue;if(!on.every(Mr=>Mr?.kind==="text"||Mr?.kind==="tab")){nt=!1;break}let Dn=0;for(const Mr of on){const Ar=typeof Mr.text=="string"?Mr.text.length:0,jr=Dn,Lr=Dn+Ar;if(jr<Ot.end&&Lr>Ot.start){ot=!0;const Ko=oe(Mr);Ko.fontFamily&&Ze.add(Ko.fontFamily),Ko.fontSize&&Qe.add(Ko.fontSize)}Dn=Lr}}if(nt&&ot){const Ot={};return Ze.size===1&&(Ot.fontFamily=[...Ze][0]),Qe.size===1&&(Ot.fontSize=[...Qe][0]),Ot}}const Ke=new Set,Fe=new Set;let Xe=!1;for(const Ze of K){if(![...b].some(ot=>cc(Ze,ot)))continue;const Qe=Array.isArray(Ze.runs)?Ze.runs:[];for(const ot of Qe){if(ot?.kind!=="text")continue;Xe=!0;const nt=oe(ot);nt.fontFamily&&Ke.add(nt.fontFamily),nt.fontSize&&Fe.add(nt.fontSize)}}if(!Xe)return{};const He={};return Ke.size===1&&(He.fontFamily=[...Ke][0]),Fe.size===1&&(He.fontSize=[...Fe][0]),He},Wo=f=>{const m=x(),b=new Set(Nr(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Lt(()=>{if(typeof I!="function")return E.call(m);const He=qi(f);return He?I.call(m,[...b],He):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=yb(z),oe=He=>({bold:He.bold===!0,italic:He.italic===!0,underline:He.underline!=null,strikethrough:He.strike===!0}),me=He=>{const Ze={};for(const Qe of Gf){const ot=He[Qe];ot.size===1&&(Ze[Qe]=[...ot][0])}return Ze},Re=ul(f),Ue=Re&&typeof Re.range?.start=="number"?Re.range.start:null;if(Re&&Ue!==null&&b.has(Re.blockId)){const He=K.find(Qe=>cc(Qe,Re.blockId)),Ze=He&&Array.isArray(He.runs)?He.runs:null;if(Ze&&Ze.length>0&&Ze.every(Qe=>Qe?.kind==="text"||Qe?.kind==="tab")){let Qe=0,ot=null;for(const nt of Ze){const Ot=typeof nt.text=="string"?nt.text.length:0;if(Ue>=Qe&&Ue<Qe+Ot){ot=nt;break}Qe+=Ot}if(!ot){for(let nt=Ze.length-1;nt>=0&&!ot;nt-=1)Ze[nt]?.kind==="text"&&(ot=Ze[nt]);ot??=Ze[Ze.length-1]??null}return ot?oe(ot):{}}}const Ke=Ou(f);if(Ke.length>0){const He={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Ze=!1,Qe=!0;for(const ot of Ke){const nt=K.find(on=>cc(on,ot.blockId));if(!nt)return{};const Ot=Array.isArray(nt.runs)?nt.runs:[];if(Ot.length===0)continue;if(!Ot.every(on=>on?.kind==="text"||on?.kind==="tab")){Qe=!1;break}let Qt=0;for(const on of Ot){const Dn=typeof on.text=="string"?on.text.length:0,Mr=Qt,Ar=Qt+Dn;if(Mr<ot.end&&Ar>ot.start){Ze=!0;const jr=oe(on);for(const Lr of Gf)He[Lr].add(jr[Lr])}Qt=Ar}}if(Qe&&Ze)return me(He)}const Fe={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Xe=!1;for(const He of K){if(![...b].some(Qe=>cc(He,Qe)))continue;const Ze=Array.isArray(He.runs)?He.runs:[];for(const Qe of Ze){if(Qe?.kind!=="text")continue;Xe=!0;const ot=oe(Qe);for(const nt of Gf)Fe[nt].add(ot[nt])}}return Xe?me(Fe):{}},Cl=(f,m)=>{if(m.fontFamily!==void 0&&m.fontSize!==void 0&&m.color!==void 0&&m.highlight!==void 0)return{values:m,effectiveUniformityStatus:"ready"};const b=Ia(f),I={...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}:{},...m};if(!f.empty&&(I.fontFamily===void 0||I.fontSize===void 0)){const E=kl(f);return E.values&&(I.fontFamily===void 0&&E.values.fontFamily!==void 0&&(I.fontFamily=E.values.fontFamily),I.fontSize===void 0&&E.values.fontSize!==void 0&&(I.fontSize=E.values.fontSize)),{values:I,effectiveUniformityStatus:E.status}}return{values:I,effectiveUniformityStatus:"ready"}},Xf=["fontFamily","fontSize","bold","italic","underline","strikethrough"],Vu=f=>{const m=f.selectionTarget;if(!m)return{value:null,status:"ready"};const b=yr(y(),"format.readEffectiveInlineUniformity");return b?Vr(`effInline:${EA(f)??bo(f)}`,At(),()=>b({target:m,offsetSpace:"selection",keys:Xf}),I=>I&&typeof I=="object"?I:null):{value:null,status:"ready"}},kl=f=>{const{value:m,status:b}=Vu(f);if(!m||m.success!==!0)return{values:null,status:b};const I=m.values,E=z=>{const K=I?.[z];if(!(!K||K.state!=="uniform"||typeof K.value!="string"))return z==="fontFamily"?gb(K.value):K.value};return{values:{fontFamily:E("fontFamily"),fontSize:E("fontSize")},status:b}},Zf=f=>{const{value:m,status:b}=Vu(f);if(!m||m.success!==!0)return{values:null,status:b};const I=m.values,E={};for(const z of Gf){const K=I?.[z];K?.state==="uniform"&&(K.value==="true"||K.value==="false")&&(E[z]=K.value==="true")}return{values:E,status:b}},Hu=(f,m)=>{const b=f.activeMark;if(!b||!Gf.includes(b))return null;const I=b,E=Wo(m)[I];if(E!==void 0)return E;const{values:z}=Zf(m),K=z?.[I];return K!==void 0?K:null},mc=async f=>{const m=f.selectionTarget;if(!m)return null;const b=yr(y(),"format.readEffectiveInlineUniformity");if(!b)return null;try{const I=await Promise.resolve(b({target:m,offsetSpace:"selection"}));return I&&typeof I=="object"&&I.success===!0?I:null}catch{return null}},gc=(f,m,b)=>{const I=b.values;for(const E of["fontFamily","fontSize"]){if(m[E]!==void 0)continue;const z=I?.[E];z?.state==="uniform"&&typeof z.value=="string"?f[E]=E==="fontFamily"?gb(z.value):z.value:delete f[E]}},Uu=f=>Cl(f,xA(Rs(f),f)),Sl=f=>Uu(f).values,Qf=async f=>{const m=y()?.query,b=wl(f);if(typeof m?.match!="function"||!b)return Sl(f);try{const I=await Promise.resolve(m.match(b)),E=xA(TA(I&&typeof I=="object"?I:null,f),f),z=Cl(f,E);if(z.effectiveUniformityStatus!=="ready"&&(E.fontFamily===void 0||E.fontSize===void 0)){const K=await mc(f);K&&gc(z.values,E,K)}return z.values}catch{return Sl(f)}},Ms=async f=>{const m=y();if(m)return typeof m.getNode=="function"?await Promise.resolve(m.getNode(f)):await Promise.resolve(m.getNodeById?.({nodeId:f.nodeId,nodeType:f.nodeType}))},vc=f=>{const m=y()?.query;if(typeof m?.match!="function")return"ready";const b=wl(f);if(!b)return"ready";const{status:I}=Vr(`query:${bo(f)}`,At(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return I},Pi=f=>{const m=Uu(f),b=m.values;if(f.empty)return m;const I=ya(f);return I?f.status==="ready"&&vc(f)==="ready"&&m.effectiveUniformityStatus==="ready"?(C={key:I,values:b},m):C&&C.key===I?{...m,values:{...C.values,...b}}:m:m},ju=f=>{const m=y(),b=Pi(f),I=b.values;f.status==="ready"&&!f.empty&&vc(f)==="ready"&&b.effectiveUniformityStatus==="ready"&&(v=I,k=`${ic(f)}:${At()}`);const E=m?.contentControls,{lockModesById:z}=xs(E,f),K={};for(const oe of le())K[oe]=bc(oe,m,f,I,z);return K},Di=f=>f?ut.operationUnavailable:_()?ut.documentApiUnavailable:ut.notReady,Gu=f=>f==="contentLocked"||f==="sdtContentLocked",Ji=f=>{for(const m of f.values())if(Gu(m))return ut.contentControlLocked},yc=(f,m,b,I,E)=>{if(!m)return f.scope==="all"?ut.bulkDecisionsDisabled:Di(E);if(b)return ut.documentReadonly;if(f.scope!=="all"&&I.activeChangeIds.length===0)return ut.selectionRequired},Wu=f=>{const m=x(),b=Lt(typeof m?.getCapabilities=="function"?()=>m.getCapabilities():void 0,null)?.editableSubset?.commands;if(Array.isArray(b))return b.find(I=>I?.command===f||I?.id===f)??null;if(b&&typeof b=="object"){const I=b[f];return I&&typeof I=="object"?I:null}return null},Ku=(f,m)=>{if(f.scope!=="all"||typeof m?.[`${f.kind}All`]=="function")return;const b=Wu(`trackedChanges.${f.kind}All`);if(!(b&&(b.status==="supported"||b.enabled===!0)))return ut.bulkDecisionsDisabled},bc=(f,m,b,I,E=new Map)=>{if(he.has(f))return ln({supported:!0,enabled:!0,...Lt(he.get(f).getState?()=>he.get(f).getState(Bu(void 0)):void 0,{})},"custom");const z=Xn()==="viewing",K=yA(f);if(K&&typeof T()?.lists?.apply=="function"){const Xe=J(),He=typeof Xe?.shippedStatus=="string"?Xe.shippedStatus:null,Ze=He!=="not-shipped"&&He!=="disabled";return ln({enabled:Ze&&(typeof Xe?.enabled=="boolean"?Xe.enabled:!0),active:(Ze?q(Xe):null)===K,supported:Ze,value:Xe?.value},"builtin")}const oe=_m(f);if(oe){const Xe=m?.trackChanges,He=typeof Xe?.decide=="function"||typeof Xe?.[oe.kind]=="function",Ze=typeof Xe?.decide=="function"||typeof Xe?.[`${oe.kind}All`]=="function",Qe=oe.scope==="all"?Ze:He,ot=Ku(oe,Xe)??yc(oe,Qe,Zi(),b,m);return ln({enabled:ot==null,active:!1,supported:Qe,reason:ot},"builtin")}if(f==="copy-format")return Xn()==="viewing"?ln({supported:!0,enabled:!1,active:!1},"builtin"):_()?ln({supported:!0,enabled:!0,active:h.mode!=="idle"},"builtin"):ln({supported:!0,enabled:!1,active:!1,reason:ut.notReady},"builtin");const me=Tu(f);if(!me)return ln({enabled:!1,active:!1,supported:!1,reason:ut.commandUnsupported},"unsupported");if(me.disposition!=="routed")return ln({enabled:!1,active:!1,supported:!1,reason:me.reason??ut.commandUnsupported},me.disposition==="unsupported"?"unsupported":"builtin");if(me.instanceRoute)return Q(me);if(me.table)return ae(me,m,z);if(me.inline?.kind==="clear"){if(me.mutates&&z)return ln({enabled:!1,active:!1,supported:!0,reason:ut.documentReadonly},"builtin");const Xe=Ji(E);if(Xe)return ln({enabled:!1,active:!1,supported:!0,reason:Xe},"builtin");const He=Nr(b).length>0||Fu(b)!=null;return ln({enabled:He,active:!1,supported:!0,reason:He?void 0:ut.selectionRequired},"builtin")}const Re=me.docRoute;if(!Re)return ln({enabled:!1,active:!1,supported:!1,reason:ut.commandUnsupported},"unsupported");if(yr(m,Re)==null)return ln({enabled:!1,active:!1,supported:!1,reason:Di(m)},"builtin");const Ue=se(f);if(Ue){const Xe=Ue.shippedStatus,He=Xe!=="not-shipped"&&Xe!=="disabled",Ze=typeof Ue.enabled=="boolean"?Ue.enabled:!0,Qe=f==="undo"||f==="redo",ot=Qe&&Ue.historyResolved===!1,nt=Qe&&He&&Ze===!1&&Ue.reason===null&&!ot,Ot=Ue.reason===void 0?void 0:nt?ut.historyEmpty:ot?ut.notReady:db(Ue.reason,ut.commandUnsupported);return me.mutates&&z?ln({enabled:!1,active:!1,supported:He,reason:ut.documentReadonly},"builtin"):ln({enabled:He&&Ze,active:!1,supported:He,reason:Ot},"builtin")}const Ke=Ea(me,m,b),Fe=Yu(me,m,b,I);if(me.list?.mode==="indent"||me.list?.mode==="outdent")return eh(me,m,z,b,Ke,Fe);if(me.list?.mode==="toggle-seed")return A(me,m,z,b,Ke,Fe);if(me.mutates&&z)return ln({enabled:!1,active:Ke,supported:!0,value:Fe,reason:ut.documentReadonly},"builtin");if(me.inline&&!Fu(b)){const Xe=Ji(E);return ln(Xe?{enabled:!1,active:Ke,supported:!0,value:Fe,reason:Xe}:Nr(b).length>0&&typeof x()?.setPendingInlineFormat=="function"?{enabled:!0,active:Ke,supported:!0,value:Fe}:{enabled:!1,active:Ke,supported:!0,value:Fe,reason:ut.rangeSelectionRequired},"builtin")}if((me.blockParagraph||me.list)&&Nr(b).length===0)return ln({enabled:!1,active:Ke,supported:!0,value:Fe,reason:ut.selectionRequired},"builtin");if(me.link&&!Ke&&pb(b).length===0&&!ul(b))return ln({enabled:!1,active:Ke,supported:!0,reason:ut.rangeSelectionRequired},"builtin");if(me.inline){const Xe=Ji(E);if(Xe)return ln({enabled:!1,active:Ke,supported:!0,value:Fe,reason:Xe},"builtin")}return ln({enabled:!0,active:Ke,supported:!0,value:Fe},"builtin")};function qu(f,m){const b=f.address?.anchor,I=b?.start,E=b?.end,z=typeof I?.blockId=="string"?I.blockId:null,K=typeof E?.blockId=="string"?E.blockId:null;if(!z||!K)return!1;const oe=typeof I?.offset=="number"?I.offset:null,me=typeof E?.offset=="number"?E.offset:null;if(oe==null||me==null)return!1;const Re=m.target,Ue=Re&&Array.isArray(Re.segments)?Re.segments:[];for(const Ke of Ue){const Fe=typeof Ke?.blockId=="string"?Ke.blockId:null;if(!Fe)continue;const Xe=Ke.range,He=typeof Xe?.start=="number"?Xe.start:null,Ze=typeof Xe?.end=="number"?Xe.end:null;if(!(He==null||Ze==null)){if(z!==K){if(Fe===z&&Ze>oe||Fe===K&&He<me)return!0;continue}if(Fe===z){if(He===Ze){if(He>=oe&&He<=me)return!0;continue}if(Math.max(He,oe)<Math.min(Ze,me))return!0}}}return!1}const wc=(f,m)=>{const b=f?.hyperlinks;if(!b||typeof b.list!="function")return null;const I=Nr(m);if(!ac(I))return null;for(const E of I){const z={kind:"block",nodeType:"paragraph",nodeId:E},{value:K}=Vr(`hyperlinks:${E}`,At(),()=>b.list({within:z}),me=>me&&typeof me=="object"?me:null),oe=(K&&Array.isArray(K.items)?K.items:[]).find(me=>qu(me,m));if(oe)return oe}return null},Ea=(f,m,b)=>{if(f.link)return wc(m,b)!=null;if(f.list?.mode==="toggle-seed"&&f.list.seed)return kc(m,b)===f.list.seed;const I=G(f);if(I!==null)return I;const E=r.get(f.id),z=ya(b);if(z&&E?.selectionSignature===z)return E.active;const K=Hu(f,b);return K!==null?K:yH(f,b)},Yu=(f,m,b,I)=>{if(f.inline&&mb(f.inline.key)){const E=R(f);if(E!==void 0)return E;const z=I[f.inline.key];if(z!==void 0)return z;const K=ya(b),oe=K?n.get(f.inline.key):void 0;if(K&&oe?.selectionSignature===K)return oe.value}if(f.id==="linked-style"){const{style:E}=ct(b,ze().cache);return!E.styleId||E.mixed?void 0:{styleId:E.styleId,styleName:E.styleName}}if(f.id==="text-align")return Ls(m,b);if(f.id==="link")return M(m,b)??void 0},Cc=(f,m,b)=>{const I=f?.lists;if(!I)return{value:null,status:"ready"};const E=b.storyType==="body",z=typeof I.getStateInStory=="function"?()=>I.getStateInStory({target:va(m),story:b}):E&&typeof I.getState=="function"?()=>I.getState({target:va(m)}):null;if(!z)return{value:null,status:"ready"};const{value:K,status:oe}=Vr(`lists:${kr(b)}:${m}`,At(),z,me=>me&&typeof me=="object"?me:null);return{value:K?.success===!0?K:null,status:oe}},Jf=(f,m,b)=>Cc(f,m,b).value,Xu=(f,m,b)=>{const I=Jf(f,m,b);return!I||I.isListItem!==!0?null:I.seed==="bullet"||I.seed==="ordered"?I.seed:null},Fo=(f,m,b)=>{const I=Cc(f,m,b),E=I.value;return{value:E&&typeof E.isListItem=="boolean"?E.isListItem:null,status:I.status}},kc=(f,m)=>{const b=Nr(m);if(b.length===0||!ac(b))return null;const I=Ki(m),E=Xu(f,b[0],I);if(E!=="bullet"&&E!=="ordered")return null;for(const z of b.slice(1))if(Xu(f,z,I)!==E)return null;return E},Ta=(f,m,b)=>{if(!f)return{value:null,status:"ready",refreshing:!1};const I=kr(b),E=I==="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 z=`node:${I}:${m}`,K=At(),oe=Vr(z,K,()=>E?f.getNodeById({nodeId:m,nodeType:"paragraph"}):f.getNode(vo(m,b)),Re=>Re&&typeof Re=="object"?Re:null),me=ee.get(z);return{...oe,refreshing:oe.status==="stale"&&me?.inflightToken===K&&me.failedToken!==K}},Sc=f=>f==="left"||f==="center"||f==="right"||f==="justify"?f:void 0,$f=f=>f==="start"||f==="end"||f==="distributed"||f==="numTab"||f==="lowKashida"||f==="mediumKashida"||f==="highKashida"||f==="thaiDistribute",_l=(f,m)=>{const b=x(),I=b?.readMountedProjectionBlocksByIds;if(typeof I!="function")return null;const E=qi(f),z=Lt(()=>E?I.call(b,[...m],E):I.call(b,[...m]),null);if(!Array.isArray(z))return new Map;const K=yb(z),oe=new Map;for(const me of m){const Re=K.find(Xe=>cc(Xe,me));if(!Re)continue;const Ue=Re.attrs,Ke=Sc(Ue?.alignment),Fe=R9(Ue);oe.set(me,Ke??(Fe==="rtl"?"right":"left"))}return oe},_c=(f,m,b,I)=>{const{value:E,status:z,refreshing:K}=Ta(f,m,b),oe=I?.get(m);if(z==="pending")return oe?{status:"uniform",value:oe}:{status:"pending"};if(z==="stale"&&!K)return{status:"pending"};if(z==="stale"&&oe)return{status:"uniform",value:oe};if(z==="stale"&&I&&!oe)return{status:"unavailable"};if(!E)return{status:"unavailable"};const me=E.node;if(!me)return{status:"unavailable"};const Re=me.kind;if(Re!=="paragraph"&&Re!=="heading")return{status:"unavailable"};const Ue=me[Re];if(!Ue||typeof Ue!="object")return{status:"unavailable"};const Ke=Ue.props?.alignment;if(Ke==null)return oe?{status:"uniform",value:oe}:{status:"unavailable"};const Fe=Sc(Ke);return Fe?{status:"uniform",value:Fe}:$f(Ke)&&oe?{status:"uniform",value:oe}:{status:"unavailable"}},Zu=(f,m)=>{const b=Nr(m);if(b.length===0||!ac(b))return{status:"unavailable"};const I=Ki(m),E=_l(m,b),z=_c(f,b[0],I,E);if(z.status!=="uniform")return z;for(const K of b.slice(1)){const oe=_c(f,K,I,E);if(oe.status!=="uniform")return oe;if(oe.value!==z.value)return{status:"mixed"}}return z},Qu=f=>{const m=Nr(f);return m.length===0?null:`${kr(Ki(f))}:${m.join(",")}`},Ls=(f,m)=>{const b=Zu(f,m),I=b.status==="uniform"?b.value:void 0,E=o;if(!E)return I;const z=Qu(m);return z&&z!==E.selectionSignature?(o=null,I):!z||!E.settled?E.value:b.status!=="pending"?(o=null,I):E.value},fo=(f,m)=>{const b=Sc(m),I=Qu(f),E=Nr(f);if(!b||!I||E.length===0)return null;const z=++i;return o={selectionSignature:I,value:b,generation:z,settled:!1,canReconcile:ac(E)},Xt(),z},Ju=(f,m)=>{if(f==null)return;const b=o;if(!(!b||b.generation!==f)){if(!yo(m)){o=null;return}if(!b.canReconcile){o=null;return}b.settled=!0}},Ps=async(f,m,b)=>{const I=f?.lists;if(!I)return null;try{const E=b.storyType==="body",z=typeof I.getStateInStory=="function"?await I.getStateInStory({target:va(m),story:b}):E&&typeof I.getState=="function"?await I.getState({target:va(m)}):null,K=z&&typeof z=="object"?z:null;return!K||K.success!==!0||typeof K.isListItem!="boolean"?null:K.isListItem}catch{return null}},Al=(f,m,b)=>{const I={resolved:!1,seed:null},E=f?.lists;if(!E)return I;const z=b.storyType==="body",K=typeof E.getStateInStory=="function"?()=>E.getStateInStory({target:va(m),story:b}):z&&typeof E.getState=="function"?()=>E.getState({target:va(m)}):null;if(!K)return I;const oe=me=>{const Re=me&&typeof me=="object"?me:null;return!Re||Re.success!==!0||typeof Re.isListItem!="boolean"?I:{resolved:!0,seed:Re.isListItem===!0&&(Re.seed==="bullet"||Re.seed==="ordered")?Re.seed:null}};try{const me=K();return Cr(me)?Promise.resolve(me).then(oe,()=>I):oe(me)}catch{return I}},Ac=async(f,m,b)=>{if(!f)return null;try{const I=!b||b.storyType==="body",E=b&&typeof f.getNode=="function"?await f.getNode(vo(m,b)):I&&typeof f.getNodeById=="function"?await f.getNodeById({nodeId:m,nodeType:"paragraph"}):null;return GV(E&&typeof E=="object"?E:null)}catch{return null}},eh=(f,m,b,I,E,z)=>{if(f.mutates&&b)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.documentReadonly},"builtin");const K=Nr(I);if(K.length===0)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.selectionRequired},"builtin");const oe=f.docRoute?yr(m,f.docRoute):null,me=yr(m,"format.paragraph.setIndentation"),Re=yr(m,"format.paragraph.clearIndentation"),Ue=f.list?.mode,Ke=Ue==="indent"?me!=null:me!=null||Re!=null,Fe=Ki(I);let Xe=null;if(Fe.storyType!=="body"){Xe=[];for(const He of K){const{value:Ze,status:Qe}=Fo(m,He,Fe);if(Ze===null)return Qe!=="ready"&&(oe!=null||Ke)?ln({enabled:!0,active:E,supported:!0,value:z},"builtin"):ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin");Xe.push(Ze)}}if(Xe?.some(He=>He===!0)){const He=Ue==="indent"?"lists.indentRange":"lists.outdentRange",Ze=Xn()!=="suggesting"&&Xe.every(ot=>ot===!0)&&yr(m,He)!=null,Qe=Ue==="outdent"&&yr(m,"lists.outdentInStory")!=null;if(!Ze&&!Qe)return ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin")}for(const[He,Ze]of K.entries()){const Qe=Xe?{value:Xe[He]??null,status:"ready"}:Fo(m,Ze,Fe),ot=Qe.value;if(ot===!0){if(oe!=null)return ln({enabled:!0,active:E,supported:!0,value:z},"builtin");continue}if(ot===!1&&Ke){if(Fe.storyType!=="body"&&typeof m?.getNode!="function")continue;return ln({enabled:!0,active:E,supported:!0,value:z},"builtin")}if(ot===null)return Qe.status!=="ready"&&(oe!=null||Ke)?ln({enabled:!0,active:E,supported:!0,value:z},"builtin"):ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin")}return ln({enabled:!1,active:E,supported:!1,value:z,reason:Di(m)},"builtin")},A=(f,m,b,I,E,z)=>{if(f.mutates&&b)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.documentReadonly},"builtin");const K=Nr(I);if(K.length===0)return ln({enabled:!1,active:E,supported:!0,value:z,reason:ut.selectionRequired},"builtin");const oe=Ki(I),me=m?.lists;if(!(typeof me?.getStateInStory=="function"||oe.storyType==="body"&&typeof me?.getState=="function"))return ln({enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");if(!ac(K))return ln(oe.storyType==="body"&&yr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");const Re=K.map(Xe=>Cc(m,Xe,oe));if(Re.some(({status:Xe})=>Xe!=="ready"))return ln({enabled:!0,active:E,supported:!0,value:z},"builtin");if(Re.some(({value:Xe})=>Xe===null))return ln({enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");const Ue=f.list?.seed,Ke=Re.every(({value:Xe})=>Xe?.isListItem===!0&&Xe.seed===Ue);if(oe.storyType==="body")return ln(!Ke||yr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin");const Fe=yr(m,"lists.removeInStory");return ln(Ke&&Fe?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:ut.operationUnavailable},"builtin")},M=(f,m)=>{const b=wc(f,m)?.properties?.href;return typeof b=="string"?b:null},Q=f=>{if(!_())return ln({enabled:!1,active:!1,supported:!1,reason:ut.notReady},"builtin");const m=f.instanceRoute;return typeof t?.[m]!="function"?ln({enabled:!1,active:!1,supported:!1,reason:ut.operationUnavailable},"builtin"):ln({enabled:!0,active:re(f),supported:!0,value:de(f)},"builtin")},re=f=>{const m=t?.config??void 0;return f.valueFrom==="ruler"?!!m?.rulers:f.valueFrom==="formattingMarks"?!!m?.layoutEngineOptions?.showFormattingMarks:!1},ae=(f,m,b)=>{if(b)return ln({enabled:!1,active:!1,supported:!0,reason:ut.documentReadonly},"builtin");const I=Ne();return I!=null&&(!f.table.requiresCell||I.cellNodeId!=null)?(f.docRoute?yr(m,f.docRoute):null)==null?ln({enabled:!1,active:!1,supported:!1,reason:Di(m)},"builtin"):ln({enabled:!0,active:!1,supported:!0},"builtin"):ln({enabled:!1,active:!1,supported:!0,reason:ut.tableContextUnavailable},"builtin")},de=f=>{if(f.valueFrom==="zoom")return bi().value;if(f.valueFrom==="documentMode")return Xn();if(f.valueFrom==="measurementUnit")return Kr();if(f.valueFrom==="ruler"||f.valueFrom==="formattingMarks")return re(f)},fe=(f,m)=>f.id==="zoom"?typeof m=="number"&&Number.isFinite(m)&&m>0:f.id==="document-mode"?m==="editing"||m==="suggesting"||m==="viewing":f.id==="measurement-unit"?m==="in"||m==="cm":!0,le=()=>[...new Set([...EN,...he.keys()])],Ae="Normal",Le={ready:!1,status:"ready",catalogRevision:null,quickGallery:[],activeParagraphStyleId:null,activeParagraphStyleName:null,mixedSelection:!1,sourceStatus:null,diagnostics:[]},Me=f=>{const m=y()?.styles;return!m||typeof m.getCatalog!="function"?{value:null,status:"ready"}:Vr(`styles:catalog:${JSON.stringify(f??{})}`,At(),()=>m.getCatalog(f),b=>b&&typeof b=="object"?b:null)},ze=()=>{const f=Me({includePreview:!0});if(!f.value)return{cache:null,status:f.status};const m=Me({view:"quickGallery",includePreview:!0}),b=m.value?m.value.items:f.value.styles.filter(E=>E.visibility.quickGallery),I=new Map;for(const E of f.value.styles)I.set(E.id,E);return{cache:{full:f.value,quickGallery:b,byId:I},status:Mu(f.status,m.status)}},tt=(f,m,b)=>{const{value:I,status:E}=Ta(f,m,b);if(!I)return{ok:!1,styleRef:null,status:E};const z=I.node;if(!z||typeof z!="object")return{ok:!1,styleRef:null,status:E};const K=z.kind,oe=typeof K=="string"?z[K]:void 0,me=oe&&typeof oe=="object"?oe.styleRef:void 0;return{ok:!0,styleRef:typeof me=="string"&&me.length>0?me:null,status:E}},ct=(f,m)=>{const b=[],I=y();if(!I)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=Nr(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(!ac(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 z=m?.full.defaults.paragraphStyleId??(m?Ae:null),K=new Set;let oe=0,me=0,Re=0,Ue="ready";const Ke=Ki(f);for(const He of E){const Ze=tt(I,He,Ke);if(Ue=Mu(Ue,Ze.status),!Ze.ok){me+=1;continue}if(!Ze.styleRef&&!z){Re+=1;continue}const Qe=Ze.styleRef??z;if(!Qe){Re+=1;continue}oe+=1,K.add(Qe)}if(oe===0){const He=Re>0&&me===0;return b.push({severity:"warning",code:He?"active-style-default-unavailable":"active-style-read-failed",message:He?"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 Fe=me+Re;if(Fe>0)return b.push({severity:"warning",code:"active-style-partial",message:`Active paragraph style resolved from ${oe} of ${oe+Fe} selected blocks; ${Fe} could not be read, so the active style is unavailable.`}),{style:{styleId:null,styleName:null,mixed:!1,diagnostics:b},status:Ue};if(K.size>1)return{style:{styleId:null,styleName:null,mixed:!0,diagnostics:b},status:Ue};const Xe=[...K][0];return{style:{styleId:Xe,styleName:m?.byId.get(Xe)?.name??null,mixed:!1,diagnostics:b},status:Ue}},qe=f=>{if(!_())return Le;const{cache:m,status:b}=ze(),{style:I,status:E}=ct(f,m);let z;return m?z=I.diagnostics.length===0?m.full.diagnostics:[...m.full.diagnostics,...I.diagnostics]:z=[{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)."},...I.diagnostics],{ready:!0,status:Mu(b,E,f.status),catalogRevision:m?.full.revision??null,quickGallery:m?.quickGallery??[],activeParagraphStyleId:I.styleId,activeParagraphStyleName:I.styleName,mixedSelection:I.mixed,sourceStatus:m?.full.sourceStatus??null,diagnostics:z}},Dt=()=>{const f=Xn(),m=Kf();m.status==="ready"&&Wf(m),B(m);const b=ya(m);for(const[I,E]of r)(!b||E.selectionSignature!==b||E.settled&&m.status==="ready")&&r.delete(I);return{ready:_()!=null,documentMode:f,document:pc(),selection:m,toolbar:{context:f,commands:ju(m),copyFormatActive:h.mode!=="idle"},comments:qf(m),trackChanges:bl(m),contentControls:Aa(m),zoom:bi(),fonts:yi(),styles:qe(m)}},gt=f=>{const m=ya(f);m&&a&&m!==a&&(n.clear(),r.clear()),m&&(a=m)};let Bt=null,xt=null,St=null,Zn=null,rn=!1;const hn=()=>{if($||rn)return;rn=!0;const f=()=>{rn&&(rn=!1,!$&&Xt())};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},mr=()=>{const f=T();if(f!==St&&(Zn&&(Zn(),Zn=null),St=f,!(!f||typeof f.subscribe!="function")))try{const m=f.subscribe(()=>hn());typeof m=="function"&&(Zn=m)}catch{St=null}};let xr=null,tr=null,No=null,$r=null,it=null,dn=null;const eo=()=>{const f=_()?.host,m=Lt(f?.getHandles?()=>f.getHandles():void 0,null)?.editing?.selection;return m&&typeof m.subscribe=="function"?m:null},wi=()=>{const f=eo();if(f!==Bt&&(xt&&(xt(),xt=null),Bt=f,!!f))try{const m=f.subscribe(b=>{yt+=1,vl(b),Xt()});typeof m=="function"&&(xt=m)}catch{Bt=null}},So=()=>{const f=_()?.host,m=Lt(f?.getHandles?()=>f.getHandles():void 0,null)?.review;return m&&typeof m.subscribe=="function"?m:null},Ci=f=>f?typeof f.getActiveReviewTarget=="function"?Lt(()=>f.getActiveReviewTarget(),null):typeof f.getSnapshot=="function"?Lt(()=>f.getSnapshot(),null)?.activeReviewTarget??null:null:null;let _o=0;const Bo=(f,m)=>{const b=(m&&typeof m=="object"?m:null)?.lastInteractionRejection;if(_o>0&&f==null&&b&&typeof b=="object"&&b.code==="review-target-invalidated"&&b.detail==="not-painted")return!1;const I=f&&typeof f=="object"?f:null;let E=null;if(I?.entityType==="trackedChange"&&typeof I.entityId=="string"&&I.entityId.length>0){const z=I.entityId,K=I.story&&typeof I.story=="object"?I.story:void 0,oe=Qi(),me=(oe?K?Pu(oe,K).toPublicId(z):ga(oe).toPublicId(z):null)??z,Re=K&&kr(K)!==kr(null)?K:void 0;E={id:me,...Re?{story:Re}:{},...typeof I.paintedEntityId=="string"&&I.paintedEntityId.length>0?{paintedEntityId:I.paintedEntityId}:me!==z?{paintedEntityId:z}:{}}}return f==null&&E==null&&ce!=null&&Tt(ce)||st(ce,E)?!1:(je(E),!0)},Il=()=>{const f=So();if(f===xr)return;if(tr&&(tr(),tr=null),xr=f,!f){Bo(null);return}let m=!0;try{const b=f.subscribe(I=>{const E=I&&typeof I=="object"?I:null;!Bo(E&&Object.prototype.hasOwnProperty.call(E,"activeReviewTarget")?E.activeReviewTarget:Ci(f),I)||m||Xt()});typeof b=="function"&&(tr=b),Bo(Ci(f))}catch{xr=null}finally{m=!1}},$i=()=>{if(Bt||Xn()!=="viewing")return null;const f=_()?.mount?.container,m=(f&&typeof f=="object"&&"ownerDocument"in f?f.ownerDocument??null:null)??globalThis.document??null;return m&&typeof m.addEventListener=="function"?m:null},Ds=()=>{const f=$i();if(f===it||(dn&&(dn(),dn=null),it=f,!f))return;const m=()=>{yt+=1,Xt()};f.addEventListener("selectionchange",m),f.addEventListener("pointerup",m,!0),f.addEventListener("mouseup",m,!0),dn=()=>{f.removeEventListener("selectionchange",m),f.removeEventListener("pointerup",m,!0),f.removeEventListener("mouseup",m,!0)}};Sa(),Bo(Ci(So()));let dt=Dt();a=ya(dt.selection);const Os=()=>{const f=_()?.host?.events,m=f&&typeof f.subscribe=="function"?f:null;if(m!==No&&($r&&($r(),$r=null),No=m,!!m))try{const b=m.subscribe(I=>{const E=I?.type;if(E==="review-mutation:started"){Pt(I.reviewMutation?.token);return}if(E==="review-mutation:aborted"){Kt(I.reviewMutation?.token),we();return}if(E==="mutation:rejected"&&I.reviewMutation&&(Kt(I.reviewMutation.token),we()),E==="mutation:committed"&&I.reviewMutation&&Kt(I.reviewMutation.token),E==="source:complete"||E==="source:signals-complete"){Nt!==null&&(Pe(),Br.onRender(!0));return}if((E==="mutation:committed"||E==="collaboration:remote-changed")&&(Ln=Date.now()),E==="mutation:committed"&&(Pe(),Wt={}),E==="mutation:committed"||E==="save:completed"||E==="collaboration:remote-changed"){const z=E==="mutation:committed"?Gk(I):null,K=E==="mutation:committed"&&Br.getPendingIds().size>0;if(z?.allResolved){Br.reset(),cn([]),Nt=null,Pn(I.receipt);return}z?.removedIds.size&&br(new Set(z.removedIds),I.receipt);const oe=z?.reconcileMode==="authoritative"&&z.upsertIds.size>0;if(oe&&(Es(),Pe(),Nt=At(),Xt()),z?.upsertIds.size||K){const Ke=I.origin==="history"?null:I.receipt,Fe=_()?.documentMutationReadiness,Xe=typeof Ke?.txId=="string"&&Ke.txId.length>0&&typeof Fe?.whenPainted=="function",He=I.origin==="history"&&typeof Fe?.getRenderEpoch=="function"?Lt(()=>Fe.getRenderEpoch.call(Fe),null):null,Ze=I.origin==="history"&&typeof Fe?.whenPainted=="function",Qe={upsertIds:z?.upsertIds??new Set,removedIds:new Set,reconcileMode:z?.reconcileMode==="authoritative"?"authoritative":"targeted"};Xe?Br.enqueueAfterPaint(Qe,()=>Fe.whenPainted.call(Fe,Ke)):Ze?Br.enqueueAfterPaint(Qe,()=>Fe.whenPainted.call(Fe,typeof He=="number"?{afterEpoch:He}:void 0)):(Br.enqueue(Qe),Br.onRender(K))}if(oe)return;const me=E==="mutation:committed"&&Mi(I)||E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0;if(me&&(Bn=Date.now()),E==="mutation:committed"&&me){ml();return}if(z?.removedIds.size&&z.upsertIds.size===0)return;(E==="collaboration:remote-changed"||E==="mutation:committed"&&!me)&&_s();const Re=E==="collaboration:remote-changed"&&Array.isArray(I.changedPartUris)&&I.changedPartUris.some(Ke=>typeof Ke=="string"&&RV.has(Ke)),Ue=E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0&&uc();Re&&!me&&(sr=!0),Es(),(Re||Ue)&&wa("comments"),Xt()}});typeof b=="function"&&($r=b)}catch{No=null}},Xt=()=>{if($)return;rn=!1,Sa(),wi(),mr(),Il(),Ds(),Os();const f=Dt();gt(f.selection),dt=f;for(const m of[...Ye])m(dt)},xa=[],es=[],Ic=f=>{for(const m of f)try{m()}catch{}},El=()=>Ic(xa),Ec=()=>Ic(es),Tl=[];((f,m)=>{if(!(!f||typeof f.on!="function"))for(const b of m){const I=b==="active-editor-change"?()=>{El(),Ec(),Xt()}:b==="document-replaced"?E=>{const z=E&&typeof E=="object"?E:null,K=z?.editor,oe=z?.host,me=!!K&&K===_(),Re=!!oe&&oe===x();!me&&!Re||(Ec(),ee.clear(),Es(),Xt())}:()=>Xt();try{f.on(b,I),Tl.push(()=>{try{typeof f.off=="function"&&f.off(b,I)}catch{}})}catch{}}})(t,_V),wi(),mr(),Il(),Ds(),Os();const Fs=(f,m=cV)=>({get:()=>f(dt),subscribe:b=>{let I=f(dt);const E=z=>{const K=f(z);m(I,K)||(I=K,b(K))};return Ye.add(E),()=>Ye.delete(E)}}),Ao=f=>Fs(f),oi=f=>{const m=b=>{const I=z=>{try{b(z)}catch{}},E=f.subscribe(I);return I(f.get()),E};return{get:()=>f.get(),getSnapshot:()=>f.get(),observe:m,subscribe:b=>m(I=>b({snapshot:I}))}};function th(f){return f&&typeof f=="object"&&typeof f.id=="string"?String(f.id):null}function xc(f){const m=qi(f);return m&&kr(m)!==kr(null)?m:void 0}function jt(f,m){return{kind:"id",id:f,...m?{story:m}:{}}}function qn(f){if(f.empty)return null;const m=f.selectionTarget,b=m?.start,I=m?.end;if(m?.kind!=="selection"||b?.kind!=="text"||I?.kind!=="text"||typeof b.blockId!="string"||b.blockId!==I.blockId||!Number.isInteger(b.offset)||!Number.isInteger(I.offset)||b.offset<0||I.offset<0||b.offset===I.offset)return null;const E=Math.min(b.offset,I.offset),z=Math.max(b.offset,I.offset),K=qi(f);return{kind:"range",coordinateSpace:m.coordinateSpace==="tracked"?"tracked":"visible",range:{kind:"text",...K?{story:K}:{},segments:[{blockId:b.blockId,range:{start:E,end:z}}]}}}function L(f,m){if(kr(m)!==kr(null))return;const b=y()?.trackChanges,I=b?.list;if(typeof I!="function")return;const E=Lt(()=>I.call(b),null);if(Cr(E)||!E||typeof E!="object")return;const z=E.items;if(Array.isArray(z))return z.map(dl).find(K=>K!=null&&Wi(K,f,m))}function H(f,m){const b=Ce(f.quotedText);if(!b)return!1;const I=km(m);return[I.insertedText,I.deletedText,I.excerpt].some(E=>Ce(E)===b)}function Ce(f){return typeof f=="string"?f.replace(/\s+/g," ").trim():""}function De(){const f=dt.selection.activeChangeIds[0];if(!f)return"unavailable";const m=qi(dt.selection),b=(dt.trackChanges.status==="ready"?dt.trackChanges.items.find(K=>Wi(K,f,m)):void 0)??L(f,m)??Qi()?.find(K=>Wi(K,f,m));if(!b)return"unavailable";const I=km(b),E=I.type,z=I.grouping;return H(dt.selection,b)?"id":E==="replacement"&&z==="replacement-pair"||(E==="insertion"||E==="deletion"||E==="insert"||E==="delete")&&z==="standalone"?"range":"id"}function pt(f,m,b,I){const E=()=>Rb(f,jt(b,I),b,I);try{const z=Rb(f,m,null);return Cr(z)?qr(Promise.resolve(z).then(K=>yo(ks(K))?K:E())):qr(yo(ks(z))?z:E())}catch{return!1}}function fn(f,m){if(f.scope==="all")return{target:{kind:"all"},changeId:null};if(typeof m=="string"&&m.length>0)return{target:{kind:"id",id:m},changeId:m};if(m&&typeof m=="object"){const E=m;if(E.target&&typeof E.target=="object"){const K=E.target;return{target:K,changeId:th(K),story:K.story}}const z=typeof E.changeId=="string"?E.changeId:E.id;if(typeof z=="string"&&z.length>0)return{target:jt(z,E.story),changeId:z,story:E.story}}const b=dt.selection.activeChangeIds[0],I=xc(dt.selection);return b?{target:jt(b,I),changeId:b,story:I}:null}function xn(f,m){if(f.scope==="id"&&m==null){if(dt.selection.activeChangeIds.length>1)return ih(f.kind,{kind:"ids",ids:dt.selection.activeChangeIds},null);if(dt.selection.activeChangeIds.length===1&&!dt.selection.empty&&dt.selection.selectionTarget){const I=De();if(I==="unavailable")return!1;if(I==="range"){const E=qn(dt.selection),z=xc(dt.selection);return E?pt(f.kind,E,dt.selection.activeChangeIds[0],z):!1}if(I==="id"){const E=dt.selection.activeChangeIds[0],z=qi(dt.selection),K=z&&kr(z)!==kr(null)?z:void 0;return xb(f.kind,K?{id:E,story:K}:E)}}}const b=fn(f,m);return b?ih(f.kind,b.target,b.changeId,b.story):!1}function Yn(f,m){const b=T()?.lists,I=b?.apply;if(typeof I!="function")return!1;const{behavior:E,preset:z,continuity:K}=typeof m=="string"?EV(m):m&&typeof m=="object"?m:{},oe={kind:f,behavior:E??"toggle"};z!==void 0&&(oe.preset=z),K!==void 0&&(oe.continuity=K);try{return qr(I.call(b,oe))}catch{return!1}}let pn=Promise.resolve(!1),gn=null,bn=Promise.resolve(!1);const Rr=async f=>{if(!Sm(f))return f;const m=_()?.documentMutationReadiness,b=m?.whenPainted;if(typeof b!="function")return f;const I=typeof f.txId=="string"?f.txId:void 0;try{await b.call(m,I?{txId:I}:void 0)}catch{}return f},zn=f=>{if(Cr(f)){const b=Promise.resolve(f);return{immediate:!0,committed:b.then(I=>ks(I),()=>!1),settled:b.then(I=>Rr(ks(I)),()=>!1)}}const m=ks(f);return{immediate:m,committed:Promise.resolve(m),settled:Rr(m)}},Ra=()=>{const f=s.shift();if(!f){u=!1,d?.(),d=null;return}try{f.resolve($?!1:f.mutate())}catch{f.resolve(!1)}},Ma=()=>{let f=!1;return()=>{f||(f=!0,Ra())}},ii=(f,m)=>{if(!u){u=!0,c=new Promise(z=>{d=z});try{return{result:m(),release:Ma()}}catch(z){throw u=!1,d?.(),d=null,z}}const b=s.find(z=>z.key===f);if(b)return b.mutate=m,{result:b.result,release:()=>{}};let I;const E=new Promise(z=>{I=z});return s.push({key:f,mutate:m,result:E,resolve:I}),{result:E,release:Ma()}},xl=new Set(["create.tableOfContents"]),Rl=f=>hr(`Tracked authoring is not supported for ${f}.`),nh=f=>{if(Xn()==="suggesting")return xl.has(f)?Rl(f):{changeMode:"tracked"}},Em=()=>Xn()==="suggesting"?aH:wb,Hr=(f,m,b)=>{const I=nh(f);return I&&I.success===!1?I:I?m(b,I):m(b)},Sb=(f,m,b,I)=>{const E=f.inline;if(!E)return;const z=ks(I);if(z===!1||typeof z=="object"&&z&&z.success===!1)return;if(E.kind==="clear"){n.clear();return}if(E.kind==="toggle"||!mb(E.key))return;const K=ya(m);if(!K)return;const oe=YV(E.key,b.value);if(oe==null){n.delete(E.key);return}n.set(E.key,{selectionSignature:K,value:oe})},_b=(f,m,b,I)=>!f.inline||f.inline.kind==="toggle"?I:Cr(I)?Promise.resolve(I).then(E=>(Sb(f,m,b,E),E)):I,rh=(f,m,b,I)=>{if(f.inline?.kind!=="toggle"||!yo(ks(I))||typeof b.value!="boolean"&&b.value!==null)return null;const E=ya(m);if(!E)return null;const z=++l;return r.set(f.id,{selectionSignature:E,active:b.value===!0,generation:z,settled:!1}),Xt(),z},nr=(f,m,b)=>{if(m==null)return;const I=r.get(f.id);if(!(!I||I.generation!==m)){if(!yo(b)){r.delete(f.id);return}I.settled=!0}},$u=(f,m)=>f.then(b=>(m?.(b),Go(),b),()=>(m?.(!1),Go(),!1)),qr=(f,m)=>{const b=gn;if(gn=null,b)return pn=$u(b,m),ks(f);if(Cr(f))return pn=$u(zn(f).settled,m),!0;const I=ks(f);return Sm(I)&&typeof _()?.documentMutationReadiness?.whenPainted=="function"?(pn=$u(Rr(I),m),I):(m?.(I),pn=Promise.resolve(I),Go(),I)},Tm=(f,m)=>!f||typeof f!="object"?m:f,La=(f,m=hr("Document API operation failed."))=>{if(Cr(f))return Promise.resolve(f).then(I=>La(I,m),()=>m);const b=Tm(f,m);return Es(),Sm(b)&&typeof _()?.documentMutationReadiness?.whenPainted=="function"?($u(Rr(b)),Xt(),b):(Xt(),b)},xm=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const oe=I(K);if(oe)try{const me=zn(Hr(f,m,oe));E.push(me.immediate),z.push(me.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return gn=z.length?Promise.all(z).then(K=>pi(K)):null,pi(E)},Rm=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const oe=I(K);if(oe)try{const me=zn(Hr(f,m,oe));E.push(me.immediate),z.push(me.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return gn=z.length?Promise.all(z).then(K=>pi(K)):null,pi(E)},ed=(f,m,b,I=dt.selection)=>{const E=nh(f);return E&&E.success===!1?E:I.selectionTarget?m(b,{...E??{},offsetSpace:"selection"}):E?m(b,E):m(b)},Ab=(f,m,b,I)=>{const E=vo(m,I);switch(f.kind){case"alignment":{const z=b;return z!=="left"&&z!=="center"&&z!=="right"&&z!=="justify"?null:{target:E,alignment:z}}case"spacing-line":{const z=typeof b=="number"?b:Number(b);return!Number.isFinite(z)||z<=0?null:{target:E,line:z,lineRule:"auto"}}case"style":if(b&&typeof b=="object"){const z=b.role;if(z&&typeof z=="object")return{target:E,role:z}}return typeof b!="string"||b.trim()===""?null:{target:E,styleId:b};case"direction":{const z=f.fixedValue;return z!=="ltr"&&z!=="rtl"?null:{target:E,direction:z}}default:return null}},Mm=(f,m)=>{const b=f.inline,I=bb(f),E=x();if(!b||typeof E?.setPendingInlineFormat!="function")return!1;if(b.kind==="clear")return Z(),!0;if(!I)return!1;let z;if(b.kind==="toggle")z=!Ea(f,y(),dt.selection);else{const K=m&&typeof m=="object"&&"value"in m?m.value:m;if(b.kind==="value-number"){const oe=typeof K=="number"?K:Number(K);z=Number.isFinite(oe)&&oe>0?oe:null}else z=typeof K=="string"&&K.trim()!==""?K:null;if(z===null)return F(I,null),!0}return F(I,z),!0},Rc=()=>{const f=y(),{lockModesById:m}=xs(f?.contentControls,dt.selection);if(Ji(m))return!1;const b=[],I=[],E=Xe=>{const He=zn(Xe);b.push(He.immediate),I.push(He.settled)},z=(Xe,He,Ze)=>{try{E(Ze?Xe(He,Ze):Xe(He))}catch{b.push(!1),I.push(Promise.resolve(!1))}},K=ze().cache?.full.defaults.paragraphStyleId??Ae,oe=Fu(dt.selection);if(oe){const Xe=yr(f,"format.apply");if(Xe)try{E(ed("format.apply",Xe,{target:oe,inline:{...Em()}}))}catch{b.push(!1),I.push(Promise.resolve(!1))}}const me=yr(f,"format.paragraph.resetDirectFormatting"),Re=yr(f,"styles.paragraph.setStyleRef"),Ue=qi(dt.selection),Ke=!Ue||Ue.storyType==="body",Fe=yr(f,Ke?"lists.remove":"lists.removeInStory");for(const Xe of Nr(dt.selection)){const He=vo(Xe,Ue);if(me&&z(me,{target:He}),Fe)try{const Ze=va(Xe),Qe=zn(Fe(Ke?{target:Ze}:{target:Ze,story:Ue}));I.push(Qe.settled.then(ot=>yo(ot)?ot:!0))}catch{}Re&&z(Re,{target:He,styleId:K})}if(!oe&&Xn()!=="suggesting"){const Xe=yr(f,"format.paragraph.setMarkRunProps");if(Xe)for(const He of Nr(dt.selection))z(Xe,{target:vo(He,Ue),markRunProps:{bold:!1,italic:!1,strikethrough:!1,doubleStrikethrough:!1,smallCaps:!1,caps:!1,verticalAlign:"baseline"}})}return gn=I.length?Promise.all(I).then(Xe=>pi(Xe)):null,pi(b.length?b:[!1])},td=(f,m,b)=>{const I=Nr(dt.selection);if(I.length===0)return!1;const E=qi(dt.selection);return xm(f.docRoute,m,I,z=>Ab(f.blockParagraph,z,b,E))},oh=(f,m,b)=>{const I=y(),E=yr(I,"format.paragraph.setIndentation"),z=yr(I,"format.paragraph.clearIndentation"),K=f.list?.mode,oe=Ki(dt.selection),me=qi(dt.selection),Re=async Ue=>{const Ke=await Ps(I,Ue,oe);if(Ke===!0)return{kind:"list",routeToCall:f.docRoute,opToCall:m,input:{target:_A(Ue)}};if(Ke===null||me&&me.storyType!=="body"&&typeof I?.getNode!="function")return null;const Fe=await Ac(I,Ue,me),Xe={};if(Fe?.right!=null&&(Xe.right=Fe.right),Fe?.firstLine!=null&&(Xe.firstLine=Fe.firstLine),Fe?.hanging!=null&&(Xe.hanging=Fe.hanging),K==="indent")return E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:vo(Ue,me),left:Math.max(0,Fe?.left??0)+AA,...Xe}}:null;const He=Math.max(0,(Fe?.left??0)-AA);return He>0&&(Xe.left=He),Object.keys(Xe).length===0?z?{kind:"paragraph",routeToCall:"format.paragraph.clearIndentation",opToCall:z,input:{target:vo(Ue,me)}}:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:vo(Ue,me),left:0}}:null:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:vo(Ue,me),...Xe}}:null};return gn=(async()=>{const Ue=await Promise.all(b.map(He=>Re(He).catch(()=>null)));if(Ue.length===b.length&&Ue.every(He=>He?.kind==="list")&&Xn()!=="suggesting"){const He=K==="indent"?"lists.indentRange":"lists.outdentRange",Ze=yr(I,He);if(Ze)try{return await zn(Hr(He,Ze,{paraIds:b,story:oe})).settled}catch{return!1}}const Ke=oe.storyType!=="body"&&Ue.some(He=>He?.kind==="list"),Fe=Ke&&K==="outdent"?yr(I,"lists.outdentInStory"):null;if(Ke&&!Fe)return!1;const Xe=Ue.map(He=>{if(!He)return Promise.resolve(!1);try{return He.kind==="list"&&Fe?zn(Hr("lists.outdentInStory",Fe,{target:He.input.target,story:oe})).settled:zn(Hr(He.routeToCall,He.opToCall,He.input)).settled}catch{return Promise.resolve(!1)}});return pi(await Promise.all(Xe))})(),!0},Rt=(f,m)=>{const b=f.list,I=y(),E=Nr(dt.selection);if(E.length===0)return!1;const z=Ki(dt.selection),K=z.storyType==="body";if(b.mode==="indent"||b.mode==="outdent")return oh(f,m,E);const oe=b.seed,me=Ke=>{if(Ke.some(ot=>!ot.resolved))return{immediate:!1,settled:null};const Fe=Ke.every(ot=>ot.seed===oe);if(!Fe&&!K)return{immediate:!1,settled:null};const Xe=Fe?K?"lists.remove":"lists.removeInStory":f.docRoute,He=Fe?yr(I,Xe):m;if(!He)return{immediate:!1,settled:null};const Ze=[],Qe=[];return E.forEach((ot,nt)=>{if(!Fe&&Ke[nt]?.seed===oe)return;const Ot=Fe?{target:va(ot),...K?{}:{story:z}}:{target:va(ot),seed:oe};try{const Qt=zn(Hr(Xe,He,Ot));Ze.push(Qt.immediate),Qe.push(Qt.settled)}catch{Ze.push(!1),Qe.push(Promise.resolve(!1))}}),{immediate:pi(Ze),settled:Qe.length?Promise.all(Qe).then(ot=>pi(ot)):null}},Re=E.map(Ke=>Al(I,Ke,z));if(Re.some(Cr))return gn=Promise.all(Re).then(async Ke=>{const Fe=me(Ke);return Fe.settled?await Fe.settled:Fe.immediate}),!0;const Ue=me(Re);return gn=Ue.settled,Ue.immediate};function Gt(f){return f&&typeof f=="object"?f:{}}function _n(f){if(typeof f=="string")return f;const m=Gt(f);if(Object.prototype.hasOwnProperty.call(m,"href"))return m.href;if(Object.prototype.hasOwnProperty.call(m,"value"))return m.value}function _r(f,m){const b=Gt(f).text;return typeof b=="string"&&b.trim()!==""?b:m}function Ur(f){const m=Gt(f),b=m.capture&&typeof m.capture=="object"?m.capture:null;return m.target??b?.target??b?.selectionTarget??m.selectionTarget??m.textTarget??null}const ho=f=>{const m=y(),b=m?.hyperlinks;if(!b)return!1;const I=Gt(f),E=_n(f),z=Ur(f),K=typeof I.text=="string"?I.text:void 0,oe=typeof I.currentText=="string"?I.currentText:void 0,me=lc(I.hyperlinkTarget)?I.hyperlinkTarget:null,Re=lc(I.textTarget)?I.textTarget:null,Ue=wc(m,dt.selection),Ke=typeof me?.storyId=="string"&&typeof me?.hyperlinkNodeId=="string";if(Ke&&E===null){const Fe=b.remove;if(typeof Fe!="function")return!1;try{return Hr("hyperlinks.remove",Fe,{storyId:me.storyId,hyperlinkNodeId:me.hyperlinkNodeId,keepText:!0})}catch{return!1}}if(Ue&&E===null){const Fe=b.remove;if(typeof Fe!="function")return!1;try{return Hr("hyperlinks.remove",Fe,{target:Ue.address,mode:"unwrap"})}catch{return!1}}if((Ue||me)&&typeof E=="string"&&E.trim()!==""){const Fe=b.patch,Xe=b.updateTarget;if(!(!Ke&&Ue&&typeof Fe=="function")&&!(Ke&&typeof Xe=="function"))return!1;const He=typeof K=="string"&&K!==(Ke?oe:Ue?.text??oe),Ze=m?.text?.replace,Qe=He?Ke?Re:tH(Ue?.address):null,ot=He&&!!Qe&&typeof Ze=="function";if(He&&!ot)return!1;const nt=[],Ot=[];let Qt=null,on=null,Dn=null,Mr=!1;try{if(Ke){if(typeof Xe!="function")return!1;const Ar=Hr("hyperlinks.updateTarget",Xe,{storyId:me.storyId,hyperlinkNodeId:me.hyperlinkNodeId,newTarget:nH(E)});Mr=Cr(Ar);const jr=zn(Ar);if(!yo(jr.immediate))return!1;nt.push(jr.immediate),Ot.push(jr.settled),Qt=jr.immediate,on=jr.committed,Dn=jr.settled}else if(Ue){if(typeof Fe!="function")return!1;const Ar=Hr("hyperlinks.patch",Fe,{target:Ue.address,patch:{href:E}});Mr=Cr(Ar);const jr=zn(Ar);if(!yo(jr.immediate))return!1;nt.push(jr.immediate),Ot.push(jr.settled),Qt=jr.immediate,on=jr.committed,Dn=jr.settled}}catch{return!1}if(ot){const Ar=(Lr,Ko)=>yo(Ko)?pi([Lr,Ko]):yo(Lr)?Hf(Lr,Ko):Ko,jr=Lr=>{if(!yo(Lr))return Lr;try{const Ko=zn(Hr("text.replace",Ze,{target:Qe,text:K}));return yo(Ko.immediate)?Promise.all([Dn??Promise.resolve(Lr),Ko.settled]).then(([Ob,kU])=>Ar(Ob,kU)):Hf(Lr,Ko.immediate)}catch{return Hf(Lr,!1)}};if(Mr)return gn=(on??Promise.resolve(Qt??!1)).then(jr),pi(nt);try{const Lr=zn(Hr("text.replace",Ze,{target:Qe,text:K}));if(!yo(Lr.immediate))return Qt?Hf(Qt,Lr.immediate):Lr.immediate;nt.push(Lr.immediate),Ot.push(Lr.settled),gn=Promise.all([Dn??Promise.resolve(Qt??!1),Lr.settled]).then(([Ko,Ob])=>Ar(Ko,Ob))}catch{return Qt?Hf(Qt,!1):!1}}return!ot&&Ot.length>0&&(gn=Promise.all(Ot).then(Ar=>pi(Ar))),pi(nt)}if(typeof E=="string"&&E.trim()!==""){const Fe=E.trim(),Xe=b.wrap,He=WV(z),Ze=He.length>0?He:pb(dt.selection);if(Ze.length>0){if(typeof Xe!="function")return!1;try{return Rm("hyperlinks.wrap",Xe,Ze,Ot=>({target:Ot,link:{destination:{href:Fe}}}))}catch{return!1}}const Qe=b.insert,ot=_r(f,Fe);if(typeof Qe!="function"||ot.trim()==="")return!1;const nt=jf(z)??ul(dt.selection);if(!nt)return!1;try{return Hr("hyperlinks.insert",Qe,{target:nt,text:ot,link:{destination:{href:Fe}}})}catch{return!1}}return!1},ki=(f,m,b)=>{const I=f.create.kind,E=b&&typeof b=="object"?b:{};if(I==="table"){const K=Number(E.rows??E.rowCount),oe=Number(E.columns??E.cols??E.colCount);if(!Number.isInteger(K)||K<1||!Number.isInteger(oe)||oe<1)return!1;const me=ul(dt.selection),Re=me&&typeof me.blockId=="string"?{kind:"inParagraph",target:vo(me.blockId),offset:me.range?.start??0}:vb(dt.selection,"nodeId");try{return Hr(f.docRoute,m,{rows:K,columns:oe,at:Re})}catch{return!1}}if(I==="image"){const K=E.src??E.value;if(typeof K!="string"||K.trim()==="")return!1;const oe=ul(dt.selection),me=Ki(dt.selection),Re=me.storyType==="body"?null:me;let Ue;oe&&typeof oe.blockId=="string"?Ue={kind:"inParagraph",target:vo(oe.blockId,Re),offset:oe.range?.start??0}:(Ue=vb(dt.selection,"target"),Re&&Ue.kind==="after"&&(Ue={...Ue,target:{...Ue.target,story:Re}}));const Ke={src:K,at:Ue};Re&&(Ke.in=Ue.kind==="inParagraph"?P(Re)??Re:Re),typeof E.alt=="string"&&(Ke.alt=E.alt),typeof E.title=="string"&&(Ke.title=E.title),E.size&&typeof E.size=="object"&&(Ke.size=E.size);try{return Hr(f.docRoute,m,Ke)}catch{return!1}}const z={at:vb(dt.selection,"target")};typeof E.instruction=="string"&&(z.instruction=E.instruction),E.config&&typeof E.config=="object"&&(z.config=E.config);try{return Hr(f.docRoute,m,z)}catch{return!1}},Ml=(f,m)=>{const b=f.table,I=Ne();if(!I||b.requiresCell&&!I.cellNodeId)return!1;const E=uH(b.action,I);if(!E)return!1;try{if(b.action==="insert-row-before"||b.action==="insert-row-after"){const z=x(),K=(typeof z?.getHandles=="function"?z.getHandles():null)?.editing?.tables;if(typeof K?.insertRow!="function")return!1;const oe=nh(f.docRoute);return oe&&oe.success===!1?oe:oe?K.insertRow(E,oe):K.insertRow(E)}return Hr(f.docRoute,m,E)}catch{return!1}},nd=f=>!f||f.disposition!=="routed"?!1:!!(f.inline||f.blockParagraph||f.list||f.link||f.create),jH=f=>{const m=Gt(f);return!!(Ur(f)||lc(m.hyperlinkTarget)||lc(m.textTarget))},GH=(f,m,b)=>dt.selection.status!=="ready"?!1:_m(f)?.scope==="id"||!m||m.disposition!=="routed"?!0:m.inline?.kind==="clear"?Nr(dt.selection).length>0||Fu(dt.selection)!=null:m.inline?Fu(dt.selection)!=null||Nr(dt.selection).length>0:m.blockParagraph||m.list?Nr(dt.selection).length>0:m.link?jH(b)||pb(dt.selection).length>0||ul(dt.selection)!=null||Ea(m,y(),dt.selection):!0,WH=(f,m)=>{const b=_m(f),I=Tu(f);return b?.scope!=="id"&&!nd(I)?!1:!GH(f,I,m)},KH=(f,m)=>WH(f,m)?yl().then(()=>{}):null,Mc=(f,m,b)=>{if(gn=null,pn=Promise.resolve(!1),$)return!1;const I=he.get(f);if(I)try{return qr(I.execute(Bu(m,b)))}catch{return!1}const E=yA(f);if(E&&typeof T()?.lists?.apply=="function")return Yn(E,m);const z=_m(f);if(z)return xn(z,m);if(f==="copy-format")return qr(qH());const K=Tu(f);if(!K||K.disposition!=="routed")return!1;const oe=K.normalizePayload?K.normalizePayload(m):m;if(K.instanceRoute){if(!_()||!fe(K,oe))return!1;const Ke=t?.[K.instanceRoute];if(typeof Ke!="function")return!1;try{const Fe=K.fixedArg!==void 0?K.fixedArg:oe;return qr(Ke.call(t,Fe))}catch{return!1}}if(K.inline?.kind==="clear")return K.mutates&&Xn()==="viewing"?!1:qr(Rc());const me=K.docRoute;if(!me||K.mutates&&Xn()==="viewing")return!1;const Re=y(),Ue=yr(Re,me);if(!Ue)return!1;if(K.inline){const{lockModesById:Ke}=xs(Re?.contentControls,dt.selection);if(Ji(Ke))return!1;const Fe=Fu(dt.selection);if(!Fe)return dt.selection.empty===!1?qr(!1):qr(Mm(K,oe));const Xe=Ea(K,Re,dt.selection),He=lH(K.inline,Fe,oe,Xe);if(!He)return!1;let Ze=null;try{const Qe=_(),ot=Xn(),nt=()=>_()!==Qe||y()!==Re||Xn()!==ot?!1:ed(me,Ue,He),Ot=ya(dt.selection)??ic(dt.selection),Qt=K.inline.kind==="toggle"?ii(`${K.id}:${Ot}`,nt):null;Ze=Qt?.release??null;const on=Qt?Qt.result:nt(),Dn=rh(K,dt.selection,He,on),Mr=qr(_b(K,dt.selection,He,on),Ar=>{nr(K,Dn,Ar),Ze?.(),Ze=null});return K.inline.kind==="toggle"&&(bn=pn),Mr}catch{return Ze?.(),!1}}if(K.blockParagraph){const Ke=td(K,Ue,oe),Fe=K.blockParagraph.kind==="alignment"&&yo(Ke)?fo(dt.selection,oe):null;return qr(Ke,Xe=>{Ju(Fe,Xe)})}if(K.list)return qr(Rt(K,Ue));if(K.link)return qr(ho(oe));if(K.create)return qr(ki(K,Ue,oe));if(K.table)return qr(Ml(K,Ue));try{return qr(K.mutates?Hr(me,Ue,oe):Ue(oe))}catch{return!1}},Lm=()=>{g+=1,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:h.lastClickAt,pointerSelecting:!1,keyboardSelecting:!1};for(const f of p)f("idle");Xt()},qH=async()=>{const f=["bold","italic","underline","strikethrough"].filter(Ue=>dt.toolbar.commands[Ue]?.active===!0),m=await bn;await c;const b=yo(m)?f:[],I=500,E=Date.now();if(h.mode!=="idle"){if(h.mode==="armed"&&E-h.lastClickAt<I){h={...h,mode:"persistent",lastClickAt:E};for(const Ue of p)Ue("persistent");return Xt(),!0}return Lm(),!1}const z=E-h.lastClickAt<I,K=++g;h={...h,lastClickAt:E};const oe=await yl(),me=`${ic(oe)}:${At()}`,Re=await YH(null,oe,me&&me===k?v:void 0,b);if(K!==g)return!0;h={...h,mode:z?"persistent":"armed",snapshot:Re,sourceSelectionKey:ic(oe),lastClickAt:E};for(const Ue of p)Ue(h.mode);return Xt(),!0},YH=async(f,m,b,I=[])=>{const E=m?.target??f?.target;if(!E||E.kind!=="text")return null;const z=Array.isArray(E.segments)?E.segments:[];if(z.length===0)return null;const K=y();if(!K)return null;const oe=E.story;let me=null;for(const He of z){const Ze=(await Ms(vo(He.blockId,oe)))?.node??null;if(!Ze)continue;const Qe=Ib(Ze),ot=XH(Array.isArray(Qe?.inlines)?Qe.inlines:[],He.range);me?me=FA(me,ot):me=ot}const Re=me?uV(me):{},Ue={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strike"},Ke=new Set([...m?.activeMarks??(Array.isArray(f?.activeMarks)?f.activeMarks:[]),...I]);for(const[He,Ze]of Object.entries(Ue))Ke.has(He)&&(Re[Ze]=!0);const Fe=b??await Qf(m??Ts(f,"ready"));if(Fe.fontFamily&&(Re.fontFamily=Fe.fontFamily),Fe.color&&(Re.color=Fe.color),Fe.highlight&&(Re.highlight=Fe.highlight),Fe.fontSize){const He=Number.parseFloat(Fe.fontSize);Number.isNaN(He)||(Re.fontSize=He)}let Xe=null;if(z.length===1){const He=z[0],Ze=(await Ms(vo(He.blockId,oe)))?.node??null;Ze&&Ib(Ze)&&(Xe=await ZH(Ze,He.blockId,K,oe))}return{story:oe??null,inline:Re,paragraph:Xe}},Ib=f=>f?f.kind==="paragraph"?f.paragraph??null:f.kind==="heading"?f.heading??null:null:null,XH=(f,m)=>{const b=K=>{const oe=K.run;return typeof oe?.text=="string"?oe.text:""},I=K=>K.run?.props;if(m.start===m.end){let K=0;for(const oe of f){const me=b(oe),Re=K,Ue=K+me.length;if(K=Ue,m.start>=Re&&m.start<=Ue){const Ke=I(oe);return Ke?{...Ke}:{}}}return{}}let E=0;const z=[];for(const K of f){const oe=b(K),me=E,Re=E+oe.length;if(E=Re,Re<=m.start||me>=m.end)continue;const Ue=I(K);Ue&&z.push(Ue)}return z.length===0?{}:z.length===1?{...z[0]}:FA(z[0],...z.slice(1))},FA=(f,...m)=>{const b={...f};for(const I of m)for(const E of Object.keys(b)){if(!(E in I)){delete b[E];continue}const z=b[E],K=I[E];(typeof z!=typeof K||JSON.stringify(z)!==JSON.stringify(K))&&delete b[E]}return b},ZH=async(f,m,b,I)=>{const E=Ib(f),z=E.props??{},K=E.styleRef??null,oe=z.alignment??null,me=z.spacing??null,Re=z.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,Ke=z.markRunProps??null,Fe=z.numbering?.numId,Xe=typeof Fe=="string"?parseInt(Fe,10):typeof Fe=="number"?Fe:NaN,He=z.numbering?.level,Ze=isNaN(Xe)?null:{numId:Xe,...He!=null?{level:He}:{}};let Qe=null;if(Ze&&typeof b.lists?.getState=="function")try{const ot=await b.lists.getState({target:vo(m,I)});ot&&typeof b.lists?.getStyle=="function"&&(Qe=await b.lists.getStyle(ot)??null)}catch{}return{styleId:K,alignment:oe,spacing:me,indentation:Ue,markRunProps:Ke,numbering:Ze,listStyle:Qe}},NA=async()=>{if(h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;const f=y()?.selection,m=async()=>uo(typeof f?.current=="function"?await Promise.resolve(f.current({includeText:!0})):_a().value),b=()=>new Promise(K=>setTimeout(K,16)),I=8;let E=null,z="";for(let K=0;K<I;K+=1){if(K>0&&await b(),h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;if(E=await m(),!(!E||E.empty)&&(z=ic(E),z!==h.sourceSelectionKey))break}if(E&&!E.empty&&z!==h.sourceSelectionKey){await BA(E);return}if(h.snapshot?.paragraph){const K=await m();if(!K||ic(K)===h.sourceSelectionKey)return;await BA(K)}},BA=async f=>{const m=h.snapshot;if(!m){h.mode==="armed"&&Lm();return}const b=y();if(!b)return;const I=Ts(f,"ready"),{lockModesById:E}=xs(b.contentControls,I);if(Ji(E)){Xt();return}const z=f.target,K=f.selectionTarget;if(f.empty!==!0&&Object.keys(m.inline).length>0){const oe=yr(b,"format.apply");if(oe&&K)try{if(!yo(ks(await Promise.resolve(ed("format.apply",oe,{target:K,inline:m.inline},f))))){Xt();return}}catch{Xt();return}}if(m.paragraph){const oe=Array.isArray(z?.segments)?z.segments:[],me=z?.story;for(const Re of oe){const Ue=vo(Re.blockId,me),Ke=await Ms(Ue),Fe=Ke?.node??null,Xe=Ke?.address??null;if(!Fe)continue;const He={kind:"block",nodeType:Xe?.nodeType??Fe.kind??"paragraph",nodeId:Re.blockId,...me&&typeof me=="object"?{story:me}:{}},{styleId:Ze,alignment:Qe,spacing:ot,indentation:nt,markRunProps:Ot,numbering:Qt,listStyle:on}=m.paragraph;if(Ze&&await b.styles?.paragraph?.setStyle?.({target:He,styleId:Ze}),Qe&&await b.format?.paragraph?.setAlignment?.({target:He,alignment:Qe}),ot){const Dn=ot,Mr=Dn.lineRule??"auto",Ar=new Set(["auto","exact","atLeast"]).has(Mr)?Mr:"auto",jr={...Dn.before!=null?{before:Math.round(Dn.before*20)}:{},...Dn.after!=null?{after:Math.round(Dn.after*20)}:{},...Dn.line!=null?{line:Math.round(Ar==="auto"?Dn.line*240:Dn.line*20),lineRule:Ar}:{}};await b.format?.paragraph?.setSpacing?.({target:He,...jr})}if(nt){const Dn={...nt.left!=null?{left:Cs(nt.left)}:{},...nt.right!=null?{right:Cs(nt.right)}:{},...nt.firstLine!=null?{firstLine:Cs(nt.firstLine)}:{},...nt.hanging!=null?{hanging:Cs(nt.hanging)}:{}};await b.format?.paragraph?.setIndentation?.({target:He,...Dn})}Ot&&await b.format?.paragraph?.setMarkRunProps?.({target:He,markRunProps:Ot}),Qt&&await b.format?.paragraph?.setNumbering?.({target:He,...Qt}),on&&((await Ms(Ue))?.address?.nodeType==="listItem"?await b.lists?.applyStyle?.({target:_A(Re.blockId,me),style:on}):Qt&&await b.format?.paragraph?.setNumbering?.({target:He,...Qt}))}}h.mode==="armed"&&Lm(),Xt()},Pm=(f,m,b)=>{const I=KH(f,m),E=I?I.then(()=>(Mc(f,m,b),pn)):(Mc(f,m,b),pn);return Tu(f)?.inline?.kind==="toggle"&&(bn=E),E},zA=f=>({id:f,getState:()=>dt.toolbar.commands[f]??bc(f,y(),dt.selection,Sl(dt.selection)),observe:m=>Fs(b=>b.toolbar.commands[f]??{enabled:!1,active:!1,supported:!1,source:"unsupported",reason:ut.commandUnsupported}).subscribe(m),execute:m=>Mc(f,m),executeAsync:m=>Pm(f,m)}),QH=f=>{he.set(f.id,f),Xt();const m=()=>{he.delete(f.id),Xt()};return Object.assign(m,{handle:zA(f.id),unregister:m})},Dm=Ao(f=>f.selection),Om=oi(Dm),VA=()=>{const f=x();if(typeof f?.getHandles!="function")return{reason:ut.hostCapabilityUnavailable};let m=null;try{m=f.getHandles()}catch(I){const E=I?.reason;return{reason:E==="host-not-ready"||E==="host-disposed"||E==="editing-mount-required"?ut.notReady:ut.hostCapabilityUnavailable}}const b=m?.editing?.selectionTargets;return typeof b?.apply!="function"?{reason:ut.hostCapabilityUnavailable}:{helper:b}},JH=f=>{const m=x();if(typeof m?.getHandles=="function")try{const b=m.getHandles()?.editing?.contentControls;typeof b?.activate=="function"&&b.activate({id:f})}catch{}},HA={get:Om.get,getSnapshot:Om.getSnapshot,subscribe:Om.subscribe,observe:Om.observe,current:()=>_a().value,capture:()=>{const f=Dm.get();return f.empty||!f.target&&!f.selectionTarget?null:{...f,capturedAt:Date.now()}},restore:f=>{const m=E=>(Xt(),{...E,success:E.ok});if(!f||typeof f!="object")return m({ok:!1,reason:ut.targetUnresolved});if(!_())return m({ok:!1,reason:ut.notReady});const b=sH(f);if(!b)return m({ok:!1,reason:ut.targetUnresolved});const I=VA();if(!("helper"in I))return m({ok:!1,reason:I.reason});try{return m(vA(I.helper.apply(b)))}catch{return m({ok:!1,reason:ut.hostCapabilityUnavailable})}},apply:f=>{if(!_())return{ok:!1,reason:ut.notReady};const m=VA();if(!("helper"in m))return{ok:!1,reason:m.reason};try{const b=m.helper.apply(f);return Xt(),vA(b)}catch{return{ok:!1,reason:ut.hostCapabilityUnavailable}}},getAnchorRect:f=>{const m=x();if(typeof m?.getSelectionAnchorRect=="function"){const b=Lt(()=>m.getSelectionAnchorRect(f),null);return b&&typeof b=="object"&&(Number(b.width)>0||Number(b.height)>0)?b:null}return null},getRects:f=>{const m=Dm.get(),b=m.selectionTarget??m.target;if(m.empty||!b)return[];const I=Wm.getRect({target:b,relativeTo:f?.relativeTo});return I.found?I.rects:[]}},$H={get ids(){return le()},has:f=>Tu(f)!=null||he.has(f),get:f=>zA(f),execute:Mc,executeAsync:Pm,register:QH,getContextMenuItems:f=>{const m=[];for(const b of he.values()){const I=b.contextMenu;I&&Lt(I.when?()=>I.when(f):void 0,!0)&&m.push({id:b.id,label:I.label,group:I.group,order:I.order,invoke:()=>Mc(b.id,void 0,f)})}return m.sort((b,I)=>(b.order??0)-(I.order??0)||b.label.localeCompare(I.label))}},Eb=oi(Ao(f=>f.toolbar)),eU={get:Eb.get,getSnapshot:()=>dt.toolbar,subscribe:Eb.subscribe,observe:Eb.observe,execute:Mc,executeAsync:Pm},Lc=async(f,m)=>{if(!_())return{success:!1,ok:!1,reason:ut.notReady};if(!f)return{success:!1,ok:!1,reason:ut.targetUnresolved};const b=x(),I=b?.scrollTargetIntoView;if(typeof I!="function")return{success:!1,ok:!1,reason:ut.hostCapabilityUnavailable};try{const E={target:f,block:m?.block??"center",behavior:m?.behavior??"smooth"},z=await Promise.resolve(m?.shouldContinue?I.call(b,E,m.shouldContinue):I.call(b,E));return z&&typeof z=="object"&&z.success===!1?{success:!1,ok:!1,reason:db(z.reason,ut.targetUnresolved)}:{success:!0,ok:!0}}catch{return{success:!1,ok:!1,reason:ut.hostCapabilityUnavailable}}},Fm=async(f,m,b,I)=>{const E=f==="trackChanges"?I?.story:void 0,z=ot=>{if(!E||!ot||typeof ot!="object")return ot;const nt=ot,Ot=nt.address&&typeof nt.address=="object"?nt.address:null;return nt.story||Ot?.story?ot:{...nt,story:E}},K=f==="trackChanges"?LV:Uf,oe=b.find(ot=>Wi(ot,m,E)),me=oe&&typeof oe=="object"?oe:null,Re=f==="trackChanges"&&me?.type==="move"&&(me.subtype==="move-to"||me.subtype==="move-from")?me.subtype:null,Ue=Re&&typeof me?.trackedChangeCanonicalId=="string"?me.trackedChangeCanonicalId:m,Ke=ot=>{if(!Re)return K(ot);const nt=Uf(ot);if(nt?.kind!=="move")return null;const Ot=Re==="move-to"?nt.destination:nt.source;return fb(Ot)?Ot:null},Fe=K(oe),Xe=f!=="trackChanges"||!Re&&fb(Uf(oe));if(Fe&&Xe)return z(Fe);const He=y()?.[f],Ze=f==="comments"?{commentId:m}:{id:Ue,...E?{story:E}:{}},Qe=He?.get;if(typeof Qe!="function")return z(Fe);try{return z(Ke(await Promise.resolve(Qe.call(He,Ze)))??Fe)}catch{return z(Fe)}};function UA(f,m){if(Zi())return hr("Comments are read-only.","DOCUMENT_READONLY");if(dc())return hr("Resolving comments is disabled.","DOCUMENT_READONLY");const b=y()?.comments,I=b?.patch;if(typeof I!="function")return hr("comments.patch is unavailable.");const E=hr("comments.patch failed.");return Lt(()=>La(I.call(b,{commentId:f,status:m}),E),E)}const Nm=()=>Zi()?hr("Comments are read-only.","DOCUMENT_READONLY"):null,jA=(f,m)=>{const b=m&&typeof m=="object"?m:null;let I=Array.from(f);b?.includeResolved===!1&&(I=I.filter(me=>me.status!=="resolved"));const E=Number(b?.offset),z=Number.isInteger(E)&&E>0?E:0,K=Number(b?.limit),oe=Number.isInteger(K)&&K>=0?z+K:void 0;return I.slice(z,oe)},rd=Ao(f=>f.comments),Bm=oi(rd),tU={get:Bm.get,getSnapshot:Bm.getSnapshot,subscribe:Bm.subscribe,observe:Bm.observe,list:f=>{const m=rd.get();if(m.status!=="pending")return jA(m.items,f);const b=y()?.comments,I=Lt(b?.list?()=>b.list(f):void 0,null);return Cr(I)?[]:jA(Array.isArray(I?.items)?I.items:[],f)},getById:f=>{const m=rd.get().items.find(E=>Kn(E)===f)??null;if(m)return m;const b=y()?.comments,I=Lt(b?.get?()=>b.get({commentId:f}):void 0,null);return Cr(I)?null:I},createFromCapture:(f,m)=>{const b=Nm();if(b)return b;const I=y()?.comments,E=I?.create;if(typeof E!="function")return hr("comments.create is unavailable.");const z=hr("comments.create failed.");return Lt(()=>La(E.call(I,{target:f.target??f.selectionTarget,text:m.text}),z),z)},createFromSelection:f=>{const m=Nm();if(m)return m;const b=y()?.comments,I=b?.create;if(typeof I!="function")return hr("comments.create is unavailable.");const E=Dm.get(),z=E.target??E.selectionTarget;if(E.empty||!z)return hr("A range selection is required to comment.","NO_SELECTION");const K=hr("comments.create failed.");return Lt(()=>La(I.call(b,{target:z,text:f.text}),K),K)},reply:(f,m)=>{const b=Nm();if(b)return b;const I=y()?.comments,E=I?.reply??I?.create;if(typeof E!="function")return hr("comments.reply is unavailable.");const z=hr("comments.reply failed.");return Lt(()=>La(E===I?.reply?E.call(I,{parentCommentId:f,text:m.text}):E.call(I,{parentCommentId:f,text:m.text}),z),z)},resolve:f=>UA(f,"resolved"),reopen:f=>UA(f,"active"),delete:f=>{const m=Nm();if(m)return m;const b=y()?.comments,I=b?.delete??b?.remove;if(typeof I!="function")return hr("comments.delete is unavailable.");const E=hr("comments.delete failed.");return Lt(()=>La(I.call(b,{commentId:f}),E),E)},setActive:f=>{if(f==null)return ye=null,Xt(),!0;if(!_())return!1;const m=rd.get();if(m.listStatus!=="ready")return!1;const b=HV(m.items,f);return!b||!m.items.some(I=>Kn(I)===b)?!1:(ye=b,Xt(),!0)},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:_()?ut.documentApiUnavailable:ut.notReady};const m=await Fm("comments",f,rd.get().items);return m?Lc(m):{success:!1,ok:!1,reason:ut.targetUnresolved}}},Pa=Ao(f=>f.trackChanges),Tb=(f,m)=>{const b=Pa.get().items.filter(Ke=>Kn(Ke)!==null);if(b.length===0)return null;const I=dt.trackChanges.activeId,E=ce?.id===I?ce.story:void 0,z=b.filter(Ke=>wm(Ke)==null),K=E||z.length===0?b:z;let oe=I?K.findIndex(Ke=>Wi(Ke,I,E)):-1;oe===-1&&I&&E&&(oe=K.findIndex(Ke=>Wi(Ke,I)));const me=K[oe===-1?f>0?0:K.length-1:(oe+f+K.length)%K.length],Re=Kn(me),Ue=wm(me);return je(Ue?{id:Re,story:Ue}:{id:Re},m),Xt(),Re};let GA=Promise.resolve();const nU=f=>{const m=ie;return GA.catch(()=>{}).then(()=>rU(f,m))},rU=async(f,m)=>{if(ie!==m)return{success:!1};const b=ce,I=Tb(f,{invalidateQueuedNavigation:!1});if(I==null)return{success:!1};const E=ce,z=ke,K=()=>ie===m&&ce===E&&ke===z,oe=()=>{K()&&(je(b,{invalidateQueuedNavigation:!1}),Xt())};E&&Je.add(E);try{const me=await Fm("trackChanges",I,Pa.get().items,E?.story?{story:E.story}:void 0);if(!K())return{success:!1};if(!me)return oe(),{success:!1};_o+=1;try{const Re=await Lc(me,{behavior:"auto",shouldContinue:K});return K()?(!Re.ok&&Re.reason!==ut.targetNotVisible?(oe(),Te(b)):Te(E),{success:Re.ok}):{success:!1}}finally{_o=Math.max(0,_o-1),_o===0&&(K()?xr&&Bo(Ci(xr)):Te(ce))}}finally{E&&Je.delete(E)}},WA=f=>{const m=nU(f);return GA=m.then(()=>{},()=>{}),m},zm=oi(Pa),oU={get:()=>(Se(),zm.get()),getSnapshot:()=>(Se(),zm.getSnapshot()),subscribe:f=>(Se(),zm.subscribe(f)),observe:f=>(Se(),zm.observe(f)),list:()=>(Se(),Pa.get().items),accept:f=>xb("accept",f),reject:f=>xb("reject",f),acceptAll:()=>ih("accept",{kind:"all"},null),rejectAll:()=>ih("reject",{kind:"all"},null),next:()=>Tb(1),previous:()=>Tb(-1),navigateNext:()=>WA(1),navigatePrevious:()=>WA(-1),getAt:f=>{if(!f||typeof f!="object"||typeof f.x!="number"||typeof f.y!="number")return null;const m=Lb(f);if(m.length===0)return null;const b=Pa.get().items;let I;for(const E of m){if(E.type!=="trackedChange")continue;let z;if(E.story){if(I===void 0&&(I=Qi()),!I)continue;z=I}else z=b;const K=z.find(oe=>Wi(oe,E.id,E.story));if(K)return E.story?{id:K.id,item:K,story:E.story}:{id:K.id,item:K}}return null},setActive:f=>{if(f==null)return je(null),Te(null),Xt(),!0;if(!_())return!1;const m=typeof f=="string"?{id:f}:{id:f.id,story:f.story};if(typeof m.id!="string"||m.id.length===0)return!1;const b=m.id;if(m.story){const I=Qi();if(!I)return!1;const E=Pu(I,m.story).toPublicId(m.id)??m.id;if(!I.some(z=>Wi(z,E,m.story)))return!1;m.id=E}else{const I=Pa.get().items,E=ga(I).toPublicId(m.id)??m.id,z=I.find(K=>Kn(K)===E);if(!z)return!1;m.id=E,m.story=wm(z)}return b!==m.id&&(m.paintedEntityId=b),je(m),Te(m),Xt(),!0},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:_()?ut.documentApiUnavailable:ut.notReady};ie+=1,xe+=1;const m=xe,b=Pa.get().items,I=ga(b).toPublicId(f)??f,E=wm(b.find(oe=>Kn(oe)===I)),z=ce,K={id:I,...E?{story:E}:{},...I!==f?{paintedEntityId:f}:{}};Je.add(K);try{const oe=await Fm("trackChanges",I,b,E?{story:E}:void 0);if(xe!==m)return{success:!1,ok:!1};if(!oe)return{success:!1,ok:!1,reason:ut.targetUnresolved};je(K);const me=xe,Re=ce,Ue=ke,Ke=()=>xe===me&&ce===Re&&ke===Ue,Fe=()=>{Ke()&&(je(z,{invalidateQueuedNavigation:!1}),Xt())};Xt(),_o+=1;try{const Xe=await Lc(oe,{behavior:"auto",shouldContinue:Ke});return Ke()?(!Xe.ok&&Xe.reason!==ut.targetNotVisible?(Fe(),Te(z)):Te(K),Xe):{success:!1,ok:!1}}finally{_o=Math.max(0,_o-1),_o===0&&(Ke()?xr&&Bo(Ci(xr)):Te(ce))}}finally{Je.delete(K)}}},xb=(f,m)=>{const{id:b,story:I}=typeof m=="string"?{id:m,story:void 0}:m;return ih(f,{kind:"id",id:b,...I?{story:I}:{}},b,I)},ih=(f,m,b,I)=>{try{return qr(Rb(f,m,b,I))}catch{return!1}},Rb=(f,m,b,I)=>{if(Zi())return!1;const E=y()?.trackChanges,z=m.kind==="all"||m.scope==="all",K=m.kind==="range",oe=m.kind==="ids";if(Ku({kind:f,scope:z?"all":"id"},E))return!1;const me=z?`${f}All`:f,Re=!K&&!oe&&!I&&E&&typeof E[me]=="function"?E[me]: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:m})},Mb=Ao(f=>f.contentControls),sh=f=>Mb.get().items.find(m=>m?.id===f)??null,Vm=oi(Mb),iU=(f=>{if(f===void 0)return Vm.get();const m=Cm(f);return m?sh(m):null}),sU={get:(f=>(f!==void 0&&jo("api"),iU(f))),getSnapshot:Vm.getSnapshot,subscribe:Vm.subscribe,observe:Vm.observe,list:()=>(jo("api"),Mb.get().items),getById:f=>(jo("api"),sh(f)),getRect:f=>{const m=Cm(f);if(!m)return fl("unresolved");jo("panel");const b=sh(m);if(!b)return fl("unresolved");const I=hb(b);return I?Wm.getRect({target:I}):fl("unavailable")},scrollIntoView:async f=>{const m=Cm(f);if(!m)return{success:!1};jo("panel");const b=sh(m);if(!b)return{success:!1};const I=hb(b);return I?{success:(await Lc(I,{block:f.block,behavior:f.behavior})).ok}:{success:!1}},focus:async f=>{const m=Cm(f);if(!m)return{success:!1,reason:"invalid-id"};if(!_())return{success:!1,reason:"not-ready"};jo("panel");const b=sh(m);if(!b)return{success:!1,reason:"not-found"};const I=hb(b);if(!I)return{success:!1,reason:"not-reachable"};if(!(await Lc(I,{block:f.block,behavior:f.behavior})).ok)return{success:!1,reason:"not-reachable"};const E=OV(I);if(!E)return{success:!1,reason:"not-reachable"};const z=HA.apply(E);return!z.ok&&z.reason!==ut.hostCapabilityUnavailable?{success:!1,reason:"not-reachable"}:(JH(m),{success:!0})}},Hm=oi(Ao(f=>f.fonts)),aU={get:Hm.get,getSnapshot:Hm.getSnapshot,subscribe:Hm.subscribe,observe:Hm.observe,getFamilyOptions:()=>dt.fonts.options,getSizeOptions:()=>dt.fonts.sizeOptions},Um=oi(Ao(f=>f.zoom)),lU={get:Um.get,getSnapshot:Um.getSnapshot,subscribe:Um.subscribe,observe:Um.observe,set:f=>{if(typeof t?.setZoom=="function")try{t.setZoom(f),Xt()}catch{}},setMode:f=>{if(typeof t?.setZoomMode=="function")try{t.setZoomMode(f),Xt()}catch{}}},jm=oi(Ao(f=>f.document)),cU={get:jm.get,getSnapshot:jm.getSnapshot,subscribe:jm.subscribe,observe:jm.observe,setMode:f=>{if(typeof t?.setDocumentMode=="function")try{t.setDocumentMode(f),Xt()}catch{}},export:f=>{if(typeof t?.export=="function")try{return Promise.resolve(t.export(f))}catch{return}},getText:()=>{const f=y(),m=Lt(f?.getText?()=>f.getText({}):void 0,null);return typeof m=="string"?m:m&&typeof m=="object"&&typeof m.text=="string"?m.text:null},replaceFile:f=>{const m=t?.replaceFile??t?.loadDocument??t?.reload;if(typeof m=="function")try{return Promise.resolve(m.call(t,f))}catch{return}}},KA=()=>{if(typeof HTMLElement>"u")return null;const f=_()?.mount?.container;if(f instanceof HTMLElement)return f;const m=t?.element;return m instanceof HTMLElement?m:null},uU=(f,m)=>{if(typeof f!="number"||typeof m!="number"||!Number.isFinite(f)||!Number.isFinite(m))return[];const b=globalThis.document;if(!b||typeof b.elementFromPoint!="function")return[];const I=KA();if(!I)return[];const E=b.elementFromPoint(f,m);if(!E||!I.contains(E))return[];const z=[E],K=nt=>{nt&&I.contains(nt)&&!z.includes(nt)&&z.push(nt)},oe=b.elementsFromPoint;if(typeof oe=="function"){let nt=[];try{nt=oe.call(b,f,m)??[]}catch{nt=[]}for(const Ot of nt)K(Ot)}const me=[],Re=nt=>{nt&&I.contains(nt)&&!me.includes(nt)&&!z.includes(nt)&&me.push(nt)},Ue=nt=>{const Ot=nt.getBoundingClientRect;if(typeof Ot!="function")return!1;let Qt;try{Qt=Ot.call(nt)}catch{return!1}return Qt!=null&&f>=Qt.left&&f<=Qt.right&&m>=Qt.top&&m<=Qt.bottom};for(const nt of z){const Ot=nt.querySelectorAll;if(typeof Ot!="function")continue;let Qt;try{Qt=Ot.call(nt,"[data-track-change-marker]")}catch{continue}for(let on=0;on<Qt.length;on+=1)Ue(Qt[on])&&Re(Qt[on])}me.reverse();const Ke=[...me,...z],Fe=gA(Ke[0],I);for(let nt=1;nt<Ke.length;nt+=1)for(const Ot of gA(Ke[nt],I))Fe.push(Ot);if(Fe.length===0)return Fe;const Xe=Pa.get().items,He=ga(Xe);let Ze;const Qe=new Set,ot=[];for(const nt of Fe){if(nt.type!=="trackedChange"){const Dn=`${nt.type}:${nt.id}`;if(Qe.has(Dn))continue;Qe.add(Dn),ot.push(nt);continue}const Ot=DV(nt.storyKey)??PV(nt.story);let Qt;if(Ot){if(Ze===void 0&&(Ze=Qi()),!Ze||(Qt=Pu(Ze,Ot).toPublicId(nt.id),!Qt||!Ze.some(Dn=>Wi(Dn,Qt,Ot))))continue}else if(Qt=He.toPublicId(nt.id),!Qt)continue;const on=`trackedChange:${Qt}`;Qe.has(on)||(Qe.add(on),ot.push(Ot?{type:"trackedChange",id:Qt,story:Ot}:{type:"trackedChange",id:Qt}))}return ot};function Lb(f,m){return typeof f=="object"?uU(f?.x,f?.y):null}const od=new Set;let Pb=!1;const qA=f=>{const m=x();if(typeof m?.observeGeometry!="function")return;let b=!1;const I=Lt(()=>{const E=m.observeGeometry(()=>f.schedule());return b=!0,E},null);f.detach=typeof I=="function"?I:null,f.boundHost=b?m:null},Gm=f=>{if(f.detach){try{f.detach()}catch{}f.detach=null}f.boundHost=null},YA=()=>{if(Pb=!1,!($||x()))for(const f of od)Gm(f)},dU=()=>{if(!Pb){if(Pb=!0,typeof queueMicrotask=="function"){queueMicrotask(YA);return}Promise.resolve().then(YA)}},fU=()=>{const f=x();if(!f){dU();return}for(const m of od)m.boundHost&&m.boundHost===f||(Gm(m),qA(m),m.schedule())};xa.push(fU);const Wm={getRect:f=>{const m=x(),b=m?.getTargetRects;if(typeof b=="function"){const I=Lt(()=>b.call(m,{target:f.target}),null);return I&&typeof I=="object"?I.success===!0&&Array.isArray(I.rects)?oH(rH(I.rects.filter(E=>E!=null&&typeof E=="object")),f.relativeTo):fl(typeof I.reason=="string"?I.reason:"unresolved"):fl("unresolved")}return fl("unavailable")},observe:f=>{const m=[];let b=0;const I=typeof requestAnimationFrame=="function",E=()=>{if(!I){f();return}b||(b=requestAnimationFrame(()=>{b=0,f()}))},z=Fs(oe=>({ready:oe.ready,selection:oe.selection,zoom:oe.zoom}));m.push(z.subscribe(()=>E()));const K={schedule:E,detach:null,boundHost:null};return qA(K),od.add(K),()=>{od.delete(K),Gm(K),b&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(b);for(const oe of m.splice(0))try{oe()}catch{}}},getHost:()=>KA(),entityAt:Lb,contextAt:f=>{const m=!!f&&typeof f.x=="number"&&typeof f.y=="number",b=m?f.x:0,I=m?f.y:0;return{point:{x:b,y:I},entities:m?Lb({x:b,y:I}):[],selection:dt.selection,position:null,insideSelection:!1}},scrollIntoView:async f=>{const m=f?.target;if(!m)return{success:!1};let b=null;if(m.kind==="entity"){const I=m.entityType==="comment"?"comments":"trackChanges",E=I==="comments"?rd.get().items:Pa.get().items,z=m.entityType==="trackedChange"&&m.story?{story:m.story}:void 0;b=await Fm(I,m.entityId,E,z)}else{const I=m,E=m,z=Array.isArray(I.segments)&&I.segments.length>0?I.segments:E.blockId&&E.range?[{blockId:E.blockId,range:E.range}]:null;if(z){const K=m.story;b={kind:"text",segments:z,...K?{story:K}:{}}}}return b?{success:(await Lc(b,{block:f.block??"center",behavior:f.behavior??"smooth"})).ok}:{success:!1}}},XA=f=>{const m=(f&&typeof f=="object"?f:null)?.target;return m&&typeof m=="object"?m:null},ZA=f=>`metadata:resolve:${f}`,hU=f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;const{value:b}=Vr(ZA(f),At(),()=>m.resolve({id:f}),XA);return b},pU=async f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;try{const b=At(),I=await Promise.resolve(m.resolve({id:f}));if(b!==At())return null;const E=XA(I);return ee.set(ZA(f),{token:b,value:E,hasSettled:!0,inflightToken:null}),E}catch{return null}},mU={getRect:f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return fl("unavailable");const b=hU(f.id);return b?Wm.getRect({target:b}):fl("unresolved")},scrollIntoView:async f=>{const m=await pU(f.id);return m?{success:(await Lc(m,{block:f.block,behavior:f.behavior})).ok}:{success:!1}}},gU={inTable:!1,tableNodeId:null,rowIndex:null,columnIndex:null,cellNodeId:null,rows:null,columns:null},vU={getContext:()=>{const f=Ne();if(!f)return{...gU};const m=pe()?.table;return{inTable:!0,tableNodeId:f.tableNodeId,rowIndex:f.rowIndex,columnIndex:f.columnIndex,cellNodeId:f.cellNodeId,rows:typeof m?.rows=="number"?m.rows:null,columns:typeof m?.columns=="number"?m.columns:null}},isInTable:()=>Ne()!=null},Km={query:"",total:0,activeIndex:-1,open:!1,available:!1,caseSensitive:!1,includeDeletedText:!1,regex:!1,canReplace:!1,reason:ut.searchUnavailable};let Vn={...Km};const qm=new Set,Da=()=>{const f=x()?.search;return f&&typeof f=="object"?f:null},Ns=()=>{const f=T()?.search;return f&&typeof f=="object"?f:null},ah=()=>{const f=Da();if(f&&typeof f.setSession=="function")return!0;const m=Ns();return!!m&&typeof m.query=="function"&&typeof m.getState=="function"},ts=()=>{for(const f of[...qm])try{f(Vn)}catch{}},si=f=>(Vn={...Vn,...f},ts(),Vn);let to=0,Pc=null;const QA=()=>{const f=Pc;Pc=null,f&&Lt(()=>(f(),null),null)},yU=()=>{to+=1,QA();const f=ah();Vn={...Km,available:f,reason:f?void 0:ut.searchUnavailable},ts()};es.push(yU);const bU=f=>{if(!f)return!1;const m=f.queryError;if(m&&typeof m=="object"&&m.code==="invalid-pattern")return!0;const b=f.rejection;return f.status==="rejected"&&!!b&&typeof b=="object"&&b.code==="invalid-pattern"},Db=(f,m=!1)=>{const b=f&&typeof f=="object"?f:null;if(!b)return null;const I=Array.isArray(b.matches)?b.matches:[],E=typeof b.total=="number"&&Number.isFinite(b.total)?b.total:I.length,z=typeof b.activeMatchIndex=="number"?b.activeMatchIndex:typeof b.activeIndex=="number"?b.activeIndex:-1;return{...typeof b.query=="string"?{query:b.query}:{},total:E,activeIndex:z,canReplace:b.canReplace===!0||m,...b.includeDeletedText===!0?{includeDeletedText:!0}:{},...b.regex===!0?{regex:!0}:{},...bU(b)?{invalidPattern:!0}:{}}},Io=()=>{const f=V("find.replace"),m=V("find.replaceAll");return f?.enabled===!0||m?.enabled===!0},Eo=(f,m=!1)=>{const b=Db(f,m);if(!b){si({total:0,activeIndex:-1,canReplace:!1,reason:void 0});return}si({...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?ut.searchInvalidPattern:void 0})},Oa=()=>{const f=Da();if(f&&typeof f.getState!="function")return Vn={...Vn,available:ah(),reason:ah()?void 0:ut.searchUnavailable},Vn;if(!f){const b=Ns();if(b&&typeof b.getState=="function"){const I=Db(Lt(()=>b.getState(),null),Io());if(I)return Vn={...Vn,...I.query!==void 0?{query:I.query}:{},total:I.total,activeIndex:I.activeIndex,canReplace:I.canReplace,available:!0,reason:I.invalidPattern?ut.searchInvalidPattern:void 0,open:Vn.open||!!I.query},Vn}return Vn={...Km,query:Vn.query,caseSensitive:Vn.caseSensitive,includeDeletedText:Vn.includeDeletedText},Vn}const m=Db(Lt(()=>f.getState(),null));return m&&(Vn={...Vn,...m.query!==void 0?{query:m.query}:{},total:m.total,activeIndex:m.activeIndex,canReplace:m.canReplace,...m.includeDeletedText!==void 0?{includeDeletedText:m.includeDeletedText}:{},...m.regex!==void 0?{regex:m.regex}:{},available:!0,reason:m.invalidPattern?ut.searchInvalidPattern:void 0,open:Vn.open||!!m.query}),Vn},id=f=>{const m=f&&typeof f=="object"?f:null;if(m?.status==="committed")return{ok:!0};if(m?.status==="rejected"&&m.reason==="read-only")return{ok:!1,reason:ut.documentReadonly};const b=m?.rejection;return m?.status==="rejected"&&b&&typeof b=="object"&&b.code==="read-only-document"?{ok:!1,reason:ut.documentReadonly}:{ok:!1,reason:ut.operationUnavailable}},Ym=oi({get:()=>Oa(),subscribe:f=>(qm.add(f),()=>qm.delete(f))}),wU={get:Ym.get,getSnapshot:Ym.getSnapshot,subscribe:Ym.subscribe,observe:Ym.observe,open:()=>ah()?(si({available:!0,open:!0,reason:void 0}),{ok:!0}):(si({available:!1,open:!1,reason:ut.searchUnavailable}),{ok:!1,reason:ut.searchUnavailable}),close:()=>{if(to+=1,Pc)QA();else{const f=Da();if(f&&typeof f.clear=="function")Lt(()=>f.clear(),null);else{const m=Ns();m&&typeof m.query=="function"&&Lt(()=>m.query({query:""}),null)}}Vn={...Km,available:ah(),reason:void 0},Vn.available||(Vn.reason=ut.searchUnavailable),ts()},search:(f,m)=>{const b=Da(),I=!!m?.caseSensitive,E=m?.includeDeletedText===!0,z=m?.regex===!0,K=++to;if(!b||typeof b.setSession!="function"){const oe=Ns();if(oe&&typeof oe.query=="function"&&typeof oe.getState=="function"){si({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),Pc=()=>{oe.query({query:""})};const me=Lt(()=>oe.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);return Cr(me)?Promise.resolve(me).then(Re=>{K===to&&Eo(Re,Io())},()=>{K===to&&si({available:!1,reason:ut.searchUnavailable})}):Eo(me,Io()),Eo(Lt(()=>oe.getState(),null),Io()),Vn}return si({query:f,total:0,activeIndex:-1,available:!1,caseSensitive:I,includeDeletedText:E,regex:z,reason:ut.searchUnavailable})}if(si({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),Pc=()=>{typeof b.clear=="function"&&b.clear()},Eo(Lt(()=>b.setSession(f,{caseSensitive:I,includeDeletedText:E,...z?{regex:!0}:{},highlight:!0}),null)),f.length>0&&Vn.total===0&&Vn.reason!==ut.searchInvalidPattern){const oe=Ns();if(oe&&typeof oe.query=="function"&&typeof oe.getState=="function"){const me=Pc;Pc=()=>{me?.(),oe.query({query:""})};const Re=Lt(()=>oe.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);Cr(Re)?Promise.resolve(Re).then(Ue=>{K===to&&Eo(Ue,Io())},()=>{K===to&&si({available:!1,reason:ut.searchUnavailable})}):Eo(Re,Io()),Eo(Lt(()=>oe.getState(),null),Io())}}return Vn},next:()=>{const f=Da();if(!f||typeof f.next!="function"){const m=Ns();if(!m||typeof m.next!="function"||typeof m.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(Vn.total===0)return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.next(),null);if(Cr(b)){const I=to;Promise.resolve(b).then(E=>{I===to&&Eo(E,Io())}).catch(()=>{I===to&&si({available:!1,reason:ut.searchUnavailable})})}else Eo(b,Io());return Eo(Lt(()=>m.getState(),null),Io()),{ok:!0}}return Vn.total===0?{ok:!1,reason:ut.operationUnavailable}:(Eo(Lt(()=>f.next(),null)),{ok:!0})},previous:()=>{const f=Da();if(!f||typeof f.previous!="function"){const m=Ns();if(!m||typeof m.previous!="function"||typeof m.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(Vn.total===0)return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.previous(),null);if(Cr(b)){const I=to;Promise.resolve(b).then(E=>{I===to&&Eo(E,Io())}).catch(()=>{I===to&&si({available:!1,reason:ut.searchUnavailable})})}else Eo(b,Io());return Eo(Lt(()=>m.getState(),null),Io()),{ok:!0}}return Vn.total===0?{ok:!1,reason:ut.operationUnavailable}:(Eo(Lt(()=>f.previous(),null)),{ok:!0})},clear:()=>{to+=1;const f=Da();if(f&&typeof f.clear=="function"&&Lt(()=>f.clear(),null),!f||typeof f.clear!="function"){const m=Ns();m&&typeof m.query=="function"&&Lt(()=>m.query({query:""}),null)}si({query:"",total:0,activeIndex:-1,canReplace:!1})},replace:f=>{const m=Da();if(!m){const I=Ns();if(!I||typeof I.replace!="function"||typeof I.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(!Io())return{ok:!1,reason:ut.operationUnavailable};const E=Lt(()=>I.replace({replacement:typeof f=="string"?f:""}),null);if(Cr(E)){const z=to;Oa(),ts();const K=()=>z===to;return Promise.resolve(E).then(oe=>(K()&&(Eo(oe,Io()),Oa(),ts()),id(oe)),()=>(K()&&si({available:!1,reason:ut.searchUnavailable}),{ok:!1,reason:ut.searchUnavailable}))}return Oa(),ts(),id(E)}if(typeof m.replaceCurrent!="function")return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.replaceCurrent(typeof f=="string"?f:""),null);return Oa(),ts(),id(b)},replaceAll:f=>{const m=Da();if(!m){const I=Ns();if(!I||typeof I.replaceAll!="function"||typeof I.getState!="function")return{ok:!1,reason:ut.searchUnavailable};if(!Io())return{ok:!1,reason:ut.operationUnavailable};const E=Lt(()=>I.replaceAll({replacement:typeof f=="string"?f:""}),null);if(Cr(E)){const z=to;Oa(),ts();const K=()=>z===to;return Promise.resolve(E).then(oe=>(K()&&(Eo(oe,Io()),Oa(),ts()),id(oe)),()=>(K()&&si({available:!1,reason:ut.searchUnavailable}),{ok:!1,reason:ut.searchUnavailable}))}return Oa(),ts(),id(E)}if(typeof m.replaceAll!="function")return{ok:!1,reason:ut.operationUnavailable};const b=Lt(()=>m.replaceAll(typeof f=="string"?f:""),null);return Oa(),ts(),id(b)}},JA=Ao(f=>f.styles),Xm=oi(JA),CU={get:Xm.get,getSnapshot:Xm.getSnapshot,subscribe:Xm.subscribe,observe:Xm.observe,getCatalog:f=>Me(f).value,getQuickGallery:()=>JA.get().quickGallery,getActiveParagraphStyle:()=>ct(dt.selection,ze().cache).style},$A={select:Fs,get state(){return dt},selection:HA,commands:$H,toolbar:eU,comments:tU,trackChanges:oU,contentControls:sU,fonts:aU,zoom:lU,document:cU,viewport:Wm,metadata:mU,tables:vU,search:wU,styles:CU,formatPainter:{setPointerSelecting(f){$||(h={...h,pointerSelecting:f})},notifyPointerUp(){$||(h={...h,pointerSelecting:!1},NA())},setKeyboardSelecting(f){$||(h={...h,keyboardSelecting:f})},notifyKeyUp(){$||(h={...h,keyboardSelecting:!1},NA())},cancel(){$||Lm()},onModeChange(f){return $?()=>{}:(p.add(f),()=>p.delete(f))}},createScope:()=>{const f=[];return{select:(m,b)=>{const I=Fs(m,b);return{get:I.get,subscribe:E=>{const z=I.subscribe(E);return f.push(z),z}}},dispose:()=>{for(const m of f.splice(0))m()}}},destroy:()=>{if(!$){$=!0,kV(In,bt),Br.reset(),Pe(),X&&(clearTimeout(X),X=null),te&&(clearTimeout(te),te=null,Y=0),U?.timer&&(clearTimeout(U.timer),U.timer=null),U=null,ve&&(clearTimeout(ve),ve=null),Co&&(clearTimeout(Co),Co=null),pr&&pr(),pr=null,co=null,ti.clear(),O.clear();for(const f of Tl.splice(0))f();xt&&xt(),xt=null,Bt=null,Zn&&Zn(),Zn=null,St=null,tr&&tr(),tr=null,xr=null,$r&&$r(),$r=null,No=null,dn&&dn(),dn=null,it=null;for(const f of od)Gm(f);od.clear(),Ye.clear(),qm.clear(),g+=1,p.clear(),to+=1,he.clear()}}};return S=$A,$A}var fH=[{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 hH(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 pH(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"?hH(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 mH(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 gH(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:fH;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 yH(e,t){return e.activeMark?t.activeMarks.includes(e.activeMark):!1}Mt();var bH=['[data-sdt-type="structuredContent"][data-sdt-id]','[data-sdt-type="structuredContent"][data-sdt-container-id]','[data-sdt-container-type="structuredContent"][data-sdt-container-id]'].join(", "),wH=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 CH(e,t){const n=new w6.default;return e.forEach((r,o)=>{n.file(t[o],r)}),n.generateAsync({type:"blob",compression:"DEFLATE"})}function Cb(e){return!!(e&&(e.synced===!0||e.isSynced===!0))}function MA(e){try{e.synced=!0}catch{}try{e.isSynced=!0}catch{}}function kH(e,t){if(!e)return()=>{};if(Cb(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=()=>{MA(e),s()},l=u=>{u!==!1&&(u===!0||Cb(e))&&(MA(e),s())};return n("synced",a),n("sync",l),Cb(e)&&s(),i}function SH(e,t){const n=e.composedPath();if(!n.includes(t))return null;const r=n.find(a=>a instanceof HTMLElement&&a.matches(bH));if(!r)return null;const o=n.some(a=>a instanceof HTMLElement&&a.classList.contains(ap.BLOCK_SDT_LABEL)),i=r.getAttribute("data-sdt-container-id")?.trim()||null,s=r.getAttribute("data-sdt-id")?.trim()||null;return o?i??s:s??i}function _H(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function AH(e){if(!e||typeof e.id!="string"||e.kind!=="inline"&&e.kind!=="block"||typeof e.controlType!="string")return null;const t=e.properties?.tag,n=e.properties?.alias;return{id:e.id,controlType:e.controlType,scope:e.kind,...typeof t=="string"&&t?{tag:t}:{},...typeof n=="string"&&n?{alias:n}:{}}}function $o(e){return!!(e&&typeof e=="object"&&e.editorVersion===2)}function IH(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 LA(e){return typeof e=="string"&&e.length>0?e:null}function kb(e){return e?$o(e)?LA(e.documentId??e.options?.documentId??null):LA(typeof e.getDocumentId=="function"?e.getDocumentId():e.options?.documentId):null}function EH(e){if(!e||$o(e))return null;const t=e;return t.documentRenderer??t.presentationEditor??null}function Yi(e){if(!e)return null;if($o(e))return e.fonts??null;const t=EH(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 Am=class extends Qm.default{static{this.allowedTypes=[Fr,ql,rp]}#t=!1;#n=!1;#e=null;#r=null;#i=null;#s=null;#d=null;#h=null;#f=e=>{this.#k(e)};#c=null;#p=W4({});get uiConfig(){return this.#p}#o=K4({});get interactionConfig(){return this.#o}#l=Y4({});get surfacesConfig(){return this.#l}#g;#u=new yN;#y=null;#w=!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:{...eb},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.#g=new sN({getModuleConfig:()=>this.#l}),this.#h=t,t.addEventListener("click",this.#f,!0),this.#I(e,t)}async#k(e){const t=this.#h;if(!t)return;const n=SH(e,t),r=this.activeEditor?.doc?.contentControls?.list;if(!(!n||typeof r!="function"))try{const o=await r();if(this.#t)return;const i=AH(_H(o).find(s=>s.id===n));i&&this.emit("content-control:click",{target:i,source:"pointer"})}catch{return}}async#I(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),hN(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.#we(),this.config.user=pN(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=zk(this.config.modules.comments),this.#p=W4(this.config),this.#o=K4(this.config),this.#l=Y4(this.config),this.config.disableContextMenu=!this.#p.contextMenu.enabled,this.config.rulers=this.#p.ruler.enabled,this.#p.comments.enabled?this.config.modules.comments===!1&&(this.config.modules.comments={}):this.config.modules.comments=!1,this.#p.comments.enabled){this.config.modules.comments===!0&&(this.config.modules.comments={});const i=this.config.modules.comments;i&&Object.assign(i,this.#o.comments)}if(this.config.colors=T6(this.config.colors),this.userColorMap=new Map,this.colorIndex=0,this.version="2.4.0-next.8",this.#C("🦋 [superdoc] Using SuperDoc version:",this.version),this.superdocId=e.superdocId||ns(),this.colors=this.config.colors??[],this.#P(),await D8(),this.#t)return;if(await this.#b(this.config.modules),this.#t){this.#de();return}this.config.cspNonce&&this.#L(),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.#y||(this.#y=this.#u.subscribe(i=>{this.#ke(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.#d=o,this.#S(),this.#M(),this.#Se(),this.#E()}#E(){if(this.#T(),this.readyEditors=0,!this.app)throw new Error("SuperDoc: #startRuntime called before #initVueApp populated this.app");this.app.mount(this.#d)}#M(){const e=this.config.modules?.whiteboard,t=e!==!1&&(e?.enabled??!1);this.whiteboard=new PD({Renderer:rN,superdoc:this,enabled:t}),this.emit("whiteboard:init",{whiteboard:this.whiteboard})}get requiredNumberOfEditors(){return this.#m("requiredNumberOfEditors").documents.filter(e=>e.type===Fr).length}get ui(){return this.#c||(this.#c=dH({superdoc:this}),this.#t&&this.#c.destroy()),this.#c}get state(){return{documents:this.#m("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}#L(){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}}#P(){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=$d(this.config.document);this.config.documents=[{id:ns(),...s}]}else if(n)this.config.documents=[{id:ns(),type:Fr,url:this.config.document,name:"document.docx"}];else if(r){const s=$d(this.config.document);this.config.documents=[{id:ns(),...s}]}else if(o){const s=$d(this.config.document);this.config.documents=[{id:ns(),...s}]}Array.isArray(this.config.documents)&&this.config.documents.length>0&&(this.config.documents=this.config.documents.map(s=>{const a=$d(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||ns()}}))}#T(){const{app:e,pinia:t,superdocStore:n,commentsStore:r,highContrastModeStore:o}=CD({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.#g),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&&b8(this),this.#ue()}#a(e,t){t&&this.on(e,t)}#S(){this.#a("editorBeforeCreate",this.config.onEditorBeforeCreate),this.#a("editorCreate",this.config.onEditorCreate),this.#a("editorDestroy",this.config.onEditorDestroy),this.#a("source:complete",this.config.onSourceComplete),this.#a("source:signals-complete",this.config.onSourceSignalsComplete),this.#a("ready",this.config.onReady),this.#a("comments-update",this.config.onCommentsUpdate),this.#a("content-control:active-change",this.config.onContentControlActiveChange),this.#a("content-control:click",this.config.onContentControlClick),this.#a("awareness-update",this.config.onAwarenessUpdate),this.#a("locked",this.config.onLocked),this.#a("pdf:document-ready",this.config.onPdfDocumentReady),this.#a("sidebar-toggle",this.config.onSidebarToggle),this.#a("collaboration-ready",this.config.onCollaborationReady),this.on("collaboration-ready",e=>this.#j(e?.editor??null)),this.#a("editor-update",this.config.onEditorUpdate),this.on("content-error",this.onContentError),this.#a("exception",this.config.onException),this.#a("list-definitions-change",this.config.onListDefinitionsChange),this.#a("pagination-update",this.config.onPaginationUpdate),this.#a("fonts-resolved",this.config.onFontsResolved),this.#a("fonts-changed",this.config.onFontsChanged),this.#a("zoomChange",this.config.onZoomChange),this.#a("viewport-change",this.config.onViewportChange)}async#b({collaboration:e}={}){return e?(this.isCollaborative=!1,this.config.documents.length===0&&(this.config.documents=[{id:ns(),type:Fr,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}#J(e,t){this.isCollaborative=!0,this._commentsCollabInitialized=!1,this.ydoc=Xr(e),this.provider=Xr(t),this.#_();const n=this.config;this._cleanupAwareness=p8(t,this,n.user),n.documents.forEach(r=>{r.ydoc=e,r.provider=t,r.role=this.config.role})}#U(){this.#s=null,this.#A(),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})}#A(){if(this.#r){try{this.#r()}catch{}this.#r=null}if(this.#i){try{this.#i()}catch{}this.#i=null}}#j(e){this.#A(),$o(e)&&(this.#D(e),this.#x(e))}#D(e){const t=e.presence;if(!t||typeof t.subscribe!="function")return;const n=xD(()=>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.#r=t.subscribe(r)}catch(o){console.warn("[SuperDoc] v2 awareness bridge failed to subscribe",o)}}#x(e){const t=e.lock;if(!t||typeof t.subscribe!="function")return;const n=r=>{this.#t||this.#v(!!r.isLocked,this.#O(r.lockedBy??null))};try{if(this.#s&&typeof t.setLocked=="function"){const o=this.#s;t.setLocked(o.isLocked,o.isLocked?o.lockedBy:null),this.#s=null}const r=t.getSnapshot?.();r&&n(r),this.#i=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}}#G(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}#v(e,t){this.isLocked===e&&this.#G(this.lockedBy,t)||(this.isLocked=e,this.lockedBy=t,this.#C("🦋 [superdoc] Locking superdoc:",e,t,`
|
|
103
103
|
|
|
104
104
|
|
|
105
105
|
`),this.emit("locked",{isLocked:e,lockedBy:t}))}#_(){const e=this.config.user;if(!e||e.color)return;const t=this.colors.length>0?this.colors:wH,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.#ge(e);this.#n=!0;try{const r=await this.#pe(),o=this.#W(),i=this.#F();this.#K();let s=null;try{this.#s=i,s=this.#me(n);const a=this.#fe(t,r);await s,this.#he(a,t),this.#s=null}catch(a){if(s&&this.#e){const l=this.#e;this.#e=null,l(),await s.catch(()=>{})}throw this.#N(o),a}}finally{this.#e=null,this.#n=!1}}#F(){return{isLocked:this.isLocked,lockedBy:this.lockedBy?{...this.lockedBy}:null}}#W(){const e=this.config.documents.find(r=>r.type===Fr),t=this.superdocStore?.documents.find(r=>r.id===e.id)??null,n=t?wn(t):null;return{isCollaborative:this.isCollaborative,configV2Collaboration:e.v2Collaboration??null,configData:e.data,storeDoc:t,storeV2Collaboration:this.#Y(n),storeData:t?.data}}#N(e){this.#s=null;const t=this.config.documents.find(n=>n.type===Fr);t.v2Collaboration=e.configV2Collaboration,t.data=e.configData,this.isCollaborative=e.isCollaborative,e.storeDoc&&(e.storeDoc.data=e.storeData,this.#B(e.storeDoc,e.storeV2Collaboration),this.#ee(e.storeDoc))}#K(){if(this.#t)throw new Error("SuperDoc: instance was destroyed during upgrade")}#m(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}#$(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.`)}#q(e,t){const n=this.superdocStore?.documents;if(Array.isArray(n))for(const r of n){const o=wn(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)}}#Y(e){if(!e)return null;const t=e.v2Collaboration;return t&&typeof t=="object"&&"value"in t?t.value:t??null}#B(e,t){const n=wn(e).v2Collaboration;if(n&&typeof n=="object"&&"value"in n){n.value=t;return}e.v2Collaboration=t}#ee(e){const t=wn(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}#te(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}:{}}}#fe(e,t){const n=this.config.documents.find(i=>i.type===Fr),r=this.#m("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.#te({...e,roomMode:"create"});return n.data=t,n.v2Collaboration=o,r.data=t,this.#B(r,o),this.isCollaborative=!0,this.readyEditors=0,this.#ee(r),{configDoc:n,storeDoc:r}}#he(e,t){const n=this.#te({...t,roomMode:"join"});e.configDoc.v2Collaboration=n,this.#B(e.storeDoc,n)}async#pe(){const e=this.activeEditor;if($o(e)&&typeof e.save=="function"){const r=await e.save();return this.#X(r)}const t=this.config.documents.find(r=>r.type===Fr),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.#X(n);throw new Error("SuperDoc: upgradeToCollaboration() requires a live v2 editor save or DOCX Blob source")}#X(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:Fr})}if(e instanceof ArrayBuffer)return new Blob([e],{type:Fr});throw new Error("SuperDoc: active v2 editor returned an unsupported DOCX save payload")}#ne(e,t){const n=kb(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.#X(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.#B(s,i))}#Ee(){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}#Te(){this.#U(),this.#q(null,null)}#xe(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))})}#me(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;$o(u)&&kb(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"))}})}#Re(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")))}})}#ge(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===Fr);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(!$o(this.#ye()))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=e_({v2Collaboration:e.v2Collaboration??this.#ve(r.v2Collaboration)??i?.v2Collaboration??i?.v2??null,legacyCollaboration:s,documentType:Fr,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}}#ve(e){return e&&typeof e=="object"&&"value"in e?e.value:e}#ye(){const e=this.config.documents.find(n=>n.type===Fr),t=this.#m("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=tu({actor:e});t&&this.users.some(n=>tu({actor:n})===t)||this.users.push(e)}removeSharedUser(e){this.#R("removeSharedUser");const t=typeof e=="string"?Jv(e):"",n=typeof e=="string"?`email:${t}`:tu({actor:e});this.users=this.users.filter(r=>{const o=tu({actor:r});return n?o!==n:t?Jv(r.email)!==t:!0})}onContentError({error:e,editor:t}){const n=t.options?.documentId,r=this.#m("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:F4(e)})}broadcastEditorCreate(e){this.readyEditors++,this.broadcastReady(),this.#be(e),this.emit("editorCreate",{editor:F4(e)})}broadcastSourceComplete(){this.emit("source:complete")}broadcastSourceSignalsComplete(){this.emit("source:signals-complete")}#re=new WeakSet;#be(e){if(!e||typeof e.on!="function"||this.#re.has(e))return;this.#re.add(e),e.on("fonts-changed",n=>{this.#oe(e)&&this.#z(n)});const t=(e.documentRenderer??e.presentationEditor)?.getLastFontsChangedPayload?.();t&&this.#oe(e)&&this.#z(t)}#oe(e){return!this.activeEditor||e===this.activeEditor}#ie=null;#z(e){this.#ie=e,this.emit("fonts-changed",e)}broadcastEditorDestroy(){this.emit("editorDestroy")}broadcastSidebarToggle(e){this.emit("sidebar-toggle",e)}#we(){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.")}#C(...e){(console.debug?console.debug:console.log)("🦋 🦸♀️ [superdoc]",...e)}#Z=null;get fonts(){return this.#Z||(this.#Z={getReport:()=>Yi(this.activeEditor)?.getReport()??[],getMissingFonts:()=>Yi(this.activeEditor)?.getMissingFonts()??[],getDocumentFontOptions:()=>Yi(this.activeEditor)?.getDocumentFontOptions()??[],getFontFamilyOptions:()=>Yi(this.activeEditor)?.getFontFamilyOptions()??[],getDocumentFonts:()=>Yi(this.activeEditor)?.getDocumentFonts()??[],onReport:e=>{const t=this.activeEditor,n=t?Yi(t)?.getLastFontsChangedPayload?.()??null:this.#ie??null;return n&&e(n),this.on("fonts-changed",e),()=>this.off("fonts-changed",e)},map:e=>{const t=Yi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.map requires an active editor");t.map(e)},unmap:e=>{const t=Yi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.unmap requires an active editor");t.unmap(e)},add:e=>{const t=Yi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.add requires an active editor");t.add(e)},preload:e=>{const t=Yi(this.activeEditor);if(!t)throw new Error("superdoc.fonts.preload requires an active editor");return t.preload(e)}}),this.#Z}#V(){const e=this.activeEditor!==null;this.#se(),this.activeEditor=null,this.toolbar?.setActiveEditor?this.toolbar.setActiveEditor(null):this.toolbar&&(this.toolbar.activeEditor=null),e&&this.emit("active-editor-change")}#H=null;#se(){if(this.#H){try{this.#H()}catch{}this.#H=null}}#Ce(e){this.#se();const t=Yi(e);if(!t?.onChanged)return;const n=t.getLastFontsChangedPayload?.();n&&this.#z(n),this.#H=t.onChanged(r=>this.#z(r))}#ke(e,t){this.#w=!0;try{if(e===null){this.#V();return}this.#u.get(e)?.kind==="v2"&&$o(t)?this.#ae(t):this.#V()}finally{this.#w=!1}}#ae(e){if($o(e)){!this.#w&&this.#u.getActive()&&this.#u.setActive(null,"set-active-v2-facade");const t=this.activeEditor;this.activeEditor=e,this.#Ce(e),this.toolbar?.setActiveEditor?.(e),t!==this.activeEditor&&this.emit("active-editor-change");return}this.#V()}setActiveEditor(e){this.#ae(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:"supported",reason:"SD-4039/SD-4040: the shipped v2 command posture exposes all-story Accept All and Reject All through the canonical doc.trackChanges.decide({ target: { kind: 'all' } }) mutation"},{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.#u.register(e)}unregisterEditorRuntime(e){return this.#u.unregister(e)}getActiveRuntime(){return this.#u.getActive()}setActiveRuntime(e,t){this.#u.setActive(e,t)}resolveRuntimeFromEventTarget(e){return this.#u.resolveFromEventTarget(e)}activateRuntimeFromEventTarget(e,t){const n=this.#u.resolveFromEventTarget(e);return n?(this.#u.setActive(n.id,t),!0):!1}toggleRuler(){const e=this.#m("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})}#Se(){const e=this.config.modules?.toolbar,t=e&&typeof e=="object"?e:{},n=this.#p.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=lV({...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 e9(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.#p.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.#ue();const t={viewing:()=>this.#ce(),editing:()=>this.#_e(),suggesting:()=>this.#le()};t[e]&&(t[e](),this.emit("document-mode-change",{documentMode:e}))}#Q(e,t){const n=typeof e.id=="string"&&e.id.length>0?e.id:null;if(n){const i=this.#u.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)})}#_e(){if(this.config.role!=="editor")return this.#le();const e=this.#m("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.#Q(t,"editing")})}#le(){if(!["editor","suggester"].includes(this.config.role??""))return this.#ce();const e=this.#m("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.#Q(t,"suggesting")})}#ce(){const e=this.#m("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.#Q(r,"viewing")})}#ue(){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=Pk(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($o(t)&&typeof t.lock?.setLocked=="function"){t.lock.setLocked(e,e?{...this.user}:null);const n=t.lock.getSnapshot?.();n&&this.#v(!!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.#v(e,e?this.user:null)}getHTML(e={}){const t=[];return this.#m("getHTML").documents.forEach(n=>{const r=n.getEditor?.();r&&t.push(r)}),t.map(n=>n.getHTML(e))}lockSuperdoc(e=!1,t=null){this.#v(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=S_(n||this.config.title),u=await this.exportEditorsToDOCX({commentsType:t,isFinalDoc:i,fieldsHighlightColor:a}),c=[...r],d=[...o];if(e.includes("docx")&&u.forEach(g=>{c.push(g),d.push(`${l}.docx`)}),c.length===1)return s?k_(c[0],l,e[0]):c[0];const h=await CH(c,d);return s?k_(h,l,"zip"):h}async replaceFile(e){const t=this.activeEditor;if($o(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.#ne(t,e),this.emit("document-replaced",{editor:t,host:t?.host})),r}const n=t&&!$o(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.#ne(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.#m("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 g=d.editorVersion===2;try{const p=await d.exportDocx(g?{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}),g&&(e==="clean"||IH(p)))throw p}return h()});return(await Promise.all(u)).filter(c=>c!=null)}finally{this.off("exception",l)}}async#Ae(){this.#C("🦋 [superdoc] Triggering collaboration saves");const e=this.#m("save");return new Promise(t=>{e.documents.forEach((n,r)=>{if(this.#C(`Before reset - Doc ${r}: pending = ${this.pendingCollaborationSaves}`),this.pendingCollaborationSaves=0,n.ydoc){this.pendingCollaborationSaves++,this.#C(`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.#C(`FINAL pending = ${this.pendingCollaborationSaves}, but we have ${e.documents.filter(n=>n.ydoc).length} docs!`)})}async save(){const e=[this.#Ae()];this.#C("🦋 [superdoc] Saving superdoc"),await Promise.all(e),this.#C("🦋 [superdoc] Save complete")}#Ie(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?.()}#de(){this.#s=null,this.#A(),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.#g.open(e)}closeSurface(e){this.#g.close(e)}async removeDocument(e){const t=typeof e=="string"?e:String(e??"");if(!t)return!1;const n=this.#m("removeDocument"),r=this.activeEditor,o=kb(r);for(const s of this.#u.getAllByDocumentId(t))this.#u.unregister(s.id);o===t&&r!==null&&this.#V();const i=n.removeDocument(t);return i?(this.#Ie(i,n.documents),await It(),!0):!1}destroy(){this.#t=!0,this.#h?.removeEventListener("click",this.#f,!0),this.#h=null,this.#e&&(this.#e(),this.#e=null),this.#g&&this.#g.destroy(),this.toolbar?.destroy?.(),this.app&&(this.#C("[superdoc] Unmounting app"),this.superdocStore?.reset(),this.app.unmount(),this.removeAllListeners(),delete this.app.config.globalProperties.$config,delete this.app.config.globalProperties.$superdoc),this.#c?.destroy(),this.#de(),this.#y?.(),this.#y=null,this.#u.clear(),this.#d&&(this.#d.remove(),this.#d=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?$o(this.activeEditor)?this.activeEditor.focus?.(e):this.activeEditor.focus?.():this.#m("focus").documents.find(n=>{const r=n.getEditor?.();return r?($o(r)?r.focus?.(e):r.focus?.(),!0):!1})}setHighContrastMode(e){this.activeEditor&&(this.activeEditor.setHighContrastMode?.(e),this.highContrastModeStore?.setHighContrastMode(e))}};Mt();const PA="__SUPERDOC_V2_BROWSER_RUNTIME__";function TH(e=globalThis){const t=e[PA];return t&&typeof t=="object"?t:null}function xH(e={},t=globalThis){const n=TH(t)??{},r={...n,...e,vue:e.vue??n.vue??v6};return t[PA]=r,r}xH();var RH={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"},MH=0;function DA(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-${++MH}`}`,l=[];if(i)for(const[u,c]of Object.entries(i)){if(c==null)continue;const d=RH[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 LH(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 PH(e){const{className:t,css:n}=DA(e);return LH(t,n),t}function DH(e){return DA(e)}function OH(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 FH=ad({BlankDOCX:()=>hk,DOCX:()=>Fr,HTML:()=>rp,PDF:()=>ql,SuperDoc:()=>Am,buildTheme:()=>DH,compareVersions:()=>A6,createTheme:()=>PH,defineSuperDocExtension:()=>OH,getFileObject:()=>$v},1),NH="SUPERDOC_ENGINE_CDN_BASE_URL",OA=Symbol.for("superdoc.docx-engine.cdn-load-state"),Im="superdocDocxEngineStatus";function BH(e,t,n=null){const r=e?.[NH],o=typeof r=="string"&&r.trim()?r:n;if(typeof o=="string"&&o.trim())return zH(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 zH(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 VH({engineVersion:e,buildBaseUrl:t}){L8(()=>{const n=BH(globalThis,e,t),r=globalThis[OA],o=r instanceof Map?r:new Map;if(globalThis[OA]=o,!o.has(n)){const i=Promise.all([import(`${n}/dist-cdn/docx-engine.es.js`),HH(`${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 HH(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=(g,p)=>{a||(a=!0,l?.disconnect(),s.dataset[Im]=g,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))})}VH({engineVersion:"0.3.0-next.
|
|
108
|
+
}`:""}}function LH(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 PH(e){const{className:t,css:n}=DA(e);return LH(t,n),t}function DH(e){return DA(e)}function OH(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 FH=ad({BlankDOCX:()=>hk,DOCX:()=>Fr,HTML:()=>rp,PDF:()=>ql,SuperDoc:()=>Am,buildTheme:()=>DH,compareVersions:()=>A6,createTheme:()=>PH,defineSuperDocExtension:()=>OH,getFileObject:()=>$v},1),NH="SUPERDOC_ENGINE_CDN_BASE_URL",OA=Symbol.for("superdoc.docx-engine.cdn-load-state"),Im="superdocDocxEngineStatus";function BH(e,t,n=null){const r=e?.[NH],o=typeof r=="string"&&r.trim()?r:n;if(typeof o=="string"&&o.trim())return zH(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 zH(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 VH({engineVersion:e,buildBaseUrl:t}){L8(()=>{const n=BH(globalThis,e,t),r=globalThis[OA],o=r instanceof Map?r:new Map;if(globalThis[OA]=o,!o.has(n)){const i=Promise.all([import(`${n}/dist-cdn/docx-engine.es.js`),HH(`${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 HH(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=(g,p)=>{a||(a=!0,l?.disconnect(),s.dataset[Im]=g,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))})}VH({engineVersion:"0.3.0-next.7",buildBaseUrl:null});for(const[e,t]of Object.entries(FH))e==="SuperDoc"||e==="default"||Object.prototype.hasOwnProperty.call(Am,e)||(Am[e]=t);var UH=Am;return UH})();
|