superdoc 2.4.0-next.20 → 2.4.0-next.21

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.
@@ -11,7 +11,7 @@ ${n.toString()}`)},hT=class{constructor(e){this.patterns=[],this.$state=e}if(e,t
11
11
 
12
12
  `).replace(/^\n+/,"").replace(/\n+$/,"")},da=sC("comments",()=>{const e={kind:"story",storyType:"body"},t=k=>{if(!k?.trackedChange)return!1;const M=k?.trackedChangeStory?.storyType;return M==null||M==="body"?!0:k?.trackedChangeAnchorKey?.startsWith?.("tc::body::")===!0},n=k=>k==null?null:t0({storyKey:"body",rawId:String(k)}),r=k=>{const M=It(k);if(!M?.startsWith("tc::"))return null;const Y=M.indexOf("::",4);if(Y<=4)return null;const ne=M.slice(4,Y),ie=M.slice(Y+2);return!ne||!ie?null:{storyKey:ne,rawId:ie}},o=(k,M)=>M==null?null:t0({storyKey:k||"body",rawId:String(M)}),i=k=>{if(!k)return null;const M=k.sourceId?String(k.sourceId):"";return M?`word:structural:${M}`:k.id?String(k.id):null},s=su(),a=Jr({name:"comments",readOnly:!1,allowResolve:!0,showResolved:!1}),l=()=>({ok:!1,reason:"read-only-document"}),c=()=>({ok:!1,reason:"resolve-disabled"}),u=()=>a.allowResolve===!1,d=()=>a.readOnly===!0,h=Jr({documentMode:"editing",commentsVisible:!1,trackChangesVisible:!1}),g=!1,p={},v=new WeakMap,S=new Map;let C=0;const A=()=>typeof window>"u"?!1:"__labsSuperDocV2PreviewDebug"in window,y=(k,M=null)=>{if(A()){if(M!==null){console.debug("[SuperDoc][comments-store]",k,M);return}console.debug("[SuperDoc][comments-store]",k)}},w=ep,x=re(!1),L=re(!1),V=re(null),G=re(!1),R=re(null),F=re(null),Z=re(null),O=re([]),N=re([]),T=new Set([]),B=re(!0),Q=re(""),q=re([]);let se=new Map;const he=Ee(()=>{const k=L8(q.value,se);return se=k,k}),Ne=k=>{const M=k?.commentId??null;return(M!=null?he.value.get(M):null)??[k].filter(Boolean)};let pe=new Map;const ye=Ee(()=>{const k=P8(q.value,pe);return pe=k,k}),me=re(!1),_e=re([]),oe=re({}),Me=re(!1),Ge=re(0),lt=re([]),Ct=re([]),Re=re(!1),Ke=re(!1),tt=re([]),ee=re(null),_=re(null),te=re(null),D=re(null),U=to(null),$=Ee(()=>h.documentMode==="viewing"),H=Ee(()=>$.value?h.commentsVisible||h.trackChangesVisible:!0),J=to(null),X=new WeakMap,W=k=>X.get(k)??0,we=k=>{if(!k||typeof k!="object"&&typeof k!="function")return 0;const M=W(k)+1;return X.set(k,M),M},ge=k=>{J.value=k??null,k&&!X.has(k)&&X.set(k,0)},be=k=>{const M=k?.activeEditor?.v2Comments??null;return M||J.value},Be=k=>k?.activeEditor?.editorVersion===2||J.value!==null,Ze=to(null),it=new WeakMap,yt=k=>it.get(k)??0,Xt=k=>{if(!k||typeof k!="object"&&typeof k!="function")return 0;const M=yt(k)+1;return it.set(k,M),M},xt=k=>{Ze.value=k??null,k&&!it.has(k)&&it.set(k,0)},Ft=k=>{const M=k?.activeEditor?.v2TrackedChanges??null;return M||Ze.value},Ut=({commentsAdapter:k,trackedChangesAdapter:M}={})=>({commentsGeneration:we(k??J.value),trackedChangesGeneration:Xt(M??Ze.value)}),mn=(k={})=>{const M={...a,...k};Object.assign(a,M),B.value=a.suppressInternalExternal||!1,k.comments&&k.comments.length&&(q.value=k.comments?.map(Y=>ca(Y))||[])},It=k=>k==null?null:String(k),Zt=k=>Array.isArray(k)?[...new Set(k.map(M=>It(M)).filter(Boolean))]:[],rt=k=>It(k?.id??k?.changeId??k?.address?.entityId),zt=k=>Zt([rt(k),k?.changeId,k?.address?.entityId,k?.trackedChangeAnchorKey,k?.anchorKey,k?.address?.anchorKey,...Array.isArray(k?.trackedChangePositionAliases)?k.trackedChangePositionAliases:[],...Array.isArray(k?.sourceIds?.rsids)?k.sourceIds.rsids:[],k?.sourceIds?.wordIdDelete,k?.sourceIds?.wordIdInsert,...Array.isArray(k?.sourceIds?.wordIdOther)?k.sourceIds.wordIdOther:[]]),Lt=k=>new Set(zt(k).flatMap(M=>{const Y=r(M);return Y?.rawId?[M,Y.rawId]:[M]})),An=k=>{const M=new Set,Y=[];for(const ne of k){const ie=rt(ne);if(ie){if(M.has(ie))continue;M.add(ie)}Y.push(ne)}return Y},Qt=k=>{if(!k?.trackedChange)return null;const M=r(k.trackedChangeAnchorKey);if(M?.storyKey)return M.storyKey;const Y=k.trackedChangeStory;switch(Y?.storyType){case"body":return"body";case"headerFooterPart":return Y.refId?`hf:${Y.refId}`:null;case"footnote":return Y.noteId?`fn:${Y.noteId}`:null;case"endnote":return Y.noteId?`en:${Y.noteId}`:null;case"textbox":return Y.textboxId?`textbox:${Y.textboxId}`:null;default:return null}},wn=k=>k?.startsWith("hf:part:")?`hf:${k.slice(8)}`:k?.startsWith("headerFooterPart:")?`hf:${k.slice(17)}`:k,Wn=(k,M)=>{const Y=wn(k),ne=wn(M);return!Y||!ne||Y===ne},go=(k,M)=>{const Y=wn(Qt(M)),ne=wn(It(k?.storyKey));return Wn(Y,ne)},jn=k=>{const M=It(k);return M?M.startsWith("imported:")?M:`imported:${M}`:null},Xn=k=>{const M=It(k);if(!M)return{key:null,entry:null};const Y=oe.value||{};if(Y[M]!==void 0)return{key:M,entry:Y[M]};for(const[ne,ie]of Object.entries(Y)){const fe=It(ie?.key),le=It(ie?.threadId);if(fe===M||le===M)return{key:ne,entry:ie}}return{key:null,entry:null}},Ao=(k,M)=>{if(!k||!M)return!1;const Y=Math.max(Number(k.left),Number(M.left)),ne=Math.min(Number(k.right),Number(M.right)),ie=Math.max(Number(k.top),Number(M.top)),fe=Math.min(Number(k.bottom),Number(M.bottom));return[Y,ne,ie,fe].every(Number.isFinite)&&ne>Y&&fe>ie},Nr=(k,M)=>{if(!k||!M||k.kind!=="trackedChange"||M.kind!=="trackedChange"||k.storyKey&&M.storyKey&&k.storyKey!==M.storyKey)return!1;const Y=Number(k.pageIndex),ne=Number(M.pageIndex);if(Number.isFinite(Y)&&Number.isFinite(ne)&&Y!==ne)return!1;if(Ao(k.bounds,M.bounds))return!0;const ie=Number(k.start),fe=Number(k.end),le=Number(M.start),ce=Number(M.end);return[ie,fe,le,ce].every(Number.isFinite)&&ie===le&&fe===ce},rr=k=>{const{entry:M}=Xn(k);if(!M)return null;const Y=q.value.filter(ne=>ne?.trackedChange?ft(ne).some(ie=>{const{entry:fe}=Xn(ie);return Nr(M,fe)}):!1);return Y.length===1?Y[0]:null},Pn=k=>k==null?null:q.value.find(M=>M.commentId==k||M.importedId==k||M.trackedChangeAnchorKey==k||M?.trackedChange&&jn(M.importedId)==k)||rr(k),De=k=>k?.parentCommentId?Pn(k.parentCommentId):k,Oe=k=>k?.trackedChangeThreadParentId?k.trackedChangeThreadParentId:lu(k)&&k?.trackedChange===!0?null:Lp(k),qe=k=>{const M=Oe(k);return M?!!Pn(M)?.trackedChange:!1},wt=k=>{if(!k)return null;const M=oe.value||{};if(typeof k=="string"){if(M[k])return k;const le=Pn(k);if(!le)return k;const ce=le.commentId??null,Ce=le.importedId??null,Ae=le.trackedChange?jn(Ce):null,Ie=le.trackedChangeAnchorKey??null;return Ie&&M[Ie]?Ie:ce&&M[ce]?ce:Ce&&M[Ce]?Ce:Ae&&M[Ae]?Ae:Ie??ce??Ae??Ce??null}const Y=k.commentId??null,ne=k.importedId??null,ie=k.trackedChange?jn(ne):null,fe=k.trackedChangeAnchorKey??null;return fe&&M[fe]?fe:Y&&M[Y]?Y:ne&&M[ne]?ne:ie&&M[ie]?ie:fe??Y??ie??ne??null},ft=k=>{if(k==null)return[];const M=typeof k=="object"?null:k,Y=typeof k=="object"?k:Pn(k),ne=Y?.trackedChange?Zt(Y?.trackedChangePositionAliases):[],ie=wn(Qt(Y)),fe=new Set;return[M,wt(Y),Y?.trackedChangeAnchorKey,Y?.commentId,Y?.importedId,Y?.trackedChange?jn(Y?.importedId):null,...ne.flatMap(le=>[ie&&!le.startsWith("tc::")?t0({storyKey:ie,rawId:le}):null,le])].map(le=>It(le)).filter(le=>!le||fe.has(le)?!1:(fe.add(le),!0))},Pt=(k,M)=>{const Y=oe.value||{},ne=typeof k=="object"?k:Pn(k),ie=new Set;for(const fe of[M,...ft(k)].map(le=>It(le)).filter(Boolean)){if(ie.has(fe))continue;ie.add(fe);const le=Y[fe];if(le!==void 0&&go(le,ne))return{key:fe,entry:le}}return{key:null,entry:null}},_n=k=>{k&&((k.resolvedTime!=null||k.resolvedById!=null||k.resolvedByEmail!=null||k.resolvedByName!=null)&&v.set(k,{resolvedTime:k.resolvedTime??null,resolvedById:k.resolvedById??null,resolvedByEmail:k.resolvedByEmail??null,resolvedByName:k.resolvedByName??null,trackedChangeDecision:k.trackedChangeDecision??null}),k.resolvedTime=null,k.resolvedById=null,k.resolvedByEmail=null,k.resolvedByName=null,k.trackedChangeDecision=null)},an=k=>{if(!k)return!1;const M=v.get(k);return M?(k.resolvedTime=M.resolvedTime??Date.now(),k.resolvedById=M.resolvedById??null,k.resolvedByEmail=M.resolvedByEmail??null,k.resolvedByName=M.resolvedByName??null,k.trackedChangeDecision=M.trackedChangeDecision??null,!0):!1},Dn=k=>typeof k?.getValues=="function"?k.getValues():{...k},Io=k=>{const M=k?.selection?.source;return M==null?!0:M===iu},Eo=k=>!!k?.trackedChange||!!Oe(k),ki=({documentId:k,editor:M}={})=>{if(!M?.state||!q.value?.length)return 0;const Y=oe.value||{};if(!Object.keys(Y).length)return 0;const ne=Ye=>Ye.find(pt=>Y[pt]!==void 0)??null,ie=new Set,fe=new Map;if(q.value.forEach(Ye=>{if(!Ye?.trackedChange)return;if(k){const At=Ye?.fileId??null;if(At&&At!==k)return}const pt=ft(Ye),et=ne(pt);et&&(ie.add(et),fe.set(et,new Set(pt)))}),!ie.size)return 0;const le=new Set(ua.getTrackChanges(M.state).map(({mark:Ye})=>Ye?.attrs?.id).filter(Ye=>Ye!=null).map(Ye=>String(Ye))),ce=typeof uu=="function"?uu(M):null;let Ce=[];try{Ce=ce?.getAll?.()??[]}catch{}const Ae=new Set(Ce.map(Ye=>Ye?.anchorKey).filter(Ye=>typeof Ye=="string"&&Ye.length>0)),Ie=new Set(Array.from(ie).filter(Ye=>{const pt=fe.get(Ye)??new Set([Ye]);return Array.from(pt).some(et=>Ae.has(et))?!1:!Array.from(pt).some(et=>le.has(et))}));if(!Ie.size)return 0;const ze=new Set;Ie.forEach(Ye=>{(fe.get(Ye)??new Set([Ye])).forEach(pt=>ze.add(pt))});const We=new Set(Ie);q.value.forEach(Ye=>{const pt=ft(Ye),et=ne(pt);et&&[Oe(Ye),Ye?.threadingParentCommentId,Ye?.parentCommentId].map(At=>It(At)).filter(Boolean).some(At=>ze.has(At))&&We.add(et)});const ut={...Y};if(We.forEach(Ye=>{delete ut[Ye]}),oe.value=ut,R.value!==void 0&&R.value!==null){const Ye=Pn(R.value),pt=new Set(ft(Ye??R.value)),et=[Oe(Ye),Ye?.threadingParentCommentId,Ye?.parentCommentId].map(At=>It(At)).filter(Boolean);(Array.from(pt).some(At=>ze.has(At))||et.some(At=>ze.has(At)))&&Gr()}return We.size},cn=k=>{const M=k?.state?.doc;if(!M||typeof M.descendants!="function")return null;const Y=new Set,ne=new Set;return M.descendants(ie=>{ie.marks?.filter(ce=>ce?.type?.name==="commentMark").forEach(ce=>{[ce.attrs?.commentId,ce.attrs?.importedId].map(Ce=>It(Ce)).filter(Boolean).forEach(Ce=>Y.add(Ce))});const fe=ie.type?.name;if(fe!=="commentRangeStart"&&fe!=="commentRangeEnd")return;const le=It(ie.attrs?.["w:id"]);le&&ne.add(le)}),{liveMarkIds:Y,resolvedAnchorIds:ne}},On=()=>{const k=s.documents;if(!Array.isArray(k))return null;for(const M of k){const Y=typeof M?.getEditor=="function"?M.getEditor():null;if(Y?.state?.doc)return Y}return null},Fn=({editor:k}={})=>{if(J.value)return 0;const M=k??On(),Y=cn(M),ne=oe.value||{},ie=new Set(Object.keys(ne));if(!Y&&!ie.size)return 0;let fe=0;return q.value.forEach(le=>{if(!Io(le)||Eo(le))return;if(Y){const Ce=ft(le),Ae=Ce.some(ze=>Y.liveMarkIds.has(ze)),Ie=Ce.some(ze=>Y.resolvedAnchorIds.has(ze));if(Ae&&le.resolvedTime!=null){_n(le),fe+=1;return}!Ae&&Ie&&le.resolvedTime==null&&an(le)&&(fe+=1);return}const{key:ce}=Pt(le);ce&&ie.has(String(ce))&&le.resolvedTime!=null&&(_n(le),fe+=1)}),fe};Vt(oe,()=>{Fn()}),Vt(q,()=>{Ku(),Fn()},{deep:!1});const lr=k=>{if(!k)return null;const M=k.start??k.pos??k.from,Y=k.end??k.to??M;return!Number.isFinite(M)||!Number.isFinite(Y)?null:{start:M,end:Y}},Jt=k=>Pt(k).entry??null,Un=(k,M={})=>{const Y=typeof k=="object"?k:Pn(k);if(!Y)return null;const ne=Pt(k).entry??null,ie=lr(ne);if(!ie)return null;const fe=s.getDocument(Y.fileId)?.getEditor?.()?.state?.doc;if(!fe?.textBetween)return null;const le=M.separator??" ",ce=fe.textBetween(ie.start,ie.end,le,le);return M.trim===!1?ce:ce?.trim()},ro=(k,M={})=>{const Y=Jt(k);return Y?{position:Y,anchoredText:Un(k,M)}:null},Pi=k=>{if(!$.value)return!0;const M=De(k);return!M&&k?.parentCommentId?!1:M?.trackedChange||Oe(k)?h.trackChangesVisible:h.commentsVisible},pl=(k,M)=>{const Y=k?.activeEditor,ne=be(k);if(M==null){if(Gr(),ne){ne.setActiveComment(null);return}Y?.commands?.setActiveComment({commentId:null});return}const ie=Pn(M);if(ie){if(R.value=ie.commentId,Ra(ie.commentId),ne){ne.setActiveComment(ie.commentId);return}Y?.commands?.setActiveComment({commentId:R.value})}},To=({superdoc:k,params:M,broadcastChanges:Y=!0,documentState:ne=void 0,trackedChangeIdentityIndex:ie=null})=>{const fe=Jy("store.trackedChanges.handleUpdate","store-reconciliation",{event:M?.event??null,changeId:M?.changeId??null,documentId:M?.documentId??null});try{const{event:le,changeId:ce,trackedChangeText:Ce,trackedChangeType:Ae,trackedChangeDisplayType:Ie,semanticColorKey:ze,semanticColor:We,deletedText:ut,trackedChangeLabel:Ye,trackedChangeDetailLines:pt,trackedChangeImagePreview:et,authorId:At,authorEmail:Gt,authorImage:kt,date:cr,author:In,importedAuthor:jt,documentId:en,coords:Xr,trackedChangeStory:Rr,trackedChangeStoryKind:Zr,trackedChangeStoryLabel:Wr,trackedChangeAnchorKey:ct,trackedChangeCanonicalId:un,trackedChangePositionAliases:yo,importedId:Yo}=M,Xo=ce!=null?String(ce):null,Os=un!=null?String(un):null,Ma=Object.prototype.hasOwnProperty.call(M,"trackedChangePositionAliases"),di=Ma?Zt(yo):void 0,Zo=Object.prototype.hasOwnProperty.call(M,"importedId"),Qo=Zo?Yo!=null?String(Yo):null:void 0,Fs=en!=null?String(en):null;if(!(Ie==="tableInsert"||Ie==="tableDelete")&&Xo){const Rt=Fs??(k?.activeEditor?.options?.documentId!=null?String(k.activeEditor.options.documentId):null),kn=Rt?s.getDocument(Rt)?.getEditor?.():null,ur=ne!==void 0?ne:kn?.state??k?.activeEditor?.state??null;if(ur){const{ranges:En,ids:Ir}=gc(ur),$o=ua.getTrackChanges(ur,Xo),Ns=En.length>0&&$o.length>0&&Xf($o,En),Bs=$o.length===0&&Ir.has(Xo);if(Ns||Bs){ac({suppressedIds:new Set([Xo]),activeDocumentId:Rt,superdoc:k,broadcastChanges:Y});return}}}const Sl=Rr!==void 0||Zr!==void 0||Wr!==void 0||ct!==void 0,La=Sl?Rr??null:e,ht=Sl?Zr??null:"body",P=Sl&&Wr!==void 0?Wr:"",j=ct!==void 0?ct??null:Sl?null:n(Xo),Se=typeof Ye=="string"&&Ye.length>0?Ye:null,Pe=H8(pt),mt=G8(et),nn=Br({documentId:en,commentId:ce,trackedChange:!0,trackedChangeText:Ce,trackedChangeType:Ae,trackedChangeDisplayType:Ie,semanticColorKey:ze,semanticColor:We,deletedText:ut,trackedChangeLabel:Se,trackedChangeDetailLines:Pe,trackedChangeImagePreview:mt,createdTime:cr,creatorId:At??null,creatorName:In,creatorEmail:Gt,creatorImage:kt,isInternal:!1,importedAuthor:jt,...Zo?{importedId:Qo}:{},trackedChangeStory:La,trackedChangeStoryKind:ht,trackedChangeStoryLabel:P,trackedChangeAnchorKey:j,trackedChangeCanonicalId:Os,...Ma?{trackedChangePositionAliases:di}:{},selection:{source:iu,selectionBounds:Xr}}),Cn=()=>{const Rt=j!=null?String(j):null;if(!Xo)return null;const kn=Qt(nn),ur=En=>{if(!En)return!1;const Ir=En.trackedChangeAnchorKey!=null?String(En.trackedChangeAnchorKey):null,$o=En.commentId!=null?String(En.commentId):null,Ns=En.importedId!=null?String(En.importedId):null,Bs=En.trackedChangeCanonicalId!=null?String(En.trackedChangeCanonicalId):null,yc=ft(En),Yu=Wn(Qt(En),kn);if(Yu&&yc.includes(Xo))return!0;const Xu=new Set(di??[]);if(Yu&&Xu.size>0&&[$o,Ns,Bs,Ir,...yc].filter(Boolean).some(Ln=>Xu.has(Ln)))return!0;const _l=Os&&Os!==Xo||Bs&&Bs!==$o;return $o===Xo||!_l&&(Ns===Xo||Qo!==void 0&&Qo!=null&&Ns===Qo)?!0:_l?!1:Rt&&Ir?Ir===Rt:!1};if(ie){const En=ie.candidates({changeId:Xo,importedId:Qo,anchorKey:Rt,canonicalId:Os,positionAliases:di});for(const Ir of En)if(ur(Ir)&&(!Fs||so(Ir,Fs)))return Ir;return null}return Fs?q.value.find(En=>ur(En)&&so(En,Fs)):q.value.find(ur)},Zn=Rt=>{Y&&(Ul(k,Rt),Nn(ce,Rt,k))},Mn=(Rt,kn,ur)=>Rt?.[kn]==null&&ur==null||!Rt||uk(Rt[kn],ur)?!1:(Rt[kn]=ur,!0),gn=Rt=>{if(!Rt)return!1;let kn=!1;return La!=null&&(kn=Mn(Rt,"trackedChangeStory",La)||kn),ht!=null&&(kn=Mn(Rt,"trackedChangeStoryKind",ht)||kn),P!==void 0&&P!==""&&(kn=Mn(Rt,"trackedChangeStoryLabel",P)||kn),j!=null&&(kn=Mn(Rt,"trackedChangeAnchorKey",j)||kn),kn},ln=Rt=>{const kn={trackedChangeText:Ce??null,trackedChangeType:Ae??null,trackedChangeDisplayType:Ie??null,semanticColorKey:ze??null,semanticColor:We??null,deletedText:ut??null,trackedChangeLabel:Se,trackedChangeImagePreview:mt,trackedChangeCanonicalId:Os,creatorId:At??null,creatorName:In??null,creatorEmail:Gt??null,creatorImage:kt??null,createdTime:cr??null};if(Zo&&(kn.importedId=Qo),Ma){const En=new Set([Rt?.commentId,Rt?.importedId,Rt?.trackedChangeCanonicalId,Rt?.trackedChangeAnchorKey,...ft(Rt)].map(Ir=>It(Ir)).filter(Boolean));kn.trackedChangePositionAliases=di.some(Ir=>En.has(Ir))?Zt([...Array.isArray(Rt?.trackedChangePositionAliases)?Rt.trackedChangePositionAliases:[],...di]):di}let ur=!1;for(const[En,Ir]of Object.entries(kn))ur=Mn(Rt,En,Ir)||ur;return Rt&&!(Rt.trackedChangeDetailLines==null&&Pe==null)&&!$8(Rt.trackedChangeDetailLines,Pe)&&(Rt.trackedChangeDetailLines=Pe,ur=!0),gn(Rt)||ur},qn=Rt=>{const kn=!!(Rt.resolvedTime||Rt.resolvedById||Rt.resolvedByEmail||Rt.resolvedByName);return kn&&_n(Rt),ln(Rt)||kn};if(le==="add"){const Rt=Cn();if(Rt){if(!qn(Rt))return;ie?.add(Rt),Zn({type:w.UPDATE,comment:Dn(Rt)});return}li({superdoc:k,comment:nn,broadcastChanges:Y}),ie?.add(nn)}else if(le==="update"){const Rt=Cn();if(!Rt||!qn(Rt))return;ie?.add(Rt),Zn({type:w.UPDATE,comment:Dn(Rt)})}else if(le==="resolve"){const Rt=Cn(),kn={id:M.resolvedById??k?.user?.id??null,email:M.resolvedByEmail??k?.user?.email??null,name:M.resolvedByName??k?.user?.name??null,decision:M.decision??null,superdoc:k};Rt&&!Rt.resolvedTime&&Rt.resolveComment({...kn,reconciliationToken:ek})}}finally{cu(fe)}},ai=(k=[])=>({insertedMark:k.find(({mark:M})=>M?.type?.name==="trackInsert")?.mark??null,deletionMark:k.find(({mark:M})=>M?.type?.name==="trackDelete")?.mark??null,formatMark:k.find(({mark:M})=>M?.type?.name==="trackFormat")?.mark??null}),ke=({superdoc:k,editor:M,changeIds:Y,broadcastChanges:ne=!0})=>{if(!k||!M?.state||!Array.isArray(Y)||!Y.length)return;const ie=M?.options?.documentId!=null?String(M.options.documentId):null;if(ie)for(const fe of new Set(Y.map(le=>le!=null?String(le):null).filter(Boolean))){const le=ua.getTrackChanges(M.state,fe);if(!le.length)continue;const ce=ai(le),Ce=e0({event:"update",marks:ce,nodes:[],newEditorState:M.state,documentId:ie,trackedChangesForId:le});Ce&&(Ce.trackedChangeStory=e,Ce.trackedChangeStoryKind="body",Ce.trackedChangeStoryLabel="",Ce.trackedChangeAnchorKey=n(Ce.changeId??fe),To({superdoc:k,params:Ce,broadcastChanges:ne}))}},He=(k=null,M=null,Y=null)=>{const ne=Number.isFinite(k);ee.value=ne?k:null,_.value=ne&&M!=null?String(M):null;const ie=Y??M;te.value=ne&&ie!=null?String(ie):null},Et=()=>{const k=ee.value;return Number.isFinite(k)?k:null},st=()=>{ee.value=null,_.value=null,te.value=null},Nn=(k,M,Y,ne=1e3)=>{p[k]&&clearTimeout(p[k]),p[k]=setTimeout(()=>{Y&&Y.emit("comments-update",M),delete p[k]},ne)},Kn=(k,M)=>{if(M?.source!=="document-editor")return null;const Y=M?.documentId??null,ne=k?.activeEditor?.options?.documentId??null;if(!Y||!ne||Y!==ne)return null;let ie;try{ie=k?.activeEditor?.doc?.selection?.current}catch{return null}if(typeof ie!="function")return null;try{return ie()}catch{return null}},_r=(k,M=null)=>{const Y=be(k),ne=Kn(k,s.activeSelection),ie={type:w.PENDING,pendingSelection:ne};if(k.emit("comments-update",ie),Y){const le=Y.getCapabilityState?.();return le&&le.canWrite===!1?{ok:!1,reason:le.reason}:Promise.resolve(Y.captureCurrentSelection?.()).then(ce=>{if(!ce?.ok)return{ok:!1,reason:ce?.reason??"editing-range-required",detail:ce?.detail};U.value=ce.target??null;const Ce=Y.documentId??k?.activeEditor?.options?.documentId??null;return D.value=Br({selection:{source:iu,documentId:Ce,page:1,selectionBounds:{}},documentId:Ce,parentCommentId:null}),k.config.isInternal||(D.value.isInternal=!1),He(M,"pending"),Ds(null),R.value=D.value.commentId,{ok:!0}}).catch(ce=>({ok:!1,reason:"selection-capture-failed",detail:ce?.message??String(ce)}))}const fe={...s.activeSelection};return fe.selectionBounds={...fe.selectionBounds},s.selectionPosition?.source&&s.selectionPosition.source!=="pdf"&&(s.selectionPosition.source=null),D.value=Br({selection:fe,documentId:fe.documentId,parentCommentId:null}),k.config.isInternal||(D.value.isInternal=!1),k.activeEditor?.commands&&k.activeEditor.commands.insertComment({...D.value.getValues(),commentId:"pending",skipEmit:!0}),D.value.selection.source==="document-editor"&&s.selectionPosition&&(s.selectionPosition.source=iu),He(M,"pending"),Ds(null),R.value=D.value.commentId,{ok:!0}},jo=k=>{const M=Pt(k).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},xo=(k,M)=>(k.createdTime??0)-(M.createdTime??0),Di=(k,M)=>{const Y=jo(k),ne=jo(M),ie=Number.isFinite(Y),fe=Number.isFinite(ne);return ie&&fe&&Y!==ne?Y-ne:ie&&!fe?-1:!ie&&fe?1:xo(k,M)},Ro=k=>{const M=[],Y=[],ne=new Map;return q.value.forEach(ie=>{if(!Pi(ie))return;const fe=qe(ie)?Oe(ie):null,le=ie.trackedChange?null:ie.parentCommentId||fe;ie.resolvedTime?Y.push(ie):!le&&!ie.resolvedTime?M.push({...ie}):le&&(ne.has(le)||ne.set(le,[]),ne.get(le).push(ie))}),{parentComments:M.sort(k),resolvedComments:Y.sort(k)}},oo=Ee(()=>Ro(xo)),io=Ee(()=>oo.value?.parentComments.some(k=>k.trackedChange&&!k.resolvedTime)??!1),Si=Ee(()=>Ro(Di)),Uo=k=>T.includes(k),es=Ee(()=>s.documents),vo=Ee(()=>a),Ho=(k,M)=>{const Y=k.getContainerLocation(M);return{top:Y.top+k.selectionBounds.top,left:Y.left+k.selectionBounds.left}},Br=({selection:k,documentId:M,parentCommentId:Y,...ne})=>Oi({selection:k,documentId:M,parentCommentId:Y,...ne}),Oi=({selection:k,documentId:M,parentCommentId:Y,...ne})=>{let ie;return M?ie=s.getDocument(M):k&&(ie=s.getDocument(k.documentId)),ie||(ie=s.documents[0]),ca({fileId:ie.id,fileType:ie.type,parentCommentId:Y,creatorId:s.user.id,creatorEmail:s.user.email,creatorName:s.user.name,creatorImage:s.user.image,commentText:Q.value,selection:k,...ne})},Fi=k=>{const M=!!D.value;Q.value="",D.value=null,U.value=null,s.selectionPosition=null,M&&Gr(),!Be(k)&&k?.activeEditor?.commands?.removeComment({commentId:"pending"})},Tu=({superdoc:k,comment:M,skipEditorUpdate:Y=!1,broadcastChanges:ne=!0,isHydration:ie=!1})=>{if(d()&&!ie)return l();const fe=!Y&&!ie?be(k):null;if(fe&&!M.trackedChange){const Ae=r0(D.value?Q.value:M.commentText),Ie=D.value?U.value:null,ze=M.parentCommentId?String(M.parentCommentId):(D.value,null);return(async()=>{try{return await(ze?fe.reply({parentCommentId:ze,text:Ae}):fe.commitPendingComment({text:Ae,target:Ie}))}catch(We){return{ok:!1,reason:"adapter-threw",detail:We?.message??String(We)}}})().then(We=>{if(!Mo(fe))return{ok:!1,reason:"adapter-stale"};if(!We?.ok)return ne&&k.emit("comments-update",{type:w.PENDING,rejected:!0,reason:We?.reason??"v2-create-failed",...We?.committed?{committed:!0}:{}}),We;const ut=ui({superdoc:k,adapter:fe,documentId:fe.documentId,items:We.items});return D.value&&Fi(k),ne&&k.emit("comments-update",{type:w.ADD,comment:ut?.added?.getValues?.()??null}),{ok:!0,comment:ut?.added??null}})}let le=q.value.find(Ae=>Ae.commentId===R.value);le||(le=M);const ce=ca(M.getValues());D.value?ce.setText({text:Q.value,suppressUpdate:!0}):ce.setText({text:M.commentText,suppressUpdate:!0}),ce.selection.source=D.value?.selection?.source??ce.selection.source,le&&(ce.isInternal=le.isInternal),k.config.isInternal||(ce.isInternal=!1),q.value.push(ce),Fi(k),!Y&&!M.trackedChange&&k.activeEditor?.commands&&!M.parentCommentId&&k.activeEditor.commands.insertComment({...ce.getValues(),skipEmit:!0});const Ce={type:w.ADD,comment:ce.getValues()};return ne&&(Ul(k,Ce),k.emit("comments-update",Ce)),{ok:!0,comment:ce}},xu=({superdoc:k,comment:M,skipEditorUpdate:Y=!1,broadcastChanges:ne=!0})=>Tu({superdoc:k,comment:M,skipEditorUpdate:Y,broadcastChanges:ne}),li=({superdoc:k,comment:M,skipEditorUpdate:Y=!1,broadcastChanges:ne=!0})=>Tu({superdoc:k,comment:M,skipEditorUpdate:Y,broadcastChanges:ne,isHydration:!0}),Ni=({commentId:k,superdoc:M})=>{if(d())return Promise.resolve(l());const Y=q.value.findIndex(Ie=>Ie.commentId===k),ne=q.value[Y];if(!ne)return Promise.resolve({ok:!1,reason:"comment-not-found"});const{commentId:ie,importedId:fe}=ne,{fileId:le}=ne,ce=be(M);if(ce&&!ne.trackedChange)return(async()=>{try{return await ce.delete({commentId:ie})}catch(Ie){return{ok:!1,reason:"adapter-threw",detail:Ie?.message??String(Ie)}}})().then(Ie=>Mo(ce)?Ie?.ok?(ui({superdoc:M,adapter:ce,documentId:ce.documentId??le,items:Ie.items}),M.emit("comments-update",{type:w.DELETED,comment:ne.getValues(),changes:[{key:"deleted",commentId:ie,fileId:le}]}),{ok:!0}):(M.emit("comments-update",{type:w.DELETED,rejected:!0,comment:ne.getValues(),reason:Ie?.reason??"v2-delete-failed",...Ie?.committed?{committed:!0}:{}}),Ie):{ok:!1,reason:"adapter-stale"});M.activeEditor?.commands?.removeComment({commentId:ie,importedId:fe}),q.value.splice(Y,1);const Ce=q.value.filter(Ie=>Ie.parentCommentId===ie).map(Ie=>Ie.commentId||Ie.importedId);q.value=q.value.filter(Ie=>!Ce.includes(Ie.commentId)),(R.value===ie||Ce.includes(R.value))&&Gr();const Ae={type:w.DELETED,comment:ne.getValues(),changes:[{key:"deleted",commentId:ie,fileId:le}]};return M.emit("comments-update",Ae),Ul(M,Ae),Promise.resolve({ok:!0})},Is=({superdoc:k,documentId:M,lifecycle:Y}={})=>{const ne=It(Y?.commentId),ie=Y?.status;if(!ne||ie!=="open"&&ie!=="resolved")return null;const fe=It(M),le=q.value.filter(et=>{if(!et||et.trackedChange===!0||lu(et))return!1;const At=It(et.fileId);return fe==null||At==null||At===fe}),ce=new Map,Ce=new Map;for(const et of le){for(const Gt of[et.commentId,et.importedId].map(It).filter(Boolean))ce.has(Gt)||ce.set(Gt,et);const At=It(et.parentCommentId);if(At){const Gt=Ce.get(At)??[];Gt.push(et),Ce.set(At,Gt)}}let Ae=ce.get(ne)??null;const Ie=new Set;for(;Ae?.parentCommentId!=null;){const et=It(Ae.parentCommentId);if(!et||Ie.has(et))break;Ie.add(et);const At=ce.get(et);if(!At)break;Ae=At}if(!Ae)return null;const ze=[],We=[Ae],ut=new Set;for(;We.length>0;){const et=We.shift();if(!(!et||ut.has(et))){ut.add(et),ze.push(et);for(const At of[et.commentId,et.importedId].map(It).filter(Boolean))We.push(...Ce.get(At)??[])}}const Ye=ie==="resolved",pt=Date.now();for(const et of ze)et.resolvedTime=Ye?et.resolvedTime??pt:null,et.resolvedById=Ye?k?.user?.id??null:null,et.resolvedByEmail=Ye?k?.user?.email??null:null,et.resolvedByName=Ye?k?.user?.name??null:null;return{added:null,lifecycleUpdated:ze.length}},Bi=async({superdoc:k,adapter:M,fileId:Y,operation:ne,eventType:ie,rejectionFallbackReason:fe,rejectionEventExtras:le={},validateOutcome:ce,successEventBuilder:Ce})=>{let Ae;try{Ae=await ne()}catch(Ye){Ae={ok:!1,reason:"adapter-threw",detail:Ye?.message??String(Ye)}}if(!Mo(M))return{ok:!1,reason:"adapter-stale"};if(!Ae?.ok){const Ye={type:ie,rejected:!0,reason:Ae?.reason??fe,...Ae?.committed?{committed:!0}:{},...Ae?.code!==void 0?{code:Ae.code}:{},...Ae?.detail!==void 0?{detail:Ae.detail}:{},...le};return k?.emit?.("comments-update",Ye),Ae}const Ie=ce?.({outcome:Ae});if(Ie?.ok===!1){const Ye={ok:!1,committed:Ie.committed??!0,reason:Ie.reason??fe,...Ie.code!==void 0?{code:Ie.code}:{},...Ie.detail!==void 0?{detail:Ie.detail}:{}},pt={type:ie,rejected:!0,reason:Ye.reason,...Ye.committed?{committed:!0}:{},...Ye.code!==void 0?{code:Ye.code}:{},...Ye.detail!==void 0?{detail:Ye.detail}:{},...le};return k?.emit?.("comments-update",pt),Ye}const ze=M.documentId??Y,We=Is({superdoc:k,documentId:ze,lifecycle:Ae.threadLifecycle})??ui({superdoc:k,adapter:M,documentId:ze,items:Ae.items??[],pruneStale:Ae.complete!==!1}),ut=Ce?.({outcome:Ae,reconciled:We})??null;return ut&&k?.emit?.("comments-update",ut),{ok:!0,items:Ae.items??[],reconciled:We,...Ae.complete===!1?{complete:!1}:{},...Ae.visibleWindowSource!=null?{visibleWindowSource:Ae.visibleWindowSource}:{},...Ae.threadLifecycle!=null?{threadLifecycle:Ae.threadLifecycle}:{},...Ae.mutationPath!=null?{mutationPath:Ae.mutationPath}:{}}},jf=({outcome:k,adapter:M,fileId:Y})=>(k.items??[]).map(ne=>M.mapV2CommentToUseCommentInput(ne,{fileId:Y,fileType:null})).filter(Boolean),Ca=k=>{const M=k?.commentId??k?.importedId;return M!=null?String(M):null},ka=k=>k?.parentCommentId!=null?String(k.parentCommentId):null,Ar=({outcome:k,adapter:M,fileId:Y,commentId:ne,expectedResolved:ie,operation:fe})=>{const le=ne!=null?String(ne):null,ce=k?.threadLifecycle;if(ce!=null){const pt=It(ce.commentId),et=ce.status==="resolved";return pt===le&&et===ie?{ok:!0}:{ok:!1,reason:`v2-${fe}-receipt-lifecycle-mismatch`,detail:{expected:{commentId:le,status:ie?"resolved":"open"},observed:ce}}}const Ce=jf({outcome:k,adapter:M,fileId:Y}),Ae=Ce.find(pt=>Ca(pt)===le)??null,Ie=Ae?.parentCommentId?Ce.find(pt=>Ca(pt)===ka(Ae))??null:Ae,ze=Ca(Ie);if(!Ie||!ze)return{ok:!1,reason:`v2-${fe}-refresh-missing`,detail:`comment ${le} was absent from the refreshed v2 comment list after ${fe}`};const We=[Ie,...Ce.filter(pt=>ka(pt)===ze)],ut=pt=>!!pt?.resolvedTime;if(We.filter(pt=>ut(pt)!==ie).length===0)return{ok:!0};const Ye=ut(Ie);return We.some(pt=>ut(pt)!==Ye)?{ok:!1,reason:`v2-${fe}-refresh-split-thread`,detail:{rootId:ze,expected:ie?"resolved":"open",observed:We.map(pt=>({commentId:Ca(pt),parentCommentId:ka(pt),status:ut(pt)?"resolved":"open"}))}}:{ok:!1,reason:ie?`v2-${fe}-refresh-still-open`:`v2-${fe}-refresh-still-resolved`,detail:`comment ${ze} remained ${Ye?"resolved":"open"} after ${fe}`}},Uf=async({superdoc:k,parentCommentId:M,text:Y}={})=>{if(d())return l();const ne=be(k);if(!ne)return{ok:!1,reason:"v2-comments-adapter-missing"};const ie=M!=null?String(M):null;if(!ie)return{ok:!1,reason:"parent-comment-id-missing"};const fe=r0(Y);if(fe.length===0)return{ok:!1,reason:"comment-text-empty"};const le=q.value.find(Ce=>String(Ce.commentId)===ie),ce=le?.fileId??ne.documentId??null;return Bi({superdoc:k,adapter:ne,fileId:ce,operation:()=>ne.reply({parentCommentId:ie,text:fe}),eventType:w.ADD,rejectionFallbackReason:"v2-reply-failed",rejectionEventExtras:le?{comment:Dn(le)}:{},successEventBuilder:({reconciled:Ce})=>({type:w.ADD,comment:Ce?.added?.getValues?.()??null})})},ml=async({superdoc:k,commentId:M,text:Y}={})=>{if(d())return l();const ne=be(k);if(!ne)return{ok:!1,reason:"v2-comments-adapter-missing"};const ie=M!=null?String(M):null;if(!ie)return{ok:!1,reason:"comment-id-missing"};const fe=r0(Y);if(fe.length===0)return{ok:!1,reason:"comment-text-empty"};const le=q.value.find(Ce=>String(Ce.commentId)===ie),ce=le?.fileId??ne.documentId??null;return Bi({superdoc:k,adapter:ne,fileId:ce,operation:()=>ne.edit({commentId:ie,text:fe}),eventType:w.UPDATE,rejectionFallbackReason:"v2-edit-failed",rejectionEventExtras:le?{comment:Dn(le),changes:[{key:"text",value:fe}]}:{},successEventBuilder:()=>{const Ce=q.value.find(Ae=>String(Ae.commentId)===ie)??le;return Ce?{type:w.UPDATE,comment:Dn(Ce),changes:[{key:"text",value:Ce.commentText??fe}]}:null}})},Hf=async({superdoc:k,commentId:M}={})=>{if(d())return l();if(u())return c();const Y=be(k);if(!Y)return{ok:!1,reason:"v2-comments-adapter-missing"};const ne=M!=null?String(M):null;if(!ne)return{ok:!1,reason:"comment-id-missing"};const ie=q.value.find(ce=>String(ce.commentId)===ne),fe=ie?.fileId??Y.documentId??null,le=await Bi({superdoc:k,adapter:Y,fileId:fe,operation:()=>Y.resolve({commentId:ne}),eventType:w.RESOLVED,rejectionFallbackReason:"v2-resolve-failed",rejectionEventExtras:ie?{comment:Dn(ie)}:{},validateOutcome:({outcome:ce})=>Ar({outcome:ce,adapter:Y,fileId:fe,commentId:ne,expectedResolved:!0,operation:"resolve"}),successEventBuilder:()=>{const ce=q.value.find(Ce=>String(Ce.commentId)===ne)??ie;return ce?{type:w.RESOLVED,comment:Dn(ce)}:null}});if(le?.ok){const Ce=!!q.value.find(Ie=>String(Ie.commentId)===ne)?.resolvedTime,Ae=R.value!=null?String(R.value):null;Ce&&Ae===ne&&Gr()}return le},rc=async({superdoc:k,commentId:M}={})=>{if(d())return l();if(u())return c();const Y=be(k);if(!Y)return{ok:!1,reason:"v2-comments-adapter-missing"};const ne=M!=null?String(M):null;if(!ne)return{ok:!1,reason:"comment-id-missing"};const ie=q.value.find(le=>String(le.commentId)===ne),fe=ie?.fileId??Y.documentId??null;return Bi({superdoc:k,adapter:Y,fileId:fe,operation:()=>Y.reopen({commentId:ne}),eventType:w.UPDATE,rejectionFallbackReason:"v2-reopen-failed",rejectionEventExtras:ie?{comment:Dn(ie),changes:[{key:"resolvedTime",value:null}]}:{},validateOutcome:({outcome:le})=>Ar({outcome:le,adapter:Y,fileId:fe,commentId:ne,expectedResolved:!1,operation:"reopen"}),successEventBuilder:()=>{const le=q.value.find(ce=>String(ce.commentId)===ne);return!le||le.resolvedTime?null:{type:w.UPDATE,comment:Dn(le),changes:[{key:"resolvedTime",value:null}]}}})},Mo=k=>k?J.value===k:!1,ci=k=>k?Ze.value===k:!1,Ru=({superdoc:k,commentsAdapter:M,trackedChangesAdapter:Y,documentId:ne,commentItems:ie,trackedChangeItems:fe,trackedList:le,sourceCoverageRevision:ce,evaluatedRevision:Ce,patch:Ae}={})=>ys("store.reviewSnapshot.apply","store-reconciliation",{commentItemCount:Array.isArray(ie)?ie.length:null,trackedItemCount:Array.isArray(fe)?fe.length:null},()=>{if(!Mo(M))return{ok:!1,reason:"comments-adapter-stale"};if(!ci(Y))return{ok:!1,reason:"tracked-changes-adapter-stale"};const Ie=ne!=null?String(ne):null,ze=k?.activeEditor?.documentId??k?.activeEditor?.options?.documentId??null;if(!Ie)return{ok:!1,reason:"document-mismatch"};for(const At of[M.documentId,Y.documentId,ze])if(At==null||String(At)!==Ie)return{ok:!1,reason:"document-mismatch"};if(!Array.isArray(ie)||!Array.isArray(fe))return{ok:!1,reason:"items-invalid"};if(le?.complete!==!1||!["review-snapshot","visible-window"].includes(le?.visibleWindowSource))return{ok:!1,reason:"tracked-list-not-partial-visible-window"};if(typeof M.mapV2CommentToUseCommentInput!="function"||typeof Y.mapV2TrackedChangeToCommentParams!="function")return{ok:!1,reason:"adapter-mapper-missing"};let We=ie,ut=!1;if(typeof M.seedReviewCatalog=="function"){const At=M.seedReviewCatalog(ie,{sourceCoverageRevision:ce,evaluatedRevision:Ce});if(At?.ok!==!0)return{ok:!1,reason:At?.reason??"comment-catalog-seed-failed"};const Gt=M.selectVisibleReviewComments?.();Gt?.ok===!0&&Array.isArray(Gt.items)&&(!Array.isArray(Gt.unresolvedIds)||Gt.unresolvedIds.length===0)&&(We=Gt.items,ut=!0)}const Ye=(Ie?s.getDocument(Ie):null)?.type??null;let pt,et;try{pt=We.filter(At=>!Zy(At)).map(At=>M.mapV2CommentToUseCommentInput(At,{fileId:Ie,fileType:Ye})).filter(Boolean),et=fe.map(At=>Y.mapV2TrackedChangeToCommentParams(At)).filter(Boolean)}catch(At){return{ok:!1,reason:"mapper-failed",detail:At?.message??String(At)}}return typeof Ae!="function"?{ok:!1,reason:"patch-missing"}:(Ae(()=>{rs({superdoc:k,adapter:Y,documentId:Ie,items:fe,preparedParams:et,pruneStale:!1}),ui({superdoc:k,adapter:M,documentId:Ie,items:We,preparedInputs:pt,pruneStale:!ut})}),{ok:!0,commentItems:pt.length,trackedItems:et.length})}),Mu=async({superdoc:k,adapter:M,documentId:Y,trackedChangesListMode:ne="all",commentIds:ie,isCurrent:fe,signal:le,hydrationGeneration:ce}={})=>ys("store.comments.hydrateFromV2","comments-list",{documentId:Y??null},async()=>{const Ce=M??be(k),Ae=ne==="visible-window",Ie=Ae?Ce?.selectVisibleReviewComments:Ce?.refresh;if(!Ce||typeof Ie!="function")return{ok:!1,reason:"adapter-missing"};const ze=()=>fe?.()!==!1&&Mo(Ce);if(!ze())return{ok:!1,reason:"adapter-stale"};if(le?.aborted)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!1};const We=W(Ce);let ut;try{const Ye={};Ae&&Array.isArray(ie)&&(Ye.targetIds=ie),le&&(Ye.signal=le),typeof ce=="number"&&(Ye.hydrationGeneration=ce),ut=Object.keys(Ye).length>0?await Ie.call(Ce,Ye):await Ie.call(Ce)}catch(Ye){return{ok:!1,reason:"adapter-threw",detail:Ye?.message??String(Ye)}}return ze()?le?.aborted||W(Ce)!==We?{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0}:ut?.ok?le?.aborted||W(Ce)!==We?{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0}:(ui({superdoc:k,adapter:Ce,documentId:Y,items:ut.items??[],pruneStale:!Ae||Array.isArray(ie)&&(!Array.isArray(ut.unresolvedIds)||ut.unresolvedIds.length===0),hydrationGeneration:ce}),{ok:!0,items:ut.items??[],reconciled:!0,...typeof ce=="number"?{hydrationGeneration:ce}:{},...ut.visibleWindowSource!=null?{visibleWindowSource:ut.visibleWindowSource}:{}}):ut:{ok:!1,reason:"adapter-stale"}}),ui=({superdoc:k,adapter:M,documentId:Y,items:ne,preparedInputs:ie=null,pruneStale:fe=!0,hydrationGeneration:le}={})=>ys("store.comments.reconcile","store-reconciliation",{documentId:Y??null,itemCount:Array.isArray(ne)?ne.length:null,hydrationGeneration:le??null},()=>{if(!M||!Array.isArray(ne))return{added:null};if(!Mo(M))return{added:null,dropped:"adapter-stale"};const ce=Y??M.documentId??null,Ce=ce!=null?String(ce):null,Ae=(ce?s.getDocument(ce):null)?.type??null,Ie=ct=>typeof ct!="string"?!0:ct.replace(/<[^>]*>/g,"").replace(/&nbsp;/gi," ").trim().length===0,ze=ct=>!ct||ct.trackedChange===!0||!ct.trackedChangeThreadParentId||ct.parentCommentId?!1:Ie(ct.commentText),We=R.value!=null?String(R.value):null,ut=We?q.value.find(ct=>String(ct.commentId)===We)??null:null,Ye=ut!=null&&D.value!=null&&(ut===D.value||D.value.commentId!=null&&String(ut.commentId??"")===String(D.value.commentId)),pt=ut!=null&&!Ye&&ut.trackedChange!==!0&&!lu(ut)&&(Ce==null||ut.fileId==null||String(ut.fileId)===Ce),et=new Map,At=new Map,Gt=[],kt=Array.isArray(ie)?ie:ne.filter(ct=>!Zy(ct)).map(ct=>M.mapV2CommentToUseCommentInput(ct,{fileId:ce,fileType:Ae})).filter(Boolean);for(const ct of kt){if(ze(ct)){At.set(String(ct.commentId),String(ct.trackedChangeThreadParentId)),y("hydrate:drop-v2-sidecar-comment",{commentId:ct.commentId??null,importedId:ct.importedId??null,parentCommentId:ct.parentCommentId??null,trackedChangeParentId:ct.trackedChangeParentId??null,trackedChangeThreadParentId:ct.trackedChangeThreadParentId??null,trackedChangeSide:ct.trackedChangeSide??null,commentText:ct.commentText??null});continue}Gt.push(ct)}for(const ct of Gt){const un=ct.parentCommentId!=null?String(ct.parentCommentId):null,yo=un?At.get(un):null;yo&&(ct.threadingParentCommentId=yo,ct.trackedChangeThreadParentId==null&&(ct.trackedChangeThreadParentId=yo));const Yo=ct.commentId!=null?String(ct.commentId):null;Yo&&et.set(Yo,ct)}const cr=ct=>{if(Ce==null)return!0;const un=ct?.fileId!=null?String(ct.fileId):null;return un==null?!0:un===Ce},In=D.value?.commentId!=null?String(D.value.commentId):null,jt=ct=>!ct||!D.value?!1:ct===D.value||In!=null&&String(ct.commentId??"")===In,en=ct=>!ct||jt(ct)||ct.trackedChange===!0||lu(ct)?!1:ct.commentId!=null,Xr=(ct,un)=>{ct.commentText=un.commentText??ct.commentText,ct.isInternal=typeof un.isInternal=="boolean"?un.isInternal:ct.isInternal,typeof un.resolvedTime=="number"?(ct.resolvedTime=un.resolvedTimeWasSynthesized===!0&&typeof ct.resolvedTime=="number"?ct.resolvedTime:un.resolvedTime,ct.resolvedByEmail=un.resolvedByEmail??null,ct.resolvedByName=un.resolvedByName??null):(ct.resolvedTime=null,ct.resolvedByEmail=null,ct.resolvedByName=null),un.parentCommentId!==void 0?ct.parentCommentId=un.parentCommentId:delete ct.parentCommentId,un.trackedChangeParentId!==void 0?ct.trackedChangeParentId=un.trackedChangeParentId:delete ct.trackedChangeParentId,un.trackedChangeThreadParentId!==void 0?ct.trackedChangeThreadParentId=un.trackedChangeThreadParentId:ct.trackedChangeThreadParentId=void 0,un.trackedChangeSide!==void 0?ct.trackedChangeSide=un.trackedChangeSide:delete ct.trackedChangeSide,un.threadingParentCommentId!==void 0?ct.threadingParentCommentId=un.threadingParentCommentId:delete ct.threadingParentCommentId},Rr=[],Zr=new Set,Wr=[];for(const ct of q.value){if(!en(ct)||!cr(ct)){Rr.push(ct);continue}const un=String(ct.commentId),yo=et.get(un);yo&&(Xr(ct,yo),Zr.add(un),Rr.push(ct)),!yo&&!fe&&Rr.push(ct)}for(const[ct,un]of et.entries()){if(Zr.has(ct))continue;const yo=ca(un);Rr.push(yo),Wr.push(yo)}return q.value=Rr,pt&&We&&!Rr.some(ct=>String(ct.commentId)===We)&&Gr(),{added:Wr[Wr.length-1]??null}}),wr=k=>{Fi(k)},$f=k=>typeof k!="string"?null:k.replace(/\s*\(imported\)\s*$/u,"").trim()||null,qo=k=>{if(!k)return null;try{if(k.isDestroyed===!0)return null;const M=k.view;if(!M||M.isDestroyed===!0||M.destroyed===!0)return null;const Y=M.state;return Y?{view:M,state:Y}:null}catch{return null}},Es=k=>k!=null&&String(k).length>0?String(k):null,zi=k=>{const M=Es(k),Y=M?[[M,S.get(M)]]:Array.from(S.entries());let ne=0;for(const[ie,fe]of Y)fe&&(S.delete(ie),fe.timeoutHandle!==null&&fe.timeoutHandle!==void 0&&clearTimeout(fe.timeoutHandle),ne+=1);return ne},Ts=k=>{const M=qo(k);if(!M)return null;let Y=[];try{Y=ua.getTrackChanges(M.state)??[]}catch{return null}const ne=ua?.enumerateStructuralRowChanges;let ie=[];if(typeof ne=="function")try{ie=ne(M.state)??[]}catch{ie=[]}let fe=[];if(typeof uu=="function")try{fe=uu(k)?.getAll?.()??[]}catch{fe=[]}return{...M,trackedChanges:Y,structuralChanges:ie,storySnapshots:fe}},ts=({superdoc:k,editor:M,documentId:Y,refreshReason:ne="tracked-change-sidebar-authoritative"}={})=>{const ie=Ft(k)??M?.v2TrackedChanges??null;if(!ie||typeof ie.listTrackedChanges!="function"||typeof ie.mapV2TrackedChangeToCommentParams!="function")return!1;const fe=Y??ie.documentId??M?.documentId??M?.options?.documentId??k?.activeEditor?.documentId??k?.activeEditor?.options?.documentId??null;if(fe==null)return!1;const le=String(fe);return fc({superdoc:k,adapter:ie,documentId:le,trackedChangesListMode:"background-reconcile",refreshReason:ne,blocking:!1,isCurrent:()=>{const ce=k?.activeEditor??null,Ce=ce?.documentId??ce?.options?.documentId??null;return Ce==null||String(Ce)===le}}),!0},oc=(k,M,Y=null)=>{if(!k||!M)return!1;const ne=Y??Ts(k);return ne?(Pu(k,M,ne.trackedChanges,{editorState:ne.state,editorView:ne.view}),ju({superdoc:M,editor:k,snapshots:ne.storySnapshots,documentState:ne.state,resolveFromEditor:!1}),_i({superdoc:M,editor:k,structuralChanges:ne.structuralChanges}),ts({superdoc:M,editor:k,documentId:k?.options?.documentId,refreshReason:"import-bootstrap-authoritative"}),!0):!1},ic=k=>{if(!k||S.get(k.documentId)!==k)return!1;try{const M=k.editor?.options?.documentId;if(M!=null&&String(M)!==k.documentId)return!1;const Y=s.getDocument(k.documentId);if(!Y||Y.getEditor?.()!==k.editor)return!1}catch{return!1}return!0},Lu=k=>{if(!ic(k))return S.get(k?.documentId)===k&&S.delete(k.documentId),!1;const M=Ts(k.editor);if(!M||!ic(k))return S.get(k.documentId)===k&&S.delete(k.documentId),!1;try{return oc(k.editor,k.superdoc,M)}finally{S.get(k.documentId)===k&&S.delete(k.documentId)}},sc=({editor:k,superdoc:M,documentId:Y,defer:ne=!0})=>{const ie=Es(Y);if(!ie||!k||!M)return!1;zi(ie);const fe={documentId:ie,editor:k,superdoc:M,generation:++C,timeoutHandle:null};return S.set(ie,fe),ne?(fe.timeoutHandle=setTimeout(()=>{fe.timeoutHandle=null,Lu(fe)},0),!0):Lu(fe)};function xs(k){const M=k!=null?String(k):null;if(!M)return;zi(M);const Y=q.value.filter(fe=>Aa(fe,M,{allowSingleDocumentMismatch:!0}));if(!Y.length)return;const ne=new Set;if(Y.forEach(fe=>{ft(fe).forEach(le=>ne.add(le))}),q.value=q.value.filter(fe=>!Y.includes(fe)),ne.size){const fe={...oe.value||{}};ne.forEach(le=>{delete fe[le]}),oe.value=fe}const ie=R.value!=null?String(R.value):null;ie&&ne.has(ie)&&Gr()}function Sa(k){xs(k)}const Rs=async({superdoc:k,editor:M,comments:Y,documentId:ne,replacedFile:ie=!1})=>{const fe=s.getDocument(ne);if(fe?.commentThreadingProfile&&(fe.commentThreadingProfile.value=M?.converter?.commentThreadingProfile||null),ie&&Sa(ne),Y.forEach(le=>{const ce=Array.isArray(le.elements)?le.elements:[],Ce=Zf(ce);if(!Ce&&!le.trackedChange)return;const Ae=$f(le.creatorName),Ie=Ae?`${Ae} (imported)`:null,ze=ca({fileId:ne,fileType:fe.type,docxCommentJSON:ce.length?ce:null,commentId:le.commentId,isInternal:!1,parentCommentId:le.parentCommentId,trackedChangeParentId:le.trackedChangeParentId,trackedChangeThreadParentId:le.trackedChangeThreadParentId,creatorId:null,creatorName:Ae,createdTime:le.createdTime,creatorEmail:le.creatorEmail,importedAuthor:{...Ie?{name:Ie}:{},email:le.creatorEmail},commentText:Ce,resolvedTime:le.isDone?Date.now():null,resolvedById:null,resolvedByEmail:le.isDone?le.creatorEmail:null,resolvedByName:le.isDone?Ie||"(Imported)":null,trackedChange:le.trackedChange||!1,trackedChangeText:le.trackedChangeText,trackedChangeType:le.trackedChangeType,trackedChangeDisplayType:le.trackedChangeDisplayType,deletedText:le.trackedDeletedText,origin:le.origin||"word",threadingMethod:le.threadingMethod,threadingStyleOverride:le.threadingStyleOverride,threadingParentCommentId:le.threadingParentCommentId,originalXmlStructure:le.originalXmlStructure});li({superdoc:k,comment:ze})}),ie){sc({editor:M,superdoc:k,documentId:ne,defer:!1});return}sc({editor:M,superdoc:k,documentId:ne})},Pu=(k,M,Y=null,ne={})=>{const{reopenResolved:ie=!1,refreshExisting:fe=!1,broadcastChanges:le=!0,editorState:ce=null,editorView:Ce=null}=ne,Ae=ce?{state:ce,view:Ce}:qo(k);if(!Ae?.state)return;const Ie=Ae.state,ze=Y??ua.getTrackChanges(Ie),We=d8(ze),ut=k?.options?.documentId!=null?String(k.options.documentId):null;if(!ut)return;const Ye=new Set,pt=new Map;q.value.forEach(In=>{if(!In?.trackedChange||!so(In,ut)||!t(In))return;const jt=[In.commentId,In.importedId].map(en=>en!=null?String(en):null).filter(Boolean);if(In.resolvedTime){ie||jt.forEach(en=>Ye.add(en));return}jt.forEach(en=>{pt.set(en,In),fe||Ye.add(en)})});const et=new Map;for(const In of ze){const jt=In.mark.attrs.id;et.has(jt)||et.set(jt,[]),et.get(jt).push(In)}const At=ut,Gt=new Set;We.forEach(({insertedMark:In,deletionMark:jt,formatMark:en})=>{const Xr=In?.mark.attrs.id||jt?.mark.attrs.id||en?.mark.attrs.id;if(Xr==null)return;const Rr=String(Xr);if(Gt.has(Rr)||(Gt.add(Rr),!fe&&Ye.has(Rr)))return;const Zr=pt.get(Rr),Wr={...In&&{insertedMark:In.mark},...jt&&{deletionMark:jt.mark},...en&&{formatMark:en.mark}},ct=e0({event:Zr?"update":"add",marks:Wr,nodes:[],newEditorState:Ie,documentId:At,trackedChangesForId:et.get(Xr)||[]});if(ct){const un=n(ct.changeId??Xr);ct.trackedChangeStory=e,ct.trackedChangeStoryKind="body",ct.trackedChangeStoryLabel="",ct.trackedChangeAnchorKey=un,To({superdoc:M,params:ct,broadcastChanges:le,documentState:Ie}),Zr||(Ye.add(Rr),ct.changeId!=null&&Ye.add(String(ct.changeId)),ct.importedId!=null&&Ye.add(String(ct.importedId)))}});const kt=Ae.view;try{if(!kt||k.view!==kt||kt.isDestroyed===!0||kt.destroyed===!0)return}catch{return}const{tr:cr}=Ie;cr.setMeta(D8,{type:"force"}),kt.dispatch(cr)},ac=({suppressedIds:k,activeDocumentId:M,superdoc:Y=null,broadcastChanges:ne=!0})=>{if(!(k instanceof Set)||!k.size||!M)return;const ie=[];if(q.value=q.value.filter(ce=>{if(!ce?.trackedChange||!t(ce)||mc(ce)||!so(ce,M))return!0;const Ce=ce.commentId!=null?String(ce.commentId):null,Ae=ce.importedId!=null?String(ce.importedId):null;return Ce&&k.has(Ce)||Ae&&k.has(Ae)?(ie.push(ce),!1):!0}),!ie.length)return;const fe=new Set;ie.forEach(ce=>{ce.commentId!=null&&fe.add(String(ce.commentId)),ce.importedId!=null&&fe.add(String(ce.importedId));const Ce=Dn(ce),Ae={type:w.DELETED,comment:Ce,changes:[{key:"deleted",commentId:Ce.commentId,fileId:Ce.fileId}]};ne&&(Ul(Y,Ae),Y?.emit?.("comments-update",Ae))});const le=R.value!=null?String(R.value):null;le&&fe.has(le)&&Gr()},Ms=k=>k?k.fileId!=null?String(k.fileId):k.documentId!=null?String(k.documentId):k.selection?.documentId!=null?String(k.selection.documentId):null:null,Gf=()=>{const k=Array.isArray(s.documents)?s.documents:s.documents?.value;return Array.isArray(k)?k:[]},_a=()=>{const k=Gf();return k.length!==1?null:k[0]?.id!=null?String(k[0].id):null},Aa=(k,M,Y={})=>{const{allowSingleDocumentMismatch:ne=!1}=Y;if(!M)return!1;const ie=Ms(k);if(ie){if(ie===M)return!0;const fe=_a();return ne&&fe===M}return _a()===M},so=(k,M)=>Aa(k,M,{allowSingleDocumentMismatch:!0}),Du=k=>{const M=typeof k=="string"?k.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},gl=({comment:k,decision:M}={})=>{const Y=M==="accept"||M==="reject"?M:null;if(!Y)return!1;const ne=Du(k?.trackedChangeDisplayType)??Du(k?.trackedChangeType);return Y==="accept"&&ne==="insertion"||Y==="reject"&&ne==="deletion"},Ls=(k,M,Y,ne=null,{broadcastChanges:ie=!0}={})=>ys("store.trackedChanges.pruneStaleComments","store-reconciliation",{activeDocumentId:Y??null,liveIdCount:k instanceof Set?k.size:null,liveAnchorKeyCount:M instanceof Set?M.size:null},()=>{if(!(k instanceof Set)||!Y)return;const fe=new Set,le=[],ce=[...q.value];if(q.value=q.value.filter(ze=>{if(!ze?.trackedChange||!so(ze,Y))return!0;const We=ze.commentId!=null?String(ze.commentId):null,ut=ze.importedId!=null?String(ze.importedId):null,Ye=ze.trackedChangeAnchorKey!=null?String(ze.trackedChangeAnchorKey):null,pt=!!(We&&k.has(We)),et=!!(ut&&k.has(ut)),At=!!(Ye&&M?.has(Ye));if(!We&&!ut&&!Ye||pt||et||At||ze.resolvedTime)return!0;const Gt=v.get(ze);return Gt?(ze.resolvedTime=Gt.resolvedTime??Date.now(),ze.resolvedById=Gt.resolvedById??null,ze.resolvedByEmail=Gt.resolvedByEmail??null,ze.resolvedByName=Gt.resolvedByName??null,ze.trackedChangeDecision=Gt.trackedChangeDecision??null,le.push(ze),!0):(We&&fe.add(We),ut&&fe.add(ut),!1)}),le.forEach(ze=>{const We=Dn(ze),ut={type:w.UPDATE,comment:We};ie&&(Ul(ne,ut),ne?.emit?.("comments-update",ut))}),!fe.size)return;let Ce=!0;for(;Ce;)Ce=!1,q.value=q.value.filter(ze=>{if(!so(ze,Y))return!0;const We=ze.parentCommentId!=null?String(ze.parentCommentId):null,ut=Oe(ze)!=null?String(Oe(ze)):null;if(!(We&&fe.has(We)||ut&&fe.has(ut))||ze.resolvedTime)return!0;const Ye=ze.commentId!=null?String(ze.commentId):null,pt=ze.importedId!=null?String(ze.importedId):null;return Ye&&fe.add(Ye),pt&&fe.add(pt),Ce=!0,!1});ce.filter(ze=>{if(!so(ze,Y))return!1;const We=ze.commentId!=null?String(ze.commentId):null,ut=ze.importedId!=null?String(ze.importedId):null;return We&&fe.has(We)||ut&&fe.has(ut)}).forEach(ze=>{const We=Dn(ze),ut={type:w.DELETED,comment:We,changes:[{key:"deleted",commentId:We.commentId,fileId:We.fileId}]};ie&&(Ul(ne,ut),ne?.emit?.("comments-update",ut))});const Ae=R.value!=null?String(R.value):null,Ie=ce.some(ze=>{const We=ze.commentId!=null?String(ze.commentId):null,ut=ze.importedId!=null?String(ze.importedId):null;return so(ze,Y)&&(We&&We===Ae||ut&&ut===Ae)});Ae&&fe.has(Ae)&&Ie&&Gr()}),lc=({superdoc:k,comment:M,decision:Y}={})=>{if(!M?.trackedChange||gl({comment:M,decision:Y}))return 0;const ne=ns(M);if(!ne.size)return 0;const ie={email:k?.user?.email??null,name:k?.user?.name??null,superdoc:k};let fe=0;return vl(M).forEach(le=>{!le||le===M||le.resolvedTime||[Oe(le),le.threadingParentCommentId,le.parentCommentId].map(ce=>It(ce)).filter(Boolean).some(ce=>ne.has(ce))&&typeof le.resolveComment=="function"&&(le.resolveComment(ie),fe+=1)}),fe},ns=k=>{const M=new Set(ft(k));k?.trackedChangeCanonicalId!=null&&M.add(String(k.trackedChangeCanonicalId));const Y=k?.trackedChangeAnchorKey!=null?String(k.trackedChangeAnchorKey):null;if(Y&&(M.add(Y),Y.startsWith("tc::"))){const ne=Y.slice(Y.lastIndexOf("::")+2);ne&&M.add(ne)}return M},vl=k=>{const M=[],Y=new Set;for(const ne of ns(k))for(const ie of ye.value.get(String(ne))??[])Y.has(ie)||(Y.add(ie),M.push(ie));return M},Ou=k=>{const M=k&&typeof k=="object"?k:null;if(!M?.success)return new Set;const Y=new Set,ne=ie=>{const fe=ie&&typeof ie=="object"?ie:null;fe?.kind!=="entity"||fe.entityType!=="trackedChange"||fe.entityId!=null&&String(fe.entityId).length>0&&Y.add(String(fe.entityId))};return Array.isArray(M.removed)&&M.removed.forEach(ne),Array.isArray(M.invalidatedRefs)&&M.invalidatedRefs.forEach(ne),Y},cc=k=>{const M=new Set;return k?.decidedId!=null&&String(k.decidedId).length>0&&M.add(String(k.decidedId)),Array.isArray(k?.decidedIds)&&k.decidedIds.forEach(Y=>{Y!=null&&String(Y).length>0&&M.add(String(Y))}),Ou(k?.receipt).forEach(Y=>M.add(Y)),M},Fu=({comment:k,decision:M}={})=>{if(!k?.trackedChange||!gl({comment:k,decision:M}))return 0;const Y=ns(k);if(!Y.size)return 0;let ne=0;return vl(k).forEach(ie=>{if(!ie||ie===k)return;const fe=It(ie.trackedChangeParentId),le=It(ie.trackedChangeThreadParentId),ce=It(ie.threadingParentCommentId),Ce=It(ie.parentCommentId);(fe&&Y.has(fe)||le&&Y.has(le)||ce&&Y.has(ce)||Ce&&Y.has(Ce))&&(delete ie.trackedChangeParentId,ie.trackedChangeThreadParentId=void 0,delete ie.trackedChangeSide,delete ie.threadingParentCommentId,Ce&&Y.has(Ce)&&delete ie.parentCommentId,ne+=1)}),ne},Nu=(k=[],{documentId:M}={})=>{const Y=It(M);if(!Array.isArray(k)||k.length===0||!Y)return;const ne=oe.value||{};let ie=!1;const fe=(ce,Ce,Ae,Ie)=>It(ce?.[Ce])!==Ae?!1:(ce[Ce]=Ie,!0),le=(ce,Ce)=>ce?.trackedChange&&so(ce,Y)&&[ce.commentId,ce.importedId,ce.trackedChangeCanonicalId,...ft(ce)].map(Ae=>It(Ae)).includes(Ce);for(const ce of k){const Ce=It(ce?.from),Ae=It(ce?.to);if(!Ce||!Ae||Ce===Ae)continue;const Ie=q.value.find(jt=>le(jt,Ce));if(!Ie)continue;const ze=It(Ie.commentId),We=It(Ie.trackedChangeCanonicalId),ut=Pt(Ie).entry,Ye=![Ie.commentId,Ie.importedId,Ie.trackedChangeCanonicalId].map(jt=>It(jt)).includes(Ce)&&ze!=null&&We!=null&&ze===We,pt={};for(const jt of["commentId","importedId"])fe(Ie,jt,Ce,Ae)&&(pt[jt]=Ae);fe(Ie,"trackedChangeCanonicalId",Ce,Ae)&&(pt.trackedChangeCanonicalId=Ae),Ye&&(Ie.commentId=Ae,Ie.trackedChangeCanonicalId=Ae,pt.commentId=Ae,pt.trackedChangeCanonicalId=Ae);const et=r(Ie.trackedChangeAnchorKey),At=et?.storyKey??wn(Qt(Ie)),Gt=o(At,Ae),kt=new Set([Ce]);Ye&&(ze&&kt.add(ze),We&&kt.add(We)),(Ie.trackedChangeAnchorKey==null||kt.has(et?.rawId))&&(Ie.trackedChangeAnchorKey=Gt),Ie.trackedChangePositionAliases=Zt([...Array.isArray(Ie.trackedChangePositionAliases)?Ie.trackedChangePositionAliases:[],Ce]);const cr=new Set([Ce]);Ye&&(ze&&cr.add(ze),We&&cr.add(We)),q.value.forEach(jt=>{if(jt===Ie||!so(jt,Y))return;const en={};for(const Xr of["trackedChangeThreadParentId","trackedChangeParentId","threadingParentCommentId","parentCommentId"])cr.has(It(jt?.[Xr]))&&(jt[Xr]=Ae,en[Xr]=Ae);Object.keys(en).length&&typeof jt.updateIdentityValues=="function"&&jt.updateIdentityValues(en)}),Object.keys(pt).length&&typeof Ie.updateIdentityValues=="function"&&Ie.updateIdentityValues(pt);const In=ut??[ne[Ce],ne[n(Ce)]].find(jt=>jt&&go(jt,Ie));if(In)for(const jt of[Ae,Gt])ne[jt]===void 0&&(ne[jt]=In,ie=!0);cr.has(It(R.value))&&(R.value=Ae),cr.has(It(F.value))&&(F.value=Ae)}ie&&(oe.value={...ne})},uc=({superdoc:k,comment:M,decidedId:Y,decidedIds:ne,documentId:ie}={})=>{const fe=new Set((Array.isArray(ne)||ne instanceof Set?Array.from(ne):[Y]).map(We=>It(We)).filter(Boolean)),le=It(ie);if(!fe.size||!le)return{removed:!1,removedIds:new Set};const ce=new Set;let Ce=!1;const Ae=M?q.value.indexOf(M):-1,Ie=M?.trackedChange?ns(M):new Set;if(Ae>=0&&so(M,le)&&Array.from(Ie).some(We=>fe.has(We))?(Ie.forEach(We=>ce.add(We)),q.value.splice(Ae,1),Ce=!0):q.value=q.value.filter(We=>{if(!We?.trackedChange||!so(We,le))return!0;const ut=ns(We);return Array.from(ut).some(Ye=>fe.has(Ye))?(Ce=!0,ut.forEach(Ye=>ce.add(Ye)),!1):!0}),!Ce)return{removed:!1,removedIds:ce};const ze=R.value!=null?String(R.value):null;return ze&&ce.has(ze)&&Gr(),{removed:!0,removedIds:ce}},Wf=({adapter:k,documentId:M}={})=>{const Y=It(M);if(!k||!Y)return{removed:0,removedIds:new Set};Xt(k);const ne=new Set,ie=It(R.value);let fe=!1;const le=q.value.filter(Ce=>{if(!Ce?.trackedChange||!so(Ce,Y))return!0;const Ae=ns(Ce);return Ae.forEach(Ie=>ne.add(Ie)),ie&&Ae.has(ie)&&(fe=!0),!1}),ce=q.value.length-le.length;return ce>0&&(q.value=le),fe&&Gr(),{removed:ce,removedIds:ne}},Bu=(k,M)=>{if(!(!M||typeof k?.clearActiveTrackedChangeTargetIfMatches!="function"))try{k.clearActiveTrackedChangeTargetIfMatches(M)}catch{}},dc=async({superdoc:k,receipt:M}={})=>{const Y=k?.activeEditor?.documentMutationReadiness;if(!(M?.success!==!0||typeof M?.txId!="string"||!M.txId||typeof Y?.whenPainted!="function"))try{await Y.whenPainted(M);const ne=globalThis.requestAnimationFrame;typeof ne=="function"&&await new Promise(ie=>{let fe=!1;const le=()=>{fe||(fe=!0,clearTimeout(ce),ie())},ce=setTimeout(le,250);ne(()=>ne(()=>setTimeout(le,0)))})}catch{}},yl=({superdoc:k,comment:M,decision:Y})=>{if(d())return{ok:!1,reason:"read-only-document"};if(!M?.trackedChange)return{ok:!1};const ne=Ft(k);if(ne){if(Y!=="accept"&&Y!=="reject")return Promise.resolve({ok:!1,reason:"decision-invalid"});const Ie=M?.trackedChangeCanonicalId!=null?String(M.trackedChangeCanonicalId):M?.commentId!=null?String(M.commentId):M?.trackedChangeAnchorKey?.startsWith?.("tc::body::")?M.trackedChangeAnchorKey.slice(10):null,ze=Ie!=null&&String(R.value??"")===Ie;return ys("store.trackedChanges.sidebarDecision","command",{decision:Y,decidedId:Ie},()=>(async()=>{try{return await(Y==="accept"?ne.accept(M):ne.reject(M))}catch(We){return{ok:!1,reason:"adapter-threw",detail:We?.message??String(We)}}})().then(async We=>{if(!ci(ne))return{ok:!1,reason:"adapter-stale"};if(!We?.ok)return{ok:!1,reason:We?.reason,detail:We?.detail};const ut=cc(We),Ye=We?.documentId??ne.documentId??k?.activeEditor?.documentId??k?.activeEditor?.options?.documentId??null,pt=async()=>{let et;try{et=await ne.listTrackedChanges({mode:"all",refreshReason:"post-decision-blocking",blocking:!0})}catch(kt){return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:kt?.message??String(kt)}}if(!ci(ne))return{ok:!1,committed:!0,reason:"adapter-stale"};if(!et?.ok)return{ok:!1,committed:!0,reason:"relist-after-commit-failed",detail:et?.reason??et?.detail??null};lc({superdoc:k,comment:M,decision:Y}),Fu({comment:M,decision:Y}),rs({superdoc:k,adapter:ne,documentId:Ye,items:et.items??[],pruneStale:et.complete===!0&&et.sourceCoverageComplete===!0});const At=new Set((et.items??[]).map(kt=>kt&&kt.id!=null?String(kt.id):null).filter(Boolean));Ie!=null&&At.has(Ie)||(ze&&Gr(),Bu(ne,Ie));const Gt=be(k);if(Gt&&typeof Gt.refresh=="function"&&Mo(Gt)){let kt;try{kt=await Gt.refresh()}catch(cr){return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:cr?.message??String(cr)}}if(!Mo(Gt))return{ok:!1,committed:!0,reason:"comments-adapter-stale"};if(!kt?.ok)return{ok:!1,committed:!0,reason:"comments-relist-after-tracked-decision-failed",detail:kt?.reason??kt?.detail??null};ui({superdoc:k,adapter:Gt,documentId:Gt.documentId??Ye,items:kt.items??[]})}return{ok:!0,success:!0}};return!ut.size||!Ye?pt():(ut.forEach(et=>Bu(ne,et)),await dc({superdoc:k,receipt:We.receipt}),lc({superdoc:k,comment:M,decision:Y}),Fu({comment:M,decision:Y}),uc({superdoc:k,comment:M,decidedIds:ut,documentId:Ye}),ze&&Gr(),{ok:!0,success:!0})}))}const ie=k?.activeEditor;if(!ie)return{ok:!1};const fe=M.commentId??M.importedId;if(!fe)return{ok:!1};const le=M.trackedChangeStory??void 0,ce=typeof ie.doc=="object"?ie.doc:null;if(ce?.trackChanges?.decide)try{const Ie=le?{id:fe,story:le}:{id:fe};return Promise.resolve(ce.trackChanges.decide({decision:Y,target:Ie})).then(ze=>({ok:!0,success:!!ze?.success}))}catch(Ie){if(le)return{ok:!1,error:Ie}}const Ce=Y==="accept"?"acceptTrackedChangeById":"rejectTrackedChangeById",Ae=ie.commands?.[Ce];return typeof Ae!="function"?{ok:!1}:{ok:!0,success:!!Ae(fe)}},fc=async({superdoc:k,adapter:M,documentId:Y,trackedChangesListMode:ne="all",refreshReason:ie,blocking:fe,isCurrent:le,targetIds:ce,reconciliationBatchSize:Ce=n0,signal:Ae,hydrationGeneration:Ie}={})=>ys("store.trackedChanges.hydrateFromV2","tracked-change-list",{documentId:Y??null,trackedChangesListMode:ne,refreshReason:ie??null,blocking:fe??null},async()=>{const ze=M??Ft(k);if(!ze||typeof ze.listTrackedChanges!="function")return{ok:!1,reason:"adapter-missing"};const We=()=>le?.()!==!1&&ci(ze);if(!We())return{ok:!1,reason:"adapter-stale"};const ut=yt(ze),Ye=()=>We()&&!Ae?.aborted&&yt(ze)===ut;if(Ae?.aborted)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!1};const pt=new Set,et=new Set;let At=0,Gt=0,kt;try{const en={mode:ne};Array.isArray(ce)&&(en.targetIds=ce),ie!=null&&(en.refreshReason=ie),typeof fe=="boolean"&&(en.blocking=fe),Ae&&(en.signal=Ae),typeof Ie=="number"&&(en.hydrationGeneration=Ie),ne==="background-reconcile"&&(en.shouldContinue=Ye,en.onPage=async Xr=>{if(!Ye())return;const Rr=Array.isArray(Xr?.items)?Xr.items:[];!rs({superdoc:k,adapter:ze,documentId:Y,items:Rr,pruneStale:!1,liveIds:pt,liveAnchorKeys:et,hydrationGeneration:Ie})||!Ye()||(At+=1,Gt+=Rr.length)}),kt=await ze.listTrackedChanges(en)}catch(en){return{ok:!1,reason:"adapter-threw",detail:en?.message??String(en)}}if(!We())return{ok:!1,reason:"adapter-stale"};if(yt(ze)!==ut)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0};if(Ae?.aborted)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0};if(!kt?.ok)return kt;const cr=ne==="startup-page"||ne==="interaction-prime"||ne==="visible-window",In=ne==="visible-window"&&Array.isArray(ce)&&(!Array.isArray(kt.visibleTrackedChangeFailedIds)||kt.visibleTrackedChangeFailedIds.length===0)||!cr&&kt.visibleWindowSource==null&&kt.complete===!0&&kt.sourceCoverageComplete===!0;if(Ae?.aborted||yt(ze)!==ut)return{ok:!1,reason:"review-hydration-superseded",lateResultDropped:!0};if(ne==="background-reconcile")if(At>0){if(!Ye())return{ok:!1,reason:"reconciliation-stale"};const en=Y??ze.documentId??k?.activeEditor?.documentId??null;In&&en&&ys("store.trackedChanges.reconcile.finalPrune","store-reconciliation",{documentId:en,liveIds:pt.size,liveAnchorKeys:et.size},()=>{Ye()&&Ls(pt,et,String(en),k,{broadcastChanges:!1})})}else{const en=await Kf({superdoc:k,adapter:ze,documentId:Y,items:kt.items??[],pruneStale:In,isCurrent:We,batchSize:Ce,hydrationGeneration:Ie});if(!en.ok)return en;Gt=en.appliedItems}else rs({superdoc:k,adapter:ze,documentId:Y,items:kt.items??[],pruneStale:In,hydrationGeneration:Ie});const jt={ok:!0,items:kt.items??[],reconciled:!0,...typeof Ie=="number"?{hydrationGeneration:Ie}:{}};typeof kt.complete=="boolean"&&(jt.complete=kt.complete),typeof kt.sourceCoverageComplete=="boolean"&&(jt.sourceCoverageComplete=kt.sourceCoverageComplete),kt.visibleWindowSource!=null&&(jt.visibleWindowSource=kt.visibleWindowSource),kt.visibleWindowFallbackReason!=null&&(jt.visibleWindowFallbackReason=kt.visibleWindowFallbackReason),typeof kt.visibleTrackedChangeExpectedRows=="number"&&(jt.visibleTrackedChangeExpectedRows=kt.visibleTrackedChangeExpectedRows),typeof kt.visibleTrackedChangeObservedRows=="number"&&(jt.visibleTrackedChangeObservedRows=kt.visibleTrackedChangeObservedRows);for(const en of["visibleTrackedChangeRequestedIds","visibleTrackedChangeSucceededIds","visibleTrackedChangeFailedIds"])Array.isArray(kt[en])&&(jt[en]=[...kt[en]]);return Array.isArray(kt.visibleWindowGetFailures)&&(jt.visibleWindowGetFailures=kt.visibleWindowGetFailures.map(en=>({...en}))),typeof kt.refreshReason=="string"&&(jt.refreshReason=kt.refreshReason),typeof kt.blocking=="boolean"&&(jt.blocking=kt.blocking),typeof kt.pageCount=="number"&&(jt.pageCount=kt.pageCount),typeof kt.pagesStarted=="number"&&(jt.pagesStarted=kt.pagesStarted),typeof kt.pagesCompleted=="number"&&(jt.pagesCompleted=kt.pagesCompleted),typeof kt.pagesSkippedAfterAbort=="number"&&(jt.pagesSkippedAfterAbort=kt.pagesSkippedAfterAbort),typeof kt.totalItems=="number"&&(jt.totalItems=kt.totalItems),typeof kt.coalesced=="boolean"&&(jt.coalesced=kt.coalesced),typeof kt.evaluatedRevision=="string"&&(jt.evaluatedRevision=kt.evaluatedRevision),ne==="background-reconcile"&&(jt.incrementalPagesApplied=At,jt.incrementalItemsApplied=Gt),jt}),Ia=async({superdoc:k,adapter:M,documentId:Y,upsertIds:ne=[],removedIds:ie=[],allResolved:fe}={})=>{const le=M??Ft(k);if(!le)return{ok:!1,reason:"adapter-missing"};if(!ci(le))return{ok:!1,reason:"adapter-stale"};const ce=Y??le.documentId??k?.activeEditor?.documentId??null;if(fe&&ce==null)return{ok:!1,reason:"document-id-missing"};if(fe)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[],allResolved:!0,removedRows:ys("store.trackedChanges.allResolved","store-reconciliation",{documentId:String(ce),logicalTargetCount:fe.logicalTargetCount??null,physicalCarrierCount:fe.physicalCarrierCount??null},()=>Wf({adapter:le,documentId:ce})).removed};const Ce=yt(le),Ae=new Set(Array.from(ie??[]).map(et=>It(et)).filter(Boolean)),Ie=[...new Set(Array.from(ne??[]).map(et=>It(et)).filter(Boolean))];if(Ae.size>0&&Ie.length===0&&ce!=null&&uc({superdoc:k,decidedIds:Ae,documentId:ce}),Ie.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};if(typeof le.getTrackedChange!="function")return{ok:!1,reason:"adapter-get-missing"};const ze=await Promise.all(Ie.map(async et=>{try{return{id:et,result:await le.getTrackedChange(et)}}catch(At){return{id:et,result:{ok:!1,reason:"adapter-threw",detail:At?.message??String(At)}}}}));if(!ci(le))return{ok:!1,reason:"adapter-stale"};if(yt(le)!==Ce)return{ok:!1,reason:"generation-stale"};const We=[],ut=[],Ye=[];for(const{id:et,result:At}of ze){const Gt=(At?.ok&&Array.isArray(At.items)?At.items:[]).filter(kt=>Lt(kt).has(et));Gt.length>0?(We.push(et),Ye.push(...Gt)):ut.push(et)}const pt=An(Ye);return Ye.length>0&&rs({superdoc:k,adapter:le,documentId:ce,items:pt,pruneStale:!1}),{ok:ut.length===0,items:pt,resolvedIds:We,unresolvedIds:ut,failures:ze.map(({result:et})=>et).filter(et=>!et?.ok)}},zu=k=>{const M=new Map,Y=new Set;let ne=0,ie=0;const fe=(ce,Ce,Ae)=>{const Ie=It(Ce);if(!Ie)return;const ze=ce.get(Ie)??new Set;ze.add(Ae),ce.set(Ie,ze)},le=ce=>{ce?.trackedChange&&(k&&!so(ce,k)||(Y.add(ce),fe(M,ce.commentId,ce),fe(M,ce.importedId,ce),fe(M,ce.trackedChangeCanonicalId,ce),fe(M,ce.trackedChangeAnchorKey,ce),ft(ce).forEach(Ce=>fe(M,Ce,ce))))};return q.value.forEach(le),{add:le,work:()=>({trackedRowsIndexed:Y.size,invalidatedIdMembershipChecks:0,incomingAliasLookups:ne,candidateVisits:ie}),candidates({changeId:ce,importedId:Ce,anchorKey:Ae,canonicalId:Ie,positionAliases:ze=[]}={}){const We=new Set,ut=Ye=>{const pt=It(Ye);if(!pt)return;ne+=1;const et=M.get(pt);et&&(ie+=et.size,et.forEach(At=>We.add(At)))};return new Set([ce,Ce,Ie,Ae,...ze]).forEach(ut),We}}},rs=({superdoc:k,adapter:M,documentId:Y,items:ne,pruneStale:ie=!0,preparedParams:fe=null,liveIds:le=null,liveAnchorKeys:ce=null,hydrationGeneration:Ce}={})=>ys("store.trackedChanges.reconcile","store-reconciliation",{documentId:Y??null,itemCount:Array.isArray(ne)?ne.length:null,pruneStale:ie,hydrationGeneration:Ce??null},()=>{if(!M||!Array.isArray(ne)||!ci(M))return;const Ae=Y??M.documentId??k?.activeEditor?.documentId??null,Ie=ce instanceof Set?ce:new Set,ze=le instanceof Set?le:new Set;let We=0;const ut=zu(Ae==null?null:String(Ae)),Ye=Jy("store.trackedChanges.batchIdentity","store-reconciliation",{itemCount:ne.length}),pt=Array.isArray(fe)?fe:ne.map(et=>M.mapV2TrackedChangeToCommentParams(et));try{for(const et of pt)if(et){if(et.event==="omit"){et.changeId!=null&&ze.add(String(et.changeId));continue}Ae&&et.documentId==null&&(et.documentId=Ae),et.changeId!=null&&ze.add(String(et.changeId)),et.trackedChangeAnchorKey!=null&&Ie.add(String(et.trackedChangeAnchorKey)),To({superdoc:k,params:et,broadcastChanges:!1,trackedChangeIdentityIndex:ut}),We+=1}}finally{cu(Ye,ut.work())}return!Ae||!ie?{liveIds:ze,liveAnchorKeys:Ie,appliedCount:We}:(Ls(ze,Ie,String(Ae),k,{broadcastChanges:!1}),{liveIds:ze,liveAnchorKeys:Ie,appliedCount:We})}),Kf=async({superdoc:k,adapter:M,documentId:Y,items:ne,pruneStale:ie,isCurrent:fe,batchSize:le=n0,hydrationGeneration:ce}={})=>{if(!M||!Array.isArray(ne))return{ok:!1,reason:"reconcile-input-invalid"};const Ce=()=>fe?.()!==!1&&ci(M);if(!Ce())return{ok:!1,reason:"reconciliation-stale"};const Ae=Math.max(1,Math.floor(Number(le)||n0)),Ie=Y??M.documentId??k?.activeEditor?.documentId??null,ze=new Set,We=new Set;let ut=0,Ye=0;for(let pt=0;pt<ne.length;pt+=Ae){if(!Ce())return{ok:!1,reason:"reconciliation-stale",appliedItems:ut,batchCount:Ye};const et=ne.slice(pt,pt+Ae);if(!rs({superdoc:k,adapter:M,documentId:Ie,items:et,pruneStale:!1,liveIds:ze,liveAnchorKeys:We,hydrationGeneration:ce})||!Ce())return{ok:!1,reason:"reconciliation-stale",appliedItems:ut,batchCount:Ye};ut+=et.length,Ye+=1,pt+Ae<ne.length&&await U8()}return Ce()?ie&&Ie&&(ys("store.trackedChanges.reconcile.finalPrune","store-reconciliation",{documentId:Ie,liveIds:ze.size,liveAnchorKeys:We.size},()=>{Ce()&&Ls(ze,We,String(Ie),k,{broadcastChanges:!1})}),!Ce())?{ok:!1,reason:"reconciliation-stale",appliedItems:ut,batchCount:Ye}:{ok:!0,appliedItems:ut,batchCount:Ye,pruned:!!(ie&&Ie)}:{ok:!1,reason:"reconciliation-stale",appliedItems:ut,batchCount:Ye}},Yr=(k=null)=>{const M=k==null?null:String(k);return q.value.filter(Y=>{if(Y?.trackedChange!==!0)return!1;if(M==null)return!0;const ne=Y?.documentId??Y?.fileId??null;return ne!=null&&String(ne)===M}).length},Vu=({superdoc:k,editor:M,broadcastChanges:Y=!0})=>{if(!k||!M)return;const ne=M?.options?.documentId!=null?String(M.options.documentId):null;if(!ne)return;const ie=Ts(M);if(!ie)return;const fe=ie.trackedChanges,le=new Set;fe.forEach(Ae=>{const Ie=Ae?.mark?.attrs?.id;Ie!=null&&le.add(String(Ie))});const ce=ie.storySnapshots,Ce=new Set(ce.map(Ae=>Ae?.anchorKey).filter(Ae=>typeof Ae=="string"&&Ae.length>0));Ls(le,Ce,ne,k,{broadcastChanges:Y}),Pu(M,k,fe,{reopenResolved:!0,refreshExisting:!0,broadcastChanges:Y,editorState:ie.state,editorView:ie.view}),ju({superdoc:k,editor:M,broadcastChanges:Y,snapshots:ce,documentState:ie.state}),_i({superdoc:k,editor:M,broadcastChanges:Y,structuralChanges:ie.structuralChanges}),ts({superdoc:k,editor:M,documentId:ne,refreshReason:"sync-authoritative"})},_i=({superdoc:k,editor:M,broadcastChanges:Y=!0,structuralChanges:ne=null})=>{const ie=M?.options?.documentId!=null?String(M.options.documentId):null;if(!ie)return;const fe=ua?.enumerateStructuralRowChanges;if(typeof fe!="function")return;let le=ne;if(!Array.isArray(le)){const ce=qo(M);if(!ce)return;try{le=fe(ce.state)??[]}catch{le=[]}}for(const ce of le){if(!ce?.decidable||!ce?.wholeTable)continue;const Ce=i(ce);if(!Ce)continue;const Ae=n(Ce),Ie=ce.subtype==="table-insert"?"tableInsert":"tableDelete",ze=ce.side==="insertion"?"trackInsert":"trackDelete",We=String(Ce),ut=Ae!=null?String(Ae):null,Ye={event:q.value.find(pt=>{if(!pt?.trackedChange||!so(pt,ie))return!1;const et=pt.trackedChangeAnchorKey!=null?String(pt.trackedChangeAnchorKey):null;if(ut&&et)return et===ut;const At=pt.commentId!=null?String(pt.commentId):null,Gt=pt.importedId!=null?String(pt.importedId):null;return At===We||Gt===We})?"update":"add",changeId:Ce,trackedChangeText:"",trackedChangeType:ze,trackedChangeDisplayType:Ie,deletedText:null,authorId:null,authorEmail:ce.authorEmail||null,authorImage:ce.authorImage||null,date:ce.date||null,author:ce.author||null,importedAuthor:ce.importedAuthor?{name:ce.importedAuthor}:null,semanticColorKey:ce.semanticColorKey??null,semanticColor:ce.semanticColor??null,documentId:ie,coords:null,trackedChangeStory:e,trackedChangeStoryKind:"body",trackedChangeStoryLabel:"",trackedChangeAnchorKey:Ae};To({superdoc:k,params:Ye,broadcastChanges:Y})}},ju=({superdoc:k,editor:M,broadcastChanges:Y=!0,snapshots:ne=null,documentState:ie=void 0,resolveFromEditor:fe=!0})=>{const le=M?.options?.documentId!=null?String(M.options.documentId):null;if(!le)return;let ce=ne;if(!Array.isArray(ce)){if(typeof uu!="function"||!qo(M))return;let Ce=null;try{Ce=uu(M)}catch{return}if(!Ce)return;try{ce=Ce.getAll()}catch{return}}for(const Ce of ce)Ce.storyKind!=="body"&&pc({superdoc:k,editor:M,snapshot:Ce,documentId:le,broadcastChanges:Y,documentState:ie,resolveFromEditor:fe})},qf=k=>k?.type!=="structural"?k?.type??null:k?.subtype==="table-delete"?"tableDelete":"tableInsert",Ea=k=>k?.type!=="structural"?k?.type??null:k?.subtype==="table-delete"?"trackDelete":"trackInsert",hc=k=>k?k.type==="delete"?!0:k.type==="structural"&&k.subtype==="table-delete":!1,Yf=({editor:k,snapshot:M,documentId:Y,event:ne,resolveFromEditor:ie=!0})=>{const fe=Ea(M),le=qf(M),ce={event:ne,changeId:M.runtimeRef.rawId,trackedChangeText:hc(M)?"":M.excerpt??"",trackedChangeType:fe,trackedChangeDisplayType:le,semanticColorKey:M.semanticColorKey??null,semanticColor:M.semanticColor??null,deletedText:hc(M)?M.excerpt??"":null,authorId:M.authorId,authorEmail:M.authorEmail,authorImage:M.authorImage,date:M.date,author:M.author,documentId:Y,coords:null,trackedChangeStory:M.story,trackedChangeStoryKind:M.storyKind,trackedChangeStoryLabel:M.storyLabel,trackedChangeAnchorKey:M.anchorKey};if(!ie||typeof ck!="function")return ce;let Ce=null;try{Ce=ck(k,{kind:"entity",entityType:"trackedChange",entityId:M.runtimeRef.rawId,story:M.story})}catch{Ce=null}const Ae=Ce?.editor?.state??null;if(!Ae)return ce;let Ie=[];try{Ie=ua.getTrackChanges(Ae,Ce.change.rawId)??[]}catch{Ie=[]}const ze=ai(Ie),We=e0({event:ne,marks:ze,nodes:[],newEditorState:Ae,documentId:Y,trackedChangesForId:Ie});return We?(We.semanticColorKey==null&&M.semanticColorKey!=null&&(We.semanticColorKey=M.semanticColorKey),We.semanticColor==null&&M.semanticColor!=null&&(We.semanticColor=M.semanticColor),We.trackedChangeStory=M.story,We.trackedChangeStoryKind=M.storyKind,We.trackedChangeStoryLabel=M.storyLabel,We.trackedChangeAnchorKey=M.anchorKey,We):ce},pc=({superdoc:k,editor:M,snapshot:Y,documentId:ne,broadcastChanges:ie,documentState:fe,resolveFromEditor:le})=>{if(!Y?.runtimeRef?.rawId)return;const ce=q.value.find(Ae=>{if(!Ae?.trackedChange)return!1;const Ie=Ae.trackedChangeAnchorKey!=null?String(Ae.trackedChangeAnchorKey):null;return Ie&&Y.anchorKey?Ie===Y.anchorKey:Ie||Y.anchorKey?!1:Ae.commentId===Y.runtimeRef.rawId||Ae.importedId===Y.runtimeRef.rawId}),Ce=Yf({editor:M,snapshot:Y,documentId:ne,event:ce?"update":"add",resolveFromEditor:le});To({superdoc:k,params:Ce,broadcastChanges:ie,documentState:fe}),ce&&(ce.trackedChangeStory=Y.story,ce.trackedChangeStoryKind=Y.storyKind,ce.trackedChangeStoryLabel=Y.storyLabel,ce.trackedChangeAnchorKey=Y.anchorKey)},Ta=k=>k?(Array.isArray(k)?k:[k]).filter(Boolean):[],Uu=()=>{const k=[];return q.value.forEach(M=>{const Y=M.getValues(),ne=Y.commentText,ie=Ta(Y.docxCommentJSON),fe=ie.length?ie:bl(ne);k.push({...Y,commentJSON:fe})}),k},bl=k=>{const M=new ak({mode:"text",isHeadless:!0,content:k,extensions:lk()}).getJSON();return Array.isArray(M?.content)?M.content.filter(Boolean):[]},Ps=(k,M={})=>{if(k==null)return;const Y=M?.retainMissingTrackedChangeGeometry===!0,ne=Y&&M?.retainedTrackedChangeIds!=null?new Set(Array.from(M.retainedTrackedChangeIds,Ce=>It(Ce)).filter(Boolean)):null,ie=oe.value||{},fe={};Object.entries(k).forEach(([Ce,Ae])=>{fe[Ce]=Ae;const Ie=Ae?.kind==="trackedChange"&&Ae?.storyKey==="body"&&Ae?.threadId!=null?String(Ae.threadId):null;Ie&&fe[Ie]===void 0&&(fe[Ie]=Ae);const ze=typeof Ae?.key=="string"?Ae.key:null;ze&&fe[ze]===void 0&&(fe[ze]=Ae)});const le=(Ce,Ae)=>{for(const Ie of ft(Ce)){const ze=Ae[Ie];if(ze!==void 0&&go(ze,Ce))return ze}return null},ce=(Ce,Ae,Ie=[])=>{const ze=[...ft(Ae),...Ie.map(We=>It(We)).filter(Boolean)];for(const We of new Set(ze))fe[We]===void 0&&(fe[We]=Ce)};q.value.forEach(Ce=>{if(!Ce?.trackedChange||Ce.resolvedTime)return;const Ae=le(Ce,fe);if(Ae){ce(Ae,Ce);return}if(!Y||ne&&!ft(Ce).some(ze=>ne.has(ze)))return;const Ie=le(Ce,ie);Ie&&ce(Ie,Ce,[Ie.key,Ie.threadId])}),oe.value=fe},xa=()=>{oe.value={}},mc=k=>{if(!k?.trackedChange)return!1;const M=k?.trackedChangeDisplayType;return M==="tableInsert"||M==="tableDelete"?!0:[k?.commentId,k?.importedId,k?.trackedChangeAnchorKey].map(Y=>Y!=null?String(Y):"").filter(Boolean).some(Y=>Y.includes("word:structural:"))},Hu=new WeakMap,gc=k=>{if(!k)return{ranges:[],ids:new Set};const M=Hu.get(k);if(M)return M;const Y=[],ne=new Set,ie=ce=>{ce!=null&&ce!==""&&ne.add(String(ce))},fe=ua?.enumerateStructuralRowChanges;if(typeof fe=="function"){let ce=[];try{ce=fe(k)??[]}catch{ce=[]}for(const Ce of ce){if(!Ce?.decidable||!Ce?.wholeTable)continue;const Ae=Number(Ce.tableFrom),Ie=Number(Ce.tableTo);Number.isFinite(Ae)&&Number.isFinite(Ie)&&Y.push({from:Ae,to:Ie}),ie(Ce.id),ie(Ce.revisionId),ie(Ce.revisionGroupId),ie(Ce.sourceId);for(const ze of Ce.rows||[]){const We=ze?.node?.attrs?.trackChange;ie(We?.id),ie(We?.sourceId)}}}const le={ranges:Y,ids:ne};return Hu.set(k,le),le},vc=k=>{const M=s.getDocument(k)?.getEditor?.();return gc(M?.state).ranges},Xf=(k,M)=>!M?.length||!k?.length?!1:k.every(Y=>{const ne=Number(Y?.from),ie=Number(Y?.to);return!Number.isFinite(ne)||!Number.isFinite(ie)?!1:M.some(fe=>ne>=fe.from&&ie<=fe.to)}),wl=k=>{if(!k?.trackedChange||mc(k))return!1;const M=vc(k?.fileId);if(!M.length)return!1;const Y=Pt(k).entry,ne=lr(Y);return ne?M.some(ie=>ne.start>=ie.from&&ne.end<=ie.to):!1},Cl=Ee(()=>oo.value?.parentComments.filter(k=>!k.resolvedTime).filter(k=>!Io(k)||Eo(k)?!0:!!Pt(k).entry).filter(k=>!wl(k))),$u=Ee(()=>Cl.value.flatMap(k=>{const{key:M,entry:Y}=Pt(k);return w8({comment:k,positionKey:M,positionEntry:Y,fallbackId:It(k?.commentId)??ft(k)[0]??null})})),Gu=k=>k==null?null:String(k),Ds=(k=null)=>{F.value=Gu(k)},Gr=()=>{R.value=null,Ds(null)},Wu=(k,M)=>k==null||M==null?!1:$u.value.some(Y=>String(Y.id)===String(k)&&String(Y.comment?.commentId??Y.threadId??"")===String(M)),Ra=k=>{Wu(F.value,k)||Ds(null)};function Ku(){const k=It(R.value);if(!k)return!1;const M=Pn(k),Y=It(M?.commentId);return!Y||Y===k?!1:(R.value=Y,Ra(Y),!0)}const qu=({documentMode:k,commentsVisible:M,trackChangesVisible:Y}={})=>{typeof k=="string"&&(h.documentMode=k),typeof M=="boolean"&&(h.commentsVisible=M),typeof Y=="boolean"&&(h.trackChangesVisible=Y)},kl=k=>{if(Array.isArray(k))return k.map(le=>kl(le)).flat().filter(Boolean);if(!k||typeof k!="object")return k;const M=le=>{if(!le)return le;const ce={...le};return delete ce.fontSize,delete ce.fontFamily,delete ce.eastAsiaFontFamily,Object.keys(ce).length?ce:void 0},Y=le=>{if(!le)return le;const ce=typeof le.type=="string"?le.type:le.type?.name,Ce=le?.attrs?{...le.attrs}:void 0;return ce==="textStyle"&&Ce?{...le,attrs:M(Ce)}:{...le,attrs:Ce}},ne=le=>Array.isArray(le)?le.filter(Boolean).map(ce=>Y(ce)):void 0,ie=le=>le&&typeof le=="object"?{...le}:void 0;if(!Array.isArray(k.content))return{type:k.type,...k.text!==void 0?{text:k.text}:{},...k.attrs?{attrs:ie(k.attrs)}:{},...k.marks?{marks:ne(k.marks)}:{}};const fe=k.content.map(le=>kl(le)).flat().filter(Boolean);return k.type==="run"?fe:{type:k.type,...k.attrs?{attrs:ie(k.attrs)}:{},...k.marks?{marks:ne(k.marks)}:{},content:fe}},Zf=k=>{const M=Array.isArray(k)?k:k?[k]:[];if(M.some(Y=>Y?.content?.length))try{const Y=kl(M),ne=Array.isArray(Y)?Y:Y?[Y]:[];return ne.length?new ak({mode:"text",isHeadless:!0,content:{type:"doc",content:ne},loadFromSchema:!0,extensions:lk()}).getHTML():null}catch(Y){console.warn("Failed to convert comment",Y);return}};return{COMMENT_EVENTS:w,isDebugging:g,hasInitializedComments:x,hasSyncedCollaborationComments:L,editingCommentId:Z,activeComment:R,activeFloatingCommentInstanceId:F,commentDialogs:O,overlappingComments:N,overlappedIds:T,suppressInternalExternal:B,pendingComment:D,currentCommentText:Q,commentsList:q,isCommentsListVisible:me,generalCommentIds:tt,editorCommentIds:_e,commentsParentElement:V,editorCommentPositions:oe,hasInitializedLocations:G,isCommentHighlighted:Me,floatingCommentsOffset:Ge,sortedConversations:lt,visibleConversations:Ct,skipSelectionUpdate:Re,isFloatingCommentsReady:Ke,instantSidebarAlignmentTargetY:ee,instantSidebarAlignmentThreadId:_,instantSidebarAlignmentInstanceId:te,getConfig:vo,documentsWithConverations:es,getGroupedComments:oo,hasOpenTrackedChanges:io,getCommentsByPosition:Si,getFloatingComments:Cl,getFloatingCommentInstances:$u,getCommentAliasIds:ft,getTrackedChangeThread:Ne,getCommentPositionKey:wt,getCommentPosition:Jt,getCommentAnchoredText:Un,getCommentAnchorData:ro,resolveCommentPositionEntry:Pt,getCommentDocumentId:Ms,belongsToDocument:Aa,viewingVisibility:h,isViewingMode:$,shouldRenderReviewInViewing:H,init:mn,setViewingVisibility:qu,getComment:Pn,setActiveComment:pl,getCommentLocation:Ho,hasOverlapId:Uo,getPendingComment:Br,showAddComment:_r,addComment:xu,addHydratedComment:li,cancelComment:wr,deleteComment:Ni,removePendingComment:Fi,cancelImportedTrackedChangeBootstrap:zi,removeCommentsForDocument:xs,processLoadedDocxComments:Rs,translateCommentsForExport:Uu,handleEditorLocationsUpdate:Ps,clearEditorCommentPositions:xa,handleTrackedChangeUpdate:To,refreshTrackedChangeCommentsByIds:ke,syncResolvedCommentsWithDocument:Fn,syncTrackedChangePositionsWithDocument:ki,setActiveFloatingCommentInstance:Ds,requestInstantSidebarAlignment:He,peekInstantSidebarAlignment:Et,clearInstantSidebarAlignment:st,syncTrackedChangeComments:Vu,decideTrackedChangeFromSidebar:yl,v2CommentsAdapter:J,setV2CommentsAdapter:ge,getV2CommentsAdapter:be,hydrateCommentsFromV2:Mu,applyReviewSnapshotFromV2:Ru,supersedeV2ReviewHydration:Ut,reconcileCommentsFromV2:ui,isV2EditorActive:Be,replyCommentV2:Uf,editCommentV2:ml,resolveCommentV2:Hf,reopenCommentV2:rc,v2TrackedChangesAdapter:Ze,setV2TrackedChangesAdapter:xt,getV2TrackedChangesAdapter:Ft,getV2TrackedChangeRowCount:Yr,hydrateTrackedChangesFromV2:fc,reconcileTrackedChangeMutationFromV2:Ia,reconcileTrackedChangesFromV2:rs,remapTrackedChangeIdentities:Nu}}),dk='<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>',fk='<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>',q8='<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>',Y8='<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>',o0='<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>',hk='<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>',pk='<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>',mk='<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>',fa={comment:dk,caretDown:fk,internal:q8,external:Y8,markDone:o0,acceptChange:o0,rejectChange:hk,overflow:pk,reopen:mk},X8=.38,Z8=".superdoc-comment-highlight",Q8=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},J8=e=>e?e.split(",").map(t=>t.trim()).filter(Boolean):[],e7=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},t7=()=>Math.round(window.innerHeight*X8),gk=(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},n7=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(Z8);for(const o of r){const i=new Set([...J8(o.getAttribute("data-comment-ids")),...e7(o.getAttribute("data-comment-imported-ids"))]);if(![...t].some(a=>i.has(a))||!Q8(o))continue;const s=o.getBoundingClientRect().top;Number.isFinite(s)&&(n=n==null?s:Math.min(n,s))}return n},r7=(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)};Dt();var o7="Arial, Helvetica, sans-serif";function i0(){const e=vr();return{uiFontFamily:Ee(()=>{const t=e?.proxy?.$superdoc?.config?.uiDisplayFallbackFont;return typeof t=="string"&&t.trim()?t.trim():o7})}}var pn,bn=Dr((()=>{pn=(e,t)=>{const n=e.__vccOpts||e;for(const[r,o]of t)n[r]=o;return n}}));Dt(),bn();var i7={class:"comments-dropdown"},s7=["onClick"],a7={key:0,class:"comments-dropdown__option-icon"},l7=["innerHTML"],c7={class:"comments-dropdown__option-label"},u7={__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=re(!1),i=re(null),s=re(null),a=re({top:"0px",left:"0px"}),l=Ee(()=>({...n.contentStyle,position:"fixed",top:a.value.top,left:a.value.left,zIndex:1200})),c=w=>{n.disabled&&w||(o.value=w)},u=()=>{n.disabled||c(!o.value)},d=()=>{o.value&&c(!1)},h=()=>{if(!i.value)return;const w=i.value.getBoundingClientRect(),x=s.value?.offsetWidth??0,L=window.innerWidth||document.documentElement.clientWidth||0,V=8;let G=w.left;const R=Math.max(V,L-x-V);G=Math.min(Math.max(V,G),R),a.value={top:`${w.bottom+4}px`,left:`${G}px`}},g=w=>{w.stopPropagation(),u()},p=w=>{w?.disabled||(r("select",w?.key,w),d())},v=w=>!!w?.iconString||!!w?.icon,S=w=>w?.iconString?w.iconString:typeof w?.icon=="function"?w.icon(w):w?.icon||null,C=Ml({name:"CommentsDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(w){return()=>S(w.option)}}),A=w=>{if(!o.value)return;const x=w.target;if(!(x instanceof Element))return;const L=i.value?.contains(x),V=s.value?.contains(x);L||V||d()},y=w=>{w.key==="Escape"&&d()};return Vt(o,async w=>{w&&(await Tt(),h())}),Vt(o,w=>{w?(document.addEventListener("pointerdown",A,!0),document.addEventListener("keydown",y,!0),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0)):(document.removeEventListener("pointerdown",A,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0))}),gr(()=>{document.removeEventListener("pointerdown",A,!0),document.removeEventListener("keydown",y,!0),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0)}),(w,x)=>(ve(),Te("div",i7,[Fe("div",{ref_key:"triggerRef",ref:i,class:"comments-dropdown__trigger",onClick:g},[Td(w.$slots,"default",{},void 0,!0)],512),(ve(),hn(Ha,{to:"body"},[o.value?(ve(),Te("div",{key:0,ref_key:"menuRef",ref:s,class:"comments-dropdown__menu",style:Sn(l.value)},[(ve(!0),Te(Yt,null,mr(e.options,L=>(ve(),Te("div",{key:L.key,class:on(["comments-dropdown__option",{"sd-disabled":L.disabled}]),onClick:V=>p(L)},[v(L)?(ve(),Te("span",a7,[L.iconString?(ve(),Te("span",{key:0,innerHTML:L.iconString},null,8,l7)):(ve(),hn(nt(C),{key:1,option:L},null,8,["option"]))])):vt("",!0),Fe("span",c7,Ht(L.label),1)],10,s7))),128))],4)):vt("",!0)]))]))}},vk=pn(u7,[["__scopeId","data-v-7eced80a"]]);Dt(),bn();var d7={class:"sd-comment-option"},f7=["innerHTML"],h7={class:"sd-option-state"},p7=["innerHTML"],m7={__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}=i0(),i=[{label:"Internal",key:"internal",iconString:fa.internal,backgroundColor:"var(--sd-ui-comments-internal-bg, #CDE6E6)"},{label:"External",key:"external",iconString:fa.external,backgroundColor:"var(--sd-ui-comments-external-bg, #F5CFDA)"}],s=Ee(()=>i.find(d=>d.key===c.value)?.label),a=Ee(()=>{if(!r.state)return{};const d=i.find(g=>g.key===c.value);if(!d)return{};const h={backgroundColor:d.backgroundColor};return r.isDisabled&&(h.opacity=.5,h.cursor="default"),h}),l=(d,h=!1)=>{c.value=d,u.value=i.find(g=>g.key===d)?.iconString,!h&&n("select",d)},c=re(r.state),u=re(null);return Vt(()=>r.state,d=>{l(d)}),Gn(()=>{l(r.state,!0)}),(d,h)=>(ve(),Te("div",{class:"sd-internal-dropdown",style:Sn(a.value),"data-sd-part":"dropdown-trigger"},[Kt(vk,{options:i,onSelect:h[0]||(h[0]=g=>l(g)),disabled:e.isDisabled,"content-style":{fontFamily:nt(o)}},{default:No(()=>[Fe("div",d7,[Fe("div",{class:"sd-active-icon",innerHTML:u.value},null,8,f7),Fe("div",h7,Ht(s.value),1),Fe("div",{class:"sd-dropdown-caret",innerHTML:nt(fa).caretDown},null,8,p7)])]),_:1},8,["disabled","content-style"])],4))}},yk=pn(m7,[["__scopeId","data-v-138d641e"]]);function g7(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}`}var po=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"}),Cr=Object.freeze({EDITOR:"editor",SUGGESTER:"suggester",VIEWER:"viewer"}),v7=Object.freeze({[po.RESOLVE_OWN]:{internal:[Cr.EDITOR],external:[Cr.EDITOR]},[po.RESOLVE_OTHER]:{internal:[Cr.EDITOR],external:[Cr.EDITOR]},[po.REJECT_OWN]:{internal:[Cr.EDITOR,Cr.SUGGESTER],external:[Cr.EDITOR,Cr.SUGGESTER]},[po.REJECT_OTHER]:{internal:[Cr.EDITOR],external:[Cr.EDITOR]},[po.COMMENTS_OVERFLOW_OWN]:{internal:[Cr.EDITOR,Cr.SUGGESTER],external:[Cr.EDITOR,Cr.SUGGESTER]},[po.COMMENTS_OVERFLOW_OTHER]:{internal:[Cr.EDITOR],external:[Cr.EDITOR]},[po.COMMENTS_DELETE_OWN]:{internal:[Cr.EDITOR,Cr.SUGGESTER],external:[Cr.EDITOR,Cr.SUGGESTER]},[po.COMMENTS_DELETE_OTHER]:{internal:[Cr.EDITOR],external:[Cr.EDITOR]},[po.UPLOAD_VERSION]:{internal:[Cr.EDITOR],external:[]},[po.VERSION_HISTORY]:{internal:[Cr.EDITOR],external:[]}}),y7=(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},b7=(e,t,n)=>{const r=n?"internal":"external";return v7[e]?.[r]?.includes(t)??!1},ha=(e,t,n,r={})=>{const o=b7(e,t,n),i=y7(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};Dt(),bn();var w7={class:"user-container"},C7=["src"],k7={key:1,class:"user-bg"},S7={__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)=>(ve(),Te("div",w7,[e.user.image?(ve(),Te("img",{key:0,class:"user-bg",src:e.user.image.startsWith("http")?e.user.image:`data:image/png;base64,${e.user.image}`},null,8,C7)):(ve(),Te("span",k7,Ht(t(e.user.name,e.user.email)),1))]))}},bk=pn(S7,[["__scopeId","data-v-c95b2073"]]);Dt(),bn();var _7={class:"card-section comment-header"},A7={class:"comment-header-left"},I7={class:"user-info"},E7={class:"user-name"},T7={key:0,class:"imported-tag"},x7={key:0,class:"user-timestamp"},R7=["data-disabled-reason","aria-disabled","innerHTML"],M7=["data-disabled-reason","aria-disabled","innerHTML"],L7=["data-disabled-reason","aria-disabled","innerHTML"],P7={class:"overflow-menu__icon"},D7=["innerHTML"],O7={__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=da(),o=e,{proxy:i}=vr(),s=i.$superdoc.config.role,a=i.$superdoc.config.isInternal,l=F=>{const Z=i.$superdoc.config.user,O={id:F?.creatorId,email:F?.creatorEmail};if(Ww({current:Z,other:O}))return!0;const N=Kd(Z),T=Kd(O);if(N.hasId||N.hasEmail||T.hasId||T.hasEmail||F?.origin!=null||F?.importedAuthor?.name)return!1;const B=Gw(Z?.name),Q=Gw(F?.creatorName);return!!(B&&Q&&B===Q)},c=Ee(()=>l(o.comment)),u=Ee(()=>Lp(o.comment)),{uiFontFamily:d}=i0(),h=Object.freeze({edit:{label:"Edit",key:"edit"},delete:{label:"Delete",key:"delete"}}),g=Ee(()=>o.config.readOnly!==!0),p=Ee(()=>!(!g.value||!o.comment||o.comment.resolvedTime||r.pendingComment||o.isPendingInput)),v=Ee(()=>{if(!p.value||!o.comment.trackedChange&&o.config.allowResolve===!1||o.comment.parentCommentId||u.value)return!1;const F={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return c.value||o.comment.trackedChange?ha(po.RESOLVE_OWN,s,a,F):ha(po.RESOLVE_OTHER,s,a,F)}),S=Ee(()=>{if(!p.value||!o.comment.trackedChange)return!1;const F={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return c.value||o.comment.trackedChange?ha(po.REJECT_OWN,s,a,F):ha(po.REJECT_OTHER,s,a,F)}),C=Ee(()=>{if(!g.value||o.config.allowResolve===!1||!o.reopenSupported||!o.comment||!o.comment.resolvedTime||r.pendingComment||o.isPendingInput||o.comment.parentCommentId||u.value||o.comment.trackedChange)return!1;const F={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return c.value?ha(po.RESOLVE_OWN,s,a,F):ha(po.RESOLVE_OTHER,s,a,F)}),A=Ee(()=>!(!p.value||o.comment.trackedChange||o.isPendingInput||y.value.length===0)),y=Ee(()=>{if(!g.value)return[];if(!p.value)return[];if(o.writeDisabledReason)return[];const F=[],Z=new Set;l(o.comment)&&Z.add("edit");const O=l(o.comment),N={comment:o.comment,currentUser:i.$superdoc.config.user,superdoc:i.$superdoc};return(O&&ha(po.COMMENTS_DELETE_OWN,s,a,N)||!O&&ha(po.COMMENTS_DELETE_OTHER,s,a,N))&&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"))},L=()=>{!g.value||o.config.allowResolve===!1||o.reopenDisabledReason||n("reopen")},V=F=>{g.value&&n("overflow-select",F)},G=Ee(()=>!(!(o.comment.origin!=null||o.comment.importedAuthor?.name)||l(o.comment))),R=Ee(()=>{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)=>(ve(),Te("div",_7,[Fe("div",A7,[Kt(bk,{user:R.value,class:"avatar"},null,8,["user"]),Fe("div",I7,[Fe("div",E7,[ji(Ht(R.value.name),1),G.value?(ve(),Te("span",T7,"IMPORTED")):vt("",!0)]),o.comment.createdTime?(ve(),Te("div",x7,Ht(nt(g7)(o.comment.createdTime)),1)):vt("",!0)])]),Fe("div",{class:on(["overflow-menu",{"is-visible":o.isActive}])},[v.value?(ve(),Te("div",{key:0,class:on(["overflow-menu__icon",{"sd-is-disabled":!!e.resolveDisabledReason}]),"data-comment-action":"resolve","data-disabled-reason":e.resolveDisabledReason||null,"aria-disabled":!!e.resolveDisabledReason,innerHTML:nt(fa).markDone,onClick:rn(w,["stop","prevent"])},null,10,R7)):vt("",!0),S.value?(ve(),Te("div",{key:1,class:on(["overflow-menu__icon",{"sd-is-disabled":!!e.rejectDisabledReason}]),"data-comment-action":"reject","data-disabled-reason":e.rejectDisabledReason||null,"aria-disabled":!!e.rejectDisabledReason,innerHTML:nt(fa).rejectChange,onClick:rn(x,["stop","prevent"])},null,10,M7)):vt("",!0),C.value?(ve(),Te("div",{key:2,class:on(["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:nt(fa).reopen,onClick:rn(L,["stop","prevent"])},null,10,L7)):vt("",!0),A.value?(ve(),hn(vk,{key:3,"data-comment-action":"overflow",options:y.value,onSelect:V,"content-style":{fontFamily:nt(d)}},{default:No(()=>[Fe("div",P7,[Fe("div",{class:"overflow-icon",innerHTML:nt(fa).overflow},null,8,D7)])]),_:1},8,["options","content-style"])):vt("",!0)],2)]))}},s0=pn(O7,[["__scopeId","data-v-ca6050aa"]]);Dt(),bn();var F7={class:"input-section"},a0=28,wk=132,N7={__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}=na(da()),i=re(null),s=p=>r("focus",p),a=()=>{i.value?.focus?.()},l=()=>{const p=i.value;if(!p)return;p.style.height=`${a0}px`;const v=p.scrollHeight||a0,S=Math.min(Math.max(v,a0),wk);p.style.height=`${S}px`,p.style.overflowY=v>wk?"auto":"hidden"},c=()=>{Tt(l)},u=p=>String(p??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),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 S=document.createElement("div");return S.innerHTML=v,S.innerText||S.textContent||""},h=p=>{const v=String(p??"").replace(/\r\n/g,`
14
- `).trim();return v?v.split(/\n{2,}/).map(S=>`<p>${u(S).replace(/\n/g,"<br>")}</p>`).join(""):"<p></p>"},g=Ee({get:()=>d(o.value),set:p=>{o.value=h(p)}});return Gn(c),Vt(o,c),t({focus:a}),(p,v)=>(ve(),Te("div",F7,[e.includeHeader?(ve(),hn(s0,{key:0,config:e.config,comment:e.comment,"is-pending-input":!0},null,8,["config","comment"])):vt("",!0),Fe("div",{class:on(["comment-entry",{"sd-input-active":e.isFocused}])},[Ks(Fe("textarea",{ref_key:"inputRef",ref:i,class:"superdoc-field",placeholder:"Add a comment","onUpdate:modelValue":v[0]||(v[0]=S=>g.value=S),rows:"1",onInput:l,onFocus:v[1]||(v[1]=S=>s(!0)),onBlur:v[2]||(v[2]=S=>s(!1))},null,544),[[Ri,g.value]])],2)]))}},l0=pn(N7,[["__scopeId","data-v-cc54b489"]]);Dt(),bn();var B7=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],z7={key:0,class:"existing-internal-input"},V7={class:"new-comment-input-wrapper"},j7={class:"reply-actions"},U7=["disabled"],H7={key:0,class:"resolved-badge"},$7=["innerHTML"],G7={key:1,class:"existing-internal-input"},W7={key:0,class:"card-section comment-body"},K7=["data-track-change-semantic-color-key"],q7={key:0},Y7={class:"change-type tracked-change-label"},X7={key:0,class:"tracked-change-detail-lines"},Z7={key:0,class:"tracked-change-text"},Q7={key:1,class:"change-type"},J7={class:"change-type"},eR={key:1},tR={class:"tracked-change-text is-inserted"},nR={key:2},rR={class:"tracked-change-text is-inserted"},oR={key:3},iR={key:4},sR={key:5},aR={key:6},lR={class:"tracked-change-text"},cR={key:7},uR={class:"tracked-change-text is-deleted"},dR={class:"tracked-change-text is-inserted"},fR={key:8},hR={class:"tracked-change-text is-deleted"},pR={key:9},mR={class:"tracked-change-text is-inserted"},gR=["data-track-change-image-preview-role"],vR=["src","alt"],yR={key:1,class:"card-section comment-body"},bR=["innerHTML"],wR={key:1,class:"comment"},CR={key:2,class:"reply-expanded"},kR={class:"reply-input-wrapper"},SR={class:"reply-actions"},_R=["onClick"],AR=["onClick","disabled","data-disabled-reason"],IR={class:"collapsed-avatars"},ER={key:3,class:"comment-separator"},TR={key:2,class:"tracked-change-decision-alert",role:"alert"},xR={class:"tracked-change-decision-alert__message"},RR=["disabled","data-disabled-reason"],MR={key:1,class:"reply-expanded"},LR={class:"reply-input-wrapper"},PR={class:"reply-actions"},DR=["disabled","data-disabled-reason"],Ck=3,kk=90,OR={__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}=vr(),i=su(),s=da(),{addComment:a,cancelComment:l,deleteComment:c,getCommentAliasIds:u,removePendingComment:d,getCommentDocumentId:h,requestInstantSidebarAlignment:g,resolveCommentPositionEntry:p,clearInstantSidebarAlignment:v,setActiveFloatingCommentInstance:S}=s,{suppressInternalExternal:C,getConfig:A,activeComment:y,activeFloatingCommentInstanceId:w,floatingCommentsOffset:x,pendingComment:L,currentCommentText:V,isDebugging:G,editingCommentId:R,editorCommentPositions:F,isCommentHighlighted:Z}=na(s),O=re(!0),N=re(null),T=re(new Map),B=re(null),Q=[[0,0],[-3,0],[Ck,0],[0,-3],[0,Ck]],q=ke=>{const He=typeof ke?.width=="number"&&Number.isFinite(ke.width)?ke.width:null,Et=typeof ke?.height=="number"&&Number.isFinite(ke.height)?ke.height:null;if(!He||!Et||He<=0||Et<=0)return{};const st=Math.min(kk/He,kk/Et,1);return{width:`${Math.max(1,Math.round(He*st))}px`,height:`${Math.max(1,Math.round(Et*st))}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(","),he=ke=>He=>{ke&&(He?(T.value.set(ke,He),R.value===ke&&Tt(()=>{ye(ke)})):T.value.delete(ke))},Ne=(ke,He,Et)=>{const st=ke?.getBoundingClientRect?.();return!st||![st.left,st.top,st.right,st.bottom].every(Number.isFinite)||st.width<=0||st.height<=0?!1:Q.some(([Nn,Kn])=>{const _r=He+Nn,jo=Et+Kn;return _r>=st.left&&_r<=st.right&&jo>=st.top&&jo<=st.bottom})},pe=(ke,He)=>{if(!Number.isFinite(ke)||!Number.isFinite(He))return null;const Et=document.querySelectorAll(se);for(const st of Et)if(st instanceof HTMLElement&&Ne(st,ke,He))return st;return null},ye=ke=>{T.value.get(ke)?.focus?.()},me=re(null),_e=ke=>ke.resolvedTime?ke.commentId:ke.importedId||ke.commentId,oe=ke=>ke?ke.trackedChange&&ke.importedId!=null?String(ke.importedId):ke.commentId!=null?String(ke.commentId):null:null,Me=(ke,He)=>{const Et=ke?.bounds?.[He];return Number.isFinite(Et)?Et:null},Ge=(ke,He)=>{if(!ke||!He||ke.pageIndex!==He.pageIndex)return!1;const Et=Me(ke,"top"),st=Me(He,"top");return Et!=null&&st!=null&&Math.abs(Et-st)<.5},lt=(ke,He)=>{const Et=Me(ke,"left"),st=Me(He,"left"),Nn=Me(ke,"right"),Kn=Me(He,"right");return[Et,st,Nn,Kn].some(_r=>_r==null)?!1:st<Nn&&Et<Kn},Ct=(ke,He)=>{const Et=ke?.start,st=ke?.end,Nn=He?.start,Kn=He?.end;return[Et,st,Nn,Kn].every(Number.isFinite)?Nn<=st&&Et<=Kn:!1},Re=(ke,He)=>!ke||!He||ke.kind&&He.kind&&ke.kind!==He.kind||ke.storyKey&&He.storyKey&&ke.storyKey!==He.storyKey?!1:He.start===ke.start&&He.end===ke.end?!0:Ge(ke,He)&&lt(ke,He)&&Ct(ke,He),Ke=ke=>{const He=new Set(u(ke)),{key:Et,entry:st}=p(ke);return Et&&He.add(Et),st?(Object.entries(F.value??{}).forEach(([Nn,Kn])=>{Re(st,Kn)&&He.add(Nn)}),[...He]):[...He]},tt=(ke,He,Et=24)=>{if(!Number.isFinite(He)||typeof ke?.getBoundingClientRect!="function")return!1;const st=ke.getBoundingClientRect().top;return Number.isFinite(st)&&Math.abs(st-He)<=Et},ee=Ee(()=>r.floatingInstanceId??r.comment.commentId??null),_=Ee(()=>typeof r.isFloatingInstanceActive=="boolean"?r.isFloatingInstanceActive:y.value!==r.comment.commentId?!1:r.floatingInstanceId==null?!0:w.value===r.floatingInstanceId),te=Ee(()=>r.comment.resolvedTime?r.comment.trackedChange?r.comment.trackedChangeDecision==="reject"?"Rejected":"Accepted":"Resolved":null),D=Ee(()=>L.value&&L.value.commentId===r.comment.commentId),U=Ee(()=>ke=>{const He=rt.value;return $.value&&ke===He.length-1?!0:He.length>1&&ke!==He.length-1}),$=Ee(()=>!A.readOnly&&_.value&&!r.comment.resolvedTime&&!Wn.value),H=()=>({ok:!1,reason:"read-only-document"}),J=()=>A.value?.readOnly===!0,X=re(!1),W=re(!1),we=()=>{if(J())return H();if(qe.value)return{ok:!1,reason:Oe.value?.reason??"v2-write-unavailable"};X.value=!0,Tt(()=>{N.value?.focus?.(),n("resize")})},ge=Ee(()=>{const ke=r.comment;return ke.trackedChange?s.getTrackedChangeThread(ke):s.commentsList.filter(He=>{const Et=He.parentCommentId===ke.commentId,st=He.commentId===ke.commentId;return Et||st}).sort((He,Et)=>He.commentId===ke.commentId?-1:Et.commentId===ke.commentId?1:He.createdTime-Et.createdTime)}),be=re(!1),Be=re(null),Ze=re(!1),it=Ee(()=>!be.value),yt=Ee(()=>({"is-truncated":it.value,"is-scrollable":be.value&&Ze.value})),Xt=()=>{be.value=!be.value,Tt(()=>n("resize"))},xt=ke=>{Be.value=ke??null},Ft=()=>{if(be.value)return;const ke=Be.value;if(!ke){Ze.value=!1;return}Ze.value=ke.scrollHeight>ke.clientHeight+1};Vt(Be,()=>{Tt(Ft)});const Ut=()=>R.value?ge.value.some(ke=>ke.commentId===R.value):!1;Vt(_,ke=>{ke||((X.value||Ut())&&(V.value="",R.value=null),be.value=!1,mn.value=!1,X.value=!1,Tt(()=>n("resize")))});const mn=re(!1),It=Ee(()=>ge.value.slice(1)),Zt=Ee(()=>mn.value?!1:It.value.length>=2),rt=Ee(()=>Zt.value?[ge.value[0],It.value[It.value.length-1]].filter(Boolean):ge.value);Vt(Ee(()=>{const ke=rt.value[0];return ke?JSON.stringify({commentId:ke.commentId,commentText:ke.commentText,trackedChange:ke.trackedChange,trackedChangeText:ke.trackedChangeText,deletedText:ke.deletedText,trackedChangeLabel:ke.trackedChangeLabel,trackedChangeDisplayType:ke.trackedChangeDisplayType,trackedChangeDetailLines:ke.trackedChangeDetailLines}):""}),()=>{Tt(Ft)});const zt=Ee(()=>Zt.value?It.value.length-1:0),Lt=Ee(()=>{if(!Zt.value)return[];const ke=It.value.slice(0,-1),He=new Set;return ke.map(Et=>typeof Et.getCommentUser=="function"?Et.getCommentUser():{name:Et.creatorName,email:Et.creatorEmail||Et.email}).filter(Et=>{if(!Et)return!1;const st=Et.email||Et.name;return He.has(st)?!1:(He.add(st),!0)}).slice(0,3)}),An=()=>{mn.value=!0,Xn(),Tt(()=>n("resize"))},Qt=Ee(()=>r.comment.resolvedTime?!0:A.value.readOnly),wn=Ee(()=>ke=>_.value&&R.value===ke.commentId),Wn=Ee(()=>!R.value||!_.value?!1:ge.value.some(ke=>ke.commentId===R.value)),go=Ee(()=>A.value.readOnly||!o.$superdoc.config.isInternal||rr.value?!1:!C.value&&!r.comment.trackedChange),jn=Ee(()=>V.value&&V.value!=="<p></p>"),Xn=async()=>{const ke=o.$superdoc.activeEditor,He=ke?.editorVersion===2?ke?.v2Comments??null:null,Et=!!r.comment?.trackedChange,st=t7(),Nn=r.floatingInstanceId!=null,Kn=me.value?.getBoundingClientRect?.().top,_r=!r.comment.resolvedTime&&(y.value!==r.comment.commentId||Nn&&ee.value!==w.value);let jo=st;if(He){const xo=!Et&&!r.comment.resolvedTime&&String(r.comment?.trackedChangeParentId??"").trim()?r.comment.trackedChangeParentId:null,Di=ke?.editorVersion===2&&(Et||xo!=null)?ke?.v2TrackedChanges??null:null,Ro=xo!=null?s.getComment(xo):null,oo=Et?r.comment:Ro?.trackedChange?Ro:xo;let io=await(Di?Di.focusTrackedChange(oo):He.focusComment(r.comment));return!Et&&io?.reason==="tracked-change-anchor-not-found"&&(io=await He.focusComment(r.comment)),io?.ok?(r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&S(r.floatingInstanceId)),_r&&!Nn?g(st,r.comment.commentId,r.floatingInstanceId??null):_r&&Number.isFinite(Kn)?g(Kn,r.comment.commentId,r.floatingInstanceId):v(),io):(v(),io)}if(ke){const{entry:xo}=p(r.comment),Di=r.floatingPositionEntry??xo,Ro=Number.isFinite(r.floatingPageIndex)&&r.comment?.trackedChangeStory?.storyType==="headerFooterPart",oo=gk(r.parent,Di),io=Ro?null:n7(Ke(r.comment)),Si=Number.isFinite(io)?io:oo,Uo=tt(me.value,Si),es=_e(r.comment),vo=null;let Ho=null;if(Et)if(r.comment.trackedChangeStory&&(r.comment.trackedChangeStory,{...Number.isFinite(r.floatingPageIndex)?{pageIndex:r.floatingPageIndex}:{}}),r.comment.resolvedTime)ke.commands?.setCursorById(es);else{const Br=r.comment.commentId;ke.commands?.setCursorById(es,{activeCommentId:Br})||ke.commands?.setActiveComment({commentId:Br})}else{if(r.comment.resolvedTime)ke.commands?.setCursorById(es);else{const Oi=r.comment.commentId;ke.commands?.setCursorById(es,{activeCommentId:Oi})||ke.commands?.setActiveComment({commentId:Oi})}const Br=r.comment.commentId;Ho=Uo?null:r7(vo,es,Br,st)}Number.isFinite(io)?jo=io:Number.isFinite(oo)?jo=oo:Number.isFinite(Ho)&&(jo=Ho)}_r&&!Nn?r.floatingInstanceId?g(jo,r.comment.commentId,r.floatingInstanceId):g(jo,r.comment.commentId):v(),r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&S(r.floatingInstanceId))},Ao=ke=>{const He=ke.target instanceof Element?ke.target:ke.target?.parentElement,Et=document.elementFromPoint(ke.clientX,ke.clientY);if(!(He?.closest?.(se)||Et?.closest?.(se)||pe(ke.clientX,ke.clientY)||Z.value)&&!(ke.target.closest?.(".comments-dialog")&&!me.value?.contains(ke.target))){if(D.value){l(o.$superdoc);return}_.value&&(x.value=0,n("dialog-exit"),y.value=null,s.setActiveComment(o.$superdoc,y.value),Z.value=!1)}},Nr=async()=>{if(J())return H();if(qe.value)return{ok:!1,reason:Oe.value?.reason??"v2-write-unavailable"};if(rr.value&&Pn.value&&!D.value){if(W.value)return{ok:!1,reason:"reply-submit-in-flight"};W.value=!0;try{const Et=await s.replyCommentV2({superdoc:o.$superdoc,parentCommentId:oe(r.comment),text:V.value});return Et?.ok?(X.value=!1,V.value="",Tt(()=>n("resize")),Et):(Tt(()=>n("resize")),Et)}finally{W.value=!1}}const ke={documentId:r.comment.fileId,isInternal:L.value?L.value.isInternal:O.value,parentCommentId:L.value?null:r.comment.commentId};L.value&&(ke.selection=L.value.selection.getValues());const He=s.getPendingComment(ke);!L.value&&V.value&&He.setText({text:V.value,suppressUpdate:!0}),Promise.resolve(a({superdoc:o.$superdoc,comment:He})).finally(()=>{X.value=!1,Tt(()=>n("resize"))})},rr=Ee(()=>o.$superdoc?.activeEditor?.editorVersion===2),Pn=Ee(()=>rr.value?o.$superdoc?.activeEditor?.v2Comments??null:null),De=Ee(()=>rr.value?o.$superdoc?.activeEditor?.v2TrackedChanges??null:null),Oe=Ee(()=>{if(!Pn.value)return null;const ke=s.viewingVisibility.documentMode,He=Pn.value.getCapabilityState?.()??null;return ke==="viewing"?{...He??{},canWrite:!1,reason:"review-surface-read-only"}:He}),qe=Ee(()=>{if(!rr.value)return!1;const ke=Oe.value;return ke?ke.canWrite===!1:!1}),wt=Ee(()=>W.value?"reply-submit-in-flight":qe.value?Oe.value?.reason??"v2-write-unavailable":null),ft=Ee(()=>{if(!De.value)return null;const ke=s.viewingVisibility.documentMode,He=De.value.getCapabilityState?.()??null;return ke==="viewing"&&He?.canDecide!==!1?{canDecide:!1,reason:"review-surface-read-only"}:He}),Pt=ke=>{if(rr.value&&ke?.trackedChange){if(!De.value)return"v2-tracked-change-adapter-missing";const He=ft.value;return He&&He.canDecide===!1?He.reason??"v2-tracked-change-unavailable":null}return qe.value?Oe.value?.reason??"v2-write-unavailable":null},_n=ke=>{if(rr.value&&ke?.trackedChange){if(!De.value)return"v2-tracked-change-adapter-missing";const He=ft.value;return He&&He.canDecide===!1?He.reason??"v2-tracked-change-unavailable":null}return qe.value?Oe.value?.reason??"v2-write-unavailable":null},an=()=>rr.value?Pn.value?A.value?.readOnly?"read-only-document":qe.value?Oe.value?.reason??"v2-write-unavailable":null:"v2-comments-adapter-missing":null,Dn=Ee(()=>!rr.value||!qe.value?null:Oe.value?.reason??"v2-write-unavailable"),Io=(ke,He)=>{B.value={decision:ke,reason:He?.reason??null},Tt(()=>n("resize"))},Eo=()=>{B.value&&(B.value=null,Tt(()=>n("resize")))},ki=Ee(()=>{const ke=B.value;if(!ke)return null;const He=ke.decision==="reject"?"reject":"accept";return ke.reason==="stale-catalog"?`Couldn't ${He} this change because the review list is stale.`:`Couldn't ${He} this change.`}),cn=()=>{const ke=B.value;if(ke){if(B.value=null,ke.decision==="reject"){On();return}Fn()}},On=async()=>{if(J())return H();const ke=o.$superdoc.config.onTrackedChangeBubbleReject;if(r.comment.trackedChange){if(rr.value){const Et=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});if(!Et?.ok||Et.success===!1){Io("reject",Et);return}Eo(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let He=!0;if(typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else{const Et=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});He=!!Et?.ok&&Et.success!==!1}He&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"reject"})}else if(rr.value&&Pn.value){if(!(await s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId});Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Fn=async()=>{if(J())return H();if(!r.comment.trackedChange&&A.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};const ke=o.$superdoc.config.onTrackedChangeBubbleAccept;if(r.comment.trackedChange&&rr.value){const Et=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});if(!Et?.ok||Et.success===!1){Io("accept",Et);return}Eo(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let He=!0;if(r.comment.trackedChange&&typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else if(r.comment.trackedChange){const Et=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});He=!!Et?.ok&&Et.success!==!1}else if(rr.value&&Pn.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&&!rr.value&&He&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"accept"}),Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},lr=async()=>{if(J())return H();if(A.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};!rr.value||!Pn.value||(await s.reopenCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok&&Tt(()=>{s.lastUpdate=new Date,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Jt=(ke,He)=>{if(J())return H();switch(ke){case"edit":V.value=He?.commentText?.value??He?.commentText??"",y.value=r.comment.commentId,r.floatingInstanceId&&S(r.floatingInstanceId),R.value=He.commentId,s.setActiveComment(o.$superdoc,y.value),Tt(()=>{ye(He.commentId)});break;case"delete":c({superdoc:o.$superdoc,commentId:He.commentId});break}},Un=async ke=>{if(J())return H();if(rr.value&&Pn.value){const He=await s.editCommentV2({superdoc:o.$superdoc,commentId:ke.commentId,text:V.value});return He?.ok&&(R.value=null,d(o.$superdoc)),He}R.value=null,ke.setText({text:V.value,superdoc:o.$superdoc}),d(o.$superdoc)},ro=ke=>{if(J())return H();const He=!!L.value,Et=ke.toLowerCase()==="internal";He?L.value.isInternal=Et:r.comment.setIsInternal({isInternal:Et,superdoc:o.$superdoc})},Pi=Ee(()=>{const ke={};return(_.value||D.value||Wn.value)&&(ke.zIndex=50),ke}),pl=ke=>typeof ke=="string"?new Date(ke).getTime():ke,To=ke=>{R.value=null,X.value=!1,l(o.$superdoc)},ai=Ee(()=>{const ke=o.$superdoc.users;return r.comment.isInternal===!0?ke.filter(He=>He.access?.role==="internal"):ke});return Gn(()=>{r.autoFocus&&Tt(()=>Xn()),D.value&&Tt(()=>{N.value?.focus?.()}),Tt(()=>{const ke=r.floatingInstanceId??(r.comment.importedId!==void 0?r.comment.importedId:r.comment.commentId);n("ready",{commentId:ke,elementRef:me}),Ft()})}),Vt($,ke=>{ke&&Tt(()=>{N.value?.focus?.()})},{immediate:!0}),Vt(R,ke=>{if(!ke||!_.value)return;const He=ge.value.find(Et=>Et.commentId===ke);!He||He.trackedChange||Tt(()=>{ye(ke)})}),Vt(()=>A.value?.readOnly===!0,ke=>{ke&&(X.value=!1,ge.value.some(He=>He.commentId===R.value)&&(R.value=null),D.value&&l(o.$superdoc),Tt(()=>n("resize")))},{immediate:!0}),Vt(qe,ke=>{ke&&(X.value=!1,Tt(()=>n("resize")))}),(ke,He)=>{const Et=$1("click-outside");return Ks((ve(),Te("div",{class:on(["comments-dialog",{"is-active":_.value||D.value,"is-resolved":r.comment.resolvedTime}]),onClick:rn(Xn,["stop","prevent"]),style:Sn(Pi.value),ref_key:"commentDialogElement",ref:me,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:""},[D.value?(ve(),Te(Yt,{key:0},[go.value?(ve(),Te("div",z7,[Kt(yk,{onClick:He[0]||(He[0]=rn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":!1,state:nt(L).isInternal?"internal":"external",onSelect:ro},null,8,["state"])])):vt("",!0),Kt(s0,{config:nt(A),comment:r.comment,"is-pending-input":!0},null,8,["config","comment"]),Fe("div",V7,[Kt(l0,{ref_key:"commentInput",ref:N,users:ai.value,config:nt(A),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Fe("div",j7,[Fe("button",{class:"sd-button reply-btn-cancel",onClick:rn(To,["stop","prevent"])},"Cancel"),Fe("button",{class:on(["sd-button primary reply-btn-primary",{"sd-is-disabled":!jn.value}]),onClick:rn(Nr,["stop","prevent"]),disabled:!jn.value}," Comment ",10,U7)])],64)):(ve(),Te(Yt,{key:1},[te.value?(ve(),Te("div",H7,[Fe("span",{class:"resolved-badge__icon",innerHTML:nt(fa).markDone},null,8,$7),ji(" "+Ht(te.value),1)])):vt("",!0),go.value?(ve(),Te("div",G7,[Kt(yk,{onClick:He[1]||(He[1]=rn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":Qt.value,state:e.comment.isInternal?"internal":"external",onSelect:ro},null,8,["is-disabled","state"])])):vt("",!0),(ve(!0),Te(Yt,null,mr(rt.value,(st,Nn)=>(ve(),Te("div",{key:st.commentId,class:"conversation-item"},[Kt(s0,{config:nt(A),timestamp:pl(st.createdTime),comment:st,"is-active":_.value,"resolve-disabled-reason":Pt(st),"reject-disabled-reason":_n(st),"reopen-supported":rr.value&&!!Pn.value,"reopen-disabled-reason":an(),"write-disabled-reason":Dn.value,onResolve:Fn,onReject:On,onReopen:lr,onOverflowSelect:Kn=>Jt(Kn,st)},null,8,["config","timestamp","comment","is-active","resolve-disabled-reason","reject-disabled-reason","reopen-supported","reopen-disabled-reason","write-disabled-reason","onOverflowSelect"]),st.trackedChange?(ve(),Te("div",W7,[Fe("div",{class:on(["tracked-change",Nn===0?yt.value:void 0]),"data-track-change-semantic-color-key":st.semanticColorKey??void 0,ref_for:!0,ref:Nn===0?xt:void 0},[st.trackedChangeLabel?(ve(),Te("div",q7,[Fe("span",Y7,Ht(st.trackedChangeLabel),1),st.trackedChangeDetailLines&&st.trackedChangeDetailLines.length?(ve(),Te("div",X7,[(ve(!0),Te(Yt,null,mr(st.trackedChangeDetailLines,(Kn,_r)=>(ve(),Te("div",{key:_r,class:"tracked-change-detail-line"},[Kn.excerpt?(ve(),Te("span",Z7,'"'+Ht(Kn.excerpt)+'"',1)):vt("",!0),Kn.excerpt?(ve(),Te("span",Q7," — ")):vt("",!0),Fe("span",J7,Ht(Kn.label),1)]))),128))])):vt("",!0)])):st.trackedChangeDisplayType==="hyperlinkAdded"?(ve(),Te("div",eR,[He[2]||(He[2]=Fe("span",{class:"change-type"},"Added hyperlink ",-1)),Fe("span",tR,'"'+Ht(st.trackedChangeText)+'"',1)])):st.trackedChangeDisplayType==="hyperlinkModified"?(ve(),Te("div",nR,[He[3]||(He[3]=Fe("span",{class:"change-type"},"Changed hyperlink to ",-1)),Fe("span",rR,'"'+Ht(st.trackedChangeText)+'"',1)])):st.trackedChangeDisplayType==="paragraphSplit"?(ve(),Te("div",oR,[...He[4]||(He[4]=[Fe("span",{class:"change-type"},"Added new line",-1)])])):st.trackedChangeDisplayType==="tableInsert"?(ve(),Te("div",iR,[...He[5]||(He[5]=[Fe("span",{class:"change-type"},"Added table",-1)])])):st.trackedChangeDisplayType==="tableDelete"?(ve(),Te("div",sR,[...He[6]||(He[6]=[Fe("span",{class:"change-type"},"Deleted table",-1)])])):st.trackedChangeType==="trackFormat"?(ve(),Te("div",aR,[He[7]||(He[7]=Fe("span",{class:"change-type"},"Format: ",-1)),Fe("span",lR,Ht(st.trackedChangeText),1)])):st.trackedChangeType==="both"?(ve(),Te("div",cR,[He[8]||(He[8]=Fe("span",{class:"change-type"},"Replaced ",-1)),Fe("span",uR,'"'+Ht(st.deletedText)+'"',1),He[9]||(He[9]=Fe("span",{class:"change-type"}," with ",-1)),Fe("span",dR,'"'+Ht(st.trackedChangeText)+'"',1)])):st.deletedText?(ve(),Te("div",fR,[He[10]||(He[10]=Fe("span",{class:"change-type"},"Deleted ",-1)),Fe("span",hR,'"'+Ht(st.deletedText)+'"',1)])):st.trackedChangeText?(ve(),Te("div",pR,[He[11]||(He[11]=Fe("span",{class:"change-type"},"Added ",-1)),Fe("span",mR,'"'+Ht(st.trackedChangeText)+'"',1)])):vt("",!0),st.trackedChangeImagePreview?.src?(ve(),Te("div",{key:10,class:"tracked-change-image-preview","data-track-change-image-preview-role":st.trackedChangeImagePreview.role??void 0},[Fe("img",{class:"tracked-change-image-preview__image",src:st.trackedChangeImagePreview.src,alt:st.trackedChangeImagePreview.alt||"Tracked image preview",style:Sn(q(st.trackedChangeImagePreview)),loading:"lazy",decoding:"async"},null,12,vR)],8,gR)):vt("",!0)],10,K7),it.value&&Ze.value&&Nn===0?(ve(),Te("div",{key:0,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show more ")):vt("",!0),be.value&&Ze.value&&Nn===0?(ve(),Te("div",{key:1,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show less ")):vt("",!0)])):vt("",!0),st.trackedChange?vt("",!0):(ve(),Te("div",yR,[!nt(G)&&!wn.value(st)?(ve(),Te("div",{key:0,class:on(["comment",Nn===0?yt.value:void 0]),ref_for:!0,ref:Nn===0?xt:void 0,innerHTML:st.commentText},null,10,bR)):nt(G)&&!wn.value(st)?(ve(),Te("div",wR,Ht(nt(F)[st.importedId!==void 0?st.importedId:st.commentId]?.bounds),1)):(ve(),Te("div",CR,[Fe("div",kR,[Kt(l0,{ref_for:!0,ref:he(st.commentId),users:ai.value,config:nt(A),"include-header":!1,comment:st},null,8,["users","config","comment"])]),Fe("div",SR,[Fe("button",{class:"sd-button reply-btn-cancel",onClick:rn(Kn=>To(st),["stop","prevent"])},"Cancel",8,_R),Fe("button",{class:on(["sd-button primary reply-btn-primary",{"sd-is-disabled":!jn.value||qe.value}]),onClick:rn(Kn=>Un(st),["stop","prevent"]),disabled:!jn.value||qe.value,"data-disabled-reason":qe.value?Oe.value?.reason??null:null}," Update ",10,AR)])])),it.value&&Ze.value&&Nn===0&&!wn.value(st)?(ve(),Te("div",{key:3,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show more ")):vt("",!0),be.value&&Ze.value&&Nn===0&&!wn.value(st)?(ve(),Te("div",{key:4,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show less ")):vt("",!0)])),Zt.value&&Nn===0?(ve(),Te(Yt,{key:2},[He[12]||(He[12]=Fe("div",{class:"comment-separator"},null,-1)),Fe("div",{class:"collapsed-replies",onClick:rn(An,["stop","prevent"])},[Fe("div",IR,[(ve(!0),Te(Yt,null,mr(Lt.value,Kn=>(ve(),hn(bk,{key:Kn.email||Kn.name,user:Kn,class:"mini-avatar"},null,8,["user"]))),128))]),Fe("span",null,Ht(zt.value)+" more "+Ht(zt.value===1?"reply":"replies"),1)])],64)):vt("",!0),U.value(Nn)?(ve(),Te("div",ER)):vt("",!0)]))),128)),B.value?(ve(),Te("div",TR,[Fe("span",xR,Ht(ki.value),1),Fe("button",{type:"button",class:"sd-button tracked-change-decision-alert__retry",onClick:rn(cn,["stop","prevent"])}," Retry ")])):vt("",!0),$.value&&!nt(A).readOnly?(ve(),Te(Yt,{key:3},[X.value?(ve(),Te("div",MR,[Fe("div",LR,[Kt(l0,{ref_key:"commentInput",ref:N,users:ai.value,config:nt(A),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Fe("div",PR,[Fe("button",{class:"sd-button reply-btn-cancel",onClick:rn(To,["stop","prevent"])},"Cancel"),Fe("button",{class:on(["sd-button primary reply-btn-primary",{"sd-is-disabled":!jn.value||qe.value||W.value}]),onClick:rn(Nr,["stop","prevent"]),disabled:!jn.value||qe.value||W.value,"data-disabled-reason":wt.value}," Reply ",10,DR)])])):(ve(),Te("button",{key:0,type:"button",class:on(["reply-pill",{"sd-is-disabled":qe.value}]),onClick:rn(we,["stop","prevent"]),disabled:qe.value,"data-disabled-reason":qe.value?Oe.value?.reason??null:null}," Reply or add others with @ ",10,RR))],64)):vt("",!0)],64))],14,B7)),[[Et,Ao]])}}},Pp=pn(OR,[["__scopeId","data-v-f26decd0"]]);Dt(),bn();var FR={class:"comments-list"},NR={key:0},BR=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],zR={key:1},VR="headerFooterPart",jR={__name:"commentsList",props:{showMainComments:{type:Boolean,default:!0},showResolvedComments:{type:Boolean,default:!0}},setup(e){const t=e,n=da(),r=dg(n,"isCommentsListVisible"),o=Ee(()=>n.getGroupedComments),i=Ee(()=>n.getFloatingCommentInstances),{activeComment:s,activeFloatingCommentInstanceId:a}=na(n),l=g=>{const p=i.value.filter(v=>v?.comment?.commentId===g?.commentId);return p.length<2?[]:g?.trackedChange?g?.trackedChangeStory?.storyType!==VR?[]:p:[]},c=g=>!g?.comment?.commentId||s.value!==g.comment.commentId?!1:a.value==null?g.isPrimary===!0:String(a.value)===String(g.id),u=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:c(v)})):[{id:g.commentId,comment:g,floatingInstanceId:null,floatingPageIndex:null,floatingPositionEntry:null,isFloatingInstanceActive:void 0}]},d=Ee(()=>o.value.parentComments.flatMap(g=>u(g))),h=Ee(()=>t.showResolvedComments&&o.value?.resolvedComments?.length>0);return Gn(()=>{r.value=!0}),gr(()=>{r.value=!1}),(g,p)=>(ve(),Te("div",FR,[e.showMainComments?(ve(),Te("div",NR,[(ve(!0),Te(Yt,null,mr(d.value,v=>(ve(),Te("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:""},[Kt(Pp,{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,BR))),128))])):vt("",!0),h.value?(ve(),Te("div",zR,[p[0]||(p[0]=Fe("div",{class:"comment-title"},"Resolved",-1)),(ve(!0),Te(Yt,null,mr(o.value.resolvedComments,v=>(ve(),Te("div",{key:v.commentId,class:"comment-item"},[Kt(Pp,{comment:v},null,8,["comment"])]))),128))])):vt("",!0)]))}},UR=pn(jR,[["__scopeId","data-v-e89dbc33"]]);Dt();var HR=class extends Gm.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=zl(UR);const e=this.superdoc?.app?._context?.provides;e&&this.app?._context?.provides&&Object.setPrototypeOf(this.app._context.provides,e),this.superdoc?.pinia&&(qd(this.superdoc.pinia),this.app.use(this.superdoc.pinia),this.app.config.globalProperties.$pinia=this.superdoc.pinia),this.app.directive("click-outside",qv),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()}},tl,c0=Dr((()=>{tl=96/72}));Dt(),c0();var $R=96,GR=".superdoc__right-sidebar",WR=".sd-pdf-viewer-page",u0=Object.freeze({min:10,max:100,padding:0}),Sk=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,u0.min),o=n(t.max,u0.max),i=typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding>=0?t.padding:u0.padding;return{min:Math.min(r,o),max:Math.max(r,o),padding:i}},_k=(e,t)=>!(e>0)||!(t>0)?null:Math.round(e/t*100),KR=(e,t,n)=>{const r=_k(e-n.padding,t);return r===null?null:Math.max(1,Math.round(Math.min(n.max,Math.max(n.min,r))))},qR=(e,t,n)=>e>0?Number.isFinite(t)&&t>0?e/t*tl:n>0?e/n:e:null;function YR({getSuperdoc:e,superdocContainerWidth:t,isReady:n,activeZoom:r,zoomMode:o,viewportMetrics:i,showCommentsSidebar:s,rightSidebarRef:a,superdocRoot:l,documents:c}){const u=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 L=null;try{L=w.getPageStyles?.()??null}catch{L=null}const V=L?.pageSize?.width;return typeof V=="number"&&Number.isFinite(V)&&V>0?V*$R:null},d=()=>{if(!(c?.value??[]).some(L=>L?.type==="application/pdf"))return null;const w=l.value;if(!w?.querySelectorAll)return null;let x=0;for(const L of w.querySelectorAll(WR)){const V=Number(L.clientWidth)||Number(L.getBoundingClientRect?.().width)||0;let G=NaN;typeof window<"u"&&typeof window.getComputedStyle=="function"&&(G=Number.parseFloat(window.getComputedStyle(L).getPropertyValue("--scale-factor")));const R=(r.value??100)/100,F=qR(V,G,R);F!==null&&F>x&&(x=F)}return x>0?x:null},h=()=>{const w=e();if(!w)return null;const x=[],L=c?.value??[];for(const G of L){if(G?.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")continue;const R=u(G.getEditor?.());R!==null&&x.push(R)}if(x.length===0){const G=u(w.activeEditor);G!==null&&x.push(G)}const V=d();if(V!==null&&x.push(V),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?.(GR),x=Number(w?.offsetWidth)||Number(w?.getBoundingClientRect?.().width)||0;return x>0?x:0},p=(w,x)=>{const L=Sk(w.config?.zoom?.fitWidth),V=KR(x.availableWidth,x.documentWidth,L);V!==null&&V!==r.value&&(r.value=V,w.emit("zoomChange",{zoom:V,mode:"fit-width"}))},v=()=>{const w=e();if(!w)return;const x=t.value;if(!(x>0)||!n.value)return;const L=h();if(L===null)return;const V=x-g(),G=_k(V,L);if(G===null)return;const R=Object.freeze({availableWidth:V,documentWidth:L,fitZoom:G}),F=i.value;(!F||F.availableWidth!==V||F.documentWidth!==L||F.fitZoom!==G)&&(i.value=R),(!F||F.fitZoom!==G||Math.round(F.documentWidth)!==Math.round(L))&&w.emit("viewport-change",R),o.value==="fit-width"&&p(w,R)};Vt(t,()=>{Tt(()=>v())}),Vt(n,w=>{w&&v()}),Vt(o,w=>{w==="fit-width"&&v()}),s&&Vt(s,()=>{Tt(()=>v())});const S=()=>{Tt(()=>v())},C=()=>{Tt(()=>v())},A=()=>{Tt(()=>v())},y=e();return y?.on?.("editorCreate",S),y?.on?.("pagination-update",C),y?.on?.("pdf:document-ready",A),gr(()=>{y?.off?.("editorCreate",S),y?.off?.("pagination-update",C),y?.off?.("pdf:document-ready",A)}),{evaluateViewport:v}}var XR=e=>!!e?.trackedChange,ZR=e=>e,QR=(e,t,n,r=e)=>!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?!1:(Number.isFinite(r)?r:e)<t||e>n,JR=({comment:e,anchorTop:t,anchorBottom:n,viewportTop:r,viewportBottom:o})=>XR(e)&&QR(t,r,o,n),e9=({comment:e,anchorTop:t,anchorBottom:n,cardHeight:r,viewportTop:o,viewportBottom:i})=>!JR({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,t9=({id:e,visibleIds:t,activeCommentInstanceId:n})=>e?!!(e==="pending"||n!=null&&String(e)===String(n)||t?.has?.(e)):!1,Ak=({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};Dt(),bn();var n9=["data-comment-id","data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Hl={},r9={__name:"FloatingComments",props:{currentDocument:{type:Object,required:!0},parent:{type:Object,required:!0}},setup(e){const r=new Set(["auto","scroll","hidden","clip"]),o=(De,Oe,qe)=>{if(Oe>=0){De[Oe].top=De[Oe].anchorTop;let wt=De[Oe].top+De[Oe].height+qe;for(let Pt=Oe+1;Pt<De.length;Pt++)De[Pt].top=Math.max(De[Pt].anchorTop,wt),wt=De[Pt].top+De[Pt].height+qe;wt=De[Oe].top-qe;for(let Pt=Oe-1;Pt>=0;Pt--){const _n=wt-De[Pt].height;De[Pt].top=Math.min(De[Pt].anchorTop,_n),wt=De[Pt].top-qe}const ft=Math.min(...De.map(Pt=>Pt.top));if(ft<0){const Pt=Math.abs(ft);for(const _n of De)_n.top+=Pt}}else for(let wt=1;wt<De.length;wt++){const ft=De[wt-1],Pt=ft.top+ft.height+qe;De[wt].top<Pt&&(De[wt].top=Pt)}},i=e,s=su(),a=da(),{clearInstantSidebarAlignment:l}=a,{activeComment:c,activeFloatingCommentInstanceId:u,editorCommentPositions:d,pendingComment:h,editingCommentId:g,instantSidebarAlignmentTargetY:p,instantSidebarAlignmentThreadId:v,instantSidebarAlignmentInstanceId:S}=na(a),{activeZoom:C}=na(s),A=Ee(()=>{const De=a.getFloatingCommentInstances;if(!Array.isArray(De))return[];const Oe=i.currentDocument?.id;return Oe==null?De:De.filter(qe=>a.belongsToDocument(qe.comment,String(Oe),{allowSingleDocumentMismatch:!0}))}),y=re(null),w=re(0),x=re(0),L=re(!1),V=re(null),G=re(0),R=De=>{const Oe=h.value?.commentId;return Oe?typeof De=="object"?De?.commentId===Oe:De===Oe||De==="pending":!1},F=De=>De?.commentId??De?.importedId??null,Z=Ee(()=>{const De=new Map,Oe=new Map;for(const qe of A.value){qe?.id!=null&&De.set(String(qe.id),qe);const wt=F(qe?.comment);if(wt==null)continue;const ft=String(wt),Pt=Oe.get(ft)??[];Pt.push(qe),Oe.set(ft,Pt)}return{byId:De,byThreadId:Oe}}),O=(De,Oe=null)=>{if(De==null)return null;const qe=String(De),wt=Z.value.byThreadId.get(qe)??[];if(!wt.length)return null;if(Oe!=null){const ft=wt.find(Pt=>String(Pt.id)===String(Oe));if(ft)return ft.id}return wt.find(ft=>ft.isPrimary)?.id??wt[0]?.id??null},N=Ee(()=>c.value?O(c.value,u.value):null),T=De=>{if(typeof De=="number")return Number.isFinite(De)?De:null;if(typeof De!="string"||De.trim()==="")return null;const Oe=Number(De);return Number.isFinite(Oe)?Oe:null},B=re({...Hl}),Q=re(new Set),q=re({});let se=null;const he=new Set;let Ne=null;const pe=()=>{Ne==null&&(Ne=requestAnimationFrame(()=>{Ne=null,G.value+=1}))},ye=De=>{if(i.currentDocument.type==="application/pdf"){const Oe=(C.value??100)/100,qe=T(De?.comment?.selection?.selectionBounds?.top);return qe==null?null:qe*Oe}return De?.positionEntry?.bounds?.top},me=(De,Oe)=>{if(i.currentDocument.type==="application/pdf"){const wt=(C.value??100)/100,ft=T(De?.comment?.selection?.selectionBounds?.bottom);return ft!=null?ft*wt:Oe}const qe=De?.positionEntry?.bounds?.bottom;return Number.isFinite(qe)?qe:Oe},_e=Ee(()=>{const De=[];for(const Oe of A.value){const qe=Oe?.id,wt=F(Oe?.comment),ft=ye(Oe);if(qe==null||wt==null||!Number.isFinite(ft))continue;const Pt=ZR(ft,Oe.comment);De.push({id:qe,threadId:wt,instance:Oe,top:Pt,anchorBottom:me(Oe,Pt)})}return De}),oe=()=>{const De=d.value.pending;if(typeof De?.bounds?.top=="number"&&!isNaN(De.bounds.top))return De.bounds.top;const Oe=i.currentDocument.type==="application/pdf"?(C.value??100)/100:1,qe=T(h.value?.selection?.selectionBounds?.top);return qe==null?null:qe*Oe},Me=De=>t9({id:De?.id,visibleIds:Q.value,activeCommentInstanceId:N.value,comment:De?.commentRef}),Ge=()=>{const De=y.value;if(!De)return null;const Oe=De.getBoundingClientRect();if(!Number.isFinite(Oe.top)||!Number.isFinite(window.innerHeight))return null;let qe=0,wt=window.innerHeight;for(let Pt=De.parentElement;Pt;Pt=Pt.parentElement){const _n=window.getComputedStyle(Pt).overflowY;if(!["auto","scroll","hidden","clip"].includes(_n))continue;const an=Pt.getBoundingClientRect();!Number.isFinite(an.top)||!Number.isFinite(an.bottom)||(qe=Math.max(qe,an.top),wt=Math.min(wt,an.bottom))}if(wt<=qe)return null;const ft=i.parent?.getBoundingClientRect?.();if(ft&&Number.isFinite(ft.top)&&Number.isFinite(ft.bottom)){const Pt=Math.max(qe,ft.top),_n=Math.min(wt,ft.bottom);_n>Pt&&(qe=Pt,wt=_n)}return{top:qe-Oe.top,bottom:wt-Oe.top}},lt=Ee(()=>v.value?O(v.value,S.value):null),Ct=Ee(()=>{G.value;const De=_e.value,Oe=h.value&&h.value.fileId===i.currentDocument.id;if(!De.length&&!A.value.length&&!Oe)return[];const qe=[],wt=Ge()??{top:0,bottom:Math.max(0,i.parent?.clientHeight||window.innerHeight||0)},ft=wt.top-600,Pt=wt.bottom+600,_n=Oe?"pending":N.value,an=new Set,Dn=({id:cn,threadId:On,instance:Fn,top:lr,anchorBottom:Jt,hasAnchorGeometry:Un})=>{const ro=String(cn);an.has(ro)||(an.add(ro),qe.push({id:cn,threadId:On,pageIndex:Fn?.pageIndex??null,anchorTop:lr,anchorBottom:Jt,hasAnchorGeometry:Un,top:lr,height:B.value[cn]||110,commentRef:Fn.comment,instanceRef:Fn}))};for(const cn of De){const{id:On,threadId:Fn,instance:lr,top:Jt,anchorBottom:Un}=cn,ro=_n!=null&&String(On)===String(_n),Pi=g.value!=null&&String(Fn)===String(g.value);!ro&&!Pi&&(Un<ft||Jt>Pt)||Dn({id:On,threadId:Fn,instance:lr,top:Jt,anchorBottom:Un,hasAnchorGeometry:!0})}const Io=[];if(_n&&_n!=="pending"){const cn=Z.value.byId.get(String(_n));cn&&Io.push(cn)}if(g.value!=null){const cn=Z.value.byThreadId.get(String(g.value))??[],On=cn.find(Fn=>Fn.isPrimary)??cn[0];On&&Io.push(On)}for(const cn of Io){const On=cn.id,Fn=F(cn.comment);On==null||Fn==null||an.has(String(On))||Dn({id:On,threadId:Fn,instance:cn,top:wt.top,anchorBottom:wt.top,hasAnchorGeometry:!1})}if(Oe){const cn=oe();typeof cn=="number"&&!isNaN(cn)&&qe.push({id:"pending",anchorTop:cn,anchorBottom:cn,hasAnchorGeometry:!0,top:cn,height:B.value.pending||110,commentRef:h.value})}qe.sort((cn,On)=>cn.anchorTop-On.anchorTop);const Eo=[];for(const cn of qe){const On=cn.hasAnchorGeometry?e9({comment:cn.commentRef,anchorTop:cn.anchorTop,anchorBottom:cn.anchorBottom,cardHeight:cn.height,viewportTop:wt.top,viewportBottom:wt.bottom}):null;On==null?Eo.push(cn):cn.top=On}const ki=_n?Eo.findIndex(cn=>cn.id===_n):-1;return o(Eo,ki,15),qe}),Re=Ee(()=>(G.value,Math.max(0,i.parent?.clientHeight||0,i.parent?.scrollHeight||0))),Ke=()=>{se&&se.disconnect(),se=new IntersectionObserver(De=>{const Oe=new Set(Q.value);for(const qe of De){const wt=qe.target.dataset.commentId;wt&&(qe.isIntersecting?Oe.add(wt):Oe.delete(wt))}Q.value=Oe},{rootMargin:"600px 0px 600px 0px"})},tt=()=>{if(!se)return;const De=new Set;for(const Oe of Ct.value){const qe=q.value[Oe.id];qe&&(De.add(qe),he.has(qe)||(se.observe(qe),he.add(qe)))}for(const Oe of he)De.has(Oe)||(se.unobserve(Oe),he.delete(Oe))},ee=(De,Oe)=>{Oe<=0||Oe===B.value[De]||(Hl[De]=Oe,B.value={...B.value,[De]:Oe})},_=De=>{if(!De)return;const{elementRef:Oe,commentId:qe}=De;Oe&&Tt(()=>{const wt=Oe.value?.getBoundingClientRect();!wt||wt.height<=0||qe&&ee(qe,wt.height)})},te=De=>{const Oe=De?.id;Oe&&Tt(()=>{const qe=q.value[Oe];if(!qe)return;const wt=qe.querySelector(".comments-dialog");if(!wt)return;ee(Oe,wt.getBoundingClientRect().height);const ft=Oe===N.value,Pt=Oe==="pending",_n=!!g.value&&!!c.value&&De?.threadId!=null&&String(De.threadId)===String(c.value);!ft&&!Pt&&!_n||(mn(Ct.value.map(an=>an.id)),rt(()=>Ct.value.map(an=>an.id)))})},D=De=>{!De&&V.value!=null||(L.value=De)},U=(De,Oe,qe)=>{if(!Number.isFinite(Oe)){qe?.(!1);return}const wt=q.value[De];if(!wt){qe?.(!1);return}const ft=wt.getBoundingClientRect().top;x.value+=Oe-ft,qe?.(!0)},$=(De,Oe)=>{if(Oe)q.value[De]=Oe,se&&!he.has(Oe)&&(se.observe(Oe),he.add(Oe));else{const qe=q.value[De];qe&&se&&(se.unobserve(qe),he.delete(qe)),delete q.value[De]}};let H=[],J=null,X=[],W=null,we=!1,ge=0,be=null,Be=null,Ze=null,it=null,yt=null;const Xt=new Set,xt=()=>{Ze=null,it=null,V.value=null,D(!1)},Ft=De=>{if(!Ze)return;const Oe=(De?.target instanceof Element?De.target:null)?.closest?.("[data-comment-action]"),qe=Oe?.getAttribute?.("data-comment-action");(qe==="resolve"||qe==="reject")&&y.value?.contains?.(Oe)||xt()},Ut=()=>{H.forEach(clearTimeout),H=[]},mn=De=>{for(const Oe of De.filter(Boolean)){const qe=q.value[Oe];if(!qe)continue;const wt=qe.querySelector(".comments-dialog");wt&&ee(Oe,wt.getBoundingClientRect().height)}},It=50,Zt=350,rt=De=>{Ut();const Oe=typeof De=="function"?De:()=>De;H.push(setTimeout(()=>mn(Oe()),It)),H.push(setTimeout(()=>mn(Oe()),Zt))},zt=()=>{l(),requestAnimationFrame(()=>{D(!1)})},Lt=(De,Oe)=>{!De||!Number.isFinite(Oe)||(D(!0),Tt(()=>{mn([De]),U(De,Oe,()=>{zt()})}))},An=()=>{W=null,ge+=1,be!=null&&(cancelAnimationFrame(be),be=null),D(!1)},Qt=()=>{!Ze&&!W||(xt(),An(),D(!0),x.value=0,yt!=null&&cancelAnimationFrame(yt),yt=requestAnimationFrame(()=>{yt=null,!Ze&&!W&&D(!1)}))},wn=()=>{Qt(),pe()},Wn=()=>{const De=Oe=>{!Oe?.addEventListener||Xt.has(Oe)||(Oe.addEventListener("scroll",wn,{passive:!0}),Xt.add(Oe))};De(i.parent);for(let Oe=y.value?.parentElement;Oe;Oe=Oe.parentElement)r.has(window.getComputedStyle(Oe).overflowY)&&De(Oe);De(window)},go=()=>{for(const De of Xt)De.removeEventListener?.("scroll",wn);Xt.clear()},jn=()=>{if(!W||we)return;we=!0;const De=ge;be!=null&&(cancelAnimationFrame(be),be=null),D(!0),Tt(()=>{if(we=!1,De!==ge){jn();return}const{key:Oe,targetClientY:qe}=W;mn([Oe]),U(Oe,qe,wt=>{if(De===ge){if(!wt){D(!1);return}be=requestAnimationFrame(()=>{be=null,De===ge&&D(!1)})}})})},Xn=(De,Oe)=>{const qe=Ak({previousIds:X,currentIds:Oe,removedId:De}),wt=(qe?q.value[qe]:null)?.getBoundingClientRect?.().top;return!qe||!Number.isFinite(wt)?(An(),!1):(W={key:qe,targetClientY:wt},ge+=1,jn(),!0)},Ao=De=>{const Oe=De?.target?.closest?.("[data-comment-action]"),qe=Oe?.getAttribute?.("data-comment-action");if(qe!=="resolve"&&qe!=="reject"||(xt(),Oe.getAttribute?.("aria-disabled")==="true"))return;const wt=Oe.closest?.("[data-comment-id]")?.getAttribute?.("data-comment-id");if(!wt||String(N.value??"")===String(wt))return;const ft=Ct.value.filter(an=>an.commentRef?.trackedChange).map((an,Dn)=>({id:an.id,index:Dn,top:an.top})).filter(an=>Number.isFinite(an.top)).sort((an,Dn)=>an.top-Dn.top||an.index-Dn.index).map(an=>an.id),Pt=Ak({previousIds:ft,currentIds:new Set(ft),removedId:wt}),_n=(Pt?q.value[Pt]:null)?.getBoundingClientRect?.().top;!Pt||!Number.isFinite(_n)||(Ze={removedKey:wt,targetKey:Pt,targetClientY:_n,applied:!1},it=wt,V.value=Pt,D(!0))};Vt(N,(De,Oe)=>{if(Ut(),!(Ze!=null&&it!=null&&[De,Oe].some(ft=>ft!=null&&String(ft)===String(it)))){if(it=null,De)xt(),An();else if(Oe){const ft=new Set(Ct.value.map(Pt=>Pt.id));ft.has(Oe)?An():Xn(Oe,ft)}}const qe=[De,Oe],wt=De&&De===lt.value&&Number.isFinite(p.value);Tt(()=>{if(wt){mn(qe);return}rt(qe)})}),Vt([N,lt,p],([De,Oe,qe])=>{!De||!Oe||De!==Oe||!Number.isFinite(qe)||Lt(De,qe)}),Vt(g,()=>{Ut(),Tt(()=>{rt(()=>Ct.value.map(De=>De.id))})}),Vt(c,()=>{if(J&&clearTimeout(J),!c.value){if(l(),W){jn();return}D(!1),x.value=0;return}if(!(R(c.value)?h.value:a.getComment(c.value)))return;const De=R(c.value)?"pending":N.value;if(De){if(De===lt.value&&Number.isFinite(p.value)){D(!0);return}Tt(()=>{J=setTimeout(()=>{const qe=q.value[De];if(!qe)return;const wt=i.parent?.getBoundingClientRect?.();if(!wt)return;const ft=Ct.value.find(Dn=>Dn.id===De),Pt=De==="pending"?oe():ft?.anchorTop;if(typeof Pt!="number"||isNaN(Pt))return;const _n=qe.getBoundingClientRect().top,an=wt.top+Pt;x.value+=an-_n},400)})}}),Vt(C,()=>{if(i.currentDocument.type==="application/pdf"){for(const De in Hl)delete Hl[De];B.value={},w.value+=1}});let Nr=new Set,rr=null,Pn=null;return Vt(Ct,De=>{const Oe=N.value?De.find(Jt=>Jt.id===N.value):null,qe=typeof Oe?.anchorTop=="number"&&Number.isFinite(Oe.anchorTop)?Oe.anchorTop:null,wt=qe!=null&&rr!=null&&Math.abs(qe-rr)>1,ft=typeof Oe?.top=="number"&&Number.isFinite(Oe.top)?Oe.top:null,Pt=ft!=null&&Pn!=null&&Math.abs(ft-Pn)>1;wt&&x.value!==0&&!Number.isFinite(p.value)?(x.value=0,D(!1)):Pt&&x.value!==0&&!Number.isFinite(p.value)&&!W&&(D(!0),x.value+=Pn-ft,Be!=null&&cancelAnimationFrame(Be),Be=requestAnimationFrame(()=>{Be=null,!W&&!Number.isFinite(p.value)&&D(!1)})),rr=qe,Pn=ft;const _n=De.map(Jt=>Jt.id),an=new Set(_n);if(Ze&&!Ze.applied&&!an.has(Ze.removedKey)){const{targetKey:Jt,targetClientY:Un}=Ze;Ze.applied=!0,an.has(Jt)&&Number.isFinite(Un)?(W={key:Jt,targetClientY:Un},ge+=1,jn()):xt()}if(Ze?.applied&&!an.has(Ze.targetKey)&&xt(),W&&!an.has(W.key)){const Jt=W.key;Xn(Jt,an)||(D(!1),x.value=0)}const Dn=new Set(Q.value);let Io=!1,Eo=-1/0,ki=1/0;const cn=y.value;if(cn){const Jt=cn.getBoundingClientRect();Eo=-Jt.top-600,ki=-Jt.top+window.innerHeight+600}const On=new Map(De.map(Jt=>[Jt.id,Jt]));for(const Jt of an)if(!Dn.has(Jt)){const Un=On.get(Jt);(!Un||Un.top>=Eo&&Un.top<=ki)&&(Dn.add(Jt),Io=!0)}for(const Jt of Dn)an.has(Jt)||(Dn.delete(Jt),Io=!0);Io&&(Q.value=Dn);for(const Jt of Nr)an.has(Jt)||delete Hl[Jt];const Fn=Nr.size!==an.size||[...Nr].some(Jt=>!an.has(Jt)),lr=X.length!==_n.length||X.some((Jt,Un)=>Jt!==_n[Un]);if(Fn){const Jt={};for(const Un of an)Hl[Un]&&(Jt[Un]=Hl[Un]);B.value=Jt,Tt(()=>{for(const Un of De){const ro=q.value[Un.id];if(!ro)continue;const Pi=ro.querySelector(".comments-dialog");Pi&&ee(Un.id,Pi.getBoundingClientRect().height)}})}W&&(Fn||lr)&&jn(),Nr=an,Tt(()=>{X=_n,tt()})}),Gn(()=>{Ke(),Wn(),window.addEventListener("resize",pe,{passive:!0}),document.addEventListener("pointerdown",Ft,!0),Tt(tt)}),gr(()=>{Ut(),J&&clearTimeout(J),xt(),An(),Be!=null&&(cancelAnimationFrame(Be),Be=null),yt!=null&&(cancelAnimationFrame(yt),yt=null),go(),window.removeEventListener("resize",pe),document.removeEventListener("pointerdown",Ft,!0),Ne!=null&&(cancelAnimationFrame(Ne),Ne=null),se&&(se.disconnect(),se=null,he.clear())}),(De,Oe)=>(ve(),Te("div",{class:"section-wrapper",ref_key:"floatingCommentsContainer",ref:y,onClickCapture:Ao,style:Sn({minHeight:Re.value+"px",transition:L.value?"none":void 0})},[Fe("div",{class:"sidebar-container",style:Sn({transform:`translateY(${x.value}px)`,transition:L.value?"none":void 0})},[(ve(!0),Te(Yt,null,mr(Ct.value,qe=>(ve(),Te("div",{key:qe.id,ref_for:!0,ref:wt=>$(qe.id,wt),"data-comment-id":qe.id,"data-comment-instance-id":qe.id,"data-comment-thread-id":qe.threadId,"data-comment-position-key":qe.instanceRef?.positionKey??"","data-comment-page-index":qe.pageIndex??"",class:on([{"is-direct-decision-continuity-target":qe.id===V.value},"comment-placeholder"]),style:Sn({top:qe.top+"px",height:qe.height+"px",transition:L.value?"none":void 0})},[Me(qe)?(ve(),hn(Pp,{key:qe.id+w.value,onReady:_,onResize:wt=>te(qe),class:"floating-comment",parent:e.parent,comment:qe.commentRef,"floating-instance-id":qe.id,"floating-page-index":qe.pageIndex,"floating-position-entry":qe.instanceRef?.positionEntry??null,"is-floating-instance-active":qe.id===N.value},null,8,["onResize","parent","comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])):vt("",!0)],14,n9))),128))],4)],36))}},o9=pn(r9,[["__scopeId","data-v-d8d03209"]]);Dt(),bn();var i9={class:"superdoc__pdf-comments-layer pdf-comments-layer","aria-hidden":"false"},s9=["data-id","data-comment-id","data-page-number","onClick","onKeydown"],a9="pdf",l9="#078383",c9="#B1124B",u9={__name:"PdfCommentsLayer",emits:["anchor-activate"],setup(e,{emit:t}){const n=t,r=da(),o=su(),{activeComment:i}=na(r),{documents:s,activeZoom:a}=na(o),{proxy:l}=vr(),c=y=>typeof y=="number"?Number.isFinite(y):typeof y=="string"&&y.trim()!==""?Number.isFinite(Number(y)):!1,u=y=>!!y&&c(y.top)&&c(y.left)&&c(y.right)&&c(y.bottom),d=Ee(()=>{const y=Array.isArray(s.value)?s.value:[];return new Set(y.filter(w=>w?.type===Vl).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}},S=Ee(()=>{const y=r.getFloatingComments;return Array.isArray(y)?y.filter(w=>w?.selection?.source===a9).filter(w=>!w.resolvedTime).filter(w=>g(w)!==null).filter(w=>u(w.selection?.selectionBounds)).filter(w=>p(w)).map(w=>{const x=g(w),L=v(w.selection.selectionBounds);return{commentId:x,page:w.selection?.page??null,isInternal:w.isInternal!==!1,bounds:L}}):[]}),C=y=>{const w=(a.value??100)/100,{top:x,left:L,right:V,bottom:G}=y.bounds,R=i.value===y.commentId,F=(y.isInternal?l9:c9)+(R?"66":"33");return{position:"absolute",top:x*w+"px",left:L*w+"px",width:(V-L)*w+"px",height:(G-x)*w+"px",backgroundColor:F}},A=y=>{r.setActiveComment(l.$superdoc,y.commentId),n("anchor-activate",y.commentId)};return(y,w)=>(ve(),Te("div",i9,[(ve(!0),Te(Yt,null,mr(S.value,x=>(ve(),Te("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:rn(L=>A(x),["stop","prevent"]),onKeydown:[oi(rn(L=>A(x),["stop","prevent"]),["enter"]),oi(rn(L=>A(x),["stop","prevent"]),["space"])]},null,44,s9))),128))]))}},d9=pn(u9,[["__scopeId","data-v-b5ad4c58"]]);Dt();var f9=({proxy:e,layers:t,documents:n,modules:r})=>{const o=Ee(()=>{const F=r.value?.whiteboard??r.whiteboard;return F===!1||F==null?null:F}),i=e?.$superdoc?.whiteboard,s=to([]),a=Jr({}),l=Jr({}),c=re(!1),u=re(0),d=re(0),h=re(1),g=re(o.value?.enabled??!1),p=()=>{if(c.value)return;u.value+=1;const F=d.value||s.value.length;F&&u.value>=F&&(c.value=!0,e?.$superdoc?.emit("whiteboard:ready",{whiteboard:i}))},v=F=>{if(!F)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&S(F)},S=F=>{const{pageIndex:Z,width:O,height:N,originalWidth:T,originalHeight:B}=F,Q={width:O,height:N,originalWidth:T,originalHeight:B};i?.setPageSize(Z,Q),a[Z]=Q;const q=i?.getPage(Z);q&&q.setSize(Q),i&&(s.value=i.getPages().sort((se,he)=>se.pageIndex-he.pageIndex).map(se=>eo(se)),d.value=s.value.length),Tt(()=>{G(),p()})},C=F=>{e?.$superdoc?.emit("whiteboard:change",F)},A=F=>{F.forEach(Z=>{const O=a[Z.pageIndex];O&&Z.setSize(O)}),s.value=F.map(Z=>eo(Z)),d.value=s.value.length,Tt(()=>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)},L=()=>{const F=n.value?.[0];F&&F.type==="application/pdf"&&V({doc:F})},V=({doc:F})=>{s.value.forEach(Z=>{const O=`${F.id}-page-${Z.pageIndex+1}`,N=document.querySelector(`[data-page-id="${O}"]`);if(!N)return;const T=N.getBoundingClientRect(),B=a[Z.pageIndex]||{},Q=B.originalWidth??Z.size?.originalWidth??T.width,q=B.originalHeight??Z.size?.originalHeight??T.height,se={width:T.width,height:T.height,originalWidth:Q,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(O=>{const N=`${F.id}-page-${O.pageIndex+1}`,T=document.querySelector(`[data-page-id="${N}"]`);if(!T)return;const B=T.getBoundingClientRect();l[O.pageIndex]={top:B.top-Z.top,left:B.left-Z.left}})};return i&&(i.on("change",C),i.on("setData",A),i.on("enabled",y),i.on("opacity",w),i.on("tool",x)),gr(()=>{i&&(i.off("change",C),i.off("setData",A),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:c,handleWhiteboardPageReady:v,updateWhiteboardPageSizes:L,updateWhiteboardPageOffsets:G}};Dt(),bn();var h9=["data-page-index"],p9={__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=re(null),r=()=>{const c=n.value;!c||!t.page||(t.page.mount(c),t.pageSize&&t.page.resize(t.pageSize.width,t.pageSize.height))},o=c=>{if(!t.page||!c?.dataTransfer||!t.enabled||t.whiteboard.getTool()!=="select")return;c.preventDefault(),c.stopPropagation();const u=n.value;if(!u)return;const d=u.getBoundingClientRect(),h=c.clientX-d.left,g=c.clientY-d.top,p=t.pageSize?.width,v=t.pageSize?.originalWidth??p,S=Number.isFinite(p)&&Number.isFinite(v)&&v?p/v:1;i(c,h,g,S)||s(c,h,g,S)||a(c,h,g)||l(c,h,g)},i=(c,u,d,h)=>{const g=c.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:u,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=(c,u,d,h)=>{const g=Array.from(c.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:u,y:d,src:p.result,type:"image"})},p.readAsDataURL(g),!0},a=(c,u,d)=>{const h=c.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:u,y:d,content:g.text}),!0):!1},l=(c,u,d)=>{const h=c.dataTransfer.getData("text/plain");return h?(t.page.addText({x:u,y:d,content:h}),!0):!1};return Vt(()=>[t.page,t.pageSize?.width,t.pageSize?.height],()=>{Tt(r)}),Gn(()=>{r()}),gr(()=>{t.page?.destroy()}),(c,u)=>(ve(),Te("div",{ref_key:"containerRef",ref:n,class:"whiteboard-page","data-page-index":e.page.pageIndex,onDragover:u[0]||(u[0]=rn(()=>{},["prevent"])),onDrop:rn(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,h9))}},m9=pn(p9,[["__scopeId","data-v-c876c9b5"]]);Dt(),bn();var g9={__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=Ee(()=>t.interactive==null?t.enabled:t.interactive);return(r,o)=>(ve(),Te("div",{class:"whiteboard-layer","aria-hidden":"true",style:Sn({opacity:e.opacity,pointerEvents:n.value?"auto":"none"})},[(ve(!0),Te(Yt,null,mr(e.pages,i=>(ve(),hn(m9,{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))}},v9=pn(g9,[["__scopeId","data-v-54546c3d"]]);function y9(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 Ik=["#1f6feb","#d1242f","#8250df","#bf3989","#1a7f37","#9a6700","#bc4c00","#0969da","#cf222e","#6639ba","#116329","#7d4e00"],b9=e=>e?`${typeof e.name=="string"?e.name:""} ${typeof e.email=="string"?e.email:""}`:"",w9=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},C9=e=>{const t=b9(e),n=w9(t)%Ik.length;return Ik[n]},ff=e=>typeof e=="string"&&e.length>0,k9=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(ff(o.email)&&ff(t[o.email]))return t[o.email];if(ff(o.name)&&ff(t[o.name]))return t[o.name]}if(n)try{const i=n(o);if(ff(i))return i}catch{}return C9(o)}},S9=["insertion","deletion","move","move-from","move-to","table-cell-insertion","table-cell-deletion","cell-merge","cell-split","image-insertion","image-deletion","image-property-change"],HH=new Set(S9),kr={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"},$H={"render.media.missing-relationship":kr.missingRelationship,"render.media.wrong-relationship-type":kr.unsupportedRelationshipType,"render.media.unsupported-target":kr.unsupportedRelationshipType,"render.media.invalid-image-size":kr.imageTooLarge,"render.media-resolver-unavailable":kr.missingMediaPart,"render.chart-not-supported":kr.unsupportedObject,"render.textbox.vml-unsupported":kr.vmlUnsupported},_9={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:kr.externalImageDeferred},missingRelationship:{family:"missingRelationship",support:"fail-closed",description:"Drawing references a relationship id absent from the owner part .rels.",contract:"none",diagnostic:kr.missingRelationship},missingMediaPart:{family:"missingMediaPart",support:"fail-closed",description:"Relationship resolves but the target media part bytes are missing or empty.",contract:"none",diagnostic:kr.missingMediaPart},wrongRelationshipType:{family:"wrongRelationshipType",support:"fail-closed",description:"Relationship exists but is not an image relationship type.",contract:"none",diagnostic:kr.unsupportedRelationshipType},unsupportedMime:{family:"unsupportedMime",support:"fail-closed",description:"Media MIME outside the supported allowlist (incl. GIF/BMP/ICO).",contract:"none",diagnostic:kr.unsupportedMime},oversizedMediaPart:{family:"oversizedMediaPart",support:"fail-closed",description:"Media part exceeds the host byte-size policy before bytes are materialized.",contract:"none",diagnostic:kr.imageTooLarge},unsafeSvg:{family:"unsafeSvg",support:"fail-closed",description:"SVG content rejected by the SVG safety policy.",contract:"none",diagnostic:kr.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:kr.unsupportedFormat},embeddedObject:{family:"embeddedObject",support:"fail-closed",description:"OLE / ActiveX / embedded package object.",contract:"none",diagnostic:kr.embeddedObjectNotSupported},smartArtOrDiagram:{family:"smartArtOrDiagram",support:"fail-closed",description:"SmartArt / diagram / unknown external graphic-data object.",contract:"none",diagnostic:kr.unsupportedObject},vml:{family:"vml",support:"fail-closed",description:"VML structure outside any supported image-like subset (default fail-closed policy).",contract:"none",diagnostic:kr.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:kr.vmlImageUnsupported},unsupportedGeometryCommand:{family:"unsupportedGeometryCommand",support:"fail-closed",description:"Custom geometry command the extractor does not implement, e.g. arcTo.",contract:"none",diagnostic:kr.unsupportedGeometryCommand},unsupportedAnchorFields:{family:"unsupportedAnchorFields",support:"fail-closed",description:"Anchor fields required for honest placement are unsupported (char-relative, alignment modes, etc.).",contract:"none",diagnostic:kr.anchorUnsupported},unsupportedWrapFields:{family:"unsupportedWrapFields",support:"fail-closed",description:"Wrap fields required for honest placement are unsupported (arbitrary wrap polygons, etc.).",contract:"none",diagnostic:kr.wrapUnsupported},alternateContentNoSupportedChoice:{family:"alternateContentNoSupportedChoice",support:"fail-closed",description:"mc:AlternateContent with no supported choice and no usable fallback.",contract:"none",diagnostic:kr.altContentNoSupportedChoice},groupChildUnsupported:{family:"groupChildUnsupported",support:"fail-closed",description:"Unsupported child inside an otherwise-supported group. Supported siblings are not dropped.",contract:"none",diagnostic:kr.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"}},GH=Object.keys(_9),WH=Object.freeze(["multiple-sections","furniture-page-tokens","non-balanceable-multi-column-sections","body-anchored-objects","footnotes","page-references","keep-constraints","tables","furniture-anchored-objects"]);Dt(),bn();var A9={class:"superdoc-html-viewer"},I9={class:"superdoc-html-viewer__document"},E9=["innerHTML"],T9={__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=re(""),o=t,i=()=>{const l=window.getSelection();console.debug("selection from html viewer",l),o("selection-change",l)},s=l=>new Promise((c,u)=>{const d=new FileReader;d.onload=h=>{const g=h.target.result;c(g)},d.onerror=h=>u(h),d.readAsText(l)}),a=async()=>{try{const l=await s(n.fileSource);r.value=l,o("ready",n.documentId)}catch(l){o("error",l),console.error("Error loading document",l)}};return Gn(()=>{a()}),(l,c)=>(ve(),Te("div",A9,[Fe("div",I9,[Fe("div",{class:"superdoc-html-viewer__content",innerHTML:r.value,onMouseup:i},null,40,E9)])]))}},x9=pn(T9,[["__scopeId","data-v-da3494ba"]]),R9=(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,c=s.parentCommentId!=null?String(s.parentCommentId):null,u=Lp(s),d=u!=null?String(u):null,h=a&&o.has(a)||l&&o.has(l),g=c&&o.has(c)||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};Dt();var Ek=re(!1);function Gi(){return{isHighContrastMode:Ek,setHighContrastMode:t=>{Ek.value=t}}}var KH="[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor",qH="sidebar",Tk=new Set(["auto","sidebar","inline"]);function M9(e){const t=e;return typeof t?.closest=="function"&&t.closest(".track-change-focused")!=null}function xk(e){if(!e||e===!1||typeof e!="object")return e;const t={...e},n=t.displayMode;Tk.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}Dt();var L9=".superdoc__document",P9=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,D9=e=>e+320+24;function O9({commentsModuleConfig:e,superdocRoot:t,layers:n}){const r=re(0),o=re(!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 S=document.querySelector(p.trim());if(a(S))return S}let v=g?.parentElement??null;for(;v;){if(a(v))return v;v=v.parentElement}return a(g)||g instanceof HTMLElement?g:null},c=()=>{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)))},u=()=>{c();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?.(L9),p=n.value,v=Number(g?.clientWidth??g?.getBoundingClientRect?.().width??0);if(Number.isFinite(v)&&v>0)return v;const S=Number(p?.clientWidth??p?.getBoundingClientRect?.().width??0);return Number.isFinite(S)&&S>0?S:816},h=()=>{const g=u(),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 S=p?.compactBreakpointPx;if(P9(S)){o.value=g<S;return}const C=d(),A=D9(C);o.value=g<A};return gr(()=>{i&&(i.disconnect(),i=null),s=null}),{superdocContainerWidth:r,isCompactCommentsMode:o,recalculateCompactCommentsMode:h,ensureCompactMeasurementObserver:c}}Dt();var Rk=320,nl=12,F9=220,N9=16,B9=500,Mk=".superdoc-comment-highlight[data-comment-ids]",Lk="data-comment-ids",z9=".sd-comment-anchor",d0=(e,t,n)=>Math.min(Math.max(e,t),n),bs=e=>Number(e),Wi=e=>Number.isFinite(e),f0=e=>e?.commentId??e?.importedId??null,Pk=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),V9=e=>{const t=e?.value;if(!t)return null;const n=bs(t.ts);if(!Wi(n)||Date.now()-n>B9)return null;const r=bs(t.x),o=bs(t.anchorRect?.bottom),i=Wi(o)?o:bs(t.y);return!Wi(r)||!Wi(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(Mk);for(const l of a)if(Pk(l.getAttribute(Lk)).includes("pending")&&typeof l.getBoundingClientRect=="function")return l.getBoundingClientRect()}const r=f0(t);if(!r)return null;const o=String(r),i=e.querySelectorAll(Mk);for(const a of i)if(Pk(a.getAttribute(Lk)).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},U9=(e,t)=>{const{entry:n}=e(f0(t)),r=bs(n?.bounds?.bottom);return Wi(r)?r:bs(n?.bounds?.top)},H9=({selectionPosition:e,comment:t,pendingComment:n})=>e.value?.source==="pdf"||t?.selection?.source==="pdf"||n.value?.selection?.source==="pdf",$9=({rootEl:e,layersRect:t,comment:n})=>{const r=f0(n);if(r==null)return NaN;const o=e.querySelector(`${z9}[data-id="${String(r)}"]`);if(!o||typeof o.getBoundingClientRect!="function")return NaN;const i=o.getBoundingClientRect();return bs(i.bottom)-bs(t.top)},G9=({comment:e,pendingComment:t,selectionPosition:n,activeZoom:r})=>{if(!t.value||e?.commentId!==t.value?.commentId)return NaN;const o=bs(n.value?.bottom);if(Wi(o))return o*(n.value?.source==="pdf"?(r.value??100)/100:1);const i=bs(n.value?.top);return Wi(i)?i*(n.value?.source==="pdf"?(r.value??100)/100:1):NaN},W9=({top:e,left:t})=>({top:`${Math.round(e)}px`,left:`${Math.round(t)}px`,right:"auto"}),K9=({rootRect:e,layersRect:t,anchorBottom:n,anchorClientX:r=NaN})=>{const o=t.top-e.top+n+N9,i=Math.max(nl,e.height-F9),s=d0(o,nl,i),a=Math.max(nl,e.width-Rk-nl);let l;if(Wi(r))l=d0(r-e.left+nl,nl,a);else{const c=e.width-(t.left-e.left+t.width)+nl;l=d0(e.width-c-Rk,nl,a)}return{top:s,left:l}};function q9({activeComment:e,pendingComment:t,activeCompactComment:n,showCommentsSidebar:r,selectionPosition:o,activeZoom:i,superdocRoot:s,layers:a,documents:l,resolveCommentPositionEntry:c,clearActiveComment:u,clearPendingComment:d}){const h={top:"12px",right:"12px"},g=re(0),p=re({x:null,y:null,ts:0,anchorRect:null});let v=null,S=null;const C=()=>{p.value={x:null,y:null,ts:0,anchorRect:null}},A=(L,V,G)=>{if(!l.value?.some(F=>F.type==="application/pdf"))return!1;const R=L.querySelector(".superdoc__compact-comment-popover");return!n.value||!R||R.contains(V)||G?!1:(t.value&&d(),u(),C(),!0)},y=L=>{const V=s.value;if(!V||!a.value?.contains(L.target))return;const G=(typeof document.elementsFromPoint=="function"?document.elementsFromPoint(L.clientX,L.clientY):[]).find(F=>F?.nodeType===1&&V.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")??(L.target?.nodeType===1?L.target.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"):null);if(A(V,L.target,G)||L.button!==0||L.pointerType!=="mouse")return;const R=G&&typeof G.getBoundingClientRect=="function"?G.getBoundingClientRect():null;R&&(p.value={x:L.clientX,y:R.bottom,ts:Date.now(),anchorRect:{left:R.left,right:R.right,top:R.top,bottom:R.bottom}})},w=Ee(()=>{g.value;const L=n.value;if(!L)return h;const V=s.value,G=a.value;if(!V||!G)return h;const R=V.getBoundingClientRect(),F=G.getBoundingClientRect(),Z=V9(p),O=Z?null:j9({rootEl:V,comment:L,pendingComment:t});let N=NaN,T=NaN;if(Z?(N=Z.y-F.top,T=Z.x):O?(N=O.bottom-F.top,T=O.left):N=U9(c,L),!Wi(N)&&H9({selectionPosition:o,comment:L,pendingComment:t})&&(N=$9({rootEl:V,layersRect:F,comment:L})),Wi(N)||(N=G9({comment:L,pendingComment:t,selectionPosition:o,activeZoom:i})),!Wi(N))return h;const B=K9({rootRect:R,layersRect:F,anchorBottom:N,anchorClientX:T});return W9(B)});return Vt([e,t,o,i,r,p],()=>{const L=typeof window<"u"?window.requestAnimationFrame:null,V=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&V?.(v),L&&(v=L(()=>{g.value+=1,v=null}))},{deep:!1}),Vt(n,(L,V)=>{if(!V&&L){const G=document.activeElement;G instanceof HTMLElement&&(S=G)}},{deep:!1}),Vt(t,(L,V)=>{!V&&L&&C()}),Gn(()=>{document.addEventListener("pointerdown",y,!0)}),gr(()=>{document.removeEventListener("pointerdown",y,!0);const L=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&(L?.(v),v=null),S=null}),{compactCommentPopoverStyle:w,closeCompactCommentPopover:()=>{n.value&&(t.value&&d(),u(),S&&typeof S.focus=="function"&&S.focus(),S=null)},resetClickAnchor:C}}function ws(...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 h0(...e){for(const t of e)if(t!==void 0)return t}function Dk(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,c)=>{l?.kind!=="entity"||l.entityType!=="trackedChange"||typeof l.entityId=="string"&&l.entityId.length>0&&c.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 c=s(l?.from),u=s(l?.to);c&&r.add(c),u&&n.add(u),c&&u&&c!==u&&o.push({from:c,to:u})}for(const l of r)n.delete(l);const a=Y9(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 Y9(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 hf=e=>new Set(Array.from(e??[]).filter(t=>typeof t=="string"&&t.length>0)),X9=e=>typeof e?.id=="string"&&e.id.length>0?e.id:typeof e?.changeId=="string"&&e.changeId.length>0?e.changeId:typeof e?.address?.entityId=="string"&&e.address.entityId.length>0?e.address.entityId:null,Z9=(e,t)=>e?.adapter===t?.adapter&&e?.documentId===t?.documentId&&e?.editor===t?.editor&&e?.reconcileToken===t?.reconcileToken;function Ok({getContext:e,reconcile:t,hydrate:n,onReconciled:r}){const o=new Map;let i=null,s=0,a=0,l=null,c=!1;const u=[],d=(R,F)=>{for(let Z=u.length-1;Z>=0;Z-=1){const O=u[Z];O.generation!==a||O.version>R||(u.splice(Z,1),O.resolve(F===!0&&O.requiresAllResolved?i==null:F))}},h=(R,F)=>a===R&&Z9(F,e()),g=(R,F)=>{const Z=new Set;for(const O of R)o.get(O)===F.get(O)&&(o.delete(O),Z.add(O));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},S=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,O=!1)=>{if(!(!O&&F.size===0||typeof r!="function"))try{await r(R,F,Z)}catch{}},A=R=>hf(R?.resolvedIds??(R?.items??[]).map(X9).filter(Boolean)),y=async(R,F,Z)=>{const O=await t(R,{upsertIds:new Set(F.keys()),removedIds:new Set,reconcileMode:"targeted"});if(!h(Z,R))return;const N=A(O),T=g(N,F);if(await C(R,T,O),new Set([...F].filter(([se,he])=>o.get(se)===he).map(([se])=>se)).size===0)return;const B=await n(R,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1});if(!h(Z,R))return;const Q=A(B),q=g(Q,F);await C(R,q,B)},w=async(R,F,Z)=>{const O=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 N=O?.ok===!0,T=N&&O?.complete===!0&&O?.sourceCoverageComplete===!0,B=N?A(O):new Set,Q=T?g(new Set(F.keys()),F):new Set;await C(R,T?Q:B,{...O,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 O=e();if(!O?.adapter)return null;c=!1;const N=a;return l=Promise.resolve().then(async()=>{if(R){let T=null;try{T=await t(O,{upsertIds:new Set,removedIds:new Set,allResolved:R.fact,reconcileMode:"targeted"})}catch{}if(!h(N,O))return;T?.ok===!0&&(i===R&&(i=null),await C(O,new Set,T,!0))}Z.size>0&&await w(O,Z,N).catch(()=>{}),F.size>0&&await y(O,F,N).catch(()=>{})}).catch(()=>{}).finally(()=>{l=null,c&&x()}),l},L=(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",O=hf(R.removedIds),N=hf(R.upsertIds);for(const B of O){const Q=o.get(B);Q?.reconcileMode==="authoritative"?o.set(B,{...Q,version:++s,gate:F,ready:!1}):o.delete(B)}const T=e();if(O.size>0&&N.size===0&&T?.adapter&&!R.allResolved)try{Promise.resolve(t(T,{upsertIds:new Set,removedIds:O})).catch(()=>{})}catch{}for(const B of N)if(!O.has(B)){const Q=o.get(B);o.set(B,{version:++s,gate:F,ready:!1,reconcileMode:Z==="authoritative"||Q?.reconcileMode==="authoritative"?"authoritative":"targeted"})}},V=R=>L(R,"render");return{enqueue:V,enqueueAfterPaint(R,F){if(!R||typeof F!="function")return V(R),Promise.resolve(!1);L(R,"exact-paint");const Z=e(),O=a,N=s;if(!Z?.adapter)return S(N),Promise.resolve(!1);const T=new Promise(q=>{u.push({generation:O,version:N,requiresAllResolved:!!R.allResolved,resolve:q})}),B=new Set([...hf(R.upsertIds),...hf(R.removedIds)]),Q=new Map([...B].flatMap(q=>{const se=o.get(q);return se?[[q,se]]:[]}));return Promise.resolve().then(()=>F()).then(async()=>{if(!h(O,Z)){d(N,!1);return}let q=v();S(N)&&(q=!0);for(const[Ne,pe]of Q)o.get(Ne)===pe&&(pe.ready||(q=!0),pe.ready=!0);l&&(q||N>0)&&(c=!0);const se=l,he=x();if(he&&await he,se){const Ne=l;Ne&&Ne!==se&&await Ne}if(!h(O,Z)){d(N,!1);return}d(N,!0)}).catch(()=>{if(!h(O,Z)){d(N,!1);return}for(const[q,se]of Q)o.get(q)===se&&(se.gate="render");i?.gate==="exact-paint"&&(i.gate="render"),d(N,!1)}),T},onRender:(R=!1)=>{const F=v();l&&(F||R)&&(c=!0),x()},reset(){for(const R of u.splice(0))R.resolve(!1);a+=1,o.clear(),i=null,c=!1},getPendingIds(){return new Set(o.keys())}}}function Q9(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 J9="no-author-configured",eM="author-required",Fk="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 Nk(e){return typeof e=="string"&&e.includes(J9)}function tM(e){if(!e||e.type!=="mutation:rejected")return!1;if(e.failureSource==="receipt"){const t=e.failure;return t?t.code==="PRECONDITION_FAILED"&&Nk(t.message):!1}return e.failureSource==="shell"?e.reason==="author-required"?!0:e.reason==="PRECONDITION_FAILED"&&Nk(e.message):!1}function nM(){const e=new Set,t=n=>typeof n=="string"&&n.length>0?n:"__default__";return{shouldNotify(n,r){if(!tM(r))return!1;const o=t(n);return e.has(o)?!1:(e.add(o),!0)},clear(n){e.delete(t(n))}}}var rM=e=>!!(e?.anchor&&e?.focus&&(e.anchor.blockId!==e.focus.blockId||e.anchor.blockOffset!==e.focus.blockOffset)),oM=(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)},iM=(e,t)=>e!=="editing"&&e!=="suggesting"?!1:rM(t),sM=Dr((()=>{})),aM=id({default:()=>qk}),Bk,zk,Vk,jk,Uk,Hk,$k,Gk,Wk,Kk,qk,lM=Dr((()=>{Dt(),sM(),bn(),Bk=["onKeydown"],zk=["id"],Vk={class:"sd-password-prompt__description"},jk={class:"sd-password-prompt__field"},Uk=["placeholder","disabled","aria-label"],Hk={key:0,class:"sd-password-prompt__error",role:"alert"},$k={class:"sd-password-prompt__actions"},Gk=["disabled"],Wk=["disabled"],Kk={__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=re(""),r=re(!1),o=re(t.passwordPrompt.errorCode==="DOCX_PASSWORD_INVALID"),i=re(o.value?t.passwordPrompt.texts.invalidMessage:""),s=Ee(()=>o.value?t.passwordPrompt.texts.invalidTitle:t.passwordPrompt.texts.title),a=Ee(()=>n.value.length>0&&!r.value);async function l(){if(!a.value)return;r.value=!0,i.value="";const u=await t.passwordPrompt.attemptPassword(n.value);if(u.success){t.resolve({password:n.value});return}r.value=!1,n.value="",u.errorCode==="DOCX_PASSWORD_INVALID"?(o.value=!0,i.value=t.passwordPrompt.texts.invalidMessage):u.errorCode==="timeout"?i.value=t.passwordPrompt.texts.timeoutMessage:i.value=t.passwordPrompt.texts.genericErrorMessage}function c(){t.close("user-cancelled")}return(u,d)=>(ve(),Te("div",{class:"sd-password-prompt",onKeydown:oi(rn(l,["prevent"]),["enter"])},[Fe("h3",{id:`sd-password-prompt-heading-${e.surfaceId}`,class:"sd-password-prompt__heading"},Ht(s.value),9,zk),Fe("p",Vk,Ht(e.passwordPrompt.texts.description),1),Fe("div",jk,[Ks(Fe("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,Uk),[[Ri,n.value]])]),i.value?(ve(),Te("p",Hk,Ht(i.value),1)):vt("",!0),Fe("div",$k,[Fe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--cancel",disabled:r.value,onClick:c},Ht(e.passwordPrompt.texts.cancelLabel),9,Gk),Fe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--submit",disabled:!a.value,onClick:l},Ht(r.value?e.passwordPrompt.texts.busyLabel:e.passwordPrompt.texts.submitLabel),9,Wk)])],40,Bk))}},qk=pn(Kk,[["__scopeId","data-v-ecf7f6fb"]])}));Dt();var cM=["DOCX_PASSWORD_REQUIRED","DOCX_PASSWORD_INVALID"],uM=3e4,Mi={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 dM({getSurfaceManager:e,getPasswordPromptConfig:t,onUnhandled:n}){const r=[],o=to(null),i=new Map;let s=!1;function a(p,v,S){if(!p||!cM.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 A=r.find(y=>y.doc.id===p.id);return A?(A.errorCode=v,A.originalException=S,!0):(o.value?.doc.id===p.id||(r.push({doc:p,errorCode:v,originalException:S}),u()),!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 c(){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 u(){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),u()})}async function d({doc:p,errorCode:v,originalException:S}){const C=e();if(!C||s)return;const A=h(),y=V=>(p.password=V,p.editorMountNonce++,new Promise(G=>{const R=setTimeout(()=>{i.delete(p.id),G({success:!1,errorCode:"timeout"})},uM);i.set(p.id,{resolve:G,timer:R})})),w={documentId:p.id,errorCode:v,texts:A.texts,attemptPassword:y},x=g(A,{documentId:p.id,errorCode:v,texts:A.texts});if(x.suppressed){n?.(p,v,S),u();return}o.value={doc:p,surfaceHandle:null};let L;if(x.component)L=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:A.texts.title,component:eo(x.component),props:{...x.props,passwordPrompt:w}});else if(x.render){const V=x.render;L=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:A.texts.title,render:G=>V({container:G.container,passwordPrompt:w,resolve:G.resolve,close:G.close,surfaceId:G.surfaceId,mode:G.mode})})}else{const V=(await Promise.resolve().then(()=>(lM(),aM))).default,G=`password-prompt-${p.id}`;L=C.open({id:G,mode:"dialog",closeOnBackdrop:!1,ariaLabelledBy:`sd-password-prompt-heading-${G}`,component:eo(V),props:{passwordPrompt:w}})}o.value={doc:p,surfaceHandle:L},await L.result,o.value=null,u()}function h(){const p=t();if(p===!1)return{enabled:!1,texts:Mi};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??Mi.title,invalidTitle:v.invalidTitle??Mi.invalidTitle,description:v.description??Mi.description,placeholder:v.placeholder??Mi.placeholder,inputAriaLabel:v.inputAriaLabel??Mi.inputAriaLabel,submitLabel:v.submitLabel??Mi.submitLabel,cancelLabel:v.cancelLabel??Mi.cancelLabel,busyLabel:v.busyLabel??Mi.busyLabel,invalidMessage:v.invalidMessage??Mi.invalidMessage,timeoutMessage:v.timeoutMessage??Mi.timeoutMessage,genericErrorMessage:v.genericErrorMessage??Mi.genericErrorMessage},component:v.component,props:v.props,render:v.render,resolver:v.resolver}}function g(p,v){if(typeof p.resolver=="function"){const S=p.resolver(v);if(S!=null&&S.type!=="default"){if(S.type==="none")return{suppressed:!0};if(S.type==="custom")return{component:S.component,props:S.props};if(S.type==="external")return{render:S.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:c}}function Yk(e,{getCurrentSession:t,applySlice:n,onSettled:r}){return()=>{if(e===t())try{n(e.getSnapshot())}catch{}r()}}var fM=Dr((()=>{})),hM=id({default:()=>yS}),Xk,Zk,Qk,Jk,eS,tS,nS,rS,oS,iS,sS,aS,lS,cS,uS,dS,fS,hS,pS,mS,gS,vS,yS,pM=Dr((()=>{Dt(),fM(),bn(),Xk=["onKeydown"],Zk={class:"sd-find-replace__row"},Qk=["title","aria-label","aria-expanded"],Jk=["value","placeholder","aria-label"],eS={key:0,class:"sd-find-replace__count"},tS=["title","aria-label","aria-pressed"],nS=["title","aria-label","aria-pressed"],rS=["title","aria-label","aria-pressed"],oS={class:"sd-find-replace__nav"},iS=["disabled","title","aria-label"],sS=["disabled","title","aria-label"],aS=["title","aria-label"],lS={key:0,class:"sd-find-replace__row"},cS={class:"sd-find-replace__field"},uS=["value","placeholder","aria-label"],dS={class:"sd-find-replace__nav sd-find-replace__nav--actions"},fS=["disabled","title"],hS=["disabled","title"],pS={key:1,class:"sd-find-replace__error",role:"alert"},mS={key:0,class:"sd-find-replace__row-indent","aria-hidden":"true"},gS={class:"sd-find-replace__error-text"},vS={__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=re(null),r=Ee(()=>{const p=t.findReplace;return!!(!p.hasMatches?.value||p.replacePending?.value===!0||p.canReplace&&p.canReplace.value===!1)}),o=Ee(()=>t.findReplace.ignoreDiacriticsSupported?.value!==!1),i=Ee(()=>t.findReplace.replaceEnabled&&t.findReplace.replaceCanMutate?.value!==!1),s=Ee(()=>t.findReplace.regexSupported?.value===!0),a=Ee(()=>t.findReplace.searchError?.value??null);function l(p){p.key==="Enter"&&!p.shiftKey?(p.preventDefault(),c()):p.key==="Enter"&&p.shiftKey&&(p.preventDefault(),u())}function c(){t.findReplace.goNext(),g()}function u(){t.findReplace.goPrev(),g()}function d(){t.findReplace.close("user-closed")}function h(p){const v=[];let S=p?.parentElement??null;for(;S;){const A=S.ownerDocument?.defaultView?.getComputedStyle?.(S);if(A){const y=`${A.overflowY} ${A.overflowX}`;(y.includes("auto")||y.includes("scroll"))&&v.push(S)}S=S.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(S=>({el:S,top:S.scrollTop,left:S.scrollLeft}));p.focus({preventScroll:!0});for(const{el:S,top:C,left:A}of v)S.scrollTop!==C&&(S.scrollTop=C),S.scrollLeft!==A&&(S.scrollLeft=A)}return Gn(()=>{t.findReplace.registerFocusFn(g)}),(p,v)=>(ve(),Te("div",{class:"sd-find-replace",onKeydown:oi(rn(d,["stop"]),["esc"])},[Fe("div",Zk,[i.value?(ve(),Te("button",{key:0,type:"button",class:on(["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]=S=>e.findReplace.showReplace.value=!e.findReplace.showReplace.value)},[...v[14]||(v[14]=[Fe("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true"},[Fe("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,Qk)):vt("",!0),Fe("div",{class:on(["sd-find-replace__field",{"sd-find-replace__field--error":a.value}])},[v[15]||(v[15]=Fe("svg",{class:"sd-find-replace__search-icon",viewBox:"0 0 16 16",width:"15",height:"15","aria-hidden":"true"},[Fe("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)),Fe("input",{ref_key:"findInputRef",ref:n,value:e.findReplace.findQuery.value,onInput:v[1]||(v[1]=S=>e.findReplace.findQuery.value=S.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,Jk),e.findReplace.findQuery.value&&!a.value?(ve(),Te("span",eS,Ht(e.findReplace.matchLabel.value),1)):vt("",!0),Fe("button",{type:"button",class:on(["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]=rn(()=>{},["prevent"])),onClick:v[3]||(v[3]=S=>e.findReplace.caseSensitive.value=!e.findReplace.caseSensitive.value)},Ht(e.findReplace.texts.matchCaseLabel),43,tS),o.value?(ve(),Te("button",{key:1,type:"button",class:on(["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]=rn(()=>{},["prevent"])),onClick:v[5]||(v[5]=S=>e.findReplace.ignoreDiacritics.value=!e.findReplace.ignoreDiacritics.value)},Ht(e.findReplace.texts.ignoreDiacriticsLabel),43,nS)):vt("",!0),s.value?(ve(),Te("button",{key:2,type:"button",class:on(["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]=rn(()=>{},["prevent"])),onClick:v[7]||(v[7]=S=>e.findReplace.regex.value=!e.findReplace.regex.value)},Ht(e.findReplace.texts.regexLabel),43,rS)):vt("",!0)],2),Fe("div",oS,[Fe("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]=S=>u())},[...v[16]||(v[16]=[Fe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Fe("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,iS),Fe("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]=S=>c())},[...v[17]||(v[17]=[Fe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Fe("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,sS),v[19]||(v[19]=Fe("span",{class:"sd-find-replace__divider","aria-hidden":"true"},null,-1)),Fe("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]=[Fe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Fe("path",{d:"m4.5 4.5 7 7m0-7-7 7",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,aS)])]),e.findReplace.showReplace.value&&i.value?(ve(),Te("div",lS,[v[20]||(v[20]=Fe("span",{class:"sd-find-replace__row-indent","aria-hidden":"true"},null,-1)),Fe("div",cS,[Fe("input",{value:e.findReplace.replaceText.value,onInput:v[10]||(v[10]=S=>e.findReplace.replaceText.value=S.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]=oi(rn(S=>e.findReplace.replaceCurrent(),["prevent"]),["enter"]))},null,40,uS)]),Fe("div",dS,[Fe("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]=S=>e.findReplace.replaceCurrent())},Ht(e.findReplace.texts.replaceLabel),9,fS),Fe("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]=S=>e.findReplace.replaceAll())},Ht(e.findReplace.texts.replaceAllLabel),9,hS)])])):vt("",!0),a.value?(ve(),Te("div",pS,[i.value?(ve(),Te("span",mS)):vt("",!0),Fe("span",gS,Ht(a.value),1)])):vt("",!0)],40,Xk))}},yS=pn(vS,[["__scopeId","data-v-41f37c29"]])}));Dt();var br={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 mM(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 gM({getSurfaceManager:e,getActiveEditor:t,activeEditorRef:n,getFindReplaceConfig:r,getSuperDocUI:o}){let i=null,s=null,a=null,l=!1,c=!1;const u=re(!1);let d=null;const h=re(""),g=re(""),p=re(!1),v=re(!1),S=re(!1),C=re(!1),A=re(0),y=re(-1),w=re(!0),x=re(!1),L=re(!0),V=re(!1),G=re(null);let R=br;const F=Ee(()=>h.value?A.value===0?R.noResultsLabel:`${y.value+1} of ${A.value}`:""),Z=Ee(()=>A.value>0),O=Ee(()=>Z.value&&!x.value&&w.value);let N=null,T=null;function B(H){return typeof H?.commands?.setSearchSession=="function"}function Q(){try{const H=(typeof o=="function"?o():null)?.search;return H&&typeof H.search=="function"?H:null}catch{return null}}function q(H){H&&(A.value=typeof H.total=="number"?H.total:0,y.value=typeof H.activeIndex=="number"?H.activeIndex:-1,w.value=H.canReplace===!0,G.value=H.reason==="search-invalid-pattern"?R.invalidPatternLabel:null)}function se(){if(a){he();return}if(s){if(!h.value){try{s.commands.clearSearchSession()}catch{}A.value=0,y.value=-1;return}try{const H=s.commands.setSearchSession(h.value,{caseSensitive:p.value,ignoreDiacritics:v.value,highlight:!0,searchModel:Re().includeDeletedText?"raw":"visible"});A.value=H.matches.length,y.value=H.activeMatchIndex}catch{}}}function he(){const H=a;if(H){if(!h.value){try{H.clear()}catch{}A.value=0,y.value=-1,G.value=null;return}try{q(H.search(h.value,{caseSensitive:p.value,includeDeletedText:Re().includeDeletedText===!0,regex:S.value}))}catch{}}}function Ne(){N&&clearTimeout(N),N=setTimeout(se,150)}Vt(h,()=>{u.value&&Ne()}),Vt(p,()=>{u.value&&se()}),Vt(v,()=>{u.value&&se()}),Vt(S,()=>{u.value&&se()});let pe=!0;function ye(){if(Z.value){if(a){try{a.next(),q(a.getSnapshot())}catch{}return}if(s)try{const H=s.commands.nextSearchMatch();y.value=H.activeMatchIndex}catch{}}}function me(){if(Z.value){if(a){try{a.previous(),q(a.getSnapshot())}catch{}return}if(s)try{const H=s.commands.previousSearchMatch();y.value=H.activeMatchIndex}catch{}}}function _e(){if(pe&&!x.value&&Z.value){if(a){if(!w.value)return;const H=a;x.value=!0;const J=Yk(H,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let X=null;try{X=H.replace(g.value)}catch{}X&&typeof X.then=="function"?Promise.resolve(X).then(J,J):J();return}if(s)try{const H=s.commands.replaceSearchMatch(g.value);A.value=H.matches.length,y.value=H.activeMatchIndex}catch{}}}function oe(){if(pe&&!x.value&&Z.value){if(a){if(!w.value)return;const H=a;x.value=!0;const J=Yk(H,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let X=null;try{X=H.replaceAll(g.value)}catch{}X&&typeof X.then=="function"?Promise.resolve(X).then(J,J):J();return}if(s)try{s.commands.replaceAllSearchMatches(g.value),A.value=0,y.value=-1}catch{}}}function Me(){if(a){try{q(a.getSnapshot())}catch{}return}const H=mM(s);if(!H)return;const J=H.searchResults,X=Array.isArray(J)?J.length:0,W=H.activeMatchIndex??-1;X!==A.value&&(A.value=X),W!==y.value&&(y.value=W)}function Ge(){lt(),T=setInterval(Me,200)}function lt(){N&&clearTimeout(N),N=null,T&&clearInterval(T),T=null}function Ct(){h.value="",g.value="",p.value=!1,v.value=!1,S.value=!1,G.value=null,C.value=!1,A.value=0,y.value=-1,w.value=!0,x.value=!1}function Re(){const H=typeof r=="function"?r():void 0;if(H===!1||H==null)return{enabled:!1,texts:br,replaceEnabled:!0};if(H===!0)return{enabled:!0,texts:br,replaceEnabled:!0};const J=typeof H=="object"?H:{};if(J.component!=null&&typeof J.render=="function")throw new Error('modules.surfaces.findReplace cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{findPlaceholder:J.findPlaceholder??br.findPlaceholder,findAriaLabel:J.findAriaLabel??br.findAriaLabel,replacePlaceholder:J.replacePlaceholder??br.replacePlaceholder,replaceAriaLabel:J.replaceAriaLabel??br.replaceAriaLabel,noResultsLabel:J.noResultsLabel??br.noResultsLabel,previousMatchLabel:J.previousMatchLabel??br.previousMatchLabel,previousMatchAriaLabel:J.previousMatchAriaLabel??br.previousMatchAriaLabel,nextMatchLabel:J.nextMatchLabel??br.nextMatchLabel,nextMatchAriaLabel:J.nextMatchAriaLabel??br.nextMatchAriaLabel,closeLabel:J.closeLabel??br.closeLabel,closeAriaLabel:J.closeAriaLabel??br.closeAriaLabel,replaceLabel:J.replaceLabel??br.replaceLabel,replaceAllLabel:J.replaceAllLabel??br.replaceAllLabel,toggleReplaceLabel:J.toggleReplaceLabel??br.toggleReplaceLabel,toggleReplaceAriaLabel:J.toggleReplaceAriaLabel??br.toggleReplaceAriaLabel,matchCaseLabel:J.matchCaseLabel??br.matchCaseLabel,matchCaseAriaLabel:J.matchCaseAriaLabel??br.matchCaseAriaLabel,regexLabel:J.regexLabel??br.regexLabel,regexAriaLabel:J.regexAriaLabel??br.regexAriaLabel,invalidPatternLabel:J.invalidPatternLabel??br.invalidPatternLabel,ignoreDiacriticsLabel:J.ignoreDiacriticsLabel??br.ignoreDiacriticsLabel,ignoreDiacriticsAriaLabel:J.ignoreDiacriticsAriaLabel??br.ignoreDiacriticsAriaLabel},replaceEnabled:J.replaceEnabled??!0,includeDeletedText:J.includeDeletedText??!1,component:J.component,props:J.props,render:J.render,resolver:J.resolver,floating:J.floating&&typeof J.floating=="object"?J.floating:void 0}}function Ke(H,J){if(typeof H.resolver=="function"){const X=H.resolver(J);if(X!=null&&X.type!=="default"){if(X.type==="none")return{suppressed:!0};if(X.type==="custom")return{component:X.component,props:X.props};if(X.type==="external")return{render:X.render}}}return H.component!=null?{component:H.component,props:H.props}:typeof H.render=="function"?{render:H.render}:{builtin:!0}}function tt(H,J){return{findQuery:h,replaceText:g,caseSensitive:p,ignoreDiacritics:v,regex:S,showReplace:C,matchCount:A,activeMatchIndex:y,matchLabel:F,hasMatches:Z,canReplace:O,replaceCanMutate:w,replacePending:x,ignoreDiacriticsSupported:L,regexSupported:V,searchError:G,replaceEnabled:H.replaceEnabled??!0,texts:H.texts,goNext:ye,goPrev:me,replaceCurrent:_e,replaceAll:oe,registerFocusFn:X=>{d=X},close:X=>J(X)}}function ee(H){return{get findQuery(){return H.findQuery.value},set findQuery(J){H.findQuery.value=J},get replaceText(){return H.replaceText.value},set replaceText(J){H.replaceText.value=J},get caseSensitive(){return H.caseSensitive.value},set caseSensitive(J){H.caseSensitive.value=J},get ignoreDiacritics(){return H.ignoreDiacritics.value},set ignoreDiacritics(J){H.ignoreDiacritics.value=J},get regex(){return H.regex.value},set regex(J){H.regex.value=J},get regexSupported(){return H.regexSupported.value},get searchError(){return H.searchError.value},get replaceCanMutate(){return H.replaceCanMutate.value},get showReplace(){return H.showReplace.value},set showReplace(J){H.showReplace.value=J},get matchCount(){return H.matchCount.value},get activeMatchIndex(){return H.activeMatchIndex.value},get matchLabel(){return H.matchLabel.value},get hasMatches(){return H.hasMatches.value},get canReplace(){return H.canReplace.value},get replacePending(){return H.replacePending.value},get ignoreDiacriticsSupported(){return H.ignoreDiacriticsSupported.value},replaceEnabled:H.replaceEnabled,texts:H.texts,goNext:H.goNext,goPrev:H.goPrev,replaceCurrent:H.replaceCurrent,replaceAll:H.replaceAll,registerFocusFn:H.registerFocusFn,close:H.close}}function _(H){if(H){if(typeof H?.commands?.clearSearchSession=="function"){try{H.commands.clearSearchSession()}catch{}return}if(a&&H===s)try{a.clear()}catch{}}}function te(){try{if(l||!e()||!t())return!1;if(i&&u.value)return!0;const H=Re();if(!H.enabled||Ke(H,{texts:H.texts,replaceEnabled:H.replaceEnabled??!0}).suppressed)return!1;if(!B(t())){const J=Q();if(!J)return!1;try{if(J.getSnapshot?.().available!==!0)return!1}catch{return!1}}return!0}catch{return!1}}async function D(){if(l)return;const H=e();if(H){if(i&&u.value){d?.();return}if(!c){c=!0;try{const J=t();if(!J){c=!1;return}const X=Re();if(!X.enabled){c=!1;return}const W=Ke(X,{texts:X.texts,replaceEnabled:X.replaceEnabled??!0});if(W.suppressed){c=!1;return}Ct(),R=X.texts,pe=X.replaceEnabled??!0;const we={placement:"top-right",autoFocus:!0,width:420,...X.floating??{}};if(s&&s!==J&&_(s),s=J,a=B(J)?null:Q(),L.value=!a,V.value=!!a,a)try{q(a.getSnapshot())}catch{}d=null;let ge=()=>{};const be=tt(X,it=>ge(it));let Be;if(W.component)Be=H.open({mode:"floating",ariaLabel:X.texts.findAriaLabel,closeOnEscape:!0,floating:we,component:eo(W.component),props:{...W.props,findReplace:be}});else if(W.render){const it=W.render;Be=H.open({mode:"floating",ariaLabel:X.texts.findAriaLabel,closeOnEscape:!0,floating:we,render:yt=>it({container:yt.container,findReplace:ee(be),resolve:yt.resolve,close:yt.close,surfaceId:yt.surfaceId,mode:yt.mode})})}else{let it;try{it=(await Promise.resolve().then(()=>(pM(),hM))).default}catch{c=!1;return}if(l||i&&u.value){c=!1;return}const yt=t()||J;s!==yt&&(_(s),s=yt,a=B(yt)?null:Q(),L.value=!a),Be=H.open({mode:"floating",ariaLabel:X.texts.findAriaLabel,component:eo(it),closeOnEscape:!0,floating:we,props:{findReplace:be}})}ge=it=>Be.close(it??"programmatic"),i=Be,u.value=!0,c=!1,Ge();const Ze=Be.id;Be.result.then(()=>{i?.id===Ze?(lt(),_(s),i=null,u.value=!1,d=null):_(J!==s?J:null)})}catch(J){throw c=!1,J}}}}function U(){i&&i.close("programmatic")}n&&Vt(n,(H,J)=>{!u.value||!i||H!==J&&(_(J),U())});function $(){l=!0,lt(),U(),s=null,a=null,d=null}return{open:D,close:U,isOpen:u,wouldOpen:te,destroy:$}}var pf=null;function p0(e){e!=null&&(pf=e)}function vM(e){pf===e&&(pf=null)}function yM(e){return pf===null||pf===e}function bM(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)&&yM(n)}var wM=/^(https?|mailto|tel):/i,CM=/^(javascript|data|vbscript):/i,kM=/^[a-z][a-z0-9+.-]*:/i;function SM(e){if(typeof e!="string")return null;const t=e.trim();return t?t.startsWith("#")?{href:t}:CM.test(t)?null:kM.test(t)?wM.test(t)?{href:t}:null:{href:t}:null}var _M='<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>',AM='<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>',IM='<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>',bS='<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>',EM=`<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(S=>`<p>${u(S).replace(/\n/g,"<br>")}</p>`).join(""):"<p></p>"},g=Ee({get:()=>d(o.value),set:p=>{o.value=h(p)}});return Gn(c),Vt(o,c),t({focus:a}),(p,v)=>(ve(),Te("div",F7,[e.includeHeader?(ve(),hn(s0,{key:0,config:e.config,comment:e.comment,"is-pending-input":!0},null,8,["config","comment"])):vt("",!0),Fe("div",{class:on(["comment-entry",{"sd-input-active":e.isFocused}])},[Ks(Fe("textarea",{ref_key:"inputRef",ref:i,class:"superdoc-field",placeholder:"Add a comment","onUpdate:modelValue":v[0]||(v[0]=S=>g.value=S),rows:"1",onInput:l,onFocus:v[1]||(v[1]=S=>s(!0)),onBlur:v[2]||(v[2]=S=>s(!1))},null,544),[[Ri,g.value]])],2)]))}},l0=pn(N7,[["__scopeId","data-v-cc54b489"]]);Dt(),bn();var B7=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],z7={key:0,class:"existing-internal-input"},V7={class:"new-comment-input-wrapper"},j7={class:"reply-actions"},U7=["disabled"],H7={key:0,class:"resolved-badge"},$7=["innerHTML"],G7={key:1,class:"existing-internal-input"},W7={key:0,class:"card-section comment-body"},K7=["data-track-change-semantic-color-key"],q7={key:0},Y7={class:"change-type tracked-change-label"},X7={key:0,class:"tracked-change-detail-lines"},Z7={key:0,class:"tracked-change-text"},Q7={key:1,class:"change-type"},J7={class:"change-type"},eR={key:1},tR={class:"tracked-change-text is-inserted"},nR={key:2},rR={class:"tracked-change-text is-inserted"},oR={key:3},iR={key:4},sR={key:5},aR={key:6},lR={class:"tracked-change-text"},cR={key:7},uR={class:"tracked-change-text is-deleted"},dR={class:"tracked-change-text is-inserted"},fR={key:8},hR={class:"tracked-change-text is-deleted"},pR={key:9},mR={class:"tracked-change-text is-inserted"},gR=["data-track-change-image-preview-role"],vR=["src","alt"],yR={key:1,class:"card-section comment-body"},bR=["innerHTML"],wR={key:1,class:"comment"},CR={key:2,class:"reply-expanded"},kR={class:"reply-input-wrapper"},SR={class:"reply-actions"},_R=["onClick"],AR=["onClick","disabled","data-disabled-reason"],IR={class:"collapsed-avatars"},ER={key:3,class:"comment-separator"},TR={key:2,class:"tracked-change-decision-alert",role:"alert"},xR={class:"tracked-change-decision-alert__message"},RR=["disabled","data-disabled-reason"],MR={key:1,class:"reply-expanded"},LR={class:"reply-input-wrapper"},PR={class:"reply-actions"},DR=["disabled","data-disabled-reason"],Ck=3,kk=90,OR={__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}=vr(),i=su(),s=da(),{addComment:a,cancelComment:l,deleteComment:c,getCommentAliasIds:u,removePendingComment:d,getCommentDocumentId:h,requestInstantSidebarAlignment:g,resolveCommentPositionEntry:p,clearInstantSidebarAlignment:v,setActiveFloatingCommentInstance:S}=s,{suppressInternalExternal:C,getConfig:A,activeComment:y,activeFloatingCommentInstanceId:w,floatingCommentsOffset:x,pendingComment:L,currentCommentText:V,isDebugging:G,editingCommentId:R,editorCommentPositions:F,isCommentHighlighted:Z}=na(s),O=re(!0),N=re(null),T=re(new Map),B=re(null),Q=[[0,0],[-3,0],[Ck,0],[0,-3],[0,Ck]],q=ke=>{const He=typeof ke?.width=="number"&&Number.isFinite(ke.width)?ke.width:null,Et=typeof ke?.height=="number"&&Number.isFinite(ke.height)?ke.height:null;if(!He||!Et||He<=0||Et<=0)return{};const st=Math.min(kk/He,kk/Et,1);return{width:`${Math.max(1,Math.round(He*st))}px`,height:`${Math.max(1,Math.round(Et*st))}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(","),he=ke=>He=>{ke&&(He?(T.value.set(ke,He),R.value===ke&&Tt(()=>{ye(ke)})):T.value.delete(ke))},Ne=(ke,He,Et)=>{const st=ke?.getBoundingClientRect?.();return!st||![st.left,st.top,st.right,st.bottom].every(Number.isFinite)||st.width<=0||st.height<=0?!1:Q.some(([Nn,Kn])=>{const _r=He+Nn,jo=Et+Kn;return _r>=st.left&&_r<=st.right&&jo>=st.top&&jo<=st.bottom})},pe=(ke,He)=>{if(!Number.isFinite(ke)||!Number.isFinite(He))return null;const Et=document.querySelectorAll(se);for(const st of Et)if(st instanceof HTMLElement&&Ne(st,ke,He))return st;return null},ye=ke=>{T.value.get(ke)?.focus?.()},me=re(null),_e=ke=>ke.resolvedTime?ke.commentId:ke.importedId||ke.commentId,oe=ke=>ke?ke.trackedChange&&ke.importedId!=null?String(ke.importedId):ke.commentId!=null?String(ke.commentId):null:null,Me=(ke,He)=>{const Et=ke?.bounds?.[He];return Number.isFinite(Et)?Et:null},Ge=(ke,He)=>{if(!ke||!He||ke.pageIndex!==He.pageIndex)return!1;const Et=Me(ke,"top"),st=Me(He,"top");return Et!=null&&st!=null&&Math.abs(Et-st)<.5},lt=(ke,He)=>{const Et=Me(ke,"left"),st=Me(He,"left"),Nn=Me(ke,"right"),Kn=Me(He,"right");return[Et,st,Nn,Kn].some(_r=>_r==null)?!1:st<Nn&&Et<Kn},Ct=(ke,He)=>{const Et=ke?.start,st=ke?.end,Nn=He?.start,Kn=He?.end;return[Et,st,Nn,Kn].every(Number.isFinite)?Nn<=st&&Et<=Kn:!1},Re=(ke,He)=>!ke||!He||ke.kind&&He.kind&&ke.kind!==He.kind||ke.storyKey&&He.storyKey&&ke.storyKey!==He.storyKey?!1:He.start===ke.start&&He.end===ke.end?!0:Ge(ke,He)&&lt(ke,He)&&Ct(ke,He),Ke=ke=>{const He=new Set(u(ke)),{key:Et,entry:st}=p(ke);return Et&&He.add(Et),st?(Object.entries(F.value??{}).forEach(([Nn,Kn])=>{Re(st,Kn)&&He.add(Nn)}),[...He]):[...He]},tt=(ke,He,Et=24)=>{if(!Number.isFinite(He)||typeof ke?.getBoundingClientRect!="function")return!1;const st=ke.getBoundingClientRect().top;return Number.isFinite(st)&&Math.abs(st-He)<=Et},ee=Ee(()=>r.floatingInstanceId??r.comment.commentId??null),_=Ee(()=>typeof r.isFloatingInstanceActive=="boolean"?r.isFloatingInstanceActive:y.value!==r.comment.commentId?!1:r.floatingInstanceId==null?!0:w.value===r.floatingInstanceId),te=Ee(()=>r.comment.resolvedTime?r.comment.trackedChange?r.comment.trackedChangeDecision==="reject"?"Rejected":"Accepted":"Resolved":null),D=Ee(()=>L.value&&L.value.commentId===r.comment.commentId),U=Ee(()=>ke=>{const He=rt.value;return $.value&&ke===He.length-1?!0:He.length>1&&ke!==He.length-1}),$=Ee(()=>!A.readOnly&&_.value&&!r.comment.resolvedTime&&!Wn.value),H=()=>({ok:!1,reason:"read-only-document"}),J=()=>A.value?.readOnly===!0,X=re(!1),W=re(!1),we=()=>{if(J())return H();if(qe.value)return{ok:!1,reason:Oe.value?.reason??"v2-write-unavailable"};X.value=!0,Tt(()=>{N.value?.focus?.(),n("resize")})},ge=Ee(()=>{const ke=r.comment;return ke.trackedChange?s.getTrackedChangeThread(ke):s.commentsList.filter(He=>{const Et=He.parentCommentId===ke.commentId,st=He.commentId===ke.commentId;return Et||st}).sort((He,Et)=>He.commentId===ke.commentId?-1:Et.commentId===ke.commentId?1:He.createdTime-Et.createdTime)}),be=re(!1),Be=re(null),Ze=re(!1),it=Ee(()=>!be.value),yt=Ee(()=>({"is-truncated":it.value,"is-scrollable":be.value&&Ze.value})),Xt=()=>{be.value=!be.value,Tt(()=>n("resize"))},xt=ke=>{Be.value=ke??null},Ft=()=>{if(be.value)return;const ke=Be.value;if(!ke){Ze.value=!1;return}Ze.value=ke.scrollHeight>ke.clientHeight+1};Vt(Be,()=>{Tt(Ft)});const Ut=()=>R.value?ge.value.some(ke=>ke.commentId===R.value):!1;Vt(_,ke=>{ke||((X.value||Ut())&&(V.value="",R.value=null),be.value=!1,mn.value=!1,X.value=!1,Tt(()=>n("resize")))});const mn=re(!1),It=Ee(()=>ge.value.slice(1)),Zt=Ee(()=>mn.value?!1:It.value.length>=2),rt=Ee(()=>Zt.value?[ge.value[0],It.value[It.value.length-1]].filter(Boolean):ge.value);Vt(Ee(()=>{const ke=rt.value[0];return ke?JSON.stringify({commentId:ke.commentId,commentText:ke.commentText,trackedChange:ke.trackedChange,trackedChangeText:ke.trackedChangeText,deletedText:ke.deletedText,trackedChangeLabel:ke.trackedChangeLabel,trackedChangeDisplayType:ke.trackedChangeDisplayType,trackedChangeDetailLines:ke.trackedChangeDetailLines}):""}),()=>{Tt(Ft)});const zt=Ee(()=>Zt.value?It.value.length-1:0),Lt=Ee(()=>{if(!Zt.value)return[];const ke=It.value.slice(0,-1),He=new Set;return ke.map(Et=>typeof Et.getCommentUser=="function"?Et.getCommentUser():{name:Et.creatorName,email:Et.creatorEmail||Et.email}).filter(Et=>{if(!Et)return!1;const st=Et.email||Et.name;return He.has(st)?!1:(He.add(st),!0)}).slice(0,3)}),An=()=>{mn.value=!0,Xn(),Tt(()=>n("resize"))},Qt=Ee(()=>r.comment.resolvedTime?!0:A.value.readOnly),wn=Ee(()=>ke=>_.value&&R.value===ke.commentId),Wn=Ee(()=>!R.value||!_.value?!1:ge.value.some(ke=>ke.commentId===R.value)),go=Ee(()=>A.value.readOnly||!o.$superdoc.config.isInternal||rr.value?!1:!C.value&&!r.comment.trackedChange),jn=Ee(()=>V.value&&V.value!=="<p></p>"),Xn=async()=>{const ke=o.$superdoc.activeEditor,He=ke?.editorVersion===2?ke?.v2Comments??null:null,Et=!!r.comment?.trackedChange,st=t7(),Nn=r.floatingInstanceId!=null,Kn=me.value?.getBoundingClientRect?.().top,_r=!r.comment.resolvedTime&&(y.value!==r.comment.commentId||Nn&&ee.value!==w.value);let jo=st;if(He){const xo=!Et&&!r.comment.resolvedTime&&String(r.comment?.trackedChangeParentId??"").trim()?r.comment.trackedChangeParentId:null,Di=ke?.editorVersion===2&&(Et||xo!=null)?ke?.v2TrackedChanges??null:null,Ro=xo!=null?s.getComment(xo):null,oo=Et?r.comment:Ro?.trackedChange?Ro:xo;let io=await(Di?Di.focusTrackedChange(oo):He.focusComment(r.comment));return!Et&&io?.reason==="tracked-change-anchor-not-found"&&(io=await He.focusComment(r.comment)),io?.ok?(r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&S(r.floatingInstanceId)),_r&&!Nn?g(st,r.comment.commentId,r.floatingInstanceId??null):_r&&Number.isFinite(Kn)?g(Kn,r.comment.commentId,r.floatingInstanceId):v(),io):(v(),io)}if(ke){const{entry:xo}=p(r.comment),Di=r.floatingPositionEntry??xo,Ro=Number.isFinite(r.floatingPageIndex)&&r.comment?.trackedChangeStory?.storyType==="headerFooterPart",oo=gk(r.parent,Di),io=Ro?null:n7(Ke(r.comment)),Si=Number.isFinite(io)?io:oo,Uo=tt(me.value,Si),es=_e(r.comment),vo=null;let Ho=null;if(Et)if(r.comment.trackedChangeStory&&(r.comment.trackedChangeStory,{...Number.isFinite(r.floatingPageIndex)?{pageIndex:r.floatingPageIndex}:{}}),r.comment.resolvedTime)ke.commands?.setCursorById(es);else{const Br=r.comment.commentId;ke.commands?.setCursorById(es,{activeCommentId:Br})||ke.commands?.setActiveComment({commentId:Br})}else{if(r.comment.resolvedTime)ke.commands?.setCursorById(es);else{const Oi=r.comment.commentId;ke.commands?.setCursorById(es,{activeCommentId:Oi})||ke.commands?.setActiveComment({commentId:Oi})}const Br=r.comment.commentId;Ho=Uo?null:r7(vo,es,Br,st)}Number.isFinite(io)?jo=io:Number.isFinite(oo)?jo=oo:Number.isFinite(Ho)&&(jo=Ho)}_r&&!Nn?r.floatingInstanceId?g(jo,r.comment.commentId,r.floatingInstanceId):g(jo,r.comment.commentId):v(),r.comment.resolvedTime||(y.value=r.comment.commentId,r.floatingInstanceId&&S(r.floatingInstanceId))},Ao=ke=>{const He=ke.target instanceof Element?ke.target:ke.target?.parentElement,Et=document.elementFromPoint(ke.clientX,ke.clientY);if(!(He?.closest?.(se)||Et?.closest?.(se)||pe(ke.clientX,ke.clientY)||Z.value)&&!(ke.target.closest?.(".comments-dialog")&&!me.value?.contains(ke.target))){if(D.value){l(o.$superdoc);return}_.value&&(x.value=0,n("dialog-exit"),y.value=null,s.setActiveComment(o.$superdoc,y.value),Z.value=!1)}},Nr=async()=>{if(J())return H();if(qe.value)return{ok:!1,reason:Oe.value?.reason??"v2-write-unavailable"};if(rr.value&&Pn.value&&!D.value){if(W.value)return{ok:!1,reason:"reply-submit-in-flight"};W.value=!0;try{const Et=await s.replyCommentV2({superdoc:o.$superdoc,parentCommentId:oe(r.comment),text:V.value});return Et?.ok?(X.value=!1,V.value="",Tt(()=>n("resize")),Et):(Tt(()=>n("resize")),Et)}finally{W.value=!1}}const ke={documentId:r.comment.fileId,isInternal:L.value?L.value.isInternal:O.value,parentCommentId:L.value?null:r.comment.commentId};L.value&&(ke.selection=L.value.selection.getValues());const He=s.getPendingComment(ke);!L.value&&V.value&&He.setText({text:V.value,suppressUpdate:!0}),Promise.resolve(a({superdoc:o.$superdoc,comment:He})).finally(()=>{X.value=!1,Tt(()=>n("resize"))})},rr=Ee(()=>o.$superdoc?.activeEditor?.editorVersion===2),Pn=Ee(()=>rr.value?o.$superdoc?.activeEditor?.v2Comments??null:null),De=Ee(()=>rr.value?o.$superdoc?.activeEditor?.v2TrackedChanges??null:null),Oe=Ee(()=>{if(!Pn.value)return null;const ke=s.viewingVisibility.documentMode,He=Pn.value.getCapabilityState?.()??null;return ke==="viewing"?{...He??{},canWrite:!1,reason:"review-surface-read-only"}:He}),qe=Ee(()=>{if(!rr.value)return!1;const ke=Oe.value;return ke?ke.canWrite===!1:!1}),wt=Ee(()=>W.value?"reply-submit-in-flight":qe.value?Oe.value?.reason??"v2-write-unavailable":null),ft=Ee(()=>{if(!De.value)return null;const ke=s.viewingVisibility.documentMode,He=De.value.getCapabilityState?.()??null;return ke==="viewing"&&He?.canDecide!==!1?{canDecide:!1,reason:"review-surface-read-only"}:He}),Pt=ke=>{if(rr.value&&ke?.trackedChange){if(!De.value)return"v2-tracked-change-adapter-missing";const He=ft.value;return He&&He.canDecide===!1?He.reason??"v2-tracked-change-unavailable":null}return qe.value?Oe.value?.reason??"v2-write-unavailable":null},_n=ke=>{if(rr.value&&ke?.trackedChange){if(!De.value)return"v2-tracked-change-adapter-missing";const He=ft.value;return He&&He.canDecide===!1?He.reason??"v2-tracked-change-unavailable":null}return qe.value?Oe.value?.reason??"v2-write-unavailable":null},an=()=>rr.value?Pn.value?A.value?.readOnly?"read-only-document":qe.value?Oe.value?.reason??"v2-write-unavailable":null:"v2-comments-adapter-missing":null,Dn=Ee(()=>!rr.value||!qe.value?null:Oe.value?.reason??"v2-write-unavailable"),Io=(ke,He)=>{B.value={decision:ke,reason:He?.reason??null},Tt(()=>n("resize"))},Eo=()=>{B.value&&(B.value=null,Tt(()=>n("resize")))},ki=Ee(()=>{const ke=B.value;if(!ke)return null;const He=ke.decision==="reject"?"reject":"accept";return ke.reason==="stale-catalog"?`Couldn't ${He} this change because the review list is stale.`:`Couldn't ${He} this change.`}),cn=()=>{const ke=B.value;if(ke){if(B.value=null,ke.decision==="reject"){On();return}Fn()}},On=async()=>{if(J())return H();const ke=o.$superdoc.config.onTrackedChangeBubbleReject;if(r.comment.trackedChange){if(rr.value){const Et=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});if(!Et?.ok||Et.success===!1){Io("reject",Et);return}Eo(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let He=!0;if(typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else{const Et=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"reject"});He=!!Et?.ok&&Et.success!==!1}He&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"reject"})}else if(rr.value&&Pn.value){if(!(await s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok)return}else s.deleteComment({superdoc:o.$superdoc,commentId:r.comment.commentId});Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Fn=async()=>{if(J())return H();if(!r.comment.trackedChange&&A.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};const ke=o.$superdoc.config.onTrackedChangeBubbleAccept;if(r.comment.trackedChange&&rr.value){const Et=await s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});if(!Et?.ok||Et.success===!1){Io("accept",Et);return}Eo(),typeof ke=="function"&&ke(r.comment,o.$superdoc.activeEditor),Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.({preventScroll:!0})});return}let He=!0;if(r.comment.trackedChange&&typeof ke=="function")ke(r.comment,o.$superdoc.activeEditor);else if(r.comment.trackedChange){const Et=s.decideTrackedChangeFromSidebar({superdoc:o.$superdoc,comment:r.comment,decision:"accept"});He=!!Et?.ok&&Et.success!==!1}else if(rr.value&&Pn.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&&!rr.value&&He&&r.comment.resolveComment({id:i.user.id,email:i.user.email,name:i.user.name,superdoc:o.$superdoc,decision:"accept"}),Tt(()=>{s.lastUpdate=new Date,y.value=null,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},lr=async()=>{if(J())return H();if(A.value?.allowResolve===!1)return{ok:!1,reason:"resolve-disabled"};!rr.value||!Pn.value||(await s.reopenCommentV2({superdoc:o.$superdoc,commentId:r.comment.commentId}))?.ok&&Tt(()=>{s.lastUpdate=new Date,s.setActiveComment(o.$superdoc,y.value),o.$superdoc.focus?.()})},Jt=(ke,He)=>{if(J())return H();switch(ke){case"edit":V.value=He?.commentText?.value??He?.commentText??"",y.value=r.comment.commentId,r.floatingInstanceId&&S(r.floatingInstanceId),R.value=He.commentId,s.setActiveComment(o.$superdoc,y.value),Tt(()=>{ye(He.commentId)});break;case"delete":c({superdoc:o.$superdoc,commentId:He.commentId});break}},Un=async ke=>{if(J())return H();if(rr.value&&Pn.value){const He=await s.editCommentV2({superdoc:o.$superdoc,commentId:ke.commentId,text:V.value});return He?.ok&&(R.value=null,d(o.$superdoc)),He}R.value=null,ke.setText({text:V.value,superdoc:o.$superdoc}),d(o.$superdoc)},ro=ke=>{if(J())return H();const He=!!L.value,Et=ke.toLowerCase()==="internal";He?L.value.isInternal=Et:r.comment.setIsInternal({isInternal:Et,superdoc:o.$superdoc})},Pi=Ee(()=>{const ke={};return(_.value||D.value||Wn.value)&&(ke.zIndex=50),ke}),pl=ke=>typeof ke=="string"?new Date(ke).getTime():ke,To=ke=>{R.value=null,X.value=!1,l(o.$superdoc)},ai=Ee(()=>{const ke=o.$superdoc.users;return r.comment.isInternal===!0?ke.filter(He=>He.access?.role==="internal"):ke});return Gn(()=>{r.autoFocus&&Tt(()=>Xn()),D.value&&Tt(()=>{N.value?.focus?.()}),Tt(()=>{const ke=r.floatingInstanceId??(r.comment.importedId!==void 0?r.comment.importedId:r.comment.commentId);n("ready",{commentId:ke,elementRef:me}),Ft()})}),Vt($,ke=>{ke&&Tt(()=>{N.value?.focus?.()})},{immediate:!0}),Vt(R,ke=>{if(!ke||!_.value)return;const He=ge.value.find(Et=>Et.commentId===ke);!He||He.trackedChange||Tt(()=>{ye(ke)})}),Vt(()=>A.value?.readOnly===!0,ke=>{ke&&(X.value=!1,ge.value.some(He=>He.commentId===R.value)&&(R.value=null),D.value&&l(o.$superdoc),Tt(()=>n("resize")))},{immediate:!0}),Vt(qe,ke=>{ke&&(X.value=!1,Tt(()=>n("resize")))}),(ke,He)=>{const Et=$1("click-outside");return Ks((ve(),Te("div",{class:on(["comments-dialog",{"is-active":_.value||D.value,"is-resolved":r.comment.resolvedTime}]),onClick:rn(Xn,["stop","prevent"]),style:Sn(Pi.value),ref_key:"commentDialogElement",ref:me,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:""},[D.value?(ve(),Te(Yt,{key:0},[go.value?(ve(),Te("div",z7,[Kt(yk,{onClick:He[0]||(He[0]=rn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":!1,state:nt(L).isInternal?"internal":"external",onSelect:ro},null,8,["state"])])):vt("",!0),Kt(s0,{config:nt(A),comment:r.comment,"is-pending-input":!0},null,8,["config","comment"]),Fe("div",V7,[Kt(l0,{ref_key:"commentInput",ref:N,users:ai.value,config:nt(A),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Fe("div",j7,[Fe("button",{class:"sd-button reply-btn-cancel",onClick:rn(To,["stop","prevent"])},"Cancel"),Fe("button",{class:on(["sd-button primary reply-btn-primary",{"sd-is-disabled":!jn.value}]),onClick:rn(Nr,["stop","prevent"]),disabled:!jn.value}," Comment ",10,U7)])],64)):(ve(),Te(Yt,{key:1},[te.value?(ve(),Te("div",H7,[Fe("span",{class:"resolved-badge__icon",innerHTML:nt(fa).markDone},null,8,$7),ji(" "+Ht(te.value),1)])):vt("",!0),go.value?(ve(),Te("div",G7,[Kt(yk,{onClick:He[1]||(He[1]=rn(()=>{},["stop","prevent"])),class:"sd-internal-dropdown","is-disabled":Qt.value,state:e.comment.isInternal?"internal":"external",onSelect:ro},null,8,["is-disabled","state"])])):vt("",!0),(ve(!0),Te(Yt,null,mr(rt.value,(st,Nn)=>(ve(),Te("div",{key:st.commentId,class:"conversation-item"},[Kt(s0,{config:nt(A),timestamp:pl(st.createdTime),comment:st,"is-active":_.value,"resolve-disabled-reason":Pt(st),"reject-disabled-reason":_n(st),"reopen-supported":rr.value&&!!Pn.value,"reopen-disabled-reason":an(),"write-disabled-reason":Dn.value,onResolve:Fn,onReject:On,onReopen:lr,onOverflowSelect:Kn=>Jt(Kn,st)},null,8,["config","timestamp","comment","is-active","resolve-disabled-reason","reject-disabled-reason","reopen-supported","reopen-disabled-reason","write-disabled-reason","onOverflowSelect"]),st.trackedChange?(ve(),Te("div",W7,[Fe("div",{class:on(["tracked-change",Nn===0?yt.value:void 0]),"data-track-change-semantic-color-key":st.semanticColorKey??void 0,ref_for:!0,ref:Nn===0?xt:void 0},[st.trackedChangeLabel?(ve(),Te("div",q7,[Fe("span",Y7,Ht(st.trackedChangeLabel),1),st.trackedChangeDetailLines&&st.trackedChangeDetailLines.length?(ve(),Te("div",X7,[(ve(!0),Te(Yt,null,mr(st.trackedChangeDetailLines,(Kn,_r)=>(ve(),Te("div",{key:_r,class:"tracked-change-detail-line"},[Kn.excerpt?(ve(),Te("span",Z7,'"'+Ht(Kn.excerpt)+'"',1)):vt("",!0),Kn.excerpt?(ve(),Te("span",Q7," — ")):vt("",!0),Fe("span",J7,Ht(Kn.label),1)]))),128))])):vt("",!0)])):st.trackedChangeDisplayType==="hyperlinkAdded"?(ve(),Te("div",eR,[He[2]||(He[2]=Fe("span",{class:"change-type"},"Added hyperlink ",-1)),Fe("span",tR,'"'+Ht(st.trackedChangeText)+'"',1)])):st.trackedChangeDisplayType==="hyperlinkModified"?(ve(),Te("div",nR,[He[3]||(He[3]=Fe("span",{class:"change-type"},"Changed hyperlink to ",-1)),Fe("span",rR,'"'+Ht(st.trackedChangeText)+'"',1)])):st.trackedChangeDisplayType==="paragraphSplit"?(ve(),Te("div",oR,[...He[4]||(He[4]=[Fe("span",{class:"change-type"},"Added new line",-1)])])):st.trackedChangeDisplayType==="tableInsert"?(ve(),Te("div",iR,[...He[5]||(He[5]=[Fe("span",{class:"change-type"},"Added table",-1)])])):st.trackedChangeDisplayType==="tableDelete"?(ve(),Te("div",sR,[...He[6]||(He[6]=[Fe("span",{class:"change-type"},"Deleted table",-1)])])):st.trackedChangeType==="trackFormat"?(ve(),Te("div",aR,[He[7]||(He[7]=Fe("span",{class:"change-type"},"Format: ",-1)),Fe("span",lR,Ht(st.trackedChangeText),1)])):st.trackedChangeType==="both"?(ve(),Te("div",cR,[He[8]||(He[8]=Fe("span",{class:"change-type"},"Replaced ",-1)),Fe("span",uR,'"'+Ht(st.deletedText)+'"',1),He[9]||(He[9]=Fe("span",{class:"change-type"}," with ",-1)),Fe("span",dR,'"'+Ht(st.trackedChangeText)+'"',1)])):st.deletedText?(ve(),Te("div",fR,[He[10]||(He[10]=Fe("span",{class:"change-type"},"Deleted ",-1)),Fe("span",hR,'"'+Ht(st.deletedText)+'"',1)])):st.trackedChangeText?(ve(),Te("div",pR,[He[11]||(He[11]=Fe("span",{class:"change-type"},"Added ",-1)),Fe("span",mR,'"'+Ht(st.trackedChangeText)+'"',1)])):vt("",!0),st.trackedChangeImagePreview?.src?(ve(),Te("div",{key:10,class:"tracked-change-image-preview","data-track-change-image-preview-role":st.trackedChangeImagePreview.role??void 0},[Fe("img",{class:"tracked-change-image-preview__image",src:st.trackedChangeImagePreview.src,alt:st.trackedChangeImagePreview.alt||"Tracked image preview",style:Sn(q(st.trackedChangeImagePreview)),loading:"lazy",decoding:"async"},null,12,vR)],8,gR)):vt("",!0)],10,K7),it.value&&Ze.value&&Nn===0?(ve(),Te("div",{key:0,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show more ")):vt("",!0),be.value&&Ze.value&&Nn===0?(ve(),Te("div",{key:1,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show less ")):vt("",!0)])):vt("",!0),st.trackedChange?vt("",!0):(ve(),Te("div",yR,[!nt(G)&&!wn.value(st)?(ve(),Te("div",{key:0,class:on(["comment",Nn===0?yt.value:void 0]),ref_for:!0,ref:Nn===0?xt:void 0,innerHTML:st.commentText},null,10,bR)):nt(G)&&!wn.value(st)?(ve(),Te("div",wR,Ht(nt(F)[st.importedId!==void 0?st.importedId:st.commentId]?.bounds),1)):(ve(),Te("div",CR,[Fe("div",kR,[Kt(l0,{ref_for:!0,ref:he(st.commentId),users:ai.value,config:nt(A),"include-header":!1,comment:st},null,8,["users","config","comment"])]),Fe("div",SR,[Fe("button",{class:"sd-button reply-btn-cancel",onClick:rn(Kn=>To(st),["stop","prevent"])},"Cancel",8,_R),Fe("button",{class:on(["sd-button primary reply-btn-primary",{"sd-is-disabled":!jn.value||qe.value}]),onClick:rn(Kn=>Un(st),["stop","prevent"]),disabled:!jn.value||qe.value,"data-disabled-reason":qe.value?Oe.value?.reason??null:null}," Update ",10,AR)])])),it.value&&Ze.value&&Nn===0&&!wn.value(st)?(ve(),Te("div",{key:3,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show more ")):vt("",!0),be.value&&Ze.value&&Nn===0&&!wn.value(st)?(ve(),Te("div",{key:4,class:"show-more-toggle",onClick:rn(Xt,["stop","prevent"])}," Show less ")):vt("",!0)])),Zt.value&&Nn===0?(ve(),Te(Yt,{key:2},[He[12]||(He[12]=Fe("div",{class:"comment-separator"},null,-1)),Fe("div",{class:"collapsed-replies",onClick:rn(An,["stop","prevent"])},[Fe("div",IR,[(ve(!0),Te(Yt,null,mr(Lt.value,Kn=>(ve(),hn(bk,{key:Kn.email||Kn.name,user:Kn,class:"mini-avatar"},null,8,["user"]))),128))]),Fe("span",null,Ht(zt.value)+" more "+Ht(zt.value===1?"reply":"replies"),1)])],64)):vt("",!0),U.value(Nn)?(ve(),Te("div",ER)):vt("",!0)]))),128)),B.value?(ve(),Te("div",TR,[Fe("span",xR,Ht(ki.value),1),Fe("button",{type:"button",class:"sd-button tracked-change-decision-alert__retry",onClick:rn(cn,["stop","prevent"])}," Retry ")])):vt("",!0),$.value&&!nt(A).readOnly?(ve(),Te(Yt,{key:3},[X.value?(ve(),Te("div",MR,[Fe("div",LR,[Kt(l0,{ref_key:"commentInput",ref:N,users:ai.value,config:nt(A),comment:r.comment,"include-header":!1},null,8,["users","config","comment"])]),Fe("div",PR,[Fe("button",{class:"sd-button reply-btn-cancel",onClick:rn(To,["stop","prevent"])},"Cancel"),Fe("button",{class:on(["sd-button primary reply-btn-primary",{"sd-is-disabled":!jn.value||qe.value||W.value}]),onClick:rn(Nr,["stop","prevent"]),disabled:!jn.value||qe.value||W.value,"data-disabled-reason":wt.value}," Reply ",10,DR)])])):(ve(),Te("button",{key:0,type:"button",class:on(["reply-pill",{"sd-is-disabled":qe.value}]),onClick:rn(we,["stop","prevent"]),disabled:qe.value,"data-disabled-reason":qe.value?Oe.value?.reason??null:null}," Reply or add others with @ ",10,RR))],64)):vt("",!0)],64))],14,B7)),[[Et,Ao]])}}},Pp=pn(OR,[["__scopeId","data-v-f26decd0"]]);Dt(),bn();var FR={class:"comments-list"},NR={key:0},BR=["data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],zR={key:1},VR="headerFooterPart",jR={__name:"commentsList",props:{showMainComments:{type:Boolean,default:!0},showResolvedComments:{type:Boolean,default:!0}},setup(e){const t=e,n=da(),r=dg(n,"isCommentsListVisible"),o=Ee(()=>n.getGroupedComments),i=Ee(()=>n.getFloatingCommentInstances),{activeComment:s,activeFloatingCommentInstanceId:a}=na(n),l=g=>{const p=i.value.filter(v=>v?.comment?.commentId===g?.commentId);return p.length<2?[]:g?.trackedChange?g?.trackedChangeStory?.storyType!==VR?[]:p:[]},c=g=>!g?.comment?.commentId||s.value!==g.comment.commentId?!1:a.value==null?g.isPrimary===!0:String(a.value)===String(g.id),u=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:c(v)})):[{id:g.commentId,comment:g,floatingInstanceId:null,floatingPageIndex:null,floatingPositionEntry:null,isFloatingInstanceActive:void 0}]},d=Ee(()=>o.value.parentComments.flatMap(g=>u(g))),h=Ee(()=>t.showResolvedComments&&o.value?.resolvedComments?.length>0);return Gn(()=>{r.value=!0}),gr(()=>{r.value=!1}),(g,p)=>(ve(),Te("div",FR,[e.showMainComments?(ve(),Te("div",NR,[(ve(!0),Te(Yt,null,mr(d.value,v=>(ve(),Te("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:""},[Kt(Pp,{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,BR))),128))])):vt("",!0),h.value?(ve(),Te("div",zR,[p[0]||(p[0]=Fe("div",{class:"comment-title"},"Resolved",-1)),(ve(!0),Te(Yt,null,mr(o.value.resolvedComments,v=>(ve(),Te("div",{key:v.commentId,class:"comment-item"},[Kt(Pp,{comment:v},null,8,["comment"])]))),128))])):vt("",!0)]))}},UR=pn(jR,[["__scopeId","data-v-e89dbc33"]]);Dt();var HR=class extends Gm.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=zl(UR);const e=this.superdoc?.app?._context?.provides;e&&this.app?._context?.provides&&Object.setPrototypeOf(this.app._context.provides,e),this.superdoc?.pinia&&(qd(this.superdoc.pinia),this.app.use(this.superdoc.pinia),this.app.config.globalProperties.$pinia=this.superdoc.pinia),this.app.directive("click-outside",qv),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()}},tl,c0=Dr((()=>{tl=96/72}));Dt(),c0();var $R=96,GR=".superdoc__right-sidebar",WR=".sd-pdf-viewer-page",u0=Object.freeze({min:10,max:100,padding:0}),Sk=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,u0.min),o=n(t.max,u0.max),i=typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding>=0?t.padding:u0.padding;return{min:Math.min(r,o),max:Math.max(r,o),padding:i}},_k=(e,t)=>!(e>0)||!(t>0)?null:Math.round(e/t*100),KR=(e,t,n)=>{const r=_k(e-n.padding,t);return r===null?null:Math.max(1,Math.round(Math.min(n.max,Math.max(n.min,r))))},qR=(e,t,n)=>e>0?Number.isFinite(t)&&t>0?e/t*tl:n>0?e/n:e:null;function YR({getSuperdoc:e,superdocContainerWidth:t,isReady:n,activeZoom:r,zoomMode:o,viewportMetrics:i,showCommentsSidebar:s,rightSidebarRef:a,superdocRoot:l,documents:c}){const u=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 L=null;try{L=w.getPageStyles?.()??null}catch{L=null}const V=L?.pageSize?.width;return typeof V=="number"&&Number.isFinite(V)&&V>0?V*$R:null},d=()=>{if(!(c?.value??[]).some(L=>L?.type==="application/pdf"))return null;const w=l.value;if(!w?.querySelectorAll)return null;let x=0;for(const L of w.querySelectorAll(WR)){const V=Number(L.clientWidth)||Number(L.getBoundingClientRect?.().width)||0;let G=NaN;typeof window<"u"&&typeof window.getComputedStyle=="function"&&(G=Number.parseFloat(window.getComputedStyle(L).getPropertyValue("--scale-factor")));const R=(r.value??100)/100,F=qR(V,G,R);F!==null&&F>x&&(x=F)}return x>0?x:null},h=()=>{const w=e();if(!w)return null;const x=[],L=c?.value??[];for(const G of L){if(G?.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")continue;const R=u(G.getEditor?.());R!==null&&x.push(R)}if(x.length===0){const G=u(w.activeEditor);G!==null&&x.push(G)}const V=d();if(V!==null&&x.push(V),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?.(GR),x=Number(w?.offsetWidth)||Number(w?.getBoundingClientRect?.().width)||0;return x>0?x:0},p=(w,x)=>{const L=Sk(w.config?.zoom?.fitWidth),V=KR(x.availableWidth,x.documentWidth,L);V!==null&&V!==r.value&&(r.value=V,w.emit("zoomChange",{zoom:V,mode:"fit-width"}))},v=()=>{const w=e();if(!w)return;const x=t.value;if(!(x>0)||!n.value)return;const L=h();if(L===null)return;const V=x-g(),G=_k(V,L);if(G===null)return;const R=Object.freeze({availableWidth:V,documentWidth:L,fitZoom:G}),F=i.value;(!F||F.availableWidth!==V||F.documentWidth!==L||F.fitZoom!==G)&&(i.value=R),(!F||F.fitZoom!==G||Math.round(F.documentWidth)!==Math.round(L))&&w.emit("viewport-change",R),o.value==="fit-width"&&p(w,R)};Vt(t,()=>{Tt(()=>v())}),Vt(n,w=>{w&&v()}),Vt(o,w=>{w==="fit-width"&&v()}),s&&Vt(s,()=>{Tt(()=>v())});const S=()=>{Tt(()=>v())},C=()=>{Tt(()=>v())},A=()=>{Tt(()=>v())},y=e();return y?.on?.("editorCreate",S),y?.on?.("pagination-update",C),y?.on?.("pdf:document-ready",A),gr(()=>{y?.off?.("editorCreate",S),y?.off?.("pagination-update",C),y?.off?.("pdf:document-ready",A)}),{evaluateViewport:v}}var XR=e=>!!e?.trackedChange,ZR=e=>e,QR=(e,t,n,r=e)=>!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?!1:(Number.isFinite(r)?r:e)<t||e>n,JR=({comment:e,anchorTop:t,anchorBottom:n,viewportTop:r,viewportBottom:o})=>XR(e)&&QR(t,r,o,n),e9=({comment:e,anchorTop:t,anchorBottom:n,cardHeight:r,viewportTop:o,viewportBottom:i})=>!JR({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,t9=({id:e,visibleIds:t,activeCommentInstanceId:n})=>e?!!(e==="pending"||n!=null&&String(e)===String(n)||t?.has?.(e)):!1,Ak=({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};Dt(),bn();var n9=["data-comment-id","data-comment-instance-id","data-comment-thread-id","data-comment-position-key","data-comment-page-index"],Hl={},r9={__name:"FloatingComments",props:{currentDocument:{type:Object,required:!0},parent:{type:Object,required:!0}},setup(e){const r=new Set(["auto","scroll","hidden","clip"]),o=(De,Oe,qe)=>{if(Oe>=0){De[Oe].top=De[Oe].anchorTop;let wt=De[Oe].top+De[Oe].height+qe;for(let Pt=Oe+1;Pt<De.length;Pt++)De[Pt].top=Math.max(De[Pt].anchorTop,wt),wt=De[Pt].top+De[Pt].height+qe;wt=De[Oe].top-qe;for(let Pt=Oe-1;Pt>=0;Pt--){const _n=wt-De[Pt].height;De[Pt].top=Math.min(De[Pt].anchorTop,_n),wt=De[Pt].top-qe}const ft=Math.min(...De.map(Pt=>Pt.top));if(ft<0){const Pt=Math.abs(ft);for(const _n of De)_n.top+=Pt}}else for(let wt=1;wt<De.length;wt++){const ft=De[wt-1],Pt=ft.top+ft.height+qe;De[wt].top<Pt&&(De[wt].top=Pt)}},i=e,s=su(),a=da(),{clearInstantSidebarAlignment:l}=a,{activeComment:c,activeFloatingCommentInstanceId:u,editorCommentPositions:d,pendingComment:h,editingCommentId:g,instantSidebarAlignmentTargetY:p,instantSidebarAlignmentThreadId:v,instantSidebarAlignmentInstanceId:S}=na(a),{activeZoom:C}=na(s),A=Ee(()=>{const De=a.getFloatingCommentInstances;if(!Array.isArray(De))return[];const Oe=i.currentDocument?.id;return Oe==null?De:De.filter(qe=>a.belongsToDocument(qe.comment,String(Oe),{allowSingleDocumentMismatch:!0}))}),y=re(null),w=re(0),x=re(0),L=re(!1),V=re(null),G=re(0),R=De=>{const Oe=h.value?.commentId;return Oe?typeof De=="object"?De?.commentId===Oe:De===Oe||De==="pending":!1},F=De=>De?.commentId??De?.importedId??null,Z=Ee(()=>{const De=new Map,Oe=new Map;for(const qe of A.value){qe?.id!=null&&De.set(String(qe.id),qe);const wt=F(qe?.comment);if(wt==null)continue;const ft=String(wt),Pt=Oe.get(ft)??[];Pt.push(qe),Oe.set(ft,Pt)}return{byId:De,byThreadId:Oe}}),O=(De,Oe=null)=>{if(De==null)return null;const qe=String(De),wt=Z.value.byThreadId.get(qe)??[];if(!wt.length)return null;if(Oe!=null){const ft=wt.find(Pt=>String(Pt.id)===String(Oe));if(ft)return ft.id}return wt.find(ft=>ft.isPrimary)?.id??wt[0]?.id??null},N=Ee(()=>c.value?O(c.value,u.value):null),T=De=>{if(typeof De=="number")return Number.isFinite(De)?De:null;if(typeof De!="string"||De.trim()==="")return null;const Oe=Number(De);return Number.isFinite(Oe)?Oe:null},B=re({...Hl}),Q=re(new Set),q=re({});let se=null;const he=new Set;let Ne=null;const pe=()=>{Ne==null&&(Ne=requestAnimationFrame(()=>{Ne=null,G.value+=1}))},ye=De=>{if(i.currentDocument.type==="application/pdf"){const Oe=(C.value??100)/100,qe=T(De?.comment?.selection?.selectionBounds?.top);return qe==null?null:qe*Oe}return De?.positionEntry?.bounds?.top},me=(De,Oe)=>{if(i.currentDocument.type==="application/pdf"){const wt=(C.value??100)/100,ft=T(De?.comment?.selection?.selectionBounds?.bottom);return ft!=null?ft*wt:Oe}const qe=De?.positionEntry?.bounds?.bottom;return Number.isFinite(qe)?qe:Oe},_e=Ee(()=>{const De=[];for(const Oe of A.value){const qe=Oe?.id,wt=F(Oe?.comment),ft=ye(Oe);if(qe==null||wt==null||!Number.isFinite(ft))continue;const Pt=ZR(ft,Oe.comment);De.push({id:qe,threadId:wt,instance:Oe,top:Pt,anchorBottom:me(Oe,Pt)})}return De}),oe=()=>{const De=d.value.pending;if(typeof De?.bounds?.top=="number"&&!isNaN(De.bounds.top))return De.bounds.top;const Oe=i.currentDocument.type==="application/pdf"?(C.value??100)/100:1,qe=T(h.value?.selection?.selectionBounds?.top);return qe==null?null:qe*Oe},Me=De=>t9({id:De?.id,visibleIds:Q.value,activeCommentInstanceId:N.value,comment:De?.commentRef}),Ge=()=>{const De=y.value;if(!De)return null;const Oe=De.getBoundingClientRect();if(!Number.isFinite(Oe.top)||!Number.isFinite(window.innerHeight))return null;let qe=0,wt=window.innerHeight;for(let Pt=De.parentElement;Pt;Pt=Pt.parentElement){const _n=window.getComputedStyle(Pt).overflowY;if(!["auto","scroll","hidden","clip"].includes(_n))continue;const an=Pt.getBoundingClientRect();!Number.isFinite(an.top)||!Number.isFinite(an.bottom)||(qe=Math.max(qe,an.top),wt=Math.min(wt,an.bottom))}if(wt<=qe)return null;const ft=i.parent?.getBoundingClientRect?.();if(ft&&Number.isFinite(ft.top)&&Number.isFinite(ft.bottom)){const Pt=Math.max(qe,ft.top),_n=Math.min(wt,ft.bottom);_n>Pt&&(qe=Pt,wt=_n)}return{top:qe-Oe.top,bottom:wt-Oe.top}},lt=Ee(()=>v.value?O(v.value,S.value):null),Ct=Ee(()=>{G.value;const De=_e.value,Oe=h.value&&h.value.fileId===i.currentDocument.id;if(!De.length&&!A.value.length&&!Oe)return[];const qe=[],wt=Ge()??{top:0,bottom:Math.max(0,i.parent?.clientHeight||window.innerHeight||0)},ft=wt.top-600,Pt=wt.bottom+600,_n=Oe?"pending":N.value,an=new Set,Dn=({id:cn,threadId:On,instance:Fn,top:lr,anchorBottom:Jt,hasAnchorGeometry:Un})=>{const ro=String(cn);an.has(ro)||(an.add(ro),qe.push({id:cn,threadId:On,pageIndex:Fn?.pageIndex??null,anchorTop:lr,anchorBottom:Jt,hasAnchorGeometry:Un,top:lr,height:B.value[cn]||110,commentRef:Fn.comment,instanceRef:Fn}))};for(const cn of De){const{id:On,threadId:Fn,instance:lr,top:Jt,anchorBottom:Un}=cn,ro=_n!=null&&String(On)===String(_n),Pi=g.value!=null&&String(Fn)===String(g.value);!ro&&!Pi&&(Un<ft||Jt>Pt)||Dn({id:On,threadId:Fn,instance:lr,top:Jt,anchorBottom:Un,hasAnchorGeometry:!0})}const Io=[];if(_n&&_n!=="pending"){const cn=Z.value.byId.get(String(_n));cn&&Io.push(cn)}if(g.value!=null){const cn=Z.value.byThreadId.get(String(g.value))??[],On=cn.find(Fn=>Fn.isPrimary)??cn[0];On&&Io.push(On)}for(const cn of Io){const On=cn.id,Fn=F(cn.comment);On==null||Fn==null||an.has(String(On))||Dn({id:On,threadId:Fn,instance:cn,top:wt.top,anchorBottom:wt.top,hasAnchorGeometry:!1})}if(Oe){const cn=oe();typeof cn=="number"&&!isNaN(cn)&&qe.push({id:"pending",anchorTop:cn,anchorBottom:cn,hasAnchorGeometry:!0,top:cn,height:B.value.pending||110,commentRef:h.value})}qe.sort((cn,On)=>cn.anchorTop-On.anchorTop);const Eo=[];for(const cn of qe){const On=cn.hasAnchorGeometry?e9({comment:cn.commentRef,anchorTop:cn.anchorTop,anchorBottom:cn.anchorBottom,cardHeight:cn.height,viewportTop:wt.top,viewportBottom:wt.bottom}):null;On==null?Eo.push(cn):cn.top=On}const ki=_n?Eo.findIndex(cn=>cn.id===_n):-1;return o(Eo,ki,15),qe}),Re=Ee(()=>(G.value,Math.max(0,i.parent?.clientHeight||0,i.parent?.scrollHeight||0))),Ke=()=>{se&&se.disconnect(),se=new IntersectionObserver(De=>{const Oe=new Set(Q.value);for(const qe of De){const wt=qe.target.dataset.commentId;wt&&(qe.isIntersecting?Oe.add(wt):Oe.delete(wt))}Q.value=Oe},{rootMargin:"600px 0px 600px 0px"})},tt=()=>{if(!se)return;const De=new Set;for(const Oe of Ct.value){const qe=q.value[Oe.id];qe&&(De.add(qe),he.has(qe)||(se.observe(qe),he.add(qe)))}for(const Oe of he)De.has(Oe)||(se.unobserve(Oe),he.delete(Oe))},ee=(De,Oe)=>{Oe<=0||Oe===B.value[De]||(Hl[De]=Oe,B.value={...B.value,[De]:Oe})},_=De=>{if(!De)return;const{elementRef:Oe,commentId:qe}=De;Oe&&Tt(()=>{const wt=Oe.value?.getBoundingClientRect();!wt||wt.height<=0||qe&&ee(qe,wt.height)})},te=De=>{const Oe=De?.id;Oe&&Tt(()=>{const qe=q.value[Oe];if(!qe)return;const wt=qe.querySelector(".comments-dialog");if(!wt)return;ee(Oe,wt.getBoundingClientRect().height);const ft=Oe===N.value,Pt=Oe==="pending",_n=!!g.value&&!!c.value&&De?.threadId!=null&&String(De.threadId)===String(c.value);!ft&&!Pt&&!_n||(mn(Ct.value.map(an=>an.id)),rt(()=>Ct.value.map(an=>an.id)))})},D=De=>{!De&&V.value!=null||(L.value=De)},U=(De,Oe,qe)=>{if(!Number.isFinite(Oe)){qe?.(!1);return}const wt=q.value[De];if(!wt){qe?.(!1);return}const ft=wt.getBoundingClientRect().top;x.value+=Oe-ft,qe?.(!0)},$=(De,Oe)=>{if(Oe)q.value[De]=Oe,se&&!he.has(Oe)&&(se.observe(Oe),he.add(Oe));else{const qe=q.value[De];qe&&se&&(se.unobserve(qe),he.delete(qe)),delete q.value[De]}};let H=[],J=null,X=[],W=null,we=!1,ge=0,be=null,Be=null,Ze=null,it=null,yt=null;const Xt=new Set,xt=()=>{Ze=null,it=null,V.value=null,D(!1)},Ft=De=>{if(!Ze)return;const Oe=(De?.target instanceof Element?De.target:null)?.closest?.("[data-comment-action]"),qe=Oe?.getAttribute?.("data-comment-action");(qe==="resolve"||qe==="reject")&&y.value?.contains?.(Oe)||xt()},Ut=()=>{H.forEach(clearTimeout),H=[]},mn=De=>{for(const Oe of De.filter(Boolean)){const qe=q.value[Oe];if(!qe)continue;const wt=qe.querySelector(".comments-dialog");wt&&ee(Oe,wt.getBoundingClientRect().height)}},It=50,Zt=350,rt=De=>{Ut();const Oe=typeof De=="function"?De:()=>De;H.push(setTimeout(()=>mn(Oe()),It)),H.push(setTimeout(()=>mn(Oe()),Zt))},zt=()=>{l(),requestAnimationFrame(()=>{D(!1)})},Lt=(De,Oe)=>{!De||!Number.isFinite(Oe)||(D(!0),Tt(()=>{mn([De]),U(De,Oe,()=>{zt()})}))},An=()=>{W=null,ge+=1,be!=null&&(cancelAnimationFrame(be),be=null),D(!1)},Qt=()=>{!Ze&&!W||(xt(),An(),D(!0),x.value=0,yt!=null&&cancelAnimationFrame(yt),yt=requestAnimationFrame(()=>{yt=null,!Ze&&!W&&D(!1)}))},wn=()=>{Qt(),pe()},Wn=()=>{const De=Oe=>{!Oe?.addEventListener||Xt.has(Oe)||(Oe.addEventListener("scroll",wn,{passive:!0}),Xt.add(Oe))};De(i.parent);for(let Oe=y.value?.parentElement;Oe;Oe=Oe.parentElement)r.has(window.getComputedStyle(Oe).overflowY)&&De(Oe);De(window)},go=()=>{for(const De of Xt)De.removeEventListener?.("scroll",wn);Xt.clear()},jn=()=>{if(!W||we)return;we=!0;const De=ge;be!=null&&(cancelAnimationFrame(be),be=null),D(!0),Tt(()=>{if(we=!1,De!==ge){jn();return}const{key:Oe,targetClientY:qe}=W;mn([Oe]),U(Oe,qe,wt=>{if(De===ge){if(!wt){D(!1);return}be=requestAnimationFrame(()=>{be=null,De===ge&&D(!1)})}})})},Xn=(De,Oe)=>{const qe=Ak({previousIds:X,currentIds:Oe,removedId:De}),wt=(qe?q.value[qe]:null)?.getBoundingClientRect?.().top;return!qe||!Number.isFinite(wt)?(An(),!1):(W={key:qe,targetClientY:wt},ge+=1,jn(),!0)},Ao=De=>{const Oe=De?.target?.closest?.("[data-comment-action]"),qe=Oe?.getAttribute?.("data-comment-action");if(qe!=="resolve"&&qe!=="reject"||(xt(),Oe.getAttribute?.("aria-disabled")==="true"))return;const wt=Oe.closest?.("[data-comment-id]")?.getAttribute?.("data-comment-id");if(!wt||String(N.value??"")===String(wt))return;const ft=Ct.value.filter(an=>an.commentRef?.trackedChange).map((an,Dn)=>({id:an.id,index:Dn,top:an.top})).filter(an=>Number.isFinite(an.top)).sort((an,Dn)=>an.top-Dn.top||an.index-Dn.index).map(an=>an.id),Pt=Ak({previousIds:ft,currentIds:new Set(ft),removedId:wt}),_n=(Pt?q.value[Pt]:null)?.getBoundingClientRect?.().top;!Pt||!Number.isFinite(_n)||(Ze={removedKey:wt,targetKey:Pt,targetClientY:_n,applied:!1},it=wt,V.value=Pt,D(!0))};Vt(N,(De,Oe)=>{if(Ut(),!(Ze!=null&&it!=null&&[De,Oe].some(ft=>ft!=null&&String(ft)===String(it)))){if(it=null,De)xt(),An();else if(Oe){const ft=new Set(Ct.value.map(Pt=>Pt.id));ft.has(Oe)?An():Xn(Oe,ft)}}const qe=[De,Oe],wt=De&&De===lt.value&&Number.isFinite(p.value);Tt(()=>{if(wt){mn(qe);return}rt(qe)})}),Vt([N,lt,p],([De,Oe,qe])=>{!De||!Oe||De!==Oe||!Number.isFinite(qe)||Lt(De,qe)}),Vt(g,()=>{Ut(),Tt(()=>{rt(()=>Ct.value.map(De=>De.id))})}),Vt(c,()=>{if(J&&clearTimeout(J),!c.value){if(l(),W){jn();return}D(!1),x.value=0;return}if(!(R(c.value)?h.value:a.getComment(c.value)))return;const De=R(c.value)?"pending":N.value;if(De){if(De===lt.value&&Number.isFinite(p.value)){D(!0);return}Tt(()=>{J=setTimeout(()=>{const qe=q.value[De];if(!qe)return;const wt=i.parent?.getBoundingClientRect?.();if(!wt)return;const ft=Ct.value.find(Dn=>Dn.id===De),Pt=De==="pending"?oe():ft?.anchorTop;if(typeof Pt!="number"||isNaN(Pt))return;const _n=qe.getBoundingClientRect().top,an=wt.top+Pt;x.value+=an-_n},400)})}}),Vt(C,()=>{if(i.currentDocument.type==="application/pdf"){for(const De in Hl)delete Hl[De];B.value={},w.value+=1}});let Nr=new Set,rr=null,Pn=null;return Vt(Ct,De=>{const Oe=N.value?De.find(Jt=>Jt.id===N.value):null,qe=typeof Oe?.anchorTop=="number"&&Number.isFinite(Oe.anchorTop)?Oe.anchorTop:null,wt=qe!=null&&rr!=null&&Math.abs(qe-rr)>1,ft=typeof Oe?.top=="number"&&Number.isFinite(Oe.top)?Oe.top:null,Pt=ft!=null&&Pn!=null&&Math.abs(ft-Pn)>1;wt&&x.value!==0&&!Number.isFinite(p.value)?(x.value=0,D(!1)):Pt&&x.value!==0&&!Number.isFinite(p.value)&&!W&&(D(!0),x.value+=Pn-ft,Be!=null&&cancelAnimationFrame(Be),Be=requestAnimationFrame(()=>{Be=null,!W&&!Number.isFinite(p.value)&&D(!1)})),rr=qe,Pn=ft;const _n=De.map(Jt=>Jt.id),an=new Set(_n);if(Ze&&!Ze.applied&&!an.has(Ze.removedKey)){const{targetKey:Jt,targetClientY:Un}=Ze;Ze.applied=!0,an.has(Jt)&&Number.isFinite(Un)?(W={key:Jt,targetClientY:Un},ge+=1,jn()):xt()}if(Ze?.applied&&!an.has(Ze.targetKey)&&xt(),W&&!an.has(W.key)){const Jt=W.key;Xn(Jt,an)||(D(!1),x.value=0)}const Dn=new Set(Q.value);let Io=!1,Eo=-1/0,ki=1/0;const cn=y.value;if(cn){const Jt=cn.getBoundingClientRect();Eo=-Jt.top-600,ki=-Jt.top+window.innerHeight+600}const On=new Map(De.map(Jt=>[Jt.id,Jt]));for(const Jt of an)if(!Dn.has(Jt)){const Un=On.get(Jt);(!Un||Un.top>=Eo&&Un.top<=ki)&&(Dn.add(Jt),Io=!0)}for(const Jt of Dn)an.has(Jt)||(Dn.delete(Jt),Io=!0);Io&&(Q.value=Dn);for(const Jt of Nr)an.has(Jt)||delete Hl[Jt];const Fn=Nr.size!==an.size||[...Nr].some(Jt=>!an.has(Jt)),lr=X.length!==_n.length||X.some((Jt,Un)=>Jt!==_n[Un]);if(Fn){const Jt={};for(const Un of an)Hl[Un]&&(Jt[Un]=Hl[Un]);B.value=Jt,Tt(()=>{for(const Un of De){const ro=q.value[Un.id];if(!ro)continue;const Pi=ro.querySelector(".comments-dialog");Pi&&ee(Un.id,Pi.getBoundingClientRect().height)}})}W&&(Fn||lr)&&jn(),Nr=an,Tt(()=>{X=_n,tt()})}),Gn(()=>{Ke(),Wn(),window.addEventListener("resize",pe,{passive:!0}),document.addEventListener("pointerdown",Ft,!0),Tt(tt)}),gr(()=>{Ut(),J&&clearTimeout(J),xt(),An(),Be!=null&&(cancelAnimationFrame(Be),Be=null),yt!=null&&(cancelAnimationFrame(yt),yt=null),go(),window.removeEventListener("resize",pe),document.removeEventListener("pointerdown",Ft,!0),Ne!=null&&(cancelAnimationFrame(Ne),Ne=null),se&&(se.disconnect(),se=null,he.clear())}),(De,Oe)=>(ve(),Te("div",{class:"section-wrapper",ref_key:"floatingCommentsContainer",ref:y,onClickCapture:Ao,style:Sn({minHeight:Re.value+"px",transition:L.value?"none":void 0})},[Fe("div",{class:"sidebar-container",style:Sn({transform:`translateY(${x.value}px)`,transition:L.value?"none":void 0})},[(ve(!0),Te(Yt,null,mr(Ct.value,qe=>(ve(),Te("div",{key:qe.id,ref_for:!0,ref:wt=>$(qe.id,wt),"data-comment-id":qe.id,"data-comment-instance-id":qe.id,"data-comment-thread-id":qe.threadId,"data-comment-position-key":qe.instanceRef?.positionKey??"","data-comment-page-index":qe.pageIndex??"",class:on([{"is-direct-decision-continuity-target":qe.id===V.value},"comment-placeholder"]),style:Sn({top:qe.top+"px",height:qe.height+"px",transition:L.value?"none":void 0})},[Me(qe)?(ve(),hn(Pp,{key:qe.id+w.value,onReady:_,onResize:wt=>te(qe),class:"floating-comment",parent:e.parent,comment:qe.commentRef,"floating-instance-id":qe.id,"floating-page-index":qe.pageIndex,"floating-position-entry":qe.instanceRef?.positionEntry??null,"is-floating-instance-active":qe.id===N.value},null,8,["onResize","parent","comment","floating-instance-id","floating-page-index","floating-position-entry","is-floating-instance-active"])):vt("",!0)],14,n9))),128))],4)],36))}},o9=pn(r9,[["__scopeId","data-v-d8d03209"]]);Dt(),bn();var i9={class:"superdoc__pdf-comments-layer pdf-comments-layer","aria-hidden":"false"},s9=["data-id","data-comment-id","data-page-number","onClick","onKeydown"],a9="pdf",l9="#078383",c9="#B1124B",u9={__name:"PdfCommentsLayer",emits:["anchor-activate"],setup(e,{emit:t}){const n=t,r=da(),o=su(),{activeComment:i}=na(r),{documents:s,activeZoom:a}=na(o),{proxy:l}=vr(),c=y=>typeof y=="number"?Number.isFinite(y):typeof y=="string"&&y.trim()!==""?Number.isFinite(Number(y)):!1,u=y=>!!y&&c(y.top)&&c(y.left)&&c(y.right)&&c(y.bottom),d=Ee(()=>{const y=Array.isArray(s.value)?s.value:[];return new Set(y.filter(w=>w?.type===Vl).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}},S=Ee(()=>{const y=r.getFloatingComments;return Array.isArray(y)?y.filter(w=>w?.selection?.source===a9).filter(w=>!w.resolvedTime).filter(w=>g(w)!==null).filter(w=>u(w.selection?.selectionBounds)).filter(w=>p(w)).map(w=>{const x=g(w),L=v(w.selection.selectionBounds);return{commentId:x,page:w.selection?.page??null,isInternal:w.isInternal!==!1,bounds:L}}):[]}),C=y=>{const w=(a.value??100)/100,{top:x,left:L,right:V,bottom:G}=y.bounds,R=i.value===y.commentId,F=(y.isInternal?l9:c9)+(R?"66":"33");return{position:"absolute",top:x*w+"px",left:L*w+"px",width:(V-L)*w+"px",height:(G-x)*w+"px",backgroundColor:F}},A=y=>{r.setActiveComment(l.$superdoc,y.commentId),n("anchor-activate",y.commentId)};return(y,w)=>(ve(),Te("div",i9,[(ve(!0),Te(Yt,null,mr(S.value,x=>(ve(),Te("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:rn(L=>A(x),["stop","prevent"]),onKeydown:[oi(rn(L=>A(x),["stop","prevent"]),["enter"]),oi(rn(L=>A(x),["stop","prevent"]),["space"])]},null,44,s9))),128))]))}},d9=pn(u9,[["__scopeId","data-v-b5ad4c58"]]);Dt();var f9=({proxy:e,layers:t,documents:n,modules:r})=>{const o=Ee(()=>{const F=r.value?.whiteboard??r.whiteboard;return F===!1||F==null?null:F}),i=e?.$superdoc?.whiteboard,s=to([]),a=Jr({}),l=Jr({}),c=re(!1),u=re(0),d=re(0),h=re(1),g=re(o.value?.enabled??!1),p=()=>{if(c.value)return;u.value+=1;const F=d.value||s.value.length;F&&u.value>=F&&(c.value=!0,e?.$superdoc?.emit("whiteboard:ready",{whiteboard:i}))},v=F=>{if(!F)return;const Z=n.value?.[0];Z&&Z.type==="application/pdf"&&S(F)},S=F=>{const{pageIndex:Z,width:O,height:N,originalWidth:T,originalHeight:B}=F,Q={width:O,height:N,originalWidth:T,originalHeight:B};i?.setPageSize(Z,Q),a[Z]=Q;const q=i?.getPage(Z);q&&q.setSize(Q),i&&(s.value=i.getPages().sort((se,he)=>se.pageIndex-he.pageIndex).map(se=>eo(se)),d.value=s.value.length),Tt(()=>{G(),p()})},C=F=>{e?.$superdoc?.emit("whiteboard:change",F)},A=F=>{F.forEach(Z=>{const O=a[Z.pageIndex];O&&Z.setSize(O)}),s.value=F.map(Z=>eo(Z)),d.value=s.value.length,Tt(()=>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)},L=()=>{const F=n.value?.[0];F&&F.type==="application/pdf"&&V({doc:F})},V=({doc:F})=>{s.value.forEach(Z=>{const O=`${F.id}-page-${Z.pageIndex+1}`,N=document.querySelector(`[data-page-id="${O}"]`);if(!N)return;const T=N.getBoundingClientRect(),B=a[Z.pageIndex]||{},Q=B.originalWidth??Z.size?.originalWidth??T.width,q=B.originalHeight??Z.size?.originalHeight??T.height,se={width:T.width,height:T.height,originalWidth:Q,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(O=>{const N=`${F.id}-page-${O.pageIndex+1}`,T=document.querySelector(`[data-page-id="${N}"]`);if(!T)return;const B=T.getBoundingClientRect();l[O.pageIndex]={top:B.top-Z.top,left:B.left-Z.left}})};return i&&(i.on("change",C),i.on("setData",A),i.on("enabled",y),i.on("opacity",w),i.on("tool",x)),gr(()=>{i&&(i.off("change",C),i.off("setData",A),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:c,handleWhiteboardPageReady:v,updateWhiteboardPageSizes:L,updateWhiteboardPageOffsets:G}};Dt(),bn();var h9=["data-page-index"],p9={__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=re(null),r=()=>{const c=n.value;!c||!t.page||(t.page.mount(c),t.pageSize&&t.page.resize(t.pageSize.width,t.pageSize.height))},o=c=>{if(!t.page||!c?.dataTransfer||!t.enabled||t.whiteboard.getTool()!=="select")return;c.preventDefault(),c.stopPropagation();const u=n.value;if(!u)return;const d=u.getBoundingClientRect(),h=c.clientX-d.left,g=c.clientY-d.top,p=t.pageSize?.width,v=t.pageSize?.originalWidth??p,S=Number.isFinite(p)&&Number.isFinite(v)&&v?p/v:1;i(c,h,g,S)||s(c,h,g,S)||a(c,h,g)||l(c,h,g)},i=(c,u,d,h)=>{const g=c.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:u,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=(c,u,d,h)=>{const g=Array.from(c.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:u,y:d,src:p.result,type:"image"})},p.readAsDataURL(g),!0},a=(c,u,d)=>{const h=c.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:u,y:d,content:g.text}),!0):!1},l=(c,u,d)=>{const h=c.dataTransfer.getData("text/plain");return h?(t.page.addText({x:u,y:d,content:h}),!0):!1};return Vt(()=>[t.page,t.pageSize?.width,t.pageSize?.height],()=>{Tt(r)}),Gn(()=>{r()}),gr(()=>{t.page?.destroy()}),(c,u)=>(ve(),Te("div",{ref_key:"containerRef",ref:n,class:"whiteboard-page","data-page-index":e.page.pageIndex,onDragover:u[0]||(u[0]=rn(()=>{},["prevent"])),onDrop:rn(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,h9))}},m9=pn(p9,[["__scopeId","data-v-c876c9b5"]]);Dt(),bn();var g9={__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=Ee(()=>t.interactive==null?t.enabled:t.interactive);return(r,o)=>(ve(),Te("div",{class:"whiteboard-layer","aria-hidden":"true",style:Sn({opacity:e.opacity,pointerEvents:n.value?"auto":"none"})},[(ve(!0),Te(Yt,null,mr(e.pages,i=>(ve(),hn(m9,{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))}},v9=pn(g9,[["__scopeId","data-v-54546c3d"]]);function y9(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 Ik=["#1f6feb","#d1242f","#8250df","#bf3989","#1a7f37","#9a6700","#bc4c00","#0969da","#cf222e","#6639ba","#116329","#7d4e00"],b9=e=>e?`${typeof e.name=="string"?e.name:""} ${typeof e.email=="string"?e.email:""}`:"",w9=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},C9=e=>{const t=b9(e),n=w9(t)%Ik.length;return Ik[n]},ff=e=>typeof e=="string"&&e.length>0,k9=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(ff(o.email)&&ff(t[o.email]))return t[o.email];if(ff(o.name)&&ff(t[o.name]))return t[o.name]}if(n)try{const i=n(o);if(ff(i))return i}catch{}return C9(o)}},S9=["insertion","deletion","move","move-from","move-to","table-cell-insertion","table-cell-deletion","cell-merge","cell-split","image-insertion","image-deletion","image-property-change"],HH=new Set(S9),kr={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"},$H={"render.media.missing-relationship":kr.missingRelationship,"render.media.wrong-relationship-type":kr.unsupportedRelationshipType,"render.media.unsupported-target":kr.unsupportedRelationshipType,"render.media.invalid-image-size":kr.imageTooLarge,"render.media-resolver-unavailable":kr.missingMediaPart,"render.chart-not-supported":kr.unsupportedObject,"render.textbox.vml-unsupported":kr.vmlUnsupported},_9={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:kr.externalImageDeferred},missingRelationship:{family:"missingRelationship",support:"fail-closed",description:"Drawing references a relationship id absent from the owner part .rels.",contract:"none",diagnostic:kr.missingRelationship},missingMediaPart:{family:"missingMediaPart",support:"fail-closed",description:"Relationship resolves but the target media part bytes are missing or empty.",contract:"none",diagnostic:kr.missingMediaPart},wrongRelationshipType:{family:"wrongRelationshipType",support:"fail-closed",description:"Relationship exists but is not an image relationship type.",contract:"none",diagnostic:kr.unsupportedRelationshipType},unsupportedMime:{family:"unsupportedMime",support:"fail-closed",description:"Media MIME outside the supported allowlist (incl. GIF/BMP/ICO).",contract:"none",diagnostic:kr.unsupportedMime},oversizedMediaPart:{family:"oversizedMediaPart",support:"fail-closed",description:"Media part exceeds the host byte-size policy before bytes are materialized.",contract:"none",diagnostic:kr.imageTooLarge},unsafeSvg:{family:"unsafeSvg",support:"fail-closed",description:"SVG content rejected by the SVG safety policy.",contract:"none",diagnostic:kr.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:kr.unsupportedFormat},embeddedObject:{family:"embeddedObject",support:"fail-closed",description:"OLE / ActiveX / embedded package object.",contract:"none",diagnostic:kr.embeddedObjectNotSupported},smartArtOrDiagram:{family:"smartArtOrDiagram",support:"fail-closed",description:"SmartArt / diagram / unknown external graphic-data object.",contract:"none",diagnostic:kr.unsupportedObject},vml:{family:"vml",support:"fail-closed",description:"VML structure outside any supported image-like subset (default fail-closed policy).",contract:"none",diagnostic:kr.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:kr.vmlImageUnsupported},unsupportedGeometryCommand:{family:"unsupportedGeometryCommand",support:"fail-closed",description:"Custom geometry command the extractor does not implement, e.g. arcTo.",contract:"none",diagnostic:kr.unsupportedGeometryCommand},unsupportedAnchorFields:{family:"unsupportedAnchorFields",support:"fail-closed",description:"Anchor fields required for honest placement are unsupported (char-relative, alignment modes, etc.).",contract:"none",diagnostic:kr.anchorUnsupported},unsupportedWrapFields:{family:"unsupportedWrapFields",support:"fail-closed",description:"Wrap fields required for honest placement are unsupported (arbitrary wrap polygons, etc.).",contract:"none",diagnostic:kr.wrapUnsupported},alternateContentNoSupportedChoice:{family:"alternateContentNoSupportedChoice",support:"fail-closed",description:"mc:AlternateContent with no supported choice and no usable fallback.",contract:"none",diagnostic:kr.altContentNoSupportedChoice},groupChildUnsupported:{family:"groupChildUnsupported",support:"fail-closed",description:"Unsupported child inside an otherwise-supported group. Supported siblings are not dropped.",contract:"none",diagnostic:kr.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"}},GH=Object.keys(_9),WH=Object.freeze(["multiple-sections","furniture-page-tokens","non-balanceable-multi-column-sections","body-anchored-objects","non-flowing-page-relative-body-anchors","footnotes","page-references","keep-constraints","tables","furniture-anchored-objects"]);Dt(),bn();var A9={class:"superdoc-html-viewer"},I9={class:"superdoc-html-viewer__document"},E9=["innerHTML"],T9={__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=re(""),o=t,i=()=>{const l=window.getSelection();console.debug("selection from html viewer",l),o("selection-change",l)},s=l=>new Promise((c,u)=>{const d=new FileReader;d.onload=h=>{const g=h.target.result;c(g)},d.onerror=h=>u(h),d.readAsText(l)}),a=async()=>{try{const l=await s(n.fileSource);r.value=l,o("ready",n.documentId)}catch(l){o("error",l),console.error("Error loading document",l)}};return Gn(()=>{a()}),(l,c)=>(ve(),Te("div",A9,[Fe("div",I9,[Fe("div",{class:"superdoc-html-viewer__content",innerHTML:r.value,onMouseup:i},null,40,E9)])]))}},x9=pn(T9,[["__scopeId","data-v-da3494ba"]]),R9=(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,c=s.parentCommentId!=null?String(s.parentCommentId):null,u=Lp(s),d=u!=null?String(u):null,h=a&&o.has(a)||l&&o.has(l),g=c&&o.has(c)||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};Dt();var Ek=re(!1);function Gi(){return{isHighContrastMode:Ek,setHighContrastMode:t=>{Ek.value=t}}}var KH="[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor",qH="sidebar",Tk=new Set(["auto","sidebar","inline"]);function M9(e){const t=e;return typeof t?.closest=="function"&&t.closest(".track-change-focused")!=null}function xk(e){if(!e||e===!1||typeof e!="object")return e;const t={...e},n=t.displayMode;Tk.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}Dt();var L9=".superdoc__document",P9=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,D9=e=>e+320+24;function O9({commentsModuleConfig:e,superdocRoot:t,layers:n}){const r=re(0),o=re(!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 S=document.querySelector(p.trim());if(a(S))return S}let v=g?.parentElement??null;for(;v;){if(a(v))return v;v=v.parentElement}return a(g)||g instanceof HTMLElement?g:null},c=()=>{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)))},u=()=>{c();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?.(L9),p=n.value,v=Number(g?.clientWidth??g?.getBoundingClientRect?.().width??0);if(Number.isFinite(v)&&v>0)return v;const S=Number(p?.clientWidth??p?.getBoundingClientRect?.().width??0);return Number.isFinite(S)&&S>0?S:816},h=()=>{const g=u(),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 S=p?.compactBreakpointPx;if(P9(S)){o.value=g<S;return}const C=d(),A=D9(C);o.value=g<A};return gr(()=>{i&&(i.disconnect(),i=null),s=null}),{superdocContainerWidth:r,isCompactCommentsMode:o,recalculateCompactCommentsMode:h,ensureCompactMeasurementObserver:c}}Dt();var Rk=320,nl=12,F9=220,N9=16,B9=500,Mk=".superdoc-comment-highlight[data-comment-ids]",Lk="data-comment-ids",z9=".sd-comment-anchor",d0=(e,t,n)=>Math.min(Math.max(e,t),n),bs=e=>Number(e),Wi=e=>Number.isFinite(e),f0=e=>e?.commentId??e?.importedId??null,Pk=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),V9=e=>{const t=e?.value;if(!t)return null;const n=bs(t.ts);if(!Wi(n)||Date.now()-n>B9)return null;const r=bs(t.x),o=bs(t.anchorRect?.bottom),i=Wi(o)?o:bs(t.y);return!Wi(r)||!Wi(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(Mk);for(const l of a)if(Pk(l.getAttribute(Lk)).includes("pending")&&typeof l.getBoundingClientRect=="function")return l.getBoundingClientRect()}const r=f0(t);if(!r)return null;const o=String(r),i=e.querySelectorAll(Mk);for(const a of i)if(Pk(a.getAttribute(Lk)).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},U9=(e,t)=>{const{entry:n}=e(f0(t)),r=bs(n?.bounds?.bottom);return Wi(r)?r:bs(n?.bounds?.top)},H9=({selectionPosition:e,comment:t,pendingComment:n})=>e.value?.source==="pdf"||t?.selection?.source==="pdf"||n.value?.selection?.source==="pdf",$9=({rootEl:e,layersRect:t,comment:n})=>{const r=f0(n);if(r==null)return NaN;const o=e.querySelector(`${z9}[data-id="${String(r)}"]`);if(!o||typeof o.getBoundingClientRect!="function")return NaN;const i=o.getBoundingClientRect();return bs(i.bottom)-bs(t.top)},G9=({comment:e,pendingComment:t,selectionPosition:n,activeZoom:r})=>{if(!t.value||e?.commentId!==t.value?.commentId)return NaN;const o=bs(n.value?.bottom);if(Wi(o))return o*(n.value?.source==="pdf"?(r.value??100)/100:1);const i=bs(n.value?.top);return Wi(i)?i*(n.value?.source==="pdf"?(r.value??100)/100:1):NaN},W9=({top:e,left:t})=>({top:`${Math.round(e)}px`,left:`${Math.round(t)}px`,right:"auto"}),K9=({rootRect:e,layersRect:t,anchorBottom:n,anchorClientX:r=NaN})=>{const o=t.top-e.top+n+N9,i=Math.max(nl,e.height-F9),s=d0(o,nl,i),a=Math.max(nl,e.width-Rk-nl);let l;if(Wi(r))l=d0(r-e.left+nl,nl,a);else{const c=e.width-(t.left-e.left+t.width)+nl;l=d0(e.width-c-Rk,nl,a)}return{top:s,left:l}};function q9({activeComment:e,pendingComment:t,activeCompactComment:n,showCommentsSidebar:r,selectionPosition:o,activeZoom:i,superdocRoot:s,layers:a,documents:l,resolveCommentPositionEntry:c,clearActiveComment:u,clearPendingComment:d}){const h={top:"12px",right:"12px"},g=re(0),p=re({x:null,y:null,ts:0,anchorRect:null});let v=null,S=null;const C=()=>{p.value={x:null,y:null,ts:0,anchorRect:null}},A=(L,V,G)=>{if(!l.value?.some(F=>F.type==="application/pdf"))return!1;const R=L.querySelector(".superdoc__compact-comment-popover");return!n.value||!R||R.contains(V)||G?!1:(t.value&&d(),u(),C(),!0)},y=L=>{const V=s.value;if(!V||!a.value?.contains(L.target))return;const G=(typeof document.elementsFromPoint=="function"?document.elementsFromPoint(L.clientX,L.clientY):[]).find(F=>F?.nodeType===1&&V.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")??(L.target?.nodeType===1?L.target.closest("[data-track-change-id], .superdoc-comment-highlight, .sd-comment-anchor"):null);if(A(V,L.target,G)||L.button!==0||L.pointerType!=="mouse")return;const R=G&&typeof G.getBoundingClientRect=="function"?G.getBoundingClientRect():null;R&&(p.value={x:L.clientX,y:R.bottom,ts:Date.now(),anchorRect:{left:R.left,right:R.right,top:R.top,bottom:R.bottom}})},w=Ee(()=>{g.value;const L=n.value;if(!L)return h;const V=s.value,G=a.value;if(!V||!G)return h;const R=V.getBoundingClientRect(),F=G.getBoundingClientRect(),Z=V9(p),O=Z?null:j9({rootEl:V,comment:L,pendingComment:t});let N=NaN,T=NaN;if(Z?(N=Z.y-F.top,T=Z.x):O?(N=O.bottom-F.top,T=O.left):N=U9(c,L),!Wi(N)&&H9({selectionPosition:o,comment:L,pendingComment:t})&&(N=$9({rootEl:V,layersRect:F,comment:L})),Wi(N)||(N=G9({comment:L,pendingComment:t,selectionPosition:o,activeZoom:i})),!Wi(N))return h;const B=K9({rootRect:R,layersRect:F,anchorBottom:N,anchorClientX:T});return W9(B)});return Vt([e,t,o,i,r,p],()=>{const L=typeof window<"u"?window.requestAnimationFrame:null,V=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&V?.(v),L&&(v=L(()=>{g.value+=1,v=null}))},{deep:!1}),Vt(n,(L,V)=>{if(!V&&L){const G=document.activeElement;G instanceof HTMLElement&&(S=G)}},{deep:!1}),Vt(t,(L,V)=>{!V&&L&&C()}),Gn(()=>{document.addEventListener("pointerdown",y,!0)}),gr(()=>{document.removeEventListener("pointerdown",y,!0);const L=typeof window<"u"?window.cancelAnimationFrame:null;v!=null&&(L?.(v),v=null),S=null}),{compactCommentPopoverStyle:w,closeCompactCommentPopover:()=>{n.value&&(t.value&&d(),u(),S&&typeof S.focus=="function"&&S.focus(),S=null)},resetClickAnchor:C}}function ws(...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 h0(...e){for(const t of e)if(t!==void 0)return t}function Dk(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,c)=>{l?.kind!=="entity"||l.entityType!=="trackedChange"||typeof l.entityId=="string"&&l.entityId.length>0&&c.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 c=s(l?.from),u=s(l?.to);c&&r.add(c),u&&n.add(u),c&&u&&c!==u&&o.push({from:c,to:u})}for(const l of r)n.delete(l);const a=Y9(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 Y9(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 hf=e=>new Set(Array.from(e??[]).filter(t=>typeof t=="string"&&t.length>0)),X9=e=>typeof e?.id=="string"&&e.id.length>0?e.id:typeof e?.changeId=="string"&&e.changeId.length>0?e.changeId:typeof e?.address?.entityId=="string"&&e.address.entityId.length>0?e.address.entityId:null,Z9=(e,t)=>e?.adapter===t?.adapter&&e?.documentId===t?.documentId&&e?.editor===t?.editor&&e?.reconcileToken===t?.reconcileToken;function Ok({getContext:e,reconcile:t,hydrate:n,onReconciled:r}){const o=new Map;let i=null,s=0,a=0,l=null,c=!1;const u=[],d=(R,F)=>{for(let Z=u.length-1;Z>=0;Z-=1){const O=u[Z];O.generation!==a||O.version>R||(u.splice(Z,1),O.resolve(F===!0&&O.requiresAllResolved?i==null:F))}},h=(R,F)=>a===R&&Z9(F,e()),g=(R,F)=>{const Z=new Set;for(const O of R)o.get(O)===F.get(O)&&(o.delete(O),Z.add(O));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},S=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,O=!1)=>{if(!(!O&&F.size===0||typeof r!="function"))try{await r(R,F,Z)}catch{}},A=R=>hf(R?.resolvedIds??(R?.items??[]).map(X9).filter(Boolean)),y=async(R,F,Z)=>{const O=await t(R,{upsertIds:new Set(F.keys()),removedIds:new Set,reconcileMode:"targeted"});if(!h(Z,R))return;const N=A(O),T=g(N,F);if(await C(R,T,O),new Set([...F].filter(([se,he])=>o.get(se)===he).map(([se])=>se)).size===0)return;const B=await n(R,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1});if(!h(Z,R))return;const Q=A(B),q=g(Q,F);await C(R,q,B)},w=async(R,F,Z)=>{const O=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 N=O?.ok===!0,T=N&&O?.complete===!0&&O?.sourceCoverageComplete===!0,B=N?A(O):new Set,Q=T?g(new Set(F.keys()),F):new Set;await C(R,T?Q:B,{...O,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 O=e();if(!O?.adapter)return null;c=!1;const N=a;return l=Promise.resolve().then(async()=>{if(R){let T=null;try{T=await t(O,{upsertIds:new Set,removedIds:new Set,allResolved:R.fact,reconcileMode:"targeted"})}catch{}if(!h(N,O))return;T?.ok===!0&&(i===R&&(i=null),await C(O,new Set,T,!0))}Z.size>0&&await w(O,Z,N).catch(()=>{}),F.size>0&&await y(O,F,N).catch(()=>{})}).catch(()=>{}).finally(()=>{l=null,c&&x()}),l},L=(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",O=hf(R.removedIds),N=hf(R.upsertIds);for(const B of O){const Q=o.get(B);Q?.reconcileMode==="authoritative"?o.set(B,{...Q,version:++s,gate:F,ready:!1}):o.delete(B)}const T=e();if(O.size>0&&N.size===0&&T?.adapter&&!R.allResolved)try{Promise.resolve(t(T,{upsertIds:new Set,removedIds:O})).catch(()=>{})}catch{}for(const B of N)if(!O.has(B)){const Q=o.get(B);o.set(B,{version:++s,gate:F,ready:!1,reconcileMode:Z==="authoritative"||Q?.reconcileMode==="authoritative"?"authoritative":"targeted"})}},V=R=>L(R,"render");return{enqueue:V,enqueueAfterPaint(R,F){if(!R||typeof F!="function")return V(R),Promise.resolve(!1);L(R,"exact-paint");const Z=e(),O=a,N=s;if(!Z?.adapter)return S(N),Promise.resolve(!1);const T=new Promise(q=>{u.push({generation:O,version:N,requiresAllResolved:!!R.allResolved,resolve:q})}),B=new Set([...hf(R.upsertIds),...hf(R.removedIds)]),Q=new Map([...B].flatMap(q=>{const se=o.get(q);return se?[[q,se]]:[]}));return Promise.resolve().then(()=>F()).then(async()=>{if(!h(O,Z)){d(N,!1);return}let q=v();S(N)&&(q=!0);for(const[Ne,pe]of Q)o.get(Ne)===pe&&(pe.ready||(q=!0),pe.ready=!0);l&&(q||N>0)&&(c=!0);const se=l,he=x();if(he&&await he,se){const Ne=l;Ne&&Ne!==se&&await Ne}if(!h(O,Z)){d(N,!1);return}d(N,!0)}).catch(()=>{if(!h(O,Z)){d(N,!1);return}for(const[q,se]of Q)o.get(q)===se&&(se.gate="render");i?.gate==="exact-paint"&&(i.gate="render"),d(N,!1)}),T},onRender:(R=!1)=>{const F=v();l&&(F||R)&&(c=!0),x()},reset(){for(const R of u.splice(0))R.resolve(!1);a+=1,o.clear(),i=null,c=!1},getPendingIds(){return new Set(o.keys())}}}function Q9(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 J9="no-author-configured",eM="author-required",Fk="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 Nk(e){return typeof e=="string"&&e.includes(J9)}function tM(e){if(!e||e.type!=="mutation:rejected")return!1;if(e.failureSource==="receipt"){const t=e.failure;return t?t.code==="PRECONDITION_FAILED"&&Nk(t.message):!1}return e.failureSource==="shell"?e.reason==="author-required"?!0:e.reason==="PRECONDITION_FAILED"&&Nk(e.message):!1}function nM(){const e=new Set,t=n=>typeof n=="string"&&n.length>0?n:"__default__";return{shouldNotify(n,r){if(!tM(r))return!1;const o=t(n);return e.has(o)?!1:(e.add(o),!0)},clear(n){e.delete(t(n))}}}var rM=e=>!!(e?.anchor&&e?.focus&&(e.anchor.blockId!==e.focus.blockId||e.anchor.blockOffset!==e.focus.blockOffset)),oM=(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)},iM=(e,t)=>e!=="editing"&&e!=="suggesting"?!1:rM(t),sM=Dr((()=>{})),aM=id({default:()=>qk}),Bk,zk,Vk,jk,Uk,Hk,$k,Gk,Wk,Kk,qk,lM=Dr((()=>{Dt(),sM(),bn(),Bk=["onKeydown"],zk=["id"],Vk={class:"sd-password-prompt__description"},jk={class:"sd-password-prompt__field"},Uk=["placeholder","disabled","aria-label"],Hk={key:0,class:"sd-password-prompt__error",role:"alert"},$k={class:"sd-password-prompt__actions"},Gk=["disabled"],Wk=["disabled"],Kk={__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=re(""),r=re(!1),o=re(t.passwordPrompt.errorCode==="DOCX_PASSWORD_INVALID"),i=re(o.value?t.passwordPrompt.texts.invalidMessage:""),s=Ee(()=>o.value?t.passwordPrompt.texts.invalidTitle:t.passwordPrompt.texts.title),a=Ee(()=>n.value.length>0&&!r.value);async function l(){if(!a.value)return;r.value=!0,i.value="";const u=await t.passwordPrompt.attemptPassword(n.value);if(u.success){t.resolve({password:n.value});return}r.value=!1,n.value="",u.errorCode==="DOCX_PASSWORD_INVALID"?(o.value=!0,i.value=t.passwordPrompt.texts.invalidMessage):u.errorCode==="timeout"?i.value=t.passwordPrompt.texts.timeoutMessage:i.value=t.passwordPrompt.texts.genericErrorMessage}function c(){t.close("user-cancelled")}return(u,d)=>(ve(),Te("div",{class:"sd-password-prompt",onKeydown:oi(rn(l,["prevent"]),["enter"])},[Fe("h3",{id:`sd-password-prompt-heading-${e.surfaceId}`,class:"sd-password-prompt__heading"},Ht(s.value),9,zk),Fe("p",Vk,Ht(e.passwordPrompt.texts.description),1),Fe("div",jk,[Ks(Fe("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,Uk),[[Ri,n.value]])]),i.value?(ve(),Te("p",Hk,Ht(i.value),1)):vt("",!0),Fe("div",$k,[Fe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--cancel",disabled:r.value,onClick:c},Ht(e.passwordPrompt.texts.cancelLabel),9,Gk),Fe("button",{type:"button",class:"sd-password-prompt__btn sd-password-prompt__btn--submit",disabled:!a.value,onClick:l},Ht(r.value?e.passwordPrompt.texts.busyLabel:e.passwordPrompt.texts.submitLabel),9,Wk)])],40,Bk))}},qk=pn(Kk,[["__scopeId","data-v-ecf7f6fb"]])}));Dt();var cM=["DOCX_PASSWORD_REQUIRED","DOCX_PASSWORD_INVALID"],uM=3e4,Mi={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 dM({getSurfaceManager:e,getPasswordPromptConfig:t,onUnhandled:n}){const r=[],o=to(null),i=new Map;let s=!1;function a(p,v,S){if(!p||!cM.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 A=r.find(y=>y.doc.id===p.id);return A?(A.errorCode=v,A.originalException=S,!0):(o.value?.doc.id===p.id||(r.push({doc:p,errorCode:v,originalException:S}),u()),!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 c(){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 u(){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),u()})}async function d({doc:p,errorCode:v,originalException:S}){const C=e();if(!C||s)return;const A=h(),y=V=>(p.password=V,p.editorMountNonce++,new Promise(G=>{const R=setTimeout(()=>{i.delete(p.id),G({success:!1,errorCode:"timeout"})},uM);i.set(p.id,{resolve:G,timer:R})})),w={documentId:p.id,errorCode:v,texts:A.texts,attemptPassword:y},x=g(A,{documentId:p.id,errorCode:v,texts:A.texts});if(x.suppressed){n?.(p,v,S),u();return}o.value={doc:p,surfaceHandle:null};let L;if(x.component)L=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:A.texts.title,component:eo(x.component),props:{...x.props,passwordPrompt:w}});else if(x.render){const V=x.render;L=C.open({mode:"dialog",closeOnBackdrop:!1,ariaLabel:A.texts.title,render:G=>V({container:G.container,passwordPrompt:w,resolve:G.resolve,close:G.close,surfaceId:G.surfaceId,mode:G.mode})})}else{const V=(await Promise.resolve().then(()=>(lM(),aM))).default,G=`password-prompt-${p.id}`;L=C.open({id:G,mode:"dialog",closeOnBackdrop:!1,ariaLabelledBy:`sd-password-prompt-heading-${G}`,component:eo(V),props:{passwordPrompt:w}})}o.value={doc:p,surfaceHandle:L},await L.result,o.value=null,u()}function h(){const p=t();if(p===!1)return{enabled:!1,texts:Mi};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??Mi.title,invalidTitle:v.invalidTitle??Mi.invalidTitle,description:v.description??Mi.description,placeholder:v.placeholder??Mi.placeholder,inputAriaLabel:v.inputAriaLabel??Mi.inputAriaLabel,submitLabel:v.submitLabel??Mi.submitLabel,cancelLabel:v.cancelLabel??Mi.cancelLabel,busyLabel:v.busyLabel??Mi.busyLabel,invalidMessage:v.invalidMessage??Mi.invalidMessage,timeoutMessage:v.timeoutMessage??Mi.timeoutMessage,genericErrorMessage:v.genericErrorMessage??Mi.genericErrorMessage},component:v.component,props:v.props,render:v.render,resolver:v.resolver}}function g(p,v){if(typeof p.resolver=="function"){const S=p.resolver(v);if(S!=null&&S.type!=="default"){if(S.type==="none")return{suppressed:!0};if(S.type==="custom")return{component:S.component,props:S.props};if(S.type==="external")return{render:S.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:c}}function Yk(e,{getCurrentSession:t,applySlice:n,onSettled:r}){return()=>{if(e===t())try{n(e.getSnapshot())}catch{}r()}}var fM=Dr((()=>{})),hM=id({default:()=>yS}),Xk,Zk,Qk,Jk,eS,tS,nS,rS,oS,iS,sS,aS,lS,cS,uS,dS,fS,hS,pS,mS,gS,vS,yS,pM=Dr((()=>{Dt(),fM(),bn(),Xk=["onKeydown"],Zk={class:"sd-find-replace__row"},Qk=["title","aria-label","aria-expanded"],Jk=["value","placeholder","aria-label"],eS={key:0,class:"sd-find-replace__count"},tS=["title","aria-label","aria-pressed"],nS=["title","aria-label","aria-pressed"],rS=["title","aria-label","aria-pressed"],oS={class:"sd-find-replace__nav"},iS=["disabled","title","aria-label"],sS=["disabled","title","aria-label"],aS=["title","aria-label"],lS={key:0,class:"sd-find-replace__row"},cS={class:"sd-find-replace__field"},uS=["value","placeholder","aria-label"],dS={class:"sd-find-replace__nav sd-find-replace__nav--actions"},fS=["disabled","title"],hS=["disabled","title"],pS={key:1,class:"sd-find-replace__error",role:"alert"},mS={key:0,class:"sd-find-replace__row-indent","aria-hidden":"true"},gS={class:"sd-find-replace__error-text"},vS={__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=re(null),r=Ee(()=>{const p=t.findReplace;return!!(!p.hasMatches?.value||p.replacePending?.value===!0||p.canReplace&&p.canReplace.value===!1)}),o=Ee(()=>t.findReplace.ignoreDiacriticsSupported?.value!==!1),i=Ee(()=>t.findReplace.replaceEnabled&&t.findReplace.replaceCanMutate?.value!==!1),s=Ee(()=>t.findReplace.regexSupported?.value===!0),a=Ee(()=>t.findReplace.searchError?.value??null);function l(p){p.key==="Enter"&&!p.shiftKey?(p.preventDefault(),c()):p.key==="Enter"&&p.shiftKey&&(p.preventDefault(),u())}function c(){t.findReplace.goNext(),g()}function u(){t.findReplace.goPrev(),g()}function d(){t.findReplace.close("user-closed")}function h(p){const v=[];let S=p?.parentElement??null;for(;S;){const A=S.ownerDocument?.defaultView?.getComputedStyle?.(S);if(A){const y=`${A.overflowY} ${A.overflowX}`;(y.includes("auto")||y.includes("scroll"))&&v.push(S)}S=S.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(S=>({el:S,top:S.scrollTop,left:S.scrollLeft}));p.focus({preventScroll:!0});for(const{el:S,top:C,left:A}of v)S.scrollTop!==C&&(S.scrollTop=C),S.scrollLeft!==A&&(S.scrollLeft=A)}return Gn(()=>{t.findReplace.registerFocusFn(g)}),(p,v)=>(ve(),Te("div",{class:"sd-find-replace",onKeydown:oi(rn(d,["stop"]),["esc"])},[Fe("div",Zk,[i.value?(ve(),Te("button",{key:0,type:"button",class:on(["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]=S=>e.findReplace.showReplace.value=!e.findReplace.showReplace.value)},[...v[14]||(v[14]=[Fe("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true"},[Fe("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,Qk)):vt("",!0),Fe("div",{class:on(["sd-find-replace__field",{"sd-find-replace__field--error":a.value}])},[v[15]||(v[15]=Fe("svg",{class:"sd-find-replace__search-icon",viewBox:"0 0 16 16",width:"15",height:"15","aria-hidden":"true"},[Fe("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)),Fe("input",{ref_key:"findInputRef",ref:n,value:e.findReplace.findQuery.value,onInput:v[1]||(v[1]=S=>e.findReplace.findQuery.value=S.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,Jk),e.findReplace.findQuery.value&&!a.value?(ve(),Te("span",eS,Ht(e.findReplace.matchLabel.value),1)):vt("",!0),Fe("button",{type:"button",class:on(["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]=rn(()=>{},["prevent"])),onClick:v[3]||(v[3]=S=>e.findReplace.caseSensitive.value=!e.findReplace.caseSensitive.value)},Ht(e.findReplace.texts.matchCaseLabel),43,tS),o.value?(ve(),Te("button",{key:1,type:"button",class:on(["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]=rn(()=>{},["prevent"])),onClick:v[5]||(v[5]=S=>e.findReplace.ignoreDiacritics.value=!e.findReplace.ignoreDiacritics.value)},Ht(e.findReplace.texts.ignoreDiacriticsLabel),43,nS)):vt("",!0),s.value?(ve(),Te("button",{key:2,type:"button",class:on(["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]=rn(()=>{},["prevent"])),onClick:v[7]||(v[7]=S=>e.findReplace.regex.value=!e.findReplace.regex.value)},Ht(e.findReplace.texts.regexLabel),43,rS)):vt("",!0)],2),Fe("div",oS,[Fe("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]=S=>u())},[...v[16]||(v[16]=[Fe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Fe("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,iS),Fe("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]=S=>c())},[...v[17]||(v[17]=[Fe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Fe("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,sS),v[19]||(v[19]=Fe("span",{class:"sd-find-replace__divider","aria-hidden":"true"},null,-1)),Fe("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]=[Fe("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true"},[Fe("path",{d:"m4.5 4.5 7 7m0-7-7 7",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,aS)])]),e.findReplace.showReplace.value&&i.value?(ve(),Te("div",lS,[v[20]||(v[20]=Fe("span",{class:"sd-find-replace__row-indent","aria-hidden":"true"},null,-1)),Fe("div",cS,[Fe("input",{value:e.findReplace.replaceText.value,onInput:v[10]||(v[10]=S=>e.findReplace.replaceText.value=S.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]=oi(rn(S=>e.findReplace.replaceCurrent(),["prevent"]),["enter"]))},null,40,uS)]),Fe("div",dS,[Fe("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]=S=>e.findReplace.replaceCurrent())},Ht(e.findReplace.texts.replaceLabel),9,fS),Fe("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]=S=>e.findReplace.replaceAll())},Ht(e.findReplace.texts.replaceAllLabel),9,hS)])])):vt("",!0),a.value?(ve(),Te("div",pS,[i.value?(ve(),Te("span",mS)):vt("",!0),Fe("span",gS,Ht(a.value),1)])):vt("",!0)],40,Xk))}},yS=pn(vS,[["__scopeId","data-v-41f37c29"]])}));Dt();var br={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 mM(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 gM({getSurfaceManager:e,getActiveEditor:t,activeEditorRef:n,getFindReplaceConfig:r,getSuperDocUI:o}){let i=null,s=null,a=null,l=!1,c=!1;const u=re(!1);let d=null;const h=re(""),g=re(""),p=re(!1),v=re(!1),S=re(!1),C=re(!1),A=re(0),y=re(-1),w=re(!0),x=re(!1),L=re(!0),V=re(!1),G=re(null);let R=br;const F=Ee(()=>h.value?A.value===0?R.noResultsLabel:`${y.value+1} of ${A.value}`:""),Z=Ee(()=>A.value>0),O=Ee(()=>Z.value&&!x.value&&w.value);let N=null,T=null;function B(H){return typeof H?.commands?.setSearchSession=="function"}function Q(){try{const H=(typeof o=="function"?o():null)?.search;return H&&typeof H.search=="function"?H:null}catch{return null}}function q(H){H&&(A.value=typeof H.total=="number"?H.total:0,y.value=typeof H.activeIndex=="number"?H.activeIndex:-1,w.value=H.canReplace===!0,G.value=H.reason==="search-invalid-pattern"?R.invalidPatternLabel:null)}function se(){if(a){he();return}if(s){if(!h.value){try{s.commands.clearSearchSession()}catch{}A.value=0,y.value=-1;return}try{const H=s.commands.setSearchSession(h.value,{caseSensitive:p.value,ignoreDiacritics:v.value,highlight:!0,searchModel:Re().includeDeletedText?"raw":"visible"});A.value=H.matches.length,y.value=H.activeMatchIndex}catch{}}}function he(){const H=a;if(H){if(!h.value){try{H.clear()}catch{}A.value=0,y.value=-1,G.value=null;return}try{q(H.search(h.value,{caseSensitive:p.value,includeDeletedText:Re().includeDeletedText===!0,regex:S.value}))}catch{}}}function Ne(){N&&clearTimeout(N),N=setTimeout(se,150)}Vt(h,()=>{u.value&&Ne()}),Vt(p,()=>{u.value&&se()}),Vt(v,()=>{u.value&&se()}),Vt(S,()=>{u.value&&se()});let pe=!0;function ye(){if(Z.value){if(a){try{a.next(),q(a.getSnapshot())}catch{}return}if(s)try{const H=s.commands.nextSearchMatch();y.value=H.activeMatchIndex}catch{}}}function me(){if(Z.value){if(a){try{a.previous(),q(a.getSnapshot())}catch{}return}if(s)try{const H=s.commands.previousSearchMatch();y.value=H.activeMatchIndex}catch{}}}function _e(){if(pe&&!x.value&&Z.value){if(a){if(!w.value)return;const H=a;x.value=!0;const J=Yk(H,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let X=null;try{X=H.replace(g.value)}catch{}X&&typeof X.then=="function"?Promise.resolve(X).then(J,J):J();return}if(s)try{const H=s.commands.replaceSearchMatch(g.value);A.value=H.matches.length,y.value=H.activeMatchIndex}catch{}}}function oe(){if(pe&&!x.value&&Z.value){if(a){if(!w.value)return;const H=a;x.value=!0;const J=Yk(H,{getCurrentSession:()=>a,applySlice:q,onSettled:()=>{x.value=!1}});let X=null;try{X=H.replaceAll(g.value)}catch{}X&&typeof X.then=="function"?Promise.resolve(X).then(J,J):J();return}if(s)try{s.commands.replaceAllSearchMatches(g.value),A.value=0,y.value=-1}catch{}}}function Me(){if(a){try{q(a.getSnapshot())}catch{}return}const H=mM(s);if(!H)return;const J=H.searchResults,X=Array.isArray(J)?J.length:0,W=H.activeMatchIndex??-1;X!==A.value&&(A.value=X),W!==y.value&&(y.value=W)}function Ge(){lt(),T=setInterval(Me,200)}function lt(){N&&clearTimeout(N),N=null,T&&clearInterval(T),T=null}function Ct(){h.value="",g.value="",p.value=!1,v.value=!1,S.value=!1,G.value=null,C.value=!1,A.value=0,y.value=-1,w.value=!0,x.value=!1}function Re(){const H=typeof r=="function"?r():void 0;if(H===!1||H==null)return{enabled:!1,texts:br,replaceEnabled:!0};if(H===!0)return{enabled:!0,texts:br,replaceEnabled:!0};const J=typeof H=="object"?H:{};if(J.component!=null&&typeof J.render=="function")throw new Error('modules.surfaces.findReplace cannot provide both "component" and "render". Use one or the other.');return{enabled:!0,texts:{findPlaceholder:J.findPlaceholder??br.findPlaceholder,findAriaLabel:J.findAriaLabel??br.findAriaLabel,replacePlaceholder:J.replacePlaceholder??br.replacePlaceholder,replaceAriaLabel:J.replaceAriaLabel??br.replaceAriaLabel,noResultsLabel:J.noResultsLabel??br.noResultsLabel,previousMatchLabel:J.previousMatchLabel??br.previousMatchLabel,previousMatchAriaLabel:J.previousMatchAriaLabel??br.previousMatchAriaLabel,nextMatchLabel:J.nextMatchLabel??br.nextMatchLabel,nextMatchAriaLabel:J.nextMatchAriaLabel??br.nextMatchAriaLabel,closeLabel:J.closeLabel??br.closeLabel,closeAriaLabel:J.closeAriaLabel??br.closeAriaLabel,replaceLabel:J.replaceLabel??br.replaceLabel,replaceAllLabel:J.replaceAllLabel??br.replaceAllLabel,toggleReplaceLabel:J.toggleReplaceLabel??br.toggleReplaceLabel,toggleReplaceAriaLabel:J.toggleReplaceAriaLabel??br.toggleReplaceAriaLabel,matchCaseLabel:J.matchCaseLabel??br.matchCaseLabel,matchCaseAriaLabel:J.matchCaseAriaLabel??br.matchCaseAriaLabel,regexLabel:J.regexLabel??br.regexLabel,regexAriaLabel:J.regexAriaLabel??br.regexAriaLabel,invalidPatternLabel:J.invalidPatternLabel??br.invalidPatternLabel,ignoreDiacriticsLabel:J.ignoreDiacriticsLabel??br.ignoreDiacriticsLabel,ignoreDiacriticsAriaLabel:J.ignoreDiacriticsAriaLabel??br.ignoreDiacriticsAriaLabel},replaceEnabled:J.replaceEnabled??!0,includeDeletedText:J.includeDeletedText??!1,component:J.component,props:J.props,render:J.render,resolver:J.resolver,floating:J.floating&&typeof J.floating=="object"?J.floating:void 0}}function Ke(H,J){if(typeof H.resolver=="function"){const X=H.resolver(J);if(X!=null&&X.type!=="default"){if(X.type==="none")return{suppressed:!0};if(X.type==="custom")return{component:X.component,props:X.props};if(X.type==="external")return{render:X.render}}}return H.component!=null?{component:H.component,props:H.props}:typeof H.render=="function"?{render:H.render}:{builtin:!0}}function tt(H,J){return{findQuery:h,replaceText:g,caseSensitive:p,ignoreDiacritics:v,regex:S,showReplace:C,matchCount:A,activeMatchIndex:y,matchLabel:F,hasMatches:Z,canReplace:O,replaceCanMutate:w,replacePending:x,ignoreDiacriticsSupported:L,regexSupported:V,searchError:G,replaceEnabled:H.replaceEnabled??!0,texts:H.texts,goNext:ye,goPrev:me,replaceCurrent:_e,replaceAll:oe,registerFocusFn:X=>{d=X},close:X=>J(X)}}function ee(H){return{get findQuery(){return H.findQuery.value},set findQuery(J){H.findQuery.value=J},get replaceText(){return H.replaceText.value},set replaceText(J){H.replaceText.value=J},get caseSensitive(){return H.caseSensitive.value},set caseSensitive(J){H.caseSensitive.value=J},get ignoreDiacritics(){return H.ignoreDiacritics.value},set ignoreDiacritics(J){H.ignoreDiacritics.value=J},get regex(){return H.regex.value},set regex(J){H.regex.value=J},get regexSupported(){return H.regexSupported.value},get searchError(){return H.searchError.value},get replaceCanMutate(){return H.replaceCanMutate.value},get showReplace(){return H.showReplace.value},set showReplace(J){H.showReplace.value=J},get matchCount(){return H.matchCount.value},get activeMatchIndex(){return H.activeMatchIndex.value},get matchLabel(){return H.matchLabel.value},get hasMatches(){return H.hasMatches.value},get canReplace(){return H.canReplace.value},get replacePending(){return H.replacePending.value},get ignoreDiacriticsSupported(){return H.ignoreDiacriticsSupported.value},replaceEnabled:H.replaceEnabled,texts:H.texts,goNext:H.goNext,goPrev:H.goPrev,replaceCurrent:H.replaceCurrent,replaceAll:H.replaceAll,registerFocusFn:H.registerFocusFn,close:H.close}}function _(H){if(H){if(typeof H?.commands?.clearSearchSession=="function"){try{H.commands.clearSearchSession()}catch{}return}if(a&&H===s)try{a.clear()}catch{}}}function te(){try{if(l||!e()||!t())return!1;if(i&&u.value)return!0;const H=Re();if(!H.enabled||Ke(H,{texts:H.texts,replaceEnabled:H.replaceEnabled??!0}).suppressed)return!1;if(!B(t())){const J=Q();if(!J)return!1;try{if(J.getSnapshot?.().available!==!0)return!1}catch{return!1}}return!0}catch{return!1}}async function D(){if(l)return;const H=e();if(H){if(i&&u.value){d?.();return}if(!c){c=!0;try{const J=t();if(!J){c=!1;return}const X=Re();if(!X.enabled){c=!1;return}const W=Ke(X,{texts:X.texts,replaceEnabled:X.replaceEnabled??!0});if(W.suppressed){c=!1;return}Ct(),R=X.texts,pe=X.replaceEnabled??!0;const we={placement:"top-right",autoFocus:!0,width:420,...X.floating??{}};if(s&&s!==J&&_(s),s=J,a=B(J)?null:Q(),L.value=!a,V.value=!!a,a)try{q(a.getSnapshot())}catch{}d=null;let ge=()=>{};const be=tt(X,it=>ge(it));let Be;if(W.component)Be=H.open({mode:"floating",ariaLabel:X.texts.findAriaLabel,closeOnEscape:!0,floating:we,component:eo(W.component),props:{...W.props,findReplace:be}});else if(W.render){const it=W.render;Be=H.open({mode:"floating",ariaLabel:X.texts.findAriaLabel,closeOnEscape:!0,floating:we,render:yt=>it({container:yt.container,findReplace:ee(be),resolve:yt.resolve,close:yt.close,surfaceId:yt.surfaceId,mode:yt.mode})})}else{let it;try{it=(await Promise.resolve().then(()=>(pM(),hM))).default}catch{c=!1;return}if(l||i&&u.value){c=!1;return}const yt=t()||J;s!==yt&&(_(s),s=yt,a=B(yt)?null:Q(),L.value=!a),Be=H.open({mode:"floating",ariaLabel:X.texts.findAriaLabel,component:eo(it),closeOnEscape:!0,floating:we,props:{findReplace:be}})}ge=it=>Be.close(it??"programmatic"),i=Be,u.value=!0,c=!1,Ge();const Ze=Be.id;Be.result.then(()=>{i?.id===Ze?(lt(),_(s),i=null,u.value=!1,d=null):_(J!==s?J:null)})}catch(J){throw c=!1,J}}}}function U(){i&&i.close("programmatic")}n&&Vt(n,(H,J)=>{!u.value||!i||H!==J&&(_(J),U())});function $(){l=!0,lt(),U(),s=null,a=null,d=null}return{open:D,close:U,isOpen:u,wouldOpen:te,destroy:$}}var pf=null;function p0(e){e!=null&&(pf=e)}function vM(e){pf===e&&(pf=null)}function yM(e){return pf===null||pf===e}function bM(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)&&yM(n)}var wM=/^(https?|mailto|tel):/i,CM=/^(javascript|data|vbscript):/i,kM=/^[a-z][a-z0-9+.-]*:/i;function SM(e){if(typeof e!="string")return null;const t=e.trim();return t?t.startsWith("#")?{href:t}:CM.test(t)?null:kM.test(t)?wM.test(t)?{href:t}:null:{href:t}:null}var _M='<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>',AM='<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>',IM='<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>',bS='<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>',EM=`<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
  `,TM=`<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
  `,xM='<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>',RM=`<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
  `,m_=()=>{if(typeof document>"u")throw new Error(kD)},Ki=class JA{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new JA(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),o=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,s=this.m[0]*-r+this.m[2]*n,a=this.m[1]*-r+this.m[3]*n;return this.m[0]=o,this.m[1]=i,this.m[2]=s,this.m[3]=a,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,o=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,s=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=o,this.m[2]=i,this.m[3]=s,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],o=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],s=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],a=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=o,this.m[3]=i,this.m[4]=s,this.m[5]=a,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,o=-this.m[2]*t,i=this.m[0]*t,s=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),a=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=o,this.m[3]=i,this.m[4]=s,this.m[5]=a,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],i=this.m[4],s=this.m[5],a=t*o-n*r,l={x:i,y:s,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const c=Math.sqrt(t*t+n*n);l.rotation=n>0?Math.acos(t/c):-Math.acos(t/c),l.scaleX=c,l.scaleY=a/c,l.skewX=(t*r+n*o)/a,l.skewY=0}else if(r!=0||o!=0){const c=Math.sqrt(r*r+o*o);l.rotation=Math.PI/2-(o>0?Math.acos(-r/c):-Math.acos(r/c)),l.scaleX=a/c,l.scaleY=c,l.skewX=0,l.skewY=(t*r+n*o)/a}return l.rotation=xe._getRotation(l.rotation),l}},SD="[object Array]",_D="[object Number]",AD="[object String]",ID="[object Boolean]",ED=Math.PI/180,TD=180/Math.PI,yf="#",xD="",RD="0",MD="Konva warning: ",g_="Konva error: ",LD="rgb(",C0={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]},PD=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,Hp=[],bf=null,DD=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(e){setTimeout(e,16)},xe={_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)===SD},_isNumber(e){return Object.prototype.toString.call(e)===_D&&!isNaN(e)&&isFinite(e)},_isString(e){return Object.prototype.toString.call(e)===AD},_isBoolean(e){return Object.prototype.toString.call(e)===ID},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){Hp.push(e),Hp.length===1&&DD(function(){const t=Hp;Hp=[],t.forEach(function(n){n()})})},createCanvasElement(){m_();const e=document.createElement("canvas");try{e.style=e.style||{}}catch{}return e},createImageElement(){return m_(),document.createElement("img")},_isInDocument(e){for(;e=e.parentNode;)if(e==document)return!0;return!1},_urlToImage(e,t){const n=xe.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(yf,xD);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=RD+e;return yf+e},isCanvasFarblingActive(){if(bf!==null)return bf;if(typeof document>"u")return bf=!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 bf=r,this.releaseCanvas(e),bf},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),yf+this._rgbToHex(e,t,n)},getSnappedHexColor(e){const t=this._hexToRgb(e);return yf+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 C0?(t=C0[e],{r:t[0],g:t[1],b:t[2]}):e[0]===yf?this._hexToRgb(e.substring(1)):e.substr(0,4)===LD?(t=PD.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",xe._namedColorToRBA(e)||xe._hex3ColorToRGBA(e)||xe._hex4ColorToRGBA(e)||xe._hex6ColorToRGBA(e)||xe._hex8ColorToRGBA(e)||xe._rgbColorToRGBA(e)||xe._rgbaColorToRGBA(e)||xe._hslColorToRGBA(e)},_namedColorToRBA(e){const t=C0[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 c=2*i-s,u=[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=c+(s-c)*6*a:2*a<1?l=s:3*a<2?l=c+(s-c)*(2/3-a)*6:l=c,u[d]=l*255;return{r:Math.round(u[0]),g:Math.round(u[1]),b:Math.round(u[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*ED},radToDeg(e){return e*TD},_degToRad(e){return xe.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),xe.degToRad(e)},_radToDeg(e){return xe.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),xe.radToDeg(e)},_getRotation(e){return St.angleDeg?xe.radToDeg(e):e},_capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)},throw(e){throw new Error(g_+e)},error(e){console.error(g_+e)},warn(e){St.showWarnings&&console.warn(MD+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 c=(e-n)*(e-n)+(t-r)*(t-r);if(c==0)s=e,a=t,l=(o-n)*(o-n)+(i-r)*(i-r);else{const u=((o-e)*(n-e)+(i-t)*(r-t))/c;u<0?(s=e,a=t,l=(e-o)*(e-o)+(t-i)*(t-i)):u>1?(s=n,a=r,l=(n-o)*(n-o)+(r-i)*(r-i)):(s=e+u*(n-e),a=t+u*(r-t),l=(s-o)*(s-o)+(a-i)*(a-i))}return[s,a,l]},_getProjectionToLine(e,t,n){const r=xe.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=xe._getProjectionToSegment(i.x,i.y,a.x,a.y,e.x,e.y),c=l[0],u=l[1],d=l[2];d<o&&(r.x=c,r.y=u,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=xe._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||xe._isElement(e[n]))if(t.configurable)delete e[n];else return null;else if(xe._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){St.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,c=0;typeof r=="number"?s=a=l=c=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),c=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-c),e.arc(o+t-c,i+n-c,c,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],c={x:a.x-s.x,y:a.y-s.y},u={x:l.x-a.x,y:l.y-a.y},d=Math.hypot(c.x,c.y),h=Math.hypot(u.x,u.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:c.x/d,y:c.y/d},v={x:u.x/h,y:u.y/h},S={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(S.x,S.y):e.lineTo(S.x,S.y),e.arcTo(a.x,a.y,C.x,C.y,g)}}};function OD(e){const t=[],n=e.length,r=xe;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 v_=",",FD="(",ND=")",BD="([",zD="])",VD=";",jD="()",UD="=",y_=["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"],HD=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],$D=100,$p=null;function b_(){if($p!==null)return $p;try{const e=xe.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:($p=!1,!1)}catch{return $p=!1,!1}}var Gp=class{constructor(e){this.canvas=e,St.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+=jD:xe._isArray(l[0])?o+=BD+l.join(v_)+zD:(t&&(l=l.map(c=>typeof c=="number"?Math.floor(c):c)),o+=FD+l.join(v_)+ND)):(o+=s.property,e||(o+=UD+s.val)),o+=VD;return o}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,n;t.push(e),n=t.length,n>=$D&&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 c=arguments,u=this._context;c.length===3?u.drawImage(e,t,n):c.length===5?u.drawImage(e,t,n,r,o):c.length===9&&u.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=y_.length,n=this.setAttr,r,o;const i=function(s){let a=e[s],l;e[s]=function(){return o=OD(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(y_[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)}};HD.forEach(function(e){Object.defineProperty(Gp.prototype,e,{get(){return this._context[e]},set(t){this._context[e]=t}})});var GD=class extends Gp{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(),c=a.x*l,u=a.y*l;this.setAttr("shadowColor",o),this.setAttr("shadowBlur",i*Math.min(Math.abs(c),Math.abs(u))),this.setAttr("shadowOffsetX",s.x*c),this.setAttr("shadowOffsetY",s.y*u)}},WD=class extends Gp{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()}}},Wp;function KD(){if(Wp)return Wp;const e=xe.createCanvasElement(),t=e.getContext("2d");return Wp=(function(){return(St._global.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)})(),xe.releaseCanvas(e),Wp}var k0=class{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const t=(e||{}).pixelRatio||St.pixelRatio||KD();this.pixelRatio=t,this._canvas=xe.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 xe.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}},rl=class extends k0{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new GD(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}},S0=class extends k0{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new WD(this),this.setSize(e.width,e.height)}},Vn={get isDragging(){let e=!1;return Vn._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(e=!0)}),e},justDragged:!1,get node(){let e;return Vn._dragElements.forEach(t=>{e=t.node}),e},_dragElements:new Map,_drag(e){const t=[];Vn._dragElements.forEach((n,r)=>{const{node:o}=n,i=o.getStage();i.setPointersPositions(e),n.pointerId===void 0&&(n.pointerId=xe._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=[];Vn._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")&&(Vn.justDragged=!0,St._mouseListenClick=!1,St._touchListenClick=!1,St._pointerListenClick=!1,n.dragStatus="stopped");const i=n.node.getLayer()||n.node instanceof St.Stage&&n.node;i&&t.indexOf(i)===-1&&t.push(i)}),t.forEach(n=>{n.draw()})},_endDragAfter(e){Vn._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:e},!0),t.dragStatus!=="dragging"&&Vn._dragElements.delete(n)})}};St.isBrowser&&(window.addEventListener("mouseup",Vn._endDragBefore,!0),window.addEventListener("touchend",Vn._endDragBefore,!0),window.addEventListener("touchcancel",Vn._endDragBefore,!0),window.addEventListener("mousemove",Vn._drag),window.addEventListener("touchmove",Vn._drag),window.addEventListener("mouseup",Vn._endDragAfter,!1),window.addEventListener("touchend",Vn._endDragAfter,!1),window.addEventListener("touchcancel",Vn._endDragAfter,!1));function ol(e){return xe._isString(e)?'"'+e+'"':Object.prototype.toString.call(e)==="[object Number]"||xe._isBoolean(e)?e:Object.prototype.toString.call(e)}function w_(e){return e>255?255:e<0?0:Math.round(e)}function bt(){if(St.isUnminified)return function(e,t){return xe._isNumber(e)||xe.warn(ol(e)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),e}}function Kp(e){if(St.isUnminified)return function(t,n){let r=xe._isNumber(t),o=xe._isArray(t)&&t.length==e;return!r&&!o&&xe.warn(ol(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array<number>('+e+")"),t}}function _0(){if(St.isUnminified)return function(e,t){return xe._isNumber(e)||e==="auto"||xe.warn(ol(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),e}}function Gl(){if(St.isUnminified)return function(e,t){return xe._isString(e)||xe.warn(ol(e)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),e}}function C_(){if(St.isUnminified)return function(e,t){const n=xe._isString(e),r=Object.prototype.toString.call(e)==="[object CanvasGradient]"||e&&e.addColorStop;return n||r||xe.warn(ol(e)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),e}}function qD(){if(St.isUnminified)return function(e,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&e instanceof n||(xe._isArray(e)?e.forEach(function(r){xe._isNumber(r)||xe.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):xe.warn(ol(e)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),e}}function qi(){if(St.isUnminified)return function(e,t){return e===!0||e===!1||xe.warn(ol(e)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),e}}function YD(e){if(St.isUnminified)return function(t,n){return t==null||xe.isObject(t)||xe.warn(ol(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+e),t}}var wf="get",Cf="set",de={addGetterSetter(e,t,n,r,o){de.addGetter(e,t,n),de.addSetter(e,t,r,o),de.addOverloadedGetterSetter(e,t)},addGetter(e,t,n){const r=wf+xe._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=Cf+xe._capitalize(t);e.prototype[o]||de.overWriteSetter(e,t,n,r)},overWriteSetter(e,t,n,r){const o=Cf+xe._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=xe._capitalize,a=wf+s(t),l=Cf+s(t);e.prototype[a]=function(){const u={};for(let d=0;d<i;d++){const h=n[d];u[h]=this.getAttr(t+s(h))}return u};const c=YD(n);e.prototype[l]=function(u){const d=this.attrs[t];r&&(u=r.call(this,u,t)),c&&c.call(this,u,t);for(const h in u)u.hasOwnProperty(h)&&this._setAttr(t+s(h),u[h]);return u||n.forEach(h=>{this._setAttr(t+s(h),void 0)}),this._fireChangeEvent(t,d,u),o&&o.call(this),this},de.addOverloadedGetterSetter(e,t)},addOverloadedGetterSetter(e,t){const n=xe._capitalize(t),r=Cf+n,o=wf+n;e.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[o]()}},addDeprecatedGetterSetter(e,t,n,r){xe.error("Adding deprecated "+t);const o=wf+xe._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";e.prototype[o]=function(){xe.error(i);const s=this.attrs[t];return s===void 0?n:s},de.addSetter(e,t,r,function(){xe.error(i)}),de.addOverloadedGetterSetter(e,t)},backCompat(e,t){xe.each(t,function(n,r){const o=e.prototype[r],i=wf+xe._capitalize(n),s=Cf+xe._capitalize(n);function a(){o.apply(this,arguments),xe.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 XD(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=St.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=St.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=St.Filters;l&&l.Contrast&&l.Contrast.call(this,s)}}case"grayscale":return function(i){const s=St.Filters;s&&s.Grayscale&&s.Grayscale.call(this,i)};case"sepia":return function(i){const s=St.Filters;s&&s.Sepia&&s.Sepia.call(this,i)};case"invert":return function(i){const s=St.Filters;s&&s.Invert&&s.Invert.call(this,i)};default:xe.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}var qp="absoluteOpacity",k_="allEventListeners",pa="absoluteTransform",S_="absoluteScale",Wl="canvas",ZD="Change",QD="children",JD="konva",A0="listening",eO="mouseenter",tO="mouseleave",nO="pointerenter",rO="pointerleave",oO="touchenter",iO="touchleave",__="set",A_="Shape",Yp=" ",I_="stage",il="transform",sO="Stage",I0="visible",aO=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Yp),lO=1,_t=class oh{constructor(t){this._id=lO++,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===il||t===pa)&&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===il||t===pa)&&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(Yp);this.on(o,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(Wl)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===pa&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(Wl)){const{scene:t,filter:n,hit:r}=this._cache.get(Wl);xe.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(Wl)}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,c=n.offset||0,u=n.drawBorder||!1,d=n.hitCanvasPixelRatio||1;if(!o||!i){xe.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+=c*2+h,i+=c*2+g,a-=c,l-=c;const p=new rl({pixelRatio:s,width:o,height:i}),v=new rl({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),S=new S0({pixelRatio:d,width:o,height:i}),C=p.getContext(),A=S.getContext(),y=new rl({width:p.width/p.pixelRatio+Math.abs(a),height:p.height/p.pixelRatio+Math.abs(l),pixelRatio:p.pixelRatio}),w=y.getContext();return S.isCache=!0,p.isCache=!0,this._cache.delete(Wl),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(p.getContext()._context.imageSmoothingEnabled=!1,v.getContext()._context.imageSmoothingEnabled=!1),C.save(),A.save(),w.save(),C.translate(-a,-l),A.translate(-a,-l),w.translate(-a,-l),y.x=a,y.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(qp),this._clearSelfAndDescendantCache(S_),this.drawScene(p,this,y),this.drawHit(S,this),this._isUnderCache=!1,C.restore(),A.restore(),u&&(C.save(),C.beginPath(),C.rect(0,0,o,i),C.closePath(),C.setAttr("strokeStyle","red"),C.setAttr("lineWidth",5),C.stroke(),C.restore()),xe.releaseCanvas(y._canvas),this._cache.set(Wl,{scene:p,filter:v,hit:S,x:a,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(Wl)}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(c){const u=l.point(c);o===void 0&&(o=s=u.x,i=a=u.y),o=Math.min(o,u.x),i=Math.min(i,u.y),s=Math.max(s,u.x),a=Math.max(a,u.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,c;if(!t||t.length===0)return r;if(this._filterUpToDate)return o;let u=!0;for(let h=0;h<t.length;h++)if(typeof t[h]=="string"&&b_(),typeof t[h]!="string"||!b_()){u=!1;break}const d=r.pixelRatio;if(o.setSize(r.width/r.pixelRatio,r.height/r.pixelRatio),u){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++)c=t[l],typeof c=="string"&&(c=XD(c)),c.call(this,a),i.putImageData(a,0,0)}catch(h){xe.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(k_),t.length===3)return this._delegate.apply(this,t);const o=n.split(Yp);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(Yp),o=r.length,i,s,a,l,c,u;if(this._cache&&this._cache.delete(k_),!t)for(s in this.eventListeners)this._off(s);for(i=0;i<o;i++)if(a=r[i],l=a.split("."),c=l[0],u=l[1],c)this.eventListeners[c]&&this._off(c,u,n);else for(s in this.eventListeners)this._off(s,u,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=xe.cloneObject(i),i.currentTarget=s[a],r.call(s[a],i)}),this}remove(){return this.isDragging()&&this.stopDrag(),Vn._dragElements.delete(this._id),Vn._dragElements.forEach((t,n)=>{this.isAncestorOf(t.node)&&Vn._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(pa),this._clearSelfAndDescendantCache(qp),this._clearSelfAndDescendantCache(S_),this._clearSelfAndDescendantCache(I_),this._clearSelfAndDescendantCache(I0),this._clearSelfAndDescendantCache(A0)}_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"+xe._capitalize(t);return xe._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!==QD&&(r=__+xe._capitalize(n),xe._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(A0,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(I0,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;Vn._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===r)&&(o=!0)});const i=!n&&!St.hitOnDragEnabled&&(o||St.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(u){for(o=[],i=u.length,s=0;s<i;s++)a=u[s],r++,a.nodeType!==A_&&(o=o.concat(a.getChildren().slice())),a._id===n._id&&(s=i);o.length>0&&o[0].getDepth()<=t&&l(o)}const c=this.getStage();return n.nodeType!==sO&&c&&l(c.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(il),this._clearSelfAndDescendantCache(pa)),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 Ki,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(il);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(il),this._clearSelfAndDescendantCache(pa),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 xe.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 xe.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 xe.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 xe.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 xe.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&xe.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(qp,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=xe.isObject(r)&&!xe._isPlainObject(r)&&!xe._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 xe._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],xe.isValidSelector(i)||(xe.warn('Selector "'+i+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),xe.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),xe.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(I_,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(pa,this._getAbsoluteTransform)}_getAbsoluteTransform(t){let n;if(t)return n=new Ki,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(pa)||new Ki,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(il,this._getTransform)}_getTransform(){var t,n;const r=this._cache.get(il)||new Ki;r.reset();const o=this.x(),i=this.y(),s=St.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,c=this.attrs.skewX||0,u=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),(c!==0||u!==0)&&r.skew(c,u),(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=xe.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(JD)<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 rl({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(),c=new rl({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,c),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,xe._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():St.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+ZD,{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[__+xe._capitalize(t)];return xe._isFunction(r)?r.call(this,n):this._setAttr(t,n),this}_requestDraw(){if(St.autoDrawEnabled){const t=this.getLayer()||this.getStage();t?.batchDraw()}}_setAttr(t,n){const r=this.attrs[t];r===n&&!xe.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===A_&&(n.target=this);const o=[eO,tO,nO,rO,oO,iO];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=oh.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,oh.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;Vn._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){Vn._dragElements.has(this._id)||this._createDragElement(t);const r=Vn._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:xe.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=Vn._dragElements.get(this._id);n&&(n.dragStatus="stopped"),Vn._endDragBefore(t),Vn._endDragAfter(t)}setDraggable(t){this._setAttr("draggable",t),this._dragChange()}isDragging(){const t=Vn._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||St.dragButtons.indexOf(t.evt.button)>=0)||this.isDragging())return;let n=!1;Vn._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=Vn._dragElements.get(this._id),n=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";n?this.stopDrag():r&&Vn._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 xe.haveIntersection(r,this.getClientRect())}static create(t,n){return xe._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=oh.prototype.getClassName.call(t),o=t.children,i,s,a;n&&(t.attrs.container=n),St[r]||(xe.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const l=St[r];if(i=new l(t.attrs),o)for(s=o.length,a=0;a<s;a++)i.add(oh._createNode(o[a]));return i}};_t.protoListenerMap=new Map,_t.prototype.nodeType="Node",_t.prototype._attrsAffectingSize=[],_t.prototype.eventListeners={},_t.prototype.on(aO,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(il),this._clearSelfAndDescendantCache(pa)}),_t.prototype.on("visibleChange.konva",function(){this._clearSelfAndDescendantCache(I0)}),_t.prototype.on("listeningChange.konva",function(){this._clearSelfAndDescendantCache(A0)}),_t.prototype.on("opacityChange.konva",function(){this._clearSelfAndDescendantCache(qp)});var ar=de.addGetterSetter;ar(_t,"zIndex"),ar(_t,"absolutePosition"),ar(_t,"position"),ar(_t,"x",0,bt()),ar(_t,"y",0,bt()),ar(_t,"globalCompositeOperation","source-over",Gl()),ar(_t,"opacity",1,bt()),ar(_t,"name","",Gl()),ar(_t,"id","",Gl()),ar(_t,"rotation",0,bt()),de.addComponentsGetterSetter(_t,"scale",["x","y"]),ar(_t,"scaleX",1,bt()),ar(_t,"scaleY",1,bt()),de.addComponentsGetterSetter(_t,"skew",["x","y"]),ar(_t,"skewX",0,bt()),ar(_t,"skewY",0,bt()),de.addComponentsGetterSetter(_t,"offset",["x","y"]),ar(_t,"offsetX",0,bt()),ar(_t,"offsetY",0,bt()),ar(_t,"dragDistance",void 0,bt()),ar(_t,"width",0,bt()),ar(_t,"height",0,bt()),ar(_t,"listening",!0,qi()),ar(_t,"preventDefault",!0,qi()),ar(_t,"filters",void 0,function(e){return this._filterUpToDate=!1,e}),ar(_t,"visible",!0,qi()),ar(_t,"transformsEnabled","all",Gl()),ar(_t,"size"),ar(_t,"dragBoundFunc"),ar(_t,"draggable",!1,qi()),de.backCompat(_t,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});var wi=class extends _t{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=_t.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=_t.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 c=this.getAbsoluteTransform(t).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[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(),c=typeof s=="number"&&typeof a=="number"||l,u=n===this;if(c){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(),S=this.clipY();i.rect(v||0,S||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=!u&&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(),c&&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 c=this;(t=this.children)===null||t===void 0||t.forEach(function(h){if(!h.visible())return;const g=h.getClientRect({relativeTo:c,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 u=this.find("Shape");let d=!1;for(let h=0;h<u.length;h++)if(u[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)}};de.addComponentsGetterSetter(wi,"clip",["x","y","width","height"]),de.addGetterSetter(wi,"clipX",void 0,bt()),de.addGetterSetter(wi,"clipY",void 0,bt()),de.addGetterSetter(wi,"clipWidth",void 0,bt()),de.addGetterSetter(wi,"clipHeight",void 0,bt()),de.addGetterSetter(wi,"clipFunc");var kf=new Map,E_=St._global.PointerEvent!==void 0;function E0(e){return kf.get(e)}function T0(e){return{evt:e,pointerId:e.pointerId}}function T_(e,t){return kf.get(e)===t}function x_(e,t){Sf(e),t.getStage()&&(kf.set(e,t),E_&&t._fire("gotpointercapture",T0(new PointerEvent("gotpointercapture"))))}function Sf(e,t){const n=kf.get(e);if(!n)return;const r=n.getStage();r&&r.content,kf.delete(e),E_&&n._fire("lostpointercapture",T0(new PointerEvent("lostpointercapture")))}var cO="Stage",uO="string",R_="px",dO="mouseout",M_="mouseleave",L_="mouseover",P_="mouseenter",D_="mousemove",O_="mousedown",F_="mouseup",_f="pointermove",Af="pointerdown",du="pointerup",If="pointercancel",fO="lostpointercapture",Xp="pointerout",Ef="pointerleave",Zp="pointerover",Qp="pointerenter",x0="contextmenu",N_="touchstart",B_="touchend",z_="touchmove",V_="touchcancel",R0="wheel",hO=5,pO=[[P_,"_pointerenter"],[O_,"_pointerdown"],[D_,"_pointermove"],[F_,"_pointerup"],[M_,"_pointerleave"],[N_,"_pointerdown"],[z_,"_pointermove"],[B_,"_pointerup"],[V_,"_pointercancel"],[L_,"_pointerover"],[R0,"_wheel"],[x0,"_contextmenu"],[Af,"_pointerdown"],[_f,"_pointermove"],[du,"_pointerup"],[If,"_pointercancel"],[Ef,"_pointerleave"],[fO,"_lostpointercapture"]],M0={mouse:{[Xp]:dO,[Ef]:M_,[Zp]:L_,[Qp]:P_,[_f]:D_,[Af]:O_,[du]:F_,[If]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Xp]:"touchout",[Ef]:"touchleave",[Zp]:"touchover",[Qp]:"touchenter",[_f]:z_,[Af]:N_,[du]:B_,[If]:V_,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Xp]:Xp,[Ef]:Ef,[Zp]:Zp,[Qp]:Qp,[_f]:_f,[Af]:Af,[du]:du,[If]:If,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Tf=e=>e.indexOf("pointer")>=0?"pointer":e.indexOf("touch")>=0?"touch":"mouse",fu=e=>{const t=Tf(e);if(t==="pointer")return St.pointerEventsEnabled&&M0.pointer;if(t==="touch")return M0.touch;if(t==="mouse")return M0.mouse};function j_(e={}){return(e.clipFunc||e.clipWidth||e.clipHeight)&&xe.warn("Stage does not support clipping. Please use clip for Layers or Groups."),e}var mO="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);",xf=[],Jp=class extends wi{constructor(e){super(j_(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),xf.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||xe.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===uO){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"),wi.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&xe._isInDocument(e)&&this.container().removeChild(e);const t=xf.indexOf(this);return t>-1&&xf.splice(t,1),xe.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}:(xe.warn(mO),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 rl({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+R_,this.content.style.height=t+R_),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>hO&&xe.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(),St.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return T_(e,this)}setPointerCapture(e){x_(e,this)}releaseCapture(e){Sf(e,this)}getLayers(){return this.children}_bindContentEvents(){St.isBrowser&&pO.forEach(([e,t])=>{this.content.addEventListener(e,n=>{this[t](n)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=fu(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=fu(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=fu(e.type),n=Tf(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(n),o=!(St.isDragging()||St.isTransforming())||St.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=fu(e.type),n=Tf(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(o=>{const i=this.getIntersection(o);if(Vn.justDragged=!1,St["_"+n+"ListenClick"]=!0,!i||!i.isListening()){this[n+"ClickStartShape"]=void 0;return}St.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=fu(e.type),n=Tf(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(St.isDragging()&&Vn.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(St.isDragging()||St.isTransforming())||St.hitOnDragEnabled))return;const o={};let i=!1;const s=this._getTargetShape(n);this._changedPointerPositions.forEach(a=>{const l=E0(a.id)||this.getIntersection(a),c=a.id,u={evt:e,pointerId:c},d=s!==l;if(d&&s&&(s._fireAndBubble(t.pointerout,{...u},l),s._fireAndBubble(t.pointerleave,{...u},l)),l){if(o[l._id])return;o[l._id]=!0}l&&l.isListening()?(i=!0,d&&(l._fireAndBubble(t.pointerover,{...u},s),l._fireAndBubble(t.pointerenter,{...u},s),this[n+"targetShape"]=l),l._fireAndBubble(t.pointermove,{...u})):s&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:c}),this[n+"targetShape"]=null)}),i||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=fu(e.type),n=Tf(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=E0(a.id)||this.getIntersection(a);if(l){if(l.releaseCapture(a.id),i[l._id])return;i[l._id]=!0}const c=a.id,u={evt:e,pointerId:c};let d=!1;St["_"+n+"InDblClickWindow"]?(d=!0,clearTimeout(this[n+"DblTimeout"])):Vn.justDragged||(St["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"])),this[n+"DblTimeout"]=setTimeout(function(){St["_"+n+"InDblClickWindow"]=!1},St.dblClickWindow),l&&l.isListening()?(s=!0,this[n+"ClickEndShape"]=l,l._fireAndBubble(t.pointerup,{...u}),St["_"+n+"ListenClick"]&&r&&r===l&&(l._fireAndBubble(t.pointerclick,{...u}),d&&o&&o===l&&l._fireAndBubble(t.pointerdblclick,{...u}))):(this[n+"ClickEndShape"]=null,s||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),s=!0),St["_"+n+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:c}),d&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:c}))}),s||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),St["_"+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(x0,{evt:e}):this._fire(x0,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(R0,{evt:e}):this._fire(R0,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=E0(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(du,T0(e)),Sf(e.pointerId)}_lostpointercapture(e){Sf(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:xe._getFirstPointerId(e)}],this._changedPointerPositions=[{x:n,y:r,id:xe._getFirstPointerId(e)}])}_setPointerPosition(e){xe.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 rl({width:this.width(),height:this.height()}),this.bufferHitCanvas=new S0({pixelRatio:1,width:this.width(),height:this.height()}),!St.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 xe.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}};Jp.prototype.nodeType=cO,Er(Jp),de.addGetterSetter(Jp,"container"),St.isBrowser&&document.addEventListener("visibilitychange",()=>{xf.forEach(e=>{e.batchDraw()})});var U_="hasShadow",H_="shadowRGBA",$_="patternImage",G_="linearGradient",W_="radialGradient",em;function L0(){return em||(em=xe.createCanvasElement().getContext("2d"),em)}var Rf={};function gO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function vO(e){e.stroke()}function yO(e){const t=this.attrs.fillRule;t?e.fill(t):e.fill()}function bO(e){e.stroke()}function wO(){this._clearCache(U_)}function CO(){this._clearCache(H_)}function kO(){this._clearCache($_)}function SO(){this._clearCache(G_)}function _O(){this._clearCache(W_)}var gt=class extends _t{constructor(e){super(e);let t,n=0;for(;t=xe.getHitColor(),!(t&&!(t in Rf));)if(n++,n>=1e4){xe.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=xe.getRandomColor();break}this.colorKey=t,Rf[t]=this}getContext(){return xe.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return xe.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(U_,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache($_,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const e=L0().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(e&&e.setTransform){const t=new Ki;t.translate(this.fillPatternX(),this.fillPatternY()),t.rotate(St.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(G_,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=L0(),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(W_,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=L0(),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(H_,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=xe.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 _t.prototype.destroy.call(this),delete Rf[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){xe.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,c=!e.skipShadow&&this.hasShadow(),u=c?this.shadowOffsetX():0,d=c?this.shadowOffsetY():0,h=a+Math.abs(u),g=l+Math.abs(d),p=c&&this.shadowBlur()||0,v={width:h+p*2,height:g+p*2,x:-(s/2+p)+Math.min(u,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 c=t===this;if(!this.isVisible()&&!c)return this;if(i){o.save();const u=this.getAbsoluteTransform(t).getMatrix();return o.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(o),o.restore(),this}if(!s)return this;if(o.save(),this._useBufferCanvas()){l=this.getStage();const u=n||l.bufferCanvas,d=u.getContext();n?(d.save(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,u.width,u.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=u.pixelRatio;a&&o._applyShadow(this),c||(o._applyOpacity(this),o._applyGlobalCompositeOperation(this)),o.drawImage(u._canvas,u.x||0,u.y||0,u.width/g,u.height/g)}else{if(o._applyLineJoin(this),o._applyMiterLimit(this),!c){const u=this.getAbsoluteTransform(t).getMatrix();o.transform(u[0],u[1],u[2],u[3],u[4],u[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||xe.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 c=this.getAbsoluteTransform(t).getMatrix();return i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore(),this}if(!s)return this;if(i.save(),i._applyLineJoin(this),i._applyMiterLimit(this),this!==t){const c=this.getAbsoluteTransform(t).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[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,c=l.length,u=xe._hexToRgb(this.colorKey);for(let d=0;d<c;d+=4)l[d+3]>e?(l[d]=u.r,l[d+1]=u.g,l[d+2]=u.b,l[d+3]=255):l[d+3]=0;o.putImageData(a,0,0)}catch(a){xe.error("Unable to draw hit graph from cached scene canvas. "+a.message)}return this}hasPointerCapture(e){return T_(e,this)}setPointerCapture(e){x_(e,this)}releaseCapture(e){Sf(e,this)}};gt.prototype._fillFunc=gO,gt.prototype._strokeFunc=vO,gt.prototype._fillFuncHit=yO,gt.prototype._strokeFuncHit=bO,gt.prototype._centroid=!1,gt.prototype.nodeType="Shape",Er(gt),gt.prototype.eventListeners={},gt.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",wO),gt.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",CO),gt.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",kO),gt.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",SO),gt.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",_O),de.addGetterSetter(gt,"stroke",void 0,C_()),de.addGetterSetter(gt,"strokeWidth",2,bt()),de.addGetterSetter(gt,"fillAfterStrokeEnabled",!1),de.addGetterSetter(gt,"hitStrokeWidth","auto",_0()),de.addGetterSetter(gt,"strokeHitEnabled",!0,qi()),de.addGetterSetter(gt,"perfectDrawEnabled",!0,qi()),de.addGetterSetter(gt,"shadowForStrokeEnabled",!0,qi()),de.addGetterSetter(gt,"lineJoin"),de.addGetterSetter(gt,"lineCap"),de.addGetterSetter(gt,"miterLimit"),de.addGetterSetter(gt,"sceneFunc"),de.addGetterSetter(gt,"hitFunc"),de.addGetterSetter(gt,"dash"),de.addGetterSetter(gt,"dashOffset",0,bt()),de.addGetterSetter(gt,"shadowColor",void 0,Gl()),de.addGetterSetter(gt,"shadowBlur",0,bt()),de.addGetterSetter(gt,"shadowOpacity",1,bt()),de.addComponentsGetterSetter(gt,"shadowOffset",["x","y"]),de.addGetterSetter(gt,"shadowOffsetX",0,bt()),de.addGetterSetter(gt,"shadowOffsetY",0,bt()),de.addGetterSetter(gt,"fillPatternImage"),de.addGetterSetter(gt,"fill",void 0,C_()),de.addGetterSetter(gt,"fillPatternX",0,bt()),de.addGetterSetter(gt,"fillPatternY",0,bt()),de.addGetterSetter(gt,"fillLinearGradientColorStops"),de.addGetterSetter(gt,"strokeLinearGradientColorStops"),de.addGetterSetter(gt,"fillRadialGradientStartRadius",0),de.addGetterSetter(gt,"fillRadialGradientEndRadius",0),de.addGetterSetter(gt,"fillRadialGradientColorStops"),de.addGetterSetter(gt,"fillPatternRepeat","repeat"),de.addGetterSetter(gt,"fillEnabled",!0),de.addGetterSetter(gt,"strokeEnabled",!0),de.addGetterSetter(gt,"shadowEnabled",!0),de.addGetterSetter(gt,"dashEnabled",!0),de.addGetterSetter(gt,"strokeScaleEnabled",!0),de.addGetterSetter(gt,"fillPriority","color"),de.addComponentsGetterSetter(gt,"fillPatternOffset",["x","y"]),de.addGetterSetter(gt,"fillPatternOffsetX",0,bt()),de.addGetterSetter(gt,"fillPatternOffsetY",0,bt()),de.addComponentsGetterSetter(gt,"fillPatternScale",["x","y"]),de.addGetterSetter(gt,"fillPatternScaleX",1,bt()),de.addGetterSetter(gt,"fillPatternScaleY",1,bt()),de.addComponentsGetterSetter(gt,"fillLinearGradientStartPoint",["x","y"]),de.addComponentsGetterSetter(gt,"strokeLinearGradientStartPoint",["x","y"]),de.addGetterSetter(gt,"fillLinearGradientStartPointX",0),de.addGetterSetter(gt,"strokeLinearGradientStartPointX",0),de.addGetterSetter(gt,"fillLinearGradientStartPointY",0),de.addGetterSetter(gt,"strokeLinearGradientStartPointY",0),de.addComponentsGetterSetter(gt,"fillLinearGradientEndPoint",["x","y"]),de.addComponentsGetterSetter(gt,"strokeLinearGradientEndPoint",["x","y"]),de.addGetterSetter(gt,"fillLinearGradientEndPointX",0),de.addGetterSetter(gt,"strokeLinearGradientEndPointX",0),de.addGetterSetter(gt,"fillLinearGradientEndPointY",0),de.addGetterSetter(gt,"strokeLinearGradientEndPointY",0),de.addComponentsGetterSetter(gt,"fillRadialGradientStartPoint",["x","y"]),de.addGetterSetter(gt,"fillRadialGradientStartPointX",0),de.addGetterSetter(gt,"fillRadialGradientStartPointY",0),de.addComponentsGetterSetter(gt,"fillRadialGradientEndPoint",["x","y"]),de.addGetterSetter(gt,"fillRadialGradientEndPointX",0),de.addGetterSetter(gt,"fillRadialGradientEndPointY",0),de.addGetterSetter(gt,"fillPatternRotation",0),de.addGetterSetter(gt,"fillRule",void 0,Gl()),de.backCompat(gt,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var AO="beforeDraw",IO="draw",K_=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],EO=K_.length,Kl=class extends wi{constructor(e){super(e),this.canvas=new rl,this.hitCanvas=new S0({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(){_t.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(!_t.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(_t.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(_t.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 _t.prototype.remove.call(this),e&&e.parentNode&&xe._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"&&xe.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(),_t.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(){xe.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){xe.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,xe.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<EO;r++){const o=K_[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=Rf[xe.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(AO,{node:this}),this.clearBeforeDraw()&&o.getContext().clear(),wi.prototype.drawScene.call(this,o,t,n),this._fire(IO,{node:this}),this}drawHit(e,t){const n=this.getLayer(),r=e||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),wi.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){xe.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return xe.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 xe.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};Kl.prototype.nodeType="Layer",Er(Kl),de.addGetterSetter(Kl,"imageSmoothingEnabled",!0),de.addGetterSetter(Kl,"clearBeforeDraw",!0),de.addGetterSetter(Kl,"hitGraphEnabled",!0,qi());var P0=class extends Kl{constructor(e){super(e),this.listening(!1),xe.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}};P0.prototype.nodeType="FastLayer",Er(P0);var hu=class extends wi{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&xe.throw("You may only add groups and shapes to groups.")}};hu.prototype.nodeType="Group",Er(hu);var D0=(function(){return $l.performance&&$l.performance.now?function(){return $l.performance.now()}:function(){return new Date().getTime()}})(),pu=class od{constructor(t,n){this.id=od.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:D0(),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=od.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=D0(),od._addAnimation(this),this}stop(){return od._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(D0());const a=i.length;let l;if(s?l=s.call(o,o.frame)!==!1:l=!0,!!l)for(let c=0;c<a;c++){const u=i[c];u._id!==void 0&&(t[u._id]=u)}}for(const r in t)t.hasOwnProperty(r)&&t[r].batchDraw()}static _animationLoop(){const t=od;t.animations.length?(t._runFrames(),xe.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,xe.requestAnimFrame(this._animationLoop))}};pu.animations=[],pu.animIdCounter=0,pu.animRunning=!1;var TO={node:1,duration:1,easing:1,onFinish:1,yoyo:1},xO=1,q_=2,Y_=3,X_=["fill","stroke","shadowColor"],RO=0,MO=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=q_,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Y_,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===q_?this.setTime(e):this.state===Y_&&this.setTime(this.duration-e)}pause(){this.state=xO,this.fire("onPause")}getTimer(){return new Date().getTime()}},tm=class Vr{constructor(t){const n=this,r=t.node,o=r._id,i=t.easing||Mf.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=RO++;const c=r.getLayer()||(r instanceof St.Stage?r.getLayers():null);c||xe.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new pu(function(){n.tween.onEnterFrame()},c),this.tween=new MO(l,function(u){n._tweenFunc(u)},i,0,1,a*1e3,s),this._addListeners(),Vr.attrs[o]||(Vr.attrs[o]={}),Vr.attrs[o][this._id]||(Vr.attrs[o][this._id]={}),Vr.tweens[o]||(Vr.tweens[o]={});for(l in t)TO[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,c;const u=Vr.tweens[o][t];u&&delete Vr.attrs[o][u][t];let d=r.getAttr(t);if(xe._isArray(n))if(i=[],s=Math.max(n.length,d.length),t==="points"&&n.length!==d.length&&(n.length>d.length?(l=d,d=xe._prepareArrayForTween(d,n,r.closed())):(a=n,n=xe._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=xe.colorToRGBA(d[h]);c=xe.colorToRGBA(n[h]),d[h]=g,i.push({r:c.r-g.r,g:c.g-g.g,b:c.b-g.b,a:c.a-g.a})}else for(let h=0;h<s;h++)i.push(n[h]-d[h]);else X_.indexOf(t)!==-1?(d=xe.colorToRGBA(d),c=xe.colorToRGBA(n),i={r:c.r-d.r,g:c.g-d.g,b:c.b-d.b,a:c.a-d.a}):i=n-d;Vr.attrs[o][this._id][t]={start:d,diff:i,end:n,trueEnd:a,trueStart:l},Vr.tweens[o][t]=this._id}_tweenFunc(t){const n=this.node,r=Vr.attrs[n._id][this._id];let o,i,s,a,l,c,u,d;for(o in r){if(i=r[o],s=i.start,a=i.diff,d=i.end,xe._isArray(s))if(l=[],u=Math.max(s.length,d.length),o.indexOf("fill")===0)for(c=0;c<u;c++)c%2===0?l.push((s[c]||0)+a[c]*t):l.push("rgba("+Math.round(s[c].r+a[c].r*t)+","+Math.round(s[c].g+a[c].g*t)+","+Math.round(s[c].b+a[c].b*t)+","+(s[c].a+a[c].a*t)+")");else for(c=0;c<u;c++)l.push((s[c]||0)+a[c]*t);else X_.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=Vr.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=Vr.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=Vr.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const o in r)delete Vr.tweens[t][o];delete Vr.attrs[t][n],Vr.tweens[t]&&(Object.keys(Vr.tweens[t]).length===0&&delete Vr.tweens[t],Object.keys(Vr.attrs[t]).length===0&&delete Vr.attrs[t])}};tm.attrs={},tm.tweens={},_t.prototype.to=function(e){const t=e.onFinish;e.node=this,e.onFinish=function(){this.destroy(),t&&t()},new tm(e).play()};var Mf={BackEaseIn(e,t,n,r){return n*(e/=r)*e*(2.70158*e-1.70158)+t},BackEaseOut(e,t,n,r){return n*((e=e/r-1)*e*(2.70158*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-Mf.BounceEaseOut(r-e,0,n,r)+t},BounceEaseInOut(e,t,n,r){return e<r/2?Mf.BounceEaseIn(e*2,0,n,r)*.5+t:Mf.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}},Z_=xe._assign(St,{Util:xe,Transform:Ki,Node:_t,Container:wi,Stage:Jp,stages:xf,Layer:Kl,FastLayer:P0,Group:hu,DD:Vn,Shape:gt,shapes:Rf,Animation:pu,Tween:tm,Easings:Mf,Context:Gp,Canvas:k0}),ma=class extends gt{_sceneFunc(e){const t=St.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=St.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),c=i*t,u=s*(s>0?e:t),d=a*(a>0?t:e);return{x:l,y:n?-1*d:u,width:c-l,height:d-u}}};ma.prototype._centroid=!0,ma.prototype.className="Arc",ma.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"],Er(ma),de.addGetterSetter(ma,"innerRadius",0,bt()),de.addGetterSetter(ma,"outerRadius",0,bt()),de.addGetterSetter(ma,"angle",0,bt()),de.addGetterSetter(ma,"clockwise",!1,qi());function O0(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)),c=s*a/(a+l),u=s*l/(a+l);return[n-c*(o-e),r-c*(i-t),n+u*(o-e),r+u*(i-t)]}function Q_(e,t){const n=e.length,r=[];for(let o=2;o<n-2;o+=2){const i=O0(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 LO(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 ga=class extends gt{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():Q_(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,n=this.tension(),r=O0(e[t-2],e[t-1],e[0],e[1],e[2],e[3],n),o=O0(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],n),i=Q_(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],...LO(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}}};ga.prototype.className="Line",ga.prototype._attrsAffectingSize=["points","bezier","tension"],Er(ga),de.addGetterSetter(ga,"closed",!1),de.addGetterSetter(ga,"bezier",!1),de.addGetterSetter(ga,"tension",0,bt()),de.addGetterSetter(ga,"points",[],qD());var PO=[[],[],[-.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]],DO=[[],[],[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]],OO=[[1],[1,1],[1,2,1],[1,3,3,1]],J_=(e,t,n)=>{let r,o;const s=n/2;r=0;for(let a=0;a<20;a++)o=s*PO[20][a]+s,r+=DO[20][a]*FO(e,t,o);return s*r},e4=(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),c=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 u=l/(2*a),d=c/a,h=n+u,g=d-u*u,p=h*h+g>0?Math.sqrt(h*h+g):0,v=u*u+g>0?Math.sqrt(u*u+g):0,S=u+Math.sqrt(u*u+g)!==0?g*Math.log(Math.abs((h+p)/(u+v))):0;return Math.sqrt(a)/2*(h*p-u*v+S)};function FO(e,t,n){const r=F0(1,n,e),o=F0(1,n,t),i=r*r+o*o;return Math.sqrt(i)}var F0=(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+=OO[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 F0(e-1,t,o)}},t4=(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 c=n(o-i),u=Math.abs(e-c)/t;u<r?(r=u,o-=i):i/=2}if(s++,s>500)break}return o},Li=class pi extends gt{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=pi.parsePathData(this.data()),this.pathLength=pi.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],c=s[2],u=s[3],d=s[4],h=s[5],g=s[6],p=s[7],v=c>u?c:u,S=c>u?1:c/u,C=c>u?u/c:1;t.translate(a,l),t.rotate(g),t.scale(S,C),t.arc(0,0,v,d,d+h,1-p),t.scale(1/S,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 c=l.points[4],u=l.points[5],d=l.points[4]+u;let h=Math.PI/180;if(Math.abs(c-d)<h&&(h=Math.abs(c-d)),u<0)for(let g=c-h;g>d;g-=h){const p=pi.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=c+h;g<d;g+=h){const p=pi.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 c=0;c<=1;c+=.01){const u=pi.getPointOnCubicBezier(c,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(u.x,u.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 pi.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 pi.getPointOnLine(t,s.start.x,s.start.y,a[0],a[1]);case"C":return pi.getPointOnCubicBezier(t4(t,pi.getPathLength(n),v=>J_([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 pi.getPointOnQuadraticBezier(t4(t,pi.getPathLength(n),v=>e4([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],c=a[1],u=a[2],d=a[3],h=a[5],g=a[6];let p=a[4];return p+=h*t/s.pathLength,pi.getPointOnEllipticalArc(l,c,u,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 c=(i-r)/(o-n),u=Math.sqrt(t*t/(1+c*c))*(o<n?-1:1),d=c*u;if(Math.abs(a-r-c*(s-n))<1e-10)return{x:s+u,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),S=Math.sqrt(t*t-v*v),C=Math.sqrt(S*S/(1+c*c))*(o<n?-1:1),A=c*C;return{x:g+C,y:p+A}}static getPointOnCubicBezier(t,n,r,o,i,s,a,l,c){function u(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*u(t)+s*d(t)+o*h(t)+n*g(t),y:c*u(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 c(d){return 2*d*(1-d)}function u(d){return(1-d)*(1-d)}return{x:s*l(t)+o*c(t)+n*u(t),y:a*l(t)+i*c(t)+r*u(t)}}static getPointOnEllipticalArc(t,n,r,o,i,s){const a=Math.cos(s),l=Math.sin(s),c={x:r*Math.cos(i),y:o*Math.sin(i)};return{x:t+(c.x*a-c.y*l),y:n+(c.x*l+c.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 c=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let u;for(let d=1;d<o.length;d++){let h=o[d],g=h.charAt(0);for(h=h.slice(1),s.length=0;u=c.exec(h);)s.push(u[0]);let p=[],v=g==="A"||g==="a"?0:-1;for(let S=0,C=s.length;S<C;S++){const A=s[S];if(A==="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(A)){p.push(parseInt(A[0],10)),p.push(parseInt(A[1],10)),p.push(parseFloat(A.slice(2))),v+=3,v>=7&&(v-=7);continue}if(A==="11"||A==="10"||A==="01"){p.push(parseInt(A[0],10)),p.push(parseInt(A[1],10)),v+=2,v>=7&&(v-=7);continue}if(A==="0"||A==="1"){p.push(parseInt(A,10)),v+=1,v>=7&&(v-=7);continue}}else if(v===4){if(/^[01]\d+(?:\.\d+)?$/.test(A)){p.push(parseInt(A[0],10)),p.push(parseFloat(A.slice(1))),v+=2,v>=7&&(v-=7);continue}if(A==="0"||A==="1"){p.push(parseInt(A,10)),v+=1,v>=7&&(v-=7);continue}}const y=parseFloat(A);isNaN(y)?p.push(0):p.push(y),v+=1,v>=7&&(v-=7)}else{const y=parseFloat(A);isNaN(y)?p.push(0):p.push(y)}}for(;p.length>0&&!isNaN(p[0]);){let S="",C=[];const A=a,y=l;let w,x,L,V,G,R,F,Z,O,N;switch(g){case"l":a+=p.shift(),l+=p.shift(),S="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(),B=p.shift();if(a+=T,l+=B,S="M",i.length>2&&i[i.length-1].command==="z"){for(let Q=i.length-2;Q>=0;Q--)if(i[Q].command==="M"){a=i[Q].points[0]+T,l=i[Q].points[1]+B;break}}C.push(a,l),g="l";break;case"M":a=p.shift(),l=p.shift(),S="M",C.push(a,l),g="L";break;case"h":a+=p.shift(),S="L",C.push(a,l);break;case"H":a=p.shift(),S="L",C.push(a,l);break;case"v":l+=p.shift(),S="L",C.push(a,l);break;case"V":l=p.shift(),S="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(),S="C",C.push(a,l);break;case"S":x=a,L=l,w=i[i.length-1],w.command==="C"&&(x=a+(a-w.points[2]),L=l+(l-w.points[3])),C.push(x,L,p.shift(),p.shift()),a=p.shift(),l=p.shift(),S="C",C.push(a,l);break;case"s":x=a,L=l,w=i[i.length-1],w.command==="C"&&(x=a+(a-w.points[2]),L=l+(l-w.points[3])),C.push(x,L,a+p.shift(),l+p.shift()),a+=p.shift(),l+=p.shift(),S="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(),S="Q",C.push(a,l);break;case"T":x=a,L=l,w=i[i.length-1],w.command==="Q"&&(x=a+(a-w.points[0]),L=l+(l-w.points[1])),a=p.shift(),l=p.shift(),S="Q",C.push(x,L,a,l);break;case"t":x=a,L=l,w=i[i.length-1],w.command==="Q"&&(x=a+(a-w.points[0]),L=l+(l-w.points[1])),a+=p.shift(),l+=p.shift(),S="Q",C.push(x,L,a,l);break;case"A":V=p.shift(),G=p.shift(),R=p.shift(),F=p.shift(),Z=p.shift(),O=a,N=l,a=p.shift(),l=p.shift(),S="A",C=this.convertEndpointToCenterParameterization(O,N,a,l,F,Z,V,G,R);break;case"a":V=p.shift(),G=p.shift(),R=p.shift(),F=p.shift(),Z=p.shift(),O=a,N=l,a+=p.shift(),l+=p.shift(),S="A",C=this.convertEndpointToCenterParameterization(O,N,a,l,F,Z,V,G,R);break}i.push({command:S||g,points:C,start:{x:A,y},pathLength:this.calcLength(A,y,S||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 c=pi;switch(r){case"L":return c.getLineLength(t,n,o[0],o[1]);case"C":return J_([t,o[0],o[2],o[4]],[n,o[1],o[3],o[5]],1);case"Q":return e4([t,o[0],o[2]],[n,o[1],o[3]],1);case"A":i=0;const u=o[4],d=o[5],h=o[4]+d;let g=Math.PI/180;if(Math.abs(u-h)<g&&(g=Math.abs(u-h)),s=c.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],u,0),d<0)for(l=u-g;l>h;l-=g)a=c.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],l,0),i+=c.getLineLength(s.x,s.y,a.x,a.y),s=a;else for(l=u+g;l<h;l+=g)a=c.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],l,0),i+=c.getLineLength(s.x,s.y,a.x,a.y),s=a;return a=c.getPointOnEllipticalArc(o[0],o[1],o[2],o[3],h,0),i+=c.getLineLength(s.x,s.y,a.x,a.y),i}return 0}static convertEndpointToCenterParameterization(t,n,r,o,i,s,a,l,c){const u=c*(Math.PI/180),d=Math.cos(u)*(t-r)/2+Math.sin(u)*(n-o)/2,h=-1*Math.sin(u)*(t-r)/2+Math.cos(u)*(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,S=p*-l*d/a,C=(t+r)/2+Math.cos(u)*v-Math.sin(u)*S,A=(n+o)/2+Math.sin(u)*v+Math.cos(u)*S,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))},L=x([1,0],[(d-v)/a,(h-S)/l]),V=[(d-v)/a,(h-S)/l],G=[(-1*d-v)/a,(-1*h-S)/l];let R=x(V,G);return w(V,G)<=-1&&(R=Math.PI),w(V,G)>=1&&(R=0),s===0&&R>0&&(R=R-2*Math.PI),s===1&&R<0&&(R=R+2*Math.PI),[C,A,a,l,L,R,u,s]}};Li.prototype.className="Path",Li.prototype._attrsAffectingSize=["data"],Er(Li),de.addGetterSetter(Li,"data");var ql=class extends ga{_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=Li.calcLength(r[r.length-4],r[r.length-3],"C",d),g=Li.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 c=(Math.atan2(l,a)+t)%t,u=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(n[s-2],n[s-1]),e.rotate(c),e.moveTo(0,0),e.lineTo(-i,u/2),e.lineTo(-i,-u/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,u/2),e.lineTo(-i,-u/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}}};ql.prototype.className="Arrow",Er(ql),de.addGetterSetter(ql,"pointerLength",10,bt()),de.addGetterSetter(ql,"pointerWidth",10,bt()),de.addGetterSetter(ql,"pointerAtBeginning",!1),de.addGetterSetter(ql,"pointerAtEnding",!0);var mu=class extends gt{_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)}};mu.prototype._centroid=!0,mu.prototype.className="Circle",mu.prototype._attrsAffectingSize=["radius"],Er(mu),de.addGetterSetter(mu,"radius",0,bt());var sl=class extends gt{_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)}};sl.prototype.className="Ellipse",sl.prototype._centroid=!0,sl.prototype._attrsAffectingSize=["radiusX","radiusY"],Er(sl),de.addComponentsGetterSetter(sl,"radius",["x","y"]),de.addGetterSetter(sl,"radiusX",0,bt()),de.addGetterSetter(sl,"radiusY",0,bt());var Yi=class eI extends gt{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?xe.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?xe.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=xe.createImageElement();o.onload=function(){n(new eI({image:o}))},o.onerror=r,o.crossOrigin="Anonymous",o.src=t}};Yi.prototype.className="Image",Yi.prototype._attrsAffectingSize=["image"],Er(Yi),de.addGetterSetter(Yi,"cornerRadius",0,Kp(4)),de.addGetterSetter(Yi,"image"),de.addComponentsGetterSetter(Yi,"crop",["x","y","width","height"]),de.addGetterSetter(Yi,"cropX",0,bt()),de.addGetterSetter(Yi,"cropY",0,bt()),de.addGetterSetter(Yi,"cropWidth",0,bt()),de.addGetterSetter(Yi,"cropHeight",0,bt());var n4=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],NO="Change.konva",BO="none",N0="up",B0="right",z0="down",V0="left",zO=n4.length,j0=class extends hu{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<zO;n++)e.on(n4[n]+NO,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 N0:s=n/2,a=-1*l;break;case B0:s=n+i,a=r/2;break;case z0:s=n/2,a=r+l;break;case V0: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})}}};j0.prototype.className="Label",Er(j0);var Yl=class extends gt{_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,c=0,u=0;typeof s=="number"?a=l=c=u=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),u=Math.min(s[2]||0,t/2,n/2),c=Math.min(s[3]||0,t/2,n/2)),e.beginPath(),e.moveTo(a,0),r===N0&&(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===B0&&(e.lineTo(t,(n-i)/2),e.lineTo(t+o,n/2),e.lineTo(t,(n+i)/2)),e.lineTo(t,n-u),e.arc(t-u,n-u,u,0,Math.PI/2,!1),r===z0&&(e.lineTo((t+o)/2,n),e.lineTo(t/2,n+i),e.lineTo((t-o)/2,n)),e.lineTo(c,n),e.arc(c,n-c,c,Math.PI/2,Math.PI,!1),r===V0&&(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===N0?(t-=r,s+=r):o===z0?s+=r:o===V0?(e-=n*1.5,i+=n):o===B0&&(i+=n*1.5),{x:e,y:t,width:i,height:s}}};Yl.prototype.className="Tag",Er(Yl),de.addGetterSetter(Yl,"pointerDirection",BO),de.addGetterSetter(Yl,"pointerWidth",0,bt()),de.addGetterSetter(Yl,"pointerHeight",0,bt()),de.addGetterSetter(Yl,"cornerRadius",0,Kp(4));var Lf=class extends gt{_sceneFunc(e){const t=this.cornerRadius(),n=this.width(),r=this.height();e.beginPath(),t?xe.drawRoundedRectPath(e,n,r,t):e.rect(0,0,n,r),e.closePath(),e.fillStrokeShape(this)}};Lf.prototype.className="Rect",Er(Lf),de.addGetterSetter(Lf,"cornerRadius",0,Kp(4));var al=class extends gt{_sceneFunc(e){const t=this._getPoints(),n=this.radius(),r=this.sides(),o=this.cornerRadius();if(e.beginPath(),o)xe.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)}};al.prototype.className="RegularPolygon",al.prototype._centroid=!0,al.prototype._attrsAffectingSize=["radius"],Er(al),de.addGetterSetter(al,"radius",0,bt()),de.addGetterSetter(al,"sides",0,bt()),de.addGetterSetter(al,"cornerRadius",0,Kp(4));var r4=Math.PI*2,Xl=class extends gt{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,r4,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),r4,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)}};Xl.prototype.className="Ring",Xl.prototype._centroid=!0,Xl.prototype._attrsAffectingSize=["innerRadius","outerRadius"],Er(Xl),de.addGetterSetter(Xl,"innerRadius",0,bt()),de.addGetterSetter(Xl,"outerRadius",0,bt());var Cs=class extends gt{constructor(e){super(e),this._updated=!0,this.anim=new pu(()=>{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],c=o[r+3],u=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,l,c),e.closePath(),e.fillStrokeShape(this)),u)if(i){const d=i[t],h=n*2;e.drawImage(u,s,a,l,c,d[h+0],d[h+1],l,c)}else e.drawImage(u,s,a,l,c,0,0,l,c)}_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],c=n*2;e.rect(l[c+0],l[c+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)}};Cs.prototype.className="Sprite",Er(Cs),de.addGetterSetter(Cs,"animation"),de.addGetterSetter(Cs,"animations"),de.addGetterSetter(Cs,"frameOffsets"),de.addGetterSetter(Cs,"image"),de.addGetterSetter(Cs,"frameIndex",0,bt()),de.addGetterSetter(Cs,"frameRate",17,bt()),de.backCompat(Cs,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});var ll=class extends gt{_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)}};ll.prototype.className="Star",ll.prototype._centroid=!0,ll.prototype._attrsAffectingSize=["innerRadius","outerRadius"],Er(ll),de.addGetterSetter(ll,"numPoints",5,bt()),de.addGetterSetter(ll,"innerRadius",0,bt()),de.addGetterSetter(ll,"outerRadius",0,bt());function cl(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 gu="auto",VO="center",o4="inherit",Pf="justify",jO="Change.konva",i4="2d",s4="-",a4="left",UO="text",HO="Text",$O="top",GO="bottom",l4="middle",c4="normal",WO="px ",nm=" ",KO="right",u4="rtl",qO="word",YO="char",d4="none",U0="…",f4=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],XO=f4.length,Df=null;function ZO(){if(Df!==null)return Df;Df=!1;try{const e=document.createElement("canvas");e.width=10,e.height=10;const t=e.getContext(i4);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){Df=!0;break}}}catch{}return Df}function QO(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 rm;function H0(){return rm||(rm=xe.createCanvasElement().getContext(i4),rm)}function JO(e){e.fillText(this._partialText,this._partialTextX,this._partialTextY)}function eF(e){e.setAttr("miterLimit",2),e.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function tF(e){return e=e||{},!e.fillLinearGradientColorStops&&!e.fillRadialGradientColorStops&&!e.fillPatternImage&&(e.fill=e.fill||"black"),e}var hr=class extends gt{constructor(e){super(tF(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<XO;t++)this.on(f4[t]+jO,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(),c=this.direction(),u=0,d=this.align(),h=this.getWidth(),g=this.letterSpacing(),p=this.charRenderFunc(),v=this.fill(),S=this.textDecoration(),C=this.underlineOffset(),A=S.indexOf("underline")!==-1,y=S.indexOf("line-through")!==-1,w;c=c===o4?e.direction:c;let x=a/2,L=l4;if(!St.legacyTextRendering){const V=this.measureSize("M");L="alphabetic",x=(((t=V.fontBoundingBoxAscent)!==null&&t!==void 0?t:V.actualBoundingBoxAscent)-((n=V.fontBoundingBoxDescent)!==null&&n!==void 0?n:V.actualBoundingBoxDescent))/2+a/2}for(c===u4&&e.setAttr("direction",c),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",L),e.setAttr("textAlign",a4),l===l4?u=(this.getHeight()-o*a-i*2)/2:l===GO&&(u=this.getHeight()-o*a-i*2),e.translate(i,u+i),w=0;w<o;w++){let V=0,G=0;const R=r[w],F=R.text,Z=R.width,O=R.lastInParagraph;if(e.save(),d===KO?V+=h-Z-i*2:d===VO&&(V+=(h-Z-i*2)/2),A){e.save(),e.beginPath();const T=C??(St.legacyTextRendering?Math.round(s/2):Math.round(s/4)),B=V,Q=x+G+T;e.moveTo(B,Q);const q=d===Pf&&!O?h-i*2:Z;e.lineTo(B+Math.round(q),Q),e.lineWidth=s/15,e.strokeStyle=this._getLinearGradient()||v,e.stroke(),e.restore()}const N=V;if(c!==u4&&(g!==0||d===Pf||p)){const T=F.split(" ").length-1,B=cl(F);for(let Q=0;Q<B.length;Q++){const q=B[Q];if(q===" "&&!O&&d===Pf&&(V+=(h-i*2-Z)/T),this._partialTextX=V,this._partialTextY=x+G,this._partialText=q,p){e.save();const se=r.slice(0,w).reduce((he,Ne)=>he+cl(Ne.text).length,0);p({char:q,index:Q+se,x:V,y:x+G,lineIndex:w,column:Q,isLastInLine:O,width:this.measureSize(q).width,context:e})}e.fillStrokeShape(this),p&&e.restore(),V+=this.measureSize(q).width+g}}else g!==0&&e.setAttr("letterSpacing",`${g}px`),this._partialTextX=V,this._partialTextY=x+G,this._partialText=F,e.fillStrokeShape(this);if(y){e.save(),e.beginPath();const T=St.legacyTextRendering?0:-Math.round(s/4),B=N;e.moveTo(B,x+G+T);const Q=d===Pf&&!O?h-i*2:Z;e.lineTo(B+Math.round(Q),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=xe._isString(e)?e:e==null?"":e+"";return this._setAttr(UO,t),this}getWidth(){return this.attrs.width===gu||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===gu||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return xe.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,c,u,d;let h=H0(),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:(c=p.fontBoundingBoxDescent)!==null&&c!==void 0?c:21*v,hangingBaseline:(u=p.hangingBaseline)!==null&&u!==void 0?u:72.80000305175781*v,ideographicBaseline:(d=p.ideographicBaseline)!==null&&d!==void 0?d:-21*v,width:p.width,height:g}}_getContextFont(){return this.fontStyle()+nm+this.fontVariant()+nm+(this.fontSize()+WO)+QO(this.fontFamily())}_addTextLine(e){this.align()===Pf&&(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 H0().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!==gu&&o!==void 0,a=i!==gu&&i!==void 0,l=this.padding(),c=o-l*2,u=i-l*2,d=0,h=this.wrap(),g=h!==YO&&h!==d4,p=this.ellipsis();this.textArr=[],H0().font=this._getContextFont();const v=p?this._getTextWidth(U0):0;for(let S=0,C=e.length;S<C;++S){let A=e[S],y=this._getTextWidth(A);if(s&&y>c)for(;A.length>0;){let w=0,x=cl(A).length,L="",V=0;for(;w<x;){const G=w+x>>>1,R=cl(A).slice(0,G+1).join(""),F=this._getTextWidth(R);(p&&a&&d+r>u?F+v:F)<=c?(w=G+1,L=R,V=F):x=G}if(L){if(g){const G=cl(A),R=cl(L),F=G[R.length],Z=F===nm||F===s4;let O;if(Z&&V<=c)O=R.length;else{const N=R.lastIndexOf(nm),T=R.lastIndexOf(s4);O=Math.max(N,T)+1}O>0&&(w=O,L=G.slice(0,w).join(""),V=this._getTextWidth(L))}if(L=L.trimRight(),this._addTextLine(L),n=Math.max(n,V),d+=r,this._shouldHandleEllipsis(d)){this._tryToAddEllipsisToLastLine();break}if(A=cl(A).slice(w).join("").trimLeft(),A.length>0&&(y=this._getTextWidth(A),y<=c)){this._addTextLine(A),d+=r,n=Math.max(n,y);break}}else break}else this._addTextLine(A),d+=r,n=Math.max(n,y),this._shouldHandleEllipsis(d)&&S<C-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),a&&d+r>u)break}this.textHeight=t,this.textWidth=n}_shouldHandleEllipsis(e){const t=+this.fontSize(),n=this.lineHeight()*t,r=this.attrs.height,o=r!==gu&&r!==void 0,i=r-this.padding()*2;return this.wrap()===d4||o&&e+n>i}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==gu&&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+U0)<n||(o.text=o.text.slice(0,o.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(o.text+U0))}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&&ZO()?!0:super._useBufferCanvas()}};hr.prototype._fillFunc=JO,hr.prototype._strokeFunc=eF,hr.prototype.className=HO,hr.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],Er(hr),de.overWriteSetter(hr,"width",_0()),de.overWriteSetter(hr,"height",_0()),de.addGetterSetter(hr,"direction",o4),de.addGetterSetter(hr,"fontFamily","Arial"),de.addGetterSetter(hr,"fontSize",12,bt()),de.addGetterSetter(hr,"fontStyle",c4),de.addGetterSetter(hr,"fontVariant",c4),de.addGetterSetter(hr,"padding",0,bt()),de.addGetterSetter(hr,"align",a4),de.addGetterSetter(hr,"verticalAlign",$O),de.addGetterSetter(hr,"lineHeight",1,bt()),de.addGetterSetter(hr,"wrap",qO),de.addGetterSetter(hr,"ellipsis",!1,qi()),de.addGetterSetter(hr,"letterSpacing",0,bt()),de.addGetterSetter(hr,"text","",Gl()),de.addGetterSetter(hr,"textDecoration",""),de.addGetterSetter(hr,"underlineOffset",void 0,bt()),de.addGetterSetter(hr,"charRenderFunc",void 0);var nF="",h4="normal";function p4(e){e.fillText(this.partialText,0,0)}function m4(e){e.strokeText(this.partialText,0,0)}var no=class extends gt{constructor(e){super(e),this.dummyCanvas=xe.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 Li.getPathLength(this.dataArray)}_getPointAtLength(e){return!this.attrs.data||e>this.pathLength?null:Li.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=Li.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 xe.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return hr.prototype.setText.call(this,e)}_getContextFont(){return hr.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=cl(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),c=Math.max(this.textWidth+((this.attrs.text||"").length-1)*i,0);let u=0;s==="center"&&(u=Math.max(0,this.pathLength/2-c/2)),s==="right"&&(u=Math.max(0,this.pathLength-c));let d=u;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 L=this.text().split(" ").length-1;v+=(this.pathLength-c)/L}const S=d+v,C=this._getPointAtLength(S>this.pathLength&&S-this.pathLength<=l?this.pathLength:S);if(!C)return;const A=Li.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=Li.getPointOnLine(y+A/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:A}),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 xe.releaseCanvas(this.dummyCanvas),super.destroy()}};no.prototype._fillFunc=p4,no.prototype._strokeFunc=m4,no.prototype._fillFuncHit=p4,no.prototype._strokeFuncHit=m4,no.prototype.className="TextPath",no.prototype._attrsAffectingSize=["text","fontSize","data"],Er(no),de.addGetterSetter(no,"data"),de.addGetterSetter(no,"fontFamily","Arial"),de.addGetterSetter(no,"fontSize",12,bt()),de.addGetterSetter(no,"fontStyle",h4),de.addGetterSetter(no,"align","left"),de.addGetterSetter(no,"letterSpacing",0,bt()),de.addGetterSetter(no,"textBaseline","middle"),de.addGetterSetter(no,"fontVariant",h4),de.addGetterSetter(no,"text",nF),de.addGetterSetter(no,"textDecoration",""),de.addGetterSetter(no,"kerningFunc",void 0);var g4="tr-konva",rF=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(e=>e+`.${g4}`).join(" "),v4="nodesRect",oF=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],iF={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},sF="ontouchstart"in St._global;function aF(e,t,n){if(e==="rotater")return n;t+=xe.degToRad(iF[e]||0);const r=(xe.radToDeg(t)%360+360)%360;return xe._inRange(r,337.5,360)||xe._inRange(r,0,22.5)?"ns-resize":xe._inRange(r,22.5,67.5)?"nesw-resize":xe._inRange(r,67.5,112.5)?"ew-resize":xe._inRange(r,112.5,157.5)?"nwse-resize":xe._inRange(r,157.5,202.5)?"ns-resize":xe._inRange(r,202.5,247.5)?"nesw-resize":xe._inRange(r,247.5,292.5)?"ew-resize":xe._inRange(r,292.5,337.5)?"nwse-resize":(xe.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}var om=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function lF(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 y4(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 cF(e,t){return y4(e,t,lF(e))}function uF(e,t,n){let r=t;for(let o=0;o<e.length;o++){const i=St.getAngle(e[o]),s=Math.abs(i-t)%(Math.PI*2);Math.min(s,Math.PI*2-s)<n&&(r=i)}return r}var $0=0,Rn=class extends hu{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(rF,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return xe.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 g4+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(n=>n.isAncestorOf(this)?(xe.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(n=>{const r=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(n._attrsAffectingSize.length){const o=n._attrsAffectingSize.map(i=>i+"Change."+this._getEventNamespace()).join(" ");n.on(o,r)}n.on(oF.map(o=>o+`.${this._getEventNamespace()}`).join(" "),r),n.on(`absoluteTransformChange.${this._getEventNamespace()}`,r),this._proxyDrag(n)}),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(v4),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(v4,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=(St.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2);return y4({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},-St.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const e=[];this.nodes().map(a=>{const l=a.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),c=[{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}],u=a.getAbsoluteTransform();c.forEach(function(d){const h=u.point(d);e.push(h)})});const t=new Ki;t.rotate(-St.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:St.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(),om.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(e){const t=new Lf({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:sF?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=aF(e,St.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 gt({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(),c=xe.degToRad(a),u=Math.sin(c),d=-Math.cos(c),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)),u<0?p=Math.min(p,-h/u):u>0&&(p=Math.min(p,(i-h)/u));const v=h+u*p,S=g+d*p,C=xe._sign(s),A=v+u*l*C,y=S+d*l*C;t.moveTo(v,S),t.lineTo(A,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},$0++,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 c=o.getAbsolutePosition();if(l.x===c.x&&l.y===c.y)return;if(this._movingAnchorName==="rotater"){const C=this._getNodeRect();t=o.x()-C.width/2,n=-o.y()+C.height/2;const A=St.getAngle(this.rotateAnchorAngle());let y=Math.atan2(-n,t)+Math.PI/2-A;C.height<0&&(y-=Math.PI);const w=St.getAngle(this.rotation())+y,x=St.getAngle(this.rotationSnapTolerance()),L=cF(C,uF(this.rotationSnaps(),w,x)-C.rotation);this._fitNodesInto(L,e);return}const u=this.shiftBehavior();let d;u==="inverted"?d=this.keepRatio()&&!e.shiftKey:u==="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 A=this.findOne(".top-left").x()>C.x?-1:1,y=this.findOne(".top-left").y()>C.y?-1:1;t=r*this.cos*A,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 A=this.findOne(".top-right").x()<C.x?-1:1,y=this.findOne(".top-right").y()>C.y?-1:1;t=r*this.cos*A,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 A=C.x<o.x()?-1:1,y=o.y()<C.y?-1:1;t=r*this.cos*A,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 A=this.findOne(".bottom-right").x()<C.x?-1:1,y=this.findOne(".bottom-right").y()<C.y?-1:1;t=r*this.cos*A,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"),A=this.findOne(".bottom-right"),y=C.x(),w=C.y(),x=this.getWidth()-A.x(),L=this.getHeight()-A.y();A.move({x:-y,y:-w}),C.move({x,y:L})}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(),S=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:n,width:v,height:S,rotation:St.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();$0--,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(xe._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(xe._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const o=new Ki;if(o.rotate(St.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:xe.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const i=1e7,s=new Ki;s.translate(n.x,n.y),s.rotate(n.rotation),s.scale(n.width/i,n.height/i);const a=new Ki,l=e.width/i,c=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(c))):(a.translate(e.x,e.y),a.rotate(e.rotation),a.scale(l,c));const u=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 Ki;v.multiply(g.copy().invert()).multiply(u).multiply(g).multiply(p);const S=v.decompose();d.setAttrs(S),(h=d.getLayer())===null||h===void 0||h.batchDraw()}),this.rotation(xe._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(xe._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 c=this.rotateAnchorAngle(),u=this.rotateAnchorOffset(),d=xe.degToRad(c),h=Math.sin(d),g=-Math.cos(d),p=n/2,v=r/2;let S=1/0;g<0?S=Math.min(S,-v/g):g>0&&(S=Math.min(S,(r-v)/g)),h<0?S=Math.min(S,-p/h):h>0&&(S=Math.min(S,(n-p)/h));const C=p+h*S,A=v+g*S,y=xe._sign(r);this._batchChangeChild(".rotater",{x:C+h*u*y,y:A+g*u*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=""),hu.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...e){return this._elementsCreated?(xe.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...e)}toObject(){return _t.prototype.toObject.call(this)}clone(e){return _t.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};Rn.isTransforming=()=>$0>0;function dF(e){return e instanceof Array||xe.warn("enabledAnchors value should be an array"),e instanceof Array&&e.forEach(function(t){om.indexOf(t)===-1&&xe.warn("Unknown anchor name: "+t+". Available names are: "+om.join(", "))}),e||[]}Rn.prototype.className="Transformer",Er(Rn),de.addGetterSetter(Rn,"enabledAnchors",om,dF),de.addGetterSetter(Rn,"flipEnabled",!0,qi()),de.addGetterSetter(Rn,"resizeEnabled",!0),de.addGetterSetter(Rn,"anchorSize",10,bt()),de.addGetterSetter(Rn,"rotateEnabled",!0),de.addGetterSetter(Rn,"rotateLineVisible",!0),de.addGetterSetter(Rn,"rotationSnaps",[]),de.addGetterSetter(Rn,"rotateAnchorOffset",50,bt()),de.addGetterSetter(Rn,"rotateAnchorAngle",0,bt()),de.addGetterSetter(Rn,"rotateAnchorCursor","crosshair"),de.addGetterSetter(Rn,"rotationSnapTolerance",5,bt()),de.addGetterSetter(Rn,"borderEnabled",!0),de.addGetterSetter(Rn,"anchorStroke","rgb(0, 161, 255)"),de.addGetterSetter(Rn,"anchorStrokeWidth",1,bt()),de.addGetterSetter(Rn,"anchorFill","white"),de.addGetterSetter(Rn,"anchorCornerRadius",0,bt()),de.addGetterSetter(Rn,"borderStroke","rgb(0, 161, 255)"),de.addGetterSetter(Rn,"borderStrokeWidth",1,bt()),de.addGetterSetter(Rn,"borderDash"),de.addGetterSetter(Rn,"keepRatio",!0),de.addGetterSetter(Rn,"shiftBehavior","default"),de.addGetterSetter(Rn,"centeredScaling",!1),de.addGetterSetter(Rn,"ignoreStroke",!1),de.addGetterSetter(Rn,"padding",0,bt()),de.addGetterSetter(Rn,"nodes"),de.addGetterSetter(Rn,"node"),de.addGetterSetter(Rn,"boundBoxFunc"),de.addGetterSetter(Rn,"anchorDragBoundFunc"),de.addGetterSetter(Rn,"anchorStyleFunc"),de.addGetterSetter(Rn,"shouldOverdrawWholeArea",!1),de.addGetterSetter(Rn,"useSingleNodeRotation",!0),de.backCompat(Rn,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var va=class extends gt{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,St.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)}};va.prototype.className="Wedge",va.prototype._centroid=!0,va.prototype._attrsAffectingSize=["radius"],Er(va),de.addGetterSetter(va,"radius",0,bt()),de.addGetterSetter(va,"angle",0,bt()),de.addGetterSetter(va,"clockwise",!1),de.backCompat(va,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function b4(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}var fF=[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],hF=[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 pF(e,t){const n=e.data,r=e.width,o=e.height;let i,s,a,l,c,u,d,h,g,p,v,S,C,A,y,w,x,L,V,G;const R=t+t+1,F=r-1,Z=o-1,O=t+1,N=O*(O+1)/2,T=new b4,B=fF[t],Q=hF[t];let q=null,se=T,he=null,Ne=null;for(let pe=1;pe<R;pe++)se=se.next=new b4,pe===O&&(q=se);se.next=T,a=s=0;for(let pe=0;pe<o;pe++){S=C=A=y=l=c=u=d=0,h=O*(w=n[s]),g=O*(x=n[s+1]),p=O*(L=n[s+2]),v=O*(V=n[s+3]),l+=N*w,c+=N*x,u+=N*L,d+=N*V,se=T;for(let ye=0;ye<O;ye++)se.r=w,se.g=x,se.b=L,se.a=V,se=se.next;for(let ye=1;ye<O;ye++)i=s+((F<ye?F:ye)<<2),l+=(se.r=w=n[i])*(G=O-ye),c+=(se.g=x=n[i+1])*G,u+=(se.b=L=n[i+2])*G,d+=(se.a=V=n[i+3])*G,S+=w,C+=x,A+=L,y+=V,se=se.next;he=T,Ne=q;for(let ye=0;ye<r;ye++)n[s+3]=V=d*B>>Q,V!==0?(V=255/V,n[s]=(l*B>>Q)*V,n[s+1]=(c*B>>Q)*V,n[s+2]=(u*B>>Q)*V):n[s]=n[s+1]=n[s+2]=0,l-=h,c-=g,u-=p,d-=v,h-=he.r,g-=he.g,p-=he.b,v-=he.a,i=a+((i=ye+t+1)<F?i:F)<<2,S+=he.r=n[i],C+=he.g=n[i+1],A+=he.b=n[i+2],y+=he.a=n[i+3],l+=S,c+=C,u+=A,d+=y,he=he.next,h+=w=Ne.r,g+=x=Ne.g,p+=L=Ne.b,v+=V=Ne.a,S-=w,C-=x,A-=L,y-=V,Ne=Ne.next,s+=4;a+=r}for(let pe=0;pe<r;pe++){C=A=y=S=c=u=d=l=0,s=pe<<2,h=O*(w=n[s]),g=O*(x=n[s+1]),p=O*(L=n[s+2]),v=O*(V=n[s+3]),l+=N*w,c+=N*x,u+=N*L,d+=N*V,se=T;for(let me=0;me<O;me++)se.r=w,se.g=x,se.b=L,se.a=V,se=se.next;let ye=r;for(let me=1;me<=t;me++)s=ye+pe<<2,l+=(se.r=w=n[s])*(G=O-me),c+=(se.g=x=n[s+1])*G,u+=(se.b=L=n[s+2])*G,d+=(se.a=V=n[s+3])*G,S+=w,C+=x,A+=L,y+=V,se=se.next,me<Z&&(ye+=r);s=pe,he=T,Ne=q;for(let me=0;me<o;me++)i=s<<2,n[i+3]=V=d*B>>Q,V>0?(V=255/V,n[i]=(l*B>>Q)*V,n[i+1]=(c*B>>Q)*V,n[i+2]=(u*B>>Q)*V):n[i]=n[i+1]=n[i+2]=0,l-=h,c-=g,u-=p,d-=v,h-=he.r,g-=he.g,p-=he.b,v-=he.a,i=pe+((i=me+O)<Z?i:Z)*r<<2,l+=S+=he.r=n[i],c+=C+=he.g=n[i+1],u+=A+=he.b=n[i+2],d+=y+=he.a=n[i+3],he=he.next,h+=w=Ne.r,g+=x=Ne.g,p+=L=Ne.b,v+=V=Ne.a,S-=w,C-=x,A-=L,y-=V,Ne=Ne.next,s+=r}}var mF=function(t){const n=Math.round(this.blurRadius());n>0&&pF(t,n)};de.addGetterSetter(_t,"blurRadius",0,bt(),de.afterSetFilter);var gF=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};de.addGetterSetter(_t,"brightness",0,bt(),de.afterSetFilter);var vF=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)},yF=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};de.addGetterSetter(_t,"contrast",0,bt(),de.afterSetFilter);var bF=function(e){var t,n,r,o,i,s,a,l,c;const u=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,S=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),C=g*10,A=p*255,y=v*Math.PI/180,w=Math.cos(y),x=Math.sin(y),L=128/1020*C,V=new Uint8ClampedArray(u),G=new Float32Array(d*h);for(let N=0,T=0;T<u.length;T+=4,N++)G[N]=.2126*V[T]+.7152*V[T+1]+.0722*V[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],O=N=>N<0?0:N>255?255:N;for(let N=1;N<h-1;N++)for(let T=1;T<d-1;T++){const B=N*d+T;let Q=0,q=0;Q+=G[B+Z[0]]*R[0],q+=G[B+Z[0]]*F[0],Q+=G[B+Z[1]]*R[1],q+=G[B+Z[1]]*F[1],Q+=G[B+Z[2]]*R[2],q+=G[B+Z[2]]*F[2],Q+=G[B+Z[3]]*R[3],q+=G[B+Z[3]]*F[3],Q+=G[B+Z[5]]*R[5],q+=G[B+Z[5]]*F[5],Q+=G[B+Z[6]]*R[6],q+=G[B+Z[6]]*F[6],Q+=G[B+Z[7]]*R[7],q+=G[B+Z[7]]*F[7],Q+=G[B+Z[8]]*R[8],q+=G[B+Z[8]]*F[8];const se=O(A+(w*Q+x*q)*L),he=B*4;if(S){const Ne=se-A;u[he]=O(V[he]+Ne),u[he+1]=O(V[he+1]+Ne),u[he+2]=O(V[he+2]+Ne),u[he+3]=V[he+3]}else u[he]=u[he+1]=u[he+2]=se,u[he+3]=V[he+3]}for(let N=0;N<d;N++){let T=N*4,B=((h-1)*d+N)*4;u[T]=V[T],u[T+1]=V[T+1],u[T+2]=V[T+2],u[T+3]=V[T+3],u[B]=V[B],u[B+1]=V[B+1],u[B+2]=V[B+2],u[B+3]=V[B+3]}for(let N=1;N<h-1;N++){let T=N*d*4,B=(N*d+(d-1))*4;u[T]=V[T],u[T+1]=V[T+1],u[T+2]=V[T+2],u[T+3]=V[T+3],u[B]=V[B],u[B+1]=V[B+1],u[B+2]=V[B+2],u[B+3]=V[B+3]}return e};de.addGetterSetter(_t,"embossStrength",.5,bt(),de.afterSetFilter),de.addGetterSetter(_t,"embossWhiteLevel",.5,bt(),de.afterSetFilter),de.addGetterSetter(_t,"embossDirection","top-left",void 0,de.afterSetFilter),de.addGetterSetter(_t,"embossBlend",!1,void 0,de.afterSetFilter);function G0(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}var wF=function(e){const t=e.data,n=t.length;let r=t[0],o=r,i,s=t[1],a=s,l,c=t[2],u=c,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<c?c=d:d>u&&(u=d);o===r&&(o=255,r=0),a===s&&(a=255,s=0),u===c&&(u=255,c=0);let g,p,v,S,C,A;if(h>0)g=o+h*(255-o),p=r-h*(r-0),v=a+h*(255-a),S=s-h*(s-0),C=u+h*(255-u),A=c-h*(c-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),S=s+h*(s-w);const x=(u+c)*.5;C=u+h*(u-x),A=c+h*(c-x)}for(let y=0;y<n;y+=4)t[y+0]=G0(t[y+0],r,o,p,g),t[y+1]=G0(t[y+1],s,a,S,v),t[y+2]=G0(t[y+2],c,u,A,C)};de.addGetterSetter(_t,"enhance",0,bt(),de.afterSetFilter);var CF=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}};de.addGetterSetter(_t,"hue",0,bt(),de.afterSetFilter),de.addGetterSetter(_t,"saturation",0,bt(),de.afterSetFilter),de.addGetterSetter(_t,"luminance",0,bt(),de.afterSetFilter);var kF=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),c=.299*r+.701*a+.167*l,u=.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,S=.587*r-.586*a-1.05*l,C=.114*r+.886*a-.2*l;let A,y,w,x;for(let L=0;L<n;L+=4)A=t[L+0],y=t[L+1],w=t[L+2],x=t[L+3],t[L+0]=c*A+u*y+d*w+s,t[L+1]=h*A+g*y+p*w+s,t[L+2]=v*A+S*y+C*w+s,t[L+3]=x},SF=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,c=.587*r-.587*s+.33*a,u=.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,S=.114*r+.886*s-.2*a;for(let C=0;C<n;C+=4){const A=t[C+0],y=t[C+1],w=t[C+2],x=t[C+3];t[C+0]=l*A+c*y+u*w,t[C+1]=d*A+h*y+g*w,t[C+2]=p*A+v*y+S*w,t[C+3]=x}};de.addGetterSetter(_t,"hue",0,bt(),de.afterSetFilter),de.addGetterSetter(_t,"saturation",0,bt(),de.afterSetFilter),de.addGetterSetter(_t,"value",0,bt(),de.afterSetFilter);var _F=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]},AF=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 c=Math.sqrt(a*a+l*l),u=i-a,d=s-l;const h=Math.sqrt(u*u+d*d);c=h>c?h:c;const g=s,p=i,v=360/p*Math.PI/180;for(let S=0;S<p;S+=1){const C=Math.sin(S*v),A=Math.cos(S*v);for(let y=0;y<g;y+=1){u=Math.floor(a+c*y/g*A),d=Math.floor(l+c*y/g*C);let w=(d*i+u)*4;const x=r[w+0],L=r[w+1],V=r[w+2],G=r[w+3];w=(S+y*i)*4,o[w+0]=x,o[w+1]=L,o[w+2]=V,o[w+3]=G}}},IF=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 c=Math.sqrt(a*a+l*l),u=i-a,d=s-l;const h=Math.sqrt(u*u+d*d);c=h>c?h:c;const g=s,p=i,v=n.polarRotation||0;let S,C;for(u=0;u<i;u+=1)for(d=0;d<s;d+=1){const A=u-a,y=d-l,w=Math.sqrt(A*A+y*y)*g/c;let x=(Math.atan2(y,A)*180/Math.PI+360+v)%360;x=x*p/360,S=Math.floor(x),C=Math.floor(w);let L=(C*i+S)*4;const V=r[L+0],G=r[L+1],R=r[L+2],F=r[L+3];L=(d*i+u)*4,o[L+0]=V,o[L+1]=G,o[L+2]=R,o[L+3]=F}},EF=function(e){const t=e.width,n=e.height;let r,o,i,s,a,l,c,u,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 S=xe.createCanvasElement();S.width=t,S.height=n;const C=S.getContext("2d").getImageData(0,0,t,n);xe.releaseCanvas(S),AF(e,C,{polarCenterX:t/2,polarCenterY:n/2});let A=t/Math.pow(2,g);for(;A<=8;)A=A*2,g-=1;A=Math.ceil(A);let y=A,w=0,x=y,L=1;for(v+A>t&&(w=y,x=0,L=-1),o=0;o<n;o+=1)for(r=w;r!==x;r+=L)i=Math.round(r+v)%t,d=(t*o+i)*4,a=C.data[d+0],l=C.data[d+1],c=C.data[d+2],u=C.data[d+3],h=(t*o+r)*4,C.data[h+0]=a,C.data[h+1]=l,C.data[h+2]=c,C.data[h+3]=u;for(o=0;o<n;o+=1)for(y=Math.floor(A),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],c=C.data[d+2],u=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]=c,C.data[h+3]=u;y*=2}IF(C,e,{polarRotation:0})};de.addGetterSetter(_t,"kaleidoscopePower",2,bt(),de.afterSetFilter),de.addGetterSetter(_t,"kaleidoscopeAngle",0,bt(),de.afterSetFilter);function im(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 Of(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 TF(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 xF(e,t){const n=im(e,0,0),r=im(e,e.width-1,0),o=im(e,0,e.height-1),i=im(e,e.width-1,e.height-1),s=t||10;if(Of(n,r)<s&&Of(r,i)<s&&Of(i,o)<s&&Of(o,n)<s){const a=TF([r,n,i,o]),l=[];for(let c=0;c<e.width*e.height;c++)l[c]=Of(a,[e.data[c*4],e.data[c*4+1],e.data[c*4+2]])<s?0:255;return l}}function RF(e,t){for(let n=0;n<e.width*e.height;n++)e.data[4*n+3]=t[n]}function MF(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 c=a*t+l;let u=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,S=r[d*o+h];u+=e[v]*S}}s[c]=u===2040?255:0}return s}function LF(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 c=a*t+l;let u=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,S=r[d*o+h];u+=e[v]*S}}s[c]=u>=1020?255:0}return s}function PF(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 c=a*t+l;let u=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,S=r[d*o+h];u+=e[v]*S}}s[c]=u}return s}var DF=function(e){let t=xF(e,this.threshold());return t&&(t=MF(t,e.width,e.height),t=LF(t,e.width,e.height),t=PF(t,e.width,e.height),RF(e,t)),e};de.addGetterSetter(_t,"threshold",0,bt(),de.afterSetFilter);var OF=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()};de.addGetterSetter(_t,"noise",.2,bt(),de.afterSetFilter);var FF=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){xe.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 c=0,u=0,d=0,h=0;const g=a*t,p=g+t,v=l*t,S=v+t;let C=0;for(let A=g;A<p;A+=1)if(!(A>=n))for(let y=v;y<S;y+=1){if(y>=r)continue;const w=(n*y+A)*4;c+=s[w+0],u+=s[w+1],d+=s[w+2],h+=s[w+3],C+=1}c=c/C,u=u/C,d=d/C,h=h/C;for(let A=g;A<p;A+=1)if(!(A>=n))for(let y=v;y<S;y+=1){if(y>=r)continue;const w=(n*y+A)*4;s[w+0]=c,s[w+1]=u,s[w+2]=d,s[w+3]=h}}};de.addGetterSetter(_t,"pixelSize",8,bt(),de.afterSetFilter);var NF=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};de.addGetterSetter(_t,"levels",.5,bt(),de.afterSetFilter);var BF=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]}};de.addGetterSetter(_t,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),de.addGetterSetter(_t,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),de.addGetterSetter(_t,"blue",0,w_,de.afterSetFilter);var zF=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}};de.addGetterSetter(_t,"red",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),de.addGetterSetter(_t,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)}),de.addGetterSetter(_t,"blue",0,w_,de.afterSetFilter),de.addGetterSetter(_t,"alpha",1,function(e){return this._filterUpToDate=!1,e>1?1:e<0?0:e});var VF=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)}},jF=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},UF=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};de.addGetterSetter(_t,"threshold",.5,bt(),de.afterSetFilter);var HF=Z_.Util._assign(Z_,{Arc:ma,Arrow:ql,Circle:mu,Ellipse:sl,Image:Yi,Label:j0,Tag:Yl,Line:ga,Path:Li,Rect:Lf,RegularPolygon:al,Ring:Xl,Sprite:Cs,Star:ll,Text:hr,TextPath:no,Transformer:Rn,Wedge:va,Filters:{Blur:mF,Brightness:vF,Brighten:gF,Contrast:yF,Emboss:bF,Enhance:wF,Grayscale:CF,HSL:kF,HSV:SF,Invert:_F,Kaleidoscope:EF,Mask:DF,Noise:OF,Pixelate:FF,Posterize:NF,RGB:BF,RGBA:zF,Sepia:VF,Solarize:jF,Threshold:UF}}),$F=HF;Dt();var GF=["dialog","floating"],w4=["top-right","top-left","bottom-right","bottom-left","top-center","bottom-center"];function WF(e){if(!e||typeof e!="object")throw new Error("SurfaceManager: request must be a non-null object.");if(!GF.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&&!w4.includes(e.floating.placement))throw new Error(`SurfaceManager: floating.placement must be one of ${w4.join(", ")}, got "${e.floating.placement}".`)}var KF=class{activeDialog=to(null);activeFloating=to(null);#t=!1;#n=1;#e;constructor({getModuleConfig:e}){this.#e=e}open(e){if(this.#t)return this.#f(e);WF(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 c=g=>{i({status:"submitted",data:g})&&this.#i(l)},u=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:c,close:u,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"})}}},qF="https://docs.superdoc.dev/guides/migration/document-api",C4=new Set;function YF(e,t){C4.has(e)||(C4.add(e),console.warn(t))}var XF={state:"editor.state",view:"editor.view",schema:"editor.schema",commands:"editor.commands",chain:"editor.chain()",can:"editor.can()",dispatch:"editor.dispatch()"},k4=Symbol.for("superdoc:rawEditor"),S4=new WeakMap;function _4(e){return!e||e[k4]?e:new Proxy(e,{get(t,n){if(n===k4)return t;const r=XF[n];r&&YF(`deprecated:${String(n)}`,`[SuperDoc] ${r} is deprecated and will be removed in a future version. Use the Document API (editor.doc) instead. See ${qF}`);const o=Reflect.get(t,n,t);if(typeof o=="function"){let i=S4.get(t);return i||(i=new Map,S4.set(t,i)),i.has(n)||i.set(n,o.bind(t)),i.get(n)}return o}})}var A4=["review","original","final","off"],ZF=["paired","independent"],I4=Symbol.for("@superdoc/trackChanges:normalized"),E4=new Set;function T4(e,t){E4.has(e)||(E4.add(e),console.warn(`[SuperDoc] ${e} is deprecated — use ${t} instead.`))}function x4(e,t,n){return typeof e=="boolean"?e:typeof t=="boolean"?t:n}function QF(e,t,n){return typeof e=="string"&&A4.includes(e)?e:typeof t=="string"&&A4.includes(t)?t:n}function JF(e){return typeof e=="string"&&ZF.includes(e)?e:null}function Zl(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function eN(e){const t=e[I4]===!0;Zl(e.modules)||(e.modules={});const n=Zl(e.modules.trackChanges),r=Zl(e.trackChanges),o=Zl(e.layoutEngineOptions?.trackedChanges);t||(r&&T4("config.trackChanges","config.modules.trackChanges"),o&&T4("config.layoutEngineOptions.trackedChanges","config.modules.trackChanges"));const i=x4(n?.visible,r?.visible,!1),s=x4(n?.enabled,o?.enabled,!0),a=JF(n?.replacements)??"paired",l=Zl(n?.authorColors)?n.authorColors:void 0,c=Zl(n?.semanticColors)?n.semanticColors:void 0,u=e.documentMode==="viewing"?i?"review":"original":"review",d=QF(n?.mode,o?.mode,u),h={visible:i,mode:d,enabled:s,replacements:a};return l&&(h.authorColors=l),c&&(h.semanticColors=c),e.modules.trackChanges=h,e.trackChanges={visible:i},Zl(e.layoutEngineOptions)||(e.layoutEngineOptions={}),e.layoutEngineOptions.trackedChanges={mode:d,enabled:s},Object.defineProperty(e,I4,{value:!0,writable:!0,configurable:!0,enumerable:!1}),h}var W0=Object.freeze({id:null,name:"Default SuperDoc user",email:null});function tN(e){return!e||typeof e!="object"?{...W0}:{...W0,...e}}var R4=Object.freeze({toolbar:!0,comments:!0,contextMenu:!0,search:!1,linkPopover:!1,ruler:!1,contentControls:!0}),nN=Object.freeze(["left","center","right"]),YH=Object.freeze(Object.keys(R4)),vu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function M4(e,t){const n=e?.[t];return n===!1?!1:n===void 0?R4[t]:!0}function rN(e,t){const n=e?.[t];return vu(n)?n:{}}var L4=Object.freeze(["readOnly","allowResolve","permissionResolver"]);function oN(e){if(!L4.some(n=>n in e))return e;const t={...e};for(const n of L4)delete t[n];return t}function P4(e={}){const t=e.ui,n=t===!1,r=vu(t)?t:void 0,o=R=>!n&&M4(r,R),i=R=>n?!1:r?.[R]===void 0?void 0:M4(r,R),s=R=>n?{}:rN(r,R),a=n||i("ruler")===!1,l=n||i("linkPopover")===!1,c=l?void 0:h0(s("linkPopover").popoverResolver,e.modules?.links?.popoverResolver),u=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=vu(g)?g:{},v=e.modules?.contextMenu??e.modules?.slashMenu,S=vu(v)?v:{},C=e.modules?.surfaces?.findReplace,A=vu(C)?C:{},y=[h.groups,p.groups],w=y.find(vu),x=h0(y.find(Array.isArray),p.toolbarGroups,e.toolbarGroups),L=Array.isArray(x)?x:null,V=(R,F)=>Object.prototype.hasOwnProperty.call(R,F),G=w&&L?Object.fromEntries([...L.filter(R=>V(w,R)),...Object.keys(w).filter(R=>!nN.includes(R))].map(R=>[R,w[R]])):w;return{enabled:!n,toolbar:{enabled:o("toolbar"),container:n?null:h0(h.container,p.selector,e.toolbar)??null,options:n?{}:{...ws(p,h),groups:G,toolbarGroups:x,icons:ws(e.toolbarIcons,p.icons,h.icons),texts:ws(e.toolbarTexts,p.texts,h.texts)}},comments:{enabled:i("comments")??(!n&&e.modules?.comments!==!1),options:n?{}:xk(oN(s("comments")))},contextMenu:{enabled:i("contextMenu")??(!n&&e.disableContextMenu!==!0),suppressed:n||i("contextMenu")===!1,options:n?{}:ws(S,s("contextMenu"))},search:{enabled:i("search")??(!n&&!!e.modules?.surfaces?.findReplace),options:n?{}:ws(A,s("search"))},linkPopover:{enabled:typeof c=="function",suppressed:l,options:ws(s("linkPopover"),{popoverResolver:c})},ruler:{enabled:i("ruler")??(!n&&!!e.rulers),suppressed:a,container:a?null:s("ruler").container??e.rulerContainer??null},contentControls:{enabled:u,options:u?ws({chrome:d},s("contentControls")):{chrome:"none"}}}}var K0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function D4(e={}){const t=K0(e.interaction)?e.interaction:{},n=K0(t.comments)?t.comments:{},r=K0(e.modules?.comments)?e.modules.comments:{};return{comments:{readOnly:(n.readOnly??r.readOnly??!1)===!0,allowResolve:(n.allowResolve??r.allowResolve??!0)!==!1}}}var O4=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function F4(e={}){const t=O4(e.surfaces)?e.surfaces:{},n=O4(e.modules?.surfaces)?e.modules.surfaces:{},r=t.resolver===void 0?n.resolver:t.resolver;return{resolver:typeof r=="function"?r:null,dialog:ws(n.dialog,t.dialog),floating:ws(n.floating,t.floating)}}var iN=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(`[${zp}]`);if(!n)return null;const r=n.getAttribute(zp),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{}}},dt={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"},N4={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 B4(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 sN(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 aN(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 z4(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 q0(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 lN(e){const t=q0(e,["alignment","value"]);if(typeof t!="string")return t;const n=t.trim().toLowerCase();return n==="justified"||n==="both"?"justify":n}function cN(e){const t=q0(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 uN(e){if(e&&typeof e=="object"&&"role"in e)return e;const t=q0(e,["styleId","value","style"]);return typeof t=="string"?t.trim():t}function dN(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 fN=dt.commandUnsupported,ks=dt.tableContextUnavailable,V4=[{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:B4,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:B4,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:sN},{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:dN},{id:"measurement-unit",family:"measurement",disposition:"routed",mutates:!1,instanceRoute:"setMeasurementUnit",valueFrom:"measurementUnit",normalizePayload:aN},{id:"text-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.color",inline:{key:"color",kind:"value-string"},normalizePayload:z4},{id:"highlight-color",family:"color",disposition:"routed",mutates:!0,docRoute:"format.highlight",inline:{key:"highlight",kind:"value-string"},normalizePayload:z4},{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:lN},{id:"line-height",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"format.paragraph.setSpacing",blockParagraph:{kind:"spacing-line"},normalizePayload:cN},{id:"linked-style",family:"paragraph",disposition:"routed",mutates:!0,docRoute:"styles.paragraph.setStyle",blockParagraph:{kind:"style"},normalizePayload:uN},{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:ks},{id:"table-add-row-after",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertRow",table:{action:"insert-row-after",op:"insertRow"},reason:ks},{id:"table-delete-row",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.deleteRow",table:{action:"delete-row",op:"deleteRow"},reason:ks},{id:"table-add-column-before",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertColumn",table:{action:"insert-column-before",op:"insertColumn"},reason:ks},{id:"table-add-column-after",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.insertColumn",table:{action:"insert-column-after",op:"insertColumn"},reason:ks},{id:"table-delete-column",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.deleteColumn",table:{action:"delete-column",op:"deleteColumn"},reason:ks},{id:"table-delete",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.delete",table:{action:"delete-table",op:"delete"},reason:ks},{id:"table-merge-cells",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.mergeCells",table:{action:"merge-cells",op:"mergeCells"},reason:ks},{id:"table-split-cell",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.splitCell",table:{action:"split-cell",op:"splitCell",requiresCell:!0},reason:ks},{id:"table-remove-borders",family:"tables",disposition:"routed",mutates:!0,docRoute:"tables.setBorders",table:{action:"remove-borders",op:"setBorders"},reason:ks},{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:fN}],hN=new Map(V4.map(e=>[e.id,e])),pN=V4.map(e=>e.id);function yu(e){return hN.get(e)??null}var mN=["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"],j4=[{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:mN,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"}],U4=new Map(j4.map(e=>[e.name,e])),XH=j4.map(e=>e.name);function Y0(e){return U4.get(e)??null}function gN(e){const t=U4.get(e);return t?.disposition==="controller-routed"?t.commandId:null}var vN=".png,.jpg,.jpeg,image/png,image/jpeg",H4=new Set(["image/png","image/jpeg","image/jpg"]),yN=/\.(png|jpe?g)$/i;function bN(e){if(!e)return!1;const t=typeof e.type=="string"?e.type.toLowerCase():"";return t?H4.has(t):yN.test(String(e.name??""))}function $4(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(wN(String(r.result),e)),r.onerror=()=>n(r.error??new Error("image-read-failed")),r.readAsDataURL(e)})}function wN(e,t){const n=/^data:([^;,]*);base64,/.exec(e);if(!n)return e;const r=n[1].toLowerCase();if(H4.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 CN(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:kN(n,e)}return $4(e)}async function kN(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 $4(o?Object.assign(r,{name:o}):r)}function SN({ownerDocument:e=document,onPick:t,onError:n}={}){const r=e.createElement("input");return r.type="file",r.accept=vN,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(!bN(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 _N=(e,t)=>{let n=e.replace(/[^0-9.]/g,"");return n=parseFloat(n),isNaN(n)&&(n=t),n=parseFloat(n),n},AN=(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=(...c)=>{const u=Date.now();!s&&n.leading===!1&&(s=u);const d=t-(u-s);return o=c,d<=0||d>t?(r&&(clearTimeout(r),r=null),s=u,i=e(...c),r||(o=null)):!r&&n.trailing!==!1&&(r=setTimeout(a,d)),i};return l.cancel=function(){clearTimeout(r),s=0,r=o=null},l};Dt(),bn();var IN={class:"sd-toolbar-icon"},EN=["innerHTML"],TN={__name:"ToolbarButtonIcon",props:{name:{type:String,required:!0},color:{type:String,default:null},icon:{type:String,default:null}},setup(e){const t=e,n=Ee(()=>{if(t.name==="color")return{backgroundColor:t.color||"#111111"};if(t.name==="highlight")return{backgroundColor:t.color||"#D6D6D6"}}),r=Ee(()=>["color","highlight"].includes(t.name));return(o,i)=>(ve(),Te("div",IN,[Fe("div",{class:on(["sd-toolbar-icon__icon",[`sd-toolbar-icon__icon--${t.name}`]]),innerHTML:e.icon},null,10,EN),r.value?(ve(),Te("div",{key:0,class:"color-bar",style:Sn(n.value)},null,4)):vt("",!0)]))}},G4=pn(TN,[["__scopeId","data-v-d7d79424"]]);Dt(),bn();var xN=["role","aria-label"],RN=["data-item"],MN=["data-item"],LN={key:1,class:"sd-button-label"},PN=["data-item","aria-label"],DN=["innerHTML"],ON={key:2},FN=["onKeydown","id"],NN=["placeholder","onKeydown","id","data-item"],BN=["data-item","innerHTML"],zN={"aria-live":"polite",class:"sd-visually-hidden"},VN={__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}=vr(),o=e,{name:i,active:s,icon:a,label:l,hideLabel:c,iconColor:u,hasCaret:d,splitButton:h,disabled:g,expand:p,inlineTextInputVisible:v,hasInlineTextInput:S,minWidth:C,style:A,attributes:y}=o.toolbarItem,w=Ee(()=>!!h?.value&&!!d?.value),x=Ee(()=>i?.value??""),L=re(""),V=re(null),{isHighContrastMode:G}=Gi();Vt(()=>l?.value,_e=>{document.activeElement!==V.value&&(L.value=_e==null?"":String(_e))},{immediate:!0});const R=()=>{S&&Tt(()=>{V.value?.focus(),V.value?.select()}),n("buttonClick")},F=_e=>{g?.value||(_e?.stopPropagation(),n("mainClick"))},Z=()=>{w.value||R()},O=_e=>{if(w.value){F(_e);return}R()},N=_e=>{o.allowEnterPropagation||_e.stopPropagation(),O(_e)},T=_e=>{const oe=o.toolbarItem?.nestedOptions?.value??[],Me=_e.trim();if(!Me)return"";const Ge=oe.find(lt=>typeof lt?.label=="string"&&lt.label.toLowerCase()===Me.toLowerCase());return Ge?.label?Ge.label:oe.find(lt=>typeof lt?.label=="string"&&lt.label.toLowerCase().startsWith(Me.toLowerCase()))?.label??Me},B=()=>{const _e=String(L.value??"").trim();let oe=_e;if(x.value==="fontSize"){const Me=Number.parseFloat(_e);oe=_e.match(/^\d+(\.5)?$/)?_e:Number.isFinite(Me)?Math.floor(Me).toString():""}else x.value==="fontFamily"&&(oe=T(_e));return oe?(n("textSubmit",oe),L.value=oe,!0):!1},Q=_e=>{const oe=_e?.currentTarget;oe instanceof HTMLInputElement&&(oe.focus({preventScroll:!0}),oe.select())},q=_e=>{requestAnimationFrame(()=>{const oe=document.getElementById(`inlineTextInput-${_e}`);oe instanceof HTMLInputElement&&(oe.focus({preventScroll:!0}),oe.select())})},se=()=>{const _e=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return _e instanceof HTMLElement?(_e.focus({preventScroll:!0}),!0):!1},he=()=>{const _e=r?.$toolbar?.pendingSelectionCapture,oe=()=>{_e&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(_e)};if(se()){oe();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),oe())},Ne=()=>{B()&&he()},pe=_e=>{if(B(),_e.shiftKey){x.value==="fontSize"&&(_e.preventDefault(),Tt(()=>q("fontFamily")));return}if(_e.preventDefault(),x.value==="fontFamily"){Tt(()=>q("fontSize"));return}x.value==="fontSize"&&Tt(he)},ye=Ee(()=>A.value?A.value:{minWidth:o.minWidth}),me=Ee(()=>p?.value?fr.dropdownCaretUp:fr.dropdownCaretDown);return(_e,oe)=>(ve(),Te("div",{class:on(["sd-toolbar-item",nt(y).className]),style:Sn(ye.value),role:e.isOverflowItem?"menuitem":"button","aria-label":nt(y).ariaLabel,"data-sd-part":"toolbar-item",onClick:Z,onKeydown:oe[9]||(oe[9]=oi(Me=>N(Me),["enter"])),tabindex:"0"},[Fe("div",{class:on(["sd-toolbar-button",{"sd-active":nt(s),"sd-disabled":nt(g),narrow:e.isNarrow,wide:e.isWide,split:w.value,"has-inline-text-input":nt(S),"high-contrast":nt(G)}]),"data-item":`btn-${nt(i)||""}`},[w.value?(ve(),Te("div",{key:0,class:"sd-toolbar-button__main","data-item":`btn-${nt(i)||""}-main`,onClick:oe[0]||(oe[0]=Me=>F(Me))},[nt(a)?(ve(),hn(G4,{key:0,color:nt(u),class:"sd-toolbar-icon",icon:nt(a),name:nt(i)},null,8,["color","icon","name"])):vt("",!0),nt(l)&&!nt(c)&&!nt(v)?(ve(),Te("div",LN,Ht(nt(l)),1)):vt("",!0)],8,MN)):vt("",!0),w.value?(ve(),Te("div",{key:1,class:"sd-toolbar-button__caret","data-item":`btn-${nt(i)||""}-caret`,"aria-label":`${nt(y).ariaLabel} options`,role:"button"},[Fe("div",{class:"sd-dropdown-caret",innerHTML:me.value,style:Sn({opacity:nt(g)?.6:1})},null,12,DN)],8,PN)):(ve(),Te(Yt,{key:2},[nt(a)?(ve(),hn(G4,{key:0,color:nt(u),class:"sd-toolbar-icon",icon:nt(a),name:nt(i)},null,8,["color","icon","name"])):vt("",!0),nt(l)&&!nt(c)&&(!nt(v)||x.value==="fontFamily")?(ve(),Te("div",{key:1,class:on(["sd-button-label",{"sd-visually-hidden":nt(v)&&x.value==="fontFamily"}])},Ht(nt(l)),3)):vt("",!0),nt(v)?(ve(),Te("span",ON,[nt(i)==="fontSize"?Ks((ve(),Te("input",{key:0,"onUpdate:modelValue":oe[1]||(oe[1]=Me=>L.value=Me),onKeydown:[oi(rn(Ne,["stop","prevent"]),["enter"]),oe[2]||(oe[2]=oi(Me=>pe(Me),["tab"]))],onClick:oe[3]||(oe[3]=rn(Me=>Q(Me),["stop"])),onFocus:oe[4]||(oe[4]=Me=>Q(Me)),type:"text",class:on(["button-text-input button-text-input--font-size",{"high-contrast":nt(G)}]),id:"inlineTextInput-"+nt(i),autocomplete:"off",ref_key:"inlineInput",ref:V},null,42,FN)),[[Ri,L.value]]):Ks((ve(),Te("input",{key:1,"onUpdate:modelValue":oe[5]||(oe[5]=Me=>L.value=Me),placeholder:nt(l),onKeydown:[oi(rn(Ne,["stop","prevent"]),["enter"]),oe[6]||(oe[6]=oi(Me=>pe(Me),["tab"]))],onClick:oe[7]||(oe[7]=rn(Me=>Q(Me),["stop"])),onFocus:oe[8]||(oe[8]=Me=>Q(Me)),type:"text",class:on(["button-text-input",{"button-text-input--font-family":x.value==="fontFamily","high-contrast":nt(G)}]),id:"inlineTextInput-"+nt(i),"data-item":x.value==="fontFamily"?`btn-${nt(i)}-input`:void 0,autocomplete:"off",ref_key:"inlineInput",ref:V},null,42,NN)),[[Ri,L.value]])])):vt("",!0),nt(d)?(ve(),Te("div",{key:3,class:"sd-dropdown-caret","data-item":`btn-${nt(i)||""}-toggle`,innerHTML:me.value,style:Sn({opacity:nt(g)?.6:1})},null,12,BN)):vt("",!0)],64)),Fe("div",zN,Ht(`${nt(y).ariaLabel} ${nt(s)?"selected":"unset"}`),1)],10,RN)],46,xN))}},X0=pn(VN,[["__scopeId","data-v-dbdea151"]]);Dt(),bn();var jN={class:"toolbar-separator",role:"separator","aria-label":"Toolbar separator"},UN={__name:"ToolbarSeparator",props:{active:{type:Boolean,default:!1}},emits:["command"],setup(e,{emit:t}){const{isHighContrastMode:n}=Gi(),r=()=>n.value?"#000":"var(--sd-ui-border, #dbdbdb)";return(o,i)=>(ve(),Te("div",jN,[Fe("div",{class:"separator-inner",style:Sn({backgroundColor:r()})},null,4)]))}},HN=pn(UN,[["__scopeId","data-v-cb82253a"]]);Dt(),bn();var $N={class:"overflow-menu"},GN={class:"overflow-menu-trigger"},WN={key:0,class:"overflow-menu_items",role:"group"},KN={__name:"OverflowMenu",props:{toolbarItem:{type:Object,required:!0},overflowItems:{type:Array,required:!0}},emits:["buttonClick","close"],setup(e,{emit:t}){const{proxy:n}=vr(),r=t,o=e,i=Ee(()=>o.toolbarItem.expand.value),s=re(!1),a=Ee(()=>({...o.toolbarItem,active:i.value})),l=()=>{r("buttonClick",o.toolbarItem)},c=({item:d,argument:h})=>{n.$toolbar.emitCommand({item:d,argument:h})},u=d=>{d.key==="Escape"&&i.value&&!s.value&&(d.preventDefault(),r("close"))};return Gn(()=>{document.addEventListener("keydown",u,!0)}),gr(()=>{document.removeEventListener("keydown",u,!0)}),(d,h)=>(ve(),Te("div",$N,[Fe("div",GN,[Kt(X0,{"toolbar-item":a.value,onButtonClick:l},null,8,["toolbar-item"])]),i.value?(ve(),Te("div",WN,[Kt(cm,{class:"superdoc-toolbar-overflow","toolbar-items":e.overflowItems,"from-overflow":"",onCommand:c,onDropdownUpdateShow:h[0]||(h[0]=g=>s.value=g)},null,8,["toolbar-items"])])):vt("",!0)]))}},qN=pn(KN,[["__scopeId","data-v-504ecd05"]]);Dt(),bn();var YN={class:"toolbar-dropdown"},XN=["onClick"],ZN={key:0,class:"toolbar-dropdown-option__icon"},QN={class:"toolbar-dropdown-option__label"},sm='button, [href], input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])',JN={__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=re(null),i=re(null),s=re({top:"0px",left:"0px",maxHeight:"none"}),a=re([]),l=re(-1),c=Ee(()=>!!n.show),u=Ee(()=>n.options.some(oe=>oe?.type==="render")),d=Ee(()=>typeof n.menuProps!="function"?{}:n.menuProps()||{}),h=Ee(()=>{const{class:oe,style:Me,...Ge}=d.value;return Ge}),g=Ee(()=>["toolbar-dropdown-menu",d.value.class,{"toolbar-dropdown-menu--render-only":n.options.length>0&&n.options.every(oe=>oe&&oe.type==="render")}]),p=Ee(()=>{const oe=d.value.style||{};return{...n.contentStyle,...oe}}),v=Ee(()=>({...p.value,position:"fixed",top:s.value.top,left:s.value.left,maxHeight:s.value.maxHeight,zIndex:2e3})),S=oe=>{r("update:show",oe)},C=()=>{c.value&&S(!1)},A=()=>{if(!o.value)return;const oe=o.value.getBoundingClientRect(),Me=i.value,Ge=Me?.offsetWidth??0,lt=Me?.scrollHeight??Me?.offsetHeight??0,Ct=window.innerWidth||document.documentElement.clientWidth||0,Re=window.innerHeight||document.documentElement.clientHeight||0,Ke=8,tt=4,ee=oe.bottom+tt,_=oe.top-tt,te=Math.max(0,Re-ee-Ke),D=Math.max(0,_-Ke),U=te<lt&&D>te,$=U?D:te,H=U?Math.max(Ke,_-(lt?Math.min(lt,$):$)):ee;let J=oe.left;n.placement==="bottom-end"&&(J=oe.right-Ge);const X=Math.max(Ke,Ct-Ge-Ke);J=Math.min(Math.max(Ke,J),X),s.value={top:`${H}px`,left:`${J}px`,maxHeight:`${$}px`}},y=()=>{n.disabled||S(!c.value)},w=oe=>typeof n.nodeProps!="function"?{}:n.nodeProps(oe)||{},x=oe=>{oe?.disabled||oe?.type!=="render"&&(r("select",oe?.key,oe),C())},L=oe=>oe?.type==="render",V=oe=>!oe?.disabled&&oe?.type!=="render",G=oe=>typeof oe?.icon=="function"||!!oe?.icon,R=oe=>typeof oe?.icon=="function"?oe.icon(oe):oe?.icon||null,F=oe=>oe?typeof oe=="string"?oe.split(/\s+/).includes("sd-selected"):Array.isArray(oe)?oe.some(F):typeof oe=="object"?!!oe["sd-selected"]:!1:!1,Z=oe=>F(oe?.props?.class)||F(oe?.class),O=()=>n.options.map((oe,Me)=>V(oe)?Me:-1).filter(oe=>oe>=0),N=()=>{const oe=n.options.findIndex(Me=>V(Me)&&Z(Me));return oe>=0?oe:O()[0]??-1},T=(oe,Me)=>{if(!oe){delete a.value[Me];return}a.value[Me]=oe},B=()=>{a.value.forEach((Me,Ge)=>{Me&&Me.setAttribute("tabindex",Ge===l.value?"0":"-1")});const oe=a.value[l.value];oe&&typeof oe.focus=="function"&&(oe.focus(),oe.scrollIntoView?.({block:"nearest",inline:"nearest"}))},Q=oe=>{const Me=O();if(!Me.length){l.value=-1;return}const Ge=Me.indexOf(l.value);if(Ge<0){l.value=oe>0?Me[0]:Me[Me.length-1];return}const lt=(Ge+oe+Me.length)%Me.length;l.value=Me[lt]},q=()=>{let oe=n.options[l.value];if(!V(oe)){const Me=O()[0];oe=Me===void 0?null:n.options[Me]}oe&&x(oe)},se=Ml({name:"ToolbarDropdownRenderOption",props:{option:{type:Object,required:!0}},setup(oe){return()=>typeof oe.option.render!="function"?null:oe.option.render()}}),he=Ml({name:"ToolbarDropdownOptionIcon",props:{option:{type:Object,required:!0}},setup(oe){return()=>R(oe.option)}}),Ne=oe=>{if(!c.value)return;const Me=oe.target;if(!(Me instanceof Element))return;const Ge=o.value?.contains(Me),lt=i.value?.contains(Me);Ge||lt||C()},pe=re(null),ye=()=>{const oe=o.value,Me=document.activeElement;if(oe&&Me instanceof HTMLElement&&oe.contains(Me)){pe.value=Me;return}pe.value=oe?.matches?.(sm)?oe:oe?.querySelector(sm)},me=()=>{const oe=pe.value;if(oe instanceof HTMLElement&&document.contains(oe)){oe.focus();return}const Me=o.value;if(!Me)return;const Ge=Me.matches?.(sm)?Me:Me.querySelector(sm);if(Ge instanceof HTMLElement){Ge.focus();return}Me.setAttribute("tabindex","-1"),Me.focus()},_e=oe=>{if(!c.value)return;const{key:Me}=oe;if(["Escape","ArrowDown","ArrowUp","Enter"].includes(Me)){if(Me==="Escape"){oe.preventDefault(),C(),Tt(()=>{requestAnimationFrame(me)});return}if(!u.value){if(oe.preventDefault(),Me==="ArrowDown"){Q(1),B();return}if(Me==="ArrowUp"){Q(-1),B();return}Me==="Enter"&&q()}}};return Vt(c,async oe=>{if(!oe){l.value=-1,a.value=[];return}ye(),await Tt(),A(),!u.value&&(l.value=N(),await Tt(),B())},{immediate:!0}),Vt(c,oe=>{oe?(document.addEventListener("pointerdown",Ne,!0),document.addEventListener("keydown",_e,!0),window.addEventListener("resize",A),window.addEventListener("scroll",A,!0)):(document.removeEventListener("pointerdown",Ne,!0),document.removeEventListener("keydown",_e,!0),window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0))},{immediate:!0}),gr(()=>{document.removeEventListener("pointerdown",Ne,!0),document.removeEventListener("keydown",_e,!0),window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0)}),(oe,Me)=>(ve(),Te("div",YN,[Fe("div",{ref_key:"triggerRef",ref:o,class:"toolbar-dropdown-trigger","data-sd-part":"dropdown-trigger",onClick:y},[Td(oe.$slots,"trigger",{},void 0,!0)],512),(ve(),hn(Ha,{to:"body"},[Kt(qh,{name:"fade-in-scale-up-transition"},{default:No(()=>[c.value?(ve(),Te("div",us({key:0,ref_key:"menuRef",ref:i,"data-sd-part":"dropdown-menu",class:g.value,style:v.value},h.value),[(ve(!0),Te(Yt,null,mr(e.options,(Ge,lt)=>(ve(),Te("div",us({key:Ge.key,ref_for:!0,ref:Ct=>T(Ct,lt),class:["toolbar-dropdown-option",[Ge.class,Ge.props?.class,{"sd-disabled":Ge.disabled,"sd-render":L(Ge)}]],tabindex:"-1",onClick:Ct=>x(Ge)},{ref_for:!0},{...Ge.props,...w(Ge)}),[L(Ge)?(ve(),hn(nt(se),{key:0,option:Ge},null,8,["option"])):(ve(),Te(Yt,{key:1},[G(Ge)?(ve(),Te("span",ZN,[Kt(nt(he),{option:Ge},null,8,["option"])])):vt("",!0),Fe("span",QN,Ht(Ge.label),1)],64))],16,XN))),128))],16)):vt("",!0)]),_:1})]))]))}},eB=pn(JN,[["__scopeId","data-v-fef410f7"]]),W4=e=>String(e??"").trim().toLowerCase(),am=(e,t)=>{const n=W4(e);if(!n)return-1;for(let r=0;r<t.length;r+=1)if(W4(t[r]).startsWith(n))return r;return-1},tB=(e,t,{autocomplete:n=!0}={})=>{const r=String(e??""),o=am(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}},nB=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},rB=e=>e<=31||e===127,oB=e=>e===32||e===160||e===65279,iB=e=>Array.from(String(e)).filter(t=>!rB(t.charCodeAt(0))).join(""),sB=e=>{let t="",n=!1;for(const r of String(e)){if(oB(r.charCodeAt(0))){n=t.length>0;continue}n&&(t+=" "),n=!1,t+=r}return t},aB=e=>{const t=String(e??"").split(",")[0]??"",n=iB(t);return sB(nB(n)).trim()},lB=1,cB=1638,uB=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<lB?"":String(Math.min(r,cB))};Dt(),bn();var dB=["data-item"],fB=["id","value","disabled","aria-label","aria-expanded","aria-controls","aria-activedescendant","data-item"],hB=["data-item","aria-label","disabled"],pB=["innerHTML"],mB=["id","aria-label"],gB=["id","aria-selected","aria-label","onMousedown","onMouseenter"],vB={class:"toolbar-dropdown-option__label"},yB={class:"sd-button-label sd-font-combobox__legacy-label","aria-hidden":"true"},bB={__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}=Gi(),i=re(null),s=re(null),a=re(null),l=re([]),c=re(!1),u=re(!1),d=re(-1),h=re(""),g=re(""),p=re(!1),v=re({top:"0px",left:"0px",minWidth:"0px",maxHeight:"none"}),S=Ee(()=>n.item.nestedOptions?.value??[]),C=Ee(()=>S.value.map(X=>String(X?.label??""))),A=Ee(()=>String(n.item.label?.value??"")),y=Ee(()=>!!n.item.disabled?.value),w=Ee(()=>String(n.item.name?.value??"")),x=Ee(()=>n.item.attributes?.value?.ariaLabel??"Font family"),L=Ee(()=>c.value?g.value:A.value),V=Ee(()=>`sd-${w.value||"combobox"}-listbox-${n.item.id?.value??"default"}`),G=X=>`${V.value}-option-${X}`,R=Ee(()=>u.value&&d.value>=0?G(d.value):void 0),F=Ee(()=>u.value?fr.dropdownCaretUp:fr.dropdownCaretDown),Z=X=>{const W=String(X??"").trim().toLowerCase();return S.value.find(we=>String(we?.label??"").trim().toLowerCase()===W)?.props?.style?.fontFamily||X||n.uiFontFamily},O=Ee(()=>n.showPreview?{fontFamily:Z(c.value?g.value:A.value)}:{fontFamily:n.uiFontFamily}),N=()=>{const X=n.item.selectedValue?.value;if(X){const W=S.value.findIndex(we=>we?.key===X);if(W>=0)return W}return C.value.findIndex(W=>W.toLowerCase()===A.value.toLowerCase())},T=(X,W)=>{const we=i.value;if(!(!we||typeof we.setSelectionRange!="function"))try{we.setSelectionRange(X,W)}catch{}},B=()=>{l.value[d.value]?.scrollIntoView?.({block:"nearest",inline:"nearest"})},Q=()=>{l.value[d.value]?.focus?.()},q=()=>{const X=s.value;if(!X)return;const W=X.getBoundingClientRect(),we=a.value,ge=we?.scrollHeight??we?.offsetHeight??0,be=window.innerHeight||document.documentElement.clientHeight||0,Be=window.innerWidth||document.documentElement.clientWidth||0,Ze=8,it=4,yt=W.bottom+it,Xt=W.top-it,xt=Math.max(0,be-yt-Ze),Ft=Math.max(0,Xt-Ze),Ut=xt<ge&&Ft>xt,mn=Ut?Ft:xt,It=Ut?Math.max(Ze,Xt-(ge?Math.min(ge,mn):mn)):yt,Zt=Math.min(Math.max(Ze,W.left),Math.max(Ze,Be-W.width-Ze));v.value={top:`${It}px`,left:`${Zt}px`,minWidth:`${W.width}px`,maxHeight:`${mn}px`}},se=Ee(()=>({position:"fixed",top:v.value.top,left:v.value.left,minWidth:v.value.minWidth,maxHeight:v.value.maxHeight,fontFamily:n.uiFontFamily,zIndex:2e3})),he=X=>{n.item.expand&&typeof n.item.expand=="object"&&"value"in n.item.expand&&(n.item.expand.value=X)},Ne=(X,{focusInput:W=!1,focusOption:we=!1}={})=>{if(y.value||!S.value.length){he(!1);return}u.value=!0,he(!0),d.value=X??-1,W&&(c.value=!0,g.value=A.value,i.value?.focus()),Tt(()=>{q(),B(),we&&Q()})},pe=({syncItem:X=!0}={})=>{u.value=!1,d.value=-1,X&&he(!1)},ye=()=>{pe(),c.value=!1,h.value="",g.value=A.value},me=()=>{y.value||(u.value||r("item-clicked"),c.value=!0,h.value="",g.value=A.value,Tt(()=>T(0,g.value.length)))},_e=X=>{if(y.value)return;const W=document.activeElement===i.value;if(r("item-clicked"),c.value=!0,W||(h.value="",g.value=A.value,X.preventDefault(),i.value?.focus({preventScroll:!0}),T(0,A.value.length)),!u.value){const we=N();Ne(we>=0?we:0)}},oe=X=>{const W=X.relatedTarget;W instanceof Node&&s.value?.contains(W)||W instanceof Node&&a.value?.contains(W)||ye()},Me=X=>{if(p.value)return;const W=X.target,we=W.value,ge=typeof W.selectionStart=="number"?W.selectionStart:we.length,be=typeof W.selectionEnd=="number"?W.selectionEnd:ge,Be=typeof X.inputType=="string"&&X.inputType.startsWith("delete"),Ze=ge===we.length&&be===we.length;h.value=we;const it=tB(we,C.value,{autocomplete:!Be&&Ze});g.value=it.display,W.value=it.display,it.display===we&&!Ze?T(ge,be):T(it.selectionStart,it.selectionEnd),u.value&&(d.value=it.matchIndex,Tt(B))},Ge=X=>{p.value=!1,Me(X)},lt=X=>{if(!S.value.length)return;const W=S.value.length,we=d.value<0?X>0?-1:0:d.value;d.value=(we+X+W)%W,Tt(B)},Ct=(X,W)=>{r("item-clicked"),r("command",{item:n.item,argument:X,option:W}),W&&(n.item.selectedValue.value=W.key)},Re=X=>{X&&(Ct(X.label,X),c.value=!1,h.value="",g.value=X.label,pe())},Ke=()=>{if(u.value&&d.value>=0)return Re(S.value[d.value]),!0;const X=am(h.value,C.value);if(X>=0)return Re(S.value[X]),!0;const W=n.normalizeValue(h.value);return W?(Ct(W,null),c.value=!1,h.value="",g.value=W,pe(),!0):!1},tt=X=>{if(!(X.isComposing||p.value||X.keyCode===229)&&!(X.ctrlKey||X.metaKey||X.altKey))switch(X.key){case"ArrowDown":if(X.preventDefault(),u.value)Q();else{const W=am(h.value,C.value),we=W>=0?W:N();Ne(we>=0?we:0,{focusOption:!0})}break;case"ArrowUp":if(X.preventDefault(),u.value)Q();else{const W=am(h.value,C.value),we=W>=0?W:N();Ne(we>=0?we:S.value.length-1,{focusOption:!0})}break;case"Enter":X.preventDefault(),Ke()&&r("editor-handoff"),i.value?.blur();break;case"Tab":X.preventDefault(),Ke(),pe(),i.value?.blur(),r("tab-out",X);break;case"Escape":X.preventDefault(),ye(),Tt(()=>i.value?.focus());break;default:break}},ee=X=>{if(X.preventDefault(),!y.value)if(r("item-clicked"),u.value)pe(),i.value?.focus();else{const W=N();Ne(W>=0?W:0,{focusOption:!0})}},_=(X,W)=>{X.preventDefault(),Re(W),r("editor-handoff"),i.value?.blur()},te=X=>{d.value=X},D=X=>{if(!(X.ctrlKey||X.metaKey||X.altKey))switch(X.key){case"ArrowDown":X.preventDefault(),lt(1),Q();break;case"ArrowUp":X.preventDefault(),lt(-1),Q();break;case"Enter":X.preventDefault(),d.value>=0&&(Re(S.value[d.value]),r("editor-handoff"));break;case"Escape":X.preventDefault(),ye(),Tt(()=>i.value?.focus());break;case"Tab":X.preventDefault(),d.value>=0?Re(S.value[d.value]):pe(),r("tab-out",{shiftKey:X.shiftKey,target:i.value});break;default:break}},U=X=>{if(!u.value)return;const W=X.target;W instanceof Element&&(s.value?.contains(W)||a.value?.contains(W)||ye())};Vt(u,X=>{X?(document.addEventListener("pointerdown",U,!0),window.addEventListener("resize",q),window.addEventListener("scroll",q,!0)):(document.removeEventListener("pointerdown",U,!0),window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),l.value=[])},{immediate:!0}),gr(()=>{document.removeEventListener("pointerdown",U,!0),window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0)});const $=(X,W)=>{if(!X){delete l.value[W];return}l.value[W]=X},H=X=>X===d.value,J=X=>X?.key&&X.key===n.item.selectedValue?.value;return Vt(A,X=>{c.value||(g.value=X)}),Vt(()=>!!n.item.expand?.value,X=>{if(X&&!u.value){const W=N();Ne(W>=0?W:0,{focusInput:!0});return}!X&&u.value&&pe({syncItem:!1})}),(X,W)=>(ve(),Te("div",{ref_key:"rootRef",ref:s,class:on(["sd-font-combobox sd-toolbar-split-field",{"sd-disabled":y.value,"high-contrast":nt(o)}]),style:Sn(n.item.style?.value),"data-item":`btn-${w.value}`},[Fe("span",{class:"sd-font-combobox__field sd-toolbar-split-field__main",onMousedown:_e},[Fe("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:L.value,style:Sn(O.value),disabled:y.value,"aria-label":x.value,"aria-expanded":u.value?"true":"false","aria-controls":V.value,"aria-activedescendant":R.value,"aria-haspopup":"listbox","aria-autocomplete":"both","data-item":`btn-${w.value}-input`,onFocus:me,onBlur:oe,onInput:Me,onKeydown:tt,onCompositionstart:W[0]||(W[0]=we=>p.value=!0),onCompositionend:Ge},null,44,fB)],32),Fe("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:ee},[Fe("span",{class:"sd-dropdown-caret",innerHTML:F.value},null,8,pB)],40,hB),(ve(),hn(Ha,{to:"body"},[u.value?(ve(),Te("div",{key:0,ref_key:"popupRef",ref:a,role:"listbox",id:V.value,"aria-label":x.value,class:on(["sd-font-combobox__listbox",{"high-contrast":nt(o)}]),style:Sn(se.value)},[(ve(!0),Te(Yt,null,mr(S.value,(we,ge)=>(ve(),Te("div",us({key:we.key,ref_for:!0,ref:be=>$(be,ge),id:G(ge),role:"option",tabindex:"-1",class:["toolbar-dropdown-option sd-font-combobox__option",{"sd-active":H(ge),"sd-selected":J(we)}],"aria-selected":J(we)?"true":"false","aria-label":`${x.value} - ${we.label}`},{ref_for:!0},we.props,{onMousedown:be=>_(be,we),onMouseenter:be=>te(ge),onKeydown:D}),[Fe("span",vB,Ht(we.label),1)],16,gB))),128))],14,mB)):vt("",!0)])),Fe("span",yB,Ht(A.value),1)],14,dB))}},K4=pn(bB,[["__scopeId","data-v-99070b63"]]);Dt();var wB={__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)=>(ve(),hn(K4,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!0,"normalize-value":nt(aB),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"]))}};Dt();var CB={__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)=>(ve(),hn(K4,{item:n.item,"ui-font-family":n.uiFontFamily,"show-preview":!1,"normalize-value":nt(uB),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"]))}};Dt(),bn();var kB=2500,SB=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=W1(),r=re(!1),o=re(null),i=re(null),s=re({top:"0px",left:"0px"});let a=null,l=null,c=null;const u=Ee(()=>["sd-tooltip-content",n.class]),d=Ee(()=>({...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=()=>{c&&(window.clearTimeout(c),c=null)},v=()=>{p(),c=window.setTimeout(()=>{c=null,A()},kB)},S=()=>{if(!o.value||!i.value)return;const F=o.value.getBoundingClientRect(),Z=i.value.offsetWidth,O=i.value.offsetHeight,N=window.innerWidth||document.documentElement.clientWidth||0,T=8;let B=F.left+F.width/2-Z/2;B=Math.max(T,Math.min(B,N-Z-T)),s.value={top:`${F.top-O-10}px`,left:`${B}px`}},C=async()=>{t.disabled||(h(),g(),!r.value&&(r.value=!0,v(),await Tt(),S()))},A=()=>{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){A();return}a=window.setTimeout(()=>{a=null,A()},t.duration)}},x=()=>{t.trigger==="hover"&&y()},L=()=>{t.trigger==="hover"&&w()},V=()=>{g(),h()},G=()=>{w()},R=F=>{F.key==="Escape"&&A()};return Vt(()=>t.disabled,F=>{F&&A()}),Vt(r,F=>{F?(window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),document.addEventListener("keydown",R,!0)):(window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0),document.removeEventListener("keydown",R,!0))}),gr(()=>{g(),h(),p(),window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0),document.removeEventListener("keydown",R,!0)}),(F,Z)=>(ve(),Te(Yt,null,[Fe("span",{ref_key:"triggerRef",ref:o,class:"sd-tooltip-trigger",onMouseenter:x,onMouseleave:L,onFocusin:x,onFocusout:L},[Td(F.$slots,"trigger",{},void 0,!0)],544),(ve(),hn(Ha,{to:"body"},[Kt(qh,{name:"fade-in-scale-up-transition"},{default:No(()=>[r.value&&!e.disabled?(ve(),Te("div",{key:0,ref_key:"contentRef",ref:i,class:on(u.value),style:Sn(d.value),onMouseenter:V,onMouseleave:G},[Z[0]||(Z[0]=Fe("span",{class:"sd-tooltip-arrow","aria-hidden":"true"},null,-1)),Td(F.$slots,"default",{},void 0,!0)],38)):vt("",!0)]),_:3})]))],64))}}),lm=pn(SB,[["__scopeId","data-v-2a872eae"]]),bu=(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})};Dt(),bn();var _B=["onKeydown","tabindex","data-item-id"],AB={key:0},IB={key:0},EB={key:0},TB={key:0},xB={key:0},RB={__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}=vr(),o=re([]),i=re(null),s=e,a=re(null),{isHighContrastMode:l}=Gi(),c=window.matchMedia("(max-width: 768px)").matches,u=Ee(()=>s.position==="left"?{minWidth:s.compactSideGroups?"auto":"120px",justifyContent:"flex-start"}:s.position==="right"?{minWidth:s.compactSideGroups?"auto":"120px",justifyContent:"flex-end"}:{flexGrow:c?0:1,justifyContent:"center"}),d=Re=>Re.type==="button",h=Re=>Re.type==="dropdown",g=Re=>Re.type==="dropdown"&&Re.name?.value==="fontFamily",p=Re=>Re.type==="dropdown"&&Re.name?.value==="fontSize",v=Re=>Re.type==="separator",S=Re=>Re.type==="overflow",C=Re=>!!Re.nestedOptions?.value?.length,A=Re=>{if(!Re)return!1;const Ke=Re.expand;return typeof Ke=="object"&&Ke!==null&&"value"in Ke?!!Ke.value:!!Ke},y=(Re,Ke)=>{Re?.expand&&(Re.expand.value=Ke)},w=(Re,Ke=void 0)=>{if(Re.disabled.value)return;if(S(Re)){const ee=!A(Re);ee&&V(),y(Re,ee),a.value=ee?Re:null,n("item-clicked");return}if(h(Re))return;a.value&&h(a.value)&&A(a.value)&&V(),n("item-clicked");const tt=Ke!==void 0?Ke:Re.argument?.value;n("command",tt===void 0?{item:Re}:{item:Re,argument:tt})},x=(Re,Ke)=>{Re.disabled.value||(a.value=null,n("command",{item:Re,argument:Ke}))},L=Re=>{if(Re.disabled.value)return;V();const Ke=Re.splitButtonCommand,tt=Re.command,ee=Ke||tt;if(!ee)return;const _={...Re,command:ee};n("item-clicked"),n("command",{item:_})},V=()=>{const Re=r?.$toolbar?.toolbarItems||[],Ke=r?.$toolbar?.overflowItems||[],tt=[...Re,...Ke];(tt.length?tt:s.toolbarItems).forEach(ee=>{const _=S(ee)&&!s.fromOverflow;(h(ee)||_)&&y(ee,!1)}),a.value=null},G=(Re,Ke)=>{V();const tt=Re.dropdownValueKey.value?Ke[Re.dropdownValueKey.value]:Ke.label;n("command",{item:Re,argument:tt,option:Ke}),Re.selectedValue.value=Ke.key,Re.restoreEditorFocus&&bu(r?.$toolbar)},R=Re=>{n("command",Re)},F=()=>{V(),n("item-clicked")},Z=()=>{const Re=document.querySelector('[role="textbox"][aria-label*="SuperDoc body"], .ProseMirror');return Re instanceof HTMLElement?(Re.focus({preventScroll:!0}),!0):!1},O=()=>{const Re=r?.$toolbar?.pendingSelectionCapture,Ke=()=>{Re&&typeof r?.$toolbar?.ui?.selection?.restore=="function"&&r.$toolbar.ui.selection.restore(Re)};if(Z()){Ke();return}typeof r?.$toolbar?.superdoc?.focus=="function"&&(r.$toolbar.superdoc.focus(),Ke())},N=Re=>!(Re instanceof HTMLElement)||Re.classList.contains("sd-disabled")?null:Re.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")||Re.querySelector('button:not([disabled]), [role="button"]:not(.sd-disabled), [tabindex]:not([tabindex="-1"])'),T=(Re,Ke)=>{const tt=Re?.target?.closest?.(".sd-toolbar-item-ctn");if(!(tt instanceof HTMLElement))return!1;let ee=Ke>0?tt.nextElementSibling:tt.previousElementSibling;for(;ee;){const _=N(ee);if(_ instanceof HTMLElement)return tt.setAttribute("tabindex","-1"),ee.setAttribute("tabindex","0"),_.focus(),!0;ee=Ke>0?ee.nextElementSibling:ee.previousElementSibling}return!1},B=Re=>{V();const Ke=Re?.shiftKey?-1:1;T(Re,Ke)||O()},Q=Re=>{if(V(),Re?.shiftKey){T(Re,-1)||O();return}O()},q=()=>{O()},se=Re=>Re.nestedOptions?.value?.length?Re.nestedOptions.value.map(Ke=>{const tt=Ke?.type!=="render"&&Re.selectedValue.value===Ke.key;return{...Ke,props:{...Ke.props,class:tt?"sd-selected":""}}}):[],he=(Re,Ke)=>({role:"menuitem",ariaLabel:`${Ke.attributes.value.ariaLabel} - ${Re.label}`}),Ne=Re=>{const Ke=Re.target,tt=Re.target.closest(".sd-toolbar-item-ctn").nextElementSibling;tt&&(Ke.setAttribute("tabindex","-1"),tt.setAttribute("tabindex","0"),tt.focus())},pe=Re=>{const Ke=Re.target,tt=Re.target.closest(".sd-toolbar-item-ctn").previousElementSibling;tt&&(Ke.setAttribute("tabindex","-1"),tt.setAttribute("tabindex","0"),tt.focus())},ye=Re=>{const Ke=Re.target.closest(".button-group").nextElementSibling;if(Ke)Ke.setAttribute("tabindex","0"),Ke.focus();else{const tt=document.querySelector(".ProseMirror");tt&&tt.focus()}},me=Re=>{const Ke=Re.target.closest(".button-group").previousElementSibling;Ke&&(Ke.setAttribute("tabindex","0"),Ke.focus())},_e=Re=>{if(!Re.disabled.value){if(h(Re)){Ge(!A(Re),Re);return}w(Re)}},oe=(Re,Ke)=>{const tt=Re.target.nodeName==="INPUT"||Re.target.nodeName==="TEXTAREA",ee=Ke.name.value==="fontSize"||Ke.name.value==="fontFamily";if(!(tt&&ee)&&["Enter"," ","Spacebar","Escape","ArrowRight","ArrowLeft","Tab"].includes(Re.key))switch(Re.preventDefault(),Re.key){case"Enter":case" ":case"Spacebar":_e(Ke);break;case"Escape":V();break;case"ArrowRight":V(),Ne(Re);break;case"ArrowLeft":V(),pe(Re);break;case"Tab":Re.shiftKey?me(Re):ye(Re);break;default:break}},Me=Re=>{const Ke=o.value.find(tt=>!tt.classList.contains("sd-disabled"));Ke&&(Ke.setAttribute("tabindex","0"),Ke.focus())},Ge=(Re,Ke)=>{if(n("item-clicked"),!Re){V(),n("dropdown-update-show",!1);return}V(),a.value=Ke,y(Ke,!0),n("dropdown-update-show",!0)},lt=Re=>{if(!a.value)return;const Ke=Re.target;Ke instanceof Element&&(Ke.closest(".sd-toolbar-dropdown-menu")||i.value?.contains(Ke)||V())};return Vt(()=>A(a.value),Re=>{Re?document.addEventListener("pointerdown",lt,!0):document.removeEventListener("pointerdown",lt,!0)},{immediate:!0}),gr(()=>{document.removeEventListener("pointerdown",lt,!0)}),(Re,Ke)=>(ve(),Te("div",{style:Sn(u.value),class:"button-group",role:"group",onFocus:Me,ref_key:"buttonGroupRef",ref:i},[(ve(!0),Te(Yt,null,mr(e.toolbarItems,(tt,ee)=>(ve(),Te("div",{key:tt.id.value,class:on([{narrow:tt.isNarrow.value,wide:tt.isWide.value,"sd-disabled":tt.disabled.value},"sd-toolbar-item-ctn"]),onKeydown:_=>oe(_,tt),ref_for:!0,ref_key:"toolbarItemRefs",ref:o,tabindex:ee===0?0:-1,"data-item-id":tt.id.value},[v(tt)?(ve(),hn(HN,{key:0,style:{width:"20px"}})):vt("",!0),g(tt)&&C(tt)?(ve(),hn(lm,{key:1,trigger:"hover",disabled:!tt.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:No(()=>[Kt(wB,{item:tt,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:R,onItemClicked:F,onTabOut:Ke[0]||(Ke[0]=_=>B(_)),onEditorHandoff:q},null,8,["item","ui-font-family"])]),default:No(()=>[Fe("div",null,[ji(Ht(tt.tooltip)+" ",1),tt.disabled.value?(ve(),Te("span",AB,"(disabled)")):vt("",!0)])]),_:2},1032,["disabled","content-style"])):p(tt)&&C(tt)?(ve(),hn(lm,{key:2,trigger:"hover",disabled:!tt.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:No(()=>[Kt(CB,{item:tt,"ui-font-family":s.uiFontFamily,class:"sd-toolbar-button sd-editor-toolbar-dropdown",onCommand:R,onItemClicked:F,onTabOut:Ke[1]||(Ke[1]=_=>Q(_)),onEditorHandoff:q},null,8,["item","ui-font-family"])]),default:No(()=>[Fe("div",null,[ji(Ht(tt.tooltip)+" ",1),tt.disabled.value?(ve(),Te("span",IB,"(disabled)")):vt("",!0)])]),_:2},1032,["disabled","content-style"])):h(tt)&&tt.nestedOptions?.value?.length?(ve(),hn(eB,{key:3,options:se(tt),disabled:tt.disabled.value,show:A(tt),"content-style":{fontFamily:s.uiFontFamily},placement:"bottom-start",class:"sd-toolbar-button sd-editor-toolbar-dropdown",onSelect:(_,te)=>G(tt,te),"onUpdate:show":_=>Ge(_,tt),style:Sn(tt.dropdownStyles.value),"menu-props":()=>({role:"menu",style:{fontFamily:s.uiFontFamily},class:["sd-toolbar-dropdown-menu",{"high-contrast":nt(l)}]}),"node-props":_=>he(_,tt)},{trigger:No(()=>[Kt(lm,{trigger:"hover",disabled:!tt.tooltip?.value,"content-style":{fontFamily:s.uiFontFamily}},{trigger:No(()=>[Kt(X0,{"toolbar-item":tt,disabled:tt.disabled.value,"allow-enter-propagation":!0,onTextSubmit:_=>x(tt,_),onMainClick:_=>L(tt)},null,8,["toolbar-item","disabled","onTextSubmit","onMainClick"])]),default:No(()=>[Fe("div",null,[ji(Ht(tt.tooltip)+" ",1),tt.disabled.value?(ve(),Te("span",EB,"(disabled)")):vt("",!0)])]),_:2},1032,["disabled","content-style"])]),_:2},1032,["options","disabled","show","content-style","onSelect","onUpdate:show","style","menu-props","node-props"])):d(tt)?(ve(),hn(lm,{key:4,trigger:"hover",class:"sd-editor-toolbar-tooltip","content-style":{fontFamily:s.uiFontFamily}},{trigger:No(()=>[Kt(X0,{"toolbar-item":tt,"is-overflow-item":e.fromOverflow,onTextSubmit:_=>x(tt,_),onButtonClick:_=>w(tt)},null,8,["toolbar-item","is-overflow-item","onTextSubmit","onButtonClick"])]),default:No(()=>[tt.tooltip?(ve(),Te("div",TB,[ji(Ht(tt.tooltip)+" ",1),tt.disabled.value?(ve(),Te("span",xB,"(disabled)")):vt("",!0)])):vt("",!0)]),_:2},1032,["content-style"])):vt("",!0),S(tt)&&e.overflowItems.length?(ve(),hn(qN,{key:5,"toolbar-item":tt,onButtonClick:_=>w(tt),"overflow-items":e.overflowItems,onClose:V},null,8,["toolbar-item","onButtonClick","overflow-items"])):vt("",!0)],42,_B))),128))],36))}},cm=pn(RB,[["__scopeId","data-v-2bc00f65"]]),MB=[["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"]],LB=MB.map(([e,t])=>({label:e,key:e,props:{style:{fontFamily:`${e}, ${t}`},"data-item":"btn-fontFamily-option"}}));function PB(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"}}))}var DB=[{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"}}],Ff={sm:768,md:1024,lg:1280,xl:1410},Z0={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"},q4={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"},Y4=Object.values(q4),ZH=[...new Set([...Object.values(Z0),...Y4])],OB=new Set(["link"]),QH=new Set(Object.keys(Z0).filter(e=>!OB.has(e)));Dt(),bn();var FB="Arial, Helvetica, sans-serif",NB={__name:"Toolbar",emits:["command","toggle","select"],setup(e,{emit:t}){const{proxy:n}=vr();let r=re(1);const o=re(0),i=re(!1);let s=null,a=null;const l=Ee(()=>{const G=n?.$toolbar?.config?.uiDisplayFallbackFont;return typeof G=="string"&&G.trim()?G.trim():FB}),c=n.$toolbar.config?.toolbarGroups?.includes("left"),u=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()<=Ff.lg},v=AN(async()=>{await n.$toolbar.onToolbarResize(),g(),r.value+=1},300),S=()=>{r.value+=1},C=()=>{o.value+=1};function A(){window.removeEventListener("resize",v),n.$toolbar.off?.("toolbar-items-changed",S),n.$toolbar.off?.("toolbar-state-change",C),s?.disconnect(),s=null}function y(){A(),window.addEventListener("resize",v),n.$toolbar.on?.("toolbar-items-changed",S),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()}Gn(y),Eg(y),Tg(A),gr(A);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})=>{L(),n.$toolbar.emitCommand({item:G,argument:R,option:F})},L=()=>{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?.()},V=G=>{w(),!G.target.closest('input, textarea, [contenteditable="true"]')&&G.preventDefault()};return(G,R)=>(ve(),Te("div",{class:"superdoc-toolbar",key:nt(r),role:"toolbar","aria-label":"Toolbar","data-sd-part":"toolbar","data-editor-ui-surface":"",onMousedown:V},[nt(c)?(ve(),hn(cm,{key:0,tabindex:"0","toolbar-items":h("left"),"overflow-items":nt(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"])):vt("",!0),Kt(cm,{tabindex:"0","toolbar-items":h("center"),"overflow-items":nt(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"]),nt(u)?(ve(),hn(cm,{key:1,tabindex:"0","toolbar-items":h("right"),"overflow-items":nt(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"])):vt("",!0)],32))}},BB=pn(NB,[["__scopeId","data-v-55b5af7a"]]),zB=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"}}};Dt();var Tn=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 "defaultLabel" - ${e.name}. "label" is the live label and is not a substitute for "defaultLabel".`);if(!e.name)throw new Error("Invalid toolbar item name - "+e.name);const t=re(is()),n=e.type,r=re(e.name),o=e.command,i=e.noArgumentCommand,s=re(e.icon),a=re(e.group||"center"),l=re(e.allowWithoutEditor),c=re(e.attributes||{}),u=e.disabled||!1,d=re(e.disabled),h=re(!1),g=re(!1),p=re(e.style),v=re(e.isNarrow),S=re(e.isWide),C=re(e.minWidth),A=re(e.suppressActiveHighlight||!1),y=re(e.argument),w=re(null),x=re(null),L=re(e.iconColor),V=re(e.hasCaret),G=re(!!e.splitButton),R=e.splitButtonCommand,F=!!e.restoreEditorFocus,Z=re(e.dropdownStyles),O=re(e.tooltip),N=re(e.tooltipVisible),T=re(e.tooltipTimeout),B=re(e.defaultLabel),Q=re(e.label),q=re(e.hideLabel),se=re(e.inlineTextInputVisible),he=re(e.hasInlineTextInput),Ne=re(e.markName),pe=re(e.labelAttr),ye=re(e.selectedValue),me=re(e.dropdownValueKey),_e=re(e.inputRef||null),oe=re([]);if(e.options){if(!Array.isArray(e.options))throw new Error("Invalid toolbar item options - "+e.options);let _=0;for(let te=0;te<e.options.length;te+=1){const D=e.options[te];(!D||typeof D!="object")&&(_+=1)}if(_)throw new Error(`Toolbar item options must all be objects - ${e.name}. ${_} row(s) are not, so this item is skipped.`);oe.value?.push(...e.options)}const Me=(_={},...te)=>{Re(_,...te),!A.value&&(h.value=!0)},Ge=()=>{Ke(),h.value=!1},lt=_=>{d.value=_},Ct=()=>{d.value=u},Re=e.onActivate||(()=>null),Ke=e.onDeactivate||(()=>null),tt=()=>{const _={};return Object.keys(ee).forEach(te=>{ee[te].value!==void 0&&(_[te]=ee[te].value)}),_},ee={id:t,name:r,type:n,command:o,noArgumentCommand:i,icon:s,tooltip:O,group:a,attributes:c,disabled:d,active:h,expand:g,nestedOptions:oe,style:p,isNarrow:v,isWide:S,minWidth:C,argument:y,parentItem:x,iconColor:L,hasCaret:V,splitButton:G,splitButtonCommand:R,dropdownStyles:Z,tooltipVisible:N,tooltipTimeout:T,defaultLabel:B,label:Q,hideLabel:q,inlineTextInputVisible:se,hasInlineTextInput:he,restoreEditorFocus:F,markName:Ne,labelAttr:pe,childItem:w,allowWithoutEditor:l,dropdownValueKey:me,selectedValue:ye,inputRef:_e};return{...ee,unref:tt,activate:Me,deactivate:Ge,setDisabled:lt,resetDisabled:Ct,onActivate:Re,onDeactivate:Ke}};Dt(),bn();var VB=["onClick","innerHTML","aria-label","onKeydown"],jB={__name:"AlignmentButtons",emits:["select"],setup(e,{emit:t}){const{isHighContrastMode:n}=Gi(),r=t,o=re([]),i=[{key:"left",ariaLabel:"Align left",icon:fr.alignLeft},{key:"center",ariaLabel:"Align center",icon:fr.alignCenter},{key:"right",ariaLabel:"Align right",icon:fr.alignRight},{key:"justify",ariaLabel:"Justify",icon:fr.alignJustify}],s=u=>{r("select",u)},a=u=>{if(u===o.value.length-1)return;const d=o.value[u+1];d&&(d.setAttribute("tabindex","0"),d.focus())},l=u=>{if(u===0)return;const d=o.value[u-1];d&&(d.setAttribute("tabindex","0"),d.focus())},c=(u,d)=>{switch(u.key){case"ArrowLeft":l(d);break;case"ArrowRight":a(d);break;case"Enter":s(i[d].key);break;default:break}};return Gn(()=>{const u=o.value[0];u&&(u.setAttribute("tabindex","0"),u.focus())}),(u,d)=>(ve(),Te("div",{class:on(["alignment-buttons",{"high-contrast":nt(n)}])},[(ve(),Te(Yt,null,mr(i,(h,g)=>Fe("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:rn(p=>c(p,g),["prevent"])},null,40,VB)),64))],2))}},UB=pn(jB,[["__scopeId","data-v-13e5f7a4"]]);Dt(),bn();var HB=["onClick","innerHTML","aria-label","onKeydown"],$B={__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}=Gi(),r=t,o=e,i=re([]),s=Ee(()=>({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())},c=d=>{if(d===0)return;const h=i.value[d-1];h&&(h.setAttribute("tabindex","0"),h.focus())},u=(d,h)=>{switch(d.key){case"ArrowLeft":c(h);break;case"ArrowRight":l(h);break;case"Enter":a(o.buttons[h].key);break;default:break}};return Gn(()=>{const d=i.value[0];d&&(d.setAttribute("tabindex","0"),d.focus())}),(d,h)=>(ve(),Te("div",{class:on(["style-buttons-list",{"high-contrast":nt(n)}])},[(ve(!0),Te(Yt,null,mr(o.buttons,(g,p)=>(ve(),Te("div",{key:g.key,class:on(["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:rn(v=>u(v,p),["prevent"])},null,46,HB))),128))],2))}},X4=pn($B,[["__scopeId","data-v-44f37ff6"]]),GB=[{key:"disc",icon:fr.bulletListDisc,ariaLabel:"Opaque circle"},{key:"circle",icon:fr.bulletListCircle,ariaLabel:"Outline circle"},{key:"square",icon:fr.bulletListSquare,ariaLabel:"Opaque square"}],WB=[{key:"decimal",icon:fr.numberedListDecimal,ariaLabel:"1. 2. 3."},{key:"decimal-paren",icon:fr.numberedListDecimalParen,ariaLabel:"1) 2) 3)"},{key:"upper-roman",icon:fr.numberedListUpperRoman,ariaLabel:"I. II. III."},{key:"lower-roman",icon:fr.numberedListLowerRoman,ariaLabel:"i. ii. iii."},{key:"upper-alpha",icon:fr.numberedListUpperAlpha,ariaLabel:"A. B. C."},{key:"upper-alpha-paren",icon:fr.numberedListUpperAlphaParen,ariaLabel:"A) B) C)"},{key:"lower-alpha",icon:fr.numberedListLowerAlpha,ariaLabel:"a. b. c."},{key:"lower-alpha-paren",icon:fr.numberedListLowerAlphaParen,ariaLabel:"a) b) c)"}];Dt(),bn();var KB=["onClick","onKeydown"],qB={class:"document-mode-column icon-column"},YB=["innerHTML"],XB={class:"document-mode-column text-column"},ZB={class:"document-mode-type"},QB={class:"document-mode-description"},JB={__name:"DocumentMode",props:{options:{type:Array}},emits:["select"],setup(e,{emit:t}){const n=t,r=re([]),{isHighContrastMode:o}=Gi(),i=e,s=u=>{n("select",u)},a=u=>{if(u===r.value.length-1)return;const d=r.value[u+1];d&&(d.setAttribute("tabindex","0"),d.focus())},l=u=>{if(u===0)return;const d=r.value[u-1];d&&(d.setAttribute("tabindex","0"),d.focus())},c=(u,d)=>{switch(u.key){case"ArrowDown":a(d);break;case"ArrowUp":l(d);break;case"Enter":s(i.options[d]);break;default:break}};return Gn(()=>{r.value[0].setAttribute("tabindex","0"),r.value[0].focus()}),(u,d)=>(ve(),Te("div",{class:on(["document-mode",{"high-contrast":nt(o)}])},[(ve(!0),Te(Yt,null,mr(e.options,(h,g)=>(ve(),Te("div",{class:on(["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:rn(p=>c(p,g),["prevent"])},[Fe("div",qB,[Fe("div",{class:"icon-column__icon",innerHTML:h.icon},null,8,YB)]),Fe("div",XB,[Fe("div",ZB,Ht(h.label),1),Fe("div",QB,Ht(h.description),1)])],42,KB))),256))],2))}},ez=pn(JB,[["__scopeId","data-v-bee14d7a"]]);Dt(),bn();var tz={class:"linked-style-buttons","data-editor-ui-surface":""},nz=["onClick","onKeydown","aria-label"],rz={__name:"LinkedStyle",props:{styles:{type:Array,default:()=>[]},selectedOption:{type:String,default:null}},emits:["select"],setup(e,{emit:t}){const n=t,r=re([]),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}},c=d=>d?.name??d?.id??"",u=d=>{const h=d?.preview?.css;return h&&typeof h=="object"?h:void 0};return Gn(()=>{r.value[0]&&(r.value[0].setAttribute("tabindex","0"),r.value[0].focus())}),(d,h)=>(ve(),Te("div",tz,[(ve(!0),Te(Yt,null,mr(o.styles,(g,p)=>(ve(),Te("div",{key:g.id??p,class:on(["style-item",{selected:e.selectedOption===g.id}]),onClick:v=>i(g),onKeydown:v=>l(v,p,g),"aria-label":`Linked style - ${g.id??c(g)}`,ref_for:!0,ref_key:"styleRefs",ref:r},[Fe("div",{class:"style-name","data-item":"btn-linkedStyles-option",style:Sn(u(g))},Ht(c(g)),5)],42,nz))),128))]))}},oz=pn(rz,[["__scopeId","data-v-43b5dcca"]]);Dt(),bn();var iz=["placeholder"],sz={class:"sd-ai-writer__footer"},az={key:0,class:"sd-ai-writer__error",role:"alert"},lz=["disabled"],cz="https://sd-dev-express-gateway-i6xtm.ondigitalocean.app/insights",uz="You are an expert copywriter and you are immersed in a document editor. Only write what is asked for.",dz={__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=re(""),r=re(!1),o=re(""),i=re(null),s=Ee(()=>t.selectedText?"Insert prompt to update text":"Insert prompt to generate text"),a=Ee(()=>n.value.trim().length>0&&!r.value);Gn(()=>{Tt(()=>{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 S=v[0];if(S&&typeof S.value=="string")return S.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 c(p){const v={"Content-Type":"application/json"};t.apiKey&&(v["x-api-key"]=t.apiKey);const S=t.selectedText.trim(),C=S?`Rewrite the following text: "${S}" using these instructions: ${p}`:`Generate text based on the following prompt: ${p}`,A=await fetch(t.endpoint||cz,{method:"POST",headers:v,body:JSON.stringify({stream:!1,context:uz,insights:[{type:"custom_prompt",name:S?"text_rewrite":"text_generation",message:C,format:[{value:""}]}]})});if(!A.ok){const w=await A.text().catch(()=>"");throw new Error(w||`AI request failed with ${A.status}`)}const y=l((A.headers.get("content-type")||"").includes("application/json")?await A.json():await A.text()).trim();if(!y)throw new Error("AI returned no text.");return y}function u(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 S=null,C=!1;if(t.selectedText&&t.target&&typeof v.replace=="function"?(S=v.replace({target:t.target,text:p}),C=!0):t.target&&typeof v.insert=="function"?(S=v.insert({target:t.target,value:p,type:"text"}),C=!0):typeof v.insert=="function"&&(S=v.insert({value:p,type:"text"}),C=!0),!C)throw new Error("Document text insertion is unavailable.");if(!u(S))throw new Error("Unable to insert generated text.")}async function h(){if(a.value){o.value="",r.value=!0;try{d(await c(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)=>(ve(),Te("form",{class:"sd-ai-writer","data-item":"ai-writer",onSubmit:rn(h,["prevent"])},[Ks(Fe("textarea",{ref_key:"textareaRef",ref:i,"onUpdate:modelValue":v[0]||(v[0]=S=>n.value=S),class:"sd-ai-writer__input",placeholder:s.value,rows:"4",onKeydown:g},null,40,iz),[[Ri,n.value]]),Fe("div",sz,[o.value?(ve(),Te("p",az,Ht(o.value),1)):vt("",!0),Fe("button",{class:"sd-ai-writer__submit",type:"submit",disabled:!a.value},Ht(r.value?"Generating":"Generate"),9,lz)])],32))}},fz=pn(dz,[["__scopeId","data-v-67f6c6f7"]]);Dt(),bn();var hz=["aria-label","onClick","onKeydown"],pz=["innerHTML"],mz=["innerHTML"],um=7,gz={__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=Ee(()=>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=re([]),l=re([]);Gn(()=>{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 c=(p,v)=>{const S=um*p+v+1,C=l.value[S];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},u=(p,v)=>{const S=um*p+v-1,C=l.value[S];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},d=(p,v)=>{const S=v+um*(p+1),C=l.value[S];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},h=(p,v)=>{const S=v+um*(p-1),C=l.value[S];C&&(C.setAttribute("tabindex","0"),C.focus({preventScroll:!0}))},g=(p,v,S,C)=>{switch(p.key){case"ArrowRight":c(v,S);break;case"ArrowLeft":u(v,S);break;case"ArrowDown":d(v,S);break;case"ArrowUp":h(v,S);break;case"Enter":s(C);break;case"Escape":n("clickoutside");break;default:break}};return(p,v)=>(ve(!0),Te(Yt,null,mr(e.icons,(S,C)=>(ve(),Te("div",{class:"sd-option-row",key:C,role:"group",ref_for:!0,ref_key:"rowRefs",ref:a},[(ve(!0),Te(Yt,null,mr(S,(A,y)=>(ve(),Te("div",{class:"sd-option",key:y,"aria-label":A.label,role:"menuitem",ref_for:!0,ref_key:"iconRefs",ref:l,onClick:rn(w=>s(A),["stop","prevent"]),onKeydown:rn(w=>g(w,C,y,A),["prevent"])},[Fe("div",{class:"sd-option__icon",innerHTML:A.icon,style:Sn(A.style)},null,12,pz),o.value(A)?(ve(),Te("div",{key:0,class:"sd-option__check",innerHTML:nt(fr).colorOptionCheck,style:Sn(i(A.value,y))},null,12,mz)):vt("",!0)],40,hz))),128))]))),128))}},Z4=pn(gz,[["__scopeId","data-v-05eb02fc"]]),vz=`<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
  `;Dt(),bn();var yz={class:"options-grid-wrap"},bz=["innerHTML"],wz={class:"option-grid-ctn"},Cz={__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)=>(ve(),Te("div",yz,[e.hasNoneIcon?(ve(),Te("div",{key:0,class:"none-option",role:"menuitem","aria-label":"Clear color selection",onClick:i[0]||(i[0]=s=>r("none"))},[Fe("span",{innerHTML:nt(vz),class:"none-icon"},null,8,bz),i[1]||(i[1]=ji(" None ",-1))])):vt("",!0),Fe("div",wz,[Kt(Z4,{icons:e.icons,"active-color":e.activeColor,onSelect:r},null,8,["icons","active-color"]),e.customIcons.flat().length?(ve(),Te(Yt,{key:0},[i[2]||(i[2]=Fe("span",{class:"option-grid-ctn__subtitle"},"Custom colors",-1)),Kt(Z4,{icons:e.customIcons,"active-color":e.activeColor,onSelect:r},null,8,["icons","active-color"])],64)):vt("",!0)])]))}},kz=pn(Cz,[["__scopeId","data-v-52b0283a"]]);Dt();var Sz=e=>{e.expand.value=!1},$t=(e,t=null)=>({label:t,icon:fr.colorOption,value:e,style:{color:e,boxShadow:"0 0 5px 1px rgba(0, 0, 0, 0.1)",borderRadius:"50%"}}),Q0=(e,t,n=[],r=!1)=>{const o=i=>{t.iconColor.value=i,e.emitCommand({item:t,argument:i}),Sz(t),bu(e)};return Kr("div",{},[Kr(kz,{icons:_z,customIcons:n,activeColor:t.iconColor,hasNoneIcon:r,onSelect:o})])},_z=[[$t("#111111","black"),$t("#333333","dark gray"),$t("#5C5C5C","medium gray"),$t("#858585","light gray"),$t("#ADADAD","very light gray"),$t("#D6D6D6","transparent gray"),$t("#FFFFFF","white")],[$t("#860028","dark red"),$t("#D2003F","red"),$t("#DB3365","coral red"),$t("#E4668C","light red"),$t("#ED99B2","pale pink"),$t("#F6CCD9","transparent pink"),$t("#FF004D","bright pink")],[$t("#83015E","dark purple"),$t("#CD0194","purple"),$t("#D734A9","orchid"),$t("#E167BF","light purple"),$t("#EB99D4","lavender"),$t("#F5CCEA","transparent pink"),$t("#FF00A8","neon pink")],[$t("#8E220A","maroon"),$t("#DD340F","red-orange"),$t("#E45C3F","burnt orange"),$t("#EB856F","peach"),$t("#F1AE9F","pale peach"),$t("#F8D6CF","transparent peach"),$t("#FF7A00","orange")],[$t("#947D02","olive"),$t("#E7C302","mustard yellow"),$t("#ECCF35","yellow"),$t("#F1DB67","light yellow"),$t("#F5E79A","very pale yellow"),$t("#FAF3CC","transparent yellow"),$t("#FAFF09","neon yellow")],[$t("#055432","forest green"),$t("#07834F","green"),$t("#399C72","medium green"),$t("#6AB595","light green"),$t("#9CCDB9","mint"),$t("#CDE6DC","transparent mint"),$t("#05F38F","bright teal")],[$t("#063E7E","navy blue"),$t("#0A60C5","blue"),$t("#3B80D1","sky blue"),$t("#6CA0DC","cornflower blue"),$t("#9DBFE8","light blue"),$t("#CEDFF3","very light blue"),$t("#21c8ce","cyan")],[$t("#3E027A","deep purple"),$t("#6103BF","indigo"),$t("#8136CC","violet"),$t("#A068D9","lavender pink"),$t("#C09AE6","light lilac"),$t("#DFCDF2","transparent lilac"),$t("#A91DFF","neon purple")]];Dt(),bn();var Az=["data-cols","data-rows","onKeydown","onClick"],Iz=["aria-valuetext"],dm=5,Ez={__name:"TableGrid",emits:["select","clickoutside"],setup(e,{emit:t}){const n=t,r=re(0),o=re(0),{isHighContrastMode:i}=Gi(),s=re([]),a=d=>{let h=d.target;if(h.dataset.grid)return;let g=[...h.parentElement.querySelectorAll("[data-item]")],p=parseInt(h.dataset.cols,10),v=parseInt(h.dataset.rows,10);l(g,p,v)},l=(d,h,g)=>{o.value=h,r.value=g;for(let p=0;p<d.length;p++){let v=d[p],S=parseInt(v.dataset.cols,10),C=parseInt(v.dataset.rows,10);S<=h&&C<=g?v.classList.add("sd-selected"):v.classList.remove("sd-selected")}},c=({cols:d,rows:h})=>{n("select",{cols:d,rows:h})},u=(d,h,g)=>{let p=h-1,v=g-1;switch(d.key){case"ArrowRight":{if(p>=4)return;const S=v*dm;s.value[S+p+1].setAttribute("tabindex","0"),s.value[S+p+1].focus(),l(s.value,h+1,g);break}case"ArrowLeft":{if(p<=0)return;const S=v*dm;s.value[S+p-1].setAttribute("tabindex","0"),s.value[S+p-1].focus(),l(s.value,h-1,g);break}case"ArrowDown":{if(v>=4)return;const S=(v+1)*dm;s.value[S+p].setAttribute("tabindex","0"),s.value[S+p].focus(),l(s.value,h,g+1);break}case"ArrowUp":{if(v<=0)return;const S=(v-1)*dm;s.value[S+p].setAttribute("tabindex","0"),s.value[S+p].focus(),l(s.value,h,g-1);break}case"Enter":c({cols:h,rows:g});break;default:break}};return Gn(()=>{s.value[0].setAttribute("tabindex","0"),s.value[0].focus(),l(s.value,1,1)}),(d,h)=>(ve(),Te("div",{class:on(["toolbar-table-grid-wrapper",{"high-contrast":nt(i)}])},[Fe("div",{class:"toolbar-table-grid",onMouseover:a,"data-grid":"true"},[(ve(),Te(Yt,null,mr(5,g=>(ve(),Te(Yt,{key:g},[(ve(),Te(Yt,null,mr(5,p=>Fe("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:rn(v=>u(v,p,g),["prevent"]),onClick:rn(v=>c({cols:p,rows:g}),["stop","prevent"])},null,40,Az)),64))],64))),64))],32),Fe("div",{class:"toolbar-table-grid-value","aria-valuetext":`${r.value} x ${o.value}`},Ht(r.value)+" x "+Ht(o.value),9,Iz)],2))}},Tz=pn(Ez,[["__scopeId","data-v-b87d6ca2"]]);Dt(),bn();var xz={class:"toolbar-table-actions"},Rz=["onClick","data-item","ariaLabel"],Mz={class:"toolbar-table-actions__icon"},Lz=["innerHTML"],Pz={class:"toolbar-table-actions__label"},Dz={__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)=>(ve(),Te("div",xz,[(ve(!0),Te(Yt,null,mr(e.options,s=>(ve(),Te("div",{class:on(["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"},[Fe("div",Mz,[Fe("div",{class:"toolbar-table-actions__icon-wrapper",innerHTML:s.icon},null,8,Lz)]),Fe("div",Pz,Ht(s.label),1)],10,Rz))),256))]))}},Oz=pn(Dz,[["__scopeId","data-v-0cdad084"]]),Fz=`<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
- `;Dt();var Ss=e=>{e.expand.value=!1};function J0(e,t){const n={...e??{}};return t?n.href=t:delete n.href,n}function Q4(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 Nz(e){return typeof e?.quotedText=="string"?e.quotedText:typeof e?.text=="string"?e.text:""}function J4(e){return e.ui?.selection?.get?.()??e.ui?.selection?.current?.()??null}function Bz(e){return!!(e.config?.superdoc?.config?.modules?.ai||e.superdoc?.config?.modules?.ai)}function zz(e){return e.config?.superdoc?.config?.modules?.ai??e.superdoc?.config?.modules?.ai??{}}var Vz=({superToolbar:e,toolbarIcons:t,toolbarTexts:n,toolbarFonts:r,hideButtons:o,availableWidth:i,role:s,isDev:a=!1}={})=>{const l=Tn({type:"button",name:"bold",command:"toggleBold",icon:t.bold,tooltip:n.bold,attributes:{ariaLabel:"Bold"}}),c=(r??LB).map(zB),u=Tn({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:c,onActivate:({fontFamily:rt}={},zt=!1)=>{if(zt){u.label.value="",u.selectedValue.value="";return}if(!rt)return;rt=rt.split(",")[0],u.label.value=rt;const Lt=c.find(Qt=>Qt.label===u.defaultLabel.value),An=c.find(Qt=>Qt.label===rt);An?u.selectedValue.value=An.key:Lt?u.selectedValue.value=Lt.key:u.selectedValue.value=""},onDeactivate:()=>{u.label.value=u.defaultLabel.value;const rt=c.find(zt=>zt.label===u.defaultLabel.value);rt?u.selectedValue.value=rt.key:u.selectedValue.value=""}}),d=Tn({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(rt){const zt=J4(e),Lt=zt?.selectionTarget??Q4(zt?.target),An=zt?.empty?"":Nz(zt),Qt=zz(e),wn=()=>Ss(rt),Wn=()=>{const go=e.pendingSelectionCapture;go&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(go)};return Kr("div",{},[Kr(fz,{handleClose:wn,selectedText:An,target:Lt,doc:e.superdoc?.activeEditor?.doc??null,apiKey:Qt?.apiKey||e.config?.aiApiKey||"",endpoint:Qt?.endpoint||e.config?.aiEndpoint||"",restoreSelection:Wn})])}const g=DB,p=Tn({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:rt},zt=!1)=>{if(zt){p.label.value="",p.selectedValue.value="";return}const Lt=g.find(Wn=>Wn.label===String(p.defaultLabel.value));if(!rt){p.label.value=p.defaultLabel.value,Lt?p.selectedValue.value=Lt.key:p.selectedValue.value="";return}let An=_N(rt,12);An<8&&(An=8),An>96&&(An=96);let Qt=String(An);const wn=g.find(Wn=>Wn.label===Qt||Wn.key===Qt);wn?p.selectedValue.value=wn.key:p.selectedValue.value="",p.label.value=Qt},onDeactivate:()=>{p.label.value=p.defaultLabel.value;const rt=g.find(zt=>zt.label===String(p.defaultLabel.value));rt?p.selectedValue.value=rt.key:p.selectedValue.value=""}}),v=Tn({type:"separator",name:"separator",isNarrow:!0}),S=Tn({type:"button",name:"italic",command:"toggleItalic",icon:t.italic,active:!1,tooltip:n.italic,attributes:{ariaLabel:"Italic"}}),C=Tn({type:"button",name:"underline",command:"toggleUnderline",icon:t.underline,active:!1,tooltip:n.underline,attributes:{ariaLabel:"Underline"}}),A=Tn({type:"button",name:"strike",command:"toggleStrike",icon:t.strikethrough,active:!1,tooltip:n.strikethrough,attributes:{ariaLabel:"Strikethrough"}}),y=Tn({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:()=>Q0(e,y,[],!0)}],onActivate:({color:rt})=>{y.iconColor.value=rt||""},onDeactivate:()=>y.iconColor.value=""}),w=Tn({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:()=>Q0(e,w)}],onActivate:({color:rt})=>{w.iconColor.value=rt},onDeactivate:()=>w.iconColor.value="#000"}),x=Tn({type:"button",name:"search",allowWithoutEditor:!0,active:!1,icon:t.search,tooltip:n.search,group:"right",attributes:{ariaLabel:"Search"}}),L=Tn({type:"dropdown",name:"link",markName:"link",icon:t.link,active:!1,tooltip:n.link,attributes:{ariaLabel:"Link dropdown"},options:[{type:"render",key:"linkDropdown",render:()=>V(L)}],onActivate:({href:rt})=>{L.attributes.value=J0(L.attributes.value,rt)},onDeactivate:()=>{L.attributes.value=J0(L.attributes.value,null),L.expand.value=!1}});function V(rt){const zt=J4(e),Lt=zt?.selectionTarget??Q4(zt?.target),An=()=>{const Qt=e.pendingSelectionCapture;Qt&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Qt)};return Kr("div",{},[Kr(SS,{ui:e.ui,linkItem:rt,textTarget:Lt,restoreSelection:An,closePopover:()=>{Ss(rt),bu(e)},goToAnchor:()=>{Ss(rt);const Qt=rt.attributes.value?.href;if(!Qt)return;const wn=Qt.slice(1),Wn=(e.ui?.viewport?.getHost?.()??null)?.querySelector?.(`a[name='${wn}']`);Wn&&mf(Wn)}})])}const G=Tn({type:"options",name:"linkInput",command:"toggleLink",active:!1});L.childItem=G,G.parentItem=L;const R=Tn({type:"button",name:"image",command:"startImageUpload",icon:t.image,active:!1,tooltip:n.image,disabled:!1,attributes:{ariaLabel:"Image"}}),F=Tn({type:"button",name:"tableOfContents",command:"insertTableOfContents",icon:t.tableOfContents,active:!1,tooltip:n.tableOfContents,disabled:!1,attributes:{ariaLabel:"Table of contents"}}),Z=Tn({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:()=>O(Z)}]});function O(rt){return Kr("div",{},[Kr(Tz,{onSelect:Lt=>{e.emitCommand({item:rt,argument:Lt}),Ss(rt),bu(e)}})])}const N=Tn({type:"dropdown",name:"tableActions",command:"executeTableCommand",tooltip:n.tableActions,icon:t.tableActions,hideLabel:!0,disabled:!0,attributes:{ariaLabel:"Table actions"},options:[{type:"render",render:()=>B(N)}]}),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 B(rt){return Kr(Oz,{options:T,onSelect:zt=>{Ss(rt);const{command:Lt}=zt;e.emitCommand({item:rt,argument:{command:Lt}})}})}const Q=Tn({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:()=>Kr("div",{},[Kr(UB,{onSelect:zt=>{Ss(Q);const Lt={...Q,command:"setTextAlign"};Lt.command="setTextAlign",e.emitCommand({item:Lt,argument:zt}),q(Q,zt),bu(e)}})]),key:"alignment"}],onActivate:({textAlign:rt})=>{q(Q,rt)},onDeactivate:()=>{q(Q,"left")}}),q=(rt,zt)=>{let Lt=zt==="both"?"justify":zt,An={left:t.alignLeft,right:t.alignRight,center:t.alignCenter,justify:t.alignJustify},Qt=An[Lt]??An.left;rt.icon.value=Qt},se=Tn({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 rt=zt=>{Ss(se);const Lt={...se,command:"toggleBulletListStyle"};e.emitCommand({item:Lt,argument:zt})};return Kr(X4,{buttons:GB,iconSize:25,selectedStyle:se.selectedValue.value,onSelect:rt})}}]}),he=Tn({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 rt=zt=>{Ss(he);const Lt={...he,command:"toggleOrderedListStyle"};e.emitCommand({item:Lt,argument:zt})};return Kr(X4,{buttons:WB,iconSize:30,selectedStyle:he.selectedValue.value,onSelect:rt})}}]}),Ne=Tn({type:"button",name:"indentleft",command:"decreaseTextIndent",icon:t.indentLeft,active:!1,tooltip:n.indentLeft,disabled:!1,attributes:{ariaLabel:"Left indent"}}),pe=Tn({type:"button",name:"indentright",command:"increaseTextIndent",icon:t.indentRight,active:!1,tooltip:n.indentRight,disabled:!1,attributes:{ariaLabel:"Right indent"}}),ye=Tn({type:"overflow",name:"overflow",command:null,icon:t.overflow,active:!1,disabled:!1,attributes:{ariaLabel:"Overflow items"}}),me=Tn({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:rt})=>{rt&&(me.label.value=rt)}}),_e=Tn({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:rt})=>{rt&&(_e.label.value=rt)}}),oe=Tn({type:"button",name:"undo",disabled:!0,tooltip:n.undo,command:"undo",icon:t.undo,group:"left",attributes:{ariaLabel:"Undo"}}),Me=Tn({type:"button",disabled:!0,name:"redo",tooltip:n.redo,command:"redo",icon:t.redo,group:"left",attributes:{ariaLabel:"Redo"}}),Ge=Tn({type:"button",disabled:!1,name:"acceptTrackedChangeBySelection",tooltip:n.trackChangesAccept,command:"acceptTrackedChangeFromToolbar",icon:t.trackChangesAccept,group:"left",attributes:{ariaLabel:"Accept tracked changes"}}),lt=Tn({type:"button",disabled:!1,name:"rejectTrackedChangeOnSelection",tooltip:n.trackChangesReject,command:"rejectTrackedChangeFromToolbar",icon:t.trackChangesReject,group:"left",attributes:{ariaLabel:"Reject tracked changes"}}),Ct=Tn({type:"button",name:"clearFormatting",command:"clearFormat",tooltip:n.clearFormatting,icon:t.clearFormatting,attributes:{ariaLabel:"Clear formatting"}}),Re=Tn({type:"button",name:"copyFormat",tooltip:n.copyFormat,icon:t.copyFormat,command:"copyFormat",active:!1,attributes:{ariaLabel:"Copy formatting"}}),Ke=(rt,zt)=>rt==="editor"?zt:rt==="suggester"?zt.filter(Lt=>Lt.value==="suggesting"):zt.filter(Lt=>Lt.value==="viewing"),tt=rt=>rt==="editor"?"Editing":rt==="suggester"?"Suggesting":"Viewing",ee=Tn({type:"dropdown",name:"documentMode",command:"setDocumentMode",allowWithoutEditor:!0,icon:t.documentMode,defaultLabel:tt(s),label:tt(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:()=>te(ee)}]}),_=[{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 te(rt){return Kr(ez,{options:Ke(s,_),onSelect:zt=>{const Lt=e.superdoc?.activeEditor??e.activeEditor;Ss(rt);const{label:An,icon:Qt,value:wn}=zt;ee.label.value=An,ee.icon.value=Qt,e.emitCommand({item:ee,argument:wn}),bu(e,Lt)}})}const D=new Map([["separator",20],["zoom",71],["measurementUnit",52],["fontFamily",118],["fontSize",57],["textAlign",40],["linkedStyles",142],["documentMode",47],["default",32]]),U=["search","ruler","undo","overflow","documentMode"],$=Tn({type:"button",name:"ruler",command:"toggleRuler",allowWithoutEditor:!0,icon:t.ruler,active:!1,tooltip:n.ruler,attributes:{ariaLabel:"Ruler"}}),H=Tn({type:"button",name:"formattingMarks",command:"toggleFormattingMarks",allowWithoutEditor:!0,icon:t.formattingMarks,active:!1,tooltip:n.formattingMarks,attributes:{ariaLabel:"Formatting marks"}}),J=Tn({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 rt=Lt=>{Ss(J);const An=typeof Lt=="string"?Lt:Lt?.id??null;if(!An)return;const Qt={...J,command:"setLinkedStyle"};e.emitCommand({item:Qt,argument:An})},zt=e.getActiveLinkedStyleId?.()??null;return Kr("div",{},[Kr(oz,{styles:e.getLinkedStyleOptions?.()??[],onSelect:rt,selectedOption:zt})])}}],onActivate:({styleId:rt,styleName:zt})=>{const Lt=zt||rt;J.label.value=rt&&rt!=="Normal"?String(Lt):n.formatText,J.disabled.value=!1},onDeactivate:()=>{J.disabled.value=!0,J.label.value=n.formatText}}),X=(rt,zt)=>{if(zt.value==rt)return Kr("div",{innerHTML:Fz,class:"dropdown-select-icon"})},W=Tn({type:"dropdown",name:"lineHeight",tooltip:n.lineHeight,icon:t.lineHeight,hasCaret:!1,hasInlineTextInput:!1,hideLabel:!0,inlineTextInputVisible:!1,suppressActiveHighlight:!0,restoreEditorFocus:!0,isWide:!1,command:"setLineHeight",dropdownValueKey:"key",selectedValue:"1",attributes:{ariaLabel:"Line height"},options:[1,1.15,1.5,2,2.5,3].map(rt=>({label:rt.toFixed(2),key:rt,icon:()=>X(rt,W.selectedValue),props:{"data-item":"btn-lineHeight-option"}}))}),we=20,ge=32,be=U.reduce((rt,zt)=>rt+(D.get(zt)||D.get("default")),0),Be=["linkedStyles","clearFormatting","copyFormat","formattingMarks"],Ze=["zoom","fontFamily","fontSize","redo"],it=i<=Ff.lg,yt=e.config?.showFormattingMarksButton===!0,Xt=e.config?.showTableOfContentsButton===!0;it&&(ee.attributes.value={...ee.attributes.value,className:`${ee.attributes.value.className} sd-toolbar-item--doc-mode-compact`}),it&&(J.attributes.value={...J.attributes.value,className:`${J.attributes.value.className} sd-toolbar-item--linked-styles-compact`});let xt=[oe,Me,Ge,lt,x,me,u,v,p,v,l,S,C,A,w,y,v,L,R,...Xt?[F]:[],Z,N,v,Q,se,he,Ne,pe,W,v,J,v,$,_e,...yt?[H]:[],Re,Ct,...Bz(e)?[d]:[],ye,ee];if(i<=Ff.md&&o&&(xt=xt.filter(rt=>rt.type!=="separator")),e.config.mode!=="docx"){const rt=xt.findIndex(Lt=>Lt.name.value==="linkedStyles");xt.splice(rt-1,2);const zt=["ruler","zoom","undo","redo"];xt=xt.filter(Lt=>!zt.includes(Lt.name.value))}const Ft=[];a||(s==="viewer"&&Ft.push(Ge,lt),xt=xt.filter(rt=>!Ft.includes(rt)));const Ut=rt=>U.includes(rt.name.value),mn=[],It=[];let Zt=ge+be;return xt.forEach(rt=>{const zt=D.get(rt.name.value)||D.get("default");if(i<Ff.xl+we&&Be.includes(rt.name.value)&&o){if(mn.push(rt),rt.name.value==="linkedStyles"){const Lt=xt.findIndex(An=>An.name.value==="linkedStyles");xt.splice(Lt+1,1)}return}if(i<Ff.sm&&Ze.includes(rt.name.value)&&o){mn.push(rt);return}if(Ut(rt)){It.push(rt),Zt+=zt;return}Zt<i||!o?(It.push(rt),Zt+=zt):mn.push(rt)}),{defaultItems:It,overflowItems:mn.filter(rt=>rt.type!=="separator")}},eA={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"},jz=e=>e?typeof e!="string"?e instanceof HTMLElement?e:null:e.startsWith("#")||e.startsWith(".")?document.querySelector(e):document.getElementById(e):null;Dt();function tA(e){return gN(e)??Z0[e]??null}function fm(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 Uz=new Set(["bold","italic","underline","strike","color","highlight","link","clearFormatting","textAlign","list","numberedlist","indentleft","indentright","lineHeight","linkedStyles"]),Hz=new Set(["list","numberedlist"]);function $z(e,t){if(e==="fontFamily"||e==="fontSize"||Hz.has(e)&&t?.disabled&&t?.supported!==!1&&t?.reason==null)return!0;if(!Uz.has(e))return!1;const n=t?.reason;return n==="range-selection-required"||n==="selection-required"}function nA(e){return!!e?.closest?.("[data-editor-ui-surface], .toolbar-dropdown-menu, .sd-toolbar-dropdown-menu, .sd-tooltip-content")}function Gz(e){return["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)}var Wz=class extends Gm.default{config={selector:null,toolbarGroups:["left","center","right"],role:"editor",icons:{...fr},texts:{...eA},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={...fr,...e.icons},this.config.texts={...eA,...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._reportedInvalidCustomItems=new Set,this._lastFontOptionsSignature="",!this.config.selector&&this.config.element&&(this.config.selector=this.config.element),this.toolbarContainer=jz(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=zl(BB),this.app.directive("click-outside",qv),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||PB(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}=Vz({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=new Set([...n,...r].map(c=>c.name?.value).filter(Boolean)),s=o.map((c,u)=>{try{if(c?.name&&i.has(c.name))throw new Error(`Toolbar item name "${c.name}" is already taken by another item, so this entry is skipped.`);const d=this.#c(c);return i.add(d.name?.value),d}catch(d){const h=`${c?.name??`<unnamed@${u}>`}::${d?.message??String(d)}`;return this._reportedInvalidCustomItems.has(h)||(this._reportedInvalidCustomItems.add(h),this.#b(d,c?.name??null)),null}}).filter(Boolean);s.length&&n.push(...s);let a=[...n.map(c=>c.name.value),...r.map(c=>c.name.value)];if(t){const c=Object.values(this.config.groups).flatMap(h=>h),u=new Set(Object.keys(this.config.groups)),d=s.filter(h=>u.has(h.group?.value||"center")).map(h=>h.name.value);a=[...new Set([...c,...d])]}const l=n.filter(c=>a.includes(c.name.value)).filter(c=>!this.config.excludeItems.includes(c.name.value));if(t)for(const[c,u]of Object.entries(this.config.groups))for(const d of l)u.includes(d.name.value)&&(d.group.value=c);this.toolbarItems=l,this.overflowItems=r.filter(c=>a.includes(c.name.value))}#c(e){const t=Tn({...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:()=>Q0(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=Y4.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(Y0(t)?.disposition==="host-routed")return e.setDisabled(!this.#u(t)),this.#g(t)?e.activate():e.deactivate(),!0;const n=tA(t);if(!n)return!1;const r=this.snapshot?.commands?.[n];$z(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=J0(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.#L(),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")}#L(){this.#l().forEach(e=>{const{allowWithoutEditor:t}=e;t?.value||e.setDisabled(!0)})}#P(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}#D(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=q4[t?.command];return i?fm(this.ui,i,void 0,r):!1}if(Y0(n)?.disposition==="unsupported")return!0;const o=tA(n);return o?fm(this.ui,o,t,r):!1}#T(){return this.snapshot?.commands?.image?.disabled||(this.#t||(this.#t=SN({ownerDocument:this.toolbarContainer?.ownerDocument??document,onPick:async e=>{const t=await CN(e,this.superdoc?.config?.handleImageUpload);fm(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=>{nA(i.target)||this.ui.formatPainter.setPointerSelecting(!0)},n=i=>{this.ui.formatPainter.setPointerSelecting(!1),!nA(i.target)&&this.ui.formatPainter.notifyPointerUp()},r=i=>{if(i.key==="Escape"){this.ui.formatPainter.cancel();return}Gz(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={error:e instanceof Error?e:new Error(String(e)),originalError:e,itemName:t??null,editor:this.superdoc?.activeEditor??this.activeEditor??null},r={...n};this.emit("exception",n),this.superdoc?.emit?.("exception",r)}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(Y0(r)?.disposition==="host-routed"){this.#P(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(!fm(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.#D(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 Kz(e){return new Wz(e)}function qz(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 Yz(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=hm(e.color);n!=null&&(t.color=n),e.highlight!=null&&(t.highlight=e.highlight);const r=Zz(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=Xz(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=Qz(e.border);return i&&(t.border=i),t}function hm(e){if(e){if(typeof e=="string")return e;if(e.model==="rgb")return e.value;if(e.model==="auto")return"auto"}}function Xz(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 Zz(e){if(!e)return;const t={},n=hm(e.fill);n!=null&&(t.fill=n);const r=hm(e.color);return r!=null&&(t.color=r),e.pattern!=null&&(t.val=e.pattern),Object.keys(t).length>0?t:void 0}function Qz(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=hm(e.color);return n!=null&&(t.color=n),Object.keys(t).length>0?t:void 0}function Ql(e){const t=e?.selectionTarget??e?.target;if(!e||!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Jz=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"]),eV=e=>e?.type!=="mutation:committed"||e.origin!=="command"?!1:Jz.has(e.editableCommandKind);function rA(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function tV(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 rA(r))n(o);return n(e.getAttribute("data-track-change-id")),t}function oA(e,t){if(!e||typeof e.getAttribute!="function")return[];const n=[],r=new Set;let o=[],i=e;for(;i;){const s=i,a=tV(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 c=s.getAttribute("data-layout-story");if(c&&o.length>0){for(const g of o)g.story=c;o=[]}const u=s.getAttribute("data-comment-ids");if(u)for(const g of rA(u)){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"),S={type:"contentControl",id:h};(p==="block"||p==="inline")&&(S.scope=p),v&&(S.tag=v),n.push(S)}}if(t&&i===t)break;i=i.parentElement}return n}var mo=()=>({oneOf:[{type:"boolean"},{type:"null"}]}),ul=()=>({oneOf:[{type:"string",minLength:1},{type:"null"}]}),wu=()=>({oneOf:[{type:"number"},{type:"null"}]}),Cu=e=>({oneOf:[{type:"object",properties:e,additionalProperties:!1,minProperties:1},{type:"null"}]}),nV={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},rV={type:"object",properties:{id:{type:"number"},val:{type:"boolean"}},required:["id"],additionalProperties:!1},oV=()=>({oneOf:[{type:"boolean"},{type:"null"},nV]}),iV=()=>({oneOf:[{type:"array",items:rV,minItems:1},{type:"null"}]});function pm(e,t){return{storage:"mark",markName:e,textStyleAttr:t}}function sV(e){return{storage:"runAttribute",nodeName:"run",runPropertyKey:e}}var e2=(e,t,n)=>({key:e,type:"boolean",ooxmlElement:t,storage:"mark",tracked:!0,carrier:pm(n),schema:mo()}),Jl=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"mark",tracked:!0,carrier:pm("textStyle",o??e),schema:r}),Yn=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"runAttribute",tracked:!1,carrier:sV(o??e),schema:r}),mm=[e2("bold","w:b","bold"),e2("italic","w:i","italic"),e2("strike","w:strike","strike"),{key:"underline",type:"object",ooxmlElement:"w:u",storage:"mark",tracked:!0,carrier:pm("underline"),schema:oV()},{key:"highlight",type:"string",ooxmlElement:"w:highlight",storage:"mark",tracked:!0,carrier:pm("highlight"),schema:ul()},Jl("color","string","w:color",ul()),Jl("fontSize","number","w:sz",wu()),Jl("fontFamily","string","w:rFonts",ul()),Jl("letterSpacing","number","w:spacing",wu()),Jl("vertAlign","string","w:vertAlign",{oneOf:[{enum:["superscript","subscript","baseline"]},{type:"null"}]}),Jl("position","number","w:position",wu()),Yn("dstrike","boolean","w:dstrike",mo()),Yn("smallCaps","boolean","w:smallCaps",mo()),Jl("caps","boolean","w:caps",mo(),"textTransform"),Yn("shading","object","w:shd",Cu({fill:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},val:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Yn("border","object","w:bdr",Cu({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"),Yn("outline","boolean","w:outline",mo()),Yn("shadow","boolean","w:shadow",mo()),Yn("emboss","boolean","w:emboss",mo()),Yn("imprint","boolean","w:imprint",mo()),Yn("charScale","number","w:w",wu(),"w"),Yn("kerning","number","w:kern",wu(),"kern"),Yn("vanish","boolean","w:vanish",mo()),Yn("webHidden","boolean","w:webHidden",mo()),Yn("specVanish","boolean","w:specVanish",mo()),Yn("rtl","boolean","w:rtl",mo()),Yn("cs","boolean","w:cs",mo()),Yn("bCs","boolean","w:bCs",mo(),"boldCs"),Yn("iCs","boolean","w:iCs",mo(),"italicCs"),Yn("eastAsianLayout","object","w:eastAsianLayout",Cu({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"}]}})),Yn("em","string","w:em",ul()),Yn("fitText","object","w:fitText",Cu({val:{oneOf:[{type:"number"},{type:"null"}]},id:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Yn("snapToGrid","boolean","w:snapToGrid",mo()),Yn("lang","object","w:lang",Cu({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},bidi:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Yn("oMath","boolean","w:oMath",mo()),Yn("rStyle","string","w:rStyle",ul(),"styleId"),Yn("rFonts","object","w:rFonts",Cu({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"),Yn("fontSizeCs","number","w:szCs",wu()),Yn("ligatures","string","w14:ligatures",ul()),Yn("numForm","string","w14:numForm",ul()),Yn("numSpacing","string","w14:numSpacing",ul()),Yn("stylisticSets","array","w14:stylisticSets",iV()),Yn("contextualAlternates","boolean","w14:cntxtAlts",mo())],JH=new Set(mm.map(e=>e.key)),aV=Object.fromEntries(mm.map(e=>[e.key,e])),e$={mark:mm.filter(e=>e.storage==="mark").map(e=>e.key),runAttribute:mm.filter(e=>e.storage==="runAttribute").map(e=>e.key)},t2=new WeakMap;function lV(e){let t=t2.get(e);return t||(t={refCount:0,generation:0,abortController:new AbortController,inFlight:null,activeMutationTokens:new Set},t2.set(e,t)),t.refCount+=1,t}function cV(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(),t2.delete(e))}var uV=new Set(Object.values(dt));function n2(e,t){return typeof e=="string"&&uV.has(e)?e:t}function iA(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:dt.notReady}:{ok:!1,reason:n2(t,dt.targetUnresolved)}}return{ok:!0}}var dV=["document-replaced","editorCreate","active-editor-change","document-mode-change","zoomChange","measurement-unit-change","viewport-change","fonts-changed"],fV={[N4.bulletList]:"bullet",[N4.numberedList]:"ordered"};function sA(e){return fV[e]??null}var hV={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 pV(e){const t=hV[e];return t?{preset:t,behavior:"toggleStyle"}:{}}var mV={status:"ready",empty:!0,target:null,selectionTarget:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[],quotedText:""},gV=[{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"}],vV=new Set(["/word/comments.xml","/word/commentsExtended.xml","/word/commentsIds.xml"]);function yV(e){return gV.some(t=>t.match==="exact"?t.key===e:e.startsWith(t.key))}var aA={ready:0,stale:1,pending:2};function ku(...e){let t="ready";for(const n of e)aA[n]>aA[t]&&(t=n);return t}function Ot(e,t){if(typeof e!="function")return t;try{const n=e();return n===void 0?t:n}catch{return t}}function Tr(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function Sr(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 nr(e,t="CAPABILITY_UNAVAILABLE"){return{success:!1,failure:{code:t,message:e}}}function Nf(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 Bf(e){if(!e||typeof e!="object")return null;const t=e.target;return t&&typeof t=="object"?t:null}function r2(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 bV(e){if(!e||typeof e!="object")return null;const t=Bf(e);if(r2(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 xr(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 Su(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=Bf(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 Xi(e,t,n){return er(e)!==t?!1:n?xr(Su(e))===xr(n):!0}function gm(e){const t=Su(e);if(!(!t||xr(t)===xr(null)))return t}function wV(e){if(typeof e!="string"||e.length===0)return;const t=y6(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 CV(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 o2(e){if(!e||typeof e!="object")return null;const t=e.selectionTarget;return t&&typeof t=="object"?t:null}function vm(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function kV(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 er(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 SV(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 lA=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 c=s.replacement;if(c&&typeof c=="object")for(const d of[c.inserted,c.deleted])d&&typeof d=="object"&&(n(d.id),n(d.wordId));const u=s.move;if(u&&typeof u=="object")for(const d of[u.source,u.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 ya(e){const t=lA.get(e);if(t)return t;const n=new Set,r=new Map;for(const i of e){const s=er(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 lA.set(e,o),o}var uA=new WeakMap,dA=new WeakMap;function _u(e,t){const n=xr(t);let r=uA.get(e);r||(r=new Map,uA.set(e,r));const o=r.get(n);if(o)return o;const i=ya(e.filter(s=>xr(Su(s))===n));return r.set(n,i),i}function _V(e){return!!e&&typeof e=="object"&&e.storyType==="textbox"}function AV(e,t){const n=t.filter(o=>e.some(i=>er(i)===o&&Su(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=>er(s)===o);if(i)for(const s of cA(i)){if(r.has(s))return null;r.add(s)}}return n[0]}function IV(e){const t=dA.get(e);if(t)return t;const n=e.filter(o=>Su(o)!=null),r=n.length===e.length?e:n;return dA.set(e,r),r}function EV(e){const{selectionIds:t,publicIds:n,selection:r,bodyItems:o,allStoryItems:i}=e;if(t.length===0)return null;const s=c=>{for(const u of t){const d=c.toPublicId(u);if(d)return d}return null},a=Zi(r),l=xr(a)===xr(null);if(i){const c=l?IV(i):i,u=s(_u(c,a));if(u)return u;const d=n?.find(h=>c.some(g=>Xi(g,h,a)));return d||(l?s(ya(o)):_V(a)?AV(i,t):null)}return l?s(ya(o))??t[0]??null:null}function TV(e,t){const n=e.find(r=>er(r)===t||r.importedId===t);return n?n.rootCommentId??n.parentCommentId??er(n)??t:null}function xV(e){const t=e.selectionTarget;if(t){const s=t.start,a=t.end,l=typeof s?.blockId=="string"?s.blockId:void 0,c=typeof a?.blockId=="string"?a.blockId:l;if(l)return{startBlockId:l,endBlockId:c??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 $r(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 RV=64;function ec(e){return e.length<=RV}function Zi(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 So(e,t){return{kind:"block",nodeType:"paragraph",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}function ba(e){return{kind:"block",nodeType:"paragraph",nodeId:e}}function fA(e,t){return{kind:"block",nodeType:"listItem",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}var hA=720;function _s(e){return Math.round(e*20)}function Au(e){return typeof e=="number"&&Number.isFinite(e)}function MV(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=Au(i.left)?_s(i.left):Au(i.start)?_s(i.start):void 0,a=Au(i.right)?_s(i.right):Au(i.end)?_s(i.end):void 0,l=Au(i.firstLine)?_s(i.firstLine):void 0,c=Au(i.hanging)?_s(i.hanging):void 0;return s==null&&a==null&&l==null&&c==null?null:{...s!=null?{left:s}:{},...a!=null?{right:a}:{},...l!=null?{firstLine:l}:{},...c!=null?{hanging:c}:{}}}function i2(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 LV(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 zf(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 dl(e){return zf(e.target)??zf(e.selectionTarget)}var pA=["fontFamily","fontSize","color","highlight"],PV={undo:"history.undo",redo:"history.redo"},Vf=["bold","italic","underline","strikethrough"];function s2(e){return pA.includes(e)}function Iu(e){const t=e.target,n=t&&Array.isArray(t.segments)?t.segments:[],r=[],o=(l,c,u)=>{typeof l!="string"||typeof c!="number"||typeof u!="number"||r.push({blockId:l,start:Math.min(c,u),end:Math.max(c,u)})};for(const l of n){const c=l?.range;o(l?.blockId,c?.start,c?.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 DV(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 wa(e){const t=Iu(e);return t.length===0?null:[DV(e),...t.map(n=>`${n.blockId}:${n.start}-${n.end}`)].join("|")}function mA(e){const t=e.selectionTarget;return!t||typeof t!="object"?null:Ql({selectionTarget:t})}function OV(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 FV(e,t){return Math.max(e.start,t.start)<Math.min(e.end,t.end)}function NV(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 BV(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 gA(e,t){const n=Iu(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=>BV(n,NV(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 zV(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 a2(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 VV(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 jV(e,t){return e==="fontFamily"?t.toLowerCase():e==="color"||e==="highlight"?t.toUpperCase():t}function vA(e,t){if(!e)return{};const n=new Map;for(const i of Iu(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 pA){const s=new Map;let a=!1,l=!1;for(const c of r){const u=typeof c?.blockId=="string"?c.blockId:null;if(!u)continue;const d=n.get(u);if(!d?.length)continue;const h=Array.isArray(c?.runs)?c.runs:[];for(const g of h){const p=g?.range,v=typeof p?.start=="number"?p.start:null,S=typeof p?.end=="number"?p.end:null;if(v==null||S==null||!d.some(y=>FV(y,{start:v,end:S})))continue;a=!0;const C=zV(g?.styles,i);if(C===void 0){l=!0;continue}const A=jV(i,C);if(s.has(A)||s.set(A,C),s.size>1)break}if(s.size>1)break}a&&!l&&s.size===1&&(o[i]=[...s.values()][0])}return o}function l2(e,t){const n=$r(e)[0];return n?t==="nodeId"?{kind:"after",nodeId:n}:{kind:"after",target:So(n)}:{kind:"documentEnd"}}function sn(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 fl(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 ym(e){const t=e,n=t.change;return n&&typeof n=="object"?n:t}function As(e){if(Tr(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 bm(e){return!!e&&typeof e=="object"&&e.success===!0}function _o(e){return!(e===!1||e&&typeof e=="object"&&e.success===!1)}function tc(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function c2(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 c of l.blocks)n(c);l?.paragraph&&n(l.paragraph)}}};if(Array.isArray(e))for(const r of e)n(r);return t}function nc(e,t){return e.sourceAnchor?.sourceNodeId===t?!0:e.id===t}function wm(e){return e.trackedChange?.kind==="delete"?0:typeof e.text=="string"?e.text.length:0}function Ci(e){let t=!1,n=null,r=null,o=null;for(const i of e)t=i,!_o(i)&&n===null&&(n=i),bm(i)&&(o=i),i!==!1&&(r=i);return n??o??r??t}function UV(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 HV(e){return e.startsWith("#")?{kind:"anchor",anchor:e.slice(1)}:{kind:"external",url:e}}function Cm(e){return yu(e)?.trackDecision??null}function $V(e){return{found:e.length>0,success:e.length>0,rects:e,rect:e[0]}}function hl(e){return{found:!1,success:!1,rects:[],reason:e}}function GV(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 WV(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 yA(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(WV))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 KV(e){return e.selectionTarget?e.selectionTarget:yA(e.target)}function Eu(e){if(e.empty)return null;if(e.selectionTarget)return e.selectionTarget;const t=yA(e.target);return t&&t.start.kind==="text"&&t.end.kind==="text"&&t.start.blockId!==t.end.blockId?null:t}function u2(e){return!e.inline||typeof e.docRoute!="string"?null:e.docRoute.startsWith("format.")?e.docRoute.slice(7):null}var d2={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},qV=Object.fromEntries(Object.entries(d2).filter(([e])=>aV[e]?.tracked===!0));function YV(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:{...d2}};default:return null}}function XV(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 ZV(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 QV(e){const t=e.superdoc,n=new Map,r=new Map;let o=null,i=0;const s=[];let a=null,l=0,c=!1,u=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={},S="",C=null;const A=()=>{const f=t?.activeEditor;return f&&typeof f=="object"?f:null},y=()=>{const f=A()?.doc;return f&&typeof f=="object"?f:null},w=()=>{const f=A()?.v2TrackedChanges;return f&&typeof f=="object"?f:null},x=()=>{const f=A();if(f?.editorVersion!==2)return null;const m=f.reviewHydration;return m&&typeof m=="object"?m:null},L=()=>{const f=x();return!f||typeof f.getSnapshot!="function"?null:Ot(()=>f.getSnapshot(),null)},V=()=>typeof x()?.getSnapshot=="function",G=f=>{const m=f?.status;return m==="ready"||m==="stale"?m:"pending"},R=()=>{const f=A()?.host;return f&&typeof f=="object"?f:null},F=f=>{if(f.storyType!=="headerFooterPart"||typeof f.refId!="string")return null;const m=A(),b=R(),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=Ot(()=>E.call(I),null);if(!K||typeof K.pageIndex!="number")return null;for(const ae of["header","footer"]){const ue=Ot(()=>z.call(b,{pageIndex:K.pageIndex,kind:ae}),null);if(!(ue?.status!=="ready"||ue.refId!==f.refId||typeof ue.sectionId!="string"||!["default","first","even"].includes(String(ue.slotVariant))))return{kind:"story",storyType:"headerFooterSlot",section:{kind:"section",sectionId:ue.sectionId},headerFooterKind:ae,variant:ue.slotVariant}}return null},Z=()=>{const f=R(),m=f?.getPendingInlineFormat;if(typeof m!="function")return null;const b=Ot(()=>m.call(f),null);return b&&typeof b=="object"?b:null},O=f=>{const m=u2(f);if(!m)return null;const b=Z();if(!b||!(m in b))return null;const I=b[m];return f.inline?.kind==="toggle"?I===!0:I!=null&&I!==""},N=f=>{const m=u2(f);if(!m)return;const b=Z();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)},T=(f,m)=>{const b=R(),I=b?.setPendingInlineFormat;typeof I=="function"&&Ot(()=>I.call(b,f,m),void 0)},B=f=>{const m=R(),b=m?.clearPendingInlineFormat;typeof b=="function"&&Ot(()=>b.call(m,f),void 0)},Q=new Set(["bold","italic","underline","strikethrough"]),q=f=>{const m=Z();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(Q.has(E))K=b.includes(E)===(z===!0);else if(s2(E)){if(z==null)continue;I||(I=yl(f)),K=I[E]===z}else K=!1;K&&B(E)}},se=()=>{const f=A()?.editCommands;return f&&typeof f=="object"?f:null},he=f=>{const m=se();if(!m||typeof m.getSnapshot!="function")return null;const b=Ot(()=>m.getSnapshot(),null)?.commands?.[f];return b&&typeof b=="object"?b:null},Ne=()=>he("lists.apply"),pe=f=>{const m=f?.value?.seed;return m==="bullet"||m==="ordered"?m:null},ye=f=>{const m=PV[f];return m?he(m):null},me=()=>{const f=R();if(!f||typeof f.getTableContext!="function")return null;const m=Ot(()=>f.getTableContext(),null);return m&&typeof m=="object"?m:null},_e=()=>{const f=me();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,ae=typeof E?.index=="number"&&Number.isInteger(E.index)?E.index:null;if(K==null||ae==null)return null;const ue=typeof z?.nodeId=="string"&&z.nodeId.length>0?z.nodeId:null,Le=f.cellRange;return{tableNodeId:b,rowIndex:K,columnIndex:ae,cellNodeId:ue,mergeRange:XV(Le)}},oe=new Map;let Me=null,Ge=null,lt=0,Ct=0,Re=0;const Ke=new Set,tt=(f,m)=>f===m?!0:!f||!m?!1:f.id===m.id&&f.paintedEntityId===m.paintedEntityId&&xr(f.story)===xr(m.story),ee=f=>Array.from(Ke).some(m=>tt(m,f)),_=f=>{const m=R();if(typeof m?.getHandles!="function")return;const b=Ot(()=>m.getHandles(),null),I=b?.review;if(I){if(f){if(typeof I.setActiveReviewTarget!="function")return;const E=b?.layout;Ot(()=>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"||Ot(()=>I.getActiveReviewTarget(),null)?.entityType==="trackedChange"&&Ot(()=>I.clearActiveReviewTarget(),void 0)}},te=(f,m)=>{Ge=f,lt+=1,Re+=1,m?.invalidateQueuedNavigation!==!1&&(Ct+=1)},D=new Set;let U=!1,$=null;const H=new Map,J=new Set;let X=null,W=null,we=!1,ge=null,be=0,Be=null,Ze=null,it=null;const yt=()=>{if(we||U)return;we=!0;const f=()=>{we=!1,U||j()};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Xt=250,xt=5e3,Ft=f=>{U||ge&&be<=f||(ge&&clearTimeout(ge),be=f,ge=setTimeout(()=>{ge=null,be=0,U||j()},Math.max(0,f-Date.now())))},Ut=new WeakMap;let mn=0;const It=f=>{if(!f)return"none";let m=Ut.get(f);return m==null&&(m=mn+=1,Ut.set(f,m)),`e${m}`};let Zt=0,rt={};const zt=e.superdoc,Lt=lV(zt),An=()=>{Lt.abortController.abort("review-mutation-started"),Lt.inFlight=null},Qt=()=>{Lt.generation+=1,Lt.abortController=new AbortController,Lt.inFlight=null},wn=f=>{const m=Lt.activeMutationTokens;if(typeof f!="string"||f.length===0||m.has(f))return;const b=m.size===0;m.add(f),b&&An()},Wn=f=>{const m=Lt.activeMutationTokens;typeof f!="string"||!m.delete(f)||m.size===0&&Qt()},go=f=>{const m=w(),b=m?.listTrackedChanges;if(typeof b!="function")return A()?.editorVersion===2?Promise.reject(new Error("v2-tracked-changes-bridge-pending")):f();if(Lt.activeMutationTokens.size>0)return Promise.reject(new Error("ui-review-catalog-superseded"));if(A()?.reviewHydration?.getDiagnostics?.()?.inFlight===!0)return Promise.reject(new Error("shell-review-hydration-in-flight"));const I=Lt.generation,E=Lt.inFlight;if(E?.generation===I)return E.promise;const z=Lt.abortController.signal,K=Le=>{if(z.aborted||I!==Lt.generation||Le?.reason==="review-hydration-superseded")throw new Error("ui-review-catalog-superseded");return Le},ae=b.call(m,{blocking:!1,signal:z});if(!Tr(ae))return K(ae);const ue=Promise.resolve(ae).then(K);return Lt.inFlight={generation:I,promise:ue},ue.then(()=>{Lt.inFlight?.promise===ue&&(Lt.inFlight=null)},()=>{Lt.inFlight?.promise===ue&&(Lt.inFlight=null)}),ue};let jn=null,Xn=null,Ao=0;const Nr=()=>{Xn&&clearTimeout(Xn),Xn=null,Ao=0};let rr=f=>{},Pn=null,De=new Set,Oe=null,qe=0,wt=null;const ft=()=>`${It(A())}|m${Zt}`,Pt=()=>{Pn=null,De=new Set},_n=f=>{for(const m of["trackChanges","trackChanges:all"]){const b=H.get(m);if(!b?.hasSettled||!Array.isArray(b.value))continue;const I=b.value.filter(E=>{const z=er(E);return!z||!f.has(z)});I.length!==b.value.length&&H.set(m,{...b,value:I})}},an=f=>{const m=()=>{if(!U)for(const z of[...D])z(ht)},b=tc(f)?f:null,I=A()?.documentMutationReadiness,E=()=>{const z=globalThis.requestAnimationFrame;return typeof z!="function"?Promise.resolve():new Promise(K=>{let ae=!1;const ue=()=>{ae||(ae=!0,clearTimeout(Le),K())},Le=setTimeout(ue,250);z(()=>z(()=>setTimeout(ue,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()},Dn=(f,m)=>{const b=ht.trackChanges,I=b.items.filter(K=>{const ae=er(K);return!ae||!f.has(ae)});if(I.length===b.items.length)return;Ge&&f.has(Ge.id)&&te(null);const E=new Set;for(const K of I){const ae=ym(K),ue=K,Le=ae.author??ae.authorEmail??ue.author??ue.authorEmail;typeof Le=="string"&&E.add(Le)}const z=b.items.length-I.length;ht={...ht,trackChanges:{...b,items:I,total:Math.max(I.length,b.total-z),activeId:b.activeId&&f.has(b.activeId)?null:b.activeId,authors:[...E]}},an(m)},Io=f=>{const m=ht.trackChanges,b=m.items.length>0||m.total!==0||m.activeId!==null||m.authors.length>0;Oe=ft(),Ge!==null&&te(null),ht={...ht,trackChanges:{...m,items:[],total:0,activeId:null,authors:[]}},b&&an(f)},Eo=(f,m)=>{if(f.size===0)return;const b=ft(),I=Pn===b?De:new Set,E=new Set([...f].filter(z=>!I.has(z)));E.size!==0&&(Pn=b,De=new Set([...I,...E]),_n(De),Dn(E,m))},ki=f=>Pn===f&&De.size>0?De:null,cn=(f,m=[])=>{const b=f.map(fl).filter(E=>E!=null&&er(E)!=null);if(b.length===0)return;const I=m.map(fl).map(E=>E==null?null:er(E)).filter(E=>E!=null);for(const E of["trackChanges","trackChanges:all"]){const z=H.get(E),K=z?.hasSettled&&Array.isArray(z.value)?[...z.value]:[],ae=new Set;let ue=!1;for(const Le of b){const Ue=er(Le);if(!Ue)continue;const je=K.findIndex(Ve=>er(Ve)===Ue);if(je<0)K.push(Le),ae.add(Ue);else{const Ve=K[je];K[je]=tc(Ve)?{...Ve,...Le}:Le}ue=!0}if(E==="trackChanges"&&ae.size>0&&I.length>0){const Le=new Set(I.filter(Ve=>ae.has(Ve))),Ue=new Map(K.filter(Ve=>Le.has(er(Ve)??"")).map(Ve=>[er(Ve),Ve])),je=K.filter(Ve=>!Le.has(er(Ve)??""));for(const[Ve,Xe]of I.entries()){if(!Le.has(Xe))continue;const $e=Ue.get(Xe);if(!$e)continue;const Qe=I.slice(Ve+1).map(at=>je.findIndex(ot=>er(ot)===at)).find(at=>at>=0);if(Qe!=null){je.splice(Qe,0,$e);continue}const Je=I.slice(0,Ve).reverse().map(at=>je.findIndex(ot=>er(ot)===at)).find(at=>at>=0);je.splice(Je==null?je.length:Je+1,0,$e)}K.splice(0,K.length,...je)}ue&&H.set(E,{token:z?.token??null,value:K,hasSettled:!0,inflightToken:null})}},On=f=>{const m=ft(),b=ki(m),I=f.map(fl).filter(E=>{if(E==null)return!1;const z=er(E);return z!=null&&!b?.has(z)});for(const E of["trackChanges","trackChanges:all"])H.set(E,{token:m,value:[...I],hasSettled:!0,inflightToken:null})},Fn=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]}}},lr=Ok({getContext:()=>{const f=A();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:rt,v2TrackedChanges:m,docTrackChanges:b}},reconcile:async(f,m)=>{m.removedIds.size>0&&Eo(new Set(m.removedIds));const b=[...new Set(m.upsertIds)];if(b.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};const I=H.get("trackChanges"),E=I?.hasSettled&&Array.isArray(I.value)?I.value:null,z=new Set(E?E.map(er).filter(Je=>Je!=null):[]),K=E?.length===0&&To()==="complete",ae=new Set(b.filter(Je=>!z.has(Je))),ue=f.v2TrackedChanges?.getTrackedChange,Le=f.docTrackChanges?.get;if(typeof ue!="function"&&typeof Le!="function")return{ok:!1,items:[],resolvedIds:[],unresolvedIds:b};const Ue=await Promise.all(b.map(async Je=>{try{if(typeof ue=="function"){const ot=await Promise.resolve(ue.call(f.v2TrackedChanges,Je));return{id:Je,ok:ot?.ok!==!1,items:ot?.ok!==!1&&Array.isArray(ot?.items)?ot.items:[],result:ot}}const at=await Promise.resolve(Le.call(f.docTrackChanges,{id:Je}));return{id:Je,ok:!0,items:at&&typeof at=="object"?[at]:[],result:at}}catch(at){return{id:Je,ok:!1,items:[],result:at}}})),je=[],Ve=[],Xe=[];for(const Je of Ue){const at=Je.items.filter(ot=>{const Nt=fl(ot);return Nt!=null&&er(Nt)===Je.id});Je.ok&&at.length>0?(je.push(...at),Ve.push(Je.id)):Xe.push(Je.id)}let $e;const Qe=Ve.filter(Je=>ae.has(Je));if(Qe.length>0&&!K){const Je=await Fn(f,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1,targetIds:Qe});Je.ok&&($e=Je.items)}return{ok:Xe.length===0,items:je,orderedItems:$e,resolvedIds:Ve,unresolvedIds:Xe,failures:Ue.filter(Je=>!Je.ok).map(Je=>Je.result)}},hydrate:Fn,onReconciled:(f,m,b)=>{if(b?.reconcileMode==="authoritative"){if(f.reconcileToken!==rt)return;b.ok===!0&&b.complete===!0&&b.sourceCoverageComplete===!0?(Nr(),On(b.items??[]),jn=null):b.ok===!0?(Nr(),cn(b.items??[])):rr(f.reconcileToken),j();return}const I=(b?.items??[]).filter(E=>{const z=fl(E),K=z==null?null:er(z);return K!=null&&m.has(K)});cn(I,b?.orderedItems??b?.items??[]),j()}});rr=f=>{if(U||Xn)return;const m=Math.min(Xt*2**Ao,xt);Ao+=1,Xn=setTimeout(()=>{Xn=null,!(U||jn===null||f!==rt)&&lr.onRender(!0)},m)};const Jt=()=>`${ft()}|m${wr()}|s${qe}`,Un=f=>JSON.stringify({t:f.target??null,s:f.selectionTarget??null}),ro=["contentControls:inRange:","query:","effInline:"],Pi=120,pl=180,To=()=>{const f=R(),m=f?.getDocumentLoadingSnapshot;if(typeof m!="function")return"unknown";const b=Ot(()=>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"},ai=new Map,ke=f=>{const m=ft();ai.get(f)!==m&&(ai.set(f,m),yt())},He=()=>{const f=H.get("comments");return f?.hasSettled?Array.isArray(f.value)&&f.value.length>0:f?.inflightToken!=null},Et=(f,m)=>ai.get(f)===m,st=f=>{ke("contentControls")},Nn=()=>{const f=H.get("trackChanges");f?.hasSettled||f?.inflightToken!=null||ke("trackChanges")},Kn=()=>{const f=H.get("comments");f?.hasSettled||f?.inflightToken!=null||ke("comments")},_r=6500,jo=250;let xo=0,Di=0,Ro=!1,oo=null;const io=()=>{if(U||oo)return;const f=()=>{if(oo=null,U)return;const m=Date.now()-xo;if(Ho()||m<_r){oo=setTimeout(f,jo);return}Ro=!1,j()};oo=setTimeout(f,0)};let Si=null,Uo=null;const es=()=>{const f=R();if(!f||Si===f)return;Uo&&(Uo(),Uo=null),Si=f;const m=f.subscribeDocumentLoading;if(typeof m!="function"){Si=null,Br(_r);return}try{const b=z=>{const K=z?.sourceStage;(K==="source-complete"||K==="source-failed"||K==="source-cancelled")&&(xo=Math.max(xo,Date.now()),io())},I=m.call(f,b);typeof I=="function"&&(Uo=I);const E=f.getDocumentLoadingSnapshot;typeof E=="function"&&b(Ot(()=>E.call(f),null))}catch{Si=null,Br(_r)}},vo=()=>{const f=A()?.host,m=f?.getForegroundMutationState;if(typeof m!="function")return null;const b=Ot(()=>m.call(f),null);return{active:typeof b?.active=="number"?b.active:0,pending:typeof b?.pending=="number"?b.pending:0}},Ho=()=>{const f=vo();return!!(f&&(f.active>0||f.pending>0))},Br=(f=Pi)=>{U||Be||(Be=setTimeout(()=>{if(Be=null,U)return;if(Ze&&Ho()){Br(),j();return}const m=Ze;Ze=null,m===Jt()&&ka("selection",m,ic,zi),j()},f))},Oi=(f,m)=>{if(!vo())return!1;const b=`${f}\0${m}`;return J.has(b)?!1:(J.add(b),Br(pl),!0)},Fi=f=>{if(X==null||f===X)return W?.timer&&clearTimeout(W.timer),W=null,X=f,!1;if(W?.key===f)return W.ready?(W=null,X=f,!1):!0;W?.timer&&clearTimeout(W.timer);const m={key:f,ready:!1,timer:null};return m.timer=setTimeout(()=>{U||W!==m||(m.timer=null,m.ready=!0,j())},pl),W=m,!0},Tu=f=>eV(f),xu=()=>{Mo(),j()};let li=null,Ni=!1,Is=0;const Bi=()=>{li=null,Ni=!1,Is+=1},jf=()=>{const f=A(),m=f?.documentMutationReadiness;if(!f||typeof m?.whenPainted!="function"||(li={editor:f,readiness:m,afterEpoch:typeof m.getRenderEpoch=="function"?Ot(()=>m.getRenderEpoch.call(m),null):null},Ni))return;Ni=!0;const b=Is;(async()=>{for(;!U&&b===Is;){const E=li;if(li=null,!E){Ni=!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(U||b!==Is)return;if(A()!==E.editor){Bi();return}z&&xu()}})()},Ca=()=>{it&&clearTimeout(it),it=setTimeout(()=>{it=null,U||xu()},500)},ka=(f,m,b,I)=>{let E;try{E=b()}catch{E=void 0}if(!Tr(E)){const ae={token:m,value:I(E),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0};return H.set(f,ae),ae}const z=H.get(f),K=z?.failedToken===m;return H.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(ae=>{const ue=H.get(f);!ue||ue.inflightToken!==m||(H.set(f,{token:m,value:I(ae),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0}),yt())},()=>{const ae=H.get(f);if(!ae||ae.inflightToken!==m)return;const ue=ae.failedToken===m?(ae.failureCount??0)+1:1,Le=Math.min(xt,Xt*2**Math.min(ue-1,8)),Ue=Date.now()+Le;H.set(f,{...ae,inflightToken:null,failedToken:m,failureCount:ue,retryAtMs:Ue}),Ft(Ue)}),null},Ar=(f,m,b,I)=>{const E=H.get(f);if(E&&E.token===m&&E.hasSettled)return{value:E.value,status:"ready"};if(yV(f)&&!Et(f,m)){if(To()==="loading")return Ro=!0,es(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(Ro)return io(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(Date.now()-Di<_r)return Ro=!0,io(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"}}if(Ho())return Br(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(E?.failedToken===m&&E.inflightToken==null&&(E.retryAtMs??0)>Date.now())return Ft(E.retryAtMs),E.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!E&&f.startsWith("effInline:")&&Fi(f))return{value:null,status:"pending"};if(!E&&Oi(f,m))return{value:null,status:"pending"};if(!E||E.inflightToken!==m){const K=ka(f,m,b,I);if(K)return{value:K.value,status:"ready"}}const z=H.get(f);return z?.hasSettled?{value:z.value,status:"stale"}:{value:null,status:"pending"}},Uf=f=>{for(const m of H.keys())f(m)&&H.delete(m)},ml=f=>{const m=Un(f),b=mA(f);return new Set([`contentControls:inRange:${m}`,`query:${m}`,...b?[`effInline:${b}`]:[]])},Hf=f=>{const m=ml(f);Uf(b=>ro.some(I=>b.startsWith(I))&&!m.has(b));for(const b of J){const I=b.split("\0",1)[0];ro.some(E=>I.startsWith(E))&&!m.has(I)&&J.delete(b)}},rc=()=>{const f=A();f!==wt&&(Bi(),lr.reset(),rt={},wt=f,H.clear(),jn=null,Nr(),ge&&clearTimeout(ge),ge=null,be=0,W?.timer&&clearTimeout(W.timer),W=null,X=null,C=null,o=null,Ze=null,J.clear(),ai.clear(),Ro=!1,Uo&&Uo(),Uo=null,Si=null,Pt(),Oe=null)},Mo=()=>{const f=jn!==null;Zt+=1,f&&(jn=ft()),Pt()},ci=()=>{const f=Oe===ft();Mo(),f&&(On([]),Oe=ft()),j()},Ru=f=>{if(typeof f!="string"||f.length===0)return nr("insertText requires a non-empty string.","INVALID_INPUT");if(wr()==="viewing")return nr("The document is read-only.","DOCUMENT_READONLY");const m=y(),b=m?.insert;if(!m||typeof b!="function")return nr("insert is unavailable.");const I=m.selection?.current;if(typeof I!="function")return nr("selection.current is unavailable.");const E=K=>{const ae=K&&typeof K=="object"?K:null,ue=ae?.selectionTarget??ae?.target??null;return!ue||typeof ue!="object"?nr("insertText requires a live selection target.","PRECONDITION_FAILED"):Ot(()=>Lo(b.call(m,{type:"text",value:f,target:ue}),nr("insert failed.")),nr("insert failed."))};let z;try{z=I.call(m.selection)}catch{return nr("insertText could not resolve the live selection.","PRECONDITION_FAILED")}return Tr(z)?Promise.resolve(z).then(E,()=>nr("insertText could not resolve the live selection.","PRECONDITION_FAILED")):E(z)},Mu=(f,m)=>({payload:f,state:ht,editor:A(),superdoc:t,context:m,ui:$,execute:(b,I)=>wc(b,I),executeAsync:(b,I)=>Tm(b,I),doc:y(),selection:ht.selection,documentMode:wr(),insertText:Ru}),ui=f=>f==="editing"||f==="suggesting"||f==="viewing"?f:null,wr=()=>{const f=A(),m=t&&typeof t=="object"?t:null,b=ui(m?.config?.documentMode),I=Ot(typeof m?.getActiveRuntime=="function"?()=>{const K=m.getActiveRuntime();return typeof K?.getSnapshot=="function"?K.getSnapshot():null}:void 0,null),E=ui(I?.documentMode),z=ui(f?.options?.documentMode);return b&&E&&b!==E?b:E??b??z},$f=()=>{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},qo=()=>{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},Es=()=>wr()==="viewing"||$f(),zi=f=>f&&typeof f=="object"?f:null,Ts=(f,m)=>{if(!f)return{...mV,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}},ts=()=>{const f=y()?.selection;return Ar("selection",Jt(),()=>f?.current?f.current({includeText:!0}):void 0,zi)},oc=()=>{const{value:f,status:m}=ts();return Ts(f,m)},ic=()=>{const f=y()?.selection;return f?.current?f.current({includeText:!0}):void 0},Lu=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},sc=f=>{const m=R(),b=m?.readLiveSelectionSyncSnapshot;if(typeof b!="function")return;const I=zi(Ot(()=>b.call(m),null));if(!I||!Lu(I))return;const E=Jt(),z=vo(),K=!!(z&&(z.active>0||z.pending>0));if(K)Ze=E,Br();else if(Ze=null,ka("selection",E,ic,zi))return;const ae=H.get("selection"),ue=Array.isArray(I.activeMarks)&&I.activeMarks.length>0?I.activeMarks:Array.isArray(ht.selection.activeMarks)?ht.selection.activeMarks:[],Le=Array.isArray(I.activeCommentIds)?I.activeCommentIds:[],Ue=SV(f),je=dl(ht.selection),Ve=zf(I.selectionTarget)??zf(I.target),Xe=je?.range,$e=Ve?.range,Qe=!!(z&&z.active>0&&je&&Ve&&je.blockId===Ve.blockId&&xr(je.story)===xr(Ve.story)&&typeof Xe?.start=="number"&&typeof $e?.start=="number"&&Math.abs($e.start-Xe.start)<=2),Je=Ue!=null||Qe?ht.selection.activeChangeIds.filter(ot=>Ue==null||ya(ht.trackChanges.items).aliasesFor(ot).includes(Ue)):[],at=Array.isArray(I.activeChangeIds)&&I.activeChangeIds.length>0?I.activeChangeIds:Je;H.set("selection",{token:E,value:{...I,activeMarks:ue,activeCommentIds:Le,activeChangeIds:at},hasSettled:!0,inflightToken:K?null:ae?.inflightToken??null})},xs=async(f=0)=>{const m=y()?.selection,b=m?.current,I=Jt();if(typeof b!="function")return H.set("selection",{token:I,value:null,hasSettled:!0,inflightToken:null}),j(),ht.selection;let E;try{E=b.call(m,{includeText:!0}),Tr(E)&&(E=await Promise.resolve(E))}catch{E=null}return U?Ts(null,"pending"):Jt()!==I?f<1?xs(f+1):ht.selection:(H.set("selection",{token:I,value:zi(E),hasSettled:!0,inflightToken:null}),j(),ht.selection)},Sa=f=>{const m=y()?.comments,b=L(),I=Ar("comments",ft(),()=>m?.list?m.list():void 0,je=>je&&Array.isArray(je.items)?je.items:[]),E=V()&&Array.isArray(b?.commentItems)?b.commentItems:null,z=I.status==="pending"&&E!=null,K=z?E:I.value,ae=z?G(b):I.status,ue=K??[],Le=f.activeCommentIds;Me&&!ue.some(je=>er(je)===Me)&&(Me=null);const Ue=Me??Le[0]??null;return{status:ku(ae,f.status),listStatus:ae,items:ue,total:ue.length,activeIds:Le,activeId:Ue}},Rs=()=>{const f=y()?.trackChanges,m=ft(),b=H.get("trackChanges:all"),{value:I,status:E}=jn===m?{value:b?.hasSettled?b.value:null,status:b?.hasSettled?"stale":"pending"}:Ar("trackChanges:all",m,()=>{if(!f?.list)return;const z=()=>f.list({in:"all"}),K=typeof w()?.listTrackedChanges=="function",ae=go(z);return K?Promise.resolve(ae).then(ue=>{const Le=tc(ue)?ue:null;return(Array.isArray(Le?.items)?Le.items:[]).some(Ue=>Su(Ue)==null)?z():ue}):ae},z=>(z&&Array.isArray(z.items)?z.items:[]).map(fl).filter(K=>K!=null));return E==="ready"?I:null},Pu=f=>{const m=y()?.trackChanges,b=w(),I=typeof b?.listTrackedChanges=="function"?b.listTrackedChanges:null,E=ft(),z=ki(E),K=H.get("trackChanges"),ae=L(),ue=jn===E?{value:K?.hasSettled?K.value:null,status:K?.hasSettled?"stale":"pending"}:Ar("trackChanges",E,()=>I?go(()=>m?.list?.()):m?.list?m.list({in:"all"}):void 0,fn=>fn&&Array.isArray(fn.items)?fn.items:[]),Le=V()&&Array.isArray(ae?.trackedChangeItems)?ae.trackedChangeItems:null,Ue=ue.status==="pending"&&Le!=null,je=Ue?Le:ue.value,Ve=Ue?G(ae):ue.status,Xe=(je??[]).map(fl).filter(fn=>fn!=null).filter(fn=>{const or=er(fn);return!or||!z?.has(or)}),$e=new Set;for(const fn of Xe){const or=ym(fn),bo=fn,rd=or.author??or.authorEmail??bo.author??bo.authorEmail;typeof rd=="string"&&$e.add(rd)}const Qe=m?.list?Rs():null,Je=Ge;Je&&(Je.story?Qe&&!Qe.some(fn=>Xi(fn,Je.id,Je.story))&&te(null):Xe.some(fn=>er(fn)===Je.id)||te(null));const at=Qe??Xe,ot=_u(at,Zi(f)),Nt=Oe===E?[]:z?f.activeChangeIds.filter(fn=>!z.has(fn)):f.activeChangeIds,qt=Nt.map(fn=>ot.toPublicId(fn)??fn),Qn=Ge?.story?_u(at,Ge.story):ya(at),tr=Ge?Qn.toPublicId(Ge.id)??Ge.id:null,Qr=EV({selectionIds:Nt,publicIds:qt,selection:f,bodyItems:Xe,allStoryItems:Qe}),zr=tr??Qr;return{status:ku(Ve,f.status),items:Xe,total:Xe.length,activeId:zr,authors:[...$e]}},ac=f=>{const m=y()?.contentControls,{value:b,status:I}=Ar("contentControls",ft(),()=>m?.list?m.list():void 0,ae=>ae&&Array.isArray(ae.items)?ae.items:[]),E=b??[],{ids:z,status:K}=Gf(m,f);return{status:ku(I,K,f.status),items:E,total:E.length,activeId:z[0]??null,activeIds:z}},Ms=(f,m)=>{if(!f||typeof f.listInRange!="function")return{lockModesById:new Map,status:"ready"};const b=xV(m);if(!b)return{lockModesById:new Map,status:"ready"};const{value:I,status:E}=Ar(`contentControls:inRange:${Un(m)}`,ft(),()=>f.listInRange(b),ae=>ae&&Array.isArray(ae.items)?ae.items:[]),z=I??[],K=new Map;for(const ae of z)typeof ae?.id=="string"&&K.set(ae.id,typeof ae.lockMode=="string"?ae.lockMode:"unlocked");return{lockModesById:K,status:E}},Gf=(f,m)=>{const{lockModesById:b,status:I}=Ms(f,m);return{ids:[...b.keys()],status:I}},_a=()=>{const f=t?.fonts;return{options:rj(tj(Ot(f?.getDocumentFontOptions?()=>f.getDocumentFontOptions():void 0,[])),nj(Ot(f?.getFontFamilyOptions?()=>f.getFontFamilyOptions():void 0,[]))),sizeOptions:oj}},Aa=()=>{const f=Ot(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}},so=()=>Ot(t?.getMeasurementUnit?()=>t.getMeasurementUnit():void 0,"in")==="cm"?"cm":"in",Du=()=>{const f=A();return{ready:f!=null,mode:wr(),dirty:f?!!f.isDirty:!1}},gl=f=>{const m=f.quotedText;if(typeof m!="string"||m.length===0)return null;const b=Iu(f);if(b.length===0||!ec(b.map(z=>z.blockId)))return null;const I=f.target,E=b.length===1?So(b[0].blockId,I?.story):void 0;return{select:{type:"text",pattern:m,mode:"contains",caseSensitive:!0},...E?{within:E}:{},require:"any"}},Ls=f=>{const m=y()?.query;if(typeof m?.match!="function")return null;const b=gl(f);if(!b)return null;const{value:I}=Ar(`query:${Un(f)}`,ft(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return gA(I,f)},lc=f=>{const m=R(),b=new Set($r(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Ot(()=>{if(typeof I!="function")return E.call(m);const Qe=Qi(f);return Qe?I.call(m,[...b],Qe):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=c2(z),ae=Qe=>{const Je={},at=a2(Qe.fontFamily);at&&(Je.fontFamily=at);const ot=VV(Qe.fontSize);return ot&&(Je.fontSize=ot),typeof Qe.color=="string"&&Qe.color.trim()!==""&&(Je.color=Qe.color.trim().toUpperCase()),typeof Qe.highlight=="string"&&Qe.highlight.trim()!==""&&(Je.highlight=Qe.highlight.trim().toUpperCase()),Je},ue=dl(f),Le=ue&&typeof ue.range?.start=="number"?ue.range.start:null;if(ue&&Le!==null&&b.has(ue.blockId)){const Qe=K.find(at=>nc(at,ue.blockId)),Je=Qe&&Array.isArray(Qe.runs)?Qe.runs:null;if(Je&&Je.length>0&&Je.every(at=>at?.kind==="text"||at?.kind==="tab")){let at=0,ot=null;for(const Nt of Je){const qt=wm(Nt);if(Le>=at&&Le<at+qt){ot=Nt;break}at+=qt}if(!ot){for(let Nt=Je.length-1;Nt>=0&&!ot;Nt-=1)Je[Nt]?.kind==="text"&&(ot=Je[Nt]);ot??=Je[Je.length-1]??null}return ot?ae(ot):{}}}const Ue=Iu(f);if(Ue.length>0){const Qe=new Set,Je=new Set;let at=!1,ot=!0;for(const Nt of Ue){const qt=K.find(Qr=>nc(Qr,Nt.blockId));if(!qt)return{};const Qn=Array.isArray(qt.runs)?qt.runs:[];if(Qn.length===0)continue;if(!Qn.every(Qr=>Qr?.kind==="text"||Qr?.kind==="tab")){ot=!1;break}let tr=0;for(const Qr of Qn){const zr=wm(Qr),fn=tr,or=tr+zr;if(fn<Nt.end&&or>Nt.start){at=!0;const bo=ae(Qr);bo.fontFamily&&Qe.add(bo.fontFamily),bo.fontSize&&Je.add(bo.fontSize)}tr=or}}if(ot&&at){const Nt={};return Qe.size===1&&(Nt.fontFamily=[...Qe][0]),Je.size===1&&(Nt.fontSize=[...Je][0]),Nt}}const je=new Set,Ve=new Set;let Xe=!1;for(const Qe of K){if(![...b].some(at=>nc(Qe,at)))continue;const Je=Array.isArray(Qe.runs)?Qe.runs:[];for(const at of Je){if(at?.kind!=="text")continue;Xe=!0;const ot=ae(at);ot.fontFamily&&je.add(ot.fontFamily),ot.fontSize&&Ve.add(ot.fontSize)}}if(!Xe)return{};const $e={};return je.size===1&&($e.fontFamily=[...je][0]),Ve.size===1&&($e.fontSize=[...Ve][0]),$e},ns=f=>{const m=R(),b=new Set($r(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Ot(()=>{if(typeof I!="function")return E.call(m);const $e=Qi(f);return $e?I.call(m,[...b],$e):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=c2(z),ae=$e=>({bold:$e.bold===!0,italic:$e.italic===!0,underline:$e.underline!=null,strikethrough:$e.strike===!0}),ue=$e=>{const Qe={};for(const Je of Vf){const at=$e[Je];at.size===1&&(Qe[Je]=[...at][0])}return Qe},Le=dl(f),Ue=Le&&typeof Le.range?.start=="number"?Le.range.start:null;if(Le&&Ue!==null&&b.has(Le.blockId)){const $e=K.find(Je=>nc(Je,Le.blockId)),Qe=$e&&Array.isArray($e.runs)?$e.runs:null;if(Qe&&Qe.length>0&&Qe.every(Je=>Je?.kind==="text"||Je?.kind==="tab")){let Je=0,at=null;for(const ot of Qe){const Nt=wm(ot);if(Ue>=Je&&Ue<Je+Nt){at=ot;break}Je+=Nt}if(!at){for(let ot=Qe.length-1;ot>=0&&!at;ot-=1)Qe[ot]?.kind==="text"&&(at=Qe[ot]);at??=Qe[Qe.length-1]??null}return at?ae(at):{}}}const je=Iu(f);if(je.length>0){const $e={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Qe=!1,Je=!0;for(const at of je){const ot=K.find(Qn=>nc(Qn,at.blockId));if(!ot)return{};const Nt=Array.isArray(ot.runs)?ot.runs:[];if(Nt.length===0)continue;if(!Nt.every(Qn=>Qn?.kind==="text"||Qn?.kind==="tab")){Je=!1;break}let qt=0;for(const Qn of Nt){const tr=wm(Qn),Qr=qt,zr=qt+tr;if(Qr<at.end&&zr>at.start){Qe=!0;const fn=ae(Qn);for(const or of Vf)$e[or].add(fn[or])}qt=zr}}if(Je&&Qe)return ue($e)}const Ve={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Xe=!1;for(const $e of K){if(![...b].some(Je=>nc($e,Je)))continue;const Qe=Array.isArray($e.runs)?$e.runs:[];for(const Je of Qe){if(Je?.kind!=="text")continue;Xe=!0;const at=ae(Je);for(const ot of Vf)Ve[ot].add(at[ot])}}return Xe?ue(Ve):{}},vl=(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=lc(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=Fu(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"}},Ou=["fontFamily","fontSize","bold","italic","underline","strikethrough"],cc=f=>{const m=f.selectionTarget;if(!m)return{value:null,status:"ready"};const b=Sr(y(),"format.readEffectiveInlineUniformity");if(!b)return{value:null,status:"ready"};const I=mA(f)??Un(f);return Ar(`effInline:${I}`,ft(),()=>b({target:m,offsetSpace:"selection",keys:Ou}),E=>E&&typeof E=="object"?E:null)},Fu=f=>{const{value:m,status:b}=cc(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"?a2(K.value):K.value};return{values:{fontFamily:E("fontFamily"),fontSize:E("fontSize")},status:b}},Nu=f=>{const{value:m,status:b}=cc(f);if(!m||m.success!==!0)return{values:null,status:b};const I=m.values,E={};for(const z of Vf){const K=I?.[z];K?.state==="uniform"&&(K.value==="true"||K.value==="false")&&(E[z]=K.value==="true")}return{values:E,status:b}},uc=(f,m)=>{const b=f.activeMark;if(!b||!Vf.includes(b))return null;const I=b,E=ns(m)[I];if(E!==void 0)return E;const{values:z}=Nu(m),K=z?.[I];return K!==void 0?K:null},Wf=async f=>{const m=f.selectionTarget;if(!m)return null;const b=Sr(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}},Bu=(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"?a2(z.value):z.value:delete f[E]}},dc=f=>vl(f,vA(Ls(f),f)),yl=f=>dc(f).values,fc=async f=>{const m=y()?.query,b=gl(f);if(typeof m?.match!="function"||!b)return yl(f);try{const I=await Promise.resolve(m.match(b)),E=vA(gA(I&&typeof I=="object"?I:null,f),f),z=vl(f,E);if(z.effectiveUniformityStatus!=="ready"&&(E.fontFamily===void 0||E.fontSize===void 0)){const K=await Wf(f);K&&Bu(z.values,E,K)}return z.values}catch{return yl(f)}},Ia=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}))},zu=f=>{const m=y()?.query;if(typeof m?.match!="function")return"ready";const b=gl(f);if(!b)return"ready";const{status:I}=Ar(`query:${Un(f)}`,ft(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return I},rs=f=>{const m=dc(f),b=m.values;if(f.empty)return m;const I=wa(f);return I?f.status==="ready"&&zu(f)==="ready"&&m.effectiveUniformityStatus==="ready"?(C={key:I,values:b},m):C&&C.key===I?{...m,values:{...C.values,...b}}:m:m},Kf=f=>{const m=y(),b=rs(f),I=b.values;f.status==="ready"&&!f.empty&&zu(f)==="ready"&&b.effectiveUniformityStatus==="ready"&&(v=I,S=`${Ql(f)}:${ft()}`);const E=m?.contentControls,{lockModesById:z}=Ms(E,f),K={};for(const ae of le())K[ae]=hc(ae,m,f,I,z);return K},Yr=f=>f?dt.operationUnavailable:A()?dt.documentApiUnavailable:dt.notReady,Vu=f=>f==="contentLocked"||f==="sdtContentLocked",_i=f=>{for(const m of f.values())if(Vu(m))return dt.contentControlLocked},ju=(f,m,b,I,E)=>{if(!m)return f.scope==="all"?dt.bulkDecisionsDisabled:Yr(E);if(b)return dt.documentReadonly;if(f.scope!=="all"&&I.activeChangeIds.length===0)return dt.selectionRequired},qf=f=>{const m=R(),b=Ot(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},Ea=(f,m)=>{if(f.scope!=="all"||typeof m?.[`${f.kind}All`]=="function")return;const b=qf(`trackedChanges.${f.kind}All`);if(!(b&&(b.status==="supported"||b.enabled===!0)))return dt.bulkDecisionsDisabled},hc=(f,m,b,I,E=new Map)=>{if(oe.has(f))return sn({supported:!0,enabled:!0,...Ot(oe.get(f).getState?()=>oe.get(f).getState(Mu(void 0)):void 0,{})},"custom");const z=wr()==="viewing",K=sA(f);if(K&&typeof se()?.lists?.apply=="function"){const Xe=Ne(),$e=typeof Xe?.shippedStatus=="string"?Xe.shippedStatus:null,Qe=$e!=="not-shipped"&&$e!=="disabled";return sn({enabled:Qe&&(typeof Xe?.enabled=="boolean"?Xe.enabled:!0),active:(Qe?pe(Xe):null)===K,supported:Qe,value:Xe?.value},"builtin")}const ae=Cm(f);if(ae){const Xe=m?.trackChanges,$e=typeof Xe?.decide=="function"||typeof Xe?.[ae.kind]=="function",Qe=typeof Xe?.decide=="function"||typeof Xe?.[`${ae.kind}All`]=="function",Je=ae.scope==="all"?Qe:$e,at=Ea(ae,Xe)??ju(ae,Je,Es(),b,m);return sn({enabled:at==null,active:!1,supported:Je,reason:at},"builtin")}if(f==="copy-format")return wr()==="viewing"?sn({supported:!0,enabled:!1,active:!1},"builtin"):A()?sn({supported:!0,enabled:!0,active:h.mode!=="idle"},"builtin"):sn({supported:!0,enabled:!1,active:!1,reason:dt.notReady},"builtin");const ue=yu(f);if(!ue)return sn({enabled:!1,active:!1,supported:!1,reason:dt.commandUnsupported},"unsupported");if(ue.disposition!=="routed")return sn({enabled:!1,active:!1,supported:!1,reason:ue.reason??dt.commandUnsupported},ue.disposition==="unsupported"?"unsupported":"builtin");if(ue.instanceRoute)return M(ue);if(ue.table)return ne(ue,m,z);if(ue.inline?.kind==="clear"){if(ue.mutates&&z)return sn({enabled:!1,active:!1,supported:!0,reason:dt.documentReadonly},"builtin");const Xe=_i(E);if(Xe)return sn({enabled:!1,active:!1,supported:!0,reason:Xe},"builtin");const $e=$r(b).length>0||Eu(b)!=null;return sn({enabled:$e,active:!1,supported:!0,reason:$e?void 0:dt.selectionRequired},"builtin")}const Le=ue.docRoute;if(!Le)return sn({enabled:!1,active:!1,supported:!1,reason:dt.commandUnsupported},"unsupported");if(Sr(m,Le)==null)return sn({enabled:!1,active:!1,supported:!1,reason:Yr(m)},"builtin");const Ue=ye(f);if(Ue){const Xe=Ue.shippedStatus,$e=Xe!=="not-shipped"&&Xe!=="disabled",Qe=typeof Ue.enabled=="boolean"?Ue.enabled:!0,Je=f==="undo"||f==="redo",at=Je&&Ue.historyResolved===!1,ot=Je&&$e&&Qe===!1&&Ue.reason===null&&!at,Nt=Ue.reason===void 0?void 0:ot?dt.historyEmpty:at?dt.notReady:n2(Ue.reason,dt.commandUnsupported);return ue.mutates&&z?sn({enabled:!1,active:!1,supported:$e,reason:dt.documentReadonly},"builtin"):sn({enabled:$e&&Qe,active:!1,supported:$e,reason:Nt},"builtin")}const je=Ta(ue,m,b),Ve=Uu(ue,m,b,I);if(ue.list?.mode==="indent"||ue.list?.mode==="outdent")return kl(ue,m,z,b,je,Ve);if(ue.list?.mode==="toggle-seed")return Zf(ue,m,z,b,je,Ve);if(ue.mutates&&z)return sn({enabled:!1,active:je,supported:!0,value:Ve,reason:dt.documentReadonly},"builtin");if(ue.inline&&!Eu(b)){const Xe=_i(E);return sn(Xe?{enabled:!1,active:je,supported:!0,value:Ve,reason:Xe}:$r(b).length>0&&typeof R()?.setPendingInlineFormat=="function"?{enabled:!0,active:je,supported:!0,value:Ve}:{enabled:!1,active:je,supported:!0,value:Ve,reason:dt.rangeSelectionRequired},"builtin")}if((ue.blockParagraph||ue.list)&&$r(b).length===0)return sn({enabled:!1,active:je,supported:!0,value:Ve,reason:dt.selectionRequired},"builtin");if(ue.link&&!je&&i2(b).length===0&&!dl(b))return sn({enabled:!1,active:je,supported:!0,reason:dt.rangeSelectionRequired},"builtin");if(ue.inline){const Xe=_i(E);if(Xe)return sn({enabled:!1,active:je,supported:!0,value:Ve,reason:Xe},"builtin")}return sn({enabled:!0,active:je,supported:!0,value:Ve},"builtin")};function Yf(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 ae=typeof I?.offset=="number"?I.offset:null,ue=typeof E?.offset=="number"?E.offset:null;if(ae==null||ue==null)return!1;const Le=m.target,Ue=Le&&Array.isArray(Le.segments)?Le.segments:[];for(const je of Ue){const Ve=typeof je?.blockId=="string"?je.blockId:null;if(!Ve)continue;const Xe=je.range,$e=typeof Xe?.start=="number"?Xe.start:null,Qe=typeof Xe?.end=="number"?Xe.end:null;if(!($e==null||Qe==null)){if(z!==K){if(Ve===z&&Qe>ae||Ve===K&&$e<ue)return!0;continue}if(Ve===z){if($e===Qe){if($e>=ae&&$e<=ue)return!0;continue}if(Math.max($e,ae)<Math.min(Qe,ue))return!0}}}return!1}const pc=(f,m)=>{const b=f?.hyperlinks;if(!b||typeof b.list!="function")return null;const I=$r(m);if(!ec(I))return null;for(const E of I){const z={kind:"block",nodeType:"paragraph",nodeId:E},{value:K}=Ar(`hyperlinks:${E}`,ft(),()=>b.list({within:z}),ue=>ue&&typeof ue=="object"?ue:null),ae=(K&&Array.isArray(K.items)?K.items:[]).find(ue=>Yf(ue,m));if(ae)return ae}return null},Ta=(f,m,b)=>{if(f.link)return pc(m,b)!=null;if(f.list?.mode==="toggle-seed"&&f.list.seed)return Hu(m,b)===f.list.seed;const I=O(f);if(I!==null)return I;const E=r.get(f.id),z=wa(b);if(z&&E?.selectionSignature===z)return E.active;const K=uc(f,b);return K!==null?K:ij(f,b)},Uu=(f,m,b,I)=>{if(f.inline&&s2(f.inline.key)){const E=N(f);if(E!==void 0)return E;const z=I[f.inline.key];if(z!==void 0)return z;const K=wa(b),ae=K?n.get(f.inline.key):void 0;if(K&&ae?.selectionSignature===K)return ae.value}if(f.id==="linked-style"){const{style:E}=We(b,Ie().cache);return!E.styleId||E.mixed?void 0:{styleId:E.styleId,styleName:E.styleName}}if(f.id==="text-align")return Ds(m,b);if(f.id==="link")return k(m,b)??void 0},bl=(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:ba(m),story:b}):E&&typeof I.getState=="function"?()=>I.getState({target:ba(m)}):null;if(!z)return{value:null,status:"ready"};const{value:K,status:ae}=Ar(`lists:${xr(b)}:${m}`,ft(),z,ue=>ue&&typeof ue=="object"?ue:null);return{value:K?.success===!0?K:null,status:ae}},Ps=(f,m,b)=>bl(f,m,b).value,xa=(f,m,b)=>{const I=Ps(f,m,b);return!I||I.isListItem!==!0?null:I.seed==="bullet"||I.seed==="ordered"?I.seed:null},mc=(f,m,b)=>{const I=bl(f,m,b),E=I.value;return{value:E&&typeof E.isListItem=="boolean"?E.isListItem:null,status:I.status}},Hu=(f,m)=>{const b=$r(m);if(b.length===0||!ec(b))return null;const I=Zi(m),E=xa(f,b[0],I);if(E!=="bullet"&&E!=="ordered")return null;for(const z of b.slice(1))if(xa(f,z,I)!==E)return null;return E},gc=(f,m,b)=>{if(!f)return{value:null,status:"ready",refreshing:!1};const I=xr(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=ft(),ae=Ar(z,K,()=>E?f.getNodeById({nodeId:m,nodeType:"paragraph"}):f.getNode(So(m,b)),Le=>Le&&typeof Le=="object"?Le:null),ue=H.get(z);return{...ae,refreshing:ae.status==="stale"&&ue?.inflightToken===K&&ue.failedToken!==K}},vc=f=>f==="left"||f==="center"||f==="right"||f==="justify"?f:void 0,Xf=f=>f==="start"||f==="end"||f==="distributed"||f==="numTab"||f==="lowKashida"||f==="mediumKashida"||f==="highKashida"||f==="thaiDistribute",wl=(f,m)=>{const b=R(),I=b?.readMountedProjectionBlocksByIds;if(typeof I!="function")return null;const E=Qi(f),z=Ot(()=>E?I.call(b,[...m],E):I.call(b,[...m]),null);if(!Array.isArray(z))return new Map;const K=c2(z),ae=new Map;for(const ue of m){const Le=K.find(Xe=>nc(Xe,ue));if(!Le)continue;const Ue=Le.attrs,je=vc(Ue?.alignment),Ve=y9(Ue);ae.set(ue,je??(Ve==="rtl"?"right":"left"))}return ae},Cl=(f,m,b,I)=>{const{value:E,status:z,refreshing:K}=gc(f,m,b),ae=I?.get(m);if(z==="pending")return ae?{status:"uniform",value:ae}:{status:"pending"};if(z==="stale"&&!K)return{status:"pending"};if(z==="stale"&&ae)return{status:"uniform",value:ae};if(z==="stale"&&I&&!ae)return{status:"unavailable"};if(!E)return{status:"unavailable"};const ue=E.node;if(!ue)return{status:"unavailable"};const Le=ue.kind;if(Le!=="paragraph"&&Le!=="heading")return{status:"unavailable"};const Ue=ue[Le];if(!Ue||typeof Ue!="object")return{status:"unavailable"};const je=Ue.props?.alignment;if(je==null)return ae?{status:"uniform",value:ae}:{status:"unavailable"};const Ve=vc(je);return Ve?{status:"uniform",value:Ve}:Xf(je)&&ae?{status:"uniform",value:ae}:{status:"unavailable"}},$u=(f,m)=>{const b=$r(m);if(b.length===0||!ec(b))return{status:"unavailable"};const I=Zi(m),E=wl(m,b),z=Cl(f,b[0],I,E);if(z.status!=="uniform")return z;for(const K of b.slice(1)){const ae=Cl(f,K,I,E);if(ae.status!=="uniform")return ae;if(ae.value!==z.value)return{status:"mixed"}}return z},Gu=f=>{const m=$r(f);return m.length===0?null:`${xr(Zi(f))}:${m.join(",")}`},Ds=(f,m)=>{const b=$u(f,m),I=b.status==="uniform"?b.value:void 0,E=o;if(!E)return I;const z=Gu(m);return z&&z!==E.selectionSignature?(o=null,I):!z||!E.settled?E.value:b.status!=="pending"?(o=null,I):E.value},Gr=(f,m)=>{const b=vc(m),I=Gu(f),E=$r(f);if(!b||!I||E.length===0)return null;const z=++i;return o={selectionSignature:I,value:b,generation:z,settled:!1,canReconcile:ec(E)},j(),z},Wu=(f,m)=>{if(f==null)return;const b=o;if(!(!b||b.generation!==f)){if(!_o(m)){o=null;return}if(!b.canReconcile){o=null;return}b.settled=!0}},Ra=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:ba(m),story:b}):E&&typeof I.getState=="function"?await I.getState({target:ba(m)}):null,K=z&&typeof z=="object"?z:null;return!K||K.success!==!0||typeof K.isListItem!="boolean"?null:K.isListItem}catch{return null}},Ku=(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:ba(m),story:b}):z&&typeof E.getState=="function"?()=>E.getState({target:ba(m)}):null;if(!K)return I;const ae=ue=>{const Le=ue&&typeof ue=="object"?ue:null;return!Le||Le.success!==!0||typeof Le.isListItem!="boolean"?I:{resolved:!0,seed:Le.isListItem===!0&&(Le.seed==="bullet"||Le.seed==="ordered")?Le.seed:null}};try{const ue=K();return Tr(ue)?Promise.resolve(ue).then(ae,()=>I):ae(ue)}catch{return I}},qu=async(f,m,b)=>{if(!f)return null;try{const I=!b||b.storyType==="body",E=b&&typeof f.getNode=="function"?await f.getNode(So(m,b)):I&&typeof f.getNodeById=="function"?await f.getNodeById({nodeId:m,nodeType:"paragraph"}):null;return MV(E&&typeof E=="object"?E:null)}catch{return null}},kl=(f,m,b,I,E,z)=>{if(f.mutates&&b)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.documentReadonly},"builtin");const K=$r(I);if(K.length===0)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.selectionRequired},"builtin");const ae=f.docRoute?Sr(m,f.docRoute):null,ue=Sr(m,"format.paragraph.setIndentation"),Le=Sr(m,"format.paragraph.clearIndentation"),Ue=f.list?.mode,je=Ue==="indent"?ue!=null:ue!=null||Le!=null,Ve=Zi(I);let Xe=null;if(Ve.storyType!=="body"){Xe=[];for(const $e of K){const{value:Qe,status:Je}=mc(m,$e,Ve);if(Qe===null)return Je!=="ready"&&(ae!=null||je)?sn({enabled:!0,active:E,supported:!0,value:z},"builtin"):sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin");Xe.push(Qe)}}if(Xe?.some($e=>$e===!0)){const $e=Ue==="indent"?"lists.indentRange":"lists.outdentRange",Qe=wr()!=="suggesting"&&Xe.every(at=>at===!0)&&Sr(m,$e)!=null,Je=Ue==="outdent"&&Sr(m,"lists.outdentInStory")!=null;if(!Qe&&!Je)return sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin")}for(const[$e,Qe]of K.entries()){const Je=Xe?{value:Xe[$e]??null,status:"ready"}:mc(m,Qe,Ve),at=Je.value;if(at===!0){if(ae!=null)return sn({enabled:!0,active:E,supported:!0,value:z},"builtin");continue}if(at===!1&&je){if(Ve.storyType!=="body"&&typeof m?.getNode!="function")continue;return sn({enabled:!0,active:E,supported:!0,value:z},"builtin")}if(at===null)return Je.status!=="ready"&&(ae!=null||je)?sn({enabled:!0,active:E,supported:!0,value:z},"builtin"):sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin")}return sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin")},Zf=(f,m,b,I,E,z)=>{if(f.mutates&&b)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.documentReadonly},"builtin");const K=$r(I);if(K.length===0)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.selectionRequired},"builtin");const ae=Zi(I),ue=m?.lists;if(!(typeof ue?.getStateInStory=="function"||ae.storyType==="body"&&typeof ue?.getState=="function"))return sn({enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");if(!ec(K))return sn(ae.storyType==="body"&&Sr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");const Le=K.map(Xe=>bl(m,Xe,ae));if(Le.some(({status:Xe})=>Xe!=="ready"))return sn({enabled:!0,active:E,supported:!0,value:z},"builtin");if(Le.some(({value:Xe})=>Xe===null))return sn({enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");const Ue=f.list?.seed,je=Le.every(({value:Xe})=>Xe?.isListItem===!0&&Xe.seed===Ue);if(ae.storyType==="body")return sn(!je||Sr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");const Ve=Sr(m,"lists.removeInStory");return sn(je&&Ve?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin")},k=(f,m)=>{const b=pc(f,m)?.properties?.href;return typeof b=="string"?b:null},M=f=>{if(!A())return sn({enabled:!1,active:!1,supported:!1,reason:dt.notReady},"builtin");const m=f.instanceRoute;return typeof t?.[m]!="function"?sn({enabled:!1,active:!1,supported:!1,reason:dt.operationUnavailable},"builtin"):sn({enabled:!0,active:Y(f),supported:!0,value:ie(f)},"builtin")},Y=f=>{const m=t?.config??void 0;return f.valueFrom==="ruler"?!!m?.rulers:f.valueFrom==="formattingMarks"?!!m?.layoutEngineOptions?.showFormattingMarks:!1},ne=(f,m,b)=>{if(b)return sn({enabled:!1,active:!1,supported:!0,reason:dt.documentReadonly},"builtin");const I=_e();return I!=null&&(!f.table.requiresCell||I.cellNodeId!=null)?(f.docRoute?Sr(m,f.docRoute):null)==null?sn({enabled:!1,active:!1,supported:!1,reason:Yr(m)},"builtin"):sn({enabled:!0,active:!1,supported:!0},"builtin"):sn({enabled:!1,active:!1,supported:!0,reason:dt.tableContextUnavailable},"builtin")},ie=f=>{if(f.valueFrom==="zoom")return Aa().value;if(f.valueFrom==="documentMode")return wr();if(f.valueFrom==="measurementUnit")return so();if(f.valueFrom==="ruler"||f.valueFrom==="formattingMarks")return Y(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([...pN,...oe.keys()])],ce="Normal",Ce={ready:!1,status:"ready",catalogRevision:null,quickGallery:[],activeParagraphStyleId:null,activeParagraphStyleName:null,mixedSelection:!1,sourceStatus:null,diagnostics:[]},Ae=f=>{const m=y()?.styles;return!m||typeof m.getCatalog!="function"?{value:null,status:"ready"}:Ar(`styles:catalog:${JSON.stringify(f??{})}`,ft(),()=>m.getCatalog(f),b=>b&&typeof b=="object"?b:null)},Ie=()=>{const f=Ae({includePreview:!0});if(!f.value)return{cache:null,status:f.status};const m=Ae({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:ku(f.status,m.status)}},ze=(f,m,b)=>{const{value:I,status:E}=gc(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,ae=typeof K=="string"?z[K]:void 0,ue=ae&&typeof ae=="object"?ae.styleRef:void 0;return{ok:!0,styleRef:typeof ue=="string"&&ue.length>0?ue:null,status:E}},We=(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=$r(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(!ec(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?ce:null),K=new Set;let ae=0,ue=0,Le=0,Ue="ready";const je=Zi(f);for(const $e of E){const Qe=ze(I,$e,je);if(Ue=ku(Ue,Qe.status),!Qe.ok){ue+=1;continue}if(!Qe.styleRef&&!z){Le+=1;continue}const Je=Qe.styleRef??z;if(!Je){Le+=1;continue}ae+=1,K.add(Je)}if(ae===0){const $e=Le>0&&ue===0;return b.push({severity:"warning",code:$e?"active-style-default-unavailable":"active-style-read-failed",message:$e?"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 Ve=ue+Le;if(Ve>0)return b.push({severity:"warning",code:"active-style-partial",message:`Active paragraph style resolved from ${ae} of ${ae+Ve} selected blocks; ${Ve} 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}},ut=f=>{if(!A())return Ce;const{cache:m,status:b}=Ie(),{style:I,status:E}=We(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:ku(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}},Ye=()=>{const f=wr(),m=oc();m.status==="ready"&&Hf(m),q(m);const b=wa(m);for(const[I,E]of r)(!b||E.selectionSignature!==b||E.settled&&m.status==="ready")&&r.delete(I);return{ready:A()!=null,documentMode:f,document:Du(),selection:m,toolbar:{context:f,commands:Kf(m),copyFormatActive:h.mode!=="idle"},comments:Sa(m),trackChanges:Pu(m),contentControls:ac(m),zoom:Aa(),fonts:_a(),styles:ut(m)}},pt=f=>{const m=wa(f);m&&a&&m!==a&&(n.clear(),r.clear()),m&&(a=m)};let et=null,At=null,Gt=null,kt=null,cr=null,In=null,jt=!1;const en=()=>{if(U||jt)return;jt=!0;const f=()=>{jt&&(jt=!1,!U&&j())};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Xr=()=>{const f=se();if(f!==Gt&&(kt&&(kt(),kt=null),Gt=f,!(!f||typeof f.subscribe!="function")))try{const m=f.subscribe(()=>en());typeof m=="function"&&(kt=m)}catch{Gt=null}},Rr=()=>{const f=x();if(f!==cr&&(In&&(In(),In=null),cr=f,!(!f||typeof f.subscribe!="function")))try{const m=f.subscribe(()=>j());typeof m=="function"&&(In=m)}catch{cr=null}};let Zr=null,Wr=null,ct=null,un=null,yo=null,Yo=null;const Xo=()=>{const f=A()?.host,m=Ot(f?.getHandles?()=>f.getHandles():void 0,null)?.editing?.selection;return m&&typeof m.subscribe=="function"?m:null},Os=()=>{const f=Xo();if(f!==et&&(At&&(At(),At=null),et=f,!!f))try{const m=f.subscribe(b=>{qe+=1,sc(b),j()});typeof m=="function"&&(At=m)}catch{et=null}},Ma=()=>{const f=A()?.host,m=Ot(f?.getHandles?()=>f.getHandles():void 0,null)?.review;return m&&typeof m.subscribe=="function"?m:null},di=f=>f?typeof f.getActiveReviewTarget=="function"?Ot(()=>f.getActiveReviewTarget(),null):typeof f.getSnapshot=="function"?Ot(()=>f.getSnapshot(),null)?.activeReviewTarget??null:null:null;let Zo=0;const Qo=(f,m)=>{const b=(m&&typeof m=="object"?m:null)?.lastInteractionRejection;if(Zo>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,ae=Rs(),ue=(ae?K?_u(ae,K).toPublicId(z):ya(ae).toPublicId(z):null)??z,Le=K&&xr(K)!==xr(null)?K:void 0;E={id:ue,...Le?{story:Le}:{},...typeof I.paintedEntityId=="string"&&I.paintedEntityId.length>0?{paintedEntityId:I.paintedEntityId}:ue!==z?{paintedEntityId:z}:{}}}return f==null&&E==null&&Ge!=null&&ee(Ge)||tt(Ge,E)?!1:(te(E),!0)},Fs=()=>{const f=Ma();if(f===Zr)return;if(Wr&&(Wr(),Wr=null),Zr=f,!f){Qo(null);return}let m=!0;try{const b=f.subscribe(I=>{const E=I&&typeof I=="object"?I:null,z=E&&Object.prototype.hasOwnProperty.call(E,"activeReviewTarget")?E.activeReviewTarget:di(f);!Qo(z,I)||m||j()});typeof b=="function"&&(Wr=b),Qo(di(f))}catch{Zr=null}finally{m=!1}},Sl=()=>{if(et||wr()!=="viewing")return null;const f=A()?.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},La=()=>{const f=Sl();if(f===yo||(Yo&&(Yo(),Yo=null),yo=f,!f))return;const m=()=>{qe+=1,j()};f.addEventListener("selectionchange",m),f.addEventListener("pointerup",m,!0),f.addEventListener("mouseup",m,!0),Yo=()=>{f.removeEventListener("selectionchange",m),f.removeEventListener("pointerup",m,!0),f.removeEventListener("mouseup",m,!0)}};rc(),Qo(di(Ma()));let ht=Ye();a=wa(ht.selection);const P=()=>{const f=A()?.host?.events,m=f&&typeof f.subscribe=="function"?f:null;if(m!==ct&&(un&&(un(),un=null),ct=m,!!m))try{const b=m.subscribe(I=>{const E=I?.type;if(E==="review-mutation:started"){wn(I.reviewMutation?.token);return}if(E==="review-mutation:aborted"){Wn(I.reviewMutation?.token),yt();return}if(E==="mutation:rejected"&&I.reviewMutation&&(Wn(I.reviewMutation.token),yt()),E==="mutation:committed"&&I.reviewMutation&&Wn(I.reviewMutation.token),E==="source:complete"||E==="source:signals-complete"){jn!==null&&(Nr(),lr.onRender(!0));return}if((E==="mutation:committed"||E==="collaboration:remote-changed")&&(xo=Date.now()),E==="mutation:committed"&&(Nr(),rt={}),E==="mutation:committed"||E==="save:completed"||E==="collaboration:remote-changed"){const z=E==="mutation:committed"?Dk(I):null,K=E==="mutation:committed"&&lr.getPendingIds().size>0;if(z?.allResolved){lr.reset(),On([]),jn=null,Io(I.receipt);return}z?.removedIds.size&&Eo(new Set(z.removedIds),I.receipt);const ae=z?.reconcileMode==="authoritative"&&z.upsertIds.size>0;if(ae&&(Mo(),Nr(),jn=ft(),j()),z?.upsertIds.size||K){const je=I.origin==="history"?null:I.receipt,Ve=A()?.documentMutationReadiness,Xe=typeof je?.txId=="string"&&je.txId.length>0&&typeof Ve?.whenPainted=="function",$e=I.origin==="history"&&typeof Ve?.getRenderEpoch=="function"?Ot(()=>Ve.getRenderEpoch.call(Ve),null):null,Qe=I.origin==="history"&&typeof Ve?.whenPainted=="function",Je={upsertIds:z?.upsertIds??new Set,removedIds:new Set,reconcileMode:z?.reconcileMode==="authoritative"?"authoritative":"targeted"};Xe?lr.enqueueAfterPaint(Je,()=>Ve.whenPainted.call(Ve,je)):Qe?lr.enqueueAfterPaint(Je,()=>Ve.whenPainted.call(Ve,typeof $e=="number"?{afterEpoch:$e}:void 0)):(lr.enqueue(Je),lr.onRender(K))}if(ae)return;const ue=E==="mutation:committed"&&Tu(I)||E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0;if(ue&&(Di=Date.now()),E==="mutation:committed"&&ue){Ca();return}if(z?.removedIds.size&&z.upsertIds.size===0)return;(E==="collaboration:remote-changed"||E==="mutation:committed"&&!ue)&&jf();const Le=E==="collaboration:remote-changed"&&Array.isArray(I.changedPartUris)&&I.changedPartUris.some(je=>typeof je=="string"&&vV.has(je)),Ue=E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0&&He();Le&&!ue&&(Ro=!0),Mo(),Le&&!ue?ke("comments"):Ue&&(Ro=!0,io()),j()}});typeof b=="function"&&(un=b)}catch{ct=null}},j=()=>{if(U)return;jt=!1,rc(),Os(),Xr(),Rr(),Fs(),La(),P();const f=Ye();pt(f.selection),ht=f;for(const m of[...D])m(ht)},Se=[],Pe=[],mt=f=>{for(const m of f)try{m()}catch{}},nn=()=>mt(Se),Cn=()=>mt(Pe),Zn=[];((f,m)=>{if(!(!f||typeof f.on!="function"))for(const b of m){const I=b==="active-editor-change"?()=>{nn(),Cn(),j()}:b==="document-replaced"?E=>{const z=E&&typeof E=="object"?E:null,K=z?.editor,ae=z?.host,ue=!!K&&K===A(),Le=!!ae&&ae===R();!ue&&!Le||(Cn(),H.clear(),Mo(),j())}:()=>j();try{f.on(b,I),Zn.push(()=>{try{typeof f.off=="function"&&f.off(b,I)}catch{}})}catch{}}})(t,dV),Os(),Xr(),Rr(),Fs(),La(),P();const gn=(f,m=qz)=>({get:()=>f(ht),subscribe:b=>{let I=f(ht);const E=z=>{const K=f(z);m(I,K)||(I=K,b(K))};return D.add(E),()=>D.delete(E)}}),ln=f=>gn(f),qn=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 Rt(f){return f&&typeof f=="object"&&typeof f.id=="string"?String(f.id):null}function kn(f){const m=Qi(f);return m&&xr(m)!==xr(null)?m:void 0}function ur(f,m){return{kind:"id",id:f,...m?{story:m}:{}}}function En(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 Ir(f,m){if(xr(m)!==xr(null))return;const b=y()?.trackChanges,I=b?.list;if(typeof I!="function")return;const E=Ot(()=>I.call(b),null);if(Tr(E)||!E||typeof E!="object")return;const z=E.items;if(Array.isArray(z))return z.map(fl).find(K=>K!=null&&Xi(K,f,m))}function $o(f,m){const b=Ns(f.quotedText);if(!b)return!1;const I=ym(m);return[I.insertedText,I.deletedText,I.excerpt].some(E=>Ns(E)===b)}function Ns(f){return typeof f=="string"?f.replace(/\s+/g," ").trim():""}function Bs(){const f=ht.selection.activeChangeIds[0];if(!f)return"unavailable";const m=Qi(ht.selection),b=(ht.trackChanges.status==="ready"?ht.trackChanges.items.find(K=>Xi(K,f,m)):void 0)??Ir(f,m)??Rs()?.find(K=>Xi(K,f,m));if(!b)return"unavailable";const I=ym(b),E=I.type,z=I.grouping;return $o(ht.selection,b)?"id":E==="replacement"&&z==="replacement-pair"||(E==="insertion"||E==="deletion"||E==="insert"||E==="delete")&&z==="standalone"?"range":"id"}function yc(f,m,b,I){const E=()=>w2(f,ur(b,I),b,I);try{const z=w2(f,m,null);if(Tr(z))return Bn(Promise.resolve(z).then(ae=>_o(As(ae))?ae:E()));const K=As(z);return Bn(_o(K)?z:E())}catch{return!1}}function Yu(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:Rt(K),story:K.story}}const z=typeof E.changeId=="string"?E.changeId:E.id;if(typeof z=="string"&&z.length>0)return{target:ur(z,E.story),changeId:z,story:E.story}}const b=ht.selection.activeChangeIds[0],I=kn(ht.selection);return b?{target:ur(b,I),changeId:b,story:I}:null}function Xu(f,m){if(f.scope==="id"&&m==null){if(ht.selection.activeChangeIds.length>1)return th(f.kind,{kind:"ids",ids:ht.selection.activeChangeIds},null);if(ht.selection.activeChangeIds.length===1&&!ht.selection.empty&&ht.selection.selectionTarget){const I=Bs();if(I==="unavailable")return!1;if(I==="range"){const E=En(ht.selection),z=kn(ht.selection);return E?yc(f.kind,E,ht.selection.activeChangeIds[0],z):!1}if(I==="id"){const E=ht.selection.activeChangeIds[0],z=Qi(ht.selection),K=z&&xr(z)!==xr(null)?z:void 0;return b2(f.kind,K?{id:E,story:K}:E)}}}const b=Yu(f,m);return b?th(f.kind,b.target,b.changeId,b.story):!1}function _l(f,m){const b=se()?.lists,I=b?.apply;if(typeof I!="function")return!1;const{behavior:E,preset:z,continuity:K}=typeof m=="string"?pV(m):m&&typeof m=="object"?m:{},ae={kind:f,behavior:E??"toggle"};z!==void 0&&(ae.preset=z),K!==void 0&&(ae.continuity=K);try{return Bn(I.call(b,ae))}catch{return!1}}let Ln=Promise.resolve(!1),fi=null,Zu=Promise.resolve(!1);const bc=async f=>{if(!bm(f))return f;const m=A()?.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},Jo=f=>{if(Tr(f)){const b=Promise.resolve(f);return{immediate:!0,committed:b.then(I=>As(I),()=>!1),settled:b.then(I=>bc(As(I)),()=>!1)}}const m=As(f);return{immediate:m,committed:Promise.resolve(m),settled:bc(m)}},_m=()=>{const f=s.shift();if(!f){c=!1,d?.(),d=null;return}try{f.resolve(U?!1:f.mutate())}catch{f.resolve(!1)}},Qf=()=>{let f=!1;return()=>{f||(f=!0,_m())}},Am=(f,m)=>{if(!c){c=!0,u=new Promise(z=>{d=z});try{return{result:m(),release:Qf()}}catch(z){throw c=!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:Qf()}},p2=new Set(["create.tableOfContents"]),Im=f=>nr(`Tracked authoring is not supported for ${f}.`),Pa=f=>{if(wr()==="suggesting")return p2.has(f)?Im(f):{changeMode:"tracked"}},Qu=()=>wr()==="suggesting"?qV:d2,Mr=(f,m,b)=>{const I=Pa(f);return I&&I.success===!1?I:I?m(b,I):m(b)},Mt=(f,m,b,I)=>{const E=f.inline;if(!E)return;const z=As(I);if(z===!1||typeof z=="object"&&z&&z.success===!1)return;if(E.kind==="clear"){n.clear();return}if(E.kind==="toggle"||!s2(E.key))return;const K=wa(m);if(!K)return;const ae=OV(E.key,b.value);if(ae==null){n.delete(E.key);return}n.set(E.key,{selectionSignature:K,value:ae})},Wt=(f,m,b,I)=>!f.inline||f.inline.kind==="toggle"?I:Tr(I)?Promise.resolve(I).then(E=>(Mt(f,m,b,E),E)):I,vn=(f,m,b,I)=>{if(f.inline?.kind!=="toggle"||!_o(As(I))||typeof b.value!="boolean"&&b.value!==null)return null;const E=wa(m);if(!E)return null;const z=++l;return r.set(f.id,{selectionSignature:E,active:b.value===!0,generation:z,settled:!1}),j(),z},Lr=(f,m,b)=>{if(m==null)return;const I=r.get(f.id);if(!(!I||I.generation!==m)){if(!_o(b)){r.delete(f.id);return}I.settled=!0}},Pr=(f,m)=>f.then(b=>(m?.(b),ci(),b),()=>(m?.(!1),ci(),!1)),Bn=(f,m)=>{const b=fi;if(fi=null,b)return Ln=Pr(b,m),As(f);if(Tr(f))return Ln=Pr(Jo(f).settled,m),!0;const I=As(f);return bm(I)&&typeof A()?.documentMutationReadiness?.whenPainted=="function"?(Ln=Pr(bc(I),m),I):(m?.(I),Ln=Promise.resolve(I),ci(),I)},Ai=(f,m)=>!f||typeof f!="object"?m:f,Lo=(f,m=nr("Document API operation failed."))=>{if(Tr(f))return Promise.resolve(f).then(I=>Lo(I,m),()=>m);const b=Ai(f,m);return Mo(),bm(b)&&typeof A()?.documentMutationReadiness?.whenPainted=="function"?(Pr(bc(b)),j(),b):(j(),b)},Ju=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const ae=I(K);if(ae)try{const ue=Jo(Mr(f,m,ae));E.push(ue.immediate),z.push(ue.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return fi=z.length?Promise.all(z).then(K=>Ci(K)):null,Ci(E)},Rj=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const ae=I(K);if(ae)try{const ue=Jo(Mr(f,m,ae));E.push(ue.immediate),z.push(ue.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return fi=z.length?Promise.all(z).then(K=>Ci(K)):null,Ci(E)},m2=(f,m,b,I=ht.selection)=>{const E=Pa(f);return E&&E.success===!1?E:I.selectionTarget?m(b,{...E??{},offsetSpace:"selection"}):E?m(b,E):m(b)},Mj=(f,m,b,I)=>{const E=So(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}},Lj=(f,m)=>{const b=f.inline,I=u2(f),E=R();if(!b||typeof E?.setPendingInlineFormat!="function")return!1;if(b.kind==="clear")return B(),!0;if(!I)return!1;let z;if(b.kind==="toggle")z=!Ta(f,y(),ht.selection);else{const K=m&&typeof m=="object"&&"value"in m?m.value:m;if(b.kind==="value-number"){const ae=typeof K=="number"?K:Number(K);z=Number.isFinite(ae)&&ae>0?ae:null}else z=typeof K=="string"&&K.trim()!==""?K:null;if(z===null)return T(I,null),!0}return T(I,z),!0},Pj=()=>{const f=y(),{lockModesById:m}=Ms(f?.contentControls,ht.selection);if(_i(m))return!1;const b=[],I=[],E=Xe=>{const $e=Jo(Xe);b.push($e.immediate),I.push($e.settled)},z=(Xe,$e,Qe)=>{try{E(Qe?Xe($e,Qe):Xe($e))}catch{b.push(!1),I.push(Promise.resolve(!1))}},K=Ie().cache?.full.defaults.paragraphStyleId??ce,ae=Eu(ht.selection);if(ae){const Xe=Sr(f,"format.apply");if(Xe)try{E(m2("format.apply",Xe,{target:ae,inline:{...Qu()}}))}catch{b.push(!1),I.push(Promise.resolve(!1))}}const ue=Sr(f,"format.paragraph.resetDirectFormatting"),Le=Sr(f,"styles.paragraph.setStyleRef"),Ue=Qi(ht.selection),je=!Ue||Ue.storyType==="body",Ve=Sr(f,je?"lists.remove":"lists.removeInStory");for(const Xe of $r(ht.selection)){const $e=So(Xe,Ue);if(ue&&z(ue,{target:$e}),Ve)try{const Qe=ba(Xe),Je=Jo(Ve(je?{target:Qe}:{target:Qe,story:Ue}));I.push(Je.settled.then(at=>_o(at)?at:!0))}catch{}Le&&z(Le,{target:$e,styleId:K})}if(!ae&&wr()!=="suggesting"){const Xe=Sr(f,"format.paragraph.setMarkRunProps");if(Xe)for(const $e of $r(ht.selection))z(Xe,{target:So($e,Ue),markRunProps:{bold:!1,italic:!1,strikethrough:!1,doubleStrikethrough:!1,smallCaps:!1,caps:!1,verticalAlign:"baseline"}})}return fi=I.length?Promise.all(I).then(Xe=>Ci(Xe)):null,Ci(b.length?b:[!1])},Dj=(f,m,b)=>{const I=$r(ht.selection);if(I.length===0)return!1;const E=Qi(ht.selection);return Ju(f.docRoute,m,I,z=>Mj(f.blockParagraph,z,b,E))},Oj=(f,m,b)=>{const I=y(),E=Sr(I,"format.paragraph.setIndentation"),z=Sr(I,"format.paragraph.clearIndentation"),K=f.list?.mode,ae=Zi(ht.selection),ue=Qi(ht.selection),Le=async Ue=>{const je=await Ra(I,Ue,ae);if(je===!0)return{kind:"list",routeToCall:f.docRoute,opToCall:m,input:{target:fA(Ue)}};if(je===null||ue&&ue.storyType!=="body"&&typeof I?.getNode!="function")return null;const Ve=await qu(I,Ue,ue),Xe={};if(Ve?.right!=null&&(Xe.right=Ve.right),Ve?.firstLine!=null&&(Xe.firstLine=Ve.firstLine),Ve?.hanging!=null&&(Xe.hanging=Ve.hanging),K==="indent")return E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:So(Ue,ue),left:Math.max(0,Ve?.left??0)+hA,...Xe}}:null;const $e=Math.max(0,(Ve?.left??0)-hA);return $e>0&&(Xe.left=$e),Object.keys(Xe).length===0?z?{kind:"paragraph",routeToCall:"format.paragraph.clearIndentation",opToCall:z,input:{target:So(Ue,ue)}}:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:So(Ue,ue),left:0}}:null:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:So(Ue,ue),...Xe}}:null};return fi=(async()=>{const Ue=await Promise.all(b.map($e=>Le($e).catch(()=>null)));if(Ue.length===b.length&&Ue.every($e=>$e?.kind==="list")&&wr()!=="suggesting"){const $e=K==="indent"?"lists.indentRange":"lists.outdentRange",Qe=Sr(I,$e);if(Qe)try{return await Jo(Mr($e,Qe,{paraIds:b,story:ae})).settled}catch{return!1}}const je=ae.storyType!=="body"&&Ue.some($e=>$e?.kind==="list"),Ve=je&&K==="outdent"?Sr(I,"lists.outdentInStory"):null;if(je&&!Ve)return!1;const Xe=Ue.map($e=>{if(!$e)return Promise.resolve(!1);try{return $e.kind==="list"&&Ve?Jo(Mr("lists.outdentInStory",Ve,{target:$e.input.target,story:ae})).settled:Jo(Mr($e.routeToCall,$e.opToCall,$e.input)).settled}catch{return Promise.resolve(!1)}});return Ci(await Promise.all(Xe))})(),!0},Fj=(f,m)=>{const b=f.list,I=y(),E=$r(ht.selection);if(E.length===0)return!1;const z=Zi(ht.selection),K=z.storyType==="body";if(b.mode==="indent"||b.mode==="outdent")return Oj(f,m,E);const ae=b.seed,ue=je=>{if(je.some(at=>!at.resolved))return{immediate:!1,settled:null};const Ve=je.every(at=>at.seed===ae);if(!Ve&&!K)return{immediate:!1,settled:null};const Xe=Ve?K?"lists.remove":"lists.removeInStory":f.docRoute,$e=Ve?Sr(I,Xe):m;if(!$e)return{immediate:!1,settled:null};const Qe=[],Je=[];return E.forEach((at,ot)=>{if(!Ve&&je[ot]?.seed===ae)return;const Nt=Ve?{target:ba(at),...K?{}:{story:z}}:{target:ba(at),seed:ae};try{const qt=Jo(Mr(Xe,$e,Nt));Qe.push(qt.immediate),Je.push(qt.settled)}catch{Qe.push(!1),Je.push(Promise.resolve(!1))}}),{immediate:Ci(Qe),settled:Je.length?Promise.all(Je).then(at=>Ci(at)):null}},Le=E.map(je=>Ku(I,je,z));if(Le.some(Tr))return fi=Promise.all(Le).then(async je=>{const Ve=ue(je);return Ve.settled?await Ve.settled:Ve.immediate}),!0;const Ue=ue(Le);return fi=Ue.settled,Ue.immediate};function Jf(f){return f&&typeof f=="object"?f:{}}function Nj(f){if(typeof f=="string")return f;const m=Jf(f);if(Object.prototype.hasOwnProperty.call(m,"href"))return m.href;if(Object.prototype.hasOwnProperty.call(m,"value"))return m.value}function Bj(f,m){const b=Jf(f).text;return typeof b=="string"&&b.trim()!==""?b:m}function _A(f){const m=Jf(f),b=m.capture&&typeof m.capture=="object"?m.capture:null;return m.target??b?.target??b?.selectionTarget??m.selectionTarget??m.textTarget??null}const zj=f=>{const m=y(),b=m?.hyperlinks;if(!b)return!1;const I=Jf(f),E=Nj(f),z=_A(f),K=typeof I.text=="string"?I.text:void 0,ae=typeof I.currentText=="string"?I.currentText:void 0,ue=tc(I.hyperlinkTarget)?I.hyperlinkTarget:null,Le=tc(I.textTarget)?I.textTarget:null,Ue=pc(m,ht.selection),je=typeof ue?.storyId=="string"&&typeof ue?.hyperlinkNodeId=="string";if(je&&E===null){const Ve=b.remove;if(typeof Ve!="function")return!1;try{return Mr("hyperlinks.remove",Ve,{storyId:ue.storyId,hyperlinkNodeId:ue.hyperlinkNodeId,keepText:!0})}catch{return!1}}if(Ue&&E===null){const Ve=b.remove;if(typeof Ve!="function")return!1;try{return Mr("hyperlinks.remove",Ve,{target:Ue.address,mode:"unwrap"})}catch{return!1}}if((Ue||ue)&&typeof E=="string"&&E.trim()!==""){const Ve=b.patch,Xe=b.updateTarget;if(!(!je&&Ue&&typeof Ve=="function")&&!(je&&typeof Xe=="function"))return!1;const $e=typeof K=="string"&&K!==(je?ae:Ue?.text??ae),Qe=m?.text?.replace,Je=$e?je?Le:UV(Ue?.address):null,at=$e&&!!Je&&typeof Qe=="function";if($e&&!at)return!1;const ot=[],Nt=[];let qt=null,Qn=null,tr=null,Qr=!1;try{if(je){if(typeof Xe!="function")return!1;const zr=Mr("hyperlinks.updateTarget",Xe,{storyId:ue.storyId,hyperlinkNodeId:ue.hyperlinkNodeId,newTarget:HV(E)});Qr=Tr(zr);const fn=Jo(zr);if(!_o(fn.immediate))return!1;ot.push(fn.immediate),Nt.push(fn.settled),qt=fn.immediate,Qn=fn.committed,tr=fn.settled}else if(Ue){if(typeof Ve!="function")return!1;const zr=Mr("hyperlinks.patch",Ve,{target:Ue.address,patch:{href:E}});Qr=Tr(zr);const fn=Jo(zr);if(!_o(fn.immediate))return!1;ot.push(fn.immediate),Nt.push(fn.settled),qt=fn.immediate,Qn=fn.committed,tr=fn.settled}}catch{return!1}if(at){const zr=(or,bo)=>_o(bo)?Ci([or,bo]):_o(or)?Nf(or,bo):bo,fn=or=>{if(!_o(or))return or;try{const bo=Jo(Mr("text.replace",Qe,{target:Je,text:K}));return _o(bo.immediate)?Promise.all([tr??Promise.resolve(or),bo.settled]).then(([rd,kU])=>zr(rd,kU)):Nf(or,bo.immediate)}catch{return Nf(or,!1)}};if(Qr)return fi=(Qn??Promise.resolve(qt??!1)).then(fn),Ci(ot);try{const or=Jo(Mr("text.replace",Qe,{target:Je,text:K}));if(!_o(or.immediate))return qt?Nf(qt,or.immediate):or.immediate;ot.push(or.immediate),Nt.push(or.settled),fi=Promise.all([tr??Promise.resolve(qt??!1),or.settled]).then(([bo,rd])=>zr(bo,rd))}catch{return qt?Nf(qt,!1):!1}}return!at&&Nt.length>0&&(fi=Promise.all(Nt).then(zr=>Ci(zr))),Ci(ot)}if(typeof E=="string"&&E.trim()!==""){const Ve=E.trim(),Xe=b.wrap,$e=LV(z),Qe=$e.length>0?$e:i2(ht.selection);if(Qe.length>0){if(typeof Xe!="function")return!1;try{return Rj("hyperlinks.wrap",Xe,Qe,Nt=>({target:Nt,link:{destination:{href:Ve}}}))}catch{return!1}}const Je=b.insert,at=Bj(f,Ve);if(typeof Je!="function"||at.trim()==="")return!1;const ot=zf(z)??dl(ht.selection);if(!ot)return!1;try{return Mr("hyperlinks.insert",Je,{target:ot,text:at,link:{destination:{href:Ve}}})}catch{return!1}}return!1},Vj=(f,m,b)=>{const I=f.create.kind,E=b&&typeof b=="object"?b:{};if(I==="table"){const K=Number(E.rows??E.rowCount),ae=Number(E.columns??E.cols??E.colCount);if(!Number.isInteger(K)||K<1||!Number.isInteger(ae)||ae<1)return!1;const ue=dl(ht.selection),Le=ue&&typeof ue.blockId=="string"?{kind:"inParagraph",target:So(ue.blockId),offset:ue.range?.start??0}:l2(ht.selection,"nodeId");try{return Mr(f.docRoute,m,{rows:K,columns:ae,at:Le})}catch{return!1}}if(I==="image"){const K=E.src??E.value;if(typeof K!="string"||K.trim()==="")return!1;const ae=dl(ht.selection),ue=Zi(ht.selection),Le=ue.storyType==="body"?null:ue;let Ue;ae&&typeof ae.blockId=="string"?Ue={kind:"inParagraph",target:So(ae.blockId,Le),offset:ae.range?.start??0}:(Ue=l2(ht.selection,"target"),Le&&Ue.kind==="after"&&(Ue={...Ue,target:{...Ue.target,story:Le}}));const je={src:K,at:Ue};Le&&(je.in=Ue.kind==="inParagraph"?F(Le)??Le:Le),typeof E.alt=="string"&&(je.alt=E.alt),typeof E.title=="string"&&(je.title=E.title),E.size&&typeof E.size=="object"&&(je.size=E.size);try{return Mr(f.docRoute,m,je)}catch{return!1}}const z={at:l2(ht.selection,"target")};typeof E.instruction=="string"&&(z.instruction=E.instruction),E.config&&typeof E.config=="object"&&(z.config=E.config);try{return Mr(f.docRoute,m,z)}catch{return!1}},jj=(f,m)=>{const b=f.table,I=_e();if(!I||b.requiresCell&&!I.cellNodeId)return!1;const E=ZV(b.action,I);if(!E)return!1;try{if(b.action==="insert-row-before"||b.action==="insert-row-after"){const z=R(),K=(typeof z?.getHandles=="function"?z.getHandles():null)?.editing?.tables;if(typeof K?.insertRow!="function")return!1;const ae=Pa(f.docRoute);return ae&&ae.success===!1?ae:ae?K.insertRow(E,ae):K.insertRow(E)}return Mr(f.docRoute,m,E)}catch{return!1}},Uj=f=>!f||f.disposition!=="routed"?!1:!!(f.inline||f.blockParagraph||f.list||f.link||f.create),Hj=f=>{const m=Jf(f);return!!(_A(f)||tc(m.hyperlinkTarget)||tc(m.textTarget))},$j=(f,m,b)=>ht.selection.status!=="ready"?!1:Cm(f)?.scope==="id"||!m||m.disposition!=="routed"?!0:m.inline?.kind==="clear"?$r(ht.selection).length>0||Eu(ht.selection)!=null:m.inline?Eu(ht.selection)!=null||$r(ht.selection).length>0:m.blockParagraph||m.list?$r(ht.selection).length>0:m.link?Hj(b)||i2(ht.selection).length>0||dl(ht.selection)!=null||Ta(m,y(),ht.selection):!0,Gj=(f,m)=>{const b=Cm(f),I=yu(f);return b?.scope!=="id"&&!Uj(I)?!1:!$j(f,I,m)},Wj=(f,m)=>Gj(f,m)?xs().then(()=>{}):null,wc=(f,m,b)=>{if(fi=null,Ln=Promise.resolve(!1),U)return!1;const I=oe.get(f);if(I)try{const je=I.execute(Mu(m,b));return Bn(je)}catch{return!1}const E=sA(f);if(E&&typeof se()?.lists?.apply=="function")return _l(E,m);const z=Cm(f);if(z)return Xu(z,m);if(f==="copy-format")return Bn(Kj());const K=yu(f);if(!K||K.disposition!=="routed")return!1;const ae=K.normalizePayload?K.normalizePayload(m):m;if(K.instanceRoute){if(!A()||!fe(K,ae))return!1;const je=t?.[K.instanceRoute];if(typeof je!="function")return!1;try{const Ve=K.fixedArg!==void 0?K.fixedArg:ae,Xe=je.call(t,Ve);return Bn(Xe)}catch{return!1}}if(K.inline?.kind==="clear")return K.mutates&&wr()==="viewing"?!1:Bn(Pj());const ue=K.docRoute;if(!ue||K.mutates&&wr()==="viewing")return!1;const Le=y(),Ue=Sr(Le,ue);if(!Ue)return!1;if(K.inline){const{lockModesById:je}=Ms(Le?.contentControls,ht.selection);if(_i(je))return!1;const Ve=Eu(ht.selection);if(!Ve)return ht.selection.empty===!1?Bn(!1):Bn(Lj(K,ae));const Xe=Ta(K,Le,ht.selection),$e=YV(K.inline,Ve,ae,Xe);if(!$e)return!1;let Qe=null;try{const Je=A(),at=wr(),ot=()=>A()!==Je||y()!==Le||wr()!==at?!1:m2(ue,Ue,$e),Nt=wa(ht.selection)??Ql(ht.selection),qt=K.inline.kind==="toggle"?Am(`${K.id}:${Nt}`,ot):null;Qe=qt?.release??null;const Qn=qt?qt.result:ot(),tr=vn(K,ht.selection,$e,Qn),Qr=Wt(K,ht.selection,$e,Qn),zr=Bn(Qr,fn=>{Lr(K,tr,fn),Qe?.(),Qe=null});return K.inline.kind==="toggle"&&(Zu=Ln),zr}catch{return Qe?.(),!1}}if(K.blockParagraph){const je=Dj(K,Ue,ae),Ve=K.blockParagraph.kind==="alignment"&&_o(je)?Gr(ht.selection,ae):null;return Bn(je,Xe=>{Wu(Ve,Xe)})}if(K.list){const je=Fj(K,Ue);return Bn(je)}if(K.link){const je=zj(ae);return Bn(je)}if(K.create){const je=Vj(K,Ue,ae);return Bn(je)}if(K.table){const je=jj(K,Ue);return Bn(je)}try{return Bn(K.mutates?Mr(ue,Ue,ae):Ue(ae))}catch{return!1}},Em=()=>{g+=1,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:h.lastClickAt,pointerSelecting:!1,keyboardSelecting:!1};for(const f of p)f("idle");j()},Kj=async()=>{const f=["bold","italic","underline","strikethrough"].filter(Ue=>ht.toolbar.commands[Ue]?.active===!0),m=await Zu;await u;const b=_o(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 j(),!0}return Em(),!1}const z=E-h.lastClickAt<I,K=++g;h={...h,lastClickAt:E};const ae=await xs(),ue=`${Ql(ae)}:${ft()}`,Le=await qj(null,ae,ue&&ue===S?v:void 0,b);if(K!==g)return!0;h={...h,mode:z?"persistent":"armed",snapshot:Le,sourceSelectionKey:Ql(ae),lastClickAt:E};for(const Ue of p)Ue(h.mode);return j(),!0},qj=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 ae=E.story;let ue=null;for(const $e of z){const Qe=(await Ia(So($e.blockId,ae)))?.node??null;if(!Qe)continue;const Je=g2(Qe),at=Array.isArray(Je?.inlines)?Je.inlines:[],ot=Yj(at,$e.range);ue?ue=AA(ue,ot):ue=ot}const Le=ue?Yz(ue):{},Ue={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strike"},je=new Set([...m?.activeMarks??(Array.isArray(f?.activeMarks)?f.activeMarks:[]),...I]);for(const[$e,Qe]of Object.entries(Ue))je.has($e)&&(Le[Qe]=!0);const Ve=b??await fc(m??Ts(f,"ready"));if(Ve.fontFamily&&(Le.fontFamily=Ve.fontFamily),Ve.color&&(Le.color=Ve.color),Ve.highlight&&(Le.highlight=Ve.highlight),Ve.fontSize){const $e=Number.parseFloat(Ve.fontSize);Number.isNaN($e)||(Le.fontSize=$e)}let Xe=null;if(z.length===1){const $e=z[0],Qe=(await Ia(So($e.blockId,ae)))?.node??null;Qe&&g2(Qe)&&(Xe=await Xj(Qe,$e.blockId,K,ae))}return{story:ae??null,inline:Le,paragraph:Xe}},g2=f=>f?f.kind==="paragraph"?f.paragraph??null:f.kind==="heading"?f.heading??null:null:null,Yj=(f,m)=>{const b=K=>{const ae=K.run;return typeof ae?.text=="string"?ae.text:""},I=K=>K.run?.props;if(m.start===m.end){let K=0;for(const ae of f){const ue=b(ae),Le=K,Ue=K+ue.length;if(K=Ue,m.start>=Le&&m.start<=Ue){const je=I(ae);return je?{...je}:{}}}return{}}let E=0;const z=[];for(const K of f){const ae=b(K),ue=E,Le=E+ae.length;if(E=Le,Le<=m.start||ue>=m.end)continue;const Ue=I(K);Ue&&z.push(Ue)}return z.length===0?{}:z.length===1?{...z[0]}:AA(z[0],...z.slice(1))},AA=(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},Xj=async(f,m,b,I)=>{const E=g2(f),z=E.props??{},K=E.styleRef??null,ae=z.alignment??null,ue=z.spacing??null,Le=z.indent??null,Ue=Le?{...Le.left!=null?{left:Le.left}:{},...Le.right!=null?{right:Le.right}:{},...Le.firstLine!=null?{firstLine:Le.firstLine}:{},...Le.hanging!=null?{hanging:Le.hanging}:{}}:null,je=z.markRunProps??null,Ve=z.numbering?.numId,Xe=typeof Ve=="string"?parseInt(Ve,10):typeof Ve=="number"?Ve:NaN,$e=z.numbering?.level,Qe=isNaN(Xe)?null:{numId:Xe,...$e!=null?{level:$e}:{}};let Je=null;if(Qe&&typeof b.lists?.getState=="function")try{const at=await b.lists.getState({target:So(m,I)});at&&typeof b.lists?.getStyle=="function"&&(Je=await b.lists.getStyle(at)??null)}catch{}return{styleId:K,alignment:ae,spacing:ue,indentation:Ue,markRunProps:je,numbering:Qe,listStyle:Je}},IA=async()=>{if(h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;const f=y()?.selection,m=async()=>{const K=typeof f?.current=="function"?await Promise.resolve(f.current({includeText:!0})):ts().value;return zi(K)},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=Ql(E),z!==h.sourceSelectionKey))break}if(E&&!E.empty&&z!==h.sourceSelectionKey){await EA(E);return}if(h.snapshot?.paragraph){const K=await m();if(!K||Ql(K)===h.sourceSelectionKey)return;await EA(K)}},EA=async f=>{const m=h.snapshot;if(!m){h.mode==="armed"&&Em();return}const b=y();if(!b)return;const I=Ts(f,"ready"),{lockModesById:E}=Ms(b.contentControls,I);if(_i(E)){j();return}const z=f.target,K=f.selectionTarget;if(f.empty!==!0&&Object.keys(m.inline).length>0){const ae=Sr(b,"format.apply");if(ae&&K)try{if(!_o(As(await Promise.resolve(m2("format.apply",ae,{target:K,inline:m.inline},f))))){j();return}}catch{j();return}}if(m.paragraph){const ae=Array.isArray(z?.segments)?z.segments:[],ue=z?.story;for(const Le of ae){const Ue=So(Le.blockId,ue),je=await Ia(Ue),Ve=je?.node??null,Xe=je?.address??null;if(!Ve)continue;const $e={kind:"block",nodeType:Xe?.nodeType??Ve.kind??"paragraph",nodeId:Le.blockId,...ue&&typeof ue=="object"?{story:ue}:{}},{styleId:Qe,alignment:Je,spacing:at,indentation:ot,markRunProps:Nt,numbering:qt,listStyle:Qn}=m.paragraph;if(Qe&&await b.styles?.paragraph?.setStyle?.({target:$e,styleId:Qe}),Je&&await b.format?.paragraph?.setAlignment?.({target:$e,alignment:Je}),at){const tr=at,Qr=tr.lineRule??"auto",zr=new Set(["auto","exact","atLeast"]).has(Qr)?Qr:"auto",fn={...tr.before!=null?{before:Math.round(tr.before*20)}:{},...tr.after!=null?{after:Math.round(tr.after*20)}:{},...tr.line!=null?{line:Math.round(zr==="auto"?tr.line*240:tr.line*20),lineRule:zr}:{}};await b.format?.paragraph?.setSpacing?.({target:$e,...fn})}if(ot){const tr={...ot.left!=null?{left:_s(ot.left)}:{},...ot.right!=null?{right:_s(ot.right)}:{},...ot.firstLine!=null?{firstLine:_s(ot.firstLine)}:{},...ot.hanging!=null?{hanging:_s(ot.hanging)}:{}};await b.format?.paragraph?.setIndentation?.({target:$e,...tr})}Nt&&await b.format?.paragraph?.setMarkRunProps?.({target:$e,markRunProps:Nt}),qt&&await b.format?.paragraph?.setNumbering?.({target:$e,...qt}),Qn&&((await Ia(Ue))?.address?.nodeType==="listItem"?await b.lists?.applyStyle?.({target:fA(Le.blockId,ue),style:Qn}):qt&&await b.format?.paragraph?.setNumbering?.({target:$e,...qt}))}}h.mode==="armed"&&Em(),j()},Tm=(f,m,b)=>{const I=Wj(f,m),E=I?I.then(()=>(wc(f,m,b),Ln)):(wc(f,m,b),Ln);return yu(f)?.inline?.kind==="toggle"&&(Zu=E),E},TA=f=>({id:f,getState:()=>ht.toolbar.commands[f]??hc(f,y(),ht.selection,yl(ht.selection)),observe:m=>gn(b=>b.toolbar.commands[f]??{enabled:!1,active:!1,supported:!1,source:"unsupported",reason:dt.commandUnsupported}).subscribe(m),execute:m=>wc(f,m),executeAsync:m=>Tm(f,m)}),Zj=f=>{oe.set(f.id,f),j();const m=()=>{oe.delete(f.id),j()};return Object.assign(m,{handle:TA(f.id),unregister:m})},xm=ln(f=>f.selection),Rm=qn(xm),xA=()=>{const f=R();if(typeof f?.getHandles!="function")return{reason:dt.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"?dt.notReady:dt.hostCapabilityUnavailable}}const b=m?.editing?.selectionTargets;return typeof b?.apply!="function"?{reason:dt.hostCapabilityUnavailable}:{helper:b}},Qj=f=>{const m=R();if(typeof m?.getHandles=="function")try{const b=m.getHandles()?.editing?.contentControls;typeof b?.activate=="function"&&b.activate({id:f})}catch{}},RA={get:Rm.get,getSnapshot:Rm.getSnapshot,subscribe:Rm.subscribe,observe:Rm.observe,current:()=>ts().value,capture:()=>{const f=xm.get();return f.empty||!f.target&&!f.selectionTarget?null:{...f,capturedAt:Date.now()}},restore:f=>{const m=E=>(j(),{...E,success:E.ok});if(!f||typeof f!="object")return m({ok:!1,reason:dt.targetUnresolved});if(!A())return m({ok:!1,reason:dt.notReady});const b=KV(f);if(!b)return m({ok:!1,reason:dt.targetUnresolved});const I=xA();if(!("helper"in I))return m({ok:!1,reason:I.reason});try{return m(iA(I.helper.apply(b)))}catch{return m({ok:!1,reason:dt.hostCapabilityUnavailable})}},apply:f=>{if(!A())return{ok:!1,reason:dt.notReady};const m=xA();if(!("helper"in m))return{ok:!1,reason:m.reason};try{const b=m.helper.apply(f);return j(),iA(b)}catch{return{ok:!1,reason:dt.hostCapabilityUnavailable}}},getAnchorRect:f=>{const m=R();if(typeof m?.getSelectionAnchorRect=="function"){const b=Ot(()=>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=xm.get(),b=m.selectionTarget??m.target;if(m.empty||!b)return[];const I=zm.getRect({target:b,relativeTo:f?.relativeTo});return I.found?I.rects:[]}},Jj={get ids(){return le()},has:f=>yu(f)!=null||oe.has(f),get:f=>TA(f),execute:wc,executeAsync:Tm,register:Zj,getContextMenuItems:f=>{const m=[];for(const b of oe.values()){const I=b.contextMenu;I&&Ot(I.when?()=>I.when(f):void 0,!0)&&m.push({id:b.id,label:I.label,group:I.group,order:I.order,invoke:()=>wc(b.id,void 0,f)})}return m.sort((b,I)=>(b.order??0)-(I.order??0)||b.label.localeCompare(I.label))}},v2=qn(ln(f=>f.toolbar)),eU={get:v2.get,getSnapshot:()=>ht.toolbar,subscribe:v2.subscribe,observe:v2.observe,execute:wc,executeAsync:Tm},Cc=async(f,m)=>{if(!A())return{success:!1,ok:!1,reason:dt.notReady};if(!f)return{success:!1,ok:!1,reason:dt.targetUnresolved};const b=R(),I=b?.scrollTargetIntoView;if(typeof I!="function")return{success:!1,ok:!1,reason:dt.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:n2(z.reason,dt.targetUnresolved)}:{success:!0,ok:!0}}catch{return{success:!1,ok:!1,reason:dt.hostCapabilityUnavailable}}},Mm=async(f,m,b,I)=>{const E=f==="trackChanges"?I?.story:void 0,z=at=>{if(!E||!at||typeof at!="object")return at;const ot=at,Nt=ot.address&&typeof ot.address=="object"?ot.address:null;return ot.story||Nt?.story?at:{...ot,story:E}},K=f==="trackChanges"?bV:Bf,ae=b.find(at=>Xi(at,m,E)),ue=ae&&typeof ae=="object"?ae:null,Le=f==="trackChanges"&&ue?.type==="move"&&(ue.subtype==="move-to"||ue.subtype==="move-from")?ue.subtype:null,Ue=Le&&typeof ue?.trackedChangeCanonicalId=="string"?ue.trackedChangeCanonicalId:m,je=at=>{if(!Le)return K(at);const ot=Bf(at);if(ot?.kind!=="move")return null;const Nt=Le==="move-to"?ot.destination:ot.source;return r2(Nt)?Nt:null},Ve=K(ae),Xe=f!=="trackChanges"||!Le&&r2(Bf(ae));if(Ve&&Xe)return z(Ve);const $e=y()?.[f],Qe=f==="comments"?{commentId:m}:{id:Ue,...E?{story:E}:{}},Je=$e?.get;if(typeof Je!="function")return z(Ve);try{return z(je(await Promise.resolve(Je.call($e,Qe)))??Ve)}catch{return z(Ve)}};function MA(f,m){if(Es())return nr("Comments are read-only.","DOCUMENT_READONLY");if(qo())return nr("Resolving comments is disabled.","DOCUMENT_READONLY");const b=y()?.comments,I=b?.patch;if(typeof I!="function")return nr("comments.patch is unavailable.");const E=nr("comments.patch failed.");return Ot(()=>Lo(I.call(b,{commentId:f,status:m}),E),E)}const eh=()=>Es()?nr("Comments are read-only.","DOCUMENT_READONLY"):null,LA=(f,m)=>{const b=m&&typeof m=="object"?m:null;let I=Array.from(f);b?.includeResolved===!1&&(I=I.filter(ue=>ue.status!=="resolved"));const E=Number(b?.offset),z=Number.isInteger(E)&&E>0?E:0,K=Number(b?.limit),ae=Number.isInteger(K)&&K>=0?z+K:void 0;return I.slice(z,ae)},ed=ln(f=>f.comments),Lm=qn(ed),tU={get:Lm.get,getSnapshot:Lm.getSnapshot,subscribe:Lm.subscribe,observe:Lm.observe,list:f=>{Kn();const m=ed.get();if(m.status!=="pending")return LA(m.items,f);const b=y()?.comments,I=Ot(b?.list?()=>b.list(f):void 0,null);return Tr(I)?[]:LA(Array.isArray(I?.items)?I.items:[],f)},getById:f=>{const m=ed.get().items.find(E=>er(E)===f)??null;if(m)return m;const b=y()?.comments,I=Ot(b?.get?()=>b.get({commentId:f}):void 0,null);return Tr(I)?null:I},createFromCapture:(f,m)=>{const b=eh();if(b)return b;const I=y()?.comments,E=I?.create;if(typeof E!="function")return nr("comments.create is unavailable.");const z=nr("comments.create failed.");return Ot(()=>{const K=f&&typeof f=="object"?f.target??f.selectionTarget:null;return K==null?nr("A range selection is required to comment.","NO_SELECTION"):Lo(E.call(I,{target:K,text:m.text}),z)},z)},createFromSelection:f=>{const m=eh();if(m)return m;const b=y()?.comments,I=b?.create;if(typeof I!="function")return nr("comments.create is unavailable.");const E=xm.get(),z=E.target??E.selectionTarget;if(E.empty||!z)return nr("A range selection is required to comment.","NO_SELECTION");const K=nr("comments.create failed.");return Ot(()=>Lo(I.call(b,{target:z,text:f.text}),K),K)},reply:(f,m)=>{const b=eh();if(b)return b;const I=y()?.comments,E=I?.reply??I?.create;if(typeof E!="function")return nr("comments.reply is unavailable.");const z=nr("comments.reply failed.");return Ot(()=>Lo(E===I?.reply?E.call(I,{parentCommentId:f,text:m.text}):E.call(I,{parentCommentId:f,text:m.text}),z),z)},edit:(f,m)=>{const b=eh();if(b)return b;const I=y()?.comments,E=I?.patch;if(typeof E!="function")return nr("comments.patch is unavailable.");const z=nr("comments.patch failed.");return Ot(()=>Lo(E.call(I,{commentId:f,text:m.text}),z),z)},resolve:f=>MA(f,"resolved"),reopen:f=>MA(f,"active"),delete:f=>{const m=eh();if(m)return m;const b=y()?.comments,I=b?.delete??b?.remove;if(typeof I!="function")return nr("comments.delete is unavailable.");const E=nr("comments.delete failed.");return Ot(()=>Lo(I.call(b,{commentId:f}),E),E)},setActive:f=>{if(f==null)return Me=null,j(),!0;if(!A())return!1;const m=ed.get();if(m.listStatus!=="ready")return!1;const b=TV(m.items,f);return!b||!m.items.some(I=>er(I)===b)?!1:(Me=b,j(),!0)},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:A()?dt.documentApiUnavailable:dt.notReady};const m=await Mm("comments",f,ed.get().items);return m?Cc(m):{success:!1,ok:!1,reason:dt.targetUnresolved}}},Da=ln(f=>f.trackChanges),y2=(f,m)=>{const b=Da.get().items.filter(je=>er(je)!==null);if(b.length===0)return null;const I=ht.trackChanges.activeId,E=Ge?.id===I?Ge.story:void 0,z=b.filter(je=>gm(je)==null),K=E||z.length===0?b:z;let ae=I?K.findIndex(je=>Xi(je,I,E)):-1;ae===-1&&I&&E&&(ae=K.findIndex(je=>Xi(je,I)));const ue=K[ae===-1?f>0?0:K.length-1:(ae+f+K.length)%K.length],Le=er(ue),Ue=gm(ue);return te(Ue?{id:Le,story:Ue}:{id:Le},m),j(),Le},PA=async f=>{const m=w(),b=m?.listTrackedChanges;if(typeof b=="function")try{await Promise.resolve(b.call(m,{mode:"visible-window",targetIds:[f],refreshReason:"ui-track-change-reveal-restamp",blocking:!0}))}catch{}};let DA=Promise.resolve();const nU=f=>{const m=Ct;return DA.catch(()=>{}).then(()=>rU(f,m))},rU=async(f,m)=>{if(Ct!==m)return{success:!1};const b=Ge,I=y2(f,{invalidateQueuedNavigation:!1});if(I==null)return{success:!1};const E=Ge,z=lt,K=()=>Ct===m&&Ge===E&&lt===z,ae=()=>{K()&&(te(b,{invalidateQueuedNavigation:!1}),j())};E&&Ke.add(E);try{const ue=await Mm("trackChanges",I,Da.get().items,E?.story?{story:E.story}:void 0);if(!K())return{success:!1};if(!ue)return ae(),{success:!1};Zo+=1;try{const Le=await Cc(ue,{behavior:"auto",shouldContinue:K});if(!K())return{success:!1};if(!Le.ok&&Le.reason!==dt.targetNotVisible)ae(),_(b);else{if(Le.ok&&await PA(I),!K())return{success:!1};_(E)}return{success:Le.ok}}finally{Zo=Math.max(0,Zo-1),Zo===0&&(K()?Zr&&Qo(di(Zr)):_(Ge))}}finally{E&&Ke.delete(E)}},OA=f=>{const m=nU(f);return DA=m.then(()=>{},()=>{}),m},Pm=qn(Da),oU={get:Pm.get,getSnapshot:Pm.getSnapshot,subscribe:Pm.subscribe,observe:Pm.observe,list:()=>(Nn(),Da.get().items),accept:f=>b2("accept",f),reject:f=>b2("reject",f),acceptAll:()=>th("accept",{kind:"all"},null),rejectAll:()=>th("reject",{kind:"all"},null),next:()=>y2(1),previous:()=>y2(-1),navigateNext:()=>OA(1),navigatePrevious:()=>OA(-1),getAt:f=>{if(!f||typeof f!="object"||typeof f.x!="number"||typeof f.y!="number")return null;const m=k2(f);if(m.length===0)return null;const b=Da.get().items;let I;for(const E of m){if(E.type!=="trackedChange")continue;let z;if(E.story){if(I===void 0&&(I=Rs()),!I)continue;z=I}else z=b;const K=z.find(ae=>Xi(ae,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 te(null),_(null),j(),!0;if(!A())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=Rs();if(!I)return!1;const E=_u(I,m.story).toPublicId(m.id)??m.id;if(!I.some(z=>Xi(z,E,m.story)))return!1;m.id=E}else{const I=Da.get().items,E=ya(I).toPublicId(m.id)??m.id,z=I.find(K=>er(K)===E);if(!z)return!1;m.id=E,m.story=gm(z)}return b!==m.id&&(m.paintedEntityId=b),te(m),_(m),j(),!0},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:A()?dt.documentApiUnavailable:dt.notReady};Ct+=1,Re+=1;const m=Re,b=Da.get().items,I=ya(b).toPublicId(f)??f,E=gm(b.find(ae=>er(ae)===I)),z=Ge,K={id:I,...E?{story:E}:{},...I!==f?{paintedEntityId:f}:{}};Ke.add(K);try{const ae=await Mm("trackChanges",I,b,E?{story:E}:void 0);if(Re!==m)return{success:!1,ok:!1};if(!ae)return{success:!1,ok:!1,reason:dt.targetUnresolved};te(K);const ue=Re,Le=Ge,Ue=lt,je=()=>Re===ue&&Ge===Le&&lt===Ue,Ve=()=>{je()&&(te(z,{invalidateQueuedNavigation:!1}),j())};j(),Zo+=1;try{const Xe=await Cc(ae,{behavior:"auto",shouldContinue:je});if(!je())return{success:!1,ok:!1};if(!Xe.ok&&Xe.reason!==dt.targetNotVisible)Ve(),_(z);else{if(Xe.ok&&await PA(I),!je())return{success:!1,ok:!1};_(K)}return Xe}finally{Zo=Math.max(0,Zo-1),Zo===0&&(je()?Zr&&Qo(di(Zr)):_(Ge))}}finally{Ke.delete(K)}}},b2=(f,m)=>{const{id:b,story:I}=typeof m=="string"?{id:m,story:void 0}:m,E={kind:"id",id:b,...I?{story:I}:{}};return th(f,E,b,I)},th=(f,m,b,I)=>{try{return Bn(w2(f,m,b,I))}catch{return!1}},w2=(f,m,b,I)=>{if(Es())return!1;const E=y()?.trackChanges,z=m.kind==="all"||m.scope==="all",K=m.kind==="range",ae=m.kind==="ids";if(Ea({kind:f,scope:z?"all":"id"},E))return!1;const ue=z?`${f}All`:f,Le=!K&&!ae&&!I&&E&&typeof E[ue]=="function"?E[ue]:null,Ue=E&&typeof E.decide=="function"?E.decide:null;return!Le&&!Ue?!1:Le?Le.call(E,b??{}):Ue.call(E,{decision:f,target:m})},C2=ln(f=>f.contentControls),nh=f=>C2.get().items.find(m=>m?.id===f)??null,Dm=qn(C2),iU=(f=>{if(f===void 0)return Dm.get();const m=vm(f);return m?nh(m):null}),sU={get:(f=>(f!==void 0&&st("api"),iU(f))),getSnapshot:Dm.getSnapshot,subscribe:Dm.subscribe,observe:Dm.observe,list:()=>(st("api"),C2.get().items),getById:f=>(st("api"),nh(f)),getRect:f=>{const m=vm(f);if(!m)return hl("unresolved");st("panel");const b=nh(m);if(!b)return hl("unresolved");const I=o2(b);return I?zm.getRect({target:I}):hl("unavailable")},scrollIntoView:async f=>{const m=vm(f);if(!m)return{success:!1};st("panel");const b=nh(m);if(!b)return{success:!1};const I=o2(b);return I?{success:(await Cc(I,{block:f.block,behavior:f.behavior})).ok}:{success:!1}},focus:async f=>{const m=vm(f);if(!m)return{success:!1,reason:"invalid-id"};if(!A())return{success:!1,reason:"not-ready"};st("panel");const b=nh(m);if(!b)return{success:!1,reason:"not-found"};const I=o2(b);if(!I)return{success:!1,reason:"not-reachable"};if(!(await Cc(I,{block:f.block,behavior:f.behavior})).ok)return{success:!1,reason:"not-reachable"};const E=kV(I);if(!E)return{success:!1,reason:"not-reachable"};const z=RA.apply(E);return!z.ok&&z.reason!==dt.hostCapabilityUnavailable?{success:!1,reason:"not-reachable"}:(Qj(m),{success:!0})}},Om=qn(ln(f=>f.fonts)),aU={get:Om.get,getSnapshot:Om.getSnapshot,subscribe:Om.subscribe,observe:Om.observe,getFamilyOptions:()=>ht.fonts.options,getSizeOptions:()=>ht.fonts.sizeOptions},Fm=qn(ln(f=>f.zoom)),lU={get:Fm.get,getSnapshot:Fm.getSnapshot,subscribe:Fm.subscribe,observe:Fm.observe,set:f=>{if(typeof t?.setZoom=="function")try{t.setZoom(f),j()}catch{}},setMode:f=>{if(typeof t?.setZoomMode=="function")try{t.setZoomMode(f),j()}catch{}}},Nm=qn(ln(f=>f.document)),cU={get:Nm.get,getSnapshot:Nm.getSnapshot,subscribe:Nm.subscribe,observe:Nm.observe,setMode:f=>{if(typeof t?.setDocumentMode=="function")try{t.setDocumentMode(f),j()}catch{}},export:f=>{if(typeof t?.export=="function")try{return Promise.resolve(t.export(f))}catch{return}},getText:()=>{const f=y(),m=Ot(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}}},FA=()=>{if(typeof HTMLElement>"u")return null;const f=A()?.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=FA();if(!I)return[];const E=b.elementFromPoint(f,m);if(!E||!I.contains(E))return[];const z=[E],K=ot=>{ot&&I.contains(ot)&&!z.includes(ot)&&z.push(ot)},ae=b.elementsFromPoint;if(typeof ae=="function"){let ot=[];try{ot=ae.call(b,f,m)??[]}catch{ot=[]}for(const Nt of ot)K(Nt)}const ue=[],Le=ot=>{ot&&I.contains(ot)&&!ue.includes(ot)&&!z.includes(ot)&&ue.push(ot)},Ue=ot=>{const Nt=ot.getBoundingClientRect;if(typeof Nt!="function")return!1;let qt;try{qt=Nt.call(ot)}catch{return!1}return qt!=null&&f>=qt.left&&f<=qt.right&&m>=qt.top&&m<=qt.bottom};for(const ot of z){const Nt=ot.querySelectorAll;if(typeof Nt!="function")continue;let qt;try{qt=Nt.call(ot,"[data-track-change-marker]")}catch{continue}for(let Qn=0;Qn<qt.length;Qn+=1)Ue(qt[Qn])&&Le(qt[Qn])}ue.reverse();const je=[...ue,...z],Ve=oA(je[0],I);for(let ot=1;ot<je.length;ot+=1)for(const Nt of oA(je[ot],I))Ve.push(Nt);if(Ve.length===0)return Ve;const Xe=Da.get().items,$e=ya(Xe);let Qe;const Je=new Set,at=[];for(const ot of Ve){if(ot.type!=="trackedChange"){const tr=`${ot.type}:${ot.id}`;if(Je.has(tr))continue;Je.add(tr),at.push(ot);continue}const Nt=CV(ot.storyKey)??wV(ot.story);let qt;if(Nt){if(Qe===void 0&&(Qe=Rs()),!Qe||(qt=_u(Qe,Nt).toPublicId(ot.id),!qt||!Qe.some(tr=>Xi(tr,qt,Nt))))continue}else if(qt=$e.toPublicId(ot.id),!qt)continue;const Qn=`trackedChange:${qt}`;Je.has(Qn)||(Je.add(Qn),at.push(Nt?{type:"trackedChange",id:qt,story:Nt}:{type:"trackedChange",id:qt}))}return at};function k2(f,m){return typeof f=="object"?uU(f?.x,f?.y):null}const td=new Set;let S2=!1;const NA=f=>{const m=R();if(typeof m?.observeGeometry!="function")return;let b=!1;const I=Ot(()=>{const E=m.observeGeometry(()=>f.schedule());return b=!0,E},null);f.detach=typeof I=="function"?I:null,f.boundHost=b?m:null},Bm=f=>{if(f.detach){try{f.detach()}catch{}f.detach=null}f.boundHost=null},BA=()=>{if(S2=!1,!(U||R()))for(const f of td)Bm(f)},dU=()=>{if(!S2){if(S2=!0,typeof queueMicrotask=="function"){queueMicrotask(BA);return}Promise.resolve().then(BA)}},fU=()=>{const f=R();if(!f){dU();return}for(const m of td)m.boundHost&&m.boundHost===f||(Bm(m),NA(m),m.schedule())};Se.push(fU);const zm={getRect:f=>{const m=R(),b=m?.getTargetRects;if(typeof b=="function"){const I=Ot(()=>b.call(m,{target:f.target}),null);return I&&typeof I=="object"?I.success===!0&&Array.isArray(I.rects)?GV($V(I.rects.filter(E=>E!=null&&typeof E=="object")),f.relativeTo):hl(typeof I.reason=="string"?I.reason:"unresolved"):hl("unresolved")}return hl("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=gn(ae=>({ready:ae.ready,selection:ae.selection,zoom:ae.zoom}));m.push(z.subscribe(()=>E()));const K={schedule:E,detach:null,boundHost:null};return NA(K),td.add(K),()=>{td.delete(K),Bm(K),b&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(b);for(const ae of m.splice(0))try{ae()}catch{}}},getHost:()=>FA(),entityAt:k2,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?k2({x:b,y:I}):[],selection:ht.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"?ed.get().items:Da.get().items,z=m.entityType==="trackedChange"&&m.story?{story:m.story}:void 0;b=await Mm(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 Cc(b,{block:f.block??"center",behavior:f.behavior??"smooth"})).ok}:{success:!1}}},zA=f=>{const m=(f&&typeof f=="object"?f:null)?.target;return m&&typeof m=="object"?m:null},VA=f=>`metadata:resolve:${f}`,hU=f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;const{value:b}=Ar(VA(f),ft(),()=>m.resolve({id:f}),zA);return b},pU=async f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;try{const b=ft(),I=await Promise.resolve(m.resolve({id:f}));if(b!==ft())return null;const E=zA(I);return H.set(VA(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 hl("unavailable");const b=hU(f.id);return b?zm.getRect({target:b}):hl("unresolved")},scrollIntoView:async f=>{const m=await pU(f.id);return m?{success:(await Cc(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=_e();if(!f)return{...gU};const m=me()?.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:()=>_e()!=null},Vm={query:"",total:0,activeIndex:-1,open:!1,available:!1,caseSensitive:!1,includeDeletedText:!1,regex:!1,canReplace:!1,reason:dt.searchUnavailable};let Hn={...Vm};const jm=new Set,Oa=()=>{const f=R()?.search;return f&&typeof f=="object"?f:null},zs=()=>{const f=se()?.search;return f&&typeof f=="object"?f:null},rh=()=>{const f=Oa();if(f&&typeof f.setSession=="function")return!0;const m=zs();return!!m&&typeof m.query=="function"&&typeof m.getState=="function"},os=()=>{for(const f of[...jm])try{f(Hn)}catch{}},hi=f=>(Hn={...Hn,...f},os(),Hn);let ao=0,kc=null;const jA=()=>{const f=kc;kc=null,f&&Ot(()=>(f(),null),null)},yU=()=>{ao+=1,jA();const f=rh();Hn={...Vm,available:f,reason:f?void 0:dt.searchUnavailable},os()};Pe.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"},_2=(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}:{}}},Po=()=>{const f=he("find.replace"),m=he("find.replaceAll");return f?.enabled===!0||m?.enabled===!0},Do=(f,m=!1)=>{const b=_2(f,m);if(!b){hi({total:0,activeIndex:-1,canReplace:!1,reason:void 0});return}hi({...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?dt.searchInvalidPattern:void 0})},Fa=()=>{const f=Oa();if(f&&typeof f.getState!="function")return Hn={...Hn,available:rh(),reason:rh()?void 0:dt.searchUnavailable},Hn;if(!f){const b=zs();if(b&&typeof b.getState=="function"){const I=_2(Ot(()=>b.getState(),null),Po());if(I)return Hn={...Hn,...I.query!==void 0?{query:I.query}:{},total:I.total,activeIndex:I.activeIndex,canReplace:I.canReplace,available:!0,reason:I.invalidPattern?dt.searchInvalidPattern:void 0,open:Hn.open||!!I.query},Hn}return Hn={...Vm,query:Hn.query,caseSensitive:Hn.caseSensitive,includeDeletedText:Hn.includeDeletedText},Hn}const m=_2(Ot(()=>f.getState(),null));return m&&(Hn={...Hn,...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?dt.searchInvalidPattern:void 0,open:Hn.open||!!m.query}),Hn},nd=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:dt.documentReadonly};const b=m?.rejection;return m?.status==="rejected"&&b&&typeof b=="object"&&b.code==="read-only-document"?{ok:!1,reason:dt.documentReadonly}:{ok:!1,reason:dt.operationUnavailable}},Um=qn({get:()=>Fa(),subscribe:f=>(jm.add(f),()=>jm.delete(f))}),wU={get:Um.get,getSnapshot:Um.getSnapshot,subscribe:Um.subscribe,observe:Um.observe,open:()=>rh()?(hi({available:!0,open:!0,reason:void 0}),{ok:!0}):(hi({available:!1,open:!1,reason:dt.searchUnavailable}),{ok:!1,reason:dt.searchUnavailable}),close:()=>{if(ao+=1,kc)jA();else{const f=Oa();if(f&&typeof f.clear=="function")Ot(()=>f.clear(),null);else{const m=zs();m&&typeof m.query=="function"&&Ot(()=>m.query({query:""}),null)}}Hn={...Vm,available:rh(),reason:void 0},Hn.available||(Hn.reason=dt.searchUnavailable),os()},search:(f,m)=>{const b=Oa(),I=!!m?.caseSensitive,E=m?.includeDeletedText===!0,z=m?.regex===!0,K=++ao;if(!b||typeof b.setSession!="function"){const ue=zs();if(ue&&typeof ue.query=="function"&&typeof ue.getState=="function"){hi({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),kc=()=>{ue.query({query:""})};const Le=Ot(()=>ue.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);return Tr(Le)?Promise.resolve(Le).then(Ue=>{K===ao&&Do(Ue,Po())},()=>{K===ao&&hi({available:!1,reason:dt.searchUnavailable})}):Do(Le,Po()),Do(Ot(()=>ue.getState(),null),Po()),Hn}return hi({query:f,total:0,activeIndex:-1,available:!1,caseSensitive:I,includeDeletedText:E,regex:z,reason:dt.searchUnavailable})}hi({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),kc=()=>{typeof b.clear=="function"&&b.clear()};const ae=Ot(()=>b.setSession(f,{caseSensitive:I,includeDeletedText:E,...z?{regex:!0}:{},highlight:!0}),null);if(Do(ae),f.length>0&&Hn.total===0&&Hn.reason!==dt.searchInvalidPattern){const ue=zs();if(ue&&typeof ue.query=="function"&&typeof ue.getState=="function"){const Le=kc;kc=()=>{Le?.(),ue.query({query:""})};const Ue=Ot(()=>ue.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);Tr(Ue)?Promise.resolve(Ue).then(je=>{K===ao&&Do(je,Po())},()=>{K===ao&&hi({available:!1,reason:dt.searchUnavailable})}):Do(Ue,Po()),Do(Ot(()=>ue.getState(),null),Po())}}return Hn},next:()=>{const f=Oa();if(!f||typeof f.next!="function"){const m=zs();if(!m||typeof m.next!="function"||typeof m.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(Hn.total===0)return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.next(),null);if(Tr(b)){const I=ao;Promise.resolve(b).then(E=>{I===ao&&Do(E,Po())}).catch(()=>{I===ao&&hi({available:!1,reason:dt.searchUnavailable})})}else Do(b,Po());return Do(Ot(()=>m.getState(),null),Po()),{ok:!0}}return Hn.total===0?{ok:!1,reason:dt.operationUnavailable}:(Do(Ot(()=>f.next(),null)),{ok:!0})},previous:()=>{const f=Oa();if(!f||typeof f.previous!="function"){const m=zs();if(!m||typeof m.previous!="function"||typeof m.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(Hn.total===0)return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.previous(),null);if(Tr(b)){const I=ao;Promise.resolve(b).then(E=>{I===ao&&Do(E,Po())}).catch(()=>{I===ao&&hi({available:!1,reason:dt.searchUnavailable})})}else Do(b,Po());return Do(Ot(()=>m.getState(),null),Po()),{ok:!0}}return Hn.total===0?{ok:!1,reason:dt.operationUnavailable}:(Do(Ot(()=>f.previous(),null)),{ok:!0})},clear:()=>{ao+=1;const f=Oa();if(f&&typeof f.clear=="function"&&Ot(()=>f.clear(),null),!f||typeof f.clear!="function"){const m=zs();m&&typeof m.query=="function"&&Ot(()=>m.query({query:""}),null)}hi({query:"",total:0,activeIndex:-1,canReplace:!1})},replace:f=>{const m=Oa();if(!m){const I=zs();if(!I||typeof I.replace!="function"||typeof I.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(!Po())return{ok:!1,reason:dt.operationUnavailable};const E=Ot(()=>I.replace({replacement:typeof f=="string"?f:""}),null);if(Tr(E)){const z=ao;Fa(),os();const K=()=>z===ao;return Promise.resolve(E).then(ae=>(K()&&(Do(ae,Po()),Fa(),os()),nd(ae)),()=>(K()&&hi({available:!1,reason:dt.searchUnavailable}),{ok:!1,reason:dt.searchUnavailable}))}return Fa(),os(),nd(E)}if(typeof m.replaceCurrent!="function")return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.replaceCurrent(typeof f=="string"?f:""),null);return Fa(),os(),nd(b)},replaceAll:f=>{const m=Oa();if(!m){const I=zs();if(!I||typeof I.replaceAll!="function"||typeof I.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(!Po())return{ok:!1,reason:dt.operationUnavailable};const E=Ot(()=>I.replaceAll({replacement:typeof f=="string"?f:""}),null);if(Tr(E)){const z=ao;Fa(),os();const K=()=>z===ao;return Promise.resolve(E).then(ae=>(K()&&(Do(ae,Po()),Fa(),os()),nd(ae)),()=>(K()&&hi({available:!1,reason:dt.searchUnavailable}),{ok:!1,reason:dt.searchUnavailable}))}return Fa(),os(),nd(E)}if(typeof m.replaceAll!="function")return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.replaceAll(typeof f=="string"?f:""),null);return Fa(),os(),nd(b)}},UA=ln(f=>f.styles),Hm=qn(UA),CU={get:Hm.get,getSnapshot:Hm.getSnapshot,subscribe:Hm.subscribe,observe:Hm.observe,getCatalog:f=>Ae(f).value,getQuickGallery:()=>UA.get().quickGallery,getActiveParagraphStyle:()=>We(ht.selection,Ie().cache).style},HA={select:gn,get state(){return ht},selection:RA,commands:Jj,toolbar:eU,comments:tU,trackChanges:oU,contentControls:sU,fonts:aU,zoom:lU,document:cU,viewport:zm,metadata:mU,tables:vU,search:wU,styles:CU,formatPainter:{setPointerSelecting(f){U||(h={...h,pointerSelecting:f})},notifyPointerUp(){U||(h={...h,pointerSelecting:!1},IA())},setKeyboardSelecting(f){U||(h={...h,keyboardSelecting:f})},notifyKeyUp(){U||(h={...h,keyboardSelecting:!1},IA())},cancel(){U||Em()},onModeChange(f){return U?()=>{}:(p.add(f),()=>p.delete(f))}},createScope:()=>{const f=[];return{select:(m,b)=>{const I=gn(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(!U){U=!0,cV(zt,Lt),lr.reset(),Nr(),Be&&(clearTimeout(Be),Be=null),ge&&(clearTimeout(ge),ge=null,be=0),W?.timer&&(clearTimeout(W.timer),W.timer=null),W=null,it&&(clearTimeout(it),it=null),oo&&(clearTimeout(oo),oo=null),Uo&&Uo(),Uo=null,Si=null,ai.clear(),J.clear();for(const f of Zn.splice(0))f();At&&At(),At=null,et=null,kt&&kt(),kt=null,Gt=null,In&&In(),In=null,cr=null,Wr&&Wr(),Wr=null,Zr=null,un&&un(),un=null,ct=null,Yo&&Yo(),Yo=null,yo=null;for(const f of td)Bm(f);td.clear(),D.clear(),jm.clear(),g+=1,p.clear(),ao+=1,oe.clear()}}};return $=HA,HA}var JV=[{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 ej(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 tj(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"?ej(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 nj(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 rj(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:JV;for(const s of i)o(s);return n}var oj=[{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 ij(e,t){return e.activeMark?t.activeMarks.includes(e.activeMark):!1}Dt();var sj=['[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(", "),aj=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 lj(e,t){const n=new c6.default;return e.forEach((r,o)=>{n.file(t[o],r)}),n.generateAsync({type:"blob",compression:"DEFLATE"})}function f2(e){return!!(e&&(e.synced===!0||e.isSynced===!0))}function bA(e){try{e.synced=!0}catch{}try{e.isSynced=!0}catch{}}function cj(e,t){if(!e)return()=>{};if(f2(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=()=>{bA(e),s()},l=c=>{c!==!1&&(c===!0||f2(e))&&(bA(e),s())};return n("synced",a),n("sync",l),f2(e)&&s(),i}function uj(e,t){const n=e.composedPath();if(!n.includes(t))return null;const r=n.find(a=>a instanceof HTMLElement&&a.matches(sj));if(!r)return null;const o=n.some(a=>a instanceof HTMLElement&&a.classList.contains(rp.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 dj(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function fj(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 si(e){return!!(e&&typeof e=="object"&&e.editorVersion===2)}function hj(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 wA(e){return typeof e=="string"&&e.length>0?e:null}function h2(e){return e?si(e)?wA(e.documentId??e.options?.documentId??null):wA(typeof e.getDocumentId=="function"?e.getDocumentId():e.options?.documentId):null}function pj(e){if(!e||si(e))return null;const t=e;return t.documentRenderer??t.presentationEditor??null}function Ji(e){if(!e)return null;if(si(e))return e.fonts??null;const t=pj(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 km=class extends Gm.default{static{this.allowedTypes=[Hr,Vl,Jh]}#t;#n;#e;#r;#i;#s;#d;#h;#f;#c;#p;get uiConfig(){return this.#p}#o;get interactionConfig(){return this.#o}#l;get surfacesConfig(){return this.#l}#g;#u;#y;#w;constructor(e){if(super(),this.#t=!1,this.#n=!1,this.#e=null,this.#r=null,this.#i=null,this.#s=null,this.#d=null,this.#h=null,this.#f=n=>{this.#k(n)},this.#c=null,this.#p=P4({}),this.#o=D4({}),this.#l=F4({}),this.version="0.0.0",this.users=[],this.whiteboard=null,this.colors=[],this.readyEditors=0,this.pendingCollaborationSaves=0,this.#u=new iN,this.#y=null,this.#w=!1,this.config={selector:"#superdoc",documentMode:"editing",allowSelectionInViewMode:!1,role:"editor",document:{},documents:[],editorExtensions:[],colors:[],users:[],user:{...W0},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},this.#Z=new WeakSet,this.#Q=null,this.#j=null,this.#M=null,!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 KF({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=uj(e,t),r=this.activeEditor?.doc?.contentControls?.list;if(!(!n||typeof r!="function"))try{const o=await r();if(this.#t)return;const i=fj(dj(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),eN(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=tN(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=xk(this.config.modules.comments),this.#p=P4(this.config),this.#o=D4(this.config),this.#l=F4(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=v6(this.config.colors),this.userColorMap=new Map,this.colorIndex=0,this.version="2.4.0-next.20",this.#C("🦋 [superdoc] Using SuperDoc version:",this.version),this.superdocId=e.superdocId||is(),this.colors=this.config.colors??[],this.#D(),await S8(),this.#t)return;if(await this.#b(this.config.modules),this.#t){this.#de();return}this.config.cspNonce&&this.#P(),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.#L(),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)}#L(){const e=this.config.modules?.whiteboard,t=e!==!1&&(e?.enabled??!1);this.whiteboard=new bD({Renderer:$F,superdoc:this,enabled:t}),this.emit("whiteboard:init",{whiteboard:this.whiteboard})}get requiredNumberOfEditors(){return this.#m("requiredNumberOfEditors").documents.filter(e=>e.type===Hr).length}get ui(){return this.#c||(this.#c=QV({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}#P(){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}}#D(){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=Zd(this.config.document);this.config.documents=[{id:is(),...s}]}else if(n)this.config.documents=[{id:is(),type:Hr,url:this.config.document,name:"document.docx"}];else if(r){const s=Zd(this.config.document);this.config.documents=[{id:is(),...s}]}else if(o){const s=Zd(this.config.document);this.config.documents=[{id:is(),...s}]}Array.isArray(this.config.documents)&&this.config.documents.length>0&&(this.config.documents=this.config.documents.map(s=>{const a=Zd(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||is()}}))}#T(){const{app:e,pinia:t,superdocStore:n,commentsStore:r,highContrastModeStore:o}=aD({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&&l8(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.#$(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:is(),type:Hr,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}#ee(e,t){this.isCollaborative=!0,this._commentsCollabInitialized=!1,this.ydoc=eo(e),this.provider=eo(t),this.#_();const n=this.config;this._cleanupAwareness=r8(t,this,n.user),n.documents.forEach(r=>{r.ydoc=e,r.provider=t,r.role=this.config.role})}#H(){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}}#$(e){this.#A(),si(e)&&(this.#O(e),this.#x(e))}#O(e){const t=e.presence;if(!t||typeof t.subscribe!="function")return;const n=mD(()=>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.#F(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)}}#F(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
+ `;Dt();var Ss=e=>{e.expand.value=!1};function J0(e,t){const n={...e??{}};return t?n.href=t:delete n.href,n}function Q4(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 Nz(e){return typeof e?.quotedText=="string"?e.quotedText:typeof e?.text=="string"?e.text:""}function J4(e){return e.ui?.selection?.get?.()??e.ui?.selection?.current?.()??null}function Bz(e){return!!(e.config?.superdoc?.config?.modules?.ai||e.superdoc?.config?.modules?.ai)}function zz(e){return e.config?.superdoc?.config?.modules?.ai??e.superdoc?.config?.modules?.ai??{}}var Vz=({superToolbar:e,toolbarIcons:t,toolbarTexts:n,toolbarFonts:r,hideButtons:o,availableWidth:i,role:s,isDev:a=!1}={})=>{const l=Tn({type:"button",name:"bold",command:"toggleBold",icon:t.bold,tooltip:n.bold,attributes:{ariaLabel:"Bold"}}),c=(r??LB).map(zB),u=Tn({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:c,onActivate:({fontFamily:rt}={},zt=!1)=>{if(zt){u.label.value="",u.selectedValue.value="";return}if(!rt)return;rt=rt.split(",")[0],u.label.value=rt;const Lt=c.find(Qt=>Qt.label===u.defaultLabel.value),An=c.find(Qt=>Qt.label===rt);An?u.selectedValue.value=An.key:Lt?u.selectedValue.value=Lt.key:u.selectedValue.value=""},onDeactivate:()=>{u.label.value=u.defaultLabel.value;const rt=c.find(zt=>zt.label===u.defaultLabel.value);rt?u.selectedValue.value=rt.key:u.selectedValue.value=""}}),d=Tn({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(rt){const zt=J4(e),Lt=zt?.selectionTarget??Q4(zt?.target),An=zt?.empty?"":Nz(zt),Qt=zz(e),wn=()=>Ss(rt),Wn=()=>{const go=e.pendingSelectionCapture;go&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(go)};return Kr("div",{},[Kr(fz,{handleClose:wn,selectedText:An,target:Lt,doc:e.superdoc?.activeEditor?.doc??null,apiKey:Qt?.apiKey||e.config?.aiApiKey||"",endpoint:Qt?.endpoint||e.config?.aiEndpoint||"",restoreSelection:Wn})])}const g=DB,p=Tn({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:rt},zt=!1)=>{if(zt){p.label.value="",p.selectedValue.value="";return}const Lt=g.find(Wn=>Wn.label===String(p.defaultLabel.value));if(!rt){p.label.value=p.defaultLabel.value,Lt?p.selectedValue.value=Lt.key:p.selectedValue.value="";return}let An=_N(rt,12);An<8&&(An=8),An>96&&(An=96);let Qt=String(An);const wn=g.find(Wn=>Wn.label===Qt||Wn.key===Qt);wn?p.selectedValue.value=wn.key:p.selectedValue.value="",p.label.value=Qt},onDeactivate:()=>{p.label.value=p.defaultLabel.value;const rt=g.find(zt=>zt.label===String(p.defaultLabel.value));rt?p.selectedValue.value=rt.key:p.selectedValue.value=""}}),v=Tn({type:"separator",name:"separator",isNarrow:!0}),S=Tn({type:"button",name:"italic",command:"toggleItalic",icon:t.italic,active:!1,tooltip:n.italic,attributes:{ariaLabel:"Italic"}}),C=Tn({type:"button",name:"underline",command:"toggleUnderline",icon:t.underline,active:!1,tooltip:n.underline,attributes:{ariaLabel:"Underline"}}),A=Tn({type:"button",name:"strike",command:"toggleStrike",icon:t.strikethrough,active:!1,tooltip:n.strikethrough,attributes:{ariaLabel:"Strikethrough"}}),y=Tn({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:()=>Q0(e,y,[],!0)}],onActivate:({color:rt})=>{y.iconColor.value=rt||""},onDeactivate:()=>y.iconColor.value=""}),w=Tn({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:()=>Q0(e,w)}],onActivate:({color:rt})=>{w.iconColor.value=rt},onDeactivate:()=>w.iconColor.value="#000"}),x=Tn({type:"button",name:"search",allowWithoutEditor:!0,active:!1,icon:t.search,tooltip:n.search,group:"right",attributes:{ariaLabel:"Search"}}),L=Tn({type:"dropdown",name:"link",markName:"link",icon:t.link,active:!1,tooltip:n.link,attributes:{ariaLabel:"Link dropdown"},options:[{type:"render",key:"linkDropdown",render:()=>V(L)}],onActivate:({href:rt})=>{L.attributes.value=J0(L.attributes.value,rt)},onDeactivate:()=>{L.attributes.value=J0(L.attributes.value,null),L.expand.value=!1}});function V(rt){const zt=J4(e),Lt=zt?.selectionTarget??Q4(zt?.target),An=()=>{const Qt=e.pendingSelectionCapture;Qt&&typeof e.ui?.selection?.restore=="function"&&e.ui.selection.restore(Qt)};return Kr("div",{},[Kr(SS,{ui:e.ui,linkItem:rt,textTarget:Lt,restoreSelection:An,closePopover:()=>{Ss(rt),bu(e)},goToAnchor:()=>{Ss(rt);const Qt=rt.attributes.value?.href;if(!Qt)return;const wn=Qt.slice(1),Wn=(e.ui?.viewport?.getHost?.()??null)?.querySelector?.(`a[name='${wn}']`);Wn&&mf(Wn)}})])}const G=Tn({type:"options",name:"linkInput",command:"toggleLink",active:!1});L.childItem=G,G.parentItem=L;const R=Tn({type:"button",name:"image",command:"startImageUpload",icon:t.image,active:!1,tooltip:n.image,disabled:!1,attributes:{ariaLabel:"Image"}}),F=Tn({type:"button",name:"tableOfContents",command:"insertTableOfContents",icon:t.tableOfContents,active:!1,tooltip:n.tableOfContents,disabled:!1,attributes:{ariaLabel:"Table of contents"}}),Z=Tn({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:()=>O(Z)}]});function O(rt){return Kr("div",{},[Kr(Tz,{onSelect:Lt=>{e.emitCommand({item:rt,argument:Lt}),Ss(rt),bu(e)}})])}const N=Tn({type:"dropdown",name:"tableActions",command:"executeTableCommand",tooltip:n.tableActions,icon:t.tableActions,hideLabel:!0,disabled:!0,attributes:{ariaLabel:"Table actions"},options:[{type:"render",render:()=>B(N)}]}),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 B(rt){return Kr(Oz,{options:T,onSelect:zt=>{Ss(rt);const{command:Lt}=zt;e.emitCommand({item:rt,argument:{command:Lt}})}})}const Q=Tn({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:()=>Kr("div",{},[Kr(UB,{onSelect:zt=>{Ss(Q);const Lt={...Q,command:"setTextAlign"};Lt.command="setTextAlign",e.emitCommand({item:Lt,argument:zt}),q(Q,zt),bu(e)}})]),key:"alignment"}],onActivate:({textAlign:rt})=>{q(Q,rt)},onDeactivate:()=>{q(Q,"left")}}),q=(rt,zt)=>{let Lt=zt==="both"?"justify":zt,An={left:t.alignLeft,right:t.alignRight,center:t.alignCenter,justify:t.alignJustify},Qt=An[Lt]??An.left;rt.icon.value=Qt},se=Tn({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 rt=zt=>{Ss(se);const Lt={...se,command:"toggleBulletListStyle"};e.emitCommand({item:Lt,argument:zt})};return Kr(X4,{buttons:GB,iconSize:25,selectedStyle:se.selectedValue.value,onSelect:rt})}}]}),he=Tn({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 rt=zt=>{Ss(he);const Lt={...he,command:"toggleOrderedListStyle"};e.emitCommand({item:Lt,argument:zt})};return Kr(X4,{buttons:WB,iconSize:30,selectedStyle:he.selectedValue.value,onSelect:rt})}}]}),Ne=Tn({type:"button",name:"indentleft",command:"decreaseTextIndent",icon:t.indentLeft,active:!1,tooltip:n.indentLeft,disabled:!1,attributes:{ariaLabel:"Left indent"}}),pe=Tn({type:"button",name:"indentright",command:"increaseTextIndent",icon:t.indentRight,active:!1,tooltip:n.indentRight,disabled:!1,attributes:{ariaLabel:"Right indent"}}),ye=Tn({type:"overflow",name:"overflow",command:null,icon:t.overflow,active:!1,disabled:!1,attributes:{ariaLabel:"Overflow items"}}),me=Tn({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:rt})=>{rt&&(me.label.value=rt)}}),_e=Tn({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:rt})=>{rt&&(_e.label.value=rt)}}),oe=Tn({type:"button",name:"undo",disabled:!0,tooltip:n.undo,command:"undo",icon:t.undo,group:"left",attributes:{ariaLabel:"Undo"}}),Me=Tn({type:"button",disabled:!0,name:"redo",tooltip:n.redo,command:"redo",icon:t.redo,group:"left",attributes:{ariaLabel:"Redo"}}),Ge=Tn({type:"button",disabled:!1,name:"acceptTrackedChangeBySelection",tooltip:n.trackChangesAccept,command:"acceptTrackedChangeFromToolbar",icon:t.trackChangesAccept,group:"left",attributes:{ariaLabel:"Accept tracked changes"}}),lt=Tn({type:"button",disabled:!1,name:"rejectTrackedChangeOnSelection",tooltip:n.trackChangesReject,command:"rejectTrackedChangeFromToolbar",icon:t.trackChangesReject,group:"left",attributes:{ariaLabel:"Reject tracked changes"}}),Ct=Tn({type:"button",name:"clearFormatting",command:"clearFormat",tooltip:n.clearFormatting,icon:t.clearFormatting,attributes:{ariaLabel:"Clear formatting"}}),Re=Tn({type:"button",name:"copyFormat",tooltip:n.copyFormat,icon:t.copyFormat,command:"copyFormat",active:!1,attributes:{ariaLabel:"Copy formatting"}}),Ke=(rt,zt)=>rt==="editor"?zt:rt==="suggester"?zt.filter(Lt=>Lt.value==="suggesting"):zt.filter(Lt=>Lt.value==="viewing"),tt=rt=>rt==="editor"?"Editing":rt==="suggester"?"Suggesting":"Viewing",ee=Tn({type:"dropdown",name:"documentMode",command:"setDocumentMode",allowWithoutEditor:!0,icon:t.documentMode,defaultLabel:tt(s),label:tt(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:()=>te(ee)}]}),_=[{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 te(rt){return Kr(ez,{options:Ke(s,_),onSelect:zt=>{const Lt=e.superdoc?.activeEditor??e.activeEditor;Ss(rt);const{label:An,icon:Qt,value:wn}=zt;ee.label.value=An,ee.icon.value=Qt,e.emitCommand({item:ee,argument:wn}),bu(e,Lt)}})}const D=new Map([["separator",20],["zoom",71],["measurementUnit",52],["fontFamily",118],["fontSize",57],["textAlign",40],["linkedStyles",142],["documentMode",47],["default",32]]),U=["search","ruler","undo","overflow","documentMode"],$=Tn({type:"button",name:"ruler",command:"toggleRuler",allowWithoutEditor:!0,icon:t.ruler,active:!1,tooltip:n.ruler,attributes:{ariaLabel:"Ruler"}}),H=Tn({type:"button",name:"formattingMarks",command:"toggleFormattingMarks",allowWithoutEditor:!0,icon:t.formattingMarks,active:!1,tooltip:n.formattingMarks,attributes:{ariaLabel:"Formatting marks"}}),J=Tn({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 rt=Lt=>{Ss(J);const An=typeof Lt=="string"?Lt:Lt?.id??null;if(!An)return;const Qt={...J,command:"setLinkedStyle"};e.emitCommand({item:Qt,argument:An})},zt=e.getActiveLinkedStyleId?.()??null;return Kr("div",{},[Kr(oz,{styles:e.getLinkedStyleOptions?.()??[],onSelect:rt,selectedOption:zt})])}}],onActivate:({styleId:rt,styleName:zt})=>{const Lt=zt||rt;J.label.value=rt&&rt!=="Normal"?String(Lt):n.formatText,J.disabled.value=!1},onDeactivate:()=>{J.disabled.value=!0,J.label.value=n.formatText}}),X=(rt,zt)=>{if(zt.value==rt)return Kr("div",{innerHTML:Fz,class:"dropdown-select-icon"})},W=Tn({type:"dropdown",name:"lineHeight",tooltip:n.lineHeight,icon:t.lineHeight,hasCaret:!1,hasInlineTextInput:!1,hideLabel:!0,inlineTextInputVisible:!1,suppressActiveHighlight:!0,restoreEditorFocus:!0,isWide:!1,command:"setLineHeight",dropdownValueKey:"key",selectedValue:"1",attributes:{ariaLabel:"Line height"},options:[1,1.15,1.5,2,2.5,3].map(rt=>({label:rt.toFixed(2),key:rt,icon:()=>X(rt,W.selectedValue),props:{"data-item":"btn-lineHeight-option"}}))}),we=20,ge=32,be=U.reduce((rt,zt)=>rt+(D.get(zt)||D.get("default")),0),Be=["linkedStyles","clearFormatting","copyFormat","formattingMarks"],Ze=["zoom","fontFamily","fontSize","redo"],it=i<=Ff.lg,yt=e.config?.showFormattingMarksButton===!0,Xt=e.config?.showTableOfContentsButton===!0;it&&(ee.attributes.value={...ee.attributes.value,className:`${ee.attributes.value.className} sd-toolbar-item--doc-mode-compact`}),it&&(J.attributes.value={...J.attributes.value,className:`${J.attributes.value.className} sd-toolbar-item--linked-styles-compact`});let xt=[oe,Me,Ge,lt,x,me,u,v,p,v,l,S,C,A,w,y,v,L,R,...Xt?[F]:[],Z,N,v,Q,se,he,Ne,pe,W,v,J,v,$,_e,...yt?[H]:[],Re,Ct,...Bz(e)?[d]:[],ye,ee];if(i<=Ff.md&&o&&(xt=xt.filter(rt=>rt.type!=="separator")),e.config.mode!=="docx"){const rt=xt.findIndex(Lt=>Lt.name.value==="linkedStyles");xt.splice(rt-1,2);const zt=["ruler","zoom","undo","redo"];xt=xt.filter(Lt=>!zt.includes(Lt.name.value))}const Ft=[];a||(s==="viewer"&&Ft.push(Ge,lt),xt=xt.filter(rt=>!Ft.includes(rt)));const Ut=rt=>U.includes(rt.name.value),mn=[],It=[];let Zt=ge+be;return xt.forEach(rt=>{const zt=D.get(rt.name.value)||D.get("default");if(i<Ff.xl+we&&Be.includes(rt.name.value)&&o){if(mn.push(rt),rt.name.value==="linkedStyles"){const Lt=xt.findIndex(An=>An.name.value==="linkedStyles");xt.splice(Lt+1,1)}return}if(i<Ff.sm&&Ze.includes(rt.name.value)&&o){mn.push(rt);return}if(Ut(rt)){It.push(rt),Zt+=zt;return}Zt<i||!o?(It.push(rt),Zt+=zt):mn.push(rt)}),{defaultItems:It,overflowItems:mn.filter(rt=>rt.type!=="separator")}},eA={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"},jz=e=>e?typeof e!="string"?e instanceof HTMLElement?e:null:e.startsWith("#")||e.startsWith(".")?document.querySelector(e):document.getElementById(e):null;Dt();function tA(e){return gN(e)??Z0[e]??null}function fm(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 Uz=new Set(["bold","italic","underline","strike","color","highlight","link","clearFormatting","textAlign","list","numberedlist","indentleft","indentright","lineHeight","linkedStyles"]),Hz=new Set(["list","numberedlist"]);function $z(e,t){if(e==="fontFamily"||e==="fontSize"||Hz.has(e)&&t?.disabled&&t?.supported!==!1&&t?.reason==null)return!0;if(!Uz.has(e))return!1;const n=t?.reason;return n==="range-selection-required"||n==="selection-required"}function nA(e){return!!e?.closest?.("[data-editor-ui-surface], .toolbar-dropdown-menu, .sd-toolbar-dropdown-menu, .sd-tooltip-content")}function Gz(e){return["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)}var Wz=class extends Gm.default{config={selector:null,toolbarGroups:["left","center","right"],role:"editor",icons:{...fr},texts:{...eA},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={...fr,...e.icons},this.config.texts={...eA,...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._reportedInvalidCustomItems=new Set,this._lastFontOptionsSignature="",!this.config.selector&&this.config.element&&(this.config.selector=this.config.element),this.toolbarContainer=jz(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=zl(BB),this.app.directive("click-outside",qv),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||PB(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}=Vz({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=new Set([...n,...r].map(c=>c.name?.value).filter(Boolean)),s=o.map((c,u)=>{try{if(c?.name&&i.has(c.name))throw new Error(`Toolbar item name "${c.name}" is already taken by another item, so this entry is skipped.`);const d=this.#c(c);return i.add(d.name?.value),d}catch(d){const h=`${c?.name??`<unnamed@${u}>`}::${d?.message??String(d)}`;return this._reportedInvalidCustomItems.has(h)||(this._reportedInvalidCustomItems.add(h),this.#b(d,c?.name??null)),null}}).filter(Boolean);s.length&&n.push(...s);let a=[...n.map(c=>c.name.value),...r.map(c=>c.name.value)];if(t){const c=Object.values(this.config.groups).flatMap(h=>h),u=new Set(Object.keys(this.config.groups)),d=s.filter(h=>u.has(h.group?.value||"center")).map(h=>h.name.value);a=[...new Set([...c,...d])]}const l=n.filter(c=>a.includes(c.name.value)).filter(c=>!this.config.excludeItems.includes(c.name.value));if(t)for(const[c,u]of Object.entries(this.config.groups))for(const d of l)u.includes(d.name.value)&&(d.group.value=c);this.toolbarItems=l,this.overflowItems=r.filter(c=>a.includes(c.name.value))}#c(e){const t=Tn({...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:()=>Q0(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=Y4.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(Y0(t)?.disposition==="host-routed")return e.setDisabled(!this.#u(t)),this.#g(t)?e.activate():e.deactivate(),!0;const n=tA(t);if(!n)return!1;const r=this.snapshot?.commands?.[n];$z(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=J0(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.#L(),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")}#L(){this.#l().forEach(e=>{const{allowWithoutEditor:t}=e;t?.value||e.setDisabled(!0)})}#P(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}#D(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=q4[t?.command];return i?fm(this.ui,i,void 0,r):!1}if(Y0(n)?.disposition==="unsupported")return!0;const o=tA(n);return o?fm(this.ui,o,t,r):!1}#T(){return this.snapshot?.commands?.image?.disabled||(this.#t||(this.#t=SN({ownerDocument:this.toolbarContainer?.ownerDocument??document,onPick:async e=>{const t=await CN(e,this.superdoc?.config?.handleImageUpload);fm(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=>{nA(i.target)||this.ui.formatPainter.setPointerSelecting(!0)},n=i=>{this.ui.formatPainter.setPointerSelecting(!1),!nA(i.target)&&this.ui.formatPainter.notifyPointerUp()},r=i=>{if(i.key==="Escape"){this.ui.formatPainter.cancel();return}Gz(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={error:e instanceof Error?e:new Error(String(e)),originalError:e,itemName:t??null,editor:this.superdoc?.activeEditor??this.activeEditor??null},r={...n};this.emit("exception",n),this.superdoc?.emit?.("exception",r)}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(Y0(r)?.disposition==="host-routed"){this.#P(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(!fm(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.#D(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 Kz(e){return new Wz(e)}function qz(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 Yz(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=hm(e.color);n!=null&&(t.color=n),e.highlight!=null&&(t.highlight=e.highlight);const r=Zz(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=Xz(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=Qz(e.border);return i&&(t.border=i),t}function hm(e){if(e){if(typeof e=="string")return e;if(e.model==="rgb")return e.value;if(e.model==="auto")return"auto"}}function Xz(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 Zz(e){if(!e)return;const t={},n=hm(e.fill);n!=null&&(t.fill=n);const r=hm(e.color);return r!=null&&(t.color=r),e.pattern!=null&&(t.val=e.pattern),Object.keys(t).length>0?t:void 0}function Qz(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=hm(e.color);return n!=null&&(t.color=n),Object.keys(t).length>0?t:void 0}function Ql(e){const t=e?.selectionTarget??e?.target;if(!e||!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Jz=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"]),eV=e=>e?.type!=="mutation:committed"||e.origin!=="command"?!1:Jz.has(e.editableCommandKind);function rA(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function tV(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 rA(r))n(o);return n(e.getAttribute("data-track-change-id")),t}function oA(e,t){if(!e||typeof e.getAttribute!="function")return[];const n=[],r=new Set;let o=[],i=e;for(;i;){const s=i,a=tV(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 c=s.getAttribute("data-layout-story");if(c&&o.length>0){for(const g of o)g.story=c;o=[]}const u=s.getAttribute("data-comment-ids");if(u)for(const g of rA(u)){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"),S={type:"contentControl",id:h};(p==="block"||p==="inline")&&(S.scope=p),v&&(S.tag=v),n.push(S)}}if(t&&i===t)break;i=i.parentElement}return n}var mo=()=>({oneOf:[{type:"boolean"},{type:"null"}]}),ul=()=>({oneOf:[{type:"string",minLength:1},{type:"null"}]}),wu=()=>({oneOf:[{type:"number"},{type:"null"}]}),Cu=e=>({oneOf:[{type:"object",properties:e,additionalProperties:!1,minProperties:1},{type:"null"}]}),nV={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},rV={type:"object",properties:{id:{type:"number"},val:{type:"boolean"}},required:["id"],additionalProperties:!1},oV=()=>({oneOf:[{type:"boolean"},{type:"null"},nV]}),iV=()=>({oneOf:[{type:"array",items:rV,minItems:1},{type:"null"}]});function pm(e,t){return{storage:"mark",markName:e,textStyleAttr:t}}function sV(e){return{storage:"runAttribute",nodeName:"run",runPropertyKey:e}}var e2=(e,t,n)=>({key:e,type:"boolean",ooxmlElement:t,storage:"mark",tracked:!0,carrier:pm(n),schema:mo()}),Jl=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"mark",tracked:!0,carrier:pm("textStyle",o??e),schema:r}),Yn=(e,t,n,r,o)=>({key:e,type:t,ooxmlElement:n,storage:"runAttribute",tracked:!1,carrier:sV(o??e),schema:r}),mm=[e2("bold","w:b","bold"),e2("italic","w:i","italic"),e2("strike","w:strike","strike"),{key:"underline",type:"object",ooxmlElement:"w:u",storage:"mark",tracked:!0,carrier:pm("underline"),schema:oV()},{key:"highlight",type:"string",ooxmlElement:"w:highlight",storage:"mark",tracked:!0,carrier:pm("highlight"),schema:ul()},Jl("color","string","w:color",ul()),Jl("fontSize","number","w:sz",wu()),Jl("fontFamily","string","w:rFonts",ul()),Jl("letterSpacing","number","w:spacing",wu()),Jl("vertAlign","string","w:vertAlign",{oneOf:[{enum:["superscript","subscript","baseline"]},{type:"null"}]}),Jl("position","number","w:position",wu()),Yn("dstrike","boolean","w:dstrike",mo()),Yn("smallCaps","boolean","w:smallCaps",mo()),Jl("caps","boolean","w:caps",mo(),"textTransform"),Yn("shading","object","w:shd",Cu({fill:{oneOf:[{type:"string",minLength:1},{type:"null"}]},color:{oneOf:[{type:"string",minLength:1},{type:"null"}]},val:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Yn("border","object","w:bdr",Cu({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"),Yn("outline","boolean","w:outline",mo()),Yn("shadow","boolean","w:shadow",mo()),Yn("emboss","boolean","w:emboss",mo()),Yn("imprint","boolean","w:imprint",mo()),Yn("charScale","number","w:w",wu(),"w"),Yn("kerning","number","w:kern",wu(),"kern"),Yn("vanish","boolean","w:vanish",mo()),Yn("webHidden","boolean","w:webHidden",mo()),Yn("specVanish","boolean","w:specVanish",mo()),Yn("rtl","boolean","w:rtl",mo()),Yn("cs","boolean","w:cs",mo()),Yn("bCs","boolean","w:bCs",mo(),"boldCs"),Yn("iCs","boolean","w:iCs",mo(),"italicCs"),Yn("eastAsianLayout","object","w:eastAsianLayout",Cu({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"}]}})),Yn("em","string","w:em",ul()),Yn("fitText","object","w:fitText",Cu({val:{oneOf:[{type:"number"},{type:"null"}]},id:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Yn("snapToGrid","boolean","w:snapToGrid",mo()),Yn("lang","object","w:lang",Cu({val:{oneOf:[{type:"string",minLength:1},{type:"null"}]},eastAsia:{oneOf:[{type:"string",minLength:1},{type:"null"}]},bidi:{oneOf:[{type:"string",minLength:1},{type:"null"}]}})),Yn("oMath","boolean","w:oMath",mo()),Yn("rStyle","string","w:rStyle",ul(),"styleId"),Yn("rFonts","object","w:rFonts",Cu({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"),Yn("fontSizeCs","number","w:szCs",wu()),Yn("ligatures","string","w14:ligatures",ul()),Yn("numForm","string","w14:numForm",ul()),Yn("numSpacing","string","w14:numSpacing",ul()),Yn("stylisticSets","array","w14:stylisticSets",iV()),Yn("contextualAlternates","boolean","w14:cntxtAlts",mo())],JH=new Set(mm.map(e=>e.key)),aV=Object.fromEntries(mm.map(e=>[e.key,e])),e$={mark:mm.filter(e=>e.storage==="mark").map(e=>e.key),runAttribute:mm.filter(e=>e.storage==="runAttribute").map(e=>e.key)},t2=new WeakMap;function lV(e){let t=t2.get(e);return t||(t={refCount:0,generation:0,abortController:new AbortController,inFlight:null,activeMutationTokens:new Set},t2.set(e,t)),t.refCount+=1,t}function cV(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(),t2.delete(e))}var uV=new Set(Object.values(dt));function n2(e,t){return typeof e=="string"&&uV.has(e)?e:t}function iA(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:dt.notReady}:{ok:!1,reason:n2(t,dt.targetUnresolved)}}return{ok:!0}}var dV=["document-replaced","editorCreate","active-editor-change","document-mode-change","zoomChange","measurement-unit-change","viewport-change","fonts-changed"],fV={[N4.bulletList]:"bullet",[N4.numberedList]:"ordered"};function sA(e){return fV[e]??null}var hV={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 pV(e){const t=hV[e];return t?{preset:t,behavior:"toggleStyle"}:{}}var mV={status:"ready",empty:!0,target:null,selectionTarget:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[],quotedText:""},gV=[{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"}],vV=new Set(["/word/comments.xml","/word/commentsExtended.xml","/word/commentsIds.xml"]);function yV(e){return gV.some(t=>t.match==="exact"?t.key===e:e.startsWith(t.key))}var aA={ready:0,stale:1,pending:2};function ku(...e){let t="ready";for(const n of e)aA[n]>aA[t]&&(t=n);return t}function Ot(e,t){if(typeof e!="function")return t;try{const n=e();return n===void 0?t:n}catch{return t}}function Tr(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function Sr(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 nr(e,t="CAPABILITY_UNAVAILABLE"){return{success:!1,failure:{code:t,message:e}}}function Nf(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 Bf(e){if(!e||typeof e!="object")return null;const t=e.target;return t&&typeof t=="object"?t:null}function r2(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 bV(e){if(!e||typeof e!="object")return null;const t=Bf(e);if(r2(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 xr(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 Su(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=Bf(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 Xi(e,t,n){return er(e)!==t?!1:n?xr(Su(e))===xr(n):!0}function gm(e){const t=Su(e);if(!(!t||xr(t)===xr(null)))return t}function wV(e){if(typeof e!="string"||e.length===0)return;const t=y6(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 CV(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 o2(e){if(!e||typeof e!="object")return null;const t=e.selectionTarget;return t&&typeof t=="object"?t:null}function vm(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function kV(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 er(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 SV(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 lA=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 c=s.replacement;if(c&&typeof c=="object")for(const d of[c.inserted,c.deleted])d&&typeof d=="object"&&(n(d.id),n(d.wordId));const u=s.move;if(u&&typeof u=="object")for(const d of[u.source,u.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 ya(e){const t=lA.get(e);if(t)return t;const n=new Set,r=new Map;for(const i of e){const s=er(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 lA.set(e,o),o}var uA=new WeakMap,dA=new WeakMap;function _u(e,t){const n=xr(t);let r=uA.get(e);r||(r=new Map,uA.set(e,r));const o=r.get(n);if(o)return o;const i=ya(e.filter(s=>xr(Su(s))===n));return r.set(n,i),i}function _V(e){return!!e&&typeof e=="object"&&e.storyType==="textbox"}function AV(e,t){const n=t.filter(o=>e.some(i=>er(i)===o&&Su(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=>er(s)===o);if(i)for(const s of cA(i)){if(r.has(s))return null;r.add(s)}}return n[0]}function IV(e){const t=dA.get(e);if(t)return t;const n=e.filter(o=>Su(o)!=null),r=n.length===e.length?e:n;return dA.set(e,r),r}function EV(e){const{selectionIds:t,publicIds:n,selection:r,bodyItems:o,allStoryItems:i}=e;if(t.length===0)return null;const s=c=>{for(const u of t){const d=c.toPublicId(u);if(d)return d}return null},a=Zi(r),l=xr(a)===xr(null);if(i){const c=l?IV(i):i,u=s(_u(c,a));if(u)return u;const d=n?.find(h=>c.some(g=>Xi(g,h,a)));return d||(l?s(ya(o)):_V(a)?AV(i,t):null)}return l?s(ya(o))??t[0]??null:null}function TV(e,t){const n=e.find(r=>er(r)===t||r.importedId===t);return n?n.rootCommentId??n.parentCommentId??er(n)??t:null}function xV(e){const t=e.selectionTarget;if(t){const s=t.start,a=t.end,l=typeof s?.blockId=="string"?s.blockId:void 0,c=typeof a?.blockId=="string"?a.blockId:l;if(l)return{startBlockId:l,endBlockId:c??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 $r(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 RV=64;function ec(e){return e.length<=RV}function Zi(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 So(e,t){return{kind:"block",nodeType:"paragraph",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}function ba(e){return{kind:"block",nodeType:"paragraph",nodeId:e}}function fA(e,t){return{kind:"block",nodeType:"listItem",nodeId:e,...t&&typeof t=="object"?{story:t}:{}}}var hA=720;function _s(e){return Math.round(e*20)}function Au(e){return typeof e=="number"&&Number.isFinite(e)}function MV(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=Au(i.left)?_s(i.left):Au(i.start)?_s(i.start):void 0,a=Au(i.right)?_s(i.right):Au(i.end)?_s(i.end):void 0,l=Au(i.firstLine)?_s(i.firstLine):void 0,c=Au(i.hanging)?_s(i.hanging):void 0;return s==null&&a==null&&l==null&&c==null?null:{...s!=null?{left:s}:{},...a!=null?{right:a}:{},...l!=null?{firstLine:l}:{},...c!=null?{hanging:c}:{}}}function i2(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 LV(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 zf(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 dl(e){return zf(e.target)??zf(e.selectionTarget)}var pA=["fontFamily","fontSize","color","highlight"],PV={undo:"history.undo",redo:"history.redo"},Vf=["bold","italic","underline","strikethrough"];function s2(e){return pA.includes(e)}function Iu(e){const t=e.target,n=t&&Array.isArray(t.segments)?t.segments:[],r=[],o=(l,c,u)=>{typeof l!="string"||typeof c!="number"||typeof u!="number"||r.push({blockId:l,start:Math.min(c,u),end:Math.max(c,u)})};for(const l of n){const c=l?.range;o(l?.blockId,c?.start,c?.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 DV(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 wa(e){const t=Iu(e);return t.length===0?null:[DV(e),...t.map(n=>`${n.blockId}:${n.start}-${n.end}`)].join("|")}function mA(e){const t=e.selectionTarget;return!t||typeof t!="object"?null:Ql({selectionTarget:t})}function OV(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 FV(e,t){return Math.max(e.start,t.start)<Math.min(e.end,t.end)}function NV(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 BV(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 gA(e,t){const n=Iu(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=>BV(n,NV(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 zV(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 a2(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 VV(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 jV(e,t){return e==="fontFamily"?t.toLowerCase():e==="color"||e==="highlight"?t.toUpperCase():t}function vA(e,t){if(!e)return{};const n=new Map;for(const i of Iu(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 pA){const s=new Map;let a=!1,l=!1;for(const c of r){const u=typeof c?.blockId=="string"?c.blockId:null;if(!u)continue;const d=n.get(u);if(!d?.length)continue;const h=Array.isArray(c?.runs)?c.runs:[];for(const g of h){const p=g?.range,v=typeof p?.start=="number"?p.start:null,S=typeof p?.end=="number"?p.end:null;if(v==null||S==null||!d.some(y=>FV(y,{start:v,end:S})))continue;a=!0;const C=zV(g?.styles,i);if(C===void 0){l=!0;continue}const A=jV(i,C);if(s.has(A)||s.set(A,C),s.size>1)break}if(s.size>1)break}a&&!l&&s.size===1&&(o[i]=[...s.values()][0])}return o}function l2(e,t){const n=$r(e)[0];return n?t==="nodeId"?{kind:"after",nodeId:n}:{kind:"after",target:So(n)}:{kind:"documentEnd"}}function sn(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 fl(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 ym(e){const t=e,n=t.change;return n&&typeof n=="object"?n:t}function As(e){if(Tr(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 bm(e){return!!e&&typeof e=="object"&&e.success===!0}function _o(e){return!(e===!1||e&&typeof e=="object"&&e.success===!1)}function tc(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function c2(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 c of l.blocks)n(c);l?.paragraph&&n(l.paragraph)}}};if(Array.isArray(e))for(const r of e)n(r);return t}function nc(e,t){return e.sourceAnchor?.sourceNodeId===t?!0:e.id===t}function wm(e){return e.trackedChange?.kind==="delete"?0:typeof e.text=="string"?e.text.length:0}function Ci(e){let t=!1,n=null,r=null,o=null;for(const i of e)t=i,!_o(i)&&n===null&&(n=i),bm(i)&&(o=i),i!==!1&&(r=i);return n??o??r??t}function UV(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 HV(e){return e.startsWith("#")?{kind:"anchor",anchor:e.slice(1)}:{kind:"external",url:e}}function Cm(e){return yu(e)?.trackDecision??null}function $V(e){return{found:e.length>0,success:e.length>0,rects:e,rect:e[0]}}function hl(e){return{found:!1,success:!1,rects:[],reason:e}}function GV(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 WV(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 yA(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(WV))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 KV(e){return e.selectionTarget?e.selectionTarget:yA(e.target)}function Eu(e){if(e.empty)return null;if(e.selectionTarget)return e.selectionTarget;const t=yA(e.target);return t&&t.start.kind==="text"&&t.end.kind==="text"&&t.start.blockId!==t.end.blockId?null:t}function u2(e){return!e.inline||typeof e.docRoute!="string"?null:e.docRoute.startsWith("format.")?e.docRoute.slice(7):null}var d2={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},qV=Object.fromEntries(Object.entries(d2).filter(([e])=>aV[e]?.tracked===!0));function YV(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:{...d2}};default:return null}}function XV(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 ZV(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 QV(e){const t=e.superdoc,n=new Map,r=new Map;let o=null,i=0;const s=[];let a=null,l=0,c=!1,u=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={},S="",C=null;const A=()=>{const f=t?.activeEditor;return f&&typeof f=="object"?f:null},y=()=>{const f=A()?.doc;return f&&typeof f=="object"?f:null},w=()=>{const f=A()?.v2TrackedChanges;return f&&typeof f=="object"?f:null},x=()=>{const f=A();if(f?.editorVersion!==2)return null;const m=f.reviewHydration;return m&&typeof m=="object"?m:null},L=()=>{const f=x();return!f||typeof f.getSnapshot!="function"?null:Ot(()=>f.getSnapshot(),null)},V=()=>typeof x()?.getSnapshot=="function",G=f=>{const m=f?.status;return m==="ready"||m==="stale"?m:"pending"},R=()=>{const f=A()?.host;return f&&typeof f=="object"?f:null},F=f=>{if(f.storyType!=="headerFooterPart"||typeof f.refId!="string")return null;const m=A(),b=R(),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=Ot(()=>E.call(I),null);if(!K||typeof K.pageIndex!="number")return null;for(const ae of["header","footer"]){const ue=Ot(()=>z.call(b,{pageIndex:K.pageIndex,kind:ae}),null);if(!(ue?.status!=="ready"||ue.refId!==f.refId||typeof ue.sectionId!="string"||!["default","first","even"].includes(String(ue.slotVariant))))return{kind:"story",storyType:"headerFooterSlot",section:{kind:"section",sectionId:ue.sectionId},headerFooterKind:ae,variant:ue.slotVariant}}return null},Z=()=>{const f=R(),m=f?.getPendingInlineFormat;if(typeof m!="function")return null;const b=Ot(()=>m.call(f),null);return b&&typeof b=="object"?b:null},O=f=>{const m=u2(f);if(!m)return null;const b=Z();if(!b||!(m in b))return null;const I=b[m];return f.inline?.kind==="toggle"?I===!0:I!=null&&I!==""},N=f=>{const m=u2(f);if(!m)return;const b=Z();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)},T=(f,m)=>{const b=R(),I=b?.setPendingInlineFormat;typeof I=="function"&&Ot(()=>I.call(b,f,m),void 0)},B=f=>{const m=R(),b=m?.clearPendingInlineFormat;typeof b=="function"&&Ot(()=>b.call(m,f),void 0)},Q=new Set(["bold","italic","underline","strikethrough"]),q=f=>{const m=Z();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(Q.has(E))K=b.includes(E)===(z===!0);else if(s2(E)){if(z==null)continue;I||(I=yl(f)),K=I[E]===z}else K=!1;K&&B(E)}},se=()=>{const f=A()?.editCommands;return f&&typeof f=="object"?f:null},he=f=>{const m=se();if(!m||typeof m.getSnapshot!="function")return null;const b=Ot(()=>m.getSnapshot(),null)?.commands?.[f];return b&&typeof b=="object"?b:null},Ne=()=>he("lists.apply"),pe=f=>{const m=f?.value?.seed;return m==="bullet"||m==="ordered"?m:null},ye=f=>{const m=PV[f];return m?he(m):null},me=()=>{const f=R();if(!f||typeof f.getTableContext!="function")return null;const m=Ot(()=>f.getTableContext(),null);return m&&typeof m=="object"?m:null},_e=()=>{const f=me();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,ae=typeof E?.index=="number"&&Number.isInteger(E.index)?E.index:null;if(K==null||ae==null)return null;const ue=typeof z?.nodeId=="string"&&z.nodeId.length>0?z.nodeId:null,Le=f.cellRange;return{tableNodeId:b,rowIndex:K,columnIndex:ae,cellNodeId:ue,mergeRange:XV(Le)}},oe=new Map;let Me=null,Ge=null,lt=0,Ct=0,Re=0;const Ke=new Set,tt=(f,m)=>f===m?!0:!f||!m?!1:f.id===m.id&&f.paintedEntityId===m.paintedEntityId&&xr(f.story)===xr(m.story),ee=f=>Array.from(Ke).some(m=>tt(m,f)),_=f=>{const m=R();if(typeof m?.getHandles!="function")return;const b=Ot(()=>m.getHandles(),null),I=b?.review;if(I){if(f){if(typeof I.setActiveReviewTarget!="function")return;const E=b?.layout;Ot(()=>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"||Ot(()=>I.getActiveReviewTarget(),null)?.entityType==="trackedChange"&&Ot(()=>I.clearActiveReviewTarget(),void 0)}},te=(f,m)=>{Ge=f,lt+=1,Re+=1,m?.invalidateQueuedNavigation!==!1&&(Ct+=1)},D=new Set;let U=!1,$=null;const H=new Map,J=new Set;let X=null,W=null,we=!1,ge=null,be=0,Be=null,Ze=null,it=null;const yt=()=>{if(we||U)return;we=!0;const f=()=>{we=!1,U||j()};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Xt=250,xt=5e3,Ft=f=>{U||ge&&be<=f||(ge&&clearTimeout(ge),be=f,ge=setTimeout(()=>{ge=null,be=0,U||j()},Math.max(0,f-Date.now())))},Ut=new WeakMap;let mn=0;const It=f=>{if(!f)return"none";let m=Ut.get(f);return m==null&&(m=mn+=1,Ut.set(f,m)),`e${m}`};let Zt=0,rt={};const zt=e.superdoc,Lt=lV(zt),An=()=>{Lt.abortController.abort("review-mutation-started"),Lt.inFlight=null},Qt=()=>{Lt.generation+=1,Lt.abortController=new AbortController,Lt.inFlight=null},wn=f=>{const m=Lt.activeMutationTokens;if(typeof f!="string"||f.length===0||m.has(f))return;const b=m.size===0;m.add(f),b&&An()},Wn=f=>{const m=Lt.activeMutationTokens;typeof f!="string"||!m.delete(f)||m.size===0&&Qt()},go=f=>{const m=w(),b=m?.listTrackedChanges;if(typeof b!="function")return A()?.editorVersion===2?Promise.reject(new Error("v2-tracked-changes-bridge-pending")):f();if(Lt.activeMutationTokens.size>0)return Promise.reject(new Error("ui-review-catalog-superseded"));if(A()?.reviewHydration?.getDiagnostics?.()?.inFlight===!0)return Promise.reject(new Error("shell-review-hydration-in-flight"));const I=Lt.generation,E=Lt.inFlight;if(E?.generation===I)return E.promise;const z=Lt.abortController.signal,K=Le=>{if(z.aborted||I!==Lt.generation||Le?.reason==="review-hydration-superseded")throw new Error("ui-review-catalog-superseded");return Le},ae=b.call(m,{blocking:!1,signal:z});if(!Tr(ae))return K(ae);const ue=Promise.resolve(ae).then(K);return Lt.inFlight={generation:I,promise:ue},ue.then(()=>{Lt.inFlight?.promise===ue&&(Lt.inFlight=null)},()=>{Lt.inFlight?.promise===ue&&(Lt.inFlight=null)}),ue};let jn=null,Xn=null,Ao=0;const Nr=()=>{Xn&&clearTimeout(Xn),Xn=null,Ao=0};let rr=f=>{},Pn=null,De=new Set,Oe=null,qe=0,wt=null;const ft=()=>`${It(A())}|m${Zt}`,Pt=()=>{Pn=null,De=new Set},_n=f=>{for(const m of["trackChanges","trackChanges:all"]){const b=H.get(m);if(!b?.hasSettled||!Array.isArray(b.value))continue;const I=b.value.filter(E=>{const z=er(E);return!z||!f.has(z)});I.length!==b.value.length&&H.set(m,{...b,value:I})}},an=f=>{const m=()=>{if(!U)for(const z of[...D])z(ht)},b=tc(f)?f:null,I=A()?.documentMutationReadiness,E=()=>{const z=globalThis.requestAnimationFrame;return typeof z!="function"?Promise.resolve():new Promise(K=>{let ae=!1;const ue=()=>{ae||(ae=!0,clearTimeout(Le),K())},Le=setTimeout(ue,250);z(()=>z(()=>setTimeout(ue,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()},Dn=(f,m)=>{const b=ht.trackChanges,I=b.items.filter(K=>{const ae=er(K);return!ae||!f.has(ae)});if(I.length===b.items.length)return;Ge&&f.has(Ge.id)&&te(null);const E=new Set;for(const K of I){const ae=ym(K),ue=K,Le=ae.author??ae.authorEmail??ue.author??ue.authorEmail;typeof Le=="string"&&E.add(Le)}const z=b.items.length-I.length;ht={...ht,trackChanges:{...b,items:I,total:Math.max(I.length,b.total-z),activeId:b.activeId&&f.has(b.activeId)?null:b.activeId,authors:[...E]}},an(m)},Io=f=>{const m=ht.trackChanges,b=m.items.length>0||m.total!==0||m.activeId!==null||m.authors.length>0;Oe=ft(),Ge!==null&&te(null),ht={...ht,trackChanges:{...m,items:[],total:0,activeId:null,authors:[]}},b&&an(f)},Eo=(f,m)=>{if(f.size===0)return;const b=ft(),I=Pn===b?De:new Set,E=new Set([...f].filter(z=>!I.has(z)));E.size!==0&&(Pn=b,De=new Set([...I,...E]),_n(De),Dn(E,m))},ki=f=>Pn===f&&De.size>0?De:null,cn=(f,m=[])=>{const b=f.map(fl).filter(E=>E!=null&&er(E)!=null);if(b.length===0)return;const I=m.map(fl).map(E=>E==null?null:er(E)).filter(E=>E!=null);for(const E of["trackChanges","trackChanges:all"]){const z=H.get(E),K=z?.hasSettled&&Array.isArray(z.value)?[...z.value]:[],ae=new Set;let ue=!1;for(const Le of b){const Ue=er(Le);if(!Ue)continue;const je=K.findIndex(Ve=>er(Ve)===Ue);if(je<0)K.push(Le),ae.add(Ue);else{const Ve=K[je];K[je]=tc(Ve)?{...Ve,...Le}:Le}ue=!0}if(E==="trackChanges"&&ae.size>0&&I.length>0){const Le=new Set(I.filter(Ve=>ae.has(Ve))),Ue=new Map(K.filter(Ve=>Le.has(er(Ve)??"")).map(Ve=>[er(Ve),Ve])),je=K.filter(Ve=>!Le.has(er(Ve)??""));for(const[Ve,Xe]of I.entries()){if(!Le.has(Xe))continue;const $e=Ue.get(Xe);if(!$e)continue;const Qe=I.slice(Ve+1).map(at=>je.findIndex(ot=>er(ot)===at)).find(at=>at>=0);if(Qe!=null){je.splice(Qe,0,$e);continue}const Je=I.slice(0,Ve).reverse().map(at=>je.findIndex(ot=>er(ot)===at)).find(at=>at>=0);je.splice(Je==null?je.length:Je+1,0,$e)}K.splice(0,K.length,...je)}ue&&H.set(E,{token:z?.token??null,value:K,hasSettled:!0,inflightToken:null})}},On=f=>{const m=ft(),b=ki(m),I=f.map(fl).filter(E=>{if(E==null)return!1;const z=er(E);return z!=null&&!b?.has(z)});for(const E of["trackChanges","trackChanges:all"])H.set(E,{token:m,value:[...I],hasSettled:!0,inflightToken:null})},Fn=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]}}},lr=Ok({getContext:()=>{const f=A();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:rt,v2TrackedChanges:m,docTrackChanges:b}},reconcile:async(f,m)=>{m.removedIds.size>0&&Eo(new Set(m.removedIds));const b=[...new Set(m.upsertIds)];if(b.length===0)return{ok:!0,items:[],resolvedIds:[],unresolvedIds:[]};const I=H.get("trackChanges"),E=I?.hasSettled&&Array.isArray(I.value)?I.value:null,z=new Set(E?E.map(er).filter(Je=>Je!=null):[]),K=E?.length===0&&To()==="complete",ae=new Set(b.filter(Je=>!z.has(Je))),ue=f.v2TrackedChanges?.getTrackedChange,Le=f.docTrackChanges?.get;if(typeof ue!="function"&&typeof Le!="function")return{ok:!1,items:[],resolvedIds:[],unresolvedIds:b};const Ue=await Promise.all(b.map(async Je=>{try{if(typeof ue=="function"){const ot=await Promise.resolve(ue.call(f.v2TrackedChanges,Je));return{id:Je,ok:ot?.ok!==!1,items:ot?.ok!==!1&&Array.isArray(ot?.items)?ot.items:[],result:ot}}const at=await Promise.resolve(Le.call(f.docTrackChanges,{id:Je}));return{id:Je,ok:!0,items:at&&typeof at=="object"?[at]:[],result:at}}catch(at){return{id:Je,ok:!1,items:[],result:at}}})),je=[],Ve=[],Xe=[];for(const Je of Ue){const at=Je.items.filter(ot=>{const Nt=fl(ot);return Nt!=null&&er(Nt)===Je.id});Je.ok&&at.length>0?(je.push(...at),Ve.push(Je.id)):Xe.push(Je.id)}let $e;const Qe=Ve.filter(Je=>ae.has(Je));if(Qe.length>0&&!K){const Je=await Fn(f,{trackedChangesListMode:"interaction-prime",refreshReason:"mutation-render-reconcile",blocking:!1,targetIds:Qe});Je.ok&&($e=Je.items)}return{ok:Xe.length===0,items:je,orderedItems:$e,resolvedIds:Ve,unresolvedIds:Xe,failures:Ue.filter(Je=>!Je.ok).map(Je=>Je.result)}},hydrate:Fn,onReconciled:(f,m,b)=>{if(b?.reconcileMode==="authoritative"){if(f.reconcileToken!==rt)return;b.ok===!0&&b.complete===!0&&b.sourceCoverageComplete===!0?(Nr(),On(b.items??[]),jn=null):b.ok===!0?(Nr(),cn(b.items??[])):rr(f.reconcileToken),j();return}const I=(b?.items??[]).filter(E=>{const z=fl(E),K=z==null?null:er(z);return K!=null&&m.has(K)});cn(I,b?.orderedItems??b?.items??[]),j()}});rr=f=>{if(U||Xn)return;const m=Math.min(Xt*2**Ao,xt);Ao+=1,Xn=setTimeout(()=>{Xn=null,!(U||jn===null||f!==rt)&&lr.onRender(!0)},m)};const Jt=()=>`${ft()}|m${wr()}|s${qe}`,Un=f=>JSON.stringify({t:f.target??null,s:f.selectionTarget??null}),ro=["contentControls:inRange:","query:","effInline:"],Pi=120,pl=180,To=()=>{const f=R(),m=f?.getDocumentLoadingSnapshot;if(typeof m!="function")return"unknown";const b=Ot(()=>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"},ai=new Map,ke=f=>{const m=ft();ai.get(f)!==m&&(ai.set(f,m),yt())},He=()=>{const f=H.get("comments");return f?.hasSettled?Array.isArray(f.value)&&f.value.length>0:f?.inflightToken!=null},Et=(f,m)=>ai.get(f)===m,st=f=>{ke("contentControls")},Nn=()=>{const f=H.get("trackChanges");f?.hasSettled||f?.inflightToken!=null||ke("trackChanges")},Kn=()=>{const f=H.get("comments");f?.hasSettled||f?.inflightToken!=null||ke("comments")},_r=6500,jo=250;let xo=0,Di=0,Ro=!1,oo=null;const io=()=>{if(U||oo)return;const f=()=>{if(oo=null,U)return;const m=Date.now()-xo;if(Ho()||m<_r){oo=setTimeout(f,jo);return}Ro=!1,j()};oo=setTimeout(f,0)};let Si=null,Uo=null;const es=()=>{const f=R();if(!f||Si===f)return;Uo&&(Uo(),Uo=null),Si=f;const m=f.subscribeDocumentLoading;if(typeof m!="function"){Si=null,Br(_r);return}try{const b=z=>{const K=z?.sourceStage;(K==="source-complete"||K==="source-failed"||K==="source-cancelled")&&(xo=Math.max(xo,Date.now()),io())},I=m.call(f,b);typeof I=="function"&&(Uo=I);const E=f.getDocumentLoadingSnapshot;typeof E=="function"&&b(Ot(()=>E.call(f),null))}catch{Si=null,Br(_r)}},vo=()=>{const f=A()?.host,m=f?.getForegroundMutationState;if(typeof m!="function")return null;const b=Ot(()=>m.call(f),null);return{active:typeof b?.active=="number"?b.active:0,pending:typeof b?.pending=="number"?b.pending:0}},Ho=()=>{const f=vo();return!!(f&&(f.active>0||f.pending>0))},Br=(f=Pi)=>{U||Be||(Be=setTimeout(()=>{if(Be=null,U)return;if(Ze&&Ho()){Br(),j();return}const m=Ze;Ze=null,m===Jt()&&ka("selection",m,ic,zi),j()},f))},Oi=(f,m)=>{if(!vo())return!1;const b=`${f}\0${m}`;return J.has(b)?!1:(J.add(b),Br(pl),!0)},Fi=f=>{if(X==null||f===X)return W?.timer&&clearTimeout(W.timer),W=null,X=f,!1;if(W?.key===f)return W.ready?(W=null,X=f,!1):!0;W?.timer&&clearTimeout(W.timer);const m={key:f,ready:!1,timer:null};return m.timer=setTimeout(()=>{U||W!==m||(m.timer=null,m.ready=!0,j())},pl),W=m,!0},Tu=f=>eV(f),xu=()=>{Mo(),j()};let li=null,Ni=!1,Is=0;const Bi=()=>{li=null,Ni=!1,Is+=1},jf=()=>{const f=A(),m=f?.documentMutationReadiness;if(!f||typeof m?.whenPainted!="function"||(li={editor:f,readiness:m,afterEpoch:typeof m.getRenderEpoch=="function"?Ot(()=>m.getRenderEpoch.call(m),null):null},Ni))return;Ni=!0;const b=Is;(async()=>{for(;!U&&b===Is;){const E=li;if(li=null,!E){Ni=!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(U||b!==Is)return;if(A()!==E.editor){Bi();return}z&&xu()}})()},Ca=()=>{it&&clearTimeout(it),it=setTimeout(()=>{it=null,U||xu()},500)},ka=(f,m,b,I)=>{let E;try{E=b()}catch{E=void 0}if(!Tr(E)){const ae={token:m,value:I(E),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0};return H.set(f,ae),ae}const z=H.get(f),K=z?.failedToken===m;return H.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(ae=>{const ue=H.get(f);!ue||ue.inflightToken!==m||(H.set(f,{token:m,value:I(ae),hasSettled:!0,inflightToken:null,failedToken:null,failureCount:0,retryAtMs:0}),yt())},()=>{const ae=H.get(f);if(!ae||ae.inflightToken!==m)return;const ue=ae.failedToken===m?(ae.failureCount??0)+1:1,Le=Math.min(xt,Xt*2**Math.min(ue-1,8)),Ue=Date.now()+Le;H.set(f,{...ae,inflightToken:null,failedToken:m,failureCount:ue,retryAtMs:Ue}),Ft(Ue)}),null},Ar=(f,m,b,I)=>{const E=H.get(f);if(E&&E.token===m&&E.hasSettled)return{value:E.value,status:"ready"};if(yV(f)&&!Et(f,m)){if(To()==="loading")return Ro=!0,es(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(Ro)return io(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(Date.now()-Di<_r)return Ro=!0,io(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"}}if(Ho())return Br(),E?.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(E?.failedToken===m&&E.inflightToken==null&&(E.retryAtMs??0)>Date.now())return Ft(E.retryAtMs),E.hasSettled?{value:E.value,status:"stale"}:{value:null,status:"pending"};if(!E&&f.startsWith("effInline:")&&Fi(f))return{value:null,status:"pending"};if(!E&&Oi(f,m))return{value:null,status:"pending"};if(!E||E.inflightToken!==m){const K=ka(f,m,b,I);if(K)return{value:K.value,status:"ready"}}const z=H.get(f);return z?.hasSettled?{value:z.value,status:"stale"}:{value:null,status:"pending"}},Uf=f=>{for(const m of H.keys())f(m)&&H.delete(m)},ml=f=>{const m=Un(f),b=mA(f);return new Set([`contentControls:inRange:${m}`,`query:${m}`,...b?[`effInline:${b}`]:[]])},Hf=f=>{const m=ml(f);Uf(b=>ro.some(I=>b.startsWith(I))&&!m.has(b));for(const b of J){const I=b.split("\0",1)[0];ro.some(E=>I.startsWith(E))&&!m.has(I)&&J.delete(b)}},rc=()=>{const f=A();f!==wt&&(Bi(),lr.reset(),rt={},wt=f,H.clear(),jn=null,Nr(),ge&&clearTimeout(ge),ge=null,be=0,W?.timer&&clearTimeout(W.timer),W=null,X=null,C=null,o=null,Ze=null,J.clear(),ai.clear(),Ro=!1,Uo&&Uo(),Uo=null,Si=null,Pt(),Oe=null)},Mo=()=>{const f=jn!==null;Zt+=1,f&&(jn=ft()),Pt()},ci=()=>{const f=Oe===ft();Mo(),f&&(On([]),Oe=ft()),j()},Ru=f=>{if(typeof f!="string"||f.length===0)return nr("insertText requires a non-empty string.","INVALID_INPUT");if(wr()==="viewing")return nr("The document is read-only.","DOCUMENT_READONLY");const m=y(),b=m?.insert;if(!m||typeof b!="function")return nr("insert is unavailable.");const I=m.selection?.current;if(typeof I!="function")return nr("selection.current is unavailable.");const E=K=>{const ae=K&&typeof K=="object"?K:null,ue=ae?.selectionTarget??ae?.target??null;return!ue||typeof ue!="object"?nr("insertText requires a live selection target.","PRECONDITION_FAILED"):Ot(()=>Lo(b.call(m,{type:"text",value:f,target:ue}),nr("insert failed.")),nr("insert failed."))};let z;try{z=I.call(m.selection)}catch{return nr("insertText could not resolve the live selection.","PRECONDITION_FAILED")}return Tr(z)?Promise.resolve(z).then(E,()=>nr("insertText could not resolve the live selection.","PRECONDITION_FAILED")):E(z)},Mu=(f,m)=>({payload:f,state:ht,editor:A(),superdoc:t,context:m,ui:$,execute:(b,I)=>wc(b,I),executeAsync:(b,I)=>Tm(b,I),doc:y(),selection:ht.selection,documentMode:wr(),insertText:Ru}),ui=f=>f==="editing"||f==="suggesting"||f==="viewing"?f:null,wr=()=>{const f=A(),m=t&&typeof t=="object"?t:null,b=ui(m?.config?.documentMode),I=Ot(typeof m?.getActiveRuntime=="function"?()=>{const K=m.getActiveRuntime();return typeof K?.getSnapshot=="function"?K.getSnapshot():null}:void 0,null),E=ui(I?.documentMode),z=ui(f?.options?.documentMode);return b&&E&&b!==E?b:E??b??z},$f=()=>{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},qo=()=>{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},Es=()=>wr()==="viewing"||$f(),zi=f=>f&&typeof f=="object"?f:null,Ts=(f,m)=>{if(!f)return{...mV,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}},ts=()=>{const f=y()?.selection;return Ar("selection",Jt(),()=>f?.current?f.current({includeText:!0}):void 0,zi)},oc=()=>{const{value:f,status:m}=ts();return Ts(f,m)},ic=()=>{const f=y()?.selection;return f?.current?f.current({includeText:!0}):void 0},Lu=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},sc=f=>{const m=R(),b=m?.readLiveSelectionSyncSnapshot;if(typeof b!="function")return;const I=zi(Ot(()=>b.call(m),null));if(!I||!Lu(I))return;const E=Jt(),z=vo(),K=!!(z&&(z.active>0||z.pending>0));if(K)Ze=E,Br();else if(Ze=null,ka("selection",E,ic,zi))return;const ae=H.get("selection"),ue=Array.isArray(I.activeMarks)&&I.activeMarks.length>0?I.activeMarks:Array.isArray(ht.selection.activeMarks)?ht.selection.activeMarks:[],Le=Array.isArray(I.activeCommentIds)?I.activeCommentIds:[],Ue=SV(f),je=dl(ht.selection),Ve=zf(I.selectionTarget)??zf(I.target),Xe=je?.range,$e=Ve?.range,Qe=!!(z&&z.active>0&&je&&Ve&&je.blockId===Ve.blockId&&xr(je.story)===xr(Ve.story)&&typeof Xe?.start=="number"&&typeof $e?.start=="number"&&Math.abs($e.start-Xe.start)<=2),Je=Ue!=null||Qe?ht.selection.activeChangeIds.filter(ot=>Ue==null||ya(ht.trackChanges.items).aliasesFor(ot).includes(Ue)):[],at=Array.isArray(I.activeChangeIds)&&I.activeChangeIds.length>0?I.activeChangeIds:Je;H.set("selection",{token:E,value:{...I,activeMarks:ue,activeCommentIds:Le,activeChangeIds:at},hasSettled:!0,inflightToken:K?null:ae?.inflightToken??null})},xs=async(f=0)=>{const m=y()?.selection,b=m?.current,I=Jt();if(typeof b!="function")return H.set("selection",{token:I,value:null,hasSettled:!0,inflightToken:null}),j(),ht.selection;let E;try{E=b.call(m,{includeText:!0}),Tr(E)&&(E=await Promise.resolve(E))}catch{E=null}return U?Ts(null,"pending"):Jt()!==I?f<1?xs(f+1):ht.selection:(H.set("selection",{token:I,value:zi(E),hasSettled:!0,inflightToken:null}),j(),ht.selection)},Sa=f=>{const m=y()?.comments,b=L(),I=Ar("comments",ft(),()=>m?.list?m.list():void 0,je=>je&&Array.isArray(je.items)?je.items:[]),E=V()&&Array.isArray(b?.commentItems)?b.commentItems:null,z=I.status==="pending"&&E!=null,K=z?E:I.value,ae=z?G(b):I.status,ue=K??[],Le=f.activeCommentIds;Me&&!ue.some(je=>er(je)===Me)&&(Me=null);const Ue=Me??Le[0]??null;return{status:ku(ae,f.status),listStatus:ae,items:ue,total:ue.length,activeIds:Le,activeId:Ue}},Rs=()=>{const f=y()?.trackChanges,m=ft(),b=H.get("trackChanges:all"),{value:I,status:E}=jn===m?{value:b?.hasSettled?b.value:null,status:b?.hasSettled?"stale":"pending"}:Ar("trackChanges:all",m,()=>{if(!f?.list)return;const z=()=>f.list({in:"all"}),K=typeof w()?.listTrackedChanges=="function",ae=go(z);return K?Promise.resolve(ae).then(ue=>{const Le=tc(ue)?ue:null;return(Array.isArray(Le?.items)?Le.items:[]).some(Ue=>Su(Ue)==null)?z():ue}):ae},z=>(z&&Array.isArray(z.items)?z.items:[]).map(fl).filter(K=>K!=null));return E==="ready"?I:null},Pu=f=>{const m=y()?.trackChanges,b=w(),I=typeof b?.listTrackedChanges=="function"?b.listTrackedChanges:null,E=ft(),z=ki(E),K=H.get("trackChanges"),ae=L(),ue=jn===E?{value:K?.hasSettled?K.value:null,status:K?.hasSettled?"stale":"pending"}:Ar("trackChanges",E,()=>I?go(()=>m?.list?.()):m?.list?m.list({in:"all"}):void 0,fn=>fn&&Array.isArray(fn.items)?fn.items:[]),Le=V()&&Array.isArray(ae?.trackedChangeItems)?ae.trackedChangeItems:null,Ue=ue.status==="pending"&&Le!=null,je=Ue?Le:ue.value,Ve=Ue?G(ae):ue.status,Xe=(je??[]).map(fl).filter(fn=>fn!=null).filter(fn=>{const or=er(fn);return!or||!z?.has(or)}),$e=new Set;for(const fn of Xe){const or=ym(fn),bo=fn,rd=or.author??or.authorEmail??bo.author??bo.authorEmail;typeof rd=="string"&&$e.add(rd)}const Qe=m?.list?Rs():null,Je=Ge;Je&&(Je.story?Qe&&!Qe.some(fn=>Xi(fn,Je.id,Je.story))&&te(null):Xe.some(fn=>er(fn)===Je.id)||te(null));const at=Qe??Xe,ot=_u(at,Zi(f)),Nt=Oe===E?[]:z?f.activeChangeIds.filter(fn=>!z.has(fn)):f.activeChangeIds,qt=Nt.map(fn=>ot.toPublicId(fn)??fn),Qn=Ge?.story?_u(at,Ge.story):ya(at),tr=Ge?Qn.toPublicId(Ge.id)??Ge.id:null,Qr=EV({selectionIds:Nt,publicIds:qt,selection:f,bodyItems:Xe,allStoryItems:Qe}),zr=tr??Qr;return{status:ku(Ve,f.status),items:Xe,total:Xe.length,activeId:zr,authors:[...$e]}},ac=f=>{const m=y()?.contentControls,{value:b,status:I}=Ar("contentControls",ft(),()=>m?.list?m.list():void 0,ae=>ae&&Array.isArray(ae.items)?ae.items:[]),E=b??[],{ids:z,status:K}=Gf(m,f);return{status:ku(I,K,f.status),items:E,total:E.length,activeId:z[0]??null,activeIds:z}},Ms=(f,m)=>{if(!f||typeof f.listInRange!="function")return{lockModesById:new Map,status:"ready"};const b=xV(m);if(!b)return{lockModesById:new Map,status:"ready"};const{value:I,status:E}=Ar(`contentControls:inRange:${Un(m)}`,ft(),()=>f.listInRange(b),ae=>ae&&Array.isArray(ae.items)?ae.items:[]),z=I??[],K=new Map;for(const ae of z)typeof ae?.id=="string"&&K.set(ae.id,typeof ae.lockMode=="string"?ae.lockMode:"unlocked");return{lockModesById:K,status:E}},Gf=(f,m)=>{const{lockModesById:b,status:I}=Ms(f,m);return{ids:[...b.keys()],status:I}},_a=()=>{const f=t?.fonts;return{options:rj(tj(Ot(f?.getDocumentFontOptions?()=>f.getDocumentFontOptions():void 0,[])),nj(Ot(f?.getFontFamilyOptions?()=>f.getFontFamilyOptions():void 0,[]))),sizeOptions:oj}},Aa=()=>{const f=Ot(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}},so=()=>Ot(t?.getMeasurementUnit?()=>t.getMeasurementUnit():void 0,"in")==="cm"?"cm":"in",Du=()=>{const f=A();return{ready:f!=null,mode:wr(),dirty:f?!!f.isDirty:!1}},gl=f=>{const m=f.quotedText;if(typeof m!="string"||m.length===0)return null;const b=Iu(f);if(b.length===0||!ec(b.map(z=>z.blockId)))return null;const I=f.target,E=b.length===1?So(b[0].blockId,I?.story):void 0;return{select:{type:"text",pattern:m,mode:"contains",caseSensitive:!0},...E?{within:E}:{},require:"any"}},Ls=f=>{const m=y()?.query;if(typeof m?.match!="function")return null;const b=gl(f);if(!b)return null;const{value:I}=Ar(`query:${Un(f)}`,ft(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return gA(I,f)},lc=f=>{const m=R(),b=new Set($r(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Ot(()=>{if(typeof I!="function")return E.call(m);const Qe=Qi(f);return Qe?I.call(m,[...b],Qe):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=c2(z),ae=Qe=>{const Je={},at=a2(Qe.fontFamily);at&&(Je.fontFamily=at);const ot=VV(Qe.fontSize);return ot&&(Je.fontSize=ot),typeof Qe.color=="string"&&Qe.color.trim()!==""&&(Je.color=Qe.color.trim().toUpperCase()),typeof Qe.highlight=="string"&&Qe.highlight.trim()!==""&&(Je.highlight=Qe.highlight.trim().toUpperCase()),Je},ue=dl(f),Le=ue&&typeof ue.range?.start=="number"?ue.range.start:null;if(ue&&Le!==null&&b.has(ue.blockId)){const Qe=K.find(at=>nc(at,ue.blockId)),Je=Qe&&Array.isArray(Qe.runs)?Qe.runs:null;if(Je&&Je.length>0&&Je.every(at=>at?.kind==="text"||at?.kind==="tab")){let at=0,ot=null;for(const Nt of Je){const qt=wm(Nt);if(Le>=at&&Le<at+qt){ot=Nt;break}at+=qt}if(!ot){for(let Nt=Je.length-1;Nt>=0&&!ot;Nt-=1)Je[Nt]?.kind==="text"&&(ot=Je[Nt]);ot??=Je[Je.length-1]??null}return ot?ae(ot):{}}}const Ue=Iu(f);if(Ue.length>0){const Qe=new Set,Je=new Set;let at=!1,ot=!0;for(const Nt of Ue){const qt=K.find(Qr=>nc(Qr,Nt.blockId));if(!qt)return{};const Qn=Array.isArray(qt.runs)?qt.runs:[];if(Qn.length===0)continue;if(!Qn.every(Qr=>Qr?.kind==="text"||Qr?.kind==="tab")){ot=!1;break}let tr=0;for(const Qr of Qn){const zr=wm(Qr),fn=tr,or=tr+zr;if(fn<Nt.end&&or>Nt.start){at=!0;const bo=ae(Qr);bo.fontFamily&&Qe.add(bo.fontFamily),bo.fontSize&&Je.add(bo.fontSize)}tr=or}}if(ot&&at){const Nt={};return Qe.size===1&&(Nt.fontFamily=[...Qe][0]),Je.size===1&&(Nt.fontSize=[...Je][0]),Nt}}const je=new Set,Ve=new Set;let Xe=!1;for(const Qe of K){if(![...b].some(at=>nc(Qe,at)))continue;const Je=Array.isArray(Qe.runs)?Qe.runs:[];for(const at of Je){if(at?.kind!=="text")continue;Xe=!0;const ot=ae(at);ot.fontFamily&&je.add(ot.fontFamily),ot.fontSize&&Ve.add(ot.fontSize)}}if(!Xe)return{};const $e={};return je.size===1&&($e.fontFamily=[...je][0]),Ve.size===1&&($e.fontSize=[...Ve][0]),$e},ns=f=>{const m=R(),b=new Set($r(f));if(b.size===0)return{};const I=m?.readMountedProjectionBlocksByIds,E=m?.readMountedProjectionBlocks;if(typeof I!="function"&&typeof E!="function")return{};const z=Ot(()=>{if(typeof I!="function")return E.call(m);const $e=Qi(f);return $e?I.call(m,[...b],$e):I.call(m,[...b])},null);if(!Array.isArray(z))return{};const K=c2(z),ae=$e=>({bold:$e.bold===!0,italic:$e.italic===!0,underline:$e.underline!=null,strikethrough:$e.strike===!0}),ue=$e=>{const Qe={};for(const Je of Vf){const at=$e[Je];at.size===1&&(Qe[Je]=[...at][0])}return Qe},Le=dl(f),Ue=Le&&typeof Le.range?.start=="number"?Le.range.start:null;if(Le&&Ue!==null&&b.has(Le.blockId)){const $e=K.find(Je=>nc(Je,Le.blockId)),Qe=$e&&Array.isArray($e.runs)?$e.runs:null;if(Qe&&Qe.length>0&&Qe.every(Je=>Je?.kind==="text"||Je?.kind==="tab")){let Je=0,at=null;for(const ot of Qe){const Nt=wm(ot);if(Ue>=Je&&Ue<Je+Nt){at=ot;break}Je+=Nt}if(!at){for(let ot=Qe.length-1;ot>=0&&!at;ot-=1)Qe[ot]?.kind==="text"&&(at=Qe[ot]);at??=Qe[Qe.length-1]??null}return at?ae(at):{}}}const je=Iu(f);if(je.length>0){const $e={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Qe=!1,Je=!0;for(const at of je){const ot=K.find(Qn=>nc(Qn,at.blockId));if(!ot)return{};const Nt=Array.isArray(ot.runs)?ot.runs:[];if(Nt.length===0)continue;if(!Nt.every(Qn=>Qn?.kind==="text"||Qn?.kind==="tab")){Je=!1;break}let qt=0;for(const Qn of Nt){const tr=wm(Qn),Qr=qt,zr=qt+tr;if(Qr<at.end&&zr>at.start){Qe=!0;const fn=ae(Qn);for(const or of Vf)$e[or].add(fn[or])}qt=zr}}if(Je&&Qe)return ue($e)}const Ve={bold:new Set,italic:new Set,underline:new Set,strikethrough:new Set};let Xe=!1;for(const $e of K){if(![...b].some(Je=>nc($e,Je)))continue;const Qe=Array.isArray($e.runs)?$e.runs:[];for(const Je of Qe){if(Je?.kind!=="text")continue;Xe=!0;const at=ae(Je);for(const ot of Vf)Ve[ot].add(at[ot])}}return Xe?ue(Ve):{}},vl=(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=lc(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=Fu(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"}},Ou=["fontFamily","fontSize","bold","italic","underline","strikethrough"],cc=f=>{const m=f.selectionTarget;if(!m)return{value:null,status:"ready"};const b=Sr(y(),"format.readEffectiveInlineUniformity");if(!b)return{value:null,status:"ready"};const I=mA(f)??Un(f);return Ar(`effInline:${I}`,ft(),()=>b({target:m,offsetSpace:"selection",keys:Ou}),E=>E&&typeof E=="object"?E:null)},Fu=f=>{const{value:m,status:b}=cc(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"?a2(K.value):K.value};return{values:{fontFamily:E("fontFamily"),fontSize:E("fontSize")},status:b}},Nu=f=>{const{value:m,status:b}=cc(f);if(!m||m.success!==!0)return{values:null,status:b};const I=m.values,E={};for(const z of Vf){const K=I?.[z];K?.state==="uniform"&&(K.value==="true"||K.value==="false")&&(E[z]=K.value==="true")}return{values:E,status:b}},uc=(f,m)=>{const b=f.activeMark;if(!b||!Vf.includes(b))return null;const I=b,E=ns(m)[I];if(E!==void 0)return E;const{values:z}=Nu(m),K=z?.[I];return K!==void 0?K:null},Wf=async f=>{const m=f.selectionTarget;if(!m)return null;const b=Sr(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}},Bu=(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"?a2(z.value):z.value:delete f[E]}},dc=f=>vl(f,vA(Ls(f),f)),yl=f=>dc(f).values,fc=async f=>{const m=y()?.query,b=gl(f);if(typeof m?.match!="function"||!b)return yl(f);try{const I=await Promise.resolve(m.match(b)),E=vA(gA(I&&typeof I=="object"?I:null,f),f),z=vl(f,E);if(z.effectiveUniformityStatus!=="ready"&&(E.fontFamily===void 0||E.fontSize===void 0)){const K=await Wf(f);K&&Bu(z.values,E,K)}return z.values}catch{return yl(f)}},Ia=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}))},zu=f=>{const m=y()?.query;if(typeof m?.match!="function")return"ready";const b=gl(f);if(!b)return"ready";const{status:I}=Ar(`query:${Un(f)}`,ft(),()=>m.match(b),E=>E&&typeof E=="object"?E:null);return I},rs=f=>{const m=dc(f),b=m.values;if(f.empty)return m;const I=wa(f);return I?f.status==="ready"&&zu(f)==="ready"&&m.effectiveUniformityStatus==="ready"?(C={key:I,values:b},m):C&&C.key===I?{...m,values:{...C.values,...b}}:m:m},Kf=f=>{const m=y(),b=rs(f),I=b.values;f.status==="ready"&&!f.empty&&zu(f)==="ready"&&b.effectiveUniformityStatus==="ready"&&(v=I,S=`${Ql(f)}:${ft()}`);const E=m?.contentControls,{lockModesById:z}=Ms(E,f),K={};for(const ae of le())K[ae]=hc(ae,m,f,I,z);return K},Yr=f=>f?dt.operationUnavailable:A()?dt.documentApiUnavailable:dt.notReady,Vu=f=>f==="contentLocked"||f==="sdtContentLocked",_i=f=>{for(const m of f.values())if(Vu(m))return dt.contentControlLocked},ju=(f,m,b,I,E)=>{if(!m)return f.scope==="all"?dt.bulkDecisionsDisabled:Yr(E);if(b)return dt.documentReadonly;if(f.scope!=="all"&&I.activeChangeIds.length===0)return dt.selectionRequired},qf=f=>{const m=R(),b=Ot(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},Ea=(f,m)=>{if(f.scope!=="all"||typeof m?.[`${f.kind}All`]=="function")return;const b=qf(`trackedChanges.${f.kind}All`);if(!(b&&(b.status==="supported"||b.enabled===!0)))return dt.bulkDecisionsDisabled},hc=(f,m,b,I,E=new Map)=>{if(oe.has(f))return sn({supported:!0,enabled:!0,...Ot(oe.get(f).getState?()=>oe.get(f).getState(Mu(void 0)):void 0,{})},"custom");const z=wr()==="viewing",K=sA(f);if(K&&typeof se()?.lists?.apply=="function"){const Xe=Ne(),$e=typeof Xe?.shippedStatus=="string"?Xe.shippedStatus:null,Qe=$e!=="not-shipped"&&$e!=="disabled";return sn({enabled:Qe&&(typeof Xe?.enabled=="boolean"?Xe.enabled:!0),active:(Qe?pe(Xe):null)===K,supported:Qe,value:Xe?.value},"builtin")}const ae=Cm(f);if(ae){const Xe=m?.trackChanges,$e=typeof Xe?.decide=="function"||typeof Xe?.[ae.kind]=="function",Qe=typeof Xe?.decide=="function"||typeof Xe?.[`${ae.kind}All`]=="function",Je=ae.scope==="all"?Qe:$e,at=Ea(ae,Xe)??ju(ae,Je,Es(),b,m);return sn({enabled:at==null,active:!1,supported:Je,reason:at},"builtin")}if(f==="copy-format")return wr()==="viewing"?sn({supported:!0,enabled:!1,active:!1},"builtin"):A()?sn({supported:!0,enabled:!0,active:h.mode!=="idle"},"builtin"):sn({supported:!0,enabled:!1,active:!1,reason:dt.notReady},"builtin");const ue=yu(f);if(!ue)return sn({enabled:!1,active:!1,supported:!1,reason:dt.commandUnsupported},"unsupported");if(ue.disposition!=="routed")return sn({enabled:!1,active:!1,supported:!1,reason:ue.reason??dt.commandUnsupported},ue.disposition==="unsupported"?"unsupported":"builtin");if(ue.instanceRoute)return M(ue);if(ue.table)return ne(ue,m,z);if(ue.inline?.kind==="clear"){if(ue.mutates&&z)return sn({enabled:!1,active:!1,supported:!0,reason:dt.documentReadonly},"builtin");const Xe=_i(E);if(Xe)return sn({enabled:!1,active:!1,supported:!0,reason:Xe},"builtin");const $e=$r(b).length>0||Eu(b)!=null;return sn({enabled:$e,active:!1,supported:!0,reason:$e?void 0:dt.selectionRequired},"builtin")}const Le=ue.docRoute;if(!Le)return sn({enabled:!1,active:!1,supported:!1,reason:dt.commandUnsupported},"unsupported");if(Sr(m,Le)==null)return sn({enabled:!1,active:!1,supported:!1,reason:Yr(m)},"builtin");const Ue=ye(f);if(Ue){const Xe=Ue.shippedStatus,$e=Xe!=="not-shipped"&&Xe!=="disabled",Qe=typeof Ue.enabled=="boolean"?Ue.enabled:!0,Je=f==="undo"||f==="redo",at=Je&&Ue.historyResolved===!1,ot=Je&&$e&&Qe===!1&&Ue.reason===null&&!at,Nt=Ue.reason===void 0?void 0:ot?dt.historyEmpty:at?dt.notReady:n2(Ue.reason,dt.commandUnsupported);return ue.mutates&&z?sn({enabled:!1,active:!1,supported:$e,reason:dt.documentReadonly},"builtin"):sn({enabled:$e&&Qe,active:!1,supported:$e,reason:Nt},"builtin")}const je=Ta(ue,m,b),Ve=Uu(ue,m,b,I);if(ue.list?.mode==="indent"||ue.list?.mode==="outdent")return kl(ue,m,z,b,je,Ve);if(ue.list?.mode==="toggle-seed")return Zf(ue,m,z,b,je,Ve);if(ue.mutates&&z)return sn({enabled:!1,active:je,supported:!0,value:Ve,reason:dt.documentReadonly},"builtin");if(ue.inline&&!Eu(b)){const Xe=_i(E);return sn(Xe?{enabled:!1,active:je,supported:!0,value:Ve,reason:Xe}:$r(b).length>0&&typeof R()?.setPendingInlineFormat=="function"?{enabled:!0,active:je,supported:!0,value:Ve}:{enabled:!1,active:je,supported:!0,value:Ve,reason:dt.rangeSelectionRequired},"builtin")}if((ue.blockParagraph||ue.list)&&$r(b).length===0)return sn({enabled:!1,active:je,supported:!0,value:Ve,reason:dt.selectionRequired},"builtin");if(ue.link&&!je&&i2(b).length===0&&!dl(b))return sn({enabled:!1,active:je,supported:!0,reason:dt.rangeSelectionRequired},"builtin");if(ue.inline){const Xe=_i(E);if(Xe)return sn({enabled:!1,active:je,supported:!0,value:Ve,reason:Xe},"builtin")}return sn({enabled:!0,active:je,supported:!0,value:Ve},"builtin")};function Yf(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 ae=typeof I?.offset=="number"?I.offset:null,ue=typeof E?.offset=="number"?E.offset:null;if(ae==null||ue==null)return!1;const Le=m.target,Ue=Le&&Array.isArray(Le.segments)?Le.segments:[];for(const je of Ue){const Ve=typeof je?.blockId=="string"?je.blockId:null;if(!Ve)continue;const Xe=je.range,$e=typeof Xe?.start=="number"?Xe.start:null,Qe=typeof Xe?.end=="number"?Xe.end:null;if(!($e==null||Qe==null)){if(z!==K){if(Ve===z&&Qe>ae||Ve===K&&$e<ue)return!0;continue}if(Ve===z){if($e===Qe){if($e>=ae&&$e<=ue)return!0;continue}if(Math.max($e,ae)<Math.min(Qe,ue))return!0}}}return!1}const pc=(f,m)=>{const b=f?.hyperlinks;if(!b||typeof b.list!="function")return null;const I=$r(m);if(!ec(I))return null;for(const E of I){const z={kind:"block",nodeType:"paragraph",nodeId:E},{value:K}=Ar(`hyperlinks:${E}`,ft(),()=>b.list({within:z}),ue=>ue&&typeof ue=="object"?ue:null),ae=(K&&Array.isArray(K.items)?K.items:[]).find(ue=>Yf(ue,m));if(ae)return ae}return null},Ta=(f,m,b)=>{if(f.link)return pc(m,b)!=null;if(f.list?.mode==="toggle-seed"&&f.list.seed)return Hu(m,b)===f.list.seed;const I=O(f);if(I!==null)return I;const E=r.get(f.id),z=wa(b);if(z&&E?.selectionSignature===z)return E.active;const K=uc(f,b);return K!==null?K:ij(f,b)},Uu=(f,m,b,I)=>{if(f.inline&&s2(f.inline.key)){const E=N(f);if(E!==void 0)return E;const z=I[f.inline.key];if(z!==void 0)return z;const K=wa(b),ae=K?n.get(f.inline.key):void 0;if(K&&ae?.selectionSignature===K)return ae.value}if(f.id==="linked-style"){const{style:E}=We(b,Ie().cache);return!E.styleId||E.mixed?void 0:{styleId:E.styleId,styleName:E.styleName}}if(f.id==="text-align")return Ds(m,b);if(f.id==="link")return k(m,b)??void 0},bl=(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:ba(m),story:b}):E&&typeof I.getState=="function"?()=>I.getState({target:ba(m)}):null;if(!z)return{value:null,status:"ready"};const{value:K,status:ae}=Ar(`lists:${xr(b)}:${m}`,ft(),z,ue=>ue&&typeof ue=="object"?ue:null);return{value:K?.success===!0?K:null,status:ae}},Ps=(f,m,b)=>bl(f,m,b).value,xa=(f,m,b)=>{const I=Ps(f,m,b);return!I||I.isListItem!==!0?null:I.seed==="bullet"||I.seed==="ordered"?I.seed:null},mc=(f,m,b)=>{const I=bl(f,m,b),E=I.value;return{value:E&&typeof E.isListItem=="boolean"?E.isListItem:null,status:I.status}},Hu=(f,m)=>{const b=$r(m);if(b.length===0||!ec(b))return null;const I=Zi(m),E=xa(f,b[0],I);if(E!=="bullet"&&E!=="ordered")return null;for(const z of b.slice(1))if(xa(f,z,I)!==E)return null;return E},gc=(f,m,b)=>{if(!f)return{value:null,status:"ready",refreshing:!1};const I=xr(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=ft(),ae=Ar(z,K,()=>E?f.getNodeById({nodeId:m,nodeType:"paragraph"}):f.getNode(So(m,b)),Le=>Le&&typeof Le=="object"?Le:null),ue=H.get(z);return{...ae,refreshing:ae.status==="stale"&&ue?.inflightToken===K&&ue.failedToken!==K}},vc=f=>f==="left"||f==="center"||f==="right"||f==="justify"?f:void 0,Xf=f=>f==="start"||f==="end"||f==="distributed"||f==="numTab"||f==="lowKashida"||f==="mediumKashida"||f==="highKashida"||f==="thaiDistribute",wl=(f,m)=>{const b=R(),I=b?.readMountedProjectionBlocksByIds;if(typeof I!="function")return null;const E=Qi(f),z=Ot(()=>E?I.call(b,[...m],E):I.call(b,[...m]),null);if(!Array.isArray(z))return new Map;const K=c2(z),ae=new Map;for(const ue of m){const Le=K.find(Xe=>nc(Xe,ue));if(!Le)continue;const Ue=Le.attrs,je=vc(Ue?.alignment),Ve=y9(Ue);ae.set(ue,je??(Ve==="rtl"?"right":"left"))}return ae},Cl=(f,m,b,I)=>{const{value:E,status:z,refreshing:K}=gc(f,m,b),ae=I?.get(m);if(z==="pending")return ae?{status:"uniform",value:ae}:{status:"pending"};if(z==="stale"&&!K)return{status:"pending"};if(z==="stale"&&ae)return{status:"uniform",value:ae};if(z==="stale"&&I&&!ae)return{status:"unavailable"};if(!E)return{status:"unavailable"};const ue=E.node;if(!ue)return{status:"unavailable"};const Le=ue.kind;if(Le!=="paragraph"&&Le!=="heading")return{status:"unavailable"};const Ue=ue[Le];if(!Ue||typeof Ue!="object")return{status:"unavailable"};const je=Ue.props?.alignment;if(je==null)return ae?{status:"uniform",value:ae}:{status:"unavailable"};const Ve=vc(je);return Ve?{status:"uniform",value:Ve}:Xf(je)&&ae?{status:"uniform",value:ae}:{status:"unavailable"}},$u=(f,m)=>{const b=$r(m);if(b.length===0||!ec(b))return{status:"unavailable"};const I=Zi(m),E=wl(m,b),z=Cl(f,b[0],I,E);if(z.status!=="uniform")return z;for(const K of b.slice(1)){const ae=Cl(f,K,I,E);if(ae.status!=="uniform")return ae;if(ae.value!==z.value)return{status:"mixed"}}return z},Gu=f=>{const m=$r(f);return m.length===0?null:`${xr(Zi(f))}:${m.join(",")}`},Ds=(f,m)=>{const b=$u(f,m),I=b.status==="uniform"?b.value:void 0,E=o;if(!E)return I;const z=Gu(m);return z&&z!==E.selectionSignature?(o=null,I):!z||!E.settled?E.value:b.status!=="pending"?(o=null,I):E.value},Gr=(f,m)=>{const b=vc(m),I=Gu(f),E=$r(f);if(!b||!I||E.length===0)return null;const z=++i;return o={selectionSignature:I,value:b,generation:z,settled:!1,canReconcile:ec(E)},j(),z},Wu=(f,m)=>{if(f==null)return;const b=o;if(!(!b||b.generation!==f)){if(!_o(m)){o=null;return}if(!b.canReconcile){o=null;return}b.settled=!0}},Ra=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:ba(m),story:b}):E&&typeof I.getState=="function"?await I.getState({target:ba(m)}):null,K=z&&typeof z=="object"?z:null;return!K||K.success!==!0||typeof K.isListItem!="boolean"?null:K.isListItem}catch{return null}},Ku=(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:ba(m),story:b}):z&&typeof E.getState=="function"?()=>E.getState({target:ba(m)}):null;if(!K)return I;const ae=ue=>{const Le=ue&&typeof ue=="object"?ue:null;return!Le||Le.success!==!0||typeof Le.isListItem!="boolean"?I:{resolved:!0,seed:Le.isListItem===!0&&(Le.seed==="bullet"||Le.seed==="ordered")?Le.seed:null}};try{const ue=K();return Tr(ue)?Promise.resolve(ue).then(ae,()=>I):ae(ue)}catch{return I}},qu=async(f,m,b)=>{if(!f)return null;try{const I=!b||b.storyType==="body",E=b&&typeof f.getNode=="function"?await f.getNode(So(m,b)):I&&typeof f.getNodeById=="function"?await f.getNodeById({nodeId:m,nodeType:"paragraph"}):null;return MV(E&&typeof E=="object"?E:null)}catch{return null}},kl=(f,m,b,I,E,z)=>{if(f.mutates&&b)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.documentReadonly},"builtin");const K=$r(I);if(K.length===0)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.selectionRequired},"builtin");const ae=f.docRoute?Sr(m,f.docRoute):null,ue=Sr(m,"format.paragraph.setIndentation"),Le=Sr(m,"format.paragraph.clearIndentation"),Ue=f.list?.mode,je=Ue==="indent"?ue!=null:ue!=null||Le!=null,Ve=Zi(I);let Xe=null;if(Ve.storyType!=="body"){Xe=[];for(const $e of K){const{value:Qe,status:Je}=mc(m,$e,Ve);if(Qe===null)return Je!=="ready"&&(ae!=null||je)?sn({enabled:!0,active:E,supported:!0,value:z},"builtin"):sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin");Xe.push(Qe)}}if(Xe?.some($e=>$e===!0)){const $e=Ue==="indent"?"lists.indentRange":"lists.outdentRange",Qe=wr()!=="suggesting"&&Xe.every(at=>at===!0)&&Sr(m,$e)!=null,Je=Ue==="outdent"&&Sr(m,"lists.outdentInStory")!=null;if(!Qe&&!Je)return sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin")}for(const[$e,Qe]of K.entries()){const Je=Xe?{value:Xe[$e]??null,status:"ready"}:mc(m,Qe,Ve),at=Je.value;if(at===!0){if(ae!=null)return sn({enabled:!0,active:E,supported:!0,value:z},"builtin");continue}if(at===!1&&je){if(Ve.storyType!=="body"&&typeof m?.getNode!="function")continue;return sn({enabled:!0,active:E,supported:!0,value:z},"builtin")}if(at===null)return Je.status!=="ready"&&(ae!=null||je)?sn({enabled:!0,active:E,supported:!0,value:z},"builtin"):sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin")}return sn({enabled:!1,active:E,supported:!1,value:z,reason:Yr(m)},"builtin")},Zf=(f,m,b,I,E,z)=>{if(f.mutates&&b)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.documentReadonly},"builtin");const K=$r(I);if(K.length===0)return sn({enabled:!1,active:E,supported:!0,value:z,reason:dt.selectionRequired},"builtin");const ae=Zi(I),ue=m?.lists;if(!(typeof ue?.getStateInStory=="function"||ae.storyType==="body"&&typeof ue?.getState=="function"))return sn({enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");if(!ec(K))return sn(ae.storyType==="body"&&Sr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");const Le=K.map(Xe=>bl(m,Xe,ae));if(Le.some(({status:Xe})=>Xe!=="ready"))return sn({enabled:!0,active:E,supported:!0,value:z},"builtin");if(Le.some(({value:Xe})=>Xe===null))return sn({enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");const Ue=f.list?.seed,je=Le.every(({value:Xe})=>Xe?.isListItem===!0&&Xe.seed===Ue);if(ae.storyType==="body")return sn(!je||Sr(m,"lists.remove")!=null?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin");const Ve=Sr(m,"lists.removeInStory");return sn(je&&Ve?{enabled:!0,active:E,supported:!0,value:z}:{enabled:!1,active:E,supported:!1,value:z,reason:dt.operationUnavailable},"builtin")},k=(f,m)=>{const b=pc(f,m)?.properties?.href;return typeof b=="string"?b:null},M=f=>{if(!A())return sn({enabled:!1,active:!1,supported:!1,reason:dt.notReady},"builtin");const m=f.instanceRoute;return typeof t?.[m]!="function"?sn({enabled:!1,active:!1,supported:!1,reason:dt.operationUnavailable},"builtin"):sn({enabled:!0,active:Y(f),supported:!0,value:ie(f)},"builtin")},Y=f=>{const m=t?.config??void 0;return f.valueFrom==="ruler"?!!m?.rulers:f.valueFrom==="formattingMarks"?!!m?.layoutEngineOptions?.showFormattingMarks:!1},ne=(f,m,b)=>{if(b)return sn({enabled:!1,active:!1,supported:!0,reason:dt.documentReadonly},"builtin");const I=_e();return I!=null&&(!f.table.requiresCell||I.cellNodeId!=null)?(f.docRoute?Sr(m,f.docRoute):null)==null?sn({enabled:!1,active:!1,supported:!1,reason:Yr(m)},"builtin"):sn({enabled:!0,active:!1,supported:!0},"builtin"):sn({enabled:!1,active:!1,supported:!0,reason:dt.tableContextUnavailable},"builtin")},ie=f=>{if(f.valueFrom==="zoom")return Aa().value;if(f.valueFrom==="documentMode")return wr();if(f.valueFrom==="measurementUnit")return so();if(f.valueFrom==="ruler"||f.valueFrom==="formattingMarks")return Y(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([...pN,...oe.keys()])],ce="Normal",Ce={ready:!1,status:"ready",catalogRevision:null,quickGallery:[],activeParagraphStyleId:null,activeParagraphStyleName:null,mixedSelection:!1,sourceStatus:null,diagnostics:[]},Ae=f=>{const m=y()?.styles;return!m||typeof m.getCatalog!="function"?{value:null,status:"ready"}:Ar(`styles:catalog:${JSON.stringify(f??{})}`,ft(),()=>m.getCatalog(f),b=>b&&typeof b=="object"?b:null)},Ie=()=>{const f=Ae({includePreview:!0});if(!f.value)return{cache:null,status:f.status};const m=Ae({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:ku(f.status,m.status)}},ze=(f,m,b)=>{const{value:I,status:E}=gc(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,ae=typeof K=="string"?z[K]:void 0,ue=ae&&typeof ae=="object"?ae.styleRef:void 0;return{ok:!0,styleRef:typeof ue=="string"&&ue.length>0?ue:null,status:E}},We=(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=$r(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(!ec(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?ce:null),K=new Set;let ae=0,ue=0,Le=0,Ue="ready";const je=Zi(f);for(const $e of E){const Qe=ze(I,$e,je);if(Ue=ku(Ue,Qe.status),!Qe.ok){ue+=1;continue}if(!Qe.styleRef&&!z){Le+=1;continue}const Je=Qe.styleRef??z;if(!Je){Le+=1;continue}ae+=1,K.add(Je)}if(ae===0){const $e=Le>0&&ue===0;return b.push({severity:"warning",code:$e?"active-style-default-unavailable":"active-style-read-failed",message:$e?"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 Ve=ue+Le;if(Ve>0)return b.push({severity:"warning",code:"active-style-partial",message:`Active paragraph style resolved from ${ae} of ${ae+Ve} selected blocks; ${Ve} 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}},ut=f=>{if(!A())return Ce;const{cache:m,status:b}=Ie(),{style:I,status:E}=We(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:ku(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}},Ye=()=>{const f=wr(),m=oc();m.status==="ready"&&Hf(m),q(m);const b=wa(m);for(const[I,E]of r)(!b||E.selectionSignature!==b||E.settled&&m.status==="ready")&&r.delete(I);return{ready:A()!=null,documentMode:f,document:Du(),selection:m,toolbar:{context:f,commands:Kf(m),copyFormatActive:h.mode!=="idle"},comments:Sa(m),trackChanges:Pu(m),contentControls:ac(m),zoom:Aa(),fonts:_a(),styles:ut(m)}},pt=f=>{const m=wa(f);m&&a&&m!==a&&(n.clear(),r.clear()),m&&(a=m)};let et=null,At=null,Gt=null,kt=null,cr=null,In=null,jt=!1;const en=()=>{if(U||jt)return;jt=!0;const f=()=>{jt&&(jt=!1,!U&&j())};typeof queueMicrotask=="function"?queueMicrotask(f):Promise.resolve().then(f)},Xr=()=>{const f=se();if(f!==Gt&&(kt&&(kt(),kt=null),Gt=f,!(!f||typeof f.subscribe!="function")))try{const m=f.subscribe(()=>en());typeof m=="function"&&(kt=m)}catch{Gt=null}},Rr=()=>{const f=x();if(f!==cr&&(In&&(In(),In=null),cr=f,!(!f||typeof f.subscribe!="function")))try{const m=f.subscribe(()=>j());typeof m=="function"&&(In=m)}catch{cr=null}};let Zr=null,Wr=null,ct=null,un=null,yo=null,Yo=null;const Xo=()=>{const f=A()?.host,m=Ot(f?.getHandles?()=>f.getHandles():void 0,null)?.editing?.selection;return m&&typeof m.subscribe=="function"?m:null},Os=()=>{const f=Xo();if(f!==et&&(At&&(At(),At=null),et=f,!!f))try{const m=f.subscribe(b=>{qe+=1,sc(b),j()});typeof m=="function"&&(At=m)}catch{et=null}},Ma=()=>{const f=A()?.host,m=Ot(f?.getHandles?()=>f.getHandles():void 0,null)?.review;return m&&typeof m.subscribe=="function"?m:null},di=f=>f?typeof f.getActiveReviewTarget=="function"?Ot(()=>f.getActiveReviewTarget(),null):typeof f.getSnapshot=="function"?Ot(()=>f.getSnapshot(),null)?.activeReviewTarget??null:null:null;let Zo=0;const Qo=(f,m)=>{const b=(m&&typeof m=="object"?m:null)?.lastInteractionRejection;if(Zo>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,ae=Rs(),ue=(ae?K?_u(ae,K).toPublicId(z):ya(ae).toPublicId(z):null)??z,Le=K&&xr(K)!==xr(null)?K:void 0;E={id:ue,...Le?{story:Le}:{},...typeof I.paintedEntityId=="string"&&I.paintedEntityId.length>0?{paintedEntityId:I.paintedEntityId}:ue!==z?{paintedEntityId:z}:{}}}return f==null&&E==null&&Ge!=null&&ee(Ge)||tt(Ge,E)?!1:(te(E),!0)},Fs=()=>{const f=Ma();if(f===Zr)return;if(Wr&&(Wr(),Wr=null),Zr=f,!f){Qo(null);return}let m=!0;try{const b=f.subscribe(I=>{const E=I&&typeof I=="object"?I:null,z=E&&Object.prototype.hasOwnProperty.call(E,"activeReviewTarget")?E.activeReviewTarget:di(f);!Qo(z,I)||m||j()});typeof b=="function"&&(Wr=b),Qo(di(f))}catch{Zr=null}finally{m=!1}},Sl=()=>{if(et||wr()!=="viewing")return null;const f=A()?.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},La=()=>{const f=Sl();if(f===yo||(Yo&&(Yo(),Yo=null),yo=f,!f))return;const m=()=>{qe+=1,j()};f.addEventListener("selectionchange",m),f.addEventListener("pointerup",m,!0),f.addEventListener("mouseup",m,!0),Yo=()=>{f.removeEventListener("selectionchange",m),f.removeEventListener("pointerup",m,!0),f.removeEventListener("mouseup",m,!0)}};rc(),Qo(di(Ma()));let ht=Ye();a=wa(ht.selection);const P=()=>{const f=A()?.host?.events,m=f&&typeof f.subscribe=="function"?f:null;if(m!==ct&&(un&&(un(),un=null),ct=m,!!m))try{const b=m.subscribe(I=>{const E=I?.type;if(E==="review-mutation:started"){wn(I.reviewMutation?.token);return}if(E==="review-mutation:aborted"){Wn(I.reviewMutation?.token),yt();return}if(E==="mutation:rejected"&&I.reviewMutation&&(Wn(I.reviewMutation.token),yt()),E==="mutation:committed"&&I.reviewMutation&&Wn(I.reviewMutation.token),E==="source:complete"||E==="source:signals-complete"){jn!==null&&(Nr(),lr.onRender(!0));return}if((E==="mutation:committed"||E==="collaboration:remote-changed")&&(xo=Date.now()),E==="mutation:committed"&&(Nr(),rt={}),E==="mutation:committed"||E==="save:completed"||E==="collaboration:remote-changed"){const z=E==="mutation:committed"?Dk(I):null,K=E==="mutation:committed"&&lr.getPendingIds().size>0;if(z?.allResolved){lr.reset(),On([]),jn=null,Io(I.receipt);return}z?.removedIds.size&&Eo(new Set(z.removedIds),I.receipt);const ae=z?.reconcileMode==="authoritative"&&z.upsertIds.size>0;if(ae&&(Mo(),Nr(),jn=ft(),j()),z?.upsertIds.size||K){const je=I.origin==="history"?null:I.receipt,Ve=A()?.documentMutationReadiness,Xe=typeof je?.txId=="string"&&je.txId.length>0&&typeof Ve?.whenPainted=="function",$e=I.origin==="history"&&typeof Ve?.getRenderEpoch=="function"?Ot(()=>Ve.getRenderEpoch.call(Ve),null):null,Qe=I.origin==="history"&&typeof Ve?.whenPainted=="function",Je={upsertIds:z?.upsertIds??new Set,removedIds:new Set,reconcileMode:z?.reconcileMode==="authoritative"?"authoritative":"targeted"};Xe?lr.enqueueAfterPaint(Je,()=>Ve.whenPainted.call(Ve,je)):Qe?lr.enqueueAfterPaint(Je,()=>Ve.whenPainted.call(Ve,typeof $e=="number"?{afterEpoch:$e}:void 0)):(lr.enqueue(Je),lr.onRender(K))}if(ae)return;const ue=E==="mutation:committed"&&Tu(I)||E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0;if(ue&&(Di=Date.now()),E==="mutation:committed"&&ue){Ca();return}if(z?.removedIds.size&&z.upsertIds.size===0)return;(E==="collaboration:remote-changed"||E==="mutation:committed"&&!ue)&&jf();const Le=E==="collaboration:remote-changed"&&Array.isArray(I.changedPartUris)&&I.changedPartUris.some(je=>typeof je=="string"&&vV.has(je)),Ue=E==="collaboration:remote-changed"&&Array.isArray(I.changedStoryIds)&&I.changedStoryIds.length>0&&He();Le&&!ue&&(Ro=!0),Mo(),Le&&!ue?ke("comments"):Ue&&(Ro=!0,io()),j()}});typeof b=="function"&&(un=b)}catch{ct=null}},j=()=>{if(U)return;jt=!1,rc(),Os(),Xr(),Rr(),Fs(),La(),P();const f=Ye();pt(f.selection),ht=f;for(const m of[...D])m(ht)},Se=[],Pe=[],mt=f=>{for(const m of f)try{m()}catch{}},nn=()=>mt(Se),Cn=()=>mt(Pe),Zn=[];((f,m)=>{if(!(!f||typeof f.on!="function"))for(const b of m){const I=b==="active-editor-change"?()=>{nn(),Cn(),j()}:b==="document-replaced"?E=>{const z=E&&typeof E=="object"?E:null,K=z?.editor,ae=z?.host,ue=!!K&&K===A(),Le=!!ae&&ae===R();!ue&&!Le||(Cn(),H.clear(),Mo(),j())}:()=>j();try{f.on(b,I),Zn.push(()=>{try{typeof f.off=="function"&&f.off(b,I)}catch{}})}catch{}}})(t,dV),Os(),Xr(),Rr(),Fs(),La(),P();const gn=(f,m=qz)=>({get:()=>f(ht),subscribe:b=>{let I=f(ht);const E=z=>{const K=f(z);m(I,K)||(I=K,b(K))};return D.add(E),()=>D.delete(E)}}),ln=f=>gn(f),qn=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 Rt(f){return f&&typeof f=="object"&&typeof f.id=="string"?String(f.id):null}function kn(f){const m=Qi(f);return m&&xr(m)!==xr(null)?m:void 0}function ur(f,m){return{kind:"id",id:f,...m?{story:m}:{}}}function En(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 Ir(f,m){if(xr(m)!==xr(null))return;const b=y()?.trackChanges,I=b?.list;if(typeof I!="function")return;const E=Ot(()=>I.call(b),null);if(Tr(E)||!E||typeof E!="object")return;const z=E.items;if(Array.isArray(z))return z.map(fl).find(K=>K!=null&&Xi(K,f,m))}function $o(f,m){const b=Ns(f.quotedText);if(!b)return!1;const I=ym(m);return[I.insertedText,I.deletedText,I.excerpt].some(E=>Ns(E)===b)}function Ns(f){return typeof f=="string"?f.replace(/\s+/g," ").trim():""}function Bs(){const f=ht.selection.activeChangeIds[0];if(!f)return"unavailable";const m=Qi(ht.selection),b=(ht.trackChanges.status==="ready"?ht.trackChanges.items.find(K=>Xi(K,f,m)):void 0)??Ir(f,m)??Rs()?.find(K=>Xi(K,f,m));if(!b)return"unavailable";const I=ym(b),E=I.type,z=I.grouping;return $o(ht.selection,b)?"id":E==="replacement"&&z==="replacement-pair"||(E==="insertion"||E==="deletion"||E==="insert"||E==="delete")&&z==="standalone"?"range":"id"}function yc(f,m,b,I){const E=()=>w2(f,ur(b,I),b,I);try{const z=w2(f,m,null);if(Tr(z))return Bn(Promise.resolve(z).then(ae=>_o(As(ae))?ae:E()));const K=As(z);return Bn(_o(K)?z:E())}catch{return!1}}function Yu(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:Rt(K),story:K.story}}const z=typeof E.changeId=="string"?E.changeId:E.id;if(typeof z=="string"&&z.length>0)return{target:ur(z,E.story),changeId:z,story:E.story}}const b=ht.selection.activeChangeIds[0],I=kn(ht.selection);return b?{target:ur(b,I),changeId:b,story:I}:null}function Xu(f,m){if(f.scope==="id"&&m==null){if(ht.selection.activeChangeIds.length>1)return th(f.kind,{kind:"ids",ids:ht.selection.activeChangeIds},null);if(ht.selection.activeChangeIds.length===1&&!ht.selection.empty&&ht.selection.selectionTarget){const I=Bs();if(I==="unavailable")return!1;if(I==="range"){const E=En(ht.selection),z=kn(ht.selection);return E?yc(f.kind,E,ht.selection.activeChangeIds[0],z):!1}if(I==="id"){const E=ht.selection.activeChangeIds[0],z=Qi(ht.selection),K=z&&xr(z)!==xr(null)?z:void 0;return b2(f.kind,K?{id:E,story:K}:E)}}}const b=Yu(f,m);return b?th(f.kind,b.target,b.changeId,b.story):!1}function _l(f,m){const b=se()?.lists,I=b?.apply;if(typeof I!="function")return!1;const{behavior:E,preset:z,continuity:K}=typeof m=="string"?pV(m):m&&typeof m=="object"?m:{},ae={kind:f,behavior:E??"toggle"};z!==void 0&&(ae.preset=z),K!==void 0&&(ae.continuity=K);try{return Bn(I.call(b,ae))}catch{return!1}}let Ln=Promise.resolve(!1),fi=null,Zu=Promise.resolve(!1);const bc=async f=>{if(!bm(f))return f;const m=A()?.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},Jo=f=>{if(Tr(f)){const b=Promise.resolve(f);return{immediate:!0,committed:b.then(I=>As(I),()=>!1),settled:b.then(I=>bc(As(I)),()=>!1)}}const m=As(f);return{immediate:m,committed:Promise.resolve(m),settled:bc(m)}},_m=()=>{const f=s.shift();if(!f){c=!1,d?.(),d=null;return}try{f.resolve(U?!1:f.mutate())}catch{f.resolve(!1)}},Qf=()=>{let f=!1;return()=>{f||(f=!0,_m())}},Am=(f,m)=>{if(!c){c=!0,u=new Promise(z=>{d=z});try{return{result:m(),release:Qf()}}catch(z){throw c=!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:Qf()}},p2=new Set(["create.tableOfContents"]),Im=f=>nr(`Tracked authoring is not supported for ${f}.`),Pa=f=>{if(wr()==="suggesting")return p2.has(f)?Im(f):{changeMode:"tracked"}},Qu=()=>wr()==="suggesting"?qV:d2,Mr=(f,m,b)=>{const I=Pa(f);return I&&I.success===!1?I:I?m(b,I):m(b)},Mt=(f,m,b,I)=>{const E=f.inline;if(!E)return;const z=As(I);if(z===!1||typeof z=="object"&&z&&z.success===!1)return;if(E.kind==="clear"){n.clear();return}if(E.kind==="toggle"||!s2(E.key))return;const K=wa(m);if(!K)return;const ae=OV(E.key,b.value);if(ae==null){n.delete(E.key);return}n.set(E.key,{selectionSignature:K,value:ae})},Wt=(f,m,b,I)=>!f.inline||f.inline.kind==="toggle"?I:Tr(I)?Promise.resolve(I).then(E=>(Mt(f,m,b,E),E)):I,vn=(f,m,b,I)=>{if(f.inline?.kind!=="toggle"||!_o(As(I))||typeof b.value!="boolean"&&b.value!==null)return null;const E=wa(m);if(!E)return null;const z=++l;return r.set(f.id,{selectionSignature:E,active:b.value===!0,generation:z,settled:!1}),j(),z},Lr=(f,m,b)=>{if(m==null)return;const I=r.get(f.id);if(!(!I||I.generation!==m)){if(!_o(b)){r.delete(f.id);return}I.settled=!0}},Pr=(f,m)=>f.then(b=>(m?.(b),ci(),b),()=>(m?.(!1),ci(),!1)),Bn=(f,m)=>{const b=fi;if(fi=null,b)return Ln=Pr(b,m),As(f);if(Tr(f))return Ln=Pr(Jo(f).settled,m),!0;const I=As(f);return bm(I)&&typeof A()?.documentMutationReadiness?.whenPainted=="function"?(Ln=Pr(bc(I),m),I):(m?.(I),Ln=Promise.resolve(I),ci(),I)},Ai=(f,m)=>!f||typeof f!="object"?m:f,Lo=(f,m=nr("Document API operation failed."))=>{if(Tr(f))return Promise.resolve(f).then(I=>Lo(I,m),()=>m);const b=Ai(f,m);return Mo(),bm(b)&&typeof A()?.documentMutationReadiness?.whenPainted=="function"?(Pr(bc(b)),j(),b):(j(),b)},Ju=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const ae=I(K);if(ae)try{const ue=Jo(Mr(f,m,ae));E.push(ue.immediate),z.push(ue.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return fi=z.length?Promise.all(z).then(K=>Ci(K)):null,Ci(E)},Rj=(f,m,b,I)=>{const E=[],z=[];for(const K of b){const ae=I(K);if(ae)try{const ue=Jo(Mr(f,m,ae));E.push(ue.immediate),z.push(ue.settled)}catch{E.push(!1),z.push(Promise.resolve(!1))}}return fi=z.length?Promise.all(z).then(K=>Ci(K)):null,Ci(E)},m2=(f,m,b,I=ht.selection)=>{const E=Pa(f);return E&&E.success===!1?E:I.selectionTarget?m(b,{...E??{},offsetSpace:"selection"}):E?m(b,E):m(b)},Mj=(f,m,b,I)=>{const E=So(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}},Lj=(f,m)=>{const b=f.inline,I=u2(f),E=R();if(!b||typeof E?.setPendingInlineFormat!="function")return!1;if(b.kind==="clear")return B(),!0;if(!I)return!1;let z;if(b.kind==="toggle")z=!Ta(f,y(),ht.selection);else{const K=m&&typeof m=="object"&&"value"in m?m.value:m;if(b.kind==="value-number"){const ae=typeof K=="number"?K:Number(K);z=Number.isFinite(ae)&&ae>0?ae:null}else z=typeof K=="string"&&K.trim()!==""?K:null;if(z===null)return T(I,null),!0}return T(I,z),!0},Pj=()=>{const f=y(),{lockModesById:m}=Ms(f?.contentControls,ht.selection);if(_i(m))return!1;const b=[],I=[],E=Xe=>{const $e=Jo(Xe);b.push($e.immediate),I.push($e.settled)},z=(Xe,$e,Qe)=>{try{E(Qe?Xe($e,Qe):Xe($e))}catch{b.push(!1),I.push(Promise.resolve(!1))}},K=Ie().cache?.full.defaults.paragraphStyleId??ce,ae=Eu(ht.selection);if(ae){const Xe=Sr(f,"format.apply");if(Xe)try{E(m2("format.apply",Xe,{target:ae,inline:{...Qu()}}))}catch{b.push(!1),I.push(Promise.resolve(!1))}}const ue=Sr(f,"format.paragraph.resetDirectFormatting"),Le=Sr(f,"styles.paragraph.setStyleRef"),Ue=Qi(ht.selection),je=!Ue||Ue.storyType==="body",Ve=Sr(f,je?"lists.remove":"lists.removeInStory");for(const Xe of $r(ht.selection)){const $e=So(Xe,Ue);if(ue&&z(ue,{target:$e}),Ve)try{const Qe=ba(Xe),Je=Jo(Ve(je?{target:Qe}:{target:Qe,story:Ue}));I.push(Je.settled.then(at=>_o(at)?at:!0))}catch{}Le&&z(Le,{target:$e,styleId:K})}if(!ae&&wr()!=="suggesting"){const Xe=Sr(f,"format.paragraph.setMarkRunProps");if(Xe)for(const $e of $r(ht.selection))z(Xe,{target:So($e,Ue),markRunProps:{bold:!1,italic:!1,strikethrough:!1,doubleStrikethrough:!1,smallCaps:!1,caps:!1,verticalAlign:"baseline"}})}return fi=I.length?Promise.all(I).then(Xe=>Ci(Xe)):null,Ci(b.length?b:[!1])},Dj=(f,m,b)=>{const I=$r(ht.selection);if(I.length===0)return!1;const E=Qi(ht.selection);return Ju(f.docRoute,m,I,z=>Mj(f.blockParagraph,z,b,E))},Oj=(f,m,b)=>{const I=y(),E=Sr(I,"format.paragraph.setIndentation"),z=Sr(I,"format.paragraph.clearIndentation"),K=f.list?.mode,ae=Zi(ht.selection),ue=Qi(ht.selection),Le=async Ue=>{const je=await Ra(I,Ue,ae);if(je===!0)return{kind:"list",routeToCall:f.docRoute,opToCall:m,input:{target:fA(Ue)}};if(je===null||ue&&ue.storyType!=="body"&&typeof I?.getNode!="function")return null;const Ve=await qu(I,Ue,ue),Xe={};if(Ve?.right!=null&&(Xe.right=Ve.right),Ve?.firstLine!=null&&(Xe.firstLine=Ve.firstLine),Ve?.hanging!=null&&(Xe.hanging=Ve.hanging),K==="indent")return E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:So(Ue,ue),left:Math.max(0,Ve?.left??0)+hA,...Xe}}:null;const $e=Math.max(0,(Ve?.left??0)-hA);return $e>0&&(Xe.left=$e),Object.keys(Xe).length===0?z?{kind:"paragraph",routeToCall:"format.paragraph.clearIndentation",opToCall:z,input:{target:So(Ue,ue)}}:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:So(Ue,ue),left:0}}:null:E?{kind:"paragraph",routeToCall:"format.paragraph.setIndentation",opToCall:E,input:{target:So(Ue,ue),...Xe}}:null};return fi=(async()=>{const Ue=await Promise.all(b.map($e=>Le($e).catch(()=>null)));if(Ue.length===b.length&&Ue.every($e=>$e?.kind==="list")&&wr()!=="suggesting"){const $e=K==="indent"?"lists.indentRange":"lists.outdentRange",Qe=Sr(I,$e);if(Qe)try{return await Jo(Mr($e,Qe,{paraIds:b,story:ae})).settled}catch{return!1}}const je=ae.storyType!=="body"&&Ue.some($e=>$e?.kind==="list"),Ve=je&&K==="outdent"?Sr(I,"lists.outdentInStory"):null;if(je&&!Ve)return!1;const Xe=Ue.map($e=>{if(!$e)return Promise.resolve(!1);try{return $e.kind==="list"&&Ve?Jo(Mr("lists.outdentInStory",Ve,{target:$e.input.target,story:ae})).settled:Jo(Mr($e.routeToCall,$e.opToCall,$e.input)).settled}catch{return Promise.resolve(!1)}});return Ci(await Promise.all(Xe))})(),!0},Fj=(f,m)=>{const b=f.list,I=y(),E=$r(ht.selection);if(E.length===0)return!1;const z=Zi(ht.selection),K=z.storyType==="body";if(b.mode==="indent"||b.mode==="outdent")return Oj(f,m,E);const ae=b.seed,ue=je=>{if(je.some(at=>!at.resolved))return{immediate:!1,settled:null};const Ve=je.every(at=>at.seed===ae);if(!Ve&&!K)return{immediate:!1,settled:null};const Xe=Ve?K?"lists.remove":"lists.removeInStory":f.docRoute,$e=Ve?Sr(I,Xe):m;if(!$e)return{immediate:!1,settled:null};const Qe=[],Je=[];return E.forEach((at,ot)=>{if(!Ve&&je[ot]?.seed===ae)return;const Nt=Ve?{target:ba(at),...K?{}:{story:z}}:{target:ba(at),seed:ae};try{const qt=Jo(Mr(Xe,$e,Nt));Qe.push(qt.immediate),Je.push(qt.settled)}catch{Qe.push(!1),Je.push(Promise.resolve(!1))}}),{immediate:Ci(Qe),settled:Je.length?Promise.all(Je).then(at=>Ci(at)):null}},Le=E.map(je=>Ku(I,je,z));if(Le.some(Tr))return fi=Promise.all(Le).then(async je=>{const Ve=ue(je);return Ve.settled?await Ve.settled:Ve.immediate}),!0;const Ue=ue(Le);return fi=Ue.settled,Ue.immediate};function Jf(f){return f&&typeof f=="object"?f:{}}function Nj(f){if(typeof f=="string")return f;const m=Jf(f);if(Object.prototype.hasOwnProperty.call(m,"href"))return m.href;if(Object.prototype.hasOwnProperty.call(m,"value"))return m.value}function Bj(f,m){const b=Jf(f).text;return typeof b=="string"&&b.trim()!==""?b:m}function _A(f){const m=Jf(f),b=m.capture&&typeof m.capture=="object"?m.capture:null;return m.target??b?.target??b?.selectionTarget??m.selectionTarget??m.textTarget??null}const zj=f=>{const m=y(),b=m?.hyperlinks;if(!b)return!1;const I=Jf(f),E=Nj(f),z=_A(f),K=typeof I.text=="string"?I.text:void 0,ae=typeof I.currentText=="string"?I.currentText:void 0,ue=tc(I.hyperlinkTarget)?I.hyperlinkTarget:null,Le=tc(I.textTarget)?I.textTarget:null,Ue=pc(m,ht.selection),je=typeof ue?.storyId=="string"&&typeof ue?.hyperlinkNodeId=="string";if(je&&E===null){const Ve=b.remove;if(typeof Ve!="function")return!1;try{return Mr("hyperlinks.remove",Ve,{storyId:ue.storyId,hyperlinkNodeId:ue.hyperlinkNodeId,keepText:!0})}catch{return!1}}if(Ue&&E===null){const Ve=b.remove;if(typeof Ve!="function")return!1;try{return Mr("hyperlinks.remove",Ve,{target:Ue.address,mode:"unwrap"})}catch{return!1}}if((Ue||ue)&&typeof E=="string"&&E.trim()!==""){const Ve=b.patch,Xe=b.updateTarget;if(!(!je&&Ue&&typeof Ve=="function")&&!(je&&typeof Xe=="function"))return!1;const $e=typeof K=="string"&&K!==(je?ae:Ue?.text??ae),Qe=m?.text?.replace,Je=$e?je?Le:UV(Ue?.address):null,at=$e&&!!Je&&typeof Qe=="function";if($e&&!at)return!1;const ot=[],Nt=[];let qt=null,Qn=null,tr=null,Qr=!1;try{if(je){if(typeof Xe!="function")return!1;const zr=Mr("hyperlinks.updateTarget",Xe,{storyId:ue.storyId,hyperlinkNodeId:ue.hyperlinkNodeId,newTarget:HV(E)});Qr=Tr(zr);const fn=Jo(zr);if(!_o(fn.immediate))return!1;ot.push(fn.immediate),Nt.push(fn.settled),qt=fn.immediate,Qn=fn.committed,tr=fn.settled}else if(Ue){if(typeof Ve!="function")return!1;const zr=Mr("hyperlinks.patch",Ve,{target:Ue.address,patch:{href:E}});Qr=Tr(zr);const fn=Jo(zr);if(!_o(fn.immediate))return!1;ot.push(fn.immediate),Nt.push(fn.settled),qt=fn.immediate,Qn=fn.committed,tr=fn.settled}}catch{return!1}if(at){const zr=(or,bo)=>_o(bo)?Ci([or,bo]):_o(or)?Nf(or,bo):bo,fn=or=>{if(!_o(or))return or;try{const bo=Jo(Mr("text.replace",Qe,{target:Je,text:K}));return _o(bo.immediate)?Promise.all([tr??Promise.resolve(or),bo.settled]).then(([rd,kU])=>zr(rd,kU)):Nf(or,bo.immediate)}catch{return Nf(or,!1)}};if(Qr)return fi=(Qn??Promise.resolve(qt??!1)).then(fn),Ci(ot);try{const or=Jo(Mr("text.replace",Qe,{target:Je,text:K}));if(!_o(or.immediate))return qt?Nf(qt,or.immediate):or.immediate;ot.push(or.immediate),Nt.push(or.settled),fi=Promise.all([tr??Promise.resolve(qt??!1),or.settled]).then(([bo,rd])=>zr(bo,rd))}catch{return qt?Nf(qt,!1):!1}}return!at&&Nt.length>0&&(fi=Promise.all(Nt).then(zr=>Ci(zr))),Ci(ot)}if(typeof E=="string"&&E.trim()!==""){const Ve=E.trim(),Xe=b.wrap,$e=LV(z),Qe=$e.length>0?$e:i2(ht.selection);if(Qe.length>0){if(typeof Xe!="function")return!1;try{return Rj("hyperlinks.wrap",Xe,Qe,Nt=>({target:Nt,link:{destination:{href:Ve}}}))}catch{return!1}}const Je=b.insert,at=Bj(f,Ve);if(typeof Je!="function"||at.trim()==="")return!1;const ot=zf(z)??dl(ht.selection);if(!ot)return!1;try{return Mr("hyperlinks.insert",Je,{target:ot,text:at,link:{destination:{href:Ve}}})}catch{return!1}}return!1},Vj=(f,m,b)=>{const I=f.create.kind,E=b&&typeof b=="object"?b:{};if(I==="table"){const K=Number(E.rows??E.rowCount),ae=Number(E.columns??E.cols??E.colCount);if(!Number.isInteger(K)||K<1||!Number.isInteger(ae)||ae<1)return!1;const ue=dl(ht.selection),Le=ue&&typeof ue.blockId=="string"?{kind:"inParagraph",target:So(ue.blockId),offset:ue.range?.start??0}:l2(ht.selection,"nodeId");try{return Mr(f.docRoute,m,{rows:K,columns:ae,at:Le})}catch{return!1}}if(I==="image"){const K=E.src??E.value;if(typeof K!="string"||K.trim()==="")return!1;const ae=dl(ht.selection),ue=Zi(ht.selection),Le=ue.storyType==="body"?null:ue;let Ue;ae&&typeof ae.blockId=="string"?Ue={kind:"inParagraph",target:So(ae.blockId,Le),offset:ae.range?.start??0}:(Ue=l2(ht.selection,"target"),Le&&Ue.kind==="after"&&(Ue={...Ue,target:{...Ue.target,story:Le}}));const je={src:K,at:Ue};Le&&(je.in=Ue.kind==="inParagraph"?F(Le)??Le:Le),typeof E.alt=="string"&&(je.alt=E.alt),typeof E.title=="string"&&(je.title=E.title),E.size&&typeof E.size=="object"&&(je.size=E.size);try{return Mr(f.docRoute,m,je)}catch{return!1}}const z={at:l2(ht.selection,"target")};typeof E.instruction=="string"&&(z.instruction=E.instruction),E.config&&typeof E.config=="object"&&(z.config=E.config);try{return Mr(f.docRoute,m,z)}catch{return!1}},jj=(f,m)=>{const b=f.table,I=_e();if(!I||b.requiresCell&&!I.cellNodeId)return!1;const E=ZV(b.action,I);if(!E)return!1;try{if(b.action==="insert-row-before"||b.action==="insert-row-after"){const z=R(),K=(typeof z?.getHandles=="function"?z.getHandles():null)?.editing?.tables;if(typeof K?.insertRow!="function")return!1;const ae=Pa(f.docRoute);return ae&&ae.success===!1?ae:ae?K.insertRow(E,ae):K.insertRow(E)}return Mr(f.docRoute,m,E)}catch{return!1}},Uj=f=>!f||f.disposition!=="routed"?!1:!!(f.inline||f.blockParagraph||f.list||f.link||f.create),Hj=f=>{const m=Jf(f);return!!(_A(f)||tc(m.hyperlinkTarget)||tc(m.textTarget))},$j=(f,m,b)=>ht.selection.status!=="ready"?!1:Cm(f)?.scope==="id"||!m||m.disposition!=="routed"?!0:m.inline?.kind==="clear"?$r(ht.selection).length>0||Eu(ht.selection)!=null:m.inline?Eu(ht.selection)!=null||$r(ht.selection).length>0:m.blockParagraph||m.list?$r(ht.selection).length>0:m.link?Hj(b)||i2(ht.selection).length>0||dl(ht.selection)!=null||Ta(m,y(),ht.selection):!0,Gj=(f,m)=>{const b=Cm(f),I=yu(f);return b?.scope!=="id"&&!Uj(I)?!1:!$j(f,I,m)},Wj=(f,m)=>Gj(f,m)?xs().then(()=>{}):null,wc=(f,m,b)=>{if(fi=null,Ln=Promise.resolve(!1),U)return!1;const I=oe.get(f);if(I)try{const je=I.execute(Mu(m,b));return Bn(je)}catch{return!1}const E=sA(f);if(E&&typeof se()?.lists?.apply=="function")return _l(E,m);const z=Cm(f);if(z)return Xu(z,m);if(f==="copy-format")return Bn(Kj());const K=yu(f);if(!K||K.disposition!=="routed")return!1;const ae=K.normalizePayload?K.normalizePayload(m):m;if(K.instanceRoute){if(!A()||!fe(K,ae))return!1;const je=t?.[K.instanceRoute];if(typeof je!="function")return!1;try{const Ve=K.fixedArg!==void 0?K.fixedArg:ae,Xe=je.call(t,Ve);return Bn(Xe)}catch{return!1}}if(K.inline?.kind==="clear")return K.mutates&&wr()==="viewing"?!1:Bn(Pj());const ue=K.docRoute;if(!ue||K.mutates&&wr()==="viewing")return!1;const Le=y(),Ue=Sr(Le,ue);if(!Ue)return!1;if(K.inline){const{lockModesById:je}=Ms(Le?.contentControls,ht.selection);if(_i(je))return!1;const Ve=Eu(ht.selection);if(!Ve)return ht.selection.empty===!1?Bn(!1):Bn(Lj(K,ae));const Xe=Ta(K,Le,ht.selection),$e=YV(K.inline,Ve,ae,Xe);if(!$e)return!1;let Qe=null;try{const Je=A(),at=wr(),ot=()=>A()!==Je||y()!==Le||wr()!==at?!1:m2(ue,Ue,$e),Nt=wa(ht.selection)??Ql(ht.selection),qt=K.inline.kind==="toggle"?Am(`${K.id}:${Nt}`,ot):null;Qe=qt?.release??null;const Qn=qt?qt.result:ot(),tr=vn(K,ht.selection,$e,Qn),Qr=Wt(K,ht.selection,$e,Qn),zr=Bn(Qr,fn=>{Lr(K,tr,fn),Qe?.(),Qe=null});return K.inline.kind==="toggle"&&(Zu=Ln),zr}catch{return Qe?.(),!1}}if(K.blockParagraph){const je=Dj(K,Ue,ae),Ve=K.blockParagraph.kind==="alignment"&&_o(je)?Gr(ht.selection,ae):null;return Bn(je,Xe=>{Wu(Ve,Xe)})}if(K.list){const je=Fj(K,Ue);return Bn(je)}if(K.link){const je=zj(ae);return Bn(je)}if(K.create){const je=Vj(K,Ue,ae);return Bn(je)}if(K.table){const je=jj(K,Ue);return Bn(je)}try{return Bn(K.mutates?Mr(ue,Ue,ae):Ue(ae))}catch{return!1}},Em=()=>{g+=1,h={mode:"idle",snapshot:null,sourceSelectionKey:null,lastClickAt:h.lastClickAt,pointerSelecting:!1,keyboardSelecting:!1};for(const f of p)f("idle");j()},Kj=async()=>{const f=["bold","italic","underline","strikethrough"].filter(Ue=>ht.toolbar.commands[Ue]?.active===!0),m=await Zu;await u;const b=_o(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 j(),!0}return Em(),!1}const z=E-h.lastClickAt<I,K=++g;h={...h,lastClickAt:E};const ae=await xs(),ue=`${Ql(ae)}:${ft()}`,Le=await qj(null,ae,ue&&ue===S?v:void 0,b);if(K!==g)return!0;h={...h,mode:z?"persistent":"armed",snapshot:Le,sourceSelectionKey:Ql(ae),lastClickAt:E};for(const Ue of p)Ue(h.mode);return j(),!0},qj=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 ae=E.story;let ue=null;for(const $e of z){const Qe=(await Ia(So($e.blockId,ae)))?.node??null;if(!Qe)continue;const Je=g2(Qe),at=Array.isArray(Je?.inlines)?Je.inlines:[],ot=Yj(at,$e.range);ue?ue=AA(ue,ot):ue=ot}const Le=ue?Yz(ue):{},Ue={bold:"bold",italic:"italic",underline:"underline",strikethrough:"strike"},je=new Set([...m?.activeMarks??(Array.isArray(f?.activeMarks)?f.activeMarks:[]),...I]);for(const[$e,Qe]of Object.entries(Ue))je.has($e)&&(Le[Qe]=!0);const Ve=b??await fc(m??Ts(f,"ready"));if(Ve.fontFamily&&(Le.fontFamily=Ve.fontFamily),Ve.color&&(Le.color=Ve.color),Ve.highlight&&(Le.highlight=Ve.highlight),Ve.fontSize){const $e=Number.parseFloat(Ve.fontSize);Number.isNaN($e)||(Le.fontSize=$e)}let Xe=null;if(z.length===1){const $e=z[0],Qe=(await Ia(So($e.blockId,ae)))?.node??null;Qe&&g2(Qe)&&(Xe=await Xj(Qe,$e.blockId,K,ae))}return{story:ae??null,inline:Le,paragraph:Xe}},g2=f=>f?f.kind==="paragraph"?f.paragraph??null:f.kind==="heading"?f.heading??null:null:null,Yj=(f,m)=>{const b=K=>{const ae=K.run;return typeof ae?.text=="string"?ae.text:""},I=K=>K.run?.props;if(m.start===m.end){let K=0;for(const ae of f){const ue=b(ae),Le=K,Ue=K+ue.length;if(K=Ue,m.start>=Le&&m.start<=Ue){const je=I(ae);return je?{...je}:{}}}return{}}let E=0;const z=[];for(const K of f){const ae=b(K),ue=E,Le=E+ae.length;if(E=Le,Le<=m.start||ue>=m.end)continue;const Ue=I(K);Ue&&z.push(Ue)}return z.length===0?{}:z.length===1?{...z[0]}:AA(z[0],...z.slice(1))},AA=(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},Xj=async(f,m,b,I)=>{const E=g2(f),z=E.props??{},K=E.styleRef??null,ae=z.alignment??null,ue=z.spacing??null,Le=z.indent??null,Ue=Le?{...Le.left!=null?{left:Le.left}:{},...Le.right!=null?{right:Le.right}:{},...Le.firstLine!=null?{firstLine:Le.firstLine}:{},...Le.hanging!=null?{hanging:Le.hanging}:{}}:null,je=z.markRunProps??null,Ve=z.numbering?.numId,Xe=typeof Ve=="string"?parseInt(Ve,10):typeof Ve=="number"?Ve:NaN,$e=z.numbering?.level,Qe=isNaN(Xe)?null:{numId:Xe,...$e!=null?{level:$e}:{}};let Je=null;if(Qe&&typeof b.lists?.getState=="function")try{const at=await b.lists.getState({target:So(m,I)});at&&typeof b.lists?.getStyle=="function"&&(Je=await b.lists.getStyle(at)??null)}catch{}return{styleId:K,alignment:ae,spacing:ue,indentation:Ue,markRunProps:je,numbering:Qe,listStyle:Je}},IA=async()=>{if(h.mode==="idle"||h.pointerSelecting||h.keyboardSelecting)return;const f=y()?.selection,m=async()=>{const K=typeof f?.current=="function"?await Promise.resolve(f.current({includeText:!0})):ts().value;return zi(K)},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=Ql(E),z!==h.sourceSelectionKey))break}if(E&&!E.empty&&z!==h.sourceSelectionKey){await EA(E);return}if(h.snapshot?.paragraph){const K=await m();if(!K||Ql(K)===h.sourceSelectionKey)return;await EA(K)}},EA=async f=>{const m=h.snapshot;if(!m){h.mode==="armed"&&Em();return}const b=y();if(!b)return;const I=Ts(f,"ready"),{lockModesById:E}=Ms(b.contentControls,I);if(_i(E)){j();return}const z=f.target,K=f.selectionTarget;if(f.empty!==!0&&Object.keys(m.inline).length>0){const ae=Sr(b,"format.apply");if(ae&&K)try{if(!_o(As(await Promise.resolve(m2("format.apply",ae,{target:K,inline:m.inline},f))))){j();return}}catch{j();return}}if(m.paragraph){const ae=Array.isArray(z?.segments)?z.segments:[],ue=z?.story;for(const Le of ae){const Ue=So(Le.blockId,ue),je=await Ia(Ue),Ve=je?.node??null,Xe=je?.address??null;if(!Ve)continue;const $e={kind:"block",nodeType:Xe?.nodeType??Ve.kind??"paragraph",nodeId:Le.blockId,...ue&&typeof ue=="object"?{story:ue}:{}},{styleId:Qe,alignment:Je,spacing:at,indentation:ot,markRunProps:Nt,numbering:qt,listStyle:Qn}=m.paragraph;if(Qe&&await b.styles?.paragraph?.setStyle?.({target:$e,styleId:Qe}),Je&&await b.format?.paragraph?.setAlignment?.({target:$e,alignment:Je}),at){const tr=at,Qr=tr.lineRule??"auto",zr=new Set(["auto","exact","atLeast"]).has(Qr)?Qr:"auto",fn={...tr.before!=null?{before:Math.round(tr.before*20)}:{},...tr.after!=null?{after:Math.round(tr.after*20)}:{},...tr.line!=null?{line:Math.round(zr==="auto"?tr.line*240:tr.line*20),lineRule:zr}:{}};await b.format?.paragraph?.setSpacing?.({target:$e,...fn})}if(ot){const tr={...ot.left!=null?{left:_s(ot.left)}:{},...ot.right!=null?{right:_s(ot.right)}:{},...ot.firstLine!=null?{firstLine:_s(ot.firstLine)}:{},...ot.hanging!=null?{hanging:_s(ot.hanging)}:{}};await b.format?.paragraph?.setIndentation?.({target:$e,...tr})}Nt&&await b.format?.paragraph?.setMarkRunProps?.({target:$e,markRunProps:Nt}),qt&&await b.format?.paragraph?.setNumbering?.({target:$e,...qt}),Qn&&((await Ia(Ue))?.address?.nodeType==="listItem"?await b.lists?.applyStyle?.({target:fA(Le.blockId,ue),style:Qn}):qt&&await b.format?.paragraph?.setNumbering?.({target:$e,...qt}))}}h.mode==="armed"&&Em(),j()},Tm=(f,m,b)=>{const I=Wj(f,m),E=I?I.then(()=>(wc(f,m,b),Ln)):(wc(f,m,b),Ln);return yu(f)?.inline?.kind==="toggle"&&(Zu=E),E},TA=f=>({id:f,getState:()=>ht.toolbar.commands[f]??hc(f,y(),ht.selection,yl(ht.selection)),observe:m=>gn(b=>b.toolbar.commands[f]??{enabled:!1,active:!1,supported:!1,source:"unsupported",reason:dt.commandUnsupported}).subscribe(m),execute:m=>wc(f,m),executeAsync:m=>Tm(f,m)}),Zj=f=>{oe.set(f.id,f),j();const m=()=>{oe.delete(f.id),j()};return Object.assign(m,{handle:TA(f.id),unregister:m})},xm=ln(f=>f.selection),Rm=qn(xm),xA=()=>{const f=R();if(typeof f?.getHandles!="function")return{reason:dt.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"?dt.notReady:dt.hostCapabilityUnavailable}}const b=m?.editing?.selectionTargets;return typeof b?.apply!="function"?{reason:dt.hostCapabilityUnavailable}:{helper:b}},Qj=f=>{const m=R();if(typeof m?.getHandles=="function")try{const b=m.getHandles()?.editing?.contentControls;typeof b?.activate=="function"&&b.activate({id:f})}catch{}},RA={get:Rm.get,getSnapshot:Rm.getSnapshot,subscribe:Rm.subscribe,observe:Rm.observe,current:()=>ts().value,capture:()=>{const f=xm.get();return f.empty||!f.target&&!f.selectionTarget?null:{...f,capturedAt:Date.now()}},restore:f=>{const m=E=>(j(),{...E,success:E.ok});if(!f||typeof f!="object")return m({ok:!1,reason:dt.targetUnresolved});if(!A())return m({ok:!1,reason:dt.notReady});const b=KV(f);if(!b)return m({ok:!1,reason:dt.targetUnresolved});const I=xA();if(!("helper"in I))return m({ok:!1,reason:I.reason});try{return m(iA(I.helper.apply(b)))}catch{return m({ok:!1,reason:dt.hostCapabilityUnavailable})}},apply:f=>{if(!A())return{ok:!1,reason:dt.notReady};const m=xA();if(!("helper"in m))return{ok:!1,reason:m.reason};try{const b=m.helper.apply(f);return j(),iA(b)}catch{return{ok:!1,reason:dt.hostCapabilityUnavailable}}},getAnchorRect:f=>{const m=R();if(typeof m?.getSelectionAnchorRect=="function"){const b=Ot(()=>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=xm.get(),b=m.selectionTarget??m.target;if(m.empty||!b)return[];const I=zm.getRect({target:b,relativeTo:f?.relativeTo});return I.found?I.rects:[]}},Jj={get ids(){return le()},has:f=>yu(f)!=null||oe.has(f),get:f=>TA(f),execute:wc,executeAsync:Tm,register:Zj,getContextMenuItems:f=>{const m=[];for(const b of oe.values()){const I=b.contextMenu;I&&Ot(I.when?()=>I.when(f):void 0,!0)&&m.push({id:b.id,label:I.label,group:I.group,order:I.order,invoke:()=>wc(b.id,void 0,f)})}return m.sort((b,I)=>(b.order??0)-(I.order??0)||b.label.localeCompare(I.label))}},v2=qn(ln(f=>f.toolbar)),eU={get:v2.get,getSnapshot:()=>ht.toolbar,subscribe:v2.subscribe,observe:v2.observe,execute:wc,executeAsync:Tm},Cc=async(f,m)=>{if(!A())return{success:!1,ok:!1,reason:dt.notReady};if(!f)return{success:!1,ok:!1,reason:dt.targetUnresolved};const b=R(),I=b?.scrollTargetIntoView;if(typeof I!="function")return{success:!1,ok:!1,reason:dt.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:n2(z.reason,dt.targetUnresolved)}:{success:!0,ok:!0}}catch{return{success:!1,ok:!1,reason:dt.hostCapabilityUnavailable}}},Mm=async(f,m,b,I)=>{const E=f==="trackChanges"?I?.story:void 0,z=at=>{if(!E||!at||typeof at!="object")return at;const ot=at,Nt=ot.address&&typeof ot.address=="object"?ot.address:null;return ot.story||Nt?.story?at:{...ot,story:E}},K=f==="trackChanges"?bV:Bf,ae=b.find(at=>Xi(at,m,E)),ue=ae&&typeof ae=="object"?ae:null,Le=f==="trackChanges"&&ue?.type==="move"&&(ue.subtype==="move-to"||ue.subtype==="move-from")?ue.subtype:null,Ue=Le&&typeof ue?.trackedChangeCanonicalId=="string"?ue.trackedChangeCanonicalId:m,je=at=>{if(!Le)return K(at);const ot=Bf(at);if(ot?.kind!=="move")return null;const Nt=Le==="move-to"?ot.destination:ot.source;return r2(Nt)?Nt:null},Ve=K(ae),Xe=f!=="trackChanges"||!Le&&r2(Bf(ae));if(Ve&&Xe)return z(Ve);const $e=y()?.[f],Qe=f==="comments"?{commentId:m}:{id:Ue,...E?{story:E}:{}},Je=$e?.get;if(typeof Je!="function")return z(Ve);try{return z(je(await Promise.resolve(Je.call($e,Qe)))??Ve)}catch{return z(Ve)}};function MA(f,m){if(Es())return nr("Comments are read-only.","DOCUMENT_READONLY");if(qo())return nr("Resolving comments is disabled.","DOCUMENT_READONLY");const b=y()?.comments,I=b?.patch;if(typeof I!="function")return nr("comments.patch is unavailable.");const E=nr("comments.patch failed.");return Ot(()=>Lo(I.call(b,{commentId:f,status:m}),E),E)}const eh=()=>Es()?nr("Comments are read-only.","DOCUMENT_READONLY"):null,LA=(f,m)=>{const b=m&&typeof m=="object"?m:null;let I=Array.from(f);b?.includeResolved===!1&&(I=I.filter(ue=>ue.status!=="resolved"));const E=Number(b?.offset),z=Number.isInteger(E)&&E>0?E:0,K=Number(b?.limit),ae=Number.isInteger(K)&&K>=0?z+K:void 0;return I.slice(z,ae)},ed=ln(f=>f.comments),Lm=qn(ed),tU={get:Lm.get,getSnapshot:Lm.getSnapshot,subscribe:Lm.subscribe,observe:Lm.observe,list:f=>{Kn();const m=ed.get();if(m.status!=="pending")return LA(m.items,f);const b=y()?.comments,I=Ot(b?.list?()=>b.list(f):void 0,null);return Tr(I)?[]:LA(Array.isArray(I?.items)?I.items:[],f)},getById:f=>{const m=ed.get().items.find(E=>er(E)===f)??null;if(m)return m;const b=y()?.comments,I=Ot(b?.get?()=>b.get({commentId:f}):void 0,null);return Tr(I)?null:I},createFromCapture:(f,m)=>{const b=eh();if(b)return b;const I=y()?.comments,E=I?.create;if(typeof E!="function")return nr("comments.create is unavailable.");const z=nr("comments.create failed.");return Ot(()=>{const K=f&&typeof f=="object"?f.target??f.selectionTarget:null;return K==null?nr("A range selection is required to comment.","NO_SELECTION"):Lo(E.call(I,{target:K,text:m.text}),z)},z)},createFromSelection:f=>{const m=eh();if(m)return m;const b=y()?.comments,I=b?.create;if(typeof I!="function")return nr("comments.create is unavailable.");const E=xm.get(),z=E.target??E.selectionTarget;if(E.empty||!z)return nr("A range selection is required to comment.","NO_SELECTION");const K=nr("comments.create failed.");return Ot(()=>Lo(I.call(b,{target:z,text:f.text}),K),K)},reply:(f,m)=>{const b=eh();if(b)return b;const I=y()?.comments,E=I?.reply??I?.create;if(typeof E!="function")return nr("comments.reply is unavailable.");const z=nr("comments.reply failed.");return Ot(()=>Lo(E===I?.reply?E.call(I,{parentCommentId:f,text:m.text}):E.call(I,{parentCommentId:f,text:m.text}),z),z)},edit:(f,m)=>{const b=eh();if(b)return b;const I=y()?.comments,E=I?.patch;if(typeof E!="function")return nr("comments.patch is unavailable.");const z=nr("comments.patch failed.");return Ot(()=>Lo(E.call(I,{commentId:f,text:m.text}),z),z)},resolve:f=>MA(f,"resolved"),reopen:f=>MA(f,"active"),delete:f=>{const m=eh();if(m)return m;const b=y()?.comments,I=b?.delete??b?.remove;if(typeof I!="function")return nr("comments.delete is unavailable.");const E=nr("comments.delete failed.");return Ot(()=>Lo(I.call(b,{commentId:f}),E),E)},setActive:f=>{if(f==null)return Me=null,j(),!0;if(!A())return!1;const m=ed.get();if(m.listStatus!=="ready")return!1;const b=TV(m.items,f);return!b||!m.items.some(I=>er(I)===b)?!1:(Me=b,j(),!0)},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:A()?dt.documentApiUnavailable:dt.notReady};const m=await Mm("comments",f,ed.get().items);return m?Cc(m):{success:!1,ok:!1,reason:dt.targetUnresolved}}},Da=ln(f=>f.trackChanges),y2=(f,m)=>{const b=Da.get().items.filter(je=>er(je)!==null);if(b.length===0)return null;const I=ht.trackChanges.activeId,E=Ge?.id===I?Ge.story:void 0,z=b.filter(je=>gm(je)==null),K=E||z.length===0?b:z;let ae=I?K.findIndex(je=>Xi(je,I,E)):-1;ae===-1&&I&&E&&(ae=K.findIndex(je=>Xi(je,I)));const ue=K[ae===-1?f>0?0:K.length-1:(ae+f+K.length)%K.length],Le=er(ue),Ue=gm(ue);return te(Ue?{id:Le,story:Ue}:{id:Le},m),j(),Le},PA=async f=>{const m=w(),b=m?.listTrackedChanges;if(typeof b=="function")try{await Promise.resolve(b.call(m,{mode:"visible-window",targetIds:[f],refreshReason:"ui-track-change-reveal-restamp",blocking:!0}))}catch{}};let DA=Promise.resolve();const nU=f=>{const m=Ct;return DA.catch(()=>{}).then(()=>rU(f,m))},rU=async(f,m)=>{if(Ct!==m)return{success:!1};const b=Ge,I=y2(f,{invalidateQueuedNavigation:!1});if(I==null)return{success:!1};const E=Ge,z=lt,K=()=>Ct===m&&Ge===E&&lt===z,ae=()=>{K()&&(te(b,{invalidateQueuedNavigation:!1}),j())};E&&Ke.add(E);try{const ue=await Mm("trackChanges",I,Da.get().items,E?.story?{story:E.story}:void 0);if(!K())return{success:!1};if(!ue)return ae(),{success:!1};Zo+=1;try{const Le=await Cc(ue,{behavior:"auto",shouldContinue:K});if(!K())return{success:!1};if(!Le.ok&&Le.reason!==dt.targetNotVisible)ae(),_(b);else{if(Le.ok&&await PA(I),!K())return{success:!1};_(E)}return{success:Le.ok}}finally{Zo=Math.max(0,Zo-1),Zo===0&&(K()?Zr&&Qo(di(Zr)):_(Ge))}}finally{E&&Ke.delete(E)}},OA=f=>{const m=nU(f);return DA=m.then(()=>{},()=>{}),m},Pm=qn(Da),oU={get:Pm.get,getSnapshot:Pm.getSnapshot,subscribe:Pm.subscribe,observe:Pm.observe,list:()=>(Nn(),Da.get().items),accept:f=>b2("accept",f),reject:f=>b2("reject",f),acceptAll:()=>th("accept",{kind:"all"},null),rejectAll:()=>th("reject",{kind:"all"},null),next:()=>y2(1),previous:()=>y2(-1),navigateNext:()=>OA(1),navigatePrevious:()=>OA(-1),getAt:f=>{if(!f||typeof f!="object"||typeof f.x!="number"||typeof f.y!="number")return null;const m=k2(f);if(m.length===0)return null;const b=Da.get().items;let I;for(const E of m){if(E.type!=="trackedChange")continue;let z;if(E.story){if(I===void 0&&(I=Rs()),!I)continue;z=I}else z=b;const K=z.find(ae=>Xi(ae,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 te(null),_(null),j(),!0;if(!A())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=Rs();if(!I)return!1;const E=_u(I,m.story).toPublicId(m.id)??m.id;if(!I.some(z=>Xi(z,E,m.story)))return!1;m.id=E}else{const I=Da.get().items,E=ya(I).toPublicId(m.id)??m.id,z=I.find(K=>er(K)===E);if(!z)return!1;m.id=E,m.story=gm(z)}return b!==m.id&&(m.paintedEntityId=b),te(m),_(m),j(),!0},scrollTo:async f=>{if(!y())return{success:!1,ok:!1,reason:A()?dt.documentApiUnavailable:dt.notReady};Ct+=1,Re+=1;const m=Re,b=Da.get().items,I=ya(b).toPublicId(f)??f,E=gm(b.find(ae=>er(ae)===I)),z=Ge,K={id:I,...E?{story:E}:{},...I!==f?{paintedEntityId:f}:{}};Ke.add(K);try{const ae=await Mm("trackChanges",I,b,E?{story:E}:void 0);if(Re!==m)return{success:!1,ok:!1};if(!ae)return{success:!1,ok:!1,reason:dt.targetUnresolved};te(K);const ue=Re,Le=Ge,Ue=lt,je=()=>Re===ue&&Ge===Le&&lt===Ue,Ve=()=>{je()&&(te(z,{invalidateQueuedNavigation:!1}),j())};j(),Zo+=1;try{const Xe=await Cc(ae,{behavior:"auto",shouldContinue:je});if(!je())return{success:!1,ok:!1};if(!Xe.ok&&Xe.reason!==dt.targetNotVisible)Ve(),_(z);else{if(Xe.ok&&await PA(I),!je())return{success:!1,ok:!1};_(K)}return Xe}finally{Zo=Math.max(0,Zo-1),Zo===0&&(je()?Zr&&Qo(di(Zr)):_(Ge))}}finally{Ke.delete(K)}}},b2=(f,m)=>{const{id:b,story:I}=typeof m=="string"?{id:m,story:void 0}:m,E={kind:"id",id:b,...I?{story:I}:{}};return th(f,E,b,I)},th=(f,m,b,I)=>{try{return Bn(w2(f,m,b,I))}catch{return!1}},w2=(f,m,b,I)=>{if(Es())return!1;const E=y()?.trackChanges,z=m.kind==="all"||m.scope==="all",K=m.kind==="range",ae=m.kind==="ids";if(Ea({kind:f,scope:z?"all":"id"},E))return!1;const ue=z?`${f}All`:f,Le=!K&&!ae&&!I&&E&&typeof E[ue]=="function"?E[ue]:null,Ue=E&&typeof E.decide=="function"?E.decide:null;return!Le&&!Ue?!1:Le?Le.call(E,b??{}):Ue.call(E,{decision:f,target:m})},C2=ln(f=>f.contentControls),nh=f=>C2.get().items.find(m=>m?.id===f)??null,Dm=qn(C2),iU=(f=>{if(f===void 0)return Dm.get();const m=vm(f);return m?nh(m):null}),sU={get:(f=>(f!==void 0&&st("api"),iU(f))),getSnapshot:Dm.getSnapshot,subscribe:Dm.subscribe,observe:Dm.observe,list:()=>(st("api"),C2.get().items),getById:f=>(st("api"),nh(f)),getRect:f=>{const m=vm(f);if(!m)return hl("unresolved");st("panel");const b=nh(m);if(!b)return hl("unresolved");const I=o2(b);return I?zm.getRect({target:I}):hl("unavailable")},scrollIntoView:async f=>{const m=vm(f);if(!m)return{success:!1};st("panel");const b=nh(m);if(!b)return{success:!1};const I=o2(b);return I?{success:(await Cc(I,{block:f.block,behavior:f.behavior})).ok}:{success:!1}},focus:async f=>{const m=vm(f);if(!m)return{success:!1,reason:"invalid-id"};if(!A())return{success:!1,reason:"not-ready"};st("panel");const b=nh(m);if(!b)return{success:!1,reason:"not-found"};const I=o2(b);if(!I)return{success:!1,reason:"not-reachable"};if(!(await Cc(I,{block:f.block,behavior:f.behavior})).ok)return{success:!1,reason:"not-reachable"};const E=kV(I);if(!E)return{success:!1,reason:"not-reachable"};const z=RA.apply(E);return!z.ok&&z.reason!==dt.hostCapabilityUnavailable?{success:!1,reason:"not-reachable"}:(Qj(m),{success:!0})}},Om=qn(ln(f=>f.fonts)),aU={get:Om.get,getSnapshot:Om.getSnapshot,subscribe:Om.subscribe,observe:Om.observe,getFamilyOptions:()=>ht.fonts.options,getSizeOptions:()=>ht.fonts.sizeOptions},Fm=qn(ln(f=>f.zoom)),lU={get:Fm.get,getSnapshot:Fm.getSnapshot,subscribe:Fm.subscribe,observe:Fm.observe,set:f=>{if(typeof t?.setZoom=="function")try{t.setZoom(f),j()}catch{}},setMode:f=>{if(typeof t?.setZoomMode=="function")try{t.setZoomMode(f),j()}catch{}}},Nm=qn(ln(f=>f.document)),cU={get:Nm.get,getSnapshot:Nm.getSnapshot,subscribe:Nm.subscribe,observe:Nm.observe,setMode:f=>{if(typeof t?.setDocumentMode=="function")try{t.setDocumentMode(f),j()}catch{}},export:f=>{if(typeof t?.export=="function")try{return Promise.resolve(t.export(f))}catch{return}},getText:()=>{const f=y(),m=Ot(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}}},FA=()=>{if(typeof HTMLElement>"u")return null;const f=A()?.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=FA();if(!I)return[];const E=b.elementFromPoint(f,m);if(!E||!I.contains(E))return[];const z=[E],K=ot=>{ot&&I.contains(ot)&&!z.includes(ot)&&z.push(ot)},ae=b.elementsFromPoint;if(typeof ae=="function"){let ot=[];try{ot=ae.call(b,f,m)??[]}catch{ot=[]}for(const Nt of ot)K(Nt)}const ue=[],Le=ot=>{ot&&I.contains(ot)&&!ue.includes(ot)&&!z.includes(ot)&&ue.push(ot)},Ue=ot=>{const Nt=ot.getBoundingClientRect;if(typeof Nt!="function")return!1;let qt;try{qt=Nt.call(ot)}catch{return!1}return qt!=null&&f>=qt.left&&f<=qt.right&&m>=qt.top&&m<=qt.bottom};for(const ot of z){const Nt=ot.querySelectorAll;if(typeof Nt!="function")continue;let qt;try{qt=Nt.call(ot,"[data-track-change-marker]")}catch{continue}for(let Qn=0;Qn<qt.length;Qn+=1)Ue(qt[Qn])&&Le(qt[Qn])}ue.reverse();const je=[...ue,...z],Ve=oA(je[0],I);for(let ot=1;ot<je.length;ot+=1)for(const Nt of oA(je[ot],I))Ve.push(Nt);if(Ve.length===0)return Ve;const Xe=Da.get().items,$e=ya(Xe);let Qe;const Je=new Set,at=[];for(const ot of Ve){if(ot.type!=="trackedChange"){const tr=`${ot.type}:${ot.id}`;if(Je.has(tr))continue;Je.add(tr),at.push(ot);continue}const Nt=CV(ot.storyKey)??wV(ot.story);let qt;if(Nt){if(Qe===void 0&&(Qe=Rs()),!Qe||(qt=_u(Qe,Nt).toPublicId(ot.id),!qt||!Qe.some(tr=>Xi(tr,qt,Nt))))continue}else if(qt=$e.toPublicId(ot.id),!qt)continue;const Qn=`trackedChange:${qt}`;Je.has(Qn)||(Je.add(Qn),at.push(Nt?{type:"trackedChange",id:qt,story:Nt}:{type:"trackedChange",id:qt}))}return at};function k2(f,m){return typeof f=="object"?uU(f?.x,f?.y):null}const td=new Set;let S2=!1;const NA=f=>{const m=R();if(typeof m?.observeGeometry!="function")return;let b=!1;const I=Ot(()=>{const E=m.observeGeometry(()=>f.schedule());return b=!0,E},null);f.detach=typeof I=="function"?I:null,f.boundHost=b?m:null},Bm=f=>{if(f.detach){try{f.detach()}catch{}f.detach=null}f.boundHost=null},BA=()=>{if(S2=!1,!(U||R()))for(const f of td)Bm(f)},dU=()=>{if(!S2){if(S2=!0,typeof queueMicrotask=="function"){queueMicrotask(BA);return}Promise.resolve().then(BA)}},fU=()=>{const f=R();if(!f){dU();return}for(const m of td)m.boundHost&&m.boundHost===f||(Bm(m),NA(m),m.schedule())};Se.push(fU);const zm={getRect:f=>{const m=R(),b=m?.getTargetRects;if(typeof b=="function"){const I=Ot(()=>b.call(m,{target:f.target}),null);return I&&typeof I=="object"?I.success===!0&&Array.isArray(I.rects)?GV($V(I.rects.filter(E=>E!=null&&typeof E=="object")),f.relativeTo):hl(typeof I.reason=="string"?I.reason:"unresolved"):hl("unresolved")}return hl("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=gn(ae=>({ready:ae.ready,selection:ae.selection,zoom:ae.zoom}));m.push(z.subscribe(()=>E()));const K={schedule:E,detach:null,boundHost:null};return NA(K),td.add(K),()=>{td.delete(K),Bm(K),b&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(b);for(const ae of m.splice(0))try{ae()}catch{}}},getHost:()=>FA(),entityAt:k2,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?k2({x:b,y:I}):[],selection:ht.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"?ed.get().items:Da.get().items,z=m.entityType==="trackedChange"&&m.story?{story:m.story}:void 0;b=await Mm(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 Cc(b,{block:f.block??"center",behavior:f.behavior??"smooth"})).ok}:{success:!1}}},zA=f=>{const m=(f&&typeof f=="object"?f:null)?.target;return m&&typeof m=="object"?m:null},VA=f=>`metadata:resolve:${f}`,hU=f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;const{value:b}=Ar(VA(f),ft(),()=>m.resolve({id:f}),zA);return b},pU=async f=>{const m=y()?.metadata;if(!m||typeof m.resolve!="function")return null;try{const b=ft(),I=await Promise.resolve(m.resolve({id:f}));if(b!==ft())return null;const E=zA(I);return H.set(VA(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 hl("unavailable");const b=hU(f.id);return b?zm.getRect({target:b}):hl("unresolved")},scrollIntoView:async f=>{const m=await pU(f.id);return m?{success:(await Cc(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=_e();if(!f)return{...gU};const m=me()?.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:()=>_e()!=null},Vm={query:"",total:0,activeIndex:-1,open:!1,available:!1,caseSensitive:!1,includeDeletedText:!1,regex:!1,canReplace:!1,reason:dt.searchUnavailable};let Hn={...Vm};const jm=new Set,Oa=()=>{const f=R()?.search;return f&&typeof f=="object"?f:null},zs=()=>{const f=se()?.search;return f&&typeof f=="object"?f:null},rh=()=>{const f=Oa();if(f&&typeof f.setSession=="function")return!0;const m=zs();return!!m&&typeof m.query=="function"&&typeof m.getState=="function"},os=()=>{for(const f of[...jm])try{f(Hn)}catch{}},hi=f=>(Hn={...Hn,...f},os(),Hn);let ao=0,kc=null;const jA=()=>{const f=kc;kc=null,f&&Ot(()=>(f(),null),null)},yU=()=>{ao+=1,jA();const f=rh();Hn={...Vm,available:f,reason:f?void 0:dt.searchUnavailable},os()};Pe.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"},_2=(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}:{}}},Po=()=>{const f=he("find.replace"),m=he("find.replaceAll");return f?.enabled===!0||m?.enabled===!0},Do=(f,m=!1)=>{const b=_2(f,m);if(!b){hi({total:0,activeIndex:-1,canReplace:!1,reason:void 0});return}hi({...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?dt.searchInvalidPattern:void 0})},Fa=()=>{const f=Oa();if(f&&typeof f.getState!="function")return Hn={...Hn,available:rh(),reason:rh()?void 0:dt.searchUnavailable},Hn;if(!f){const b=zs();if(b&&typeof b.getState=="function"){const I=_2(Ot(()=>b.getState(),null),Po());if(I)return Hn={...Hn,...I.query!==void 0?{query:I.query}:{},total:I.total,activeIndex:I.activeIndex,canReplace:I.canReplace,available:!0,reason:I.invalidPattern?dt.searchInvalidPattern:void 0,open:Hn.open||!!I.query},Hn}return Hn={...Vm,query:Hn.query,caseSensitive:Hn.caseSensitive,includeDeletedText:Hn.includeDeletedText},Hn}const m=_2(Ot(()=>f.getState(),null));return m&&(Hn={...Hn,...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?dt.searchInvalidPattern:void 0,open:Hn.open||!!m.query}),Hn},nd=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:dt.documentReadonly};const b=m?.rejection;return m?.status==="rejected"&&b&&typeof b=="object"&&b.code==="read-only-document"?{ok:!1,reason:dt.documentReadonly}:{ok:!1,reason:dt.operationUnavailable}},Um=qn({get:()=>Fa(),subscribe:f=>(jm.add(f),()=>jm.delete(f))}),wU={get:Um.get,getSnapshot:Um.getSnapshot,subscribe:Um.subscribe,observe:Um.observe,open:()=>rh()?(hi({available:!0,open:!0,reason:void 0}),{ok:!0}):(hi({available:!1,open:!1,reason:dt.searchUnavailable}),{ok:!1,reason:dt.searchUnavailable}),close:()=>{if(ao+=1,kc)jA();else{const f=Oa();if(f&&typeof f.clear=="function")Ot(()=>f.clear(),null);else{const m=zs();m&&typeof m.query=="function"&&Ot(()=>m.query({query:""}),null)}}Hn={...Vm,available:rh(),reason:void 0},Hn.available||(Hn.reason=dt.searchUnavailable),os()},search:(f,m)=>{const b=Oa(),I=!!m?.caseSensitive,E=m?.includeDeletedText===!0,z=m?.regex===!0,K=++ao;if(!b||typeof b.setSession!="function"){const ue=zs();if(ue&&typeof ue.query=="function"&&typeof ue.getState=="function"){hi({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),kc=()=>{ue.query({query:""})};const Le=Ot(()=>ue.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);return Tr(Le)?Promise.resolve(Le).then(Ue=>{K===ao&&Do(Ue,Po())},()=>{K===ao&&hi({available:!1,reason:dt.searchUnavailable})}):Do(Le,Po()),Do(Ot(()=>ue.getState(),null),Po()),Hn}return hi({query:f,total:0,activeIndex:-1,available:!1,caseSensitive:I,includeDeletedText:E,regex:z,reason:dt.searchUnavailable})}hi({query:f,caseSensitive:I,includeDeletedText:E,regex:z,available:!0,open:!0,reason:void 0}),kc=()=>{typeof b.clear=="function"&&b.clear()};const ae=Ot(()=>b.setSession(f,{caseSensitive:I,includeDeletedText:E,...z?{regex:!0}:{},highlight:!0}),null);if(Do(ae),f.length>0&&Hn.total===0&&Hn.reason!==dt.searchInvalidPattern){const ue=zs();if(ue&&typeof ue.query=="function"&&typeof ue.getState=="function"){const Le=kc;kc=()=>{Le?.(),ue.query({query:""})};const Ue=Ot(()=>ue.query({query:f,caseSensitive:I,includeDeletedText:E,regex:z}),null);Tr(Ue)?Promise.resolve(Ue).then(je=>{K===ao&&Do(je,Po())},()=>{K===ao&&hi({available:!1,reason:dt.searchUnavailable})}):Do(Ue,Po()),Do(Ot(()=>ue.getState(),null),Po())}}return Hn},next:()=>{const f=Oa();if(!f||typeof f.next!="function"){const m=zs();if(!m||typeof m.next!="function"||typeof m.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(Hn.total===0)return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.next(),null);if(Tr(b)){const I=ao;Promise.resolve(b).then(E=>{I===ao&&Do(E,Po())}).catch(()=>{I===ao&&hi({available:!1,reason:dt.searchUnavailable})})}else Do(b,Po());return Do(Ot(()=>m.getState(),null),Po()),{ok:!0}}return Hn.total===0?{ok:!1,reason:dt.operationUnavailable}:(Do(Ot(()=>f.next(),null)),{ok:!0})},previous:()=>{const f=Oa();if(!f||typeof f.previous!="function"){const m=zs();if(!m||typeof m.previous!="function"||typeof m.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(Hn.total===0)return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.previous(),null);if(Tr(b)){const I=ao;Promise.resolve(b).then(E=>{I===ao&&Do(E,Po())}).catch(()=>{I===ao&&hi({available:!1,reason:dt.searchUnavailable})})}else Do(b,Po());return Do(Ot(()=>m.getState(),null),Po()),{ok:!0}}return Hn.total===0?{ok:!1,reason:dt.operationUnavailable}:(Do(Ot(()=>f.previous(),null)),{ok:!0})},clear:()=>{ao+=1;const f=Oa();if(f&&typeof f.clear=="function"&&Ot(()=>f.clear(),null),!f||typeof f.clear!="function"){const m=zs();m&&typeof m.query=="function"&&Ot(()=>m.query({query:""}),null)}hi({query:"",total:0,activeIndex:-1,canReplace:!1})},replace:f=>{const m=Oa();if(!m){const I=zs();if(!I||typeof I.replace!="function"||typeof I.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(!Po())return{ok:!1,reason:dt.operationUnavailable};const E=Ot(()=>I.replace({replacement:typeof f=="string"?f:""}),null);if(Tr(E)){const z=ao;Fa(),os();const K=()=>z===ao;return Promise.resolve(E).then(ae=>(K()&&(Do(ae,Po()),Fa(),os()),nd(ae)),()=>(K()&&hi({available:!1,reason:dt.searchUnavailable}),{ok:!1,reason:dt.searchUnavailable}))}return Fa(),os(),nd(E)}if(typeof m.replaceCurrent!="function")return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.replaceCurrent(typeof f=="string"?f:""),null);return Fa(),os(),nd(b)},replaceAll:f=>{const m=Oa();if(!m){const I=zs();if(!I||typeof I.replaceAll!="function"||typeof I.getState!="function")return{ok:!1,reason:dt.searchUnavailable};if(!Po())return{ok:!1,reason:dt.operationUnavailable};const E=Ot(()=>I.replaceAll({replacement:typeof f=="string"?f:""}),null);if(Tr(E)){const z=ao;Fa(),os();const K=()=>z===ao;return Promise.resolve(E).then(ae=>(K()&&(Do(ae,Po()),Fa(),os()),nd(ae)),()=>(K()&&hi({available:!1,reason:dt.searchUnavailable}),{ok:!1,reason:dt.searchUnavailable}))}return Fa(),os(),nd(E)}if(typeof m.replaceAll!="function")return{ok:!1,reason:dt.operationUnavailable};const b=Ot(()=>m.replaceAll(typeof f=="string"?f:""),null);return Fa(),os(),nd(b)}},UA=ln(f=>f.styles),Hm=qn(UA),CU={get:Hm.get,getSnapshot:Hm.getSnapshot,subscribe:Hm.subscribe,observe:Hm.observe,getCatalog:f=>Ae(f).value,getQuickGallery:()=>UA.get().quickGallery,getActiveParagraphStyle:()=>We(ht.selection,Ie().cache).style},HA={select:gn,get state(){return ht},selection:RA,commands:Jj,toolbar:eU,comments:tU,trackChanges:oU,contentControls:sU,fonts:aU,zoom:lU,document:cU,viewport:zm,metadata:mU,tables:vU,search:wU,styles:CU,formatPainter:{setPointerSelecting(f){U||(h={...h,pointerSelecting:f})},notifyPointerUp(){U||(h={...h,pointerSelecting:!1},IA())},setKeyboardSelecting(f){U||(h={...h,keyboardSelecting:f})},notifyKeyUp(){U||(h={...h,keyboardSelecting:!1},IA())},cancel(){U||Em()},onModeChange(f){return U?()=>{}:(p.add(f),()=>p.delete(f))}},createScope:()=>{const f=[];return{select:(m,b)=>{const I=gn(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(!U){U=!0,cV(zt,Lt),lr.reset(),Nr(),Be&&(clearTimeout(Be),Be=null),ge&&(clearTimeout(ge),ge=null,be=0),W?.timer&&(clearTimeout(W.timer),W.timer=null),W=null,it&&(clearTimeout(it),it=null),oo&&(clearTimeout(oo),oo=null),Uo&&Uo(),Uo=null,Si=null,ai.clear(),J.clear();for(const f of Zn.splice(0))f();At&&At(),At=null,et=null,kt&&kt(),kt=null,Gt=null,In&&In(),In=null,cr=null,Wr&&Wr(),Wr=null,Zr=null,un&&un(),un=null,ct=null,Yo&&Yo(),Yo=null,yo=null;for(const f of td)Bm(f);td.clear(),D.clear(),jm.clear(),g+=1,p.clear(),ao+=1,oe.clear()}}};return $=HA,HA}var JV=[{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 ej(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 tj(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"?ej(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 nj(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 rj(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:JV;for(const s of i)o(s);return n}var oj=[{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 ij(e,t){return e.activeMark?t.activeMarks.includes(e.activeMark):!1}Dt();var sj=['[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(", "),aj=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 lj(e,t){const n=new c6.default;return e.forEach((r,o)=>{n.file(t[o],r)}),n.generateAsync({type:"blob",compression:"DEFLATE"})}function f2(e){return!!(e&&(e.synced===!0||e.isSynced===!0))}function bA(e){try{e.synced=!0}catch{}try{e.isSynced=!0}catch{}}function cj(e,t){if(!e)return()=>{};if(f2(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=()=>{bA(e),s()},l=c=>{c!==!1&&(c===!0||f2(e))&&(bA(e),s())};return n("synced",a),n("sync",l),f2(e)&&s(),i}function uj(e,t){const n=e.composedPath();if(!n.includes(t))return null;const r=n.find(a=>a instanceof HTMLElement&&a.matches(sj));if(!r)return null;const o=n.some(a=>a instanceof HTMLElement&&a.classList.contains(rp.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 dj(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function fj(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 si(e){return!!(e&&typeof e=="object"&&e.editorVersion===2)}function hj(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 wA(e){return typeof e=="string"&&e.length>0?e:null}function h2(e){return e?si(e)?wA(e.documentId??e.options?.documentId??null):wA(typeof e.getDocumentId=="function"?e.getDocumentId():e.options?.documentId):null}function pj(e){if(!e||si(e))return null;const t=e;return t.documentRenderer??t.presentationEditor??null}function Ji(e){if(!e)return null;if(si(e))return e.fonts??null;const t=pj(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 km=class extends Gm.default{static{this.allowedTypes=[Hr,Vl,Jh]}#t;#n;#e;#r;#i;#s;#d;#h;#f;#c;#p;get uiConfig(){return this.#p}#o;get interactionConfig(){return this.#o}#l;get surfacesConfig(){return this.#l}#g;#u;#y;#w;constructor(e){if(super(),this.#t=!1,this.#n=!1,this.#e=null,this.#r=null,this.#i=null,this.#s=null,this.#d=null,this.#h=null,this.#f=n=>{this.#k(n)},this.#c=null,this.#p=P4({}),this.#o=D4({}),this.#l=F4({}),this.version="0.0.0",this.users=[],this.whiteboard=null,this.colors=[],this.readyEditors=0,this.pendingCollaborationSaves=0,this.#u=new iN,this.#y=null,this.#w=!1,this.config={selector:"#superdoc",documentMode:"editing",allowSelectionInViewMode:!1,role:"editor",document:{},documents:[],editorExtensions:[],colors:[],users:[],user:{...W0},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},this.#Z=new WeakSet,this.#Q=null,this.#j=null,this.#M=null,!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 KF({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=uj(e,t),r=this.activeEditor?.doc?.contentControls?.list;if(!(!n||typeof r!="function"))try{const o=await r();if(this.#t)return;const i=fj(dj(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),eN(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=tN(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=xk(this.config.modules.comments),this.#p=P4(this.config),this.#o=D4(this.config),this.#l=F4(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=v6(this.config.colors),this.userColorMap=new Map,this.colorIndex=0,this.version="2.4.0-next.21",this.#C("🦋 [superdoc] Using SuperDoc version:",this.version),this.superdocId=e.superdocId||is(),this.colors=this.config.colors??[],this.#D(),await S8(),this.#t)return;if(await this.#b(this.config.modules),this.#t){this.#de();return}this.config.cspNonce&&this.#P(),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.#L(),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)}#L(){const e=this.config.modules?.whiteboard,t=e!==!1&&(e?.enabled??!1);this.whiteboard=new bD({Renderer:$F,superdoc:this,enabled:t}),this.emit("whiteboard:init",{whiteboard:this.whiteboard})}get requiredNumberOfEditors(){return this.#m("requiredNumberOfEditors").documents.filter(e=>e.type===Hr).length}get ui(){return this.#c||(this.#c=QV({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}#P(){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}}#D(){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=Zd(this.config.document);this.config.documents=[{id:is(),...s}]}else if(n)this.config.documents=[{id:is(),type:Hr,url:this.config.document,name:"document.docx"}];else if(r){const s=Zd(this.config.document);this.config.documents=[{id:is(),...s}]}else if(o){const s=Zd(this.config.document);this.config.documents=[{id:is(),...s}]}Array.isArray(this.config.documents)&&this.config.documents.length>0&&(this.config.documents=this.config.documents.map(s=>{const a=Zd(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||is()}}))}#T(){const{app:e,pinia:t,superdocStore:n,commentsStore:r,highContrastModeStore:o}=aD({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&&l8(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.#$(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:is(),type:Hr,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}#ee(e,t){this.isCollaborative=!0,this._commentsCollabInitialized=!1,this.ydoc=eo(e),this.provider=eo(t),this.#_();const n=this.config;this._cleanupAwareness=r8(t,this,n.user),n.documents.forEach(r=>{r.ydoc=e,r.provider=t,r.role=this.config.role})}#H(){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}}#$(e){this.#A(),si(e)&&(this.#O(e),this.#x(e))}#O(e){const t=e.presence;if(!t||typeof t.subscribe!="function")return;const n=mD(()=>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.#F(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)}}#F(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:aj,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.#N();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.#B(o),a}}finally{this.#e=null,this.#n=!1}}#N(){return{isLocked:this.isLocked,lockedBy:this.lockedBy?{...this.lockedBy}:null}}#W(){const e=this.config.documents.find(r=>r.type===Hr),t=this.superdocStore?.documents.find(r=>r.id===e.id)??null,n=t?yn(t):null;return{isCollaborative:this.isCollaborative,configV2Collaboration:e.v2Collaboration??null,configData:e.data,storeDoc:t,storeV2Collaboration:this.#Y(n),storeData:t?.data}}#B(e){this.#s=null;const t=this.config.documents.find(n=>n.type===Hr);t.v2Collaboration=e.configV2Collaboration,t.data=e.configData,this.isCollaborative=e.isCollaborative,e.storeDoc&&(e.storeDoc.data=e.storeData,this.#z(e.storeDoc,e.storeV2Collaboration),this.#ne(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}#te(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=yn(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}#z(e,t){const n=yn(e).v2Collaboration;if(n&&typeof n=="object"&&"value"in n){n.value=t;return}e.v2Collaboration=t}#ne(e){const t=yn(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}#re(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===Hr),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.#re({...e,roomMode:"create"});return n.data=t,n.v2Collaboration=o,r.data=t,this.#z(r,o),this.isCollaborative=!0,this.readyEditors=0,this.#ne(r),{configDoc:n,storeDoc:r}}#he(e,t){const n=this.#re({...t,roomMode:"join"});e.configDoc.v2Collaboration=n,this.#z(e.storeDoc,n)}async#pe(){const e=this.activeEditor;if(si(e)&&typeof e.save=="function"){const r=await e.save();return this.#X(r)}const t=this.config.documents.find(r=>r.type===Hr),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:Hr})}if(e instanceof ArrayBuffer)return new Blob([e],{type:Hr});throw new Error("SuperDoc: active v2 editor returned an unsupported DOCX save payload")}#oe(e,t){const n=h2(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.#z(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.#H(),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 c=l?.editor;si(c)&&h2(c)===e&&(!c.presence&&!c.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=cj(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===Hr);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(!si(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=US({v2Collaboration:e.v2Collaboration??this.#ve(r.v2Collaboration)??i?.v2Collaboration??i?.v2??null,legacyCollaboration:s,documentType:Hr,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===Hr),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=$c({actor:e});t&&this.users.some(n=>$c({actor:n})===t)||this.users.push(e)}removeSharedUser(e){this.#R("removeSharedUser");const t=typeof e=="string"?Wv(e):"",n=typeof e=="string"?`email:${t}`:$c({actor:e});this.users=this.users.filter(r=>{const o=$c({actor:r});return n?o!==n:t?Wv(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:_4(e)})}broadcastEditorCreate(e){this.readyEditors++,this.broadcastReady(),this.#be(e),this.emit("editorCreate",{editor:_4(e)})}broadcastSourceComplete(){this.emit("source:complete")}broadcastSourceSignalsComplete(){this.emit("source:signals-complete")}#Z;#be(e){if(!e||typeof e.on!="function"||this.#Z.has(e))return;this.#Z.add(e),e.on("fonts-changed",n=>{this.#ie(e)&&this.#V(n)});const t=(e.documentRenderer??e.presentationEditor)?.getLastFontsChangedPayload?.();t&&this.#ie(e)&&this.#V(t)}#ie(e){return!this.activeEditor||e===this.activeEditor}#Q;#V(e){this.#Q=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)}#j;get fonts(){return this.#j||(this.#j={getReport:()=>Ji(this.activeEditor)?.getReport()??[],getMissingFonts:()=>Ji(this.activeEditor)?.getMissingFonts()??[],getDocumentFontOptions:()=>Ji(this.activeEditor)?.getDocumentFontOptions()??[],getFontFamilyOptions:()=>Ji(this.activeEditor)?.getFontFamilyOptions()??[],getDocumentFonts:()=>Ji(this.activeEditor)?.getDocumentFonts()??[],onReport:e=>{const t=this.activeEditor,n=t?Ji(t)?.getLastFontsChangedPayload?.()??null:this.#Q??null;return n&&e(n),this.on("fonts-changed",e),()=>this.off("fonts-changed",e)},map:e=>{const t=Ji(this.activeEditor);if(!t)throw new Error("superdoc.fonts.map requires an active editor");t.map(e)},unmap:e=>{const t=Ji(this.activeEditor);if(!t)throw new Error("superdoc.fonts.unmap requires an active editor");t.unmap(e)},add:e=>{const t=Ji(this.activeEditor);if(!t)throw new Error("superdoc.fonts.add requires an active editor");t.add(e)},preload:e=>{const t=Ji(this.activeEditor);if(!t)throw new Error("superdoc.fonts.preload requires an active editor");return t.preload(e)}}),this.#j}#U(){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")}#M;#se(){if(this.#M){try{this.#M()}catch{}this.#M=null}}#Ce(e){this.#se();const t=Ji(e);if(!t?.onChanged)return;const n=t.getLastFontsChangedPayload?.();n&&this.#V(n),this.#M=t.onChanged(r=>this.#V(r))}#ke(e,t){this.#w=!0;try{if(e===null){this.#U();return}this.#u.get(e)?.kind==="v2"&&si(t)?this.#ae(t):this.#U()}finally{this.#w=!1}}#ae(e){if(si(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.#U()}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:"supported",reason:"v2 renders the built-in right-click and slash context menu, forwards ui.contextMenu custom items, and honors ui.contextMenu: false for application-owned replacements"},{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 ha(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=Kz({...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 HR(this.config.modules?.comments,this),this.config.onCommentsListChange&&this.config.onCommentsListChange({isRendered:!0}),this.emit("comments-list-change",{isRendered:!0}))}removeCommentsList(){this.commentsList&&(this.commentsList.close(),this.commentsList=null,this.config.onCommentsListChange&&this.config.onCommentsListChange({isRendered:!1}),this.emit("comments-list-change",{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}))}#J(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.#J(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.#J(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.#J(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=Sk(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(si(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.#F(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=f_(n||this.config.title),c=await this.exportEditorsToDOCX({commentsType:t,isFinalDoc:i,fieldsHighlightColor:a}),u=[...r],d=[...o];if(e.includes("docx")&&c.forEach(g=>{u.push(g),d.push(`${l}.docx`)}),u.length===1)return s?d_(u[0],l,e[0]):u[0];const h=await lj(u,d);return s?d_(h,l,"zip"):h}async replaceFile(e){const t=this.activeEditor;if(si(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.#oe(t,e),this.emit("document-replaced",{editor:t,host:t?.host})),r}const n=t&&!si(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.#oe(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=c=>{"editor"in c&&c.error&&typeof c.error=="object"&&a.add(c.error)};this.on("exception",l);try{const c=this.#m("exportEditorsToDOCX").documents.map(async u=>{if(!u||u.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document")return null;const d=typeof u.getEditor=="function"?u.getEditor():null,h=()=>!u.data||u.data.type&&u.data.type!=="application/vnd.openxmlformats-officedocument.wordprocessingml.document"?null:u.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:u}),g&&(e==="clean"||hj(p)))throw p}return h()});return(await Promise.all(c)).filter(u=>u!=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=h2(r);for(const s of this.#u.getAllByDocumentId(t))this.#u.unregister(s.id);o===t&&r!==null&&this.#U();const i=n.removeDocument(t);return i?(this.#Ie(i,n.documents),await Tt(),!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?si(this.activeEditor)?this.activeEditor.focus?.(e):this.activeEditor.focus?.():this.#m("focus").documents.find(n=>{const r=n.getEditor?.();return r?(si(r)?r.focus?.(e):r.focus?.(),!0):!1})}setHighContrastMode(e){this.activeEditor&&(this.activeEditor.setHighContrastMode?.(e),this.highContrastModeStore?.setHighContrastMode(e))}};Dt();var CA="__SUPERDOC_V2_BROWSER_RUNTIME__";function mj(e=globalThis){const t=e[CA];return t&&typeof t=="object"?t:null}function gj(e={},t=globalThis){const n=mj(t)??{},r={...n,...e,vue:e.vue??n.vue??s6};return t[CA]=r,r}gj();var vj={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"},yj=0;function kA(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-${++yj}`}`,l=[];if(i)for(const[c,u]of Object.entries(i)){if(u==null)continue;const d=vj[c];d&&l.push(` ${d}: ${u};`)}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[c,u]of Object.entries(s))u!=null&&l.push(` ${c}: ${u};`);return{className:a,css:l.length>0?`.${a} {
106
106
  ${l.join(`
107
107
  `)}
108
- }`:""}}function bj(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 wj(e){const{className:t,css:n}=kA(e);return bj(t,n),t}function Cj(e){return kA(e)}function kj(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 Sj=id({BlankDOCX:()=>nk,DOCX:()=>Hr,HTML:()=>Jh,PDF:()=>Vl,SuperDoc:()=>km,buildTheme:()=>Cj,compareVersions:()=>p6,createTheme:()=>wj,defineSuperDocExtension:()=>kj,getFileObject:()=>Kv}),_j="SUPERDOC_ENGINE_CDN_BASE_URL",SA=Symbol.for("superdoc.docx-engine.cdn-load-state"),Sm="superdocDocxEngineStatus";function Aj(e,t,n=null){const r=e?.[_j],o=typeof r=="string"&&r.trim()?r:n;if(typeof o=="string"&&o.trim())return Ij(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 Ij(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 Ej({engineVersion:e,buildBaseUrl:t}){C8(()=>{const n=Aj(globalThis,e,t),r=globalThis[SA],o=r instanceof Map?r:new Map;if(globalThis[SA]=o,!o.has(n)){const i=Promise.all([import(`${n}/dist-cdn/docx-engine.es.js`),Tj(`${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 Tj(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[Sm]==="loaded")return Promise.resolve();const r=n?.dataset[Sm]==="loading";return n&&!r&&n.remove(),new Promise((o,i)=>{const s=r?n:document.createElement("link");let a=!1,l;const c=(g,p)=>{a||(a=!0,l?.disconnect(),s.dataset[Sm]=g,p())},u=()=>c("loaded",o),d=()=>c("error",()=>i(new Error(`SuperDoc: failed to load DOCX Engine styles from ${t}`))),h=()=>{s.isConnected||c("error",()=>i(new Error(`SuperDoc: DOCX Engine stylesheet was removed while loading from ${t}`)))};s.addEventListener("load",u,{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[Sm]="loading",document.head.appendChild(s))})}Ej({engineVersion:"0.3.0-next.17",buildBaseUrl:null});for(const[e,t]of Object.entries(Sj))e==="SuperDoc"||e==="default"||Object.prototype.hasOwnProperty.call(km,e)||(km[e]=t);var xj=km;return xj})();
108
+ }`:""}}function bj(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 wj(e){const{className:t,css:n}=kA(e);return bj(t,n),t}function Cj(e){return kA(e)}function kj(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 Sj=id({BlankDOCX:()=>nk,DOCX:()=>Hr,HTML:()=>Jh,PDF:()=>Vl,SuperDoc:()=>km,buildTheme:()=>Cj,compareVersions:()=>p6,createTheme:()=>wj,defineSuperDocExtension:()=>kj,getFileObject:()=>Kv}),_j="SUPERDOC_ENGINE_CDN_BASE_URL",SA=Symbol.for("superdoc.docx-engine.cdn-load-state"),Sm="superdocDocxEngineStatus";function Aj(e,t,n=null){const r=e?.[_j],o=typeof r=="string"&&r.trim()?r:n;if(typeof o=="string"&&o.trim())return Ij(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 Ij(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 Ej({engineVersion:e,buildBaseUrl:t}){C8(()=>{const n=Aj(globalThis,e,t),r=globalThis[SA],o=r instanceof Map?r:new Map;if(globalThis[SA]=o,!o.has(n)){const i=Promise.all([import(`${n}/dist-cdn/docx-engine.es.js`),Tj(`${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 Tj(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[Sm]==="loaded")return Promise.resolve();const r=n?.dataset[Sm]==="loading";return n&&!r&&n.remove(),new Promise((o,i)=>{const s=r?n:document.createElement("link");let a=!1,l;const c=(g,p)=>{a||(a=!0,l?.disconnect(),s.dataset[Sm]=g,p())},u=()=>c("loaded",o),d=()=>c("error",()=>i(new Error(`SuperDoc: failed to load DOCX Engine styles from ${t}`))),h=()=>{s.isConnected||c("error",()=>i(new Error(`SuperDoc: DOCX Engine stylesheet was removed while loading from ${t}`)))};s.addEventListener("load",u,{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[Sm]="loading",document.head.appendChild(s))})}Ej({engineVersion:"0.3.0-next.18",buildBaseUrl:null});for(const[e,t]of Object.entries(Sj))e==="SuperDoc"||e==="default"||Object.prototype.hasOwnProperty.call(km,e)||(km[e]=t);var xj=km;return xj})();