@datalking/begonia-browser-sdk 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v1.js CHANGED
@@ -1,9 +1,9 @@
1
- import{createDocumentSurface as yj}from"@datalking/begonia-engine";import{createOoxmlFamilyEnvelope as gm}from"@datalking/begonia-engine";var Hi="ald:advanced-ooxml-nodeview-action";function Lr(e){return typeof e=="object"&&e!==null}function nm(e){if(!Lr(e)||typeof e.family!="string"||typeof e.action!="string"||typeof e.objectId!="string")return!1;switch(e.action){case"replace-math-model":return e.family==="math"&&Lr(e.model);case"set-math-plain-text":return e.family==="math"&&typeof e.text=="string"&&(e.displayMode==="inline"||e.displayMode==="block");case"replace-chart-model":return e.family==="chart"&&Lr(e.model);case"replace-shape-model":return e.family==="shape"&&Lr(e.model);case"apply-math-edits":return e.family==="math"&&Lr(e.model)&&Array.isArray(e.edits);case"apply-chart-edits":return e.family==="chart"&&Lr(e.model)&&Array.isArray(e.edits);case"apply-shape-edits":return e.family==="shape"&&Lr(e.model)&&Array.isArray(e.edits);case"remove-advanced-ooxml":return e.family==="math"||e.family==="chart"||e.family==="shape";default:return!1}}function rr(e,t){e.dispatchEvent(new CustomEvent(Hi,{bubbles:!0,cancelable:!0,detail:t}))}function hb(e,t){e.disabled=!t,e.style.opacity=t?"1":"0.65",e.style.cursor=t?"pointer":"default"}function yb(e,t){e.textContent=t?"Local subtree edits pending. Leave this card or press Cmd/Ctrl+Enter to apply.":"Auto-applies when you leave this card. Apply is still available for an immediate commit.",e.style.color=t?"#0f766e":"#64748b",e.style.fontWeight=t?"600":"400"}function ho(e){let t=!1,r=!1,o=null,n=()=>{o!==null&&(window.clearTimeout(o),o=null)},i=()=>{hb(e.applyButton,r),yb(e.status,r)},s=()=>{if(n(),t||!r)return!1;try{let d=e.onCommit();return r=!1,i(),d}catch(d){throw i(),d}},a=()=>{t||!r||(n(),o=window.setTimeout(()=>{o=null,e.root.contains(document.activeElement)||s()},0))},l=()=>{a()},c=d=>{r&&(d.metaKey||d.ctrlKey)&&d.key==="Enter"&&(d.preventDefault(),s())};return e.root.addEventListener("focusout",l),e.root.addEventListener("keydown",c),i(),{destroy(){t=!0,n(),e.root.removeEventListener("focusout",l),e.root.removeEventListener("keydown",c)},flush:s,markDirty(){t||r||(r=!0,i())},reset(){n(),r=!1,i()}}}function Ft(e,t){return Object.assign(e.style,t),e}function yo(e,t=!1){let r=document.createElement(e);return r.contentEditable="false",Ft(r,{display:t?"inline-flex":"grid",gap:"8px",padding:"10px",border:"1px solid #cbd5e1",borderRadius:"14px",background:"#f8fafc",margin:t?"0 4px":"8px 0",minWidth:t?"280px":"100%",boxSizing:"border-box",verticalAlign:"middle"}),r}function bo(e,t){let r=document.createElement("div");Ft(r,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px"});let o=document.createElement("strong");o.textContent=e,Ft(o,{fontSize:"12px",color:"#0f172a"});let n=document.createElement("span");return n.textContent=t,Ft(n,{fontSize:"11px",fontWeight:"600",color:"#475569",background:"#e2e8f0",borderRadius:"999px",padding:"2px 8px"}),r.append(o,n),{header:r,heading:o}}function Bo(){let e=document.createElement("div");return Ft(e,{fontSize:"11px",color:"#64748b"}),e}function Fr(e){let t=document.createElement("section");Ft(t,{display:"grid",gap:"8px",padding:"10px",borderRadius:"12px",background:"#ffffff",border:"1px solid #e2e8f0"});let r=document.createElement("div");return r.textContent=e,Ft(r,{fontSize:"11px",fontWeight:"700",letterSpacing:"0.08em",textTransform:"uppercase",color:"#475569"}),t.append(r),{section:t,title:r}}function zt(e){let t=document.createElement("div");return t.textContent=e,Ft(t,{fontSize:"11px",color:"#64748b"}),t}function or(){let e=document.createElement("div");return Ft(e,{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}),e}function _e(e,t="default"){let r=document.createElement("button");return r.type="button",r.textContent=e,Ft(r,{padding:"6px 12px",borderRadius:"999px",border:t==="danger"?"1px solid #fecaca":"1px solid #99f6e4",background:t==="danger"?"#fff1f2":"#f0fdfa",color:t==="danger"?"#be123c":"#0f766e",fontSize:"12px",fontWeight:"600",cursor:"pointer"}),r}function xo(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement}import{listOoxmlChartAxisIds as im,listOoxmlChartSeriesIds as sm}from"@datalking/begonia-engine";function pe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function bb(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function br(e){return new Set(e).size===e.length}function kn(e,t){let r=new Set(t),o=e.filter(a=>r.has(a)),n=new Set(e),i=t.filter(a=>n.has(a));if(!bb(o,i))return!1;let s=t.findIndex(a=>!n.has(a));return s===-1||t.slice(s).every(a=>!n.has(a))}function Bb(e,t){if(pe(e.series,t.series))return[];let r=sm(e),o=sm(t);if(!br(r)||!br(o)||!kn(r,o))return[{type:"set-series-list",series:[...t.series]}];let n=new Map(e.series.map((a,l)=>[r[l],a])),i=new Map(t.series.map((a,l)=>[o[l],a])),s=[];for(let a=r.length-1;a>=0;a-=1){let l=r[a];i.has(l)||s.push({type:"remove-series",target:l})}return o.forEach(a=>{let l=i.get(a),c=n.get(a);if(!c){s.push({type:"append-series",series:l});return}pe(c,l)||s.push({type:"set-series",target:a,series:l})}),s}function xb(e,t){if(pe(e.axes,t.axes))return[];let r=im(e),o=im(t);if(!br(r)||!br(o)||!kn(r,o))return[{type:"set-axes",axes:[...t.axes]}];let n=new Map(e.axes.map((a,l)=>[r[l],a])),i=new Map(t.axes.map((a,l)=>[o[l],a])),s=[];for(let a=r.length-1;a>=0;a-=1){let l=r[a];i.has(l)||s.push({type:"remove-axis",axisId:l})}return o.forEach(a=>{let l=i.get(a),c=n.get(a);(!c||!pe(c,l))&&s.push({type:"upsert-axis",axisId:a,axis:l})}),s}function am(e,t){if(pe(e,t))return[];let r=[];return(e.title!==t.title||e.chartType!==t.chartType||e.subtitle!==t.subtitle)&&r.push({type:"set-metadata",title:t.title,chartType:t.chartType,subtitle:t.subtitle}),pe(e.textBody,t.textBody)||r.push({type:"set-text-body",textBody:t.textBody}),pe(e.plotArea,t.plotArea)||r.push({type:"set-plot-area",plotArea:t.plotArea}),pe(e.legend,t.legend)||r.push({type:"set-legend",legend:t.legend}),r.push(...xb(e,t)),r.push(...Bb(e,t)),r}import{Schema as Cb}from"prosemirror-model";import{EditorState as Pb}from"prosemirror-state";import{EditorView as Rb}from"prosemirror-view";var Tb=["display:grid","gap:8px","padding:10px","border:1px solid #dbe3ea","border-radius:12px","background:#f8fafc"].join(";"),kb=["font-size:11px","font-weight:700","letter-spacing:0.08em","text-transform:uppercase","color:#334155"].join(";"),Eb=["display:grid","gap:8px","padding-left:8px"].join(";"),Mb=["display:grid","gap:4px"].join(";"),Ib=["font-size:11px","font-weight:600","letter-spacing:0.06em","text-transform:uppercase","color:#64748b"].join(";"),Ab=["min-height:36px","padding:8px 10px","border:1px solid #cbd5e1","border-radius:10px","background:#ffffff","font-size:12px","color:#0f172a","white-space:pre-wrap"].join(";"),Nb=["display:grid","gap:10px","outline:none"].join(";"),kt=new Cb({nodes:{doc:{content:"entry*"},section:{group:"entry",content:"entry*",attrs:{key:{default:""},label:{default:"Section"}},parseDOM:[{tag:"section[data-ald-structured-section]",getAttrs:e=>{let t=e;return{key:t.dataset.key??"",label:t.dataset.label??"Section"}}}],toDOM(e){return["section",{"data-ald-structured-section":"true","data-key":e.attrs.key,"data-label":e.attrs.label,style:Tb},["div",{style:kb},e.attrs.label],["div",{style:Eb},0]]}},field:{group:"entry",content:"text*",marks:"",parseDOM:[{tag:"div[data-ald-structured-field]",getAttrs:e=>{let t=e;return{key:t.dataset.key??"",label:t.dataset.label??"Field"}}}],toDOM(e){return["div",{"data-ald-structured-field":"true","data-key":e.attrs.key,"data-label":e.attrs.label,style:Mb},["div",{style:Ib},e.attrs.label],["div",{style:Ab},0]]}},text:{}}});function Db(e){return kt.nodes.field.create({key:e.key,label:e.label},e.value?kt.text(e.value):void 0)}function Ob(e){let t=e.children.map(Oa);return kt.nodes.section.create({key:e.key,label:e.label},t)}function Oa(e){return e.type==="field"?Db(e):Ob(e)}function jb(e){return kt.nodes.doc.create(null,e.map(Oa))}function lm(e){return e.content.content.map(t=>um(t)).filter(t=>t!==null)}function um(e){return e.type===kt.nodes.field?{type:"field",key:String(e.attrs.key??""),label:String(e.attrs.label??"Field"),value:e.textContent}:e.type===kt.nodes.section?{type:"section",key:String(e.attrs.key??""),label:String(e.attrs.label??"Section"),children:e.content.content.map(t=>um(t)).filter(t=>t!==null)}:null}function cm(e){return Pb.create({schema:kt,doc:jb(e)})}function Vb(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1)if(t.node(r).type===kt.nodes.section)return t.end(r)-1;return e.doc.content.size}function Lb(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1){let o=t.node(r);if(o.type===kt.nodes.field||o.type===kt.nodes.section)return{from:t.before(r),to:t.before(r)+o.nodeSize}}return null}function dm(e){let{$from:t}=e.selection,r=[],o=e.doc;for(let n=1;n<=t.depth;n+=1){if(t.node(n).type!==kt.nodes.section)continue;let i=String(t.node(n).attrs.key??"").trim();i.length>0&&r.push(i),o=t.node(n)}return{sectionKeys:r,containerKey:r[r.length-1]??null,childKeys:o.content.content.map(n=>String(n.attrs.key??"").trim()).filter(n=>n.length>0)}}function Fb(e){Object.assign(e.style,{display:"grid",gap:"10px",padding:"10px",borderRadius:"12px",border:"1px solid #dbe3ea",background:"#ffffff",minHeight:"160px",boxSizing:"border-box",overflow:"auto"})}function w(e,t,r=""){return{type:"field",key:e,label:t,value:r}}function T(e,t,r=[]){return{type:"section",key:e,label:t,children:[...r]}}function Co(e,t,r={}){Fb(e);let o,n=()=>{r.onSelectionChange?.(dm(o.state))};return o=new Rb(e,{dispatchTransaction(i){let s=o.state.apply(i);o.updateState(s),i.docChanged&&r.onChange?.({entries:lm(s.doc)}),(i.docChanged||i.selectionSet)&&n()},state:cm(t),attributes:{style:Nb,class:"ald-advanced-ooxml-subtree-editor"}}),n(),{dom:e,appendEntry(i){let s=Oa(i),a=Vb(o.state);o.dispatch(o.state.tr.insert(a,s)),o.focus()},destroy(){o.destroy()},focus(){o.focus()},readEntries(){return lm(o.state.doc)},readSelection(){return dm(o.state)},removeSelectedEntry(){let i=Lb(o.state);return i?(o.dispatch(o.state.tr.delete(i.from,i.to)),o.focus(),!0):!1},setEntries(i){o.updateState(cm(i)),n()}}}import{normalizeOoxmlChartModel as Hb}from"@datalking/begonia-engine";function H(e){let t=e.trim();return t.length>0?t:null}function oe(e){let t=e.trim();if(!t)return null;let r=Number(t);return Number.isFinite(r)?r:null}function fe(e){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:null}function Pe(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Re(e){return e==null?"":JSON.stringify(e,null,2)}function C(e,t){let r=e.find(o=>o.type==="field"&&o.key===t);return r?.type==="field"?r.value:""}function pt(e,t){return e.filter(r=>r.type==="section"&&r.key===t)}function ja(e,t){return pt(e,t)[0]??null}function mm(e){return e.type==="field"?e.value.trim().length>0:e.children.some(t=>mm(t))}function zb(e){return e.some(t=>mm(t))}function Te(e,t){let r=ja(e,t);return r&&zb(r.children)?r:null}function Po(e,t,r){let o=r?.paragraphs?.length?r.paragraphs:r?.plainText?[r.plainText]:[];return T(e,t,(o.length>0?o:[""]).map(n=>w("paragraph","Paragraph",n)))}function qi(e){if(!e)return null;let t=e.children.filter(r=>r.type==="field"&&r.key==="paragraph").map(r=>r.value);return t.length===0?null:{paragraphs:t,plainText:t.join(`
2
- `)}}function Wi(e,t){return T(e,t,[w("paragraph","Paragraph","")])}function qb(e){return T("marker","Marker",[w("symbol","Symbol",e.marker?.symbol??""),w("size","Size",e.marker?.size==null?"":String(e.marker.size))])}function Wb(e){return T("data-labels","Data Labels",[w("show-value","Show Value",e.dataLabels?.showValue==null?"":String(e.dataLabels.showValue)),w("show-category","Show Category",e.dataLabels?.showCategory==null?"":String(e.dataLabels.showCategory)),w("show-series-name","Show Series Name",e.dataLabels?.showSeriesName==null?"":String(e.dataLabels.showSeriesName)),w("show-percentage","Show Percentage",e.dataLabels?.showPercentage==null?"":String(e.dataLabels.showPercentage)),w("position","Position",e.dataLabels?.position??""),w("separator","Separator",e.dataLabels?.separator??"")])}function Kb(e){return T("series","Series",[w("id","Series Id",e.id??""),w("order","Order",e.order==null?"":String(e.order)),w("name","Name",e.name??""),w("categories","Categories",e.categories.join(", ")),w("values","Values",e.values.map(t=>t==null?"":String(t)).join(", ")),w("color","Color",e.color??""),w("smooth","Smooth",e.smooth==null?"":String(e.smooth)),w("explosion","Explosion",e.explosion==null?"":String(e.explosion)),qb(e),Wb(e)])}function _b(e){return T("axis","Axis",[w("id","Axis Id",e.id??""),w("kind","Kind",e.kind??""),w("title","Title",e.title??""),w("format-code","Format Code",e.formatCode??""),w("orientation","Orientation",e.orientation??""),w("visible","Visible",e.visible==null?"":String(e.visible)),w("minimum","Minimum",e.minimum==null?"":String(e.minimum)),w("maximum","Maximum",e.maximum==null?"":String(e.maximum)),w("major-unit","Major Unit",e.majorUnit==null?"":String(e.majorUnit)),w("minor-unit","Minor Unit",e.minorUnit==null?"":String(e.minorUnit)),w("crosses-at","Crosses At",e.crossesAt==null?"":String(e.crossesAt)),w("major-gridlines","Major Gridlines",e.majorGridlines==null?"":String(e.majorGridlines)),w("minor-gridlines","Minor Gridlines",e.minorGridlines==null?"":String(e.minorGridlines))])}function Ub(e){return T("legend","Legend",[w("visible","Visible",e.legend==null?"":String(e.legend.visible)),w("position","Position",e.legend?.position??""),w("overlay","Overlay",e.legend?.overlay==null?"":String(e.legend.overlay))])}function Zb(e){return T("plot-area","Plot Area",[w("stacked","Stacked",e.plotArea?.stacked==null?"":String(e.plotArea.stacked)),w("percent-stacked","Percent Stacked",e.plotArea?.percentStacked==null?"":String(e.plotArea.percentStacked)),w("vary-colors","Vary Colors",e.plotArea?.varyColors==null?"":String(e.plotArea.varyColors)),w("hole-size","Hole Size",e.plotArea?.holeSize==null?"":String(e.plotArea.holeSize))])}function Gb(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Xb(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>{let r=Number(t);return Number.isFinite(r)?r:null})}function $b(e){return e.length>0?e:null}function Yb(e){let t=Te(e,"marker"),r=Te(e,"data-labels");return{id:H(C(e,"id")),order:oe(C(e,"order")),name:H(C(e,"name")),categories:Gb(C(e,"categories")),values:Xb(C(e,"values")),color:H(C(e,"color")),marker:t?{symbol:H(C(t.children,"symbol"))??"unknown",size:oe(C(t.children,"size"))}:null,dataLabels:r?{showValue:fe(C(r.children,"show-value")),showCategory:fe(C(r.children,"show-category")),showSeriesName:fe(C(r.children,"show-series-name")),showPercentage:fe(C(r.children,"show-percentage")),position:H(C(r.children,"position")),separator:$b(C(r.children,"separator"))}:null,smooth:fe(C(e,"smooth")),explosion:oe(C(e,"explosion"))}}function Jb(e){let t=C(e,"kind"),r=C(e,"orientation");return{id:H(C(e,"id")),kind:t==="category"||t==="value"||t==="series"||t==="date"?t:"unknown",title:H(C(e,"title")),formatCode:H(C(e,"format-code")),orientation:r==="minMax"||r==="maxMin"?r:null,visible:fe(C(e,"visible")),minimum:oe(C(e,"minimum")),maximum:oe(C(e,"maximum")),majorUnit:oe(C(e,"major-unit")),minorUnit:oe(C(e,"minor-unit")),crossesAt:oe(C(e,"crosses-at")),majorGridlines:fe(C(e,"major-gridlines")),minorGridlines:fe(C(e,"minor-gridlines"))}}function pm(e){return[w("title","Title",e.title??""),w("chart-type","Chart Type",e.chartType??""),w("subtitle","Subtitle",e.subtitle??""),Po("text-body","Text Body",e.textBody),Zb(e),...e.series.map(t=>Kb(t)),...e.axes.map(t=>_b(t)),Ub(e)]}function fm(e,t){let r=Te(e,"text-body"),o=Te(e,"plot-area"),n=Te(e,"legend");return Hb({...t,title:H(C(e,"title")),chartType:H(C(e,"chart-type")),subtitle:H(C(e,"subtitle")),textBody:qi(r),plotArea:o?{stacked:fe(C(o.children,"stacked")),percentStacked:fe(C(o.children,"percent-stacked")),varyColors:fe(C(o.children,"vary-colors")),holeSize:oe(C(o.children,"hole-size"))}:null,series:pt(e,"series").map(i=>Yb(i.children)),axes:pt(e,"axis").map(i=>Jb(i.children)),legend:n?{visible:fe(C(n.children,"visible"))!==!1,position:H(C(n.children,"position"))??"unknown",overlay:fe(C(n.children,"overlay"))}:null},t.title??"Chart")}function Qb(){return T("series","Series",[w("id","Series Id",""),w("order","Order",""),w("name","Name",""),w("categories","Categories",""),w("values","Values",""),w("color","Color",""),w("smooth","Smooth",""),w("explosion","Explosion",""),T("marker","Marker",[w("symbol","Symbol",""),w("size","Size","")]),T("data-labels","Data Labels",[w("show-value","Show Value",""),w("show-category","Show Category",""),w("show-series-name","Show Series Name",""),w("show-percentage","Show Percentage",""),w("position","Position",""),w("separator","Separator","")])])}function eB(){return T("axis","Axis",[w("id","Axis Id",""),w("kind","Kind","category"),w("title","Title",""),w("format-code","Format Code",""),w("orientation","Orientation",""),w("visible","Visible",""),w("minimum","Minimum",""),w("maximum","Maximum",""),w("major-unit","Major Unit",""),w("minor-unit","Minor Unit",""),w("crosses-at","Crosses At",""),w("major-gridlines","Major Gridlines",""),w("minor-gridlines","Minor Gridlines","")])}function tB(){return T("legend","Legend",[w("visible","Visible","true"),w("position","Position","right"),w("overlay","Overlay","")])}function rB(){return T("plot-area","Plot Area",[w("stacked","Stacked",""),w("percent-stacked","Percent Stacked",""),w("vary-colors","Vary Colors",""),w("hole-size","Hole Size","")])}function oB(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function nB(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function iB(e){return e==null}function wm(e={}){let t=oB(e.containerKey),r=nB(e.childKeys),o=n=>r.has(n);return t==="text-body"?[{label:"Paragraph",createEntry:()=>w("paragraph","Paragraph","")}]:iB(t)?[{label:"Series",createEntry:Qb},{label:"Axis",createEntry:eB},...o("legend")?[]:[{label:"Legend",createEntry:tB}],...o("plot-area")?[]:[{label:"Plot Area",createEntry:rB}],...o("text-body")?[]:[{label:"Text Body",createEntry:()=>Wi("text-body","Text Body")}]]:[]}function Va(e){let t=String(e.attrs.label??"Chart"),r=String(e.attrs.text??""),o=gm("chart",{title:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=gm("chart",e.attrs.familyData,{label:t,text:r})??o;return{objectId:String(e.attrs.objectId??""),label:t,model:n.data.model??o.data.model,evidence:n.evidence}}function sB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function Sm(){return e=>{let t=e,r=yo("div"),{header:o,heading:n}=bo("Chart","chart"),i=Bo(),{section:s}=Fr("Native Subtree"),a=zt("Edit chart metadata, series, axes, legend, and plot area as a structured nested tree. Use insert buttons at the current subtree selection. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),l=or();l.style.justifyContent="flex-start";let c=_e("Remove Selected","danger"),d=sB(),u=or();u.style.justifyContent="space-between",u.style.alignItems="center";let m=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=_e("Apply"),f=_e("Remove Chart","danger");m.style.marginRight="auto",u.append(m,p,f),s.append(a,l,d,c),r.append(o,i,s,u);let g=null,v=(P,h)=>{l.replaceChildren(),wm({containerKey:P,childKeys:h}).forEach(b=>{let x=_e(b.label);x.addEventListener("click",()=>{E.appendEntry(b.createEntry())}),l.append(x)})},E=Co(d,[],{onChange(){g?.markDirty()},onSelectionChange(P){v(P.containerKey,P.childKeys)}});c.addEventListener("click",()=>{E.removeSelectedEntry()}),g=ho({applyButton:p,onCommit:()=>{let P=Va(t),h=fm(E.readEntries(),P.model),b=am(P.model,h);return b.length===0?!1:(rr(r,{family:"chart",action:"apply-chart-edits",objectId:P.objectId,model:h,edits:b}),!0)},root:r,status:m});let S=P=>{t=P;let h=Va(P);n.textContent=h.label,i.textContent=`${h.evidence.chartType??"chart"} | ${h.evidence.seriesCount} series | ${h.evidence.axisCount} axes`,g?.reset(),E.setEntries(pm(h.model))};return p.addEventListener("click",()=>{g?.flush()}),f.addEventListener("click",()=>{g?.reset();let P=Va(t);rr(r,{family:"chart",action:"remove-advanced-ooxml",objectId:P.objectId})}),S(e),{dom:r,destroy(){g?.destroy(),E.destroy()},update(P){return P.type!==t.type?!1:(S(P),!0)},stopEvent(P){return xo(P.target)||P.target instanceof Node&&d.contains(P.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as Bm,normalizeOoxmlMathModel as VB}from"@datalking/begonia-engine";function vm(e,t){if(pe(e,t))return[];if(e.root.type==="text"&&t.root.type==="text"){let r=e.root.value,o=t.root.value;return r!==o?[{type:"set-plain-text",text:o,displayMode:t.displayMode}]:e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[]}return t.root.type==="text"?[{type:"set-plain-text",text:t.root.value,displayMode:t.displayMode}]:pe(e.root,t.root)&&e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[{type:"replace-model",model:t}]}import{normalizeOoxmlMathModel as jB}from"@datalking/begonia-engine";import{createOoxmlMathTextNode as aB}from"@datalking/begonia-engine";var lB=new Set(["numerator","denominator","body","degree","base","superscript-slot","subscript-slot","lower","upper","name","argument","matrix-cell","equation-row"]);function La(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function hm(e){let t=La(e);return t==null||lB.has(t)}function Fa(e){return aB(e)}function za(){return Fa("")}function cB(e=""){return w("text","Text",e)}function ue(e,t){return T(e,t,[cB()])}function ym(e){throw new Error(`Unsupported math node type: ${JSON.stringify(e)}.`)}function ke(e){return hm(e)}function dB(){return T("fraction","Fraction",[ue("numerator","Numerator"),ue("denominator","Denominator")])}function uB(){return T("radical","Radical",[ue("body","Body"),T("degree","Degree",[])])}function mB(){return T("superscript","Superscript",[ue("base","Base"),ue("superscript-slot","Superscript")])}function pB(){return T("subscript","Subscript",[ue("base","Base"),ue("subscript-slot","Subscript")])}function fB(){return T("subsup","Subscript and Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function wB(){return T("preSubSup","Pre-Sub/Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function gB(){return T("matrix","Matrix",[T("matrix-row","Row",[T("matrix-cell","Cell",[w("text","Text","")])])])}function SB(){return T("equationArray","Equation Array",[T("equation-row","Row",[w("text","Text","")])])}function vB(){return T("delimiter","Delimiter",[w("begin","Begin Delimiter","("),w("end","End Delimiter",")"),ue("body","Body")])}function hB(){return T("operator","Operator",[w("operator-symbol","Operator","sum"),ue("body","Body"),T("lower","Lower",[]),T("upper","Upper",[])])}function yB(){return T("nary","N-ary Operator",[w("operator-symbol","Operator","prod"),ue("body","Body"),T("subscript-slot","Subscript",[]),T("superscript-slot","Superscript",[])])}function bB(){return T("limitLower","Lower Limit",[ue("base","Base"),ue("lower","Lower")])}function BB(){return T("limitUpper","Upper Limit",[ue("base","Base"),ue("upper","Upper")])}function xB(){return T("function","Function",[ue("name","Name"),ue("argument","Argument")])}function CB(){return T("accent","Accent",[w("accent-symbol","Accent","hat"),ue("body","Body")])}function PB(){return T("bar","Bar",[w("bar-position","Position","top"),ue("body","Body")])}function RB(){return T("box","Box",[w("border-box","Border Box","true"),ue("body","Body")])}function TB(){return T("groupCharacter","Group Character",[w("group-character","Character","_"),w("group-position","Position","bottom"),ue("body","Body")])}function kB(){return T("phantom","Phantom",[w("zero-width","Zero Width","false"),w("zero-ascent","Zero Ascent","false"),w("zero-descent","Zero Descent","false"),w("transparent","Transparent","true"),ue("body","Body")])}function EB(){return T("matrix-row","Row",[T("matrix-cell","Cell",[w("text","Text","")])])}function MB(){return T("matrix-cell","Cell",[w("text","Text","")])}function IB(){return T("equation-row","Row",[w("text","Text","")])}var AB=[{label:"Text",createEntry:()=>w("text","Text",""),supportsContainer:ke},{label:"Fraction",createEntry:dB,supportsContainer:ke},{label:"Radical",createEntry:uB,supportsContainer:ke},{label:"Superscript",createEntry:mB,supportsContainer:ke},{label:"Subscript",createEntry:pB,supportsContainer:ke},{label:"Sub+Sup",createEntry:fB,supportsContainer:ke},{label:"Pre-Sub/Sup",createEntry:wB,supportsContainer:ke},{label:"Matrix",createEntry:gB,supportsContainer:ke},{label:"Matrix Row",createEntry:EB,supportsContainer:e=>e==="matrix"},{label:"Matrix Cell",createEntry:MB,supportsContainer:e=>e==="matrix-row"},{label:"Equation Array",createEntry:SB,supportsContainer:ke},{label:"Equation Row",createEntry:IB,supportsContainer:e=>e==="equationArray"},{label:"Delimiter",createEntry:vB,supportsContainer:ke},{label:"Operator",createEntry:hB,supportsContainer:ke},{label:"N-ary",createEntry:yB,supportsContainer:ke},{label:"Lower Limit",createEntry:bB,supportsContainer:ke},{label:"Upper Limit",createEntry:BB,supportsContainer:ke},{label:"Function",createEntry:xB,supportsContainer:ke},{label:"Accent",createEntry:CB,supportsContainer:ke},{label:"Bar",createEntry:PB,supportsContainer:ke},{label:"Box",createEntry:RB,supportsContainer:ke},{label:"Group Char",createEntry:TB,supportsContainer:ke},{label:"Phantom",createEntry:kB,supportsContainer:ke}];function Ha(e={}){let t=La(e.containerKey);return AB.filter(r=>r.supportsContainer(t)).map(({label:r,createEntry:o})=>({label:r,createEntry:o}))}function ie(e,t){return ja(e,t)?.children??[]}function NB(e){let t=e.map(r=>OB(r)).filter(r=>r!==null);return t.length===0?za():t.length===1?t[0]:{type:"sequence",items:t}}function Ki(e){return e.length>0?ne(e):null}function DB(e){let t=pt(e,"matrix-cell").map(r=>ne(r.children));return t.length>0?t:[za()]}function OB(e){if(e.type==="field")return e.key==="text"?Fa(e.value):null;switch(e.key){case"fraction":return{type:"fraction",numerator:ne(ie(e.children,"numerator")),denominator:ne(ie(e.children,"denominator"))};case"radical":{let t=ie(e.children,"degree");return{type:"radical",body:ne(ie(e.children,"body")),degree:t.length>0?ne(t):null}}case"superscript":return{type:"superscript",base:ne(ie(e.children,"base")),superscript:ne(ie(e.children,"superscript-slot"))};case"subscript":return{type:"subscript",base:ne(ie(e.children,"base")),subscript:ne(ie(e.children,"subscript-slot"))};case"subsup":return{type:"subsup",base:ne(ie(e.children,"base")),subscript:ne(ie(e.children,"subscript-slot")),superscript:ne(ie(e.children,"superscript-slot"))};case"preSubSup":return{type:"preSubSup",base:ne(ie(e.children,"base")),subscript:ne(ie(e.children,"subscript-slot")),superscript:ne(ie(e.children,"superscript-slot"))};case"matrix":return{type:"matrix",rows:pt(e.children,"matrix-row").map(t=>DB(t.children))};case"equationArray":return{type:"equationArray",rows:pt(e.children,"equation-row").map(t=>ne(t.children))};case"delimiter":return{type:"delimiter",begin:H(C(e.children,"begin")),end:H(C(e.children,"end")),body:ne(ie(e.children,"body"))};case"operator":return{type:"operator",operator:H(C(e.children,"operator-symbol")),body:ne(ie(e.children,"body")),lower:Ki(ie(e.children,"lower")),upper:Ki(ie(e.children,"upper"))};case"nary":return{type:"nary",operator:H(C(e.children,"operator-symbol")),body:ne(ie(e.children,"body")),subscript:Ki(ie(e.children,"subscript-slot")),superscript:Ki(ie(e.children,"superscript-slot"))};case"limitLower":return{type:"limitLower",base:ne(ie(e.children,"base")),lower:ne(ie(e.children,"lower"))};case"limitUpper":return{type:"limitUpper",base:ne(ie(e.children,"base")),upper:ne(ie(e.children,"upper"))};case"function":return{type:"function",name:ne(ie(e.children,"name")),argument:ne(ie(e.children,"argument"))};case"accent":return{type:"accent",accent:H(C(e.children,"accent-symbol")),body:ne(ie(e.children,"body"))};case"bar":{let t=C(e.children,"bar-position").trim().toLowerCase();return{type:"bar",position:t==="top"||t==="bottom"?t:"unknown",body:ne(ie(e.children,"body"))}}case"box":return{type:"box",body:ne(ie(e.children,"body")),borderBox:fe(C(e.children,"border-box"))};case"groupCharacter":{let t=C(e.children,"group-position").trim().toLowerCase();return{type:"groupCharacter",character:H(C(e.children,"group-character")),position:t==="top"||t==="bottom"?t:"unknown",body:ne(ie(e.children,"body"))}}case"phantom":return{type:"phantom",body:ne(ie(e.children,"body")),zeroWidth:fe(C(e.children,"zero-width")),zeroAscent:fe(C(e.children,"zero-ascent")),zeroDescent:fe(C(e.children,"zero-descent")),transparent:fe(C(e.children,"transparent"))};default:return e.children.length>0?ne(e.children):null}}function ne(e){return NB(e)}function te(e){switch(e.type){case"sequence":return e.items.flatMap(t=>te(t));case"text":return[w("text","Text",e.value)];case"fraction":return[T("fraction","Fraction",[T("numerator","Numerator",te(e.numerator)),T("denominator","Denominator",te(e.denominator))])];case"radical":return[T("radical","Radical",[T("body","Body",te(e.body)),T("degree","Degree",e.degree?te(e.degree):[])])];case"superscript":return[T("superscript","Superscript",[T("base","Base",te(e.base)),T("superscript-slot","Superscript",te(e.superscript))])];case"subscript":return[T("subscript","Subscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript))])];case"subsup":return[T("subsup","Subscript and Superscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript)),T("superscript-slot","Superscript",te(e.superscript))])];case"preSubSup":return[T("preSubSup","Pre-Sub/Superscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript)),T("superscript-slot","Superscript",te(e.superscript))])];case"matrix":return[T("matrix","Matrix",e.rows.map(t=>T("matrix-row","Row",t.map(r=>T("matrix-cell","Cell",te(r))))))];case"equationArray":return[T("equationArray","Equation Array",e.rows.map(t=>T("equation-row","Row",te(t))))];case"delimiter":return[T("delimiter","Delimiter",[w("begin","Begin Delimiter",e.begin??""),w("end","End Delimiter",e.end??""),T("body","Body",te(e.body))])];case"operator":return[T("operator","Operator",[w("operator-symbol","Operator",e.operator??""),T("body","Body",te(e.body)),T("lower","Lower",e.lower?te(e.lower):[]),T("upper","Upper",e.upper?te(e.upper):[])])];case"nary":return[T("nary","N-ary Operator",[w("operator-symbol","Operator",e.operator??""),T("body","Body",te(e.body)),T("subscript-slot","Subscript",e.subscript?te(e.subscript):[]),T("superscript-slot","Superscript",e.superscript?te(e.superscript):[])])];case"limitLower":return[T("limitLower","Lower Limit",[T("base","Base",te(e.base)),T("lower","Lower",te(e.lower))])];case"limitUpper":return[T("limitUpper","Upper Limit",[T("base","Base",te(e.base)),T("upper","Upper",te(e.upper))])];case"function":return[T("function","Function",[T("name","Name",te(e.name)),T("argument","Argument",te(e.argument))])];case"accent":return[T("accent","Accent",[w("accent-symbol","Accent",e.accent??""),T("body","Body",te(e.body))])];case"bar":return[T("bar","Bar",[w("bar-position","Position",e.position),T("body","Body",te(e.body))])];case"box":return[T("box","Box",[w("border-box","Border Box",e.borderBox==null?"":String(e.borderBox)),T("body","Body",te(e.body))])];case"groupCharacter":return[T("groupCharacter","Group Character",[w("group-character","Character",e.character??""),w("group-position","Position",e.position),T("body","Body",te(e.body))])];case"phantom":return[T("phantom","Phantom",[w("zero-width","Zero Width",e.zeroWidth==null?"":String(e.zeroWidth)),w("zero-ascent","Zero Ascent",e.zeroAscent==null?"":String(e.zeroAscent)),w("zero-descent","Zero Descent",e.zeroDescent==null?"":String(e.zeroDescent)),w("transparent","Transparent",e.transparent==null?"":String(e.transparent)),T("body","Body",te(e.body))])]}return ym(e)}function qa(e){return[w("display-mode","Display Mode",e.displayMode),...te(e.root)]}function bm(e){let r=C(e,"display-mode").trim().toLowerCase()==="block"?"block":"inline",o=e.filter(n=>!(n.type==="field"&&n.key==="display-mode"));return jB({displayMode:r,root:ne(o)},"",r)}function Wa(e){let t=String(e.attrs.text??""),r=String(e.attrs.label??"Equation"),o=Bm("math",{plainText:t,displayMode:"inline"},{label:r,text:t}),n=Bm("math",e.attrs.familyData,{label:r,text:t})??o,i=VB(n.data,n.data.plainText??t,n.data.displayMode??"inline");return{objectId:String(e.attrs.objectId??""),label:r,model:i,evidence:n.evidence}}function LB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%",maxWidth:"720px"}),e}function xm(){return e=>{let t=e,r=yo("span",!0);Object.assign(r.style,{display:"inline-grid",width:"min(720px, 100%)",verticalAlign:"top"});let{header:o,heading:n}=bo("Equation","math"),i=Bo(),{section:s}=Fr("Native Subtree"),a=zt("Edit the equation as a nested ProseMirror tree. Insert structures into the selected slot. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),l=or();l.style.justifyContent="flex-start";let c=_e("Remove Selected","danger"),d=LB(),u=or();u.style.justifyContent="space-between",u.style.alignItems="center";let m=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=_e("Apply"),f=_e("Remove Equation","danger");m.style.marginRight="auto",u.append(m,p,f),s.append(a,l,d,c),r.append(o,i,s,u);let g=null,v=P=>{l.replaceChildren(),Ha({containerKey:P}).forEach(h=>{let b=_e(h.label);b.addEventListener("click",()=>{E.appendEntry(h.createEntry())}),l.append(b)})},E=Co(d,[],{onChange(){g?.markDirty()},onSelectionChange(P){v(P.containerKey)}});c.addEventListener("click",()=>{E.removeSelectedEntry()}),g=ho({applyButton:p,onCommit:()=>{let P=Wa(t),h=bm(E.readEntries()),b=vm(P.model,h);return b.length===0?!1:(rr(r,{family:"math",action:"apply-math-edits",objectId:P.objectId,model:h,edits:b}),!0)},root:r,status:m});let S=P=>{t=P;let h=Wa(P);n.textContent=h.label,i.textContent=`${h.evidence.displayMode} | root ${h.evidence.rootType} | ${h.evidence.structureCount} structures`,g?.reset(),E.setEntries(qa(h.model))};return p.addEventListener("click",()=>{g?.flush()}),f.addEventListener("click",()=>{g?.reset();let P=Wa(t);rr(r,{family:"math",action:"remove-advanced-ooxml",objectId:P.objectId})}),S(e),{dom:r,destroy(){g?.destroy(),E.destroy()},update(P){return P.type!==t.type?!1:(S(P),!0)},stopEvent(P){return xo(P.target)||P.target instanceof Node&&d.contains(P.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as qm,createOoxmlShapePreview as YB}from"@datalking/begonia-engine";function Cm(e){return e.map((t,r)=>t.id??`shape-child-${r+1}`)}function Pm(e,t){return pe({...e,children:[]},{...t,children:[]})}function Ka(e,t,r){for(let o=0;o<e.length;o+=1){let n=e[o],i=n.id?.trim(),s=e[o+1]?.id?.trim()??null;if(!i||r.has(i)||e[o+1]&&!s||(r.set(i,{child:n,parentId:t,beforeId:s}),!Ka(n.children,i,r)))return!1}return!0}function FB(e,t){return e.size===t.size&&[...t.keys()].every(r=>e.has(r))}function zB(e,t){return{...t,children:[...e.children]}}function Rm(e,t,r){t.forEach(o=>{let n=o.id?.trim();if(!n)return;let i=e.get(n);i&&!Pm(i.child,o)&&r.push({type:"set-child",target:n,child:zB(i.child,o)}),Rm(e,o.children,r)})}function Tm(e,t,r,o){let n=null;for(let i=t.length-1;i>=0;i-=1){let s=t[i],a=s.id?.trim();if(!a)continue;let l=e.get(a);l&&(l.parentId!==r||l.beforeId!==n)&&o.push({type:"move-child",target:a,parentTarget:r,beforeTarget:n}),Tm(e,s.children,a,o),n=a}}function HB(e,t){let r=new Map,o=new Map;if(!Ka(e,null,r)||!Ka(t,null,o)||!FB(r,o))return null;let n=[];return Rm(r,t,n),Tm(r,t,null,n),n}function qB(e,t,r){return t==null||r==null?[{type:"set-children",children:[...e]}]:[{type:"set-child",target:t,child:r}]}function km(e,t,r,o){if(pe(e,t))return[];let n=Cm(e),i=Cm(t);if(!br(n)||!br(i)||!kn(n,i))return qB(t,r,o);let s=new Map(e.map((c,d)=>[n[d],c])),a=new Map(t.map((c,d)=>[i[d],c])),l=[];for(let c=n.length-1;c>=0;c-=1){let d=n[c];a.has(d)||l.push({type:"remove-child",target:d})}return i.forEach(c=>{let d=a.get(c),u=s.get(c);if(!u){l.push(r==null?{type:"append-child",child:d}:{type:"append-child-to-parent",parentTarget:r,child:d});return}if(!Pm(u,d)){l.push({type:"set-child",target:c,child:d});return}l.push(...km(u.children,d.children,c,d))}),l}function Em(e,t){if(pe(e,t))return[];if(!pe(e.groupTransform,t.groupTransform))return[{type:"replace-model",model:t}];let r=[];(e.label!==t.label||e.shapeType!==t.shapeType||e.groupKind!==t.groupKind)&&r.push({type:"set-metadata",label:t.label,shapeType:t.shapeType,groupKind:t.groupKind}),(e.isWatermark??!1)!==(t.isWatermark??!1)&&r.push({type:"set-watermark",isWatermark:t.isWatermark??!1}),pe(e.textBody,t.textBody)||r.push({type:"set-text-body",paragraphs:t.textBody?.paragraphs?[...t.textBody.paragraphs]:[]}),pe(e.geometry,t.geometry)||r.push({type:"set-geometry",geometry:t.geometry}),pe(e.transform,t.transform)||r.push({type:"set-transform",transform:t.transform}),pe(e.fill,t.fill)||r.push({type:"set-fill",fill:t.fill}),pe(e.stroke,t.stroke)||r.push({type:"set-stroke",stroke:t.stroke}),pe(e.effects,t.effects)||r.push({type:"set-effects",effects:t.effects??null}),pe(e.anchor,t.anchor)||r.push({type:"set-anchor",anchor:t.anchor}),pe(e.connector,t.connector)||r.push({type:"set-connector",connector:t.connector}),pe(e.picture,t.picture)||r.push({type:"set-picture",picture:t.picture}),pe(e.wordArt,t.wordArt)||r.push({type:"set-word-art",wordArt:t.wordArt});let o=HB(e.children,t.children);return o?(r.push(...o),r):(r.push(...km(e.children,t.children,null,null)),r)}function Mm(e){return T("shape-child","Child Object",[w("kind","Kind",e.kind??""),w("id","Id",e.id??""),w("label","Label",e.label??""),Po("text-body","Text Body",e.textBody),_a(e.geometry),Ua(e.transform),Za(e.groupTransform??null),Ga(e.fill??null),Xa(e.stroke??null),$a(e.effects??null),Ya(e.connector),Ja(e.picture),Qa(e.wordArt),...e.children.map(t=>Mm(t))])}function _a(e){return T("geometry","Geometry",[w("preset","Preset",e?.preset??""),w("custom-path-count","Custom Path Count",e?.customPathCount==null?"":String(e.customPathCount)),w("adjustments","Adjustments",e?.adjustments.join(", ")??""),w("custom-geometry-json","Custom Geometry JSON",Re(e?.customGeometry??null))])}function Ua(e){return T("transform","Transform",[w("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),w("height-emu","Height (EMU)",e?.heightEmu==null?"":String(e.heightEmu)),w("offset-x-emu","Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),w("offset-y-emu","Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),w("rotation","Rotation",e?.rotation==null?"":String(e.rotation)),w("flip-h","Flip H",e?.flipH==null?"":String(e.flipH)),w("flip-v","Flip V",e?.flipV==null?"":String(e.flipV))])}function Za(e){return T("group-transform","Group Transform",[w("child-offset-x-emu","Child Offset X (EMU)",e?.childOffsetXEmu==null?"":String(e.childOffsetXEmu)),w("child-offset-y-emu","Child Offset Y (EMU)",e?.childOffsetYEmu==null?"":String(e.childOffsetYEmu)),w("child-width-emu","Child Width (EMU)",e?.childWidthEmu==null?"":String(e.childWidthEmu)),w("child-height-emu","Child Height (EMU)",e?.childHeightEmu==null?"":String(e.childHeightEmu))])}function Ga(e){return T("fill","Fill",[w("kind","Kind",e?.kind??""),w("color","Color",e?.color??""),w("secondary-color","Secondary Color",e?.secondaryColor??""),w("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),w("gradient-angle","Gradient Angle",e?.gradientAngle==null?"":String(e.gradientAngle)),w("gradient-path","Gradient Path",e?.gradientPath??""),w("pattern-preset","Pattern Preset",e?.patternPreset??""),w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("color-source-json","Color Source JSON",Re(e?.colorSource??null)),w("secondary-color-source-json","Secondary Color Source JSON",Re(e?.secondaryColorSource??null)),w("gradient-stops-json","Gradient Stops JSON",e?Re(e.gradientStops??[]):""),w("picture-fill-json","Picture Fill JSON",Re(e?.pictureFill??null))])}function Xa(e){return T("stroke","Stroke",[w("kind","Kind",e?.kind??""),w("color","Color",e?.color??""),w("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),w("dash","Dash",e?.dash??""),w("cap","Cap",e?.cap??""),w("join","Join",e?.join??""),w("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("compound","Compound",e?.compound??""),w("color-source-json","Color Source JSON",Re(e?.colorSource??null)),w("head-end-json","Head End JSON",Re(e?.headEnd??null)),w("tail-end-json","Tail End JSON",Re(e?.tailEnd??null))])}function $a(e){return T("effects","Effects",[w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("style-ref-color-source-json","Style Ref Color Source JSON",Re(e?.styleRefColorSource??null)),w("effect-nodes-json","Effect Nodes JSON",e?Re(e.effectNodes??[]):""),w("glow-json","Glow JSON",Re(e?.glow??null)),w("outer-shadow-json","Outer Shadow JSON",Re(e?.outerShadow??null)),w("inner-shadow-json","Inner Shadow JSON",Re(e?.innerShadow??null)),w("soft-edge-json","Soft Edge JSON",Re(e?.softEdge??null)),w("blur-json","Blur JSON",Re(e?.blur??null)),w("reflection-json","Reflection JSON",Re(e?.reflection??null)),w("preset-shadow-json","Preset Shadow JSON",Re(e?.presetShadow??null)),w("effect-dag-json","Effect DAG JSON",Re(e?.effectDag??null))])}function WB(e){return T("anchor","Anchor",[w("kind","Kind",e?.kind??""),w("wrap","Wrap",e?.wrap??""),w("behind-doc","Behind Doc",e?.behindDoc==null?"":String(e.behindDoc)),w("allow-overlap","Allow Overlap",e?.allowOverlap==null?"":String(e.allowOverlap)),w("layout-in-cell","Layout In Cell",e?.layoutInCell==null?"":String(e.layoutInCell)),w("relative-height","Relative Height",e?.relativeHeight==null?"":String(e.relativeHeight)),w("dist-top-emu","Dist Top (EMU)",e?.distTopEmu==null?"":String(e.distTopEmu)),w("dist-bottom-emu","Dist Bottom (EMU)",e?.distBottomEmu==null?"":String(e.distBottomEmu)),w("dist-left-emu","Dist Left (EMU)",e?.distLeftEmu==null?"":String(e.distLeftEmu)),w("dist-right-emu","Dist Right (EMU)",e?.distRightEmu==null?"":String(e.distRightEmu)),w("position-h","Position H",e?.positionH??""),w("position-v","Position V",e?.positionV??""),w("offset-x-emu","Anchor Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),w("offset-y-emu","Anchor Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),w("align-h","Align H",e?.alignH??""),w("align-v","Align V",e?.alignV??"")])}function Ya(e){return T("connector","Connector",[w("connector-type","Connector Type",e?.connectorType??""),w("begin-shape-id","Begin Shape Id",e?.beginShapeId??""),w("end-shape-id","End Shape Id",e?.endShapeId??"")])}function Ja(e){return T("picture","Picture",[w("src","Source",e?.src??""),w("alt","Alt",e?.alt??""),w("title","Title",e?.title??""),w("relationship-id","Relationship Id",e?.relationshipId??""),w("blip-fill-json","Blip Fill JSON",Re(e?.blipFill??null)),w("hyperlink-url","Hyperlink URL",e?.hyperlink?.url??""),w("hyperlink-tooltip","Hyperlink Tooltip",e?.hyperlink?.tooltip??"")])}function Qa(e){return T("word-art","WordArt",[w("text","Text",e?.text??""),w("preset","Preset",e?.preset??"")])}function el(e){return[w("label","Label",e.label??""),w("shape-type","Shape Type",e.shapeType??""),w("group-kind","Group Kind",e.groupKind??""),w("is-watermark","Is Watermark",e.isWatermark==null?"":String(e.isWatermark)),Po("text-body","Text Body",e.textBody),_a(e.geometry),Ua(e.transform),Za(e.groupTransform??null),Ga(e.fill),Xa(e.stroke),$a(e.effects??null),WB(e.anchor),Ya(e.connector),Ja(e.picture),Qa(e.wordArt),...e.children.map(t=>Mm(t))]}function zr(e){return T("shape-child","Child Object",[w("kind","Kind",e),w("id","Id",""),w("label","Label",""),Po("text-body","Text Body",null),_a(null),Ua(null),Za(null),Ga(null),Xa(null),$a(null),Ya(null),Ja(null),Qa(null)])}function KB(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function _B(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function UB(){return[{label:"Child Shape",createEntry:()=>zr("shape")},{label:"Child Group",createEntry:()=>zr("group")},{label:"Text Box",createEntry:()=>zr("textBox")},{label:"Connector",createEntry:()=>zr("connector")},{label:"Picture",createEntry:()=>zr("picture")},{label:"WordArt",createEntry:()=>zr("wordArt")}]}function tl(e={}){let t=KB(e.containerKey),r=_B(e.childKeys),o=(t==null||t==="shape-child")&&!r.has("text-body");return t==="text-body"?[{label:"Paragraph",createEntry:()=>w("paragraph","Paragraph","")}]:t!=null&&t!=="shape-child"?[]:[...o?[{label:"Text Body",createEntry:()=>Wi("text-body","Text Body")}]:[],...UB()]}import{normalizeOoxmlShapeModel as ZB}from"@datalking/begonia-engine";function GB(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Im(e){return{kind:H(C(e,"kind"))??"unknown",color:H(C(e,"color")),secondaryColor:H(C(e,"secondary-color")),opacity:oe(C(e,"opacity")),gradientAngle:oe(C(e,"gradient-angle")),gradientPath:H(C(e,"gradient-path")),patternPreset:H(C(e,"pattern-preset")),styleRefIndex:oe(C(e,"style-ref-index")),colorSource:Pe(C(e,"color-source-json")),secondaryColorSource:Pe(C(e,"secondary-color-source-json")),gradientStops:Pe(C(e,"gradient-stops-json"))??[],pictureFill:Pe(C(e,"picture-fill-json"))}}function Am(e){return{kind:H(C(e,"kind"))??"unknown",color:H(C(e,"color")),widthEmu:oe(C(e,"width-emu")),dash:H(C(e,"dash")),cap:H(C(e,"cap")),join:H(C(e,"join")),opacity:oe(C(e,"opacity")),styleRefIndex:oe(C(e,"style-ref-index")),compound:H(C(e,"compound")),colorSource:Pe(C(e,"color-source-json")),headEnd:Pe(C(e,"head-end-json")),tailEnd:Pe(C(e,"tail-end-json"))}}function Nm(e){return{styleRefIndex:oe(C(e,"style-ref-index")),styleRefColorSource:Pe(C(e,"style-ref-color-source-json")),effectNodes:Pe(C(e,"effect-nodes-json"))??[],glow:Pe(C(e,"glow-json")),outerShadow:Pe(C(e,"outer-shadow-json")),innerShadow:Pe(C(e,"inner-shadow-json")),softEdge:Pe(C(e,"soft-edge-json")),blur:Pe(C(e,"blur-json")),reflection:Pe(C(e,"reflection-json")),presetShadow:Pe(C(e,"preset-shadow-json")),effectDag:Pe(C(e,"effect-dag-json"))}}function Dm(e){let t=Te(e,"geometry");return t?{preset:H(C(t.children,"preset")),customPathCount:oe(C(t.children,"custom-path-count")),adjustments:GB(C(t.children,"adjustments")),customGeometry:Pe(C(t.children,"custom-geometry-json"))}:null}function Om(e){let t=Te(e,"transform");return t?{widthEmu:oe(C(t.children,"width-emu")),heightEmu:oe(C(t.children,"height-emu")),offsetXEmu:oe(C(t.children,"offset-x-emu")),offsetYEmu:oe(C(t.children,"offset-y-emu")),rotation:oe(C(t.children,"rotation")),flipH:fe(C(t.children,"flip-h")),flipV:fe(C(t.children,"flip-v"))}:null}function jm(e){let t=Te(e,"group-transform");return t?{childOffsetXEmu:oe(C(t.children,"child-offset-x-emu")),childOffsetYEmu:oe(C(t.children,"child-offset-y-emu")),childWidthEmu:oe(C(t.children,"child-width-emu")),childHeightEmu:oe(C(t.children,"child-height-emu"))}:null}function Vm(e){let t=Te(e,"connector");return t?{connectorType:H(C(t.children,"connector-type")),beginShapeId:H(C(t.children,"begin-shape-id")),endShapeId:H(C(t.children,"end-shape-id"))}:null}function Lm(e){let t=Te(e,"picture");if(!t)return null;let r=H(C(t.children,"hyperlink-url"));return{src:H(C(t.children,"src")),alt:H(C(t.children,"alt")),title:H(C(t.children,"title")),relationshipId:H(C(t.children,"relationship-id")),blipFill:Pe(C(t.children,"blip-fill-json")),hyperlink:r?{url:r,tooltip:H(C(t.children,"hyperlink-tooltip"))}:null}}function Fm(e){let t=Te(e,"word-art");return t?{text:H(C(t.children,"text")),preset:H(C(t.children,"preset"))}:null}function zm(e){return qi(pt(e,"text-body")[0]??null)}function XB(e){let t=Te(e,"anchor");return t?{kind:H(C(t.children,"kind"))??"unknown",wrap:H(C(t.children,"wrap"))??"unknown",behindDoc:fe(C(t.children,"behind-doc")),allowOverlap:fe(C(t.children,"allow-overlap")),layoutInCell:fe(C(t.children,"layout-in-cell")),relativeHeight:oe(C(t.children,"relative-height")),distTopEmu:oe(C(t.children,"dist-top-emu")),distBottomEmu:oe(C(t.children,"dist-bottom-emu")),distLeftEmu:oe(C(t.children,"dist-left-emu")),distRightEmu:oe(C(t.children,"dist-right-emu")),positionH:H(C(t.children,"position-h")),positionV:H(C(t.children,"position-v")),offsetXEmu:oe(C(t.children,"offset-x-emu")),offsetYEmu:oe(C(t.children,"offset-y-emu")),alignH:H(C(t.children,"align-h")),alignV:H(C(t.children,"align-v"))}:null}function $B(e){return e==="shape"||e==="group"||e==="textBox"||e==="connector"||e==="picture"||e==="wordArt"}function Hm(e){let t=Te(e,"fill"),r=Te(e,"stroke"),o=Te(e,"effects"),n=C(e,"kind");return{kind:$B(n)?n:"unknown",id:H(C(e,"id")),label:H(C(e,"label")),textBody:zm(e),geometry:Dm(e),transform:Om(e),groupTransform:jm(e),fill:t?Im(t.children):null,stroke:r?Am(r.children):null,effects:o?Nm(o.children):null,connector:Vm(e),picture:Lm(e),wordArt:Fm(e),children:pt(e,"shape-child").map(i=>Hm(i.children))}}function rl(e,t){let r=Te(e,"fill"),o=Te(e,"stroke"),n=Te(e,"effects");return ZB({...t,label:H(C(e,"label")),shapeType:H(C(e,"shape-type")),groupKind:H(C(e,"group-kind")),isWatermark:fe(C(e,"is-watermark")),textBody:zm(e),geometry:Dm(e),transform:Om(e),groupTransform:jm(e),fill:r?Im(r.children):null,stroke:o?Am(o.children):null,effects:n?Nm(n.children):null,anchor:XB(e),connector:Vm(e),picture:Lm(e),wordArt:Fm(e),children:pt(e,"shape-child").map(i=>Hm(i.children))},t.label??"Shape")}function ol(e){let t=String(e.attrs.label??"Shape"),r=String(e.attrs.text??""),o=qm("shape",{label:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=qm("shape",e.attrs.familyData,{label:t,text:r})??o;return{objectId:String(e.attrs.objectId??""),label:t,model:n.data.model??o.data.model,evidence:n.evidence}}function JB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function QB(){let e=document.createElement("div");return Object.assign(e.style,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"84px",padding:"12px",borderRadius:"12px",background:"linear-gradient(180deg, #ffffff, #f8fafc)",border:"1px solid #e2e8f0"}),e}function ex(e,t,r,o){let n=YB(o,{idPrefix:t||r,maxWidth:280,maxHeight:180});return e.dataset.previewKind=n.kind,e.dataset.previewSupported=String(n.supported),e.innerHTML=n.svg,n}function Wm(){return e=>{let t=e,r=yo("div"),{header:o,heading:n}=bo("Shape","shape"),i=Bo(),{section:s}=Fr("Visual Preview"),a=zt("Preview uses begonia\u2019s clean-room SVG geometry renderer for preset, connector, group, and custom-path shape families."),l=QB(),{section:c}=Fr("Native Subtree"),d=zt("Edit the shape object graph, text boxes, connector data, pictures, and child objects in a nested ProseMirror subtree. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),u=or();u.style.justifyContent="flex-start";let m=_e("Remove Selected","danger"),p=JB(),f=or();f.style.justifyContent="space-between",f.style.alignItems="center";let g=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),v=_e("Apply"),E=_e("Remove Shape","danger");g.style.marginRight="auto",f.append(g,v,E),s.append(a,l),c.append(d,u,p,m),r.append(o,i,s,c,f);let R=null,S=(x,A)=>{u.replaceChildren(),tl({containerKey:x,childKeys:A}).forEach(O=>{let j=_e(O.label);j.addEventListener("click",()=>{P.appendEntry(O.createEntry())}),u.append(j)})},P=Co(p,[],{onChange(){R?.markDirty()},onSelectionChange(x){S(x.containerKey,x.childKeys)}});m.addEventListener("click",()=>{P.removeSelectedEntry()}),R=ho({applyButton:v,onCommit:()=>{let x=ol(t),A=rl(P.readEntries(),x.model),O=Em(x.model,A);return O.length===0?!1:(rr(r,{family:"shape",action:"apply-shape-edits",objectId:x.objectId,model:A,edits:O}),!0)},root:r,status:g});let b=x=>{t=x;let A=ol(x);n.textContent=A.label;let O=ex(l,A.objectId,A.label,A.model);i.textContent=`${A.evidence.shapeType??"shape"} | ${A.evidence.childCount} child objects | ${A.evidence.anchorKind} | preview ${O.kind}${O.supported?"":" fallback"}`,R?.reset(),P.setEntries(el(A.model))};return v.addEventListener("click",()=>{R?.flush()}),E.addEventListener("click",()=>{R?.reset();let x=ol(t);rr(r,{family:"shape",action:"remove-advanced-ooxml",objectId:x.objectId})}),b(e),{dom:r,destroy(){R?.destroy(),P.destroy()},update(x){return x.type!==t.type?!1:(b(x),!0)},stopEvent(x){return xo(x.target)||x.target instanceof Node&&p.contains(x.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{inlineOoxmlDrawingMetadata as tx}from"@datalking/begonia-editor-adapters";function Km(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function rx(){let e=document.createElement("span");return e.contentEditable="false",e.className="ald-editor-inline-drawing",Object.assign(e.style,{display:"inline-block",boxSizing:"border-box",margin:"0 2px",lineHeight:"0",maxWidth:"100%",verticalAlign:"baseline"}),e}function _m(e,t){let r=tx(t),o=r?.label||String(t.attrs.label??"Drawing"),n=r?.family??(t.attrs.family==="chart"?"chart":"shape"),i=r?.drawing,s=Km(r?.width??i?.width,80),a=Km(r?.height??i?.height,40);if(e.dataset.family=n,e.dataset.objectId=r?.objectId??String(t.attrs.objectId??""),e.setAttribute("aria-label",o),e.title=o,e.style.width=`${s}px`,e.style.height=`${a}px`,e.style.border=i?"0":"1px solid #94a3b8",e.style.background=i?"transparent":"#f8fafc",!i?.svg){e.replaceChildren();let c=document.createElement("span");c.textContent=o,Object.assign(c.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"#334155",fontSize:"12px",lineHeight:"1.2",overflow:"hidden"}),e.append(c);return}e.innerHTML=i.svg;let l=e.querySelector("svg");l&&(l.setAttribute("width","100%"),l.setAttribute("height","100%"),l.setAttribute("aria-hidden","true"),Object.assign(l.style,{display:"block"}))}function Um(){return e=>{let t=e,r=rx();return _m(r,e),{dom:r,update(o){return o.type!==t.type?!1:(t=o,_m(r,o),!0)},ignoreMutation(){return!0},selectNode(){r.style.outline="2px solid #0f766e",r.style.outlineOffset="2px"},deselectNode(){r.style.outline="",r.style.outlineOffset=""}}}}var nl="browser-advanced-ooxml-nodeviews";function Zm(){return{id:nl,createPlugins(){return[]},createNodeViews(){return{ooxml_math:xm(),ooxml_chart:Sm(),ooxml_shape:Wm(),inline_ooxml_drawing:Um()}}}}function _i(e=[]){return e.some(t=>t.id===nl)?[...e]:[...e,Zm()]}import{createEditorSessionController as Sj}from"@datalking/begonia-editor-ui";function il(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}function Ro(e){return typeof e=="object"&&e!==null}function sl(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.text!="string"?null:{text:e.text,displayMode:e.displayMode==="block"?"block":e.displayMode==="inline"?"inline":void 0}}function Gm(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.title!="string"?null:{title:e.title}}function Xm(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.color!="string"?null:{color:e.color,kind:e.kind==="solid"||e.kind==="scheme"||e.kind==="none"||e.kind==="unknown"?e.kind:void 0}}function $m(e,t=0){if(typeof e=="string")return{id:null,name:e.trim()||`Series ${t+1}`,categories:[],values:[],color:null};if(!Ro(e))return{id:null,name:`Series ${t+1}`,categories:[],values:[],color:null};let r=Array.isArray(e.categories)?e.categories.filter(n=>typeof n=="string"):[],o=Array.isArray(e.values)?e.values.map(n=>typeof n=="number"&&Number.isFinite(n)?n:null):[];return{id:typeof e.id=="string"?e.id:null,name:typeof e.name=="string"?e.name:`Series ${t+1}`,categories:r,values:o,color:typeof e.color=="string"?e.color:null}}function Ym(e,t=0){return typeof e=="string"?{id:null,kind:"category",title:e.trim()||`Axis ${t+1}`,formatCode:null}:Ro(e)?{id:typeof e.id=="string"?e.id:null,kind:e.kind==="category"||e.kind==="value"||e.kind==="series"||e.kind==="date"?e.kind:"category",title:typeof e.title=="string"?e.title:`Axis ${t+1}`,formatCode:typeof e.formatCode=="string"?e.formatCode:null}:{id:null,kind:"category",title:`Axis ${t+1}`,formatCode:null}}function Jm(e,t=0){if(typeof e=="string"){let o=e.trim()||`Child ${t+1}`;return{parentId:null,child:{label:o,kind:"shape",text:o,shapeType:"shape"}}}if(!Ro(e)){let o=`Child ${t+1}`;return{parentId:null,child:{label:o,kind:"shape",text:o,shapeType:"shape"}}}let r=typeof e.label=="string"&&e.label.trim()?e.label.trim():`Child ${t+1}`;return{parentId:typeof e.parentId=="string"&&e.parentId.trim()?e.parentId:null,child:{label:r,kind:e.kind==="shape"||e.kind==="group"||e.kind==="textBox"||e.kind==="connector"||e.kind==="picture"||e.kind==="wordArt"?e.kind:"shape",text:typeof e.text=="string"?e.text:r,shapeType:typeof e.shapeType=="string"?e.shapeType:"shape"}}}function Ue(e){return e?e.surface??null:null}function ve(e){let t=Ue(e);if(!t)throw new Error("Browser editor surface is not available on this controller.");return t}function ox(e,t=!0){return{ok:!0,changed:t,value:e}}function st(e){return{ok:!1,changed:!1,reason:e}}function ft(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?st(e.reason):ox(e)}function En(e){return typeof e=="object"&&e!==null}function nx(e){return e==="block"?"block":"inline"}function al(e){return{chartType:"barChart",styleId:null,styleSource:null,title:e,subtitle:null,series:[],axes:[],legend:null,plotArea:null,textBody:{paragraphs:[e],plainText:e}}}function ll(e){return{shapeType:"shape",label:e,textBody:{paragraphs:[e],plainText:e},geometry:null,transform:null,groupTransform:null,fill:null,stroke:null,anchor:null,connector:null,picture:null,wordArt:null,childCount:0,children:[],groupKind:null,isWatermark:null}}function ix(e,t){return{id:e.id??null,order:t,name:e.name??`Series ${t+1}`,categories:e.categories??[],values:e.values??[],color:e.color??null,marker:null,dataLabels:null,smooth:null,explosion:null}}function sx(e,t){return{id:e.id??null,kind:e.kind??"category",title:e.title??`Axis ${t+1}`,formatCode:e.formatCode??null,orientation:null,visible:null,minimum:null,maximum:null,majorUnit:null,minorUnit:null,crossesAt:null,majorGridlines:null,minorGridlines:null}}function ax(e,t){let r=e.text?.trim()||e.label?.trim()||`Child ${t+1}`;return{kind:e.kind??"shape",id:null,label:e.label??r,textBody:{paragraphs:il(r),plainText:r},geometry:e.shapeType?{preset:e.shapeType,customPathCount:null,adjustments:[]}:null,transform:null,groupTransform:null,fill:null,stroke:null,connector:e.kind==="connector"?{connectorType:e.shapeType??null,beginShapeId:null,endShapeId:null}:null,picture:null,wordArt:e.kind==="wordArt"?{text:r,preset:e.shapeType??null}:null,children:[]}}function lx(e){if(typeof e=="string"){let r=e.trim();return r?{text:r,displayMode:"inline",label:null}:null}if(!En(e)||typeof e.text!="string")return null;let t=e.text.trim();return t?{text:t,displayMode:e.displayMode==="block"?"block":"inline",label:typeof e.label=="string"?e.label:null}:null}function cx(e){if(typeof e=="string"){let o=e.trim()||"Chart";return{model:al(o),options:{label:o}}}if(!En(e))return{model:al("Chart"),options:{label:"Chart"}};let t=typeof e.title=="string"&&e.title.trim()?e.title.trim():"Chart";return{model:En(e.model)?e.model:al(t),options:{label:typeof e.label=="string"?e.label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function dx(e){if(typeof e=="string"){let o=e.trim()||"Shape";return{model:ll(o),options:{label:o}}}if(!En(e))return{model:ll("Shape"),options:{label:"Shape"}};let t=typeof e.label=="string"&&e.label.trim()?e.label.trim():"Shape";return{model:En(e.model)?e.model:ll(t),options:{label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function Qm(e){let t=e.getState().advancedOoxml.selected;return t?.family==="chart"?e.documentApi.ooxml.charts.getById(t.objectId):null}function ux(e){let t=e.getState().advancedOoxml.selected;return t?.family==="math"?e.documentApi.ooxml.math.getById(t.objectId):null}function mx(e){let t=e.getState().advancedOoxml.selected;return t?.family==="shape"?e.documentApi.ooxml.shapes.getById(t.objectId):null}function ep(e,t,r){let o=ve(e);switch(t){case"insert-math-inline":{let n=lx(r);if(!n)return st("Expected inline math text for advanced OOXML insertion.");let i=e.documentApi.ooxml.math.createModelFromText(n.text,n.displayMode),s=o.trackingEnabled?e.appendMathToCurrentTextblockTracked(i,{source:"browser-ooxml"},{label:n.label??n.text}):e.appendMathToCurrentTextblock(i,{label:n.label??n.text});return ft(s)}case"insert-chart-block":{let n=cx(r),i=o.trackingEnabled?e.insertChartAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertChartAfterCurrentBlock(n.model,n.options);return ft(i)}case"insert-shape-block":{let n=dx(r),i=o.trackingEnabled?e.insertShapeAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertShapeAfterCurrentBlock(n.model,n.options);return ft(i)}case"remove-selected-ooxml":return ft(e.removeSelectedAdvancedOoxml());case"selected-math-set-plain-text":{let n=sl(r);if(!n)return st("Expected math plain text for the selected OOXML equation.");let i=typeof n=="string"?e.setSelectedMathPlainText(n):e.setSelectedMathPlainText(n.text,n.displayMode);return ft(i)}case"selected-math-toggle-display-mode":{let n=ux(e);if(!n)return st("No advanced OOXML math node is selected.");let i=nx(n.familyData?.displayMode)==="block"?"inline":"block";return ft(e.setSelectedMathDisplayMode(i))}case"selected-chart-set-title":{let n=Gm(r);return n?ft(e.setSelectedChartTitle(typeof n=="string"?n:n.title)):st("Expected a chart title for the selected OOXML chart.")}case"selected-chart-add-series":{let n=Qm(e);if(!n)return st("No advanced OOXML chart node is selected.");let i=$m(r,n.familyData?.model?.series.length??0);return i?ft(e.appendSelectedChartSeries(ix(i,n.familyData?.model?.series.length??0))):st("Expected a series payload for the selected OOXML chart.")}case"selected-chart-add-axis":{let n=Qm(e);if(!n)return st("No advanced OOXML chart node is selected.");let i=Ym(r,n.familyData?.model?.axes.length??0);return i?ft(e.appendSelectedChartAxis(sx(i,n.familyData?.model?.axes.length??0))):st("Expected an axis payload for the selected OOXML chart.")}case"selected-shape-set-text-body":{let n=sl(r);if(!n)return st("Expected replacement text for the selected OOXML shape.");let i=typeof n=="string"?n:n.text;return ft(e.setSelectedShapeTextBody(il(i)))}case"selected-shape-set-fill":{let n=Xm(r);if(!n)return st("Expected a fill color for the selected OOXML shape.");let i=e.setSelectedShapeFill(typeof n=="string"?{kind:"solid",color:n.trim()||null,secondaryColor:null,opacity:null}:{kind:n.kind??"solid",color:n.color.trim()||null,secondaryColor:null,opacity:null});return ft(i)}case"selected-shape-add-child":{let n=mx(e);if(!n)return st("No advanced OOXML shape node is selected.");let i=Jm(r,n.familyData?.model?.children.length??0);if(!i)return st("Expected a child payload for the selected OOXML shape.");let s=ax(i.child,n.familyData?.model?.children.length??0);return ft(i.parentId?e.appendSelectedShapeChildToParent(i.parentId,s):e.appendSelectedShapeChild(s))}default:return null}}import{resolveCollapsedSelectionFormattingMarks as TP}from"@datalking/begonia-engine";import{addressableBlockTypeForNodeType as yp,formatAddressableBlockId as mC,formatAddressableBlockIdWithLogicalId as bp}from"@datalking/begonia-doc-service/structure";import{normalizeDocumentStoryLocator as pC,readSyntheticSideStoryDocOriginPath as fC,readSyntheticSideStoryDocStoryLocator as wC}from"@datalking/begonia-doc-service/v1";import{hasVisibleSemanticContent as gC}from"@datalking/begonia-engine";function cl(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function Hr(e,t){return e==="listItem"?cl(t.attrs?.listItemId):e==="paragraph"||e==="heading"?cl(t.attrs?.paraId)??cl(t.attrs?.sdBlockId):null}import{DELETION_MARK_NAME as fx,INSERTION_MARK_NAME as wx,collectRevisionSpans as gx,createRevisionGroupingContext as Sx,listSelectionRevisionRanges as vx,logicalRevisionIdForRange as hx,resolveParagraphLikeBlockInlineRangeAtPath as yx}from"@datalking/begonia-engine";import{groupLogicalRevisions as bx}from"@datalking/begonia-doc-service/v1";import{orderOverlapRevisionIds as px}from"@datalking/begonia-engine";function Mn(e,t){return px(e,t)}function tp(e){return e.threadId}function Ui(e){return`${e.threadId}\0${e.entryId}`}function rp(e,t){let r=Math.min(e,t),o=Math.max(e,t),n=r===o;return{start:r,selectionEnd:n?o+1:o,collapsed:n}}function Bx(e,t){return t<e.selectionEnd&&t+1>e.start}function op(e,t,r){return t<e.selectionEnd&&r>e.start}function dl(e,t,r,o={}){let n=o.includeLeadingBoundary??!0,i=o.includeTrailingBoundary??!0,s=n&&e.collapsed&&r>t&&e.start+1===t,a=i&&e.collapsed&&r>t&&e.start===r;return op(e,t,r)||s||a}function xx(e){return e.marks.some(t=>t.type.name===wx||t.type.name===fx)}function Cx(e,t){return t.target?.nodeType!=="bookmark_anchor"&&t.target?.nodeType!=="structural_revision_carrier"||(t.text??"").length>0||!t.target.blockPath.length?null:yx(e,t.target.blockPath)}function Px(e,t){if(e.type.name!=="comment_range_start"&&e.type.name!=="comment_range_end"&&e.type.name!=="comment_anchor")return null;let r=typeof e.attrs.threadId=="string"?e.attrs.threadId.trim():"";if(r.length===0)return null;let o=typeof e.attrs.entryId=="string"?e.attrs.entryId.trim():"";return{threadId:r,entryId:o||r,kind:e.type.name==="comment_range_start"?"start":e.type.name==="comment_range_end"?"end":"anchor",pos:t,tracked:xx(e)}}function Rx(e){let t=[];return e.nodesBetween(0,e.content.size,(r,o)=>{let n=Px(r,o);return n&&t.push(n),!0}),t}function ul(e,t,r){let o=e.get(t)??[];o.push(r),e.set(t,o)}function Tx(e,t){let r=Ui(t),o=e.get(r)??{hasStart:!1,hasEnd:!1};t.kind==="start"&&(o.hasStart=!0),t.kind==="end"&&(o.hasEnd=!0),e.set(r,o)}function kx(e,t,r){return(e.get(Ui(r))??[]).find(o=>o.pos>=r.pos&&!t.has(o))??null}function Ex(e,t,r){let o=e.get(Ui(r))??[];for(let n=o.length-1;n>=0;n-=1){let i=o[n];if(i&&i.pos<=r.pos&&!t.has(i))return i}return null}function Mx(e,t){let r=rp(t.from,t.to),o=Rx(e),n=new Set,i=new Map,s=new Map,a=new Map,l=new Map,c=new Set;for(let d of o){if(Tx(l,d),d.kind==="anchor"){ul(a,Ui(d),d);continue}if(d.kind==="start"){ul(i,tp(d),d);continue}let u=tp(d),m=i.get(u)??[],p=m.pop()??null;if(m.length>0?i.set(u,m):i.delete(u),!p){ul(s,u,d);continue}dl(r,p.pos+1,d.pos,{includeLeadingBoundary:!p.tracked,includeTrailingBoundary:!d.tracked})&&n.add(p.threadId)}for(let d of i.values())for(let u of d){let m=kx(a,c,u);m&&(c.add(m),dl(r,u.pos+1,m.pos,{includeLeadingBoundary:!u.tracked,includeTrailingBoundary:!m.tracked})&&n.add(u.threadId))}for(let d of s.values())for(let u of d){let m=Ex(a,c,u);m&&(c.add(m),dl(r,m.pos,u.pos,{includeLeadingBoundary:!m.tracked,includeTrailingBoundary:!u.tracked})&&n.add(u.threadId))}for(let[d,u]of a){let m=l.get(d);if(!(m?.hasStart||m?.hasEnd))for(let p of u)!p.tracked&&Bx(r,p.pos)&&n.add(p.threadId)}return[...n]}function Ix(e,t){let r=gx(e.doc,e.schema),o=Sx(r),n=new Set;for(let i of vx(e)){let s=Cx(e.doc,i);(!s||op(rp(e.selection.from,e.selection.to),s.from,s.to))&&n.add(hx(i,o,t))}return Mn([...n],bx(r,t))}function np(e,t={}){return{activeCommentIds:Mx(e.doc,e.selection),activeChangeIds:Ix(e,t.reviewReplacementMode??"paired")}}import{DELETION_MARK_NAME as Nx}from"@datalking/begonia-engine";import{isDocumentNodePathIndex as Dx}from"@datalking/begonia-document-model";import{NodeSelection as Ax}from"prosemirror-state";function K(e){return e instanceof Ax||typeof e=="object"&&e!=null&&"node"in e&&e.node!=null&&"from"in e&&typeof e.from=="number"&&"to"in e&&typeof e.to=="number"&&"$from"in e&&e.$from!=null}function Zi(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function ze(e){return t=>Zi(t.attrs[e])}function ip(...e){return t=>{for(let r of e){let o=Zi(t.attrs[r]);if(o)return o}return null}}function ml(e){let t=Zi(e.attrs.threadId);return t?`${t}\0${Zi(e.attrs.entryId)??t}`:null}function sp(){return null}function ap(e){return e==="paragraph"||e==="heading"}function To(e,t){return e===t||ap(e)&&ap(t)}var pl=Object.freeze({bookmark_anchor:ze("bookmarkId"),bookmark_end:ze("bookmarkId"),comment_anchor:ml,comment_range_end:ml,comment_range_start:ml,column_break:ze("columnBreakId"),endnote_reference:ze("noteId"),heading:ip("paraId","sdBlockId","captionId"),horizontal_rule:sp,image:ze("imageId"),inline_ooxml_drawing:ze("objectId"),ooxml_chart:ze("objectId"),ooxml_math:ze("objectId"),ooxml_shape:ze("objectId"),page_break:ze("pageBreakId"),paragraph:ip("paraId","sdBlockId","captionId"),footnote_reference:ze("noteId"),permission_range_end:ze("rangeId"),permission_range_start:ze("rangeId"),section_break:ze("sectionId"),table:sp,template_block:ze("fieldId"),template_field:ze("fieldId")});function Ox(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function qr(e){try{return Ox(JSON.stringify(e.toJSON()))}catch{return null}}function cp(e,t){let r=e,o=-1;for(let n of t){if(!Dx(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function jx(e,t,r,o,n,i){if(i==null)return null;let s=!1,a=!1;return e.descendants((l,c)=>c===o||!To(l.type.name,t)||n(l)!==r?!0:(s=!0,qr(l)===i?(a=!0,!1):!0)),s&&!a?i:null}function lp(e,t,r){let o=cp(e,t.path);return!o||!To(o.node.type.name,t.nodeType)||r(o.node)!==t.stableIdentity||t.nodeFingerprint!=null&&qr(o.node)!==t.nodeFingerprint?null:o}function Vx(e,t,r){let o=[];return e.descendants((n,i)=>(To(n.type.name,t.nodeType)&&r(n)===t.stableIdentity&&o.push({node:n,position:i}),!0)),o}function Lx(e,t){return t.nodeFingerprint==null?[]:e.filter(r=>qr(r.node)===t.nodeFingerprint)}function dp(e){return!!e?.node.marks.some(t=>t.type.name===Nx)}function Fx(e){return e.filter(t=>!dp(t))}function Ie(e){let t=e?.selection;if(!e||!K(t))return null;let r=t.node.type.name,o=r?pl[r]:null;if(!r||!o)return null;let n=o(t.node),i=[];for(let l=0;l<t.$from.depth;l+=1)i.push(t.$from.index(l));i.push(t.$from.index(t.$from.depth));let s=qr(t.node),a=n?jx(e.doc,r,n,t.from,o,s):s;return{kind:"node",nodeType:r,stableIdentity:n,path:i,...a!=null?{nodeFingerprint:a}:{}}}function Gi(e,t){let r=pl[t.nodeType];if(t.stableIdentity&&r){let i=Vx(e,t,r);if(i.length===0)return null;if(i.length===1){let l=i[0];return t.nodeFingerprint==null||lp(e,t,r)?.position===l.position||qr(l.node)===t.nodeFingerprint?l:null}let s=lp(e,t,r);if(t.nodeFingerprint==null){if(!dp(s))return s;let l=Fx(i);return l.length===1?l[0]:s}let a=Lx(i,t);return a.length!==1?null:s?.position===a[0]?.position?s:null}let o=cp(e,t.path);if(o!=null&&To(o.node.type.name,t.nodeType)&&(t.nodeFingerprint==null||qr(o.node)===t.nodeFingerprint))return o;if(t.nodeFingerprint==null)return null;let n=[];return e.descendants((i,s)=>(To(i.type.name,t.nodeType)&&qr(i)===t.nodeFingerprint&&n.push({node:i,position:s}),n.length<=1)),n.length===1?n[0]:null}function up(e,t,r){if(!r.empty||!t.stableIdentity)return!1;let o=pl[t.nodeType];if(!o)return!1;let n=!1;return e.descendants((i,s)=>To(i.type.name,t.nodeType)&&o(i)===t.stableIdentity&&r.from>=s&&r.from<=s+i.nodeSize?(n=!0,!1):!0),n}import{hasVisibleSemanticContent as zx}from"@datalking/begonia-document-model";function Xi(e){return[...new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0))]}function Hx(e,t){let r=e?.selection;return t!=null&&K(r)&&r.node.isInline&&r.node.isLeaf&&zx(r.node)}function fl(e,t,r=!1){return t!=="node"||e.target==null||r||Xi(e.activeChangeIds).length>0?e:{...e,target:null}}function ko(e,t,r){let o=Ie(e??null);return fl(t,r,r==="node"&&t.target!=null&&Hx(e,o))}import{projectAcceptedTextBetween as rC}from"@datalking/begonia-engine";import{createDocumentNoteAwareTextOffsetOptions as qx}from"@datalking/begonia-doc-service/v1";function se(e,t={}){return qx(e,t)}import{pmPositionToAddressableTextOffset as Wx,readAddressableText as Kx,resolveAddressableTextOffsetPosition as _x,resolveAddressableTextOffsetRange as Ux,resolveCollapsedAddressableTextOffsetPosition as Zx}from"@datalking/begonia-document-model";function In(e){return{includeDeletedText:!0,...e}}function Br(e,t={}){return Kx(e,In(t))}function we(e,t,r,o={}){return Wx(e,t,r,In(o))}function He(e,t,r,o="end",n={}){return _x(e,t,r,o,In(n))}function mp(e,t,r,o,n={}){return Ux(e,t,r,o,In(n))}function Eo(e,t,r,o={}){return Zx(e,t,r,In(o))}import{semanticNodeText as $x}from"@datalking/begonia-document-model";import{isRevisionMarkHiddenInProjection as Gx,isRevisionNodeHiddenInProjection as Xx}from"@datalking/begonia-engine";function pp(e,t){return Gx(e,t)}function wt(e,t,r=!1){return Xx(e,t,r)}function Yx(e,t){return wt(e,"final",t)}function wp(e,t){let r=$x(e),o=t?.resolveLeafText?.(e,r);return typeof o=="string"?o:r}function Jx(e,t,r){return r?"":wp(e,t)}function Qx(e,t){return t?"":e.text??""}function fp(e,t){return e.isText?(e.text??"").length:e.childCount===0?wp(e,t).length:0}function eC(e,t,r,o,n,i,s){if(o.length===0)return r;t.push(o);let a=r+o.length;return e.push({atomic:s,text:o,startOffset:n,endOffset:i,visibleStart:r,visibleEnd:a}),a}function wl(e,t){let r=[],o=[],n=t?.blockSeparator??"",i=0,s=0,a=(c,d,u=!1)=>{let m=i,p=m+d;s=eC(r,o,s,c,m,p,u),i=p},l=(c,d=!1)=>{let u=Yx(c,d);if(c.isText){let p=fp(c,t);a(Qx(c,u),p);return}if(c.childCount===0){let p=fp(c,t);a(Jx(c,t,u),p,!0);return}let m=!0;c.forEach(p=>{p.isBlock&&!m&&n.length>0&&a(n,n.length),l(p,u&&c.isInline),m=!1})};return l(e),{runs:r,text:o.join(""),maxOffset:i}}function tC(e,t,r,o){if(!Number.isInteger(r))return 0;if(r<=0)return o==="start"?e[0]?.startOffset??0:0;for(let[n,i]of e.entries()){if(r<i.visibleStart)return i.startOffset;if(r>i.visibleEnd)continue;if(r===i.visibleEnd){let l=e[n+1];return o==="start"&&l&&l.visibleStart===r?l.startOffset:i.endOffset}let s=i.visibleEnd-i.visibleStart,a=i.endOffset-i.startOffset;return i.atomic?o==="end"&&r>i.visibleStart?i.endOffset:i.startOffset:a===s?i.startOffset+(r-i.visibleStart):o==="end"&&r>i.visibleStart?i.endOffset:i.startOffset}return t}function Mo(e,t={}){let{text:r,maxOffset:o}=wl(e,t);return{text:r,maxOffset:o}}function Io(e,t,r="end",o={}){let{runs:n,text:i,maxOffset:s}=wl(e,o);return!Number.isInteger(t)||t<0||t>i.length?null:tC(n,s,t,r)}function nr(e,t,r="end",o={}){let{runs:n}=wl(e,o);if(!Number.isInteger(t)||t<=0)return 0;let i=0;for(let s of n){if(t<=s.startOffset)return i;if(t<=s.endOffset)return s.atomic&&t<s.endOffset?r==="end"?s.visibleEnd:s.visibleStart:s.visibleStart+(t-s.startOffset);i=s.visibleEnd}return i}var oC=Object.freeze({blockSeparator:" "});function nC(e){return e.empty??e.from===e.to}function iC(e,t){let r=Math.max(0,e.content.size),o=Math.min(r,Math.max(0,Math.min(t.from,t.to))),n=Math.min(r,Math.max(o,Math.max(t.from,t.to))),i=se(e,oC),s=[],a=!1;return e.nodesBetween(o,n,(l,c)=>{if(!l.isTextblock)return!0;a=!0;let d=Math.max(o,c+1),u=Math.min(n,c+l.nodeSize-1),m=we(l,c,d,i),p=Math.max(m,we(l,c,u,i)),f=Mo(l,i),g=nr(l,m,"start",i),v=nr(l,p,"end",i);return s.push(f.text.slice(Math.min(g,v),Math.max(g,v))),!1}),a?s.join(" "):null}function ge(e,t,r){return nC(r)?"":iC(e,r)??rC(e,t,Math.min(r.from,r.to),Math.max(r.from,r.to)," ")}function gp(e){return[...new Set(e)]}function An(e){return JSON.stringify([e.empty,e.target??null,[...new Set(e.activeMarks)].sort(),gp(e.activeCommentIds),gp(e.activeChangeIds),e.text??null])}import{hasVisibleSemanticContent as vp,isInlineFormatMarkEnabled as sC}from"@datalking/begonia-document-model";var aC=new Set(["strong","em","underline","strike"]);function $i(e,t){for(let r of t){if(aC.has(r.type.name)&&!sC(r)){e.delete(r.type.name);continue}e.add(r.type.name)}}function lC(e){let t=new Set;return $i(t,e),t}function Sp(e,t){let r=new Set(e);return $i(r,t.marks),r}function hp(e){return e.isInline&&!e.isText&&vp(e)}function cC(e){return e.isText||e.isInline&&e.isLeaf&&vp(e)}function dC(e,t){return e.isText?{start:t,end:t+(e.text?.length??0)}:{start:t,end:t+e.nodeSize}}function Yi(e,t,r){let o=null,n=(i,s,a)=>{let l=hp(i)?Sp(a,i):new Set(a);if(cC(i)){let d=dC(i,s),u=Math.max(d.start,t);if(Math.min(d.end,r)>u){let p=Sp(l,i);if(o==null)o=p;else for(let f of[...o])p.has(f)||o.delete(f)}return}if(i.childCount===0)return;let c=0;i.forEach(d=>{let u=s+1+c,m=u+d.nodeSize;c+=d.nodeSize,!(m<=t||u>=r)&&n(d,u,l)})};return n(e,-1,new Set),o??new Set}function Ji(e,t=null){if(t!=null)return lC(t);let r=new Set;for(let o=1;o<=e.depth;o+=1){let n=e.node(o);if(!hp(n))continue;let i=e.start(o),s=e.end(o);e.pos<i||e.pos>s||$i(r,n.marks)}return $i(r,e.marks()),r}import{parseAddressableBlockId as uC}from"@datalking/begonia-doc-service/structure";function Ao(e){return uC(e)?.logicalId==null}var Qi=Object.freeze({blockSeparator:`
3
- `});function SC(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function es(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=yp(r.type.name);if(o)return{type:o,path:SC(e,t),node:r,pos:e.start(t)-1}}return null}function vC(e,t,r,o){let n=e[e.length-1];if(n?.blockId===t){n.range.end=Math.max(n.range.end,o),n.range.start=Math.min(n.range.start,r);return}e.push({blockId:t,range:{start:r,end:o}})}function Bp(e,t){let r=fC(e);return r?[...r,...t]:[...t]}function Sl(e,t,r){let o=Bp(e,t.path);return r?mC(t.type,o):bp(t.type,o,Hr(t.type,t.node))}function hC(e,t=null){return e.length===0?null:{kind:"text",segments:e,...t?{story:t}:{}}}function vl(e,t,r,o,n){return Ao(e)?{start:nr(t,r,"start",n),end:nr(t,o,"end",n)}:{start:r,end:o}}function gl(e){return e.node.isLeaf&&e.node.isInline&&e.$from.parent.inlineContent&&gC(e.node)}function xp(e){let t=yp(e.node.type.name);return t==="listItem"?t:null}function yC(e){return"$anchorCell"in e?!1:K(e)?gl(e)||xp(e)!=null:!0}function bC(e,t){let r=t.$from.doc.resolve(t.from+1),o=es(r);if(!o||o.node!==t.node)return null;let n=se(e,Qi),i=Math.max(t.from,o.pos+1),s=Math.min(t.to,o.pos+o.node.nodeSize-1),a=we(o.node,o.pos,i,n),l=Math.max(a,we(o.node,o.pos,s,n)),c=Sl(e,o,!1);return[{blockId:c,range:vl(c,o.node,a,l,n)}]}function BC(e,t){let r=es(t.$from);if(!r||!r.node.isTextblock)return null;let o=se(e,Qi),n=we(r.node,r.pos,t.from,o),i=Math.max(n,we(r.node,r.pos,t.to,o)),s=Sl(e,r,!0);return[{blockId:s,range:vl(s,r.node,n,i,o)}]}function xC(e,t){let r=K(t)&&gl(t),o=se(e,Qi);if(K(t)&&gl(t)){let s=BC(e,t);if(s)return s}if(K(t)&&xp(t)){let s=bC(e,t);if(s)return s}let n=[],i=!1;return e.nodesBetween(t.from,t.to,(s,a)=>{if(i)return!1;if(!s.isTextblock)return!0;let l=e.resolve(a+1),c=es(l);if(!c)return i=!0,!1;let d=Math.max(t.from,a+1),u=Math.min(t.to,a+s.nodeSize-1),m=we(c.node,c.pos,d,o),p=Math.max(m,we(c.node,c.pos,u,o)),f=Sl(e,c,r),g=vl(f,c.node,m,p,o);return vC(n,f,g.start,g.end),!1}),i?null:n}function CC(e,t,r){return Yi(e,t,r)}function PC(e){let t=new Set,{from:r,to:o}=e.selection;if(r===o){for(let n of Ji(e.doc.resolve(r),e.storedMarks))t.add(n);return[...t]}for(let n of CC(e.doc,r,o))t.add(n);return[...t]}function RC(e,t){let{selection:r}=e,o=K(r)?Ie(e):null;return JSON.stringify([r.from,r.to,r.empty,K(r)?"node":"text",An({...t,target:t.target?{...t.target,...t.target.story?{story:pC(t.target.story)??t.target.story}:{}}:null}),K(r)?o??{nodeType:r.node.type.name,position:r.$from.pos,nodeSize:r.node.nodeSize}:null])}function Ee(e,t={},r={}){let o=t??{},n=r??{},{selection:i,doc:s}=e,a=hl(s,i),{activeCommentIds:l,activeChangeIds:c}=np(e,{reviewReplacementMode:n.reviewReplacementMode}),d={empty:i.empty,target:a,activeMarks:PC(e),activeCommentIds:l,activeChangeIds:c};return o.includeText&&!i.empty&&(d.text=ge(s,e.schema,i)),d}function hl(e,t){let r=wC(e);return yC(t)?hC(xC(e,t)??[],r):null}function Ht(e){let t=Ee(e).target;if(t)return t;if(!e.selection.empty)return null;let r=es(e.selection.$from);if(!r)return null;let o=se(e.doc,Qi),n=we(r.node,r.pos,e.selection.from,o);return{kind:"text",blockId:bp(r.type,Bp(e.doc,r.path),Hr(r.type,r.node)),range:{start:n,end:n}}}function yl(e,t={}){let r=n=>K(n.selection)?"node":"text",o=n=>{let i=e.state;return{state:i,info:ko(i,Ee(i,n,t),r(i))}};return{current(n){return o(n).info},onChange(n){let i=!1,s=!1,a=null,l=()=>{if(s=!1,i)return;let m=o({includeText:!0}),p=RC(m.state,m.info);p!==a&&(a=p,n(m.info))},c=()=>{i||s||(s=!0,queueMicrotask(l))},d;try{d=e.subscribe(c)}catch(m){throw i=!0,m}let u=!1;return()=>{u||(u=!0,i=!0,d())}}}}function TC(e){return e?.selectionKind!=="node"&&e?.selectionTarget!=null}function ir(e,t,r=null){return e?e.editable?r?.selectionKind==="node"?"Place the caret in text or select text before applying inline formatting.":TC(r)?null:t&&K(t.selection)?"Place the caret in text or select text before applying inline formatting.":t?Ht(t)?null:"Place the caret in text or select text before applying inline formatting.":r?.selectionTarget?null:"Place the caret in text or select text before applying inline formatting.":"Document is read-only in the current document mode.":"Editor is not ready."}import{createSelectionTrackingBookmark as BP}from"@datalking/begonia-engine";import{NodeSelection as as}from"prosemirror-state";import{NodeSelection as Pp,TextSelection as ts}from"prosemirror-state";function Cp(e,t,r){try{return e.resolve(t).parent.inlineContent&&e.resolve(r).parent.inlineContent}catch{return!1}}function Rp(e){return typeof e=="object"&&e!=null&&"parent"in e&&typeof e.parent=="object"&&e.parent!=null&&"inlineContent"in e.parent&&e.parent.inlineContent===!0}function Wr(e,t){return Math.max(1,Math.min(t,e.content.size))}function rs(e,t){return Math.max(0,Math.min(t,e.content.size))}function Z(e,t,r=t){let o=Wr(e.doc,t),n=Wr(e.doc,r),i=Math.min(o,n),s=Math.max(o,n),a=Tp(e),l=c=>{if(!Kr(c))return null;if(a&&typeof c.toJSON=="function")try{let d=a.fromJSON(e.doc,c.toJSON());return Kr(d)?d:null}catch{}return c};if(Cp(e.doc,i,s))try{return l(ts.create(e.doc,o,n))}catch{}try{return l(ts.between(e.doc.resolve(o),e.doc.resolve(n),n>=o?1:-1))}catch{if(o!==n)return null}try{return l(ts.near(e.doc.resolve(o),n>=o?1:-1))}catch{return null}}function Kr(e){return e instanceof ts||typeof e=="object"&&e!=null&&!("$anchorCell"in e)&&!("node"in e&&e.node!=null)&&"anchor"in e&&typeof e.anchor=="number"&&"head"in e&&typeof e.head=="number"&&"empty"in e&&typeof e.empty=="boolean"&&"$anchor"in e&&"$head"in e&&Rp(e.$anchor)&&Rp(e.$head)}function qt(e,t){let r=K(e),o=K(t);if(r!==o||e.from!==t.from||e.to!==t.to||e.empty!==t.empty)return!1;let n=Kr(e),i=Kr(t);return!n&&!i?!0:n&&i&&e.anchor===t.anchor&&e.head===t.head}function bl(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function Tp(e){let t=e.selection.constructor,r=typeof t=="function"?Object.getPrototypeOf(t):null;return r&&typeof r.fromJSON=="function"?r:null}function kC(e,t){return Kr(e)?Kr(t)?t:null:K(e)?K(t)?t:null:t}function at(e,t){let r=Tp(e);if(r&&typeof t.toJSON=="function")try{return kC(t,r.fromJSON(e.doc,t.toJSON()))}catch{}if(K(t)){let o=rs(e.doc,Math.min(t.from,t.to)),n=e.doc.nodeAt(o);if(!n||!Pp.isSelectable(n))return null;try{return Pp.create(e.doc,o)}catch{return null}}return Kr(t)?Z(e,t.anchor,t.head):t}import{readPreservedSelection as wP}from"@datalking/begonia-engine";import{NodeSelection as gP}from"prosemirror-state";import{isDocumentStoryLocator as nP,readSyntheticSideStoryDocStoryLocator as iP,sameDocumentStoryLocator as sP}from"@datalking/begonia-doc-service/v1";import{resolveAddressableBlockIdPath as NC}from"@datalking/begonia-doc-service/v1";import{parseAddressableBlockId as DC}from"@datalking/begonia-doc-service/structure";import{readSyntheticSideStoryDocOriginPath as EC}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as xl,isDocumentNodePathIndex as Cl}from"@datalking/begonia-document-model";function Bl(e){return Cl(e)}function MC(e){let t=e[0];return t===-101||t===-102||t===-211||t===-212?e.length>=2&&Bl(e[1])&&xl(e.slice(2))?e.slice(2):null:(t===-201||t===-202)&&e.length>=3&&Bl(e[1])&&Bl(e[2])&&xl(e.slice(3))?e.slice(3):null}function IC(e,t){return e.length>=t.length&&t.every((r,o)=>e[o]===r)}function AC(e,t){let r=e,o=-1;for(let n of t){if(!Cl(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function Nn(e,t){if(!Array.isArray(t))return null;if(t.length===0)return[];if(xl(t))return[...t];let r=MC(t);if(!r)return null;let o=EC(e);return o&&IC(t,o)?r:null}function No(e,t){let r=Nn(e,t);if(!r)return null;if(r.length===0)return 0;let o=0,n=e;for(let i of r){if(!Cl(i)||i>=n.childCount)return null;o+=1;for(let s=0;s<i;s+=1)o+=n.child(s).nodeSize;n=n.child(i)}return o}function Ve(e,t){let r=Nn(e,t);return r?AC(e,r):null}function kp(e){return e==="paragraph"||e==="heading"}function OC(e){return{readDocument(){return e},readNode(t){return Ve(e,t)?.node??null}}}function Le(e,t){let r=NC(OC(e),t),o=Nn(e,r);if(o)return o;let n=DC(t);if(!n?.path.length||!kp(n.nodeType))return null;let i=Nn(e,n.path),s=i?Ve(e,i)?.node??null:null;return s?.isBlock&&kp(s.type.name)?[...i]:null}import{hasVisibleSemanticContent as jC,semanticNodeText as VC}from"@datalking/begonia-document-model";var LC=new Set(["structural_revision_carrier","bookmark_anchor","bookmark_end","comment_anchor","comment_range_start","comment_range_end","permission_range_start","permission_range_end"]);function FC(e){if(LC.has(e.type.name))return"";let t=VC(e);return t.length>0?t:jC(e)?"":""}function zC(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.textBetween(o,n,"",FC);if(i.length===0)return!0;if(i.trim().length>0)return!1;let s=e.resolve(o),a=e.resolve(n);for(let l=Math.min(s.depth,a.depth);l>=0;l-=1)if(s.node(l)===a.node(l)&&s.node(l).isTextblock)return!0;return!1}function _r(e,t,r={}){if(t.length===0)return null;let o=t[0],n=o;for(let i of t.slice(1)){if(i.from<n.from||i.from===n.from&&i.to<n.to||i.from<o.to)return null;if(i.from===o.to||zC(e,o.to,i.from)){o={from:o.from,to:Math.max(o.to,i.to)},n=i;continue}return r.strict?null:o}return o}import{readSyntheticSideStoryDocOriginPath as JC}from"@datalking/begonia-doc-service/v1";import{cloneSelectionTextRange as HC}from"@datalking/begonia-document-api/core";import{sameDocumentStoryLocator as Ep}from"@datalking/begonia-doc-service/v1";function Wt(e,t){return e.empty&&e.from>=t.from&&e.from<=t.to}function Kt(e,t){return{kind:"text",segments:t.map(r=>({blockId:r.blockId,range:HC(r.range)})),...e.story?{story:structuredClone(e.story)}:{}}}function Et(e){return Kt(e,e.segments)}function Dn(e){return e?{kind:"node",nodeType:e.nodeType,stableIdentity:e.stableIdentity,path:[...e.path],...e.nodeFingerprint!=null?{nodeFingerprint:e.nodeFingerprint}:{}}:null}function On(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!Ep(e.story,t.story)?!1:e.segments.every((r,o)=>{let n=t.segments[o];return n?.blockId===r.blockId&&n.range.start===r.range.start&&n.range.end===r.range.end&&n.range.startAffinity===r.range.startAffinity&&n.range.endAffinity===r.range.endAffinity})}function os(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!Ep(e.story,t.story)?!1:e.segments.every((r,o)=>{let n=t.segments[o];return!!(n&&r.blockId===n.blockId&&r.range.start===r.range.end&&r.range.start>=n.range.start&&r.range.end<=n.range.end)})}function sr(e,t){return!e||!t?e===t:e.nodeType!==t.nodeType?!1:e.stableIdentity!=null&&t.stableIdentity!=null?e.stableIdentity===t.stableIdentity&&(e.nodeFingerprint==null||t.nodeFingerprint==null||e.nodeFingerprint===t.nodeFingerprint):e.path.length===t.path.length&&e.path.every((r,o)=>r===t.path[o])}import{canonicalizeRevisionIds as qC,normalizeRevisionIds as Pl,selectionOverlapsRevisionRange as WC}from"@datalking/begonia-engine";function KC(e){if("from"in e)return{from:e.from,to:e.to};let{anchor:t,head:r}=e.range.range;return t.story.storyType!=="body"||r.story.storyType!=="body"||t.path.length>0||r.path.length>0?null:{from:Math.min(t.offset,r.offset),to:Math.max(t.offset,r.offset)}}function _C(e,t){return t.length>0?qC(e,t):[]}function le(e,t){let r=Pl(e);return t&&t.length>0?_C(r,t):r}function UC(e){return e==="paragraph"||e==="heading"}function ZC(e){return(e.target?.nodeType==="bookmark_anchor"||e.target?.nodeType==="structural_revision_carrier")&&UC(e.target.blockType)&&e.target.blockPath.length>0&&(e.text??"").trim().length===0}function GC(e,t){let r=KC(e);return r?Mn(Pl(t.filter(o=>WC(r.from,r.to,o)).map(o=>o.id)),t):[]}function ce(e){return Pl(e)}function ar(e,t){let r=ce(e),o=ce(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function lr(e,t){let r=le(e.trackedChangeIds,t),o=GC(e,t),n=new Set(t.filter(ZC).map(a=>a.id));if(o.length===0)return r;if(r.length===0)return o;let i=new Set(o),s=Mn(r.filter(a=>i.has(a)||n.has(a)),t);return s.length>0?s:o}function Do(e,t){let r=lr(e,t),o=e.trackedChangeIds??[];return e.trackedChangeIds!=null&&r.length===o.length&&r.every((n,i)=>n===o[i])?e:{...e,trackedChangeIds:r}}function Ur(e,t,r){let o=e.activeChangeIds??[],n=lr("from"in t?{from:t.from,to:t.to,trackedChangeIds:o}:{range:t.range,trackedChangeIds:o},r);return e.activeChangeIds!=null&&n.length===o.length&&n.every((i,s)=>i===o[s])?e:{...e,activeChangeIds:n}}function XC(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Mt(e,t=[]){return le([...e?.activeChangeIds??[],...e?.selection.trackedChangeIds??[]],t)}function Rl(e,t,r=[]){if(!e||!t)return e===t;let o=XC(Mt(e,r),Mt(t,r));return e.selectionKind!==t.selectionKind||e.projectedMode!==t.projectedMode||e.selection.empty!==t.selection.empty||!o?!1:e.selectionKind==="node"||t.selectionKind==="node"?sr(e.nodeSelectionTarget,t.nodeSelectionTarget):e.selectionTarget||t.selectionTarget?On(e.selectionTarget,t.selectionTarget):e.selection.from!==t.selection.from||e.selection.to!==t.selection.to?!1:e.text==null||t.text==null||e.text===t.text}var Ip=Symbol.for("@datalking/begonia-browser-sdk/selection-capture-document-identity"),Mp=1;function $C(){let e=globalThis.crypto?.randomUUID?.();if(typeof e=="string"&&e.length>0)return e;let t=Mp;return Mp+=1,`browser-selection-capture-document:${t}`}function jn(e){let t=e==null?null:Reflect.get(e,Ip);return typeof t=="string"&&t.length>0?t:null}function Ap(e){let t=jn(e);if(t!=null||e==null||!Object.isExtensible(e))return t;let r=$C();return Object.defineProperty(e,Ip,{configurable:!0,enumerable:!1,value:r,writable:!1}),r}function YC(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Oo(e){if(e==null)return null;try{return YC(JSON.stringify(e.toJSON()))}catch{return null}}var QC=Object.freeze({success:!0}),eP=Object.freeze({success:!1,reason:"read-only"});function jo(){return{success:!1,reason:"stale"}}function tP(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function qe(e,t,r={}){try{let o=at(e.view.state,t);return o?(e.view.dispatch(e.view.state.tr.setSelection(o).scrollIntoView()),r.focus!==!1&&e.focus(),!0):!1}catch{return!1}}function rP(e,t){return e.documentIdentity==null&&e.documentHash==null?!0:e.documentIdentity!=null&&e.documentIdentity!==jn(t)?!1:e.documentHash==null||e.documentHash===Oo(t)}function oP(e){let t=Mt(e);return e.selectionKind==="text"&&typeof e.text=="string"&&(e.text.length>0||t.length>0)}function Tl(e){let{capture:t,options:r={},resolveSelection:o,surface:n}=e;if(!n.view?.state||typeof n.view.dispatch!="function")return{success:!1,reason:"not-ready"};if(!t||!t.target&&!t.selectionTarget&&!t.nodeSelectionTarget)return{success:!1,reason:"missing-target"};if(n.editable===!1)return eP;if(!tP(t.storyOriginPath,JC(n.view.state.doc))||r.validateDocumentIdentity!==!1&&!rP(t,n.view.state.doc))return jo();let i=o(t);return!i||t.selectionKind==="node"&&!K(i)||r.validateText!==!1&&oP(t)&&ge(n.view.state.doc,n.view.state.schema,i)!==t.text?jo():qe(n,i,r)?QC:jo()}var ns=Object.freeze({blockSeparator:`
4
- `});function is(e,t){if(t.story===void 0)return!0;if(!nP(t.story))return!1;let r=iP(e)??{kind:"story",storyType:"body"};return sP(r,t.story)}function aP(e,t,r,o,n){let i=se(e,ns),s=Io(t,o,n,i);return s==null?null:He(t,r,s,n,i)}function lP(e,t,r,o,n){let i=se(e,ns),s=Io(t,o,"start",i),a=Io(t,n,"end",i);if(s==null||a==null)return null;let l=He(t,r,Math.min(s,a),"start",i),c=He(t,r,Math.max(s,a),"end",i);return typeof l=="number"&&typeof c=="number"?{from:Math.min(l,c),to:Math.max(l,c)}:null}function cP(e,t,r,o,n){let i=He(e,t,r,"start",n),s=He(e,t,o,"end",n);return typeof i=="number"&&typeof s=="number"?{from:Math.min(i,s),to:Math.max(i,s)}:null}function dP(e,t){return t.collapsedAcceptedVisibleBias==="hidden-anchor"||e.range.start===0?"end":"start"}function uP(e,t,r={}){let o=Le(e,t.blockId);if(!o)return null;let n=Ve(e,o);if(!n?.node.isBlock)return null;let i=se(e,ns);if(Ao(t.blockId)){if(t.range.start===t.range.end){let l=aP(e,n.node,n.position,t.range.start,dP(t,r));return typeof l=="number"?{from:l,to:l}:null}let a=lP(e,n.node,n.position,t.range.start,t.range.end);return a||null}if(t.range.start===t.range.end){let a=Eo(n.node,n.position,t.range.start,i);return typeof a=="number"?{from:a,to:a}:null}if(r.strict)return cP(n.node,n.position,t.range.start,t.range.end,i);let s=mp(n.node,n.position,t.range.start,t.range.end,i);return s||null}function Np(e,t){return ge(e,e.type.schema,t)}function mP(e,t){let r=Q(e,{kind:"text",segments:[t]},{strict:!0});return r?Np(e,r):null}function pP(e,t){let r=e.indexOf(t);return r<0||e.indexOf(t,r+1)>=0?null:{start:r,end:r+t.length}}function kl(e,t,r){if(!is(e,t)||t.segments.length!==1||r.length===0)return null;let[o]=t.segments,n=Le(e,o.blockId);if(!n)return null;let i=Ve(e,n);if(!i?.node.isBlock)return null;let s=se(e,ns),a=Mo(i.node,s),l=pP(a.text,r);if(!l)return null;let c=Io(i.node,l.start,"start",s),d=Io(i.node,l.end,"end",s);if(c==null||d==null)return null;let u=He(i.node,i.position,c,"start",s),m=He(i.node,i.position,d,"end",s);return typeof u!="number"||typeof m!="number"?null:{selection:{from:Math.min(u,m),to:Math.max(u,m)},target:Kt(t,[{blockId:o.blockId,range:{start:Ao(o.blockId)?Math.min(l.start,l.end):Math.min(c,d),end:Ao(o.blockId)?Math.max(l.start,l.end):Math.max(c,d)}}])}}function fP(e,t,r){return kl(e,t,r)?.selection??null}function Q(e,t,r={}){if(!t||!is(e,t))return null;let o=[];for(let n of t.segments){let i=uP(e,n,r);if(!i)return null;o.push(i)}return _r(e,o,r)}function Ae(e,t,r,o={}){let n=Q(e,t,o);return n&&(typeof r!="string"||r.length===0||Np(e,n)===r)?n:!t||typeof r!="string"||r.length===0?null:fP(e,t,r)}function lt(e,t){if(!t||!is(e,t))return null;let r=[];for(let o of t.segments){let n=mP(e,o);if(n==null)return null;r.push(n)}return r}function tt(e,t,r,o={}){if(!t||!is(e,t)||!r||r.length!==t.segments.length)return null;let n=[];for(let[i,s]of t.segments.entries()){let a=Ae(e,{kind:"text",segments:[s]},r[i]??null,{...o,strict:!0});if(!a)return null;n.push(a)}return _r(e,n,o)}function El(e,t){let r=e.view;if(!r?.state||typeof r.dispatch!="function")return!1;let o=Q(r.state.doc,t,{strict:!0});if(!o)return!1;let n=Z(r.state,o.from,o.to);return n?qe(e,n):!1}function Dp(e){return e.anchor>e.head?"backward":"forward"}function xr(e){return e.anchor!=null&&e.head!=null&&e.anchor>e.head?"backward":"forward"}function gt(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to);return t==="backward"?{anchor:o,head:r}:{anchor:r,head:o}}function Op(e,t){return Math.max(1,Math.min(t,e.content.size))}function Ml(e,t){let r=Op(e.doc,Math.min(t.from,t.to)),o=Op(e.doc,Math.max(t.from,t.to));if(r>=o)return null;let n=gt({from:r,to:o},t.direction),i=Z(e,n.anchor,n.head);if(!i||i.empty)return null;try{return e.apply(e.tr.setSelection(i))}catch{return null}}function SP(e,t,r=null,o=null,n){let i=tt(e.doc,t,r,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"})??Ae(e.doc,t,o,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"});if(!i||i.from>=i.to)return null;let s=gt(i,n),a=Z(e,s.anchor,s.head);if(!a||a.empty)return null;try{return e.apply(e.tr.setSelection(a))}catch{return null}}function Zr(e,t){if(!t)return null;let r=Gi(e.doc,t);if(!r)return null;try{return e.apply(e.tr.setSelection(gP.create(e.doc,r.position)))}catch{return null}}function Il(e,t){return Zr(e,t.nodeSelectionTarget)??SP(e,t.target,t.segmentTexts,t.text,t.direction)??Ml(e,t)}function jp(e){let t=wP(e);if(!t||t.empty)return null;let r=at(e,t);if(!r)return null;if(qt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function vP(e,t){if(!t.selectionTarget||!t.segmentTexts||t.selectionTarget.segments.length!==t.segmentTexts.length)return null;let r=t.selectionTarget.segments.map((o,n)=>Ae(e.doc,{kind:"text",segments:[o]},t.segmentTexts?.[n]??null,{strict:!0}));return r.every(o=>o!=null)?r:null}function hP(e,t){let r=vP(e,t);if(!r||r.length===0)return null;let o=r[0].from,n=r[0].to;for(let i of r.slice(1)){if(!i||i.from<n)return null;n=Math.max(n,i.to)}return{from:o,to:n}}function cs(e,t){return t.selectionTarget?tt(e.doc,t.selectionTarget,t.segmentTexts??null,{strict:!0})??Ae(e.doc,t.selectionTarget,t.text??null,{strict:!0})??hP(e,t):null}function ss(e){return Math.max(0,Math.abs(e.to-e.from))}function yP(e,t,r){let o=ce([...ce(t.activeChangeIds),...ce(t.selection.trackedChangeIds)]);return t.selectionKind==="text"&&!t.selection.empty&&o.length>0&&ss(t.selection)>0&&(ss(r??{from:0,to:0})===0||(()=>{if(!r)return!1;let n=ls(e,t);return!n||n.empty||ss(n)<=ss(r)?!1:ge(e.doc,e.schema,n)===ge(e.doc,e.schema,r)})())}function Al(e,t){let r=at(e,t);if(!r)return null;if(qt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function ls(e,t){if(t.selectionKind==="node"){let o=rs(e.doc,Math.min(t.selection.from,t.selection.to)),n=e.doc.nodeAt(o);if(n&&as.isSelectable(n))try{return as.create(e.doc,o)}catch{}}let r=gt(t.selection,xr(t.selection));return Z(e,Wr(e.doc,r.anchor),Wr(e.doc,r.head))}function Vp(e,t,r,o){if(r==="node"){let i=rs(e.doc,Math.min(t.from,t.to)),s=e.doc.nodeAt(i);if(s&&as.isSelectable(s))try{return as.create(e.doc,i)}catch{return null}}let n=gt(t,o);return Z(e,Wr(e.doc,n.anchor),Wr(e.doc,n.head))}function bP(e,t){let r=Zr(e,t.nodeSelectionTarget)?.selection;if(K(r))return r;let o=cs(e,t);if(o){let i=Vp(e,o,t.selectionKind,xr(t.selection));if(K(i))return i}let n=ls(e,t);return K(n)?n:null}function cr(e,t){if(t.selectionKind==="node")return bP(e.state,t);let r=cs(e.state,t);return r?yP(e.state,t,r)?ls(e.state,t):Vp(e.state,r,t.selectionKind,xr(t.selection)):ls(e.state,t)}function xP(e,t,r){return Z(e,t,r)}function CP(e){let t=e;return(t.selectionKind==="text"||t.selectionKind==="node")&&"selectionTarget"in e&&"nodeSelectionTarget"in e&&(t.selectionKind==="node"||typeof t.text=="string"||Array.isArray(t.segmentTexts)||Array.isArray(t.activeChangeIds))}function PP(e,t){if(CP(t))return cr({state:e},t);let r=Math.min(t.selection.from,t.selection.to),o=Math.max(t.selection.from,t.selection.to);return xP(e,r,o)}function RP(e){let t=e.view;return t?.state&&typeof t.dispatch=="function"?t:null}function rt(e,t,r,o={}){let n=RP(e);if(!n)return!1;if(!t)return r(e);let i=o.restoreSelection??!0,s=n.state.selection,a=PP(n.state,t);if(!a||qt(s,a))return r(e);let c=BP(s),d=n.dispatch.bind(n);n.dispatch=(u=>{if(u.docChanged&&c)try{c=c.map(u.mapping)}catch{c=null}return d(u)});try{try{n.dispatch(n.state.tr.setSelection(a))}catch{return r(e)}return r(e)}finally{if(n.dispatch=d,i&&c)try{let u=c.resolve(n.state.doc);if(u){let m=at(n.state,u);m&&n.dispatch(n.state.tr.setSelection(m))}}catch{}}}var kP=["color","highlight","fontFamily","fontSize","fontSizeCs","rFonts"];function Gr(e,t){return{ok:!0,changed:t,value:e}}function ot(e){return{ok:!1,changed:!1,reason:e}}function Fp(e,t){let r=ve(e),o=ir({editable:e.getState().editable},r.state,t);return o||(t?null:"Place the caret in text or select text before applying inline formatting.")}function zp(e,t,r){return e.empty&&!t?`Collapsed ${r} formatting requires a live editor surface. Select text to format in headless mode.`:null}function Hp(e){return e.target&&"segments"in e.target?e.target:e.selectionTarget??null}function qp(e,t,r){let o=ve(e),n=e.documentApi.format.apply({target:t,inline:r,participant:o.trackingEnabled?o.participant:void 0,context:o.trackingEnabled?{source:"formatting"}:void 0});return n.success?Gr(n,!0):n.failure.code==="NO_OP"?Gr(n,!1):ot(n.failure.message)}function Wp(e){return e?{...e}:{}}function EP(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t))return!1;let r=e,o=t,n=Object.keys(r).sort(),i=Object.keys(o).sort();return n.length===i.length&&n.every((s,a)=>s===i[a]&&Object.is(r[s],o[s]))}function MP(e,t){let r=Wp(e),o=!1;for(let n of kP){if(t[n]===void 0)continue;let i=n==="fontSize"||n==="fontSizeCs"?typeof t[n]=="number"?t[n]:null:n==="rFonts"?t.rFonts&&typeof t.rFonts=="object"?structuredClone(t.rFonts):null:typeof t[n]=="string"?t[n]:null;(n==="rFonts"?EP(r[n],i):Object.is(r[n],i))||(r[n]=i,o=!0)}return{changed:o,attrs:Object.values(r).some(n=>n!=null)?r:null}}function Lp(e,t){let r=ve(e);if(!r.view)return ot("Collapsed text-style formatting requires a live editor surface. Select text to format in headless mode.");let{state:o,dispatch:n}=r.view,i=o.schema.marks.text_style;if(!i)return ot("Inline text-style marks are not available on this surface.");let a=TP(o).find(d=>d.type===i)??null,l=MP(Wp(a?.attrs),t);if(!l.changed)return Gr(a?.attrs??null,!1);let c=o.tr.removeStoredMark(i);return l.attrs&&(c=c.addStoredMark(i.create(l.attrs))),n(c),Gr(l.attrs,!0)}function Vo(e,t,r=null,o={}){let n=r?e.readSelectionCapture(r):e.readEffectiveSelection();if(r&&!n)return ot("Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.");let i=Fp(e,n);if(i)return ot(i);if(!n)return ot("Place the caret in text or select text before applying inline formatting.");let s=zp(n,ve(e).view!=null,"text-style");if(s)return ot(s);if(n.empty){if(r){let l=null;return rt(ve(e),n,()=>(l=Lp(e,t),l.changed),{restoreSelection:o.restoreSelection??!1}),l??ot("Inline formatting could not be applied.")}return Lp(e,t)}let a=Hp(n);return a?qp(e,a,t):ot("Place the caret in text or select text before applying inline formatting.")}function Nl(e,t){switch(t){case"bold":return e.toggleBold();case"italic":return e.toggleItalic();case"underline":return e.toggleUnderline();case"strike":return e.toggleStrike()}}function IP(e,t){let r=Nl(ve(e),t);return Gr(r,r)}function AP(e,t){return t==="bold"?e.selection.formatting.bold:t==="italic"?e.selection.formatting.italic:t==="underline"?e.selection.formatting.underline:e.selection.formatting.strike}function _t(e,t,r=null,o={}){let n=r?e.readSelectionCapture(r):e.readEffectiveSelection();if(r&&!n)return ot("Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.");let i=Fp(e,n);if(i)return ot(i);if(!n)return ot("Place the caret in text or select text before applying inline formatting.");let s=zp(n,ve(e).view!=null,"inline");if(s)return ot(s);if(n.empty){if(r){let d=rt(ve(e),n,u=>Nl(u,t),{restoreSelection:o.restoreSelection??!1});return Gr(d,d)}return IP(e,t)}let a=ve(e);if(a.view&&!r){let d=rt(a,n,u=>Nl(u,t),{restoreSelection:o.restoreSelection??!1});return Gr(d,d)}let l=Hp(n);if(!l)return ot("Place the caret in text or select text before applying inline formatting.");let c=!AP(n,t);return qp(e,l,{[t]:c})}function ds(e){let t=e?.layoutMode??"vertical";return{flowMode:e?.flowMode??"paginated",layoutMode:t,preferredPaginatedLayoutMode:e?.preferredPaginatedLayoutMode??t,zoomPercent:e?.zoom?.percent??e?.zoomPercent??100,zoomMode:e?.zoom?.mode??"manual"}}function us(e,t){switch(t.type){case"flow":return{flowMode:t.flowMode};case"toggle-pagination":return{flowMode:e.flowMode==="paginated"?"web":"paginated"};case"layout":return{flowMode:"paginated",layoutMode:t.layoutMode};case"zoom":return{zoomPercent:t.zoomPercent}}}import{normalizeHyperlinkHref as Kp}from"@datalking/begonia-document-model";var _p=8,Up=96;function It(e){return typeof e=="object"&&e!==null}function NP(e,t=!0){return typeof e=="boolean"?e:It(e)&&typeof e.changed=="boolean"?e.changed:t}function $(e,t=NP(e)){return{ok:!0,changed:t,value:e}}function ye(e){return{ok:!1,changed:!1,reason:e}}function Zp(e){if(typeof e=="string"){let r=Kp(e);return r?{href:r,title:null}:null}if(!It(e))return null;let t=Kp(e.href);return t?{href:t,title:typeof e.title=="string"?e.title:e.title==null?null:String(e.title)}:null}function Gp(e){return typeof e=="string"?e.trim()?e:null:!It(e)||typeof e.text!="string"||e.text.trim().length===0?null:{text:e.text,isInternal:typeof e.isInternal=="boolean"?e.isInternal:void 0}}function Lo(e){if(e==null)return null;if(typeof e!="string")return;let t=e.trim();if(t)return t.toLowerCase()==="none"?null:t}function Dl(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?Math.min(Up,Math.max(_p,e)):void 0;if(typeof e!="string")return;let t=e.trim();if(!t)return;if(t.toLowerCase()==="none")return null;let r=Number.parseFloat(t);return Number.isFinite(r)?Math.min(Up,Math.max(_p,r)):void 0}function jl(e){let t=Lo(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"color"))return Lo(e.color);if(Object.hasOwn(e,"value"))return Lo(e.value)}}function Xp(e){let t=Lo(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"fontFamily"))return Lo(e.fontFamily);if(Object.hasOwn(e,"value"))return Lo(e.value)}}function $p(e){let t=Dl(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"fontSize"))return Dl(e.fontSize);if(Object.hasOwn(e,"value"))return Dl(e.value)}}function Ol(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?e:null;if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=t.endsWith("%")?t.slice(0,-1).trim():t;if(!r||!/^(?:\d+(?:\.\d+)?|\.\d+)$/u.test(r))return null;let o=Number.parseFloat(r);return Number.isFinite(o)&&o>0?o:null}function Yp(e){let t=Ol(e);if(t!=null)return t;if(!It(e))return null;let r=Ol(e.zoomPercent);if(r!=null)return{zoomPercent:r};let o=Ol(e.zoom);return o!=null?{zoom:o}:null}function Jp(e){return typeof e=="string"?e:!It(e)||typeof e.query!="string"?null:{query:e.query,options:It(e.options)?e.options:void 0}}function Vl(e){return typeof e=="string"?e:!It(e)||typeof e.text!="string"?null:{text:e.text,hitId:typeof e.hitId=="string"?e.hitId:e.hitId==null?null:String(e.hitId)}}function Qp(e){return typeof e=="string"?e:!It(e)||typeof e.text!="string"?null:{text:e.text,diagnosticId:typeof e.diagnosticId=="string"?e.diagnosticId:e.diagnosticId==null?null:String(e.diagnosticId)}}function ms(e){return e.getZoomState().mode}function ef(e){return e.getZoomPercent()}function Ll(e,t){return e.getState().preferredPaginatedLayoutMode!==t}function Fo(e,t){let r=ve(e);return rt(r,e.readEffectiveSelection(),t)}function Ut(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?ye(e.reason):$(e)}function DP(e){return e===!1?ye("Comment could not be created."):Ut(e)}function OP(e,t,r){let o=ve(e);switch(t){case"font-size":{let n=$p(r),i=n===null?null:Number(n);return n===void 0?ye('Expected a font-size payload or "none".'):Vo(e,{fontSize:i,fontSizeCs:i})}case"font-family":{let n=Xp(r);return n===void 0?ye('Expected a font-family payload or "none".'):Vo(e,{fontFamily:n==null?null:String(n),rFonts:null})}case"text-color":{let n=jl(r);return n===void 0?ye('Expected a text-color payload or "none".'):Vo(e,{color:n==null?null:String(n)})}case"highlight-color":{let n=jl(r);return n===void 0?ye('Expected a highlight-color payload or "none".'):Vo(e,{highlight:n==null?null:String(n)})}case"zoom":{let n=Yp(r);if(!n)return ye("Expected a positive zoom percentage payload.");let i=typeof n=="number"?n:n.zoomPercent??n.zoom??null;if(i==null)return ye("Expected a positive zoom percentage payload.");let s=ef(e),a=ms(e);return e.setViewState(us(ds(e.getState()),{type:"zoom",zoomPercent:i})),$(i,ef(e)!==s||ms(e)!==a)}case"zoom-fit-width":{let n=ms(e);e.setZoomMode(n==="fit-width"?"manual":"fit-width");let i=ms(e);return $(i,i!==n)}case"document-mode-editing":{let n=e.getState().documentMode;return e.setDocumentMode("editing"),$("editing",e.getState().documentMode!==n)}case"document-mode-suggesting":{let n=e.getState().documentMode;return e.setDocumentMode("suggesting"),$("suggesting",e.getState().documentMode!==n)}case"document-mode-viewing":{let n=e.getState().documentMode;return e.setDocumentMode("viewing"),$("viewing",e.getState().documentMode!==n)}case"flow-mode-paginated":{let n=e.getFlowMode();return e.setViewState(us(ds(e.getState()),{type:"flow",flowMode:"paginated"})),$("paginated",e.getFlowMode()!==n)}case"flow-mode-web":{let n=e.getFlowMode();return e.setViewState(us(ds(e.getState()),{type:"flow",flowMode:"web"})),$("web",e.getFlowMode()!==n)}case"layout-mode-vertical":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"vertical"}),$("vertical",e.getLayoutMode()!==i||Ll(e,n))}case"layout-mode-horizontal":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"horizontal"}),$("horizontal",e.getLayoutMode()!==i||Ll(e,n))}case"layout-mode-book":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"book"}),$("book",e.getLayoutMode()!==i||Ll(e,n))}case"track-changes-display-review":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("review"),$("review",e.getState().trackChanges.mode!==n)}case"track-changes-display-original":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("original"),$("original",e.getState().trackChanges.mode!==n)}case"track-changes-display-final":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("final"),$("final",e.getState().trackChanges.mode!==n)}case"track-changes-display-off":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("off"),$("off",e.getState().trackChanges.mode!==n)}case"comments-visible":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!0),$(!0,e.getState().commentsDisplay.visible!==n)}case"comments-hidden":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!1),$(!1,e.getState().commentsDisplay.visible!==n)}case"comments-show-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!0),$(!0,e.getState().commentsDisplay.showResolved!==n)}case"comments-hide-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!1),$(!1,e.getState().commentsDisplay.showResolved!==n)}case"comments-visibility-all":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("all"),$("all",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-internal":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("internal"),$("internal",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-external":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("external"),$("external",e.getState().commentsDisplay.visibility!==n)}case"undo":return $(o.undo());case"redo":return $(o.redo());case"bold":return _t(e,"bold");case"italic":return _t(e,"italic");case"underline":return _t(e,"underline");case"strikethrough":return _t(e,"strike");case"paragraph":return $(Fo(e,n=>n.setParagraph()));case"heading-1":return $(Fo(e,n=>n.setHeading(1)));case"heading-2":return $(Fo(e,n=>n.setHeading(2)));case"heading-3":return $(Fo(e,n=>n.setHeading(3)));case"bullet-list":return $(Fo(e,n=>n.toggleBulletList()));case"numbered-list":return $(Fo(e,n=>n.toggleOrderedList()));case"link-set":{let n=Zp(r);return n?$(typeof n=="string"?e.setLink(n):e.setLink(n.href,n.title??null)):ye("Expected a non-empty link payload.")}case"link-clear":return $(e.clearLink());case"comment-create":{let n=Gp(r);if(!n)return ye("Expected non-empty comment text for comment creation.");let i=e.readEffectiveSelection();return DP(typeof n=="string"?i?e.createCommentFromCapture(i,n):e.createComment(n):i?e.createCommentFromCapture(i,n.text,{isInternal:n.isInternal??void 0}):e.createComment(n.text,{isInternal:n.isInternal??void 0}))}case"tracking-toggle":return e.setDocumentMode(e.getState().documentMode==="suggesting"?"editing":"suggesting"),$(!0,!0);default:return null}}function tf(e,t,r){let o=OP(e,t,r);if(o)return o;let n=ep(e,t,r);if(n)return n;switch(t){case"search-set-query":{let i=Jp(r);if(!i)return ye("Expected a search query payload.");let s=typeof i=="string"?e.search(i):e.search(i.query,i.options??{});return $(s,!0)}case"search-next":return(()=>{let i=e.nextSearchHit();return $(i,i!=null)})();case"search-previous":return(()=>{let i=e.previousSearchHit();return $(i,i!=null)})();case"search-clear":{let i=e.getState().search.query.length>0;return e.clearSearch(),$(void 0,i)}case"search-replace-active":{let i=Vl(r);if(!i)return ye("Expected replacement text for the active search hit.");let s=e.getState(),a=typeof i=="string"?s.search.activeHitId:i.hitId??s.search.activeHitId;if(!a)return ye("No active search hit is available to replace.");let l=typeof i=="string"?e.replaceSearchHit(a,i):e.replaceSearchHit(a,i.text);return Ut(l)}case"search-replace-all":{let i=Vl(r);if(!i)return ye("Expected replacement text for search replace-all.");let s=typeof i=="string"?e.replaceAllSearchHits(i):e.replaceAllSearchHits(i.text);return Ut(s)}case"review-accept-all":return Ut(e.acceptAll());case"track-changes-accept-selection":return Ut(e.acceptSelection());case"review-reject-all":return Ut(e.rejectAll());case"track-changes-reject-selection":return Ut(e.rejectSelection());case"proofing-ignore-first":{let i=e.getState().proofing.diagnostics[0]?.diagnosticId;return i?Ut(e.ignoreProofingDiagnostic(i)):ye("No proofing diagnostic is available to ignore.")}case"proofing-accept-first":{let i=e.getState().proofing.diagnostics[0]?.diagnosticId;return i?Ut(e.acceptProofingSuggestion(i)):ye("No proofing diagnostic is available to accept.")}case"proofing-replace-first-tracked":{let i=Qp(r),a=e.getState().proofing.diagnostics[0],l=typeof i=="string"?a?.diagnosticId:i?.diagnosticId??a?.diagnosticId,c=typeof i=="string"?i:i?.text??a?.replacementText??a?.suggestion??"";return!l||!c?ye("No tracked proofing replacement could be resolved."):Ut(e.replaceProofingDiagnosticTracked(l,c))}default:return null}}import{createEditorSessionController as LT}from"@datalking/begonia-editor-ui";function ct(e){return e?.trim()??""}function Vn(e,t){let r=ct(e);return r.length===0?"":ct(t?.id)||r}function rf(e){return/(?:^|[-_:])wire(?:[-_:]|$)/i.test(ct(e))}function Ze(e){let t=new Map,r=new Set;for(let n of e??[]){let i=ct(n.id);i.length!==0&&(r.add(i),t.set(i,i))}let o=new Map;for(let n of e??[]){let i=ct(n.id);if(i.length===0)continue;let s=ct(n.wireId);if(s.length===0||r.has(s))continue;let a=o.get(s);a===void 0||a===i?o.set(s,i):o.set(s,null)}for(let[n,i]of o)i&&t.set(n,i);return t}function zo(e,t){let r=ct(e);return t.get(r)??r}function jP(e,t){let r=ct(t);if(r.length===0)return"";let o=e?.get?.(r)??null;if(o)return Vn(r,o);let n=rf(r),i=e?.target?.(r)??null;if(i&&(ct(i.id)===r||n))return Vn(r,i);let s=e?.targetSnapshot?.(r)??null;return s&&(ct(s.id)===r||n)?Vn(r,s):r}function At(e,t){return[...new Set((e??[]).map(r=>zo(r,t)).filter(r=>r.length>0))]}function of(e,t){let r=(e??[]).map(s=>ct(s)).filter(s=>s.length>0),o=t?.get==null&&r.length>1&&r.every(s=>!rf(s)),n=[],i=new Set;for(let s of r){let a=o?s:jP(t,s);a.length===0||i.has(a)||(i.add(a),n.push(a))}return n}function nf(){return{success:!1}}function sf(e,t){try{e.restoreSelectionHandle?.(t,{focus:!1})}catch{return}}function af(e){return e.shouldContinue?.()??!0}async function ps(e,t,r={}){let o=e.captureEffectiveSelectionHandle();try{let n=await t();return af(r)?(n.success||sf(e,o),n):nf()}catch{return af(r)&&sf(e,o),nf()}finally{e.releaseSelectionHandle(o)}}function VP(e){return"host"in e}function he(e){return e?VP(e)?e.host:e:null}function LP(e){return"getState"in e&&typeof e.getState=="function"&&"subscribe"in e&&typeof e.subscribe=="function"&&"readLayoutSource"in e&&typeof e.readLayoutSource=="function"&&"readLayoutAdapter"in e&&typeof e.readLayoutAdapter=="function"&&"requestPreviewNavigation"in e&&typeof e.requestPreviewNavigation=="function"&&"ackPreviewNavigationRequest"in e&&typeof e.ackPreviewNavigationRequest=="function"&&"setViewState"in e&&typeof e.setViewState=="function"&&"setZoomViewportMetrics"in e&&typeof e.setZoomViewportMetrics=="function"}function lf(e){return e?LP(e)?e:he(e)?.preview??null:null}function fs(e={}){return{commentTarget:null,selected:!1,selectionTarget:null,navigationRequest:null,...e}}function cf(e,t){return t?typeof t=="string"?e.documentApi.comments.target(t):t:null}function df(e){return e.documentApi.selection.current({includeText:!0}).target}function FP(e){return e&&"id"in e&&typeof e.id=="string"&&e.id.length>0?e.id:null}function Fl(){return{success:!1}}function uf(e,t){let r=he(e);if(!r)return fs();let o=cf(r,t);if(!o)return fs();if(!r.selectionTargets.selectCommentTarget(o))return fs({commentTarget:o});let i=df(r);return fs({commentTarget:o,selected:!0,selectionTarget:i,navigationRequest:r.browserViewport.requestNavigationForTextTarget(i)})}async function mf(e,t,r={},o={}){let n=he(e);if(!n)return Fl();let i=cf(n,t);return i?ps(n.selectionHandles,async()=>{if(n.selectionTargets.selectCommentTarget(i)){let a=df(n);if(a)return n.browserViewport.scrollIntoView({target:a,timeoutMs:r.timeoutMs,continuation:o.continuation})}let s=FP(i);return s?n.browserViewport.scrollIntoView({target:{type:"comment",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Fl()},{shouldContinue:o.continuation?.shouldContinue}):Fl()}function zP(e,t,r){return{shouldContinue(){return e()===t},subscribe(o){return r(t,o)}}}function ws(){let e=0,t=new Set,r=()=>{let n=[...t];e+=1,t=new Set;for(let i of n)try{i()}catch{continue}return e},o=(n,i)=>n!==e?()=>{}:(t.add(i),()=>{n===e&&t.delete(i)});return{begin(){let n=r();return zP(()=>e,n,o)},invalidate(){r()}}}function HP(e){return e.find(t=>t.type==="comment")??null}function qP(e,t){return[...new Set(e.filter(r=>r.type==="comment").map(r=>zo(r.id,t)).filter(r=>r.length>0))]}function WP(e,t){let r=Ze(e),o=zo(t,r);return e.find(n=>zo(n.id,r)===o||zo(n.wireId,r)===o)??null}function KP(e,t){let r=Ze(e),o=qP(t,r);if(o.length!==1)return null;let n=o[0]??HP(t)?.id??null;if(!n)return null;let i=WP(e,n);return!i||typeof i.id!="string"||i.id.length===0?null:{id:i.id,item:i}}function pf(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=he(e);return o?KP(r,o.browserViewport.entitiesAtPoint(t)):null}import{listProjectionSelectionRects as PR,resolveProjectionCaretRect as RR}from"@datalking/begonia-page-layout";import{isDenseArray as TR}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as _P,INSERTION_MARK_NAME as UP,semanticNodeText as ZP}from"@datalking/begonia-engine";function ff(e){return typeof e=="number"?Math.max(0,e):null}function GP(e){return e.startPath?e.startPath:e.segments?.find(t=>t.kind==="range")?.startPath??null}function XP(e){if(e.endPath)return e.endPath;for(let t=(e.segments?.length??0)-1;t>=0;t-=1){let r=e.segments?.[t];if(r?.kind==="range"&&r.endPath)return r.endPath}return null}function $P(e){return e.anchorPath?e.anchorPath:e.segments?.find(t=>t.kind==="anchor")?.anchorPath??null}function YP(e,t){let r=e,o=Ve(r,t),n=o?.node.type.name==="comment_anchor"?o.position:No(r,t);return ff(n)}function gs(e){return e.marks.some(t=>t.type.name===UP||t.type.name===_P)}function JP(e,t,r){let o=!1;return e.nodesBetween(t,r,(n,i)=>{if(o)return!1;if(!(n.isText||n.isInline&&n.isLeaf&&ZP(n).length>0))return!0;let a=Math.max(t,i);return Math.min(r,i+n.nodeSize)<=a?!1:(o=gs(n),!o)}),o}function wf(e,t){let r=e,o=Ve(r,t);return o?o.node.type.name!=="comment_range_start"?No(r,t):gs(o.node)?No(r,t):o.position:null}function QP(e,t,r={}){if(t?.kind!=="range"||!t.startPath||!t.endPath)return null;let o=e,n=wf(e,t.startPath),i=No(o,t.endPath);if(typeof n!="number"||typeof i!="number"||n>i)return null;let s={from:n,to:i},a=JP(e,s.from,s.to),l=r.allowTrackedContentFallback??!0,c=se(o,{blockSeparator:`
5
- `}),d=t.addressableBlockPath??t.blockPath??null,u=d?Ve(o,d):null,m=u?.node??null,p=t.text;if(!u||!m?.isBlock||typeof p!="string"||p.length===0)return s;let f=Br(m,c),g=we(m,u.position,s.from,c),v=Math.max(g,we(m,u.position,s.to,c)),E=f.slice(g,v);if(E===p)return s;let R=E.indexOf(p);if(R<0||E.indexOf(p,R+1)>=0)return a&&!l?null:s;let S=g+R,P=S+p.length,h=He(m,u.position,S,"start",c),b=He(m,u.position,P,"end",c),x=Ve(o,t.startPath)?.node??null,A=Ve(o,t.endPath)?.node??null,O=R===0&&!(a&&x?.type.name==="comment_range_start"&&!gs(x)),j=P===v&&!(a&&A?.type.name==="comment_range_end"&&!gs(A)),_=O?s.from:h,V=j?s.to:b;return typeof _!="number"||typeof V!="number"||V<=_?a&&!l?null:s:{from:Math.min(_,V),to:Math.max(_,V)}}function eR(e){return e!=null}function tR(e,t){let r=e,o=t.segments??[],n=t.source==="live",i=o.map(a=>QP(e,a,{allowTrackedContentFallback:n}));if(o.length>0&&!n&&i.some(a=>a==null))return null;let s=i.filter(eR);if(s.length===0){let a=GP(t),l=XP(t);if(!a||!l)return null;let c=wf(e,a),d=No(r,l);return typeof c!="number"||typeof d!="number"?null:{from:Math.min(c,d),to:Math.max(c,d)}}return _r(r,s,{strict:!n})}function Ge(e,t){if(!t)return null;if(t.targetKind==="range")return tR(e,t);let r=$P(t);if(!r)return null;let o=YP(e,r);return typeof o!="number"?null:{from:o,to:o}}import{readSyntheticSideStoryDocContext as rR,resolveSyntheticSideStoryPathPosition as oR}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as nR}from"@datalking/begonia-document-model";import{parseAddressableBlockId as iR}from"@datalking/begonia-doc-service/structure";function sR(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function gf(e,t){let r=e,o=-1;for(let n of t){if(!nR(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function aR(e,t){let r=gf(e,t);return r?.node.isBlock?{path:[...t],localPath:[...t],document:e,position:r.position,node:r.node,syntheticRootPath:null,positionRoot:null}:null}function lR(e,t){let r=rR(sR(e),t);if(!r)return null;let o=r.localizePath(t),n=r.globalizePath([]),i=oR(e.type.schema,e,n),s=o?gf(r.doc,o):null;return o&&s?.node.isBlock&&typeof i=="number"?{path:[...t],localPath:[...o],document:r.doc,position:s.position,node:s.node,syntheticRootPath:n,positionRoot:i}:null}function Cr(e,t){let r=Le(e,t);if(r)return aR(e,r);let o=iR(t);return o?.path.some(n=>n<0)?lR(e,o.path):null}function Zt(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?t-e.positionRoot:t}import{resolveDocumentStoryLocatorFromPath as cR}from"@datalking/begonia-doc-service/v1";import{addressableBlockTypeForNodeType as dR,formatAddressableBlockId as uR,formatAddressableBlockIdWithLogicalId as mR}from"@datalking/begonia-doc-service/structure";function pR(e,t){return{kind:"text",segments:[{blockId:e,range:{start:0,end:0}}],...t?{story:t}:{}}}function fR(e,t,r){return r?structuredClone(r):cR({listSections:()=>e.sections?.list?.()??[],listFootnotes:()=>e.notes?.footnotes?.list?.()??e.notes?.list?.()??[],listEndnotes:()=>e.notes?.endnotes?.list?.()??[],listHeaderFooterParts:()=>e.headerFooters?.parts?.list?.()?.items??[]},t)}function Ss(e,t,r){if(!e||!Array.isArray(t)||t.length===0)return null;let o=e.blocks.read(t);if(!o)return null;let n=dR(o.type.name);if(!n)return null;let i=Hr(n,o),s=i?mR(n,t,i):uR(n,t);return pR(s,fR(e,t,r)??void 0)}function Ln(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.trunc(e):null}function wR(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Sf(e,t){return!Array.isArray(t)||t.length===0?null:Ss(e,t)}function gR(e,t){let r=Math.max(0,typeof e.text=="string"?e.text.length:typeof t.text=="string"?t.text.length:0),o=Ln(e.startOffset)??Ln(t.startOffset)??0,n=Ln(e.endOffset)??Ln(t.endOffset)??(r>0?o+r:o);return{start:o,end:Math.max(o,n)}}function SR(e){let t=e.segments?.filter(r=>r.kind==="range")??[];return t.length>0?t:[{kind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:e.blockPath??null,addressableBlockPath:e.addressableBlockPath??null,startOffset:e.startOffset??null,endOffset:e.endOffset??null,text:e.text}]}function vR(e){let t=e.segments?.find(r=>r.kind==="anchor");return t?.addressableBlockPath??t?.blockPath??e.addressableBlockPath??e.blockPath??null}function vs(e,t){if(!e||!t)return null;if(t.targetKind==="range"){let n=[],i;for(let s of SR(t)){let a=s.addressableBlockPath??s.blockPath??null,l=Sf(e,a);if(!l)return null;if(i===void 0)i=l.story;else if(!wR(i,l.story))return null;n.push({blockId:l.segments[0].blockId,range:gR(s,t)})}return n.length>0?{kind:"text",segments:n,...i?{story:i}:{}}:null}let r=Sf(e,vR(t));if(!r)return null;let o=Ln(t.anchorOffset)??0;return{kind:"text",segments:[{blockId:r.segments[0].blockId,range:{start:o,end:o}}],...r.story?{story:r.story}:{}}}import{isIntegerPath as hR}from"@datalking/begonia-document-model";var yR=Object.freeze({blockSeparator:`
6
- `});function Ho(e){return typeof e=="number"&&Number.isFinite(e)}function bR(e){return Array.isArray(e)&&e.length>0&&hR(e)}function BR(e){return!!e&&typeof e=="object"&&bR(e.blockPath)}function xR(e){let t=s=>[s.blockPath.join("."),Ho(s.from)?Math.min(s.from,s.to??s.from):"",Ho(s.to)?Math.max(s.from??s.to,s.to):""].join(":"),r=[e?.target??null,...e?.targets??[]].filter(BR),o=s=>Ho(s.from)&&Ho(s.to)?0:1,n=s=>o(s)===0?Math.min(s.from,s.to):Number.POSITIVE_INFINITY,i=s=>o(s)===0?Math.max(s.from,s.to):Number.POSITIVE_INFINITY;return r.map((s,a)=>({target:s,index:a})).sort((s,a)=>o(s.target)-o(a.target)||n(s.target)-n(a.target)||i(s.target)-i(a.target)||s.index-a.index).reduce((s,a)=>{let l=t(a.target);return s.some(c=>t(c)===l)||s.push(a.target),s},[])}function vf(e,t,r){return Math.min(Math.max(e,t),r)}function CR(e,t,r){if(!e||!Ho(r.from)||!Ho(r.to))return null;let o=Cr(e,t);if(!o)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=Zt(o,Math.min(r.from,r.to)),a=Zt(o,Math.max(r.from,r.to)),l=vf(s,n,i),c=vf(a,l,i),d=se(o.document,yR),u=we(o.node,o.position,l,d),m=we(o.node,o.position,c,d);return{start:Math.min(u,m),end:Math.max(u,m)}}function zl(e,t,r){if(!e||!r)return{target:null,selectionTarget:null};let o=null,n=null;for(let i of xR(r)){let s=Ss(e,i.blockPath,r.story);if(!s)continue;let a=s.segments[0]?.blockId;if(!a)continue;n||(o=i,n={kind:"text",segments:[{blockId:a,range:{start:0,end:0}}],...s.story?{story:s.story}:{}});let l=CR(t,a,i);if(l)return{target:i,selectionTarget:{kind:"text",segments:[{blockId:a,range:l}],...s.story?{story:s.story}:{}}}}return{target:o,selectionTarget:n}}function hs(e,t,r){return zl(e,t,r).selectionTarget}function Gt(e){return typeof e?.readLayoutSource=="function"?e.readLayoutSource():null}function qo(e){return e?.getResolvedProjection?.()??null}function Xt(e){return e?.getResolvedProjectionGeometryOptions?.()??null}function St(e){return{success:!1,reason:e}}function kR(e){return!e||typeof e!="object"?!1:!!e&&"kind"in e&&e.kind==="text"&&TR(e.segments)}function hf(e){return typeof e=="number"&&Number.isFinite(e)}function ER(e){return!e||e.segments.length===0?!1:e.segments.every(t=>typeof t?.blockId=="string"&&t.blockId.trim().length>0&&hf(t.range?.start)&&hf(t.range?.end))}function MR(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"id"in e&&typeof e.id=="string"}function IR(e){return e?typeof e.id=="string"&&e.id.trim().length>0:!1}function Hl(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"childCount"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function yf(e,t){return typeof e!="number"||!Number.isFinite(e)||typeof t!="number"||!Number.isFinite(t)?null:{from:Math.min(e,t),to:Math.max(e,t)}}function AR(e){return{pageIndex:e.pageIndex,pageNumber:e.pageNumber,sectionId:e.sectionId??null,region:e.region,blockIndex:e.blockIndex,fragmentIndex:e.fragmentIndex,columnIndex:e.columnIndex,lineIndex:e.lineIndex,lineCount:e.lineCount,left:e.left,top:e.top,width:e.width,height:e.height}}function NR(e){return{pageIndex:e.pageIndex,pageNumber:e.pageNumber,sectionId:e.sectionId??null,region:e.region,blockIndex:e.blockIndex,fragmentIndex:e.fragmentIndex,columnIndex:e.columnIndex,lineIndex:e.lineIndex,lineCount:e.lineCount,left:e.left,top:e.top,width:1,height:e.height}}function DR(e){return[e.pageIndex,e.pageNumber,e.sectionId??"",e.region,e.blockIndex,e.fragmentIndex,e.columnIndex,e.lineIndex,e.lineCount,e.left,e.top,e.width,e.height].join(":")}function OR(e){let t=[],r=new Set;for(let o of e){let n=DR(o);r.has(n)||(r.add(n),t.push(o))}return t}function jR(e,t){let r=qo(e),o=Xt(e)??{};if(!r)return[];if(t.from===t.to){let n=RR(r,t.from,o);return n?[NR(n)]:[]}return PR(r,t.from,t.to,o).map(AR)}function ql(e,t){if(t.segments.length===0)return null;let r=[];for(let o of t.segments){let n=LR(e,o);if(!n)return null;r.push(n)}return r}function VR(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?{from:e.positionRoot+t.from,to:e.positionRoot+t.to}:t}function LR(e,t){let r={kind:"text",segments:[t]},o=Q(e,r,{strict:!0});if(o)return o;let n=Cr(e,t.blockId);if(!n||n.document===e)return null;let i=Q(n.document,r,{strict:!0});return i?VR(n,i):null}function FR(e){if(!e)return[];let t=(e.segments??[]).map(o=>yf(o.from,o.to)).filter(o=>o!=null).sort((o,n)=>o.from-n.from||o.to-n.to);if(t.length>0)return t;let r=yf(e.from,e.to);return r?[r]:[]}function zR(e,t,r){if(!r||typeof t?.blocks?.read!="function")return null;let o=hs(t,e,r);return o?ql(e,o):null}function HR(e,t="unresolved"){let[r]=e;return r?{success:!0,rect:r,rects:[...e],pageIndex:r.pageIndex,pageNumber:r.pageNumber}:St(t)}function Fn(e,t){let r=OR(t.flatMap(o=>jR(e,o)));return HR(r,t.length>0?"not-mounted":"unresolved")}function Wo(e,t){let r=e.preview??null;if(!r||!qo(r))return St("not-ready");let o=t.target??null;if(!o)return St("invalid-target");if(kR(o)){if(!ER(o))return St("invalid-target");let n=Gt(r);if(!Hl(n))return St("not-ready");let i=ql(n,o);return i?Fn(r,i):St("unresolved")}if(!MR(o)||!IR(o))return St("invalid-target");if(o.type==="comment"){let n=Gt(r);if(!Hl(n))return St("not-ready");let i=e.documentApi?.comments.target(o.id)??null,s=vs(e.documentApi,i),a=s?ql(n,s):null;if(a)return Fn(r,a);let l=Ge(n,i);return l?Fn(r,[l]):St("unresolved")}if(o.type==="trackedChange"){let n=e.documentApi?.trackChanges.get(o.id)??null,i=Gt(r),s=Hl(i)?zR(i,e.documentApi,n):null;if(s)return Fn(r,s);let a=FR(n);return a.length===0?St("unresolved"):Fn(r,a)}return St("invalid-target")}var qR=Object.freeze([]),WR=[],KR=Object.freeze({});function Wl(e){let t=e?.items??WR,r=e?.permissions??KR;return{items:t,permissions:r,total:typeof e?.total=="number"?Math.max(0,Math.trunc(e.total)):t.length,activeCommentId:e?.activeCommentId??null,activeCommentIds:e?.activeCommentIds??qR,enabled:e?.enabled??!1,visible:e?.visible??!1,readOnly:e?.readOnly??!1,showResolved:e?.showResolved??!1,visibility:e?.visibility??null}}function bf(e){return structuredClone(e)}function Kl(e){return Wl(e?e.session.readState()?.comments??null:null)}function Bf(e,t){return At(typeof t=="string"?[t]:[],Ze(Kl(e).items))[0]??null}function xf(e,t){let r=ws(),o=()=>bf(Wl(t.getSnapshot())),n=i=>t.subscribe(s=>{i(bf(Wl(s)))});return{getSnapshot:o,subscribe:n,observe(i){return n(i)},create(i,s){return e.commentActions.createComment(i,s)},reply(i,s,a=null){return e.commentActions.replyComment(i,s,a)},setInternal(i,s){return e.commentActions.setCommentInternal(i,s)},resolve(i){return e.commentActions.resolveComment(i)},reopen(i){return e.commentActions.reopenComment(i)},setActive(i){return r.invalidate(),e.commentFocus.setActiveComment(i)},reveal(i){r.invalidate();let s=Kl(e).activeCommentId??null,a=typeof i=="string"?Bf(e,i):null;a&&e.commentFocus.setActiveComment(a);let l=uf(e,i);return!l.selected&&a&&e.commentFocus.setActiveComment(s),l},async scrollTo(i,s){let a=r.begin(),l=Kl(e).activeCommentId??null,c=typeof i=="string"?Bf(e,i):null;c&&e.commentFocus.setActiveComment(c);let d=await mf(e,i,s,{continuation:a});return a.shouldContinue()?(!d.success&&c&&e.commentFocus.setActiveComment(l),d):{success:!1}},getAt(i){return pf(e,i,o().items)},getRect({id:i}){return Wo(e,{target:{type:"comment",id:i}})}}}var Cf=["editing","suggesting","viewing"],Pf=["review","original","final","off"],Rf=["paired","independent"],Tf=["all","internal","external"];function ys(e,t){return typeof e=="string"&&t.includes(e)}function _R(e){return e.map(t=>`"${t}"`).join(", ")}function bs(e,t,r){return new TypeError(`[BrowserEditor] ${e} must be one of ${_R(r)}; received ${JSON.stringify(t)}.`)}function _l(e){return ys(e,Cf)?e:null}function Bs(e){let t=_l(e);if(t)return t;throw bs("documentMode",e,Cf)}function Xr(e){return ys(e,Pf)?e:null}function kf(e){let t=Xr(e);if(t)return t;throw bs("trackChanges.mode",e,Pf)}function $r(e){return ys(e,Rf)?e:null}function Ef(e){let t=$r(e);if(t)return t;throw bs("trackChanges.replacements",e,Rf)}function Yr(e){return ys(e,Tf)?e:null}function Mf(e){let t=Yr(e);if(t)return t;throw bs("comments.visibility",e,Tf)}function zn(e,t){if(typeof e=="boolean")return e;throw new TypeError(`[BrowserEditor] ${t} must be a boolean; received ${JSON.stringify(e)}.`)}function Hn(e){return e==="paginated"||e==="web"?e:null}function Jr(e){return Hn(e)??"paginated"}function dt(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function dr(e,t){return t==="web"?"vertical":dt(e)??"vertical"}function Qr(e){let t=Jr(e.flowMode),r=dt(e.preferredPaginatedLayoutMode)??dt(e.layoutMode)??"vertical";return{flowMode:t,layoutMode:dr(dt(e.layoutMode)??r,t),preferredPaginatedLayoutMode:r}}import{resolveEditorSelectionRootOffsets as If}from"@datalking/begonia-editor-contracts";import{listProjectionSelectionRects as UR,resolveProjectionCaretRect as ZR}from"@datalking/begonia-page-layout";function GR(e){return e==="end"||e==="union"?e:"start"}function XR(e){return e?{left:e.left,top:e.top,width:1,height:e.height}:null}function $R(e){if(e.length===0)return null;let t=e[0].left,r=e[0].top,o=e[0].left+e[0].width,n=e[0].top+e[0].height;for(let i of e.slice(1))t=Math.min(t,i.left),r=Math.min(r,i.top),o=Math.max(o,i.left+i.width),n=Math.max(n,i.top+i.height);return{left:t,top:r,width:Math.max(1,o-t),height:Math.max(1,n-r)}}function qn(e,t){let r=qo(e),o=Xt(e)??{};if(!r||!t||t.empty)return[];let n=If(t);return n?UR(r,n.from,n.to,o):[]}function Ul(e,t,r={}){let o=qo(e),n=Xt(e)??{};if(!o||!t||!t.empty)return null;let i=If(t);return i?ZR(o,i.from,{bias:r.bias,measureText:n.measureText,measurementEpoch:n.measurementEpoch}):null}function Af(e,t,r={}){let o=qn(e,t);if(o.length===0)return XR(Ul(e,t));switch(GR(r.placement)){case"end":{let n=o.at(-1)??null;return n?{left:n.left,top:n.top,width:n.width,height:n.height}:null}case"union":return $R(o);default:{let n=o[0]??null;return n?{left:n.left,top:n.top,width:n.width,height:n.height}:null}}}import{cloneEditorSelectionSnapshot as YR}from"@datalking/begonia-editor-contracts";function Ko(e){return e?{empty:e.empty,target:e.target?Et(e.target):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}var Zl=Object.freeze([]);function JR(e){return e?structuredClone(e):void 0}function QR(e){if(!e||!Array.isArray(e.segments))return null;let t=e.segments[0]??null,r=e.segments[e.segments.length-1]??null;if(!t||!r)return null;let o=JR(e.story);return{kind:"selection",start:{kind:"text",blockId:t.blockId,offset:t.range.start,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end,...o?{story:o}:{}},segments:e.segments.map(n=>({blockId:n.blockId,start:n.range.start,end:n.range.end})),...o?{story:o}:{}}}function xs(e,t){if(!e)return null;let r=YR(e),o=Ko(t),n=o?.target??null;return{...r,target:n,selectionTarget:QR(n),activeMarks:o?.activeMarks??Zl,activeCommentIds:o?.activeCommentIds??Zl,activeChangeIds:o?.activeChangeIds??Zl,quotedText:o?.text??""}}import{clonePageViewportAnchor as Ff,hasFreshViewportRequest as nT,normalizeViewportRequestKey as iT,samePageViewportAnchor as sT,sameViewportRequestKey as aT}from"@datalking/begonia-layout-renderer/core";import{hasLogicalViewportAnchorHint as eT}from"@datalking/begonia-layout-renderer/core";var Wn=100,Nt=1,Df=1e-6;function Xe(e){return typeof e=="number"&&Number.isFinite(e)}function vt(e,t,r=0){return e===t||Math.abs(e-t)<=r}function Of(e,t,r=0){return e==null||t==null?e===t:vt(e,t,r)}function jf(e,t=0){return Xe(e)?Math.max(0,Math.trunc(e)):t}function Xl(e){return Xe(e)&&Number.isInteger(e)&&e>=0?e:null}function eo(e){return Xe(e)&&Number.isInteger(e)&&e>0?e:null}function Gl(e,t){if(!Array.isArray(e))return[];let r=e.filter(o=>Xe(o)&&Number.isInteger(o)&&o>=t);return[...new Set(r)].sort((o,n)=>o-n)}function tT(e){return e.map(t=>t+1)}function Nf(e){return e.map(t=>t-1)}function rT(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function $l(e,t){let r=Gl(t,1);if(r.length>0){let n=Gl(e,0);return n.length>0&&!rT(Nf(r),n)?null:{pageIndexes:Nf(r),pageNumbers:r}}let o=Gl(e,0);return{pageIndexes:o,pageNumbers:tT(o)}}function Yl(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function Jl(e){return e==="paginated"||e==="web"?e:null}function Vf(e){return Xe(e)&&e>0?e:null}function Ql(e,t){let r=Jl(e),o=Yl(t);return e!=null&&r==null||t!=null&&o==null?null:r==="web"?o!=null&&o!=="vertical"?null:{flowMode:r,layoutMode:"vertical"}:{flowMode:r,layoutMode:o}}function oT(e){return e==="header"||e==="body"||e==="footer"}function Lf(e){return oT(e?.region)&&!eT(e)&&e?.fragmentIndex==null&&e?.columnIndex==null&&e?.blockOffsetTopPx==null&&e?.blockOffsetTopRatio==null&&e?.blockOffsetLeftPx==null&&e?.blockOffsetLeftRatio==null}function $t(e,t){let r=eo(t),o=Xl(e);return r!=null&&o!=null&&o!==r-1?{pageIndex:null,pageNumber:null}:{pageIndex:r!=null?r-1:o,pageNumber:r??(o!=null?o+1:null)}}function lT(e){if(e.visiblePageNumbers.length>0){let o=eo(e.firstVisiblePageNumber),n=eo(e.lastVisiblePageNumber);return o!=null&&o!==e.visiblePageNumbers[0]||n!=null&&n!==e.visiblePageNumbers[e.visiblePageNumbers.length-1]?null:{firstVisiblePageNumber:e.visiblePageNumbers[0]??null,lastVisiblePageNumber:e.visiblePageNumbers[e.visiblePageNumbers.length-1]??null}}let t=eo(e.firstVisiblePageNumber),r=eo(e.lastVisiblePageNumber);return t!=null&&r!=null&&t>r?null:{firstVisiblePageNumber:t,lastVisiblePageNumber:r}}function cT(e){return!!(e&&typeof e=="object"&&(Object.hasOwn(e,"pageNumber")||Object.hasOwn(e,"pageIndex")))}function zf(e,t,r){let o=Xe(t)?Math.max(0,t):Math.max(0,(Xe(r)?r:e)-e);return{size:o,end:e+o}}var dT=10,uT=500;function ht(e){return!Xe(e)||e<=0?null:Math.min(uT,Math.max(dT,e))}function Ne(e){return iT(e)}function Ps(e,t){return aT(e,t)}function tc(e,t){return nT(e,t)}function ur(e){return ht(e?.zoomPercent)??Wn}function _o(e,t){return re(e)?.flowMode===t}function Uo(e,t){return re(e)?.layoutMode===t}function to(e,t,r){return _o(e,t)&&Uo(e,r)}function Cs(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Zo(e,t){return sT(e,t)}function ec(e){let t=eo(e?.pageNumber),r=Xl(e?.pageIndex);if(t==null&&r==null||t!=null&&r!=null&&r!==t-1)return null;let o=t??(r??0)+1;return{pageIndex:o-1,pageNumber:o}}function Go(e,t=null){if(e&&typeof e=="object"&&cT(e)&&!ec(e))return null;let r=Ff(e);if(r)return r;if(!e||typeof e!="object")return null;let o=ec(e)??ec(t);return o?Ff({...e,...o}):null}function Xo(e){let t=$t(e?.anchorPageIndex,e?.anchorPageNumber).pageNumber??$t(e?.currentPageIndex,e?.currentPageNumber).pageNumber,r=Go(e?.viewportAnchor??null,{pageNumber:t});return r?t!=null&&r.pageNumber!==t?Lf(r)?r:null:r:null}function rc(e,t,r){let o=Ql(e?.flowMode,e?.layoutMode);if(e&&typeof e=="object"&&o==null)return!0;let n=o?.flowMode??null,i=o?.layoutMode??null;return n!=null&&n!==t||i!=null&&i!==r}function nt(e,t){let r=re(e),o=re(t);return!r||!o?r===o:Kn(r,o)&&Cs(r.mountedPageIndexes,o.mountedPageIndexes)&&Cs(r.mountedPageNumbers,o.mountedPageNumbers)&&vt(r.topSpacer,o.topSpacer,Nt)&&vt(r.bottomSpacer,o.bottomSpacer,Nt)&&vt(r.leftSpacer,o.leftSpacer,Nt)&&vt(r.rightSpacer,o.rightSpacer,Nt)}function Kn(e,t){let r=re(e),o=re(t);return!r||!o?r===o:r.totalPages===o.totalPages&&r.currentPageIndex===o.currentPageIndex&&r.currentPageNumber===o.currentPageNumber&&r.anchorPageIndex===o.anchorPageIndex&&r.anchorPageNumber===o.anchorPageNumber&&Zo(r.viewportAnchor,o.viewportAnchor)&&Cs(r.visiblePageIndexes,o.visiblePageIndexes)&&Cs(r.visiblePageNumbers,o.visiblePageNumbers)&&r.firstVisiblePageNumber===o.firstVisiblePageNumber&&r.lastVisiblePageNumber===o.lastVisiblePageNumber&&vt(r.viewportTop,o.viewportTop,Nt)&&vt(r.viewportBottom,o.viewportBottom,Nt)&&vt(r.viewportHeight,o.viewportHeight,Nt)&&vt(r.viewportLeft,o.viewportLeft,Nt)&&vt(r.viewportRight,o.viewportRight,Nt)&&vt(r.viewportWidth,o.viewportWidth,Nt)&&r.layoutMode===o.layoutMode&&r.flowMode===o.flowMode&&Of(r.scale,o.scale,Df)}function re(e){if(!e||typeof e!="object")return null;let t=Ql(e.flowMode,e.layoutMode);if(!t)return null;let r=$t(e.currentPageIndex,e.currentPageNumber),o=$t(e.anchorPageIndex,e.anchorPageNumber),n=Xe(e.viewportTop)?e.viewportTop:0,i=Xe(e.viewportLeft)?e.viewportLeft:0,s=zf(n,e.viewportHeight,e.viewportBottom),a=zf(i,e.viewportWidth,e.viewportRight),l=$l(e.visiblePageIndexes,e.visiblePageNumbers);if(!l)return null;let c=$l(e.mountedPageIndexes,e.mountedPageNumbers);if(!c)return null;let d=lT({visiblePageNumbers:l.pageNumbers,firstVisiblePageNumber:e.firstVisiblePageNumber,lastVisiblePageNumber:e.lastVisiblePageNumber});if(!d)return null;let u=Go(e.viewportAnchor,{pageIndex:o.pageIndex??r.pageIndex,pageNumber:o.pageNumber??r.pageNumber});return{totalPages:jf(e.totalPages),currentPageIndex:r.pageIndex,currentPageNumber:r.pageNumber,anchorPageIndex:o.pageIndex,anchorPageNumber:o.pageNumber,viewportAnchor:u,visiblePageIndexes:l.pageIndexes,visiblePageNumbers:l.pageNumbers,mountedPageIndexes:c.pageIndexes,mountedPageNumbers:c.pageNumbers,firstVisiblePageNumber:d.firstVisiblePageNumber,lastVisiblePageNumber:d.lastVisiblePageNumber,viewportTop:n,viewportBottom:s.end,viewportHeight:s.size,viewportLeft:i,viewportRight:a.end,viewportWidth:a.size,topSpacer:Xe(e.topSpacer)?Math.max(0,e.topSpacer):0,bottomSpacer:Xe(e.bottomSpacer)?Math.max(0,e.bottomSpacer):0,leftSpacer:Xe(e.leftSpacer)?Math.max(0,e.leftSpacer):0,rightSpacer:Xe(e.rightSpacer)?Math.max(0,e.rightSpacer):0,layoutMode:t.layoutMode,flowMode:t.flowMode,scale:Vf(e.scale)}}function Yt(e,t){let r=re(e);if(!r)return null;let o=r.flowMode??Jl(t.flowMode),n=o==="web"?"vertical":r.layoutMode??Yl(t.layoutMode);return{...r,flowMode:o,layoutMode:n}}var mT=Object.freeze({percent:100,mode:"manual",value:100,fitZoom:null,min:10,max:400,viewportMetrics:null});function $o(e){return{getSnapshot(){return e.get()},subscribe(t){return e.subscribe(t)},observe(t){return e.subscribe(t)}}}function pT(e){let t=Qr(e);return{flowMode:t.flowMode,layoutMode:t.layoutMode,preferredPaginatedLayoutMode:t.preferredPaginatedLayoutMode,zoom:Hf(e)}}function fT(e){return xs(e.selection,e.selectionInfo)}function wT(e){return{editable:e.editable,documentMode:_l(e.documentMode),trackingEnabled:e.trackingEnabled,trackChanges:{enabled:e.review.enabled,visible:e.review.visible,mode:Xr(e.review.mode),replacementMode:$r(e.review.replacementMode)}}}function gT(e){return{enabled:e.comments.enabled,visible:e.comments.visible,readOnly:e.comments.readOnly,allowResolve:e.comments.allowResolve??!1,showResolved:e.comments.showResolved,visibility:Yr(e.comments.visibility),useInternalExternalComments:e.comments.useInternalExternalComments??!1,suppressInternalExternal:e.comments.suppressInternalExternal??!1,enforceVisibilityPolicy:e.comments.enforceVisibilityPolicy??!1,total:e.comments.total??e.comments.items.length}}function Hf(e){return e.zoom?{percent:e.zoom.percent,mode:e.zoom.mode==="fit-width"?"fit-width":"manual",value:typeof e.zoom.value=="number"?e.zoom.value:e.zoom.percent,fitZoom:typeof e.zoom.fitZoom=="number"?e.zoom.fitZoom:null,min:typeof e.zoom.min=="number"?e.zoom.min:10,max:typeof e.zoom.max=="number"?e.zoom.max:400,viewportMetrics:e.zoom.viewportMetrics}:mT}function ST(e){if(!e.viewport)return null;let t=re(e.viewport.value);return{value:t,requestKey:e.viewport.requestKey,previewNavigationRequest:e.viewport.previewNavigationRequest,totalPages:t?.totalPages??null,currentPageIndex:t?.currentPageIndex??null,currentPageNumber:t?.currentPageNumber??null}}function qf(e,t){return{...$o(t.select(pT)),setViewState(o){e.view.setViewState(o)},getZoomState(){return e.view.getZoomState()},setZoomMode(o){e.view.setZoomMode(o)}}}function Wf(e,t){let r=$o(t.select(fT));return{...r,getRects(){return qn(e.preview,r.getSnapshot())},getAnchorRect(o){return Af(e.preview,r.getSnapshot(),o)},getCaretRect(o){return Ul(e.preview,r.getSnapshot(),o)}}}function Kf(e,t){return{...$o(t.select(wT)),setDocumentMode(o){e.documentMode.setDocumentMode(o)},setTrackChangesDisplayMode(o){e.documentMode.setTrackChangesDisplayMode(o)}}}function _f(e,t){return{...$o(t.select(gT)),setCommentsVisible(o){e.commentsDisplay.setCommentsVisible(o)},setCommentsShowResolved(o){e.commentsDisplay.setCommentsShowResolved(o)},setCommentsVisibility(o){e.commentsDisplay.setCommentsVisibility(o)}}}function Uf(e,t){return{...$o(t.select(Hf)),set(o){e.view.setViewState({zoomPercent:o})},setMode(o){e.view.setZoomMode(o)}}}function Zf(e,t){return{...$o(t.select(ST)),getHost(){return e.browserViewport.getHost?.()??null},getScrollContainer(){return e.browserViewport.getScrollContainer?.()??null},observeGeometry(o){return e.browserViewport.observeGeometry(o)},scrollIntoView(o){return e.browserViewport.scrollIntoView(o)},getRect(o){return Wo(e,o)},entitiesAtPoint(o){return e.browserViewport.entitiesAtPoint(o)},contextAtPoint(o){return e.browserViewport.contextAtPoint(o)},positionAtPoint(o){return e.browserViewport.positionAtPoint(o)},requestNavigation(o){return e.browserViewport.requestNavigation(o)},requestNavigationForTextTarget(o){return e.browserViewport.requestNavigationForTextTarget(o)},ackNavigationRequest(o){e.browserViewport.ackNavigationRequest(o)}}}import{isIntegerPath as vT}from"@datalking/begonia-document-model";function Yo(e={}){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,...e}}function hT(e){return Array.isArray(e)&&e.length>0&&vT(e)}function Rs(e){return!!e&&typeof e=="object"&&hT(e.blockPath)}function Xf(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;let t="revisionId"in e?e.revisionId:"id"in e?e.id:null;return typeof t=="string"&&t.length>0?t:null}function yT(e){return e?Rs(e.target)?e.target:(e.targets??[]).find(Rs)??null:null}function bT(e){let t="target"in e?e.target:null,r="targets"in e?e.targets:null;return Rs(t)||(r??[]).some(Rs)}function BT(e,t){if(typeof t!="string"&&bT(t))return t;let r=Xf(t);return r?e.documentApi.trackChanges.get(r):null}function xT(e,t){let r=Gt(lf(e));return zl(e.documentApi,CT(r)?r:null,t)}function CT(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function PT(e,t){return(typeof t?.id=="string"&&t.id.length>0?t.id:typeof t?.revisionId=="string"&&t.revisionId.length>0?t.revisionId:null)??e}function _n(e,t){if(!e||!t)return Yo();let r=he(e);if(!r)return Yo();let o=Xf(t),n=BT(r,t);if(!n)return Yo({revisionId:o});let i=PT(o,n),s=xT(r,n),a=s.target??yT(n);if(!a)return Yo({revisionId:i,trackChange:n});let l=s.selectionTarget;return Yo(l?{revisionId:i,trackChange:n,target:a,selectionTarget:l}:{revisionId:i,trackChange:n,target:a})}function Gf(){return{success:!1}}function RT(e){let t=e.revisionId;if(typeof t=="string"&&t.length>0)return t;let r=e.trackChange?.id;return typeof r=="string"&&r.length>0?r:null}async function Ts(e,t,r={},o={}){let n=_n(e,t),i=he(e);return!i||!n.selectionTarget?Gf():ps(i.selectionHandles,async()=>{if(i.selectionTargets.selectTextTarget(n.selectionTarget))return i.browserViewport.scrollIntoView({target:n.selectionTarget,timeoutMs:r.timeoutMs,continuation:o.continuation});let s=RT(n);return s?i.browserViewport.scrollIntoView({target:{type:"trackedChange",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Gf()},{shouldContinue:o.continuation?.shouldContinue})}function $f(e){if(e==null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jo(e,t){if(Object.is(e,t))return!0;if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Jo(e[n],t[n]))return!1;return!0}if(!$f(e)||!$f(t))return!1;let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let n of r)if(!Object.hasOwn(t,n)||!Jo(e[n],t[n]))return!1;return!0}function oc(e,t,r){let o=e.filter(s=>typeof s.id=="string"&&s.id.length>0);if(o.length===0)return null;let n=t==null?-1:o.findIndex(s=>s.id===t),i=r==="next"?n<0||n>=o.length-1?0:n+1:n<=0?o.length-1:n-1;return o[i]?.id??null}function TT(e){return e.find(t=>t.type==="trackedChange")??null}function kT(e){return[...new Set(e.filter(t=>t.type==="trackedChange").map(t=>t.id))]}function ET(e,t){return e.find(r=>r.id===t)??null}function MT(e,t){let r=kT(t);if(r.length!==1)return null;let o=r[0]??TT(t)?.id??null;if(!o)return null;let n=ET(e,o);return!n||typeof n.id!="string"||n.id.length===0?null:{id:n.id,item:n}}function Yf(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=he(e);return o?MT(r,o.browserViewport.entitiesAtPoint(t)):null}var Jf=Object.freeze([]),IT=Object.freeze([]),AT=Object.freeze([]),NT=Object.freeze({});function nc(e){return structuredClone(e)}function DT(){return{items:IT,permissions:NT,timeline:AT,summary:null,total:0,activeRevisionId:null,activeRevisionIds:Jf,enabled:!1,visible:!1,mode:null,replacementMode:null}}function OT(e,t){return Jo(e,t)}function jT(e){return e?{items:e.revisions,permissions:e.permissions,timeline:e.timeline,summary:e.summary,total:e.revisions.length,activeRevisionId:e.activeRevisionId??null,activeRevisionIds:e.activeRevisionIds??Jf,enabled:e.enabled,visible:e.visible,mode:e.mode,replacementMode:e.replacementMode}:DT()}function Pr(e){let r=he(e)?.session.readState();return jT(r?.review)}function sc(){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,selected:!1}}function ic(e,t){let r=he(e);if(!r||!t)return sc();let o=_n(e,t);if(!o.selectionTarget)return{...o,selected:!1};let n=r.selectionTargets.selectTextTarget(o.selectionTarget),i=r.browserViewport.requestNavigationForTextTarget(o.selectionTarget);return{...o,navigationRequest:i,selected:n}}function en(e,t){let r=he(e);return r?r.reviewFocus.setActiveRevision(t):!1}function Qo(e,t){let r=he(e);return r?t==="next"?r.reviewFocus.nextActiveRevision():r.reviewFocus.previousActiveRevision():null}async function VT(e,t,r,o){if(!he(e))return{success:!1};let i=Pr(e).activeRevisionId??null,s=_n(e,t);s.revisionId&&en(e,s.revisionId);let a=await Ts(e,t,r,{continuation:o});return o.shouldContinue()?(!a.success&&s.revisionId&&en(e,i),a):{success:!1}}function Qf(e){let t=he(e);if(!t)throw new Error("createBrowserEditorTrackChangesController requires a valid browser editor UI source.");let r=Pr(e),o=null,n=new Set,i=ws(),s=()=>{o||n.size===0||(o=t.session.subscribe(()=>{let c=Pr(e);if(OT(r,c)){r=c;return}r=c;for(let d of[...n])d(nc(r))}))},a=()=>{n.size>0||!o||(o(),o=null)},l=c=>(r=Pr(e),n.add(c),s(),c(nc(r)),()=>{n.delete(c),a()});return{getSnapshot(){return r=Pr(e),nc(r)},subscribe:l,observe(c){return l(c)},accept(c){return t.reviewActions.acceptRevision(c)},reject(c){return t.reviewActions.rejectRevision(c)},acceptAll(){return t.reviewActions.acceptAll()},rejectAll(){return t.reviewActions.rejectAll()},setActive(c){return i.invalidate(),en(e,c)},next(){return i.invalidate(),Qo(e,"next")},previous(){return i.invalidate(),Qo(e,"previous")},reveal(c){i.invalidate();let d=_n(e,c);return d.revisionId&&en(e,d.revisionId),ic(e,c)},revealNext(){i.invalidate();let c=Qo(e,"next");return c?ic(e,c):sc()},revealPrevious(){i.invalidate();let c=Qo(e,"previous");return c?ic(e,c):sc()},getAt(c){return r=Pr(e),Yf(e,c,r.items)},scrollTo(c,d){return VT(e,c,d,i.begin())},navigateNext(c){let d=i.begin(),u=Pr(e).activeRevisionId??null,m=Qo(e,"next");return m?Ts(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||en(e,u),p):{success:!1}):Promise.resolve({success:!1})},navigatePrevious(c){let d=i.begin(),u=Pr(e).activeRevisionId??null,m=Qo(e,"previous");return m?Ts(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||en(e,u),p):{success:!1}):Promise.resolve({success:!1})},getRect({id:c}){return Wo(t,{target:{type:"trackedChange",id:c}})}}}function ks(e){let t=LT(e.session),r=Wf(e,t),o=qf(e,t),n=Kf(e,t),i=_f(e,t),s=Zf(e,t),a=Uf(e,t),l=xf(e,t.comments),c=Qf(e),d=Object.assign(t,{host:e,session:e.session,documentApi:e.documentApi,readCommandSnapshot(u){return e.readCommandSnapshot(u)},selection:r,selectionHandles:e.selectionHandles,linkSelection:e.linkSelection,activeLink:e.activeLink,view:o,documentMode:n,comments:l,commentsDisplay:i,commentActions:e.commentActions,commentFocus:e.commentFocus,reviewActions:e.reviewActions,reviewFocus:e.reviewFocus,trackChanges:c,selectionTargets:e.selectionTargets,viewport:s,zoom:a,browserViewport:e.browserViewport,preview:e.preview,overlayState:e.overlayState,overlays:e.overlays??{}});return Object.defineProperty(d,"actor",{configurable:!1,enumerable:!0,get(){return e.actor}}),d}var FT=["insert-math-inline","insert-chart-block","insert-shape-block","remove-selected-ooxml","selected-math-set-plain-text","selected-math-toggle-display-mode","selected-chart-set-title","selected-chart-add-series","selected-chart-add-axis","selected-shape-set-text-body","selected-shape-set-fill","selected-shape-add-child"],zT=new Set(FT);function ew(e){return zT.has(e)}function D(e,t,r,o,n=[],i=!0){return{id:e,title:t,group:r,description:o,keywords:n,slash:i}}var Un=Object.freeze([D("undo","Undo","history","Revert the latest local editing step.",["history"],!1),D("redo","Redo","history","Re-apply the latest reverted step.",["history"],!1),D("zoom","Zoom","view","Set the document zoom level as a percentage.",["view","scale","percent"],!1),D("zoom-fit-width","Fit Width","view","Toggle fit-width zoom mode for the current viewport.",["view","scale","fit","width"],!1),D("document-mode-editing","Editing Mode","review","Switch the editor into direct editing mode.",["edit","write","author"],!1),D("document-mode-suggesting","Suggesting Mode","review","Switch the editor into suggestion authoring mode.",["suggest","track changes","review"],!1),D("document-mode-viewing","Viewing Mode","review","Switch the editor into read-only viewing mode.",["view","read-only","preview"],!1),D("flow-mode-paginated","Paginated Layout","view","Switch the editor into paginated layout mode.",["pagination","pages","print"],!1),D("flow-mode-web","Web Layout","view","Switch the editor into continuous web layout mode.",["web","continuous","scroll"],!1),D("layout-mode-vertical","Vertical Spread","view","Arrange paginated pages in a vertical stack.",["vertical","stack"],!1),D("layout-mode-horizontal","Horizontal Spread","view","Arrange paginated pages in a horizontal strip.",["horizontal","row"],!1),D("layout-mode-book","Book Spread","view","Arrange paginated pages in facing book spreads.",["book","spread","facing"],!1),D("track-changes-display-review","Review Markup","review","Display the document with review markup visible.",["markup","review mode"],!1),D("track-changes-display-original","Original Document","review","Project the document back to its original review baseline.",["original","projection"],!1),D("track-changes-display-final","Final Document","review","Project the document forward to its final accepted review state.",["final","projection"],!1),D("track-changes-display-off","Hide Review Markup","review","Hide tracked-change markup without switching authoring mode.",["hide markup","off"],!1),D("bold","Bold","format","Toggle bold formatting.",["strong","weight"]),D("italic","Italic","format","Toggle italic formatting.",["emphasis"]),D("underline","Underline","format","Toggle underline formatting.",["decoration"]),D("strikethrough","Strikethrough","format","Toggle strikethrough formatting.",["strike","delete","decoration"]),D("font-size","Font Size","format","Set or clear the font size on the current text selection.",["type","points"],!1),D("font-family","Font Family","format","Set or clear the font family on the current text selection.",["typeface","font"],!1),D("text-color","Text Color","format","Set or clear the text color on the current text selection.",["color","foreground"],!1),D("highlight-color","Highlight Color","format","Set or clear text highlight on the current selection.",["highlight","background"],!1),D("paragraph","Paragraph","block","Reset the current block to body paragraph text.",["body","normal"]),D("heading-1","Heading 1","block","Promote the current block to the top heading level.",["title","h1"]),D("heading-2","Heading 2","block","Promote the current block to a section heading.",["section","h2"]),D("heading-3","Heading 3","block","Promote the current block to a subsection heading.",["subsection","h3"]),D("bullet-list","Bulleted List","block","Toggle a bulleted list around the current block.",["list","bullets","unordered"]),D("numbered-list","Numbered List","block","Toggle a numbered list around the current block.",["list","ordered","numbers"]),D("insert-math-inline","Insert Equation","insert","Append an editable math OOXML node to the active text block.",["equation","math","formula"]),D("insert-chart-block","Insert Chart","insert","Insert an editable chart OOXML block after the current block.",["chart","graph","series"]),D("insert-shape-block","Insert Shape","insert","Insert an editable shape OOXML block after the current block.",["shape","callout","diagram"]),D("remove-selected-ooxml","Remove Selected OOXML","insert","Remove the currently selected advanced OOXML node.",["equation","chart","shape","delete"]),D("selected-math-set-plain-text","Edit Selected Equation","insert","Replace the currently selected math OOXML node with plain-text math content.",["equation","math","formula"],!1),D("selected-math-toggle-display-mode","Toggle Equation Display Mode","insert","Switch the selected OOXML equation between inline and block display mode.",["equation","math","display"],!1),D("selected-chart-set-title","Edit Selected Chart Title","insert","Update the title on the currently selected chart OOXML node.",["chart","title"],!1),D("selected-chart-add-series","Add Selected Chart Series","insert","Append a new data series to the currently selected chart OOXML node.",["chart","series","data"],!1),D("selected-chart-add-axis","Add Selected Chart Axis","insert","Append a new axis to the currently selected chart OOXML node.",["chart","axis","scale"],!1),D("selected-shape-set-text-body","Edit Selected Shape Text","insert","Update the text body on the currently selected shape OOXML node.",["shape","text"],!1),D("selected-shape-set-fill","Edit Selected Shape Fill","insert","Update the fill color on the currently selected shape OOXML node.",["shape","fill","color"],!1),D("selected-shape-add-child","Add Selected Shape Child","insert","Append a child shape node to the currently selected OOXML shape.",["shape","group","child"],!1),D("link-set","Set Link","insert","Apply or update a link on the current selection.",["hyperlink","url"],!1),D("link-clear","Clear Link","insert","Remove link formatting from the current selection.",["unlink"],!1),D("comment-create","Create Comment","review","Create a comment at the current selection or caret.",["comment","annotation","note"],!1),D("comments-visible","Show Comments","review","Show comment highlights and threads in the browser editor.",["comments","visible"],!1),D("comments-hidden","Hide Comments","review","Hide comment highlights and threads in the browser editor.",["comments","hidden"],!1),D("comments-show-resolved","Show Resolved Comments","review","Include resolved comments in the comment list and review timeline.",["comments","resolved"],!1),D("comments-hide-resolved","Hide Resolved Comments","review","Filter resolved comments out of the comment list and review timeline.",["comments","resolved"],!1),D("comments-visibility-all","All Comments","review","Show both internal and external comments.",["comments","all"],!1),D("comments-visibility-internal","Internal Comments","review","Filter the comment display to internal comment threads.",["comments","internal"],!1),D("comments-visibility-external","External Comments","review","Filter the comment display to external comment threads.",["comments","external"],!1),D("tracking-toggle","Toggle Track Changes","review","Switch between direct editing and suggestion mode.",["suggesting","review","changes"]),D("track-changes-accept-selection","Accept Selection Changes","review","Accept tracked revisions that overlap the current selection.",["track changes","selection","accept"],!1),D("track-changes-reject-selection","Reject Selection Changes","review","Reject tracked revisions that overlap the current selection.",["track changes","selection","reject"],!1),D("search-set-query","Search","search","Run a document search query.",["find"],!1),D("search-next","Next Search Result","search","Advance to the next current search hit.",["find","next"],!1),D("search-previous","Previous Search Result","search","Move back to the previous current search hit.",["find","previous"],!1),D("search-clear","Clear Search","search","Clear the current search session.",["find","reset"]),D("search-replace-active","Replace Current Search Result","search","Replace the active current search hit.",["find","replace"],!1),D("search-replace-all","Replace All Search Results","search","Replace every current search hit.",["find","replace","all"],!1),D("review-accept-all","Accept All Changes","review","Accept all tracked revisions in the document.",["track changes","approve"]),D("review-reject-all","Reject All Changes","review","Reject all tracked revisions in the document.",["track changes","discard"]),D("proofing-ignore-first","Ignore First Proofing Issue","proofing","Ignore the first current proofing diagnostic.",["spelling","grammar","ignore"]),D("proofing-accept-first","Accept First Proofing Suggestion","proofing","Apply the first current proofing suggestion without tracking.",["spelling","grammar","fix"]),D("proofing-replace-first-tracked","Track First Proofing Fix","proofing","Apply the first current proofing suggestion with tracked changes.",["spelling","grammar","review"],!1)]),yq=Object.freeze(Un.map(e=>e.id)),tn=Object.freeze(Un.filter(e=>!ew(e.id))),bq=Object.freeze(tn.map(e=>e.id)),Bq=new Map(Un.map(e=>[e.id,e]));function HT(e){let t=e.members?.length?e.members:null;return t?t.every(r=>(r.text?.length??0)===0&&r.target?.nodeType!=="text"):(e.text?.length??0)===0&&e.target?.nodeType!=="text"}function qT(e,t){if(!t||e.length===0)return!1;let r=new Map(t.map(o=>[o.id,o]));return e.every(o=>{let n=r.get(o);return n?HT(n):!1})}function ac(e,t){return le([...e.activeChangeIds??[],...e.selection.trackedChangeIds??[]],t)}function lc(e){let t=le(e.liveSelectionInfo?.activeChangeIds,e.revisions);return t.length>0?t:le(e.liveSelection.trackedChangeIds,e.revisions)}function WT(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&!e.effectiveSelection.selection.empty&&e.liveSelection.from>=e.effectiveSelection.selection.from&&e.liveSelection.from<=e.effectiveSelection.selection.to}function KT(e,t){return e.length>0&&e.length<t.length&&e.every(r=>t.includes(r))}function _T(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.liveReviewChangeIds.length>0&&e.effectiveReviewChangeIds.length>0&&!(WT(e)&&KT(e.liveReviewChangeIds,e.effectiveReviewChangeIds))&&!ar(e.liveReviewChangeIds,e.effectiveReviewChangeIds)}function UT(e){let t=ac(e.effectiveSelection,e.revisions),r=lc({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions});return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&!e.effectiveSelection.selection.empty&&e.liveSelection.from===(e.boundary==="start"?e.effectiveSelection.selection.from:e.effectiveSelection.selection.to)&&e.effectiveSelection.selection.from!==e.effectiveSelection.selection.to&&r.length===0&&t.length>0}function cc(e){return UT({...e,boundary:"end"})}function ZT(e){let t=ac(e.effectiveSelection,e.revisions),r=lc({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions}),o=qT(t,e.revisions);return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.effectiveSelection.selection.empty&&e.liveSelection.from===e.effectiveSelection.selection.to&&r.length===0&&t.length>0&&!o}function yt(e){let t=lc(e);if(!e.effectiveSelection)return t;if(cc({liveSelection:e.liveSelection,liveActiveChangeIds:ce(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];if(ZT({liveSelection:e.liveSelection,liveActiveChangeIds:ce(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];let r=ac(e.effectiveSelection,e.revisions);return _T({liveSelection:e.liveSelection,liveReviewChangeIds:t,effectiveReviewChangeIds:r,effectiveSelection:e.effectiveSelection})?t:r.length>0?r:t}import{readSyntheticSideStoryDocOriginPath as GT}from"@datalking/begonia-doc-service/v1";var XT="Detached side-story surfaces are read-only. Route mutations through the host document controller.";function rn(e){return GT(e?.document??null)!=null}function Jt(e){return e?rn(e)?XT:e.editable?null:"Document is read-only in the current document mode.":"Editor is not ready."}function it(e){return Jt(e)==null}function Es(e){if(!e)return"Editor is not ready.";let t=Jt({editable:e.editable,document:e.document});return t||(e.commentsDisplay.enabled?e.commentsDisplay.readOnly?"Comments are read-only in the current document mode.":null:"Comments are disabled for this editor.")}function dc(e,t,r=null){let o=Es(e);return o||(r?.target||r?.selectionTarget||t&&Ht(t)?null:"Place the caret in text or select text before creating a comment.")}function $T(e){return Xi([...e.activeChangeIds??[],...e.selection?.trackedChangeIds??[]])}function Rr(e,t=$T(e)){return fl({empty:e.empty,target:e.selectionTarget,activeMarks:[...e.activeMarks??[]],activeCommentIds:[...e.activeCommentIds??[]],activeChangeIds:[...t],...typeof e.text=="string"?{text:e.text}:{}},e.selectionKind,e.selectionKind==="node"&&e.selectionTarget!=null&&e.nodeSelectionTarget!=null)}import{createEditorSelectionSnapshot as YT}from"@datalking/begonia-editor-contracts";import{resolveEditorSelectionRootOffsets as tw}from"@datalking/begonia-editor-contracts";function Ms(e){let t=tw(e);return t?{...t,empty:e.empty,trackedChangeIds:e.trackedChangeIds}:null}function rw(e){let t=tw(e);return t?{kind:e.kind,...t,empty:e.empty,editable:e.editable,trackedChangeIds:[...e.trackedChangeIds],block:{...e.block},formatting:structuredClone(e.formatting)}:null}function q(e,t=!0,r=!1,o=null,n=!1){return{active:r,disabled:t,...n?{mixed:!0}:{},value:o,title:e.title,description:e.description??null,group:e.group??null}}function on(e){let t=Qr(e);return t.flowMode==="web"?t.preferredPaginatedLayoutMode:t.layoutMode}function ow(e){return e.flowMode==="paginated"||e.flowMode==="web"}function nw(e){return e.zoom?.mode==="fit-width"?"fit-width":"manual"}function iw(e,t,r,o){return e!=null||!t||r?e:`Collapsed ${o} formatting requires a live editor surface. Select text to format in headless mode.`}function sw(e,t){return e||!t}function aw(e){let t=e&&typeof e=="object"?e.nodeType:null;return t==="paragraph"||t==="heading"}function JT(e,t){return t?t.selectionKind==="node"&&aw(t.nodeSelectionTarget):aw(Ie(e??null))}function nn(e){let t=e?.catalog??tn,r=e?.commandIds;if(!r||r.length===0)return t;let o=e?.catalog??Un,n=new Map(o.map(i=>[i.id,i]));return r.map(i=>n.get(i)).filter(i=>i!=null)}function lw(e){return e.revisions}function cw(e,t){let r=Qr(e),o=e.search.activeHitId?e.search.hits.findIndex(l=>l.hitId===e.search.activeHitId):-1,n=lw(e),i=re(e.viewport),s=t?YT(t.selection,e.selection.range.revision,e.selection.range.range.anchor.story):e.toolbar.selection??e.selection,a=t?Rr(t):e.selectionInfo;return{selection:uw(s,a,n),documentMode:e.documentMode,editable:e.editable,trackChanges:e.trackChanges,flowMode:r.flowMode,layoutMode:r.layoutMode,preferredPaginatedLayoutMode:r.preferredPaginatedLayoutMode,zoomPercent:e.zoomPercent,viewport:i,totalPages:i?.totalPages??null,currentPageIndex:i?.currentPageIndex??null,currentPageNumber:i?.currentPageNumber??null,searchQuery:e.search.query,searchHitCount:e.search.hits.length,activeSearchHitId:e.search.activeHitId,activeSearchHitIndex:o,revisionCount:n.length,firstRevisionId:n[0]?.id??null,proofingDiagnosticCount:e.proofing.diagnostics.length,firstProofingDiagnosticId:e.proofing.diagnostics[0]?.diagnosticId??null}}function dw(e,t,r,o,n,i){let s=i?.selection??rw(t.selection)??{from:0,to:0,empty:!0},a=t.trackChanges.enabled,l=lw(t),c=yt({liveSelection:Ms(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:l,effectiveSelection:i}),d=t.editable?ir({editable:t.editable},o,i):"Document is read-only in the current document mode.",u=iw(d,s.empty,n,"inline"),m=iw(d,s.empty,n,"text-style"),p=t.editable?dc({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i):dc({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i),f=JT(o,i),g=sw(!t.editable||!s.editable&&!f,n),v=s.formatting.mixed??{},E=sw(d!=null,n);switch(r.id){case"bold":return q(r,u!=null,s.formatting.bold,s.formatting.bold,v.bold===!0);case"italic":return q(r,u!=null,s.formatting.italic,s.formatting.italic,v.italic===!0);case"underline":return q(r,u!=null,s.formatting.underline,s.formatting.underline,v.underline===!0);case"strikethrough":return q(r,u!=null,s.formatting.strike,s.formatting.strike,v.strike===!0);case"font-size":return q(r,m!=null,s.formatting.fontSize!=null||v.fontSize===!0,s.formatting.fontSize,v.fontSize===!0);case"font-family":return q(r,m!=null,s.formatting.fontFamily!=null||v.fontFamily===!0,s.formatting.fontFamily,v.fontFamily===!0);case"text-color":return q(r,m!=null,s.formatting.color!=null||v.color===!0,s.formatting.color,v.color===!0);case"highlight-color":return q(r,m!=null,s.formatting.highlight!=null||v.highlight===!0,s.formatting.highlight,v.highlight===!0);case"paragraph":return q(r,g,s.block.kind==="paragraph",s.block.kind);case"heading-1":return q(r,g,s.block.kind==="heading"&&s.block.headingLevel===1,s.block.headingLevel);case"heading-2":return q(r,g,s.block.kind==="heading"&&s.block.headingLevel===2,s.block.headingLevel);case"heading-3":return q(r,g,s.block.kind==="heading"&&s.block.headingLevel===3,s.block.headingLevel);case"bullet-list":return q(r,g,s.block.listKind==="bullet_list",s.block.listKind);case"numbered-list":return q(r,g,s.block.listKind==="ordered_list",s.block.listKind);case"zoom":return q(r,!1,!1,t.zoomPercent);case"zoom-fit-width":return q(r,!1,nw(t)==="fit-width",nw(t));case"document-mode-editing":return q(r,!1,t.documentMode==="editing",t.documentMode);case"document-mode-suggesting":return q(r,!t.trackChanges.enabled,t.documentMode==="suggesting",t.documentMode);case"document-mode-viewing":return q(r,!1,t.documentMode==="viewing",t.documentMode);case"flow-mode-paginated":return q(r,!1,t.flowMode==="paginated",t.flowMode);case"flow-mode-web":return q(r,!1,t.flowMode==="web",t.flowMode);case"layout-mode-vertical":return q(r,!1,on(t)==="vertical",on(t));case"layout-mode-horizontal":return q(r,!ow(t),on(t)==="horizontal",on(t));case"layout-mode-book":return q(r,!ow(t),on(t)==="book",on(t));case"track-changes-display-review":return q(r,!1,t.trackChanges.mode==="review",t.trackChanges.mode);case"track-changes-display-original":return q(r,t.documentMode!=="viewing",t.trackChanges.mode==="original",t.trackChanges.mode);case"track-changes-display-final":return q(r,t.documentMode!=="viewing",t.trackChanges.mode==="final",t.trackChanges.mode);case"track-changes-display-off":return q(r,!1,t.trackChanges.mode==="off",t.trackChanges.mode);case"comments-visible":return q(r,!t.commentsDisplay.enabled,t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-hidden":return q(r,!t.commentsDisplay.enabled,!t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-show-resolved":return q(r,!t.commentsDisplay.enabled,t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-hide-resolved":return q(r,!t.commentsDisplay.enabled,!t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-visibility-all":return q(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="all",t.commentsDisplay.visibility);case"comments-visibility-internal":return q(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="internal",t.commentsDisplay.visibility);case"comments-visibility-external":return q(r,!t.commentsDisplay.enabled,t.commentsDisplay.visibility==="external",t.commentsDisplay.visibility);case"tracking-toggle":return q(r,!t.editable||!a,a&&t.documentMode==="suggesting",t.documentMode);case"comment-create":return q(r,p!=null,!1,t.comments.length);case"link-set":return q(r,E,s.formatting.link||v.linkHref===!0,s.formatting.linkHref,v.link===!0||v.linkHref===!0);case"link-clear":return q(r,E||!s.formatting.link&&v.linkHref!==!0,s.formatting.link||v.linkHref===!0,s.formatting.linkHref,v.link===!0||v.linkHref===!0);case"track-changes-accept-selection":case"track-changes-reject-selection":return q(r,c.length===0||!t.editable,c.length>0,c);case"review-accept-all":case"review-reject-all":return q(r,l.length===0||!t.editable,!1,l.length)}let S=(t.toolbar.commands??{})[r.id];if(S)return{...S,title:r.title,description:r.description??null,group:r.group??null};switch(r.id){case"search-set-query":return q(r,!1,t.search.query.length>0,t.search.query);case"search-next":case"search-previous":return q(r,t.search.hits.length===0,!1,t.search.activeHitId);case"search-clear":return q(r,t.search.query.length===0,!1,t.search.query);case"search-replace-active":return q(r,t.search.hits.length===0||!t.editable,!1,t.search.activeHitId);case"search-replace-all":return q(r,t.search.hits.length===0||!t.editable,!1,t.search.hits.length);case"proofing-ignore-first":case"proofing-accept-first":case"proofing-replace-first-tracked":return q(r,t.proofing.diagnostics.length===0||!t.editable,!1,t.proofing.diagnostics[0]?.diagnosticId??null);case"insert-math-inline":return q(r,!t.editable||!s.editable||f,!1,s.block.kind);case"insert-chart-block":case"insert-shape-block":return q(r,!t.editable,!1,t.selection.block.kind);case"remove-selected-ooxml":return q(r,t.advancedOoxml.selected==null||!t.editable,t.advancedOoxml.selected!=null,t.advancedOoxml.selected?.objectId??null);case"selected-math-set-plain-text":case"selected-math-toggle-display-mode":return q(r,t.advancedOoxml.selected?.family!=="math"||!t.editable,t.advancedOoxml.selected?.family==="math",t.advancedOoxml.selected?.objectId??null);case"selected-chart-set-title":case"selected-chart-add-series":case"selected-chart-add-axis":return q(r,t.advancedOoxml.selected?.family!=="chart"||!t.editable,t.advancedOoxml.selected?.family==="chart",t.advancedOoxml.selected?.objectId??null);case"selected-shape-set-text-body":case"selected-shape-set-fill":case"selected-shape-add-child":return q(r,t.advancedOoxml.selected?.family!=="shape"||!t.editable,t.advancedOoxml.selected?.family==="shape",t.advancedOoxml.selected?.objectId??null);default:return q(r)}}function uw(e,t,r){if(!e)return null;let o=Do(e,r),n=t?Ur(t,o,r):null;return xs(o,n)}function mw(e,t){let r=Qr(e),o=re(e.viewport?.value??null),n=e.selection?Do(e.selection,e.review.revisions):e.selection,i=n??e.selection,s=e.selectionInfo&&i?Ur(e.selectionInfo,i,e.review.revisions):e.selectionInfo,a=e.advancedOoxml;return{...e,flowMode:r.flowMode,layoutMode:r.layoutMode,preferredPaginatedLayoutMode:r.preferredPaginatedLayoutMode,selection:n,selectionInfo:s,viewport:e.viewport?{...e.viewport,value:o,totalPages:o?.totalPages??null,currentPageIndex:o?.currentPageIndex??null,currentPageNumber:o?.currentPageNumber??null}:e.viewport,trackChanges:t?.trackChanges??{enabled:e.review.enabled,visible:e.review.visible,mode:e.review.mode,replacements:e.review.replacementMode},viewportRequestKey:t?.viewportRequestKey??e.viewport?.requestKey??null,previewNavigationRequest:t?.previewNavigationRequest??e.viewport?.previewNavigationRequest??null,advancedOoxml:t?.advancedOoxml??a}}import{cloneEditorSelectionSnapshot as Cw,deriveEditorUiSnapshot as gk}from"@datalking/begonia-editor-contracts";function QT(e){let t=[],r=new Set;for(let o of e)typeof o!="string"||o.length===0||r.has(o)||(r.add(o),t.push(o));return t}function pw(e,t){if(t==null)return[...e];let r=new Set(Ze(t).values());return e.filter(o=>r.has(o))}function ek(e){return pw(At(e.selectionInfo?.activeCommentIds,Ze(e.comments)),e.comments)}function uc(e){let t=ek(e);return{activeCommentIds:t,activeCommentId:t.length===1?t[0]??null:null}}function mc(e){return pw(At(QT([...e.explicitActiveCommentIds??[],e.explicitActiveCommentId]),Ze(e.comments)),e.comments)}function sn(e){let t=uc(e);if(t.activeCommentIds.length>0)return t;let r=mc(e);return{activeCommentIds:r,activeCommentId:r.length===1?r[0]??null:null}}function pc(e){let t=[],r=new Set;for(let o of e)typeof o!="string"||o.length===0||r.has(o)||(r.add(o),t.push(o));return t}function tk(e){let t=pc(le(e.selectionInfo?.activeChangeIds,e.revisions));if(!e.revisions||e.revisions.length===0)return t;let r=new Set(e.revisions.map(o=>o.id));return t.filter(o=>r.has(o))}function ro(e){let t=tk(e);return{activeRevisionIds:t,activeRevisionId:t.length===1?t[0]??null:null}}function rk(e){let t=pc([...e.explicitActiveRevisionIds??[],e.explicitActiveRevisionId]),r=pc(le(t,e.revisions));if(!e.revisions||e.revisions.length===0)return r;let o=new Set(e.revisions.map(n=>n.id));return r.filter(n=>o.has(n))}function fw(e){let t=ro(e);if(t.activeRevisionIds.length>0)return t;let r=rk(e);return{activeRevisionIds:r,activeRevisionId:r.length===1?r[0]??null:null}}function Tr(e){return Object.freeze([...e])}var oo=Object.freeze({history:Tr(["undo","redo"]),view:Tr(["zoom","zoom-fit-width","flow-mode-paginated","flow-mode-web","layout-mode-vertical","layout-mode-horizontal","layout-mode-book"]),formatting:Tr(["bold","italic","underline","strikethrough","font-size","font-family","text-color","highlight-color","link-set","link-clear"]),blocks:Tr(["paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list"]),review:Tr(["document-mode-editing","document-mode-suggesting","document-mode-viewing","comment-create","comments-visible","comments-hidden","comments-show-resolved","comments-hide-resolved","comments-visibility-all","comments-visibility-internal","comments-visibility-external","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection","track-changes-display-review","track-changes-display-original","track-changes-display-final","track-changes-display-off","review-accept-all","review-reject-all"]),search:Tr(["search-set-query","search-next","search-previous","search-clear","search-replace-active","search-replace-all"]),proofing:Tr(["proofing-ignore-first","proofing-accept-first","proofing-replace-first-tracked"]),advancedOoxml:Tr(["insert-math-inline","insert-chart-block","insert-shape-block","remove-selected-ooxml","selected-math-set-plain-text","selected-math-toggle-display-mode","selected-chart-set-title","selected-chart-add-series","selected-chart-add-axis","selected-shape-set-text-body","selected-shape-set-fill","selected-shape-add-child"])}),Is=Object.freeze([{id:"history",label:"History",commandIds:oo.history},{id:"view",label:"View",commandIds:oo.view},{id:"formatting",label:"Formatting",commandIds:oo.formatting},{id:"blocks",label:"Blocks",commandIds:oo.blocks},{id:"review",label:"Review",commandIds:oo.review},{id:"search",label:"Search",commandIds:oo.search},{id:"proofing",label:"Proofing",commandIds:oo.proofing}]),n1=Object.freeze(Is.flatMap(e=>[...e.commandIds]));function ok(e){return[{id:"commands",label:"Commands",commandIds:e.map(t=>t.id)}]}function nk(e,t){if(t&&t.length>0)return t;if(e.length===0)return[];let r=new Set(Is.flatMap(n=>n.commandIds));return e.every(n=>r.has(n.id))?Is:ok(e)}function ik(e){return e?[...e]:[]}function sk(e,t){return{id:e.id,title:e.title,description:e.description??null,group:e.group??null,keywords:ik(e.keywords),slash:e.slash??!1,state:t}}function ak(e,t,r){return e.flatMap(o=>{let n=t.get(o);return n?[sk(n,r[o]??null)]:[]})}function ww(e){let t=nk(e.catalog,e.sections),r=new Map(e.catalog.map(o=>[o.id,o]));return t.map(o=>({id:o.id,label:o.label,items:ak(o.commandIds,r,e.commands)})).filter(o=>o.items.length>0)}import{normalizeCommittedDocument as dk}from"@datalking/begonia-document-model";import{createDocumentRuntimeKernel as uk}from"@datalking/begonia-document-api/v1";import{resolveRevisionProjectedDocument as mk}from"@datalking/begonia-engine";import{preserveSyntheticSideStoryDocMetadata as lk,readSyntheticSideStoryDocOriginPath as gw}from"@datalking/begonia-doc-service/v1";function ck(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function Sw(e){let t=null;for(let r of e){let o=gw(r);if(o){if(t&&!ck(t,o))return null;t=o}}return t}function bt(e,t){return gw(e)?lk(e,t):t}function pk(e,t){let r=null,o=null,n=s=>((s!==r||!o)&&(r=s,o=dk(s)),o),i=()=>n(e());return{readDocument(){return i()},replaceDocument(){throw new Error("Browser projected review runtime is read-only.")},...t?{documentSource:{readSnapshot(){let s=t.readSnapshot();return{document:i(),revision:s.revision}},subscribeDocument(s){return t.subscribeDocument(s)}}}:{}}}function vw(e){return e??null}function hw(e,t,r){return bt(e,mk(e,t,r))}function yw(e,t,r){let o=fk(e,t,r),n=!1,i=()=>{if(n)throw new Error("Browser projected runtime bank is disposed.")};return{resolveRuntime(s="tracked"){return i(),o.projections.resolveRuntime(s)},resolveProjection(s="tracked",a={}){return i(),o.projections.resolveProjection(s,a)},resolveLayout(s="tracked",a={}){return i(),o.projections.resolveLayout(s,a)},invalidate(){i(),o.projections.invalidate()},dispose(){n||(n=!0,o.dispose())}}}function fk(e,t,r){return uk(pk(e,r),{review:{replacementMode:t}})}function bw(e){return e==="final"||e==="original"?e:null}function mr(e,t){return typeof e=="boolean"?e:t}function wk(e,t){return Yr(e)??t}function As(e,t){return e!=null?Bs(e):t===!1?"editing":"suggesting"}function an(e,t){let r=mr(t?.enabled,!0),o=mr(t?.visible,e!=="viewing"),n=e==="viewing"?o?"review":"original":"review";return{enabled:r,visible:o,mode:Xr(t?.mode)??n,replacements:$r(t?.replacements)??"paired"}}function Bw(e,t){let r=mr(t?.enabled,!0),o=mr(t?.visible,e!=="viewing"),n=mr(t?.readOnly,e==="viewing"),i=mr(t?.useInternalExternalComments,!1),s=mr(t?.suppressInternalExternal,!1),a=s?"external":wk(t?.visibility,"all");return{enabled:r,visible:o,readOnly:n,allowResolve:n?!1:mr(t?.allowResolve,!0),showResolved:mr(t?.showResolved,!1),visibility:a,useInternalExternalComments:i,suppressInternalExternal:s,enforceVisibilityPolicy:i||s}}function xw(e,t,r){if(!e)return e??null;let o=t?.suppressInternalExternal?!1:e.canViewInternalComments,n=r??e.permissionResolver,i=t?.permissionResolver??e.commentPermissionResolver;return o===e.canViewInternalComments&&n===e.permissionResolver&&i===e.commentPermissionResolver?e:{...e,canViewInternalComments:o,permissionResolver:n,commentPermissionResolver:i}}function ln(e){return e!=="viewing"}function kr(e,t){return e==="suggesting"&&t.enabled}function Ns(e,t,r,o=!1){return e.collaborative&&!o||t!=="viewing"?null:r.mode==="original"||r.mode==="final"?r.mode:null}function Me(e,t,r){return r==null?e:bt(e,hw(e,t.schema,r))}function fc(e,t,r,o,n,i){let s=e.view?.dom;s&&(s.dataset.aldDocumentMode=t,s.dataset.aldFlowMode=r,s.dataset.aldLayoutMode=o,s.dataset.aldTrackChangesMode=n.mode,s.dataset.aldTrackChangesVisible=String(n.visible),s.dataset.aldTrackChangesEnabled=String(n.enabled),s.dataset.aldCommentsVisible=String(i.visible),s.dataset.aldCommentsReadOnly=String(i.readOnly),s.dataset.aldCommentsShowResolved=String(i.showResolved),s.dataset.aldCommentsVisibility=i.visibility)}var Pw=["undo","redo","bold","italic","underline","strikethrough","paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list","link-set","link-clear","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection"];function Sk(e){return kr(e.documentMode,e.trackChanges)}function vk(e){return e.collaboration.collaborative??!1}function hk(e){return{selection:Cw(e.selection),editable:e.editable,trackingEnabled:Sk(e),collaborative:vk(e),canUndo:e.canUndo,canRedo:e.canRedo,commandStates:e.commandStates}}function yk(e,t=e.toolbar.commands){return{selection:e.selection,editable:e.editable,documentMode:e.documentMode,trackChanges:e.trackChanges,collaboration:e.collaboration,canUndo:t.undo?.disabled===!1,canRedo:t.redo?.disabled===!1,commandStates:t}}function bk(e,t){return t?.commands??e.toolbar.commands}function Ds(e){return gk(hk(e))}function Bk(e,t){let r=Ds(yk(e,bk(e,t))),o=t?.catalog??[];return{...r,catalog:o,sections:ww({catalog:o,commands:r.commands})}}function cn(e,t){let r=Bk(e,t),o=e.zoom??{mode:"manual",value:e.zoomPercent,fitZoom:null,min:10,max:400,viewportMetrics:null},n=e.commentsDisplay??{enabled:!1,visible:!1,readOnly:!1,showResolved:!1,visibility:"all"},i=e.trackChanges??{enabled:!1,visible:!1,mode:"off",replacements:"paired"},s=e.collaboration??{collaborative:!1,mode:"none",reconfigurable:!1,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null},a=ro({revisions:e.revisions,selectionInfo:e.selectionInfo}),l=sn({comments:e.comments,selectionInfo:e.selectionInfo,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds}),c=e.activeRevisionId??a.activeRevisionId,d=e.activeRevisionIds??a.activeRevisionIds;return{selection:Cw(e.selection),selectionInfo:Ko(e.selectionInfo),trackingEnabled:r.trackingEnabled,collaborative:r.collaborative,commands:r.commands,editable:e.editable,documentMode:e.documentMode,flowMode:e.flowMode,layoutMode:e.layoutMode,preferredPaginatedLayoutMode:e.preferredPaginatedLayoutMode,commandCatalog:r.catalog,toolbar:r,viewport:{value:e.viewport,requestKey:e.viewportRequestKey,previewNavigationRequest:e.previewNavigationRequest,totalPages:e.viewport?.totalPages??null,currentPageIndex:e.viewport?.currentPageIndex??null,currentPageNumber:e.viewport?.currentPageNumber??null},zoom:{percent:e.zoomPercent,mode:o.mode,value:o.value,fitZoom:o.fitZoom,min:o.min,max:o.max,viewportMetrics:o.viewportMetrics},comments:{items:e.comments,permissions:e.commentPermissions,total:e.comments.length,activeCommentId:l.activeCommentId,activeCommentIds:l.activeCommentIds,enabled:n.enabled,visible:n.visible,readOnly:n.readOnly,allowResolve:n.allowResolve,showResolved:n.showResolved,visibility:n.visibility,useInternalExternalComments:n.useInternalExternalComments,suppressInternalExternal:n.suppressInternalExternal,enforceVisibilityPolicy:n.enforceVisibilityPolicy},review:{revisions:e.revisions,permissions:e.reviewPermissions,timeline:e.reviewTimeline,summary:e.reviewTimelineSummary,activeRevisionId:c,activeRevisionIds:d,enabled:i.enabled,visible:i.visible,mode:i.mode,replacementMode:i.replacements},search:{query:e.search.query,hits:e.search.hits,activeHitId:e.search.activeHitId},proofing:{diagnostics:e.proofing.diagnostics},advancedOoxml:{selected:e.advancedOoxml.selected},collaboration:{...s,connected:s.connected??!1}}}function Zn(e,t=nn(void 0)){let r=e.getState(),o=e.surface?.state,n=e.surface?.view!=null,i=e.readEffectiveSelection?.()??e.captureEffectiveSelection?.()??null;return{editor:r,context:cw(r,i),catalog:t,commands:Object.fromEntries(t.map(s=>[s.id,dw(e,r,s,o,n,i)]))}}function Rw(e,t=nn(void 0)){let r=Zn(e,t),o=e.getState();return{editor:mw(cn(o,r),{trackChanges:o.trackChanges,viewportRequestKey:o.viewportRequestKey,previewNavigationRequest:o.previewNavigationRequest,advancedOoxml:{selected:o.advancedOoxml.selected}}),context:r.context,catalog:r.catalog,commands:r.commands}}import{documentWideMutationEffect as xk}from"@datalking/begonia-editor-contracts";function wc(e){return e?e.documentService.readDocument():null}function gc(e){return Ue(e)?.view??null}function Sc(e){return Ue(e)?.automation??null}function vc(e,t){let r=Ue(e);return r?(r.replaceDocument(t,{origin:"api",intent:"replace-browser-document",effects:[xk("content")]}),!0):!1}function Ck(e){return e?"documentApi"in e?Ue(e):e:null}function no(e,t){let r=Ck(e),o=r?.view;if(!o?.state||typeof o.dispatch!="function")return!1;let n=r,i=Ge(o.state.doc,t);if(!i)return!1;let s=Z(o.state,i.from,i.to);return s?qe(n,s):!1}var Os=Symbol("captureBrowserEditorPositionAtPointInternal");import{NodeSelection as kw}from"prosemirror-state";function Pk(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Math.trunc(t),e.doc.content.size))}function Tw(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(Math.trunc(t),e.doc.content.size))}function Rk(e,t,r){let o=e.view.dom,n=e.view.dom.ownerDocument,i=typeof o.getBoundingClientRect=="function"?o.getBoundingClientRect():null;if(i&&Number.isFinite(i.left)&&Number.isFinite(i.right)&&Number.isFinite(i.top)&&Number.isFinite(i.bottom)&&(t<i.left||t>i.right||r<i.top||r>i.bottom))return!1;if(!o||!n||typeof n.elementFromPoint!="function"||typeof o.contains!="function")return!0;let s=n.elementFromPoint(t,r);return!s||o.contains(s)}function Tk(e,t){let r=Z(e,t,t);if(!r)return null;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function kk(e,t){try{return e.apply(e.tr.setSelection(kw.create(e.doc,t)))}catch{return null}}function Ek(e,t){let r=e.doc.nodeAt(t);return!!(r&&kw.isSelectable(r)&&(r.isLeaf||r.isAtom))}function Mk(e,t){return[Tw(e,t?.inside),Tw(e,t?.pos)].filter((o,n,i)=>o!=null&&i.indexOf(o)===n).find(o=>Ek(e,o))??null}function dn(e){let t=e.surface.view;if(!t?.state||typeof t.posAtCoords!="function"||!Rk(e.surface,e.clientX,e.clientY))return null;let r=t.posAtCoords({left:e.clientX,top:e.clientY})??null;if((e.mode??"node-or-text")!=="text-only"){let s=Mk(t.state,r);if(s!=null){let a=kk(t.state,s);if(a)return{pos:s,state:a}}}let n=Pk(t.state,r?.pos);if(n==null)return null;let i=Tk(t.state,n);return i?{pos:n,state:i}:null}function Ik(e){let t=e?.selectionTarget;if(t&&t.segments.length===1&&t.segments[0]?.range.start===t.segments[0]?.range.end){let i=t.segments[0];return{kind:"text",blockId:i.blockId,offset:i.range.start}}let r=e?.target;if(!r||typeof r!="object"||!("blockId"in r)||!("range"in r))return null;let o=typeof r.blockId=="string"?r.blockId:null,n=r.range;return!o||!n||typeof n!="object"||typeof n.start!="number"||typeof n.end!="number"||n.start!==n.end?null:{kind:"text",blockId:o,offset:n.start}}function Ak(e,t){let r=dn({surface:e.surface,clientX:t.clientX,clientY:t.clientY});if(!r?.state.selection.empty)return null;let o=Ee(r.state).target,n=o?.segments[0];return!o||o.segments.length!==1||!n||n.range.start!==n.range.end?null:{point:{kind:"text",blockId:n.blockId,offset:n.range.start},target:{kind:"text",segments:[{blockId:n.blockId,range:{start:n.range.start,end:n.range.end}}]}}}function Nk(e,t){return e&&typeof e=="object"&&"kind"in e&&e.kind==="text"?t:e}function Ew(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Ew(t);return e}function Dk(e,t){let r=e.selectionTarget?.segments[0],o=t.segments[0];return e.selectionTarget?.segments.length===1&&r&&r.blockId===o.blockId&&r.range.start===o.range.start&&r.range.end===o.range.end?e:Ew(structuredClone({...e,selectionTarget:t,target:Nk(e.target,t)}))}function io(e,t){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let r=e[Os]?.(t)??null;if(!r||!r.selection.empty)return null;let o=Ak(e,t),n=o?.point??Ik(r),i=o?.target??(n?{kind:"text",segments:[{blockId:n.blockId,range:{start:n.offset,end:n.offset}}],...r.selectionTarget?.story?{story:structuredClone(r.selectionTarget.story)}:{}}:null);if(!n||!i)return null;let s=o?Dk(r,o.target):r;return{point:n,target:i,capture:s}}function Mw(e){return{readDocument(){return wc(e)},replaceDocument(t){return vc(e,t)},readView(){return gc(e)},readAutomation(){return Sc(e)}}}function Ok(e){return{positionAtPoint(t){return io(e,t)},selectTextTarget(t){return El(e.surface,t)},selectCommentTarget(t){return no(e,t)}}}function Iw(e){return{selectionHandles:e,linkSelection:e,activeLink:e,view:e,documentMode:e,commentsDisplay:e,commentActions:e,commentFocus:e,reviewActions:e,reviewFocus:e,selectionTargets:Ok(e)}}import{createCanonicalRevisionIdsByAlias as jk,resolveCanonicalRevisionId as Vk,resolveTrackedOverlapParentIdMap as Lk}from"@datalking/begonia-engine";var js=3,Fk=[[0,0],[-js,0],[js,0],[0,-js],[0,js]];function pr(e,t){if(!e||typeof e.getAttribute!="function")return null;let r=e.getAttribute(t);return typeof r=="string"?r.trim():null}function Nw(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function zk(e,t){return!t||!e.includes(t)?[...e]:[t,...e.filter(r=>r!==t)]}function Hk(e){let t=Nw(pr(e,"data-track-change-ids"));if(t.length>0)return zk(t,pr(e,"data-track-change-preferred-target-id"));let r=pr(e,"data-track-change-id");if(r)return[r];let o=pr(e,"data-change-id");return o?[o]:[]}function qk(e){return!!(pr(e,"data-ald-comment-anchor")||pr(e,"data-ald-comment-range-start")||pr(e,"data-ald-comment-range-end"))}function Wk(e){let t=Nw(pr(e,"data-comment-ids"));if(t.length>0)return t;let r=pr(e,"data-thread-id");return r&&qk(e)?[r]:[]}function Dw(e,t){let r=e??null;for(;r;){if(r===t)return!0;r=r.parentElement??null}return!1}function Kk(e,t,r){if(!e||!Dw(e,t))return[];let o=[],n=e;for(;n;){for(let i of Hk(n)){let s=`trackedChange:${i}`;r.has(s)||(r.add(s),o.push({kind:"trackedChange",id:i}))}for(let i of Wk(n)){let s=`comment:${i}`;r.has(s)||(r.add(s),o.push({kind:"comment",id:i}))}if(n===t)break;n=n.parentElement??null}return o}function _k(e,t,r){let o=e?.ownerDocument??null;if(!o)return[];let n=(()=>{if(typeof o.elementsFromPoint!="function")return[];try{return o.elementsFromPoint(t,r)??[]}catch{return[]}})();if(n.length>0)return n;let i=(()=>{if(typeof o.elementFromPoint!="function")return null;try{return o.elementFromPoint(t,r)}catch{return null}})();return i?[i]:[]}function Uk(e,t){return e.some(r=>Dw(r,t))}function Aw(e,t){let r=Number(t);return Number.isFinite(r)?Math.max(0,Math.min(e,Math.max(0,r-1))):e}function Zk(e,t,r){let o=e.ownerDocument??null,n=o?.defaultView?.innerWidth??null,i=o?.defaultView?.innerHeight??null,s=[],a=new Set;for(let[l,c]of Fk.slice(1)){let d=Aw(t+l,n),u=Aw(r+c,i),m=`${d}:${u}`;a.has(m)||(a.add(m),s.push({x:d,y:u}))}return s}function Ow(e,t,r,o){let n=_k(e,t,r);return{stack:n,candidates:n.flatMap(i=>Kk(i,e,o))}}function Gk(e,t,r,o){let n=[];for(let i of Zk(e,t,r))n.push(...Ow(e,i.x,i.y,o).candidates);return n}function Xk(e,t){let r=le(e,t??[]),o=r.length>0?r:[...e],n=o[0]??null;return!n||o.length>1&&!tE(o,t)?null:{status:"resolved",kind:"trackedChange",trackedChangeIds:[n],commentIds:[]}}function $k(e){return e.relationship==="child"||!!e.overlapParentId||(e.members??[]).some(t=>t.relationship==="child"||!!t.overlapParentId)}function Yk(e){return[e.overlapParentId,...(e.members??[]).map(t=>t.overlapParentId)]}function Jk(e,t,r){let o=new Set;for(let n of Yk(e)){let i=Vk(n,t);i&&i!==e.id&&r.has(i)&&o.add(i)}return o.size===1?[...o][0]:null}function Qk(e){if(!e||e.length===0)return new Map;let t=jk(e),r=new Set(e.map(o=>o.id));return Lk(e.map(o=>({id:o.id,overlapParentId:$k(o)?Jk(o,t,r):null})))}function eE(e,t){let r=[e],o=new Set(r),n=e;for(;;){let i=t.get(n);if(!i||o.has(i))return r;r.push(i),o.add(i),n=i}}function tE(e,t){if(e.length<=1)return!0;if(!t||t.length===0)return!1;let r=le(e,t);if(r.length<=1)return r.length===1;let o=eE(r[0],Qk(t)),n=new Map(o.map((s,a)=>[s,a])),i=-1;for(let s of r){let a=n.get(s);if(a==null||a<=i)return!1;i=a}return!0}function hc(e){let t=e.host??null;if(!t)return[];let r=new Set,o=Ow(t,e.clientX,e.clientY,r),n=o.candidates.length>0?o.candidates:Uk(o.stack,t)?Gk(t,e.clientX,e.clientY,r):[];if(n.length===0)return[];let i=e.revisions??[],s=Ze(e.comments),a=[],l=new Set;for(let c of n){let d=c.kind==="trackedChange"?le([c.id],i)[0]??c.id:At([c.id],s)[0]??null;if(!d)continue;let u=`${c.kind}:${d}`;l.has(u)||(l.add(u),a.push({kind:c.kind,id:d}))}return a}function jw(e){let t=hc(e),r=t.filter(s=>s.kind==="trackedChange").map(s=>s.id),o=t.filter(s=>s.kind==="comment").map(s=>s.id),n=r.length+o.length;if(n===0)return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]};let i=o.length===0?Xk(r,e.revisions):null;return i||(n>1?{status:"ambiguous",kind:null,trackedChangeIds:r,commentIds:o}:{status:"resolved",kind:r.length===1?"trackedChange":"comment",trackedChangeIds:r,commentIds:o})}function rE(e){return e?{empty:e.empty,target:e.selectionTarget?Et(e.selectionTarget):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}function oE(e,t){let r=e.getState();return hc({host:e.surface.view.dom,clientX:t.clientX,clientY:t.clientY,revisions:r.revisions,comments:r.comments}).map(n=>({type:n.kind,id:n.id}))}function nE(e,t,r,o,n){if(e)return!1;let i=t?.selectionTarget??n;if(t?.selectionKind==="node"||r?.selectionKind==="node")return sr(t?.nodeSelectionTarget,r?.nodeSelectionTarget);let s=r?.empty?r.selectionTarget:null;return os(s??o,i)}function iE(e,t,r){for(let o of r)if(e>=o.left&&e<=o.left+o.width&&t>=o.top&&t<=o.top+o.height)return!0;return!1}function sE(e,t,r,o){if(!e||!t||t.empty)return null;let n=qn(e,t);return n.length===0?null:iE(r,o,n)}function yc(e,t){return!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number"?[]:oE(e,t)}function Vw(e,t,r=null){let o=e.getState(),n=io(e,t),i=e.readEffectiveSelection({includeText:!0}),s=e.readPointSelection({clientX:t?.clientX??0,clientY:t?.clientY??0,includeText:!1}),a=typeof t?.clientX=="number"?t.clientX:0,l=typeof t?.clientY=="number"?t.clientY:0,c=sE(r,o.selection,a,l);return{point:{x:a,y:l},entities:yc(e,t),position:n,selection:Ko(o.selectionInfo??rE(i)),insideSelection:c??nE(o.selection.empty,i,s,n?.target??null,o.selectionInfo?.target??null)}}function Gn(e){return e!=null&&typeof e.contains=="function"}function bc(e){return typeof e=="string"?e.trim().toLowerCase():""}function aE(e){return e.ownerDocument?.defaultView?.getComputedStyle?.(e)??null}function Lw(e){let t=aE(e);if(!t)return{horizontal:"",vertical:""};let r=bc(t.overflow);return{horizontal:bc(t.overflowX)||r,vertical:bc(t.overflowY)||r}}function Vs(e){return e==="auto"||e==="scroll"||e==="overlay"}function lE(e){return{vertical:(e.scrollHeight??0)>(e.clientHeight??0),horizontal:(e.scrollWidth??0)>(e.clientWidth??0)}}function cE(e){let t=Lw(e),r=lE(e);return r.vertical&&Vs(t.vertical)||r.horizontal&&Vs(t.horizontal)}function dE(e){let t=Lw(e);return Vs(t.vertical)||Vs(t.horizontal)}function un(e){let t=Ls(e);return t?(Gn(t.parentElement)?t.parentElement:null)??t:null}function Ls(e){let t=e?.view?.dom??null;return Gn(t)?t:null}function uE(e){let t=e??null;for(;Gn(t);){if(cE(t))return t;t=t.parentElement}return null}function mE(e){let t=[],r=e??null;for(;Gn(r);)dE(r)&&t.push(r),r=r.parentElement;return t}function Xn(e){let t=e?.view?.dom??null;return Gn(t)?uE(t):null}function Fw(e){let t=Ls(e);return t?mE(t):[]}import{createVirtualPagedPreviewAncestorMutationObserver as pE,resolveVirtualPagedPreviewClippingAncestorElements as Ww}from"@datalking/begonia-layout-renderer";var zw={passive:!0};function Hw(e){if(typeof e.getState!="function")return null;let t=e.getState();return t.zoom?.value??t.zoomPercent??null}function $n(e){return typeof e.getState=="function"?e.getState():null}function Bc(e){return e?.commentsDisplay?.enabled===!0&&e.commentsDisplay.visible===!0}function xc(e){return typeof e.getViewportState=="function"?re(e.getViewportState()):null}function fE(e){let t=e;return{request(r){return typeof t?.requestAnimationFrame=="function"?{handle:t.requestAnimationFrame(r),mode:"animation-frame"}:{handle:typeof t?.setTimeout=="function"?t.setTimeout(()=>r(0),0):setTimeout(()=>r(0),0),mode:"timeout"}},cancel(r){if(r){if(r.mode==="animation-frame"&&typeof t?.cancelAnimationFrame=="function"){t.cancelAnimationFrame(r.handle);return}if(typeof t?.clearTimeout=="function"){t.clearTimeout(r.handle);return}clearTimeout(r.handle)}}}}function qw(e){return!e||typeof e!="object"?!1:"ownerDocument"in e}function wE(e){let t=e;return typeof t?.ResizeObserver=="function"?t.ResizeObserver:typeof ResizeObserver=="function"?ResizeObserver:null}function gE(e,t){let r=new Set;if(qw(e)){r.add(e);for(let o of Ww(e))r.add(o)}for(let o of t)qw(o)&&r.add(o);return[...r]}function SE(e,t,r,o){let n=new Set;r&&n.add(r);let i=Ls(t);i&&n.add(i);for(let s of Fw(t))n.add(s);if(e)for(let s of Ww(e))n.add(s);return n.size===0&&o&&n.add(o),[...n]}function vE(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Kw(e,t=null){let r=new Set,o=new Set,n=!1,i=null,s=xc(e),a=$n(e)?.flowMode??null,l=$n(e)?.layoutMode??null,c=Bc($n(e)),d=Hw(e),u=!1,m=null,p=null,f=null,g=[],v=null,E=[],R=null,S=null,P=!1,h=e.surface??null,b=()=>{P=!0,V("scroll")},x=()=>{P=!0,V("resize")},A=()=>{let ae=un(e.surface)?.ownerDocument?.defaultView??null;return fE(ae)},O=()=>{let L=i;i=null,L?.cancel()},j=L=>{if(i?.token!==L)return;i=null;let ae=[...o];if(o.clear(),n=!1,P&&(P=!1,I(),S?.sync()),r.size===0||ae.length===0)return;let je=ae.length===1?ae[0]:"mixed";for(let me of[...r])try{me({reason:je})}catch{}},_=()=>{let L=A(),ae={},je=null;i={token:ae,cancel(){L.cancel(je)}};try{je=L.request(()=>j(ae))}catch(me){throw i?.token===ae&&(i=null),me}},V=L=>{r.size!==0&&((L==="layout"||L==="zoom")&&n&&(o.delete("scroll"),n=!1),L==="scroll"&&(n=!1),o.add(L),!i&&_())},de=()=>{r.size!==0&&(o.has("scroll")||(n=!0),o.add("scroll"),!i&&_())},k=()=>{f?.removeEventListener?.("scroll",b,!0),f?.removeEventListener?.("resize",x);for(let L of g)L!==f&&L.removeEventListener?.("scroll",b,zw);R?.disconnect(),f=null,g=[],v=null,E=[],R=null},I=()=>{let L=un(e.surface),ae=L?.ownerDocument?.defaultView??null,je=Xn(e.surface),me=SE(L,e.surface,je,ae),Ke=gE(L,me);if(L===v&&ae===f&&me.length===g.length&&me.every((Ce,mt)=>Ce===g[mt])&&vE(Ke,E))return;k(),v=L,f=ae,g=me,E=Ke,f?.addEventListener?.("scroll",b,!0),f?.addEventListener?.("resize",x);for(let Ce of me)Ce!==f&&Ce.addEventListener?.("scroll",b,zw);let Tt=wE(f);if(!Tt)return;let Je=new Tt(()=>{I(),S?.sync(),V("resize")});for(let Ce of Ke)Je.observe(Ce);R=Je},F=()=>{S||(S=pE({getPreviewHost:()=>un(e.surface),getAdditionalHosts:()=>[Xn(e.surface)],onMutation(){I(),S?.sync(),V("layout")}})),S.sync()},y=()=>{let L=$n(e);if(!L)return;P=!0;let ae=(e.surface??null)!==h;h=e.surface??null;let je=L.zoom?.value??L.zoomPercent??null;je!==d&&(u=!0,d=je);let me=xc(e),Ke=s,Tt=me?.scale!==Ke?.scale,Je=!nt(Ke,me);s=me;let Ce=L.flowMode,mt=L.layoutMode,hr=Ce!==a||mt!==l;a=Ce,l=mt;let jt=Bc(L),vo=jt!==c;if(c=jt,Tt&&u){u=!1,V("zoom");return}if(u&&Ce==="web"){u=!1,V("zoom");return}if(hr||Je&&me?.totalPages!==Ke?.totalPages){let Vt=u?"zoom":"layout";u=!1,V(Vt);return}if(vo){V("layout");return}if(ae){V("layout");return}Je&&de()},B=()=>{if(P=!0,u){u=!1,V("zoom");return}V("layout")},M=()=>{if(m)return;h=e.surface??null,s=xc(e);let L=$n(e);a=L?.flowMode??null,l=L?.layoutMode??null,c=Bc(L),d=Hw(e),u=!1,I(),F(),m=typeof e.subscribe=="function"?e.subscribe(y):null,p=t?.subscribeResolvedProjection?.(B)??null},N=()=>{m?.(),p?.(),m=null,p=null,k(),S?.cleanup(),S=null,O(),o.clear(),n=!1,u=!1,P=!1};return{observe(L){return r.add(L),r.size===1&&M(),()=>{r.delete(L)&&r.size===0&&N()}}}}import{resolveProjectionCaretRect as hE}from"@datalking/begonia-page-layout";function mn(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Er(e,t){return t>0?e/t:null}function Uw(e){return Array.isArray(e)&&e.length>0?[...e]:null}function Zw(e){return typeof e=="number"&&Number.isInteger(e)?e:null}function yE(e,t){let r=Number.isFinite(e)?Math.max(0,Math.trunc(e)):0;return t==null?r:Math.min(t,r)}function Gw(e,t){let r=e.pages.findIndex(n=>n.pageNumber===t);if(r<0)return null;let o=e.pages[r]??null;return o?{pageIndex:r,page:o}:null}function bE(e){return!e||e.kind!=="text"||!Array.isArray(e.segments)||e.segments.length===0?[]:e.segments.filter(t=>!!t?.blockId)}function BE(e,t){return e.targets?.resolve?.({kind:"block",blockId:t})??null}function xE(e,t){let r=Uw(t?.path??null);if(r)return e.blocks?.ancestorOf?.(r)??null;let o=Zw(t?.anchorFrom);return o==null?null:e.blocks?.byAnchor?.(o)??null}function CE(e,t){let r=BE(e,t.blockId);if(!r)return null;let o=xE(e,r),n=Zw(o?.from??r.anchorFrom);if(n==null)return null;let i=yE(t.range.start,typeof r.text=="string"?r.text.length:null);return{absolutePos:n+i,anchorFrom:n,pathHint:Uw(o?.path??r.path??null)}}function PE(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex}function RE(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex&&e.lineIndex===t.lineIndex}function _w(e){let t=new Set,r=[];for(let o of e){if(!Number.isFinite(o))continue;let n=o.toFixed(3);t.has(n)||(t.add(n),r.push(o))}return r}function TE(e){return e.left+Math.min(Math.max(0,e.width/2),Math.max(0,e.width-1))}function kE(e){return e.top+Math.min(Math.max(0,e.height/2),Math.max(0,e.height-1))}function EE(e,t,r,o){if(!r||typeof e.pagination.hitTest!="function")return null;let n=_w([TE(r),o.left,r.left,r.left+Math.max(0,r.width-1)]),i=_w([kE(r),o.top+Math.max(0,o.height/2),o.top,r.top]);for(let s of i)for(let a of n){let l=e.pagination.hitTest(o.pageNumber,a,s,t);if(l&&PE(l,r))return l}return null}function ME(e,t){return e.find(r=>RE(r,t))??null}function IE(e,t,r,o,n,i){let s=Gw(e,t.pageNumber);if(!s)return null;let a=Math.max(0,Number(s.page.pageSize.width??0)),l=Math.max(0,Number(s.page.pageSize.height??0)),c=mn(t.top,l),d=mn(t.left,a),u=n??i,m=u?t.top-u.top:null,p=u?t.left-u.left:null,f=m==null?null:mn(m,u?.height??0),g=p==null?null:mn(p,u?.width??0);return{pageIndex:s.pageIndex,pageNumber:t.pageNumber,offsetTopPx:c,offsetTopRatio:Er(c,l),offsetLeftPx:d,offsetLeftRatio:Er(d,a),offsetPx:c,offsetRatio:Er(c,l),region:n?.region??t.region??i?.region??null,sectionId:n?.sectionId??t.sectionId??i?.sectionId??null,anchorFrom:r,pathHint:o,blockIdentity:n?.blockIdentity??i?.blockIdentity??null,fragmentIndex:n?.fragmentIndex??t.fragmentIndex??i?.fragmentIndex??null,columnIndex:n?.columnIndex??t.columnIndex??i?.columnIndex??null,placementOrderHint:n?.blockIndex??t.blockIndex??i?.blockIndex??null,blockOffsetTopPx:f,blockOffsetTopRatio:f==null||!u?null:Er(f,u.height),blockOffsetLeftPx:g,blockOffsetLeftRatio:g==null||!u?null:Er(g,u.width)}}function AE(e,t,r,o={}){let n=CE(e,r);if(!n)return null;let i=hE(t,n.absolutePos,{bias:"start",measureText:o.measureText,measurementEpoch:o.measurementEpoch});if(!i)return null;let s=e.pagination.lines?.(t)??[],a=ME(s,i),l=EE(e,t,a,i),c=typeof e.pagination.locateAnchor=="function"?e.pagination.locateAnchor(n.anchorFrom,t):null,d=IE(t,i,n.anchorFrom,n.pathHint,l,c);return d?{anchorPageNumber:i.pageNumber,viewportAnchor:d}:null}function Xw(e,t,r={}){let o=bE(t);if(o.length===0)return null;let n=e.pagination.project();for(let i of o){let s=AE(e,n,i,r);if(s)return s;let a=e.pagination.locateTarget({kind:"block",blockId:i.blockId},n);if(!a)continue;let l=Gw(n,a.pageNumber);if(!l)continue;let c=Math.max(0,Number(l.page.pageSize.width??0)),d=Math.max(0,Number(l.page.pageSize.height??0)),u=mn(a.top,d),m=mn(a.left,c);return{anchorPageNumber:a.pageNumber,viewportAnchor:{pageIndex:l.pageIndex,pageNumber:a.pageNumber,offsetTopPx:u,offsetTopRatio:Er(u,d),offsetLeftPx:m,offsetLeftRatio:Er(m,c),offsetPx:u,offsetRatio:Er(u,d),region:a.region??null,sectionId:a.sectionId??null,anchorFrom:a.from,pathHint:a.pathHint?[...a.pathHint]:null,blockIdentity:a.blockIdentity??null,fragmentIndex:a.fragmentIndex,columnIndex:a.columnIndex,placementOrderHint:a.blockIndex,blockOffsetTopPx:0,blockOffsetTopRatio:0,blockOffsetLeftPx:0,blockOffsetLeftRatio:0}}}return null}function Cc(e,t,r=null){let o=Xw(e.documentApi,t,Xt(r)??{});if(!o)return null;let n={anchorPageNumber:o.anchorPageNumber,viewportAnchor:o.viewportAnchor};return e.requestPreviewNavigation(n)}import{TextSelection as NE}from"prosemirror-state";var DE=1e3;function OE(e){return typeof e!="number"||!Number.isFinite(e)?DE:Math.max(0,Math.trunc(e))}function jE(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&Array.isArray(e.segments)}function VE(e){return e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"&&"id"in e&&typeof e.id=="string"}function LE(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function $w(e){let t=Gt(e);return LE(t)?t:null}function FE(e,t){let r=e.documentApi?.trackChanges.get(t)??null;return hs(e.documentApi,$w(e.preview),r)}function zE(e,t){let r=e.documentApi?.comments.target(t)??null;if(!r)return null;let o=vs(e.documentApi,r);if(o)return o;let n=$w(e.preview);if(!n)return null;let i=Ge(n,r);if(!i)return null;try{return hl(n,NE.create(n,i.from,i.to))}catch{return null}}function HE(e,t){return jE(t)?t:VE(t)?t.type==="comment"?zE(e,t.id):t.type==="trackedChange"?FE(e,t.id):null:null}function qE(e,t){let r=e.readPendingNavigationRequest();return r?r.requestKey===t?"pending":"failed":"success"}function Pc(e){return e?.shouldContinue?.()??!0}function WE(e,t,r,o){return new Promise(n=>{let i=!1,s=()=>{},a=()=>{},l=null,c=m=>{let p=typeof m=="function"?m:()=>{};return i?(p(),()=>{}):p},d=m=>{i||(i=!0,s(),a(),l!=null&&clearTimeout(l),n(m))},u=()=>{if(!Pc(o)){d(!1);return}let m=qE(e,t);m!=="pending"&&d(m==="success")};s=c(e.subscribe(u)),i||(a=c(o?.subscribe?.(u))),i||(l=setTimeout(()=>d(!1),r),u())})}async function Yw(e,t){let r=HE(e,t.target);if(!r)return{success:!1};if(!Pc(t.continuation))return{success:!1};let o=e.requestNavigationForTextTarget(r);return o?Pc(t.continuation)?{success:await WE(e,o.requestKey,OE(t.timeoutMs),t.continuation)}:{success:!1}:{success:!1}}function Yn(e){return re(e.getViewportState())}function Jw(e,t){let r=Yn(e);return e.subscribe(()=>{let o=Yn(e);nt(r,o)||(r=o,t())})}function Qw(e,t=null){let r=null;return{getSnapshot(){return Yn(e)},subscribe(o){return Jw(e,o)},observe(o){return o(Yn(e)),Jw(e,()=>{o(Yn(e))})},observeGeometry(o){return r??=Kw(e,t),r.observe(o)},scrollIntoView(o){return Yw({documentApi:e.documentApi,preview:t,subscribe(n){return e.subscribe(()=>{n()})},readPendingNavigationRequest(){return e.getState().previewNavigationRequest??null},requestNavigationForTextTarget(n){return Cc(e,n,t)}},o)},getHost(){return un(e.surface)},getScrollContainer(){return Xn(e.surface)},entitiesAtPoint(o){return yc(e,o)},contextAtPoint(o){return Vw(e,o,t)},positionAtPoint(o){return io(e,o)},requestNavigation(o){return e.requestPreviewNavigation(o)},requestNavigationForTextTarget(o){return Cc(e,o,t)},ackNavigationRequest(o){e.ackPreviewNavigationRequest(o)}}}import{createProseMirrorLayoutAdapter as uI}from"@datalking/begonia-editor-adapters";import{NodeSelection as cI}from"prosemirror-state";function Fs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function KE(e){let t=e.selectionAnchor;return Fs(t?.resolvedSelectionPos)??Fs(t?.hit?.pos)}function _E(e){return Fs(e.hit?.pos)??Fs(e.resolvedSelectionPos)}function eg(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to),n=KE(t),i=_E(t);return n!=null&&i!=null&&i<n?{anchor:o,head:r}:{anchor:r,head:o}}import{readSyntheticSideStoryDocOriginPath as YE}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as rg,isDocumentNodePathIndex as JE,isIntegerPath as og}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as QE}from"@datalking/begonia-layout-renderer";import{findProjectionPage as eM,resolveProjectionPageRegionBlocks as tM}from"@datalking/begonia-page-layout";import{findProjectionPage as UE,listProjectionPageBlocks as ZE,pointHitsProjectionPlacement as GE}from"@datalking/begonia-page-layout";function tg(e,t,r,o){let n=UE(e,t);return n?ZE(n).reduce((i,s)=>GE(s,r,o)?s:i,null):null}function De(e){return ve(e)}function XE(e,t){return e.pages.find(r=>r.pageNumber===t)??null}function $E(e,t,r){let o=XE(e,t);return o?r<o.regions.bodyTop?"header":r>=o.regions.footerTop?"footer":null:null}function pn(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=$E(e,r,t.y);if(!o)return t.hit?.region??"body";if(!t.hit||t.hit.region!=="body")return o;let n=t.hit.top,i=t.hit.top+t.hit.height;return(o==="header"?Math.max(0,n-t.y):Math.max(0,t.y-i))>Math.max(12,t.hit.height/2)?o:t.hit.region}function ng(e,t,r){let o=Qn(t,r);if(!Array.isArray(o?.path)||o.path.length===0)return!1;let n=YE(e);return n?og(o.path)&&og(n)&&o.path.length>=n.length&&n.every((i,s)=>o.path?.[s]===i)&&rg(o.path.slice(n.length)):pn(t,r)==="body"&&rg(o.path)}function Qn(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=eM(e,r);if(!o)return null;let n=tg(e,r,t.x,t.y);if(!t.hit)return n;let i=tM(o,t.hit.region)[t.hit.blockIndex]??null;return n??i}function Jn(e){return!!(e&&!e.drawing&&e.type!=="image"&&e.type!=="page_break"&&e.type!=="section_break")}function fn(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function rM(e){let t=QE(e);return t?.nodeType==="ooxml_math"||t?.nodeType==="ooxml_chart"||t?.nodeType==="ooxml_shape"||t?.nodeType==="inline_ooxml_drawing"}function ig(e,t){return t.shiftKey===!0?rM(t.target)||!Jn(e):fn(t.clickCount)<=1?!0:!Jn(e)}function so(e,t){let r=Number(t),o=Number.isNaN(r)?1:Math.round(r);return Math.max(1,Math.min(o,De(e).view.state.doc.content.size))}function sg(e,t){let r=e,o=-1;for(let n of t){if(!JE(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function ao(e,t){let r=so(e,t.from),o=so(e,t.to);return r<=o?{from:r,to:o}:{from:o,to:r}}function ag(e,t){return{from:Math.min(e.from,e.to,t.from,t.to),to:Math.max(e.from,e.to,t.from,t.to)}}function oM(e){if(e.resolvedSelectionPos==null&&e.resolvedSelectionRange==null)return!1;let t=fn(e.clickCount);return e.resolvedSelectionClickCount==null?t<=1:fn(e.resolvedSelectionClickCount)===t}function Rc(e){let t=e.hit;if(!t||!oM(e))return!1;let r=e.resolvedSelectionRange;if(r){let o=Math.min(r.from,r.to),n=Math.max(r.from,r.to);return o===n?t.pos===o&&(e.resolvedSelectionPos==null||e.resolvedSelectionPos===o):t.pos>=o&&t.pos<=n&&(e.resolvedSelectionPos==null||e.resolvedSelectionPos===o)}return e.resolvedSelectionPos!=null&&t.pos===e.resolvedSelectionPos}import{readNodeAtPath as iI}from"@datalking/begonia-document-api/structure";import{NodeSelection as cS}from"prosemirror-state";function lo(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function lg(e){return Object.hasOwn(e,"anchorPageNumber")}function cg(e){return lg(e)&&e.anchorPageNumber!=null&&lo(e.anchorPageNumber)==null}function nM(e,t){let r=e==null?"paginated":e==="web"||e==="paginated"?e:null,o=t==null?"vertical":t==="vertical"||t==="horizontal"||t==="book"?t:null;return!r||!o||r==="web"&&o!=="vertical"?null:{flowMode:r,layoutMode:o}}function iM(e){return`preview-navigation:${Math.max(1,Math.trunc(e))}`}function sM(e,t){return Ne(e)??iM(t)}function aM(e){return $t(e?.anchorPageIndex??e?.currentPageIndex??null,e?.anchorPageNumber??e?.currentPageNumber??null)}function lM(e,t){return e!=null?{pageNumber:e}:t}function cM(e,t){let r=lo(e.anchorPageNumber),o=aM(t);return Object.hasOwn(e,"viewportAnchor")?Go(e.viewportAnchor??null,{...lM(r,o)}):Object.hasOwn(e,"anchorPageNumber")?null:Xo(t)}function dg(e,t){return e==null||t==null||t.pageNumber===e}function dM(e,t,r){return lg(e)?lo(e.anchorPageNumber):lo(t?.pageNumber??r?.anchorPageNumber??r?.currentPageNumber??null)}function zs(e,t){if(!e||typeof e!="object"||cg(e))return null;let r=lo(e.anchorPageNumber),o=cM(e,t.fallbackViewport);if(Object.hasOwn(e,"viewportAnchor")&&e.viewportAnchor!=null&&!o||!dg(r,o))return null;let n=dM(e,o,t.fallbackViewport);return n==null&&!o?null:{requestKey:sM(e.requestKey,t.nextToken),flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:n,viewportAnchor:o}}function be(e){if(!e||typeof e!="object"||cg(e))return null;let t=nM(e.flowMode,e.layoutMode);if(!t)return null;let r=lo(e.anchorPageNumber),o=Go(e.viewportAnchor,{pageNumber:r}),n=Ne(e.requestKey);return n==null||r==null&&!o||e.viewportAnchor!=null&&!o||!dg(r,o)?null:{requestKey:n,flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:r??lo(o?.pageNumber),viewportAnchor:o}}function Mr(e,t){let r=be(e),o=be(t);return!r||!o?r===o:r.requestKey===o.requestKey&&r.flowMode===o.flowMode&&r.layoutMode===o.layoutMode&&r.anchorPageNumber===o.anchorPageNumber&&Zo(r.viewportAnchor,o.viewportAnchor)}function ug(e,t,r){let o=be(e);return o!=null&&o.flowMode===t&&o.layoutMode===r}function mg(e,t){let r=be(e),o=Ne(t);return r!=null&&o!=null&&r.requestKey===o}function Tc(e,t){return $t(t,e).pageNumber}function uM(e,t){return qs(e)!=null||wg(t)!=null}function pg(e,t){if(!uM(e,t))return!1;let r=$t(t,e);return r.pageNumber==null&&r.pageIndex==null}function Hs(e,t){let r=Tc(e,t);return r??(typeof t=="number"&&Number.isInteger(t)&&t>=0?t+1:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):null)}function qs(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function wg(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function mM(e,t){let r=Array.isArray(e)?[...new Set(e.map(n=>qs(n)).filter(n=>n!=null))].sort((n,i)=>n-i):[],o=Array.isArray(t)?[...new Set(t.map(n=>wg(n)).filter(n=>n!=null).map(n=>n+1))].sort((n,i)=>n-i):[];return r.length>0?o.length>0&&(o.length!==r.length||o.some((n,i)=>n!==r[i]))?[]:r:o}function fg(e,t){let r=mM(e,t);return r.length===1?r[0]??null:null}function pM(e,t){let r=qs(e),o=qs(t);return r!=null&&o!=null&&r===o?r:null}function gg(e){return fg(e?.visiblePageNumbers,e?.visiblePageIndexes)??pM(e?.firstVisiblePageNumber,e?.lastVisiblePageNumber)??fg(e?.mountedPageNumbers,e?.mountedPageIndexes)??null}function kc(e){return pg(e?.anchorPageNumber,e?.anchorPageIndex)&&pg(e?.currentPageNumber,e?.currentPageIndex)}function wn(e){return Tc(e?.anchorPageNumber,e?.anchorPageIndex)??Tc(e?.currentPageNumber,e?.currentPageIndex)??(kc(e)?null:gg(e))??null}function co(e){let t=gg(e);return{anchorPageNumber:Hs(e?.anchorPageNumber,e?.anchorPageIndex)??Hs(e?.currentPageNumber,e?.currentPageIndex)??t??null,currentPageNumber:Hs(e?.currentPageNumber,e?.currentPageIndex)??Hs(e?.anchorPageNumber,e?.anchorPageIndex)??t??null}}function Ec(e){let t=wn(e);if(t!=null)return t;let r=co(e);return r.anchorPageNumber!=null&&r.currentPageNumber!=null&&r.anchorPageNumber!==r.currentPageNumber?null:r.currentPageNumber??r.anchorPageNumber??null}function ei(e,t){return e.anchorPageNumber===t.anchorPageNumber&&e.currentPageNumber===t.currentPageNumber}function Sg(e,t){if(e.flowMode!==t.flowMode||e.layoutMode!==t.layoutMode)return!1;let r=e.viewportAnchor??null,o=t.viewportAnchor??null,n=ei(co(e),co(t));return!r||!o?n&&r===o:n&&Zo(r,o)}function fM(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:Yt({...e,layoutMode:"vertical"},t)}function wM(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:be({...e,layoutMode:"vertical"})}function gM(e){let t=Xo(e),r=t===e.viewportAnchor?e:{...e,viewportAnchor:t};return t!=null||wn(r)!=null?r:null}function Bt(e,t={}){let r=e?.viewport??null;if(!r)return null;let{flowMode:o,layoutMode:n}=t;if(Xo(r)==null&&kc(r))return null;let i=Yt(r,{flowMode:o,layoutMode:n})??fM(r,t);if(!i)return null;let s=gM(i);return s?o&&n?to(s,o,n)?s:null:o?_o(s,o)?s:null:n?Uo(s,n)?s:null:s:null}function xt(e,t={}){let r=be(e?.previewNavigationRequest??null)??(e?.previewNavigationRequest!=null?wM(e.previewNavigationRequest,t):null);if(!r)return null;let{flowMode:o,layoutMode:n}=t;return o&&r.flowMode!==o||n&&r.layoutMode!==n?null:r}function Ws(e,t){if(!e)return null;let r=Bt({viewport:e},t);return r?{kind:"full",viewport:r}:{kind:"page",state:co(e)}}function Ks(e){return e.kind==="full"?co(e.viewport):e.state}function vg(e,t,r={}){let o=Ws(e,r),n=Ws(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?Sg(o.viewport,n.viewport):ei(Ks(o),Ks(n))}function sK(e,t,r={}){let o=Ws(e,r),n=Ws(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?nt(o.viewport,n.viewport):ei(Ks(o),Ks(n))}function hg(e){let t=Gt(e.editor),r=e.source==null?null:e.source,o=e.explicitProjection??null,n=e.boundToEditorDocument===!0||!!(t&&(e.source===t||e.source==null&&e.explicitProjection==null)),i=n?null:r!=null?o==null?r:{source:r,projection:o}:t==null?o:null;return{sourceMatchesEditorDocument:n,lifecycleSourceIdentity:i}}function Mc(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function wK(e){let t=Mc(e.controllerNavigationMode);return e.sourceMatchesEditorDocument?{controllerNavigationMode:t,syncViewportToEditor:e.syncViewportToEditor}:{controllerNavigationMode:"ignore",syncViewportToEditor:!1}}function yg(e){return Mc(e)!=="ignore"}function gn(e){return Mc(e)==="consume"}function Sn(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function SM(e,t,r){if(!t||t.viewportAnchor!=null||Bt({viewport:t},r))return!1;let o=Ec(e),n=Ec(t);return o!=null&&o===n}function bg(e,t,r,o,n=null,i={}){if(Sn(t)!=null||!r||!gn(o))return null;let a=xt(e,i);return!a||a.requestKey===n?null:be(a)}function Bg(e,t,r,o,n={}){return Sn(t)!=null||r||!gn(o)?null:xt(e,n)?.requestKey??null}function xg(e,t,r,o,n,i=null,s={}){if(Sn(t)!=null||!r||!gn(o))return null;let l=Bt(e,s);if(!l)return null;if(tc(e?.viewportRequestKey,i))return l;let c=Bt({viewport:n??null},s);return c?vg(l,c,s)?null:l:SM(l,n??null,s)?null:l}function Cg(e,t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let r=ht(e?.zoomPercent)??100;return Math.max(.01,r/100)}function Pg(e,t,r,o,n={}){let i=Sn(t);if(i!=null)return i;if(r)return null;if(gn(o)){let a=xt(e,n);if(a?.viewportAnchor)return null;if(a?.anchorPageNumber!=null)return a.anchorPageNumber}if(!yg(o))return null;let s=Bt(e,n);return s?.viewportAnchor?null:wn(s)??wn(e?.viewport??null)}function Rg(e,t,r,o,n={}){if(Sn(t)!=null||r)return null;if(gn(o)){let s=xt(e,n);if(s)return s.viewportAnchor??null}return yg(o)?Bt(e,n)?.viewportAnchor??null:null}function Tg(e,t,r,o,n={}){if(Sn(t)!=null||!gn(o))return null;let s=xt(e,n);return s?s.requestKey:Bt(e,n)?Ne(e?.viewportRequestKey):null}function Ic(e,t){return Hn(t)??Jr(e?.flowMode)}function kg(e,t,r){let o=Ic(e,r),n=dt(e?.preferredPaginatedLayoutMode),i=e?.flowMode==="paginated"?dt(e?.layoutMode):null;return dr(dt(t)??(o==="paginated"?i??n??e?.layoutMode:e?.layoutMode),o)}import{buildTableGridModel as vM,readNodeAtPath as Ac,resolveRectAtLogicalPosition as hM}from"@datalking/begonia-document-api/structure";import{isDocumentNodePathIndex as yM}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as bM}from"@datalking/begonia-layout-renderer";import{NodeSelection as BM}from"prosemirror-state";function Eg(e,t){let r=e,o=-1;for(let n of t){if(!yM(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function xM(e){return bM(e)}function CM(e,t,r,o,n={}){return!e.isInline||e.childCount!==0||!BM.isSelectable(e)||e.type.name!==t.nodeType||!n.ignoreObjectId&&t.objectId&&(typeof e.attrs.objectId=="string"?e.attrs.objectId:"")!==t.objectId?!1:t.fromOffset<o&&t.toOffset>r}function Nc(e,t,r,o,n={},i=0,s=[]){if(e.isText)return{positions:s,nextOffset:i+(e.text?.length??0)};if(e.childCount===0){let c=o(e),d=i+c.length;return CM(e,r,i,d,n)&&s.push(t),{positions:s,nextOffset:d}}let a=i,l=0;for(let c=0;c<e.childCount;c+=1){let d=e.child(c);a=Nc(d,t+l+1,r,o,n,a,s).nextOffset,l+=d.nodeSize}return{positions:s,nextOffset:a}}function PM(e,t,r){if(t.type!=="table"||!Array.isArray(t.path)||t.path.length===0||r.tableOriginRow==null||r.tableOriginColumn==null)return null;let o=De(e).view.state.doc,n=Ac(o,t.path);if(!n||n.type.name!=="table")return null;let i=vM(n);if(i.invalidReason)return null;let s=hM(i,r.tableOriginRow,r.tableOriginColumn);if(!s)return null;let a=i.physicalRows[s.originRow]?.find(u=>u.rect===s)??null;if(!a)return null;let l=[...t.path,s.originRow,a.childIndex],c=Ac(o,l),d=Eg(o,l);return!c||d==null?null:{node:c,nodePos:d}}function RM(e,t){if(!Array.isArray(t.path)||t.path.length===0)return null;let r=De(e).view.state.doc,o=Ac(r,t.path),n=Eg(r,t.path);return!o?.isTextblock||n==null?null:{node:o,nodePos:n}}function Dc(e,t,r){if(!t||!Array.isArray(t.path)||t.path.length===0)return null;let o=xM(r.target);if(!o)return null;let n=De(e).view.state.doc,i=se(n),s=d=>Br(d,i),a=PM(e,t,o)??RM(e,t);if(!a)return null;let l=Nc(a.node,a.nodePos,o,s).positions;if(l.length===1)return l[0];if(l.length>1||!o.objectId)return null;let c=Nc(a.node,a.nodePos,o,s,{ignoreObjectId:!0}).positions;return c.length===1?c[0]:null}import{captureProjectionViewportLogicalAnchor as TM}from"@datalking/begonia-page-layout";function Mg(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Oc(e,t){return t>0?e/t:0}function jc(e){return e==="header"||e==="body"||e==="footer"}function kM(e,t,r){return jc(e)&&(r.hit==null||r.hit.region!==e)&&(t==null||t.region!==e)}function EM(e,t,r){return r&&(t==null||r.region===t||!jc(t))||!jc(t)?r:{region:t,sectionId:e.sectionId??null,anchorFrom:null,pathHint:null,blockIdentity:null,fragmentIndex:null,columnIndex:null,blockOffsetTopPx:null,blockOffsetTopRatio:null,blockOffsetLeftPx:null,blockOffsetLeftRatio:null}}function MM(e,t){let r=e.pages.findIndex(o=>o.pageNumber===t);return r<0?null:{pageIndex:r,page:e.pages[r]??null}}function Ig(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=MM(e,r);if(!o?.page)return null;let n=Math.max(0,Number(t.frame.page.pageSize.width??t.frame.contentWidth??0)),i=Math.max(0,Number(t.frame.page.pageSize.height??t.frame.contentHeight??0)),s=Number(t.frame.contentTop??0),a=Mg(t.y-s,i),l=TM(o.page,t.x,t.y),c=pn(e,t),d=kM(c,l,t)?t.x:t.pageX,u=Mg(d,n),m=EM(o.page,c,l);return{pageIndex:o.pageIndex,pageNumber:o.page.pageNumber,offsetTopPx:a,offsetTopRatio:Oc(a,i),offsetLeftPx:u,offsetLeftRatio:Oc(u,n),offsetPx:a,offsetRatio:Oc(a,i),...m}}function Vc(e){return e.selectionAnchor?{...e,pageNumber:e.selectionAnchor.pageNumber,x:e.selectionAnchor.x,pageX:e.selectionAnchor.pageX,y:e.selectionAnchor.y,hit:e.selectionAnchor.hit,clickCount:e.selectionAnchor.clickCount??e.clickCount??1,resolvedSelectionPos:e.selectionAnchor.resolvedSelectionPos??null,resolvedSelectionRange:e.selectionAnchor.resolvedSelectionRange??null,resolvedSelectionClickCount:e.selectionAnchor.resolvedSelectionClickCount??null,selectionAnchor:null,target:e.selectionAnchor.target??null}:null}function Ag(e){return{...e,clickCount:e.clickCount??e.selectionAnchor?.clickCount??1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}function Ng(e){return{...e,clickCount:1,shiftKey:!1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}import{buildTableGridModel as eI,readNodeAtPath as tI,resolveRectAtLogicalPosition as rI}from"@datalking/begonia-document-api/structure";import{isDenseArray as oI}from"@datalking/begonia-document-model/contracts";import{PREVIEW_TABLE_CELL_HORIZONTAL_PADDING as ti,PREVIEW_TABLE_CELL_VERTICAL_PADDING as _s}from"@datalking/begonia-layout-renderer";import{readNodeAtPath as AM}from"@datalking/begonia-document-api/structure";import{resolveNodeAnchorPosition as NM}from"@datalking/begonia-doc-service/v1";function Ir(e,t,r,o={}){return we(e,t,r,o)}function Lc(e,t,r,o={}){return Eo(e,t,r,o)}function Fc(e){return e+1}function Og(e,t){return Math.max(Fc(t),t+e.nodeSize-1)}function jg(e,t,r){return Ir(e,t,Og(e,t),r)}function Vg(e,t){return Number.isInteger(e)&&e>=0&&e<=t}function IM(e,t,r,o){let n=Fc(t),i=Og(e,t);for(;n<i;){let s=n+Math.floor((i-n)/2);Ir(e,t,s,o)<r?n=s+1:i=s}return n}function Dg(e,t,r,o="end",n={}){let i=jg(e,t,n);if(!Vg(r,i))return null;let s=He(e,t,r,o,n);if(s!=null)return s;let a=IM(e,t,r,n);return o==="start"?Math.max(Fc(t),a-1):a}function ri(e,t,r,o={}){let n=jg(e,t,o);if(!Vg(r,n))return null;let i=Lc(e,t,r,o);if(i!=null)return i;let s=Dg(e,t,r,"start",o),a=Dg(e,t,r,"end",o);if(s==null||a==null)return s??a;if(s===a)return s;let l=Ir(e,t,s,o),c=Ir(e,t,a,o);return r-l<=c-r?s:a}function DM(e){return e.isBlock&&e.childCount===0}function OM(e,t,r){let o=Math.max(t+1,t+e.nodeSize-1),n=Ir(e,t,o,r);return n>0?n:DM(e)?1:0}function jM(e,t,r,o=[]){let n=(i,s)=>{if(i.isTextblock||!i.firstChild?.isBlock){let a=OM(i,s,r);a>0&&o.push({node:i,from:s,flatLength:a});return}i.forEach((a,l)=>{a.isBlock&&n(a,s+l+1)})};return e.forEach((i,s)=>{i.isBlock&&n(i,t+s+1)}),o}function zc(e,t,r){let o=se(e),n=AM(e,t),i=NM(e,t);if(!n||i==null)return null;let s=jM(n,i,o),a=0,l=null;for(let d of s){let u=Math.max(0,Math.min(d.flatLength,r-a)),m=d.node.isLeaf?d.from+d.node.nodeSize:ri(d.node,d.from,u,o);if(m!=null&&(l=m),r<=a+d.flatLength)return m??l;a+=d.flatLength}let c=Math.max(0,Math.min(r,a));return l??ri(n,i,c,o)}import{resolveTableFragmentRows as VM}from"@datalking/begonia-layout-contracts";function Hc(e,t,r){return e.originRow===t&&e.originColumn===r}function Lg(e,t,r,o){let n=VM(e);if(!(n[t]??null)?.cells.some(l=>Hc(l,r,o)))return null;let s=n.find(l=>l.cells.some(c=>Hc(c,r,o)))??null,a=s?.cells.find(l=>Hc(l,r,o))??null;return!s||!a?null:{cellLayoutChildIndex:a.physicalIndex,cellLayoutIndex:s.fragmentRowIndex,sourceRowIndex:s.sourceRowIndex}}import{segmentTextGraphemes as Fg}from"@datalking/begonia-layout-contracts";function zg(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function vn(e){return{from:e,to:e}}function Hg(e,t){return e<=t?{from:e,to:t}:{from:t,to:e}}function Us(e,t){return Math.max(0,Math.min(Math.round(Number(t)||0),e.content.size))}function oi(e,t,r,o,n){return Lc(e,t,Math.max(0,r),n)??o}function LM(e,t,r){return Us(e,r+Math.max(1,t.nodeSize-1))}function FM(e,t,r){return Math.max(0,Math.min(r,Math.round(Number(e)||0)-t))}function zM(e,t,r,o,n){let i=LM(e,t,r);return ri(t,r,o,n)??i}function qg(e){return/\s/u.test(e)}function HM(e){return/^[\p{L}\p{N}\p{M}\u200c\u200d'\u2018\u2019_~-]+$/u.test(e)}function qM(e){return/\p{Extended_Pictographic}/u.test(e)}function WM(e){return/^[\p{P}]+$/u.test(e)}function KM(e){return/^[\p{S}]+$/u.test(e)}function qc(e){return qg(e)?"whitespace":HM(e)?"word":qM(e)?"emoji":WM(e)?"punctuation":KM(e)?"symbol":"other"}function _M(e,t){let r=Fg(e);if(r.length===0)return null;let o=Math.max(0,Math.min(e.length,t)),n=[Math.max(0,Math.min(e.length-1,o)),Math.max(0,Math.min(e.length-1,o-1))],i=new Set;for(let s of n){let a=r.findIndex(l=>l.fromOffset<=s&&s<l.toOffset);if(!(a<0||i.has(a))&&(i.add(a),!qg(r[a]?.text??"")))return a}return null}function UM(e,t){let r=Fg(e),o=_M(e,t);if(o==null)return null;let n=r[o];if(!n)return null;let i=qc(n.text);if(i==="whitespace")return null;let s=o;for(;s>0&&qc(r[s-1]?.text??"")===i;)s-=1;let a=o+1;for(;a<r.length&&qc(r[a]?.text??"")===i;)a+=1;return{start:r[s]?.fromOffset??n.fromOffset,end:r[a-1]?.toOffset??n.toOffset}}function ZM(e,t,r,o){let n=Br(e,o).length;return n<=0?vn(r):Hg(oi(e,t,0,r,o),oi(e,t,n,r,o))}function GM(e,t,r,o,n){let i=Br(e,n),s=UM(i,r);return s?Hg(oi(e,t,s.start,o,n),oi(e,t,s.end,o,n)):vn(o)}function XM(e,t){let r=Us(e,t),o=e.resolve(r);for(let n=o.depth;n>0;n-=1){let i=o.node(n);if(i.isTextblock)return{blockNode:i,blockPos:o.before(n)}}return null}function Wg(e,t,r,o,n,i){return n>=3?ZM(e,t,o,i):n===2?GM(e,t,r,o,i):vn(o)}function Kg(e){let{doc:t,rawPos:r}=e,o=se(t),n=XM(t,r);if(!n)return vn(Us(t,r));let i=Us(t,r),s=Math.max(0,Ir(n.blockNode,n.blockPos,i,o)),a=oi(n.blockNode,n.blockPos,s,i,o);return Wg(n.blockNode,n.blockPos,s,a,zg(e.clickCount),o)}function _g(e){let{doc:t,block:r,rawPos:o}=e,n=se(t);if(!Array.isArray(r.path)||r.path.length===0)return vn(o);let i=Ve(t,r.path);if(!i?.node.isTextblock)return vn(o);let s=i.node,a=i.position,l=Br(s,n).length,c=FM(o,r.from,l),d=zM(t,s,a,c,n);return Wg(s,a,c,d,zg(e.clickCount),n)}import{readNodeAtPath as Ug,resolvePathToPosition as Zg}from"@datalking/begonia-document-api/structure";import{isDenseArray as fr}from"@datalking/begonia-document-model/contracts";import{resolveMeasuredTextOffsetAtPoint as $M,resolveProjectionTextOffsetAtPoint as YM}from"@datalking/begonia-page-layout";function Be(e){try{let t=Number(e);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function JM(e){try{let t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:null}catch{return null}}function Zs(e){if(!fr(e))return 0;let t=0;for(let r of e)t+=Be(r);return t}function Wc(e,t){if(!fr(e))return 0;let r=Math.min(e.length,Math.max(0,Math.floor(t))),o=0;for(let n=0;n<r;n+=1)o+=Be(e[n]);return o}function Gg(e,t){let r=Array.isArray(e.tableRowSourceIndexes)&&fr(e.tableRowSourceIndexes)?e.tableRowSourceIndexes:null;return Array.from({length:t},(o,n)=>JM(r?.[n])??n)}function QM(e,t){let r=Array.from({length:t},()=>0);return e.forEach(o=>{let n=0;o.forEach(i=>{let s=Math.max(1,Math.round(Be(i.attrs.colSpan)||1)),a=Be(i.attrs.width),l=a>0?a/s:0;for(let c=0;c<s;c+=1){let d=n+c;d<r.length&&(r[d]=Math.max(r[d]??0,l))}n+=s})}),r}function Xg(e,t,r){let o=Array.isArray(t.tableColumnWidths)&&fr(t.tableColumnWidths)?t.tableColumnWidths.map(s=>Be(s)):Array.isArray(e.attrs.columnWidths)&&fr(e.attrs.columnWidths)?e.attrs.columnWidths.map(s=>Be(s)):[],n=QM(e,r),i=Math.max(24,(Be(t.tableWidth)||Be(t.width)||Zs(o)||Zs(n)||r*96)/Math.max(1,r));return Array.from({length:r},(s,a)=>{let l=o[a]??0,c=n[a]??0;return Math.max(24,l||c||i)})}function $g(e,t){if(t.length===0)return 0;let r=0;for(let o=0;o<t.length;o+=1){let n=Math.max(1,Be(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function Yg(e,t){if(t.length===0)return 0;let r=0;for(let o=0;o<t.length;o+=1){let n=Math.max(1,Be(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function Jg(e){return fr(e.tableRowHeights)?e.tableRowHeights.map(t=>Math.max(1,Be(t)||1)):[]}function Qg(e,t){if(e.isTextblock)return[...t];for(let r=0;r<e.childCount;r+=1){let o=e.child(r),n=[...t,r],i=Qg(o,n);if(i)return i}return null}function eS(e,t){let r=Ug(e,t);if(!r)return null;let o=Qg(r,t);if(o){let i=Zg(e,o);return i==null?null:Ug(e,o)?.content.size===0?i:i+1}let n=Zg(e,t);return n==null?null:n+1}function tS(e){let{block:t,cellLayout:r,height:o,hit:n,left:i,line:s,lineCount:a,lineIndex:l,measureText:c,measurementEpoch:d,top:u,width:m,x:p}=e,f=nS(oS(r),s.fromOffset),g={pageNumber:n?.pageNumber??0,sectionIndex:n?.sectionIndex??0,sectionPageNumber:n?.sectionPageNumber??0,sectionId:n?.sectionId??null,region:n?.region??"body",blockIndex:n?.blockIndex??t.index,fragmentIndex:n?.fragmentIndex??0,columnIndex:n?.columnIndex??0,lineIndex:l,lineCount:a,from:s.fromOffset,to:s.toOffset,left:i,top:u,width:m,height:o,text:s.text,logicalText:s.text,nodeType:f?.nodeType??n?.nodeType??"table_cell",align:n?.align??t.align??null,direction:n?.direction??t.direction??null,fontSize:f?.fontSize??n?.fontSize??t.fontSize??null,tabs:f?.tabs??null,inlineSpans:f?.inlineSpans??r.inlineSpans??n?.inlineSpans??null,continuesToNext:n?.continuesToNext??!1,label:s.text},v=c?$M(g,p,c,d):YM(g,p);return Math.max(s.fromOffset,Math.min(s.toOffset,v))}function rS(e,t,r){let o=e.lineHeights,n=oS(e);return t.map((i,s)=>{let a=Be(i.lineHeight);if(a>0)return a;let l=fr(o)?Be(o[s]):0;if(l>0)return l;let c=nS(n,i.fromOffset),d=Be(c?.lineHeight);return d>0?d:r})}function oS(e){let t=fr(e.segments)?e.segments:[],r=0;return t.map(o=>{let n={segment:o,fromOffset:r,toOffset:r+o.text.length};return r=n.toOffset,n})}function nS(e,t){return e.find(r=>t<r.toOffset||r.segment.text.length===0&&t===r.fromOffset)?.segment??null}function iS(e,t){if(!fr(e)||e.length===0)return{lineIndex:0,lineTop:0};let r=Be(t),o=0;for(let n=0;n<e.length;n+=1){let i=Math.max(1,Be(e[n])||1);if(r<o+i||n===e.length-1)return{lineIndex:n,lineTop:o};o+=i}return{lineIndex:0,lineTop:0}}function sS(e){return Kc(e)?.resolvedPos??null}function Kc(e){let{doc:t,block:r,x:o,y:n}=e;if(r.type!=="table"||!r.path?.length)return null;let i=tI(t,r.path);if(!i||i.type.name!=="table")return null;let s=eI(i);if(s.invalidReason||s.rows.length===0||s.width<=0)return null;let a=Jg(r),l=Gg(r,a.length);if(l.length===0)return null;let c=Xg(i,r,s.width),d=Math.max(0,o-r.left),u=Math.max(0,n-r.top),m=$g(u,a),p=l[m]??m,f=Yg(d,c),g=rI(s,p,f);if(!g)return null;let v=nI({doc:t,block:r,fragmentRowIndex:m,rowHeights:a,model:s,rect:g});if(!v)return null;let{cellLayoutChildIndex:E,cellLayoutIndex:R,cellPath:S,cellStartPos:P,rowTop:h}=v,b=Wc(c,g.originColumn),x=Zs(c.slice(g.originColumn,g.originColumn+g.colSpan)),A=r.tableCells?.[R]?.[E]??null,O=oI(A?.lineSlices)?A.lineSlices:null;if(!O||O.length===0)return{cellPath:S,cellStartPos:P,cellLeft:b,cellWidth:x,rowTop:h,lineIndex:0,lineCount:1,line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:P,lineTop:0,lineHeight:Math.max(1,Be(r.lineHeight))};let j=Math.max(0,u-h-_s),_=Math.max(1,Be(r.lineHeight)),V=rS(A,O,_),{lineIndex:de,lineTop:k}=iS(V,j),I=O[de]??null,F=Math.max(1,V[de]??_);if(!I)return{cellPath:S,cellStartPos:P,cellLeft:b,cellWidth:x,rowTop:h,lineIndex:de,lineCount:Math.max(1,O.length),line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:P,lineTop:k,lineHeight:F};let y=tS({block:r,cellLayout:A,height:F,line:I,lineCount:Math.max(1,O.length),lineIndex:de,left:r.left+b+ti,top:r.top+h+_s+k,width:Math.max(0,x-ti*2),x:o,measureText:e.measureText,measurementEpoch:e.measurementEpoch});return{cellPath:S,cellStartPos:P,cellLeft:b,cellWidth:x,rowTop:h,lineIndex:de,lineCount:Math.max(1,O.length),line:I,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:zc(t,S,y)??P,lineTop:k,lineHeight:F}}function nI(e){let{doc:t,block:r,fragmentRowIndex:o,rowHeights:n,model:i,rect:s}=e;if(!Array.isArray(r.path)||r.path.length===0)return null;let a=Lg(r,o,s.originRow,s.originColumn);if(!a)return null;let l=i.physicalRows[a.sourceRowIndex]?.find(u=>u.rect===s)??null;if(!l)return null;let c=[...r.path,a.sourceRowIndex,l.childIndex],d=eS(t,c);return d==null?null:{cellLayoutChildIndex:a.cellLayoutChildIndex,cellLayoutIndex:a.cellLayoutIndex,cellPath:c,cellStartPos:d,rowTop:Wc(n,a.cellLayoutIndex)}}function aS(e,t,r,o){return zc(e,t,r)??o}function _c(e){let t=sS(e);return t==null?null:Kg({doc:e.doc,rawPos:t,clickCount:e.clickCount})}function Uc(e){let t=Kc(e);if(!t)return null;let{cellPath:r,cellLeft:o,cellStartPos:n,cellText:i,cellWidth:s,line:a,lineCount:l,lineIndex:c,resolvedPos:d,rowTop:u,lineTop:m,lineHeight:p}=t,f=a?aS(e.doc,r,a.fromOffset,n):d,g=a?aS(e.doc,r,a.toOffset,d):d,v=a?.text??i,E=Math.max(1,p||Be(e.block.lineHeight)||Be(e.hit.height)||1);return{...e.hit,lineIndex:c,lineCount:l,from:Math.min(f,g),to:Math.max(f,g),left:e.block.left+o+ti,top:e.block.top+u+_s+m,width:Math.max(0,s-ti*2),height:E,text:v,label:v.trim()||e.hit.label,pos:d}}function sI(e,t,r,o){return _g({doc:De(e).view.state.doc,block:t,rawPos:r,clickCount:o})}function aI(e,t){if(t.type==="table"||Jn(t)||!Array.isArray(t.path)||t.path.length===0)return null;let r=De(e).view.state.doc,o=iI(r,t.path);return!o||!cS.isSelectable(o)?null:sg(r,t.path)}function ni(e){return hg({editor:e.editor,source:e.previewSource,explicitProjection:e.explicitProjection,boundToEditorDocument:e.boundToEditorDocument}).sourceMatchesEditorDocument}function ii(e,t){return ng(De(e).view.state.doc,t.projection,t)}function Gc(e,t){let r=Ig(t.projection,t);return r?e.requestPreviewNavigation({anchorPageNumber:r.pageNumber,viewportAnchor:r})!=null:!1}function Zc(e,t){if(t==null)return null;try{let r=cS.create(De(e).view.state.doc,t);return{from:r.from,to:r.to}}catch{return null}}function si(e){let{editor:t,event:r}=e;if(!t||!r.hit||!ni(e)||!ii(t,r))return{block:null,nodeSelectionPos:null,nodeSelectionRange:null};let o=Qn(r.projection,r);if(!ig(o,r))return{block:o,nodeSelectionPos:null,nodeSelectionRange:null};let n=Dc(t,o,r);if(n!=null)return{block:o,nodeSelectionPos:n,nodeSelectionRange:Zc(t,n)};let i=o?aI(t,o):null;return{block:o,nodeSelectionPos:i,nodeSelectionRange:Zc(t,i)}}function lI(e,t){let r=ao(e,t),o=so(e,De(e).view.state.selection.anchor);return{from:Math.min(o,r.from),to:Math.max(o,r.to)}}function Xc(e,t){let{editor:r}=e;if(!r||!t.hit||!ni(e)||!ii(r,t))return null;let o=Qn(t.projection,t);if(!o)return null;if(o.type==="table"){let n=Xt(r)??{};return _c({doc:De(r).view.state.doc,block:o,x:t.x,y:t.y,clickCount:t.clickCount,measureText:n.measureText,measurementEpoch:n.measurementEpoch})}if(t.shiftKey){let n=Zc(r,Dc(r,o,t));if(n)return n}return!Jn(o)||!t.hit?null:sI(r,o,t.hit.pos,t.clickCount)}function lS(e,t){if(t.resolvedSelectionRange)return t.resolvedSelectionRange;let r=si({...e,event:t});return r.nodeSelectionRange?r.nodeSelectionRange:Xc(e,t)}function dS(e,t){if(!t.selectionAnchor)return t.selectionAnchor??null;let r=Vc(t);if(!r)return t.selectionAnchor;let o=ai({...e,event:r});return{...t.selectionAnchor,hit:o.hit,clickCount:o.clickCount??t.selectionAnchor.clickCount??1,resolvedSelectionPos:o.resolvedSelectionPos??null,resolvedSelectionRange:o.resolvedSelectionRange??null,resolvedSelectionClickCount:o.resolvedSelectionClickCount??null,pageX:o.pageX,target:o.target??t.selectionAnchor.target??null}}function uS(e){let{editor:t,event:r}=e;if(!t||!r.hit||!ni(e)||!ii(t,r))return r.hit??null;let o=Qn(r.projection,r);if(!o||o.type!=="table")return r.hit;let n=Xt(t)??{};return Uc({doc:De(t).view.state.doc,block:o,x:r.x,y:r.y,hit:r.hit,measureText:n.measureText,measurementEpoch:n.measurementEpoch})??r.hit}function mS(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r.hit?.pos??null;let o=Xc(e,Ng(r));return o?ao(t,o).from:r.hit.pos}function Gs(e){let{editor:t,event:r}=e;if(!t)return null;let o=Vc(r),n=o?(()=>{let i=lS(e,o),s=lS(e,Ag(r));return!i||!s?null:ag(i,s)})():Xc(e,r);return n?r.shiftKey?lI(t,n):n:null}function pS(e,t){return e<=t.from?t.to:e>=t.to||Math.abs(e-t.from)>Math.abs(e-t.to)?t.from:t.to}function fS(e){let{editor:t}=e;if(!t)return null;let r=si(e);if(r.nodeSelectionPos!=null)return r.nodeSelectionPos;let o=Gs(e);return o?ao(t,o).from:null}function ai(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r;let o=uS(e),n=o===r.hit?r:{...r,hit:o},i=dS(e,n),s=i===n.selectionAnchor?n:{...n,selectionAnchor:i},a=s.hit;if(!a||Rc(s))return s;let l={...e,event:s},c=fn(s.clickCount),d=si(l);if(d.nodeSelectionPos!=null)return{...s,resolvedSelectionPos:d.nodeSelectionPos,resolvedSelectionRange:null,resolvedSelectionClickCount:c,hit:{...a,pos:d.nodeSelectionPos}};let u=Gs(l);if(!u)return s;let m=ao(t,u),p=mS(l)??m.from,f=m.from===m.to;return{...s,resolvedSelectionPos:m.from,resolvedSelectionRange:m,resolvedSelectionClickCount:c,hit:{...a,pos:f?m.from:p}}}function wS(e){let{editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n,event:i}=e;if(!t||!ni(e))return!1;let s={editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n},a=Rc(i)?i:ai(e),l=pn(a.projection,a);if(!a.hit)return l?Gc(t,a):!1;if(!ii(t,a))return Gc(t,a);let c=si({...s,event:a});if(c.nodeSelectionPos!=null){let m=De(t);return m.view.dispatch(m.view.state.tr.setSelection(cI.create(m.view.state.doc,c.nodeSelectionPos))),m.focus(),!0}let d=a.resolvedSelectionRange?ao(t,a.resolvedSelectionRange):Gs({...s,event:a});if(a.shiftKey&&d){let m=De(t),p=so(t,m.view.state.selection.anchor),f=pS(p,d),g=Z(m.view.state,p,f);return g?(m.view.dispatch(m.view.state.tr.setSelection(g)),m.focus(),!0):!1}if(d){let m=De(t),p=eg(d,a),f=Z(m.view.state,p.anchor,p.head);return f?(m.view.dispatch(m.view.state.tr.setSelection(f)),m.focus(),!0):!1}let u=a.resolvedSelectionPos??fS({...s,event:a});if(u!=null){let m=De(t),p=Z(m.view.state,so(t,u));return p?(m.view.dispatch(m.view.state.tr.setSelection(p)),m.focus(),!0):!1}return!1}var dI={resolvePositionHitEvent(e){return ai(e)},handlePositionHit(e){return wS(e)}};function Xs(){return dI}var mI=uI();function $s(e){let t=null,r=null,o=new Set,n=i=>{for(let s of[...o])s(i)};return{readLayoutAdapter(){return mI},readLayoutSource(){let i=e();return i?.view?.state.doc??i?.document??null},readDocumentSize(){return e()?.view?.state.doc.content.size??null},getResolvedProjection(){return t},getResolvedProjectionGeometryOptions(){return r},setResolvedProjection(i,s=null){t=i??null,r=s??null,n(t)},subscribeResolvedProjection(i){return o.add(i),()=>{o.delete(i)}},selection:Xs()}}function gS(e){let t=()=>Ue(e),o={...$s(t),getState(){return e.getState()},subscribe(n){return e.subscribe(n)},requestPreviewNavigation(n){return e.requestPreviewNavigation(n)},ackPreviewNavigationRequest(n){e.ackPreviewNavigationRequest(n)},setViewState(n){e.setViewState(n)},setZoomViewportMetrics(n){e.setZoomViewportMetrics(n)}};return Object.defineProperty(o,"surface",{configurable:!1,enumerable:!1,get:t}),o}var Jc=Symbol.for("@datalking/begonia-browser-sdk/browser-editor-v1-runtime"),li=new WeakMap,Qc=new WeakMap;function Yc(e,t){Object.defineProperty(e,Jc,{configurable:!0,enumerable:!1,writable:!0,value:t})}function $c(e){return!e||typeof e!="object"?null:e[Jc]??null}function SS(e){!e||typeof e!="object"||delete e[Jc]}function pI(e){return"host"in e}function ed(e,t){li.set(e,t),Yc(e,t)}function Ys(e,t,r){li.set(e,r),Qc.set(t,r),Yc(e,r),Yc(t,r)}function vS(e,t){e&&(li.delete(e),SS(e)),t&&(Qc.delete(t),SS(t))}function wr(e){if(!e)return null;if(pI(e))return Qc.get(e)??$c(e)??li.get(e.host)??$c(e.host)??null;let t=he(e);return t?li.get(t)??$c(t)??null:null}function td(e){return wr(e)?.controller??null}function hS(e){return wr(e)?.advancedOoxmlActions??null}var Q_=nn({commandIds:Pw});function fI(e){let t=e.getState();return{linkPopover:t.linkPopover,contextMenu:t.contextMenu}}function wI(e){let t=null,r=()=>{let o=fI(e);return(t==null||!Jo(t,o))&&(t=o),t};return{getSnapshot:r,subscribe(o){return e.subscribe(()=>{let n=t;n!=null&&r()!==n&&o()})}}}function gI(e,t=tn){let r=e.getState(),o=Zn(e,t);return cn(r,o)}function ci(e){let t=()=>gI(e);return{doc:e.documentApi,readState:t,subscribe(r){return e.subscribe(()=>{r()})},execute(r,o){return t().commands[r]?.disabled?ye("Command is disabled in the current document mode or selection."):tf(e,r,o)??ye(`Unsupported browser command: ${String(r)}`)}}}function hn(e){let t={controller:e,backend:Mw(e),advancedOoxmlActions:e},r=gS(e),o={session:ci(e),actor:null,documentApi:e.documentApi,readCommandSnapshot(n=tn){return Rw(e,n)},...Iw(e),browserViewport:Qw(e,r),preview:r,overlayState:wI(e),overlays:{closeLinkPopover:()=>e.closeLinkPopover(),closeContextMenu:()=>e.closeContextMenu()}};return Object.defineProperty(o,"actor",{configurable:!1,enumerable:!0,get(){return e.actor??null}}),ed(o,t),o}function uo(e){let t=hn(e),r={...t,overlays:t.overlays??{}},o=wr(t);return o&&ed(r,o),r}function yS(e){return td(e)}function Js(e){let t=hn(e),r=ks(t),o=wr(t);return o&&Ys(t,r,o),r}var SI=ci,vI=uo,hI=hn;import{errorBegoniaResult as CS,okBegoniaResult as ea,runBegoniaResult as PS}from"@datalking/begonia-result";import{errorBegoniaResult as rd,okBegoniaResult as od,toBegoniaError as bS}from"@datalking/begonia-result";function BS(e){return!!e&&typeof e=="object"&&"ok"in e}function yI(e){return{collaborative:!0,mode:"binding",reconfigurable:e,providerName:null,roomId:null,status:"disconnected",connected:null,synced:null,awarenessClientCount:null,message:"Collaboration binding attached without session metadata."}}function Qs(e,t,r){return t?{...t.getSnapshot(),mode:"session",reconfigurable:r}:e.collaborative?yI(r):{collaborative:!1,mode:"none",reconfigurable:r,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null}}async function yn(e,t,r){if(!e?.[t])return od(r);try{let o=await e[t]();return BS(o)?o:od(o??r)}catch(o){return rd(bS(o))}}async function xS(e,t){if(!t?.encodeSnapshot)return rd({code:"invalid_request",message:"Collaboration snapshot capture requires a session with encodeSnapshot()."});try{let r=await t.encodeSnapshot();return BS(r)?r:od(r??{document:e.document,documentJson:e.document.toJSON(),update:new Uint8Array,awareness:null,snapshot:t.getSnapshot()})}catch(r){return rd(bS(r))}}function RS(e){let t=async r=>{if(!e.reconfigurable)return CS({code:"invalid_request",message:"This browser controller cannot attach collaboration because it does not own surface reconfiguration."});let o=e.getCollaborationSession(),n=e.readCollaboration(),i=o===r?n:Qs(e.getSourceRuntime().surface,r,e.reconfigurable),s=await yn(r,"connect",i);if(!s.ok)return s;if(o===r&&e.getSourceRuntime().surface.collaborative)return e.emit(),ea(e.readCollaboration());let l=await PS(()=>e.createReplacementSurface(r.binding,r));if(!l.ok)return o!==r&&await yn(r,"disconnect",i),l;if(o&&o!==r){let c=await yn(o,"disconnect",n);if(!c.ok)return l.value.destroy(),await yn(r,"disconnect",i),c}return e.swapSurface(l.value,r),e.emit(),ea(e.readCollaboration())};return{attachCollaboration:t,upgradeToCollaboration:t,async detachCollaboration(r={}){if(!e.reconfigurable)return CS({code:"invalid_request",message:"This browser controller cannot detach collaboration because it does not own surface reconfiguration."});let o=e.getCollaborationSession(),n=e.getSourceRuntime().surface;if(!o&&!n.collaborative)return e.emit(),ea(e.readCollaboration());let i=await PS(()=>e.createReplacementSurface(void 0,null));if(!i.ok)return i;let s=await yn(o,"disconnect",e.readCollaboration());return s.ok?(e.swapSurface(i.value,null),r.destroySession&&await o?.destroy?.(),e.emit(),ea(e.readCollaboration())):(i.value.destroy(),s)},async saveCollaborationSnapshot(){return xS(e.getSourceRuntime().surface,e.getCollaborationSession())}}}import{hasVisibleSemanticContent as bI,isDocumentNodePathIndex as TS}from"@datalking/begonia-document-model";function BI(e){return!!e&&typeof e=="object"&&Array.isArray(e.segments)&&e.segments.length>0}function xI(e,t){let r=e;for(let o of t){if(!r||!TS(o)||o>=r.childCount)return null;r=r.child(o)}return r}function CI(e,t){if(t.length===0)return 0;let r=0,o=e;for(let n of t){if(!TS(n)||n>=o.childCount)return null;r+=1;for(let i=0;i<n;i+=1)r+=o.child(i).nodeSize;o=o.child(n)}return r}function PI(e,t){let r=e.nodeAt(t.from)??null;return!r||t.to!==t.from+r.nodeSize||!r.isLeaf||!r.isInline||!bI(r)?null:r}function nd(e){if(e.selectionKind!=="node"||!BI(e.target))return null;let t=PI(e.doc,e.selection),r=e.target.segments[0];if(!t||!r||e.target.segments.length!==1)return null;let o=Le(e.doc,r.blockId),n=o?xI(e.doc,o):null,i=o?CI(e.doc,o):null,s=i==null?null:Math.max(-1,i-1);if(!o||!n?.isBlock||s==null)return null;let a=se(e.doc),l=we(n,s,e.selection.from,a),c=Math.max(l,we(n,s,e.selection.to,a)),d=typeof e.text=="string"?e.text:"";return{id:"browser-selection",targetKind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:[...o],addressableBlockPath:[...o],addressableBlockId:r.blockId,startOffset:l,endOffset:c,segments:[{kind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:[...o],addressableBlockPath:[...o],startOffset:l,endOffset:c,text:d}],text:d,source:"live",frozenAt:null}}import{createDocumentSurface as RI}from"@datalking/begonia-engine";function Ct(e){return typeof e=="boolean"?e:void 0}function kS(e,t){return e||!!t}function TI(e){return{...e}}function kI(e){return{...e,items:e.items.map(TI)}}function ES(e,t,r){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((o,n)=>r(o,t[n]))}function Qt(e){return{...e??{},links:e?.links?{...e.links,enabled:Ct(e.links.enabled)}:void 0,contextMenu:e?.contextMenu?{...e.contextMenu,enabled:Ct(e.contextMenu.enabled),includeDefaultItems:Ct(e.contextMenu.includeDefaultItems),customItems:e.contextMenu.customItems?.map(kI)}:void 0,trackChanges:e?.trackChanges?{...e.trackChanges,enabled:Ct(e.trackChanges.enabled),visible:Ct(e.trackChanges.visible),mode:Xr(e.trackChanges.mode)??void 0,replacements:$r(e.trackChanges.replacements)??void 0}:void 0,comments:e?.comments?{...e.comments,enabled:Ct(e.comments.enabled),visible:Ct(e.comments.visible),readOnly:Ct(e.comments.readOnly),allowResolve:Ct(e.comments.allowResolve),showResolved:Ct(e.comments.showResolved),visibility:Yr(e.comments.visibility)??void 0,useInternalExternalComments:Ct(e.comments.useInternalExternalComments),suppressInternalExternal:Ct(e.comments.suppressInternalExternal)}:void 0}}function EI(e,t){return e.id===t.id&&e.label===t.label&&e.action===t.action&&e.showWhen===t.showWhen&&e.enabledWhen===t.enabledWhen&&e.disabledReason===t.disabledReason&&e.tone===t.tone}function MI(e,t){return e.id===t.id&&(e.label??null)===(t.label??null)&&ES(e.items,t.items,EI)}function id(e,t){let r=Qt(e),o=Qt(t);return r.links?.enabled===o.links?.enabled&&r.links?.popoverResolver===o.links?.popoverResolver&&r.contextMenu?.enabled===o.contextMenu?.enabled&&r.contextMenu?.includeDefaultItems===o.contextMenu?.includeDefaultItems&&r.contextMenu?.menuProvider===o.contextMenu?.menuProvider&&ES(r.contextMenu?.customItems,o.contextMenu?.customItems,MI)&&r.trackChanges?.enabled===o.trackChanges?.enabled&&r.trackChanges?.visible===o.trackChanges?.visible&&r.trackChanges?.mode===o.trackChanges?.mode&&r.trackChanges?.replacements===o.trackChanges?.replacements&&r.comments?.enabled===o.comments?.enabled&&r.comments?.visible===o.comments?.visible&&r.comments?.readOnly===o.comments?.readOnly&&r.comments?.allowResolve===o.comments?.allowResolve&&r.comments?.showResolved===o.comments?.showResolved&&r.comments?.visibility===o.comments?.visibility&&r.comments?.useInternalExternalComments===o.comments?.useInternalExternalComments&&r.comments?.suppressInternalExternal===o.comments?.suppressInternalExternal&&r.comments?.permissionResolver===o.comments?.permissionResolver}function MS(e){let{actor:t,templates:r,viewSelect:o,collaborationSession:n,documentMode:i,enableEmbeddedAdvancedOoxmlEditors:s,zoomPercent:a,modules:l,permissionResolver:c,surfaceFactory:d,...u}=e;return({collaborative:m,documentStory:p,editable:f,element:g,initialContent:v,participant:E,schema:R,trackingEnabled:S})=>RI({...u,element:g??u.element,collaborative:m,documentStory:p,editable:f,initialContent:v,schema:R??u.schema,participant:E,trackingEnabled:S,features:e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:_i(e.features??[])})}function Ar(e,t){return e.eq(t)}function W(e){return{changed:!1,reason:e}}function IS(e,t,r,o=!1){let n=an(t,r.trackChanges),i=Bw(t,r.comments),s=t!=="viewing"||e.collaborative&&!o,a=it(e),l=s&&(n.mode==="original"||n.mode==="final")?{...n,mode:"review"}:n,c=!a&&!i.readOnly?{...i,readOnly:!0,allowResolve:!1}:i;return{trackChanges:l,comments:c}}function Nr(e){if(!e||typeof e!="object")return!1;let t=e.selection,r=e.selectionKind,o=e.selectionTarget;return t!=null&&typeof t=="object"&&Number.isInteger(t.from)&&Number.isInteger(t.to)&&(r==="text"||r==="node")&&"selectionTarget"in e&&(o==null||typeof o=="object")}function AS(e){let t=o=>At(typeof o=="string"?[o]:[],Ze(e.readVisibleComments()))[0]??null,r=(o,n,i={})=>e.runAndEmit(()=>{let s=e.getRuntime().documentApi.comments.create({text:o,target:structuredClone(n),actor:e.getCurrentActor()??void 0,isInternal:i.isInternal,authorId:e.getCurrentActor()?.id??null,authorName:e.getCurrentActor()?.name??null});if(s.changed&&"id"in s&&typeof s.id=="string"){let a=e.getRuntime().documentApi.comments.target(s.id);a&&no(e.getRuntime().surface,a)}return s});return{createComment(o,n={}){let i=e.commentWriteReason();if(i)return W(i);let s=e.readEffectiveSelection(),a=s?.target??Ht(e.getRuntime().surface.state);if(!a)return W("Place the caret in text or select text before creating a comment.");let l=s?nd({doc:e.getRuntime().surface.state.doc,selection:s.selection,selectionKind:s.selectionKind,target:a,text:s.text??null}):null;return r(o,l??a,n)},createCommentFromCapture(o,n,i={}){let s=e.commentWriteReason();if(s)return W(s);let a=Nr(o)?o.selectionTarget:null;if(!o?.target&&!a)return W("Capture a text selection or caret before creating a comment.");let l=Nr(o)?e.resolveSelectionCapture(o,{includeText:!0})??e.readSelectionCapture(o,{includeText:!0})??o:o,c=e.resolveCommentTargetFromCapture(o);if(!c)return W("Captured selection is no longer available after the document changed. Capture a new text selection or caret before creating a comment.");let u=(Nr(l)?nd({doc:e.getRuntime().surface.state.doc,selection:l.selection,selectionKind:l.selectionKind,target:c,text:l.text??null}):null)??c;if(Nr(l)&&l.target){let m=l.text??null;if(m!=null&&m.length>0)return r(n,u,i)}return r(n,u,i)},replyComment(o,n,i=null){let s=e.commentWriteReason();return s?W(s):e.runAndEmit(()=>e.getRuntime().documentApi.comments.reply(o,{parentEntryId:i,text:n,authorId:e.getCurrentActor()?.id??null,authorName:e.getCurrentActor()?.name??null},e.getCurrentActor()??void 0))},setCommentInternal(o,n){let i=e.commentWriteReason();return i?W(i):e.runAndEmit(()=>e.getRuntime().documentApi.comments.patch(o,{isInternal:n},e.getCurrentActor()??void 0))},resolveComment(o){if(!e.readCommentResolveState().allowResolve)return W("Comment resolution is disabled.");let n=e.commentWriteReason();return n?W(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.resolve(o,e.getCurrentActor()??void 0))},reopenComment(o){if(!e.readCommentResolveState().allowResolve)return W("Comment resolution is disabled.");let n=e.commentWriteReason();return n?W(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.reopen(o,e.getCurrentActor()??void 0))},setActiveComment(o){if(o==null)return e.setActiveCommentId(null),e.emit(),!0;let n=t(o);return n?(e.setActiveCommentId(n),e.emit(),!0):!1}}}import{normalizeHyperlinkHref as oa}from"@datalking/begonia-document-model";import{NodeSelection as NS}from"prosemirror-state";function OS(e,t){return{left:e+8,top:t+12}}function II(){return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]}}function AI(e){let{selection:t}=e,{$from:r}=t,o=new Set;K(t)&&o.add(t.node.type.name);for(let n=0;n<=r.depth;n+=1)o.add(r.node(n).type.name);return[...o]}function DS(e,t){return Math.max(1,Math.min(t,e.content.size))}function NI(e,t){return Math.max(0,Math.min(t,e.content.size))}function DI(e,t){let r=Math.min(e.selection.from,e.selection.to),o=Math.max(e.selection.from,e.selection.to);return(t.segments?.length?t.segments:[t]).every(i=>r<=i.from&&o>=i.to)}function OI(e){let t=le(e.effectiveTrackedChangeIds,e.revisions);if(!e.selectionCapture||e.selectionCapture.selection.empty)return t;if(t.length===0)return[];let r=lr({from:e.selectionCapture.selection.from,to:e.selectionCapture.selection.to,trackedChangeIds:[]},e.revisions);if(r.length<=t.length)return t;let o=new Set(t),n=new Map(e.revisions.map(s=>[s.id,s]));return r.filter(s=>!o.has(s)).some(s=>{let a=n.get(s);return a?!DI(e.selectionCapture,a):!1})?r:t}function jI(e,t){let{selection:r}=e;return r.from===t.selection.from&&r.to===t.selection.to&&r.empty===t.selection.empty&&(t.selectionKind!=="node"||K(r)&&(!t.nodeSelectionTarget||sr(Ie(e),t.nodeSelectionTarget)))}function VI(e,t){if(t.selectionKind==="node"){let n=Zr(e,t.nodeSelectionTarget);if(n)return n;let i=NI(e.doc,Math.min(t.selection.from,t.selection.to)),s=e.doc.nodeAt(i);if(s&&NS.isSelectable(s))try{return e.apply(e.tr.setSelection(NS.create(e.doc,i)))}catch{}}let r=DS(e.doc,Math.min(t.selection.from,t.selection.to)),o=DS(e.doc,Math.max(t.selection.from,t.selection.to));try{let n=Z(e,r,o);return n?e.apply(e.tr.setSelection(n)):null}catch{return null}}function LI(e,t,r){return t||(!r||jI(e,r)?e:VI(e,r)??e)}function FI(e){return K(e.selection)?e.selection.node.type.name:e.selection.$from.parent.type.name}function zI(e,t){return t?[...t.activeMarks]:Ee(e).activeMarks}function HI(e,t){return t?[...t.activeCommentIds]:Ee(e).activeCommentIds}function qI(e){let t=new Set(Ee(e).activeMarks);if(!e.selection.empty)return[...t];for(let r of e.storedMarks??[])t.add(r.type.name);for(let r of e.selection.$from.marks())t.add(r.type.name);for(let r of e.selection.$from.nodeBefore?.marks??[])t.add(r.type.name);for(let r of e.selection.$from.nodeAfter?.marks??[])t.add(r.type.name);return[...t]}function WI(e){if(!e.pointSelectionCapture)return II();let t=e.surface.view?.dom;return jw({host:t,clientX:e.clientX,clientY:e.clientY,revisions:e.revisions,comments:e.comments})}function ta(e,t){try{let r=e.view.posAtDOM(t,0),o=e.view.posAtDOM(t,t.childNodes.length);if(r>=o)return!1;let n=Z(e.view.state,r,o);return n?qe(e,n):!1}catch{return!1}}function jS(e,t,r,o,n,i,s){return{host:e,href:o.getAttribute("href")??"",title:o.getAttribute("title"),target:o.getAttribute("target"),rel:o.getAttribute("rel"),tooltip:o.getAttribute("title"),element:o,clientX:n,clientY:i,isAnchorLink:(o.getAttribute("href")??"").startsWith("#"),documentMode:r,position:OS(n,i),resolution:s}}function ra(e,t,r){let o=ve(e),n=uo(e),i=r.selectionCapture??null,s=r.actionSelectionCapture??i,a=r.pointSelectionCapture??null,l=r.pointSelectionState??null,c=e.documentApi?.comments?.list?.()??e.getState?.().comments??[],d=WI({surface:o,pointSelectionCapture:a,clientX:r.clientX,clientY:r.clientY,revisions:r.revisions,comments:c}),u=[...d.trackedChangeIds],m=[...d.commentIds],p=LI(o.state,r.selectionState,i),f=l??p,g=r.selection??p.selection,v=AI(f),E=HI(p,i),R=l?qI(f):zI(p,i),S=r.reviewActionsEnabled,P=(()=>{if(!S)return[];let b=ce(r.selection?.trackedChangeIds??r.selectionTrackedChangeIds);if(r.selection?.trackedChangeIdsExplicit===!0)return OI({effectiveTrackedChangeIds:b,selectionCapture:s??i,revisions:r.revisions});let x=ce(o.listSelectionRevisionIds?.());return lr({from:g.from,to:g.to,trackedChangeIds:b.length>0?b:x},r.revisions)})(),h=a&&P.length===0&&d.status==="resolved"&&u.length>0?[...u]:P;return{host:n,trigger:"contextmenu",selectedText:g.empty?"":ge(p.doc,o.schema,g),hasSelection:!g.empty,selectionStart:g.from,selectionEnd:g.to,isInTable:v.some(b=>b==="table"||b==="table_row"||b==="table_cell"),isInList:v.some(b=>b==="bullet_list"||b==="ordered_list"||b==="list_item"),isTrackedChange:h.length>0,trackedChangeIds:[...h],hasAmbiguousPointReviewTarget:a!=null&&d.status==="ambiguous",pointReviewTrackedChangeIds:u,pointReviewCommentIds:m,documentMode:t,currentNodeType:FI(f),activeCommentIds:E,activeMarks:R,selectionCapture:i,actionSelectionCapture:s,pointSelectionCapture:a,isEditable:it(o),pos:l?l.selection.from:g.from,clientX:r.clientX,clientY:r.clientY,position:OS(r.clientX,r.clientY)}}function VS(e){let t=()=>e.reviewWriteReason()==null,r=l=>ir({editable:t()},e.getRuntime().surface.state,l??null),o=l=>{if(!l)return null;let c=e.readSelectionCapture(l,{includeText:!0});return c&&r(c)==null?c:null},n=l=>{let c=e.readEffectiveSelection();return r(c)!=null?!1:rt(e.getRuntime().surface,c,l)},i=(l,c,d={})=>{let u=o(l);return u?rt(e.getRuntime().surface,u,c,d):!1},s=(l,c,d={})=>i(e.resolveSelectionHandle(l,{includeText:!0}),c,d),a=l=>{let c=e.getLinkPopover();if(!c||!t())return!1;let d=e.getLinkPopoverSelectionCapture();if(d){let u=o(d);return u?.selection.formatting.link?rt(e.getRuntime().surface,u,l,{restoreSelection:!1}):(e.setLinkPopover(null),!1)}return ta(e.getRuntime().surface,c.element)?l(e.getRuntime().surface):(e.setLinkPopover(null),!1)};return{search(l,c={}){let d=l.trim();e.setSearchQuery(d),e.setSearchOptions(c);let u=d?e.getPresentationReadApi().search.query(d,c):[];return e.setActiveSearchHitId(u[0]?.hitId??null),e.emit(),u},nextSearchHit(){let l=e.getSearchQuery(),c=l?e.getPresentationReadApi().search.next(l,e.getActiveSearchHitId(),e.getSearchOptions()):null;return e.setActiveSearchHitId(c?.hitId??e.getActiveSearchHitId()),e.emit(),c},previousSearchHit(){let l=e.getSearchQuery(),c=l?e.getPresentationReadApi().search.previous(l,e.getActiveSearchHitId(),e.getSearchOptions()):null;return e.setActiveSearchHitId(c?.hitId??e.getActiveSearchHitId()),e.emit(),c},clearSearch(){e.setSearchQuery(""),e.setSearchOptions({}),e.setActiveSearchHitId(null),e.emit()},replaceSearchHit(l,c){let d=e.reviewWriteReason();return d?W(d):e.runAndEmit(()=>e.getWritableRuntimeApi().search.replace(e.getSearchQuery(),l,c,e.getSearchOptions()))},replaceAllSearchHits(l){let c=e.reviewWriteReason();return c?W(c):e.runAndEmit(()=>e.getWritableRuntimeApi().search.replaceAll(e.getSearchQuery(),l,e.getSearchOptions()))},ignoreProofingDiagnostic(l){let c=e.reviewWriteReason();return c?W(c):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.ignore(l))},acceptProofingSuggestion(l){let c=e.reviewWriteReason();return c?W(c):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.acceptSuggestion(l))},replaceProofingDiagnosticTracked(l,c){let d=e.reviewWriteReason();return d?W(d):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.replaceTracked(l,c,e.getRuntime().surface.participant,{source:"browser-proofing"}))},setLink(l,c=null){let d=oa(l);if(!t()||!d)return!1;let u=n(p=>p.setLink(d,c)),m=e.getLinkPopover();return u&&m&&e.setLinkPopover({...m,href:d,title:c}),e.emit(),u},setLinkFromCapture(l,c,d=null,u={}){let m=oa(c);if(!t()||!m)return!1;let p=i(l,g=>g.setLink(m,d),u),f=e.getLinkPopover();return p&&f&&e.setLinkPopover({...f,href:m,title:d}),e.emit(),p},setLinkFromHandle(l,c,d=null,u={}){let m=oa(c);if(!t()||!m)return!1;let p=s(l,g=>g.setLink(m,d),u),f=e.getLinkPopover();return p&&f&&e.setLinkPopover({...f,href:m,title:d}),e.emit(),p},clearLink(){if(!t())return!1;let l=n(c=>c.clearLink());return l&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),l},clearLinkFromCapture(l,c={}){if(!t())return!1;let d=i(l,u=>u.clearLink(),c);return d&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),d},clearLinkFromHandle(l,c={}){if(!t())return!1;let d=s(l,u=>u.clearLink(),c);return d&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),d},updateActiveLink(l,c=null){let d=e.getLinkPopover(),u=oa(l);if(!d||!t()||!u)return!1;let m=a(p=>p.setLink(u,c));return m&&e.setLinkPopover({...d,href:u,title:c}),e.emit(),m},clearActiveLink(){return!e.getLinkPopover()||!t()?!1:a(c=>c.clearLink())?(e.closeLinkPopover(),!0):(e.emit(),!1)}}}import{preservedSelectionPluginKey as rA}from"@datalking/begonia-engine";function Dr(e,t={},r="paired"){return Ee(e.state,t,{reviewReplacementMode:r})}function KI(e){return e!=null}function LS(e){return[e.comments?.target(e.commentId),e.comments?.targetSnapshot?.(e.commentId),e.fallbackTarget].filter(KI)}function _I(e){return LS(e)[0]??null}function di(e){for(let t of LS(e)){let r=e.resolve(t);if(r!=null)return{target:t,resolution:r}}return null}function UI(e){return e.hasSemanticSelection?e.captureSelectionIsRanged?!e.semanticSelectionIsCollapsed:e.semanticSelectionIsCollapsed:!1}function ZI(e){return e.hasUniqueCommentId&&(e.captureSelectionIsRanged||e.captureSelectionIsCollapsed||!e.hasCaptureSelection)}function FS(e){let t=[];return UI(e)&&t.push("semantic-selection"),ZI(e)&&t.push("comment-target"),e.hasAmbiguousCommentIds||(e.captureSelectionIsCollapsed?t.push("collapsed-absolute"):e.captureSelectionIsRanged&&t.push("ranged-absolute")),t}function GI(e){return e.length===1?e[0]:null}function XI(e,t){return of(e?.activeCommentIds,t)}function ui(e){return!!(e&&e.from===e.to)}function $I(e,t){return e.from===t.from&&e.to===t.to}function na(e){return Math.max(e.to-e.from,0)}function YI(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.targetKind;return t==="range"||t==="anchor"||t==="comment"}function JI(e){return YI(e?.target)?e.target:null}function QI(e){return{get state(){return e.state},view:e}}function eA(e){let t=e.surface.view;if(!t?.state||typeof t.dispatch!="function")return!1;let r=[e.captureSelection?.from,t.state.selection.from,t.state.selection.to].filter(o=>Number.isInteger(o));for(let o of new Set(r)){let n=Z(t.state,o,o);if(n&&qe(e.surface,n))return!0}return!1}function tA(e){let t=e.collapsedSemanticSelection.from,r=e.activeCommentIds.map(a=>di({comments:e.comments,commentId:a,fallbackTarget:null,resolve:l=>Ge(e.doc,l)})).filter(a=>a!=null&&a.resolution.from<a.resolution.to&&a.resolution.from<=t&&t<a.resolution.to).sort((a,l)=>na(a.resolution)-na(l.resolution));if(r.length===0)return null;let[o,...n]=r,i=na(o.resolution);return n.filter(a=>na(a.resolution)===i).every(a=>$I(a.resolution,o.resolution))?o.target:null}function mi(e){let t=e.capture?.selection??null,r=t!=null&&t.from===t.to,o=t!=null&&t.from!==t.to,n=XI(e.capture,e.comments),i=GI(n),s=e.surface.view;if(!s?.state||typeof s.dispatch!="function")return!1;if(e.capture?.selectionKind==="node"){let f=cr(QI(s),e.capture);if(f)return qe(e.surface,f)}let a=e.capture?cs(s.state,{selectionTarget:e.capture.selectionTarget??null,segmentTexts:e.capture.segmentTexts??null,text:e.capture.text??void 0})??Ae(s.state.doc,e.capture.selectionTarget??null,e.capture.text??null,{strict:!0}):null,c=(i?di({comments:e.comments,commentId:i,fallbackTarget:JI(e.capture),resolve:f=>Ge(s.state.doc,f)}):null)?.resolution??null;if(r&&t!=null&&Number.isInteger(t.from)&&t.from>=1&&t.from<=s.state.doc.content.size&&t&&i&&(!a||ui(a)&&a.from!==t.from)){let f=Z(s.state,t.from,t.to);if(f&&qe(e.surface,f))return!0}let m=FS({captureSelectionIsCollapsed:r,captureSelectionIsRanged:o,hasCaptureSelection:t!=null,hasSemanticSelection:a!=null,semanticSelectionIsCollapsed:ui(a),hasUniqueCommentId:i!=null,hasAmbiguousCommentIds:n.length>1});for(let f of m){if(f==="semantic-selection"&&a){let g=Z(s.state,a.from,a.to);if(!g)continue;if(qe(e.surface,g))return!0;continue}if(f==="comment-target"&&i){let g=c?Z(s.state,c.from,c.to):null;if(g&&qe(e.surface,g))return!0;continue}if((f==="collapsed-absolute"||f==="ranged-absolute")&&t){if(f==="ranged-absolute"&&n.length>0&&(!a||ui(a)))continue;let g=Z(s.state,t.from,t.to);if(!g)continue;try{if(qe(e.surface,g))return!0}catch{continue}}}let p=n.length>1&&a&&ui(a)?tA({activeCommentIds:n,comments:e.comments,collapsedSemanticSelection:a,doc:s.state.doc}):null;return p&&no(e.surface,p)?!0:o&&n.length>0&&(!a||ui(a))?eA({captureSelection:t,surface:e.surface}):!1}function zS(e){let t=()=>{let h=e.readEffectiveSelection(),{surface:b,documentApi:x,replacementMode:A}=e.getRuntime(),O=b.describeSelection(),j=Dr(b,{},A);return h?{effectiveSelection:h,liveSelection:O,revisionIds:yt({liveSelection:O,liveSelectionInfo:j,revisions:x.review.list(),effectiveSelection:h})}:{effectiveSelection:null,liveSelection:O,revisionIds:lr(O,x.review.list())}},r=h=>h.revisionIds.length===1&&(h.effectiveSelection?.selection.empty??h.liveSelection.empty),o=(h,b,x=null)=>e.runAndEmit(()=>{let A=h==="accept"?e.getRuntime().documentApi.review.accept(b,e.getCurrentActor()??void 0):e.getRuntime().documentApi.review.reject(b,e.getCurrentActor()??void 0);return A.changed&&x?.(),A}),n=h=>mi({capture:h,surface:e.getRuntime().surface,comments:e.getRuntime().documentApi.comments}),i=(h,b)=>{let x=e.readEffectiveSelection();return o(h,[b],()=>n(x))},s=h=>{let{surface:b}=e.getRuntime();return typeof b.listSelectionRevisionIds!="function"||ar(h,b.listSelectionRevisionIds())},a=(h,b)=>({changed:h,revisionIds:[...b],activityId:null,activityIds:[],decisions:[],activities:[]}),l=()=>e.getRuntime().documentApi.review.decisionActivity({sort:"asc"}),c=()=>new Set(l().map(h=>h.activityId)),d=(h,b,x)=>{let A=l().filter(j=>!x.has(j.activityId));if(A.length===0)return a(h,b);let O=A.map(j=>({activityId:j.activityId,revisionId:j.revisionId,decision:j.decision,relatedKinds:[...j.relatedKinds],memberCount:j.memberCount,memberRevisionIds:[...new Set(j.record.members.map(_=>_.revisionId))],memberEntryIds:[...j.memberEntryIds],createdAt:j.updatedAt??null,authorId:j.authorId??null,authorName:j.authorName??null,revisionAuthorId:j.revisionAuthorId??null,revisionAuthorName:j.revisionAuthorName??null,revisionCreatedAt:j.revisionCreatedAt??null}));return{changed:h,revisionIds:[...new Set([...b,...A.map(j=>j.revisionId)])],activityId:A[0]?.activityId??null,activityIds:A.map(j=>j.activityId),decisions:O,activities:A}},u=h=>rt(e.getRuntime().surface,e.readEffectiveSelection(),h),m=h=>{let b=h.effectiveSelection,x=h.liveSelection,A=e.getRuntime().surface,O=A.view;if(!b||b.selection.empty||b.activeCommentIds.length>0||x.empty||!O?.state||typeof O.dispatch!="function")return!1;let j=Z(O.state,Math.min(x.from,x.to),Math.min(x.from,x.to));return j?qe(A,j):!1},p=h=>{n(h.effectiveSelection),m(h)},f=()=>{let{surface:h}=e.getRuntime(),b=h.view;!b?.state||typeof b.dispatch!="function"||b.dispatch(b.state.tr.setMeta(rA,{preservedSelection:null}))},g=(h,b,x,A)=>{let{revisionIds:O}=b;if(r(b)){let V=O[0];return V?i(h,V):W("No tracked changes overlap the current selection.")}if(O.length===0)return W("No tracked changes overlap the current selection.");let j=c();return(x&&s(O)?u(x):!1)?(A(),d(!0,O,j)):o(h,O,A)},v=()=>e.getPresentationReadApi().review.list(),E=h=>le(typeof h=="string"?[h]:[],v())[0]??null,R=h=>{e.setActiveRevisionIds(h),e.emit()},S=()=>{e.setActiveRevisionIds([]),e.emit()},P=h=>{let b=v(),x=oc(b,e.getActiveRevisionId(),h);return x?(R([x]),x):null};return{acceptRevision(h){let b=e.reviewWriteReason();if(b)return W(b);let x=e.readEffectiveSelection();return o("accept",[h],()=>n(x))},rejectRevision(h){let b=e.reviewWriteReason();if(b)return W(b);let x=e.readEffectiveSelection();return o("reject",[h],()=>n(x))},acceptSelection(){let h=e.reviewWriteReason();if(h)return W(h);let b=t();return g("accept",b,x=>typeof x.acceptSelectionRevisions=="function"?x.acceptSelectionRevisions():!1,()=>p(b))},rejectSelection(){let h=e.reviewWriteReason();if(h)return W(h);let b=t();return g("reject",b,x=>typeof x.rejectSelectionRevisions=="function"?x.rejectSelectionRevisions():!1,()=>{e.clearPreservedRangeSelection(),p(b),f()})},acceptAll(){let h=e.reviewWriteReason();if(h)return W(h);let b=e.readEffectiveSelection();return o("accept",void 0,()=>n(b))},rejectAll(){let h=e.reviewWriteReason();if(h)return W(h);let b=e.readEffectiveSelection();return o("reject",void 0,()=>n(b))},setActiveRevision(h){if(h==null)return S(),!0;let b=E(h);return b?(R([b]),!0):!1},nextActiveRevision(){return P("next")},previousActiveRevision(){return P("previous")}}}function HS(e){return{...RS(e),...AS(e),...zS(e),...VS(e)}}function oA(e){return{id:e.id,name:e.name,role:"reviewer"}}function sd(e,t,r,o){return xw(e===void 0?oA(t):e,r,o??void 0)}function mo(e,t,r,o){return sd(e,t.participant,r,o)}import{createDefaultViewportFitControllerState as pA}from"@datalking/begonia-layout-renderer/core";function ia(e,t="paired"){return{sourceRuntime:null,activeRuntime:null,canonicalDocument:e,projectionKind:"none",projectedRuntimeBank:null,replacementMode:t,collaborativeProjection:null}}function po(e){return e.projectionKind==="inline"}function nA(e){return e.projectionKind==="collaborative"}function ad(e,t,r=t.replacementMode){return{...e,sourceRuntime:t,activeRuntime:nA(e)&&e.activeRuntime?e.activeRuntime:t,replacementMode:r,canonicalDocument:po(e)?e.canonicalDocument:t.surface.document}}function bn(e){if(!e.sourceRuntime||po(e))return e;let t=e.sourceRuntime.surface.document;return ld(e,t)}function ld(e,t){return t===e.canonicalDocument?e:{...e,canonicalDocument:t}}function pi(e,t,r=e.replacementMode){return e.projectedRuntimeBank===t&&e.replacementMode===r?e:{...e,projectedRuntimeBank:t,replacementMode:r}}function qS(e){return e.sourceRuntime?{...e,activeRuntime:e.sourceRuntime,projectionKind:"inline",collaborativeProjection:null}:e}function WS(e,t){return{...e,activeRuntime:t.runtime,projectionKind:"collaborative",collaborativeProjection:t}}function fi(e){return{...e,activeRuntime:e.sourceRuntime,projectionKind:"none",collaborativeProjection:null}}function KS(e){return{...e,sourceRuntime:null,activeRuntime:null,projectedRuntimeBank:null,collaborativeProjection:null,projectionKind:"none"}}function cd(e,t){let r=zs(t,{flowMode:e.flowMode,layoutMode:e.layoutMode,fallbackViewport:re(e.viewport),nextToken:e.nextPreviewNavigationRequestToken});return r?Mr(e.previewNavigationRequest,r)?{nextState:e,request:be(e.previewNavigationRequest),changed:!1}:{nextState:{...e,previewNavigationRequest:r,nextPreviewNavigationRequestToken:e.nextPreviewNavigationRequestToken+1},request:be(r),changed:!0}:{nextState:e,request:null,changed:!1}}function dd(e,t){return!e.previewNavigationRequest||t!=null&&!mg(e.previewNavigationRequest,t)?e:{...e,previewNavigationRequest:null}}function wi(e,t){return Object.hasOwn(e,t)&&e[t]!==void 0}function iA(e,t){return t||(e.flowMode==="paginated"?e.layoutMode:e.preferredPaginatedLayoutMode)}function _S(e,t,r){return!e||!to(e,t,r)||rc(e,t,r)?null:e}function sA(e,t,r,o,n){if(!r)return{viewport:e,ignoredIncompatibleViewport:!1};let i=Yt(t.viewport??null,{flowMode:o,layoutMode:n});if(!i)return{viewport:null,ignoredIncompatibleViewport:!1};let s=_S(i,o,n);return{viewport:s??e,ignoredIncompatibleViewport:s==null}}function aA(e){if(e.hasViewportRequestKey){if(e.hasViewport){if(e.ignoredIncompatibleViewport)return e.currentViewportState!=null?e.state.viewportRequestKey:null;if(e.normalizedViewportState==null)return null}return e.currentViewportState!=null||e.normalizedViewportState!=null?e.requestedViewportRequestKey:null}return e.hasViewport?e.normalizedViewportState==null?null:nt(e.currentViewportState,e.normalizedViewportState)?e.state.viewportRequestKey:null:e.normalizedViewportState!=null?e.requestedViewportRequestKey:e.state.viewport!=null?null:e.requestedViewportRequestKey}function lA(e){return e.previewNavigationRequest?e.appliedViewportRequestKey&&e.nextViewportRequestKey!=null&&!Ps(e.currentViewportRequestKey,e.nextViewportRequestKey)?!0:e.hasViewport&&e.normalizedViewportState!=null&&!nt(e.currentViewportState,e.normalizedViewportState):!1}function cA(e){return be(e)}function dA(e){return re(e)}function uA(e){return e.request?{anchorPageNumber:e.request.anchorPageNumber,viewportAnchor:e.request.viewportAnchor}:e.viewport?{}:null}function mA(e){if(!e.modesChanged||e.normalizedViewportState!=null)return null;let t=uA({request:e.previousPreviewNavigationRequest,viewport:e.previousViewportState});return t?zs(t,{flowMode:e.nextFlowMode,layoutMode:e.nextLayoutMode,fallbackViewport:e.previousViewportState,nextToken:e.state.nextPreviewNavigationRequestToken}):null}function ud(e,t,r){let o=wi(t,"flowMode"),n=wi(t,"layoutMode"),i=wi(t,"zoomPercent"),s=wi(t,"viewport"),a=wi(t,"viewportRequestKey"),l=o?Hn(t.flowMode):null,c=n?dt(t.layoutMode):null,d=a?Ne(t.viewportRequestKey):e.viewportRequestKey,u=l??e.flowMode,m=iA(e,c),p=dr(m,u),f=cA(e.previewNavigationRequest),g=dA(e.viewport),v=_S(g,u,p),{viewport:E,ignoredIncompatibleViewport:R}=sA(v,t,s,u,p),S=aA({state:e,requestedViewportRequestKey:d,hasViewportRequestKey:a,hasViewport:s,currentViewportState:v,normalizedViewportState:E,ignoredIncompatibleViewport:R}),P=i?ht(t.zoomPercent)??r:r,h=u!==e.flowMode||p!==e.layoutMode,b=ug(e.previewNavigationRequest,u,p)?be(e.previewNavigationRequest):null,x=lA({previewNavigationRequest:b,currentViewportRequestKey:e.viewportRequestKey,hasViewport:s,currentViewportState:v,normalizedViewportState:E,appliedViewportRequestKey:a&&(!s||!R&&E!=null),nextViewportRequestKey:S})?null:b,A=x??mA({state:e,nextFlowMode:u,nextLayoutMode:p,normalizedViewportState:E,previousPreviewNavigationRequest:f,previousViewportState:g,modesChanged:h}),j=x==null&&A!=null?e.nextPreviewNavigationRequestToken+1:e.nextPreviewNavigationRequestToken,_=e.previewNavigationRequest!=null&&f==null,V=m!==e.preferredPaginatedLayoutMode,de=!nt(e.viewport,E),k=!Ps(e.viewportRequestKey,S),I=_||!Mr(e.previewNavigationRequest,A);return!h&&!V&&!de&&!k&&!I&&!(P!==r)?{nextState:e,nextZoomPercent:P,changed:!1,modesChanged:!1}:{nextState:{...e,flowMode:u,layoutMode:p,preferredPaginatedLayoutMode:m,viewport:E,viewportRequestKey:S,previewNavigationRequest:A,nextPreviewNavigationRequestToken:j},nextZoomPercent:P,changed:!0,modesChanged:h}}function md(e,t,r=t){return{flowMode:e,layoutMode:t,preferredPaginatedLayoutMode:r,viewport:null,viewportRequestKey:null,previewNavigationRequest:null,nextPreviewNavigationRequestToken:1}}function US(e,t,r,o,n,i,s,a,l,c,d){return{resolvedModules:e,listeners:new Set,reconfigurable:t,allowSelectionInViewMode:r,actorInput:o,currentActor:n,documentMode:i,readModel:ia(c),viewportSession:md(s,a,l),searchQuery:"",activeSearchHitId:null,searchOptions:{},activeCommentId:null,activeRevisionId:null,activeRevisionIds:[],normalizeOverlayState:null,linkPopover:null,contextMenu:null,preservedRangeSelection:null,collaborationSession:d,unsubscribeCollaborationSession:null,viewportFitState:pA()}}function X(e){if(!e.readModel.activeRuntime)throw new Error("Browser editor runtime is not mounted.");return e.readModel.activeRuntime}function xe(e){if(!e.readModel.sourceRuntime)throw new Error("Browser editor source runtime is not mounted.");return e.readModel.sourceRuntime}function fA(e){return!!(e.previous&&e.previous.from!==e.previous.to&&(!e.current||e.current.from===e.current.to))}function gr(e,t,r=!0){let o=(r&&e.readState(),e.context.preservedRangeSelection);t()&&e.runBatchedEmit(()=>{e.clearEphemeralOverlays(),e.applySurfaceDisplayState(),r&&o&&(e.context.preservedRangeSelection=o),e.readState(),r&&fA({current:e.context.preservedRangeSelection,previous:o})&&(e.context.preservedRangeSelection=o,e.readState()),e.emit()})}function pd(e,t){return{...e??{},...t}}function sa(e,t){return{...e??{},...t}}function ZS(e){return{setModules(t){gr(e,()=>(e.context.resolvedModules=Qt(t),e.context.currentActor=mo(e.context.actorInput,e.getSurface(),e.context.resolvedModules.comments,e.permissionResolver),!0))},setDocumentMode(t){let r=Bs(t);gr(e,()=>e.context.documentMode===r?!1:(e.context.documentMode=r,!0))},setTrackChangesDisplayMode(t){let r=kf(t);gr(e,()=>e.context.resolvedModules.trackChanges?.mode===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{mode:r}),!0))},setTrackChangesReplacementMode(t){let r=Ef(t);gr(e,()=>e.context.resolvedModules.trackChanges?.replacements===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{replacements:r}),!0))},setTrackChangesVisible(t){let r=zn(t,"trackChanges.visible");gr(e,()=>e.context.resolvedModules.trackChanges?.visible===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{visible:r}),!0))},setCommentsVisible(t){let r=zn(t,"comments.visible");gr(e,()=>e.context.resolvedModules.comments?.visible===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{visible:r}),!0),!1)},setCommentsReadOnly(t){let r=zn(t,"comments.readOnly");gr(e,()=>e.context.resolvedModules.comments?.readOnly===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{readOnly:r}),!0),!1)},setCommentsShowResolved(t){let r=zn(t,"comments.showResolved");gr(e,()=>e.context.resolvedModules.comments?.showResolved===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{showResolved:r}),!0),!1)},setCommentsVisibility(t){let r=Mf(t);gr(e,()=>e.context.resolvedModules.comments?.visibility===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{visibility:r}),!0),!1)}}}function fd(e){return e==null?e:structuredClone(e)}function aa(e){return e&&{...e,groups:e.groups?[...e.groups]:e.groups}}function GS(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function XS(e){return{...e,zoomPercent:Object.hasOwn(e,"zoomPercent")&&e.zoomPercent!==void 0?ht(e.zoomPercent)??void 0:e.zoomPercent,viewportRequestKey:Object.hasOwn(e,"viewportRequestKey")&&e.viewportRequestKey!==void 0?Ne(e.viewportRequestKey):e.viewportRequestKey}}function wA(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&"segments"in e&&Array.isArray(e.segments)}function $S(e){if(!e.captureTarget||!wA(e.captureTarget))return e.resolvedTarget??null;if(e.captureStillTracked&&e.resolvedTarget)return e.resolvedTarget;if(e.originalTargetText!=null&&typeof e.captureText=="string"&&e.originalTargetText===e.captureText){let t=e.resolvedText?.length??-1;if((e.resolvedTarget||e.captureStillTracked)&&e.originalTargetText.length>=t)return e.captureTarget}return e.originalTargetText!=null&&e.resolvedText!=null?e.resolvedTarget??e.captureTarget:e.resolvedTarget??null}function la(e){return"documentService"in e?{documentApi:e.documentApi,documentService:e.documentService}:{documentApi:e.documentApi,documentService:e.service}}function gA(e){return{projectedMode:e.projectedMode,projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,presentationReadRuntime:e.presentationReadRuntime,canonicalReviewRuntime:e.canonicalReviewRuntime,writableRuntime:e.writableRuntime}}function YS(e){let t=bw(e.trackChangesMode),r=vw(e.projectedRuntimeBank),o=la(e.presentationRuntime),n=la(e.writableRuntime??e.presentationRuntime),i=t&&r?la(r.resolveRuntime(t)):o,s=t&&r?la(r.resolveRuntime("tracked")):n;return gA({projectedMode:t,projectedRuntimeBank:r,canonicalDocument:e.canonicalDocument??null,presentationReadRuntime:i,canonicalReviewRuntime:s,writableRuntime:n})}function SA(e){let t=e.activeRuntime??e.sourceRuntime;if(!t)throw new Error("Browser editor presentation runtime is not mounted.");return t}function vA(e){let t=e.sourceRuntime??e.activeRuntime;if(!t)throw new Error("Browser editor writable runtime is not mounted.");return t}function Or(e,t){return YS({presentationRuntime:SA(e),writableRuntime:vA(e),projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,trackChangesMode:t})}import{readViewportFitState as hA,resolveViewportFitZoomPercent as yA,updateViewportFitMetrics as bA,updateViewportFitMode as BA,updateViewportFitWidthOptions as xA}from"@datalking/begonia-layout-renderer/core";function ca(e,t){return hA(e.viewportFitState,{zoomPercent:t,flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function JS(e){return yA(e.viewportFitState,{flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function wd(e,t){let r=BA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function QS(e,t){let r=xA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function ev(e,t){let r=bA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function tv({context:e,emit:t,getEmissionVersion:r,applySurfaceDisplayState:o}){let n=()=>ur(xe(e).documentApi.preferences.get()),i=l=>{let c=xe(e),d=ur(c.documentApi.preferences.get());return l===d?!1:(c.documentApi.preferences.set({zoomPercent:l}),!0)},s=()=>{let l=JS(e);return l==null?!1:i(l)},a=l=>{r()===l&&t()};return{getFlowMode(){return e.viewportSession.flowMode},getLayoutMode(){return e.viewportSession.layoutMode},getZoomPercent:n,getZoomState(){return ca(e,n())},getViewportState(){return re(e.viewportSession.viewport)},requestPreviewNavigation(l){let c=cd(e.viewportSession,l);return c.request?(e.viewportSession=c.nextState,c.changed&&t(),c.request):null},ackPreviewNavigationRequest(l){let c=dd(e.viewportSession,l);c!==e.viewportSession&&(e.viewportSession=c,t())},setViewState(l){if(!l||typeof l!="object")return;let c=xe(e),d=ur(c.documentApi.preferences.get()),u=XS(l),m=Object.hasOwn(u,"zoomPercent")&&u.zoomPercent!==void 0?wd(e,"manual"):!1,p=ud(e.viewportSession,u,d);if(!p.changed&&!m)return;e.viewportSession=p.nextState,p.modesChanged&&o();let f=r();p.nextZoomPercent!==d&&c.documentApi.preferences.set({zoomPercent:p.nextZoomPercent}),a(f)},setZoomMode(l){if(!wd(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setFitWidthOptions(l){if(!QS(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setZoomViewportMetrics(l){if(!ev(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)}}}import{DELETION_MARK_NAME as pD,describeSurfaceSelection as fD,INSERTION_MARK_NAME as wD}from"@datalking/begonia-engine";import{NodeSelection as gD}from"prosemirror-state";import{documentWideMutationEffect as SD}from"@datalking/begonia-editor-contracts";import{cloneSelectionTextRange as dD}from"@datalking/begonia-document-api/core";import{cloneSelectionTextRange as CA}from"@datalking/begonia-document-api/core";import{resolveRevisionProjectedDocument as PA}from"@datalking/begonia-engine";import{collectDocumentNodesIncludingSyntheticSideStories as RA,readSyntheticSideStoryDocOriginPath as TA}from"@datalking/begonia-doc-service/v1";import{formatAddressableBlockIdWithLogicalId as kA,parseAddressableBlockId as EA}from"@datalking/begonia-doc-service/structure";var rv=new WeakMap,ov=new WeakMap;function MA(e){let t=rv.get(e);if(t)return t;let r=RA({schema:e.type.schema,readDocument:()=>e},{include:(o,n)=>o.type.name==="doc"&&n.length>0,map:(o,n)=>({doc:o,path:[...n]})});return rv.set(e,r),r}function IA(e,t){if(!t)return e;let r=ov.get(e)??{},o=r[t];if(o)return o;let n=PA(e,e.type.schema,t);return ov.set(e,{...r,[t]:n}),n}function AA(e,t,r){if(!e||!t||e.eq(t))return null;let o=TA(e);if(o)return o;let n=MA(IA(t,r)).filter(i=>i.doc.eq(e));return n.length===1?n[0].path:null}function er(e){let t=AA(e.projectedDocument,e.canonicalDocument,e.projectedMode);if(!t)return e.blockId;let r=EA(e.blockId);return!r||r.path.some(o=>o<0)?e.blockId:kA(r.blockType,[...t,...r.path],r.logicalId)}function nv(e){if(!e.target)return e.target;let t=e.target.segments.map(o=>({blockId:er({blockId:o.blockId,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),range:CA(o.range)}));return t.some((o,n)=>o.blockId!==e.target?.segments[n]?.blockId)?{kind:"text",segments:t,...e.target.story?{story:structuredClone(e.target.story)}:{}}:e.target}import{readSyntheticSideStoryDocContext as DA}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as OA,semanticNodeText as jA}from"@datalking/begonia-document-model";import{isAddressableTextHiddenLeaf as NA}from"@datalking/begonia-document-model";function tr(e){return e.isText?e.text?.length??0:!e.isLeaf||NA(e)?0:1}var VA="\uFFFC";function iv(e){if(e.isText)return e.text??"";if(e.childCount===0){if(tr(e)===0)return"";let o=jA(e);return o.length===1?o:VA}let t=[],r=!0;return e.forEach(o=>{o.isBlock&&!r&&t.push(`
7
- `),t.push(iv(o)),r=!1}),t.join("")}function da(e,t){let r=Le(e,t);if(!r)return null;let o=e;for(let n of r){if(!OA(n)||n>=o.childCount)return null;o=o.child(n)}return o.isBlock?{node:o,path:r}:null}function Pt(e,t){let r=da(e,t);return r?iv(r.node):null}function jr(e){let t=Sw([e.currentDocument,e.expectedProjectedDocument]);return t?DA({schema:e.schema,port:{replaceDocument(){}},readDocument(){return e.expectedProjectedDocument}},t)?.doc??null:e.expectedProjectedDocument}import{isAddressableTextHiddenLeaf as FA,isDocumentNodePathIndex as zA}from"@datalking/begonia-document-model";import{readReviewLedger as LA}from"@datalking/begonia-engine";function gd(e){return e.join(".")}function sv(e,t,r){return e.isInline?!wt(e,t,!r):r}function Sd(e,t){if(e.marks.some(o=>pp(o.type.name,t)&&(o.attrs.blockAttrsBefore!=null||o.attrs.blockAttrsAfter!=null)))return!0;let r=!1;return e.forEach(o=>{!r&&Sd(o,t)&&(r=!0)}),r}function av(e,t){let r=t==="final"?"delete":"insert";return new Set(LA(e).filter(o=>o.entryType==="revision"&&o.kind===r&&o.target?.blockPath.length).map(o=>gd(o.target.blockPath)))}function gi(e){let t=av(e,"final"),r=av(e,"original"),o=new Map,n=(i,s,a,l)=>{let c=sv(i,"final",a),d=sv(i,"original",l);if(i.isText||i.isLeaf){let p=tr(i)>0;return{contentFinal:c&&p,contentOriginal:d&&p}}let u=!1,m=!1;if(i.forEach((p,f,g)=>{let v=n(p,[...s,g],c,d);u||=v.contentFinal,m||=v.contentOriginal}),i.isBlock){let p=gd(s);o.set(p,{final:!(t.has(p)&&!u&&!Sd(i,"final")),original:!(r.has(p)&&!m&&!Sd(i,"original"))})}return{contentFinal:u,contentOriginal:m}};return n(e,[],!0,!0),{isBlockPresent(i,s){return o.get(gd(i))?.[s]??!0}}}var cv=Object.freeze({blockSeparator:`
8
- `});function dv(e,t){let r=Le(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!zA(i)||i>=o.childCount)return null;n+=1;for(let s=0;s<i;s+=1)n+=o.child(s).nodeSize;o=o.child(i)}return o.isBlock?{document:e,node:o,path:r,position:n}:null}function lv(e,t,r){return e.isInline?!wt(e,t,!r):r}function HA(e){return e.isText?e.text?.length??0:!e.isLeaf||FA(e)?0:tr(e)}function fo(e,t,r,o,n,i){let s=t+1;if(r<=s)return 0;let a=0,l=!1,c=(u,m,p,f)=>{let g=0,v=!0,E=!1;for(let R=0;R<u.childCount;R+=1){if(l)return;let S=u.child(R),P=m+g,h=[...f,R],b=!S.isBlock||i.isBlockPresent(h,o);if(S.isBlock&&!v)if(r>=P+1)a+=p&&b&&E?1:0;else{l=!0;return}d(S,P,p&&b,h),g+=S.nodeSize,S.isBlock&&(E||=p&&b),v=!1}},d=(u,m,p,f)=>{if(l)return;let g=lv(u,o,p);if(u.isText){let v=u.text?.length??0,E=m+v;r>=E?a+=g?v:0:(a+=g?Math.max(0,r-m):0,l=!0);return}if(u.isLeaf){r>=m+u.nodeSize?a+=g?HA(u):0:l=!0;return}c(u,m+1,g,f)};return c(e,s,lv(e,o,!0)&&i.isBlockPresent(n,o),n),a}function vd(e,t,r,o,n,i,s){let a=t+1,l=Math.max(a,t+e.nodeSize-1),c=fo(e,t,l,n,i,s);if(!Number.isInteger(r)||r<0||r>c)return null;let d=a,u=l;for(;d<u;){let p=d+Math.floor((u-d)/2);fo(e,t,p,n,i,s)<r?d=p+1:u=p}if(o!=="start")return d;let m=d;for(;m<l&&fo(e,t,m+1,n,i,s)===r;)m+=1;return m}function Vr(e){let t=dv(e.document,e.blockId);if(!t)return null;let r=se(e.document,cv),o=gi(t.document);if(e.range.start===e.range.end){let l=Eo(t.node,t.position,e.range.start,r);return typeof l=="number"?{start:fo(t.node,t.position,l,e.projectedMode,t.path,o),end:fo(t.node,t.position,l,e.projectedMode,t.path,o)}:null}let n=He(t.node,t.position,e.range.start,"start",r),i=He(t.node,t.position,e.range.end,"end",r);if(typeof n!="number"||typeof i!="number")return null;let s=fo(t.node,t.position,n,e.projectedMode,t.path,o),a=fo(t.node,t.position,i,e.projectedMode,t.path,o);return{start:Math.min(s,a),end:Math.max(s,a)}}function ua(e){let t=dv(e.document,e.blockId);if(!t)return null;let r=se(e.document,cv),o=gi(t.document);if(e.range.start===e.range.end){let l=vd(t.node,t.position,e.range.start,"end",e.projectedMode,t.path,o);return typeof l=="number"?{start:we(t.node,t.position,l,r),end:we(t.node,t.position,l,r)}:null}let n=vd(t.node,t.position,e.range.start,"start",e.projectedMode,t.path,o),i=vd(t.node,t.position,e.range.end,"end",e.projectedMode,t.path,o);if(typeof n!="number"||typeof i!="number")return null;let s=we(t.node,t.position,n,r),a=we(t.node,t.position,i,r);return{start:Math.min(s,a),end:Math.max(s,a)}}import{hasVisibleSemanticContent as KA}from"@datalking/begonia-engine";function qA(e,t){let r=Math.min(e.length,t.length),o=0;for(;o<r&&e[o]===t[o];)o+=1;return o}function WA(e,t,r){let o=Math.min(e.length-r,t.length-r),n=0;for(;n<o&&e[e.length-1-n]===t[t.length-1-n];)n+=1;return n}function Si(e,t){if(e===t)return{current:{start:0,end:e.length},next:{start:0,end:t.length}};let r=qA(e,t),o=WA(e,t,r);return{current:{start:r,end:e.length-o},next:{start:r,end:t.length-o}}}function _A(e){return tr(e)}function uv(e){return e.length>0&&e.trim().length===0}function UA(e){return e==="paragraph"||e==="heading"}function mv(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function ZA(e,t){return Cr(e,t)}function GA(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.position+e.node.nodeSize;return o>=e.position&&n<=i}function XA(e){let t=[],r=(o,n,i,s)=>{let a=o.isInline?wt(o,"final",i):!1,l=o.isInline?wt(o,"original",s):!1,c=o.isText||o.isLeaf&&KA(o)?_A(o):0;if(c>0){t.push({from:n,to:n+(o.isText?c:o.nodeSize),projectedLength:c,visibleFinal:!a,visibleOriginal:!l});return}o.forEach((d,u)=>{r(d,n+1+u,a&&o.isInline,l&&o.isInline)})};return r(e.node,e.position,!1,!1),t}function hv(e){return Math.max(0,e.end-e.start)}function pv(e,t){return!!(e?.precise&&t.length>0&&hv(e.range)!==t.length)}function fv(e,t){return!!(e?.precise&&t.length>0&&hv(e.range)===t.length)}function yd(e,t,r){let o=0;for(let n of e){let i=t==="final"?n.visibleFinal:n.visibleOriginal;if(r<=n.from)break;if(r>=n.to){i&&(o+=n.projectedLength);continue}i&&(o+=n.projectedLength===n.to-n.from?r-n.from:r>n.from?n.projectedLength:0);break}return o}function yv(e,t,r){let o=e.target;if(o&&mv(o.blockPath,r.path)&&typeof o.from=="number"&&typeof o.to=="number")return{range:{start:Zt(r,o.from),end:Zt(r,o.to)},precise:!0};if(typeof e.from=="number"&&typeof e.to=="number")return GA(r,e.from,e.to)?{range:{start:Zt(r,e.from),end:Zt(r,e.to)},precise:!0}:null;let n=t.target;return n&&mv(n.blockPath,r.path)&&typeof n.from=="number"&&typeof n.to=="number"?{range:{start:Zt(r,n.from),end:Zt(r,n.to)},precise:!1}:null}function wv(e,t,r,o,n){let i=yv(n.member,o,t);if(!i)return null;let s=yd(e,r,i.range.start),a=yd(e,r,i.range.end);return{range:{start:Math.min(s,a),end:Math.max(s,a)},precise:i.precise}}function gv(e,t,r,o,n){let i=yv(n.member,o,t);if(!i)return null;let s=yd(e,r,i.range.start);return{start:s,end:s}}function hd(e,t){let r=0;for(let o of e)(t==="final"?o.visibleFinal:o.visibleOriginal)&&(r+=o.projectedLength);return{start:0,end:r}}function Sv(e,t){let r=t?.member.target??e?.target??null;return r&&(r.nodeType==="bookmark_anchor"||r.nodeType==="structural_revision_carrier")&&UA(r.blockType)?r:null}function $A(e){return e.currentText.length>0||e.nextText.length>0?!1:!!(Sv(e.currentRevision,e.currentSide)||Sv(e.nextRevision,e.nextSide))}function vv(e,t,r,o){let n=Si(t,r),i=o==="current"?n.current:n.next;return{start:e.start+i.start,end:e.start+i.end}}function bv(e){let t=ZA(e.canonicalDocument,e.blockId);if(!t)return null;let r=XA(t),o=e.projectedMode==="final"?"original":"final",n=$A({currentRevision:e.currentRevision,currentSide:e.currentSide,nextRevision:e.nextRevision,nextSide:e.nextSide,currentText:e.currentText,nextText:e.nextText}),i=uv(e.currentText)&&uv(e.nextText),s=e.currentSide&&e.currentRevision?wv(r,t,e.projectedMode,e.currentRevision,e.currentSide):null,a=e.nextSide&&e.nextRevision?wv(r,t,o,e.nextRevision,e.nextSide):null,l=pv(s,e.currentText),c=pv(a,e.nextText),d=fv(s,e.currentText),u=fv(a,e.nextText),m=n?hd(r,e.projectedMode):i&&s||d&&s||l&&s?s.range:s?vv(s.range,e.currentText,e.nextText,"current"):e.nextSide&&e.nextRevision?gv(r,t,e.projectedMode,e.nextRevision,e.nextSide):null,p=n?hd(r,e.projectedMode):s?.precise||s&&e.currentText.length>0&&e.currentText.trim().length===0?s.range:m,f=n?hd(r,o):i&&a||u&&a||c&&a?a.range:a?vv(a.range,e.currentText,e.nextText,"next"):e.currentSide&&e.currentRevision?gv(r,t,o,e.currentRevision,e.currentSide):null;return m&&p&&f?{currentRange:m,currentActiveRange:p,nextRange:f}:null}function Bv(e){return typeof e?.member.text=="string"?e.member.text:""}function YA(e){return e==="final"?new Set(["insert","format"]):new Set(["delete","format"])}function xv(e,t){let r=YA(t),o=(e.members??[]).filter(n=>r.has(n.kind)).map(n=>({revisionId:e.id,member:n,sortFrom:n.target?.from??n.from??e.target?.from??e.from}));return o.length>0?o:e.kind&&r.has(e.kind)?[{revisionId:e.id,member:{revisionId:e.id,kind:e.kind,text:"text"in e&&typeof e.text=="string"?e.text:"",from:e.from,to:e.to,target:e.target??null},sortFrom:e.target?.from??e.from}]:[]}function JA(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function QA(e){let t=new Map;return e.forEach((r,o)=>{let n=JA(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...xv(r,"final")),i.originals.push(...xv(r,"original")),t.set(n,i)}),[...t.values()]}function Cv(e,t){return e.sortFrom-t.sortFrom}function Bn(e){let t=[],r=e.revisions,o=new Map(r.map(i=>[i.id,i]));for(let i of QA(r)){let s=[...e.projectedMode==="final"?i.finals:i.originals].sort(Cv),a=[...e.projectedMode==="final"?i.originals:i.finals].sort(Cv),l=Math.max(s.length,a.length);if(l!==0)for(let c=0;c<l;c+=1){let d=s[c]??null,u=a[c]??null;if(!d&&!u)continue;let m=d?o.get(d.revisionId)??null:null,p=u?o.get(u.revisionId)??null:null,f=Bv(d),g=Bv(u),v=bv({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,currentRevision:m,currentSide:d,nextRevision:p,nextSide:u,currentText:f,nextText:g});v&&t.push({revisionId:d?.revisionId??u?.revisionId??"",preservesWholeCurrentSide:!!(d&&(!u||d.revisionId!==u.revisionId)),currentActiveRange:v.currentActiveRange,currentRange:v.currentRange,nextRange:v.nextRange})}}let n=new Map;return t.sort((i,s)=>i.currentRange.start-s.currentRange.start||i.currentRange.end-s.currentRange.end||i.nextRange.start-s.nextRange.start||i.nextRange.end-s.nextRange.end||i.revisionId.localeCompare(s.revisionId)).forEach(i=>{n.set(JSON.stringify([i.revisionId,i.preservesWholeCurrentSide,i.currentActiveRange.start,i.currentActiveRange.end,i.currentRange.start,i.currentRange.end,i.nextRange.start,i.nextRange.end]),i)}),[...n.values()]}function Pv(e){return typeof e=="string"&&e.length>0?e:""}function Rv(e,t){let r=t==="final"?new Set(["insert","format"]):new Set(["delete","format"]),o=(e.members??[]).filter(i=>r.has(i.kind)).map(i=>({revisionId:e.id,text:Pv(i.text)})).filter(i=>i.text.length>0);if(o.length>0)return o;let n=Pv(e.text);return e.kind&&r.has(e.kind)&&n.length>0?[{revisionId:e.id,text:n}]:[]}function Tv(e){let t=new Map;for(let r of e)t.set(JSON.stringify([r.revisionId,r.text]),r);return[...t.values()]}function eN(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function kv(e){let t=new Map;return e.forEach((r,o)=>{let n=eN(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...Rv(r,"final")),i.originals.push(...Rv(r,"original")),t.set(n,i)}),[...t.values()].map(r=>({finals:Tv(r.finals),originals:Tv(r.originals)}))}function Ev(e){let t=new Map;for(let r of e)t.set(`${r.currentText}\0${r.nextText}`,r);return[...t.values()]}function Mv(e){let t=[];for(let r of kv(e)){if(r.finals.length>0&&r.originals.length>0){for(let o of r.finals)for(let n of r.originals)t.push({currentText:o.text,nextText:n.text}),t.push({currentText:n.text,nextText:o.text});continue}for(let o of r.finals)t.push({currentText:o.text,nextText:""});for(let o of r.originals)t.push({currentText:o.text,nextText:""})}return Ev(t)}function Iv(e,t){let r=[];for(let n of kv(e)){let i=t==="final"?n.finals:n.originals,s=Ev((t==="final"?n.originals:n.finals).map(a=>({currentText:a.text,nextText:a.text}))).map(a=>a.currentText);for(let a of i){if(s.length===0){r.push({revisionId:a.revisionId,currentText:a.text,nextText:""});continue}for(let l of s)r.push({revisionId:a.revisionId,currentText:a.text,nextText:l})}}let o=new Map;for(let n of r)o.set(`${n.revisionId}\0${n.currentText}\0${n.nextText}`,n);return[...o.values()]}function ma(e,t){let r=[];if(t.length===0)return r;let o=0;for(;o<=e.length;){let n=e.indexOf(t,o);if(n<0)break;r.push({start:n,end:n+t.length}),o=n+1}return r}function pa(e,t){return t.start===t.end?e.start===e.end?e.start===t.start:e.start<=t.start&&e.end>t.start:e.start===e.end?t.end>t.start&&e.start>=t.start&&e.start<t.end:e.end>t.start&&e.start<t.end}function fa(e,t){return e.end>t.start}function wa(e,t,r){if(e<=t.start)return e;if(e<t.end){let o=t.end-t.start;if(r<=0||o<=0)return t.start;let n=Math.round((e-t.start)/o*r);return t.start+Math.max(0,Math.min(r-1,n))}return t.start+r+(e-t.end)}function tN(e){return e.currentText.length===0&&e.nextText.length>0||e.currentText.length>0&&e.nextText.length===0}function rN(e){return e.filter(tN).length===1}function oN(e){return e.length>0&&e.trim().length===0}function nN(e){return{current:e.occurrence,next:{start:e.occurrence.start,end:e.occurrence.start+e.nextText.length}}}function Bd(e,t){let r=nN(t),o=r.next.end-r.next.start;return{active:pa(e,oN(t.currentText)?t.occurrence:r.current),needsRebase:fa(e,r.current),nextRange:{start:wa(e.start,r.current,o),end:wa(e.end,r.current,o)}}}function iN(e){let t=new Map;for(let r of e)t.set(`${r.start}:${r.end}`,r);return[...t.values()]}function bd(e,t,r){if(t===r)return null;let o=Si(t,r),n=o.next.end-o.next.start;if(!fa(e,o.current))return null;let i=l=>l<=o.current.start?l:l<o.current.end?o.current.start+Math.max(0,Math.min(n,l-o.current.start)):o.current.start+n+(l-o.current.end),s=i(e.start),a=i(e.end);return{start:Math.min(s,a),end:Math.max(s,a)}}function sN(e,t,r){let o=Si(t,r),n=o.current.end-o.current.start,i=o.next.end-o.next.start;return e.currentRange.end-e.currentRange.start===n&&e.nextRange.end-e.nextRange.start===i}function aN(e,t,r){return e.currentRange.start===0&&e.currentRange.end===t.length&&e.nextRange.start===0&&e.nextRange.end===r.length}function Av(e,t){let r=0;for(let o of t){let n=o.currentRange.end-o.currentRange.start,i=o.nextRange.end-o.nextRange.start;if(e<=o.currentRange.start)return e+r;if(e<o.currentRange.end)return o.nextRange.start+wa(e-o.currentRange.start,{start:0,end:n},i);r+=i-n}return e+r}function lN(e,t){let r=[...t].sort((s,a)=>s.currentRange.start-a.currentRange.start||s.currentRange.end-a.currentRange.end||s.nextRange.start-a.nextRange.start||s.nextRange.end-a.nextRange.end||s.revisionId.localeCompare(a.revisionId));if(!r.some(s=>fa(e,s.currentRange)))return null;let n=Av(e.start,r),i=Av(e.end,r);return{start:Math.min(n,i),end:Math.max(n,i)}}function Sr(e){if(e.canonicalDocument&&e.projectedMode&&e.blockId){let o=Bn({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(o.length>0){if(o.length===1&&sN(o[0],e.currentBlockText,e.nextBlockText)){let i=bd(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}if(o.length===1&&aN(o[0],e.currentBlockText,e.nextBlockText)){let i=bd(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}let n=lN(e.selectionRange,o);return n||null}}let t=Mv(e.revisions),r=iN(t.flatMap(o=>ma(e.currentBlockText,o.currentText).flatMap(n=>{let i=e.currentBlockText.slice(0,n.start),s=e.currentBlockText.slice(n.end);if(e.nextBlockText!==`${i}${o.nextText}${s}`)return[];let a=Bd(e.selectionRange,{occurrence:n,currentText:o.currentText,nextText:o.nextText});return a.needsRebase?[a.nextRange]:[]})));return r.length===1?r[0]:r.length===0&&rN(t)?bd(e.selectionRange,e.currentBlockText,e.nextBlockText):null}function cN(e,t){return t!=="visible"||e.preservesWholeCurrentSide||e.currentActiveRange.start<e.currentRange.start||e.currentActiveRange.end>e.currentRange.end?e.currentActiveRange:e.currentRange}function vi(e){if(!e.projectedMode||!e.projectedDocument||!e.selectionTarget)return lr(e.selection,e.revisions);let t=e.activationScope??"preserved",r=nv({target:e.selectionTarget,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode})??e.selectionTarget;if(e.canonicalDocument){let s=new Set,a=!1;for(let l of r.segments){let c=Bn({blockId:l.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(c.length===0)continue;let d=Vr({document:e.projectedDocument,blockId:l.blockId,projectedMode:e.projectedMode,range:l.range})??l.range;a=!0;for(let u of c)pa(d,cN(u,t))&&s.add(u.revisionId)}if(s.size>0)return le([...s],e.revisions);if(a)return[]}let o=Iv(e.revisions,e.projectedMode),n=!1,i=new Set;for(let s of r.segments){let a=Pt(e.projectedDocument,s.blockId);if(typeof a=="string")for(let l of o){let c=ma(a,l.currentText);if(c.length===0||(n=!0,c.length!==1))continue;Bd(s.range,{occurrence:c[0],currentText:l.currentText,nextText:l.nextText}).active&&i.add(l.revisionId)}}return i.size>0?le([...i],e.revisions):n?[]:le(e.selection.trackedChangeIds,e.revisions)}function We(e){return e.view?.state?.doc??e.state?.doc??e.document}import{readSyntheticSideStoryDocContext as dN,readSyntheticSideStoryDocOriginPath as uN}from"@datalking/begonia-doc-service/v1";import{projectAcceptedTextBetween as mN}from"@datalking/begonia-engine";function pN(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function xn(e,t){return e.content.size>0?mN(e,t,1,e.content.size,`
9
- `):""}function Nv(e,t,r,o){let n=Me(e,t,r);return dN(pN(n),o)?.doc??null}function fN(e,t){let r=uN(e.document);if(!r)return null;let o=Nv(t,e,"final",r),n=Nv(t,e,"original",r),i=!!o?.eq(e.document),s=!!n?.eq(e.document);if(i!==s)return i?"final":"original";if(!o||!n)return null;let a=xn(e.document,e.schema),l=xn(o,e.schema),c=xn(n,e.schema),d=a===l;return d!==(a===c)?d?"final":"original":null}function ga(e,t){if(!t||e.document.eq(t))return null;let r=fN(e,t);if(r)return r;let o=Me(t,e,"final");if(e.document.eq(o))return"final";let n=Me(t,e,"original");if(e.document.eq(n))return"original";let i=xn(e.document,e.schema),s=xn(o,e.schema),a=xn(n,e.schema),l=i===s;return l===(i===a)?null:l?"final":"original"}import{describeSurfaceSelection as Qv}from"@datalking/begonia-engine";import{formatAddressableBlockIdWithLogicalId as wN,parseAddressableBlockId as Dv}from"@datalking/begonia-doc-service/structure";import{resolveRevisionProjectedDocument as gN}from"@datalking/begonia-engine";function SN(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function vN(e){return e==="final"?"original":"final"}function Ov(e){if(!e.target||!e.sourceTarget||!e.projectedDocument||!e.canonicalDocument||!e.projectedMode)return e.target;let t=gN(e.canonicalDocument,e.canonicalDocument.type.schema,vN(e.projectedMode)),r=e.target.segments.map((n,i)=>{let s=e.sourceTarget?.segments[i],a=Dv(n.blockId),l=s?Dv(s.blockId):null;if(!s||!a||!l?.logicalId)return n;let c=wN(a.blockType,a.path,l.logicalId),d=Q(t,{kind:"text",segments:[n]},{strict:!0}),u=Q(t,{kind:"text",segments:[{blockId:c,range:{start:n.range.start,end:n.range.end}}]},{strict:!0});return!(u&&(!d||!SN([d.from,d.to],[u.from,u.to])))?n:{blockId:c,range:{start:n.range.start,end:n.range.end}}});return r.some((n,i)=>n.blockId!==e.target?.segments[i]?.blockId)?Kt(e.target,r):e.target}import{addressableBlockTypeForNodeType as hN,formatAddressableBlockId as yN}from"@datalking/begonia-doc-service/structure";function hi(e,t){let r=da(e,t);if(!r)return t;let o=hN(r.node.type.name);return o?yN(o,r.path):t}function wo(e,t){if(!t)return t;let r=se(e),o=t.segments.map(i=>{let s=hi(e,i.blockId),a=da(e,i.blockId),l=s===i.blockId||!a?{start:i.range.start,end:i.range.end}:{start:nr(a.node,i.range.start,"start",r),end:nr(a.node,i.range.end,"end",r)};return{blockId:s,range:l}});return o.some((i,s)=>i.blockId!==t.segments[s]?.blockId||i.range.start!==t.segments[s]?.range.start||i.range.end!==t.segments[s]?.range.end)?Kt(t,o):t}function xd(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?ge(e,t,o):null}function jv(e){return e.includes("revision_delete")&&!e.includes("revision_insert")?["original"]:e.includes("revision_insert")&&!e.includes("revision_delete")?["final"]:["original","final"]}function Vv(e,t){return e.from!==t.from||e.to!==t.to||e.text!==t.text||e.target.segments.length!==t.target.segments.length?!1:e.target.segments.every((r,o)=>{let n=t.target.segments[o];return!!(n&&r.blockId===n.blockId&&r.range.start===n.range.start&&r.range.end===n.range.end)})}function Lv(e,t,r){let o=new Set;for(let n of Ji(e.resolve(t)))o.add(n);if(t===r)return[...o];for(let n of Yi(e,t,r))o.add(n);return[...o]}import{parseAddressableBlockId as Wv}from"@datalking/begonia-doc-service/structure";import{DELETION_MARK_NAME as _v,FORMAT_MARK_NAME as DN,INSERTION_MARK_NAME as Uv,resolveRevisionProjectedDocument as Kv}from"@datalking/begonia-engine";function bN(e){return tr(e)}function Sa(e,t){return t==="final"?e.visibleFinal:e.visibleOriginal}function zv(e,t){let r=Cr(e,t);if(!r)return null;let o=r.node;if(!o?.isBlock)return null;let n=[],i=gi(r.document),s=0,a=(l,c,d,u)=>{let m=l.isInline?!wt(l,"final",!c):c,p=l.isInline?!wt(l,"original",!d):d,f=bN(l);if(f>0){n.push({start:s,end:s+f,visibleFinal:m,visibleOriginal:p}),s+=f;return}let g=!0,v=!1,E=!1;l.forEach((R,S,P)=>{let h=[...u,P],b=!R.isBlock||i.isBlockPresent(h,"final"),x=!R.isBlock||i.isBlockPresent(h,"original");R.isBlock&&!g&&(n.push({start:s,end:s+1,visibleFinal:m&&b&&v,visibleOriginal:p&&x&&E}),s+=1),a(R,(l.isInline?m:c)&&b,(l.isInline?p:d)&&x,h),R.isBlock&&(v||=m&&b,E||=p&&x),g=!1})};return a(o,i.isBlockPresent(r.localPath,"final"),i.isBlockPresent(r.localPath,"original"),r.localPath),{runs:n,textLength:s}}function BN(e,t){return e.reduce((r,o)=>r+(Sa(o,t)?o.end-o.start:0),0)}function Cd(e,t,r,o){let n=e.filter(a=>Sa(a,t)),i=BN(e,t);if(!Number.isInteger(r)||r<0||r>i)return null;if(n.length===0)return r===0?0:null;let s=0;for(let a=0;a<n.length;a+=1){let l=n[a],c=l.end-l.start,d=s+c;if(r<d)return l.start+(r-s);if(r===d)return o==="end"||a===n.length-1?l.end:n[a+1].start;s=d}return r===s?n[n.length-1].end:null}function Fv(e,t,r,o){if(!Number.isInteger(r)||r<0||r>o)return null;let n=0;for(let i of e){if(r<=i.start)return n;let s=i.end-i.start,a=Sa(i,t)?s:0;if(r<i.end)return n+(Sa(i,t)?r-i.start:0);n+=a}return n}function Hv(e){let t=zv(e.canonicalDocument,e.blockId);if(!t)return null;if(e.range.start===e.range.end){let n=Cd(t.runs,e.projectedMode,e.range.start,"start");return n==null?null:{start:n,end:n}}let r=Cd(t.runs,e.projectedMode,e.range.start,"start"),o=Cd(t.runs,e.projectedMode,e.range.end,"end");return r==null||o==null?null:{start:Math.min(r,o),end:Math.max(r,o)}}function yi(e){let t=zv(e.canonicalDocument,e.blockId);if(!t)return null;let r=Fv(t.runs,e.projectedMode,e.range.start,t.textLength),o=Fv(t.runs,e.projectedMode,e.range.end,t.textLength);return r==null||o==null?null:{start:Math.min(r,o),end:Math.max(r,o)}}import{addressableBlockTypeForNodeType as xN,formatAddressableBlockIdWithLogicalId as CN}from"@datalking/begonia-doc-service/structure";import{isAddressableTextHiddenLeaf as PN,isDocumentNodePathIndex as RN,semanticNodeText as TN}from"@datalking/begonia-document-model";function kN(e){return e.isText?e.text?.length??0:!e.isLeaf||PN(e)?0:Math.max(1,TN(e).length)}function EN(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function MN(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=xN(r.type.name);if(o)return{type:o,path:EN(e,t),node:r,pos:e.start(t)-1}}return null}function IN(e,t,r,o){let n=e[e.length-1];if(n?.blockId===t){n.range.start=Math.min(n.range.start,r),n.range.end=Math.max(n.range.end,o);return}e.push({blockId:t,range:{start:r,end:o}})}function AN(e,t){let r=Le(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!RN(i)||i>=o.childCount)return null;n+=1;for(let s=0;s<i;s+=1)n+=o.child(s).nodeSize;o=o.child(i)}return o.isBlock?{node:o,position:n}:null}function bi(e,t,r){let o=t+1;if(r<=o)return 0;let n=0,i=!1,s=(l,c)=>{let d=0,u=!0;for(let m=0;m<l.childCount;m+=1){if(i)return;let p=l.child(m),f=c+d;if(p.isBlock&&!u)if(r>=f+1)n+=1;else{i=!0;return}a(p,f),d+=p.nodeSize,u=!1}},a=(l,c)=>{if(!i){if(l.isText){let d=l.text??"",u=c+d.length;r>=u?n+=d.length:(n+=Math.max(0,r-c),i=!0);return}if(l.isLeaf){let d=kN(l);r>=c+l.nodeSize?n+=d:i=!0;return}s(l,c+1)}};return s(e,o),n}function Pd(e,t,r,o="end"){let n=t+1,i=Math.max(n,t+e.nodeSize-1),s=bi(e,t,i);if(!Number.isInteger(r)||r<0||r>s)return null;let a=n,l=i;for(;a<l;){let d=a+Math.floor((l-a)/2);bi(e,t,d)<r?a=d+1:l=d}if(o!=="start")return a;let c=a;for(;c<i&&bi(e,t,c+1)===r;)c+=1;return c}function Bi(e,t){let r=[],o=!1,n=Math.min(t.from,t.to),i=Math.max(t.from,t.to);return e.nodesBetween(n,i,(s,a)=>{if(o)return!1;if(!s.isTextblock)return!0;let l=e.resolve(a+1),c=MN(l);if(!c)return o=!0,!1;let d=Math.max(n,a+1),u=Math.min(i,a+s.nodeSize-1),m=bi(c.node,c.pos,d),p=Math.max(m,bi(c.node,c.pos,u));return IN(r,CN(c.type,c.path,Hr(c.type,c.node)),m,p),!1}),o?null:r}function NN(e,t){let r=AN(e,t.blockId);if(!r)return null;if(t.range.start===t.range.end){let i=Pd(r.node,r.position,t.range.start,"start");return typeof i=="number"?{from:i,to:i}:null}let o=Pd(r.node,r.position,t.range.start,"start"),n=Pd(r.node,r.position,t.range.end,"end");return typeof o!="number"||typeof n!="number"?null:{from:Math.min(o,n),to:Math.max(o,n)}}function qv(e,t){let r=[];for(let o of t){let n=NN(e,o);if(!n)return null;r.push(n)}return _r(e,r,{strict:!0})}function Zv(e,t){let r=Wv(e),o=Wv(t);return!r||!o?e===t:r.blockType===o.blockType&&r.path.length===o.path.length&&r.path.every((n,i)=>n===o.path[i])}function Gv(e,t){return!!(t&&e.range.start===e.range.end&&t.range.start<t.range.end&&Zv(e.blockId,t.blockId))}function ON(e,t){return t?.segments.length===e.length&&e.some((r,o)=>Gv(r,t.segments[o]))}function Xv(e){return(e??[]).some(t=>t===Uv||t===_v||t===DN)}function Rd(e){if(!e.selectionInfo.target||!e.projectedDocument)return!1;let t=Q(e.projectedDocument,e.selectionInfo.target,{strict:!0});return!!(t&&t.from===e.selection.from&&t.to===e.selection.to)}function jN(e){if(!e.selectionInfo.target||!e.projectedDocument)return null;if(Rd(e))return e.selectionInfo.target;let t=wo(e.projectedDocument,e.selectionInfo.target),r=t?Q(e.projectedDocument,t,{strict:!0}):null;return r&&r.from===e.selection.from&&r.to===e.selection.to?t:$v(e)?.target??null}function $v(e){let t=e.selectionInfo.text??"";if(!e.projectedDocument||!e.selectionInfo.target||t.length===0)return null;let r=kl(e.projectedDocument,e.selectionInfo.target,t);if(!r)return null;let o=Rd(e),n=r.selection.from===e.selection.from&&r.selection.to===e.selection.to;if(!o&&!n)return null;let i=ge(e.projectedDocument,e.projectedDocument.type.schema,r.selection);return i!==t?null:{target:r.target,text:i,from:r.selection.from,to:r.selection.to}}function Td(e,t="preserved"){if(e.projectedMode||!e.canonicalDocument||!e.selectionInfo.target)return null;if(e.selection.empty&&e.selection.from===e.selection.to){let o=wo(e.projectedDocument??e.canonicalDocument,e.selectionInfo.target),n=o?Q(e.projectedDocument??e.canonicalDocument,o,{strict:!0}):null;if(n&&(n.from!==e.selection.from||n.to!==e.selection.to))return ce(e.selectionInfo.activeChangeIds).length===0?[]:null}let r=jN(e);return r?vi({selection:e.selection,selectionTarget:r,projectedDocument:e.projectedDocument??e.canonicalDocument,canonicalDocument:e.canonicalDocument,projectedMode:"final",revisions:e.revisions,activationScope:t}):ce(e.selectionInfo.activeChangeIds).length===0?[]:null}function Yv(e){if(e.projectedMode||!e.projectedDocument||!e.selectionInfo.target||!e.selection.empty&&ce(e.selectionInfo.activeChangeIds).length===0||e.selection.empty&&e.selectionInfo.activeMarks.includes(_v)&&!e.selectionInfo.activeMarks.includes(Uv))return null;let t=$v(e);if(t)return{target:t.target,text:t.text};if(!e.canonicalDocument||!e.projectedDocument.eq(e.canonicalDocument))return null;let r=e.selectionInfo.text??"",o=Bi(e.projectedDocument,e.selection);if(!o||o.length===0||r.length>0&&Rd(e)&&o.every(l=>l.range.start===l.range.end)&&!ON(o,e.selectionInfo.target))return null;let n=e.projectedDocument.type.schema,i={final:Kv(e.canonicalDocument,n,"final"),original:Kv(e.canonicalDocument,n,"original")},s=e.selection.empty?["final"]:jv(e.selectionInfo.activeMarks),a=null;for(let l of s){let c=i[l],d=o.map((S,P)=>{let h=e.selectionInfo.target?.segments[P],b=h&&Zv(S.blockId,h.blockId)?h.blockId:S.blockId,x=hi(e.projectedDocument,b),A=hi(i.final,b),O=F=>({review:{blockId:x,range:{start:F.start,end:F.end}},expected:{blockId:A,range:{start:F.start,end:F.end}}}),j=Gv(S,h)?Vr({document:e.projectedDocument,blockId:h.blockId,projectedMode:l,range:h.range}):yi({canonicalDocument:e.canonicalDocument,blockId:S.blockId,projectedMode:l,range:S.range});if(!j)return null;if(l==="final")return O(j);let _=Pt(c,S.blockId),V=Pt(i.final,S.blockId);if(typeof _!="string"||typeof V!="string")return null;let de=Sr({selectionRange:j,currentBlockText:_,nextBlockText:V,blockId:S.blockId,canonicalDocument:e.canonicalDocument,projectedMode:l,revisions:e.revisions});if(de)return O(de);let k=xd(c,n,{blockId:S.blockId,range:j});return k==null||xd(e.projectedDocument,n,{blockId:S.blockId,range:j})!==k?null:O(j)});if(d.some(S=>!S))continue;let u=Kt(e.selectionInfo.target,d.map(S=>S.review)),m=Kt(e.selectionInfo.target,d.map(S=>S.expected)),p=Q(e.projectedDocument,u,{strict:!0});if(!p)continue;let f=jr({currentDocument:e.projectedDocument,expectedProjectedDocument:i.final,schema:n});if(!f)continue;let g=Q(f,m,{strict:!0});if(!g)continue;let v=ge(e.projectedDocument,n,p),E=ge(f,n,g);if(v!==E)continue;let R={target:u,text:v,from:p.from,to:p.to};if(!a){a=R;continue}if(!Vv(a,R))return null}return a?{target:a.target,text:a.text}:null}function kd(e,t){let r=e.trackedChangeIds??[];return e.trackedChangeIds!=null&&t.length===r.length&&t.every((o,n)=>o===r[n])?e:{...e,trackedChangeIds:[...t]}}function Jv(e,t){let r=e.activeChangeIds??[];return e.activeChangeIds!=null&&t.length===r.length&&t.every((o,n)=>o===r[n])?e:{...e,activeChangeIds:[...t]}}function VN(e,t,r,o){if(e.projectedMode!=null||e.selection.empty||o)return!1;let n=Math.max(ce(e.selection.trackedChangeIds).length,ce(e.selectionInfo.activeChangeIds).length),i=Math.max(ce(t).length,ce(r).length);return n>i&&(e.selectionInfo.text??"").length>0}function $e(e){let t=Do(e.selection,e.revisions),r=Td({...e,selection:t})??vi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions}),o=Td({...e,selection:t},"visible")??vi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions,activationScope:"visible"}),n=Ur(e.selectionInfo,t,e.revisions),i=kd(t,r),s=Yv({...e,selection:i});if(VN(e,r,o,s)){let E=ce(t.trackedChangeIds),R=ce(n.activeChangeIds);return{selection:kd(t,E),selectionInfo:Jv(n,R.length>0?R:E),trackedChangeIds:E}}let a=s?Q(e.projectedDocument,s.target,{strict:!0}):null,l=e.selection.empty&&ce(e.selectionInfo.activeCommentIds).length===0,c=!!a&&(l||(s?.text??"").length>0),d=c&&a?(()=>{let E=gt(a,xr(i));return kd({...i,from:a.from,to:a.to,anchor:E.anchor,head:E.head,empty:a.from===a.to},r)})():i,u=c&&a?Lv(e.projectedDocument,d.from,d.to):e.selectionInfo.activeMarks,m=s&&e.selection.empty&&s.text.length===0?void 0:s?.text,p=Ur(s?{...e.selectionInfo,...s,text:m,activeMarks:u}:e.selectionInfo,d,e.revisions),f=e.projectedDocument&&p.target&&(s!=null||e.projectedMode==null&&ce(o).length>0||e.projectedMode!=null||Xv(e.selectionInfo.activeMarks))?wo(e.projectedDocument,p.target):p.target,g=Ov({target:f,sourceTarget:p.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),v=g!==p.target?{...p,target:g}:p;return{selection:d,selectionInfo:Jv(v,o),trackedChangeIds:r}}function Ye(e){return e.view?.state??e.state??null}function va(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function vr(e,t=null){let r=Ye(e);if(!r)return null;let o=Ee(r,{includeText:!0});return t?$e({selection:Qv(r),selectionInfo:o,projectedDocument:r.doc,revisions:t.review.list()}).selectionInfo:o}function ha(e){let t=Ye(e.surface);if(!t)return null;let r=Ee(t,{includeText:!0});return $e({selection:Qv(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}).selectionInfo}function eh(e,t,r){return ge(e,t,r)}function ya(e,t,r){return r!=null&&eh(e.doc,e.schema,t)===r}function LN(e,t){let r=Ye(e);return!!(r&&t&&r.selection.from===t.from&&r.selection.to===t.to)}function FN(e,t){return Vn(e,t)}function zN(e,t,r){let o=[],n=new Set;for(let i of r){let s=t.comments.target(i),a=Ge(We(e),s);if(s&&a&&LN(e,a)){let l=FN(i,s);if(n.has(l))continue;n.add(l),o.push({commentId:l,target:s})}}return o.length===0?null:o.length===1?o[0]:null}function th(e,t,r){if(r.length===0)return null;let o=zN(e,t,r);return o?{kind:"comment",commentId:o.commentId,target:o.target}:null}function Dt(e,t,r){return eh(e,t,r)}import{pmPositionToAddressableTextOffset as nD}from"@datalking/begonia-document-model";import{EditorState as iD,NodeSelection as Sh}from"prosemirror-state";import{cloneSelectionTextRange as qN}from"@datalking/begonia-document-api/core";function HN(e){return e.hasExpectedSegmentTexts?e.expectedSegmentSelection??e.expectedTextSelection:e.hasExpectedText?e.expectedTextSelection:e.strictSelection}function rh(e){return e==="original"?"original":"final"}function oh(e){if(!e.hasExpandedTarget)return e.strictSelection;let t=rh(e.sourceMode),r=rh(e.projectedMode);if(t===r&&!e.hasExpectedSegmentTexts&&!e.hasExpectedText&&!e.expectedSegmentSelection&&!e.expectedTextSelection){if(e.strictSelection&&e.strictSelection.from!==e.strictSelection.to)return e.strictSelection;if(e.anchorSelection)return e.anchorSelection;if(e.strictSelection&&e.strictSelection.from===e.strictSelection.to)return e.strictSelection}return t!==r?e.strictSelection:HN(e)}function nh(e){return e?{kind:"text",segments:e.segments.map(t=>({blockId:t.blockId,range:{start:t.range.start,end:t.range.start,...t.range.startAffinity?{startAffinity:t.range.startAffinity}:{},...t.range.endAffinity?{endAffinity:t.range.endAffinity}:{}}})),...e.story?{story:structuredClone(e.story)}:{}}:null}function WN(e){let{target:t}=e,r=t.segments.map(n=>({blockId:er({blockId:n.blockId,projectedDocument:e.sourceDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode}),range:qN(n.range)}));return r.some((n,i)=>n.blockId!==t.segments[i]?.blockId)?{kind:"text",segments:r,...t.story?{story:structuredClone(t.story)}:{}}:t}function ih(e,t){return e?Me(e,{schema:e.type.schema},t):null}function KN(e,t){return e.start===t.start&&e.end===t.end}function Ed(e){return e.start===e.end}function _N(e){if(!e.canonicalDocument)return!1;let t=e.target.segments.filter(r=>!Ed(r.range));return t.length===0?!1:t.every(r=>Bn({blockId:r.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode,revisions:e.revisions}).some(o=>KN(r.range,o.currentRange)&&!Ed(o.currentRange)&&Ed(o.nextRange)))}function UN(e){let t=e.projectionSnapshot.canonicalDocument;if(!t)return null;let r=ih(t,e.sourceMode),n=(r?wo(r,e.target):null)??Et(e.target);if(!n)return null;let i=WN({target:n,sourceDocument:r,canonicalDocument:t,sourceMode:e.sourceMode}),s=nh(i);if(e.projectionSnapshot.projectedMode===e.sourceMode)return s&&_N({canonicalDocument:t,sourceMode:e.sourceMode,target:i,revisions:e.revisions})?{target:s,anchorTarget:s}:{target:i,anchorTarget:s};let a=e.projectionSnapshot.projectedMode??"final";if(e.projectionSnapshot.projectedMode==null&&e.sourceMode==="final")return{target:i,anchorTarget:s};let l=ih(t,a);if(!l)return{target:i,anchorTarget:s};let c=n.segments.map((m,p)=>{let f=i.segments[p];if(!f)return null;let g=r?Pt(r,m.blockId):null,v=Pt(l,f.blockId),E=Sr({selectionRange:m.range,currentBlockText:g??"",nextBlockText:v??"",blockId:f.blockId,canonicalDocument:t,projectedMode:e.sourceMode,revisions:e.revisions})??{start:f.range.start,end:f.range.end};return{blockId:f.blockId,range:E}});if(c.some(m=>!m))return null;let d={kind:"text",segments:c,...e.target.story?{story:structuredClone(e.target.story)}:{}},u=nh(d);return{target:d,anchorTarget:u}}function sh(e){return e.sourceMode==null?(()=>{let t=Et(e.target);return t?{target:t,anchorTarget:null}:null})():UN({...e,sourceMode:e.sourceMode})}function ut(e){let t=sh(e);if(!t)return null;let{target:r,anchorTarget:o}=t,n=Array.isArray(e.expectedSegmentTexts)&&e.expectedSegmentTexts.length>0,i=typeof e.expectedText=="string"&&e.expectedText.length>0,s=r.segments.some(p=>p.range.start!==p.range.end),a={strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"},l=Q(e.state.doc,r,a),c=o?Q(e.state.doc,o,a):null,d=n?tt(e.state.doc,r,e.expectedSegmentTexts??null,a):null,u=i?Ae(e.state.doc,r,e.expectedText??null,a):null,m=oh({sourceMode:e.sourceMode,projectedMode:e.projectionSnapshot.projectedMode,hasExpandedTarget:s,hasExpectedText:i,hasExpectedSegmentTexts:n,strictSelection:l,anchorSelection:c,expectedTextSelection:u,expectedSegmentSelection:d});return m?{target:r,selection:{from:Math.min(m.from,m.to),to:Math.max(m.from,m.to)}}:null}function Md(e,t,r){return ge(e,t,r)}function ah(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?Md(e,t,o):null}function ZN(e){let t=Me(e.canonicalDocument,{schema:e.schema},e.projectedMode);return jr({currentDocument:e.referenceDocuments[0]??t,expectedProjectedDocument:t,schema:e.schema})}function Id(e){let t=ZN({canonicalDocument:e.canonicalDocument,schema:e.schema,projectedMode:e.nextProjectionMode,referenceDocuments:[e.nextDocument,e.currentDocument]});if(!t)return null;let r=e.selectionTarget.segments.map(l=>{let c=er({blockId:l.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),d=Vr({document:e.currentDocument,blockId:l.blockId,projectedMode:e.currentProjectionMode,range:l.range})??l.range,u=Pt(e.currentDocument,c),m=Pt(t,c);if(typeof u!="string"||typeof m!="string")return null;let p=Sr({selectionRange:d,currentBlockText:u,nextBlockText:m,blockId:c,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode,revisions:e.canonicalReviewApi.review.list()});if(p){let v=ua({document:t,blockId:c,projectedMode:e.nextProjectionMode,range:p});return v?{blockId:c,range:v}:null}let f=ah(e.currentDocument,e.schema,l);return f==null||ah(t,e.schema,{blockId:c,range:l.range})!==f?null:{blockId:c,range:l.range}});if(r.some(l=>!l))return null;let o={kind:"text",segments:r,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},n=Q(e.nextDocument,o,{strict:!0});if(!n)return null;let i=Q(t,o,{strict:!0});if(!i)return null;let s=Md(e.nextDocument,e.schema,n),a=Md(t,e.schema,i);return s===a?n:null}function lh(e){let t=Vr({document:e.currentDocument,blockId:e.currentBlockId,projectedMode:e.currentProjectionMode,range:e.range});return t?ua({document:e.canonicalDocument,blockId:e.canonicalBlockId,projectedMode:e.currentProjectionMode,range:t}):null}function ch(e){let t=s=>({blockId:er({blockId:s.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),range:structuredClone(s.range)}),[r,...o]=e.selectionTarget.segments,n={kind:"text",segments:[t(r),...o.map(t)],...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},i=lt(e.currentDocument,e.selectionTarget);return tt(e.nextDocument,n,i,{strict:!0})??Ae(e.nextDocument,n,e.expectedText,{strict:!0})}import{buildExtractOverlapParentAliasMap as JN}from"@datalking/begonia-document-api/review";function GN(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function XN(e,t){let r=e??[],o=t??[],n=Math.min(r.length,o.length);for(let i=0;i<n;i+=1){let s=r[i]-o[i];if(s!==0)return s}return r.length-o.length}function Ad(e){return!!(e&&e.nodeType&&e.objectId)}function $N(e,t){return Ad(e.target)&&e.target?.nodeType===t}function dh(e,t){return typeof e.entryId=="string"&&typeof t.entryId=="string"&&e.entryId===t.entryId?!0:!!(Ad(e.target)&&Ad(t.target)&&e.target?.objectId===t.target?.objectId&&GN(e.target?.path,t.target?.path))}function YN(e){return[...e].sort((t,r)=>XN(t.target?.path,r.target?.path)||(t.from??0)-(r.from??0)||(t.to??0)-(r.to??0)||String(t.entryId??"").localeCompare(String(r.entryId??"")))}function uh(e){let t=e.currentMember.kind==="insert"?new Set(["delete"]):e.currentMember.kind==="delete"?new Set(["insert"]):new Set([e.currentMember.kind]),r=e.nextProjectionMode==="original"?new Set(["delete","format"]):new Set(["insert","format"]),o=YN(e.revisions.flatMap(l=>l.members??[]).filter(l=>$N(l,e.nodeType))),n=o.find(l=>r.has(l.kind)&&dh(l,e.currentMember));if(n)return n;let s=o.filter(l=>l.kind===e.currentMember.kind).findIndex(l=>dh(l,e.currentMember));return s<0?null:o.filter(l=>t.has(l.kind))[s]??null}function QN(e){return!!(e&&e.nodeType&&e.objectId)}function ph(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function eD(e,t){let r=ph(e);return r?t.get(r)?.id??r:null}function mh(e,t){let r=ph(e.operationId);if(!r)return null;let o=eD(e.overlapParentId,t);return o==null?r:`${r}\0${o}`}function tD(e){for(let t of e.revisions)for(let r of t.members??[])if(QN(r.target)&&r.target?.nodeType===e.currentSelectionTarget.nodeType&&r.target?.objectId===e.currentSelectionTarget.stableIdentity)return{revision:t,member:r};return null}function fh(e){let t=e.currentSelectionTarget,r=tD(e);if(!r)return null;let o=JN(e.revisions),n=mh(r.revision,o),i=n==null?[r.revision]:e.revisions.filter(a=>mh(a,o)===n),s=uh({currentMember:r.member,revisions:i,nodeType:t.nodeType,nextProjectionMode:e.nextProjectionMode});return s?.target?.objectId?{kind:"node",nodeType:t.nodeType,stableIdentity:s.target.objectId,path:s.target.path}:null}import{collectRevisionSpans as wh,selectionOverlapsRevisionRange as rD}from"@datalking/begonia-engine";function xi(e,t,r,o){return Dt(e,t,{from:r,to:o}).length}function oD(e){let t=xi(e.doc,e.schema,e.from,e.to);if(!Number.isInteger(e.acceptedOffset)||e.acceptedOffset<0||e.acceptedOffset>t)return null;let r=e.from,o=e.to;for(;r<o;){let n=r+Math.floor((o-r)/2);xi(e.doc,e.schema,e.from,n)<e.acceptedOffset?r=n+1:o=n}return xi(e.doc,e.schema,e.from,r)===e.acceptedOffset?r:null}function gh(e){if(e.selection.from!==e.selection.to)return null;let t=wh(e.currentDocument,e.schema).filter(l=>rD(e.selection.from,e.selection.to,l)),r=t.length===1?t[0]:null;if(!r||xi(e.currentDocument,e.schema,r.from,r.to)===0)return null;let n=wh(e.nextDocument,e.schema).filter(l=>l.id===r.id&&l.kind===r.kind),i=n.length===1?n[0]:null;if(!i)return null;let s=xi(e.currentDocument,e.schema,r.from,e.selection.from),a=oD({doc:e.nextDocument,schema:e.schema,from:i.from,to:i.to,acceptedOffset:s});return typeof a=="number"?{from:a,to:a}:null}function sD(e){if(!K(e.state.selection)||!e.state.selection.node.isInline||e.state.selection.node.childCount!==0||!Ie(e.state))return e.selectionTarget;let t=Bi(e.state.doc,e.state.selection);return t&&t.length>0?{kind:"text",segments:t,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}}:e.selectionTarget}function aD(e){let t=e.selectionTarget.segments.map(d=>{let u=er({blockId:d.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),m=Hv({canonicalDocument:e.canonicalDocument,blockId:u,projectedMode:e.currentProjectionMode,range:d.range});return m?{blockId:u,range:m}:null});if(t.some(d=>!d))return null;let r=t.map(d=>{let u=d,m=yi({canonicalDocument:e.canonicalDocument,blockId:u.blockId,projectedMode:e.nextProjectionMode,range:u.range});return m?{blockId:u.blockId,range:m}:null});if(r.some(d=>!d))return null;let o={kind:"text",segments:r,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},n=Q(e.nextDocument,o,{strict:!0});if(!n)return null;let i=Me(e.canonicalDocument,{schema:e.schema},e.nextProjectionMode),s=jr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:e.schema});if(!s)return null;let a=Q(s,o,{strict:!0});if(!a)return null;let l=Dt(e.nextDocument,e.schema,n),c=Dt(s,e.schema,a);return l===c?n:null}function lD(e){if(e.selection.from!==e.selection.to||e.segments.length!==1)return null;let t=e.segments[0];if(t.range.start!==t.range.end)return null;let r=Le(e.nextDocument,t.blockId),o=r?Ve(e.nextDocument,r):null;if(!o?.node.isBlock)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=e.selection.from;return s<n||s>i?null:nD(o.node,o.position,s)===t.range.start?{from:s,to:s}:null}function Nd(e){let t=e.currentProjectionMode??null,r=We(e.surface),o=t?ha({surface:e.surface,canonicalReviewApi:e.canonicalReviewApi,canonicalDocument:e.canonicalDocument,projectedMode:t})??e.selectionInfo??vr(e.surface,e.canonicalReviewApi):vr(e.surface,e.canonicalReviewApi);if(!o||!o.target)return null;let n=Ye(e.surface);if(!n)return null;let i=t?sD({state:n,selectionTarget:o.target}):o.target,s=!!e.nextProjectionMode&&K(n.selection)&&n.selection.node.isInline&&n.selection.node.childCount===0,a=!!t&&s,l=s?Ie(n):null;if(l&&e.nextProjectionMode){let u=fh({currentSelectionTarget:l,revisions:e.canonicalReviewApi.review.list(),nextProjectionMode:e.nextProjectionMode});if(u)return u}let c=(()=>{if(a)return aD({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,nextProjectionMode:e.nextProjectionMode});if(!t&&!e.nextProjectionMode&&!n.selection.empty){let g=lt(r,i),v=tt(e.nextDocument,i,g??null,{strict:!0})??Ae(e.nextDocument,i,o.text??null,{strict:!0});if(v)return v}if(t&&e.nextProjectionMode)return Id({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:e.nextProjectionMode});let u=t?i.segments.map(g=>{let v=er({blockId:g.blockId,projectedDocument:r,canonicalDocument:e.canonicalDocument,projectedMode:t}),E=lh({currentDocument:r,canonicalDocument:e.canonicalDocument,currentBlockId:g.blockId,canonicalBlockId:v,currentProjectionMode:t,range:g.range});return E?{blockId:v,range:E}:null}):Bi(n.doc,n.selection);if(!u)return null;let m=u.filter(g=>g!=null);if(m.length!==u.length)return null;if(!e.nextProjectionMode){if(t){let g=lD({nextDocument:e.nextDocument,selection:n.selection,segments:m});if(g)return g;if(!n.selection.empty){let v=ch({currentDocument:r,nextDocument:e.nextDocument,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,expectedText:o.text});if(v)return v;let E=Id({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:"final"});if(E)return E}}if(!t){let g=gh({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selection:n.selection});if(g)return g}return qv(e.nextDocument,m)}let p=e.nextProjectionMode,f=m.map(g=>{let v=yi({canonicalDocument:e.canonicalDocument,blockId:g.blockId,projectedMode:p,range:g.range});return v?{blockId:g.blockId,range:v}:null});return f.some(g=>!g)?null:Q(e.nextDocument,{kind:"text",segments:f,...i.story?{story:structuredClone(i.story)}:{}},{strict:!0})})();if(!c)return null;let d=K(n.selection)?cD(e.nextDocument,c):null;return d||{kind:"tracked",selection:c,text:Dt(e.nextDocument,n.schema,c)}}function vh(e){if(!e.preservedRangeSelection.target)return null;let t=Ye(e.surface);if(!Dd(e)||!t)return null;let r=e.preservedRangeSelection.target,o=Ae(e.nextDocument,r,e.preservedRangeSelection.text,{strict:!0})??tt(e.nextDocument,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!o)return null;let n=e.nextProjectionMode??e.preservedRangeSelection.projectedMode;if(!n)return null;let i=Me(e.canonicalDocument,{schema:t.schema},n),s=jr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:t.schema});if(!s)return null;let a=Ae(s,r,e.preservedRangeSelection.text,{strict:!0})??tt(s,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!a)return null;let l=Dt(e.nextDocument,t.schema,o),c=Dt(s,t.schema,a);return o.from===a.from&&o.to===a.to&&l===c?{kind:"tracked",selection:o,text:l,...e.preservedRangeSelection.direction?{direction:e.preservedRangeSelection.direction}:{}}:null}function Dd(e){if(!e.preservedRangeSelection.target)return!1;let t=Ye(e.surface);if(!t||!t.selection.empty||e.preservedRangeSelection.projectedMode!==(e.nextProjectionMode??null))return!1;let r=ut({state:t,target:e.preservedRangeSelection.target,projectionSnapshot:{canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode??null},sourceMode:e.preservedRangeSelection.projectedMode,revisions:e.canonicalReviewApi.review.list(),expectedText:e.preservedRangeSelection.text,expectedSegmentTexts:e.preservedRangeSelection.segmentTexts});return!!(r&&r.selection.from===r.selection.to&&r.selection.from===t.selection.from&&r.selection.to===t.selection.to)}function cD(e,t){let r=e.nodeAt(t.from);if(!r||!r.isInline||r.childCount!==0||!Sh.isSelectable(r))return null;let o;try{o=Sh.create(e,t.from)}catch{return null}if(o.from!==Math.min(t.from,t.to)||o.to!==Math.max(t.from,t.to))return null;let n=iD.create({doc:e,selection:o});return Ie(n)}function hh(e,t){let r=Le(e,t),o=r?Ve(e,r):null;return o?.node.isBlock?Mo(o.node,se(e)).text:null}function uD(e){let t=Ye(e.surface);if(!t||!e.selectionInfo.target)return null;let r=We(e.surface),n={kind:"text",segments:e.selectionInfo.target.segments.map(s=>{let a=hh(r,s.blockId),l=hh(e.nextDocument,s.blockId),c=a!=null&&l!=null?Sr({selectionRange:s.range,currentBlockText:a,nextBlockText:l,revisions:e.canonicalReviewApi.review.list()}):null;return{blockId:s.blockId,range:c??dD(s.range)}})},i=Q(e.nextDocument,n,{strict:!0});return i?{kind:"text",target:n,text:Dt(e.nextDocument,t.schema,i),segmentTexts:lt(e.nextDocument,n)}:null}function mD(e,t,r,o,n,i,s){let a=vr(e),l=vr(e,o),c=!!(o&&n&&(ga(e,i?n:t)||i)),d=c?ga(e,i?n:t):null,u=c&&d?ha({surface:e,canonicalReviewApi:o,canonicalDocument:n,projectedMode:d})??l:l;if(a?.target&&d==="original"&&!i&&u?.activeMarks.length===0&&a.target.segments.every(g=>g.range.start===g.range.end)){let g=Ye(e),v=g?.selection??null;if(v)return{kind:"tracked",selection:{from:v.from,to:v.to},text:Dt(t,g?.schema??t.type.schema,v)}}let p=Ie(Ye(e)),f=u?.target&&r?th(e,r,u.activeCommentIds):null;if(f&&!p)return f;if(c&&u?.target){if(s){let v=Dd({surface:e,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s}),E=vh({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s});if(E)return E;if(v)return null}if(d&&!i&&u.activeChangeIds.length===0&&!p){let v=uD({surface:e,nextDocument:t,canonicalReviewApi:o,canonicalDocument:n,currentProjectionMode:d,selectionInfo:u});if(v)return v}let g=Nd({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(g)return g}if(o&&u?.target&&u.activeChangeIds.length>0){let g=Nd({surface:e,nextDocument:t,canonicalDocument:n??t,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(g)return g}return f||p||(u?.target&&u.activeChangeIds.length===0?{kind:"text",target:u.target,text:u.text??null,segmentTexts:lt(We(e),u.target)}:null)}function go(e){let t=mD(e.surface,e.nextDocument,e.documentApi,e.canonicalReviewApi,e.canonicalDocument,e.nextProjectionMode,e.preservedRangeSelection);if(!t||t.kind==="node")return t;let r=Ye(e.surface)?.selection;return r&&Dp(r)==="backward"?{...t,direction:"backward"}:t}function vD(e){return!!(e&&e.activeCommentIds.length===0&&e.activeMarks.includes(pD)&&!e.activeMarks.includes(wD)&&(e.text??"").length===0)}function Ci(e){if(!e.target||!va(e.surface))return;let t=e.surface.view.state.doc,r=e.target.kind==="node"?Gi(t,e.target):null,o=e.target.kind==="node"?null:e.target.kind==="comment"?di({comments:e.documentApi?.comments,commentId:e.target.commentId,fallbackTarget:e.target.target,resolve:l=>Ge(t,l)})?.resolution??null:e.target.kind==="tracked"?e.target.selection:tt(t,e.target.target,e.target.segmentTexts,{strict:!0})??Ae(t,e.target.target,e.target.text,{strict:!0}),n=()=>{let l=e.surface.view?.state;if(!l||typeof e.surface.view?.dispatch!="function")return;let c=l.selection,d=Z(l,c.from,c.from);!d||K(d)||e.surface.view.dispatch(l.tr.setSelection(d))};if(!r&&!o){e.target.kind==="node"&&n();return}if(e.target.kind!=="comment"&&e.target.kind!=="node"&&o&&!ya(e.surface.view.state,o,e.target.text))return;let i=e.surface.view.state.selection,s=o?gt(o,e.target.kind==="node"?void 0:e.target.direction):null;if(r?K(i)&&i.from===r.position:o&&i.from===o.from&&i.to===o.to&&i.anchor===s?.anchor&&i.head===s.head)return;let a=r?gD.create(e.surface.view.state.doc,r.position):Z(e.surface.view.state,s.anchor,s.head);a&&e.surface.view.dispatch(e.surface.view.state.tr.setSelection(a))}function ba(e){if(!va(e.surface))return!1;let t=Ye(e.surface);if(!t||t.selection.empty)return!1;let r=vr(e.surface),o=r&&e.canonicalReviewApi?$e({selection:fD(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}):null;if(vD(r))return!1;let n=o?.selectionInfo??r;if(!n?.target||n.activeCommentIds.length>0||n.activeChangeIds.length===0||typeof n.text!="string"||n.text.length===0)return!1;let i=o?{from:o.selection.from,to:o.selection.to}:Q(e.surface.view.state.doc,n.target,{strict:!0});if(!i||i.from>=i.to||t.selection.from===i.from&&t.selection.to===i.to||!ya(e.surface.view.state,i,n.text))return!1;let s=Z(e.surface.view.state,i.from,i.to);return!s||s.empty?!1:(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(s)),!0)}function Cn(e){let{surface:t,nextDocument:r,documentApi:o,nextDocumentApi:n}=e,i=go(e);t.replaceDocument(r,{origin:"system",intent:"replace-projected-document-preserving-selection",effects:[SD("review")]}),Ci({surface:t,target:i,documentApi:n??o})}import{createDocumentRuntimeKernel as nO}from"@datalking/begonia-document-api/v1";import{summarizeReviewTimeline as iO}from"@datalking/begonia-document-api/review";import{createEditorSelectionSnapshot as sO}from"@datalking/begonia-editor-contracts";function yh(e,t){return{surface:e,documentApi:t,context:{source:"browser-ooxml-nodeview"},runMutation(o,n){if(it(e)){if(e.trackingEnabled){o();return}n()}}}}function Pn(e,t){e.runMutation(()=>{e.documentApi.ooxml.removeByIdTracked(t,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.removeById(t)})}function Od(e,t){switch(t.action){case"replace-chart-model":e.runMutation(()=>{e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.replaceModelById(t.objectId,t.model)});return;case"apply-chart-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-metadata":e.runMutation(()=>{e.documentApi.ooxml.charts.setMetadataByIdTracked(t.objectId,r,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setMetadataById(t.objectId,r)});return;case"set-text-body":e.runMutation(()=>{e.documentApi.ooxml.charts.setTextBodyByIdTracked(t.objectId,r.textBody,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setTextBodyById(t.objectId,r.textBody)});return;case"set-plot-area":e.runMutation(()=>{e.documentApi.ooxml.charts.setPlotAreaByIdTracked(t.objectId,r.plotArea,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setPlotAreaById(t.objectId,r.plotArea)});return;case"set-legend":e.runMutation(()=>{e.documentApi.ooxml.charts.setLegendByIdTracked(t.objectId,r.legend,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setLegendById(t.objectId,r.legend)});return;case"set-series":e.runMutation(()=>{e.documentApi.ooxml.charts.setSeriesByIdTracked(t.objectId,r.target,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setSeriesById(t.objectId,r.target,r.series)});return;case"set-series-list":e.runMutation(()=>{e.documentApi.ooxml.charts.setSeriesListByIdTracked(t.objectId,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setSeriesListById(t.objectId,r.series)});return;case"upsert-series":e.runMutation(()=>{e.documentApi.ooxml.charts.upsertSeriesByIdTracked(t.objectId,r.series,e.surface.participant,e.context,r.seriesId)},()=>{e.documentApi.ooxml.charts.upsertSeriesById(t.objectId,r.series,r.seriesId)});return;case"append-series":e.runMutation(()=>{e.documentApi.ooxml.charts.appendSeriesByIdTracked(t.objectId,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.appendSeriesById(t.objectId,r.series)});return;case"remove-series":e.runMutation(()=>{e.documentApi.ooxml.charts.removeSeriesByIdTracked(t.objectId,r.target,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.removeSeriesById(t.objectId,r.target)});return;case"set-axes":e.runMutation(()=>{e.documentApi.ooxml.charts.setAxesByIdTracked(t.objectId,r.axes,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setAxesById(t.objectId,r.axes)});return;case"upsert-axis":e.runMutation(()=>{e.documentApi.ooxml.charts.upsertAxisByIdTracked(t.objectId,r.axis,e.surface.participant,e.context,r.axisId)},()=>{e.documentApi.ooxml.charts.upsertAxisById(t.objectId,r.axis,r.axisId)});return;case"remove-axis":e.runMutation(()=>{e.documentApi.ooxml.charts.removeAxisByIdTracked(t.objectId,r.axisId,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.removeAxisById(t.objectId,r.axisId)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function jd(e,t){switch(t.action){case"replace-math-model":e.runMutation(()=>{e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.replaceModelById(t.objectId,t.model)});return;case"set-math-plain-text":e.runMutation(()=>{e.documentApi.ooxml.math.setPlainTextByIdTracked(t.objectId,t.text,e.surface.participant,e.context,t.displayMode)},()=>{e.documentApi.ooxml.math.setPlainTextById(t.objectId,t.text,t.displayMode)});return;case"apply-math-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-display-mode":e.runMutation(()=>{e.documentApi.ooxml.math.setDisplayModeByIdTracked(t.objectId,r.displayMode,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.setDisplayModeById(t.objectId,r.displayMode)});return;case"set-plain-text":e.runMutation(()=>{e.documentApi.ooxml.math.setPlainTextByIdTracked(t.objectId,r.text,e.surface.participant,e.context,r.displayMode)},()=>{e.documentApi.ooxml.math.setPlainTextById(t.objectId,r.text,r.displayMode)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function Vd(e,t){switch(t.action){case"replace-shape-model":e.runMutation(()=>{e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.replaceModelById(t.objectId,t.model)});return;case"apply-shape-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-metadata":e.runMutation(()=>{e.documentApi.ooxml.shapes.setMetadataByIdTracked(t.objectId,r,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setMetadataById(t.objectId,r)});return;case"set-watermark":e.runMutation(()=>{e.documentApi.ooxml.shapes.setWatermarkByIdTracked(t.objectId,r.isWatermark,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setWatermarkById(t.objectId,r.isWatermark)});return;case"set-text-body":e.runMutation(()=>{e.documentApi.ooxml.shapes.setTextBodyByIdTracked(t.objectId,r.paragraphs,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setTextBodyById(t.objectId,r.paragraphs)});return;case"set-geometry":e.runMutation(()=>{e.documentApi.ooxml.shapes.setGeometryByIdTracked(t.objectId,r.geometry,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setGeometryById(t.objectId,r.geometry)});return;case"set-transform":e.runMutation(()=>{e.documentApi.ooxml.shapes.setTransformByIdTracked(t.objectId,r.transform,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setTransformById(t.objectId,r.transform)});return;case"set-fill":e.runMutation(()=>{e.documentApi.ooxml.shapes.setFillByIdTracked(t.objectId,r.fill,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setFillById(t.objectId,r.fill)});return;case"set-stroke":e.runMutation(()=>{e.documentApi.ooxml.shapes.setStrokeByIdTracked(t.objectId,r.stroke,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setStrokeById(t.objectId,r.stroke)});return;case"set-effects":e.runMutation(()=>{e.documentApi.ooxml.shapes.setEffectsByIdTracked(t.objectId,r.effects,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setEffectsById(t.objectId,r.effects)});return;case"set-anchor":e.runMutation(()=>{e.documentApi.ooxml.shapes.setAnchorByIdTracked(t.objectId,r.anchor,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setAnchorById(t.objectId,r.anchor)});return;case"set-children":e.runMutation(()=>{e.documentApi.ooxml.shapes.setChildrenByIdTracked(t.objectId,r.children,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setChildrenById(t.objectId,r.children)});return;case"set-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.setChildByIdTracked(t.objectId,r.target,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setChildById(t.objectId,r.target,r.child)});return;case"append-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.appendChildByIdTracked(t.objectId,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.appendChildById(t.objectId,r.child)});return;case"append-child-to-parent":e.runMutation(()=>{e.documentApi.ooxml.shapes.appendChildToParentByIdTracked(t.objectId,r.parentTarget,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.appendChildToParentById(t.objectId,r.parentTarget,r.child)});return;case"move-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.moveChildByIdTracked(t.objectId,r.target,e.surface.participant,e.context,{parentId:r.parentTarget,beforeId:r.beforeTarget})},()=>{e.documentApi.ooxml.shapes.moveChildById(t.objectId,r.target,{parentId:r.parentTarget,beforeId:r.beforeTarget})});return;case"remove-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.removeChildByIdTracked(t.objectId,r.target,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.removeChildById(t.objectId,r.target)});return;case"set-connector":e.runMutation(()=>{e.documentApi.ooxml.shapes.setConnectorByIdTracked(t.objectId,r.connector,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setConnectorById(t.objectId,r.connector)});return;case"set-picture":e.runMutation(()=>{e.documentApi.ooxml.shapes.setPictureByIdTracked(t.objectId,r.picture,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setPictureById(t.objectId,r.picture)});return;case"set-word-art":e.runMutation(()=>{e.documentApi.ooxml.shapes.setWordArtByIdTracked(t.objectId,r.wordArt,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setWordArtById(t.objectId,r.wordArt)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function bh(e,t){let r=yh(e,t),o=e.view?.dom??null;if(!o)return()=>{};let n=i=>{let s=i instanceof CustomEvent?i.detail:null;if(nm(s))switch(i.preventDefault(),i.stopPropagation(),s.family){case"math":if(s.action==="remove-advanced-ooxml"){jd(r,{family:"math",action:s.action,objectId:s.objectId});return}jd(r,s);return;case"chart":if(s.action==="remove-advanced-ooxml"){Od(r,{family:"chart",action:s.action,objectId:s.objectId});return}Od(r,s);return;case"shape":if(s.action==="remove-advanced-ooxml"){Vd(r,{family:"shape",action:s.action,objectId:s.objectId});return}Vd(r,s);return}};return o.addEventListener(Hi,n),()=>{o.removeEventListener(Hi,n)}}import{describeSurfaceSelection as Th}from"@datalking/begonia-engine";import{describeSurfaceSelection as hD}from"@datalking/begonia-engine";function yD(e,t,r){if(!r.target){if(Wt(t,r))return!0;let i=e.preservedRangeSelection;return!!(r.nodeSelectionTarget&&i?.nodeSelectionTarget&&sr(r.nodeSelectionTarget,i.nodeSelectionTarget)&&Wt(t,i))||!!(r.nodeSelectionTarget&&up(e.state.doc,r.nodeSelectionTarget,t))}if(Wt(t,r))return!0;let o=e.preservedRangeSelection;if(!o||!o.target||e.projectionSnapshot.projectedMode!==null||o.projectedMode==null||r.projectedMode!==null)return!1;if(Wt(t,o))return!0;let n=ut({state:e.state,target:o.target,projectionSnapshot:e.projectionSnapshot,sourceMode:o.projectedMode,revisions:e.revisions,expectedText:o.text,expectedSegmentTexts:o.segmentTexts});return!!(n&&Wt(t,n.selection))}function bD(e,t,r,o,n=null){if(t.empty)return null;let i=Dn(n??Ie(e));return!r.target&&!i?null:{from:Math.min(t.from,t.to),to:Math.max(t.from,t.to),...xr(t)==="backward"?{direction:"backward"}:{},target:r.target?Et(r.target):null,text:r.text??null,segmentTexts:r.target?lt(e.doc,r.target):null,projectedMode:o,nodeSelectionTarget:i}}function BD(e,t){return On(e.target,t.target)&&(e.text??null)===t.text}function xD(e,t){return!e.selection.empty&&e.selection.from===t.from&&e.selection.to===t.to&&(e.selectionInfo.text??null)===t.text}function CD(e){if(!e.preserved.nodeSelectionTarget)return null;let t=Zr(e.state,e.preserved.nodeSelectionTarget);return t?{from:Math.min(t.selection.from,t.selection.to),to:Math.max(t.selection.from,t.selection.to),target:null,text:Ee(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode}).text??null,segmentTexts:null,projectedMode:e.projectedMode,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}:null}function xh(e,t){let r=Ee(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode});return $e({selection:hD(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}function Ld(e){if(!e.preserved.target)return null;let t=e.context.projectionSnapshot.projectedMode,r=ut({state:e.context.state,target:e.preserved.target,projectionSnapshot:e.context.projectionSnapshot,sourceMode:e.sourceMode,revisions:e.context.revisions,expectedText:e.preserved.text,expectedSegmentTexts:e.preserved.segmentTexts});if(!r)return null;let o=Il(e.context.state,{...e.preserved,from:r.selection.from,to:r.selection.to,target:r.target});if(!o)return null;if(e.sourceMode!==t){let i=Ml(e.context.state,{...r.selection,...e.preserved.direction?{direction:e.preserved.direction}:{}})??o,s=Ee(i,{includeText:!0},{reviewReplacementMode:e.context.reviewReplacementMode});return{from:r.selection.from,to:r.selection.to,...e.preserved.direction?{direction:e.preserved.direction}:{},target:Et(r.target),text:s.text??e.preserved.text??null,segmentTexts:lt(i.doc,r.target),projectedMode:t,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}}let n=xh(e.context,o);return n.selection.empty||!n.selectionInfo.target?null:{from:Math.min(n.selection.from,n.selection.to),to:Math.max(n.selection.from,n.selection.to),...e.preserved.direction?{direction:e.preserved.direction}:{},target:Et(n.selectionInfo.target),text:n.selectionInfo.text??null,segmentTexts:lt(o.doc,n.selectionInfo.target),projectedMode:t,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}}function Ch(e){let t="previous"in e?e.previous:e.preservedRangeSelection;if(!t)return[];if(t.nodeSelectionTarget){let r=CD({state:e.state,preserved:t,projectedMode:e.projectionSnapshot.projectedMode,reviewReplacementMode:e.reviewReplacementMode});if(r&&t.target==null)return[r];let o=[];return r&&o.push(r),[...o,...Bh(e,t)]}return Bh(e,t)}function Bh(e,t){let r=[],o=e.projectionSnapshot.projectedMode;if(!t.projectedMode&&!o)r.push(t);else if(t.projectedMode&&!o){let n=Ld({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else if(t.projectedMode)if(t.projectedMode===o)r.push(t);else{let n=Ld({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else{let n=Ld({context:e,preserved:t,sourceMode:null});n&&r.push(n)}return r}function Fd(e){let t=bD(e.state,e.selection,e.selectionInfo,e.projectionSnapshot.projectedMode,e.selectionNodeSelectionTarget??null);if(t)return e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&e.selectionInfo.empty&&!e.selection.empty&&t.text==null&&os(t.target,e.previous.target)||e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&On(t.target,e.previous.target)&&t.text===e.previous.text?e.previous:t;let r=Ch(e),o=r.find(i=>Wt(e.selection,i));if(o)return o;let n=e.previous?.projectedMode!==e.projectionSnapshot.projectedMode&&e.selection.empty&&e.selectionInfo.activeChangeIds.length>0&&e.previous?.target?ut({state:e.state,target:e.previous.target,projectionSnapshot:e.projectionSnapshot,sourceMode:e.previous.projectedMode,revisions:e.revisions,expectedText:e.previous.text,expectedSegmentTexts:e.previous.segmentTexts}):null;return n&&n.selection.from===n.selection.to&&e.selection.from===n.selection.from&&e.selection.to===n.selection.to||e.surfaceSelectionReliable===!1&&e.selection.empty&&e.previous?.projectedMode!=null&&r.length>0||e.previous&&Wt(e.selection,e.previous)?e.previous:null}function Ph(e,t){let r=e.surfaceSelectionReliable===!1&&t.empty,o=t.empty&&e.preservedRangeSelection?.target!=null&&e.preservedRangeSelection.projectedMode!==e.projectionSnapshot.projectedMode;for(let n of Ch(e)){if(!r&&!yD(e,t,n))continue;let i=Il(e.state,n);if(!i)continue;let s=xh(e,i);if(n.target==null&&sr(Ie(i),n.nodeSelectionTarget)||BD(s.selectionInfo,n)||n.target!=null&&n.projectedMode===e.projectionSnapshot.projectedMode&&xD(s,n)&&(r||e.projectionSnapshot.projectedMode==null)||o&&n.target)return i}if(t.empty){let n=jp(e.state);if(n)return n}return e.state}function Rh(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Rh(t);return e}function zd(e,t,r,o,n,i=null,s=null,a=null){let l=e.target??null;if(!t&&!l&&!r)return null;let{target:c,...d}=e,u={...d,selection:o,selectionTarget:l,segmentTexts:l&&a?lt(a,l):null,nodeSelectionTarget:r??null,selectionKind:n,projectedMode:i,storyOriginPath:s,documentIdentity:Ap(a),documentHash:Oo(a),target:t??null};return Rh(structuredClone(u))}import{readSyntheticSideStoryDocOriginPath as PD}from"@datalking/begonia-doc-service/v1";function kh(e,t,r){let o=Ee(t,r,{reviewReplacementMode:e.reviewReplacementMode}),n=Th(t),i=$e({selection:{...n,editable:n.editable&&e.surfaceEditable},selectionInfo:o,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions}),s=t!==e.state?le([...n.trackedChangeIds,...i.selection.trackedChangeIds],e.revisions):i.selection.trackedChangeIds,a=s.length===i.selection.trackedChangeIds.length&&s.every((m,p)=>m===i.selection.trackedChangeIds[p])?i.selection:{...i.selection,trackedChangeIds:[...s]},l=t!==e.state&&e.preservedRangeSelection?.target?ut({state:t,target:e.preservedRangeSelection.target,projectionSnapshot:e.projectionSnapshot,sourceMode:e.preservedRangeSelection.projectedMode,revisions:e.revisions,expectedText:e.preservedRangeSelection.text,expectedSegmentTexts:e.preservedRangeSelection.segmentTexts}):null,c=l&&l.selection.from===a.from&&l.selection.to===a.to?{...i.selectionInfo,target:l.target}:i.selectionInfo,d=c.target??Ht(t),u=zd(c,d,Ie(t),a,K(t.selection)?"node":"text",e.projectionSnapshot.projectedMode,PD(t.doc),t.doc);return u||null}function RD(e,t){let r=e.preservedRangeSelection;if(!r||!t.empty||e.projectionSnapshot.projectedMode!==null||r.projectedMode==null||!r.target||!Wt(t,r))return null;let o=ut({state:e.state,target:r.target,projectionSnapshot:e.projectionSnapshot,sourceMode:r.projectedMode,revisions:e.revisions,expectedText:r.text,expectedSegmentTexts:r.segmentTexts});if(!o)return null;let n=gt(o.selection,r.direction),i=Z(e.state,n.anchor,n.head);if(!i)return null;try{return e.state.apply(e.state.tr.setSelection(i))}catch{return null}}function Pi(e){let t=Th(e.state),r=Ph(e,t);return r===e.state?RD(e,t)??r:r}function Eh(e){return kh(e,e.state,e.selectionInput??{})}function So(e){return kh(e,Pi(e),e.selectionInput??{})}import{isDocumentNodePathIndex as TD}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as kD}from"@datalking/begonia-engine";function Ih(e){return e==="ooxml_math"||e==="ooxml_chart"||e==="ooxml_shape"||e==="inline_ooxml_drawing"}function Ah(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.$from.index(o));return r}function ED(e){if(!K(e)||!Ih(e.node.type.name))return null;let t=Ah(e,e.$from.depth);return t.push(e.$from.index(e.$from.depth)),t}function MD(e,t){let r=e;for(let o of t){if(!TD(o)||o>=r.childCount)return null;r=r.child(o)}return r}function Mh(e,t){let r=MD(e.doc,t);return!!(r&&Ih(r.type.name)&&r.marks.some(o=>o.type.name===kD))}function Hd(e){let{selection:t}=e.state;for(let r=t.$from.depth;r>0;r-=1)if(t.$from.node(r).isTextblock)return Ah(t,r);return null}function Rn(e,t){let r=t.blocks.topLevel(),o=e.state.selection.from,n=r.find(i=>o>=i.from&&o<=i.from+i.nodeSize);return n?n.index+1:r.length}function G(){return{source:"browser-ooxml"}}function Ba(e,t){let r=ED(e.selection);if(!r)return null;let o=t.ooxml.get(r);if(!o)return null;let n=Mh(e,o.path),i=t.ooxml.getById(o.objectId);if(!i)return n?null:o;let s=Mh(e,i.path);return n?s?null:i:s?o:i}function Ri(e,t){if(t)return Ba(e.state,t);let r=e,o=Ue(r);return o?Ba(o.state,r.documentApi):null}function Y(e,t,r){let o=Ri(e,t);return o?.family===r?o:null}function J(e){return{changed:!1,reason:`No advanced OOXML ${e} node is selected.`}}function qd(e,t,r){let o=Ri(e,t);return o?e.trackingEnabled?t.ooxml.updateTracked(o.path,r,e.participant,G()):t.ooxml.update(o.path,r):{changed:!1,reason:"No advanced OOXML node is selected."}}function Wd(e,t){let r=Ri(e,t);return r?e.trackingEnabled?t.ooxml.removeTracked(r.path,e.participant,G()):t.ooxml.remove(r.path):{changed:!1,reason:"No advanced OOXML node is selected."}}function Kd(e){return[...new Set((e??[]).map(t=>ct(t)).filter(t=>t.length>0))]}function ID(e,t){let r=Kd(e),o=Kd(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function AD(e){let t=Math.min(e.from,e.to),r=Math.max(e.from,e.to);return{start:t,selectionEnd:t===r?r+1:r}}function ND(e,t){if(!e||!t)return!1;let r=AD(e),o=Math.min(t.from,t.to),n=Math.max(t.from,t.to);return o===n?o<r.selectionEnd&&o>=r.start:o<r.selectionEnd&&n>r.start}function Ti(e){let t=Ze(e.comments),r=At(e.activeCommentIds,t);if(r.length>0||!e.selection||!e.projectedDocument)return r;let o=Kd((e.comments??[]).map(n=>{let i=e.readTarget(n.id),s=Ge(e.projectedDocument,i);return ND(e.selection,s)?n.id:null}).filter(n=>typeof n=="string"));return o.length===1?o:r}function ki(e,t){return ID(e.activeCommentIds,t)?e:{...e,activeCommentIds:[...t]}}function Nh(e){return{left:e.left,top:e.top}}function DD(e){return e.type==="external"?{...e}:{...e}}function xa(e){return e?{...e,position:Nh(e.position),resolution:DD(e.resolution)}:null}function OD(e){return{...e}}function jD(e){return{...e,items:e.items.map(OD)}}function VD(e){return{...e,trackedChangeIds:[...e.trackedChangeIds],pointReviewTrackedChangeIds:[...e.pointReviewTrackedChangeIds],pointReviewCommentIds:[...e.pointReviewCommentIds],activeCommentIds:[...e.activeCommentIds],activeMarks:[...e.activeMarks],position:Nh(e.position)}}function Ca(e){return e?{context:VD(e.context),sections:e.sections.map(jD)}:null}import{listCapabilities as GD}from"@datalking/begonia-document-api/core";import{listCapabilities as LD}from"@datalking/begonia-document-api/core";var Dh=Object.freeze([...LD()].filter(e=>e.mode==="write"&&e.memberPath).map(e=>e.memberPath)),FD=new Set(Dh),zD=Object.freeze(["controls.create","controls.text.setValueTracked","fields.refreshGroup","layout.replaceFooterTextTracked","layout.replaceFooters","layout.replaceHeaderTextTracked","layout.replaceHeaders","mergeFields.sources.remove","mergeFields.sources.set","mergeFields.update","mergeFields.updateAll","formulas.update","formulas.updateAll","sequences.update","sequences.updateAll","notes.remove","notes.replaceTextTracked","notes.upsert","styles.replaceAll"]),HD=new Set(["byFamily","get","getById","list"]),qD=new Set(["createNode","get","getById","getModel","getModelById","list"]),WD=new Set(["createModelFromText","createNode","get","getById","getModel","getModelById","list"]);function KD(e){return e[e.length-1]??null}function _D(e){return e!=null&&(e==="createNode"||e.startsWith("find")||e.startsWith("get")||e.startsWith("list")||e.startsWith("read"))}function UD(e){let t=e.split(".");if(t[0]!=="ooxml")return!1;let r=t[1]??null;if(r==null)return!1;if(t.length===2)return!HD.has(r);let o=t[2]??null,n=KD(t);return o==="commands"?!1:r==="chart"?n!=null&&!qD.has(n):r==="math"?n!=null&&!WD.has(n):r==="shape"?!_D(n):!1}function Oh(e,t="",r=new WeakSet,o=[]){if(e==null||typeof e!="object"&&typeof e!="function")return o;let n=e;if(r.has(n))return o;r.add(n);for(let i of Object.keys(e)){let s=e[i],a=t?`${t}.${i}`:i;typeof s=="function"&&o.push(a),s!=null&&(typeof s=="object"||typeof s=="function")&&Oh(s,a,r,o)}return o}function ZD(e){let t=new Set;for(let r of e){let o=r.split("."),n="";for(let i=0;i<o.length-1;i+=1)n=n?`${n}.${o[i]}`:o[i],t.add(n)}return t}function jh(e){return zD.includes(e)||UD(e)}function Vh(e){return FD.has(e)||jh(e)}function Lh(e){let t=new Set(Dh);for(let r of Oh(e))jh(r)&&t.add(r);return{deniedMemberPaths:t,descendantMemberPaths:ZD(t)}}var Hh=new Map([...GD()].filter(e=>e.memberPath).map(e=>[e.memberPath,e.mode])),XD=(()=>{let e=new Set;for(let t of Hh.keys()){let r=t.split("."),o="";for(let n=0;n<r.length-1;n+=1)o=o?`${o}.${r[n]}`:r[n],e.add(o)}return e})();function Fh(e,t){if(!t)return{owner:null,value:e};let r=t.split("."),o=null,n=e;for(let i of r)o=n,n=n?.[i];return{owner:o,value:n}}function $D(e){return XD.has(e)}function zh(e){return Vh(e)?"write":Hh.get(e)??null}function YD(e){return e==="final"||e==="original"||e==="tracked"?e:null}function JD(e){return!e||typeof e!="object"?null:YD(e.revisionProjection)}function QD(e){for(let t of e){let r=JD(t);if(r)return r}return null}function Pa(e){return{presentationReadApi:e.presentationReadRuntime.documentApi,canonicalReviewApi:e.canonicalReviewRuntime.documentApi,writableRuntimeApi:e.writableRuntime.documentApi}}function qh(e){let t=new Map,r=(i,s=[])=>{if(zh(i)==="write")return e.readWritableApi();let a=QD(s);return a?e.readProjectedApiForMode(a)??e.readPresentationApi():e.readPresentationApi()},o=(i,s=[])=>{let a=Fh(r(i,s),i);return a.value!==void 0||zh(i)==="write"?a:Fh(e.readWritableApi(),i)},n=i=>{if(t.has(i))return t.get(i);let s=o(i),{value:a}=s;if(a==null||typeof a!="object"&&typeof a!="function")return a;let l=$D(i);if(typeof a=="function"&&!l){let d=(...u)=>{let m=o(i,u);return Reflect.apply(m.value,m.owner,u)};return t.set(i,d),d}let c=new Proxy(a,{get(d,u){if(typeof u!="string"){let p=o(i);return Reflect.get(p.value,u,p.owner)}let m=i?`${i}.${u}`:u;return n(m)},apply(d,u,m){let p=o(i,m);return Reflect.apply(p.value,p.owner,m)}});return t.set(i,c),c};return n}function Ei(e){return e.kind!=="revision"&&e.kind!=="revision-decision"}function Wh(e){let t=e?.trim()??"";if(!t)return 0;let r=Date.parse(t);return Number.isFinite(r)?r:0}function eO(e,t,r){let o=Wh(e.sortAt),n=Wh(t.sortAt);return o!==n?r==="asc"?o-n:n-o:e.id.localeCompare(t.id)}function _d(e,t,r="desc"){let o=new Map(t.filter(Ei).map(s=>[s.id,s])),n=e.map(s=>Ei(s)?o.get(s.id)??s:s),i=new Set(n.map(s=>s.id));for(let s of t)!Ei(s)||i.has(s.id)||(n.push(s),i.add(s.id));return n.sort((s,a)=>eO(s,a,r))}function tO(e,t){if(e.projectedMode==null)return null;let r={actor:t.actor,enforceVisibilityPolicy:t.enforceVisibilityPolicy},o=e.presentationReadRuntime.documentApi.comments,n=new Map;return(i,s)=>{let a=`${i}\0${s}`;return n.has(a)||n.set(a,o.entryTarget(i,s,r)??o.target(i,r)??o.targetSnapshot(i,r)??null),n.get(a)??null}}function Kh(e,t,r){let o=tO(t,r);return o?e.map(n=>{if(!Ei(n))return n;let i=o(n.commentId,n.entryId);return i?{...n,target:i}:n}):e}function rO(e){let t=e.reviewOptions??{},{presentationReadRuntime:r,canonicalReviewRuntime:o}=e.projectionSnapshot,n=r.documentApi,i=o.documentApi,s=i.review.timeline(t);return n===i?s:_d(s,n.review.timeline(t),t.sort??"desc")}function oO(e){let t=e.reviewOptions??{},{presentationReadRuntime:r,canonicalReviewRuntime:o}=e.projectionSnapshot,n=r.documentApi,i=o.documentApi,s=i.review.timelineByObject(e.objectId,t);return n===i?s:_d(s,n.review.timelineByObject(e.objectId,t),t.sort??"desc")}function Ra(e){let t=e.reviewOptions??{};return Kh(rO(e),e.projectionSnapshot,t)}function _h(e){let t=e.reviewOptions??{};return Kh(oO(e),e.projectionSnapshot,t)}function Oe(e){return{allowed:!1,reason:e,matchedPermissionIds:[],authorOwned:!1}}function Mi(e,t){return{...e,toggleInternal:Oe("Comments are read-only in the current document mode."),reply:Oe("Comments are read-only in the current document mode."),resolve:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:Oe("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({...r,edit:Oe("Comments are read-only in the current document mode."),remove:Oe("Comments are read-only in the current document mode.")}))}}function Ii(e){let t=Oe("Tracked changes are read-only in the current document mode.");return{...e,accept:t,reject:t}}function Uh(e){return e&&{...e,edit:Oe("Comments are read-only in the current document mode."),remove:Oe("Comments are read-only in the current document mode.")}}function Ud(e,t){return{threadId:e.id,view:{allowed:!0,reason:null,matchedPermissionIds:[],authorOwned:!1},reply:Oe("Comments are read-only in the current document mode."),resolve:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:Oe("Comments are read-only in the current document mode."),toggleInternal:Oe("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({entryId:r.id,edit:Oe("Comments are read-only in the current document mode."),remove:Oe("Comments are read-only in the current document mode.")}))}}function Zd(e){return{revisionId:e,accept:Oe("Tracked changes are read-only in the current document mode."),reject:Oe("Tracked changes are read-only in the current document mode.")}}function Zh(e,t,r){return e.filter(o=>o.kind==="revision"||o.kind==="revision-decision"?!0:r.enabled&&r.visible)}function Ai(e,t,r){return e.map(o=>o.kind==="revision"?t?o:{...o,permissions:o.permissions?Ii(o.permissions):Zd(o.revisionId)}:o.kind==="revision-decision"?o:r.readOnly?{...o,threadPermissions:o.threadPermissions?Mi(o.threadPermissions,r):Ud(o.comment,r)}:o)}function Gh(e){return{source:e.documentSource,replace(t,r){e.replaceDocument(t,r)}}}function aO(e){let t=Gh(e);return{readDocument(){return e.document},replaceDocument(r,o){t.replace(bt(e.document,r),o)},documentSource:t.source}}function lO(e,t,r,o){return Object.fromEntries(t.map(n=>{let i=r?e.comments.permissions(n.id,r):o.readOnly?Ud(n,o):null;return[n.id,i&&o.readOnly?Mi(i,o):i]}))}function cO(e,t,r,o){let n=r?e.review.permissions(r):o?[]:t.map(i=>Zd(i.id));return Object.fromEntries(n.map(i=>[i.revisionId,o?i:Ii(i)]))}function dO(e,t){return e.length===0?null:e.some(r=>r.hitId===t)?t:e[0]?.hitId??null}function Ta(e,t,r={}){let o=aO(e),n=nO(o,{templates:r.templates??void 0,review:{replacementMode:r.replacementMode??"paired"},selection:yl(e,{reviewReplacementMode:r.replacementMode??"paired"})}),i=n.api,s=e.subscribe(()=>t()),a=bh(e,i),l=!1,c=()=>{l||(l=!0,a(),s(),n.dispose())};return{surface:e,documentRuntimeKernel:n,documentService:n.service,documentApi:i,replacementMode:r.replacementMode??"paired",templatesAdapter:r.templates??null,unsubscribeSurface:s,uninstallAdvancedOoxmlNodeViewBridge:a,release:c}}function uO(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function Xh(e){let{runtime:t,projectionSnapshot:r,preservedRangeSelection:o,actor:n,linkPopover:i,contextMenu:s,search:a,collaboration:l,documentMode:c,zoomPercent:d,zoom:u,viewportSession:m,display:p,activeCommentId:f,activeCommentIds:g,activeRevisionId:v,activeRevisionIds:E}=e,{surface:R,documentApi:S}=t,P=it(R),{presentationReadApi:h,canonicalReviewApi:b}=Pa(r),x=p.comments.enabled?h.comments.list({includeResolved:p.comments.showResolved,actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,visibility:p.comments.visibility,sort:"desc"}):[],A=p.comments.visible?x:[],O=b.review.list(),j={actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,includeResolvedComments:p.comments.showResolved,commentVisibility:p.comments.visibility},_=Ai(Zh(Ra({projectionSnapshot:r,reviewOptions:j}),p.trackChanges,p.comments),P,p.comments),V=a.query?h.search.query(a.query,a.options):[],de=h.proofing.list(),k=uO(R),I=R.describeSelection(),F=Dr(R,{includeText:!0},t.replacementMode),y=$e({selection:I,selectionInfo:F,projectedDocument:We(R),canonicalDocument:r.canonicalDocument,projectedMode:r.projectedMode,revisions:O}),B=So({state:R.state,surfaceEditable:P,surfaceSelectionReliable:k,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:O,projectionSnapshot:r,preservedRangeSelection:o}),M=Pi({state:R.state,surfaceEditable:P,surfaceSelectionReliable:k,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:O,projectionSnapshot:r,preservedRangeSelection:o}),N=yt({liveSelection:y.selection,liveSelectionInfo:y.selectionInfo,revisions:O,effectiveSelection:B}),L=!k&&B?B.selection:y.selection,ae=ar(L.trackedChangeIds,N)?L:{...L,trackedChangeIds:[...N]},je=!k&&B?Rr(B,N):null,me=je??y.selectionInfo,Ke=Ti({activeCommentIds:me.activeCommentIds,selection:k?I:ae,projectedDocument:We(R),comments:x,readTarget:h.comments.target}),Tt=ki(me,Ke),Je=ko(R.state,Tt,K(R.state.selection)?"node":"text"),Ce=je??(y.selection.empty&&ar(Je.activeChangeIds,N)?Je:y.selection.empty?{...Je,activeChangeIds:[...N]}:Je),mt=fw({revisions:O,selectionInfo:Ce,explicitActiveRevisionId:v,explicitActiveRevisionIds:E}),hr=sn({comments:A,selectionInfo:Ce,explicitActiveCommentId:f,explicitActiveCommentIds:g}),jt=sO(ae,t.documentRuntimeKernel.readSnapshot().revision,R.documentStory),Vt={toolbar:Ds({selection:jt,editable:P,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:R.canUndo(),canRedo:R.canRedo()}),comments:A,commentPermissions:lO(h,A,n,p.comments),activeCommentId:hr.activeCommentId,activeCommentIds:hr.activeCommentIds,revisions:O,activeRevisionId:mt.activeRevisionId,activeRevisionIds:mt.activeRevisionIds,reviewPermissions:cO(b,O,n,P),reviewTimeline:_,reviewTimelineSummary:iO(_),search:{query:a.query,hits:V,activeHitId:dO(V,a.activeHitId)},proofing:{diagnostics:de},advancedOoxml:{selected:Ba(M,S)},selectionInfo:Ce,selection:jt,editable:P,documentMode:c,flowMode:m.flowMode,layoutMode:m.layoutMode,preferredPaginatedLayoutMode:m.preferredPaginatedLayoutMode,zoomPercent:d,zoom:u,viewport:m.viewport,viewportRequestKey:m.viewportRequestKey,previewNavigationRequest:m.previewNavigationRequest,trackChanges:p.trackChanges,commentsDisplay:p.comments,collaboration:l,linkPopover:xa(i),contextMenu:Ca(s),selectionNodeSelectionTarget:k?null:B?.nodeSelectionTarget??null},Lt=Zn({getState:()=>Vt,readEffectiveSelection:()=>B,surface:R}),yr=Ds({selection:jt,editable:P,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:Lt.commands.undo?.disabled===!1,canRedo:Lt.commands.redo?.disabled===!1,commandStates:Lt.commands});return{...Vt,toolbar:yr}}function mO(e){return e.view.dom.parentElement??null}function pO(e){return e.view.dom.ownerDocument?.createElement?.("div")}function $h(e){e.view.updateRoot?.call(e.view)}function Yh(e,t){if(t){if(typeof t.replaceChildren=="function"){t.replaceChildren(e.view.dom),$h(e);return}typeof t.appendChild=="function"&&(t.appendChild(e.view.dom),$h(e))}}function Jh(e){return!!e}function Qh(e){let{canonicalDocument:t,emit:r,projectionMode:o,readPreservedRangeSelection:n,replacementMode:i="paired",sourceRuntime:s,surfaceFactory:a}=e,l=s.surface,c=mO(l),d=bt(t,Me(t,l,o)),u=a({currentSurface:l,collaborative:void 0,documentStory:l.documentStory,editable:!1,element:pO(l),initialContent:d,schema:l.schema,participant:l.participant,trackingEnabled:!1}),m=Ta(u,r,{replacementMode:i});return Yh(u,c),{runtime:m,restore(){Yh(l,c)},sync(p,f){let g=Me(p,l,f);return Ar(m.surface.document,g)?!1:(Cn({surface:m.surface,nextDocument:g,documentApi:m.documentApi,canonicalReviewApi:s.documentApi,canonicalDocument:p,nextProjectionMode:f,preservedRangeSelection:n?.()??null}),!0)}}}function Gd(e,t,r,o={}){let n=Hd(e);return n?t.ooxml.math.appendInline(n,r,o):{changed:!1,reason:"Advanced OOXML math insertion requires an active text block selection."}}function Xd(e,t,r,o={},n={}){let i=Hd(e);return i?t.ooxml.math.appendInlineTracked(i,r,e.participant,o,n):{changed:!1,reason:"Tracked math insertion requires an active text block selection."}}function $d(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.math.replaceModelById(o.objectId,r):J("math")}function Yd(e,t,r,o){let n=Y(e,t,"math");return n?e.trackingEnabled?t.ooxml.math.setPlainTextByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.math.setPlainTextById(n.objectId,r,o):J("math")}function Jd(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.setDisplayModeByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.math.setDisplayModeById(o.objectId,r):J("math")}function Qd(e,t,r,o={}){return t.ooxml.charts.insertBlock(Rn(e,t),r,o)}function eu(e,t,r,o={},n={}){return t.ooxml.charts.insertBlockTracked(Rn(e,t),r,e.participant,o,n)}function tu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.replaceModelById(o.objectId,r):J("chart")}function ru(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setMetadataByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setMetadataById(o.objectId,r):J("chart")}function ou(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTitleByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setTitleById(o.objectId,r):J("chart")}function nu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTextBodyByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setTextBodyById(o.objectId,r):J("chart")}function iu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.appendSeriesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.appendSeriesById(o.objectId,r):J("chart")}function su(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setSeriesListByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setSeriesListById(o.objectId,r):J("chart")}function au(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.setSeriesByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.charts.setSeriesById(n.objectId,r,o):J("chart")}function lu(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertSeriesByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.charts.upsertSeriesById(n.objectId,r,o):J("chart")}function cu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeSeriesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.removeSeriesById(o.objectId,r):J("chart")}function du(e,t,r){return ka(e,t,r)}function uu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setAxesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setAxesById(o.objectId,r):J("chart")}function ka(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertAxisByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.charts.upsertAxisById(n.objectId,r,o):J("chart")}function mu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeAxisByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.removeAxisById(o.objectId,r):J("chart")}function pu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setLegendByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setLegendById(o.objectId,r):J("chart")}function fu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setPlotAreaByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setPlotAreaById(o.objectId,r):J("chart")}function wu(e,t,r,o={}){return t.ooxml.shapes.insertBlock(Rn(e,t),r,o)}function gu(e,t,r,o={},n={}){return t.ooxml.shapes.insertBlockTracked(Rn(e,t),r,e.participant,o,n)}function Su(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.replaceModelById(o.objectId,r):J("shape")}function vu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setMetadataByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setMetadataById(o.objectId,r):J("shape")}function hu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWatermarkByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setWatermarkById(o.objectId,r):J("shape")}function yu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTextBodyByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setTextBodyById(o.objectId,r):J("shape")}function bu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setGeometryByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setGeometryById(o.objectId,r):J("shape")}function Bu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTransformByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setTransformById(o.objectId,r):J("shape")}function xu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setFillByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setFillById(o.objectId,r):J("shape")}function Cu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setStrokeByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setStrokeById(o.objectId,r):J("shape")}function Pu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setAnchorByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setAnchorById(o.objectId,r):J("shape")}function Ru(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setConnectorByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setConnectorById(o.objectId,r):J("shape")}function Tu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setPictureByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setPictureById(o.objectId,r):J("shape")}function ku(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWordArtByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setWordArtById(o.objectId,r):J("shape")}function Eu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setChildrenByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setChildrenById(o.objectId,r):J("shape")}function Mu(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.setChildByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.shapes.setChildById(n.objectId,r,o):J("shape")}function Iu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.appendChildByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.appendChildById(o.objectId,r):J("shape")}function Au(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.appendChildToParentByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.shapes.appendChildToParentById(n.objectId,r,o):J("shape")}function Nu(e,t,r,o={}){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.moveChildByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.shapes.moveChildById(n.objectId,r,o):J("shape")}function Du(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.removeChildByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.removeChildById(o.objectId,r):J("shape")}import{isDocumentNodePathIndex as fO}from"@datalking/begonia-document-model";import{NodeSelection as wO}from"prosemirror-state";function Ou(e,t){return K(e.selection)&&e.selection.node.type.name===`ooxml_${t.family}`&&e.selection.node.attrs.objectId===t.objectId}function gO(e,t){let r=e,o=-1;for(let n of t){if(!fO(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function SO(e,t){let r=gO(e,t.path),o=r==null?null:e.nodeAt(r);if(r!=null&&o?.type.name===`ooxml_${t.family}`&&o.attrs.objectId===t.objectId)return r;let n=null;return e.descendants((i,s)=>n==null&&i.type.name===`ooxml_${t.family}`&&i.attrs.objectId===t.objectId?(n=s,!1):!0),n}function ey(e,t){if(!t||Ou(e,t))return e;let r=SO(e.doc,t);if(r==null)return null;let o=at(e,wO.create(e.doc,r));if(!o)return null;if(qt(e.selection,o))return e;try{return e.apply(e.tr.setSelection(o))}catch{return null}}function vO(e,t){return new Proxy(e,{get(r,o,n){return o==="state"?t:Reflect.get(r,o,n)}})}function hO(e,t){if(!t||Ou(e.surface.state,t))return e;let r=e.surface.view?.state,o=r?ey(r,t):null;if(r&&o&&(o!==r&&e.surface.view.dispatch(r.tr.setSelection(o.selection)),Ou(e.surface.state,t)))return e;let n=ey(e.surface.state,t);return!n||n===e.surface.state?e:{...e,surface:vO(e.surface,n)}}function yO(e){return!!(e&&typeof e=="object"&&"changed"in e&&e.changed===!0)}function ty(e){let t=o=>{let n=e.getRuntime(),i=Jt(n.surface);return i?W(i):e.runAndEmit(()=>o(n))},r=o=>t(n=>o(hO(n,e.readState().advancedOoxml.selected)));return{appendMathToCurrentTextblock(o,n={}){return t(i=>Gd(i.surface,i.documentApi,o,n))},appendMathToCurrentTextblockTracked(o,n={},i={}){return t(s=>Xd(s.surface,s.documentApi,o,n,i))},insertChartAfterCurrentBlock(o,n={}){return t(i=>Qd(i.surface,i.documentApi,o,n))},insertChartAfterCurrentBlockTracked(o,n={},i={}){return t(s=>eu(s.surface,s.documentApi,o,n,i))},insertShapeAfterCurrentBlock(o,n={}){return t(i=>wu(i.surface,i.documentApi,o,n))},insertShapeAfterCurrentBlockTracked(o,n={},i={}){return t(s=>gu(s.surface,s.documentApi,o,n,i))},updateSelectedAdvancedOoxml(o){return r(n=>qd(n.surface,n.documentApi,o))},removeSelectedAdvancedOoxml(){return r(o=>{let n=Wd(o.surface,o.documentApi);return yO(n)&&e.clearPreservedRangeSelection(),n})},replaceSelectedMathModel(o){return r(n=>$d(n.surface,n.documentApi,o))},setSelectedMathPlainText(o,n){return r(i=>Yd(i.surface,i.documentApi,o,n))},setSelectedMathDisplayMode(o){return r(n=>Jd(n.surface,n.documentApi,o))},replaceSelectedChartModel(o){return r(n=>tu(n.surface,n.documentApi,o))},setSelectedChartMetadata(o){return r(n=>ru(n.surface,n.documentApi,o))},setSelectedChartTitle(o){return r(n=>ou(n.surface,n.documentApi,o))},setSelectedChartTextBody(o){return r(n=>nu(n.surface,n.documentApi,o))},appendSelectedChartSeries(o){return r(n=>iu(n.surface,n.documentApi,o))},setSelectedChartSeriesList(o){return r(n=>su(n.surface,n.documentApi,o))},setSelectedChartSeries(o,n){return r(i=>au(i.surface,i.documentApi,o,n))},upsertSelectedChartSeries(o,n){return r(i=>lu(i.surface,i.documentApi,o,n))},removeSelectedChartSeries(o){return r(n=>cu(n.surface,n.documentApi,o))},appendSelectedChartAxis(o){return r(n=>du(n.surface,n.documentApi,o))},setSelectedChartAxes(o){return r(n=>uu(n.surface,n.documentApi,o))},upsertSelectedChartAxis(o,n){return r(i=>ka(i.surface,i.documentApi,o,n))},removeSelectedChartAxis(o){return r(n=>mu(n.surface,n.documentApi,o))},setSelectedChartLegend(o){return r(n=>pu(n.surface,n.documentApi,o))},setSelectedChartPlotArea(o){return r(n=>fu(n.surface,n.documentApi,o))},replaceSelectedShapeModel(o){return r(n=>Su(n.surface,n.documentApi,o))},setSelectedShapeMetadata(o){return r(n=>vu(n.surface,n.documentApi,o))},setSelectedShapeWatermark(o){return r(n=>hu(n.surface,n.documentApi,o))},setSelectedShapeTextBody(o){return r(n=>yu(n.surface,n.documentApi,o))},setSelectedShapeGeometry(o){return r(n=>bu(n.surface,n.documentApi,o))},setSelectedShapeTransform(o){return r(n=>Bu(n.surface,n.documentApi,o))},setSelectedShapeFill(o){return r(n=>xu(n.surface,n.documentApi,o))},setSelectedShapeStroke(o){return r(n=>Cu(n.surface,n.documentApi,o))},setSelectedShapeAnchor(o){return r(n=>Pu(n.surface,n.documentApi,o))},setSelectedShapeConnector(o){return r(n=>Ru(n.surface,n.documentApi,o))},setSelectedShapePicture(o){return r(n=>Tu(n.surface,n.documentApi,o))},setSelectedShapeWordArt(o){return r(n=>ku(n.surface,n.documentApi,o))},setSelectedShapeChildren(o){return r(n=>Eu(n.surface,n.documentApi,o))},setSelectedShapeChild(o,n){return r(i=>Mu(i.surface,i.documentApi,o,n))},appendSelectedShapeChild(o){return r(n=>Iu(n.surface,n.documentApi,o))},appendSelectedShapeChildToParent(o,n){return r(i=>Au(i.surface,i.documentApi,o,n))},moveSelectedShapeChild(o,n={}){return r(i=>Nu(i.surface,i.documentApi,o,n))},removeSelectedShapeChild(o){return r(n=>Du(n.surface,n.documentApi,o))}}}function Ea(e){let t=dn({surface:e.surface,clientX:e.clientX,clientY:e.clientY});if(!t)return null;let r=e.captureSelectionFromState(t.state);return r?{state:t.state,capture:r}:null}function ry(e,t){let r=t.readEffectiveSelection();return{selectionCapture:r,resolvedSelectionCapture:r,stale:!1}}function Ni(e,t,r){if(!r)return{selectionCapture:null,resolvedSelectionCapture:null,stale:!1};let o=t.readSelectionCapture(r);return o?{selectionCapture:r,resolvedSelectionCapture:o,stale:!1}:{selectionCapture:r,resolvedSelectionCapture:null,stale:!0}}function bO(e,t){return e.selectionCapture?Ni(e,t,e.selectionCapture):e.pointSelectionCapture?Ni(e,t,e.pointSelectionCapture):ry(e,t)}function BO(e,t){let r=e.actionSelectionCapture??e.selectionCapture??null;if(!r)return e.pointSelectionCapture?{...Ni(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...ry(e,t),restoreSelection:!1};let o=Ni(e,t,r);return e.pointSelectionCapture===r?{...o,restoreSelection:!1}:o.resolvedSelectionCapture&&!o.resolvedSelectionCapture.selection.empty?{...o,restoreSelection:!0}:e.pointSelectionCapture&&e.pointSelectionCapture!==r?{...Ni(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...o,restoreSelection:!0}}function ju(e,t){let r=t??e.controller;if(!r)throw new Error("Browser context-menu selection policy requires a selection controller.");return{effectiveSelection:bO(e,r),actionSelection:BO(e,r)}}function xO(e=""){return typeof window>"u"?null:window.prompt("Enter link URL",e)}function CO(e,t){let r=new Map(e.map(o=>[o.id,{...o,items:[...o.items]}]));for(let o of t){let n=r.get(o.id);if(n){n.items.push(...o.items);continue}r.set(o.id,{...o,items:[...o.items]})}return[...r.values()]}function PO(e,t){let r=Math.min(e.selection.from,e.selection.to),o=Math.max(e.selection.from,e.selection.to);return(t.segments?.length?t.segments:[t]).every(i=>r<=i.from&&o>=i.to)}function oy(e,t,r){let o=new Set(e.trackedChangeIds),n=t.getState().revisions.filter(i=>o.has(i.id));return n.length===0||n.some(i=>i.relatedKinds.length!==1)?!1:n.some(i=>!PO(r,i))}function RO(e,t,r){if(!t||!e.hasSelection)return r;let o=Math.min(t.selection.from,t.selection.to),n=Math.max(t.selection.from,t.selection.to),i=Math.min(e.selectionStart,e.selectionEnd),s=Math.max(e.selectionStart,e.selectionEnd),a=r?Math.min(r.selection.from,r.selection.to):o,l=r?Math.max(r.selection.from,r.selection.to):n;return(i!==a||s!==l)&&i===o&&s===n?{selection:{...t.selection,from:i,to:s,empty:!1,trackedChangeIds:[...e.trackedChangeIds]}}:r}function ny(e,t,r){let{hasSelection:o,trackedChangeIds:n}=e,i=Ue(t);if(n.length===0)return;let s=t.readEffectiveSelection({includeText:!0}),a=e.actionSelectionCapture??e.selectionCapture,l=t.getState().revisions,c=Rl(s,a,l),d=!c&&a?t.readSelectionCapture(a,{includeText:!0}):null,u=RO(e,a,d),m=d?Rl(s,d,l):c;if(n.length===1&&!o){let p=n[0];if(!p)return;if(r==="accept"){t.acceptRevision(p);return}t.rejectRevision(p);return}if(i&&(r==="accept"&&typeof i.acceptSelectionRevisions=="function"||r==="reject"&&typeof i.rejectSelectionRevisions=="function")&&u&&!u.selection.empty&&oy(e,t,u)){rt(i,u,p=>r==="accept"?p.acceptSelectionRevisions?.()??!1:p.rejectSelectionRevisions?.()??!1,{restoreSelection:!1});return}if(!(u&&!u.selection.empty&&oy(e,t,u)&&(r==="accept"?t.documentApi.review.accept([...n],t.actor??void 0):t.documentApi.review.reject([...n],t.actor??void 0)).changed)){if(n.length===1&&!c&&!m){let p=n[0];if(!p)return;if(r==="accept"){t.acceptRevision(p);return}t.rejectRevision(p);return}if(a&&!c&&!m){if(r==="accept"){t.documentApi.review.accept([...n],t.actor??void 0);return}t.documentApi.review.reject([...n],t.actor??void 0);return}if(r==="accept"){t.acceptSelection();return}t.rejectSelection()}}function Rt(e,t){let r=ju(e,t).actionSelection;if(r.stale)return"Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.";let o=Ue(t);return o?ir({editable:e.isEditable},o.state,r.resolvedSelectionCapture):"Live editor surface is unavailable for inline formatting."}function Vu(e){return e.hasAmbiguousPointReviewTarget?"Right-click hit multiple overlapping review targets. Click a specific change or narrow the selection before accepting or rejecting changes.":e.isEditable?null:"Document is read-only in the current document mode."}function iy(e){return Vu(e)==null}function TO(e,t){let r=Ue(t),{effectiveSelection:o,actionSelection:n}=ju(e,t),i=o.stale?!1:o.resolvedSelectionCapture?.selection.formatting.link??e.activeMarks.includes("link"),s=o.stale?"":o.resolvedSelectionCapture?.selection.formatting.linkHref??"",a=[{id:"formatting",items:[{id:"bold",label:"Bold",action:()=>{n.stale||_t(t,"bold",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"italic",label:"Italic",action:()=>{n.stale||_t(t,"italic",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"underline",label:"Underline",action:()=>{n.stale||_t(t,"underline",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"strikethrough",label:"Strikethrough",action:()=>{n.stale||_t(t,"strike",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)}]},{id:"links",items:[{id:"insert-link",label:i?"Edit link":"Insert link",action:()=>{if(n.stale)return;let l=t.captureSelectionHandleFromCapture(n.selectionCapture);if(!l)return;let c=xO(s);try{c&&t.setLinkFromHandle(l,c,null,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"clear-link",label:"Clear link",showWhen:()=>i,enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t),action:()=>{if(n.stale)return;let l=t.captureSelectionHandleFromCapture(n.selectionCapture);if(l)try{t.clearLinkFromHandle(l,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}}}]},{id:"history",items:[{id:"undo",label:"Undo",action:()=>{r?.undo()},enabledWhen:l=>l.isEditable&&(r?.canUndo()??!1)},{id:"redo",label:"Redo",action:()=>{r?.redo()},enabledWhen:l=>l.isEditable&&(r?.canRedo()??!1)}]}];return e.trackedChangeIds.length>0&&a.unshift({id:"track-changes",items:[{id:"accept-change",label:e.trackedChangeIds.length===1?"Accept change":"Accept changes",tone:"success",enabledWhen:iy,disabledReason:Vu,action:()=>ny(e,t,"accept")},{id:"reject-change",label:e.trackedChangeIds.length===1?"Reject change":"Reject changes",tone:"danger",enabledWhen:iy,disabledReason:Vu,action:()=>ny(e,t,"reject")}]}),a}function kO(e,t,r){return r?null:typeof e.disabledReason=="function"?e.disabledReason(t)??"Action unavailable.":e.disabledReason??"Action unavailable."}function Ma(e,t,r){let o=r??yS(e.host)??e.controller??null,n=t?.includeDefaultItems===!1||!o?[]:TO(e,o),i=CO(n,t?.customItems??[]);return(t?.menuProvider?.(e,i)??i).map(a=>{let l=a.items.filter(c=>c.showWhen?.(e)??!0).map(c=>{let d=c.enabledWhen?.(e)??!0;return{...c,enabled:d,disabledReason:kO(c,e,d)}});return{id:a.id,label:a.label,items:l}}).filter(a=>a.items.length>0)}function EO(e){let t=e.pointSelection?.capture.selection.from??null,r=Mt(e.pointSelection?.capture,e.revisions),o=!!(e.effectiveSelectionRange&&typeof t=="number"&&t>=e.effectiveSelectionRange.from&&t<=e.effectiveSelectionRange.to);return!!(e.pointSelection&&(!e.effectiveSelectionRange||!o)&&(r.length>0||e.pointSelection.capture.selectionKind==="node"||e.pointSelection.capture.selection.formatting.link||e.pointSelection.capture.selection.empty))}function Lu(e){let t=e.controller.getState(),r=e.actionSelectionCapture&&!e.actionSelectionCapture.selection.empty?{from:Math.min(e.actionSelectionCapture.selection.from,e.actionSelectionCapture.selection.to),to:Math.max(e.actionSelectionCapture.selection.from,e.actionSelectionCapture.selection.to)}:null,o=EO({pointSelection:e.pointSelection,effectiveSelectionRange:r,revisions:t.revisions}),n=o?e.pointSelection?.capture??null:e.effectiveSelection,i=o?e.pointSelection?.capture??null:e.actionSelectionCapture,s=i?.selection??n?.selection??null,a=o?Mt(e.pointSelection?.capture,t.revisions):yt({liveSelection:Ms(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:t.revisions,effectiveSelection:i??e.effectiveSelection});return ra(e.controller,e.documentMode,{revisions:t.revisions,reviewActionsEnabled:e.reviewActionsEnabled,selection:n?{from:s?.from??n.selection.from,to:s?.to??n.selection.to,empty:s?.empty??n.selection.empty,trackedChangeIds:a,trackedChangeIdsExplicit:!0}:null,selectionCapture:n,actionSelectionCapture:i,pointSelectionCapture:o?e.pointSelection?.capture??null:null,pointSelectionState:o?e.pointSelection?.state??void 0:void 0,selectionTrackedChangeIds:t.selection.trackedChangeIds,clientX:e.clientX,clientY:e.clientY,selectionState:o?e.pointSelection?.state??void 0:void 0})}function MO(e,t){let r=ve(e).view;if(!r?.state||typeof r.posAtCoords!="function")return null;let o=t.includeText??!0,n=e.readPointSelection({clientX:t.clientX,clientY:t.clientY,includeText:o}),i=e.readEffectiveSelection({includeText:o}),s=e.readEffectiveSelection()??i;if(!n&&!i)return null;let a=e.getState();return Lu({controller:e,documentMode:a.documentMode,reviewActionsEnabled:a.trackChanges.enabled,effectiveSelection:i,actionSelectionCapture:s,pointSelection:n?{capture:n}:null,clientX:t.clientX,clientY:t.clientY})}function IO(e){let{from:t,to:r}=e.selection;if(t>=r)return e;let o=Math.min(r-1,t+Math.max(1,Math.floor((r-t)/2))),n=Z(e,o,o);if(!n)return e;try{return e.apply(e.tr.setSelection(n))}catch{return e}}function sy(e){let{captureSelectionFromState:t,closeContextMenu:r,closeLinkPopover:o,emit:n,getController:i,getDocumentMode:s,getResolvedModules:a,getRuntime:l,setLinkPopover:c}=e;return d=>{let u=a();if(u.links?.enabled===!1)return;let m=d.target?.closest("a[href]");if(!(m instanceof HTMLAnchorElement)){o();return}let p=l(),f=s();d.preventDefault(),d.stopPropagation(),ta(p.surface,m);let g=()=>o(),v=u.links?.popoverResolver?.({host:uo(i()),href:m.getAttribute("href")??"",title:m.getAttribute("title"),target:m.getAttribute("target"),rel:m.getAttribute("rel"),tooltip:m.getAttribute("title"),element:m,clientX:d.clientX,clientY:d.clientY,isAnchorLink:(m.getAttribute("href")??"").startsWith("#"),documentMode:f,position:{left:d.clientX+8,top:d.clientY+12},closePopover:g})??{type:"default"};if(v.type==="none"){o();return}c(jS(uo(i()),p.surface,f,m,d.clientX,d.clientY,v),t(IO(p.surface.state))),r(),n()}}function ay(e){let{closeContextMenu:t,closeLinkPopover:r,emit:o,getController:n,getDocumentMode:i,getResolvedModules:s,readTrackChangesDisplayState:a,captureEffectiveSelectionFromState:l,setContextMenu:c}=e;return d=>{let u=s();if(u.contextMenu?.enabled===!1)return;d.preventDefault(),d.stopPropagation(),r();let m=n(),p=ve(m),f=m.captureEffectiveSelection({includeText:!0}),g=m.captureEffectiveSelection()??f,v=Ea({surface:p,clientX:d.clientX,clientY:d.clientY,captureSelectionFromState:l}),E=a(),R=Lu({controller:m,documentMode:i(),reviewActionsEnabled:E.enabled,effectiveSelection:f,actionSelectionCapture:g,pointSelection:v,clientX:d.clientX,clientY:d.clientY}),S=Ma(R,u.contextMenu,m);if(S.length===0){t();return}c({context:R,sections:S}),o()}}function ly(e){return Ea({surface:e.surface,clientX:e.pointSelectionInput.clientX,clientY:e.pointSelectionInput.clientY,captureSelectionFromState:e.captureSelectionFromState})?.capture??null}function cy(e){let{context:t,readProjectionSnapshot:r,readState:o,selectionCaptureTracker:n}=e,i=(R,S={},P=null)=>{let h=X(t),b=r();return{state:R,surfaceEditable:it(h.surface),surfaceSelectionReliable:GS(h.surface),selectionInput:S,reviewReplacementMode:h.replacementMode,revisions:b.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:b,preservedRangeSelection:P}},s=(R,S={})=>Eh(i(R,S)),a=(R,S={})=>{let P=X(t);return n.track(P.surface,R,s(R,S))},l=(R,S={},P=null)=>{let h=X(t),b=i(R,S,P);return n.track(h.surface,Pi(b),So(b))},c=(R,S={},P=null)=>So(i(R,S,P)),d=(R={})=>{let S=X(t);return S.surface.consumeHistoryChange?.()&&(t.preservedRangeSelection=null),o(),{selectionInput:R,runtime:S,preservedRangeSelection:t.preservedRangeSelection}};return{captureSelection:(R={})=>a(X(t).surface.state,R),captureEffectiveSelection:(R={})=>{let S=d(R);return l(S.runtime.surface.state,S.selectionInput,S.preservedRangeSelection)},readEffectiveSelection:(R={})=>{let S=d(R);return c(S.runtime.surface.state,S.selectionInput,S.preservedRangeSelection)},captureCurrentSelectionFromState:a,captureEffectiveSelectionFromState:l,capturePointSelection:R=>{let S=d(R);return ly({surface:S.runtime.surface,pointSelectionInput:R,captureSelectionFromState:P=>l(P,S.selectionInput,S.preservedRangeSelection)})},readPointSelection:R=>{let S=d(R);return ly({surface:S.runtime.surface,pointSelectionInput:R,captureSelectionFromState:P=>c(P,S.selectionInput,S.preservedRangeSelection)})},readSelectionCapture:(R,S={})=>{if(!R)return null;let P=X(t),h=n.resolveState(P.surface,R);return h?s(h,S):null},resolveSelectionCapture:(R,S={})=>{if(!R)return null;let P=X(t),h=n.resolveState(P.surface,R);return h?n.track(P.surface,h,s(h,S)):null}}}import{documentWideMutationEffect as OO}from"@datalking/begonia-editor-contracts";function Fu(e,t,r={}){return Ta(e,t,r)}function dy(e,t,r=e.replacementMode){if(e.replacementMode===r)return e;let o=e.surface;return e.release(),Fu(o,t,{replacementMode:r,templates:e.templatesAdapter})}function uy(e,t,r){r(e.surface),e.release(),t&&e.surface.destroy()}function my(e){let{canonicalDocument:t,collaborative:r,documentMode:o,nextSurfaceSession:n,sourceRuntime:i,surfaceFactory:s,trackChanges:a}=e;return s({currentSurface:i.surface,collaborative:r??n?.binding,documentStory:i.surface.documentStory,editable:ln(o),initialContent:bt(t,t.copy(t.content)),schema:i.surface.schema,participant:i.surface.participant,trackingEnabled:kr(o,a)})}function py(e){return ht(e)??Wn}function AO(e){return py(e)/100}function NO(e){return e.view?.dom??null}function DO(e){if(e.style)return e.style;let t={};return e.style=t,t}function zu(e,t){let r=NO(e);if(!r)return;let o=py(t),n=String(AO(o)),i=DO(r);r.dataset.aldZoomPercent=String(o),i.zoom=n,i.transformOrigin="top left"}function fy({context:e,templates:t,ownsSurface:r,surfaceFactory:o,allowCollaborativeProjection:n,emit:i,readCurrentDisplayState:s,clearEphemeralOverlays:a,handleLinkClick:l,handleContextMenu:c}){let d=new WeakMap,u=null,m=null,p=()=>{u?.dispose(),u=null,m=null},f=k=>((!u||m!==k)&&(p(),u=yw(()=>e.readModel.canonicalDocument,k,xe(e).documentRuntimeKernel.documentSource),m=k),u),g=k=>{let I=xe(e),F=po(e.readModel),y=F?f(k):I.documentRuntimeKernel.projections;F||p(),e.readModel=pi(e.readModel,y,k)},v=()=>e.readModel.projectedRuntimeBank?.resolveRuntime("tracked").documentApi??null,E=k=>{k.addEventListener("click",l),k.addEventListener("contextmenu",c)},R=k=>{k.removeEventListener("click",l),k.removeEventListener("contextmenu",c)},S=k=>{let I=k.view?.dom;if(!I)return;let F=d.get(k);F&&F!==I&&R(F),E(I),d.set(k,I);let y=s();fc(k,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,y.trackChanges,y.comments)},P=k=>{let I=d.get(k)??k.view?.dom??null;I&&(R(I),d.delete(k))},h=()=>{let k=e.readModel.collaborativeProjection;if(!k){e.readModel=fi(e.readModel);return}let I=xe(e),F=go({surface:k.runtime.surface,nextDocument:I.surface.document,documentApi:k.runtime.documentApi,canonicalReviewApi:v(),canonicalDocument:I.surface.document,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection});a(),P(k.runtime.surface),k.restore(),Ci({surface:I.surface,target:F,documentApi:I.documentApi}),k.runtime.release(),k.runtime.surface.destroy(),e.readModel=bn(fi(e.readModel))},b=k=>{let I=xe(e);if(I.replacementMode!==k){let F=dy(I,x,k);e.readModel=ad(e.readModel,F,k),e.readModel=bn(e.readModel)}g(k),e.readModel.collaborativeProjection&&e.readModel.collaborativeProjection.runtime.replacementMode!==k&&h()},x=()=>{let k=xe(e);A(k);let I=s(),F=Ns(k.surface,e.documentMode,I.trackChanges,n());if(po(e.readModel)&&F){let y=Me(e.readModel.canonicalDocument,k.surface,F);if(!Ar(k.surface.document,y)){e.readModel=ld(e.readModel,k.surface.document);let B=Me(e.readModel.canonicalDocument,k.surface,F);if(!Ar(k.surface.document,B)){Cn({surface:k.surface,nextDocument:B,documentApi:k.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:F,preservedRangeSelection:e.preservedRangeSelection});return}}}else e.readModel=bn(e.readModel);if(e.readModel.collaborativeProjection&&F){e.readModel.collaborativeProjection.sync(e.readModel.canonicalDocument,F)||i();return}e.documentMode==="viewing"&&I.trackChanges.enabled&&I.trackChanges.mode==="review"&&ba({surface:k.surface,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,projectedMode:F})||i()},A=(k=xe(e))=>{let I=ur(k.documentApi.preferences.get());zu(k.surface,I);let F=e.readModel.activeRuntime;F&&F.surface!==k.surface&&zu(F.surface,I)},O=()=>{let k=s();b(k.trackChanges.replacements);let I=xe(e),F=Ns(I.surface,e.documentMode,k.trackChanges,n()),y=ln(e.documentMode),B=kr(e.documentMode,k.trackChanges),M=rn(I.surface)?!1:y;if(e.readModel=bn(e.readModel),I.surface.editable!==M&&I.surface.setEditable(M),I.surface.trackingEnabled!==B&&I.surface.setTrackingEnabled(B),F&&I.surface.collaborative&&o){if(po(e.readModel)&&(Ar(I.surface.document,e.readModel.canonicalDocument)||I.surface.replaceDocument(bt(I.surface.document,e.readModel.canonicalDocument),{origin:"system",intent:"restore-canonical-projection-document",effects:[OO("review")]}),e.readModel=fi(e.readModel),g(k.trackChanges.replacements)),!e.readModel.collaborativeProjection){a();let ae=Me(e.readModel.canonicalDocument,I.surface,F),je=go({surface:I.surface,nextDocument:ae,documentApi:I.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:F,preservedRangeSelection:e.preservedRangeSelection}),me=Qh({sourceRuntime:I,surfaceFactory:o,canonicalDocument:e.readModel.canonicalDocument,projectionMode:F,emit:i,readPreservedRangeSelection:()=>e.preservedRangeSelection,replacementMode:k.trackChanges.replacements});Ci({surface:me.runtime.surface,target:je,documentApi:me.runtime.documentApi}),S(me.runtime.surface),e.readModel=WS(e.readModel,me)}e.readModel.collaborativeProjection?.sync(e.readModel.canonicalDocument,F)}else if(e.readModel.collaborativeProjection&&h(),F){let ae=Me(e.readModel.canonicalDocument,I.surface,F);e.readModel=qS(e.readModel),g(k.trackChanges.replacements),Ar(I.surface.document,ae)||Cn({surface:I.surface,nextDocument:ae,documentApi:I.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:F,preservedRangeSelection:e.preservedRangeSelection})}else po(e.readModel)&&(Ar(I.surface.document,e.readModel.canonicalDocument)||Cn({surface:I.surface,nextDocument:e.readModel.canonicalDocument,documentApi:I.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection}),e.readModel=fi(e.readModel),g(k.trackChanges.replacements));let N=e.readModel.activeRuntime??I;A(I);let L=rn(N.surface)?!1:y;N.surface.editable!==L&&N.surface.setEditable(L),N.surface.trackingEnabled!==B&&N.surface.setTrackingEnabled(B),fc(N.surface,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,k.trackChanges,k.comments)},j=k=>{let I=an(e.documentMode,e.resolvedModules.trackChanges).replacements;e.readModel=ad(e.readModel,Fu(k,x,{replacementMode:I,templates:t}),I),e.readModel=bn(e.readModel),g(I),S(k),A()},_=k=>{p(),e.readModel=pi(e.readModel,null),uy(xe(e),k,P),e.readModel=KS(e.readModel)};return{destroyCollaborativeProjection:h,handleSourceRuntimeUpdate:x,applySurfaceDisplayState:O,mountSourceRuntime:j,unmountSourceRuntime:_,createReplacementSurface:(k,I)=>{if(!o)throw new Error("Browser editor cannot reconfigure collaboration without a managed surface factory.");let F=s();return my({surfaceFactory:o,sourceRuntime:xe(e),canonicalDocument:e.readModel.canonicalDocument,documentMode:e.documentMode,trackChanges:F.trackChanges,collaborative:k,nextSurfaceSession:I})},swapSurface:(k,I)=>{let F=s(),y=Ns(k,e.documentMode,F.trackChanges,n()),B=go({surface:X(e).surface,nextDocument:Me(e.readModel.canonicalDocument,k,y),documentApi:X(e).documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:y,preservedRangeSelection:e.preservedRangeSelection});a(),h(),_(r||!!o),e.collaborationSession=I,j(k),O(),Ci({surface:X(e).surface,target:B,documentApi:X(e).documentApi})}}}function wy(e){let t=e.currentState.context,r=t.selectionCapture??null,o=t.actionSelectionCapture??null,n=t.pointSelectionCapture??null,i=ce(t.trackedChangeIds),s=ce(e.liveSelection.trackedChangeIds),a=ce(e.liveSelectionInfo.activeChangeIds),l=e.resolveSelectionCapture(r),c=n===r?l:e.resolveSelectionCapture(n),d=o===r?l:o===n?c:e.resolveSelectionCapture(o);if(r&&!l||n&&!c)return null;let u=n!=null,m=u?n:r,p=u?n:o,f=u?e.resolveSelectionState(n):null,g=u?null:e.resolveSelectionState(r),v=a.length>0||s.length>0,E=u?c:l,R=!u&&v?d??E:E,P=(!u&&v&&i.length>1?p?.selection??null:null)??R?.selection??E?.selection??null,h=u?Mt(c,e.revisions):yt({liveSelection:e.liveSelection,liveSelectionInfo:e.liveSelectionInfo,revisions:e.revisions,effectiveSelection:R}),b=ra(e.controller,e.documentMode,{revisions:e.revisions,reviewActionsEnabled:e.reviewActionsEnabled,selection:m?{from:P?.from??m.selection.from,to:P?.to??m.selection.to,empty:P?.empty??m.selection.empty,trackedChangeIds:h,trackedChangeIdsExplicit:!0}:null,selectionCapture:m,actionSelectionCapture:p,pointSelectionCapture:u?n:null,pointSelectionState:f??void 0,selectionTrackedChangeIds:s,clientX:t.clientX,clientY:t.clientY,selectionState:f??g??void 0}),x=Ma(b,e.contextMenuOptions,e.controller);return x.length>0?{context:b,sections:x}:null}function gy(e){let t=new Set([e.nextState?.context.selectionCapture,e.nextState?.context.actionSelectionCapture,e.nextState?.context.pointSelectionCapture].filter(o=>o!=null)),r=new Set([e.currentState?.context.selectionCapture,e.currentState?.context.actionSelectionCapture,e.currentState?.context.pointSelectionCapture].filter(o=>o!=null));for(let o of r)o&&!t.has(o)&&e.untrack(o)}function Sy(e){return{releaseContextMenuCaptures(t,r=null){gy({currentState:t,nextState:r,untrack:e})},untrackCapture:e}}function vy(e){return $e({selection:e.surface.describeSelection(),selectionInfo:e.selectionInfo,projectedDocument:We(e.surface),canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}import{createInvokeBridge as tj}from"@datalking/begonia-document-api/v1";import{createTrackChangesFacade as rj,summarizeReviewTimeline as Ey}from"@datalking/begonia-document-api/review";import{describeCapability as qO,planStepMode as WO,resolvePlanStepFailureReason as KO,resolveUnsupportedPlanStepReason as _O}from"@datalking/begonia-document-api/core";import{documentWideMutationEffect as UO}from"@datalking/begonia-editor-contracts";import{preserveNodeSymbolMetadata as jO}from"@datalking/begonia-engine";import{sameCommittedDocument as VO}from"@datalking/begonia-document-model";import{createDocumentChange as LO,createDocumentChangePublisher as FO}from"@datalking/begonia-editor-contracts";function Hu(e){let t=e,r=0,o=FO();return{readDocument(){return t},replaceDocument(n,i={origin:"api"}){let s=jO(t,n);if(VO(t,s)){t=s;return}let a=r;t=s,r+=1,o.publish(LO(a,r,i))},readProjectedDocument(){return t},documentSource:{readSnapshot(){return{document:t,revision:r}},subscribeDocument(n){return o.subscribe(n)}}}}function zO(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Di(e){let t=e.review.list().map(i=>i.id).filter((i,s,a)=>a.indexOf(i)===s).sort((i,s)=>i.localeCompare(s)),r=e.history.get(),o=e.info.text(),n=JSON.stringify(e.info.json());return{summary:e.info.summary(),revisionIds:t,historyRevision:r.currentRevision,textLength:o.length,documentHash:zO(n)}}function HO(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function qu(e,t){return e.summary.blockCount===t.summary.blockCount&&e.summary.wordCount===t.summary.wordCount&&e.summary.revisionCount===t.summary.revisionCount&&e.summary.footnoteCount===t.summary.footnoteCount&&e.summary.endnoteCount===t.summary.endnoteCount&&e.summary.commentCount===t.summary.commentCount&&e.summary.bookmarkCount===t.summary.bookmarkCount&&HO(e.revisionIds,t.revisionIds)&&e.historyRevision===t.historyRevision&&e.textLength===t.textLength&&e.documentHash===t.documentHash}function Wu(e,t){return t.filter(r=>!e.includes(r))}function hy(e){return e==="sequential"?"sequential":"all_or_nothing"}function Oi(e){return e??null}import{createDocumentRuntimeKernel as yy}from"@datalking/begonia-document-api/v1";function ZO(e,t){let r=Hu(t),o=yy(r,{review:{replacementMode:e.replacementMode}});return{surface:{editable:it(e.surface),get document(){return r.readProjectedDocument()}},documentRuntimeKernel:o,documentService:o.service,documentApi:o.api,replacementMode:e.replacementMode}}function GO(e,t){let r=ZO(e,e.surface.document),o=t.canonicalDocument??e.surface.document,n=Hu(o),i=yy(n,{review:{replacementMode:r.replacementMode}}),s=pi({...ia(o,r.replacementMode),sourceRuntime:r,activeRuntime:r},i.projections,r.replacementMode);return{detachedRuntime:r,projectionSnapshot:Or(s,t.projectedMode)}}function XO(e){let t=e.getRuntime(),r=e.readCurrentDisplayState(),o=e.readProjectionSnapshot(),{detachedRuntime:n,projectionSnapshot:i}=GO(t,o);return{detachedRuntime:n,api:e.createDocumentApi({getRuntime:()=>n,readProjectionSnapshot:()=>i,readCurrentDisplayState:()=>r})}}function by(e){let t=o=>{let n=XO(e),{api:i}=n,s=hy(o.commitMode),a=Di(i),l=i.info().revision;if(o.expectedRevision!=null&&o.expectedRevision!==l)return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:!1,changed:!1,committed:!1,commitMode:s,stoppedEarly:!0,error:`Document revision mismatch. Expected ${o.expectedRevision} but found ${l}.`,before:a,after:a,steps:[]}};if(o.expectedDocumentHash&&o.expectedDocumentHash!==a.documentHash)return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:!1,changed:!1,committed:!1,commitMode:s,stoppedEarly:!0,error:`Document hash mismatch. Expected ${o.expectedDocumentHash} but found ${a.documentHash}.`,before:a,after:a,steps:[]}};let c=[],d=!0,u=!1;for(let[p,f]of o.steps.entries()){let g=qO(f.operationId),v=Di(i),E=Oi(f.label),R=_O(f.operationId,g),S=WO(g);if(R){if(d=!1,c.push({index:p,label:E,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:S,ok:!1,changed:!1,error:R,revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}let P=i.operations.invokeDynamic({operationId:f.operationId,input:f.input,options:f.options}),h=Di(i),b=S==="write"&&!qu(v,h),x=P.ok?KO(P.value):null;if(!P.ok||x){if(d=!1,c.push({index:p,label:E,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:S,ok:!1,changed:!1,error:P.ok?x:P.error.message,...P.ok?{result:P.value}:{},revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}c.push({index:p,label:E,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:S,ok:!0,changed:b,result:P.value,revisionIdsCreated:Wu(v.revisionIds,h.revisionIds),revisionIdsRemoved:Wu(h.revisionIds,v.revisionIds)})}let m=Di(i);return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:d,changed:!qu(a,m),committed:!1,commitMode:s,stoppedEarly:u,before:a,after:m,steps:c}}};return{preview:o=>t(o).receipt,apply(o){let{detachedRuntime:n,receipt:i}=t(o),s=i.changed&&(i.commitMode==="sequential"||i.executable);return s&&e.getRuntime().surface.replaceDocument(n.surface.document,{origin:"api",intent:"commit-document-operation-plan",effects:[UO("structure")]}),{...i,preview:!1,committed:s}}}}function By(e){let t=e.subscribeStateChange??e.subscribeRawSelectionChange??null;return{onChange(r){if(!t)return()=>{};let o=!1,n=!1,i=An(e.readSelectionInfo()),s=()=>{if(n=!1,o)return;let d=e.readSelectionInfo(),u=An(d);u!==i&&(i=u,r(d))},a=()=>{o||n||(n=!0,queueMicrotask(s))},l;try{l=t(a)}catch(d){throw o=!0,d}let c=!1;return()=>{c||(c=!0,o=!0,l())}}}}function $O(e){let t=e.surface.view;return!!(t?.state&&typeof t.dispatch=="function")}function YO(e,t){let r=[...e??[]],o=[...t??[]];return r.length===o.length&&r.every((n,i)=>n===o[i])}function JO(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function xy(e){return e?.kind==="text"?e.segments.length:0}function QO(e){let t=e.members?.length?e.members:null;return t?t.every(r=>(r.text?.length??0)===0&&r.target?.nodeType!=="text"):(e.text?.length??0)===0&&e.target?.nodeType!=="text"}function Cy(e,t){return le([...e.activeChangeIds,...e.selection.trackedChangeIds??[]],t)}function Py(e,t){if(e.length===0)return!1;let r=le(e,t);if(r.length===0)return!1;let o=new Map(t.map(n=>[n.id,n]));return r.every(n=>{let i=o.get(n);return i?QO(i):!1})}function Ry(e){let{getRuntime:t,readProjectionSnapshot:r,readCurrentDisplayState:o,readPresentationComments:n,readCanonicalReviewApi:i,readEffectiveSelection:s,captureEffectiveSelection:a}=e,l=(d,u={})=>{let m=o().comments.enabled?n().list({includeResolved:o().comments.showResolved,enforceVisibilityPolicy:o().comments.enforceVisibilityPolicy,visibility:o().comments.visibility,sort:"desc"}):[],p=s?.(u)??a?.(u)??null,f=t(),g=$O(f),v=f.surface.describeSelection(),E=K(f.surface.state.selection)?"node":"text",R=i().review.list(),S=r(),P=$e({selection:v,selectionInfo:d,projectedDocument:We(f.surface),canonicalDocument:S.canonicalDocument,projectedMode:S.projectedMode,revisions:R}),h=ki(P.selectionInfo,Ti({activeCommentIds:P.selectionInfo.activeCommentIds,selection:v,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),b=ko(f.surface.state,h,E);if(p){let x=yt({liveSelection:P.selection,liveSelectionInfo:h,revisions:R,effectiveSelection:p}),A=Cy(p,R),O=cc({liveSelection:P.selection,liveActiveChangeIds:h.activeChangeIds,effectiveSelection:p}),j=ki(Rr(p,A),Ti({activeCommentIds:p.activeCommentIds,selection:p.selection,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),_=Py(A,R),V=!_&&p.projectedMode!=null,de=!_&&xy(p.selectionTarget)>xy(b.target),k=!_&&((j.text??null)!==(b.text??null)||!JO(j.target,b.target)||!YO(j.activeMarks,b.activeMarks));return P.selection.empty&&!p.selection.empty&&(p.activeCommentIds.length>0||A.length>0)&&(p.activeCommentIds.length>0||V||de||k||!g)?j:g?!O&&P.selection.empty&&!ar(h.activeChangeIds,x)?{...b,activeChangeIds:[...x]}:b:j}return b};return{resolvePublicSelectionInfo:l,readPublicSelectionInfo:(d={includeText:!0})=>{let u=t();return l(Dr(u.surface,d,u.replacementMode),d)}}}function ej(e){return()=>W(e)}function Ty(e,t,r,o,n){if(e==null||typeof e!="object"&&typeof e!="function"||typeof e=="function"||t!==""&&!o.deniedMemberPaths.has(t)&&!o.descendantMemberPaths.has(t))return e;let i=e,s=n.get(i)?.get(t);if(s)return s;let a=new Proxy(e,{get(c,d){let u=Reflect.get(c,d,c);if(typeof d!="string")return u;let m=Reflect.getOwnPropertyDescriptor(c,d);if(m&&"value"in m&&!m.configurable&&!m.writable)return m.value;let p=t?`${t}.${d}`:d;return o.deniedMemberPaths.has(p)?typeof u=="function"?ej(r):u:o.descendantMemberPaths.has(p)?Ty(u,p,r,o,n):u},apply(c,d,u){return o.deniedMemberPaths.has(t)?W(r):Reflect.apply(c,c,u)}}),l=n.get(i)??new Map;return l.set(t,a),n.set(i,l),a}function ky(e,t){return Ty(e,"",t,Lh(e),new WeakMap)}function Ot(e,t){return Jt(e.surface)??(t.comments.readOnly?"Comments are read-only in the current document mode.":null)}function My(e,t){return t.comments.allowResolve?Ot(e,t):"Comment resolution is disabled."}function Ku(e){let{getRuntime:t,readCurrentDisplayState:r,readProjectionSnapshot:o}=e,{readEffectiveSelection:n,captureEffectiveSelection:i,subscribeStateChange:s}=e,a=new WeakMap,l=()=>o(),c=()=>Pa(l()),d=()=>c().presentationReadApi,u=()=>c().canonicalReviewApi,m=()=>c().writableRuntimeApi,p=()=>Jt(t().surface),f=()=>it(t().surface),g=y=>{let B=l();return B.projectedMode==null||B.projectedRuntimeBank==null?null:y===B.projectedMode?B.presentationReadRuntime.documentApi:y==="tracked"?B.canonicalReviewRuntime.documentApi:B.projectedRuntimeBank.resolveRuntime(y).documentApi},v=()=>{let y=m(),B=p();if(!B)return y;let M=a.get(y)?.get(B);if(M)return M;let N=ky(y,B),L=a.get(y)??new Map;return L.set(B,N),a.set(y,L),N},E=qh({readPresentationApi:d,readWritableApi:v,readProjectedApiForMode:g}),R=by({getRuntime:t,readProjectionSnapshot:o,readCurrentDisplayState:r,createDocumentApi:Ku}),S=()=>d().comments,{readPublicSelectionInfo:P}=Ry({getRuntime:t,readProjectionSnapshot:o,readCurrentDisplayState:r,readPresentationComments:S,readCanonicalReviewApi:u,readEffectiveSelection:n,captureEffectiveSelection:i}),h=By({readSelectionInfo:()=>P({includeText:!0}),subscribeRawSelectionChange:y=>t().documentApi.selection.onChange(()=>y()),subscribeStateChange:s}),b=y=>{let B=n?.()??i?.()??null,M=m(),N=y(M);return N.changed&&mi({capture:B,surface:t().surface,comments:M.comments}),N},x=()=>m().comments,A={list:(y={})=>S().list(y),get:(y,B={})=>S().get(y,B),activity:(y,B={})=>S().activity(y,B),activityTimeline:(y,B={})=>S().activityTimeline(y,B),activitySummary:(y,B={})=>S().activitySummary(y,B),activityEntry:(y,B,M={})=>S().activityEntry(y,B,M),target:(y,B={})=>S().target(y,B),entryTarget:(y,B,M={})=>S().entryTarget(y,B,M),targetSnapshot:(y,B={})=>S().targetSnapshot(y,B),create:y=>{let B=Ot(t(),r());return B?W(B):x().create(y)},permissions:(y,B)=>{let M=S().permissions(y,B);return r().comments.readOnly?M&&Mi(M,r().comments):M},entryPermissions:(y,B,M)=>{let N=S().entryPermissions(y,B,M);return r().comments.readOnly?Uh(N):N},move:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().move(y,B,M)},upsert:y=>{let B=Ot(t(),r());return B?W(B):x().upsert(y)},reply:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().reply(y,B,M)},patch:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().patch(y,B,M)},update:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().update(y,B,M)},updateEntry:(y,B,M,N)=>{let L=Ot(t(),r());return L?W(L):x().updateEntry(y,B,M,N)},resolve:(y,B)=>{let M=My(t(),r());return M?W(M):x().resolve(y,B)},reopen:(y,B)=>{let M=My(t(),r());return M?W(M):x().reopen(y,B)},replaceTargetTextTracked:(y,B,M,N={})=>{let L=Ot(t(),r());return L?W(L):x().replaceTargetTextTracked(y,B,M,N)},removeEntry:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().removeEntry(y,B,M)},remove:(y,B)=>{let M=Ot(t(),r());return M?W(M):x().remove(y,B)}},O={query:(y,B={})=>d().search.query(y,B),next:(y,B=null,M={})=>d().search.next(y,B,M),previous:(y,B=null,M={})=>d().search.previous(y,B,M),replace:(y,B,M,N={})=>v().search.replace(y,B,M,N),replaceTracked:(y,B,M,N,L={},ae={})=>v().search.replaceTracked(y,B,M,N,L,ae),replaceAll:(y,B,M={})=>v().search.replaceAll(y,B,M),replaceAllTracked:(y,B,M,N={},L={})=>v().search.replaceAllTracked(y,B,M,N,L),clear:()=>d().search.clear()},j={list:(y={})=>d().proofing.list(y),ignore:y=>v().proofing.ignore(y),acceptSuggestion:y=>v().proofing.acceptSuggestion(y),replaceTracked:(y,B,M,N={})=>v().proofing.replaceTracked(y,B,M,N)},_={current:(y={})=>P(y),onChange:y=>h.onChange(y)},V={list:y=>u().review.list(y),decisionActivity:(y={})=>u().review.decisionActivity(y),decisionActivityEntry:(y,B={})=>u().review.decisionActivityEntry(y,B),decisionActivitySummary:(y={})=>u().review.decisionActivitySummary(y),decisionActivityByObject:(y,B={})=>u().review.decisionActivityByObject(y,B),decisionActivitySummaryByObject:(y,B={})=>u().review.decisionActivitySummaryByObject(y,B),timeline:(y={})=>{let B=r(),M=l();return Ai(Ra({projectionSnapshot:M,reviewOptions:y}),f(),B.comments)},timelineSummary:(y={})=>Ey(V.timeline(y)),timelineByObject:(y,B={})=>{let M=r(),N=l();return Ai(_h({projectionSnapshot:N,objectId:y,reviewOptions:B}),f(),M.comments)},timelineSummaryByObject:(y,B={})=>Ey(V.timelineByObject(y,B)),permissions:(y,B)=>{let M=u().review.permissions(y,B);return p()?M.map(Ii):M},accept:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.accept(y,B)),reject:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.reject(y,B)),acceptMatching:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.acceptMatching(y,B)),rejectMatching:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.rejectMatching(y,B)),decideRange:(y,B,M)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(N=>N.review.decideRange(y,B,M))},de=rj({service:null,review:V}),k=Object.assign(((y={})=>{let B=d().info,M=V.list().length,N=B(y);return{...N,counts:{...N.counts,trackedChanges:M}}}),{summary:()=>({...d().info.summary(),revisionCount:V.list().length}),outline:()=>d().info.outline(),json:()=>d().info.json(),text:()=>d().info.text(),html:(y={})=>(g(y.revisionProjection??l().projectedMode??"tracked")??d()).info.html(y),markdown:(y={})=>(g(y.revisionProjection??l().projectedMode??"tracked")??d()).info.markdown(y)}),I,F=tj(()=>new Proxy({},{get(y,B,M){return B==="service"?t().documentService:Reflect.get(I,B,M)}}));return I=new Proxy({},{get(y,B,M){let N=l();return B==="comments"?A:B==="review"?V:B==="search"?O:B==="proofing"?j:B==="selection"?_:B==="trackChanges"?de:B==="info"&&N.canonicalDocument!=null&&N.projectedMode!=null?k:B==="operations"?F:B==="plans"&&N.canonicalDocument!=null&&N.projectedMode!=null?R:typeof B=="string"?E(B):Reflect.get(d(),B,M)}}),I}import{emitClonedOrderedListeners as aj,throwOrderedListenerErrors as lj}from"@datalking/begonia-layout-renderer/core";function oj(e){return e==null?e:structuredClone(e)}function nj(e){return{empty:e.empty,target:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[...e.trackedChangeIds]}}function _u(e){let t=structuredClone({...e.selection,trackedChangeIds:le(e.selection.trackedChangeIds,e.revisions)}),r=e.selectionInfo,o=r?structuredClone({...r,activeChangeIds:le(r.activeChangeIds,e.revisions)}):nj(t),n=ro({revisions:e.revisions,selectionInfo:o}),i=sn({comments:e.comments,selectionInfo:o,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds});return{toolbar:structuredClone(e.toolbar),comments:structuredClone(e.comments),commentPermissions:structuredClone(e.commentPermissions),activeCommentId:i.activeCommentId,activeCommentIds:structuredClone(i.activeCommentIds),revisions:structuredClone(e.revisions),activeRevisionId:e.activeRevisionId??n.activeRevisionId,activeRevisionIds:structuredClone(e.activeRevisionIds??n.activeRevisionIds),reviewPermissions:structuredClone(e.reviewPermissions),reviewTimeline:structuredClone(e.reviewTimeline),reviewTimelineSummary:oj(e.reviewTimelineSummary),search:structuredClone(e.search),proofing:structuredClone(e.proofing),advancedOoxml:structuredClone(e.advancedOoxml),selectionInfo:o,selection:t,editable:e.editable,documentMode:e.documentMode,flowMode:e.flowMode,layoutMode:e.layoutMode,preferredPaginatedLayoutMode:e.preferredPaginatedLayoutMode,zoomPercent:e.zoomPercent,zoom:structuredClone(e.zoom),viewport:re(e.viewport),viewportRequestKey:e.viewportRequestKey,previewNavigationRequest:be(e.previewNavigationRequest),trackChanges:structuredClone(e.trackChanges),commentsDisplay:structuredClone(e.commentsDisplay),collaboration:structuredClone(e.collaboration),linkPopover:xa(e.linkPopover),contextMenu:Ca(e.contextMenu)}}function ij(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function sj(e){let t=e.view.state.doc,r=Math.max(1,t.content.size);return Math.max(1,Math.min(e.view.state.selection.head,r))}function Ia(e){if(e.allowSelectionInViewMode||e.documentMode!=="viewing"||!ij(e.surface)||e.surface.view.state.selection.empty)return!1;let t=sj(e.surface),r=e.surface.view.state.selection;if(r.from===t&&r.to===t)return!1;let o=Z(e.surface.view.state,t,t);return o?(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(o)),!0):!1}function Iy(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function Ay(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Ny({context:e,allowCollaborativeProjection:t,releaseContextMenuCaptures:r}){let o=!1,n=0,i=!1,s=0,a=!1,l=()=>e.collaborationSession?{...e.collaborationSession.getSnapshot(),mode:"session",reconfigurable:e.reconfigurable}:{collaborative:!1,mode:"none",reconfigurable:e.reconfigurable,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null},c=()=>{if(e.resolvedModules.trackChanges?.enabled===!1)return;let b=xe(e);if(rn(b.surface))return;let x=b.surface.editable?b.surface.trackingEnabled?"suggesting":"editing":"viewing";x!==e.documentMode&&(e.documentMode=x)},d=()=>IS(xe(e).surface,e.documentMode,e.resolvedModules,t()),u=()=>e.readModel.sourceRuntime?Qs(e.readModel.sourceRuntime.surface,e.collaborationSession,e.reconfigurable):l(),m=()=>{c(),e.normalizeOverlayState?.();let b=xe(e),x=X(e);x.surface.consumeHistoryChange?.()&&(e.preservedRangeSelection=null);let A=d(),O=ur(b.documentApi.preferences.get()),j=ca(e,O),_=Or(e.readModel,A.trackChanges.mode),V=Xh({runtime:x,projectionSnapshot:_,preservedRangeSelection:e.preservedRangeSelection,actor:e.currentActor,linkPopover:e.linkPopover,contextMenu:e.contextMenu,search:{query:e.searchQuery,options:e.searchOptions,activeHitId:e.activeSearchHitId},collaboration:u(),documentMode:e.documentMode,zoomPercent:O,zoom:j,viewportSession:e.viewportSession,display:{trackChanges:A.trackChanges,comments:A.comments},activeCommentId:e.activeCommentId,activeRevisionId:e.activeRevisionId,activeRevisionIds:e.activeRevisionIds}),de=uc({comments:V.comments,selectionInfo:V.selectionInfo});if(de.activeCommentId)e.activeCommentId!==de.activeCommentId&&(e.activeCommentId=de.activeCommentId);else if(e.activeCommentId!=null){let B=mc({comments:V.comments,selectionInfo:V.selectionInfo,explicitActiveCommentId:e.activeCommentId}),M=B.length===1?B[0]??null:null;e.activeCommentId!==M&&(e.activeCommentId=M)}let k=ro({revisions:V.revisions,selectionInfo:V.selectionInfo});if(k.activeRevisionIds.length>0)(e.activeRevisionId!==k.activeRevisionId||!Ay(e.activeRevisionIds,k.activeRevisionIds))&&(e.activeRevisionId=k.activeRevisionId,e.activeRevisionIds=[...k.activeRevisionIds]);else if(e.activeRevisionIds.length>0&&V.activeRevisionIds){let B=new Set(V.revisions.map(N=>N.id)),M=e.activeRevisionIds.filter(N=>B.has(N));Ay(e.activeRevisionIds,M)?M.length===0&&e.activeRevisionId!=null&&(e.activeRevisionId=null):(e.activeRevisionIds=[...M],e.activeRevisionId=M.length===1?M[0]??null:null)}let I=So({state:x.surface.state,surfaceEditable:x.surface.editable,surfaceSelectionReliable:Iy(x.surface),selectionInput:{includeText:!0},reviewReplacementMode:x.replacementMode,revisions:_.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:_,preservedRangeSelection:e.preservedRangeSelection}),F=!!(_.projectedMode!=null&&I&&V.selection.empty&&!I.empty&&e.preservedRangeSelection?.projectedMode!==_.projectedMode),y=I&&F?{selection:I.selection,selectionInfo:Rr(I),selectionNodeSelectionTarget:I.nodeSelectionTarget}:{selection:x.surface.describeSelection(),selectionInfo:V.selectionInfo,selectionNodeSelectionTarget:V.selectionNodeSelectionTarget??null};return e.preservedRangeSelection=Fd({selection:y.selection,selectionInfo:y.selectionInfo,selectionNodeSelectionTarget:y.selectionNodeSelectionTarget??null,previous:e.preservedRangeSelection,state:x.surface.state,surfaceSelectionReliable:Iy(x.surface),reviewReplacementMode:x.replacementMode,revisions:_.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:_}),e.activeSearchHitId=V.search.activeHitId,V},p=()=>_u(m()),f=()=>e.readModel.activeRuntime?Ia({surface:e.readModel.activeRuntime.surface,documentMode:e.documentMode,allowSelectionInViewMode:e.allowSelectionInViewMode}):!1,g=()=>{let b=null;do{if(i=!1,f()){i=!0;continue}b=m()}while(i);if(b==null)throw new Error("Browser editor state emission could not stabilize.");return b},v=()=>{if(s>0&&!o){a=!0;return}if(o){i=!0;return}o=!0;let b=[];try{do{let x=g();n+=1,b.push(...aj(e.listeners,x,_u))}while(i)}finally{o=!1,i=!1}lj(b,"Browser editor state listeners failed.")};return{syncDocumentModeFromSurface:c,readCurrentDisplayState:d,readCollaboration:u,readState:p,getEmissionVersion:()=>n,emit:v,runBatchedEmit:b=>{s+=1;try{return b()}finally{s-=1,s===0&&a&&(a=!1,v())}},closeLinkPopover:()=>{e.linkPopover&&(e.linkPopover=null,v())},closeContextMenu:()=>{e.contextMenu&&(r?.(),e.contextMenu=null,v())},clearEphemeralOverlays:()=>{r?.(),e.linkPopover=null,e.contextMenu=null},subscribeCollaborationSession:b=>{e.unsubscribeCollaborationSession?.(),e.unsubscribeCollaborationSession=b?.subscribe?b.subscribe(()=>v()):null}}}function Dy(e){let t=null,r=null,o=!1,n=s=>{r&&r!==s&&e.untrackCapture(r),r=s},i=()=>{n(null)};return{getSelectionCapture(){return r},sync(s){return!t||!r||!o||s(r)?.selection.formatting.link?!1:(t=null,i(),o=!1,e.setState(null),!0)},set(s,a=r){let l=s?a??null:null;e.setState(s),n(l),o=!!(s&&l?.selection.formatting.link),t=s??null},close(){t=null,i(),o=!1,e.closeState()},clearOverlays(){t=null,i(),o=!1,e.clearOverlayState()}}}import{createSelectionTrackingBookmark as Gu}from"@datalking/begonia-engine";import{readSyntheticSideStoryDocOriginPath as uj}from"@datalking/begonia-doc-service/v1";function cj(e){return typeof e.capture.text=="string"&&!e.selection.empty&&ge(e.surface.state.doc,e.surface.state.schema,e.selection)!==e.capture.text}function dj(e){let t=Mt(e.capture);return e.capture.selectionKind!=="text"||t.length===0?!1:!e.selection||e.selection.empty!==e.capture.selection.empty?!0:cj({surface:e.surface,selection:e.selection,capture:e.capture})}function Oy(e){return dj(e)?e.resolveSemanticSelection():e.selection}var mj=256;function Vy(e,t){if(!e||!t.docChanged)return e;try{return e.map(t.mapping)}catch{return null}}function Ly(e,t,r){for(let o of r.captures)t.add(o),e.delete(o);r.captures.clear()}function jy(e,t){for(;t.captures.size>mj;){let r=t.captures.values().next().value;if(!r)return;t.captures.delete(r),e.delete(r)}}function pj(e){return typeof e.view?.dispatch=="function"&&typeof e.subscribe=="function"}function fj(e,t,r){if(r.docChanged){e.pendingDispatchDocChange=!0;for(let o of e.captures){let n=t.get(o);if(!n){e.captures.delete(o);continue}n.bookmark=Vy(n.bookmark,r)}}}function Fy(e,t){let r=e.trackedView;if(!r){e.restoreDispatch=()=>{};return}if(e.usesAppliedTransactionStream){e.restoreDispatch=()=>{};return}let o=r.dispatch.bind(r),n=(i=>{if(!i.docChanged)return o(i);let s=r.state.doc,a=e.pendingDispatchDocChange,l=new Map;e.pendingDispatchDocChange=!0;for(let c of e.captures){let d=t.get(c);if(!d){e.captures.delete(c);continue}l.set(c,{tracked:d,bookmark:d.bookmark}),d.bookmark=Vy(d.bookmark,i)}try{return o(i)}catch(c){if(r.state.doc===s){e.pendingDispatchDocChange=a;for(let[d,u]of l)t.get(d)===u.tracked&&(u.tracked.bookmark=u.bookmark)}throw c}});r.dispatch=n,e.restoreDispatch=()=>{r.dispatch===n&&(r.dispatch=o)}}function zy(e,t,r){e.trackedView!==r.view&&(e.restoreDispatch(),e.trackedView=r.view,Fy(e,t))}function Uu(e,t,r,o,n={}){if(!pj(o))return null;let i=e.get(o);if(i)return zy(i,t,o),i;let s=o.subscribeTransactions?.bind(o)??null,a={captures:new Set,lastDocument:o.document,pendingDispatchDocChange:!1,programmaticDocChangeDepth:0,trackedView:o.view,usesAppliedTransactionStream:s!=null,restoreDispatch(){},unsubscribe(){},unsubscribeTransactions(){}};return s&&(a.unsubscribeTransactions=s(l=>{fj(a,t,l)})),Fy(a,t),a.unsubscribe=o.subscribe(()=>{let l=o.document;if(l!==a.lastDocument){if(!a.pendingDispatchDocChange)if(a.programmaticDocChangeDepth===0)Ly(t,r,a);else{let c=[];for(let d of a.captures){let u=t.get(d);if(!u){c.push(d);continue}let m=n.resolveProgrammaticSelection?.(o,d)??cr(o,d);if(!m){c.push(d);continue}u.bookmark=Gu(m)}for(let d of c)r.add(d),t.delete(d),a.captures.delete(d)}a.pendingDispatchDocChange=!1,a.lastDocument=l}}),e.set(o,a),a}function Zu(e,t,r,o,n=!0){let i=e.get(o);i&&(i.unsubscribe(),i.unsubscribeTransactions(),i.restoreDispatch(),i.trackedView=null,n?Ly(t,r,i):i.captures.clear(),e.delete(o))}function wj(e,t,r,o={}){let n=qy(e,t,r,o);return n?Ht(n):null}function gj(e,t){if(!t.bookmark)return null;try{let r=t.bookmark.resolve(e.state.doc);return!r||!t.empty&&r.empty?null:r}catch{return null}}function Hy(e,t,r,o={}){let n=gj(e,r),i=n?at(e.state,n):null,s=Oy({surface:e,selection:i,capture:t,resolveSemanticSelection:()=>o.resolveProgrammaticSelection?.(e,t)??cr(e,t)});if(s===i)return i;if(!s)return null;let a=at(e.state,s);return a?i&&qt(i,a)?i:(r.bookmark=Gu(a),a):null}function qy(e,t,r,o={}){let n=Hy(e,t,r,o);return n?Al(e.state,n):null}function Wy(e={}){let t=new Map,r=new Map,o=new WeakMap,n=new WeakSet,i=(a,l)=>{if(n.has(l))return!1;let c=o.get(l),d=uj(a.document);return bl(l.storyOriginPath,d)?l.documentIdentity!=null?l.documentIdentity===jn(a.document)&&l.documentHash===Oo(a.document):c?c.surface===a&&c.document===a.document:l.storyOriginPath!=null&&bl(l.storyOriginPath,d):!1},s=a=>{Zu(t,r,n,a)};return{clear(){for(let a of[...t.keys()])s(a);r.clear()},isTracked(a,l){return!l||n.has(l)?!1:r.get(l)?.surface===a},releaseSurface:s,transferSurface(a,l){if(a===l)return!0;let c=t.get(a);if(!c||c.captures.size===0)return Zu(t,r,n,a,!1),!0;let d=Uu(t,r,n,l,e);if(!d)return!1;for(let u of c.captures){let m=r.get(u);m&&(m.surface=l,o.set(u,{surface:l,document:l.document}),n.delete(u),d.captures.delete(u),d.captures.add(u))}return jy(r,d),Zu(t,r,n,a,!1),!0},runWithProgrammaticDocumentChange(a,l){let c=Uu(t,r,n,a,e);if(!c)return l();c.programmaticDocChangeDepth+=1;try{return l()}finally{c.programmaticDocChangeDepth>0&&(c.programmaticDocChangeDepth-=1),zy(c,r,a)}},untrack(a){if(!a)return;let l=r.get(a);l&&(t.get(l.surface)?.captures.delete(a),r.delete(a))},resolveSelection(a,l){if(!l)return null;let c=r.get(l);return!c||c.surface!==a?i(a,l)?cr(a,l):null:Hy(a,l,c,e)},resolveState(a,l){if(!l)return null;let c=r.get(l);if(!c||c.surface!==a){if(!i(a,l))return null;let d=cr(a,l);return d?Al(a.state,d):null}return qy(a,l,c,e)},resolveTarget(a,l){if(!l)return null;let c=l.target??l.selectionTarget;if(!c)return null;let d=r.get(l);return!d||d.surface!==a?i(a,l)?c:null:wj(a,l,d,e)},track(a,l,c){if(!c)return c;o.set(c,{surface:a,document:a.document}),n.delete(c);let d=Uu(t,r,n,a,e);if(!d)return c;let u=r.get(c);return u&&u.surface!==a&&t.get(u.surface)?.captures.delete(c),r.set(c,{surface:a,bookmark:Gu(l.selection),empty:c.selection.empty}),d.captures.delete(c),d.captures.add(c),jy(r,d),c}}}function Ky(e,t){return Object.freeze({id:e,kind:t})}function _y(e){let{captureCurrentSelectionFromState:t,getSurface:r,readSelectionCapture:o,selectionCaptureTracker:n}=e,i=new WeakMap,s=new Map,a=1,l=(c,d)=>{if(!d)return null;let u=Ky(a,c);return a+=1,i.set(u,d),s.set(d,(s.get(d)??0)+1),u};return{clear(){for(let c of s.keys())n.untrack(c);i=new WeakMap,s=new Map},capture:l,captureFromCapture(c){if(!c)return null;let d=n.resolveState(r(),c);return d?l("current",t(d)):null},resolve(c,d={}){return c?o(i.get(c)??null,d):null},peek(c){return c?i.get(c)??null:null},release(c){if(!c)return;let d=i.get(c)??null;if(i.delete(c),d){let u=(s.get(d)??0)-1;u>0?s.set(d,u):(s.delete(d),n.untrack(d))}}}}function Uy(e,t,r){return t.resolveSelection(e(),r)}function Zy(e){let{getSurface:t,selectionCaptureTracker:r,captureSelection:o,captureEffectiveSelection:n,captureCurrentSelectionFromState:i,readSelectionCapture:s}=e,a=_y({getSurface:t,selectionCaptureTracker:r,captureCurrentSelectionFromState:i,readSelectionCapture:s});return{clearDeferredSelectionState(){r.clear(),a.clear()},captureSelectionHandle(l={}){return a.capture("current",o(l))},captureEffectiveSelectionHandle(l={}){return a.capture("effective",n(l))},captureSelectionHandleFromCapture(l){return a.captureFromCapture(l)},resolveSelectionHandle(l,c={}){return a.resolve(l,c)},restoreSelectionCapture(l,c={}){return Tl({surface:t(),capture:l,resolveSelection:d=>Uy(t,r,d),options:{...c,validateDocumentIdentity:!1}})},restoreSelectionHandle(l,c={}){return Tl({surface:t(),capture:a.peek(l),resolveSelection:d=>Uy(t,r,d),options:{...c,validateText:!1,validateDocumentIdentity:!1}})},releaseSelectionHandle(l){a.release(l)},runAndEmit(l,c,d){let u=c(),m=r.runWithProgrammaticDocumentChange(t(),l);return c()===u&&d(),m}}}function Gy(e,t,r,o,n,i,s,a,l,c,d,u,m){let p=Qt(n),f=kS(i,s),g=mo(r,e,p.comments,o),v=As(c,e.trackingEnabled),E=Jr(d),R=dt(u)??"vertical",S=US(p,f,l??!0,r,g,v,E,dr(R,E),R,e.document,a??null),P=()=>Jh(s),h=Wy({resolveProgrammaticSelection(U,Se){if(Se.projectedMode!=null&&Se.selectionTarget){let Fe=V(),et=ut({state:U.state,target:Se.selectionTarget,projectionSnapshot:{canonicalDocument:Fe.canonicalDocument,projectedMode:Fe.projectedMode},sourceMode:Se.projectedMode,revisions:Fe.canonicalReviewRuntime.documentApi.review.list(),expectedText:Se.text??null});if(et&&Se.selectionKind==="text")return Z(U.state,et.selection.from,et.selection.to)}return null}}),b=Sy(U=>h.untrack(U)),x=Ny({context:S,allowCollaborativeProjection:P,releaseContextMenuCaptures:()=>b.releaseContextMenuCaptures(S.contextMenu)}),A=Dy({setState:U=>{S.linkPopover=U},closeState:x.closeLinkPopover,clearOverlayState:x.clearEphemeralOverlays,untrackCapture:b.untrackCapture}),O=sy({getController:m,getDocumentMode:()=>S.documentMode,getRuntime:()=>X(S),getResolvedModules:()=>S.resolvedModules,captureSelectionFromState:U=>M(U),setLinkPopover:A.set,closeContextMenu:x.closeContextMenu,closeLinkPopover:A.close,emit:x.emit}),j=ay({getController:m,getDocumentMode:()=>S.documentMode,getResolvedModules:()=>S.resolvedModules,readTrackChangesDisplayState:()=>x.readCurrentDisplayState().trackChanges,captureEffectiveSelectionFromState:U=>N(U,{includeText:!0}),setContextMenu:U=>{b.releaseContextMenuCaptures(S.contextMenu,U),S.contextMenu=U},closeContextMenu:x.closeContextMenu,closeLinkPopover:A.close,emit:x.emit}),_=fy({context:S,templates:t,ownsSurface:i,surfaceFactory:s,allowCollaborativeProjection:P,emit:x.emit,readCurrentDisplayState:x.readCurrentDisplayState,clearEphemeralOverlays:A.clearOverlays,handleLinkClick:O,handleContextMenu:j}),V=()=>Or(S.readModel,x.readCurrentDisplayState().trackChanges.mode),de=()=>{let U=X(S).surface;h.runWithProgrammaticDocumentChange(U,()=>_.applySurfaceDisplayState());let Se=X(S).surface;U!==Se&&!h.transferSurface(U,Se)&&Tt();let Fe=x.readCurrentDisplayState();if(Ia({surface:X(S).surface,documentMode:S.documentMode,allowSelectionInViewMode:S.allowSelectionInViewMode}),S.documentMode==="viewing"&&Fe.trackChanges.enabled&&Fe.trackChanges.mode==="review"){let et=V();ba({surface:X(S).surface,canonicalReviewApi:et.canonicalReviewRuntime.documentApi,canonicalDocument:et.canonicalDocument,projectedMode:et.projectedMode})}},k=Ku({getRuntime:()=>X(S),readProjectionSnapshot:V,readCurrentDisplayState:x.readCurrentDisplayState,readEffectiveSelection:U=>B(U),captureEffectiveSelection:U=>y(U),subscribeStateChange:U=>{let Se=()=>U();return S.listeners.add(Se),()=>{S.listeners.delete(Se)}}}),I=cy({context:S,readProjectionSnapshot:V,readState:x.readState,selectionCaptureTracker:h}),{captureSelection:F,captureEffectiveSelection:y,readEffectiveSelection:B,captureCurrentSelectionFromState:M,captureEffectiveSelectionFromState:N,readSelectionCapture:L,resolveSelectionCapture:ae}=I,je=U=>ae(U,{includeText:!0}),me=U=>L(U,{includeText:!0});S.normalizeOverlayState=()=>{let U=A.sync(me),Se=S.contextMenu;if(!Se)return U;let Fe=X(S),et=V(),Vi=et.canonicalReviewRuntime.documentApi.review.list(),Li=vy({surface:Fe.surface,selectionInfo:Dr(Fe.surface,{includeText:!0},Fe.replacementMode),projectionSnapshot:et,revisions:Vi}),Fi=wy({currentState:Se,controller:m(),documentMode:S.documentMode,contextMenuOptions:S.resolvedModules.contextMenu,reviewActionsEnabled:x.readCurrentDisplayState().trackChanges.enabled,revisions:Vi,liveSelection:Li.selection,liveSelectionInfo:Li.selectionInfo,resolveSelectionCapture:je,resolveSelectionState:zi=>h.resolveState(Fe.surface,zi)});return b.releaseContextMenuCaptures(Se,Fi),S.contextMenu=Fi,!0};let Ke=Zy({getSurface:()=>X(S).surface,selectionCaptureTracker:h,captureSelection:F,captureEffectiveSelection:y,captureCurrentSelectionFromState:M,readSelectionCapture:L}),{clearDeferredSelectionState:Tt,captureSelectionHandle:Je,captureEffectiveSelectionHandle:Ce,captureSelectionHandleFromCapture:mt,resolveSelectionHandle:hr,restoreSelectionCapture:jt,restoreSelectionHandle:vo,releaseSelectionHandle:Vt}=Ke,Lt=U=>Ke.runAndEmit(U,x.getEmissionVersion,x.emit),yr=ty({getRuntime:()=>X(S),runAndEmit:Lt,readState:()=>x.readState(),clearPreservedRangeSelection:()=>{S.preservedRangeSelection=null}}),z=()=>Es({editable:X(S).surface.editable,document:X(S).surface.document,commentsDisplay:x.readCurrentDisplayState().comments}),Qe=()=>Jt(X(S).surface);return _.mountSourceRuntime(e),x.subscribeCollaborationSession(S.collaborationSession),de(),{context:S,permissionResolver:o,stateRuntime:x,lifecycle:_,selectionRuntime:I,linkPopoverRuntime:A,advancedOoxmlMethods:yr,publicDocumentApi:k,commentWriteReason:z,reviewWriteReason:Qe,applySurfaceDisplayState:de,clearDeferredSelectionState:Tt,selectionCaptureTracker:h,captureCurrentSelectionFromState:M,runAndEmit:Lt,captureSelectionHandle:Je,captureEffectiveSelectionHandle:Ce,captureSelectionHandleFromCapture:mt,resolveSelectionHandle:hr,restoreSelectionCapture:jt,restoreSelectionHandle:vo,releaseSelectionHandle:Vt}}function ji(e,t,r,o,n,i,s,a,l,c,d,u){let m,p=Gy(e,t,r,o,n,i,s,a,l,c,d,u,()=>m),{context:f,permissionResolver:g,stateRuntime:v,lifecycle:E,selectionRuntime:R,linkPopoverRuntime:S,advancedOoxmlMethods:P,publicDocumentApi:h,commentWriteReason:b,reviewWriteReason:x,applySurfaceDisplayState:A,clearDeferredSelectionState:O,selectionCaptureTracker:j,captureCurrentSelectionFromState:_,runAndEmit:V,captureSelectionHandle:de,captureEffectiveSelectionHandle:k,captureSelectionHandleFromCapture:I,resolveSelectionHandle:F,restoreSelectionCapture:y,restoreSelectionHandle:B,releaseSelectionHandle:M}=p,N=g,L=()=>Or(f.readModel,v.readCurrentDisplayState().trackChanges.mode),ae=!1,{captureSelection:je,captureEffectiveSelection:me,readEffectiveSelection:Ke,capturePointSelection:Tt,readPointSelection:Je,readSelectionCapture:Ce,resolveSelectionCapture:mt}=R,hr=ZS({context:f,permissionResolver:N,getSurface:()=>X(f).surface,readState:v.readState,runBatchedEmit:v.runBatchedEmit,clearEphemeralOverlays:S.clearOverlays,applySurfaceDisplayState:A,emit:v.emit}),jt=HS({reconfigurable:f.reconfigurable,getRuntime:()=>X(f),getSourceRuntime:()=>xe(f),getCurrentActor:()=>f.currentActor,getCollaborationSession:()=>f.collaborationSession,readCollaboration:v.readCollaboration,readCommentResolveState:()=>v.readCurrentDisplayState().comments,commentWriteReason:b,reviewWriteReason:x,createReplacementSurface:E.createReplacementSurface,swapSurface:(z,Qe)=>{let U=f.preservedRangeSelection,Se=X(f).surface;f.collaborationSession=Qe,v.subscribeCollaborationSession(f.collaborationSession),E.swapSurface(z,Qe);let Fe=X(f).surface;j.transferSurface(Se,Fe)||O(),f.currentActor=mo(f.actorInput,Fe,f.resolvedModules.comments,N),f.preservedRangeSelection??=U},emit:v.emit,runAndEmit:V,readEffectiveSelection:Ke,captureEffectiveSelection:me,readSelectionCapture:Ce,resolveSelectionCapture:mt,resolveSelectionHandle:F,resolveCommentTargetFromCapture:z=>{if(!z)return null;let Qe=Nr(z)?z.selectionTarget:null,U=z.target??Qe;if(!U)return null;if(!Nr(z))return U;let Se=X(f),Fe=j.resolveTarget(Se.surface,z),et=Ce(z,{includeText:!0}),Vi=et?.target??et?.selectionTarget??Fe,Li=j.isTracked(Se.surface,z),Fi="segments"in U?(()=>{let zi=Q(Se.surface.state.doc,U,{strict:!0});return zi?ge(Se.surface.state.doc,Se.surface.state.schema,zi):null})():null;return $S({captureTarget:U,captureText:z.text,originalTargetText:Fi,resolvedTarget:Vi,resolvedText:et?.text??null,captureStillTracked:Li})},getPresentationReadApi:()=>L().presentationReadRuntime.documentApi,getWritableRuntimeApi:()=>L().writableRuntime.documentApi,getSearchQuery:()=>f.searchQuery,setSearchQuery:z=>{f.searchQuery=z},getSearchOptions:()=>f.searchOptions,setSearchOptions:z=>{f.searchOptions=z},getActiveSearchHitId:()=>f.activeSearchHitId,setActiveSearchHitId:z=>{f.activeSearchHitId=z},getActiveCommentId:()=>v.readState().activeCommentId??null,setActiveCommentId:z=>{f.activeCommentId=z},readVisibleComments:()=>v.readState().comments,getActiveRevisionId:()=>v.readState().activeRevisionId??null,setActiveRevisionIds:z=>{f.activeRevisionIds=[...z],f.activeRevisionId=z.length===1?z[0]??null:null},getLinkPopover:()=>f.linkPopover,getLinkPopoverSelectionCapture:S.getSelectionCapture,setLinkPopover:S.set,closeLinkPopover:S.close,clearPreservedRangeSelection:()=>{f.preservedRangeSelection=null}}),vo=tv({context:f,emit:v.emit,getEmissionVersion:v.getEmissionVersion,applySurfaceDisplayState:A}),Vt,Lt;m={get surface(){return X(f).surface},get documentService(){return X(f).documentService},get documentApi(){return h},get editorHost(){return Vt},get editor(){return Lt},get modules(){return Qt(f.resolvedModules)},get actor(){return aa(f.currentActor)},get collaboration(){return fd(v.readCollaboration())},getState(){return v.readState()},getCollaborationState(){return fd(v.readCollaboration())},...hr,...vo,setActor(z){f.actorInput=z,f.currentActor=mo(f.actorInput,X(f).surface,f.resolvedModules.comments,N),v.emit()},setParticipant(z){f.currentActor=sd(f.actorInput,z,f.resolvedModules.comments,N);let Qe=xe(f),U=f.readModel.activeRuntime;U&&U.surface!==Qe.surface&&U.surface.setParticipant(z),Qe.surface.setParticipant(z)},subscribe(z){f.listeners.add(z);try{ae||z(v.readState())}catch(Qe){throw f.listeners.delete(z),Qe}return()=>f.listeners.delete(z)},captureSelection:je,captureEffectiveSelection:me,readEffectiveSelection:Ke,readSelectionCapture:Ce,captureSelectionHandle:de,captureEffectiveSelectionHandle:k,captureSelectionHandleFromCapture:I,resolveSelectionCapture:mt,resolveSelectionHandle:F,restoreSelectionCapture:y,restoreSelectionHandle:B,releaseSelectionHandle:M,capturePointSelection(z){return!z||typeof z!="object"||typeof z.clientX!="number"||typeof z.clientY!="number"?null:Tt(z)},readPointSelection(z){return!z||typeof z!="object"||typeof z.clientX!="number"||typeof z.clientY!="number"?null:Je(z)},...jt,...P,closeLinkPopover:S.close,closeContextMenu:v.closeContextMenu,destroy(){if(ae)return;ae=!0,O(),f.unsubscribeCollaborationSession?.(),f.unsubscribeCollaborationSession=null,f.listeners.clear(),Lt.destroy(),E.destroyCollaborativeProjection();let z=i||!!s;E.unmountSourceRuntime(z),f.preservedRangeSelection=null,f.collaborationSession=null}},Vt=ci(m),Lt=Sj(Vt);let yr=$s(()=>X(f).surface);return Object.defineProperty(m,Os,{value(z){if(!z||typeof z!="object"||typeof z.clientX!="number"||typeof z.clientY!="number")return null;let Qe=dn({surface:X(f).surface,clientX:z.clientX,clientY:z.clientY,mode:"text-only"});return Qe?_(Qe.state,z):null}}),Object.defineProperties(m,{readLayoutAdapter:{configurable:!1,enumerable:!1,value:yr.readLayoutAdapter},readLayoutSource:{configurable:!1,enumerable:!1,value:yr.readLayoutSource},readDocumentSize:{configurable:!1,enumerable:!1,value:yr.readDocumentSize},selection:{configurable:!1,enumerable:!1,value:yr.selection}}),m}import{createDocumentFontCatalog as Xy,createDocumentFontRegistrationManager as vj}from"@datalking/begonia-font-system";function Xu(e){return e.document.attrs.ooxmlPackageResources}function hj(e,t){let r=e.view?.dom;if(r?.querySelectorAll)for(let o of Array.from(r.querySelectorAll("[data-font-family], [data-font-family-resolved]"))){let n=o.getAttribute("data-font-family")??o.getAttribute("data-font-family-resolved");if(!n)continue;let i=t(n),s=o.style;s&&(s.fontFamily=i??n)}}function $u(e,t,r){let o=Xy(Xu(t),"browser-document"),n=vj(r,o),i=Xu(t),s=!1,a=()=>{s||hj(e.surface,u=>n.catalog.resolveFamily(u))},l=()=>{if(s)return;let u=e.surface,m=Xu(u);m!==i&&(i=m,n.replace(Xy(m,"browser-document"))),a(),n.ready.then(a)},c=e.subscribe(l),d=e.destroy.bind(e);return Object.defineProperties(e,{documentFontCatalog:{configurable:!0,enumerable:!0,get:()=>n.catalog},documentFontsReady:{configurable:!0,enumerable:!0,get:()=>n.ready}}),e.destroy=()=>{s||(s=!0,c(),n.dispose(),d())},l(),e}function $y(e,t){t.fitWidthOptions!==void 0&&e.setFitWidthOptions(t.fitWidthOptions),t.zoomMode&&e.setZoomMode(t.zoomMode);let r=ht(t.zoomPercent);return r!=null&&t.zoomMode!=="fit-width"&&r!==e.getZoomPercent()&&e.setViewState({zoomPercent:r}),e}function bj(e,t={}){let r=$y(ji(e,t.templates,t.actor,t.permissionResolver,t.modules,!1,t.surfaceFactory,t.collaborationSession,t.viewSelect,t.documentMode,t.flowMode,t.layoutMode),t);return $u(r,e,t.documentFontProvider)}function Yu(e){let t=e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:_i(e.features??[]),r=As(e.documentMode,e.trackingEnabled),o=an(r,e.modules?.trackChanges),{actor:n,templates:i,collaborationSession:s,documentMode:a,documentFontProvider:l,enableEmbeddedAdvancedOoxmlEditors:c,flowMode:d,layoutMode:u,zoomPercent:m,zoomMode:p,fitWidthOptions:f,modules:g,permissionResolver:v,surfaceFactory:E,viewSelect:R,...S}=e,P=yj({...S,collaborative:e.collaborationSession?.binding??e.collaborative,editable:ln(r),trackingEnabled:kr(r,o),features:t}),h=$y(ji(P,e.templates,e.actor,e.permissionResolver,e.modules,!0,MS({...e,features:t}),e.collaborationSession,e.viewSelect,e.documentMode,e.flowMode,e.layoutMode),e);return $u(h,P,e.documentFontProvider)}import{DEFAULT_VIEWPORT_FIT_WIDTH_OPTIONS as V3,cloneViewportFitMetrics as L3,cloneViewportFitWidthOptions as F3,computeAppliedViewportFitZoom as z3,computeViewportFitZoom as H3,normalizeViewportFitMetrics as q3,normalizeViewportFitWidthOptions as Bj,resolveViewportFitMetricsFromPreview as W3,sameViewportFitMetrics as K3,sameViewportFitWidthOptions as xj}from"@datalking/begonia-layout-renderer/core";function Ju(e){return Bj(e)}function Yy(e,t){return xj(e,t)}var Cj=Object.freeze([]);function Qy(e,t){return e.length===t.length&&e.every((r,o)=>Object.is(r,t[o]))}function Pj(e,t){return e===t?!0:!e||!t?e==null&&t==null:Qy(e,t)}function eb(e,t){return e===t?!0:!e||!t?e==null&&t==null:(e.id??null)===(t.id??null)&&(e.name??null)===(t.name??null)&&(e.createdAt??null)===(t.createdAt??null)&&(e.role??null)===(t.role??null)&&(e.bypassPermissions??!1)===(t.bypassPermissions??!1)&&(e.canViewInternalComments??!1)===(t.canViewInternalComments??!1)&&(e.canToggleCommentVisibility??!1)===(t.canToggleCommentVisibility??!1)&&(e.permissionResolver??null)===(t.permissionResolver??null)&&(e.commentPermissionResolver??null)===(t.commentPermissionResolver??null)&&Pj(e.groups,t.groups)}function tb(e,t){return e.id===t.id&&e.name===t.name&&(e.color??null)===(t.color??null)}function Rj(e){return{...e}}function Tj(e){return e?.length?[...e]:Cj}function kj(e){return!e||typeof e!="object"?e:{...e}}function rb(e,t){return Yy(Ju(e),Ju(t))}function Jy(e){return{...e,collaborationSession:e.collaborationSession??null,enableEmbeddedAdvancedOoxmlEditors:e.enableEmbeddedAdvancedOoxmlEditors!==!1,...e.actor!==void 0?{actor:aa(e.actor??null)}:{},features:Tj(e.features),...e.fitWidthOptions!==void 0?{fitWidthOptions:kj(e.fitWidthOptions)}:{},...e.modules!==void 0?{modules:Qt(e.modules)}:{},participant:Rj(e.participant),trackingEnabled:e.trackingEnabled!==!1,viewSelect:e.viewSelect!==!1}}function ob(e,t){return e.room===t.room&&e.collaborative===t.collaborative&&e.collaborationSession===t.collaborationSession&&e.enableEmbeddedAdvancedOoxmlEditors===t.enableEmbeddedAdvancedOoxmlEditors&&Qy(e.features,t.features)&&e.initialContent===t.initialContent&&e.schema===t.schema&&e.permissionResolver===t.permissionResolver&&e.surfaceFactory===t.surfaceFactory&&e.trackingEnabled===t.trackingEnabled&&e.viewSelect===t.viewSelect}function Ej(e,t){return eb(e.actor,t.actor)&&ob(e,t)&&e.documentMode===t.documentMode&&e.flowMode===t.flowMode&&e.layoutMode===t.layoutMode&&id(e.modules,t.modules)&&e.onTransaction===t.onTransaction&&e.onUpdate===t.onUpdate&&tb(e.participant,t.participant)&&e.zoomMode===t.zoomMode&&rb(e.fitWidthOptions,t.fitWidthOptions)&&e.zoomPercent===t.zoomPercent}function Mj(e,t){return e.controller===t.controller&&e.state===t.state}function Qu(e){return{controller:e.controller,state:e.state}}function Ij(e,t,r){let{room:o,...n}=e;return{...n,collaborative:e.collaborationSession?.binding??e.collaborative??e.room,element:t,onTransaction:r.onTransaction,onUpdate:r.onUpdate}}function Aj(e){let{controller:t,previous:r,next:o}=e;eb(r.actor,o.actor)||t.setActor(o.actor??null),tb(r.participant,o.participant)||t.setParticipant(o.participant),r.documentMode!==o.documentMode&&o.documentMode!=null&&t.setDocumentMode(o.documentMode),id(r.modules,o.modules)||t.setModules(o.modules),r.zoomMode!==o.zoomMode&&o.zoomMode!=null&&t.setZoomMode(o.zoomMode),!rb(r.fitWidthOptions,o.fitWidthOptions)&&o.fitWidthOptions!==void 0&&t.setFitWidthOptions(o.fitWidthOptions);let n={...r.flowMode!==o.flowMode&&o.flowMode?{flowMode:o.flowMode}:{},...r.layoutMode!==o.layoutMode&&o.layoutMode?{layoutMode:o.layoutMode}:{},...r.zoomPercent!==o.zoomPercent&&o.zoomPercent!=null&&o.zoomMode!=="fit-width"?{zoomPercent:o.zoomPercent}:{}};Object.keys(n).length>0&&t.setViewState(n)}function em(e,t={}){let r=new Set,o=t.createEditor??Yu,n={destroyed:!1,host:null,input:Jy(e),controller:null,state:null,unsubscribeController:null,snapshot:{controller:null,state:null}},i=()=>{let c={controller:n.controller,state:n.state};if(!Mj(n.snapshot,c)){n.snapshot=c;for(let d of[...r])d(Qu(c))}},s=()=>{let c=n.controller,d=n.unsubscribeController;n.unsubscribeController=null,n.controller=null,n.state=null,i(),d?.(),c&&c.destroy()},a=()=>{if(!n.host)return;let c=o(Ij(n.input,n.host,{onTransaction(d){n.input.onTransaction?.(d)},onUpdate(){n.input.onUpdate?.()}}));n.controller=c,n.state=c.getState(),i(),n.unsubscribeController=c.subscribe(d=>{n.controller===c&&(n.state=d,i())})},l=()=>{s(),a()};return{getSnapshot(){return Qu(n.snapshot)},subscribe(c){return r.add(c),c(Qu(n.snapshot)),()=>{r.delete(c)}},setHost(c){if(!(n.destroyed||n.host===c)){if(n.host=c,!c){s();return}if(!n.controller){a();return}l()}},setInput(c){if(n.destroyed)return;let d=n.input,u=Jy(c);if(n.input=u,Ej(d,u)||!n.host)return;let m=!ob(d,u);if(!n.controller||m){l();return}Aj({controller:n.controller,previous:d,next:u})},destroy(){n.destroyed||(n.destroyed=!0,n.host=null,s(),r.clear())}}}function Nj(){return{ui:null,host:null,snapshot:null}}function ib(e){vS(e.host,e.ui),e.ui?.destroy(),e.controller=null,e.host=null,e.ui=null}function Dj(e,t){if(e.controller===t||(ib(e),!t))return;let r=hn(t);e.controller=t,e.host=r,e.ui=ks(r);let o=wr(r);o&&Ys(r,e.ui,o)}function nb(e,t){return Dj(e,t.controller),{ui:e.ui,host:e.host,snapshot:t.state?cn(t.state):null}}function Oj(e){let t=em(e),r=new Set,o={controller:null,host:null,ui:null},n=nb(o,t.getSnapshot()),i=t.subscribe(s=>{n=nb(o,s);for(let a of[...r])a(n)});return{getSnapshot(){return n},subscribe(s){return r.add(s),s(n),()=>{r.delete(s)}},setHost(s){t.setHost(s)},setInput(s){t.setInput(s)},destroy(){i(),r.clear(),ib(o),t.destroy(),n=Nj()}}}function jj(){return{createMount(e){return Oj(e)}}}function Vj(e){return Js(e)}import{collectOoxmlMathStructures as Lj,countOoxmlChartCategories as Fj,normalizeOoxmlChartModel as zj,normalizeOoxmlMathModel as Hj,normalizeOoxmlShapeModel as qj}from"@datalking/begonia-engine";function Aa(e){return e.trackingEnabled??e.toolbar?.trackingEnabled??!1}function Na(e){return e.documentMode==="editing"||e.documentMode==="suggesting"||e.documentMode==="viewing"?e.documentMode:"editing"}function Wj(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="math")return null;let r=Hj(t.familyData??{plainText:t.text,displayMode:"inline"},t.text,"inline");return{family:"math",record:t,model:r,plainText:t.familyData?.plainText??t.text,displayMode:r.displayMode,structures:t.familyData?.structures?.length?t.familyData.structures:Lj(r),trackingEnabled:Aa(e),documentMode:Na(e)}}function Kj(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="chart")return null;let r=zj(t.familyData?.model??t.familyData??{title:t.label,textBody:{plainText:t.text}},t.label);return{family:"chart",record:t,model:r,series:r.series,seriesCount:r.series.length,categoryCount:Fj(r),trackingEnabled:Aa(e),documentMode:Na(e)}}function _j(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="shape")return null;let r=qj(t.familyData?.model??t.familyData??{label:t.label,textBody:t.text?{plainText:t.text,paragraphs:[t.text]}:null},t.label);return{family:"shape",record:t,model:r,trackingEnabled:Aa(e),documentMode:Na(e)}}function tm(e="editing",t=!1){return{selected:null,documentMode:e,trackingEnabled:t}}function sb(e){return{selected:Wj(e)??Kj(e)??_j(e),trackingEnabled:Aa(e),documentMode:Na(e)}}function Da(e){return structuredClone(e)}function ee(e){return{changed:!1,reason:e}}function Uj(e){let t=e,r=he(t),o=wr(t),n=hS(t),i=o?.controller.documentApi??{},s=()=>{let m=o?.controller.getState();return m?sb(m):tm()},a=s(),l=new Set,c=()=>{a=s();for(let m of[...l])m(Da(a))},d=r?.session.subscribe(()=>c())??(()=>{}),u="Advanced OOXML editing requires a mounted browser editor backend.";return{actor:o?.controller.actor??null,documentApi:i,getSnapshot(){return a=s(),Da(a)},subscribe(m){return l.add(m),m(Da(a)),()=>{l.delete(m)}},replaceSelectedMathModel(m){return n?n.replaceSelectedMathModel(m):ee(u)},setSelectedMathPlainText(m,p){return n?n.setSelectedMathPlainText(m,p):ee(u)},setSelectedMathDisplayMode(m){return n?n.setSelectedMathDisplayMode(m):ee(u)},replaceSelectedChartModel(m){return n?n.replaceSelectedChartModel(m):ee(u)},setSelectedChartMetadata(m){return n?n.setSelectedChartMetadata(m):ee(u)},appendSelectedChartSeries(m){return n?n.appendSelectedChartSeries(m):ee(u)},setSelectedChartSeriesList(m){return n?n.setSelectedChartSeriesList(m):ee(u)},setSelectedChartTitle(m){return n?n.setSelectedChartTitle(m):ee(u)},setSelectedChartTextBody(m){return n?n.setSelectedChartTextBody(m):ee(u)},setSelectedChartSeries(m,p){return n?n.setSelectedChartSeries(m,p):ee(u)},upsertSelectedChartSeries(m,p){return n?n.upsertSelectedChartSeries(m,p):ee(u)},removeSelectedChartSeries(m){return n?n.removeSelectedChartSeries(m):ee(u)},appendSelectedChartAxis(m){return n?n.appendSelectedChartAxis(m):ee(u)},setSelectedChartAxes(m){return n?n.setSelectedChartAxes(m):ee(u)},upsertSelectedChartAxis(m,p){return n?n.upsertSelectedChartAxis(m,p):ee(u)},removeSelectedChartAxis(m){return n?n.removeSelectedChartAxis(m):ee(u)},setSelectedChartLegend(m){return n?n.setSelectedChartLegend(m):ee(u)},setSelectedChartPlotArea(m){return n?n.setSelectedChartPlotArea(m):ee(u)},replaceSelectedShapeModel(m){return n?n.replaceSelectedShapeModel(m):ee(u)},setSelectedShapeMetadata(m){return n?n.setSelectedShapeMetadata(m):ee(u)},setSelectedShapeWatermark(m){return n?n.setSelectedShapeWatermark(m):ee(u)},setSelectedShapeTextBody(m){return n?n.setSelectedShapeTextBody(m):ee(u)},setSelectedShapeGeometry(m){return n?n.setSelectedShapeGeometry(m):ee(u)},setSelectedShapeTransform(m){return n?n.setSelectedShapeTransform(m):ee(u)},setSelectedShapeFill(m){return n?n.setSelectedShapeFill(m):ee(u)},setSelectedShapeStroke(m){return n?n.setSelectedShapeStroke(m):ee(u)},setSelectedShapeAnchor(m){return n?n.setSelectedShapeAnchor(m):ee(u)},setSelectedShapeConnector(m){return n?n.setSelectedShapeConnector(m):ee(u)},setSelectedShapePicture(m){return n?n.setSelectedShapePicture(m):ee(u)},setSelectedShapeWordArt(m){return n?n.setSelectedShapeWordArt(m):ee(u)},setSelectedShapeChildren(m){return n?n.setSelectedShapeChildren(m):ee(u)},setSelectedShapeChild(m,p){return n?n.setSelectedShapeChild(m,p):ee(u)},appendSelectedShapeChild(m){return n?n.appendSelectedShapeChild(m):ee(u)},appendSelectedShapeChildToParent(m,p){return n?n.appendSelectedShapeChildToParent(m,p):ee(u)},moveSelectedShapeChild(m,p){return n?n.moveSelectedShapeChild(m,p):ee(u)},removeSelectedShapeChild(m){return n?n.removeSelectedShapeChild(m):ee(u)},removeSelected(){return n?n.removeSelectedAdvancedOoxml():ee(u)},destroy(){d(),l.clear(),a=tm()}}}function ab(e){return e?.selection??null}function Zj(e){return ab(e.editor)?.resolvePositionHitEvent?.(e)??e.event}function Gj(e){let t=ab(e.editor);if(!t?.handlePositionHit)return!1;let r=t.resolvePositionHitEvent?.(e)??e.event;return t.handlePositionHit({...e,event:r})}function lb(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function cb(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function db(e){return e==="web"||e==="paginated"?e:null}function ub(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function S7(e){return e.previousEditor!==e.nextEditor?"editor-instance":e.previousPreviewSourceIdentity!==e.previewSourceIdentity?"preview-source":cb(e.previousControllerNavigationMode)!==cb(e.controllerNavigationMode)?"controller-navigation-mode":db(e.previousFlowMode)!==db(e.flowMode)||ub(e.previousLayoutMode)!==ub(e.layoutMode)?"preview-mode":e.previousSyncViewportToEditor!==e.syncViewportToEditor?"sync-viewport-toggle":lb(e.previousExplicitAnchorPageNumber)!==lb(e.explicitAnchorPageNumber)?"explicit-anchor":null}import{resolveProjectionSelectionPageIndexes as Xj}from"@datalking/begonia-page-layout";function rm(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>0?t:null}function $j(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.trunc(e)):null}function pb(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>=0?t:null}function Yj(e,t){if(!e||typeof e!="object")return t;let r=e,o=rm(r.pageNumber),n=pb(r.pageIndex);return o!=null&&n!=null&&n!==o-1?null:o??(n!=null?n+1:t)}function Jj(e){if(!e||typeof e!="object")return null;let t=rm(e.anchorPageNumber),r=e.viewportAnchor==null?t:Yj(e.viewportAnchor,t);return e.viewportAnchor!=null&&r==null||t!=null&&r!=null&&r!==t?null:t??r}function Tn(e,t){let r=new Set([...e].map(o=>rm(o)).filter(o=>o!=null));return!t||t.length===0?[...r].sort((o,n)=>o-n):t.filter(o=>r.has(o))}function mb(e,t){if(!t||t.length===0)return[];let r=new Map(t.map((o,n)=>[o,n]));return Tn(e??[],t).flatMap(o=>{let n=r.get(o);return n==null?[]:[n]})}function Qj(e,t){return Tn(e.flatMap(r=>{let o=pb(r),n=o==null?null:t[o]??null;return n==null?[]:[n]}),t)}function y7(e){let t=e.projection?.pages.map(s=>s.pageNumber)??null,r=Tn(e.selectionPageNumbers??[],t),o=new Set(Tn(e.pinnedPageNumbers??[],t));for(let s of r)o.add(s);if(!e.projection||e.sourceMatchesEditorDocument===!1){let s=Tn(o,t);return s.length>0?s:void 0}let n=Jj(e.previewNavigationRequest),i=r.length>0?Tn(n==null?o:[...o,n],t):Qj(Xj(e.projection,e.selection,{docSize:$j(e.documentSize),preferredPageIndexes:mb(e.pinnedPageNumbers,t),extraPageIndexes:n==null?[]:mb([n],t)}),t??[]);return i.length>0?i:void 0}function eV(e){let t=xg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,e.syncViewportToEditor?e.lastAppliedViewport??null:e.trackingState.editorViewport,e.trackingState.editorViewportRequestKey,e.modeOptions);return t?{viewport:t,cause:"controller-viewport-request"}:null}function om(e,t){return t?fb({editorViewport:null,editorViewportRequestKey:null,previewNavigationRequestKey:null,previewNavigationRequest:null},e,t):{editorViewport:re(e?.viewport??null),editorViewportRequestKey:Ne(e?.viewportRequestKey??null),previewNavigationRequestKey:Ne(e?.previewNavigationRequest?.requestKey??null),previewNavigationRequest:be(e?.previewNavigationRequest??null)}}function fb(e,t,r){let o=Bt(t,r),n=xt(t,r),i=t?.viewport!=null,s=t?.previewNavigationRequest!=null;return{editorViewport:o?re(o):i?re(e.editorViewport):null,editorViewportRequestKey:o?Ne(t?.viewportRequestKey??null):i?Ne(e.editorViewportRequestKey):null,previewNavigationRequestKey:n?Ne(n.requestKey):s?Ne(e.previewNavigationRequestKey):null,previewNavigationRequest:n?be(n):s?be(e.previewNavigationRequest):null}}function wb(e){let t=xt(e.editorState,e.modeOptions),r=bg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,Mr(t,e.trackingState.previewNavigationRequest)?e.trackingState.previewNavigationRequestKey:null,e.modeOptions),o=eV(e),n=o?.viewport??null,i=fb(e.trackingState,e.editorState,e.modeOptions);return n&&(i.editorViewport=re(n),i.editorViewportRequestKey=Ne(e.editorState?.viewportRequestKey??null)),{previewNavigationRequest:r,externalViewportRequest:n,resetCause:r?"preview-navigation-request":o?.cause??null,shouldResetViewport:r!=null||n!=null,nextTrackingState:i}}function tV(e){let t=Ic(e.editorState,e.explicitFlowMode),r=kg(e.editorState,e.explicitLayoutMode,t);return{flowMode:t,layoutMode:r}}function E7(e){let t=tV(e),{flowMode:r,layoutMode:o}=t;return{scale:Cg(e.editorState,e.explicitScale),flowMode:r,layoutMode:o,modeOptions:t,anchorPageNumber:Pg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),initialViewportAnchor:Rg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),viewportRequestKey:Tg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),acknowledgementRequestKey:Bg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t)}}function gb(e){if(!e.syncViewportToEditor)return null;let t=Yt(e.viewport,{flowMode:e.controllerFlowMode,layoutMode:e.controllerLayoutMode});if(!t||e.controllerFlowMode&&!_o(t,e.controllerFlowMode)||e.controllerLayoutMode&&!Uo(t,e.controllerLayoutMode)||e.controllerFlowMode&&e.controllerLayoutMode&&!to(t,e.controllerFlowMode,e.controllerLayoutMode))return null;let r=e.controllerFlowMode??t.flowMode,o=e.controllerLayoutMode??t.layoutMode,n=Yt(e.lastAppliedViewport,{flowMode:r,layoutMode:o}),i=Yt(e.controllerViewport,{flowMode:r,layoutMode:o});return Kn(t,n)||Kn(t,i)?null:t}function Sb(e){return e?{requestKey:e.requestKey,viewportResetVersion:e.viewportResetVersion}:null}function rV(e,t){return e?.requestKey===t?.requestKey&&e?.viewportResetVersion===t?.viewportResetVersion}function oV(e,t){return nt(e.editorViewport,t.editorViewport)&&e.editorViewportRequestKey===t.editorViewportRequestKey&&e.previewNavigationRequestKey===t.previewNavigationRequestKey&&Mr(e.previewNavigationRequest,t.previewNavigationRequest)}function vb(e,t){return e.viewportHydrated===t.viewportHydrated&&e.viewportResetVersion===t.viewportResetVersion&&nt(e.lastAppliedViewport,t.lastAppliedViewport)&&e.lastResetCause===t.lastResetCause&&oV(e.trackingState,t.trackingState)&&rV(e.pendingAcknowledgement,t.pendingAcknowledgement)}function nV(e,t){return e==null?null:{requestKey:e,viewportResetVersion:t}}function iV(e){return e.acknowledgementRequestKey!=null?nV(e.acknowledgementRequestKey,e.viewportResetVersion):e.shouldResetViewport?null:e.current!=null&&e.compatiblePreviewNavigationRequestKey===e.current.requestKey?Sb(e.current):null}function j7(e,t){return{viewportHydrated:!1,viewportResetVersion:0,lastAppliedViewport:null,lastResetCause:null,trackingState:om(e,t),pendingAcknowledgement:null}}function V7(e,t,r=null,o){return{viewportHydrated:!1,viewportResetVersion:e.viewportResetVersion+1,lastAppliedViewport:null,lastResetCause:r,trackingState:om(t,o),pendingAcknowledgement:null}}function L7(e){let t=wb({editorState:e.editorState,explicitAnchorPageNumber:e.explicitAnchorPageNumber,viewportHydrated:e.state.viewportHydrated,controllerNavigationMode:e.controllerNavigationMode,modeOptions:e.modeOptions,syncViewportToEditor:e.syncViewportToEditor,lastAppliedViewport:e.state.lastAppliedViewport,trackingState:e.state.trackingState}),r=t.shouldResetViewport?e.state.viewportResetVersion+1:e.state.viewportResetVersion,o=xt(e.editorState,e.modeOptions)?.requestKey??null,n={viewportHydrated:t.shouldResetViewport?!1:e.state.viewportHydrated,viewportResetVersion:r,lastAppliedViewport:t.shouldResetViewport?null:re(e.state.lastAppliedViewport),lastResetCause:t.shouldResetViewport?t.resetCause:e.state.lastResetCause,trackingState:t.nextTrackingState,pendingAcknowledgement:iV({current:e.state.pendingAcknowledgement,acknowledgementRequestKey:e.acknowledgementRequestKey,compatiblePreviewNavigationRequestKey:o,shouldResetViewport:t.shouldResetViewport,viewportResetVersion:r})};return{nextState:n,changed:!vb(e.state,n)}}function F7(e){if(e.observedViewportResetVersion!==e.state.viewportResetVersion)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let t=re(e.viewport);if(!t)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let r=Bt({viewport:t},e.modeOptions);if(!r)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let o=gb({viewport:r,lastAppliedViewport:e.state.lastAppliedViewport,controllerViewport:e.controllerViewport,controllerFlowMode:e.controllerFlowMode,controllerLayoutMode:e.controllerLayoutMode,syncViewportToEditor:e.syncViewportToEditor}),n=Sb(e.state.pendingAcknowledgement),i=xt({previewNavigationRequest:e.previewNavigationRequest??null},e.modeOptions)?.requestKey??null,s=n!=null&&n.viewportResetVersion===e.state.viewportResetVersion&&i===n.requestKey,a={viewportHydrated:!0,viewportResetVersion:e.state.viewportResetVersion,lastAppliedViewport:re(r),lastResetCause:e.state.lastResetCause,trackingState:e.state.trackingState,pendingAcknowledgement:s?null:n};return{nextState:a,controllerViewportPatch:o,acknowledgementRequestKey:s?n.requestKey:null,changed:!vb(e.state,a)}}export{Wn as DEFAULT_BROWSER_ZOOM_PERCENT,Vo as applyBrowserInlineFormatPatch,rc as browserViewportStateHasExplicitModeConflict,om as captureBrowserPaginatedPreviewTrackingState,go as captureBrowserSurfaceSelectionRebaseTarget,re as cloneBrowserViewportState,Uj as createBrowserAdvancedOoxmlInspectorController,Yu as createBrowserEditor,jj as createBrowserEditorBackendAdapter,bj as createBrowserEditorController,ci as createBrowserEditorHost,em as createBrowserEditorMountController,uo as createBrowserEditorOverlayHost,vI as createBrowserEditorOverlayHostFromController,SI as createBrowserEditorSessionHostFromController,Vj as createBrowserEditorUiController,Js as createBrowserEditorUiFromController,hn as createBrowserEditorUiHost,hI as createBrowserEditorUiHostFromController,Xs as createBrowserPaginatedPreviewSelectionActionsV1,j7 as createBrowserPaginatedPreviewSessionState,zd as createBrowserSelectionCapture,yl as createSurfaceSelectionAdapter,Yt as fillBrowserViewportStateModes,Gj as handleBrowserPaginatedPreviewPositionHit,tc as hasFreshBrowserViewportRequest,_o as isBrowserViewportStateCompatibleWithFlowMode,Uo as isBrowserViewportStateCompatibleWithLayoutMode,to as isBrowserViewportStateCompatibleWithModes,Mc as normalizeBrowserPreviewControllerNavigationMode,ba as normalizeBrowserSurfaceReviewSelection,Go as normalizeBrowserViewportAnchor,$t as normalizeBrowserViewportPageAddress,Ne as normalizeBrowserViewportRequestKey,ht as normalizeBrowserZoomPercent,Sc as readBrowserEditorAutomation,wc as readBrowserEditorDocument,gc as readBrowserEditorView,ur as readBrowserZoomPercent,Ri as readSelectedAdvancedOoxmlRecord,vc as replaceBrowserEditorDocument,Cn as replaceBrowserSurfaceDocumentPreservingSelection,V7 as resetBrowserPaginatedPreviewSessionState,_I as resolveBrowserCommentReplayTarget,Es as resolveBrowserCommentWriteReason,MO as resolveBrowserEditorContextMenuContextAtPoint,io as resolveBrowserEditorPositionAtPoint,td as resolveBrowserEditorUiController,ir as resolveBrowserInlineFormatDisabledReason,Bg as resolveBrowserPaginatedPreviewAcknowledgementRequestKey,Pg as resolveBrowserPaginatedPreviewAnchorPageNumber,wK as resolveBrowserPaginatedPreviewControllerSyncState,gb as resolveBrowserPaginatedPreviewControllerViewportPatch,xg as resolveBrowserPaginatedPreviewExternalViewportRequest,Ic as resolveBrowserPaginatedPreviewFlowMode,kg as resolveBrowserPaginatedPreviewLayoutMode,S7 as resolveBrowserPaginatedPreviewLifecycleResetCause,tV as resolveBrowserPaginatedPreviewModeOptions,bg as resolveBrowserPaginatedPreviewNavigationRequest,y7 as resolveBrowserPaginatedPreviewPinnedPageNumbers,Zj as resolveBrowserPaginatedPreviewPositionHitEvent,wb as resolveBrowserPaginatedPreviewResetPlan,Cg as resolveBrowserPaginatedPreviewScale,L7 as resolveBrowserPaginatedPreviewSessionUpdate,hg as resolveBrowserPaginatedPreviewSourceBinding,E7 as resolveBrowserPaginatedPreviewViewModel,Rg as resolveBrowserPaginatedPreviewViewportAnchor,Ig as resolveBrowserPaginatedPreviewViewportAnchorFromHit,F7 as resolveBrowserPaginatedPreviewViewportObservation,Tg as resolveBrowserPaginatedPreviewViewportRequestKey,ut as resolveBrowserPreservedRangeTargetSelection,ga as resolveBrowserSurfaceProjectionMode,Q as resolveBrowserTextTargetSelection,Ae as resolveBrowserTextTargetSelectionWithExpectedText,xt as resolveCompatibleBrowserPreviewNavigationRequest,Bt as resolveCompatibleBrowserPreviewViewport,Xo as resolveCompatibleBrowserPreviewViewportAnchor,Sr as resolveProjectedSelectionRebaseRange,vi as resolveProjectedSelectionTrackedChangeIds,Ee as resolveSelectionInfo,Ci as restoreBrowserSurfaceSelectionFromRebaseTarget,mi as restoreTrackedCommentSelectionAfterReviewMutation,vg as sameBrowserPaginatedPreviewViewportRequest,sK as sameBrowserPaginatedPreviewViewportSyncState,Zo as sameBrowserViewportAnchor,Ps as sameBrowserViewportRequestKey,nt as sameBrowserViewportState,Kn as sameBrowserViewportStateForControllerSync,no as selectBrowserCommentTarget,El as selectBrowserTextTarget};
1
+ import{createDocumentSurface as bj}from"@datalking/begonia-engine";import{createOoxmlFamilyEnvelope as gm}from"@datalking/begonia-engine";var Hi="ald:advanced-ooxml-nodeview-action";function Lr(e){return typeof e=="object"&&e!==null}function nm(e){if(!Lr(e)||typeof e.family!="string"||typeof e.action!="string"||typeof e.objectId!="string")return!1;switch(e.action){case"replace-math-model":return e.family==="math"&&Lr(e.model);case"set-math-plain-text":return e.family==="math"&&typeof e.text=="string"&&(e.displayMode==="inline"||e.displayMode==="block");case"replace-chart-model":return e.family==="chart"&&Lr(e.model);case"replace-shape-model":return e.family==="shape"&&Lr(e.model);case"apply-math-edits":return e.family==="math"&&Lr(e.model)&&Array.isArray(e.edits);case"apply-chart-edits":return e.family==="chart"&&Lr(e.model)&&Array.isArray(e.edits);case"apply-shape-edits":return e.family==="shape"&&Lr(e.model)&&Array.isArray(e.edits);case"remove-advanced-ooxml":return e.family==="math"||e.family==="chart"||e.family==="shape";default:return!1}}function rr(e,t){e.dispatchEvent(new CustomEvent(Hi,{bubbles:!0,cancelable:!0,detail:t}))}function yb(e,t){e.disabled=!t,e.style.opacity=t?"1":"0.65",e.style.cursor=t?"pointer":"default"}function bb(e,t){e.textContent=t?"Local subtree edits pending. Leave this card or press Cmd/Ctrl+Enter to apply.":"Auto-applies when you leave this card. Apply is still available for an immediate commit.",e.style.color=t?"#0f766e":"#64748b",e.style.fontWeight=t?"600":"400"}function ho(e){let t=!1,r=!1,o=null,n=()=>{o!==null&&(window.clearTimeout(o),o=null)},i=()=>{yb(e.applyButton,r),bb(e.status,r)},s=()=>{if(n(),t||!r)return!1;try{let d=e.onCommit();return r=!1,i(),d}catch(d){throw i(),d}},a=()=>{t||!r||(n(),o=window.setTimeout(()=>{o=null,e.root.contains(document.activeElement)||s()},0))},l=()=>{a()},c=d=>{r&&(d.metaKey||d.ctrlKey)&&d.key==="Enter"&&(d.preventDefault(),s())};return e.root.addEventListener("focusout",l),e.root.addEventListener("keydown",c),i(),{destroy(){t=!0,n(),e.root.removeEventListener("focusout",l),e.root.removeEventListener("keydown",c)},flush:s,markDirty(){t||r||(r=!0,i())},reset(){n(),r=!1,i()}}}function Ft(e,t){return Object.assign(e.style,t),e}function yo(e,t=!1){let r=document.createElement(e);return r.contentEditable="false",Ft(r,{display:t?"inline-flex":"grid",gap:"8px",padding:"10px",border:"1px solid #cbd5e1",borderRadius:"14px",background:"#f8fafc",margin:t?"0 4px":"8px 0",minWidth:t?"280px":"100%",boxSizing:"border-box",verticalAlign:"middle"}),r}function bo(e,t){let r=document.createElement("div");Ft(r,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px"});let o=document.createElement("strong");o.textContent=e,Ft(o,{fontSize:"12px",color:"#0f172a"});let n=document.createElement("span");return n.textContent=t,Ft(n,{fontSize:"11px",fontWeight:"600",color:"#475569",background:"#e2e8f0",borderRadius:"999px",padding:"2px 8px"}),r.append(o,n),{header:r,heading:o}}function Bo(){let e=document.createElement("div");return Ft(e,{fontSize:"11px",color:"#64748b"}),e}function Fr(e){let t=document.createElement("section");Ft(t,{display:"grid",gap:"8px",padding:"10px",borderRadius:"12px",background:"#ffffff",border:"1px solid #e2e8f0"});let r=document.createElement("div");return r.textContent=e,Ft(r,{fontSize:"11px",fontWeight:"700",letterSpacing:"0.08em",textTransform:"uppercase",color:"#475569"}),t.append(r),{section:t,title:r}}function zt(e){let t=document.createElement("div");return t.textContent=e,Ft(t,{fontSize:"11px",color:"#64748b"}),t}function or(){let e=document.createElement("div");return Ft(e,{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}),e}function _e(e,t="default"){let r=document.createElement("button");return r.type="button",r.textContent=e,Ft(r,{padding:"6px 12px",borderRadius:"999px",border:t==="danger"?"1px solid #fecaca":"1px solid #99f6e4",background:t==="danger"?"#fff1f2":"#f0fdfa",color:t==="danger"?"#be123c":"#0f766e",fontSize:"12px",fontWeight:"600",cursor:"pointer"}),r}function xo(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement}import{listOoxmlChartAxisIds as im,listOoxmlChartSeriesIds as sm}from"@datalking/begonia-engine";function pe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Bb(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function br(e){return new Set(e).size===e.length}function kn(e,t){let r=new Set(t),o=e.filter(a=>r.has(a)),n=new Set(e),i=t.filter(a=>n.has(a));if(!Bb(o,i))return!1;let s=t.findIndex(a=>!n.has(a));return s===-1||t.slice(s).every(a=>!n.has(a))}function xb(e,t){if(pe(e.series,t.series))return[];let r=sm(e),o=sm(t);if(!br(r)||!br(o)||!kn(r,o))return[{type:"set-series-list",series:[...t.series]}];let n=new Map(e.series.map((a,l)=>[r[l],a])),i=new Map(t.series.map((a,l)=>[o[l],a])),s=[];for(let a=r.length-1;a>=0;a-=1){let l=r[a];i.has(l)||s.push({type:"remove-series",target:l})}return o.forEach(a=>{let l=i.get(a),c=n.get(a);if(!c){s.push({type:"append-series",series:l});return}pe(c,l)||s.push({type:"set-series",target:a,series:l})}),s}function Cb(e,t){if(pe(e.axes,t.axes))return[];let r=im(e),o=im(t);if(!br(r)||!br(o)||!kn(r,o))return[{type:"set-axes",axes:[...t.axes]}];let n=new Map(e.axes.map((a,l)=>[r[l],a])),i=new Map(t.axes.map((a,l)=>[o[l],a])),s=[];for(let a=r.length-1;a>=0;a-=1){let l=r[a];i.has(l)||s.push({type:"remove-axis",axisId:l})}return o.forEach(a=>{let l=i.get(a),c=n.get(a);(!c||!pe(c,l))&&s.push({type:"upsert-axis",axisId:a,axis:l})}),s}function am(e,t){if(pe(e,t))return[];let r=[];return(e.title!==t.title||e.chartType!==t.chartType||e.subtitle!==t.subtitle)&&r.push({type:"set-metadata",title:t.title,chartType:t.chartType,subtitle:t.subtitle}),pe(e.textBody,t.textBody)||r.push({type:"set-text-body",textBody:t.textBody}),pe(e.plotArea,t.plotArea)||r.push({type:"set-plot-area",plotArea:t.plotArea}),pe(e.legend,t.legend)||r.push({type:"set-legend",legend:t.legend}),r.push(...Cb(e,t)),r.push(...xb(e,t)),r}import{Schema as Pb}from"prosemirror-model";import{EditorState as Rb}from"prosemirror-state";import{EditorView as Tb}from"prosemirror-view";var kb=["display:grid","gap:8px","padding:10px","border:1px solid #dbe3ea","border-radius:12px","background:#f8fafc"].join(";"),Eb=["font-size:11px","font-weight:700","letter-spacing:0.08em","text-transform:uppercase","color:#334155"].join(";"),Mb=["display:grid","gap:8px","padding-left:8px"].join(";"),Ib=["display:grid","gap:4px"].join(";"),Ab=["font-size:11px","font-weight:600","letter-spacing:0.06em","text-transform:uppercase","color:#64748b"].join(";"),Nb=["min-height:36px","padding:8px 10px","border:1px solid #cbd5e1","border-radius:10px","background:#ffffff","font-size:12px","color:#0f172a","white-space:pre-wrap"].join(";"),Db=["display:grid","gap:10px","outline:none"].join(";"),kt=new Pb({nodes:{doc:{content:"entry*"},section:{group:"entry",content:"entry*",attrs:{key:{default:""},label:{default:"Section"}},parseDOM:[{tag:"section[data-ald-structured-section]",getAttrs:e=>{let t=e;return{key:t.dataset.key??"",label:t.dataset.label??"Section"}}}],toDOM(e){return["section",{"data-ald-structured-section":"true","data-key":e.attrs.key,"data-label":e.attrs.label,style:kb},["div",{style:Eb},e.attrs.label],["div",{style:Mb},0]]}},field:{group:"entry",content:"text*",marks:"",parseDOM:[{tag:"div[data-ald-structured-field]",getAttrs:e=>{let t=e;return{key:t.dataset.key??"",label:t.dataset.label??"Field"}}}],toDOM(e){return["div",{"data-ald-structured-field":"true","data-key":e.attrs.key,"data-label":e.attrs.label,style:Ib},["div",{style:Ab},e.attrs.label],["div",{style:Nb},0]]}},text:{}}});function Ob(e){return kt.nodes.field.create({key:e.key,label:e.label},e.value?kt.text(e.value):void 0)}function jb(e){let t=e.children.map(Oa);return kt.nodes.section.create({key:e.key,label:e.label},t)}function Oa(e){return e.type==="field"?Ob(e):jb(e)}function Vb(e){return kt.nodes.doc.create(null,e.map(Oa))}function lm(e){return e.content.content.map(t=>um(t)).filter(t=>t!==null)}function um(e){return e.type===kt.nodes.field?{type:"field",key:String(e.attrs.key??""),label:String(e.attrs.label??"Field"),value:e.textContent}:e.type===kt.nodes.section?{type:"section",key:String(e.attrs.key??""),label:String(e.attrs.label??"Section"),children:e.content.content.map(t=>um(t)).filter(t=>t!==null)}:null}function cm(e){return Rb.create({schema:kt,doc:Vb(e)})}function Lb(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1)if(t.node(r).type===kt.nodes.section)return t.end(r)-1;return e.doc.content.size}function Fb(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1){let o=t.node(r);if(o.type===kt.nodes.field||o.type===kt.nodes.section)return{from:t.before(r),to:t.before(r)+o.nodeSize}}return null}function dm(e){let{$from:t}=e.selection,r=[],o=e.doc;for(let n=1;n<=t.depth;n+=1){if(t.node(n).type!==kt.nodes.section)continue;let i=String(t.node(n).attrs.key??"").trim();i.length>0&&r.push(i),o=t.node(n)}return{sectionKeys:r,containerKey:r[r.length-1]??null,childKeys:o.content.content.map(n=>String(n.attrs.key??"").trim()).filter(n=>n.length>0)}}function zb(e){Object.assign(e.style,{display:"grid",gap:"10px",padding:"10px",borderRadius:"12px",border:"1px solid #dbe3ea",background:"#ffffff",minHeight:"160px",boxSizing:"border-box",overflow:"auto"})}function w(e,t,r=""){return{type:"field",key:e,label:t,value:r}}function T(e,t,r=[]){return{type:"section",key:e,label:t,children:[...r]}}function Co(e,t,r={}){zb(e);let o,n=()=>{r.onSelectionChange?.(dm(o.state))};return o=new Tb(e,{dispatchTransaction(i){let s=o.state.apply(i);o.updateState(s),i.docChanged&&r.onChange?.({entries:lm(s.doc)}),(i.docChanged||i.selectionSet)&&n()},state:cm(t),attributes:{style:Db,class:"ald-advanced-ooxml-subtree-editor"}}),n(),{dom:e,appendEntry(i){let s=Oa(i),a=Lb(o.state);o.dispatch(o.state.tr.insert(a,s)),o.focus()},destroy(){o.destroy()},focus(){o.focus()},readEntries(){return lm(o.state.doc)},readSelection(){return dm(o.state)},removeSelectedEntry(){let i=Fb(o.state);return i?(o.dispatch(o.state.tr.delete(i.from,i.to)),o.focus(),!0):!1},setEntries(i){o.updateState(cm(i)),n()}}}import{normalizeOoxmlChartModel as qb}from"@datalking/begonia-engine";function z(e){let t=e.trim();return t.length>0?t:null}function oe(e){let t=e.trim();if(!t)return null;let r=Number(t);return Number.isFinite(r)?r:null}function fe(e){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:null}function Pe(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Re(e){return e==null?"":JSON.stringify(e,null,2)}function C(e,t){let r=e.find(o=>o.type==="field"&&o.key===t);return r?.type==="field"?r.value:""}function pt(e,t){return e.filter(r=>r.type==="section"&&r.key===t)}function ja(e,t){return pt(e,t)[0]??null}function mm(e){return e.type==="field"?e.value.trim().length>0:e.children.some(t=>mm(t))}function Hb(e){return e.some(t=>mm(t))}function Te(e,t){let r=ja(e,t);return r&&Hb(r.children)?r:null}function Po(e,t,r){let o=r?.paragraphs?.length?r.paragraphs:r?.plainText?[r.plainText]:[];return T(e,t,(o.length>0?o:[""]).map(n=>w("paragraph","Paragraph",n)))}function qi(e){if(!e)return null;let t=e.children.filter(r=>r.type==="field"&&r.key==="paragraph").map(r=>r.value);return t.length===0?null:{paragraphs:t,plainText:t.join(`
2
+ `)}}function Wi(e,t){return T(e,t,[w("paragraph","Paragraph","")])}function Wb(e){return T("marker","Marker",[w("symbol","Symbol",e.marker?.symbol??""),w("size","Size",e.marker?.size==null?"":String(e.marker.size))])}function Kb(e){return T("data-labels","Data Labels",[w("show-value","Show Value",e.dataLabels?.showValue==null?"":String(e.dataLabels.showValue)),w("show-category","Show Category",e.dataLabels?.showCategory==null?"":String(e.dataLabels.showCategory)),w("show-series-name","Show Series Name",e.dataLabels?.showSeriesName==null?"":String(e.dataLabels.showSeriesName)),w("show-percentage","Show Percentage",e.dataLabels?.showPercentage==null?"":String(e.dataLabels.showPercentage)),w("position","Position",e.dataLabels?.position??""),w("separator","Separator",e.dataLabels?.separator??"")])}function _b(e){return T("series","Series",[w("id","Series Id",e.id??""),w("order","Order",e.order==null?"":String(e.order)),w("name","Name",e.name??""),w("categories","Categories",e.categories.join(", ")),w("values","Values",e.values.map(t=>t==null?"":String(t)).join(", ")),w("color","Color",e.color??""),w("smooth","Smooth",e.smooth==null?"":String(e.smooth)),w("explosion","Explosion",e.explosion==null?"":String(e.explosion)),Wb(e),Kb(e)])}function Ub(e){return T("axis","Axis",[w("id","Axis Id",e.id??""),w("kind","Kind",e.kind??""),w("title","Title",e.title??""),w("format-code","Format Code",e.formatCode??""),w("orientation","Orientation",e.orientation??""),w("visible","Visible",e.visible==null?"":String(e.visible)),w("minimum","Minimum",e.minimum==null?"":String(e.minimum)),w("maximum","Maximum",e.maximum==null?"":String(e.maximum)),w("major-unit","Major Unit",e.majorUnit==null?"":String(e.majorUnit)),w("minor-unit","Minor Unit",e.minorUnit==null?"":String(e.minorUnit)),w("crosses-at","Crosses At",e.crossesAt==null?"":String(e.crossesAt)),w("major-gridlines","Major Gridlines",e.majorGridlines==null?"":String(e.majorGridlines)),w("minor-gridlines","Minor Gridlines",e.minorGridlines==null?"":String(e.minorGridlines))])}function Zb(e){return T("legend","Legend",[w("visible","Visible",e.legend==null?"":String(e.legend.visible)),w("position","Position",e.legend?.position??""),w("overlay","Overlay",e.legend?.overlay==null?"":String(e.legend.overlay))])}function Gb(e){return T("plot-area","Plot Area",[w("stacked","Stacked",e.plotArea?.stacked==null?"":String(e.plotArea.stacked)),w("percent-stacked","Percent Stacked",e.plotArea?.percentStacked==null?"":String(e.plotArea.percentStacked)),w("vary-colors","Vary Colors",e.plotArea?.varyColors==null?"":String(e.plotArea.varyColors)),w("hole-size","Hole Size",e.plotArea?.holeSize==null?"":String(e.plotArea.holeSize))])}function Xb(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function $b(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>{let r=Number(t);return Number.isFinite(r)?r:null})}function Yb(e){return e.length>0?e:null}function Jb(e){let t=Te(e,"marker"),r=Te(e,"data-labels");return{id:z(C(e,"id")),order:oe(C(e,"order")),name:z(C(e,"name")),categories:Xb(C(e,"categories")),values:$b(C(e,"values")),color:z(C(e,"color")),marker:t?{symbol:z(C(t.children,"symbol"))??"unknown",size:oe(C(t.children,"size"))}:null,dataLabels:r?{showValue:fe(C(r.children,"show-value")),showCategory:fe(C(r.children,"show-category")),showSeriesName:fe(C(r.children,"show-series-name")),showPercentage:fe(C(r.children,"show-percentage")),position:z(C(r.children,"position")),separator:Yb(C(r.children,"separator"))}:null,smooth:fe(C(e,"smooth")),explosion:oe(C(e,"explosion"))}}function Qb(e){let t=C(e,"kind"),r=C(e,"orientation");return{id:z(C(e,"id")),kind:t==="category"||t==="value"||t==="series"||t==="date"?t:"unknown",title:z(C(e,"title")),formatCode:z(C(e,"format-code")),orientation:r==="minMax"||r==="maxMin"?r:null,visible:fe(C(e,"visible")),minimum:oe(C(e,"minimum")),maximum:oe(C(e,"maximum")),majorUnit:oe(C(e,"major-unit")),minorUnit:oe(C(e,"minor-unit")),crossesAt:oe(C(e,"crosses-at")),majorGridlines:fe(C(e,"major-gridlines")),minorGridlines:fe(C(e,"minor-gridlines"))}}function pm(e){return[w("title","Title",e.title??""),w("chart-type","Chart Type",e.chartType??""),w("subtitle","Subtitle",e.subtitle??""),Po("text-body","Text Body",e.textBody),Gb(e),...e.series.map(t=>_b(t)),...e.axes.map(t=>Ub(t)),Zb(e)]}function fm(e,t){let r=Te(e,"text-body"),o=Te(e,"plot-area"),n=Te(e,"legend");return qb({...t,title:z(C(e,"title")),chartType:z(C(e,"chart-type")),subtitle:z(C(e,"subtitle")),textBody:qi(r),plotArea:o?{stacked:fe(C(o.children,"stacked")),percentStacked:fe(C(o.children,"percent-stacked")),varyColors:fe(C(o.children,"vary-colors")),holeSize:oe(C(o.children,"hole-size"))}:null,series:pt(e,"series").map(i=>Jb(i.children)),axes:pt(e,"axis").map(i=>Qb(i.children)),legend:n?{visible:fe(C(n.children,"visible"))!==!1,position:z(C(n.children,"position"))??"unknown",overlay:fe(C(n.children,"overlay"))}:null},t.title??"Chart")}function eB(){return T("series","Series",[w("id","Series Id",""),w("order","Order",""),w("name","Name",""),w("categories","Categories",""),w("values","Values",""),w("color","Color",""),w("smooth","Smooth",""),w("explosion","Explosion",""),T("marker","Marker",[w("symbol","Symbol",""),w("size","Size","")]),T("data-labels","Data Labels",[w("show-value","Show Value",""),w("show-category","Show Category",""),w("show-series-name","Show Series Name",""),w("show-percentage","Show Percentage",""),w("position","Position",""),w("separator","Separator","")])])}function tB(){return T("axis","Axis",[w("id","Axis Id",""),w("kind","Kind","category"),w("title","Title",""),w("format-code","Format Code",""),w("orientation","Orientation",""),w("visible","Visible",""),w("minimum","Minimum",""),w("maximum","Maximum",""),w("major-unit","Major Unit",""),w("minor-unit","Minor Unit",""),w("crosses-at","Crosses At",""),w("major-gridlines","Major Gridlines",""),w("minor-gridlines","Minor Gridlines","")])}function rB(){return T("legend","Legend",[w("visible","Visible","true"),w("position","Position","right"),w("overlay","Overlay","")])}function oB(){return T("plot-area","Plot Area",[w("stacked","Stacked",""),w("percent-stacked","Percent Stacked",""),w("vary-colors","Vary Colors",""),w("hole-size","Hole Size","")])}function nB(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function iB(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function sB(e){return e==null}function wm(e={}){let t=nB(e.containerKey),r=iB(e.childKeys),o=n=>r.has(n);return t==="text-body"?[{label:"Paragraph",createEntry:()=>w("paragraph","Paragraph","")}]:sB(t)?[{label:"Series",createEntry:eB},{label:"Axis",createEntry:tB},...o("legend")?[]:[{label:"Legend",createEntry:rB}],...o("plot-area")?[]:[{label:"Plot Area",createEntry:oB}],...o("text-body")?[]:[{label:"Text Body",createEntry:()=>Wi("text-body","Text Body")}]]:[]}function Va(e){let t=String(e.attrs.label??"Chart"),r=String(e.attrs.text??""),o=gm("chart",{title:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=gm("chart",e.attrs.familyData,{label:t,text:r})??o;return{objectId:String(e.attrs.objectId??""),label:t,model:n.data.model??o.data.model,evidence:n.evidence}}function aB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function Sm(){return e=>{let t=e,r=yo("div"),{header:o,heading:n}=bo("Chart","chart"),i=Bo(),{section:s}=Fr("Native Subtree"),a=zt("Edit chart metadata, series, axes, legend, and plot area as a structured nested tree. Use insert buttons at the current subtree selection. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),l=or();l.style.justifyContent="flex-start";let c=_e("Remove Selected","danger"),d=aB(),u=or();u.style.justifyContent="space-between",u.style.alignItems="center";let m=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=_e("Apply"),f=_e("Remove Chart","danger");m.style.marginRight="auto",u.append(m,p,f),s.append(a,l,d,c),r.append(o,i,s,u);let g=null,v=(B,S)=>{l.replaceChildren(),wm({containerKey:B,childKeys:S}).forEach(b=>{let P=_e(b.label);P.addEventListener("click",()=>{k.appendEntry(b.createEntry())}),l.append(P)})},k=Co(d,[],{onChange(){g?.markDirty()},onSelectionChange(B){v(B.containerKey,B.childKeys)}});c.addEventListener("click",()=>{k.removeSelectedEntry()}),g=ho({applyButton:p,onCommit:()=>{let B=Va(t),S=fm(k.readEntries(),B.model),b=am(B.model,S);return b.length===0?!1:(rr(r,{family:"chart",action:"apply-chart-edits",objectId:B.objectId,model:S,edits:b}),!0)},root:r,status:m});let h=B=>{t=B;let S=Va(B);n.textContent=S.label,i.textContent=`${S.evidence.chartType??"chart"} | ${S.evidence.seriesCount} series | ${S.evidence.axisCount} axes`,g?.reset(),k.setEntries(pm(S.model))};return p.addEventListener("click",()=>{g?.flush()}),f.addEventListener("click",()=>{g?.reset();let B=Va(t);rr(r,{family:"chart",action:"remove-advanced-ooxml",objectId:B.objectId})}),h(e),{dom:r,destroy(){g?.destroy(),k.destroy()},update(B){return B.type!==t.type?!1:(h(B),!0)},stopEvent(B){return xo(B.target)||B.target instanceof Node&&d.contains(B.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as Bm,normalizeOoxmlMathModel as LB}from"@datalking/begonia-engine";function vm(e,t){if(pe(e,t))return[];if(e.root.type==="text"&&t.root.type==="text"){let r=e.root.value,o=t.root.value;return r!==o?[{type:"set-plain-text",text:o,displayMode:t.displayMode}]:e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[]}return t.root.type==="text"?[{type:"set-plain-text",text:t.root.value,displayMode:t.displayMode}]:pe(e.root,t.root)&&e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[{type:"replace-model",model:t}]}import{normalizeOoxmlMathModel as VB}from"@datalking/begonia-engine";import{createOoxmlMathTextNode as lB}from"@datalking/begonia-engine";var cB=new Set(["numerator","denominator","body","degree","base","superscript-slot","subscript-slot","lower","upper","name","argument","matrix-cell","equation-row"]);function La(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function hm(e){let t=La(e);return t==null||cB.has(t)}function Fa(e){return lB(e)}function za(){return Fa("")}function dB(e=""){return w("text","Text",e)}function ue(e,t){return T(e,t,[dB()])}function ym(e){throw new Error(`Unsupported math node type: ${JSON.stringify(e)}.`)}function ke(e){return hm(e)}function uB(){return T("fraction","Fraction",[ue("numerator","Numerator"),ue("denominator","Denominator")])}function mB(){return T("radical","Radical",[ue("body","Body"),T("degree","Degree",[])])}function pB(){return T("superscript","Superscript",[ue("base","Base"),ue("superscript-slot","Superscript")])}function fB(){return T("subscript","Subscript",[ue("base","Base"),ue("subscript-slot","Subscript")])}function wB(){return T("subsup","Subscript and Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function gB(){return T("preSubSup","Pre-Sub/Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function SB(){return T("matrix","Matrix",[T("matrix-row","Row",[T("matrix-cell","Cell",[w("text","Text","")])])])}function vB(){return T("equationArray","Equation Array",[T("equation-row","Row",[w("text","Text","")])])}function hB(){return T("delimiter","Delimiter",[w("begin","Begin Delimiter","("),w("end","End Delimiter",")"),ue("body","Body")])}function yB(){return T("operator","Operator",[w("operator-symbol","Operator","sum"),ue("body","Body"),T("lower","Lower",[]),T("upper","Upper",[])])}function bB(){return T("nary","N-ary Operator",[w("operator-symbol","Operator","prod"),ue("body","Body"),T("subscript-slot","Subscript",[]),T("superscript-slot","Superscript",[])])}function BB(){return T("limitLower","Lower Limit",[ue("base","Base"),ue("lower","Lower")])}function xB(){return T("limitUpper","Upper Limit",[ue("base","Base"),ue("upper","Upper")])}function CB(){return T("function","Function",[ue("name","Name"),ue("argument","Argument")])}function PB(){return T("accent","Accent",[w("accent-symbol","Accent","hat"),ue("body","Body")])}function RB(){return T("bar","Bar",[w("bar-position","Position","top"),ue("body","Body")])}function TB(){return T("box","Box",[w("border-box","Border Box","true"),ue("body","Body")])}function kB(){return T("groupCharacter","Group Character",[w("group-character","Character","_"),w("group-position","Position","bottom"),ue("body","Body")])}function EB(){return T("phantom","Phantom",[w("zero-width","Zero Width","false"),w("zero-ascent","Zero Ascent","false"),w("zero-descent","Zero Descent","false"),w("transparent","Transparent","true"),ue("body","Body")])}function MB(){return T("matrix-row","Row",[T("matrix-cell","Cell",[w("text","Text","")])])}function IB(){return T("matrix-cell","Cell",[w("text","Text","")])}function AB(){return T("equation-row","Row",[w("text","Text","")])}var NB=[{label:"Text",createEntry:()=>w("text","Text",""),supportsContainer:ke},{label:"Fraction",createEntry:uB,supportsContainer:ke},{label:"Radical",createEntry:mB,supportsContainer:ke},{label:"Superscript",createEntry:pB,supportsContainer:ke},{label:"Subscript",createEntry:fB,supportsContainer:ke},{label:"Sub+Sup",createEntry:wB,supportsContainer:ke},{label:"Pre-Sub/Sup",createEntry:gB,supportsContainer:ke},{label:"Matrix",createEntry:SB,supportsContainer:ke},{label:"Matrix Row",createEntry:MB,supportsContainer:e=>e==="matrix"},{label:"Matrix Cell",createEntry:IB,supportsContainer:e=>e==="matrix-row"},{label:"Equation Array",createEntry:vB,supportsContainer:ke},{label:"Equation Row",createEntry:AB,supportsContainer:e=>e==="equationArray"},{label:"Delimiter",createEntry:hB,supportsContainer:ke},{label:"Operator",createEntry:yB,supportsContainer:ke},{label:"N-ary",createEntry:bB,supportsContainer:ke},{label:"Lower Limit",createEntry:BB,supportsContainer:ke},{label:"Upper Limit",createEntry:xB,supportsContainer:ke},{label:"Function",createEntry:CB,supportsContainer:ke},{label:"Accent",createEntry:PB,supportsContainer:ke},{label:"Bar",createEntry:RB,supportsContainer:ke},{label:"Box",createEntry:TB,supportsContainer:ke},{label:"Group Char",createEntry:kB,supportsContainer:ke},{label:"Phantom",createEntry:EB,supportsContainer:ke}];function Ha(e={}){let t=La(e.containerKey);return NB.filter(r=>r.supportsContainer(t)).map(({label:r,createEntry:o})=>({label:r,createEntry:o}))}function ae(e,t){return ja(e,t)?.children??[]}function DB(e){let t=e.map(r=>jB(r)).filter(r=>r!==null);return t.length===0?za():t.length===1?t[0]:{type:"sequence",items:t}}function Ki(e){return e.length>0?ie(e):null}function OB(e){let t=pt(e,"matrix-cell").map(r=>ie(r.children));return t.length>0?t:[za()]}function jB(e){if(e.type==="field")return e.key==="text"?Fa(e.value):null;switch(e.key){case"fraction":return{type:"fraction",numerator:ie(ae(e.children,"numerator")),denominator:ie(ae(e.children,"denominator"))};case"radical":{let t=ae(e.children,"degree");return{type:"radical",body:ie(ae(e.children,"body")),degree:t.length>0?ie(t):null}}case"superscript":return{type:"superscript",base:ie(ae(e.children,"base")),superscript:ie(ae(e.children,"superscript-slot"))};case"subscript":return{type:"subscript",base:ie(ae(e.children,"base")),subscript:ie(ae(e.children,"subscript-slot"))};case"subsup":return{type:"subsup",base:ie(ae(e.children,"base")),subscript:ie(ae(e.children,"subscript-slot")),superscript:ie(ae(e.children,"superscript-slot"))};case"preSubSup":return{type:"preSubSup",base:ie(ae(e.children,"base")),subscript:ie(ae(e.children,"subscript-slot")),superscript:ie(ae(e.children,"superscript-slot"))};case"matrix":return{type:"matrix",rows:pt(e.children,"matrix-row").map(t=>OB(t.children))};case"equationArray":return{type:"equationArray",rows:pt(e.children,"equation-row").map(t=>ie(t.children))};case"delimiter":return{type:"delimiter",begin:z(C(e.children,"begin")),end:z(C(e.children,"end")),body:ie(ae(e.children,"body"))};case"operator":return{type:"operator",operator:z(C(e.children,"operator-symbol")),body:ie(ae(e.children,"body")),lower:Ki(ae(e.children,"lower")),upper:Ki(ae(e.children,"upper"))};case"nary":return{type:"nary",operator:z(C(e.children,"operator-symbol")),body:ie(ae(e.children,"body")),subscript:Ki(ae(e.children,"subscript-slot")),superscript:Ki(ae(e.children,"superscript-slot"))};case"limitLower":return{type:"limitLower",base:ie(ae(e.children,"base")),lower:ie(ae(e.children,"lower"))};case"limitUpper":return{type:"limitUpper",base:ie(ae(e.children,"base")),upper:ie(ae(e.children,"upper"))};case"function":return{type:"function",name:ie(ae(e.children,"name")),argument:ie(ae(e.children,"argument"))};case"accent":return{type:"accent",accent:z(C(e.children,"accent-symbol")),body:ie(ae(e.children,"body"))};case"bar":{let t=C(e.children,"bar-position").trim().toLowerCase();return{type:"bar",position:t==="top"||t==="bottom"?t:"unknown",body:ie(ae(e.children,"body"))}}case"box":return{type:"box",body:ie(ae(e.children,"body")),borderBox:fe(C(e.children,"border-box"))};case"groupCharacter":{let t=C(e.children,"group-position").trim().toLowerCase();return{type:"groupCharacter",character:z(C(e.children,"group-character")),position:t==="top"||t==="bottom"?t:"unknown",body:ie(ae(e.children,"body"))}}case"phantom":return{type:"phantom",body:ie(ae(e.children,"body")),zeroWidth:fe(C(e.children,"zero-width")),zeroAscent:fe(C(e.children,"zero-ascent")),zeroDescent:fe(C(e.children,"zero-descent")),transparent:fe(C(e.children,"transparent"))};default:return e.children.length>0?ie(e.children):null}}function ie(e){return DB(e)}function te(e){switch(e.type){case"sequence":return e.items.flatMap(t=>te(t));case"text":return[w("text","Text",e.value)];case"fraction":return[T("fraction","Fraction",[T("numerator","Numerator",te(e.numerator)),T("denominator","Denominator",te(e.denominator))])];case"radical":return[T("radical","Radical",[T("body","Body",te(e.body)),T("degree","Degree",e.degree?te(e.degree):[])])];case"superscript":return[T("superscript","Superscript",[T("base","Base",te(e.base)),T("superscript-slot","Superscript",te(e.superscript))])];case"subscript":return[T("subscript","Subscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript))])];case"subsup":return[T("subsup","Subscript and Superscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript)),T("superscript-slot","Superscript",te(e.superscript))])];case"preSubSup":return[T("preSubSup","Pre-Sub/Superscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript)),T("superscript-slot","Superscript",te(e.superscript))])];case"matrix":return[T("matrix","Matrix",e.rows.map(t=>T("matrix-row","Row",t.map(r=>T("matrix-cell","Cell",te(r))))))];case"equationArray":return[T("equationArray","Equation Array",e.rows.map(t=>T("equation-row","Row",te(t))))];case"delimiter":return[T("delimiter","Delimiter",[w("begin","Begin Delimiter",e.begin??""),w("end","End Delimiter",e.end??""),T("body","Body",te(e.body))])];case"operator":return[T("operator","Operator",[w("operator-symbol","Operator",e.operator??""),T("body","Body",te(e.body)),T("lower","Lower",e.lower?te(e.lower):[]),T("upper","Upper",e.upper?te(e.upper):[])])];case"nary":return[T("nary","N-ary Operator",[w("operator-symbol","Operator",e.operator??""),T("body","Body",te(e.body)),T("subscript-slot","Subscript",e.subscript?te(e.subscript):[]),T("superscript-slot","Superscript",e.superscript?te(e.superscript):[])])];case"limitLower":return[T("limitLower","Lower Limit",[T("base","Base",te(e.base)),T("lower","Lower",te(e.lower))])];case"limitUpper":return[T("limitUpper","Upper Limit",[T("base","Base",te(e.base)),T("upper","Upper",te(e.upper))])];case"function":return[T("function","Function",[T("name","Name",te(e.name)),T("argument","Argument",te(e.argument))])];case"accent":return[T("accent","Accent",[w("accent-symbol","Accent",e.accent??""),T("body","Body",te(e.body))])];case"bar":return[T("bar","Bar",[w("bar-position","Position",e.position),T("body","Body",te(e.body))])];case"box":return[T("box","Box",[w("border-box","Border Box",e.borderBox==null?"":String(e.borderBox)),T("body","Body",te(e.body))])];case"groupCharacter":return[T("groupCharacter","Group Character",[w("group-character","Character",e.character??""),w("group-position","Position",e.position),T("body","Body",te(e.body))])];case"phantom":return[T("phantom","Phantom",[w("zero-width","Zero Width",e.zeroWidth==null?"":String(e.zeroWidth)),w("zero-ascent","Zero Ascent",e.zeroAscent==null?"":String(e.zeroAscent)),w("zero-descent","Zero Descent",e.zeroDescent==null?"":String(e.zeroDescent)),w("transparent","Transparent",e.transparent==null?"":String(e.transparent)),T("body","Body",te(e.body))])]}return ym(e)}function qa(e){return[w("display-mode","Display Mode",e.displayMode),...te(e.root)]}function bm(e){let r=C(e,"display-mode").trim().toLowerCase()==="block"?"block":"inline",o=e.filter(n=>!(n.type==="field"&&n.key==="display-mode"));return VB({displayMode:r,root:ie(o)},"",r)}function Wa(e){let t=String(e.attrs.text??""),r=String(e.attrs.label??"Equation"),o=Bm("math",{plainText:t,displayMode:"inline"},{label:r,text:t}),n=Bm("math",e.attrs.familyData,{label:r,text:t})??o,i=LB(n.data,n.data.plainText??t,n.data.displayMode??"inline");return{objectId:String(e.attrs.objectId??""),label:r,model:i,evidence:n.evidence}}function FB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%",maxWidth:"720px"}),e}function xm(){return e=>{let t=e,r=yo("span",!0);Object.assign(r.style,{display:"inline-grid",width:"min(720px, 100%)",verticalAlign:"top"});let{header:o,heading:n}=bo("Equation","math"),i=Bo(),{section:s}=Fr("Native Subtree"),a=zt("Edit the equation as a nested ProseMirror tree. Insert structures into the selected slot. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),l=or();l.style.justifyContent="flex-start";let c=_e("Remove Selected","danger"),d=FB(),u=or();u.style.justifyContent="space-between",u.style.alignItems="center";let m=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=_e("Apply"),f=_e("Remove Equation","danger");m.style.marginRight="auto",u.append(m,p,f),s.append(a,l,d,c),r.append(o,i,s,u);let g=null,v=B=>{l.replaceChildren(),Ha({containerKey:B}).forEach(S=>{let b=_e(S.label);b.addEventListener("click",()=>{k.appendEntry(S.createEntry())}),l.append(b)})},k=Co(d,[],{onChange(){g?.markDirty()},onSelectionChange(B){v(B.containerKey)}});c.addEventListener("click",()=>{k.removeSelectedEntry()}),g=ho({applyButton:p,onCommit:()=>{let B=Wa(t),S=bm(k.readEntries()),b=vm(B.model,S);return b.length===0?!1:(rr(r,{family:"math",action:"apply-math-edits",objectId:B.objectId,model:S,edits:b}),!0)},root:r,status:m});let h=B=>{t=B;let S=Wa(B);n.textContent=S.label,i.textContent=`${S.evidence.displayMode} | root ${S.evidence.rootType} | ${S.evidence.structureCount} structures`,g?.reset(),k.setEntries(qa(S.model))};return p.addEventListener("click",()=>{g?.flush()}),f.addEventListener("click",()=>{g?.reset();let B=Wa(t);rr(r,{family:"math",action:"remove-advanced-ooxml",objectId:B.objectId})}),h(e),{dom:r,destroy(){g?.destroy(),k.destroy()},update(B){return B.type!==t.type?!1:(h(B),!0)},stopEvent(B){return xo(B.target)||B.target instanceof Node&&d.contains(B.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as qm,createOoxmlShapePreview as JB}from"@datalking/begonia-engine";function Cm(e){return e.map((t,r)=>t.id??`shape-child-${r+1}`)}function Pm(e,t){return pe({...e,children:[]},{...t,children:[]})}function Ka(e,t,r){for(let o=0;o<e.length;o+=1){let n=e[o],i=n.id?.trim(),s=e[o+1]?.id?.trim()??null;if(!i||r.has(i)||e[o+1]&&!s||(r.set(i,{child:n,parentId:t,beforeId:s}),!Ka(n.children,i,r)))return!1}return!0}function zB(e,t){return e.size===t.size&&[...t.keys()].every(r=>e.has(r))}function HB(e,t){return{...t,children:[...e.children]}}function Rm(e,t,r){t.forEach(o=>{let n=o.id?.trim();if(!n)return;let i=e.get(n);i&&!Pm(i.child,o)&&r.push({type:"set-child",target:n,child:HB(i.child,o)}),Rm(e,o.children,r)})}function Tm(e,t,r,o){let n=null;for(let i=t.length-1;i>=0;i-=1){let s=t[i],a=s.id?.trim();if(!a)continue;let l=e.get(a);l&&(l.parentId!==r||l.beforeId!==n)&&o.push({type:"move-child",target:a,parentTarget:r,beforeTarget:n}),Tm(e,s.children,a,o),n=a}}function qB(e,t){let r=new Map,o=new Map;if(!Ka(e,null,r)||!Ka(t,null,o)||!zB(r,o))return null;let n=[];return Rm(r,t,n),Tm(r,t,null,n),n}function WB(e,t,r){return t==null||r==null?[{type:"set-children",children:[...e]}]:[{type:"set-child",target:t,child:r}]}function km(e,t,r,o){if(pe(e,t))return[];let n=Cm(e),i=Cm(t);if(!br(n)||!br(i)||!kn(n,i))return WB(t,r,o);let s=new Map(e.map((c,d)=>[n[d],c])),a=new Map(t.map((c,d)=>[i[d],c])),l=[];for(let c=n.length-1;c>=0;c-=1){let d=n[c];a.has(d)||l.push({type:"remove-child",target:d})}return i.forEach(c=>{let d=a.get(c),u=s.get(c);if(!u){l.push(r==null?{type:"append-child",child:d}:{type:"append-child-to-parent",parentTarget:r,child:d});return}if(!Pm(u,d)){l.push({type:"set-child",target:c,child:d});return}l.push(...km(u.children,d.children,c,d))}),l}function Em(e,t){if(pe(e,t))return[];if(!pe(e.groupTransform,t.groupTransform))return[{type:"replace-model",model:t}];let r=[];(e.label!==t.label||e.shapeType!==t.shapeType||e.groupKind!==t.groupKind)&&r.push({type:"set-metadata",label:t.label,shapeType:t.shapeType,groupKind:t.groupKind}),(e.isWatermark??!1)!==(t.isWatermark??!1)&&r.push({type:"set-watermark",isWatermark:t.isWatermark??!1}),pe(e.textBody,t.textBody)||r.push({type:"set-text-body",paragraphs:t.textBody?.paragraphs?[...t.textBody.paragraphs]:[]}),pe(e.geometry,t.geometry)||r.push({type:"set-geometry",geometry:t.geometry}),pe(e.transform,t.transform)||r.push({type:"set-transform",transform:t.transform}),pe(e.fill,t.fill)||r.push({type:"set-fill",fill:t.fill}),pe(e.stroke,t.stroke)||r.push({type:"set-stroke",stroke:t.stroke}),pe(e.effects,t.effects)||r.push({type:"set-effects",effects:t.effects??null}),pe(e.anchor,t.anchor)||r.push({type:"set-anchor",anchor:t.anchor}),pe(e.connector,t.connector)||r.push({type:"set-connector",connector:t.connector}),pe(e.picture,t.picture)||r.push({type:"set-picture",picture:t.picture}),pe(e.wordArt,t.wordArt)||r.push({type:"set-word-art",wordArt:t.wordArt});let o=qB(e.children,t.children);return o?(r.push(...o),r):(r.push(...km(e.children,t.children,null,null)),r)}function Mm(e){return T("shape-child","Child Object",[w("kind","Kind",e.kind??""),w("id","Id",e.id??""),w("label","Label",e.label??""),Po("text-body","Text Body",e.textBody),_a(e.geometry),Ua(e.transform),Za(e.groupTransform??null),Ga(e.fill??null),Xa(e.stroke??null),$a(e.effects??null),Ya(e.connector),Ja(e.picture),Qa(e.wordArt),...e.children.map(t=>Mm(t))])}function _a(e){return T("geometry","Geometry",[w("preset","Preset",e?.preset??""),w("custom-path-count","Custom Path Count",e?.customPathCount==null?"":String(e.customPathCount)),w("adjustments","Adjustments",e?.adjustments.join(", ")??""),w("custom-geometry-json","Custom Geometry JSON",Re(e?.customGeometry??null))])}function Ua(e){return T("transform","Transform",[w("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),w("height-emu","Height (EMU)",e?.heightEmu==null?"":String(e.heightEmu)),w("offset-x-emu","Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),w("offset-y-emu","Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),w("rotation","Rotation",e?.rotation==null?"":String(e.rotation)),w("flip-h","Flip H",e?.flipH==null?"":String(e.flipH)),w("flip-v","Flip V",e?.flipV==null?"":String(e.flipV))])}function Za(e){return T("group-transform","Group Transform",[w("child-offset-x-emu","Child Offset X (EMU)",e?.childOffsetXEmu==null?"":String(e.childOffsetXEmu)),w("child-offset-y-emu","Child Offset Y (EMU)",e?.childOffsetYEmu==null?"":String(e.childOffsetYEmu)),w("child-width-emu","Child Width (EMU)",e?.childWidthEmu==null?"":String(e.childWidthEmu)),w("child-height-emu","Child Height (EMU)",e?.childHeightEmu==null?"":String(e.childHeightEmu))])}function Ga(e){return T("fill","Fill",[w("kind","Kind",e?.kind??""),w("color","Color",e?.color??""),w("secondary-color","Secondary Color",e?.secondaryColor??""),w("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),w("gradient-angle","Gradient Angle",e?.gradientAngle==null?"":String(e.gradientAngle)),w("gradient-path","Gradient Path",e?.gradientPath??""),w("pattern-preset","Pattern Preset",e?.patternPreset??""),w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("color-source-json","Color Source JSON",Re(e?.colorSource??null)),w("secondary-color-source-json","Secondary Color Source JSON",Re(e?.secondaryColorSource??null)),w("gradient-stops-json","Gradient Stops JSON",e?Re(e.gradientStops??[]):""),w("picture-fill-json","Picture Fill JSON",Re(e?.pictureFill??null))])}function Xa(e){return T("stroke","Stroke",[w("kind","Kind",e?.kind??""),w("color","Color",e?.color??""),w("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),w("dash","Dash",e?.dash??""),w("cap","Cap",e?.cap??""),w("join","Join",e?.join??""),w("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("compound","Compound",e?.compound??""),w("color-source-json","Color Source JSON",Re(e?.colorSource??null)),w("head-end-json","Head End JSON",Re(e?.headEnd??null)),w("tail-end-json","Tail End JSON",Re(e?.tailEnd??null))])}function $a(e){return T("effects","Effects",[w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("style-ref-color-source-json","Style Ref Color Source JSON",Re(e?.styleRefColorSource??null)),w("effect-nodes-json","Effect Nodes JSON",e?Re(e.effectNodes??[]):""),w("glow-json","Glow JSON",Re(e?.glow??null)),w("outer-shadow-json","Outer Shadow JSON",Re(e?.outerShadow??null)),w("inner-shadow-json","Inner Shadow JSON",Re(e?.innerShadow??null)),w("soft-edge-json","Soft Edge JSON",Re(e?.softEdge??null)),w("blur-json","Blur JSON",Re(e?.blur??null)),w("reflection-json","Reflection JSON",Re(e?.reflection??null)),w("preset-shadow-json","Preset Shadow JSON",Re(e?.presetShadow??null)),w("effect-dag-json","Effect DAG JSON",Re(e?.effectDag??null))])}function KB(e){return T("anchor","Anchor",[w("kind","Kind",e?.kind??""),w("wrap","Wrap",e?.wrap??""),w("behind-doc","Behind Doc",e?.behindDoc==null?"":String(e.behindDoc)),w("allow-overlap","Allow Overlap",e?.allowOverlap==null?"":String(e.allowOverlap)),w("layout-in-cell","Layout In Cell",e?.layoutInCell==null?"":String(e.layoutInCell)),w("relative-height","Relative Height",e?.relativeHeight==null?"":String(e.relativeHeight)),w("dist-top-emu","Dist Top (EMU)",e?.distTopEmu==null?"":String(e.distTopEmu)),w("dist-bottom-emu","Dist Bottom (EMU)",e?.distBottomEmu==null?"":String(e.distBottomEmu)),w("dist-left-emu","Dist Left (EMU)",e?.distLeftEmu==null?"":String(e.distLeftEmu)),w("dist-right-emu","Dist Right (EMU)",e?.distRightEmu==null?"":String(e.distRightEmu)),w("position-h","Position H",e?.positionH??""),w("position-v","Position V",e?.positionV??""),w("offset-x-emu","Anchor Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),w("offset-y-emu","Anchor Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),w("align-h","Align H",e?.alignH??""),w("align-v","Align V",e?.alignV??"")])}function Ya(e){return T("connector","Connector",[w("connector-type","Connector Type",e?.connectorType??""),w("begin-shape-id","Begin Shape Id",e?.beginShapeId??""),w("end-shape-id","End Shape Id",e?.endShapeId??"")])}function Ja(e){return T("picture","Picture",[w("src","Source",e?.src??""),w("alt","Alt",e?.alt??""),w("title","Title",e?.title??""),w("relationship-id","Relationship Id",e?.relationshipId??""),w("blip-fill-json","Blip Fill JSON",Re(e?.blipFill??null)),w("hyperlink-url","Hyperlink URL",e?.hyperlink?.url??""),w("hyperlink-tooltip","Hyperlink Tooltip",e?.hyperlink?.tooltip??"")])}function Qa(e){return T("word-art","WordArt",[w("text","Text",e?.text??""),w("preset","Preset",e?.preset??"")])}function el(e){return[w("label","Label",e.label??""),w("shape-type","Shape Type",e.shapeType??""),w("group-kind","Group Kind",e.groupKind??""),w("is-watermark","Is Watermark",e.isWatermark==null?"":String(e.isWatermark)),Po("text-body","Text Body",e.textBody),_a(e.geometry),Ua(e.transform),Za(e.groupTransform??null),Ga(e.fill),Xa(e.stroke),$a(e.effects??null),KB(e.anchor),Ya(e.connector),Ja(e.picture),Qa(e.wordArt),...e.children.map(t=>Mm(t))]}function zr(e){return T("shape-child","Child Object",[w("kind","Kind",e),w("id","Id",""),w("label","Label",""),Po("text-body","Text Body",null),_a(null),Ua(null),Za(null),Ga(null),Xa(null),$a(null),Ya(null),Ja(null),Qa(null)])}function _B(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function UB(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function ZB(){return[{label:"Child Shape",createEntry:()=>zr("shape")},{label:"Child Group",createEntry:()=>zr("group")},{label:"Text Box",createEntry:()=>zr("textBox")},{label:"Connector",createEntry:()=>zr("connector")},{label:"Picture",createEntry:()=>zr("picture")},{label:"WordArt",createEntry:()=>zr("wordArt")}]}function tl(e={}){let t=_B(e.containerKey),r=UB(e.childKeys),o=(t==null||t==="shape-child")&&!r.has("text-body");return t==="text-body"?[{label:"Paragraph",createEntry:()=>w("paragraph","Paragraph","")}]:t!=null&&t!=="shape-child"?[]:[...o?[{label:"Text Body",createEntry:()=>Wi("text-body","Text Body")}]:[],...ZB()]}import{normalizeOoxmlShapeModel as GB}from"@datalking/begonia-engine";function XB(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Im(e){return{kind:z(C(e,"kind"))??"unknown",color:z(C(e,"color")),secondaryColor:z(C(e,"secondary-color")),opacity:oe(C(e,"opacity")),gradientAngle:oe(C(e,"gradient-angle")),gradientPath:z(C(e,"gradient-path")),patternPreset:z(C(e,"pattern-preset")),styleRefIndex:oe(C(e,"style-ref-index")),colorSource:Pe(C(e,"color-source-json")),secondaryColorSource:Pe(C(e,"secondary-color-source-json")),gradientStops:Pe(C(e,"gradient-stops-json"))??[],pictureFill:Pe(C(e,"picture-fill-json"))}}function Am(e){return{kind:z(C(e,"kind"))??"unknown",color:z(C(e,"color")),widthEmu:oe(C(e,"width-emu")),dash:z(C(e,"dash")),cap:z(C(e,"cap")),join:z(C(e,"join")),opacity:oe(C(e,"opacity")),styleRefIndex:oe(C(e,"style-ref-index")),compound:z(C(e,"compound")),colorSource:Pe(C(e,"color-source-json")),headEnd:Pe(C(e,"head-end-json")),tailEnd:Pe(C(e,"tail-end-json"))}}function Nm(e){return{styleRefIndex:oe(C(e,"style-ref-index")),styleRefColorSource:Pe(C(e,"style-ref-color-source-json")),effectNodes:Pe(C(e,"effect-nodes-json"))??[],glow:Pe(C(e,"glow-json")),outerShadow:Pe(C(e,"outer-shadow-json")),innerShadow:Pe(C(e,"inner-shadow-json")),softEdge:Pe(C(e,"soft-edge-json")),blur:Pe(C(e,"blur-json")),reflection:Pe(C(e,"reflection-json")),presetShadow:Pe(C(e,"preset-shadow-json")),effectDag:Pe(C(e,"effect-dag-json"))}}function Dm(e){let t=Te(e,"geometry");return t?{preset:z(C(t.children,"preset")),customPathCount:oe(C(t.children,"custom-path-count")),adjustments:XB(C(t.children,"adjustments")),customGeometry:Pe(C(t.children,"custom-geometry-json"))}:null}function Om(e){let t=Te(e,"transform");return t?{widthEmu:oe(C(t.children,"width-emu")),heightEmu:oe(C(t.children,"height-emu")),offsetXEmu:oe(C(t.children,"offset-x-emu")),offsetYEmu:oe(C(t.children,"offset-y-emu")),rotation:oe(C(t.children,"rotation")),flipH:fe(C(t.children,"flip-h")),flipV:fe(C(t.children,"flip-v"))}:null}function jm(e){let t=Te(e,"group-transform");return t?{childOffsetXEmu:oe(C(t.children,"child-offset-x-emu")),childOffsetYEmu:oe(C(t.children,"child-offset-y-emu")),childWidthEmu:oe(C(t.children,"child-width-emu")),childHeightEmu:oe(C(t.children,"child-height-emu"))}:null}function Vm(e){let t=Te(e,"connector");return t?{connectorType:z(C(t.children,"connector-type")),beginShapeId:z(C(t.children,"begin-shape-id")),endShapeId:z(C(t.children,"end-shape-id"))}:null}function Lm(e){let t=Te(e,"picture");if(!t)return null;let r=z(C(t.children,"hyperlink-url"));return{src:z(C(t.children,"src")),alt:z(C(t.children,"alt")),title:z(C(t.children,"title")),relationshipId:z(C(t.children,"relationship-id")),blipFill:Pe(C(t.children,"blip-fill-json")),hyperlink:r?{url:r,tooltip:z(C(t.children,"hyperlink-tooltip"))}:null}}function Fm(e){let t=Te(e,"word-art");return t?{text:z(C(t.children,"text")),preset:z(C(t.children,"preset"))}:null}function zm(e){return qi(pt(e,"text-body")[0]??null)}function $B(e){let t=Te(e,"anchor");return t?{kind:z(C(t.children,"kind"))??"unknown",wrap:z(C(t.children,"wrap"))??"unknown",behindDoc:fe(C(t.children,"behind-doc")),allowOverlap:fe(C(t.children,"allow-overlap")),layoutInCell:fe(C(t.children,"layout-in-cell")),relativeHeight:oe(C(t.children,"relative-height")),distTopEmu:oe(C(t.children,"dist-top-emu")),distBottomEmu:oe(C(t.children,"dist-bottom-emu")),distLeftEmu:oe(C(t.children,"dist-left-emu")),distRightEmu:oe(C(t.children,"dist-right-emu")),positionH:z(C(t.children,"position-h")),positionV:z(C(t.children,"position-v")),offsetXEmu:oe(C(t.children,"offset-x-emu")),offsetYEmu:oe(C(t.children,"offset-y-emu")),alignH:z(C(t.children,"align-h")),alignV:z(C(t.children,"align-v"))}:null}function YB(e){return e==="shape"||e==="group"||e==="textBox"||e==="connector"||e==="picture"||e==="wordArt"}function Hm(e){let t=Te(e,"fill"),r=Te(e,"stroke"),o=Te(e,"effects"),n=C(e,"kind");return{kind:YB(n)?n:"unknown",id:z(C(e,"id")),label:z(C(e,"label")),textBody:zm(e),geometry:Dm(e),transform:Om(e),groupTransform:jm(e),fill:t?Im(t.children):null,stroke:r?Am(r.children):null,effects:o?Nm(o.children):null,connector:Vm(e),picture:Lm(e),wordArt:Fm(e),children:pt(e,"shape-child").map(i=>Hm(i.children))}}function rl(e,t){let r=Te(e,"fill"),o=Te(e,"stroke"),n=Te(e,"effects");return GB({...t,label:z(C(e,"label")),shapeType:z(C(e,"shape-type")),groupKind:z(C(e,"group-kind")),isWatermark:fe(C(e,"is-watermark")),textBody:zm(e),geometry:Dm(e),transform:Om(e),groupTransform:jm(e),fill:r?Im(r.children):null,stroke:o?Am(o.children):null,effects:n?Nm(n.children):null,anchor:$B(e),connector:Vm(e),picture:Lm(e),wordArt:Fm(e),children:pt(e,"shape-child").map(i=>Hm(i.children))},t.label??"Shape")}function ol(e){let t=String(e.attrs.label??"Shape"),r=String(e.attrs.text??""),o=qm("shape",{label:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=qm("shape",e.attrs.familyData,{label:t,text:r})??o;return{objectId:String(e.attrs.objectId??""),label:t,model:n.data.model??o.data.model,evidence:n.evidence}}function QB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function ex(){let e=document.createElement("div");return Object.assign(e.style,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"84px",padding:"12px",borderRadius:"12px",background:"linear-gradient(180deg, #ffffff, #f8fafc)",border:"1px solid #e2e8f0"}),e}function tx(e,t,r,o){let n=JB(o,{idPrefix:t||r,maxWidth:280,maxHeight:180});return e.dataset.previewKind=n.kind,e.dataset.previewSupported=String(n.supported),e.innerHTML=n.svg,n}function Wm(){return e=>{let t=e,r=yo("div"),{header:o,heading:n}=bo("Shape","shape"),i=Bo(),{section:s}=Fr("Visual Preview"),a=zt("Preview uses begonia\u2019s clean-room SVG geometry renderer for preset, connector, group, and custom-path shape families."),l=ex(),{section:c}=Fr("Native Subtree"),d=zt("Edit the shape object graph, text boxes, connector data, pictures, and child objects in a nested ProseMirror subtree. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),u=or();u.style.justifyContent="flex-start";let m=_e("Remove Selected","danger"),p=QB(),f=or();f.style.justifyContent="space-between",f.style.alignItems="center";let g=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),v=_e("Apply"),k=_e("Remove Shape","danger");g.style.marginRight="auto",f.append(g,v,k),s.append(a,l),c.append(d,u,p,m),r.append(o,i,s,c,f);let R=null,h=(P,A)=>{u.replaceChildren(),tl({containerKey:P,childKeys:A}).forEach(O=>{let j=_e(O.label);j.addEventListener("click",()=>{B.appendEntry(O.createEntry())}),u.append(j)})},B=Co(p,[],{onChange(){R?.markDirty()},onSelectionChange(P){h(P.containerKey,P.childKeys)}});m.addEventListener("click",()=>{B.removeSelectedEntry()}),R=ho({applyButton:v,onCommit:()=>{let P=ol(t),A=rl(B.readEntries(),P.model),O=Em(P.model,A);return O.length===0?!1:(rr(r,{family:"shape",action:"apply-shape-edits",objectId:P.objectId,model:A,edits:O}),!0)},root:r,status:g});let b=P=>{t=P;let A=ol(P);n.textContent=A.label;let O=tx(l,A.objectId,A.label,A.model);i.textContent=`${A.evidence.shapeType??"shape"} | ${A.evidence.childCount} child objects | ${A.evidence.anchorKind} | preview ${O.kind}${O.supported?"":" fallback"}`,R?.reset(),B.setEntries(el(A.model))};return v.addEventListener("click",()=>{R?.flush()}),k.addEventListener("click",()=>{R?.reset();let P=ol(t);rr(r,{family:"shape",action:"remove-advanced-ooxml",objectId:P.objectId})}),b(e),{dom:r,destroy(){R?.destroy(),B.destroy()},update(P){return P.type!==t.type?!1:(b(P),!0)},stopEvent(P){return xo(P.target)||P.target instanceof Node&&p.contains(P.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{inlineOoxmlDrawingMetadata as rx}from"@datalking/begonia-editor-adapters";function Km(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ox(){let e=document.createElement("span");return e.contentEditable="false",e.className="ald-editor-inline-drawing",Object.assign(e.style,{display:"inline-block",boxSizing:"border-box",margin:"0 2px",lineHeight:"0",maxWidth:"100%",verticalAlign:"baseline"}),e}function _m(e,t){let r=rx(t),o=r?.label||String(t.attrs.label??"Drawing"),n=r?.family??(t.attrs.family==="chart"?"chart":"shape"),i=r?.drawing,s=Km(r?.width??i?.width,80),a=Km(r?.height??i?.height,40);if(e.dataset.family=n,e.dataset.objectId=r?.objectId??String(t.attrs.objectId??""),e.setAttribute("aria-label",o),e.title=o,e.style.width=`${s}px`,e.style.height=`${a}px`,e.style.border=i?"0":"1px solid #94a3b8",e.style.background=i?"transparent":"#f8fafc",!i?.svg){e.replaceChildren();let c=document.createElement("span");c.textContent=o,Object.assign(c.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"#334155",fontSize:"12px",lineHeight:"1.2",overflow:"hidden"}),e.append(c);return}e.innerHTML=i.svg;let l=e.querySelector("svg");l&&(l.setAttribute("width","100%"),l.setAttribute("height","100%"),l.setAttribute("aria-hidden","true"),Object.assign(l.style,{display:"block"}))}function Um(){return e=>{let t=e,r=ox();return _m(r,e),{dom:r,update(o){return o.type!==t.type?!1:(t=o,_m(r,o),!0)},ignoreMutation(){return!0},selectNode(){r.style.outline="2px solid #0f766e",r.style.outlineOffset="2px"},deselectNode(){r.style.outline="",r.style.outlineOffset=""}}}}var nl="browser-advanced-ooxml-nodeviews";function Zm(){return{id:nl,createPlugins(){return[]},createNodeViews(){return{ooxml_math:xm(),ooxml_chart:Sm(),ooxml_shape:Wm(),inline_ooxml_drawing:Um()}}}}function _i(e=[]){return e.some(t=>t.id===nl)?[...e]:[...e,Zm()]}import{createEditorSessionController as vj}from"@datalking/begonia-editor-ui";function il(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}function Ro(e){return typeof e=="object"&&e!==null}function sl(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.text!="string"?null:{text:e.text,displayMode:e.displayMode==="block"?"block":e.displayMode==="inline"?"inline":void 0}}function Gm(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.title!="string"?null:{title:e.title}}function Xm(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.color!="string"?null:{color:e.color,kind:e.kind==="solid"||e.kind==="scheme"||e.kind==="none"||e.kind==="unknown"?e.kind:void 0}}function $m(e,t=0){if(typeof e=="string")return{id:null,name:e.trim()||`Series ${t+1}`,categories:[],values:[],color:null};if(!Ro(e))return{id:null,name:`Series ${t+1}`,categories:[],values:[],color:null};let r=Array.isArray(e.categories)?e.categories.filter(n=>typeof n=="string"):[],o=Array.isArray(e.values)?e.values.map(n=>typeof n=="number"&&Number.isFinite(n)?n:null):[];return{id:typeof e.id=="string"?e.id:null,name:typeof e.name=="string"?e.name:`Series ${t+1}`,categories:r,values:o,color:typeof e.color=="string"?e.color:null}}function Ym(e,t=0){return typeof e=="string"?{id:null,kind:"category",title:e.trim()||`Axis ${t+1}`,formatCode:null}:Ro(e)?{id:typeof e.id=="string"?e.id:null,kind:e.kind==="category"||e.kind==="value"||e.kind==="series"||e.kind==="date"?e.kind:"category",title:typeof e.title=="string"?e.title:`Axis ${t+1}`,formatCode:typeof e.formatCode=="string"?e.formatCode:null}:{id:null,kind:"category",title:`Axis ${t+1}`,formatCode:null}}function Jm(e,t=0){if(typeof e=="string"){let o=e.trim()||`Child ${t+1}`;return{parentId:null,child:{label:o,kind:"shape",text:o,shapeType:"shape"}}}if(!Ro(e)){let o=`Child ${t+1}`;return{parentId:null,child:{label:o,kind:"shape",text:o,shapeType:"shape"}}}let r=typeof e.label=="string"&&e.label.trim()?e.label.trim():`Child ${t+1}`;return{parentId:typeof e.parentId=="string"&&e.parentId.trim()?e.parentId:null,child:{label:r,kind:e.kind==="shape"||e.kind==="group"||e.kind==="textBox"||e.kind==="connector"||e.kind==="picture"||e.kind==="wordArt"?e.kind:"shape",text:typeof e.text=="string"?e.text:r,shapeType:typeof e.shapeType=="string"?e.shapeType:"shape"}}}function it(e){return e?e.surface??null:null}function Qm(e){if(!e)return null;try{return e.surface??null}catch{return null}}function ve(e){let t=it(e);if(!t)throw new Error("Browser editor surface is not available on this controller.");return t}function nx(e,t=!0){return{ok:!0,changed:t,value:e}}function st(e){return{ok:!1,changed:!1,reason:e}}function ft(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?st(e.reason):nx(e)}function En(e){return typeof e=="object"&&e!==null}function ix(e){return e==="block"?"block":"inline"}function al(e){return{chartType:"barChart",styleId:null,styleSource:null,title:e,subtitle:null,series:[],axes:[],legend:null,plotArea:null,textBody:{paragraphs:[e],plainText:e}}}function ll(e){return{shapeType:"shape",label:e,textBody:{paragraphs:[e],plainText:e},geometry:null,transform:null,groupTransform:null,fill:null,stroke:null,anchor:null,connector:null,picture:null,wordArt:null,childCount:0,children:[],groupKind:null,isWatermark:null}}function sx(e,t){return{id:e.id??null,order:t,name:e.name??`Series ${t+1}`,categories:e.categories??[],values:e.values??[],color:e.color??null,marker:null,dataLabels:null,smooth:null,explosion:null}}function ax(e,t){return{id:e.id??null,kind:e.kind??"category",title:e.title??`Axis ${t+1}`,formatCode:e.formatCode??null,orientation:null,visible:null,minimum:null,maximum:null,majorUnit:null,minorUnit:null,crossesAt:null,majorGridlines:null,minorGridlines:null}}function lx(e,t){let r=e.text?.trim()||e.label?.trim()||`Child ${t+1}`;return{kind:e.kind??"shape",id:null,label:e.label??r,textBody:{paragraphs:il(r),plainText:r},geometry:e.shapeType?{preset:e.shapeType,customPathCount:null,adjustments:[]}:null,transform:null,groupTransform:null,fill:null,stroke:null,connector:e.kind==="connector"?{connectorType:e.shapeType??null,beginShapeId:null,endShapeId:null}:null,picture:null,wordArt:e.kind==="wordArt"?{text:r,preset:e.shapeType??null}:null,children:[]}}function cx(e){if(typeof e=="string"){let r=e.trim();return r?{text:r,displayMode:"inline",label:null}:null}if(!En(e)||typeof e.text!="string")return null;let t=e.text.trim();return t?{text:t,displayMode:e.displayMode==="block"?"block":"inline",label:typeof e.label=="string"?e.label:null}:null}function dx(e){if(typeof e=="string"){let o=e.trim()||"Chart";return{model:al(o),options:{label:o}}}if(!En(e))return{model:al("Chart"),options:{label:"Chart"}};let t=typeof e.title=="string"&&e.title.trim()?e.title.trim():"Chart";return{model:En(e.model)?e.model:al(t),options:{label:typeof e.label=="string"?e.label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function ux(e){if(typeof e=="string"){let o=e.trim()||"Shape";return{model:ll(o),options:{label:o}}}if(!En(e))return{model:ll("Shape"),options:{label:"Shape"}};let t=typeof e.label=="string"&&e.label.trim()?e.label.trim():"Shape";return{model:En(e.model)?e.model:ll(t),options:{label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function ep(e){let t=e.getState().advancedOoxml.selected;return t?.family==="chart"?e.documentApi.ooxml.charts.getById(t.objectId):null}function mx(e){let t=e.getState().advancedOoxml.selected;return t?.family==="math"?e.documentApi.ooxml.math.getById(t.objectId):null}function px(e){let t=e.getState().advancedOoxml.selected;return t?.family==="shape"?e.documentApi.ooxml.shapes.getById(t.objectId):null}function tp(e,t,r){let o=ve(e);switch(t){case"insert-math-inline":{let n=cx(r);if(!n)return st("Expected inline math text for advanced OOXML insertion.");let i=e.documentApi.ooxml.math.createModelFromText(n.text,n.displayMode),s=o.trackingEnabled?e.appendMathToCurrentTextblockTracked(i,{source:"browser-ooxml"},{label:n.label??n.text}):e.appendMathToCurrentTextblock(i,{label:n.label??n.text});return ft(s)}case"insert-chart-block":{let n=dx(r),i=o.trackingEnabled?e.insertChartAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertChartAfterCurrentBlock(n.model,n.options);return ft(i)}case"insert-shape-block":{let n=ux(r),i=o.trackingEnabled?e.insertShapeAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertShapeAfterCurrentBlock(n.model,n.options);return ft(i)}case"remove-selected-ooxml":return ft(e.removeSelectedAdvancedOoxml());case"selected-math-set-plain-text":{let n=sl(r);if(!n)return st("Expected math plain text for the selected OOXML equation.");let i=typeof n=="string"?e.setSelectedMathPlainText(n):e.setSelectedMathPlainText(n.text,n.displayMode);return ft(i)}case"selected-math-toggle-display-mode":{let n=mx(e);if(!n)return st("No advanced OOXML math node is selected.");let i=ix(n.familyData?.displayMode)==="block"?"inline":"block";return ft(e.setSelectedMathDisplayMode(i))}case"selected-chart-set-title":{let n=Gm(r);return n?ft(e.setSelectedChartTitle(typeof n=="string"?n:n.title)):st("Expected a chart title for the selected OOXML chart.")}case"selected-chart-add-series":{let n=ep(e);if(!n)return st("No advanced OOXML chart node is selected.");let i=$m(r,n.familyData?.model?.series.length??0);return i?ft(e.appendSelectedChartSeries(sx(i,n.familyData?.model?.series.length??0))):st("Expected a series payload for the selected OOXML chart.")}case"selected-chart-add-axis":{let n=ep(e);if(!n)return st("No advanced OOXML chart node is selected.");let i=Ym(r,n.familyData?.model?.axes.length??0);return i?ft(e.appendSelectedChartAxis(ax(i,n.familyData?.model?.axes.length??0))):st("Expected an axis payload for the selected OOXML chart.")}case"selected-shape-set-text-body":{let n=sl(r);if(!n)return st("Expected replacement text for the selected OOXML shape.");let i=typeof n=="string"?n:n.text;return ft(e.setSelectedShapeTextBody(il(i)))}case"selected-shape-set-fill":{let n=Xm(r);if(!n)return st("Expected a fill color for the selected OOXML shape.");let i=e.setSelectedShapeFill(typeof n=="string"?{kind:"solid",color:n.trim()||null,secondaryColor:null,opacity:null}:{kind:n.kind??"solid",color:n.color.trim()||null,secondaryColor:null,opacity:null});return ft(i)}case"selected-shape-add-child":{let n=px(e);if(!n)return st("No advanced OOXML shape node is selected.");let i=Jm(r,n.familyData?.model?.children.length??0);if(!i)return st("Expected a child payload for the selected OOXML shape.");let s=lx(i.child,n.familyData?.model?.children.length??0);return ft(i.parentId?e.appendSelectedShapeChildToParent(i.parentId,s):e.appendSelectedShapeChild(s))}default:return null}}import{resolveCollapsedSelectionFormattingMarks as kP}from"@datalking/begonia-engine";import{addressableBlockTypeForNodeType as bp,formatAddressableBlockId as pC,formatAddressableBlockIdWithLogicalId as Bp}from"@datalking/begonia-doc-service/structure";import{normalizeDocumentStoryLocator as fC,readSyntheticSideStoryDocOriginPath as wC,readSyntheticSideStoryDocStoryLocator as gC}from"@datalking/begonia-doc-service/v1";import{hasVisibleSemanticContent as SC}from"@datalking/begonia-engine";function cl(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function Hr(e,t){return e==="listItem"?cl(t.attrs?.listItemId):e==="paragraph"||e==="heading"?cl(t.attrs?.paraId)??cl(t.attrs?.sdBlockId):null}import{DELETION_MARK_NAME as wx,INSERTION_MARK_NAME as gx,collectRevisionSpans as Sx,createRevisionGroupingContext as vx,listSelectionRevisionRanges as hx,logicalRevisionIdForRange as yx,resolveParagraphLikeBlockInlineRangeAtPath as bx}from"@datalking/begonia-engine";import{groupLogicalRevisions as Bx}from"@datalking/begonia-doc-service/v1";import{orderOverlapRevisionIds as fx}from"@datalking/begonia-engine";function Mn(e,t){return fx(e,t)}function rp(e){return e.threadId}function Ui(e){return`${e.threadId}\0${e.entryId}`}function op(e,t){let r=Math.min(e,t),o=Math.max(e,t),n=r===o;return{start:r,selectionEnd:n?o+1:o,collapsed:n}}function xx(e,t){return t<e.selectionEnd&&t+1>e.start}function np(e,t,r){return t<e.selectionEnd&&r>e.start}function dl(e,t,r,o={}){let n=o.includeLeadingBoundary??!0,i=o.includeTrailingBoundary??!0,s=n&&e.collapsed&&r>t&&e.start+1===t,a=i&&e.collapsed&&r>t&&e.start===r;return np(e,t,r)||s||a}function Cx(e){return e.marks.some(t=>t.type.name===gx||t.type.name===wx)}function Px(e,t){return t.target?.nodeType!=="bookmark_anchor"&&t.target?.nodeType!=="structural_revision_carrier"||(t.text??"").length>0||!t.target.blockPath.length?null:bx(e,t.target.blockPath)}function Rx(e,t){if(e.type.name!=="comment_range_start"&&e.type.name!=="comment_range_end"&&e.type.name!=="comment_anchor")return null;let r=typeof e.attrs.threadId=="string"?e.attrs.threadId.trim():"";if(r.length===0)return null;let o=typeof e.attrs.entryId=="string"?e.attrs.entryId.trim():"";return{threadId:r,entryId:o||r,kind:e.type.name==="comment_range_start"?"start":e.type.name==="comment_range_end"?"end":"anchor",pos:t,tracked:Cx(e)}}function Tx(e){let t=[];return e.nodesBetween(0,e.content.size,(r,o)=>{let n=Rx(r,o);return n&&t.push(n),!0}),t}function ul(e,t,r){let o=e.get(t)??[];o.push(r),e.set(t,o)}function kx(e,t){let r=Ui(t),o=e.get(r)??{hasStart:!1,hasEnd:!1};t.kind==="start"&&(o.hasStart=!0),t.kind==="end"&&(o.hasEnd=!0),e.set(r,o)}function Ex(e,t,r){return(e.get(Ui(r))??[]).find(o=>o.pos>=r.pos&&!t.has(o))??null}function Mx(e,t,r){let o=e.get(Ui(r))??[];for(let n=o.length-1;n>=0;n-=1){let i=o[n];if(i&&i.pos<=r.pos&&!t.has(i))return i}return null}function Ix(e,t){let r=op(t.from,t.to),o=Tx(e),n=new Set,i=new Map,s=new Map,a=new Map,l=new Map,c=new Set;for(let d of o){if(kx(l,d),d.kind==="anchor"){ul(a,Ui(d),d);continue}if(d.kind==="start"){ul(i,rp(d),d);continue}let u=rp(d),m=i.get(u)??[],p=m.pop()??null;if(m.length>0?i.set(u,m):i.delete(u),!p){ul(s,u,d);continue}dl(r,p.pos+1,d.pos,{includeLeadingBoundary:!p.tracked,includeTrailingBoundary:!d.tracked})&&n.add(p.threadId)}for(let d of i.values())for(let u of d){let m=Ex(a,c,u);m&&(c.add(m),dl(r,u.pos+1,m.pos,{includeLeadingBoundary:!u.tracked,includeTrailingBoundary:!m.tracked})&&n.add(u.threadId))}for(let d of s.values())for(let u of d){let m=Mx(a,c,u);m&&(c.add(m),dl(r,m.pos,u.pos,{includeLeadingBoundary:!m.tracked,includeTrailingBoundary:!u.tracked})&&n.add(u.threadId))}for(let[d,u]of a){let m=l.get(d);if(!(m?.hasStart||m?.hasEnd))for(let p of u)!p.tracked&&xx(r,p.pos)&&n.add(p.threadId)}return[...n]}function Ax(e,t){let r=Sx(e.doc,e.schema),o=vx(r),n=new Set;for(let i of hx(e)){let s=Px(e.doc,i);(!s||np(op(e.selection.from,e.selection.to),s.from,s.to))&&n.add(yx(i,o,t))}return Mn([...n],Bx(r,t))}function ip(e,t={}){return{activeCommentIds:Ix(e.doc,e.selection),activeChangeIds:Ax(e,t.reviewReplacementMode??"paired")}}import{DELETION_MARK_NAME as Dx}from"@datalking/begonia-engine";import{isDocumentNodePathIndex as Ox}from"@datalking/begonia-document-model";import{NodeSelection as Nx}from"prosemirror-state";function W(e){return e instanceof Nx||typeof e=="object"&&e!=null&&"node"in e&&e.node!=null&&"from"in e&&typeof e.from=="number"&&"to"in e&&typeof e.to=="number"&&"$from"in e&&e.$from!=null}function Zi(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function ze(e){return t=>Zi(t.attrs[e])}function sp(...e){return t=>{for(let r of e){let o=Zi(t.attrs[r]);if(o)return o}return null}}function ml(e){let t=Zi(e.attrs.threadId);return t?`${t}\0${Zi(e.attrs.entryId)??t}`:null}function ap(){return null}function lp(e){return e==="paragraph"||e==="heading"}function To(e,t){return e===t||lp(e)&&lp(t)}var pl=Object.freeze({bookmark_anchor:ze("bookmarkId"),bookmark_end:ze("bookmarkId"),comment_anchor:ml,comment_range_end:ml,comment_range_start:ml,column_break:ze("columnBreakId"),endnote_reference:ze("noteId"),heading:sp("paraId","sdBlockId","captionId"),horizontal_rule:ap,image:ze("imageId"),inline_ooxml_drawing:ze("objectId"),ooxml_chart:ze("objectId"),ooxml_math:ze("objectId"),ooxml_shape:ze("objectId"),page_break:ze("pageBreakId"),paragraph:sp("paraId","sdBlockId","captionId"),footnote_reference:ze("noteId"),permission_range_end:ze("rangeId"),permission_range_start:ze("rangeId"),section_break:ze("sectionId"),table:ap,template_block:ze("fieldId"),template_field:ze("fieldId")});function jx(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function qr(e){try{return jx(JSON.stringify(e.toJSON()))}catch{return null}}function dp(e,t){let r=e,o=-1;for(let n of t){if(!Ox(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function Vx(e,t,r,o,n,i){if(i==null)return null;let s=!1,a=!1;return e.descendants((l,c)=>c===o||!To(l.type.name,t)||n(l)!==r?!0:(s=!0,qr(l)===i?(a=!0,!1):!0)),s&&!a?i:null}function cp(e,t,r){let o=dp(e,t.path);return!o||!To(o.node.type.name,t.nodeType)||r(o.node)!==t.stableIdentity||t.nodeFingerprint!=null&&qr(o.node)!==t.nodeFingerprint?null:o}function Lx(e,t,r){let o=[];return e.descendants((n,i)=>(To(n.type.name,t.nodeType)&&r(n)===t.stableIdentity&&o.push({node:n,position:i}),!0)),o}function Fx(e,t){return t.nodeFingerprint==null?[]:e.filter(r=>qr(r.node)===t.nodeFingerprint)}function up(e){return!!e?.node.marks.some(t=>t.type.name===Dx)}function zx(e){return e.filter(t=>!up(t))}function Ae(e){let t=e?.selection;if(!e||!W(t))return null;let r=t.node.type.name,o=r?pl[r]:null;if(!r||!o)return null;let n=o(t.node),i=[];for(let l=0;l<t.$from.depth;l+=1)i.push(t.$from.index(l));i.push(t.$from.index(t.$from.depth));let s=qr(t.node),a=n?Vx(e.doc,r,n,t.from,o,s):s;return{kind:"node",nodeType:r,stableIdentity:n,path:i,...a!=null?{nodeFingerprint:a}:{}}}function Gi(e,t){let r=pl[t.nodeType];if(t.stableIdentity&&r){let i=Lx(e,t,r);if(i.length===0)return null;if(i.length===1){let l=i[0];return t.nodeFingerprint==null||cp(e,t,r)?.position===l.position||qr(l.node)===t.nodeFingerprint?l:null}let s=cp(e,t,r);if(t.nodeFingerprint==null){if(!up(s))return s;let l=zx(i);return l.length===1?l[0]:s}let a=Fx(i,t);return a.length!==1?null:s?.position===a[0]?.position?s:null}let o=dp(e,t.path);if(o!=null&&To(o.node.type.name,t.nodeType)&&(t.nodeFingerprint==null||qr(o.node)===t.nodeFingerprint))return o;if(t.nodeFingerprint==null)return null;let n=[];return e.descendants((i,s)=>(To(i.type.name,t.nodeType)&&qr(i)===t.nodeFingerprint&&n.push({node:i,position:s}),n.length<=1)),n.length===1?n[0]:null}function mp(e,t,r){if(!r.empty||!t.stableIdentity)return!1;let o=pl[t.nodeType];if(!o)return!1;let n=!1;return e.descendants((i,s)=>To(i.type.name,t.nodeType)&&o(i)===t.stableIdentity&&r.from>=s&&r.from<=s+i.nodeSize?(n=!0,!1):!0),n}import{hasVisibleSemanticContent as Hx}from"@datalking/begonia-document-model";function Xi(e){return[...new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0))]}function qx(e,t){let r=e?.selection;return t!=null&&W(r)&&r.node.isInline&&r.node.isLeaf&&Hx(r.node)}function fl(e,t,r=!1){return t!=="node"||e.target==null||r||Xi(e.activeChangeIds).length>0?e:{...e,target:null}}function ko(e,t,r){let o=Ae(e??null);return fl(t,r,r==="node"&&t.target!=null&&qx(e,o))}import{projectAcceptedTextBetween as oC}from"@datalking/begonia-engine";import{createDocumentNoteAwareTextOffsetOptions as Wx}from"@datalking/begonia-doc-service/v1";function le(e,t={}){return Wx(e,t)}import{pmPositionToAddressableTextOffset as Kx,readAddressableText as _x,resolveAddressableTextOffsetPosition as Ux,resolveAddressableTextOffsetRange as Zx,resolveCollapsedAddressableTextOffsetPosition as Gx}from"@datalking/begonia-document-model";function In(e){return{includeDeletedText:!0,...e}}function Br(e,t={}){return _x(e,In(t))}function we(e,t,r,o={}){return Kx(e,t,r,In(o))}function He(e,t,r,o="end",n={}){return Ux(e,t,r,o,In(n))}function pp(e,t,r,o,n={}){return Zx(e,t,r,o,In(n))}function Eo(e,t,r,o={}){return Gx(e,t,r,In(o))}import{semanticNodeText as Yx}from"@datalking/begonia-document-model";import{isRevisionMarkHiddenInProjection as Xx,isRevisionNodeHiddenInProjection as $x}from"@datalking/begonia-engine";function fp(e,t){return Xx(e,t)}function wt(e,t,r=!1){return $x(e,t,r)}function Jx(e,t){return wt(e,"final",t)}function gp(e,t){let r=Yx(e),o=t?.resolveLeafText?.(e,r);return typeof o=="string"?o:r}function Qx(e,t,r){return r?"":gp(e,t)}function eC(e,t){return t?"":e.text??""}function wp(e,t){return e.isText?(e.text??"").length:e.childCount===0?gp(e,t).length:0}function tC(e,t,r,o,n,i,s){if(o.length===0)return r;t.push(o);let a=r+o.length;return e.push({atomic:s,text:o,startOffset:n,endOffset:i,visibleStart:r,visibleEnd:a}),a}function wl(e,t){let r=[],o=[],n=t?.blockSeparator??"",i=0,s=0,a=(c,d,u=!1)=>{let m=i,p=m+d;s=tC(r,o,s,c,m,p,u),i=p},l=(c,d=!1)=>{let u=Jx(c,d);if(c.isText){let p=wp(c,t);a(eC(c,u),p);return}if(c.childCount===0){let p=wp(c,t);a(Qx(c,t,u),p,!0);return}let m=!0;c.forEach(p=>{p.isBlock&&!m&&n.length>0&&a(n,n.length),l(p,u&&c.isInline),m=!1})};return l(e),{runs:r,text:o.join(""),maxOffset:i}}function rC(e,t,r,o){if(!Number.isInteger(r))return 0;if(r<=0)return o==="start"?e[0]?.startOffset??0:0;for(let[n,i]of e.entries()){if(r<i.visibleStart)return i.startOffset;if(r>i.visibleEnd)continue;if(r===i.visibleEnd){let l=e[n+1];return o==="start"&&l&&l.visibleStart===r?l.startOffset:i.endOffset}let s=i.visibleEnd-i.visibleStart,a=i.endOffset-i.startOffset;return i.atomic?o==="end"&&r>i.visibleStart?i.endOffset:i.startOffset:a===s?i.startOffset+(r-i.visibleStart):o==="end"&&r>i.visibleStart?i.endOffset:i.startOffset}return t}function Mo(e,t={}){let{text:r,maxOffset:o}=wl(e,t);return{text:r,maxOffset:o}}function Io(e,t,r="end",o={}){let{runs:n,text:i,maxOffset:s}=wl(e,o);return!Number.isInteger(t)||t<0||t>i.length?null:rC(n,s,t,r)}function nr(e,t,r="end",o={}){let{runs:n}=wl(e,o);if(!Number.isInteger(t)||t<=0)return 0;let i=0;for(let s of n){if(t<=s.startOffset)return i;if(t<=s.endOffset)return s.atomic&&t<s.endOffset?r==="end"?s.visibleEnd:s.visibleStart:s.visibleStart+(t-s.startOffset);i=s.visibleEnd}return i}var nC=Object.freeze({blockSeparator:" "});function iC(e){return e.empty??e.from===e.to}function sC(e,t){let r=Math.max(0,e.content.size),o=Math.min(r,Math.max(0,Math.min(t.from,t.to))),n=Math.min(r,Math.max(o,Math.max(t.from,t.to))),i=le(e,nC),s=[],a=!1;return e.nodesBetween(o,n,(l,c)=>{if(!l.isTextblock)return!0;a=!0;let d=Math.max(o,c+1),u=Math.min(n,c+l.nodeSize-1),m=we(l,c,d,i),p=Math.max(m,we(l,c,u,i)),f=Mo(l,i),g=nr(l,m,"start",i),v=nr(l,p,"end",i);return s.push(f.text.slice(Math.min(g,v),Math.max(g,v))),!1}),a?s.join(" "):null}function ge(e,t,r){return iC(r)?"":sC(e,r)??oC(e,t,Math.min(r.from,r.to),Math.max(r.from,r.to)," ")}function Sp(e){return[...new Set(e)]}function An(e){return JSON.stringify([e.empty,e.target??null,[...new Set(e.activeMarks)].sort(),Sp(e.activeCommentIds),Sp(e.activeChangeIds),e.text??null])}import{hasVisibleSemanticContent as hp,isInlineFormatMarkEnabled as aC}from"@datalking/begonia-document-model";var lC=new Set(["strong","em","underline","strike"]);function $i(e,t){for(let r of t){if(lC.has(r.type.name)&&!aC(r)){e.delete(r.type.name);continue}e.add(r.type.name)}}function cC(e){let t=new Set;return $i(t,e),t}function vp(e,t){let r=new Set(e);return $i(r,t.marks),r}function yp(e){return e.isInline&&!e.isText&&hp(e)}function dC(e){return e.isText||e.isInline&&e.isLeaf&&hp(e)}function uC(e,t){return e.isText?{start:t,end:t+(e.text?.length??0)}:{start:t,end:t+e.nodeSize}}function Yi(e,t,r){let o=null,n=(i,s,a)=>{let l=yp(i)?vp(a,i):new Set(a);if(dC(i)){let d=uC(i,s),u=Math.max(d.start,t);if(Math.min(d.end,r)>u){let p=vp(l,i);if(o==null)o=p;else for(let f of[...o])p.has(f)||o.delete(f)}return}if(i.childCount===0)return;let c=0;i.forEach(d=>{let u=s+1+c,m=u+d.nodeSize;c+=d.nodeSize,!(m<=t||u>=r)&&n(d,u,l)})};return n(e,-1,new Set),o??new Set}function Ji(e,t=null){if(t!=null)return cC(t);let r=new Set;for(let o=1;o<=e.depth;o+=1){let n=e.node(o);if(!yp(n))continue;let i=e.start(o),s=e.end(o);e.pos<i||e.pos>s||$i(r,n.marks)}return $i(r,e.marks()),r}import{parseAddressableBlockId as mC}from"@datalking/begonia-doc-service/structure";function Ao(e){return mC(e)?.logicalId==null}var Qi=Object.freeze({blockSeparator:`
3
+ `});function vC(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function es(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=bp(r.type.name);if(o)return{type:o,path:vC(e,t),node:r,pos:e.start(t)-1}}return null}function hC(e,t,r,o){let n=e[e.length-1];if(n?.blockId===t){n.range.end=Math.max(n.range.end,o),n.range.start=Math.min(n.range.start,r);return}e.push({blockId:t,range:{start:r,end:o}})}function xp(e,t){let r=wC(e);return r?[...r,...t]:[...t]}function Sl(e,t,r){let o=xp(e,t.path);return r?pC(t.type,o):Bp(t.type,o,Hr(t.type,t.node))}function yC(e,t=null){return e.length===0?null:{kind:"text",segments:e,...t?{story:t}:{}}}function vl(e,t,r,o,n){return Ao(e)?{start:nr(t,r,"start",n),end:nr(t,o,"end",n)}:{start:r,end:o}}function gl(e){return e.node.isLeaf&&e.node.isInline&&e.$from.parent.inlineContent&&SC(e.node)}function Cp(e){let t=bp(e.node.type.name);return t==="listItem"?t:null}function bC(e){return"$anchorCell"in e?!1:W(e)?gl(e)||Cp(e)!=null:!0}function BC(e,t){let r=t.$from.doc.resolve(t.from+1),o=es(r);if(!o||o.node!==t.node)return null;let n=le(e,Qi),i=Math.max(t.from,o.pos+1),s=Math.min(t.to,o.pos+o.node.nodeSize-1),a=we(o.node,o.pos,i,n),l=Math.max(a,we(o.node,o.pos,s,n)),c=Sl(e,o,!1);return[{blockId:c,range:vl(c,o.node,a,l,n)}]}function xC(e,t){let r=es(t.$from);if(!r||!r.node.isTextblock)return null;let o=le(e,Qi),n=we(r.node,r.pos,t.from,o),i=Math.max(n,we(r.node,r.pos,t.to,o)),s=Sl(e,r,!0);return[{blockId:s,range:vl(s,r.node,n,i,o)}]}function CC(e,t){let r=W(t)&&gl(t),o=le(e,Qi);if(W(t)&&gl(t)){let s=xC(e,t);if(s)return s}if(W(t)&&Cp(t)){let s=BC(e,t);if(s)return s}let n=[],i=!1;return e.nodesBetween(t.from,t.to,(s,a)=>{if(i)return!1;if(!s.isTextblock)return!0;let l=e.resolve(a+1),c=es(l);if(!c)return i=!0,!1;let d=Math.max(t.from,a+1),u=Math.min(t.to,a+s.nodeSize-1),m=we(c.node,c.pos,d,o),p=Math.max(m,we(c.node,c.pos,u,o)),f=Sl(e,c,r),g=vl(f,c.node,m,p,o);return hC(n,f,g.start,g.end),!1}),i?null:n}function PC(e,t,r){return Yi(e,t,r)}function RC(e){let t=new Set,{from:r,to:o}=e.selection;if(r===o){for(let n of Ji(e.doc.resolve(r),e.storedMarks))t.add(n);return[...t]}for(let n of PC(e.doc,r,o))t.add(n);return[...t]}function TC(e,t){let{selection:r}=e,o=W(r)?Ae(e):null;return JSON.stringify([r.from,r.to,r.empty,W(r)?"node":"text",An({...t,target:t.target?{...t.target,...t.target.story?{story:fC(t.target.story)??t.target.story}:{}}:null}),W(r)?o??{nodeType:r.node.type.name,position:r.$from.pos,nodeSize:r.node.nodeSize}:null])}function Ee(e,t={},r={}){let o=t??{},n=r??{},{selection:i,doc:s}=e,a=hl(s,i),{activeCommentIds:l,activeChangeIds:c}=ip(e,{reviewReplacementMode:n.reviewReplacementMode}),d={empty:i.empty,target:a,activeMarks:RC(e),activeCommentIds:l,activeChangeIds:c};return o.includeText&&!i.empty&&(d.text=ge(s,e.schema,i)),d}function hl(e,t){let r=gC(e);return bC(t)?yC(CC(e,t)??[],r):null}function Ht(e){let t=Ee(e).target;if(t)return t;if(!e.selection.empty)return null;let r=es(e.selection.$from);if(!r)return null;let o=le(e.doc,Qi),n=we(r.node,r.pos,e.selection.from,o);return{kind:"text",blockId:Bp(r.type,xp(e.doc,r.path),Hr(r.type,r.node)),range:{start:n,end:n}}}function yl(e,t={}){let r=n=>W(n.selection)?"node":"text",o=n=>{let i=e.state;return{state:i,info:ko(i,Ee(i,n,t),r(i))}};return{current(n){return o(n).info},onChange(n){let i=!1,s=!1,a=null,l=()=>{if(s=!1,i)return;let m=o({includeText:!0}),p=TC(m.state,m.info);p!==a&&(a=p,n(m.info))},c=()=>{i||s||(s=!0,queueMicrotask(l))},d;try{d=e.subscribe(c)}catch(m){throw i=!0,m}let u=!1;return()=>{u||(u=!0,i=!0,d())}}}}function kC(e){return e?.selectionKind!=="node"&&e?.selectionTarget!=null}function ir(e,t,r=null){return e?e.editable?r?.selectionKind==="node"?"Place the caret in text or select text before applying inline formatting.":kC(r)?null:t&&W(t.selection)?"Place the caret in text or select text before applying inline formatting.":t?Ht(t)?null:"Place the caret in text or select text before applying inline formatting.":r?.selectionTarget?null:"Place the caret in text or select text before applying inline formatting.":"Document is read-only in the current document mode.":"Editor is not ready."}import{createSelectionTrackingBookmark as xP}from"@datalking/begonia-engine";import{NodeSelection as as}from"prosemirror-state";import{NodeSelection as Rp,TextSelection as ts}from"prosemirror-state";function Pp(e,t,r){try{return e.resolve(t).parent.inlineContent&&e.resolve(r).parent.inlineContent}catch{return!1}}function Tp(e){return typeof e=="object"&&e!=null&&"parent"in e&&typeof e.parent=="object"&&e.parent!=null&&"inlineContent"in e.parent&&e.parent.inlineContent===!0}function Wr(e,t){return Math.max(1,Math.min(t,e.content.size))}function rs(e,t){return Math.max(0,Math.min(t,e.content.size))}function Z(e,t,r=t){let o=Wr(e.doc,t),n=Wr(e.doc,r),i=Math.min(o,n),s=Math.max(o,n),a=kp(e),l=c=>{if(!Kr(c))return null;if(a&&typeof c.toJSON=="function")try{let d=a.fromJSON(e.doc,c.toJSON());return Kr(d)?d:null}catch{}return c};if(Pp(e.doc,i,s))try{return l(ts.create(e.doc,o,n))}catch{}try{return l(ts.between(e.doc.resolve(o),e.doc.resolve(n),n>=o?1:-1))}catch{if(o!==n)return null}try{return l(ts.near(e.doc.resolve(o),n>=o?1:-1))}catch{return null}}function Kr(e){return e instanceof ts||typeof e=="object"&&e!=null&&!("$anchorCell"in e)&&!("node"in e&&e.node!=null)&&"anchor"in e&&typeof e.anchor=="number"&&"head"in e&&typeof e.head=="number"&&"empty"in e&&typeof e.empty=="boolean"&&"$anchor"in e&&"$head"in e&&Tp(e.$anchor)&&Tp(e.$head)}function qt(e,t){let r=W(e),o=W(t);if(r!==o||e.from!==t.from||e.to!==t.to||e.empty!==t.empty)return!1;let n=Kr(e),i=Kr(t);return!n&&!i?!0:n&&i&&e.anchor===t.anchor&&e.head===t.head}function bl(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function kp(e){let t=e.selection.constructor,r=typeof t=="function"?Object.getPrototypeOf(t):null;return r&&typeof r.fromJSON=="function"?r:null}function EC(e,t){return Kr(e)?Kr(t)?t:null:W(e)?W(t)?t:null:t}function at(e,t){let r=kp(e);if(r&&typeof t.toJSON=="function")try{return EC(t,r.fromJSON(e.doc,t.toJSON()))}catch{}if(W(t)){let o=rs(e.doc,Math.min(t.from,t.to)),n=e.doc.nodeAt(o);if(!n||!Rp.isSelectable(n))return null;try{return Rp.create(e.doc,o)}catch{return null}}return Kr(t)?Z(e,t.anchor,t.head):t}import{readPreservedSelection as gP}from"@datalking/begonia-engine";import{NodeSelection as SP}from"prosemirror-state";import{isDocumentStoryLocator as iP,readSyntheticSideStoryDocStoryLocator as sP,sameDocumentStoryLocator as aP}from"@datalking/begonia-doc-service/v1";import{resolveAddressableBlockIdPath as DC}from"@datalking/begonia-doc-service/v1";import{parseAddressableBlockId as OC}from"@datalking/begonia-doc-service/structure";import{readSyntheticSideStoryDocOriginPath as MC}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as xl,isDocumentNodePathIndex as Cl}from"@datalking/begonia-document-model";function Bl(e){return Cl(e)}function IC(e){let t=e[0];return t===-101||t===-102||t===-211||t===-212?e.length>=2&&Bl(e[1])&&xl(e.slice(2))?e.slice(2):null:(t===-201||t===-202)&&e.length>=3&&Bl(e[1])&&Bl(e[2])&&xl(e.slice(3))?e.slice(3):null}function AC(e,t){return e.length>=t.length&&t.every((r,o)=>e[o]===r)}function NC(e,t){let r=e,o=-1;for(let n of t){if(!Cl(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function Nn(e,t){if(!Array.isArray(t))return null;if(t.length===0)return[];if(xl(t))return[...t];let r=IC(t);if(!r)return null;let o=MC(e);return o&&AC(t,o)?r:null}function No(e,t){let r=Nn(e,t);if(!r)return null;if(r.length===0)return 0;let o=0,n=e;for(let i of r){if(!Cl(i)||i>=n.childCount)return null;o+=1;for(let s=0;s<i;s+=1)o+=n.child(s).nodeSize;n=n.child(i)}return o}function Ve(e,t){let r=Nn(e,t);return r?NC(e,r):null}function Ep(e){return e==="paragraph"||e==="heading"}function jC(e){return{readDocument(){return e},readNode(t){return Ve(e,t)?.node??null}}}function Le(e,t){let r=DC(jC(e),t),o=Nn(e,r);if(o)return o;let n=OC(t);if(!n?.path.length||!Ep(n.nodeType))return null;let i=Nn(e,n.path),s=i?Ve(e,i)?.node??null:null;return s?.isBlock&&Ep(s.type.name)?[...i]:null}import{hasVisibleSemanticContent as VC,semanticNodeText as LC}from"@datalking/begonia-document-model";var FC=new Set(["structural_revision_carrier","bookmark_anchor","bookmark_end","comment_anchor","comment_range_start","comment_range_end","permission_range_start","permission_range_end"]);function zC(e){if(FC.has(e.type.name))return"";let t=LC(e);return t.length>0?t:VC(e)?"":""}function HC(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.textBetween(o,n,"",zC);if(i.length===0)return!0;if(i.trim().length>0)return!1;let s=e.resolve(o),a=e.resolve(n);for(let l=Math.min(s.depth,a.depth);l>=0;l-=1)if(s.node(l)===a.node(l)&&s.node(l).isTextblock)return!0;return!1}function _r(e,t,r={}){if(t.length===0)return null;let o=t[0],n=o;for(let i of t.slice(1)){if(i.from<n.from||i.from===n.from&&i.to<n.to||i.from<o.to)return null;if(i.from===o.to||HC(e,o.to,i.from)){o={from:o.from,to:Math.max(o.to,i.to)},n=i;continue}return r.strict?null:o}return o}import{readSyntheticSideStoryDocOriginPath as QC}from"@datalking/begonia-doc-service/v1";import{cloneSelectionTextRange as qC}from"@datalking/begonia-document-api/core";import{sameDocumentStoryLocator as Mp}from"@datalking/begonia-doc-service/v1";function Wt(e,t){return e.empty&&e.from>=t.from&&e.from<=t.to}function Kt(e,t){return{kind:"text",segments:t.map(r=>({blockId:r.blockId,range:qC(r.range)})),...e.story?{story:structuredClone(e.story)}:{}}}function Et(e){return Kt(e,e.segments)}function Dn(e){return e?{kind:"node",nodeType:e.nodeType,stableIdentity:e.stableIdentity,path:[...e.path],...e.nodeFingerprint!=null?{nodeFingerprint:e.nodeFingerprint}:{}}:null}function On(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!Mp(e.story,t.story)?!1:e.segments.every((r,o)=>{let n=t.segments[o];return n?.blockId===r.blockId&&n.range.start===r.range.start&&n.range.end===r.range.end&&n.range.startAffinity===r.range.startAffinity&&n.range.endAffinity===r.range.endAffinity})}function os(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!Mp(e.story,t.story)?!1:e.segments.every((r,o)=>{let n=t.segments[o];return!!(n&&r.blockId===n.blockId&&r.range.start===r.range.end&&r.range.start>=n.range.start&&r.range.end<=n.range.end)})}function sr(e,t){return!e||!t?e===t:e.nodeType!==t.nodeType?!1:e.stableIdentity!=null&&t.stableIdentity!=null?e.stableIdentity===t.stableIdentity&&(e.nodeFingerprint==null||t.nodeFingerprint==null||e.nodeFingerprint===t.nodeFingerprint):e.path.length===t.path.length&&e.path.every((r,o)=>r===t.path[o])}import{canonicalizeRevisionIds as WC,normalizeRevisionIds as Pl,selectionOverlapsRevisionRange as KC}from"@datalking/begonia-engine";function _C(e){if("from"in e)return{from:e.from,to:e.to};let{anchor:t,head:r}=e.range.range;return t.story.storyType!=="body"||r.story.storyType!=="body"||t.path.length>0||r.path.length>0?null:{from:Math.min(t.offset,r.offset),to:Math.max(t.offset,r.offset)}}function UC(e,t){return t.length>0?WC(e,t):[]}function ce(e,t){let r=Pl(e);return t&&t.length>0?UC(r,t):r}function ZC(e){return e==="paragraph"||e==="heading"}function GC(e){return(e.target?.nodeType==="bookmark_anchor"||e.target?.nodeType==="structural_revision_carrier")&&ZC(e.target.blockType)&&e.target.blockPath.length>0&&(e.text??"").trim().length===0}function XC(e,t){let r=_C(e);return r?Mn(Pl(t.filter(o=>KC(r.from,r.to,o)).map(o=>o.id)),t):[]}function de(e){return Pl(e)}function ar(e,t){let r=de(e),o=de(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function lr(e,t){let r=ce(e.trackedChangeIds,t),o=XC(e,t),n=new Set(t.filter(GC).map(a=>a.id));if(o.length===0)return r;if(r.length===0)return o;let i=new Set(o),s=Mn(r.filter(a=>i.has(a)||n.has(a)),t);return s.length>0?s:o}function Do(e,t){let r=lr(e,t),o=e.trackedChangeIds??[];return e.trackedChangeIds!=null&&r.length===o.length&&r.every((n,i)=>n===o[i])?e:{...e,trackedChangeIds:r}}function Ur(e,t,r){let o=e.activeChangeIds??[],n=lr("from"in t?{from:t.from,to:t.to,trackedChangeIds:o}:{range:t.range,trackedChangeIds:o},r);return e.activeChangeIds!=null&&n.length===o.length&&n.every((i,s)=>i===o[s])?e:{...e,activeChangeIds:n}}function $C(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Mt(e,t=[]){return ce([...e?.activeChangeIds??[],...e?.selection.trackedChangeIds??[]],t)}function Rl(e,t,r=[]){if(!e||!t)return e===t;let o=$C(Mt(e,r),Mt(t,r));return e.selectionKind!==t.selectionKind||e.projectedMode!==t.projectedMode||e.selection.empty!==t.selection.empty||!o?!1:e.selectionKind==="node"||t.selectionKind==="node"?sr(e.nodeSelectionTarget,t.nodeSelectionTarget):e.selectionTarget||t.selectionTarget?On(e.selectionTarget,t.selectionTarget):e.selection.from!==t.selection.from||e.selection.to!==t.selection.to?!1:e.text==null||t.text==null||e.text===t.text}var Ap=Symbol.for("@datalking/begonia-browser-sdk/selection-capture-document-identity"),Ip=1;function YC(){let e=globalThis.crypto?.randomUUID?.();if(typeof e=="string"&&e.length>0)return e;let t=Ip;return Ip+=1,`browser-selection-capture-document:${t}`}function jn(e){let t=e==null?null:Reflect.get(e,Ap);return typeof t=="string"&&t.length>0?t:null}function Np(e){let t=jn(e);if(t!=null||e==null||!Object.isExtensible(e))return t;let r=YC();return Object.defineProperty(e,Ap,{configurable:!0,enumerable:!1,value:r,writable:!1}),r}function JC(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Oo(e){if(e==null)return null;try{return JC(JSON.stringify(e.toJSON()))}catch{return null}}var eP=Object.freeze({success:!0}),tP=Object.freeze({success:!1,reason:"read-only"});function jo(){return{success:!1,reason:"stale"}}function rP(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function qe(e,t,r={}){try{let o=at(e.view.state,t);return o?(e.view.dispatch(e.view.state.tr.setSelection(o).scrollIntoView()),r.focus!==!1&&e.focus(),!0):!1}catch{return!1}}function oP(e,t){return e.documentIdentity==null&&e.documentHash==null?!0:e.documentIdentity!=null&&e.documentIdentity!==jn(t)?!1:e.documentHash==null||e.documentHash===Oo(t)}function nP(e){let t=Mt(e);return e.selectionKind==="text"&&typeof e.text=="string"&&(e.text.length>0||t.length>0)}function Tl(e){let{capture:t,options:r={},resolveSelection:o,surface:n}=e;if(!n.view?.state||typeof n.view.dispatch!="function")return{success:!1,reason:"not-ready"};if(!t||!t.target&&!t.selectionTarget&&!t.nodeSelectionTarget)return{success:!1,reason:"missing-target"};if(n.editable===!1)return tP;if(!rP(t.storyOriginPath,QC(n.view.state.doc))||r.validateDocumentIdentity!==!1&&!oP(t,n.view.state.doc))return jo();let i=o(t);return!i||t.selectionKind==="node"&&!W(i)||r.validateText!==!1&&nP(t)&&ge(n.view.state.doc,n.view.state.schema,i)!==t.text?jo():qe(n,i,r)?eP:jo()}var ns=Object.freeze({blockSeparator:`
4
+ `});function is(e,t){if(t.story===void 0)return!0;if(!iP(t.story))return!1;let r=sP(e)??{kind:"story",storyType:"body"};return aP(r,t.story)}function lP(e,t,r,o,n){let i=le(e,ns),s=Io(t,o,n,i);return s==null?null:He(t,r,s,n,i)}function cP(e,t,r,o,n){let i=le(e,ns),s=Io(t,o,"start",i),a=Io(t,n,"end",i);if(s==null||a==null)return null;let l=He(t,r,Math.min(s,a),"start",i),c=He(t,r,Math.max(s,a),"end",i);return typeof l=="number"&&typeof c=="number"?{from:Math.min(l,c),to:Math.max(l,c)}:null}function dP(e,t,r,o,n){let i=He(e,t,r,"start",n),s=He(e,t,o,"end",n);return typeof i=="number"&&typeof s=="number"?{from:Math.min(i,s),to:Math.max(i,s)}:null}function uP(e,t){return t.collapsedAcceptedVisibleBias==="hidden-anchor"||e.range.start===0?"end":"start"}function mP(e,t,r={}){let o=Le(e,t.blockId);if(!o)return null;let n=Ve(e,o);if(!n?.node.isBlock)return null;let i=le(e,ns);if(Ao(t.blockId)){if(t.range.start===t.range.end){let l=lP(e,n.node,n.position,t.range.start,uP(t,r));return typeof l=="number"?{from:l,to:l}:null}let a=cP(e,n.node,n.position,t.range.start,t.range.end);return a||null}if(t.range.start===t.range.end){let a=Eo(n.node,n.position,t.range.start,i);return typeof a=="number"?{from:a,to:a}:null}if(r.strict)return dP(n.node,n.position,t.range.start,t.range.end,i);let s=pp(n.node,n.position,t.range.start,t.range.end,i);return s||null}function Dp(e,t){return ge(e,e.type.schema,t)}function pP(e,t){let r=Q(e,{kind:"text",segments:[t]},{strict:!0});return r?Dp(e,r):null}function fP(e,t){let r=e.indexOf(t);return r<0||e.indexOf(t,r+1)>=0?null:{start:r,end:r+t.length}}function kl(e,t,r){if(!is(e,t)||t.segments.length!==1||r.length===0)return null;let[o]=t.segments,n=Le(e,o.blockId);if(!n)return null;let i=Ve(e,n);if(!i?.node.isBlock)return null;let s=le(e,ns),a=Mo(i.node,s),l=fP(a.text,r);if(!l)return null;let c=Io(i.node,l.start,"start",s),d=Io(i.node,l.end,"end",s);if(c==null||d==null)return null;let u=He(i.node,i.position,c,"start",s),m=He(i.node,i.position,d,"end",s);return typeof u!="number"||typeof m!="number"?null:{selection:{from:Math.min(u,m),to:Math.max(u,m)},target:Kt(t,[{blockId:o.blockId,range:{start:Ao(o.blockId)?Math.min(l.start,l.end):Math.min(c,d),end:Ao(o.blockId)?Math.max(l.start,l.end):Math.max(c,d)}}])}}function wP(e,t,r){return kl(e,t,r)?.selection??null}function Q(e,t,r={}){if(!t||!is(e,t))return null;let o=[];for(let n of t.segments){let i=mP(e,n,r);if(!i)return null;o.push(i)}return _r(e,o,r)}function Ne(e,t,r,o={}){let n=Q(e,t,o);return n&&(typeof r!="string"||r.length===0||Dp(e,n)===r)?n:!t||typeof r!="string"||r.length===0?null:wP(e,t,r)}function lt(e,t){if(!t||!is(e,t))return null;let r=[];for(let o of t.segments){let n=pP(e,o);if(n==null)return null;r.push(n)}return r}function et(e,t,r,o={}){if(!t||!is(e,t)||!r||r.length!==t.segments.length)return null;let n=[];for(let[i,s]of t.segments.entries()){let a=Ne(e,{kind:"text",segments:[s]},r[i]??null,{...o,strict:!0});if(!a)return null;n.push(a)}return _r(e,n,o)}function El(e,t){let r=e.view;if(!r?.state||typeof r.dispatch!="function")return!1;let o=Q(r.state.doc,t,{strict:!0});if(!o)return!1;let n=Z(r.state,o.from,o.to);return n?qe(e,n):!1}function Op(e){return e.anchor>e.head?"backward":"forward"}function xr(e){return e.anchor!=null&&e.head!=null&&e.anchor>e.head?"backward":"forward"}function gt(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to);return t==="backward"?{anchor:o,head:r}:{anchor:r,head:o}}function jp(e,t){return Math.max(1,Math.min(t,e.content.size))}function Ml(e,t){let r=jp(e.doc,Math.min(t.from,t.to)),o=jp(e.doc,Math.max(t.from,t.to));if(r>=o)return null;let n=gt({from:r,to:o},t.direction),i=Z(e,n.anchor,n.head);if(!i||i.empty)return null;try{return e.apply(e.tr.setSelection(i))}catch{return null}}function vP(e,t,r=null,o=null,n){let i=et(e.doc,t,r,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"})??Ne(e.doc,t,o,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"});if(!i||i.from>=i.to)return null;let s=gt(i,n),a=Z(e,s.anchor,s.head);if(!a||a.empty)return null;try{return e.apply(e.tr.setSelection(a))}catch{return null}}function Zr(e,t){if(!t)return null;let r=Gi(e.doc,t);if(!r)return null;try{return e.apply(e.tr.setSelection(SP.create(e.doc,r.position)))}catch{return null}}function Il(e,t){return Zr(e,t.nodeSelectionTarget)??vP(e,t.target,t.segmentTexts,t.text,t.direction)??Ml(e,t)}function Vp(e){let t=gP(e);if(!t||t.empty)return null;let r=at(e,t);if(!r)return null;if(qt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function hP(e,t){if(!t.selectionTarget||!t.segmentTexts||t.selectionTarget.segments.length!==t.segmentTexts.length)return null;let r=t.selectionTarget.segments.map((o,n)=>Ne(e.doc,{kind:"text",segments:[o]},t.segmentTexts?.[n]??null,{strict:!0}));return r.every(o=>o!=null)?r:null}function yP(e,t){let r=hP(e,t);if(!r||r.length===0)return null;let o=r[0].from,n=r[0].to;for(let i of r.slice(1)){if(!i||i.from<n)return null;n=Math.max(n,i.to)}return{from:o,to:n}}function cs(e,t){return t.selectionTarget?et(e.doc,t.selectionTarget,t.segmentTexts??null,{strict:!0})??Ne(e.doc,t.selectionTarget,t.text??null,{strict:!0})??yP(e,t):null}function ss(e){return Math.max(0,Math.abs(e.to-e.from))}function bP(e,t,r){let o=de([...de(t.activeChangeIds),...de(t.selection.trackedChangeIds)]);return t.selectionKind==="text"&&!t.selection.empty&&o.length>0&&ss(t.selection)>0&&(ss(r??{from:0,to:0})===0||(()=>{if(!r)return!1;let n=ls(e,t);return!n||n.empty||ss(n)<=ss(r)?!1:ge(e.doc,e.schema,n)===ge(e.doc,e.schema,r)})())}function Al(e,t){let r=at(e,t);if(!r)return null;if(qt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function ls(e,t){if(t.selectionKind==="node"){let o=rs(e.doc,Math.min(t.selection.from,t.selection.to)),n=e.doc.nodeAt(o);if(n&&as.isSelectable(n))try{return as.create(e.doc,o)}catch{}}let r=gt(t.selection,xr(t.selection));return Z(e,Wr(e.doc,r.anchor),Wr(e.doc,r.head))}function Lp(e,t,r,o){if(r==="node"){let i=rs(e.doc,Math.min(t.from,t.to)),s=e.doc.nodeAt(i);if(s&&as.isSelectable(s))try{return as.create(e.doc,i)}catch{return null}}let n=gt(t,o);return Z(e,Wr(e.doc,n.anchor),Wr(e.doc,n.head))}function BP(e,t){let r=Zr(e,t.nodeSelectionTarget)?.selection;if(W(r))return r;let o=cs(e,t);if(o){let i=Lp(e,o,t.selectionKind,xr(t.selection));if(W(i))return i}let n=ls(e,t);return W(n)?n:null}function cr(e,t){if(t.selectionKind==="node")return BP(e.state,t);let r=cs(e.state,t);return r?bP(e.state,t,r)?ls(e.state,t):Lp(e.state,r,t.selectionKind,xr(t.selection)):ls(e.state,t)}function CP(e,t,r){return Z(e,t,r)}function PP(e){let t=e;return(t.selectionKind==="text"||t.selectionKind==="node")&&"selectionTarget"in e&&"nodeSelectionTarget"in e&&(t.selectionKind==="node"||typeof t.text=="string"||Array.isArray(t.segmentTexts)||Array.isArray(t.activeChangeIds))}function RP(e,t){if(PP(t))return cr({state:e},t);let r=Math.min(t.selection.from,t.selection.to),o=Math.max(t.selection.from,t.selection.to);return CP(e,r,o)}function TP(e){let t=e.view;return t?.state&&typeof t.dispatch=="function"?t:null}function tt(e,t,r,o={}){let n=TP(e);if(!n)return!1;if(!t)return r(e);let i=o.restoreSelection??!0,s=n.state.selection,a=RP(n.state,t);if(!a||qt(s,a))return r(e);let c=xP(s),d=n.dispatch.bind(n);n.dispatch=(u=>{if(u.docChanged&&c)try{c=c.map(u.mapping)}catch{c=null}return d(u)});try{try{n.dispatch(n.state.tr.setSelection(a))}catch{return r(e)}return r(e)}finally{if(n.dispatch=d,i&&c)try{let u=c.resolve(n.state.doc);if(u){let m=at(n.state,u);m&&n.dispatch(n.state.tr.setSelection(m))}}catch{}}}var EP=["color","highlight","fontFamily","fontSize","fontSizeCs","rFonts"];function Gr(e,t){return{ok:!0,changed:t,value:e}}function rt(e){return{ok:!1,changed:!1,reason:e}}function zp(e,t){let r=ve(e),o=ir({editable:e.getState().editable},r.state,t);return o||(t?null:"Place the caret in text or select text before applying inline formatting.")}function Hp(e,t,r){return e.empty&&!t?`Collapsed ${r} formatting requires a live editor surface. Select text to format in headless mode.`:null}function qp(e){return e.target&&"segments"in e.target?e.target:e.selectionTarget??null}function Wp(e,t,r){let o=ve(e),n=e.documentApi.format.apply({target:t,inline:r,participant:o.trackingEnabled?o.participant:void 0,context:o.trackingEnabled?{source:"formatting"}:void 0});return n.success?Gr(n,!0):n.failure.code==="NO_OP"?Gr(n,!1):rt(n.failure.message)}function Kp(e){return e?{...e}:{}}function MP(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t))return!1;let r=e,o=t,n=Object.keys(r).sort(),i=Object.keys(o).sort();return n.length===i.length&&n.every((s,a)=>s===i[a]&&Object.is(r[s],o[s]))}function IP(e,t){let r=Kp(e),o=!1;for(let n of EP){if(t[n]===void 0)continue;let i=n==="fontSize"||n==="fontSizeCs"?typeof t[n]=="number"?t[n]:null:n==="rFonts"?t.rFonts&&typeof t.rFonts=="object"?structuredClone(t.rFonts):null:typeof t[n]=="string"?t[n]:null;(n==="rFonts"?MP(r[n],i):Object.is(r[n],i))||(r[n]=i,o=!0)}return{changed:o,attrs:Object.values(r).some(n=>n!=null)?r:null}}function Fp(e,t){let r=ve(e);if(!r.view)return rt("Collapsed text-style formatting requires a live editor surface. Select text to format in headless mode.");let{state:o,dispatch:n}=r.view,i=o.schema.marks.text_style;if(!i)return rt("Inline text-style marks are not available on this surface.");let a=kP(o).find(d=>d.type===i)??null,l=IP(Kp(a?.attrs),t);if(!l.changed)return Gr(a?.attrs??null,!1);let c=o.tr.removeStoredMark(i);return l.attrs&&(c=c.addStoredMark(i.create(l.attrs))),n(c),Gr(l.attrs,!0)}function Vo(e,t,r=null,o={}){let n=r?e.readSelectionCapture(r):e.readEffectiveSelection();if(r&&!n)return rt("Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.");let i=zp(e,n);if(i)return rt(i);if(!n)return rt("Place the caret in text or select text before applying inline formatting.");let s=Hp(n,ve(e).view!=null,"text-style");if(s)return rt(s);if(n.empty){if(r){let l=null;return tt(ve(e),n,()=>(l=Fp(e,t),l.changed),{restoreSelection:o.restoreSelection??!1}),l??rt("Inline formatting could not be applied.")}return Fp(e,t)}let a=qp(n);return a?Wp(e,a,t):rt("Place the caret in text or select text before applying inline formatting.")}function Nl(e,t){switch(t){case"bold":return e.toggleBold();case"italic":return e.toggleItalic();case"underline":return e.toggleUnderline();case"strike":return e.toggleStrike()}}function AP(e,t){let r=Nl(ve(e),t);return Gr(r,r)}function NP(e,t){return t==="bold"?e.selection.formatting.bold:t==="italic"?e.selection.formatting.italic:t==="underline"?e.selection.formatting.underline:e.selection.formatting.strike}function _t(e,t,r=null,o={}){let n=r?e.readSelectionCapture(r):e.readEffectiveSelection();if(r&&!n)return rt("Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.");let i=zp(e,n);if(i)return rt(i);if(!n)return rt("Place the caret in text or select text before applying inline formatting.");let s=Hp(n,ve(e).view!=null,"inline");if(s)return rt(s);if(n.empty){if(r){let d=tt(ve(e),n,u=>Nl(u,t),{restoreSelection:o.restoreSelection??!1});return Gr(d,d)}return AP(e,t)}let a=ve(e);if(a.view&&!r){let d=tt(a,n,u=>Nl(u,t),{restoreSelection:o.restoreSelection??!1});return Gr(d,d)}let l=qp(n);if(!l)return rt("Place the caret in text or select text before applying inline formatting.");let c=!NP(n,t);return Wp(e,l,{[t]:c})}function ds(e){let t=e?.layoutMode??"vertical";return{flowMode:e?.flowMode??"paginated",layoutMode:t,preferredPaginatedLayoutMode:e?.preferredPaginatedLayoutMode??t,zoomPercent:e?.zoom?.percent??e?.zoomPercent??100,zoomMode:e?.zoom?.mode??"manual"}}function us(e,t){switch(t.type){case"flow":return{flowMode:t.flowMode};case"toggle-pagination":return{flowMode:e.flowMode==="paginated"?"web":"paginated"};case"layout":return{flowMode:"paginated",layoutMode:t.layoutMode};case"zoom":return{zoomPercent:t.zoomPercent}}}import{normalizeHyperlinkHref as _p}from"@datalking/begonia-document-model";var Up=8,Zp=96;function It(e){return typeof e=="object"&&e!==null}function DP(e,t=!0){return typeof e=="boolean"?e:It(e)&&typeof e.changed=="boolean"?e.changed:t}function $(e,t=DP(e)){return{ok:!0,changed:t,value:e}}function ye(e){return{ok:!1,changed:!1,reason:e}}function Gp(e){if(typeof e=="string"){let r=_p(e);return r?{href:r,title:null}:null}if(!It(e))return null;let t=_p(e.href);return t?{href:t,title:typeof e.title=="string"?e.title:e.title==null?null:String(e.title)}:null}function Xp(e){return typeof e=="string"?e.trim()?e:null:!It(e)||typeof e.text!="string"||e.text.trim().length===0?null:{text:e.text,isInternal:typeof e.isInternal=="boolean"?e.isInternal:void 0}}function Lo(e){if(e==null)return null;if(typeof e!="string")return;let t=e.trim();if(t)return t.toLowerCase()==="none"?null:t}function Dl(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?Math.min(Zp,Math.max(Up,e)):void 0;if(typeof e!="string")return;let t=e.trim();if(!t)return;if(t.toLowerCase()==="none")return null;let r=Number.parseFloat(t);return Number.isFinite(r)?Math.min(Zp,Math.max(Up,r)):void 0}function jl(e){let t=Lo(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"color"))return Lo(e.color);if(Object.hasOwn(e,"value"))return Lo(e.value)}}function $p(e){let t=Lo(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"fontFamily"))return Lo(e.fontFamily);if(Object.hasOwn(e,"value"))return Lo(e.value)}}function Yp(e){let t=Dl(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"fontSize"))return Dl(e.fontSize);if(Object.hasOwn(e,"value"))return Dl(e.value)}}function Ol(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?e:null;if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=t.endsWith("%")?t.slice(0,-1).trim():t;if(!r||!/^(?:\d+(?:\.\d+)?|\.\d+)$/u.test(r))return null;let o=Number.parseFloat(r);return Number.isFinite(o)&&o>0?o:null}function Jp(e){let t=Ol(e);if(t!=null)return t;if(!It(e))return null;let r=Ol(e.zoomPercent);if(r!=null)return{zoomPercent:r};let o=Ol(e.zoom);return o!=null?{zoom:o}:null}function Qp(e){return typeof e=="string"?e:!It(e)||typeof e.query!="string"?null:{query:e.query,options:It(e.options)?e.options:void 0}}function Vl(e){return typeof e=="string"?e:!It(e)||typeof e.text!="string"?null:{text:e.text,hitId:typeof e.hitId=="string"?e.hitId:e.hitId==null?null:String(e.hitId)}}function ef(e){return typeof e=="string"?e:!It(e)||typeof e.text!="string"?null:{text:e.text,diagnosticId:typeof e.diagnosticId=="string"?e.diagnosticId:e.diagnosticId==null?null:String(e.diagnosticId)}}function ms(e){return e.getZoomState().mode}function tf(e){return e.getZoomPercent()}function Ll(e,t){return e.getState().preferredPaginatedLayoutMode!==t}function Fo(e,t){let r=ve(e);return tt(r,e.readEffectiveSelection(),t)}function Ut(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?ye(e.reason):$(e)}function OP(e){return e===!1?ye("Comment could not be created."):Ut(e)}function jP(e,t,r){let o=ve(e);switch(t){case"font-size":{let n=Yp(r),i=n===null?null:Number(n);return n===void 0?ye('Expected a font-size payload or "none".'):Vo(e,{fontSize:i,fontSizeCs:i})}case"font-family":{let n=$p(r);return n===void 0?ye('Expected a font-family payload or "none".'):Vo(e,{fontFamily:n==null?null:String(n),rFonts:null})}case"text-color":{let n=jl(r);return n===void 0?ye('Expected a text-color payload or "none".'):Vo(e,{color:n==null?null:String(n)})}case"highlight-color":{let n=jl(r);return n===void 0?ye('Expected a highlight-color payload or "none".'):Vo(e,{highlight:n==null?null:String(n)})}case"zoom":{let n=Jp(r);if(!n)return ye("Expected a positive zoom percentage payload.");let i=typeof n=="number"?n:n.zoomPercent??n.zoom??null;if(i==null)return ye("Expected a positive zoom percentage payload.");let s=tf(e),a=ms(e);return e.setViewState(us(ds(e.getState()),{type:"zoom",zoomPercent:i})),$(i,tf(e)!==s||ms(e)!==a)}case"zoom-fit-width":{let n=ms(e);e.setZoomMode(n==="fit-width"?"manual":"fit-width");let i=ms(e);return $(i,i!==n)}case"document-mode-editing":{let n=e.getState().documentMode;return e.setDocumentMode("editing"),$("editing",e.getState().documentMode!==n)}case"document-mode-suggesting":{let n=e.getState().documentMode;return e.setDocumentMode("suggesting"),$("suggesting",e.getState().documentMode!==n)}case"document-mode-viewing":{let n=e.getState().documentMode;return e.setDocumentMode("viewing"),$("viewing",e.getState().documentMode!==n)}case"flow-mode-paginated":{let n=e.getFlowMode();return e.setViewState(us(ds(e.getState()),{type:"flow",flowMode:"paginated"})),$("paginated",e.getFlowMode()!==n)}case"flow-mode-web":{let n=e.getFlowMode();return e.setViewState(us(ds(e.getState()),{type:"flow",flowMode:"web"})),$("web",e.getFlowMode()!==n)}case"layout-mode-vertical":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"vertical"}),$("vertical",e.getLayoutMode()!==i||Ll(e,n))}case"layout-mode-horizontal":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"horizontal"}),$("horizontal",e.getLayoutMode()!==i||Ll(e,n))}case"layout-mode-book":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"book"}),$("book",e.getLayoutMode()!==i||Ll(e,n))}case"track-changes-display-review":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("review"),$("review",e.getState().trackChanges.mode!==n)}case"track-changes-display-original":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("original"),$("original",e.getState().trackChanges.mode!==n)}case"track-changes-display-final":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("final"),$("final",e.getState().trackChanges.mode!==n)}case"track-changes-display-off":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("off"),$("off",e.getState().trackChanges.mode!==n)}case"comments-visible":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!0),$(!0,e.getState().commentsDisplay.visible!==n)}case"comments-hidden":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!1),$(!1,e.getState().commentsDisplay.visible!==n)}case"comments-show-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!0),$(!0,e.getState().commentsDisplay.showResolved!==n)}case"comments-hide-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!1),$(!1,e.getState().commentsDisplay.showResolved!==n)}case"comments-visibility-all":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("all"),$("all",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-internal":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("internal"),$("internal",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-external":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("external"),$("external",e.getState().commentsDisplay.visibility!==n)}case"undo":return $(o.undo());case"redo":return $(o.redo());case"bold":return _t(e,"bold");case"italic":return _t(e,"italic");case"underline":return _t(e,"underline");case"strikethrough":return _t(e,"strike");case"paragraph":return $(Fo(e,n=>n.setParagraph()));case"heading-1":return $(Fo(e,n=>n.setHeading(1)));case"heading-2":return $(Fo(e,n=>n.setHeading(2)));case"heading-3":return $(Fo(e,n=>n.setHeading(3)));case"bullet-list":return $(Fo(e,n=>n.toggleBulletList()));case"numbered-list":return $(Fo(e,n=>n.toggleOrderedList()));case"link-set":{let n=Gp(r);return n?$(typeof n=="string"?e.setLink(n):e.setLink(n.href,n.title??null)):ye("Expected a non-empty link payload.")}case"link-clear":return $(e.clearLink());case"comment-create":{let n=Xp(r);if(!n)return ye("Expected non-empty comment text for comment creation.");let i=e.readEffectiveSelection();return OP(typeof n=="string"?i?e.createCommentFromCapture(i,n):e.createComment(n):i?e.createCommentFromCapture(i,n.text,{isInternal:n.isInternal??void 0}):e.createComment(n.text,{isInternal:n.isInternal??void 0}))}case"tracking-toggle":return e.setDocumentMode(e.getState().documentMode==="suggesting"?"editing":"suggesting"),$(!0,!0);default:return null}}function rf(e,t,r){let o=jP(e,t,r);if(o)return o;let n=tp(e,t,r);if(n)return n;switch(t){case"search-set-query":{let i=Qp(r);if(!i)return ye("Expected a search query payload.");let s=typeof i=="string"?e.search(i):e.search(i.query,i.options??{});return $(s,!0)}case"search-next":return(()=>{let i=e.nextSearchHit();return $(i,i!=null)})();case"search-previous":return(()=>{let i=e.previousSearchHit();return $(i,i!=null)})();case"search-clear":{let i=e.getState().search.query.length>0;return e.clearSearch(),$(void 0,i)}case"search-replace-active":{let i=Vl(r);if(!i)return ye("Expected replacement text for the active search hit.");let s=e.getState(),a=typeof i=="string"?s.search.activeHitId:i.hitId??s.search.activeHitId;if(!a)return ye("No active search hit is available to replace.");let l=typeof i=="string"?e.replaceSearchHit(a,i):e.replaceSearchHit(a,i.text);return Ut(l)}case"search-replace-all":{let i=Vl(r);if(!i)return ye("Expected replacement text for search replace-all.");let s=typeof i=="string"?e.replaceAllSearchHits(i):e.replaceAllSearchHits(i.text);return Ut(s)}case"review-accept-all":return Ut(e.acceptAll());case"track-changes-accept-selection":return Ut(e.acceptSelection());case"review-reject-all":return Ut(e.rejectAll());case"track-changes-reject-selection":return Ut(e.rejectSelection());case"proofing-ignore-first":{let i=e.getState().proofing.diagnostics[0]?.diagnosticId;return i?Ut(e.ignoreProofingDiagnostic(i)):ye("No proofing diagnostic is available to ignore.")}case"proofing-accept-first":{let i=e.getState().proofing.diagnostics[0]?.diagnosticId;return i?Ut(e.acceptProofingSuggestion(i)):ye("No proofing diagnostic is available to accept.")}case"proofing-replace-first-tracked":{let i=ef(r),a=e.getState().proofing.diagnostics[0],l=typeof i=="string"?a?.diagnosticId:i?.diagnosticId??a?.diagnosticId,c=typeof i=="string"?i:i?.text??a?.replacementText??a?.suggestion??"";return!l||!c?ye("No tracked proofing replacement could be resolved."):Ut(e.replaceProofingDiagnosticTracked(l,c))}default:return null}}import{createEditorSessionController as FT}from"@datalking/begonia-editor-ui";function ct(e){return e?.trim()??""}function Vn(e,t){let r=ct(e);return r.length===0?"":ct(t?.id)||r}function of(e){return/(?:^|[-_:])wire(?:[-_:]|$)/i.test(ct(e))}function Ue(e){let t=new Map,r=new Set;for(let n of e??[]){let i=ct(n.id);i.length!==0&&(r.add(i),t.set(i,i))}let o=new Map;for(let n of e??[]){let i=ct(n.id);if(i.length===0)continue;let s=ct(n.wireId);if(s.length===0||r.has(s))continue;let a=o.get(s);a===void 0||a===i?o.set(s,i):o.set(s,null)}for(let[n,i]of o)i&&t.set(n,i);return t}function zo(e,t){let r=ct(e);return t.get(r)??r}function VP(e,t){let r=ct(t);if(r.length===0)return"";let o=e?.get?.(r)??null;if(o)return Vn(r,o);let n=of(r),i=e?.target?.(r)??null;if(i&&(ct(i.id)===r||n))return Vn(r,i);let s=e?.targetSnapshot?.(r)??null;return s&&(ct(s.id)===r||n)?Vn(r,s):r}function At(e,t){return[...new Set((e??[]).map(r=>zo(r,t)).filter(r=>r.length>0))]}function nf(e,t){let r=(e??[]).map(s=>ct(s)).filter(s=>s.length>0),o=t?.get==null&&r.length>1&&r.every(s=>!of(s)),n=[],i=new Set;for(let s of r){let a=o?s:VP(t,s);a.length===0||i.has(a)||(i.add(a),n.push(a))}return n}function sf(){return{success:!1}}function af(e,t){try{e.restoreSelectionHandle?.(t,{focus:!1})}catch{return}}function lf(e){return e.shouldContinue?.()??!0}async function ps(e,t,r={}){let o=e.captureEffectiveSelectionHandle();try{let n=await t();return lf(r)?(n.success||af(e,o),n):sf()}catch{return lf(r)&&af(e,o),sf()}finally{e.releaseSelectionHandle(o)}}function LP(e){return"host"in e}function he(e){return e?LP(e)?e.host:e:null}function FP(e){return"getState"in e&&typeof e.getState=="function"&&"subscribe"in e&&typeof e.subscribe=="function"&&"readLayoutSource"in e&&typeof e.readLayoutSource=="function"&&"readLayoutAdapter"in e&&typeof e.readLayoutAdapter=="function"&&"requestPreviewNavigation"in e&&typeof e.requestPreviewNavigation=="function"&&"ackPreviewNavigationRequest"in e&&typeof e.ackPreviewNavigationRequest=="function"&&"setViewState"in e&&typeof e.setViewState=="function"&&"setZoomViewportMetrics"in e&&typeof e.setZoomViewportMetrics=="function"}function cf(e){return e?FP(e)?e:he(e)?.preview??null:null}function fs(e={}){return{commentTarget:null,selected:!1,selectionTarget:null,navigationRequest:null,...e}}function df(e,t){return t?typeof t=="string"?e.documentApi.comments.target(t):t:null}function uf(e){return e.documentApi.selection.current({includeText:!0}).target}function zP(e){return e&&"id"in e&&typeof e.id=="string"&&e.id.length>0?e.id:null}function Fl(){return{success:!1}}function mf(e,t){let r=he(e);if(!r)return fs();let o=df(r,t);if(!o)return fs();if(!r.selectionTargets.selectCommentTarget(o))return fs({commentTarget:o});let i=uf(r);return fs({commentTarget:o,selected:!0,selectionTarget:i,navigationRequest:r.browserViewport.requestNavigationForTextTarget(i)})}async function pf(e,t,r={},o={}){let n=he(e);if(!n)return Fl();let i=df(n,t);return i?ps(n.selectionHandles,async()=>{if(n.selectionTargets.selectCommentTarget(i)){let a=uf(n);if(a)return n.browserViewport.scrollIntoView({target:a,timeoutMs:r.timeoutMs,continuation:o.continuation})}let s=zP(i);return s?n.browserViewport.scrollIntoView({target:{type:"comment",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Fl()},{shouldContinue:o.continuation?.shouldContinue}):Fl()}function HP(e,t,r){return{shouldContinue(){return e()===t},subscribe(o){return r(t,o)}}}function ws(){let e=0,t=new Set,r=()=>{let n=[...t];e+=1,t=new Set;for(let i of n)try{i()}catch{continue}return e},o=(n,i)=>n!==e?()=>{}:(t.add(i),()=>{n===e&&t.delete(i)});return{begin(){let n=r();return HP(()=>e,n,o)},invalidate(){r()}}}function qP(e){return e.find(t=>t.type==="comment")??null}function WP(e,t){return[...new Set(e.filter(r=>r.type==="comment").map(r=>zo(r.id,t)).filter(r=>r.length>0))]}function KP(e,t){let r=Ue(e),o=zo(t,r);return e.find(n=>zo(n.id,r)===o||zo(n.wireId,r)===o)??null}function _P(e,t){let r=Ue(e),o=WP(t,r);if(o.length!==1)return null;let n=o[0]??qP(t)?.id??null;if(!n)return null;let i=KP(e,n);return!i||typeof i.id!="string"||i.id.length===0?null:{id:i.id,item:i}}function ff(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=he(e);return o?_P(r,o.browserViewport.entitiesAtPoint(t)):null}import{listProjectionSelectionRects as RR,resolveProjectionCaretRect as TR}from"@datalking/begonia-page-layout";import{isDenseArray as kR}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as UP,INSERTION_MARK_NAME as ZP,semanticNodeText as GP}from"@datalking/begonia-engine";function wf(e){return typeof e=="number"?Math.max(0,e):null}function XP(e){return e.startPath?e.startPath:e.segments?.find(t=>t.kind==="range")?.startPath??null}function $P(e){if(e.endPath)return e.endPath;for(let t=(e.segments?.length??0)-1;t>=0;t-=1){let r=e.segments?.[t];if(r?.kind==="range"&&r.endPath)return r.endPath}return null}function YP(e){return e.anchorPath?e.anchorPath:e.segments?.find(t=>t.kind==="anchor")?.anchorPath??null}function JP(e,t){let r=e,o=Ve(r,t),n=o?.node.type.name==="comment_anchor"?o.position:No(r,t);return wf(n)}function gs(e){return e.marks.some(t=>t.type.name===ZP||t.type.name===UP)}function QP(e,t,r){let o=!1;return e.nodesBetween(t,r,(n,i)=>{if(o)return!1;if(!(n.isText||n.isInline&&n.isLeaf&&GP(n).length>0))return!0;let a=Math.max(t,i);return Math.min(r,i+n.nodeSize)<=a?!1:(o=gs(n),!o)}),o}function gf(e,t){let r=e,o=Ve(r,t);return o?o.node.type.name!=="comment_range_start"?No(r,t):gs(o.node)?No(r,t):o.position:null}function eR(e,t,r={}){if(t?.kind!=="range"||!t.startPath||!t.endPath)return null;let o=e,n=gf(e,t.startPath),i=No(o,t.endPath);if(typeof n!="number"||typeof i!="number"||n>i)return null;let s={from:n,to:i},a=QP(e,s.from,s.to),l=r.allowTrackedContentFallback??!0,c=le(o,{blockSeparator:`
5
+ `}),d=t.addressableBlockPath??t.blockPath??null,u=d?Ve(o,d):null,m=u?.node??null,p=t.text;if(!u||!m?.isBlock||typeof p!="string"||p.length===0)return s;let f=Br(m,c),g=we(m,u.position,s.from,c),v=Math.max(g,we(m,u.position,s.to,c)),k=f.slice(g,v);if(k===p)return s;let R=k.indexOf(p);if(R<0||k.indexOf(p,R+1)>=0)return a&&!l?null:s;let h=g+R,B=h+p.length,S=He(m,u.position,h,"start",c),b=He(m,u.position,B,"end",c),P=Ve(o,t.startPath)?.node??null,A=Ve(o,t.endPath)?.node??null,O=R===0&&!(a&&P?.type.name==="comment_range_start"&&!gs(P)),j=B===v&&!(a&&A?.type.name==="comment_range_end"&&!gs(A)),K=O?s.from:S,F=j?s.to:b;return typeof K!="number"||typeof F!="number"||F<=K?a&&!l?null:s:{from:Math.min(K,F),to:Math.max(K,F)}}function tR(e){return e!=null}function rR(e,t){let r=e,o=t.segments??[],n=t.source==="live",i=o.map(a=>eR(e,a,{allowTrackedContentFallback:n}));if(o.length>0&&!n&&i.some(a=>a==null))return null;let s=i.filter(tR);if(s.length===0){let a=XP(t),l=$P(t);if(!a||!l)return null;let c=gf(e,a),d=No(r,l);return typeof c!="number"||typeof d!="number"?null:{from:Math.min(c,d),to:Math.max(c,d)}}return _r(r,s,{strict:!n})}function Ze(e,t){if(!t)return null;if(t.targetKind==="range")return rR(e,t);let r=YP(t);if(!r)return null;let o=JP(e,r);return typeof o!="number"?null:{from:o,to:o}}import{readSyntheticSideStoryDocContext as oR,resolveSyntheticSideStoryPathPosition as nR}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as iR}from"@datalking/begonia-document-model";import{parseAddressableBlockId as sR}from"@datalking/begonia-doc-service/structure";function aR(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function Sf(e,t){let r=e,o=-1;for(let n of t){if(!iR(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function lR(e,t){let r=Sf(e,t);return r?.node.isBlock?{path:[...t],localPath:[...t],document:e,position:r.position,node:r.node,syntheticRootPath:null,positionRoot:null}:null}function cR(e,t){let r=oR(aR(e),t);if(!r)return null;let o=r.localizePath(t),n=r.globalizePath([]),i=nR(e.type.schema,e,n),s=o?Sf(r.doc,o):null;return o&&s?.node.isBlock&&typeof i=="number"?{path:[...t],localPath:[...o],document:r.doc,position:s.position,node:s.node,syntheticRootPath:n,positionRoot:i}:null}function Cr(e,t){let r=Le(e,t);if(r)return lR(e,r);let o=sR(t);return o?.path.some(n=>n<0)?cR(e,o.path):null}function Zt(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?t-e.positionRoot:t}import{resolveDocumentStoryLocatorFromPath as dR}from"@datalking/begonia-doc-service/v1";import{addressableBlockTypeForNodeType as uR,formatAddressableBlockId as mR,formatAddressableBlockIdWithLogicalId as pR}from"@datalking/begonia-doc-service/structure";function fR(e,t){return{kind:"text",segments:[{blockId:e,range:{start:0,end:0}}],...t?{story:t}:{}}}function wR(e,t,r){return r?structuredClone(r):dR({listSections:()=>e.sections?.list?.()??[],listFootnotes:()=>e.notes?.footnotes?.list?.()??e.notes?.list?.()??[],listEndnotes:()=>e.notes?.endnotes?.list?.()??[],listHeaderFooterParts:()=>e.headerFooters?.parts?.list?.()?.items??[]},t)}function Ss(e,t,r){if(!e||!Array.isArray(t)||t.length===0)return null;let o=e.blocks.read(t);if(!o)return null;let n=uR(o.type.name);if(!n)return null;let i=Hr(n,o),s=i?pR(n,t,i):mR(n,t);return fR(s,wR(e,t,r)??void 0)}function Ln(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.trunc(e):null}function gR(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function vf(e,t){return!Array.isArray(t)||t.length===0?null:Ss(e,t)}function SR(e,t){let r=Math.max(0,typeof e.text=="string"?e.text.length:typeof t.text=="string"?t.text.length:0),o=Ln(e.startOffset)??Ln(t.startOffset)??0,n=Ln(e.endOffset)??Ln(t.endOffset)??(r>0?o+r:o);return{start:o,end:Math.max(o,n)}}function vR(e){let t=e.segments?.filter(r=>r.kind==="range")??[];return t.length>0?t:[{kind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:e.blockPath??null,addressableBlockPath:e.addressableBlockPath??null,startOffset:e.startOffset??null,endOffset:e.endOffset??null,text:e.text}]}function hR(e){let t=e.segments?.find(r=>r.kind==="anchor");return t?.addressableBlockPath??t?.blockPath??e.addressableBlockPath??e.blockPath??null}function vs(e,t){if(!e||!t)return null;if(t.targetKind==="range"){let n=[],i;for(let s of vR(t)){let a=s.addressableBlockPath??s.blockPath??null,l=vf(e,a);if(!l)return null;if(i===void 0)i=l.story;else if(!gR(i,l.story))return null;n.push({blockId:l.segments[0].blockId,range:SR(s,t)})}return n.length>0?{kind:"text",segments:n,...i?{story:i}:{}}:null}let r=vf(e,hR(t));if(!r)return null;let o=Ln(t.anchorOffset)??0;return{kind:"text",segments:[{blockId:r.segments[0].blockId,range:{start:o,end:o}}],...r.story?{story:r.story}:{}}}import{isIntegerPath as yR}from"@datalking/begonia-document-model";var bR=Object.freeze({blockSeparator:`
6
+ `});function Ho(e){return typeof e=="number"&&Number.isFinite(e)}function BR(e){return Array.isArray(e)&&e.length>0&&yR(e)}function xR(e){return!!e&&typeof e=="object"&&BR(e.blockPath)}function CR(e){let t=s=>[s.blockPath.join("."),Ho(s.from)?Math.min(s.from,s.to??s.from):"",Ho(s.to)?Math.max(s.from??s.to,s.to):""].join(":"),r=[e?.target??null,...e?.targets??[]].filter(xR),o=s=>Ho(s.from)&&Ho(s.to)?0:1,n=s=>o(s)===0?Math.min(s.from,s.to):Number.POSITIVE_INFINITY,i=s=>o(s)===0?Math.max(s.from,s.to):Number.POSITIVE_INFINITY;return r.map((s,a)=>({target:s,index:a})).sort((s,a)=>o(s.target)-o(a.target)||n(s.target)-n(a.target)||i(s.target)-i(a.target)||s.index-a.index).reduce((s,a)=>{let l=t(a.target);return s.some(c=>t(c)===l)||s.push(a.target),s},[])}function hf(e,t,r){return Math.min(Math.max(e,t),r)}function PR(e,t,r){if(!e||!Ho(r.from)||!Ho(r.to))return null;let o=Cr(e,t);if(!o)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=Zt(o,Math.min(r.from,r.to)),a=Zt(o,Math.max(r.from,r.to)),l=hf(s,n,i),c=hf(a,l,i),d=le(o.document,bR),u=we(o.node,o.position,l,d),m=we(o.node,o.position,c,d);return{start:Math.min(u,m),end:Math.max(u,m)}}function zl(e,t,r){if(!e||!r)return{target:null,selectionTarget:null};let o=null,n=null;for(let i of CR(r)){let s=Ss(e,i.blockPath,r.story);if(!s)continue;let a=s.segments[0]?.blockId;if(!a)continue;n||(o=i,n={kind:"text",segments:[{blockId:a,range:{start:0,end:0}}],...s.story?{story:s.story}:{}});let l=PR(t,a,i);if(l)return{target:i,selectionTarget:{kind:"text",segments:[{blockId:a,range:l}],...s.story?{story:s.story}:{}}}}return{target:o,selectionTarget:n}}function hs(e,t,r){return zl(e,t,r).selectionTarget}function Gt(e){return typeof e?.readLayoutSource=="function"?e.readLayoutSource():null}function qo(e){return e?.getResolvedProjection?.()??null}function Xt(e){return e?.getResolvedProjectionGeometryOptions?.()??null}function St(e){return{success:!1,reason:e}}function ER(e){return!e||typeof e!="object"?!1:!!e&&"kind"in e&&e.kind==="text"&&kR(e.segments)}function yf(e){return typeof e=="number"&&Number.isFinite(e)}function MR(e){return!e||e.segments.length===0?!1:e.segments.every(t=>typeof t?.blockId=="string"&&t.blockId.trim().length>0&&yf(t.range?.start)&&yf(t.range?.end))}function IR(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"id"in e&&typeof e.id=="string"}function AR(e){return e?typeof e.id=="string"&&e.id.trim().length>0:!1}function Hl(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"childCount"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function bf(e,t){return typeof e!="number"||!Number.isFinite(e)||typeof t!="number"||!Number.isFinite(t)?null:{from:Math.min(e,t),to:Math.max(e,t)}}function NR(e){return{pageIndex:e.pageIndex,pageNumber:e.pageNumber,sectionId:e.sectionId??null,region:e.region,blockIndex:e.blockIndex,fragmentIndex:e.fragmentIndex,columnIndex:e.columnIndex,lineIndex:e.lineIndex,lineCount:e.lineCount,left:e.left,top:e.top,width:e.width,height:e.height}}function DR(e){return{pageIndex:e.pageIndex,pageNumber:e.pageNumber,sectionId:e.sectionId??null,region:e.region,blockIndex:e.blockIndex,fragmentIndex:e.fragmentIndex,columnIndex:e.columnIndex,lineIndex:e.lineIndex,lineCount:e.lineCount,left:e.left,top:e.top,width:1,height:e.height}}function OR(e){return[e.pageIndex,e.pageNumber,e.sectionId??"",e.region,e.blockIndex,e.fragmentIndex,e.columnIndex,e.lineIndex,e.lineCount,e.left,e.top,e.width,e.height].join(":")}function jR(e){let t=[],r=new Set;for(let o of e){let n=OR(o);r.has(n)||(r.add(n),t.push(o))}return t}function VR(e,t){let r=qo(e),o=Xt(e)??{};if(!r)return[];if(t.from===t.to){let n=TR(r,t.from,o);return n?[DR(n)]:[]}return RR(r,t.from,t.to,o).map(NR)}function ql(e,t){if(t.segments.length===0)return null;let r=[];for(let o of t.segments){let n=FR(e,o);if(!n)return null;r.push(n)}return r}function LR(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?{from:e.positionRoot+t.from,to:e.positionRoot+t.to}:t}function FR(e,t){let r={kind:"text",segments:[t]},o=Q(e,r,{strict:!0});if(o)return o;let n=Cr(e,t.blockId);if(!n||n.document===e)return null;let i=Q(n.document,r,{strict:!0});return i?LR(n,i):null}function zR(e){if(!e)return[];let t=(e.segments??[]).map(o=>bf(o.from,o.to)).filter(o=>o!=null).sort((o,n)=>o.from-n.from||o.to-n.to);if(t.length>0)return t;let r=bf(e.from,e.to);return r?[r]:[]}function HR(e,t,r){if(!r||typeof t?.blocks?.read!="function")return null;let o=hs(t,e,r);return o?ql(e,o):null}function qR(e,t="unresolved"){let[r]=e;return r?{success:!0,rect:r,rects:[...e],pageIndex:r.pageIndex,pageNumber:r.pageNumber}:St(t)}function Fn(e,t){let r=jR(t.flatMap(o=>VR(e,o)));return qR(r,t.length>0?"not-mounted":"unresolved")}function Wo(e,t){let r=e.preview??null;if(!r||!qo(r))return St("not-ready");let o=t.target??null;if(!o)return St("invalid-target");if(ER(o)){if(!MR(o))return St("invalid-target");let n=Gt(r);if(!Hl(n))return St("not-ready");let i=ql(n,o);return i?Fn(r,i):St("unresolved")}if(!IR(o)||!AR(o))return St("invalid-target");if(o.type==="comment"){let n=Gt(r);if(!Hl(n))return St("not-ready");let i=e.documentApi?.comments.target(o.id)??null,s=vs(e.documentApi,i),a=s?ql(n,s):null;if(a)return Fn(r,a);let l=Ze(n,i);return l?Fn(r,[l]):St("unresolved")}if(o.type==="trackedChange"){let n=e.documentApi?.trackChanges.get(o.id)??null,i=Gt(r),s=Hl(i)?HR(i,e.documentApi,n):null;if(s)return Fn(r,s);let a=zR(n);return a.length===0?St("unresolved"):Fn(r,a)}return St("invalid-target")}var WR=Object.freeze([]),KR=[],_R=Object.freeze({});function Wl(e){let t=e?.items??KR,r=e?.permissions??_R;return{items:t,permissions:r,total:typeof e?.total=="number"?Math.max(0,Math.trunc(e.total)):t.length,activeCommentId:e?.activeCommentId??null,activeCommentIds:e?.activeCommentIds??WR,enabled:e?.enabled??!1,visible:e?.visible??!1,readOnly:e?.readOnly??!1,showResolved:e?.showResolved??!1,visibility:e?.visibility??null}}function Bf(e){return structuredClone(e)}function Kl(e){return Wl(e?e.session.readState()?.comments??null:null)}function xf(e,t){return At(typeof t=="string"?[t]:[],Ue(Kl(e).items))[0]??null}function Cf(e,t){let r=ws(),o=()=>Bf(Wl(t.getSnapshot())),n=i=>t.subscribe(s=>{i(Bf(Wl(s)))});return{getSnapshot:o,subscribe:n,observe(i){return n(i)},create(i,s){return e.commentActions.createComment(i,s)},reply(i,s,a=null){return e.commentActions.replyComment(i,s,a)},setInternal(i,s){return e.commentActions.setCommentInternal(i,s)},resolve(i){return e.commentActions.resolveComment(i)},reopen(i){return e.commentActions.reopenComment(i)},setActive(i){return r.invalidate(),e.commentFocus.setActiveComment(i)},reveal(i){r.invalidate();let s=Kl(e).activeCommentId??null,a=typeof i=="string"?xf(e,i):null;a&&e.commentFocus.setActiveComment(a);let l=mf(e,i);return!l.selected&&a&&e.commentFocus.setActiveComment(s),l},async scrollTo(i,s){let a=r.begin(),l=Kl(e).activeCommentId??null,c=typeof i=="string"?xf(e,i):null;c&&e.commentFocus.setActiveComment(c);let d=await pf(e,i,s,{continuation:a});return a.shouldContinue()?(!d.success&&c&&e.commentFocus.setActiveComment(l),d):{success:!1}},getAt(i){return ff(e,i,o().items)},getRect({id:i}){return Wo(e,{target:{type:"comment",id:i}})}}}var Pf=["editing","suggesting","viewing"],Rf=["review","original","final","off"],Tf=["paired","independent"],kf=["all","internal","external"];function ys(e,t){return typeof e=="string"&&t.includes(e)}function UR(e){return e.map(t=>`"${t}"`).join(", ")}function bs(e,t,r){return new TypeError(`[BrowserEditor] ${e} must be one of ${UR(r)}; received ${JSON.stringify(t)}.`)}function _l(e){return ys(e,Pf)?e:null}function Bs(e){let t=_l(e);if(t)return t;throw bs("documentMode",e,Pf)}function Xr(e){return ys(e,Rf)?e:null}function Ef(e){let t=Xr(e);if(t)return t;throw bs("trackChanges.mode",e,Rf)}function $r(e){return ys(e,Tf)?e:null}function Mf(e){let t=$r(e);if(t)return t;throw bs("trackChanges.replacements",e,Tf)}function Yr(e){return ys(e,kf)?e:null}function If(e){let t=Yr(e);if(t)return t;throw bs("comments.visibility",e,kf)}function zn(e,t){if(typeof e=="boolean")return e;throw new TypeError(`[BrowserEditor] ${t} must be a boolean; received ${JSON.stringify(e)}.`)}function Hn(e){return e==="paginated"||e==="web"?e:null}function Jr(e){return Hn(e)??"paginated"}function dt(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function dr(e,t){return t==="web"?"vertical":dt(e)??"vertical"}function Qr(e){let t=Jr(e.flowMode),r=dt(e.preferredPaginatedLayoutMode)??dt(e.layoutMode)??"vertical";return{flowMode:t,layoutMode:dr(dt(e.layoutMode)??r,t),preferredPaginatedLayoutMode:r}}import{resolveEditorSelectionRootOffsets as Af}from"@datalking/begonia-editor-contracts";import{listProjectionSelectionRects as ZR,resolveProjectionCaretRect as GR}from"@datalking/begonia-page-layout";function XR(e){return e==="end"||e==="union"?e:"start"}function $R(e){return e?{left:e.left,top:e.top,width:1,height:e.height}:null}function YR(e){if(e.length===0)return null;let t=e[0].left,r=e[0].top,o=e[0].left+e[0].width,n=e[0].top+e[0].height;for(let i of e.slice(1))t=Math.min(t,i.left),r=Math.min(r,i.top),o=Math.max(o,i.left+i.width),n=Math.max(n,i.top+i.height);return{left:t,top:r,width:Math.max(1,o-t),height:Math.max(1,n-r)}}function qn(e,t){let r=qo(e),o=Xt(e)??{};if(!r||!t||t.empty)return[];let n=Af(t);return n?ZR(r,n.from,n.to,o):[]}function Ul(e,t,r={}){let o=qo(e),n=Xt(e)??{};if(!o||!t||!t.empty)return null;let i=Af(t);return i?GR(o,i.from,{bias:r.bias,measureText:n.measureText,measurementEpoch:n.measurementEpoch}):null}function Nf(e,t,r={}){let o=qn(e,t);if(o.length===0)return $R(Ul(e,t));switch(XR(r.placement)){case"end":{let n=o.at(-1)??null;return n?{left:n.left,top:n.top,width:n.width,height:n.height}:null}case"union":return YR(o);default:{let n=o[0]??null;return n?{left:n.left,top:n.top,width:n.width,height:n.height}:null}}}import{cloneEditorSelectionSnapshot as JR}from"@datalking/begonia-editor-contracts";function Ko(e){return e?{empty:e.empty,target:e.target?Et(e.target):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}var Zl=Object.freeze([]);function QR(e){return e?structuredClone(e):void 0}function eT(e){if(!e||!Array.isArray(e.segments))return null;let t=e.segments[0]??null,r=e.segments[e.segments.length-1]??null;if(!t||!r)return null;let o=QR(e.story);return{kind:"selection",start:{kind:"text",blockId:t.blockId,offset:t.range.start,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end,...o?{story:o}:{}},segments:e.segments.map(n=>({blockId:n.blockId,start:n.range.start,end:n.range.end})),...o?{story:o}:{}}}function xs(e,t){if(!e)return null;let r=JR(e),o=Ko(t),n=o?.target??null;return{...r,target:n,selectionTarget:eT(n),activeMarks:o?.activeMarks??Zl,activeCommentIds:o?.activeCommentIds??Zl,activeChangeIds:o?.activeChangeIds??Zl,quotedText:o?.text??""}}import{clonePageViewportAnchor as zf,hasFreshViewportRequest as iT,normalizeViewportRequestKey as sT,samePageViewportAnchor as aT,sameViewportRequestKey as lT}from"@datalking/begonia-layout-renderer/core";import{hasLogicalViewportAnchorHint as tT}from"@datalking/begonia-layout-renderer/core";var Wn=100,Nt=1,Of=1e-6;function Ge(e){return typeof e=="number"&&Number.isFinite(e)}function vt(e,t,r=0){return e===t||Math.abs(e-t)<=r}function jf(e,t,r=0){return e==null||t==null?e===t:vt(e,t,r)}function Vf(e,t=0){return Ge(e)?Math.max(0,Math.trunc(e)):t}function Xl(e){return Ge(e)&&Number.isInteger(e)&&e>=0?e:null}function eo(e){return Ge(e)&&Number.isInteger(e)&&e>0?e:null}function Gl(e,t){if(!Array.isArray(e))return[];let r=e.filter(o=>Ge(o)&&Number.isInteger(o)&&o>=t);return[...new Set(r)].sort((o,n)=>o-n)}function rT(e){return e.map(t=>t+1)}function Df(e){return e.map(t=>t-1)}function oT(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function $l(e,t){let r=Gl(t,1);if(r.length>0){let n=Gl(e,0);return n.length>0&&!oT(Df(r),n)?null:{pageIndexes:Df(r),pageNumbers:r}}let o=Gl(e,0);return{pageIndexes:o,pageNumbers:rT(o)}}function Yl(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function Jl(e){return e==="paginated"||e==="web"?e:null}function Lf(e){return Ge(e)&&e>0?e:null}function Ql(e,t){let r=Jl(e),o=Yl(t);return e!=null&&r==null||t!=null&&o==null?null:r==="web"?o!=null&&o!=="vertical"?null:{flowMode:r,layoutMode:"vertical"}:{flowMode:r,layoutMode:o}}function nT(e){return e==="header"||e==="body"||e==="footer"}function Ff(e){return nT(e?.region)&&!tT(e)&&e?.fragmentIndex==null&&e?.columnIndex==null&&e?.blockOffsetTopPx==null&&e?.blockOffsetTopRatio==null&&e?.blockOffsetLeftPx==null&&e?.blockOffsetLeftRatio==null}function $t(e,t){let r=eo(t),o=Xl(e);return r!=null&&o!=null&&o!==r-1?{pageIndex:null,pageNumber:null}:{pageIndex:r!=null?r-1:o,pageNumber:r??(o!=null?o+1:null)}}function cT(e){if(e.visiblePageNumbers.length>0){let o=eo(e.firstVisiblePageNumber),n=eo(e.lastVisiblePageNumber);return o!=null&&o!==e.visiblePageNumbers[0]||n!=null&&n!==e.visiblePageNumbers[e.visiblePageNumbers.length-1]?null:{firstVisiblePageNumber:e.visiblePageNumbers[0]??null,lastVisiblePageNumber:e.visiblePageNumbers[e.visiblePageNumbers.length-1]??null}}let t=eo(e.firstVisiblePageNumber),r=eo(e.lastVisiblePageNumber);return t!=null&&r!=null&&t>r?null:{firstVisiblePageNumber:t,lastVisiblePageNumber:r}}function dT(e){return!!(e&&typeof e=="object"&&(Object.hasOwn(e,"pageNumber")||Object.hasOwn(e,"pageIndex")))}function Hf(e,t,r){let o=Ge(t)?Math.max(0,t):Math.max(0,(Ge(r)?r:e)-e);return{size:o,end:e+o}}var uT=10,mT=500;function ht(e){return!Ge(e)||e<=0?null:Math.min(mT,Math.max(uT,e))}function De(e){return sT(e)}function Ps(e,t){return lT(e,t)}function tc(e,t){return iT(e,t)}function ur(e){return ht(e?.zoomPercent)??Wn}function _o(e,t){return re(e)?.flowMode===t}function Uo(e,t){return re(e)?.layoutMode===t}function to(e,t,r){return _o(e,t)&&Uo(e,r)}function Cs(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Zo(e,t){return aT(e,t)}function ec(e){let t=eo(e?.pageNumber),r=Xl(e?.pageIndex);if(t==null&&r==null||t!=null&&r!=null&&r!==t-1)return null;let o=t??(r??0)+1;return{pageIndex:o-1,pageNumber:o}}function Go(e,t=null){if(e&&typeof e=="object"&&dT(e)&&!ec(e))return null;let r=zf(e);if(r)return r;if(!e||typeof e!="object")return null;let o=ec(e)??ec(t);return o?zf({...e,...o}):null}function Xo(e){let t=$t(e?.anchorPageIndex,e?.anchorPageNumber).pageNumber??$t(e?.currentPageIndex,e?.currentPageNumber).pageNumber,r=Go(e?.viewportAnchor??null,{pageNumber:t});return r?t!=null&&r.pageNumber!==t?Ff(r)?r:null:r:null}function rc(e,t,r){let o=Ql(e?.flowMode,e?.layoutMode);if(e&&typeof e=="object"&&o==null)return!0;let n=o?.flowMode??null,i=o?.layoutMode??null;return n!=null&&n!==t||i!=null&&i!==r}function ot(e,t){let r=re(e),o=re(t);return!r||!o?r===o:Kn(r,o)&&Cs(r.mountedPageIndexes,o.mountedPageIndexes)&&Cs(r.mountedPageNumbers,o.mountedPageNumbers)&&vt(r.topSpacer,o.topSpacer,Nt)&&vt(r.bottomSpacer,o.bottomSpacer,Nt)&&vt(r.leftSpacer,o.leftSpacer,Nt)&&vt(r.rightSpacer,o.rightSpacer,Nt)}function Kn(e,t){let r=re(e),o=re(t);return!r||!o?r===o:r.totalPages===o.totalPages&&r.currentPageIndex===o.currentPageIndex&&r.currentPageNumber===o.currentPageNumber&&r.anchorPageIndex===o.anchorPageIndex&&r.anchorPageNumber===o.anchorPageNumber&&Zo(r.viewportAnchor,o.viewportAnchor)&&Cs(r.visiblePageIndexes,o.visiblePageIndexes)&&Cs(r.visiblePageNumbers,o.visiblePageNumbers)&&r.firstVisiblePageNumber===o.firstVisiblePageNumber&&r.lastVisiblePageNumber===o.lastVisiblePageNumber&&vt(r.viewportTop,o.viewportTop,Nt)&&vt(r.viewportBottom,o.viewportBottom,Nt)&&vt(r.viewportHeight,o.viewportHeight,Nt)&&vt(r.viewportLeft,o.viewportLeft,Nt)&&vt(r.viewportRight,o.viewportRight,Nt)&&vt(r.viewportWidth,o.viewportWidth,Nt)&&r.layoutMode===o.layoutMode&&r.flowMode===o.flowMode&&jf(r.scale,o.scale,Of)}function re(e){if(!e||typeof e!="object")return null;let t=Ql(e.flowMode,e.layoutMode);if(!t)return null;let r=$t(e.currentPageIndex,e.currentPageNumber),o=$t(e.anchorPageIndex,e.anchorPageNumber),n=Ge(e.viewportTop)?e.viewportTop:0,i=Ge(e.viewportLeft)?e.viewportLeft:0,s=Hf(n,e.viewportHeight,e.viewportBottom),a=Hf(i,e.viewportWidth,e.viewportRight),l=$l(e.visiblePageIndexes,e.visiblePageNumbers);if(!l)return null;let c=$l(e.mountedPageIndexes,e.mountedPageNumbers);if(!c)return null;let d=cT({visiblePageNumbers:l.pageNumbers,firstVisiblePageNumber:e.firstVisiblePageNumber,lastVisiblePageNumber:e.lastVisiblePageNumber});if(!d)return null;let u=Go(e.viewportAnchor,{pageIndex:o.pageIndex??r.pageIndex,pageNumber:o.pageNumber??r.pageNumber});return{totalPages:Vf(e.totalPages),currentPageIndex:r.pageIndex,currentPageNumber:r.pageNumber,anchorPageIndex:o.pageIndex,anchorPageNumber:o.pageNumber,viewportAnchor:u,visiblePageIndexes:l.pageIndexes,visiblePageNumbers:l.pageNumbers,mountedPageIndexes:c.pageIndexes,mountedPageNumbers:c.pageNumbers,firstVisiblePageNumber:d.firstVisiblePageNumber,lastVisiblePageNumber:d.lastVisiblePageNumber,viewportTop:n,viewportBottom:s.end,viewportHeight:s.size,viewportLeft:i,viewportRight:a.end,viewportWidth:a.size,topSpacer:Ge(e.topSpacer)?Math.max(0,e.topSpacer):0,bottomSpacer:Ge(e.bottomSpacer)?Math.max(0,e.bottomSpacer):0,leftSpacer:Ge(e.leftSpacer)?Math.max(0,e.leftSpacer):0,rightSpacer:Ge(e.rightSpacer)?Math.max(0,e.rightSpacer):0,layoutMode:t.layoutMode,flowMode:t.flowMode,scale:Lf(e.scale)}}function Yt(e,t){let r=re(e);if(!r)return null;let o=r.flowMode??Jl(t.flowMode),n=o==="web"?"vertical":r.layoutMode??Yl(t.layoutMode);return{...r,flowMode:o,layoutMode:n}}var pT=Object.freeze({percent:100,mode:"manual",value:100,fitZoom:null,min:10,max:400,viewportMetrics:null});function $o(e){return{getSnapshot(){return e.get()},subscribe(t){return e.subscribe(t)},observe(t){return e.subscribe(t)}}}function fT(e){let t=Qr(e);return{flowMode:t.flowMode,layoutMode:t.layoutMode,preferredPaginatedLayoutMode:t.preferredPaginatedLayoutMode,zoom:qf(e)}}function wT(e){return xs(e.selection,e.selectionInfo)}function gT(e){return{editable:e.editable,documentMode:_l(e.documentMode),trackingEnabled:e.trackingEnabled,trackChanges:{enabled:e.review.enabled,visible:e.review.visible,mode:Xr(e.review.mode),replacementMode:$r(e.review.replacementMode)}}}function ST(e){return{enabled:e.comments.enabled,visible:e.comments.visible,readOnly:e.comments.readOnly,allowResolve:e.comments.allowResolve??!1,showResolved:e.comments.showResolved,visibility:Yr(e.comments.visibility),useInternalExternalComments:e.comments.useInternalExternalComments??!1,suppressInternalExternal:e.comments.suppressInternalExternal??!1,enforceVisibilityPolicy:e.comments.enforceVisibilityPolicy??!1,total:e.comments.total??e.comments.items.length}}function qf(e){return e.zoom?{percent:e.zoom.percent,mode:e.zoom.mode==="fit-width"?"fit-width":"manual",value:typeof e.zoom.value=="number"?e.zoom.value:e.zoom.percent,fitZoom:typeof e.zoom.fitZoom=="number"?e.zoom.fitZoom:null,min:typeof e.zoom.min=="number"?e.zoom.min:10,max:typeof e.zoom.max=="number"?e.zoom.max:400,viewportMetrics:e.zoom.viewportMetrics}:pT}function vT(e){if(!e.viewport)return null;let t=re(e.viewport.value);return{value:t,requestKey:e.viewport.requestKey,previewNavigationRequest:e.viewport.previewNavigationRequest,totalPages:t?.totalPages??null,currentPageIndex:t?.currentPageIndex??null,currentPageNumber:t?.currentPageNumber??null}}function Wf(e,t){return{...$o(t.select(fT)),setViewState(o){e.view.setViewState(o)},getZoomState(){return e.view.getZoomState()},setZoomMode(o){e.view.setZoomMode(o)}}}function Kf(e,t){let r=$o(t.select(wT));return{...r,getRects(){return qn(e.preview,r.getSnapshot())},getAnchorRect(o){return Nf(e.preview,r.getSnapshot(),o)},getCaretRect(o){return Ul(e.preview,r.getSnapshot(),o)}}}function _f(e,t){return{...$o(t.select(gT)),setDocumentMode(o){e.documentMode.setDocumentMode(o)},setTrackChangesDisplayMode(o){e.documentMode.setTrackChangesDisplayMode(o)}}}function Uf(e,t){return{...$o(t.select(ST)),setCommentsVisible(o){e.commentsDisplay.setCommentsVisible(o)},setCommentsShowResolved(o){e.commentsDisplay.setCommentsShowResolved(o)},setCommentsVisibility(o){e.commentsDisplay.setCommentsVisibility(o)}}}function Zf(e,t){return{...$o(t.select(qf)),set(o){e.view.setViewState({zoomPercent:o})},setMode(o){e.view.setZoomMode(o)}}}function Gf(e,t){return{...$o(t.select(vT)),getHost(){return e.browserViewport.getHost?.()??null},getScrollContainer(){return e.browserViewport.getScrollContainer?.()??null},observeGeometry(o){return e.browserViewport.observeGeometry(o)},scrollIntoView(o){return e.browserViewport.scrollIntoView(o)},getRect(o){return Wo(e,o)},entitiesAtPoint(o){return e.browserViewport.entitiesAtPoint(o)},contextAtPoint(o){return e.browserViewport.contextAtPoint(o)},positionAtPoint(o){return e.browserViewport.positionAtPoint(o)},requestNavigation(o){return e.browserViewport.requestNavigation(o)},requestNavigationForTextTarget(o){return e.browserViewport.requestNavigationForTextTarget(o)},ackNavigationRequest(o){e.browserViewport.ackNavigationRequest(o)}}}import{isIntegerPath as hT}from"@datalking/begonia-document-model";function Yo(e={}){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,...e}}function yT(e){return Array.isArray(e)&&e.length>0&&hT(e)}function Rs(e){return!!e&&typeof e=="object"&&yT(e.blockPath)}function $f(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;let t="revisionId"in e?e.revisionId:"id"in e?e.id:null;return typeof t=="string"&&t.length>0?t:null}function bT(e){return e?Rs(e.target)?e.target:(e.targets??[]).find(Rs)??null:null}function BT(e){let t="target"in e?e.target:null,r="targets"in e?e.targets:null;return Rs(t)||(r??[]).some(Rs)}function xT(e,t){if(typeof t!="string"&&BT(t))return t;let r=$f(t);return r?e.documentApi.trackChanges.get(r):null}function CT(e,t){let r=Gt(cf(e));return zl(e.documentApi,PT(r)?r:null,t)}function PT(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function RT(e,t){return(typeof t?.id=="string"&&t.id.length>0?t.id:typeof t?.revisionId=="string"&&t.revisionId.length>0?t.revisionId:null)??e}function _n(e,t){if(!e||!t)return Yo();let r=he(e);if(!r)return Yo();let o=$f(t),n=xT(r,t);if(!n)return Yo({revisionId:o});let i=RT(o,n),s=CT(r,n),a=s.target??bT(n);if(!a)return Yo({revisionId:i,trackChange:n});let l=s.selectionTarget;return Yo(l?{revisionId:i,trackChange:n,target:a,selectionTarget:l}:{revisionId:i,trackChange:n,target:a})}function Xf(){return{success:!1}}function TT(e){let t=e.revisionId;if(typeof t=="string"&&t.length>0)return t;let r=e.trackChange?.id;return typeof r=="string"&&r.length>0?r:null}async function Ts(e,t,r={},o={}){let n=_n(e,t),i=he(e);return!i||!n.selectionTarget?Xf():ps(i.selectionHandles,async()=>{if(i.selectionTargets.selectTextTarget(n.selectionTarget))return i.browserViewport.scrollIntoView({target:n.selectionTarget,timeoutMs:r.timeoutMs,continuation:o.continuation});let s=TT(n);return s?i.browserViewport.scrollIntoView({target:{type:"trackedChange",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Xf()},{shouldContinue:o.continuation?.shouldContinue})}function Yf(e){if(e==null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jo(e,t){if(Object.is(e,t))return!0;if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Jo(e[n],t[n]))return!1;return!0}if(!Yf(e)||!Yf(t))return!1;let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let n of r)if(!Object.hasOwn(t,n)||!Jo(e[n],t[n]))return!1;return!0}function oc(e,t,r){let o=e.filter(s=>typeof s.id=="string"&&s.id.length>0);if(o.length===0)return null;let n=t==null?-1:o.findIndex(s=>s.id===t),i=r==="next"?n<0||n>=o.length-1?0:n+1:n<=0?o.length-1:n-1;return o[i]?.id??null}function kT(e){return e.find(t=>t.type==="trackedChange")??null}function ET(e){return[...new Set(e.filter(t=>t.type==="trackedChange").map(t=>t.id))]}function MT(e,t){return e.find(r=>r.id===t)??null}function IT(e,t){let r=ET(t);if(r.length!==1)return null;let o=r[0]??kT(t)?.id??null;if(!o)return null;let n=MT(e,o);return!n||typeof n.id!="string"||n.id.length===0?null:{id:n.id,item:n}}function Jf(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=he(e);return o?IT(r,o.browserViewport.entitiesAtPoint(t)):null}var Qf=Object.freeze([]),AT=Object.freeze([]),NT=Object.freeze([]),DT=Object.freeze({});function nc(e){return structuredClone(e)}function OT(){return{items:AT,permissions:DT,timeline:NT,summary:null,total:0,activeRevisionId:null,activeRevisionIds:Qf,enabled:!1,visible:!1,mode:null,replacementMode:null}}function jT(e,t){return Jo(e,t)}function VT(e){return e?{items:e.revisions,permissions:e.permissions,timeline:e.timeline,summary:e.summary,total:e.revisions.length,activeRevisionId:e.activeRevisionId??null,activeRevisionIds:e.activeRevisionIds??Qf,enabled:e.enabled,visible:e.visible,mode:e.mode,replacementMode:e.replacementMode}:OT()}function Pr(e){let r=he(e)?.session.readState();return VT(r?.review)}function sc(){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,selected:!1}}function ic(e,t){let r=he(e);if(!r||!t)return sc();let o=_n(e,t);if(!o.selectionTarget)return{...o,selected:!1};let n=r.selectionTargets.selectTextTarget(o.selectionTarget),i=r.browserViewport.requestNavigationForTextTarget(o.selectionTarget);return{...o,navigationRequest:i,selected:n}}function en(e,t){let r=he(e);return r?r.reviewFocus.setActiveRevision(t):!1}function Qo(e,t){let r=he(e);return r?t==="next"?r.reviewFocus.nextActiveRevision():r.reviewFocus.previousActiveRevision():null}async function LT(e,t,r,o){if(!he(e))return{success:!1};let i=Pr(e).activeRevisionId??null,s=_n(e,t);s.revisionId&&en(e,s.revisionId);let a=await Ts(e,t,r,{continuation:o});return o.shouldContinue()?(!a.success&&s.revisionId&&en(e,i),a):{success:!1}}function ew(e){let t=he(e);if(!t)throw new Error("createBrowserEditorTrackChangesController requires a valid browser editor UI source.");let r=Pr(e),o=null,n=new Set,i=ws(),s=()=>{o||n.size===0||(o=t.session.subscribe(()=>{let c=Pr(e);if(jT(r,c)){r=c;return}r=c;for(let d of[...n])d(nc(r))}))},a=()=>{n.size>0||!o||(o(),o=null)},l=c=>(r=Pr(e),n.add(c),s(),c(nc(r)),()=>{n.delete(c),a()});return{getSnapshot(){return r=Pr(e),nc(r)},subscribe:l,observe(c){return l(c)},accept(c){return t.reviewActions.acceptRevision(c)},reject(c){return t.reviewActions.rejectRevision(c)},acceptAll(){return t.reviewActions.acceptAll()},rejectAll(){return t.reviewActions.rejectAll()},setActive(c){return i.invalidate(),en(e,c)},next(){return i.invalidate(),Qo(e,"next")},previous(){return i.invalidate(),Qo(e,"previous")},reveal(c){i.invalidate();let d=_n(e,c);return d.revisionId&&en(e,d.revisionId),ic(e,c)},revealNext(){i.invalidate();let c=Qo(e,"next");return c?ic(e,c):sc()},revealPrevious(){i.invalidate();let c=Qo(e,"previous");return c?ic(e,c):sc()},getAt(c){return r=Pr(e),Jf(e,c,r.items)},scrollTo(c,d){return LT(e,c,d,i.begin())},navigateNext(c){let d=i.begin(),u=Pr(e).activeRevisionId??null,m=Qo(e,"next");return m?Ts(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||en(e,u),p):{success:!1}):Promise.resolve({success:!1})},navigatePrevious(c){let d=i.begin(),u=Pr(e).activeRevisionId??null,m=Qo(e,"previous");return m?Ts(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||en(e,u),p):{success:!1}):Promise.resolve({success:!1})},getRect({id:c}){return Wo(t,{target:{type:"trackedChange",id:c}})}}}function ks(e){let t=FT(e.session),r=Kf(e,t),o=Wf(e,t),n=_f(e,t),i=Uf(e,t),s=Gf(e,t),a=Zf(e,t),l=Cf(e,t.comments),c=ew(e),d=Object.assign(t,{host:e,session:e.session,documentApi:e.documentApi,readCommandSnapshot(u){return e.readCommandSnapshot(u)},selection:r,selectionHandles:e.selectionHandles,linkSelection:e.linkSelection,activeLink:e.activeLink,view:o,documentMode:n,comments:l,commentsDisplay:i,commentActions:e.commentActions,commentFocus:e.commentFocus,reviewActions:e.reviewActions,reviewFocus:e.reviewFocus,trackChanges:c,selectionTargets:e.selectionTargets,viewport:s,zoom:a,browserViewport:e.browserViewport,preview:e.preview,overlayState:e.overlayState,overlays:e.overlays??{}});return Object.defineProperty(d,"actor",{configurable:!1,enumerable:!0,get(){return e.actor}}),d}var zT=["insert-math-inline","insert-chart-block","insert-shape-block","remove-selected-ooxml","selected-math-set-plain-text","selected-math-toggle-display-mode","selected-chart-set-title","selected-chart-add-series","selected-chart-add-axis","selected-shape-set-text-body","selected-shape-set-fill","selected-shape-add-child"],HT=new Set(zT);function tw(e){return HT.has(e)}function D(e,t,r,o,n=[],i=!0){return{id:e,title:t,group:r,description:o,keywords:n,slash:i}}var Un=Object.freeze([D("undo","Undo","history","Revert the latest local editing step.",["history"],!1),D("redo","Redo","history","Re-apply the latest reverted step.",["history"],!1),D("zoom","Zoom","view","Set the document zoom level as a percentage.",["view","scale","percent"],!1),D("zoom-fit-width","Fit Width","view","Toggle fit-width zoom mode for the current viewport.",["view","scale","fit","width"],!1),D("document-mode-editing","Editing Mode","review","Switch the editor into direct editing mode.",["edit","write","author"],!1),D("document-mode-suggesting","Suggesting Mode","review","Switch the editor into suggestion authoring mode.",["suggest","track changes","review"],!1),D("document-mode-viewing","Viewing Mode","review","Switch the editor into read-only viewing mode.",["view","read-only","preview"],!1),D("flow-mode-paginated","Paginated Layout","view","Switch the editor into paginated layout mode.",["pagination","pages","print"],!1),D("flow-mode-web","Web Layout","view","Switch the editor into continuous web layout mode.",["web","continuous","scroll"],!1),D("layout-mode-vertical","Vertical Spread","view","Arrange paginated pages in a vertical stack.",["vertical","stack"],!1),D("layout-mode-horizontal","Horizontal Spread","view","Arrange paginated pages in a horizontal strip.",["horizontal","row"],!1),D("layout-mode-book","Book Spread","view","Arrange paginated pages in facing book spreads.",["book","spread","facing"],!1),D("track-changes-display-review","Review Markup","review","Display the document with review markup visible.",["markup","review mode"],!1),D("track-changes-display-original","Original Document","review","Project the document back to its original review baseline.",["original","projection"],!1),D("track-changes-display-final","Final Document","review","Project the document forward to its final accepted review state.",["final","projection"],!1),D("track-changes-display-off","Hide Review Markup","review","Hide tracked-change markup without switching authoring mode.",["hide markup","off"],!1),D("bold","Bold","format","Toggle bold formatting.",["strong","weight"]),D("italic","Italic","format","Toggle italic formatting.",["emphasis"]),D("underline","Underline","format","Toggle underline formatting.",["decoration"]),D("strikethrough","Strikethrough","format","Toggle strikethrough formatting.",["strike","delete","decoration"]),D("font-size","Font Size","format","Set or clear the font size on the current text selection.",["type","points"],!1),D("font-family","Font Family","format","Set or clear the font family on the current text selection.",["typeface","font"],!1),D("text-color","Text Color","format","Set or clear the text color on the current text selection.",["color","foreground"],!1),D("highlight-color","Highlight Color","format","Set or clear text highlight on the current selection.",["highlight","background"],!1),D("paragraph","Paragraph","block","Reset the current block to body paragraph text.",["body","normal"]),D("heading-1","Heading 1","block","Promote the current block to the top heading level.",["title","h1"]),D("heading-2","Heading 2","block","Promote the current block to a section heading.",["section","h2"]),D("heading-3","Heading 3","block","Promote the current block to a subsection heading.",["subsection","h3"]),D("bullet-list","Bulleted List","block","Toggle a bulleted list around the current block.",["list","bullets","unordered"]),D("numbered-list","Numbered List","block","Toggle a numbered list around the current block.",["list","ordered","numbers"]),D("insert-math-inline","Insert Equation","insert","Append an editable math OOXML node to the active text block.",["equation","math","formula"]),D("insert-chart-block","Insert Chart","insert","Insert an editable chart OOXML block after the current block.",["chart","graph","series"]),D("insert-shape-block","Insert Shape","insert","Insert an editable shape OOXML block after the current block.",["shape","callout","diagram"]),D("remove-selected-ooxml","Remove Selected OOXML","insert","Remove the currently selected advanced OOXML node.",["equation","chart","shape","delete"]),D("selected-math-set-plain-text","Edit Selected Equation","insert","Replace the currently selected math OOXML node with plain-text math content.",["equation","math","formula"],!1),D("selected-math-toggle-display-mode","Toggle Equation Display Mode","insert","Switch the selected OOXML equation between inline and block display mode.",["equation","math","display"],!1),D("selected-chart-set-title","Edit Selected Chart Title","insert","Update the title on the currently selected chart OOXML node.",["chart","title"],!1),D("selected-chart-add-series","Add Selected Chart Series","insert","Append a new data series to the currently selected chart OOXML node.",["chart","series","data"],!1),D("selected-chart-add-axis","Add Selected Chart Axis","insert","Append a new axis to the currently selected chart OOXML node.",["chart","axis","scale"],!1),D("selected-shape-set-text-body","Edit Selected Shape Text","insert","Update the text body on the currently selected shape OOXML node.",["shape","text"],!1),D("selected-shape-set-fill","Edit Selected Shape Fill","insert","Update the fill color on the currently selected shape OOXML node.",["shape","fill","color"],!1),D("selected-shape-add-child","Add Selected Shape Child","insert","Append a child shape node to the currently selected OOXML shape.",["shape","group","child"],!1),D("link-set","Set Link","insert","Apply or update a link on the current selection.",["hyperlink","url"],!1),D("link-clear","Clear Link","insert","Remove link formatting from the current selection.",["unlink"],!1),D("comment-create","Create Comment","review","Create a comment at the current selection or caret.",["comment","annotation","note"],!1),D("comments-visible","Show Comments","review","Show comment highlights and threads in the browser editor.",["comments","visible"],!1),D("comments-hidden","Hide Comments","review","Hide comment highlights and threads in the browser editor.",["comments","hidden"],!1),D("comments-show-resolved","Show Resolved Comments","review","Include resolved comments in the comment list and review timeline.",["comments","resolved"],!1),D("comments-hide-resolved","Hide Resolved Comments","review","Filter resolved comments out of the comment list and review timeline.",["comments","resolved"],!1),D("comments-visibility-all","All Comments","review","Show both internal and external comments.",["comments","all"],!1),D("comments-visibility-internal","Internal Comments","review","Filter the comment display to internal comment threads.",["comments","internal"],!1),D("comments-visibility-external","External Comments","review","Filter the comment display to external comment threads.",["comments","external"],!1),D("tracking-toggle","Toggle Track Changes","review","Switch between direct editing and suggestion mode.",["suggesting","review","changes"]),D("track-changes-accept-selection","Accept Selection Changes","review","Accept tracked revisions that overlap the current selection.",["track changes","selection","accept"],!1),D("track-changes-reject-selection","Reject Selection Changes","review","Reject tracked revisions that overlap the current selection.",["track changes","selection","reject"],!1),D("search-set-query","Search","search","Run a document search query.",["find"],!1),D("search-next","Next Search Result","search","Advance to the next current search hit.",["find","next"],!1),D("search-previous","Previous Search Result","search","Move back to the previous current search hit.",["find","previous"],!1),D("search-clear","Clear Search","search","Clear the current search session.",["find","reset"]),D("search-replace-active","Replace Current Search Result","search","Replace the active current search hit.",["find","replace"],!1),D("search-replace-all","Replace All Search Results","search","Replace every current search hit.",["find","replace","all"],!1),D("review-accept-all","Accept All Changes","review","Accept all tracked revisions in the document.",["track changes","approve"]),D("review-reject-all","Reject All Changes","review","Reject all tracked revisions in the document.",["track changes","discard"]),D("proofing-ignore-first","Ignore First Proofing Issue","proofing","Ignore the first current proofing diagnostic.",["spelling","grammar","ignore"]),D("proofing-accept-first","Accept First Proofing Suggestion","proofing","Apply the first current proofing suggestion without tracking.",["spelling","grammar","fix"]),D("proofing-replace-first-tracked","Track First Proofing Fix","proofing","Apply the first current proofing suggestion with tracked changes.",["spelling","grammar","review"],!1)]),bq=Object.freeze(Un.map(e=>e.id)),tn=Object.freeze(Un.filter(e=>!tw(e.id))),Bq=Object.freeze(tn.map(e=>e.id)),xq=new Map(Un.map(e=>[e.id,e]));function qT(e){let t=e.members?.length?e.members:null;return t?t.every(r=>(r.text?.length??0)===0&&r.target?.nodeType!=="text"):(e.text?.length??0)===0&&e.target?.nodeType!=="text"}function WT(e,t){if(!t||e.length===0)return!1;let r=new Map(t.map(o=>[o.id,o]));return e.every(o=>{let n=r.get(o);return n?qT(n):!1})}function ac(e,t){return ce([...e.activeChangeIds??[],...e.selection.trackedChangeIds??[]],t)}function lc(e){let t=ce(e.liveSelectionInfo?.activeChangeIds,e.revisions);return t.length>0?t:ce(e.liveSelection.trackedChangeIds,e.revisions)}function KT(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&!e.effectiveSelection.selection.empty&&e.liveSelection.from>=e.effectiveSelection.selection.from&&e.liveSelection.from<=e.effectiveSelection.selection.to}function _T(e,t){return e.length>0&&e.length<t.length&&e.every(r=>t.includes(r))}function UT(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.liveReviewChangeIds.length>0&&e.effectiveReviewChangeIds.length>0&&!(KT(e)&&_T(e.liveReviewChangeIds,e.effectiveReviewChangeIds))&&!ar(e.liveReviewChangeIds,e.effectiveReviewChangeIds)}function ZT(e){let t=ac(e.effectiveSelection,e.revisions),r=lc({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions});return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&!e.effectiveSelection.selection.empty&&e.liveSelection.from===(e.boundary==="start"?e.effectiveSelection.selection.from:e.effectiveSelection.selection.to)&&e.effectiveSelection.selection.from!==e.effectiveSelection.selection.to&&r.length===0&&t.length>0}function cc(e){return ZT({...e,boundary:"end"})}function GT(e){let t=ac(e.effectiveSelection,e.revisions),r=lc({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions}),o=WT(t,e.revisions);return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.effectiveSelection.selection.empty&&e.liveSelection.from===e.effectiveSelection.selection.to&&r.length===0&&t.length>0&&!o}function yt(e){let t=lc(e);if(!e.effectiveSelection)return t;if(cc({liveSelection:e.liveSelection,liveActiveChangeIds:de(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];if(GT({liveSelection:e.liveSelection,liveActiveChangeIds:de(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];let r=ac(e.effectiveSelection,e.revisions);return UT({liveSelection:e.liveSelection,liveReviewChangeIds:t,effectiveReviewChangeIds:r,effectiveSelection:e.effectiveSelection})?t:r.length>0?r:t}import{readSyntheticSideStoryDocOriginPath as XT}from"@datalking/begonia-doc-service/v1";var $T="Detached side-story surfaces are read-only. Route mutations through the host document controller.";function rn(e){return XT(e?.document??null)!=null}function Jt(e){return e?rn(e)?$T:e.editable?null:"Document is read-only in the current document mode.":"Editor is not ready."}function nt(e){return Jt(e)==null}function Es(e){if(!e)return"Editor is not ready.";let t=Jt({editable:e.editable,document:e.document});return t||(e.commentsDisplay.enabled?e.commentsDisplay.readOnly?"Comments are read-only in the current document mode.":null:"Comments are disabled for this editor.")}function dc(e,t,r=null){let o=Es(e);return o||(r?.target||r?.selectionTarget||t&&Ht(t)?null:"Place the caret in text or select text before creating a comment.")}function YT(e){return Xi([...e.activeChangeIds??[],...e.selection?.trackedChangeIds??[]])}function Rr(e,t=YT(e)){return fl({empty:e.empty,target:e.selectionTarget,activeMarks:[...e.activeMarks??[]],activeCommentIds:[...e.activeCommentIds??[]],activeChangeIds:[...t],...typeof e.text=="string"?{text:e.text}:{}},e.selectionKind,e.selectionKind==="node"&&e.selectionTarget!=null&&e.nodeSelectionTarget!=null)}import{createEditorSelectionSnapshot as JT}from"@datalking/begonia-editor-contracts";import{resolveEditorSelectionRootOffsets as rw}from"@datalking/begonia-editor-contracts";function Ms(e){let t=rw(e);return t?{...t,empty:e.empty,trackedChangeIds:e.trackedChangeIds}:null}function ow(e){let t=rw(e);return t?{kind:e.kind,...t,empty:e.empty,editable:e.editable,trackedChangeIds:[...e.trackedChangeIds],block:{...e.block},formatting:structuredClone(e.formatting)}:null}function H(e,t=!0,r=!1,o=null,n=!1){return{active:r,disabled:t,...n?{mixed:!0}:{},value:o,title:e.title,description:e.description??null,group:e.group??null}}function on(e){let t=Qr(e);return t.flowMode==="web"?t.preferredPaginatedLayoutMode:t.layoutMode}function nw(e){return e.flowMode==="paginated"||e.flowMode==="web"}function iw(e){return e.zoom?.mode==="fit-width"?"fit-width":"manual"}function sw(e,t,r,o){return e!=null||!t||r?e:`Collapsed ${o} formatting requires a live editor surface. Select text to format in headless mode.`}function aw(e,t){return e||!t}function lw(e){let t=e&&typeof e=="object"?e.nodeType:null;return t==="paragraph"||t==="heading"}function QT(e,t){return t?t.selectionKind==="node"&&lw(t.nodeSelectionTarget):lw(Ae(e??null))}function nn(e){let t=e?.catalog??tn,r=e?.commandIds;if(!r||r.length===0)return t;let o=e?.catalog??Un,n=new Map(o.map(i=>[i.id,i]));return r.map(i=>n.get(i)).filter(i=>i!=null)}function cw(e){return e.revisions}function dw(e,t){let r=Qr(e),o=e.search.activeHitId?e.search.hits.findIndex(l=>l.hitId===e.search.activeHitId):-1,n=cw(e),i=re(e.viewport),s=t?JT(t.selection,e.selection.range.revision,e.selection.range.range.anchor.story):e.toolbar.selection??e.selection,a=t?Rr(t):e.selectionInfo;return{selection:mw(s,a,n),documentMode:e.documentMode,editable:e.editable,trackChanges:e.trackChanges,flowMode:r.flowMode,layoutMode:r.layoutMode,preferredPaginatedLayoutMode:r.preferredPaginatedLayoutMode,zoomPercent:e.zoomPercent,viewport:i,totalPages:i?.totalPages??null,currentPageIndex:i?.currentPageIndex??null,currentPageNumber:i?.currentPageNumber??null,searchQuery:e.search.query,searchHitCount:e.search.hits.length,activeSearchHitId:e.search.activeHitId,activeSearchHitIndex:o,revisionCount:n.length,firstRevisionId:n[0]?.id??null,proofingDiagnosticCount:e.proofing.diagnostics.length,firstProofingDiagnosticId:e.proofing.diagnostics[0]?.diagnosticId??null}}function uw(e,t,r,o,n,i){let s=i?.selection??ow(t.selection)??{from:0,to:0,empty:!0},a=t.trackChanges.enabled,l=cw(t),c=yt({liveSelection:Ms(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:l,effectiveSelection:i}),d=t.editable?ir({editable:t.editable},o,i):"Document is read-only in the current document mode.",u=sw(d,s.empty,n,"inline"),m=sw(d,s.empty,n,"text-style"),p=t.editable?dc({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i):dc({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i),f=QT(o,i),g=aw(!t.editable||!s.editable&&!f,n),v=s.formatting.mixed??{},k=aw(d!=null,n);switch(r.id){case"bold":return H(r,u!=null,s.formatting.bold,s.formatting.bold,v.bold===!0);case"italic":return H(r,u!=null,s.formatting.italic,s.formatting.italic,v.italic===!0);case"underline":return H(r,u!=null,s.formatting.underline,s.formatting.underline,v.underline===!0);case"strikethrough":return H(r,u!=null,s.formatting.strike,s.formatting.strike,v.strike===!0);case"font-size":return H(r,m!=null,s.formatting.fontSize!=null||v.fontSize===!0,s.formatting.fontSize,v.fontSize===!0);case"font-family":return H(r,m!=null,s.formatting.fontFamily!=null||v.fontFamily===!0,s.formatting.fontFamily,v.fontFamily===!0);case"text-color":return H(r,m!=null,s.formatting.color!=null||v.color===!0,s.formatting.color,v.color===!0);case"highlight-color":return H(r,m!=null,s.formatting.highlight!=null||v.highlight===!0,s.formatting.highlight,v.highlight===!0);case"paragraph":return H(r,g,s.block.kind==="paragraph",s.block.kind);case"heading-1":return H(r,g,s.block.kind==="heading"&&s.block.headingLevel===1,s.block.headingLevel);case"heading-2":return H(r,g,s.block.kind==="heading"&&s.block.headingLevel===2,s.block.headingLevel);case"heading-3":return H(r,g,s.block.kind==="heading"&&s.block.headingLevel===3,s.block.headingLevel);case"bullet-list":return H(r,g,s.block.listKind==="bullet_list",s.block.listKind);case"numbered-list":return H(r,g,s.block.listKind==="ordered_list",s.block.listKind);case"zoom":return H(r,!1,!1,t.zoomPercent);case"zoom-fit-width":return H(r,!1,iw(t)==="fit-width",iw(t));case"document-mode-editing":return H(r,!1,t.documentMode==="editing",t.documentMode);case"document-mode-suggesting":return H(r,!t.trackChanges.enabled,t.documentMode==="suggesting",t.documentMode);case"document-mode-viewing":return H(r,!1,t.documentMode==="viewing",t.documentMode);case"flow-mode-paginated":return H(r,!1,t.flowMode==="paginated",t.flowMode);case"flow-mode-web":return H(r,!1,t.flowMode==="web",t.flowMode);case"layout-mode-vertical":return H(r,!1,on(t)==="vertical",on(t));case"layout-mode-horizontal":return H(r,!nw(t),on(t)==="horizontal",on(t));case"layout-mode-book":return H(r,!nw(t),on(t)==="book",on(t));case"track-changes-display-review":return H(r,!1,t.trackChanges.mode==="review",t.trackChanges.mode);case"track-changes-display-original":return H(r,t.documentMode!=="viewing",t.trackChanges.mode==="original",t.trackChanges.mode);case"track-changes-display-final":return H(r,t.documentMode!=="viewing",t.trackChanges.mode==="final",t.trackChanges.mode);case"track-changes-display-off":return H(r,!1,t.trackChanges.mode==="off",t.trackChanges.mode);case"comments-visible":return H(r,!t.commentsDisplay.enabled,t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-hidden":return H(r,!t.commentsDisplay.enabled,!t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-show-resolved":return H(r,!t.commentsDisplay.enabled,t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-hide-resolved":return H(r,!t.commentsDisplay.enabled,!t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-visibility-all":return H(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="all",t.commentsDisplay.visibility);case"comments-visibility-internal":return H(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="internal",t.commentsDisplay.visibility);case"comments-visibility-external":return H(r,!t.commentsDisplay.enabled,t.commentsDisplay.visibility==="external",t.commentsDisplay.visibility);case"tracking-toggle":return H(r,!t.editable||!a,a&&t.documentMode==="suggesting",t.documentMode);case"comment-create":return H(r,p!=null,!1,t.comments.length);case"link-set":return H(r,k,s.formatting.link||v.linkHref===!0,s.formatting.linkHref,v.link===!0||v.linkHref===!0);case"link-clear":return H(r,k||!s.formatting.link&&v.linkHref!==!0,s.formatting.link||v.linkHref===!0,s.formatting.linkHref,v.link===!0||v.linkHref===!0);case"track-changes-accept-selection":case"track-changes-reject-selection":return H(r,c.length===0||!t.editable,c.length>0,c);case"review-accept-all":case"review-reject-all":return H(r,l.length===0||!t.editable,!1,l.length)}let h=(t.toolbar.commands??{})[r.id];if(h)return{...h,title:r.title,description:r.description??null,group:r.group??null};switch(r.id){case"search-set-query":return H(r,!1,t.search.query.length>0,t.search.query);case"search-next":case"search-previous":return H(r,t.search.hits.length===0,!1,t.search.activeHitId);case"search-clear":return H(r,t.search.query.length===0,!1,t.search.query);case"search-replace-active":return H(r,t.search.hits.length===0||!t.editable,!1,t.search.activeHitId);case"search-replace-all":return H(r,t.search.hits.length===0||!t.editable,!1,t.search.hits.length);case"proofing-ignore-first":case"proofing-accept-first":case"proofing-replace-first-tracked":return H(r,t.proofing.diagnostics.length===0||!t.editable,!1,t.proofing.diagnostics[0]?.diagnosticId??null);case"insert-math-inline":return H(r,!t.editable||!s.editable||f,!1,s.block.kind);case"insert-chart-block":case"insert-shape-block":return H(r,!t.editable,!1,t.selection.block.kind);case"remove-selected-ooxml":return H(r,t.advancedOoxml.selected==null||!t.editable,t.advancedOoxml.selected!=null,t.advancedOoxml.selected?.objectId??null);case"selected-math-set-plain-text":case"selected-math-toggle-display-mode":return H(r,t.advancedOoxml.selected?.family!=="math"||!t.editable,t.advancedOoxml.selected?.family==="math",t.advancedOoxml.selected?.objectId??null);case"selected-chart-set-title":case"selected-chart-add-series":case"selected-chart-add-axis":return H(r,t.advancedOoxml.selected?.family!=="chart"||!t.editable,t.advancedOoxml.selected?.family==="chart",t.advancedOoxml.selected?.objectId??null);case"selected-shape-set-text-body":case"selected-shape-set-fill":case"selected-shape-add-child":return H(r,t.advancedOoxml.selected?.family!=="shape"||!t.editable,t.advancedOoxml.selected?.family==="shape",t.advancedOoxml.selected?.objectId??null);default:return H(r)}}function mw(e,t,r){if(!e)return null;let o=Do(e,r),n=t?Ur(t,o,r):null;return xs(o,n)}function pw(e,t){let r=Qr(e),o=re(e.viewport?.value??null),n=e.selection?Do(e.selection,e.review.revisions):e.selection,i=n??e.selection,s=e.selectionInfo&&i?Ur(e.selectionInfo,i,e.review.revisions):e.selectionInfo,a=e.advancedOoxml;return{...e,flowMode:r.flowMode,layoutMode:r.layoutMode,preferredPaginatedLayoutMode:r.preferredPaginatedLayoutMode,selection:n,selectionInfo:s,viewport:e.viewport?{...e.viewport,value:o,totalPages:o?.totalPages??null,currentPageIndex:o?.currentPageIndex??null,currentPageNumber:o?.currentPageNumber??null}:e.viewport,trackChanges:t?.trackChanges??{enabled:e.review.enabled,visible:e.review.visible,mode:e.review.mode,replacements:e.review.replacementMode},viewportRequestKey:t?.viewportRequestKey??e.viewport?.requestKey??null,previewNavigationRequest:t?.previewNavigationRequest??e.viewport?.previewNavigationRequest??null,advancedOoxml:t?.advancedOoxml??a}}import{cloneEditorSelectionSnapshot as Pw,deriveEditorUiSnapshot as Sk}from"@datalking/begonia-editor-contracts";function ek(e){let t=[],r=new Set;for(let o of e)typeof o!="string"||o.length===0||r.has(o)||(r.add(o),t.push(o));return t}function fw(e,t){if(t==null)return[...e];let r=new Set(Ue(t).values());return e.filter(o=>r.has(o))}function tk(e){return fw(At(e.selectionInfo?.activeCommentIds,Ue(e.comments)),e.comments)}function uc(e){let t=tk(e);return{activeCommentIds:t,activeCommentId:t.length===1?t[0]??null:null}}function mc(e){return fw(At(ek([...e.explicitActiveCommentIds??[],e.explicitActiveCommentId]),Ue(e.comments)),e.comments)}function sn(e){let t=uc(e);if(t.activeCommentIds.length>0)return t;let r=mc(e);return{activeCommentIds:r,activeCommentId:r.length===1?r[0]??null:null}}function pc(e){let t=[],r=new Set;for(let o of e)typeof o!="string"||o.length===0||r.has(o)||(r.add(o),t.push(o));return t}function rk(e){let t=pc(ce(e.selectionInfo?.activeChangeIds,e.revisions));if(!e.revisions||e.revisions.length===0)return t;let r=new Set(e.revisions.map(o=>o.id));return t.filter(o=>r.has(o))}function ro(e){let t=rk(e);return{activeRevisionIds:t,activeRevisionId:t.length===1?t[0]??null:null}}function ok(e){let t=pc([...e.explicitActiveRevisionIds??[],e.explicitActiveRevisionId]),r=pc(ce(t,e.revisions));if(!e.revisions||e.revisions.length===0)return r;let o=new Set(e.revisions.map(n=>n.id));return r.filter(n=>o.has(n))}function ww(e){let t=ro(e);if(t.activeRevisionIds.length>0)return t;let r=ok(e);return{activeRevisionIds:r,activeRevisionId:r.length===1?r[0]??null:null}}function Tr(e){return Object.freeze([...e])}var oo=Object.freeze({history:Tr(["undo","redo"]),view:Tr(["zoom","zoom-fit-width","flow-mode-paginated","flow-mode-web","layout-mode-vertical","layout-mode-horizontal","layout-mode-book"]),formatting:Tr(["bold","italic","underline","strikethrough","font-size","font-family","text-color","highlight-color","link-set","link-clear"]),blocks:Tr(["paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list"]),review:Tr(["document-mode-editing","document-mode-suggesting","document-mode-viewing","comment-create","comments-visible","comments-hidden","comments-show-resolved","comments-hide-resolved","comments-visibility-all","comments-visibility-internal","comments-visibility-external","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection","track-changes-display-review","track-changes-display-original","track-changes-display-final","track-changes-display-off","review-accept-all","review-reject-all"]),search:Tr(["search-set-query","search-next","search-previous","search-clear","search-replace-active","search-replace-all"]),proofing:Tr(["proofing-ignore-first","proofing-accept-first","proofing-replace-first-tracked"]),advancedOoxml:Tr(["insert-math-inline","insert-chart-block","insert-shape-block","remove-selected-ooxml","selected-math-set-plain-text","selected-math-toggle-display-mode","selected-chart-set-title","selected-chart-add-series","selected-chart-add-axis","selected-shape-set-text-body","selected-shape-set-fill","selected-shape-add-child"])}),Is=Object.freeze([{id:"history",label:"History",commandIds:oo.history},{id:"view",label:"View",commandIds:oo.view},{id:"formatting",label:"Formatting",commandIds:oo.formatting},{id:"blocks",label:"Blocks",commandIds:oo.blocks},{id:"review",label:"Review",commandIds:oo.review},{id:"search",label:"Search",commandIds:oo.search},{id:"proofing",label:"Proofing",commandIds:oo.proofing}]),i1=Object.freeze(Is.flatMap(e=>[...e.commandIds]));function nk(e){return[{id:"commands",label:"Commands",commandIds:e.map(t=>t.id)}]}function ik(e,t){if(t&&t.length>0)return t;if(e.length===0)return[];let r=new Set(Is.flatMap(n=>n.commandIds));return e.every(n=>r.has(n.id))?Is:nk(e)}function sk(e){return e?[...e]:[]}function ak(e,t){return{id:e.id,title:e.title,description:e.description??null,group:e.group??null,keywords:sk(e.keywords),slash:e.slash??!1,state:t}}function lk(e,t,r){return e.flatMap(o=>{let n=t.get(o);return n?[ak(n,r[o]??null)]:[]})}function gw(e){let t=ik(e.catalog,e.sections),r=new Map(e.catalog.map(o=>[o.id,o]));return t.map(o=>({id:o.id,label:o.label,items:lk(o.commandIds,r,e.commands)})).filter(o=>o.items.length>0)}import{normalizeCommittedDocument as uk}from"@datalking/begonia-document-model";import{createDocumentRuntimeKernel as mk}from"@datalking/begonia-document-api/v1";import{resolveRevisionProjectedDocument as pk}from"@datalking/begonia-engine";import{preserveSyntheticSideStoryDocMetadata as ck,readSyntheticSideStoryDocOriginPath as Sw}from"@datalking/begonia-doc-service/v1";function dk(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function vw(e){let t=null;for(let r of e){let o=Sw(r);if(o){if(t&&!dk(t,o))return null;t=o}}return t}function bt(e,t){return Sw(e)?ck(e,t):t}function fk(e,t){let r=null,o=null,n=s=>((s!==r||!o)&&(r=s,o=uk(s)),o),i=()=>n(e());return{readDocument(){return i()},replaceDocument(){throw new Error("Browser projected review runtime is read-only.")},...t?{documentSource:{readSnapshot(){let s=t.readSnapshot();return{document:i(),revision:s.revision}},subscribeDocument(s){return t.subscribeDocument(s)}}}:{}}}function hw(e){return e??null}function yw(e,t,r){return bt(e,pk(e,t,r))}function bw(e,t,r){let o=wk(e,t,r),n=!1,i=()=>{if(n)throw new Error("Browser projected runtime bank is disposed.")};return{resolveRuntime(s="tracked"){return i(),o.projections.resolveRuntime(s)},resolveProjection(s="tracked",a={}){return i(),o.projections.resolveProjection(s,a)},resolveLayout(s="tracked",a={}){return i(),o.projections.resolveLayout(s,a)},invalidate(){i(),o.projections.invalidate()},dispose(){n||(n=!0,o.dispose())}}}function wk(e,t,r){return mk(fk(e,r),{review:{replacementMode:t}})}function Bw(e){return e==="final"||e==="original"?e:null}function mr(e,t){return typeof e=="boolean"?e:t}function gk(e,t){return Yr(e)??t}function As(e,t){return e!=null?Bs(e):t===!1?"editing":"suggesting"}function an(e,t){let r=mr(t?.enabled,!0),o=mr(t?.visible,e!=="viewing"),n=e==="viewing"?o?"review":"original":"review";return{enabled:r,visible:o,mode:Xr(t?.mode)??n,replacements:$r(t?.replacements)??"paired"}}function xw(e,t){let r=mr(t?.enabled,!0),o=mr(t?.visible,e!=="viewing"),n=mr(t?.readOnly,e==="viewing"),i=mr(t?.useInternalExternalComments,!1),s=mr(t?.suppressInternalExternal,!1),a=s?"external":gk(t?.visibility,"all");return{enabled:r,visible:o,readOnly:n,allowResolve:n?!1:mr(t?.allowResolve,!0),showResolved:mr(t?.showResolved,!1),visibility:a,useInternalExternalComments:i,suppressInternalExternal:s,enforceVisibilityPolicy:i||s}}function Cw(e,t,r){if(!e)return e??null;let o=t?.suppressInternalExternal?!1:e.canViewInternalComments,n=r??e.permissionResolver,i=t?.permissionResolver??e.commentPermissionResolver;return o===e.canViewInternalComments&&n===e.permissionResolver&&i===e.commentPermissionResolver?e:{...e,canViewInternalComments:o,permissionResolver:n,commentPermissionResolver:i}}function ln(e){return e!=="viewing"}function kr(e,t){return e==="suggesting"&&t.enabled}function Ns(e,t,r,o=!1){return e.collaborative&&!o||t!=="viewing"?null:r.mode==="original"||r.mode==="final"?r.mode:null}function Me(e,t,r){return r==null?e:bt(e,yw(e,t.schema,r))}function fc(e,t,r,o,n,i){let s=e.view?.dom;s&&(s.dataset.aldDocumentMode=t,s.dataset.aldFlowMode=r,s.dataset.aldLayoutMode=o,s.dataset.aldTrackChangesMode=n.mode,s.dataset.aldTrackChangesVisible=String(n.visible),s.dataset.aldTrackChangesEnabled=String(n.enabled),s.dataset.aldCommentsVisible=String(i.visible),s.dataset.aldCommentsReadOnly=String(i.readOnly),s.dataset.aldCommentsShowResolved=String(i.showResolved),s.dataset.aldCommentsVisibility=i.visibility)}var Rw=["undo","redo","bold","italic","underline","strikethrough","paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list","link-set","link-clear","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection"];function vk(e){return kr(e.documentMode,e.trackChanges)}function hk(e){return e.collaboration.collaborative??!1}function yk(e){return{selection:Pw(e.selection),editable:e.editable,trackingEnabled:vk(e),collaborative:hk(e),canUndo:e.canUndo,canRedo:e.canRedo,commandStates:e.commandStates}}function bk(e,t=e.toolbar.commands){return{selection:e.selection,editable:e.editable,documentMode:e.documentMode,trackChanges:e.trackChanges,collaboration:e.collaboration,canUndo:t.undo?.disabled===!1,canRedo:t.redo?.disabled===!1,commandStates:t}}function Bk(e,t){return t?.commands??e.toolbar.commands}function Ds(e){return Sk(yk(e))}function xk(e,t){let r=Ds(bk(e,Bk(e,t))),o=t?.catalog??[];return{...r,catalog:o,sections:gw({catalog:o,commands:r.commands})}}function cn(e,t){let r=xk(e,t),o=e.zoom??{mode:"manual",value:e.zoomPercent,fitZoom:null,min:10,max:400,viewportMetrics:null},n=e.commentsDisplay??{enabled:!1,visible:!1,readOnly:!1,showResolved:!1,visibility:"all"},i=e.trackChanges??{enabled:!1,visible:!1,mode:"off",replacements:"paired"},s=e.collaboration??{collaborative:!1,mode:"none",reconfigurable:!1,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null},a=ro({revisions:e.revisions,selectionInfo:e.selectionInfo}),l=sn({comments:e.comments,selectionInfo:e.selectionInfo,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds}),c=e.activeRevisionId??a.activeRevisionId,d=e.activeRevisionIds??a.activeRevisionIds;return{selection:Pw(e.selection),selectionInfo:Ko(e.selectionInfo),trackingEnabled:r.trackingEnabled,collaborative:r.collaborative,commands:r.commands,editable:e.editable,documentMode:e.documentMode,flowMode:e.flowMode,layoutMode:e.layoutMode,preferredPaginatedLayoutMode:e.preferredPaginatedLayoutMode,commandCatalog:r.catalog,toolbar:r,viewport:{value:e.viewport,requestKey:e.viewportRequestKey,previewNavigationRequest:e.previewNavigationRequest,totalPages:e.viewport?.totalPages??null,currentPageIndex:e.viewport?.currentPageIndex??null,currentPageNumber:e.viewport?.currentPageNumber??null},zoom:{percent:e.zoomPercent,mode:o.mode,value:o.value,fitZoom:o.fitZoom,min:o.min,max:o.max,viewportMetrics:o.viewportMetrics},comments:{items:e.comments,permissions:e.commentPermissions,total:e.comments.length,activeCommentId:l.activeCommentId,activeCommentIds:l.activeCommentIds,enabled:n.enabled,visible:n.visible,readOnly:n.readOnly,allowResolve:n.allowResolve,showResolved:n.showResolved,visibility:n.visibility,useInternalExternalComments:n.useInternalExternalComments,suppressInternalExternal:n.suppressInternalExternal,enforceVisibilityPolicy:n.enforceVisibilityPolicy},review:{revisions:e.revisions,permissions:e.reviewPermissions,timeline:e.reviewTimeline,summary:e.reviewTimelineSummary,activeRevisionId:c,activeRevisionIds:d,enabled:i.enabled,visible:i.visible,mode:i.mode,replacementMode:i.replacements},search:{query:e.search.query,hits:e.search.hits,activeHitId:e.search.activeHitId},proofing:{diagnostics:e.proofing.diagnostics},advancedOoxml:{selected:e.advancedOoxml.selected},collaboration:{...s,connected:s.connected??!1}}}function Zn(e,t=nn(void 0)){let r=e.getState(),o=e.surface?.state,n=e.surface?.view!=null,i=e.readEffectiveSelection?.()??e.captureEffectiveSelection?.()??null;return{editor:r,context:dw(r,i),catalog:t,commands:Object.fromEntries(t.map(s=>[s.id,uw(e,r,s,o,n,i)]))}}function Tw(e,t=nn(void 0)){let r=Zn(e,t),o=e.getState();return{editor:pw(cn(o,r),{trackChanges:o.trackChanges,viewportRequestKey:o.viewportRequestKey,previewNavigationRequest:o.previewNavigationRequest,advancedOoxml:{selected:o.advancedOoxml.selected}}),context:r.context,catalog:r.catalog,commands:r.commands}}import{documentWideMutationEffect as Ck}from"@datalking/begonia-editor-contracts";function wc(e){return e?e.documentService.readDocument():null}function gc(e){return it(e)?.view??null}function Sc(e){return it(e)?.automation??null}function vc(e,t){let r=it(e);return r?(r.replaceDocument(t,{origin:"api",intent:"replace-browser-document",effects:[Ck("content")]}),!0):!1}function Pk(e){return e?"documentApi"in e?it(e):e:null}function no(e,t){let r=Pk(e),o=r?.view;if(!o?.state||typeof o.dispatch!="function")return!1;let n=r,i=Ze(o.state.doc,t);if(!i)return!1;let s=Z(o.state,i.from,i.to);return s?qe(n,s):!1}var Os=Symbol("captureBrowserEditorPositionAtPointInternal");import{NodeSelection as Ew}from"prosemirror-state";function Rk(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Math.trunc(t),e.doc.content.size))}function kw(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(Math.trunc(t),e.doc.content.size))}function Tk(e,t,r){let o=e.view.dom,n=e.view.dom.ownerDocument,i=typeof o.getBoundingClientRect=="function"?o.getBoundingClientRect():null;if(i&&Number.isFinite(i.left)&&Number.isFinite(i.right)&&Number.isFinite(i.top)&&Number.isFinite(i.bottom)&&(t<i.left||t>i.right||r<i.top||r>i.bottom))return!1;if(!o||!n||typeof n.elementFromPoint!="function"||typeof o.contains!="function")return!0;let s=n.elementFromPoint(t,r);return!s||o.contains(s)}function kk(e,t){let r=Z(e,t,t);if(!r)return null;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function Ek(e,t){try{return e.apply(e.tr.setSelection(Ew.create(e.doc,t)))}catch{return null}}function Mk(e,t){let r=e.doc.nodeAt(t);return!!(r&&Ew.isSelectable(r)&&(r.isLeaf||r.isAtom))}function Ik(e,t){return[kw(e,t?.inside),kw(e,t?.pos)].filter((o,n,i)=>o!=null&&i.indexOf(o)===n).find(o=>Mk(e,o))??null}function dn(e){let t=e.surface.view;if(!t?.state||typeof t.posAtCoords!="function"||!Tk(e.surface,e.clientX,e.clientY))return null;let r=t.posAtCoords({left:e.clientX,top:e.clientY})??null;if((e.mode??"node-or-text")!=="text-only"){let s=Ik(t.state,r);if(s!=null){let a=Ek(t.state,s);if(a)return{pos:s,state:a}}}let n=Rk(t.state,r?.pos);if(n==null)return null;let i=kk(t.state,n);return i?{pos:n,state:i}:null}function Ak(e){let t=e?.selectionTarget;if(t&&t.segments.length===1&&t.segments[0]?.range.start===t.segments[0]?.range.end){let i=t.segments[0];return{kind:"text",blockId:i.blockId,offset:i.range.start}}let r=e?.target;if(!r||typeof r!="object"||!("blockId"in r)||!("range"in r))return null;let o=typeof r.blockId=="string"?r.blockId:null,n=r.range;return!o||!n||typeof n!="object"||typeof n.start!="number"||typeof n.end!="number"||n.start!==n.end?null:{kind:"text",blockId:o,offset:n.start}}function Nk(e,t){let r=dn({surface:e.surface,clientX:t.clientX,clientY:t.clientY});if(!r?.state.selection.empty)return null;let o=Ee(r.state).target,n=o?.segments[0];return!o||o.segments.length!==1||!n||n.range.start!==n.range.end?null:{point:{kind:"text",blockId:n.blockId,offset:n.range.start},target:{kind:"text",segments:[{blockId:n.blockId,range:{start:n.range.start,end:n.range.end}}]}}}function Dk(e,t){return e&&typeof e=="object"&&"kind"in e&&e.kind==="text"?t:e}function Mw(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Mw(t);return e}function Ok(e,t){let r=e.selectionTarget?.segments[0],o=t.segments[0];return e.selectionTarget?.segments.length===1&&r&&r.blockId===o.blockId&&r.range.start===o.range.start&&r.range.end===o.range.end?e:Mw(structuredClone({...e,selectionTarget:t,target:Dk(e.target,t)}))}function io(e,t){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let r=e[Os]?.(t)??null;if(!r||!r.selection.empty)return null;let o=Nk(e,t),n=o?.point??Ak(r),i=o?.target??(n?{kind:"text",segments:[{blockId:n.blockId,range:{start:n.offset,end:n.offset}}],...r.selectionTarget?.story?{story:structuredClone(r.selectionTarget.story)}:{}}:null);if(!n||!i)return null;let s=o?Ok(r,o.target):r;return{point:n,target:i,capture:s}}function Iw(e){return{readDocument(){return wc(e)},replaceDocument(t){return vc(e,t)},readView(){return gc(e)},readAutomation(){return Sc(e)}}}function jk(e){return{positionAtPoint(t){return io(e,t)},selectTextTarget(t){return El(e.surface,t)},selectCommentTarget(t){return no(e,t)}}}function Aw(e){return{selectionHandles:e,linkSelection:e,activeLink:e,view:e,documentMode:e,commentsDisplay:e,commentActions:e,commentFocus:e,reviewActions:e,reviewFocus:e,selectionTargets:jk(e)}}import{createCanonicalRevisionIdsByAlias as Vk,resolveCanonicalRevisionId as Lk,resolveTrackedOverlapParentIdMap as Fk}from"@datalking/begonia-engine";var js=3,zk=[[0,0],[-js,0],[js,0],[0,-js],[0,js]];function pr(e,t){if(!e||typeof e.getAttribute!="function")return null;let r=e.getAttribute(t);return typeof r=="string"?r.trim():null}function Dw(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Hk(e,t){return!t||!e.includes(t)?[...e]:[t,...e.filter(r=>r!==t)]}function qk(e){let t=Dw(pr(e,"data-track-change-ids"));if(t.length>0)return Hk(t,pr(e,"data-track-change-preferred-target-id"));let r=pr(e,"data-track-change-id");if(r)return[r];let o=pr(e,"data-change-id");return o?[o]:[]}function Wk(e){return!!(pr(e,"data-ald-comment-anchor")||pr(e,"data-ald-comment-range-start")||pr(e,"data-ald-comment-range-end"))}function Kk(e){let t=Dw(pr(e,"data-comment-ids"));if(t.length>0)return t;let r=pr(e,"data-thread-id");return r&&Wk(e)?[r]:[]}function Ow(e,t){let r=e??null;for(;r;){if(r===t)return!0;r=r.parentElement??null}return!1}function _k(e,t,r){if(!e||!Ow(e,t))return[];let o=[],n=e;for(;n;){for(let i of qk(n)){let s=`trackedChange:${i}`;r.has(s)||(r.add(s),o.push({kind:"trackedChange",id:i}))}for(let i of Kk(n)){let s=`comment:${i}`;r.has(s)||(r.add(s),o.push({kind:"comment",id:i}))}if(n===t)break;n=n.parentElement??null}return o}function Uk(e,t,r){let o=e?.ownerDocument??null;if(!o)return[];let n=(()=>{if(typeof o.elementsFromPoint!="function")return[];try{return o.elementsFromPoint(t,r)??[]}catch{return[]}})();if(n.length>0)return n;let i=(()=>{if(typeof o.elementFromPoint!="function")return null;try{return o.elementFromPoint(t,r)}catch{return null}})();return i?[i]:[]}function Zk(e,t){return e.some(r=>Ow(r,t))}function Nw(e,t){let r=Number(t);return Number.isFinite(r)?Math.max(0,Math.min(e,Math.max(0,r-1))):e}function Gk(e,t,r){let o=e.ownerDocument??null,n=o?.defaultView?.innerWidth??null,i=o?.defaultView?.innerHeight??null,s=[],a=new Set;for(let[l,c]of zk.slice(1)){let d=Nw(t+l,n),u=Nw(r+c,i),m=`${d}:${u}`;a.has(m)||(a.add(m),s.push({x:d,y:u}))}return s}function jw(e,t,r,o){let n=Uk(e,t,r);return{stack:n,candidates:n.flatMap(i=>_k(i,e,o))}}function Xk(e,t,r,o){let n=[];for(let i of Gk(e,t,r))n.push(...jw(e,i.x,i.y,o).candidates);return n}function $k(e,t){let r=ce(e,t??[]),o=r.length>0?r:[...e],n=o[0]??null;return!n||o.length>1&&!rE(o,t)?null:{status:"resolved",kind:"trackedChange",trackedChangeIds:[n],commentIds:[]}}function Yk(e){return e.relationship==="child"||!!e.overlapParentId||(e.members??[]).some(t=>t.relationship==="child"||!!t.overlapParentId)}function Jk(e){return[e.overlapParentId,...(e.members??[]).map(t=>t.overlapParentId)]}function Qk(e,t,r){let o=new Set;for(let n of Jk(e)){let i=Lk(n,t);i&&i!==e.id&&r.has(i)&&o.add(i)}return o.size===1?[...o][0]:null}function eE(e){if(!e||e.length===0)return new Map;let t=Vk(e),r=new Set(e.map(o=>o.id));return Fk(e.map(o=>({id:o.id,overlapParentId:Yk(o)?Qk(o,t,r):null})))}function tE(e,t){let r=[e],o=new Set(r),n=e;for(;;){let i=t.get(n);if(!i||o.has(i))return r;r.push(i),o.add(i),n=i}}function rE(e,t){if(e.length<=1)return!0;if(!t||t.length===0)return!1;let r=ce(e,t);if(r.length<=1)return r.length===1;let o=tE(r[0],eE(t)),n=new Map(o.map((s,a)=>[s,a])),i=-1;for(let s of r){let a=n.get(s);if(a==null||a<=i)return!1;i=a}return!0}function hc(e){let t=e.host??null;if(!t)return[];let r=new Set,o=jw(t,e.clientX,e.clientY,r),n=o.candidates.length>0?o.candidates:Zk(o.stack,t)?Xk(t,e.clientX,e.clientY,r):[];if(n.length===0)return[];let i=e.revisions??[],s=Ue(e.comments),a=[],l=new Set;for(let c of n){let d=c.kind==="trackedChange"?ce([c.id],i)[0]??c.id:At([c.id],s)[0]??null;if(!d)continue;let u=`${c.kind}:${d}`;l.has(u)||(l.add(u),a.push({kind:c.kind,id:d}))}return a}function Vw(e){let t=hc(e),r=t.filter(s=>s.kind==="trackedChange").map(s=>s.id),o=t.filter(s=>s.kind==="comment").map(s=>s.id),n=r.length+o.length;if(n===0)return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]};let i=o.length===0?$k(r,e.revisions):null;return i||(n>1?{status:"ambiguous",kind:null,trackedChangeIds:r,commentIds:o}:{status:"resolved",kind:r.length===1?"trackedChange":"comment",trackedChangeIds:r,commentIds:o})}function oE(e){return e?{empty:e.empty,target:e.selectionTarget?Et(e.selectionTarget):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}function nE(e,t){let r=e.getState();return hc({host:e.surface.view.dom,clientX:t.clientX,clientY:t.clientY,revisions:r.revisions,comments:r.comments}).map(n=>({type:n.kind,id:n.id}))}function iE(e,t,r,o,n){if(e)return!1;let i=t?.selectionTarget??n;if(t?.selectionKind==="node"||r?.selectionKind==="node")return sr(t?.nodeSelectionTarget,r?.nodeSelectionTarget);let s=r?.empty?r.selectionTarget:null;return os(s??o,i)}function sE(e,t,r){for(let o of r)if(e>=o.left&&e<=o.left+o.width&&t>=o.top&&t<=o.top+o.height)return!0;return!1}function aE(e,t,r,o){if(!e||!t||t.empty)return null;let n=qn(e,t);return n.length===0?null:sE(r,o,n)}function yc(e,t){return!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number"?[]:nE(e,t)}function Lw(e,t,r=null){let o=e.getState(),n=io(e,t),i=e.readEffectiveSelection({includeText:!0}),s=e.readPointSelection({clientX:t?.clientX??0,clientY:t?.clientY??0,includeText:!1}),a=typeof t?.clientX=="number"?t.clientX:0,l=typeof t?.clientY=="number"?t.clientY:0,c=aE(r,o.selection,a,l);return{point:{x:a,y:l},entities:yc(e,t),position:n,selection:Ko(o.selectionInfo??oE(i)),insideSelection:c??iE(o.selection.empty,i,s,n?.target??null,o.selectionInfo?.target??null)}}function Gn(e){return e!=null&&typeof e.contains=="function"}function bc(e){return typeof e=="string"?e.trim().toLowerCase():""}function lE(e){return e.ownerDocument?.defaultView?.getComputedStyle?.(e)??null}function Fw(e){let t=lE(e);if(!t)return{horizontal:"",vertical:""};let r=bc(t.overflow);return{horizontal:bc(t.overflowX)||r,vertical:bc(t.overflowY)||r}}function Vs(e){return e==="auto"||e==="scroll"||e==="overlay"}function cE(e){return{vertical:(e.scrollHeight??0)>(e.clientHeight??0),horizontal:(e.scrollWidth??0)>(e.clientWidth??0)}}function dE(e){let t=Fw(e),r=cE(e);return r.vertical&&Vs(t.vertical)||r.horizontal&&Vs(t.horizontal)}function uE(e){let t=Fw(e);return Vs(t.vertical)||Vs(t.horizontal)}function un(e){let t=Ls(e);return t?(Gn(t.parentElement)?t.parentElement:null)??t:null}function Ls(e){let t=e?.view?.dom??null;return Gn(t)?t:null}function mE(e){let t=e??null;for(;Gn(t);){if(dE(t))return t;t=t.parentElement}return null}function pE(e){let t=[],r=e??null;for(;Gn(r);)uE(r)&&t.push(r),r=r.parentElement;return t}function Xn(e){let t=e?.view?.dom??null;return Gn(t)?mE(t):null}function zw(e){let t=Ls(e);return t?pE(t):[]}import{createVirtualPagedPreviewAncestorMutationObserver as fE,resolveVirtualPagedPreviewClippingAncestorElements as Kw}from"@datalking/begonia-layout-renderer";var Hw={passive:!0};function qw(e){if(typeof e.getState!="function")return null;let t=e.getState();return t.zoom?.value??t.zoomPercent??null}function $n(e){return typeof e.getState=="function"?e.getState():null}function Bc(e){return e?.commentsDisplay?.enabled===!0&&e.commentsDisplay.visible===!0}function xc(e){return typeof e.getViewportState=="function"?re(e.getViewportState()):null}function wE(e){let t=e;return{request(r){return typeof t?.requestAnimationFrame=="function"?{handle:t.requestAnimationFrame(r),mode:"animation-frame"}:{handle:typeof t?.setTimeout=="function"?t.setTimeout(()=>r(0),0):setTimeout(()=>r(0),0),mode:"timeout"}},cancel(r){if(r){if(r.mode==="animation-frame"&&typeof t?.cancelAnimationFrame=="function"){t.cancelAnimationFrame(r.handle);return}if(typeof t?.clearTimeout=="function"){t.clearTimeout(r.handle);return}clearTimeout(r.handle)}}}}function Ww(e){return!e||typeof e!="object"?!1:"ownerDocument"in e}function gE(e){let t=e;return typeof t?.ResizeObserver=="function"?t.ResizeObserver:typeof ResizeObserver=="function"?ResizeObserver:null}function SE(e,t){let r=new Set;if(Ww(e)){r.add(e);for(let o of Kw(e))r.add(o)}for(let o of t)Ww(o)&&r.add(o);return[...r]}function vE(e,t,r,o){let n=new Set;r&&n.add(r);let i=Ls(t);i&&n.add(i);for(let s of zw(t))n.add(s);if(e)for(let s of Kw(e))n.add(s);return n.size===0&&o&&n.add(o),[...n]}function hE(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function _w(e,t=null){let r=new Set,o=new Set,n=!1,i=null,s=xc(e),a=$n(e)?.flowMode??null,l=$n(e)?.layoutMode??null,c=Bc($n(e)),d=qw(e),u=!1,m=null,p=null,f=null,g=[],v=null,k=[],R=null,h=null,B=!1,S=e.surface??null,b=()=>{B=!0,F("scroll")},P=()=>{B=!0,F("resize")},A=()=>{let U=un(e.surface)?.ownerDocument?.defaultView??null;return wE(U)},O=()=>{let I=i;i=null,I?.cancel()},j=I=>{if(i?.token!==I)return;i=null;let U=[...o];if(o.clear(),n=!1,B&&(B=!1,N(),h?.sync()),r.size===0||U.length===0)return;let xe=U.length===1?U[0]:"mixed";for(let me of[...r])try{me({reason:xe})}catch{}},K=()=>{let I=A(),U={},xe=null;i={token:U,cancel(){I.cancel(xe)}};try{xe=I.request(()=>j(U))}catch(me){throw i?.token===U&&(i=null),me}},F=I=>{r.size!==0&&((I==="layout"||I==="zoom")&&n&&(o.delete("scroll"),n=!1),I==="scroll"&&(n=!1),o.add(I),!i&&K())},se=()=>{r.size!==0&&(o.has("scroll")||(n=!0),o.add("scroll"),!i&&K())},E=()=>{f?.removeEventListener?.("scroll",b,!0),f?.removeEventListener?.("resize",P);for(let I of g)I!==f&&I.removeEventListener?.("scroll",b,Hw);R?.disconnect(),f=null,g=[],v=null,k=[],R=null},N=()=>{let I=un(e.surface),U=I?.ownerDocument?.defaultView??null,xe=Xn(e.surface),me=vE(I,e.surface,xe,U),Ke=SE(I,me);if(I===v&&U===f&&me.length===g.length&&me.every((Ce,mt)=>Ce===g[mt])&&hE(Ke,k))return;E(),v=I,f=U,g=me,k=Ke,f?.addEventListener?.("scroll",b,!0),f?.addEventListener?.("resize",P);for(let Ce of me)Ce!==f&&Ce.addEventListener?.("scroll",b,Hw);let Tt=gE(f);if(!Tt)return;let Ye=new Tt(()=>{N(),h?.sync(),F("resize")});for(let Ce of Ke)Ye.observe(Ce);R=Ye},L=()=>{h||(h=fE({getPreviewHost:()=>un(e.surface),getAdditionalHosts:()=>[Xn(e.surface)],onMutation(){N(),h?.sync(),F("layout")}})),h.sync()},ne=()=>{let I=$n(e);if(!I)return;B=!0;let U=(e.surface??null)!==S;S=e.surface??null;let xe=I.zoom?.value??I.zoomPercent??null;xe!==d&&(u=!0,d=xe);let me=xc(e),Ke=s,Tt=me?.scale!==Ke?.scale,Ye=!ot(Ke,me);s=me;let Ce=I.flowMode,mt=I.layoutMode,hr=Ce!==a||mt!==l;a=Ce,l=mt;let jt=Bc(I),vo=jt!==c;if(c=jt,Tt&&u){u=!1,F("zoom");return}if(u&&Ce==="web"){u=!1,F("zoom");return}if(hr||Ye&&me?.totalPages!==Ke?.totalPages){let Vt=u?"zoom":"layout";u=!1,F(Vt);return}if(vo){F("layout");return}if(U){F("layout");return}Ye&&se()},y=()=>{if(B=!0,u){u=!1,F("zoom");return}F("layout")},x=()=>{if(m)return;S=e.surface??null,s=xc(e);let I=$n(e);a=I?.flowMode??null,l=I?.layoutMode??null,c=Bc(I),d=qw(e),u=!1,N(),L(),m=typeof e.subscribe=="function"?e.subscribe(ne):null,p=t?.subscribeResolvedProjection?.(y)??null},M=()=>{m?.(),p?.(),m=null,p=null,E(),h?.cleanup(),h=null,O(),o.clear(),n=!1,u=!1,B=!1};return{observe(I){return r.add(I),r.size===1&&x(),()=>{r.delete(I)&&r.size===0&&M()}}}}import{resolveProjectionCaretRect as yE}from"@datalking/begonia-page-layout";function mn(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Er(e,t){return t>0?e/t:null}function Zw(e){return Array.isArray(e)&&e.length>0?[...e]:null}function Gw(e){return typeof e=="number"&&Number.isInteger(e)?e:null}function bE(e,t){let r=Number.isFinite(e)?Math.max(0,Math.trunc(e)):0;return t==null?r:Math.min(t,r)}function Xw(e,t){let r=e.pages.findIndex(n=>n.pageNumber===t);if(r<0)return null;let o=e.pages[r]??null;return o?{pageIndex:r,page:o}:null}function BE(e){return!e||e.kind!=="text"||!Array.isArray(e.segments)||e.segments.length===0?[]:e.segments.filter(t=>!!t?.blockId)}function xE(e,t){return e.targets?.resolve?.({kind:"block",blockId:t})??null}function CE(e,t){let r=Zw(t?.path??null);if(r)return e.blocks?.ancestorOf?.(r)??null;let o=Gw(t?.anchorFrom);return o==null?null:e.blocks?.byAnchor?.(o)??null}function PE(e,t){let r=xE(e,t.blockId);if(!r)return null;let o=CE(e,r),n=Gw(o?.from??r.anchorFrom);if(n==null)return null;let i=bE(t.range.start,typeof r.text=="string"?r.text.length:null);return{absolutePos:n+i,anchorFrom:n,pathHint:Zw(o?.path??r.path??null)}}function RE(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex}function TE(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex&&e.lineIndex===t.lineIndex}function Uw(e){let t=new Set,r=[];for(let o of e){if(!Number.isFinite(o))continue;let n=o.toFixed(3);t.has(n)||(t.add(n),r.push(o))}return r}function kE(e){return e.left+Math.min(Math.max(0,e.width/2),Math.max(0,e.width-1))}function EE(e){return e.top+Math.min(Math.max(0,e.height/2),Math.max(0,e.height-1))}function ME(e,t,r,o){if(!r||typeof e.pagination.hitTest!="function")return null;let n=Uw([kE(r),o.left,r.left,r.left+Math.max(0,r.width-1)]),i=Uw([EE(r),o.top+Math.max(0,o.height/2),o.top,r.top]);for(let s of i)for(let a of n){let l=e.pagination.hitTest(o.pageNumber,a,s,t);if(l&&RE(l,r))return l}return null}function IE(e,t){return e.find(r=>TE(r,t))??null}function AE(e,t,r,o,n,i){let s=Xw(e,t.pageNumber);if(!s)return null;let a=Math.max(0,Number(s.page.pageSize.width??0)),l=Math.max(0,Number(s.page.pageSize.height??0)),c=mn(t.top,l),d=mn(t.left,a),u=n??i,m=u?t.top-u.top:null,p=u?t.left-u.left:null,f=m==null?null:mn(m,u?.height??0),g=p==null?null:mn(p,u?.width??0);return{pageIndex:s.pageIndex,pageNumber:t.pageNumber,offsetTopPx:c,offsetTopRatio:Er(c,l),offsetLeftPx:d,offsetLeftRatio:Er(d,a),offsetPx:c,offsetRatio:Er(c,l),region:n?.region??t.region??i?.region??null,sectionId:n?.sectionId??t.sectionId??i?.sectionId??null,anchorFrom:r,pathHint:o,blockIdentity:n?.blockIdentity??i?.blockIdentity??null,fragmentIndex:n?.fragmentIndex??t.fragmentIndex??i?.fragmentIndex??null,columnIndex:n?.columnIndex??t.columnIndex??i?.columnIndex??null,placementOrderHint:n?.blockIndex??t.blockIndex??i?.blockIndex??null,blockOffsetTopPx:f,blockOffsetTopRatio:f==null||!u?null:Er(f,u.height),blockOffsetLeftPx:g,blockOffsetLeftRatio:g==null||!u?null:Er(g,u.width)}}function NE(e,t,r,o={}){let n=PE(e,r);if(!n)return null;let i=yE(t,n.absolutePos,{bias:"start",measureText:o.measureText,measurementEpoch:o.measurementEpoch});if(!i)return null;let s=e.pagination.lines?.(t)??[],a=IE(s,i),l=ME(e,t,a,i),c=typeof e.pagination.locateAnchor=="function"?e.pagination.locateAnchor(n.anchorFrom,t):null,d=AE(t,i,n.anchorFrom,n.pathHint,l,c);return d?{anchorPageNumber:i.pageNumber,viewportAnchor:d}:null}function $w(e,t,r={}){let o=BE(t);if(o.length===0)return null;let n=e.pagination.project();for(let i of o){let s=NE(e,n,i,r);if(s)return s;let a=e.pagination.locateTarget({kind:"block",blockId:i.blockId},n);if(!a)continue;let l=Xw(n,a.pageNumber);if(!l)continue;let c=Math.max(0,Number(l.page.pageSize.width??0)),d=Math.max(0,Number(l.page.pageSize.height??0)),u=mn(a.top,d),m=mn(a.left,c);return{anchorPageNumber:a.pageNumber,viewportAnchor:{pageIndex:l.pageIndex,pageNumber:a.pageNumber,offsetTopPx:u,offsetTopRatio:Er(u,d),offsetLeftPx:m,offsetLeftRatio:Er(m,c),offsetPx:u,offsetRatio:Er(u,d),region:a.region??null,sectionId:a.sectionId??null,anchorFrom:a.from,pathHint:a.pathHint?[...a.pathHint]:null,blockIdentity:a.blockIdentity??null,fragmentIndex:a.fragmentIndex,columnIndex:a.columnIndex,placementOrderHint:a.blockIndex,blockOffsetTopPx:0,blockOffsetTopRatio:0,blockOffsetLeftPx:0,blockOffsetLeftRatio:0}}}return null}function Cc(e,t,r=null){let o=$w(e.documentApi,t,Xt(r)??{});if(!o)return null;let n={anchorPageNumber:o.anchorPageNumber,viewportAnchor:o.viewportAnchor};return e.requestPreviewNavigation(n)}import{TextSelection as DE}from"prosemirror-state";var OE=1e3;function jE(e){return typeof e!="number"||!Number.isFinite(e)?OE:Math.max(0,Math.trunc(e))}function VE(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&Array.isArray(e.segments)}function LE(e){return e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"&&"id"in e&&typeof e.id=="string"}function FE(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function Yw(e){let t=Gt(e);return FE(t)?t:null}function zE(e,t){let r=e.documentApi?.trackChanges.get(t)??null;return hs(e.documentApi,Yw(e.preview),r)}function HE(e,t){let r=e.documentApi?.comments.target(t)??null;if(!r)return null;let o=vs(e.documentApi,r);if(o)return o;let n=Yw(e.preview);if(!n)return null;let i=Ze(n,r);if(!i)return null;try{return hl(n,DE.create(n,i.from,i.to))}catch{return null}}function qE(e,t){return VE(t)?t:LE(t)?t.type==="comment"?HE(e,t.id):t.type==="trackedChange"?zE(e,t.id):null:null}function WE(e,t){let r=e.readPendingNavigationRequest();return r?r.requestKey===t?"pending":"failed":"success"}function Pc(e){return e?.shouldContinue?.()??!0}function KE(e,t,r,o){return new Promise(n=>{let i=!1,s=()=>{},a=()=>{},l=null,c=m=>{let p=typeof m=="function"?m:()=>{};return i?(p(),()=>{}):p},d=m=>{i||(i=!0,s(),a(),l!=null&&clearTimeout(l),n(m))},u=()=>{if(!Pc(o)){d(!1);return}let m=WE(e,t);m!=="pending"&&d(m==="success")};s=c(e.subscribe(u)),i||(a=c(o?.subscribe?.(u))),i||(l=setTimeout(()=>d(!1),r),u())})}async function Jw(e,t){let r=qE(e,t.target);if(!r)return{success:!1};if(!Pc(t.continuation))return{success:!1};let o=e.requestNavigationForTextTarget(r);return o?Pc(t.continuation)?{success:await KE(e,o.requestKey,jE(t.timeoutMs),t.continuation)}:{success:!1}:{success:!1}}function Yn(e){return re(e.getViewportState())}function Qw(e,t){let r=Yn(e);return e.subscribe(()=>{let o=Yn(e);ot(r,o)||(r=o,t())})}function eg(e,t=null){let r=null;return{getSnapshot(){return Yn(e)},subscribe(o){return Qw(e,o)},observe(o){return o(Yn(e)),Qw(e,()=>{o(Yn(e))})},observeGeometry(o){return r??=_w(e,t),r.observe(o)},scrollIntoView(o){return Jw({documentApi:e.documentApi,preview:t,subscribe(n){return e.subscribe(()=>{n()})},readPendingNavigationRequest(){return e.getState().previewNavigationRequest??null},requestNavigationForTextTarget(n){return Cc(e,n,t)}},o)},getHost(){return un(e.surface)},getScrollContainer(){return Xn(e.surface)},entitiesAtPoint(o){return yc(e,o)},contextAtPoint(o){return Lw(e,o,t)},positionAtPoint(o){return io(e,o)},requestNavigation(o){return e.requestPreviewNavigation(o)},requestNavigationForTextTarget(o){return Cc(e,o,t)},ackNavigationRequest(o){e.ackPreviewNavigationRequest(o)}}}import{createProseMirrorLayoutAdapter as mI}from"@datalking/begonia-editor-adapters";import{NodeSelection as dI}from"prosemirror-state";function Fs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function _E(e){let t=e.selectionAnchor;return Fs(t?.resolvedSelectionPos)??Fs(t?.hit?.pos)}function UE(e){return Fs(e.hit?.pos)??Fs(e.resolvedSelectionPos)}function tg(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to),n=_E(t),i=UE(t);return n!=null&&i!=null&&i<n?{anchor:o,head:r}:{anchor:r,head:o}}import{readSyntheticSideStoryDocOriginPath as JE}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as og,isDocumentNodePathIndex as QE,isIntegerPath as ng}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as eM}from"@datalking/begonia-layout-renderer";import{findProjectionPage as tM,resolveProjectionPageRegionBlocks as rM}from"@datalking/begonia-page-layout";import{findProjectionPage as ZE,listProjectionPageBlocks as GE,pointHitsProjectionPlacement as XE}from"@datalking/begonia-page-layout";function rg(e,t,r,o){let n=ZE(e,t);return n?GE(n).reduce((i,s)=>XE(s,r,o)?s:i,null):null}function Oe(e){return ve(e)}function $E(e,t){return e.pages.find(r=>r.pageNumber===t)??null}function YE(e,t,r){let o=$E(e,t);return o?r<o.regions.bodyTop?"header":r>=o.regions.footerTop?"footer":null:null}function pn(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=YE(e,r,t.y);if(!o)return t.hit?.region??"body";if(!t.hit||t.hit.region!=="body")return o;let n=t.hit.top,i=t.hit.top+t.hit.height;return(o==="header"?Math.max(0,n-t.y):Math.max(0,t.y-i))>Math.max(12,t.hit.height/2)?o:t.hit.region}function ig(e,t,r){let o=Qn(t,r);if(!Array.isArray(o?.path)||o.path.length===0)return!1;let n=JE(e);return n?ng(o.path)&&ng(n)&&o.path.length>=n.length&&n.every((i,s)=>o.path?.[s]===i)&&og(o.path.slice(n.length)):pn(t,r)==="body"&&og(o.path)}function Qn(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=tM(e,r);if(!o)return null;let n=rg(e,r,t.x,t.y);if(!t.hit)return n;let i=rM(o,t.hit.region)[t.hit.blockIndex]??null;return n??i}function Jn(e){return!!(e&&!e.drawing&&e.type!=="image"&&e.type!=="page_break"&&e.type!=="section_break")}function fn(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function oM(e){let t=eM(e);return t?.nodeType==="ooxml_math"||t?.nodeType==="ooxml_chart"||t?.nodeType==="ooxml_shape"||t?.nodeType==="inline_ooxml_drawing"}function sg(e,t){return t.shiftKey===!0?oM(t.target)||!Jn(e):fn(t.clickCount)<=1?!0:!Jn(e)}function so(e,t){let r=Number(t),o=Number.isNaN(r)?1:Math.round(r);return Math.max(1,Math.min(o,Oe(e).view.state.doc.content.size))}function ag(e,t){let r=e,o=-1;for(let n of t){if(!QE(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function ao(e,t){let r=so(e,t.from),o=so(e,t.to);return r<=o?{from:r,to:o}:{from:o,to:r}}function lg(e,t){return{from:Math.min(e.from,e.to,t.from,t.to),to:Math.max(e.from,e.to,t.from,t.to)}}function nM(e){if(e.resolvedSelectionPos==null&&e.resolvedSelectionRange==null)return!1;let t=fn(e.clickCount);return e.resolvedSelectionClickCount==null?t<=1:fn(e.resolvedSelectionClickCount)===t}function Rc(e){let t=e.hit;if(!t||!nM(e))return!1;let r=e.resolvedSelectionRange;if(r){let o=Math.min(r.from,r.to),n=Math.max(r.from,r.to);return o===n?t.pos===o&&(e.resolvedSelectionPos==null||e.resolvedSelectionPos===o):t.pos>=o&&t.pos<=n&&(e.resolvedSelectionPos==null||e.resolvedSelectionPos===o)}return e.resolvedSelectionPos!=null&&t.pos===e.resolvedSelectionPos}import{readNodeAtPath as sI}from"@datalking/begonia-document-api/structure";import{NodeSelection as dS}from"prosemirror-state";function lo(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function cg(e){return Object.hasOwn(e,"anchorPageNumber")}function dg(e){return cg(e)&&e.anchorPageNumber!=null&&lo(e.anchorPageNumber)==null}function iM(e,t){let r=e==null?"paginated":e==="web"||e==="paginated"?e:null,o=t==null?"vertical":t==="vertical"||t==="horizontal"||t==="book"?t:null;return!r||!o||r==="web"&&o!=="vertical"?null:{flowMode:r,layoutMode:o}}function sM(e){return`preview-navigation:${Math.max(1,Math.trunc(e))}`}function aM(e,t){return De(e)??sM(t)}function lM(e){return $t(e?.anchorPageIndex??e?.currentPageIndex??null,e?.anchorPageNumber??e?.currentPageNumber??null)}function cM(e,t){return e!=null?{pageNumber:e}:t}function dM(e,t){let r=lo(e.anchorPageNumber),o=lM(t);return Object.hasOwn(e,"viewportAnchor")?Go(e.viewportAnchor??null,{...cM(r,o)}):Object.hasOwn(e,"anchorPageNumber")?null:Xo(t)}function ug(e,t){return e==null||t==null||t.pageNumber===e}function uM(e,t,r){return cg(e)?lo(e.anchorPageNumber):lo(t?.pageNumber??r?.anchorPageNumber??r?.currentPageNumber??null)}function zs(e,t){if(!e||typeof e!="object"||dg(e))return null;let r=lo(e.anchorPageNumber),o=dM(e,t.fallbackViewport);if(Object.hasOwn(e,"viewportAnchor")&&e.viewportAnchor!=null&&!o||!ug(r,o))return null;let n=uM(e,o,t.fallbackViewport);return n==null&&!o?null:{requestKey:aM(e.requestKey,t.nextToken),flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:n,viewportAnchor:o}}function be(e){if(!e||typeof e!="object"||dg(e))return null;let t=iM(e.flowMode,e.layoutMode);if(!t)return null;let r=lo(e.anchorPageNumber),o=Go(e.viewportAnchor,{pageNumber:r}),n=De(e.requestKey);return n==null||r==null&&!o||e.viewportAnchor!=null&&!o||!ug(r,o)?null:{requestKey:n,flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:r??lo(o?.pageNumber),viewportAnchor:o}}function Mr(e,t){let r=be(e),o=be(t);return!r||!o?r===o:r.requestKey===o.requestKey&&r.flowMode===o.flowMode&&r.layoutMode===o.layoutMode&&r.anchorPageNumber===o.anchorPageNumber&&Zo(r.viewportAnchor,o.viewportAnchor)}function mg(e,t,r){let o=be(e);return o!=null&&o.flowMode===t&&o.layoutMode===r}function pg(e,t){let r=be(e),o=De(t);return r!=null&&o!=null&&r.requestKey===o}function Tc(e,t){return $t(t,e).pageNumber}function mM(e,t){return qs(e)!=null||gg(t)!=null}function fg(e,t){if(!mM(e,t))return!1;let r=$t(t,e);return r.pageNumber==null&&r.pageIndex==null}function Hs(e,t){let r=Tc(e,t);return r??(typeof t=="number"&&Number.isInteger(t)&&t>=0?t+1:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):null)}function qs(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function gg(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function pM(e,t){let r=Array.isArray(e)?[...new Set(e.map(n=>qs(n)).filter(n=>n!=null))].sort((n,i)=>n-i):[],o=Array.isArray(t)?[...new Set(t.map(n=>gg(n)).filter(n=>n!=null).map(n=>n+1))].sort((n,i)=>n-i):[];return r.length>0?o.length>0&&(o.length!==r.length||o.some((n,i)=>n!==r[i]))?[]:r:o}function wg(e,t){let r=pM(e,t);return r.length===1?r[0]??null:null}function fM(e,t){let r=qs(e),o=qs(t);return r!=null&&o!=null&&r===o?r:null}function Sg(e){return wg(e?.visiblePageNumbers,e?.visiblePageIndexes)??fM(e?.firstVisiblePageNumber,e?.lastVisiblePageNumber)??wg(e?.mountedPageNumbers,e?.mountedPageIndexes)??null}function kc(e){return fg(e?.anchorPageNumber,e?.anchorPageIndex)&&fg(e?.currentPageNumber,e?.currentPageIndex)}function wn(e){return Tc(e?.anchorPageNumber,e?.anchorPageIndex)??Tc(e?.currentPageNumber,e?.currentPageIndex)??(kc(e)?null:Sg(e))??null}function co(e){let t=Sg(e);return{anchorPageNumber:Hs(e?.anchorPageNumber,e?.anchorPageIndex)??Hs(e?.currentPageNumber,e?.currentPageIndex)??t??null,currentPageNumber:Hs(e?.currentPageNumber,e?.currentPageIndex)??Hs(e?.anchorPageNumber,e?.anchorPageIndex)??t??null}}function Ec(e){let t=wn(e);if(t!=null)return t;let r=co(e);return r.anchorPageNumber!=null&&r.currentPageNumber!=null&&r.anchorPageNumber!==r.currentPageNumber?null:r.currentPageNumber??r.anchorPageNumber??null}function ei(e,t){return e.anchorPageNumber===t.anchorPageNumber&&e.currentPageNumber===t.currentPageNumber}function vg(e,t){if(e.flowMode!==t.flowMode||e.layoutMode!==t.layoutMode)return!1;let r=e.viewportAnchor??null,o=t.viewportAnchor??null,n=ei(co(e),co(t));return!r||!o?n&&r===o:n&&Zo(r,o)}function wM(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:Yt({...e,layoutMode:"vertical"},t)}function gM(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:be({...e,layoutMode:"vertical"})}function SM(e){let t=Xo(e),r=t===e.viewportAnchor?e:{...e,viewportAnchor:t};return t!=null||wn(r)!=null?r:null}function Bt(e,t={}){let r=e?.viewport??null;if(!r)return null;let{flowMode:o,layoutMode:n}=t;if(Xo(r)==null&&kc(r))return null;let i=Yt(r,{flowMode:o,layoutMode:n})??wM(r,t);if(!i)return null;let s=SM(i);return s?o&&n?to(s,o,n)?s:null:o?_o(s,o)?s:null:n?Uo(s,n)?s:null:s:null}function xt(e,t={}){let r=be(e?.previewNavigationRequest??null)??(e?.previewNavigationRequest!=null?gM(e.previewNavigationRequest,t):null);if(!r)return null;let{flowMode:o,layoutMode:n}=t;return o&&r.flowMode!==o||n&&r.layoutMode!==n?null:r}function Ws(e,t){if(!e)return null;let r=Bt({viewport:e},t);return r?{kind:"full",viewport:r}:{kind:"page",state:co(e)}}function Ks(e){return e.kind==="full"?co(e.viewport):e.state}function hg(e,t,r={}){let o=Ws(e,r),n=Ws(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?vg(o.viewport,n.viewport):ei(Ks(o),Ks(n))}function aK(e,t,r={}){let o=Ws(e,r),n=Ws(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?ot(o.viewport,n.viewport):ei(Ks(o),Ks(n))}function yg(e){let t=Gt(e.editor),r=e.source==null?null:e.source,o=e.explicitProjection??null,n=e.boundToEditorDocument===!0||!!(t&&(e.source===t||e.source==null&&e.explicitProjection==null)),i=n?null:r!=null?o==null?r:{source:r,projection:o}:t==null?o:null;return{sourceMatchesEditorDocument:n,lifecycleSourceIdentity:i}}function Mc(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function gK(e){let t=Mc(e.controllerNavigationMode);return e.sourceMatchesEditorDocument?{controllerNavigationMode:t,syncViewportToEditor:e.syncViewportToEditor}:{controllerNavigationMode:"ignore",syncViewportToEditor:!1}}function bg(e){return Mc(e)!=="ignore"}function gn(e){return Mc(e)==="consume"}function Sn(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function vM(e,t,r){if(!t||t.viewportAnchor!=null||Bt({viewport:t},r))return!1;let o=Ec(e),n=Ec(t);return o!=null&&o===n}function Bg(e,t,r,o,n=null,i={}){if(Sn(t)!=null||!r||!gn(o))return null;let a=xt(e,i);return!a||a.requestKey===n?null:be(a)}function xg(e,t,r,o,n={}){return Sn(t)!=null||r||!gn(o)?null:xt(e,n)?.requestKey??null}function Cg(e,t,r,o,n,i=null,s={}){if(Sn(t)!=null||!r||!gn(o))return null;let l=Bt(e,s);if(!l)return null;if(tc(e?.viewportRequestKey,i))return l;let c=Bt({viewport:n??null},s);return c?hg(l,c,s)?null:l:vM(l,n??null,s)?null:l}function Pg(e,t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let r=ht(e?.zoomPercent)??100;return Math.max(.01,r/100)}function Rg(e,t,r,o,n={}){let i=Sn(t);if(i!=null)return i;if(r)return null;if(gn(o)){let a=xt(e,n);if(a?.viewportAnchor)return null;if(a?.anchorPageNumber!=null)return a.anchorPageNumber}if(!bg(o))return null;let s=Bt(e,n);return s?.viewportAnchor?null:wn(s)??wn(e?.viewport??null)}function Tg(e,t,r,o,n={}){if(Sn(t)!=null||r)return null;if(gn(o)){let s=xt(e,n);if(s)return s.viewportAnchor??null}return bg(o)?Bt(e,n)?.viewportAnchor??null:null}function kg(e,t,r,o,n={}){if(Sn(t)!=null||!gn(o))return null;let s=xt(e,n);return s?s.requestKey:Bt(e,n)?De(e?.viewportRequestKey):null}function Ic(e,t){return Hn(t)??Jr(e?.flowMode)}function Eg(e,t,r){let o=Ic(e,r),n=dt(e?.preferredPaginatedLayoutMode),i=e?.flowMode==="paginated"?dt(e?.layoutMode):null;return dr(dt(t)??(o==="paginated"?i??n??e?.layoutMode:e?.layoutMode),o)}import{buildTableGridModel as hM,readNodeAtPath as Ac,resolveRectAtLogicalPosition as yM}from"@datalking/begonia-document-api/structure";import{isDocumentNodePathIndex as bM}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as BM}from"@datalking/begonia-layout-renderer";import{NodeSelection as xM}from"prosemirror-state";function Mg(e,t){let r=e,o=-1;for(let n of t){if(!bM(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function CM(e){return BM(e)}function PM(e,t,r,o,n={}){return!e.isInline||e.childCount!==0||!xM.isSelectable(e)||e.type.name!==t.nodeType||!n.ignoreObjectId&&t.objectId&&(typeof e.attrs.objectId=="string"?e.attrs.objectId:"")!==t.objectId?!1:t.fromOffset<o&&t.toOffset>r}function Nc(e,t,r,o,n={},i=0,s=[]){if(e.isText)return{positions:s,nextOffset:i+(e.text?.length??0)};if(e.childCount===0){let c=o(e),d=i+c.length;return PM(e,r,i,d,n)&&s.push(t),{positions:s,nextOffset:d}}let a=i,l=0;for(let c=0;c<e.childCount;c+=1){let d=e.child(c);a=Nc(d,t+l+1,r,o,n,a,s).nextOffset,l+=d.nodeSize}return{positions:s,nextOffset:a}}function RM(e,t,r){if(t.type!=="table"||!Array.isArray(t.path)||t.path.length===0||r.tableOriginRow==null||r.tableOriginColumn==null)return null;let o=Oe(e).view.state.doc,n=Ac(o,t.path);if(!n||n.type.name!=="table")return null;let i=hM(n);if(i.invalidReason)return null;let s=yM(i,r.tableOriginRow,r.tableOriginColumn);if(!s)return null;let a=i.physicalRows[s.originRow]?.find(u=>u.rect===s)??null;if(!a)return null;let l=[...t.path,s.originRow,a.childIndex],c=Ac(o,l),d=Mg(o,l);return!c||d==null?null:{node:c,nodePos:d}}function TM(e,t){if(!Array.isArray(t.path)||t.path.length===0)return null;let r=Oe(e).view.state.doc,o=Ac(r,t.path),n=Mg(r,t.path);return!o?.isTextblock||n==null?null:{node:o,nodePos:n}}function Dc(e,t,r){if(!t||!Array.isArray(t.path)||t.path.length===0)return null;let o=CM(r.target);if(!o)return null;let n=Oe(e).view.state.doc,i=le(n),s=d=>Br(d,i),a=RM(e,t,o)??TM(e,t);if(!a)return null;let l=Nc(a.node,a.nodePos,o,s).positions;if(l.length===1)return l[0];if(l.length>1||!o.objectId)return null;let c=Nc(a.node,a.nodePos,o,s,{ignoreObjectId:!0}).positions;return c.length===1?c[0]:null}import{captureProjectionViewportLogicalAnchor as kM}from"@datalking/begonia-page-layout";function Ig(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Oc(e,t){return t>0?e/t:0}function jc(e){return e==="header"||e==="body"||e==="footer"}function EM(e,t,r){return jc(e)&&(r.hit==null||r.hit.region!==e)&&(t==null||t.region!==e)}function MM(e,t,r){return r&&(t==null||r.region===t||!jc(t))||!jc(t)?r:{region:t,sectionId:e.sectionId??null,anchorFrom:null,pathHint:null,blockIdentity:null,fragmentIndex:null,columnIndex:null,blockOffsetTopPx:null,blockOffsetTopRatio:null,blockOffsetLeftPx:null,blockOffsetLeftRatio:null}}function IM(e,t){let r=e.pages.findIndex(o=>o.pageNumber===t);return r<0?null:{pageIndex:r,page:e.pages[r]??null}}function Ag(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=IM(e,r);if(!o?.page)return null;let n=Math.max(0,Number(t.frame.page.pageSize.width??t.frame.contentWidth??0)),i=Math.max(0,Number(t.frame.page.pageSize.height??t.frame.contentHeight??0)),s=Number(t.frame.contentTop??0),a=Ig(t.y-s,i),l=kM(o.page,t.x,t.y),c=pn(e,t),d=EM(c,l,t)?t.x:t.pageX,u=Ig(d,n),m=MM(o.page,c,l);return{pageIndex:o.pageIndex,pageNumber:o.page.pageNumber,offsetTopPx:a,offsetTopRatio:Oc(a,i),offsetLeftPx:u,offsetLeftRatio:Oc(u,n),offsetPx:a,offsetRatio:Oc(a,i),...m}}function Vc(e){return e.selectionAnchor?{...e,pageNumber:e.selectionAnchor.pageNumber,x:e.selectionAnchor.x,pageX:e.selectionAnchor.pageX,y:e.selectionAnchor.y,hit:e.selectionAnchor.hit,clickCount:e.selectionAnchor.clickCount??e.clickCount??1,resolvedSelectionPos:e.selectionAnchor.resolvedSelectionPos??null,resolvedSelectionRange:e.selectionAnchor.resolvedSelectionRange??null,resolvedSelectionClickCount:e.selectionAnchor.resolvedSelectionClickCount??null,selectionAnchor:null,target:e.selectionAnchor.target??null}:null}function Ng(e){return{...e,clickCount:e.clickCount??e.selectionAnchor?.clickCount??1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}function Dg(e){return{...e,clickCount:1,shiftKey:!1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}import{buildTableGridModel as tI,readNodeAtPath as rI,resolveRectAtLogicalPosition as oI}from"@datalking/begonia-document-api/structure";import{isDenseArray as nI}from"@datalking/begonia-document-model/contracts";import{PREVIEW_TABLE_CELL_HORIZONTAL_PADDING as ti,PREVIEW_TABLE_CELL_VERTICAL_PADDING as _s}from"@datalking/begonia-layout-renderer";import{readNodeAtPath as NM}from"@datalking/begonia-document-api/structure";import{resolveNodeAnchorPosition as DM}from"@datalking/begonia-doc-service/v1";function Ir(e,t,r,o={}){return we(e,t,r,o)}function Lc(e,t,r,o={}){return Eo(e,t,r,o)}function Fc(e){return e+1}function jg(e,t){return Math.max(Fc(t),t+e.nodeSize-1)}function Vg(e,t,r){return Ir(e,t,jg(e,t),r)}function Lg(e,t){return Number.isInteger(e)&&e>=0&&e<=t}function AM(e,t,r,o){let n=Fc(t),i=jg(e,t);for(;n<i;){let s=n+Math.floor((i-n)/2);Ir(e,t,s,o)<r?n=s+1:i=s}return n}function Og(e,t,r,o="end",n={}){let i=Vg(e,t,n);if(!Lg(r,i))return null;let s=He(e,t,r,o,n);if(s!=null)return s;let a=AM(e,t,r,n);return o==="start"?Math.max(Fc(t),a-1):a}function ri(e,t,r,o={}){let n=Vg(e,t,o);if(!Lg(r,n))return null;let i=Lc(e,t,r,o);if(i!=null)return i;let s=Og(e,t,r,"start",o),a=Og(e,t,r,"end",o);if(s==null||a==null)return s??a;if(s===a)return s;let l=Ir(e,t,s,o),c=Ir(e,t,a,o);return r-l<=c-r?s:a}function OM(e){return e.isBlock&&e.childCount===0}function jM(e,t,r){let o=Math.max(t+1,t+e.nodeSize-1),n=Ir(e,t,o,r);return n>0?n:OM(e)?1:0}function VM(e,t,r,o=[]){let n=(i,s)=>{if(i.isTextblock||!i.firstChild?.isBlock){let a=jM(i,s,r);a>0&&o.push({node:i,from:s,flatLength:a});return}i.forEach((a,l)=>{a.isBlock&&n(a,s+l+1)})};return e.forEach((i,s)=>{i.isBlock&&n(i,t+s+1)}),o}function zc(e,t,r){let o=le(e),n=NM(e,t),i=DM(e,t);if(!n||i==null)return null;let s=VM(n,i,o),a=0,l=null;for(let d of s){let u=Math.max(0,Math.min(d.flatLength,r-a)),m=d.node.isLeaf?d.from+d.node.nodeSize:ri(d.node,d.from,u,o);if(m!=null&&(l=m),r<=a+d.flatLength)return m??l;a+=d.flatLength}let c=Math.max(0,Math.min(r,a));return l??ri(n,i,c,o)}import{resolveTableFragmentRows as LM}from"@datalking/begonia-layout-contracts";function Hc(e,t,r){return e.originRow===t&&e.originColumn===r}function Fg(e,t,r,o){let n=LM(e);if(!(n[t]??null)?.cells.some(l=>Hc(l,r,o)))return null;let s=n.find(l=>l.cells.some(c=>Hc(c,r,o)))??null,a=s?.cells.find(l=>Hc(l,r,o))??null;return!s||!a?null:{cellLayoutChildIndex:a.physicalIndex,cellLayoutIndex:s.fragmentRowIndex,sourceRowIndex:s.sourceRowIndex}}import{segmentTextGraphemes as zg}from"@datalking/begonia-layout-contracts";function Hg(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function vn(e){return{from:e,to:e}}function qg(e,t){return e<=t?{from:e,to:t}:{from:t,to:e}}function Us(e,t){return Math.max(0,Math.min(Math.round(Number(t)||0),e.content.size))}function oi(e,t,r,o,n){return Lc(e,t,Math.max(0,r),n)??o}function FM(e,t,r){return Us(e,r+Math.max(1,t.nodeSize-1))}function zM(e,t,r){return Math.max(0,Math.min(r,Math.round(Number(e)||0)-t))}function HM(e,t,r,o,n){let i=FM(e,t,r);return ri(t,r,o,n)??i}function Wg(e){return/\s/u.test(e)}function qM(e){return/^[\p{L}\p{N}\p{M}\u200c\u200d'\u2018\u2019_~-]+$/u.test(e)}function WM(e){return/\p{Extended_Pictographic}/u.test(e)}function KM(e){return/^[\p{P}]+$/u.test(e)}function _M(e){return/^[\p{S}]+$/u.test(e)}function qc(e){return Wg(e)?"whitespace":qM(e)?"word":WM(e)?"emoji":KM(e)?"punctuation":_M(e)?"symbol":"other"}function UM(e,t){let r=zg(e);if(r.length===0)return null;let o=Math.max(0,Math.min(e.length,t)),n=[Math.max(0,Math.min(e.length-1,o)),Math.max(0,Math.min(e.length-1,o-1))],i=new Set;for(let s of n){let a=r.findIndex(l=>l.fromOffset<=s&&s<l.toOffset);if(!(a<0||i.has(a))&&(i.add(a),!Wg(r[a]?.text??"")))return a}return null}function ZM(e,t){let r=zg(e),o=UM(e,t);if(o==null)return null;let n=r[o];if(!n)return null;let i=qc(n.text);if(i==="whitespace")return null;let s=o;for(;s>0&&qc(r[s-1]?.text??"")===i;)s-=1;let a=o+1;for(;a<r.length&&qc(r[a]?.text??"")===i;)a+=1;return{start:r[s]?.fromOffset??n.fromOffset,end:r[a-1]?.toOffset??n.toOffset}}function GM(e,t,r,o){let n=Br(e,o).length;return n<=0?vn(r):qg(oi(e,t,0,r,o),oi(e,t,n,r,o))}function XM(e,t,r,o,n){let i=Br(e,n),s=ZM(i,r);return s?qg(oi(e,t,s.start,o,n),oi(e,t,s.end,o,n)):vn(o)}function $M(e,t){let r=Us(e,t),o=e.resolve(r);for(let n=o.depth;n>0;n-=1){let i=o.node(n);if(i.isTextblock)return{blockNode:i,blockPos:o.before(n)}}return null}function Kg(e,t,r,o,n,i){return n>=3?GM(e,t,o,i):n===2?XM(e,t,r,o,i):vn(o)}function _g(e){let{doc:t,rawPos:r}=e,o=le(t),n=$M(t,r);if(!n)return vn(Us(t,r));let i=Us(t,r),s=Math.max(0,Ir(n.blockNode,n.blockPos,i,o)),a=oi(n.blockNode,n.blockPos,s,i,o);return Kg(n.blockNode,n.blockPos,s,a,Hg(e.clickCount),o)}function Ug(e){let{doc:t,block:r,rawPos:o}=e,n=le(t);if(!Array.isArray(r.path)||r.path.length===0)return vn(o);let i=Ve(t,r.path);if(!i?.node.isTextblock)return vn(o);let s=i.node,a=i.position,l=Br(s,n).length,c=zM(o,r.from,l),d=HM(t,s,a,c,n);return Kg(s,a,c,d,Hg(e.clickCount),n)}import{readNodeAtPath as Zg,resolvePathToPosition as Gg}from"@datalking/begonia-document-api/structure";import{isDenseArray as fr}from"@datalking/begonia-document-model/contracts";import{resolveMeasuredTextOffsetAtPoint as YM,resolveProjectionTextOffsetAtPoint as JM}from"@datalking/begonia-page-layout";function Be(e){try{let t=Number(e);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function QM(e){try{let t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:null}catch{return null}}function Zs(e){if(!fr(e))return 0;let t=0;for(let r of e)t+=Be(r);return t}function Wc(e,t){if(!fr(e))return 0;let r=Math.min(e.length,Math.max(0,Math.floor(t))),o=0;for(let n=0;n<r;n+=1)o+=Be(e[n]);return o}function Xg(e,t){let r=Array.isArray(e.tableRowSourceIndexes)&&fr(e.tableRowSourceIndexes)?e.tableRowSourceIndexes:null;return Array.from({length:t},(o,n)=>QM(r?.[n])??n)}function eI(e,t){let r=Array.from({length:t},()=>0);return e.forEach(o=>{let n=0;o.forEach(i=>{let s=Math.max(1,Math.round(Be(i.attrs.colSpan)||1)),a=Be(i.attrs.width),l=a>0?a/s:0;for(let c=0;c<s;c+=1){let d=n+c;d<r.length&&(r[d]=Math.max(r[d]??0,l))}n+=s})}),r}function $g(e,t,r){let o=Array.isArray(t.tableColumnWidths)&&fr(t.tableColumnWidths)?t.tableColumnWidths.map(s=>Be(s)):Array.isArray(e.attrs.columnWidths)&&fr(e.attrs.columnWidths)?e.attrs.columnWidths.map(s=>Be(s)):[],n=eI(e,r),i=Math.max(24,(Be(t.tableWidth)||Be(t.width)||Zs(o)||Zs(n)||r*96)/Math.max(1,r));return Array.from({length:r},(s,a)=>{let l=o[a]??0,c=n[a]??0;return Math.max(24,l||c||i)})}function Yg(e,t){if(t.length===0)return 0;let r=0;for(let o=0;o<t.length;o+=1){let n=Math.max(1,Be(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function Jg(e,t){if(t.length===0)return 0;let r=0;for(let o=0;o<t.length;o+=1){let n=Math.max(1,Be(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function Qg(e){return fr(e.tableRowHeights)?e.tableRowHeights.map(t=>Math.max(1,Be(t)||1)):[]}function eS(e,t){if(e.isTextblock)return[...t];for(let r=0;r<e.childCount;r+=1){let o=e.child(r),n=[...t,r],i=eS(o,n);if(i)return i}return null}function tS(e,t){let r=Zg(e,t);if(!r)return null;let o=eS(r,t);if(o){let i=Gg(e,o);return i==null?null:Zg(e,o)?.content.size===0?i:i+1}let n=Gg(e,t);return n==null?null:n+1}function rS(e){let{block:t,cellLayout:r,height:o,hit:n,left:i,line:s,lineCount:a,lineIndex:l,measureText:c,measurementEpoch:d,top:u,width:m,x:p}=e,f=iS(nS(r),s.fromOffset),g={pageNumber:n?.pageNumber??0,sectionIndex:n?.sectionIndex??0,sectionPageNumber:n?.sectionPageNumber??0,sectionId:n?.sectionId??null,region:n?.region??"body",blockIndex:n?.blockIndex??t.index,fragmentIndex:n?.fragmentIndex??0,columnIndex:n?.columnIndex??0,lineIndex:l,lineCount:a,from:s.fromOffset,to:s.toOffset,left:i,top:u,width:m,height:o,text:s.text,logicalText:s.text,nodeType:f?.nodeType??n?.nodeType??"table_cell",align:n?.align??t.align??null,direction:n?.direction??t.direction??null,fontSize:f?.fontSize??n?.fontSize??t.fontSize??null,tabs:f?.tabs??null,inlineSpans:f?.inlineSpans??r.inlineSpans??n?.inlineSpans??null,continuesToNext:n?.continuesToNext??!1,label:s.text},v=c?YM(g,p,c,d):JM(g,p);return Math.max(s.fromOffset,Math.min(s.toOffset,v))}function oS(e,t,r){let o=e.lineHeights,n=nS(e);return t.map((i,s)=>{let a=Be(i.lineHeight);if(a>0)return a;let l=fr(o)?Be(o[s]):0;if(l>0)return l;let c=iS(n,i.fromOffset),d=Be(c?.lineHeight);return d>0?d:r})}function nS(e){let t=fr(e.segments)?e.segments:[],r=0;return t.map(o=>{let n={segment:o,fromOffset:r,toOffset:r+o.text.length};return r=n.toOffset,n})}function iS(e,t){return e.find(r=>t<r.toOffset||r.segment.text.length===0&&t===r.fromOffset)?.segment??null}function sS(e,t){if(!fr(e)||e.length===0)return{lineIndex:0,lineTop:0};let r=Be(t),o=0;for(let n=0;n<e.length;n+=1){let i=Math.max(1,Be(e[n])||1);if(r<o+i||n===e.length-1)return{lineIndex:n,lineTop:o};o+=i}return{lineIndex:0,lineTop:0}}function aS(e){return Kc(e)?.resolvedPos??null}function Kc(e){let{doc:t,block:r,x:o,y:n}=e;if(r.type!=="table"||!r.path?.length)return null;let i=rI(t,r.path);if(!i||i.type.name!=="table")return null;let s=tI(i);if(s.invalidReason||s.rows.length===0||s.width<=0)return null;let a=Qg(r),l=Xg(r,a.length);if(l.length===0)return null;let c=$g(i,r,s.width),d=Math.max(0,o-r.left),u=Math.max(0,n-r.top),m=Yg(u,a),p=l[m]??m,f=Jg(d,c),g=oI(s,p,f);if(!g)return null;let v=iI({doc:t,block:r,fragmentRowIndex:m,rowHeights:a,model:s,rect:g});if(!v)return null;let{cellLayoutChildIndex:k,cellLayoutIndex:R,cellPath:h,cellStartPos:B,rowTop:S}=v,b=Wc(c,g.originColumn),P=Zs(c.slice(g.originColumn,g.originColumn+g.colSpan)),A=r.tableCells?.[R]?.[k]??null,O=nI(A?.lineSlices)?A.lineSlices:null;if(!O||O.length===0)return{cellPath:h,cellStartPos:B,cellLeft:b,cellWidth:P,rowTop:S,lineIndex:0,lineCount:1,line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:B,lineTop:0,lineHeight:Math.max(1,Be(r.lineHeight))};let j=Math.max(0,u-S-_s),K=Math.max(1,Be(r.lineHeight)),F=oS(A,O,K),{lineIndex:se,lineTop:E}=sS(F,j),N=O[se]??null,L=Math.max(1,F[se]??K);if(!N)return{cellPath:h,cellStartPos:B,cellLeft:b,cellWidth:P,rowTop:S,lineIndex:se,lineCount:Math.max(1,O.length),line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:B,lineTop:E,lineHeight:L};let ne=rS({block:r,cellLayout:A,height:L,line:N,lineCount:Math.max(1,O.length),lineIndex:se,left:r.left+b+ti,top:r.top+S+_s+E,width:Math.max(0,P-ti*2),x:o,measureText:e.measureText,measurementEpoch:e.measurementEpoch});return{cellPath:h,cellStartPos:B,cellLeft:b,cellWidth:P,rowTop:S,lineIndex:se,lineCount:Math.max(1,O.length),line:N,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:zc(t,h,ne)??B,lineTop:E,lineHeight:L}}function iI(e){let{doc:t,block:r,fragmentRowIndex:o,rowHeights:n,model:i,rect:s}=e;if(!Array.isArray(r.path)||r.path.length===0)return null;let a=Fg(r,o,s.originRow,s.originColumn);if(!a)return null;let l=i.physicalRows[a.sourceRowIndex]?.find(u=>u.rect===s)??null;if(!l)return null;let c=[...r.path,a.sourceRowIndex,l.childIndex],d=tS(t,c);return d==null?null:{cellLayoutChildIndex:a.cellLayoutChildIndex,cellLayoutIndex:a.cellLayoutIndex,cellPath:c,cellStartPos:d,rowTop:Wc(n,a.cellLayoutIndex)}}function lS(e,t,r,o){return zc(e,t,r)??o}function _c(e){let t=aS(e);return t==null?null:_g({doc:e.doc,rawPos:t,clickCount:e.clickCount})}function Uc(e){let t=Kc(e);if(!t)return null;let{cellPath:r,cellLeft:o,cellStartPos:n,cellText:i,cellWidth:s,line:a,lineCount:l,lineIndex:c,resolvedPos:d,rowTop:u,lineTop:m,lineHeight:p}=t,f=a?lS(e.doc,r,a.fromOffset,n):d,g=a?lS(e.doc,r,a.toOffset,d):d,v=a?.text??i,k=Math.max(1,p||Be(e.block.lineHeight)||Be(e.hit.height)||1);return{...e.hit,lineIndex:c,lineCount:l,from:Math.min(f,g),to:Math.max(f,g),left:e.block.left+o+ti,top:e.block.top+u+_s+m,width:Math.max(0,s-ti*2),height:k,text:v,label:v.trim()||e.hit.label,pos:d}}function aI(e,t,r,o){return Ug({doc:Oe(e).view.state.doc,block:t,rawPos:r,clickCount:o})}function lI(e,t){if(t.type==="table"||Jn(t)||!Array.isArray(t.path)||t.path.length===0)return null;let r=Oe(e).view.state.doc,o=sI(r,t.path);return!o||!dS.isSelectable(o)?null:ag(r,t.path)}function ni(e){return yg({editor:e.editor,source:e.previewSource,explicitProjection:e.explicitProjection,boundToEditorDocument:e.boundToEditorDocument}).sourceMatchesEditorDocument}function ii(e,t){return ig(Oe(e).view.state.doc,t.projection,t)}function Gc(e,t){let r=Ag(t.projection,t);return r?e.requestPreviewNavigation({anchorPageNumber:r.pageNumber,viewportAnchor:r})!=null:!1}function Zc(e,t){if(t==null)return null;try{let r=dS.create(Oe(e).view.state.doc,t);return{from:r.from,to:r.to}}catch{return null}}function si(e){let{editor:t,event:r}=e;if(!t||!r.hit||!ni(e)||!ii(t,r))return{block:null,nodeSelectionPos:null,nodeSelectionRange:null};let o=Qn(r.projection,r);if(!sg(o,r))return{block:o,nodeSelectionPos:null,nodeSelectionRange:null};let n=Dc(t,o,r);if(n!=null)return{block:o,nodeSelectionPos:n,nodeSelectionRange:Zc(t,n)};let i=o?lI(t,o):null;return{block:o,nodeSelectionPos:i,nodeSelectionRange:Zc(t,i)}}function cI(e,t){let r=ao(e,t),o=so(e,Oe(e).view.state.selection.anchor);return{from:Math.min(o,r.from),to:Math.max(o,r.to)}}function Xc(e,t){let{editor:r}=e;if(!r||!t.hit||!ni(e)||!ii(r,t))return null;let o=Qn(t.projection,t);if(!o)return null;if(o.type==="table"){let n=Xt(r)??{};return _c({doc:Oe(r).view.state.doc,block:o,x:t.x,y:t.y,clickCount:t.clickCount,measureText:n.measureText,measurementEpoch:n.measurementEpoch})}if(t.shiftKey){let n=Zc(r,Dc(r,o,t));if(n)return n}return!Jn(o)||!t.hit?null:aI(r,o,t.hit.pos,t.clickCount)}function cS(e,t){if(t.resolvedSelectionRange)return t.resolvedSelectionRange;let r=si({...e,event:t});return r.nodeSelectionRange?r.nodeSelectionRange:Xc(e,t)}function uS(e,t){if(!t.selectionAnchor)return t.selectionAnchor??null;let r=Vc(t);if(!r)return t.selectionAnchor;let o=ai({...e,event:r});return{...t.selectionAnchor,hit:o.hit,clickCount:o.clickCount??t.selectionAnchor.clickCount??1,resolvedSelectionPos:o.resolvedSelectionPos??null,resolvedSelectionRange:o.resolvedSelectionRange??null,resolvedSelectionClickCount:o.resolvedSelectionClickCount??null,pageX:o.pageX,target:o.target??t.selectionAnchor.target??null}}function mS(e){let{editor:t,event:r}=e;if(!t||!r.hit||!ni(e)||!ii(t,r))return r.hit??null;let o=Qn(r.projection,r);if(!o||o.type!=="table")return r.hit;let n=Xt(t)??{};return Uc({doc:Oe(t).view.state.doc,block:o,x:r.x,y:r.y,hit:r.hit,measureText:n.measureText,measurementEpoch:n.measurementEpoch})??r.hit}function pS(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r.hit?.pos??null;let o=Xc(e,Dg(r));return o?ao(t,o).from:r.hit.pos}function Gs(e){let{editor:t,event:r}=e;if(!t)return null;let o=Vc(r),n=o?(()=>{let i=cS(e,o),s=cS(e,Ng(r));return!i||!s?null:lg(i,s)})():Xc(e,r);return n?r.shiftKey?cI(t,n):n:null}function fS(e,t){return e<=t.from?t.to:e>=t.to||Math.abs(e-t.from)>Math.abs(e-t.to)?t.from:t.to}function wS(e){let{editor:t}=e;if(!t)return null;let r=si(e);if(r.nodeSelectionPos!=null)return r.nodeSelectionPos;let o=Gs(e);return o?ao(t,o).from:null}function ai(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r;let o=mS(e),n=o===r.hit?r:{...r,hit:o},i=uS(e,n),s=i===n.selectionAnchor?n:{...n,selectionAnchor:i},a=s.hit;if(!a||Rc(s))return s;let l={...e,event:s},c=fn(s.clickCount),d=si(l);if(d.nodeSelectionPos!=null)return{...s,resolvedSelectionPos:d.nodeSelectionPos,resolvedSelectionRange:null,resolvedSelectionClickCount:c,hit:{...a,pos:d.nodeSelectionPos}};let u=Gs(l);if(!u)return s;let m=ao(t,u),p=pS(l)??m.from,f=m.from===m.to;return{...s,resolvedSelectionPos:m.from,resolvedSelectionRange:m,resolvedSelectionClickCount:c,hit:{...a,pos:f?m.from:p}}}function gS(e){let{editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n,event:i}=e;if(!t||!ni(e))return!1;let s={editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n},a=Rc(i)?i:ai(e),l=pn(a.projection,a);if(!a.hit)return l?Gc(t,a):!1;if(!ii(t,a))return Gc(t,a);let c=si({...s,event:a});if(c.nodeSelectionPos!=null){let m=Oe(t);return m.view.dispatch(m.view.state.tr.setSelection(dI.create(m.view.state.doc,c.nodeSelectionPos))),m.focus(),!0}let d=a.resolvedSelectionRange?ao(t,a.resolvedSelectionRange):Gs({...s,event:a});if(a.shiftKey&&d){let m=Oe(t),p=so(t,m.view.state.selection.anchor),f=fS(p,d),g=Z(m.view.state,p,f);return g?(m.view.dispatch(m.view.state.tr.setSelection(g)),m.focus(),!0):!1}if(d){let m=Oe(t),p=tg(d,a),f=Z(m.view.state,p.anchor,p.head);return f?(m.view.dispatch(m.view.state.tr.setSelection(f)),m.focus(),!0):!1}let u=a.resolvedSelectionPos??wS({...s,event:a});if(u!=null){let m=Oe(t),p=Z(m.view.state,so(t,u));return p?(m.view.dispatch(m.view.state.tr.setSelection(p)),m.focus(),!0):!1}return!1}var uI={resolvePositionHitEvent(e){return ai(e)},handlePositionHit(e){return gS(e)}};function Xs(){return uI}var pI=mI();function $s(e){let t=null,r=null,o=new Set,n=i=>{for(let s of[...o])s(i)};return{readLayoutAdapter(){return pI},readLayoutSource(){let i=e();return i?.view?.state.doc??i?.document??null},readDocumentSize(){return e()?.view?.state.doc.content.size??null},getResolvedProjection(){return t},getResolvedProjectionGeometryOptions(){return r},setResolvedProjection(i,s=null){t=i??null,r=s??null,n(t)},subscribeResolvedProjection(i){return o.add(i),()=>{o.delete(i)}},selection:Xs()}}function SS(e){let t=()=>Qm(e),o={...$s(t),getState(){return e.getState()},subscribe(n){return e.subscribe(n)},requestPreviewNavigation(n){return e.requestPreviewNavigation(n)},ackPreviewNavigationRequest(n){e.ackPreviewNavigationRequest(n)},setViewState(n){e.setViewState(n)},setZoomViewportMetrics(n){e.setZoomViewportMetrics(n)}};return Object.defineProperty(o,"surface",{configurable:!1,enumerable:!1,get:t}),o}var Jc=Symbol.for("@datalking/begonia-browser-sdk/browser-editor-v1-runtime"),li=new WeakMap,Qc=new WeakMap;function Yc(e,t){Object.defineProperty(e,Jc,{configurable:!0,enumerable:!1,writable:!0,value:t})}function $c(e){return!e||typeof e!="object"?null:e[Jc]??null}function vS(e){!e||typeof e!="object"||delete e[Jc]}function fI(e){return"host"in e}function ed(e,t){li.set(e,t),Yc(e,t)}function Ys(e,t,r){li.set(e,r),Qc.set(t,r),Yc(e,r),Yc(t,r)}function hS(e,t){e&&(li.delete(e),vS(e)),t&&(Qc.delete(t),vS(t))}function wr(e){if(!e)return null;if(fI(e))return Qc.get(e)??$c(e)??li.get(e.host)??$c(e.host)??null;let t=he(e);return t?li.get(t)??$c(t)??null:null}function td(e){return wr(e)?.controller??null}function yS(e){return wr(e)?.advancedOoxmlActions??null}var eU=nn({commandIds:Rw});function wI(e){let t=e.getState();return{linkPopover:t.linkPopover,contextMenu:t.contextMenu}}function gI(e){let t=null,r=()=>{let o=wI(e);return(t==null||!Jo(t,o))&&(t=o),t};return{getSnapshot:r,subscribe(o){return e.subscribe(()=>{let n=t;n!=null&&r()!==n&&o()})}}}function SI(e,t=tn){let r=e.getState(),o=Zn(e,t);return cn(r,o)}function ci(e){let t=()=>SI(e);return{doc:e.documentApi,readState:t,subscribe(r){return e.subscribe(()=>{r()})},execute(r,o){return t().commands[r]?.disabled?ye("Command is disabled in the current document mode or selection."):rf(e,r,o)??ye(`Unsupported browser command: ${String(r)}`)}}}function hn(e){let t={controller:e,backend:Iw(e),advancedOoxmlActions:e},r=SS(e),o={session:ci(e),actor:null,documentApi:e.documentApi,readCommandSnapshot(n=tn){return Tw(e,n)},...Aw(e),browserViewport:eg(e,r),preview:r,overlayState:gI(e),overlays:{closeLinkPopover:()=>e.closeLinkPopover(),closeContextMenu:()=>e.closeContextMenu()}};return Object.defineProperty(o,"actor",{configurable:!1,enumerable:!0,get(){return e.actor??null}}),ed(o,t),o}function uo(e){let t=hn(e),r={...t,overlays:t.overlays??{}},o=wr(t);return o&&ed(r,o),r}function bS(e){return td(e)}function Js(e){let t=hn(e),r=ks(t),o=wr(t);return o&&Ys(t,r,o),r}var vI=ci,hI=uo,yI=hn;import{errorBegoniaResult as PS,okBegoniaResult as ea,runBegoniaResult as RS}from"@datalking/begonia-result";import{errorBegoniaResult as rd,okBegoniaResult as od,toBegoniaError as BS}from"@datalking/begonia-result";function xS(e){return!!e&&typeof e=="object"&&"ok"in e}function bI(e){return{collaborative:!0,mode:"binding",reconfigurable:e,providerName:null,roomId:null,status:"disconnected",connected:null,synced:null,awarenessClientCount:null,message:"Collaboration binding attached without session metadata."}}function Qs(e,t,r){return t?{...t.getSnapshot(),mode:"session",reconfigurable:r}:e.collaborative?bI(r):{collaborative:!1,mode:"none",reconfigurable:r,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null}}async function yn(e,t,r){if(!e?.[t])return od(r);try{let o=await e[t]();return xS(o)?o:od(o??r)}catch(o){return rd(BS(o))}}async function CS(e,t){if(!t?.encodeSnapshot)return rd({code:"invalid_request",message:"Collaboration snapshot capture requires a session with encodeSnapshot()."});try{let r=await t.encodeSnapshot();return xS(r)?r:od(r??{document:e.document,documentJson:e.document.toJSON(),update:new Uint8Array,awareness:null,snapshot:t.getSnapshot()})}catch(r){return rd(BS(r))}}function TS(e){let t=async r=>{if(!e.reconfigurable)return PS({code:"invalid_request",message:"This browser controller cannot attach collaboration because it does not own surface reconfiguration."});let o=e.getCollaborationSession(),n=e.readCollaboration(),i=o===r?n:Qs(e.getSourceRuntime().surface,r,e.reconfigurable),s=await yn(r,"connect",i);if(!s.ok)return s;if(o===r&&e.getSourceRuntime().surface.collaborative)return e.emit(),ea(e.readCollaboration());let l=await RS(()=>e.createReplacementSurface(r.binding,r));if(!l.ok)return o!==r&&await yn(r,"disconnect",i),l;if(o&&o!==r){let c=await yn(o,"disconnect",n);if(!c.ok)return l.value.destroy(),await yn(r,"disconnect",i),c}return e.swapSurface(l.value,r),e.emit(),ea(e.readCollaboration())};return{attachCollaboration:t,upgradeToCollaboration:t,async detachCollaboration(r={}){if(!e.reconfigurable)return PS({code:"invalid_request",message:"This browser controller cannot detach collaboration because it does not own surface reconfiguration."});let o=e.getCollaborationSession(),n=e.getSourceRuntime().surface;if(!o&&!n.collaborative)return e.emit(),ea(e.readCollaboration());let i=await RS(()=>e.createReplacementSurface(void 0,null));if(!i.ok)return i;let s=await yn(o,"disconnect",e.readCollaboration());return s.ok?(e.swapSurface(i.value,null),r.destroySession&&await o?.destroy?.(),e.emit(),ea(e.readCollaboration())):(i.value.destroy(),s)},async saveCollaborationSnapshot(){return CS(e.getSourceRuntime().surface,e.getCollaborationSession())}}}import{hasVisibleSemanticContent as BI,isDocumentNodePathIndex as kS}from"@datalking/begonia-document-model";function xI(e){return!!e&&typeof e=="object"&&Array.isArray(e.segments)&&e.segments.length>0}function CI(e,t){let r=e;for(let o of t){if(!r||!kS(o)||o>=r.childCount)return null;r=r.child(o)}return r}function PI(e,t){if(t.length===0)return 0;let r=0,o=e;for(let n of t){if(!kS(n)||n>=o.childCount)return null;r+=1;for(let i=0;i<n;i+=1)r+=o.child(i).nodeSize;o=o.child(n)}return r}function RI(e,t){let r=e.nodeAt(t.from)??null;return!r||t.to!==t.from+r.nodeSize||!r.isLeaf||!r.isInline||!BI(r)?null:r}function nd(e){if(e.selectionKind!=="node"||!xI(e.target))return null;let t=RI(e.doc,e.selection),r=e.target.segments[0];if(!t||!r||e.target.segments.length!==1)return null;let o=Le(e.doc,r.blockId),n=o?CI(e.doc,o):null,i=o?PI(e.doc,o):null,s=i==null?null:Math.max(-1,i-1);if(!o||!n?.isBlock||s==null)return null;let a=le(e.doc),l=we(n,s,e.selection.from,a),c=Math.max(l,we(n,s,e.selection.to,a)),d=typeof e.text=="string"?e.text:"";return{id:"browser-selection",targetKind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:[...o],addressableBlockPath:[...o],addressableBlockId:r.blockId,startOffset:l,endOffset:c,segments:[{kind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:[...o],addressableBlockPath:[...o],startOffset:l,endOffset:c,text:d}],text:d,source:"live",frozenAt:null}}import{createDocumentSurface as TI}from"@datalking/begonia-engine";function Ct(e){return typeof e=="boolean"?e:void 0}function ES(e,t){return e||!!t}function kI(e){return{...e}}function EI(e){return{...e,items:e.items.map(kI)}}function MS(e,t,r){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((o,n)=>r(o,t[n]))}function Qt(e){return{...e??{},links:e?.links?{...e.links,enabled:Ct(e.links.enabled)}:void 0,contextMenu:e?.contextMenu?{...e.contextMenu,enabled:Ct(e.contextMenu.enabled),includeDefaultItems:Ct(e.contextMenu.includeDefaultItems),customItems:e.contextMenu.customItems?.map(EI)}:void 0,trackChanges:e?.trackChanges?{...e.trackChanges,enabled:Ct(e.trackChanges.enabled),visible:Ct(e.trackChanges.visible),mode:Xr(e.trackChanges.mode)??void 0,replacements:$r(e.trackChanges.replacements)??void 0}:void 0,comments:e?.comments?{...e.comments,enabled:Ct(e.comments.enabled),visible:Ct(e.comments.visible),readOnly:Ct(e.comments.readOnly),allowResolve:Ct(e.comments.allowResolve),showResolved:Ct(e.comments.showResolved),visibility:Yr(e.comments.visibility)??void 0,useInternalExternalComments:Ct(e.comments.useInternalExternalComments),suppressInternalExternal:Ct(e.comments.suppressInternalExternal)}:void 0}}function MI(e,t){return e.id===t.id&&e.label===t.label&&e.action===t.action&&e.showWhen===t.showWhen&&e.enabledWhen===t.enabledWhen&&e.disabledReason===t.disabledReason&&e.tone===t.tone}function II(e,t){return e.id===t.id&&(e.label??null)===(t.label??null)&&MS(e.items,t.items,MI)}function id(e,t){let r=Qt(e),o=Qt(t);return r.links?.enabled===o.links?.enabled&&r.links?.popoverResolver===o.links?.popoverResolver&&r.contextMenu?.enabled===o.contextMenu?.enabled&&r.contextMenu?.includeDefaultItems===o.contextMenu?.includeDefaultItems&&r.contextMenu?.menuProvider===o.contextMenu?.menuProvider&&MS(r.contextMenu?.customItems,o.contextMenu?.customItems,II)&&r.trackChanges?.enabled===o.trackChanges?.enabled&&r.trackChanges?.visible===o.trackChanges?.visible&&r.trackChanges?.mode===o.trackChanges?.mode&&r.trackChanges?.replacements===o.trackChanges?.replacements&&r.comments?.enabled===o.comments?.enabled&&r.comments?.visible===o.comments?.visible&&r.comments?.readOnly===o.comments?.readOnly&&r.comments?.allowResolve===o.comments?.allowResolve&&r.comments?.showResolved===o.comments?.showResolved&&r.comments?.visibility===o.comments?.visibility&&r.comments?.useInternalExternalComments===o.comments?.useInternalExternalComments&&r.comments?.suppressInternalExternal===o.comments?.suppressInternalExternal&&r.comments?.permissionResolver===o.comments?.permissionResolver}function IS(e){let{actor:t,templates:r,viewSelect:o,collaborationSession:n,documentMode:i,enableEmbeddedAdvancedOoxmlEditors:s,zoomPercent:a,modules:l,permissionResolver:c,surfaceFactory:d,...u}=e;return({collaborative:m,documentStory:p,editable:f,element:g,initialContent:v,participant:k,schema:R,trackingEnabled:h})=>TI({...u,element:g??u.element,collaborative:m,documentStory:p,editable:f,initialContent:v,schema:R??u.schema,participant:k,trackingEnabled:h,features:e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:_i(e.features??[])})}function Ar(e,t){return e.eq(t)}function q(e){return{changed:!1,reason:e}}function AS(e,t,r,o=!1){let n=an(t,r.trackChanges),i=xw(t,r.comments),s=t!=="viewing"||e.collaborative&&!o,a=nt(e),l=s&&(n.mode==="original"||n.mode==="final")?{...n,mode:"review"}:n,c=!a&&!i.readOnly?{...i,readOnly:!0,allowResolve:!1}:i;return{trackChanges:l,comments:c}}function Nr(e){if(!e||typeof e!="object")return!1;let t=e.selection,r=e.selectionKind,o=e.selectionTarget;return t!=null&&typeof t=="object"&&Number.isInteger(t.from)&&Number.isInteger(t.to)&&(r==="text"||r==="node")&&"selectionTarget"in e&&(o==null||typeof o=="object")}function NS(e){let t=o=>At(typeof o=="string"?[o]:[],Ue(e.readVisibleComments()))[0]??null,r=(o,n,i={})=>e.runAndEmit(()=>{let s=e.getRuntime().documentApi.comments.create({text:o,target:structuredClone(n),actor:e.getCurrentActor()??void 0,isInternal:i.isInternal,authorId:e.getCurrentActor()?.id??null,authorName:e.getCurrentActor()?.name??null});if(s.changed&&"id"in s&&typeof s.id=="string"){let a=e.getRuntime().documentApi.comments.target(s.id);a&&no(e.getRuntime().surface,a)}return s});return{createComment(o,n={}){let i=e.commentWriteReason();if(i)return q(i);let s=e.readEffectiveSelection(),a=s?.target??Ht(e.getRuntime().surface.state);if(!a)return q("Place the caret in text or select text before creating a comment.");let l=s?nd({doc:e.getRuntime().surface.state.doc,selection:s.selection,selectionKind:s.selectionKind,target:a,text:s.text??null}):null;return r(o,l??a,n)},createCommentFromCapture(o,n,i={}){let s=e.commentWriteReason();if(s)return q(s);let a=Nr(o)?o.selectionTarget:null;if(!o?.target&&!a)return q("Capture a text selection or caret before creating a comment.");let l=Nr(o)?e.resolveSelectionCapture(o,{includeText:!0})??e.readSelectionCapture(o,{includeText:!0})??o:o,c=e.resolveCommentTargetFromCapture(o);if(!c)return q("Captured selection is no longer available after the document changed. Capture a new text selection or caret before creating a comment.");let u=(Nr(l)?nd({doc:e.getRuntime().surface.state.doc,selection:l.selection,selectionKind:l.selectionKind,target:c,text:l.text??null}):null)??c;if(Nr(l)&&l.target){let m=l.text??null;if(m!=null&&m.length>0)return r(n,u,i)}return r(n,u,i)},replyComment(o,n,i=null){let s=e.commentWriteReason();return s?q(s):e.runAndEmit(()=>e.getRuntime().documentApi.comments.reply(o,{parentEntryId:i,text:n,authorId:e.getCurrentActor()?.id??null,authorName:e.getCurrentActor()?.name??null},e.getCurrentActor()??void 0))},setCommentInternal(o,n){let i=e.commentWriteReason();return i?q(i):e.runAndEmit(()=>e.getRuntime().documentApi.comments.patch(o,{isInternal:n},e.getCurrentActor()??void 0))},resolveComment(o){if(!e.readCommentResolveState().allowResolve)return q("Comment resolution is disabled.");let n=e.commentWriteReason();return n?q(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.resolve(o,e.getCurrentActor()??void 0))},reopenComment(o){if(!e.readCommentResolveState().allowResolve)return q("Comment resolution is disabled.");let n=e.commentWriteReason();return n?q(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.reopen(o,e.getCurrentActor()??void 0))},setActiveComment(o){if(o==null)return e.setActiveCommentId(null),e.emit(),!0;let n=t(o);return n?(e.setActiveCommentId(n),e.emit(),!0):!1}}}import{normalizeHyperlinkHref as oa}from"@datalking/begonia-document-model";import{NodeSelection as DS}from"prosemirror-state";function jS(e,t){return{left:e+8,top:t+12}}function AI(){return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]}}function NI(e){let{selection:t}=e,{$from:r}=t,o=new Set;W(t)&&o.add(t.node.type.name);for(let n=0;n<=r.depth;n+=1)o.add(r.node(n).type.name);return[...o]}function OS(e,t){return Math.max(1,Math.min(t,e.content.size))}function DI(e,t){return Math.max(0,Math.min(t,e.content.size))}function OI(e,t){let r=Math.min(e.selection.from,e.selection.to),o=Math.max(e.selection.from,e.selection.to);return(t.segments?.length?t.segments:[t]).every(i=>r<=i.from&&o>=i.to)}function jI(e){let t=ce(e.effectiveTrackedChangeIds,e.revisions);if(!e.selectionCapture||e.selectionCapture.selection.empty)return t;if(t.length===0)return[];let r=lr({from:e.selectionCapture.selection.from,to:e.selectionCapture.selection.to,trackedChangeIds:[]},e.revisions);if(r.length<=t.length)return t;let o=new Set(t),n=new Map(e.revisions.map(s=>[s.id,s]));return r.filter(s=>!o.has(s)).some(s=>{let a=n.get(s);return a?!OI(e.selectionCapture,a):!1})?r:t}function VI(e,t){let{selection:r}=e;return r.from===t.selection.from&&r.to===t.selection.to&&r.empty===t.selection.empty&&(t.selectionKind!=="node"||W(r)&&(!t.nodeSelectionTarget||sr(Ae(e),t.nodeSelectionTarget)))}function LI(e,t){if(t.selectionKind==="node"){let n=Zr(e,t.nodeSelectionTarget);if(n)return n;let i=DI(e.doc,Math.min(t.selection.from,t.selection.to)),s=e.doc.nodeAt(i);if(s&&DS.isSelectable(s))try{return e.apply(e.tr.setSelection(DS.create(e.doc,i)))}catch{}}let r=OS(e.doc,Math.min(t.selection.from,t.selection.to)),o=OS(e.doc,Math.max(t.selection.from,t.selection.to));try{let n=Z(e,r,o);return n?e.apply(e.tr.setSelection(n)):null}catch{return null}}function FI(e,t,r){return t||(!r||VI(e,r)?e:LI(e,r)??e)}function zI(e){return W(e.selection)?e.selection.node.type.name:e.selection.$from.parent.type.name}function HI(e,t){return t?[...t.activeMarks]:Ee(e).activeMarks}function qI(e,t){return t?[...t.activeCommentIds]:Ee(e).activeCommentIds}function WI(e){let t=new Set(Ee(e).activeMarks);if(!e.selection.empty)return[...t];for(let r of e.storedMarks??[])t.add(r.type.name);for(let r of e.selection.$from.marks())t.add(r.type.name);for(let r of e.selection.$from.nodeBefore?.marks??[])t.add(r.type.name);for(let r of e.selection.$from.nodeAfter?.marks??[])t.add(r.type.name);return[...t]}function KI(e){if(!e.pointSelectionCapture)return AI();let t=e.surface.view?.dom;return Vw({host:t,clientX:e.clientX,clientY:e.clientY,revisions:e.revisions,comments:e.comments})}function ta(e,t){try{let r=e.view.posAtDOM(t,0),o=e.view.posAtDOM(t,t.childNodes.length);if(r>=o)return!1;let n=Z(e.view.state,r,o);return n?qe(e,n):!1}catch{return!1}}function VS(e,t,r,o,n,i,s){return{host:e,href:o.getAttribute("href")??"",title:o.getAttribute("title"),target:o.getAttribute("target"),rel:o.getAttribute("rel"),tooltip:o.getAttribute("title"),element:o,clientX:n,clientY:i,isAnchorLink:(o.getAttribute("href")??"").startsWith("#"),documentMode:r,position:jS(n,i),resolution:s}}function ra(e,t,r){let o=ve(e),n=uo(e),i=r.selectionCapture??null,s=r.actionSelectionCapture??i,a=r.pointSelectionCapture??null,l=r.pointSelectionState??null,c=e.documentApi?.comments?.list?.()??e.getState?.().comments??[],d=KI({surface:o,pointSelectionCapture:a,clientX:r.clientX,clientY:r.clientY,revisions:r.revisions,comments:c}),u=[...d.trackedChangeIds],m=[...d.commentIds],p=FI(o.state,r.selectionState,i),f=l??p,g=r.selection??p.selection,v=NI(f),k=qI(p,i),R=l?WI(f):HI(p,i),h=r.reviewActionsEnabled,B=(()=>{if(!h)return[];let b=de(r.selection?.trackedChangeIds??r.selectionTrackedChangeIds);if(r.selection?.trackedChangeIdsExplicit===!0)return jI({effectiveTrackedChangeIds:b,selectionCapture:s??i,revisions:r.revisions});let P=de(o.listSelectionRevisionIds?.());return lr({from:g.from,to:g.to,trackedChangeIds:b.length>0?b:P},r.revisions)})(),S=a&&B.length===0&&d.status==="resolved"&&u.length>0?[...u]:B;return{host:n,trigger:"contextmenu",selectedText:g.empty?"":ge(p.doc,o.schema,g),hasSelection:!g.empty,selectionStart:g.from,selectionEnd:g.to,isInTable:v.some(b=>b==="table"||b==="table_row"||b==="table_cell"),isInList:v.some(b=>b==="bullet_list"||b==="ordered_list"||b==="list_item"),isTrackedChange:S.length>0,trackedChangeIds:[...S],hasAmbiguousPointReviewTarget:a!=null&&d.status==="ambiguous",pointReviewTrackedChangeIds:u,pointReviewCommentIds:m,documentMode:t,currentNodeType:zI(f),activeCommentIds:k,activeMarks:R,selectionCapture:i,actionSelectionCapture:s,pointSelectionCapture:a,isEditable:nt(o),pos:l?l.selection.from:g.from,clientX:r.clientX,clientY:r.clientY,position:jS(r.clientX,r.clientY)}}function LS(e){let t=()=>e.reviewWriteReason()==null,r=l=>ir({editable:t()},e.getRuntime().surface.state,l??null),o=l=>{if(!l)return null;let c=e.readSelectionCapture(l,{includeText:!0});return c&&r(c)==null?c:null},n=l=>{let c=e.readEffectiveSelection();return r(c)!=null?!1:tt(e.getRuntime().surface,c,l)},i=(l,c,d={})=>{let u=o(l);return u?tt(e.getRuntime().surface,u,c,d):!1},s=(l,c,d={})=>i(e.resolveSelectionHandle(l,{includeText:!0}),c,d),a=l=>{let c=e.getLinkPopover();if(!c||!t())return!1;let d=e.getLinkPopoverSelectionCapture();if(d){let u=o(d);return u?.selection.formatting.link?tt(e.getRuntime().surface,u,l,{restoreSelection:!1}):(e.setLinkPopover(null),!1)}return ta(e.getRuntime().surface,c.element)?l(e.getRuntime().surface):(e.setLinkPopover(null),!1)};return{search(l,c={}){let d=l.trim();e.setSearchQuery(d),e.setSearchOptions(c);let u=d?e.getPresentationReadApi().search.query(d,c):[];return e.setActiveSearchHitId(u[0]?.hitId??null),e.emit(),u},nextSearchHit(){let l=e.getSearchQuery(),c=l?e.getPresentationReadApi().search.next(l,e.getActiveSearchHitId(),e.getSearchOptions()):null;return e.setActiveSearchHitId(c?.hitId??e.getActiveSearchHitId()),e.emit(),c},previousSearchHit(){let l=e.getSearchQuery(),c=l?e.getPresentationReadApi().search.previous(l,e.getActiveSearchHitId(),e.getSearchOptions()):null;return e.setActiveSearchHitId(c?.hitId??e.getActiveSearchHitId()),e.emit(),c},clearSearch(){e.setSearchQuery(""),e.setSearchOptions({}),e.setActiveSearchHitId(null),e.emit()},replaceSearchHit(l,c){let d=e.reviewWriteReason();return d?q(d):e.runAndEmit(()=>e.getWritableRuntimeApi().search.replace(e.getSearchQuery(),l,c,e.getSearchOptions()))},replaceAllSearchHits(l){let c=e.reviewWriteReason();return c?q(c):e.runAndEmit(()=>e.getWritableRuntimeApi().search.replaceAll(e.getSearchQuery(),l,e.getSearchOptions()))},ignoreProofingDiagnostic(l){let c=e.reviewWriteReason();return c?q(c):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.ignore(l))},acceptProofingSuggestion(l){let c=e.reviewWriteReason();return c?q(c):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.acceptSuggestion(l))},replaceProofingDiagnosticTracked(l,c){let d=e.reviewWriteReason();return d?q(d):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.replaceTracked(l,c,e.getRuntime().surface.participant,{source:"browser-proofing"}))},setLink(l,c=null){let d=oa(l);if(!t()||!d)return!1;let u=n(p=>p.setLink(d,c)),m=e.getLinkPopover();return u&&m&&e.setLinkPopover({...m,href:d,title:c}),e.emit(),u},setLinkFromCapture(l,c,d=null,u={}){let m=oa(c);if(!t()||!m)return!1;let p=i(l,g=>g.setLink(m,d),u),f=e.getLinkPopover();return p&&f&&e.setLinkPopover({...f,href:m,title:d}),e.emit(),p},setLinkFromHandle(l,c,d=null,u={}){let m=oa(c);if(!t()||!m)return!1;let p=s(l,g=>g.setLink(m,d),u),f=e.getLinkPopover();return p&&f&&e.setLinkPopover({...f,href:m,title:d}),e.emit(),p},clearLink(){if(!t())return!1;let l=n(c=>c.clearLink());return l&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),l},clearLinkFromCapture(l,c={}){if(!t())return!1;let d=i(l,u=>u.clearLink(),c);return d&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),d},clearLinkFromHandle(l,c={}){if(!t())return!1;let d=s(l,u=>u.clearLink(),c);return d&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),d},updateActiveLink(l,c=null){let d=e.getLinkPopover(),u=oa(l);if(!d||!t()||!u)return!1;let m=a(p=>p.setLink(u,c));return m&&e.setLinkPopover({...d,href:u,title:c}),e.emit(),m},clearActiveLink(){return!e.getLinkPopover()||!t()?!1:a(c=>c.clearLink())?(e.closeLinkPopover(),!0):(e.emit(),!1)}}}import{preservedSelectionPluginKey as oA}from"@datalking/begonia-engine";function Dr(e,t={},r="paired"){return Ee(e.state,t,{reviewReplacementMode:r})}function _I(e){return e!=null}function FS(e){return[e.comments?.target(e.commentId),e.comments?.targetSnapshot?.(e.commentId),e.fallbackTarget].filter(_I)}function UI(e){return FS(e)[0]??null}function di(e){for(let t of FS(e)){let r=e.resolve(t);if(r!=null)return{target:t,resolution:r}}return null}function ZI(e){return e.hasSemanticSelection?e.captureSelectionIsRanged?!e.semanticSelectionIsCollapsed:e.semanticSelectionIsCollapsed:!1}function GI(e){return e.hasUniqueCommentId&&(e.captureSelectionIsRanged||e.captureSelectionIsCollapsed||!e.hasCaptureSelection)}function zS(e){let t=[];return ZI(e)&&t.push("semantic-selection"),GI(e)&&t.push("comment-target"),e.hasAmbiguousCommentIds||(e.captureSelectionIsCollapsed?t.push("collapsed-absolute"):e.captureSelectionIsRanged&&t.push("ranged-absolute")),t}function XI(e){return e.length===1?e[0]:null}function $I(e,t){return nf(e?.activeCommentIds,t)}function ui(e){return!!(e&&e.from===e.to)}function YI(e,t){return e.from===t.from&&e.to===t.to}function na(e){return Math.max(e.to-e.from,0)}function JI(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.targetKind;return t==="range"||t==="anchor"||t==="comment"}function QI(e){return JI(e?.target)?e.target:null}function eA(e){return{get state(){return e.state},view:e}}function tA(e){let t=e.surface.view;if(!t?.state||typeof t.dispatch!="function")return!1;let r=[e.captureSelection?.from,t.state.selection.from,t.state.selection.to].filter(o=>Number.isInteger(o));for(let o of new Set(r)){let n=Z(t.state,o,o);if(n&&qe(e.surface,n))return!0}return!1}function rA(e){let t=e.collapsedSemanticSelection.from,r=e.activeCommentIds.map(a=>di({comments:e.comments,commentId:a,fallbackTarget:null,resolve:l=>Ze(e.doc,l)})).filter(a=>a!=null&&a.resolution.from<a.resolution.to&&a.resolution.from<=t&&t<a.resolution.to).sort((a,l)=>na(a.resolution)-na(l.resolution));if(r.length===0)return null;let[o,...n]=r,i=na(o.resolution);return n.filter(a=>na(a.resolution)===i).every(a=>YI(a.resolution,o.resolution))?o.target:null}function mi(e){let t=e.capture?.selection??null,r=t!=null&&t.from===t.to,o=t!=null&&t.from!==t.to,n=$I(e.capture,e.comments),i=XI(n),s=e.surface.view;if(!s?.state||typeof s.dispatch!="function")return!1;if(e.capture?.selectionKind==="node"){let f=cr(eA(s),e.capture);if(f)return qe(e.surface,f)}let a=e.capture?cs(s.state,{selectionTarget:e.capture.selectionTarget??null,segmentTexts:e.capture.segmentTexts??null,text:e.capture.text??void 0})??Ne(s.state.doc,e.capture.selectionTarget??null,e.capture.text??null,{strict:!0}):null,c=(i?di({comments:e.comments,commentId:i,fallbackTarget:QI(e.capture),resolve:f=>Ze(s.state.doc,f)}):null)?.resolution??null;if(r&&t!=null&&Number.isInteger(t.from)&&t.from>=1&&t.from<=s.state.doc.content.size&&t&&i&&(!a||ui(a)&&a.from!==t.from)){let f=Z(s.state,t.from,t.to);if(f&&qe(e.surface,f))return!0}let m=zS({captureSelectionIsCollapsed:r,captureSelectionIsRanged:o,hasCaptureSelection:t!=null,hasSemanticSelection:a!=null,semanticSelectionIsCollapsed:ui(a),hasUniqueCommentId:i!=null,hasAmbiguousCommentIds:n.length>1});for(let f of m){if(f==="semantic-selection"&&a){let g=Z(s.state,a.from,a.to);if(!g)continue;if(qe(e.surface,g))return!0;continue}if(f==="comment-target"&&i){let g=c?Z(s.state,c.from,c.to):null;if(g&&qe(e.surface,g))return!0;continue}if((f==="collapsed-absolute"||f==="ranged-absolute")&&t){if(f==="ranged-absolute"&&n.length>0&&(!a||ui(a)))continue;let g=Z(s.state,t.from,t.to);if(!g)continue;try{if(qe(e.surface,g))return!0}catch{continue}}}let p=n.length>1&&a&&ui(a)?rA({activeCommentIds:n,comments:e.comments,collapsedSemanticSelection:a,doc:s.state.doc}):null;return p&&no(e.surface,p)?!0:o&&n.length>0&&(!a||ui(a))?tA({captureSelection:t,surface:e.surface}):!1}function HS(e){let t=()=>{let S=e.readEffectiveSelection(),{surface:b,documentApi:P,replacementMode:A}=e.getRuntime(),O=b.describeSelection(),j=Dr(b,{},A);return S?{effectiveSelection:S,liveSelection:O,revisionIds:yt({liveSelection:O,liveSelectionInfo:j,revisions:P.review.list(),effectiveSelection:S})}:{effectiveSelection:null,liveSelection:O,revisionIds:lr(O,P.review.list())}},r=S=>S.revisionIds.length===1&&(S.effectiveSelection?.selection.empty??S.liveSelection.empty),o=(S,b,P=null)=>e.runAndEmit(()=>{let A=S==="accept"?e.getRuntime().documentApi.review.accept(b,e.getCurrentActor()??void 0):e.getRuntime().documentApi.review.reject(b,e.getCurrentActor()??void 0);return A.changed&&P?.(),A}),n=S=>mi({capture:S,surface:e.getRuntime().surface,comments:e.getRuntime().documentApi.comments}),i=(S,b)=>{let P=e.readEffectiveSelection();return o(S,[b],()=>n(P))},s=S=>{let{surface:b}=e.getRuntime();return typeof b.listSelectionRevisionIds!="function"||ar(S,b.listSelectionRevisionIds())},a=(S,b)=>({changed:S,revisionIds:[...b],activityId:null,activityIds:[],decisions:[],activities:[]}),l=()=>e.getRuntime().documentApi.review.decisionActivity({sort:"asc"}),c=()=>new Set(l().map(S=>S.activityId)),d=(S,b,P)=>{let A=l().filter(j=>!P.has(j.activityId));if(A.length===0)return a(S,b);let O=A.map(j=>({activityId:j.activityId,revisionId:j.revisionId,decision:j.decision,relatedKinds:[...j.relatedKinds],memberCount:j.memberCount,memberRevisionIds:[...new Set(j.record.members.map(K=>K.revisionId))],memberEntryIds:[...j.memberEntryIds],createdAt:j.updatedAt??null,authorId:j.authorId??null,authorName:j.authorName??null,revisionAuthorId:j.revisionAuthorId??null,revisionAuthorName:j.revisionAuthorName??null,revisionCreatedAt:j.revisionCreatedAt??null}));return{changed:S,revisionIds:[...new Set([...b,...A.map(j=>j.revisionId)])],activityId:A[0]?.activityId??null,activityIds:A.map(j=>j.activityId),decisions:O,activities:A}},u=S=>tt(e.getRuntime().surface,e.readEffectiveSelection(),S),m=S=>{let b=S.effectiveSelection,P=S.liveSelection,A=e.getRuntime().surface,O=A.view;if(!b||b.selection.empty||b.activeCommentIds.length>0||P.empty||!O?.state||typeof O.dispatch!="function")return!1;let j=Z(O.state,Math.min(P.from,P.to),Math.min(P.from,P.to));return j?qe(A,j):!1},p=S=>{n(S.effectiveSelection),m(S)},f=()=>{let{surface:S}=e.getRuntime(),b=S.view;!b?.state||typeof b.dispatch!="function"||b.dispatch(b.state.tr.setMeta(oA,{preservedSelection:null}))},g=(S,b,P,A)=>{let{revisionIds:O}=b;if(r(b)){let F=O[0];return F?i(S,F):q("No tracked changes overlap the current selection.")}if(O.length===0)return q("No tracked changes overlap the current selection.");let j=c();return(P&&s(O)?u(P):!1)?(A(),d(!0,O,j)):o(S,O,A)},v=()=>e.getPresentationReadApi().review.list(),k=S=>ce(typeof S=="string"?[S]:[],v())[0]??null,R=S=>{e.setActiveRevisionIds(S),e.emit()},h=()=>{e.setActiveRevisionIds([]),e.emit()},B=S=>{let b=v(),P=oc(b,e.getActiveRevisionId(),S);return P?(R([P]),P):null};return{acceptRevision(S){let b=e.reviewWriteReason();if(b)return q(b);let P=e.readEffectiveSelection();return o("accept",[S],()=>n(P))},rejectRevision(S){let b=e.reviewWriteReason();if(b)return q(b);let P=e.readEffectiveSelection();return o("reject",[S],()=>n(P))},acceptSelection(){let S=e.reviewWriteReason();if(S)return q(S);let b=t();return g("accept",b,P=>typeof P.acceptSelectionRevisions=="function"?P.acceptSelectionRevisions():!1,()=>p(b))},rejectSelection(){let S=e.reviewWriteReason();if(S)return q(S);let b=t();return g("reject",b,P=>typeof P.rejectSelectionRevisions=="function"?P.rejectSelectionRevisions():!1,()=>{e.clearPreservedRangeSelection(),p(b),f()})},acceptAll(){let S=e.reviewWriteReason();if(S)return q(S);let b=e.readEffectiveSelection();return o("accept",void 0,()=>n(b))},rejectAll(){let S=e.reviewWriteReason();if(S)return q(S);let b=e.readEffectiveSelection();return o("reject",void 0,()=>n(b))},setActiveRevision(S){if(S==null)return h(),!0;let b=k(S);return b?(R([b]),!0):!1},nextActiveRevision(){return B("next")},previousActiveRevision(){return B("previous")}}}function qS(e){return{...TS(e),...NS(e),...HS(e),...LS(e)}}function nA(e){return{id:e.id,name:e.name,role:"reviewer"}}function sd(e,t,r,o){return Cw(e===void 0?nA(t):e,r,o??void 0)}function mo(e,t,r,o){return sd(e,t.participant,r,o)}import{createDefaultViewportFitControllerState as fA}from"@datalking/begonia-layout-renderer/core";function ia(e,t="paired"){return{sourceRuntime:null,activeRuntime:null,canonicalDocument:e,projectionKind:"none",projectedRuntimeBank:null,replacementMode:t,collaborativeProjection:null}}function po(e){return e.projectionKind==="inline"}function iA(e){return e.projectionKind==="collaborative"}function ad(e,t,r=t.replacementMode){return{...e,sourceRuntime:t,activeRuntime:iA(e)&&e.activeRuntime?e.activeRuntime:t,replacementMode:r,canonicalDocument:po(e)?e.canonicalDocument:t.surface.document}}function bn(e){if(!e.sourceRuntime||po(e))return e;let t=e.sourceRuntime.surface.document;return ld(e,t)}function ld(e,t){return t===e.canonicalDocument?e:{...e,canonicalDocument:t}}function pi(e,t,r=e.replacementMode){return e.projectedRuntimeBank===t&&e.replacementMode===r?e:{...e,projectedRuntimeBank:t,replacementMode:r}}function WS(e){return e.sourceRuntime?{...e,activeRuntime:e.sourceRuntime,projectionKind:"inline",collaborativeProjection:null}:e}function KS(e,t){return{...e,activeRuntime:t.runtime,projectionKind:"collaborative",collaborativeProjection:t}}function fi(e){return{...e,activeRuntime:e.sourceRuntime,projectionKind:"none",collaborativeProjection:null}}function _S(e){return{...e,sourceRuntime:null,activeRuntime:null,projectedRuntimeBank:null,collaborativeProjection:null,projectionKind:"none"}}function cd(e,t){let r=zs(t,{flowMode:e.flowMode,layoutMode:e.layoutMode,fallbackViewport:re(e.viewport),nextToken:e.nextPreviewNavigationRequestToken});return r?Mr(e.previewNavigationRequest,r)?{nextState:e,request:be(e.previewNavigationRequest),changed:!1}:{nextState:{...e,previewNavigationRequest:r,nextPreviewNavigationRequestToken:e.nextPreviewNavigationRequestToken+1},request:be(r),changed:!0}:{nextState:e,request:null,changed:!1}}function dd(e,t){return!e.previewNavigationRequest||t!=null&&!pg(e.previewNavigationRequest,t)?e:{...e,previewNavigationRequest:null}}function wi(e,t){return Object.hasOwn(e,t)&&e[t]!==void 0}function sA(e,t){return t||(e.flowMode==="paginated"?e.layoutMode:e.preferredPaginatedLayoutMode)}function US(e,t,r){return!e||!to(e,t,r)||rc(e,t,r)?null:e}function aA(e,t,r,o,n){if(!r)return{viewport:e,ignoredIncompatibleViewport:!1};let i=Yt(t.viewport??null,{flowMode:o,layoutMode:n});if(!i)return{viewport:null,ignoredIncompatibleViewport:!1};let s=US(i,o,n);return{viewport:s??e,ignoredIncompatibleViewport:s==null}}function lA(e){if(e.hasViewportRequestKey){if(e.hasViewport){if(e.ignoredIncompatibleViewport)return e.currentViewportState!=null?e.state.viewportRequestKey:null;if(e.normalizedViewportState==null)return null}return e.currentViewportState!=null||e.normalizedViewportState!=null?e.requestedViewportRequestKey:null}return e.hasViewport?e.normalizedViewportState==null?null:ot(e.currentViewportState,e.normalizedViewportState)?e.state.viewportRequestKey:null:e.normalizedViewportState!=null?e.requestedViewportRequestKey:e.state.viewport!=null?null:e.requestedViewportRequestKey}function cA(e){return e.previewNavigationRequest?e.appliedViewportRequestKey&&e.nextViewportRequestKey!=null&&!Ps(e.currentViewportRequestKey,e.nextViewportRequestKey)?!0:e.hasViewport&&e.normalizedViewportState!=null&&!ot(e.currentViewportState,e.normalizedViewportState):!1}function dA(e){return be(e)}function uA(e){return re(e)}function mA(e){return e.request?{anchorPageNumber:e.request.anchorPageNumber,viewportAnchor:e.request.viewportAnchor}:e.viewport?{}:null}function pA(e){if(!e.modesChanged||e.normalizedViewportState!=null)return null;let t=mA({request:e.previousPreviewNavigationRequest,viewport:e.previousViewportState});return t?zs(t,{flowMode:e.nextFlowMode,layoutMode:e.nextLayoutMode,fallbackViewport:e.previousViewportState,nextToken:e.state.nextPreviewNavigationRequestToken}):null}function ud(e,t,r){let o=wi(t,"flowMode"),n=wi(t,"layoutMode"),i=wi(t,"zoomPercent"),s=wi(t,"viewport"),a=wi(t,"viewportRequestKey"),l=o?Hn(t.flowMode):null,c=n?dt(t.layoutMode):null,d=a?De(t.viewportRequestKey):e.viewportRequestKey,u=l??e.flowMode,m=sA(e,c),p=dr(m,u),f=dA(e.previewNavigationRequest),g=uA(e.viewport),v=US(g,u,p),{viewport:k,ignoredIncompatibleViewport:R}=aA(v,t,s,u,p),h=lA({state:e,requestedViewportRequestKey:d,hasViewportRequestKey:a,hasViewport:s,currentViewportState:v,normalizedViewportState:k,ignoredIncompatibleViewport:R}),B=i?ht(t.zoomPercent)??r:r,S=u!==e.flowMode||p!==e.layoutMode,b=mg(e.previewNavigationRequest,u,p)?be(e.previewNavigationRequest):null,P=cA({previewNavigationRequest:b,currentViewportRequestKey:e.viewportRequestKey,hasViewport:s,currentViewportState:v,normalizedViewportState:k,appliedViewportRequestKey:a&&(!s||!R&&k!=null),nextViewportRequestKey:h})?null:b,A=P??pA({state:e,nextFlowMode:u,nextLayoutMode:p,normalizedViewportState:k,previousPreviewNavigationRequest:f,previousViewportState:g,modesChanged:S}),j=P==null&&A!=null?e.nextPreviewNavigationRequestToken+1:e.nextPreviewNavigationRequestToken,K=e.previewNavigationRequest!=null&&f==null,F=m!==e.preferredPaginatedLayoutMode,se=!ot(e.viewport,k),E=!Ps(e.viewportRequestKey,h),N=K||!Mr(e.previewNavigationRequest,A);return!S&&!F&&!se&&!E&&!N&&!(B!==r)?{nextState:e,nextZoomPercent:B,changed:!1,modesChanged:!1}:{nextState:{...e,flowMode:u,layoutMode:p,preferredPaginatedLayoutMode:m,viewport:k,viewportRequestKey:h,previewNavigationRequest:A,nextPreviewNavigationRequestToken:j},nextZoomPercent:B,changed:!0,modesChanged:S}}function md(e,t,r=t){return{flowMode:e,layoutMode:t,preferredPaginatedLayoutMode:r,viewport:null,viewportRequestKey:null,previewNavigationRequest:null,nextPreviewNavigationRequestToken:1}}function ZS(e,t,r,o,n,i,s,a,l,c,d){return{resolvedModules:e,listeners:new Set,reconfigurable:t,allowSelectionInViewMode:r,actorInput:o,currentActor:n,documentMode:i,readModel:ia(c),viewportSession:md(s,a,l),searchQuery:"",activeSearchHitId:null,searchOptions:{},activeCommentId:null,activeRevisionId:null,activeRevisionIds:[],normalizeOverlayState:null,linkPopover:null,contextMenu:null,preservedRangeSelection:null,collaborationSession:d,unsubscribeCollaborationSession:null,viewportFitState:fA()}}function X(e){if(!e.readModel.activeRuntime)throw new Error("Browser editor runtime is not mounted.");return e.readModel.activeRuntime}function Ie(e){if(!e.readModel.sourceRuntime)throw new Error("Browser editor source runtime is not mounted.");return e.readModel.sourceRuntime}function wA(e){return!!(e.previous&&e.previous.from!==e.previous.to&&(!e.current||e.current.from===e.current.to))}function gr(e,t,r=!0){let o=(r&&e.readState(),e.context.preservedRangeSelection);t()&&e.runBatchedEmit(()=>{e.clearEphemeralOverlays(),e.applySurfaceDisplayState(),r&&o&&(e.context.preservedRangeSelection=o),e.readState(),r&&wA({current:e.context.preservedRangeSelection,previous:o})&&(e.context.preservedRangeSelection=o,e.readState()),e.emit()})}function pd(e,t){return{...e??{},...t}}function sa(e,t){return{...e??{},...t}}function GS(e){return{setModules(t){gr(e,()=>(e.context.resolvedModules=Qt(t),e.context.currentActor=mo(e.context.actorInput,e.getSurface(),e.context.resolvedModules.comments,e.permissionResolver),!0))},setDocumentMode(t){let r=Bs(t);gr(e,()=>e.context.documentMode===r?!1:(e.context.documentMode=r,!0))},setTrackChangesDisplayMode(t){let r=Ef(t);gr(e,()=>e.context.resolvedModules.trackChanges?.mode===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{mode:r}),!0))},setTrackChangesReplacementMode(t){let r=Mf(t);gr(e,()=>e.context.resolvedModules.trackChanges?.replacements===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{replacements:r}),!0))},setTrackChangesVisible(t){let r=zn(t,"trackChanges.visible");gr(e,()=>e.context.resolvedModules.trackChanges?.visible===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{visible:r}),!0))},setCommentsVisible(t){let r=zn(t,"comments.visible");gr(e,()=>e.context.resolvedModules.comments?.visible===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{visible:r}),!0),!1)},setCommentsReadOnly(t){let r=zn(t,"comments.readOnly");gr(e,()=>e.context.resolvedModules.comments?.readOnly===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{readOnly:r}),!0),!1)},setCommentsShowResolved(t){let r=zn(t,"comments.showResolved");gr(e,()=>e.context.resolvedModules.comments?.showResolved===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{showResolved:r}),!0),!1)},setCommentsVisibility(t){let r=If(t);gr(e,()=>e.context.resolvedModules.comments?.visibility===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{visibility:r}),!0),!1)}}}function fd(e){return e==null?e:structuredClone(e)}function aa(e){return e&&{...e,groups:e.groups?[...e.groups]:e.groups}}function XS(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function $S(e){return{...e,zoomPercent:Object.hasOwn(e,"zoomPercent")&&e.zoomPercent!==void 0?ht(e.zoomPercent)??void 0:e.zoomPercent,viewportRequestKey:Object.hasOwn(e,"viewportRequestKey")&&e.viewportRequestKey!==void 0?De(e.viewportRequestKey):e.viewportRequestKey}}function gA(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&"segments"in e&&Array.isArray(e.segments)}function YS(e){if(!e.captureTarget||!gA(e.captureTarget))return e.resolvedTarget??null;if(e.captureStillTracked&&e.resolvedTarget)return e.resolvedTarget;if(e.originalTargetText!=null&&typeof e.captureText=="string"&&e.originalTargetText===e.captureText){let t=e.resolvedText?.length??-1;if((e.resolvedTarget||e.captureStillTracked)&&e.originalTargetText.length>=t)return e.captureTarget}return e.originalTargetText!=null&&e.resolvedText!=null?e.resolvedTarget??e.captureTarget:e.resolvedTarget??null}function la(e){return"documentService"in e?{documentApi:e.documentApi,documentService:e.documentService}:{documentApi:e.documentApi,documentService:e.service}}function SA(e){return{projectedMode:e.projectedMode,projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,presentationReadRuntime:e.presentationReadRuntime,canonicalReviewRuntime:e.canonicalReviewRuntime,writableRuntime:e.writableRuntime}}function JS(e){let t=Bw(e.trackChangesMode),r=hw(e.projectedRuntimeBank),o=la(e.presentationRuntime),n=la(e.writableRuntime??e.presentationRuntime),i=t&&r?la(r.resolveRuntime(t)):o,s=t&&r?la(r.resolveRuntime("tracked")):n;return SA({projectedMode:t,projectedRuntimeBank:r,canonicalDocument:e.canonicalDocument??null,presentationReadRuntime:i,canonicalReviewRuntime:s,writableRuntime:n})}function vA(e){let t=e.activeRuntime??e.sourceRuntime;if(!t)throw new Error("Browser editor presentation runtime is not mounted.");return t}function hA(e){let t=e.sourceRuntime??e.activeRuntime;if(!t)throw new Error("Browser editor writable runtime is not mounted.");return t}function Or(e,t){return JS({presentationRuntime:vA(e),writableRuntime:hA(e),projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,trackChangesMode:t})}import{readViewportFitState as yA,resolveViewportFitZoomPercent as bA,updateViewportFitMetrics as BA,updateViewportFitMode as xA,updateViewportFitWidthOptions as CA}from"@datalking/begonia-layout-renderer/core";function ca(e,t){return yA(e.viewportFitState,{zoomPercent:t,flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function QS(e){return bA(e.viewportFitState,{flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function wd(e,t){let r=xA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function ev(e,t){let r=CA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function tv(e,t){let r=BA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function rv({context:e,emit:t,getEmissionVersion:r,applySurfaceDisplayState:o}){let n=()=>ur(Ie(e).documentApi.preferences.get()),i=l=>{let c=Ie(e),d=ur(c.documentApi.preferences.get());return l===d?!1:(c.documentApi.preferences.set({zoomPercent:l}),!0)},s=()=>{let l=QS(e);return l==null?!1:i(l)},a=l=>{r()===l&&t()};return{getFlowMode(){return e.viewportSession.flowMode},getLayoutMode(){return e.viewportSession.layoutMode},getZoomPercent:n,getZoomState(){return ca(e,n())},getViewportState(){return re(e.viewportSession.viewport)},requestPreviewNavigation(l){if(e.readModel.sourceRuntime==null)return null;let c=cd(e.viewportSession,l);return c.request?(e.viewportSession=c.nextState,c.changed&&t(),c.request):null},ackPreviewNavigationRequest(l){if(e.readModel.sourceRuntime==null)return;let c=dd(e.viewportSession,l);c!==e.viewportSession&&(e.viewportSession=c,t())},setViewState(l){if(!l||typeof l!="object")return;let c=e.readModel.sourceRuntime;if(c==null)return;let d=ur(c.documentApi.preferences.get()),u=$S(l),m=Object.hasOwn(u,"zoomPercent")&&u.zoomPercent!==void 0?wd(e,"manual"):!1,p=ud(e.viewportSession,u,d);if(!p.changed&&!m)return;e.viewportSession=p.nextState,p.modesChanged&&o();let f=r();p.nextZoomPercent!==d&&c.documentApi.preferences.set({zoomPercent:p.nextZoomPercent}),a(f)},setZoomMode(l){if(!wd(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setFitWidthOptions(l){if(!ev(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setZoomViewportMetrics(l){if(!tv(e,l)||e.readModel.sourceRuntime==null)return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)}}}import{DELETION_MARK_NAME as fD,describeSurfaceSelection as wD,INSERTION_MARK_NAME as gD}from"@datalking/begonia-engine";import{NodeSelection as SD}from"prosemirror-state";import{documentWideMutationEffect as vD}from"@datalking/begonia-editor-contracts";import{cloneSelectionTextRange as uD}from"@datalking/begonia-document-api/core";import{cloneSelectionTextRange as PA}from"@datalking/begonia-document-api/core";import{resolveRevisionProjectedDocument as RA}from"@datalking/begonia-engine";import{collectDocumentNodesIncludingSyntheticSideStories as TA,readSyntheticSideStoryDocOriginPath as kA}from"@datalking/begonia-doc-service/v1";import{formatAddressableBlockIdWithLogicalId as EA,parseAddressableBlockId as MA}from"@datalking/begonia-doc-service/structure";var ov=new WeakMap,nv=new WeakMap;function IA(e){let t=ov.get(e);if(t)return t;let r=TA({schema:e.type.schema,readDocument:()=>e},{include:(o,n)=>o.type.name==="doc"&&n.length>0,map:(o,n)=>({doc:o,path:[...n]})});return ov.set(e,r),r}function AA(e,t){if(!t)return e;let r=nv.get(e)??{},o=r[t];if(o)return o;let n=RA(e,e.type.schema,t);return nv.set(e,{...r,[t]:n}),n}function NA(e,t,r){if(!e||!t||e.eq(t))return null;let o=kA(e);if(o)return o;let n=IA(AA(t,r)).filter(i=>i.doc.eq(e));return n.length===1?n[0].path:null}function er(e){let t=NA(e.projectedDocument,e.canonicalDocument,e.projectedMode);if(!t)return e.blockId;let r=MA(e.blockId);return!r||r.path.some(o=>o<0)?e.blockId:EA(r.blockType,[...t,...r.path],r.logicalId)}function iv(e){if(!e.target)return e.target;let t=e.target.segments.map(o=>({blockId:er({blockId:o.blockId,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),range:PA(o.range)}));return t.some((o,n)=>o.blockId!==e.target?.segments[n]?.blockId)?{kind:"text",segments:t,...e.target.story?{story:structuredClone(e.target.story)}:{}}:e.target}import{readSyntheticSideStoryDocContext as OA}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as jA,semanticNodeText as VA}from"@datalking/begonia-document-model";import{isAddressableTextHiddenLeaf as DA}from"@datalking/begonia-document-model";function tr(e){return e.isText?e.text?.length??0:!e.isLeaf||DA(e)?0:1}var LA="\uFFFC";function sv(e){if(e.isText)return e.text??"";if(e.childCount===0){if(tr(e)===0)return"";let o=VA(e);return o.length===1?o:LA}let t=[],r=!0;return e.forEach(o=>{o.isBlock&&!r&&t.push(`
7
+ `),t.push(sv(o)),r=!1}),t.join("")}function da(e,t){let r=Le(e,t);if(!r)return null;let o=e;for(let n of r){if(!jA(n)||n>=o.childCount)return null;o=o.child(n)}return o.isBlock?{node:o,path:r}:null}function Pt(e,t){let r=da(e,t);return r?sv(r.node):null}function jr(e){let t=vw([e.currentDocument,e.expectedProjectedDocument]);return t?OA({schema:e.schema,port:{replaceDocument(){}},readDocument(){return e.expectedProjectedDocument}},t)?.doc??null:e.expectedProjectedDocument}import{isAddressableTextHiddenLeaf as zA,isDocumentNodePathIndex as HA}from"@datalking/begonia-document-model";import{readReviewLedger as FA}from"@datalking/begonia-engine";function gd(e){return e.join(".")}function av(e,t,r){return e.isInline?!wt(e,t,!r):r}function Sd(e,t){if(e.marks.some(o=>fp(o.type.name,t)&&(o.attrs.blockAttrsBefore!=null||o.attrs.blockAttrsAfter!=null)))return!0;let r=!1;return e.forEach(o=>{!r&&Sd(o,t)&&(r=!0)}),r}function lv(e,t){let r=t==="final"?"delete":"insert";return new Set(FA(e).filter(o=>o.entryType==="revision"&&o.kind===r&&o.target?.blockPath.length).map(o=>gd(o.target.blockPath)))}function gi(e){let t=lv(e,"final"),r=lv(e,"original"),o=new Map,n=(i,s,a,l)=>{let c=av(i,"final",a),d=av(i,"original",l);if(i.isText||i.isLeaf){let p=tr(i)>0;return{contentFinal:c&&p,contentOriginal:d&&p}}let u=!1,m=!1;if(i.forEach((p,f,g)=>{let v=n(p,[...s,g],c,d);u||=v.contentFinal,m||=v.contentOriginal}),i.isBlock){let p=gd(s);o.set(p,{final:!(t.has(p)&&!u&&!Sd(i,"final")),original:!(r.has(p)&&!m&&!Sd(i,"original"))})}return{contentFinal:u,contentOriginal:m}};return n(e,[],!0,!0),{isBlockPresent(i,s){return o.get(gd(i))?.[s]??!0}}}var dv=Object.freeze({blockSeparator:`
8
+ `});function uv(e,t){let r=Le(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!HA(i)||i>=o.childCount)return null;n+=1;for(let s=0;s<i;s+=1)n+=o.child(s).nodeSize;o=o.child(i)}return o.isBlock?{document:e,node:o,path:r,position:n}:null}function cv(e,t,r){return e.isInline?!wt(e,t,!r):r}function qA(e){return e.isText?e.text?.length??0:!e.isLeaf||zA(e)?0:tr(e)}function fo(e,t,r,o,n,i){let s=t+1;if(r<=s)return 0;let a=0,l=!1,c=(u,m,p,f)=>{let g=0,v=!0,k=!1;for(let R=0;R<u.childCount;R+=1){if(l)return;let h=u.child(R),B=m+g,S=[...f,R],b=!h.isBlock||i.isBlockPresent(S,o);if(h.isBlock&&!v)if(r>=B+1)a+=p&&b&&k?1:0;else{l=!0;return}d(h,B,p&&b,S),g+=h.nodeSize,h.isBlock&&(k||=p&&b),v=!1}},d=(u,m,p,f)=>{if(l)return;let g=cv(u,o,p);if(u.isText){let v=u.text?.length??0,k=m+v;r>=k?a+=g?v:0:(a+=g?Math.max(0,r-m):0,l=!0);return}if(u.isLeaf){r>=m+u.nodeSize?a+=g?qA(u):0:l=!0;return}c(u,m+1,g,f)};return c(e,s,cv(e,o,!0)&&i.isBlockPresent(n,o),n),a}function vd(e,t,r,o,n,i,s){let a=t+1,l=Math.max(a,t+e.nodeSize-1),c=fo(e,t,l,n,i,s);if(!Number.isInteger(r)||r<0||r>c)return null;let d=a,u=l;for(;d<u;){let p=d+Math.floor((u-d)/2);fo(e,t,p,n,i,s)<r?d=p+1:u=p}if(o!=="start")return d;let m=d;for(;m<l&&fo(e,t,m+1,n,i,s)===r;)m+=1;return m}function Vr(e){let t=uv(e.document,e.blockId);if(!t)return null;let r=le(e.document,dv),o=gi(t.document);if(e.range.start===e.range.end){let l=Eo(t.node,t.position,e.range.start,r);return typeof l=="number"?{start:fo(t.node,t.position,l,e.projectedMode,t.path,o),end:fo(t.node,t.position,l,e.projectedMode,t.path,o)}:null}let n=He(t.node,t.position,e.range.start,"start",r),i=He(t.node,t.position,e.range.end,"end",r);if(typeof n!="number"||typeof i!="number")return null;let s=fo(t.node,t.position,n,e.projectedMode,t.path,o),a=fo(t.node,t.position,i,e.projectedMode,t.path,o);return{start:Math.min(s,a),end:Math.max(s,a)}}function ua(e){let t=uv(e.document,e.blockId);if(!t)return null;let r=le(e.document,dv),o=gi(t.document);if(e.range.start===e.range.end){let l=vd(t.node,t.position,e.range.start,"end",e.projectedMode,t.path,o);return typeof l=="number"?{start:we(t.node,t.position,l,r),end:we(t.node,t.position,l,r)}:null}let n=vd(t.node,t.position,e.range.start,"start",e.projectedMode,t.path,o),i=vd(t.node,t.position,e.range.end,"end",e.projectedMode,t.path,o);if(typeof n!="number"||typeof i!="number")return null;let s=we(t.node,t.position,n,r),a=we(t.node,t.position,i,r);return{start:Math.min(s,a),end:Math.max(s,a)}}import{hasVisibleSemanticContent as _A}from"@datalking/begonia-engine";function WA(e,t){let r=Math.min(e.length,t.length),o=0;for(;o<r&&e[o]===t[o];)o+=1;return o}function KA(e,t,r){let o=Math.min(e.length-r,t.length-r),n=0;for(;n<o&&e[e.length-1-n]===t[t.length-1-n];)n+=1;return n}function Si(e,t){if(e===t)return{current:{start:0,end:e.length},next:{start:0,end:t.length}};let r=WA(e,t),o=KA(e,t,r);return{current:{start:r,end:e.length-o},next:{start:r,end:t.length-o}}}function UA(e){return tr(e)}function mv(e){return e.length>0&&e.trim().length===0}function ZA(e){return e==="paragraph"||e==="heading"}function pv(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function GA(e,t){return Cr(e,t)}function XA(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.position+e.node.nodeSize;return o>=e.position&&n<=i}function $A(e){let t=[],r=(o,n,i,s)=>{let a=o.isInline?wt(o,"final",i):!1,l=o.isInline?wt(o,"original",s):!1,c=o.isText||o.isLeaf&&_A(o)?UA(o):0;if(c>0){t.push({from:n,to:n+(o.isText?c:o.nodeSize),projectedLength:c,visibleFinal:!a,visibleOriginal:!l});return}o.forEach((d,u)=>{r(d,n+1+u,a&&o.isInline,l&&o.isInline)})};return r(e.node,e.position,!1,!1),t}function yv(e){return Math.max(0,e.end-e.start)}function fv(e,t){return!!(e?.precise&&t.length>0&&yv(e.range)!==t.length)}function wv(e,t){return!!(e?.precise&&t.length>0&&yv(e.range)===t.length)}function yd(e,t,r){let o=0;for(let n of e){let i=t==="final"?n.visibleFinal:n.visibleOriginal;if(r<=n.from)break;if(r>=n.to){i&&(o+=n.projectedLength);continue}i&&(o+=n.projectedLength===n.to-n.from?r-n.from:r>n.from?n.projectedLength:0);break}return o}function bv(e,t,r){let o=e.target;if(o&&pv(o.blockPath,r.path)&&typeof o.from=="number"&&typeof o.to=="number")return{range:{start:Zt(r,o.from),end:Zt(r,o.to)},precise:!0};if(typeof e.from=="number"&&typeof e.to=="number")return XA(r,e.from,e.to)?{range:{start:Zt(r,e.from),end:Zt(r,e.to)},precise:!0}:null;let n=t.target;return n&&pv(n.blockPath,r.path)&&typeof n.from=="number"&&typeof n.to=="number"?{range:{start:Zt(r,n.from),end:Zt(r,n.to)},precise:!1}:null}function gv(e,t,r,o,n){let i=bv(n.member,o,t);if(!i)return null;let s=yd(e,r,i.range.start),a=yd(e,r,i.range.end);return{range:{start:Math.min(s,a),end:Math.max(s,a)},precise:i.precise}}function Sv(e,t,r,o,n){let i=bv(n.member,o,t);if(!i)return null;let s=yd(e,r,i.range.start);return{start:s,end:s}}function hd(e,t){let r=0;for(let o of e)(t==="final"?o.visibleFinal:o.visibleOriginal)&&(r+=o.projectedLength);return{start:0,end:r}}function vv(e,t){let r=t?.member.target??e?.target??null;return r&&(r.nodeType==="bookmark_anchor"||r.nodeType==="structural_revision_carrier")&&ZA(r.blockType)?r:null}function YA(e){return e.currentText.length>0||e.nextText.length>0?!1:!!(vv(e.currentRevision,e.currentSide)||vv(e.nextRevision,e.nextSide))}function hv(e,t,r,o){let n=Si(t,r),i=o==="current"?n.current:n.next;return{start:e.start+i.start,end:e.start+i.end}}function Bv(e){let t=GA(e.canonicalDocument,e.blockId);if(!t)return null;let r=$A(t),o=e.projectedMode==="final"?"original":"final",n=YA({currentRevision:e.currentRevision,currentSide:e.currentSide,nextRevision:e.nextRevision,nextSide:e.nextSide,currentText:e.currentText,nextText:e.nextText}),i=mv(e.currentText)&&mv(e.nextText),s=e.currentSide&&e.currentRevision?gv(r,t,e.projectedMode,e.currentRevision,e.currentSide):null,a=e.nextSide&&e.nextRevision?gv(r,t,o,e.nextRevision,e.nextSide):null,l=fv(s,e.currentText),c=fv(a,e.nextText),d=wv(s,e.currentText),u=wv(a,e.nextText),m=n?hd(r,e.projectedMode):i&&s||d&&s||l&&s?s.range:s?hv(s.range,e.currentText,e.nextText,"current"):e.nextSide&&e.nextRevision?Sv(r,t,e.projectedMode,e.nextRevision,e.nextSide):null,p=n?hd(r,e.projectedMode):s?.precise||s&&e.currentText.length>0&&e.currentText.trim().length===0?s.range:m,f=n?hd(r,o):i&&a||u&&a||c&&a?a.range:a?hv(a.range,e.currentText,e.nextText,"next"):e.currentSide&&e.currentRevision?Sv(r,t,o,e.currentRevision,e.currentSide):null;return m&&p&&f?{currentRange:m,currentActiveRange:p,nextRange:f}:null}function xv(e){return typeof e?.member.text=="string"?e.member.text:""}function JA(e){return e==="final"?new Set(["insert","format"]):new Set(["delete","format"])}function Cv(e,t){let r=JA(t),o=(e.members??[]).filter(n=>r.has(n.kind)).map(n=>({revisionId:e.id,member:n,sortFrom:n.target?.from??n.from??e.target?.from??e.from}));return o.length>0?o:e.kind&&r.has(e.kind)?[{revisionId:e.id,member:{revisionId:e.id,kind:e.kind,text:"text"in e&&typeof e.text=="string"?e.text:"",from:e.from,to:e.to,target:e.target??null},sortFrom:e.target?.from??e.from}]:[]}function QA(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function eN(e){let t=new Map;return e.forEach((r,o)=>{let n=QA(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...Cv(r,"final")),i.originals.push(...Cv(r,"original")),t.set(n,i)}),[...t.values()]}function Pv(e,t){return e.sortFrom-t.sortFrom}function Bn(e){let t=[],r=e.revisions,o=new Map(r.map(i=>[i.id,i]));for(let i of eN(r)){let s=[...e.projectedMode==="final"?i.finals:i.originals].sort(Pv),a=[...e.projectedMode==="final"?i.originals:i.finals].sort(Pv),l=Math.max(s.length,a.length);if(l!==0)for(let c=0;c<l;c+=1){let d=s[c]??null,u=a[c]??null;if(!d&&!u)continue;let m=d?o.get(d.revisionId)??null:null,p=u?o.get(u.revisionId)??null:null,f=xv(d),g=xv(u),v=Bv({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,currentRevision:m,currentSide:d,nextRevision:p,nextSide:u,currentText:f,nextText:g});v&&t.push({revisionId:d?.revisionId??u?.revisionId??"",preservesWholeCurrentSide:!!(d&&(!u||d.revisionId!==u.revisionId)),currentActiveRange:v.currentActiveRange,currentRange:v.currentRange,nextRange:v.nextRange})}}let n=new Map;return t.sort((i,s)=>i.currentRange.start-s.currentRange.start||i.currentRange.end-s.currentRange.end||i.nextRange.start-s.nextRange.start||i.nextRange.end-s.nextRange.end||i.revisionId.localeCompare(s.revisionId)).forEach(i=>{n.set(JSON.stringify([i.revisionId,i.preservesWholeCurrentSide,i.currentActiveRange.start,i.currentActiveRange.end,i.currentRange.start,i.currentRange.end,i.nextRange.start,i.nextRange.end]),i)}),[...n.values()]}function Rv(e){return typeof e=="string"&&e.length>0?e:""}function Tv(e,t){let r=t==="final"?new Set(["insert","format"]):new Set(["delete","format"]),o=(e.members??[]).filter(i=>r.has(i.kind)).map(i=>({revisionId:e.id,text:Rv(i.text)})).filter(i=>i.text.length>0);if(o.length>0)return o;let n=Rv(e.text);return e.kind&&r.has(e.kind)&&n.length>0?[{revisionId:e.id,text:n}]:[]}function kv(e){let t=new Map;for(let r of e)t.set(JSON.stringify([r.revisionId,r.text]),r);return[...t.values()]}function tN(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function Ev(e){let t=new Map;return e.forEach((r,o)=>{let n=tN(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...Tv(r,"final")),i.originals.push(...Tv(r,"original")),t.set(n,i)}),[...t.values()].map(r=>({finals:kv(r.finals),originals:kv(r.originals)}))}function Mv(e){let t=new Map;for(let r of e)t.set(`${r.currentText}\0${r.nextText}`,r);return[...t.values()]}function Iv(e){let t=[];for(let r of Ev(e)){if(r.finals.length>0&&r.originals.length>0){for(let o of r.finals)for(let n of r.originals)t.push({currentText:o.text,nextText:n.text}),t.push({currentText:n.text,nextText:o.text});continue}for(let o of r.finals)t.push({currentText:o.text,nextText:""});for(let o of r.originals)t.push({currentText:o.text,nextText:""})}return Mv(t)}function Av(e,t){let r=[];for(let n of Ev(e)){let i=t==="final"?n.finals:n.originals,s=Mv((t==="final"?n.originals:n.finals).map(a=>({currentText:a.text,nextText:a.text}))).map(a=>a.currentText);for(let a of i){if(s.length===0){r.push({revisionId:a.revisionId,currentText:a.text,nextText:""});continue}for(let l of s)r.push({revisionId:a.revisionId,currentText:a.text,nextText:l})}}let o=new Map;for(let n of r)o.set(`${n.revisionId}\0${n.currentText}\0${n.nextText}`,n);return[...o.values()]}function ma(e,t){let r=[];if(t.length===0)return r;let o=0;for(;o<=e.length;){let n=e.indexOf(t,o);if(n<0)break;r.push({start:n,end:n+t.length}),o=n+1}return r}function pa(e,t){return t.start===t.end?e.start===e.end?e.start===t.start:e.start<=t.start&&e.end>t.start:e.start===e.end?t.end>t.start&&e.start>=t.start&&e.start<t.end:e.end>t.start&&e.start<t.end}function fa(e,t){return e.end>t.start}function wa(e,t,r){if(e<=t.start)return e;if(e<t.end){let o=t.end-t.start;if(r<=0||o<=0)return t.start;let n=Math.round((e-t.start)/o*r);return t.start+Math.max(0,Math.min(r-1,n))}return t.start+r+(e-t.end)}function rN(e){return e.currentText.length===0&&e.nextText.length>0||e.currentText.length>0&&e.nextText.length===0}function oN(e){return e.filter(rN).length===1}function nN(e){return e.length>0&&e.trim().length===0}function iN(e){return{current:e.occurrence,next:{start:e.occurrence.start,end:e.occurrence.start+e.nextText.length}}}function Bd(e,t){let r=iN(t),o=r.next.end-r.next.start;return{active:pa(e,nN(t.currentText)?t.occurrence:r.current),needsRebase:fa(e,r.current),nextRange:{start:wa(e.start,r.current,o),end:wa(e.end,r.current,o)}}}function sN(e){let t=new Map;for(let r of e)t.set(`${r.start}:${r.end}`,r);return[...t.values()]}function bd(e,t,r){if(t===r)return null;let o=Si(t,r),n=o.next.end-o.next.start;if(!fa(e,o.current))return null;let i=l=>l<=o.current.start?l:l<o.current.end?o.current.start+Math.max(0,Math.min(n,l-o.current.start)):o.current.start+n+(l-o.current.end),s=i(e.start),a=i(e.end);return{start:Math.min(s,a),end:Math.max(s,a)}}function aN(e,t,r){let o=Si(t,r),n=o.current.end-o.current.start,i=o.next.end-o.next.start;return e.currentRange.end-e.currentRange.start===n&&e.nextRange.end-e.nextRange.start===i}function lN(e,t,r){return e.currentRange.start===0&&e.currentRange.end===t.length&&e.nextRange.start===0&&e.nextRange.end===r.length}function Nv(e,t){let r=0;for(let o of t){let n=o.currentRange.end-o.currentRange.start,i=o.nextRange.end-o.nextRange.start;if(e<=o.currentRange.start)return e+r;if(e<o.currentRange.end)return o.nextRange.start+wa(e-o.currentRange.start,{start:0,end:n},i);r+=i-n}return e+r}function cN(e,t){let r=[...t].sort((s,a)=>s.currentRange.start-a.currentRange.start||s.currentRange.end-a.currentRange.end||s.nextRange.start-a.nextRange.start||s.nextRange.end-a.nextRange.end||s.revisionId.localeCompare(a.revisionId));if(!r.some(s=>fa(e,s.currentRange)))return null;let n=Nv(e.start,r),i=Nv(e.end,r);return{start:Math.min(n,i),end:Math.max(n,i)}}function Sr(e){if(e.canonicalDocument&&e.projectedMode&&e.blockId){let o=Bn({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(o.length>0){if(o.length===1&&aN(o[0],e.currentBlockText,e.nextBlockText)){let i=bd(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}if(o.length===1&&lN(o[0],e.currentBlockText,e.nextBlockText)){let i=bd(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}let n=cN(e.selectionRange,o);return n||null}}let t=Iv(e.revisions),r=sN(t.flatMap(o=>ma(e.currentBlockText,o.currentText).flatMap(n=>{let i=e.currentBlockText.slice(0,n.start),s=e.currentBlockText.slice(n.end);if(e.nextBlockText!==`${i}${o.nextText}${s}`)return[];let a=Bd(e.selectionRange,{occurrence:n,currentText:o.currentText,nextText:o.nextText});return a.needsRebase?[a.nextRange]:[]})));return r.length===1?r[0]:r.length===0&&oN(t)?bd(e.selectionRange,e.currentBlockText,e.nextBlockText):null}function dN(e,t){return t!=="visible"||e.preservesWholeCurrentSide||e.currentActiveRange.start<e.currentRange.start||e.currentActiveRange.end>e.currentRange.end?e.currentActiveRange:e.currentRange}function vi(e){if(!e.projectedMode||!e.projectedDocument||!e.selectionTarget)return lr(e.selection,e.revisions);let t=e.activationScope??"preserved",r=iv({target:e.selectionTarget,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode})??e.selectionTarget;if(e.canonicalDocument){let s=new Set,a=!1;for(let l of r.segments){let c=Bn({blockId:l.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(c.length===0)continue;let d=Vr({document:e.projectedDocument,blockId:l.blockId,projectedMode:e.projectedMode,range:l.range})??l.range;a=!0;for(let u of c)pa(d,dN(u,t))&&s.add(u.revisionId)}if(s.size>0)return ce([...s],e.revisions);if(a)return[]}let o=Av(e.revisions,e.projectedMode),n=!1,i=new Set;for(let s of r.segments){let a=Pt(e.projectedDocument,s.blockId);if(typeof a=="string")for(let l of o){let c=ma(a,l.currentText);if(c.length===0||(n=!0,c.length!==1))continue;Bd(s.range,{occurrence:c[0],currentText:l.currentText,nextText:l.nextText}).active&&i.add(l.revisionId)}}return i.size>0?ce([...i],e.revisions):n?[]:ce(e.selection.trackedChangeIds,e.revisions)}function We(e){return e.view?.state?.doc??e.state?.doc??e.document}import{readSyntheticSideStoryDocContext as uN,readSyntheticSideStoryDocOriginPath as mN}from"@datalking/begonia-doc-service/v1";import{projectAcceptedTextBetween as pN}from"@datalking/begonia-engine";function fN(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function xn(e,t){return e.content.size>0?pN(e,t,1,e.content.size,`
9
+ `):""}function Dv(e,t,r,o){let n=Me(e,t,r);return uN(fN(n),o)?.doc??null}function wN(e,t){let r=mN(e.document);if(!r)return null;let o=Dv(t,e,"final",r),n=Dv(t,e,"original",r),i=!!o?.eq(e.document),s=!!n?.eq(e.document);if(i!==s)return i?"final":"original";if(!o||!n)return null;let a=xn(e.document,e.schema),l=xn(o,e.schema),c=xn(n,e.schema),d=a===l;return d!==(a===c)?d?"final":"original":null}function ga(e,t){if(!t||e.document.eq(t))return null;let r=wN(e,t);if(r)return r;let o=Me(t,e,"final");if(e.document.eq(o))return"final";let n=Me(t,e,"original");if(e.document.eq(n))return"original";let i=xn(e.document,e.schema),s=xn(o,e.schema),a=xn(n,e.schema),l=i===s;return l===(i===a)?null:l?"final":"original"}import{describeSurfaceSelection as eh}from"@datalking/begonia-engine";import{formatAddressableBlockIdWithLogicalId as gN,parseAddressableBlockId as Ov}from"@datalking/begonia-doc-service/structure";import{resolveRevisionProjectedDocument as SN}from"@datalking/begonia-engine";function vN(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function hN(e){return e==="final"?"original":"final"}function jv(e){if(!e.target||!e.sourceTarget||!e.projectedDocument||!e.canonicalDocument||!e.projectedMode)return e.target;let t=SN(e.canonicalDocument,e.canonicalDocument.type.schema,hN(e.projectedMode)),r=e.target.segments.map((n,i)=>{let s=e.sourceTarget?.segments[i],a=Ov(n.blockId),l=s?Ov(s.blockId):null;if(!s||!a||!l?.logicalId)return n;let c=gN(a.blockType,a.path,l.logicalId),d=Q(t,{kind:"text",segments:[n]},{strict:!0}),u=Q(t,{kind:"text",segments:[{blockId:c,range:{start:n.range.start,end:n.range.end}}]},{strict:!0});return!(u&&(!d||!vN([d.from,d.to],[u.from,u.to])))?n:{blockId:c,range:{start:n.range.start,end:n.range.end}}});return r.some((n,i)=>n.blockId!==e.target?.segments[i]?.blockId)?Kt(e.target,r):e.target}import{addressableBlockTypeForNodeType as yN,formatAddressableBlockId as bN}from"@datalking/begonia-doc-service/structure";function hi(e,t){let r=da(e,t);if(!r)return t;let o=yN(r.node.type.name);return o?bN(o,r.path):t}function wo(e,t){if(!t)return t;let r=le(e),o=t.segments.map(i=>{let s=hi(e,i.blockId),a=da(e,i.blockId),l=s===i.blockId||!a?{start:i.range.start,end:i.range.end}:{start:nr(a.node,i.range.start,"start",r),end:nr(a.node,i.range.end,"end",r)};return{blockId:s,range:l}});return o.some((i,s)=>i.blockId!==t.segments[s]?.blockId||i.range.start!==t.segments[s]?.range.start||i.range.end!==t.segments[s]?.range.end)?Kt(t,o):t}function xd(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?ge(e,t,o):null}function Vv(e){return e.includes("revision_delete")&&!e.includes("revision_insert")?["original"]:e.includes("revision_insert")&&!e.includes("revision_delete")?["final"]:["original","final"]}function Lv(e,t){return e.from!==t.from||e.to!==t.to||e.text!==t.text||e.target.segments.length!==t.target.segments.length?!1:e.target.segments.every((r,o)=>{let n=t.target.segments[o];return!!(n&&r.blockId===n.blockId&&r.range.start===n.range.start&&r.range.end===n.range.end)})}function Fv(e,t,r){let o=new Set;for(let n of Ji(e.resolve(t)))o.add(n);if(t===r)return[...o];for(let n of Yi(e,t,r))o.add(n);return[...o]}import{parseAddressableBlockId as Kv}from"@datalking/begonia-doc-service/structure";import{DELETION_MARK_NAME as Uv,FORMAT_MARK_NAME as ON,INSERTION_MARK_NAME as Zv,resolveRevisionProjectedDocument as _v}from"@datalking/begonia-engine";function BN(e){return tr(e)}function Sa(e,t){return t==="final"?e.visibleFinal:e.visibleOriginal}function Hv(e,t){let r=Cr(e,t);if(!r)return null;let o=r.node;if(!o?.isBlock)return null;let n=[],i=gi(r.document),s=0,a=(l,c,d,u)=>{let m=l.isInline?!wt(l,"final",!c):c,p=l.isInline?!wt(l,"original",!d):d,f=BN(l);if(f>0){n.push({start:s,end:s+f,visibleFinal:m,visibleOriginal:p}),s+=f;return}let g=!0,v=!1,k=!1;l.forEach((R,h,B)=>{let S=[...u,B],b=!R.isBlock||i.isBlockPresent(S,"final"),P=!R.isBlock||i.isBlockPresent(S,"original");R.isBlock&&!g&&(n.push({start:s,end:s+1,visibleFinal:m&&b&&v,visibleOriginal:p&&P&&k}),s+=1),a(R,(l.isInline?m:c)&&b,(l.isInline?p:d)&&P,S),R.isBlock&&(v||=m&&b,k||=p&&P),g=!1})};return a(o,i.isBlockPresent(r.localPath,"final"),i.isBlockPresent(r.localPath,"original"),r.localPath),{runs:n,textLength:s}}function xN(e,t){return e.reduce((r,o)=>r+(Sa(o,t)?o.end-o.start:0),0)}function Cd(e,t,r,o){let n=e.filter(a=>Sa(a,t)),i=xN(e,t);if(!Number.isInteger(r)||r<0||r>i)return null;if(n.length===0)return r===0?0:null;let s=0;for(let a=0;a<n.length;a+=1){let l=n[a],c=l.end-l.start,d=s+c;if(r<d)return l.start+(r-s);if(r===d)return o==="end"||a===n.length-1?l.end:n[a+1].start;s=d}return r===s?n[n.length-1].end:null}function zv(e,t,r,o){if(!Number.isInteger(r)||r<0||r>o)return null;let n=0;for(let i of e){if(r<=i.start)return n;let s=i.end-i.start,a=Sa(i,t)?s:0;if(r<i.end)return n+(Sa(i,t)?r-i.start:0);n+=a}return n}function qv(e){let t=Hv(e.canonicalDocument,e.blockId);if(!t)return null;if(e.range.start===e.range.end){let n=Cd(t.runs,e.projectedMode,e.range.start,"start");return n==null?null:{start:n,end:n}}let r=Cd(t.runs,e.projectedMode,e.range.start,"start"),o=Cd(t.runs,e.projectedMode,e.range.end,"end");return r==null||o==null?null:{start:Math.min(r,o),end:Math.max(r,o)}}function yi(e){let t=Hv(e.canonicalDocument,e.blockId);if(!t)return null;let r=zv(t.runs,e.projectedMode,e.range.start,t.textLength),o=zv(t.runs,e.projectedMode,e.range.end,t.textLength);return r==null||o==null?null:{start:Math.min(r,o),end:Math.max(r,o)}}import{addressableBlockTypeForNodeType as CN,formatAddressableBlockIdWithLogicalId as PN}from"@datalking/begonia-doc-service/structure";import{isAddressableTextHiddenLeaf as RN,isDocumentNodePathIndex as TN,semanticNodeText as kN}from"@datalking/begonia-document-model";function EN(e){return e.isText?e.text?.length??0:!e.isLeaf||RN(e)?0:Math.max(1,kN(e).length)}function MN(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function IN(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=CN(r.type.name);if(o)return{type:o,path:MN(e,t),node:r,pos:e.start(t)-1}}return null}function AN(e,t,r,o){let n=e[e.length-1];if(n?.blockId===t){n.range.start=Math.min(n.range.start,r),n.range.end=Math.max(n.range.end,o);return}e.push({blockId:t,range:{start:r,end:o}})}function NN(e,t){let r=Le(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!TN(i)||i>=o.childCount)return null;n+=1;for(let s=0;s<i;s+=1)n+=o.child(s).nodeSize;o=o.child(i)}return o.isBlock?{node:o,position:n}:null}function bi(e,t,r){let o=t+1;if(r<=o)return 0;let n=0,i=!1,s=(l,c)=>{let d=0,u=!0;for(let m=0;m<l.childCount;m+=1){if(i)return;let p=l.child(m),f=c+d;if(p.isBlock&&!u)if(r>=f+1)n+=1;else{i=!0;return}a(p,f),d+=p.nodeSize,u=!1}},a=(l,c)=>{if(!i){if(l.isText){let d=l.text??"",u=c+d.length;r>=u?n+=d.length:(n+=Math.max(0,r-c),i=!0);return}if(l.isLeaf){let d=EN(l);r>=c+l.nodeSize?n+=d:i=!0;return}s(l,c+1)}};return s(e,o),n}function Pd(e,t,r,o="end"){let n=t+1,i=Math.max(n,t+e.nodeSize-1),s=bi(e,t,i);if(!Number.isInteger(r)||r<0||r>s)return null;let a=n,l=i;for(;a<l;){let d=a+Math.floor((l-a)/2);bi(e,t,d)<r?a=d+1:l=d}if(o!=="start")return a;let c=a;for(;c<i&&bi(e,t,c+1)===r;)c+=1;return c}function Bi(e,t){let r=[],o=!1,n=Math.min(t.from,t.to),i=Math.max(t.from,t.to);return e.nodesBetween(n,i,(s,a)=>{if(o)return!1;if(!s.isTextblock)return!0;let l=e.resolve(a+1),c=IN(l);if(!c)return o=!0,!1;let d=Math.max(n,a+1),u=Math.min(i,a+s.nodeSize-1),m=bi(c.node,c.pos,d),p=Math.max(m,bi(c.node,c.pos,u));return AN(r,PN(c.type,c.path,Hr(c.type,c.node)),m,p),!1}),o?null:r}function DN(e,t){let r=NN(e,t.blockId);if(!r)return null;if(t.range.start===t.range.end){let i=Pd(r.node,r.position,t.range.start,"start");return typeof i=="number"?{from:i,to:i}:null}let o=Pd(r.node,r.position,t.range.start,"start"),n=Pd(r.node,r.position,t.range.end,"end");return typeof o!="number"||typeof n!="number"?null:{from:Math.min(o,n),to:Math.max(o,n)}}function Wv(e,t){let r=[];for(let o of t){let n=DN(e,o);if(!n)return null;r.push(n)}return _r(e,r,{strict:!0})}function Gv(e,t){let r=Kv(e),o=Kv(t);return!r||!o?e===t:r.blockType===o.blockType&&r.path.length===o.path.length&&r.path.every((n,i)=>n===o.path[i])}function Xv(e,t){return!!(t&&e.range.start===e.range.end&&t.range.start<t.range.end&&Gv(e.blockId,t.blockId))}function jN(e,t){return t?.segments.length===e.length&&e.some((r,o)=>Xv(r,t.segments[o]))}function $v(e){return(e??[]).some(t=>t===Zv||t===Uv||t===ON)}function Rd(e){if(!e.selectionInfo.target||!e.projectedDocument)return!1;let t=Q(e.projectedDocument,e.selectionInfo.target,{strict:!0});return!!(t&&t.from===e.selection.from&&t.to===e.selection.to)}function VN(e){if(!e.selectionInfo.target||!e.projectedDocument)return null;if(Rd(e))return e.selectionInfo.target;let t=wo(e.projectedDocument,e.selectionInfo.target),r=t?Q(e.projectedDocument,t,{strict:!0}):null;return r&&r.from===e.selection.from&&r.to===e.selection.to?t:Yv(e)?.target??null}function Yv(e){let t=e.selectionInfo.text??"";if(!e.projectedDocument||!e.selectionInfo.target||t.length===0)return null;let r=kl(e.projectedDocument,e.selectionInfo.target,t);if(!r)return null;let o=Rd(e),n=r.selection.from===e.selection.from&&r.selection.to===e.selection.to;if(!o&&!n)return null;let i=ge(e.projectedDocument,e.projectedDocument.type.schema,r.selection);return i!==t?null:{target:r.target,text:i,from:r.selection.from,to:r.selection.to}}function Td(e,t="preserved"){if(e.projectedMode||!e.canonicalDocument||!e.selectionInfo.target)return null;if(e.selection.empty&&e.selection.from===e.selection.to){let o=wo(e.projectedDocument??e.canonicalDocument,e.selectionInfo.target),n=o?Q(e.projectedDocument??e.canonicalDocument,o,{strict:!0}):null;if(n&&(n.from!==e.selection.from||n.to!==e.selection.to))return de(e.selectionInfo.activeChangeIds).length===0?[]:null}let r=VN(e);return r?vi({selection:e.selection,selectionTarget:r,projectedDocument:e.projectedDocument??e.canonicalDocument,canonicalDocument:e.canonicalDocument,projectedMode:"final",revisions:e.revisions,activationScope:t}):de(e.selectionInfo.activeChangeIds).length===0?[]:null}function Jv(e){if(e.projectedMode||!e.projectedDocument||!e.selectionInfo.target||!e.selection.empty&&de(e.selectionInfo.activeChangeIds).length===0||e.selection.empty&&e.selectionInfo.activeMarks.includes(Uv)&&!e.selectionInfo.activeMarks.includes(Zv))return null;let t=Yv(e);if(t)return{target:t.target,text:t.text};if(!e.canonicalDocument||!e.projectedDocument.eq(e.canonicalDocument))return null;let r=e.selectionInfo.text??"",o=Bi(e.projectedDocument,e.selection);if(!o||o.length===0||r.length>0&&Rd(e)&&o.every(l=>l.range.start===l.range.end)&&!jN(o,e.selectionInfo.target))return null;let n=e.projectedDocument.type.schema,i={final:_v(e.canonicalDocument,n,"final"),original:_v(e.canonicalDocument,n,"original")},s=e.selection.empty?["final"]:Vv(e.selectionInfo.activeMarks),a=null;for(let l of s){let c=i[l],d=o.map((h,B)=>{let S=e.selectionInfo.target?.segments[B],b=S&&Gv(h.blockId,S.blockId)?S.blockId:h.blockId,P=hi(e.projectedDocument,b),A=hi(i.final,b),O=L=>({review:{blockId:P,range:{start:L.start,end:L.end}},expected:{blockId:A,range:{start:L.start,end:L.end}}}),j=Xv(h,S)?Vr({document:e.projectedDocument,blockId:S.blockId,projectedMode:l,range:S.range}):yi({canonicalDocument:e.canonicalDocument,blockId:h.blockId,projectedMode:l,range:h.range});if(!j)return null;if(l==="final")return O(j);let K=Pt(c,h.blockId),F=Pt(i.final,h.blockId);if(typeof K!="string"||typeof F!="string")return null;let se=Sr({selectionRange:j,currentBlockText:K,nextBlockText:F,blockId:h.blockId,canonicalDocument:e.canonicalDocument,projectedMode:l,revisions:e.revisions});if(se)return O(se);let E=xd(c,n,{blockId:h.blockId,range:j});return E==null||xd(e.projectedDocument,n,{blockId:h.blockId,range:j})!==E?null:O(j)});if(d.some(h=>!h))continue;let u=Kt(e.selectionInfo.target,d.map(h=>h.review)),m=Kt(e.selectionInfo.target,d.map(h=>h.expected)),p=Q(e.projectedDocument,u,{strict:!0});if(!p)continue;let f=jr({currentDocument:e.projectedDocument,expectedProjectedDocument:i.final,schema:n});if(!f)continue;let g=Q(f,m,{strict:!0});if(!g)continue;let v=ge(e.projectedDocument,n,p),k=ge(f,n,g);if(v!==k)continue;let R={target:u,text:v,from:p.from,to:p.to};if(!a){a=R;continue}if(!Lv(a,R))return null}return a?{target:a.target,text:a.text}:null}function kd(e,t){let r=e.trackedChangeIds??[];return e.trackedChangeIds!=null&&t.length===r.length&&t.every((o,n)=>o===r[n])?e:{...e,trackedChangeIds:[...t]}}function Qv(e,t){let r=e.activeChangeIds??[];return e.activeChangeIds!=null&&t.length===r.length&&t.every((o,n)=>o===r[n])?e:{...e,activeChangeIds:[...t]}}function LN(e,t,r,o){if(e.projectedMode!=null||e.selection.empty||o)return!1;let n=Math.max(de(e.selection.trackedChangeIds).length,de(e.selectionInfo.activeChangeIds).length),i=Math.max(de(t).length,de(r).length);return n>i&&(e.selectionInfo.text??"").length>0}function Xe(e){let t=Do(e.selection,e.revisions),r=Td({...e,selection:t})??vi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions}),o=Td({...e,selection:t},"visible")??vi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions,activationScope:"visible"}),n=Ur(e.selectionInfo,t,e.revisions),i=kd(t,r),s=Jv({...e,selection:i});if(LN(e,r,o,s)){let k=de(t.trackedChangeIds),R=de(n.activeChangeIds);return{selection:kd(t,k),selectionInfo:Qv(n,R.length>0?R:k),trackedChangeIds:k}}let a=s?Q(e.projectedDocument,s.target,{strict:!0}):null,l=e.selection.empty&&de(e.selectionInfo.activeCommentIds).length===0,c=!!a&&(l||(s?.text??"").length>0),d=c&&a?(()=>{let k=gt(a,xr(i));return kd({...i,from:a.from,to:a.to,anchor:k.anchor,head:k.head,empty:a.from===a.to},r)})():i,u=c&&a?Fv(e.projectedDocument,d.from,d.to):e.selectionInfo.activeMarks,m=s&&e.selection.empty&&s.text.length===0?void 0:s?.text,p=Ur(s?{...e.selectionInfo,...s,text:m,activeMarks:u}:e.selectionInfo,d,e.revisions),f=e.projectedDocument&&p.target&&(s!=null||e.projectedMode==null&&de(o).length>0||e.projectedMode!=null||$v(e.selectionInfo.activeMarks))?wo(e.projectedDocument,p.target):p.target,g=jv({target:f,sourceTarget:p.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),v=g!==p.target?{...p,target:g}:p;return{selection:d,selectionInfo:Qv(v,o),trackedChangeIds:r}}function $e(e){return e.view?.state??e.state??null}function va(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function vr(e,t=null){let r=$e(e);if(!r)return null;let o=Ee(r,{includeText:!0});return t?Xe({selection:eh(r),selectionInfo:o,projectedDocument:r.doc,revisions:t.review.list()}).selectionInfo:o}function ha(e){let t=$e(e.surface);if(!t)return null;let r=Ee(t,{includeText:!0});return Xe({selection:eh(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}).selectionInfo}function th(e,t,r){return ge(e,t,r)}function ya(e,t,r){return r!=null&&th(e.doc,e.schema,t)===r}function FN(e,t){let r=$e(e);return!!(r&&t&&r.selection.from===t.from&&r.selection.to===t.to)}function zN(e,t){return Vn(e,t)}function HN(e,t,r){let o=[],n=new Set;for(let i of r){let s=t.comments.target(i),a=Ze(We(e),s);if(s&&a&&FN(e,a)){let l=zN(i,s);if(n.has(l))continue;n.add(l),o.push({commentId:l,target:s})}}return o.length===0?null:o.length===1?o[0]:null}function rh(e,t,r){if(r.length===0)return null;let o=HN(e,t,r);return o?{kind:"comment",commentId:o.commentId,target:o.target}:null}function Dt(e,t,r){return th(e,t,r)}import{pmPositionToAddressableTextOffset as iD}from"@datalking/begonia-document-model";import{EditorState as sD,NodeSelection as vh}from"prosemirror-state";import{cloneSelectionTextRange as WN}from"@datalking/begonia-document-api/core";function qN(e){return e.hasExpectedSegmentTexts?e.expectedSegmentSelection??e.expectedTextSelection:e.hasExpectedText?e.expectedTextSelection:e.strictSelection}function oh(e){return e==="original"?"original":"final"}function nh(e){if(!e.hasExpandedTarget)return e.strictSelection;let t=oh(e.sourceMode),r=oh(e.projectedMode);if(t===r&&!e.hasExpectedSegmentTexts&&!e.hasExpectedText&&!e.expectedSegmentSelection&&!e.expectedTextSelection){if(e.strictSelection&&e.strictSelection.from!==e.strictSelection.to)return e.strictSelection;if(e.anchorSelection)return e.anchorSelection;if(e.strictSelection&&e.strictSelection.from===e.strictSelection.to)return e.strictSelection}return t!==r?e.strictSelection:qN(e)}function ih(e){return e?{kind:"text",segments:e.segments.map(t=>({blockId:t.blockId,range:{start:t.range.start,end:t.range.start,...t.range.startAffinity?{startAffinity:t.range.startAffinity}:{},...t.range.endAffinity?{endAffinity:t.range.endAffinity}:{}}})),...e.story?{story:structuredClone(e.story)}:{}}:null}function KN(e){let{target:t}=e,r=t.segments.map(n=>({blockId:er({blockId:n.blockId,projectedDocument:e.sourceDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode}),range:WN(n.range)}));return r.some((n,i)=>n.blockId!==t.segments[i]?.blockId)?{kind:"text",segments:r,...t.story?{story:structuredClone(t.story)}:{}}:t}function sh(e,t){return e?Me(e,{schema:e.type.schema},t):null}function _N(e,t){return e.start===t.start&&e.end===t.end}function Ed(e){return e.start===e.end}function UN(e){if(!e.canonicalDocument)return!1;let t=e.target.segments.filter(r=>!Ed(r.range));return t.length===0?!1:t.every(r=>Bn({blockId:r.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode,revisions:e.revisions}).some(o=>_N(r.range,o.currentRange)&&!Ed(o.currentRange)&&Ed(o.nextRange)))}function ZN(e){let t=e.projectionSnapshot.canonicalDocument;if(!t)return null;let r=sh(t,e.sourceMode),n=(r?wo(r,e.target):null)??Et(e.target);if(!n)return null;let i=KN({target:n,sourceDocument:r,canonicalDocument:t,sourceMode:e.sourceMode}),s=ih(i);if(e.projectionSnapshot.projectedMode===e.sourceMode)return s&&UN({canonicalDocument:t,sourceMode:e.sourceMode,target:i,revisions:e.revisions})?{target:s,anchorTarget:s}:{target:i,anchorTarget:s};let a=e.projectionSnapshot.projectedMode??"final";if(e.projectionSnapshot.projectedMode==null&&e.sourceMode==="final")return{target:i,anchorTarget:s};let l=sh(t,a);if(!l)return{target:i,anchorTarget:s};let c=n.segments.map((m,p)=>{let f=i.segments[p];if(!f)return null;let g=r?Pt(r,m.blockId):null,v=Pt(l,f.blockId),k=Sr({selectionRange:m.range,currentBlockText:g??"",nextBlockText:v??"",blockId:f.blockId,canonicalDocument:t,projectedMode:e.sourceMode,revisions:e.revisions})??{start:f.range.start,end:f.range.end};return{blockId:f.blockId,range:k}});if(c.some(m=>!m))return null;let d={kind:"text",segments:c,...e.target.story?{story:structuredClone(e.target.story)}:{}},u=ih(d);return{target:d,anchorTarget:u}}function ah(e){return e.sourceMode==null?(()=>{let t=Et(e.target);return t?{target:t,anchorTarget:null}:null})():ZN({...e,sourceMode:e.sourceMode})}function ut(e){let t=ah(e);if(!t)return null;let{target:r,anchorTarget:o}=t,n=Array.isArray(e.expectedSegmentTexts)&&e.expectedSegmentTexts.length>0,i=typeof e.expectedText=="string"&&e.expectedText.length>0,s=r.segments.some(p=>p.range.start!==p.range.end),a={strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"},l=Q(e.state.doc,r,a),c=o?Q(e.state.doc,o,a):null,d=n?et(e.state.doc,r,e.expectedSegmentTexts??null,a):null,u=i?Ne(e.state.doc,r,e.expectedText??null,a):null,m=nh({sourceMode:e.sourceMode,projectedMode:e.projectionSnapshot.projectedMode,hasExpandedTarget:s,hasExpectedText:i,hasExpectedSegmentTexts:n,strictSelection:l,anchorSelection:c,expectedTextSelection:u,expectedSegmentSelection:d});return m?{target:r,selection:{from:Math.min(m.from,m.to),to:Math.max(m.from,m.to)}}:null}function Md(e,t,r){return ge(e,t,r)}function lh(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?Md(e,t,o):null}function GN(e){let t=Me(e.canonicalDocument,{schema:e.schema},e.projectedMode);return jr({currentDocument:e.referenceDocuments[0]??t,expectedProjectedDocument:t,schema:e.schema})}function Id(e){let t=GN({canonicalDocument:e.canonicalDocument,schema:e.schema,projectedMode:e.nextProjectionMode,referenceDocuments:[e.nextDocument,e.currentDocument]});if(!t)return null;let r=e.selectionTarget.segments.map(l=>{let c=er({blockId:l.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),d=Vr({document:e.currentDocument,blockId:l.blockId,projectedMode:e.currentProjectionMode,range:l.range})??l.range,u=Pt(e.currentDocument,c),m=Pt(t,c);if(typeof u!="string"||typeof m!="string")return null;let p=Sr({selectionRange:d,currentBlockText:u,nextBlockText:m,blockId:c,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode,revisions:e.canonicalReviewApi.review.list()});if(p){let v=ua({document:t,blockId:c,projectedMode:e.nextProjectionMode,range:p});return v?{blockId:c,range:v}:null}let f=lh(e.currentDocument,e.schema,l);return f==null||lh(t,e.schema,{blockId:c,range:l.range})!==f?null:{blockId:c,range:l.range}});if(r.some(l=>!l))return null;let o={kind:"text",segments:r,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},n=Q(e.nextDocument,o,{strict:!0});if(!n)return null;let i=Q(t,o,{strict:!0});if(!i)return null;let s=Md(e.nextDocument,e.schema,n),a=Md(t,e.schema,i);return s===a?n:null}function ch(e){let t=Vr({document:e.currentDocument,blockId:e.currentBlockId,projectedMode:e.currentProjectionMode,range:e.range});return t?ua({document:e.canonicalDocument,blockId:e.canonicalBlockId,projectedMode:e.currentProjectionMode,range:t}):null}function dh(e){let t=s=>({blockId:er({blockId:s.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),range:structuredClone(s.range)}),[r,...o]=e.selectionTarget.segments,n={kind:"text",segments:[t(r),...o.map(t)],...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},i=lt(e.currentDocument,e.selectionTarget);return et(e.nextDocument,n,i,{strict:!0})??Ne(e.nextDocument,n,e.expectedText,{strict:!0})}import{buildExtractOverlapParentAliasMap as QN}from"@datalking/begonia-document-api/review";function XN(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function $N(e,t){let r=e??[],o=t??[],n=Math.min(r.length,o.length);for(let i=0;i<n;i+=1){let s=r[i]-o[i];if(s!==0)return s}return r.length-o.length}function Ad(e){return!!(e&&e.nodeType&&e.objectId)}function YN(e,t){return Ad(e.target)&&e.target?.nodeType===t}function uh(e,t){return typeof e.entryId=="string"&&typeof t.entryId=="string"&&e.entryId===t.entryId?!0:!!(Ad(e.target)&&Ad(t.target)&&e.target?.objectId===t.target?.objectId&&XN(e.target?.path,t.target?.path))}function JN(e){return[...e].sort((t,r)=>$N(t.target?.path,r.target?.path)||(t.from??0)-(r.from??0)||(t.to??0)-(r.to??0)||String(t.entryId??"").localeCompare(String(r.entryId??"")))}function mh(e){let t=e.currentMember.kind==="insert"?new Set(["delete"]):e.currentMember.kind==="delete"?new Set(["insert"]):new Set([e.currentMember.kind]),r=e.nextProjectionMode==="original"?new Set(["delete","format"]):new Set(["insert","format"]),o=JN(e.revisions.flatMap(l=>l.members??[]).filter(l=>YN(l,e.nodeType))),n=o.find(l=>r.has(l.kind)&&uh(l,e.currentMember));if(n)return n;let s=o.filter(l=>l.kind===e.currentMember.kind).findIndex(l=>uh(l,e.currentMember));return s<0?null:o.filter(l=>t.has(l.kind))[s]??null}function eD(e){return!!(e&&e.nodeType&&e.objectId)}function fh(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function tD(e,t){let r=fh(e);return r?t.get(r)?.id??r:null}function ph(e,t){let r=fh(e.operationId);if(!r)return null;let o=tD(e.overlapParentId,t);return o==null?r:`${r}\0${o}`}function rD(e){for(let t of e.revisions)for(let r of t.members??[])if(eD(r.target)&&r.target?.nodeType===e.currentSelectionTarget.nodeType&&r.target?.objectId===e.currentSelectionTarget.stableIdentity)return{revision:t,member:r};return null}function wh(e){let t=e.currentSelectionTarget,r=rD(e);if(!r)return null;let o=QN(e.revisions),n=ph(r.revision,o),i=n==null?[r.revision]:e.revisions.filter(a=>ph(a,o)===n),s=mh({currentMember:r.member,revisions:i,nodeType:t.nodeType,nextProjectionMode:e.nextProjectionMode});return s?.target?.objectId?{kind:"node",nodeType:t.nodeType,stableIdentity:s.target.objectId,path:s.target.path}:null}import{collectRevisionSpans as gh,selectionOverlapsRevisionRange as oD}from"@datalking/begonia-engine";function xi(e,t,r,o){return Dt(e,t,{from:r,to:o}).length}function nD(e){let t=xi(e.doc,e.schema,e.from,e.to);if(!Number.isInteger(e.acceptedOffset)||e.acceptedOffset<0||e.acceptedOffset>t)return null;let r=e.from,o=e.to;for(;r<o;){let n=r+Math.floor((o-r)/2);xi(e.doc,e.schema,e.from,n)<e.acceptedOffset?r=n+1:o=n}return xi(e.doc,e.schema,e.from,r)===e.acceptedOffset?r:null}function Sh(e){if(e.selection.from!==e.selection.to)return null;let t=gh(e.currentDocument,e.schema).filter(l=>oD(e.selection.from,e.selection.to,l)),r=t.length===1?t[0]:null;if(!r||xi(e.currentDocument,e.schema,r.from,r.to)===0)return null;let n=gh(e.nextDocument,e.schema).filter(l=>l.id===r.id&&l.kind===r.kind),i=n.length===1?n[0]:null;if(!i)return null;let s=xi(e.currentDocument,e.schema,r.from,e.selection.from),a=nD({doc:e.nextDocument,schema:e.schema,from:i.from,to:i.to,acceptedOffset:s});return typeof a=="number"?{from:a,to:a}:null}function aD(e){if(!W(e.state.selection)||!e.state.selection.node.isInline||e.state.selection.node.childCount!==0||!Ae(e.state))return e.selectionTarget;let t=Bi(e.state.doc,e.state.selection);return t&&t.length>0?{kind:"text",segments:t,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}}:e.selectionTarget}function lD(e){let t=e.selectionTarget.segments.map(d=>{let u=er({blockId:d.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),m=qv({canonicalDocument:e.canonicalDocument,blockId:u,projectedMode:e.currentProjectionMode,range:d.range});return m?{blockId:u,range:m}:null});if(t.some(d=>!d))return null;let r=t.map(d=>{let u=d,m=yi({canonicalDocument:e.canonicalDocument,blockId:u.blockId,projectedMode:e.nextProjectionMode,range:u.range});return m?{blockId:u.blockId,range:m}:null});if(r.some(d=>!d))return null;let o={kind:"text",segments:r,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},n=Q(e.nextDocument,o,{strict:!0});if(!n)return null;let i=Me(e.canonicalDocument,{schema:e.schema},e.nextProjectionMode),s=jr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:e.schema});if(!s)return null;let a=Q(s,o,{strict:!0});if(!a)return null;let l=Dt(e.nextDocument,e.schema,n),c=Dt(s,e.schema,a);return l===c?n:null}function cD(e){if(e.selection.from!==e.selection.to||e.segments.length!==1)return null;let t=e.segments[0];if(t.range.start!==t.range.end)return null;let r=Le(e.nextDocument,t.blockId),o=r?Ve(e.nextDocument,r):null;if(!o?.node.isBlock)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=e.selection.from;return s<n||s>i?null:iD(o.node,o.position,s)===t.range.start?{from:s,to:s}:null}function Nd(e){let t=e.currentProjectionMode??null,r=We(e.surface),o=t?ha({surface:e.surface,canonicalReviewApi:e.canonicalReviewApi,canonicalDocument:e.canonicalDocument,projectedMode:t})??e.selectionInfo??vr(e.surface,e.canonicalReviewApi):vr(e.surface,e.canonicalReviewApi);if(!o||!o.target)return null;let n=$e(e.surface);if(!n)return null;let i=t?aD({state:n,selectionTarget:o.target}):o.target,s=!!e.nextProjectionMode&&W(n.selection)&&n.selection.node.isInline&&n.selection.node.childCount===0,a=!!t&&s,l=s?Ae(n):null;if(l&&e.nextProjectionMode){let u=wh({currentSelectionTarget:l,revisions:e.canonicalReviewApi.review.list(),nextProjectionMode:e.nextProjectionMode});if(u)return u}let c=(()=>{if(a)return lD({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,nextProjectionMode:e.nextProjectionMode});if(!t&&!e.nextProjectionMode&&!n.selection.empty){let g=lt(r,i),v=et(e.nextDocument,i,g??null,{strict:!0})??Ne(e.nextDocument,i,o.text??null,{strict:!0});if(v)return v}if(t&&e.nextProjectionMode)return Id({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:e.nextProjectionMode});let u=t?i.segments.map(g=>{let v=er({blockId:g.blockId,projectedDocument:r,canonicalDocument:e.canonicalDocument,projectedMode:t}),k=ch({currentDocument:r,canonicalDocument:e.canonicalDocument,currentBlockId:g.blockId,canonicalBlockId:v,currentProjectionMode:t,range:g.range});return k?{blockId:v,range:k}:null}):Bi(n.doc,n.selection);if(!u)return null;let m=u.filter(g=>g!=null);if(m.length!==u.length)return null;if(!e.nextProjectionMode){if(t){let g=cD({nextDocument:e.nextDocument,selection:n.selection,segments:m});if(g)return g;if(!n.selection.empty){let v=dh({currentDocument:r,nextDocument:e.nextDocument,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,expectedText:o.text});if(v)return v;let k=Id({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:"final"});if(k)return k}}if(!t){let g=Sh({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selection:n.selection});if(g)return g}return Wv(e.nextDocument,m)}let p=e.nextProjectionMode,f=m.map(g=>{let v=yi({canonicalDocument:e.canonicalDocument,blockId:g.blockId,projectedMode:p,range:g.range});return v?{blockId:g.blockId,range:v}:null});return f.some(g=>!g)?null:Q(e.nextDocument,{kind:"text",segments:f,...i.story?{story:structuredClone(i.story)}:{}},{strict:!0})})();if(!c)return null;let d=W(n.selection)?dD(e.nextDocument,c):null;return d||{kind:"tracked",selection:c,text:Dt(e.nextDocument,n.schema,c)}}function hh(e){if(!e.preservedRangeSelection.target)return null;let t=$e(e.surface);if(!Dd(e)||!t)return null;let r=e.preservedRangeSelection.target,o=Ne(e.nextDocument,r,e.preservedRangeSelection.text,{strict:!0})??et(e.nextDocument,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!o)return null;let n=e.nextProjectionMode??e.preservedRangeSelection.projectedMode;if(!n)return null;let i=Me(e.canonicalDocument,{schema:t.schema},n),s=jr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:t.schema});if(!s)return null;let a=Ne(s,r,e.preservedRangeSelection.text,{strict:!0})??et(s,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!a)return null;let l=Dt(e.nextDocument,t.schema,o),c=Dt(s,t.schema,a);return o.from===a.from&&o.to===a.to&&l===c?{kind:"tracked",selection:o,text:l,...e.preservedRangeSelection.direction?{direction:e.preservedRangeSelection.direction}:{}}:null}function Dd(e){if(!e.preservedRangeSelection.target)return!1;let t=$e(e.surface);if(!t||!t.selection.empty||e.preservedRangeSelection.projectedMode!==(e.nextProjectionMode??null))return!1;let r=ut({state:t,target:e.preservedRangeSelection.target,projectionSnapshot:{canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode??null},sourceMode:e.preservedRangeSelection.projectedMode,revisions:e.canonicalReviewApi.review.list(),expectedText:e.preservedRangeSelection.text,expectedSegmentTexts:e.preservedRangeSelection.segmentTexts});return!!(r&&r.selection.from===r.selection.to&&r.selection.from===t.selection.from&&r.selection.to===t.selection.to)}function dD(e,t){let r=e.nodeAt(t.from);if(!r||!r.isInline||r.childCount!==0||!vh.isSelectable(r))return null;let o;try{o=vh.create(e,t.from)}catch{return null}if(o.from!==Math.min(t.from,t.to)||o.to!==Math.max(t.from,t.to))return null;let n=sD.create({doc:e,selection:o});return Ae(n)}function yh(e,t){let r=Le(e,t),o=r?Ve(e,r):null;return o?.node.isBlock?Mo(o.node,le(e)).text:null}function mD(e){let t=$e(e.surface);if(!t||!e.selectionInfo.target)return null;let r=We(e.surface),n={kind:"text",segments:e.selectionInfo.target.segments.map(s=>{let a=yh(r,s.blockId),l=yh(e.nextDocument,s.blockId),c=a!=null&&l!=null?Sr({selectionRange:s.range,currentBlockText:a,nextBlockText:l,revisions:e.canonicalReviewApi.review.list()}):null;return{blockId:s.blockId,range:c??uD(s.range)}})},i=Q(e.nextDocument,n,{strict:!0});return i?{kind:"text",target:n,text:Dt(e.nextDocument,t.schema,i),segmentTexts:lt(e.nextDocument,n)}:null}function pD(e,t,r,o,n,i,s){let a=vr(e),l=vr(e,o),c=!!(o&&n&&(ga(e,i?n:t)||i)),d=c?ga(e,i?n:t):null,u=c&&d?ha({surface:e,canonicalReviewApi:o,canonicalDocument:n,projectedMode:d})??l:l;if(a?.target&&d==="original"&&!i&&u?.activeMarks.length===0&&a.target.segments.every(g=>g.range.start===g.range.end)){let g=$e(e),v=g?.selection??null;if(v)return{kind:"tracked",selection:{from:v.from,to:v.to},text:Dt(t,g?.schema??t.type.schema,v)}}let p=Ae($e(e)),f=u?.target&&r?rh(e,r,u.activeCommentIds):null;if(f&&!p)return f;if(c&&u?.target){if(s){let v=Dd({surface:e,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s}),k=hh({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s});if(k)return k;if(v)return null}if(d&&!i&&u.activeChangeIds.length===0&&!p){let v=mD({surface:e,nextDocument:t,canonicalReviewApi:o,canonicalDocument:n,currentProjectionMode:d,selectionInfo:u});if(v)return v}let g=Nd({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(g)return g}if(o&&u?.target&&u.activeChangeIds.length>0){let g=Nd({surface:e,nextDocument:t,canonicalDocument:n??t,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(g)return g}return f||p||(u?.target&&u.activeChangeIds.length===0?{kind:"text",target:u.target,text:u.text??null,segmentTexts:lt(We(e),u.target)}:null)}function go(e){let t=pD(e.surface,e.nextDocument,e.documentApi,e.canonicalReviewApi,e.canonicalDocument,e.nextProjectionMode,e.preservedRangeSelection);if(!t||t.kind==="node")return t;let r=$e(e.surface)?.selection;return r&&Op(r)==="backward"?{...t,direction:"backward"}:t}function hD(e){return!!(e&&e.activeCommentIds.length===0&&e.activeMarks.includes(fD)&&!e.activeMarks.includes(gD)&&(e.text??"").length===0)}function Ci(e){if(!e.target||!va(e.surface))return;let t=e.surface.view.state.doc,r=e.target.kind==="node"?Gi(t,e.target):null,o=e.target.kind==="node"?null:e.target.kind==="comment"?di({comments:e.documentApi?.comments,commentId:e.target.commentId,fallbackTarget:e.target.target,resolve:l=>Ze(t,l)})?.resolution??null:e.target.kind==="tracked"?e.target.selection:et(t,e.target.target,e.target.segmentTexts,{strict:!0})??Ne(t,e.target.target,e.target.text,{strict:!0}),n=()=>{let l=e.surface.view?.state;if(!l||typeof e.surface.view?.dispatch!="function")return;let c=l.selection,d=Z(l,c.from,c.from);!d||W(d)||e.surface.view.dispatch(l.tr.setSelection(d))};if(!r&&!o){e.target.kind==="node"&&n();return}if(e.target.kind!=="comment"&&e.target.kind!=="node"&&o&&!ya(e.surface.view.state,o,e.target.text))return;let i=e.surface.view.state.selection,s=o?gt(o,e.target.kind==="node"?void 0:e.target.direction):null;if(r?W(i)&&i.from===r.position:o&&i.from===o.from&&i.to===o.to&&i.anchor===s?.anchor&&i.head===s.head)return;let a=r?SD.create(e.surface.view.state.doc,r.position):Z(e.surface.view.state,s.anchor,s.head);a&&e.surface.view.dispatch(e.surface.view.state.tr.setSelection(a))}function ba(e){if(!va(e.surface))return!1;let t=$e(e.surface);if(!t||t.selection.empty)return!1;let r=vr(e.surface),o=r&&e.canonicalReviewApi?Xe({selection:wD(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}):null;if(hD(r))return!1;let n=o?.selectionInfo??r;if(!n?.target||n.activeCommentIds.length>0||n.activeChangeIds.length===0||typeof n.text!="string"||n.text.length===0)return!1;let i=o?{from:o.selection.from,to:o.selection.to}:Q(e.surface.view.state.doc,n.target,{strict:!0});if(!i||i.from>=i.to||t.selection.from===i.from&&t.selection.to===i.to||!ya(e.surface.view.state,i,n.text))return!1;let s=Z(e.surface.view.state,i.from,i.to);return!s||s.empty?!1:(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(s)),!0)}function Cn(e){let{surface:t,nextDocument:r,documentApi:o,nextDocumentApi:n}=e,i=go(e);t.replaceDocument(r,{origin:"system",intent:"replace-projected-document-preserving-selection",effects:[vD("review")]}),Ci({surface:t,target:i,documentApi:n??o})}import{createDocumentRuntimeKernel as iO}from"@datalking/begonia-document-api/v1";import{summarizeReviewTimeline as sO}from"@datalking/begonia-document-api/review";import{createEditorSelectionSnapshot as aO}from"@datalking/begonia-editor-contracts";function bh(e,t){return{surface:e,documentApi:t,context:{source:"browser-ooxml-nodeview"},runMutation(o,n){if(nt(e)){if(e.trackingEnabled){o();return}n()}}}}function Pn(e,t){e.runMutation(()=>{e.documentApi.ooxml.removeByIdTracked(t,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.removeById(t)})}function Od(e,t){switch(t.action){case"replace-chart-model":e.runMutation(()=>{e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.replaceModelById(t.objectId,t.model)});return;case"apply-chart-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-metadata":e.runMutation(()=>{e.documentApi.ooxml.charts.setMetadataByIdTracked(t.objectId,r,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setMetadataById(t.objectId,r)});return;case"set-text-body":e.runMutation(()=>{e.documentApi.ooxml.charts.setTextBodyByIdTracked(t.objectId,r.textBody,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setTextBodyById(t.objectId,r.textBody)});return;case"set-plot-area":e.runMutation(()=>{e.documentApi.ooxml.charts.setPlotAreaByIdTracked(t.objectId,r.plotArea,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setPlotAreaById(t.objectId,r.plotArea)});return;case"set-legend":e.runMutation(()=>{e.documentApi.ooxml.charts.setLegendByIdTracked(t.objectId,r.legend,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setLegendById(t.objectId,r.legend)});return;case"set-series":e.runMutation(()=>{e.documentApi.ooxml.charts.setSeriesByIdTracked(t.objectId,r.target,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setSeriesById(t.objectId,r.target,r.series)});return;case"set-series-list":e.runMutation(()=>{e.documentApi.ooxml.charts.setSeriesListByIdTracked(t.objectId,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setSeriesListById(t.objectId,r.series)});return;case"upsert-series":e.runMutation(()=>{e.documentApi.ooxml.charts.upsertSeriesByIdTracked(t.objectId,r.series,e.surface.participant,e.context,r.seriesId)},()=>{e.documentApi.ooxml.charts.upsertSeriesById(t.objectId,r.series,r.seriesId)});return;case"append-series":e.runMutation(()=>{e.documentApi.ooxml.charts.appendSeriesByIdTracked(t.objectId,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.appendSeriesById(t.objectId,r.series)});return;case"remove-series":e.runMutation(()=>{e.documentApi.ooxml.charts.removeSeriesByIdTracked(t.objectId,r.target,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.removeSeriesById(t.objectId,r.target)});return;case"set-axes":e.runMutation(()=>{e.documentApi.ooxml.charts.setAxesByIdTracked(t.objectId,r.axes,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setAxesById(t.objectId,r.axes)});return;case"upsert-axis":e.runMutation(()=>{e.documentApi.ooxml.charts.upsertAxisByIdTracked(t.objectId,r.axis,e.surface.participant,e.context,r.axisId)},()=>{e.documentApi.ooxml.charts.upsertAxisById(t.objectId,r.axis,r.axisId)});return;case"remove-axis":e.runMutation(()=>{e.documentApi.ooxml.charts.removeAxisByIdTracked(t.objectId,r.axisId,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.removeAxisById(t.objectId,r.axisId)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function jd(e,t){switch(t.action){case"replace-math-model":e.runMutation(()=>{e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.replaceModelById(t.objectId,t.model)});return;case"set-math-plain-text":e.runMutation(()=>{e.documentApi.ooxml.math.setPlainTextByIdTracked(t.objectId,t.text,e.surface.participant,e.context,t.displayMode)},()=>{e.documentApi.ooxml.math.setPlainTextById(t.objectId,t.text,t.displayMode)});return;case"apply-math-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-display-mode":e.runMutation(()=>{e.documentApi.ooxml.math.setDisplayModeByIdTracked(t.objectId,r.displayMode,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.setDisplayModeById(t.objectId,r.displayMode)});return;case"set-plain-text":e.runMutation(()=>{e.documentApi.ooxml.math.setPlainTextByIdTracked(t.objectId,r.text,e.surface.participant,e.context,r.displayMode)},()=>{e.documentApi.ooxml.math.setPlainTextById(t.objectId,r.text,r.displayMode)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function Vd(e,t){switch(t.action){case"replace-shape-model":e.runMutation(()=>{e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.replaceModelById(t.objectId,t.model)});return;case"apply-shape-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-metadata":e.runMutation(()=>{e.documentApi.ooxml.shapes.setMetadataByIdTracked(t.objectId,r,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setMetadataById(t.objectId,r)});return;case"set-watermark":e.runMutation(()=>{e.documentApi.ooxml.shapes.setWatermarkByIdTracked(t.objectId,r.isWatermark,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setWatermarkById(t.objectId,r.isWatermark)});return;case"set-text-body":e.runMutation(()=>{e.documentApi.ooxml.shapes.setTextBodyByIdTracked(t.objectId,r.paragraphs,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setTextBodyById(t.objectId,r.paragraphs)});return;case"set-geometry":e.runMutation(()=>{e.documentApi.ooxml.shapes.setGeometryByIdTracked(t.objectId,r.geometry,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setGeometryById(t.objectId,r.geometry)});return;case"set-transform":e.runMutation(()=>{e.documentApi.ooxml.shapes.setTransformByIdTracked(t.objectId,r.transform,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setTransformById(t.objectId,r.transform)});return;case"set-fill":e.runMutation(()=>{e.documentApi.ooxml.shapes.setFillByIdTracked(t.objectId,r.fill,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setFillById(t.objectId,r.fill)});return;case"set-stroke":e.runMutation(()=>{e.documentApi.ooxml.shapes.setStrokeByIdTracked(t.objectId,r.stroke,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setStrokeById(t.objectId,r.stroke)});return;case"set-effects":e.runMutation(()=>{e.documentApi.ooxml.shapes.setEffectsByIdTracked(t.objectId,r.effects,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setEffectsById(t.objectId,r.effects)});return;case"set-anchor":e.runMutation(()=>{e.documentApi.ooxml.shapes.setAnchorByIdTracked(t.objectId,r.anchor,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setAnchorById(t.objectId,r.anchor)});return;case"set-children":e.runMutation(()=>{e.documentApi.ooxml.shapes.setChildrenByIdTracked(t.objectId,r.children,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setChildrenById(t.objectId,r.children)});return;case"set-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.setChildByIdTracked(t.objectId,r.target,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setChildById(t.objectId,r.target,r.child)});return;case"append-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.appendChildByIdTracked(t.objectId,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.appendChildById(t.objectId,r.child)});return;case"append-child-to-parent":e.runMutation(()=>{e.documentApi.ooxml.shapes.appendChildToParentByIdTracked(t.objectId,r.parentTarget,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.appendChildToParentById(t.objectId,r.parentTarget,r.child)});return;case"move-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.moveChildByIdTracked(t.objectId,r.target,e.surface.participant,e.context,{parentId:r.parentTarget,beforeId:r.beforeTarget})},()=>{e.documentApi.ooxml.shapes.moveChildById(t.objectId,r.target,{parentId:r.parentTarget,beforeId:r.beforeTarget})});return;case"remove-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.removeChildByIdTracked(t.objectId,r.target,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.removeChildById(t.objectId,r.target)});return;case"set-connector":e.runMutation(()=>{e.documentApi.ooxml.shapes.setConnectorByIdTracked(t.objectId,r.connector,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setConnectorById(t.objectId,r.connector)});return;case"set-picture":e.runMutation(()=>{e.documentApi.ooxml.shapes.setPictureByIdTracked(t.objectId,r.picture,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setPictureById(t.objectId,r.picture)});return;case"set-word-art":e.runMutation(()=>{e.documentApi.ooxml.shapes.setWordArtByIdTracked(t.objectId,r.wordArt,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setWordArtById(t.objectId,r.wordArt)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function Bh(e,t){let r=bh(e,t),o=e.view?.dom??null;if(!o)return()=>{};let n=i=>{let s=i instanceof CustomEvent?i.detail:null;if(nm(s))switch(i.preventDefault(),i.stopPropagation(),s.family){case"math":if(s.action==="remove-advanced-ooxml"){jd(r,{family:"math",action:s.action,objectId:s.objectId});return}jd(r,s);return;case"chart":if(s.action==="remove-advanced-ooxml"){Od(r,{family:"chart",action:s.action,objectId:s.objectId});return}Od(r,s);return;case"shape":if(s.action==="remove-advanced-ooxml"){Vd(r,{family:"shape",action:s.action,objectId:s.objectId});return}Vd(r,s);return}};return o.addEventListener(Hi,n),()=>{o.removeEventListener(Hi,n)}}import{describeSurfaceSelection as kh}from"@datalking/begonia-engine";import{describeSurfaceSelection as yD}from"@datalking/begonia-engine";function bD(e,t,r){if(!r.target){if(Wt(t,r))return!0;let i=e.preservedRangeSelection;return!!(r.nodeSelectionTarget&&i?.nodeSelectionTarget&&sr(r.nodeSelectionTarget,i.nodeSelectionTarget)&&Wt(t,i))||!!(r.nodeSelectionTarget&&mp(e.state.doc,r.nodeSelectionTarget,t))}if(Wt(t,r))return!0;let o=e.preservedRangeSelection;if(!o||!o.target||e.projectionSnapshot.projectedMode!==null||o.projectedMode==null||r.projectedMode!==null)return!1;if(Wt(t,o))return!0;let n=ut({state:e.state,target:o.target,projectionSnapshot:e.projectionSnapshot,sourceMode:o.projectedMode,revisions:e.revisions,expectedText:o.text,expectedSegmentTexts:o.segmentTexts});return!!(n&&Wt(t,n.selection))}function BD(e,t,r,o,n=null){if(t.empty)return null;let i=Dn(n??Ae(e));return!r.target&&!i?null:{from:Math.min(t.from,t.to),to:Math.max(t.from,t.to),...xr(t)==="backward"?{direction:"backward"}:{},target:r.target?Et(r.target):null,text:r.text??null,segmentTexts:r.target?lt(e.doc,r.target):null,projectedMode:o,nodeSelectionTarget:i}}function xD(e,t){return On(e.target,t.target)&&(e.text??null)===t.text}function CD(e,t){return!e.selection.empty&&e.selection.from===t.from&&e.selection.to===t.to&&(e.selectionInfo.text??null)===t.text}function PD(e){if(!e.preserved.nodeSelectionTarget)return null;let t=Zr(e.state,e.preserved.nodeSelectionTarget);return t?{from:Math.min(t.selection.from,t.selection.to),to:Math.max(t.selection.from,t.selection.to),target:null,text:Ee(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode}).text??null,segmentTexts:null,projectedMode:e.projectedMode,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}:null}function Ch(e,t){let r=Ee(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode});return Xe({selection:yD(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}function Ld(e){if(!e.preserved.target)return null;let t=e.context.projectionSnapshot.projectedMode,r=ut({state:e.context.state,target:e.preserved.target,projectionSnapshot:e.context.projectionSnapshot,sourceMode:e.sourceMode,revisions:e.context.revisions,expectedText:e.preserved.text,expectedSegmentTexts:e.preserved.segmentTexts});if(!r)return null;let o=Il(e.context.state,{...e.preserved,from:r.selection.from,to:r.selection.to,target:r.target});if(!o)return null;if(e.sourceMode!==t){let i=Ml(e.context.state,{...r.selection,...e.preserved.direction?{direction:e.preserved.direction}:{}})??o,s=Ee(i,{includeText:!0},{reviewReplacementMode:e.context.reviewReplacementMode});return{from:r.selection.from,to:r.selection.to,...e.preserved.direction?{direction:e.preserved.direction}:{},target:Et(r.target),text:s.text??e.preserved.text??null,segmentTexts:lt(i.doc,r.target),projectedMode:t,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}}let n=Ch(e.context,o);return n.selection.empty||!n.selectionInfo.target?null:{from:Math.min(n.selection.from,n.selection.to),to:Math.max(n.selection.from,n.selection.to),...e.preserved.direction?{direction:e.preserved.direction}:{},target:Et(n.selectionInfo.target),text:n.selectionInfo.text??null,segmentTexts:lt(o.doc,n.selectionInfo.target),projectedMode:t,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}}function Ph(e){let t="previous"in e?e.previous:e.preservedRangeSelection;if(!t)return[];if(t.nodeSelectionTarget){let r=PD({state:e.state,preserved:t,projectedMode:e.projectionSnapshot.projectedMode,reviewReplacementMode:e.reviewReplacementMode});if(r&&t.target==null)return[r];let o=[];return r&&o.push(r),[...o,...xh(e,t)]}return xh(e,t)}function xh(e,t){let r=[],o=e.projectionSnapshot.projectedMode;if(!t.projectedMode&&!o)r.push(t);else if(t.projectedMode&&!o){let n=Ld({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else if(t.projectedMode)if(t.projectedMode===o)r.push(t);else{let n=Ld({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else{let n=Ld({context:e,preserved:t,sourceMode:null});n&&r.push(n)}return r}function Fd(e){let t=BD(e.state,e.selection,e.selectionInfo,e.projectionSnapshot.projectedMode,e.selectionNodeSelectionTarget??null);if(t)return e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&e.selectionInfo.empty&&!e.selection.empty&&t.text==null&&os(t.target,e.previous.target)||e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&On(t.target,e.previous.target)&&t.text===e.previous.text?e.previous:t;let r=Ph(e),o=r.find(i=>Wt(e.selection,i));if(o)return o;let n=e.previous?.projectedMode!==e.projectionSnapshot.projectedMode&&e.selection.empty&&e.selectionInfo.activeChangeIds.length>0&&e.previous?.target?ut({state:e.state,target:e.previous.target,projectionSnapshot:e.projectionSnapshot,sourceMode:e.previous.projectedMode,revisions:e.revisions,expectedText:e.previous.text,expectedSegmentTexts:e.previous.segmentTexts}):null;return n&&n.selection.from===n.selection.to&&e.selection.from===n.selection.from&&e.selection.to===n.selection.to||e.surfaceSelectionReliable===!1&&e.selection.empty&&e.previous?.projectedMode!=null&&r.length>0||e.previous&&Wt(e.selection,e.previous)?e.previous:null}function Rh(e,t){let r=e.surfaceSelectionReliable===!1&&t.empty,o=t.empty&&e.preservedRangeSelection?.target!=null&&e.preservedRangeSelection.projectedMode!==e.projectionSnapshot.projectedMode;for(let n of Ph(e)){if(!r&&!bD(e,t,n))continue;let i=Il(e.state,n);if(!i)continue;let s=Ch(e,i);if(n.target==null&&sr(Ae(i),n.nodeSelectionTarget)||xD(s.selectionInfo,n)||n.target!=null&&n.projectedMode===e.projectionSnapshot.projectedMode&&CD(s,n)&&(r||e.projectionSnapshot.projectedMode==null)||o&&n.target)return i}if(t.empty){let n=Vp(e.state);if(n)return n}return e.state}function Th(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Th(t);return e}function zd(e,t,r,o,n,i=null,s=null,a=null){let l=e.target??null;if(!t&&!l&&!r)return null;let{target:c,...d}=e,u={...d,selection:o,selectionTarget:l,segmentTexts:l&&a?lt(a,l):null,nodeSelectionTarget:r??null,selectionKind:n,projectedMode:i,storyOriginPath:s,documentIdentity:Np(a),documentHash:Oo(a),target:t??null};return Th(structuredClone(u))}import{readSyntheticSideStoryDocOriginPath as RD}from"@datalking/begonia-doc-service/v1";function Eh(e,t,r){let o=Ee(t,r,{reviewReplacementMode:e.reviewReplacementMode}),n=kh(t),i=Xe({selection:{...n,editable:n.editable&&e.surfaceEditable},selectionInfo:o,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions}),s=t!==e.state?ce([...n.trackedChangeIds,...i.selection.trackedChangeIds],e.revisions):i.selection.trackedChangeIds,a=s.length===i.selection.trackedChangeIds.length&&s.every((m,p)=>m===i.selection.trackedChangeIds[p])?i.selection:{...i.selection,trackedChangeIds:[...s]},l=t!==e.state&&e.preservedRangeSelection?.target?ut({state:t,target:e.preservedRangeSelection.target,projectionSnapshot:e.projectionSnapshot,sourceMode:e.preservedRangeSelection.projectedMode,revisions:e.revisions,expectedText:e.preservedRangeSelection.text,expectedSegmentTexts:e.preservedRangeSelection.segmentTexts}):null,c=l&&l.selection.from===a.from&&l.selection.to===a.to?{...i.selectionInfo,target:l.target}:i.selectionInfo,d=c.target??Ht(t),u=zd(c,d,Ae(t),a,W(t.selection)?"node":"text",e.projectionSnapshot.projectedMode,RD(t.doc),t.doc);return u||null}function TD(e,t){let r=e.preservedRangeSelection;if(!r||!t.empty||e.projectionSnapshot.projectedMode!==null||r.projectedMode==null||!r.target||!Wt(t,r))return null;let o=ut({state:e.state,target:r.target,projectionSnapshot:e.projectionSnapshot,sourceMode:r.projectedMode,revisions:e.revisions,expectedText:r.text,expectedSegmentTexts:r.segmentTexts});if(!o)return null;let n=gt(o.selection,r.direction),i=Z(e.state,n.anchor,n.head);if(!i)return null;try{return e.state.apply(e.state.tr.setSelection(i))}catch{return null}}function Pi(e){let t=kh(e.state),r=Rh(e,t);return r===e.state?TD(e,t)??r:r}function Mh(e){return Eh(e,e.state,e.selectionInput??{})}function So(e){return Eh(e,Pi(e),e.selectionInput??{})}import{isDocumentNodePathIndex as kD}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as ED}from"@datalking/begonia-engine";function Ah(e){return e==="ooxml_math"||e==="ooxml_chart"||e==="ooxml_shape"||e==="inline_ooxml_drawing"}function Nh(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.$from.index(o));return r}function MD(e){if(!W(e)||!Ah(e.node.type.name))return null;let t=Nh(e,e.$from.depth);return t.push(e.$from.index(e.$from.depth)),t}function ID(e,t){let r=e;for(let o of t){if(!kD(o)||o>=r.childCount)return null;r=r.child(o)}return r}function Ih(e,t){let r=ID(e.doc,t);return!!(r&&Ah(r.type.name)&&r.marks.some(o=>o.type.name===ED))}function Hd(e){let{selection:t}=e.state;for(let r=t.$from.depth;r>0;r-=1)if(t.$from.node(r).isTextblock)return Nh(t,r);return null}function Rn(e,t){let r=t.blocks.topLevel(),o=e.state.selection.from,n=r.find(i=>o>=i.from&&o<=i.from+i.nodeSize);return n?n.index+1:r.length}function G(){return{source:"browser-ooxml"}}function Ba(e,t){let r=MD(e.selection);if(!r)return null;let o=t.ooxml.get(r);if(!o)return null;let n=Ih(e,o.path),i=t.ooxml.getById(o.objectId);if(!i)return n?null:o;let s=Ih(e,i.path);return n?s?null:i:s?o:i}function Ri(e,t){if(t)return Ba(e.state,t);let r=e,o=it(r);return o?Ba(o.state,r.documentApi):null}function Y(e,t,r){let o=Ri(e,t);return o?.family===r?o:null}function J(e){return{changed:!1,reason:`No advanced OOXML ${e} node is selected.`}}function qd(e,t,r){let o=Ri(e,t);return o?e.trackingEnabled?t.ooxml.updateTracked(o.path,r,e.participant,G()):t.ooxml.update(o.path,r):{changed:!1,reason:"No advanced OOXML node is selected."}}function Wd(e,t){let r=Ri(e,t);return r?e.trackingEnabled?t.ooxml.removeTracked(r.path,e.participant,G()):t.ooxml.remove(r.path):{changed:!1,reason:"No advanced OOXML node is selected."}}function Kd(e){return[...new Set((e??[]).map(t=>ct(t)).filter(t=>t.length>0))]}function AD(e,t){let r=Kd(e),o=Kd(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function ND(e){let t=Math.min(e.from,e.to),r=Math.max(e.from,e.to);return{start:t,selectionEnd:t===r?r+1:r}}function DD(e,t){if(!e||!t)return!1;let r=ND(e),o=Math.min(t.from,t.to),n=Math.max(t.from,t.to);return o===n?o<r.selectionEnd&&o>=r.start:o<r.selectionEnd&&n>r.start}function Ti(e){let t=Ue(e.comments),r=At(e.activeCommentIds,t);if(r.length>0||!e.selection||!e.projectedDocument)return r;let o=Kd((e.comments??[]).map(n=>{let i=e.readTarget(n.id),s=Ze(e.projectedDocument,i);return DD(e.selection,s)?n.id:null}).filter(n=>typeof n=="string"));return o.length===1?o:r}function ki(e,t){return AD(e.activeCommentIds,t)?e:{...e,activeCommentIds:[...t]}}function Dh(e){return{left:e.left,top:e.top}}function OD(e){return e.type==="external"?{...e}:{...e}}function xa(e){return e?{...e,position:Dh(e.position),resolution:OD(e.resolution)}:null}function jD(e){return{...e}}function VD(e){return{...e,items:e.items.map(jD)}}function LD(e){return{...e,trackedChangeIds:[...e.trackedChangeIds],pointReviewTrackedChangeIds:[...e.pointReviewTrackedChangeIds],pointReviewCommentIds:[...e.pointReviewCommentIds],activeCommentIds:[...e.activeCommentIds],activeMarks:[...e.activeMarks],position:Dh(e.position)}}function Ca(e){return e?{context:LD(e.context),sections:e.sections.map(VD)}:null}import{listCapabilities as XD}from"@datalking/begonia-document-api/core";import{listCapabilities as FD}from"@datalking/begonia-document-api/core";var Oh=Object.freeze([...FD()].filter(e=>e.mode==="write"&&e.memberPath).map(e=>e.memberPath)),zD=new Set(Oh),HD=Object.freeze(["controls.create","controls.text.setValueTracked","fields.refreshGroup","layout.replaceFooterTextTracked","layout.replaceFooters","layout.replaceHeaderTextTracked","layout.replaceHeaders","mergeFields.sources.remove","mergeFields.sources.set","mergeFields.update","mergeFields.updateAll","formulas.update","formulas.updateAll","sequences.update","sequences.updateAll","notes.remove","notes.replaceTextTracked","notes.upsert","styles.replaceAll"]),qD=new Set(["byFamily","get","getById","list"]),WD=new Set(["createNode","get","getById","getModel","getModelById","list"]),KD=new Set(["createModelFromText","createNode","get","getById","getModel","getModelById","list"]);function _D(e){return e[e.length-1]??null}function UD(e){return e!=null&&(e==="createNode"||e.startsWith("find")||e.startsWith("get")||e.startsWith("list")||e.startsWith("read"))}function ZD(e){let t=e.split(".");if(t[0]!=="ooxml")return!1;let r=t[1]??null;if(r==null)return!1;if(t.length===2)return!qD.has(r);let o=t[2]??null,n=_D(t);return o==="commands"?!1:r==="chart"?n!=null&&!WD.has(n):r==="math"?n!=null&&!KD.has(n):r==="shape"?!UD(n):!1}function jh(e,t="",r=new WeakSet,o=[]){if(e==null||typeof e!="object"&&typeof e!="function")return o;let n=e;if(r.has(n))return o;r.add(n);for(let i of Object.keys(e)){let s=e[i],a=t?`${t}.${i}`:i;typeof s=="function"&&o.push(a),s!=null&&(typeof s=="object"||typeof s=="function")&&jh(s,a,r,o)}return o}function GD(e){let t=new Set;for(let r of e){let o=r.split("."),n="";for(let i=0;i<o.length-1;i+=1)n=n?`${n}.${o[i]}`:o[i],t.add(n)}return t}function Vh(e){return HD.includes(e)||ZD(e)}function Lh(e){return zD.has(e)||Vh(e)}function Fh(e){let t=new Set(Oh);for(let r of jh(e))Vh(r)&&t.add(r);return{deniedMemberPaths:t,descendantMemberPaths:GD(t)}}var qh=new Map([...XD()].filter(e=>e.memberPath).map(e=>[e.memberPath,e.mode])),$D=(()=>{let e=new Set;for(let t of qh.keys()){let r=t.split("."),o="";for(let n=0;n<r.length-1;n+=1)o=o?`${o}.${r[n]}`:r[n],e.add(o)}return e})();function zh(e,t){if(!t)return{owner:null,value:e};let r=t.split("."),o=null,n=e;for(let i of r)o=n,n=n?.[i];return{owner:o,value:n}}function YD(e){return $D.has(e)}function Hh(e){return Lh(e)?"write":qh.get(e)??null}function JD(e){return e==="final"||e==="original"||e==="tracked"?e:null}function QD(e){return!e||typeof e!="object"?null:JD(e.revisionProjection)}function eO(e){for(let t of e){let r=QD(t);if(r)return r}return null}function Pa(e){return{presentationReadApi:e.presentationReadRuntime.documentApi,canonicalReviewApi:e.canonicalReviewRuntime.documentApi,writableRuntimeApi:e.writableRuntime.documentApi}}function Wh(e){let t=new Map,r=(i,s=[])=>{if(Hh(i)==="write")return e.readWritableApi();let a=eO(s);return a?e.readProjectedApiForMode(a)??e.readPresentationApi():e.readPresentationApi()},o=(i,s=[])=>{let a=zh(r(i,s),i);return a.value!==void 0||Hh(i)==="write"?a:zh(e.readWritableApi(),i)},n=i=>{if(t.has(i))return t.get(i);let s=o(i),{value:a}=s;if(a==null||typeof a!="object"&&typeof a!="function")return a;let l=YD(i);if(typeof a=="function"&&!l){let d=(...u)=>{let m=o(i,u);return Reflect.apply(m.value,m.owner,u)};return t.set(i,d),d}let c=new Proxy(a,{get(d,u){if(typeof u!="string"){let p=o(i);return Reflect.get(p.value,u,p.owner)}let m=i?`${i}.${u}`:u;return n(m)},apply(d,u,m){let p=o(i,m);return Reflect.apply(p.value,p.owner,m)}});return t.set(i,c),c};return n}function Ei(e){return e.kind!=="revision"&&e.kind!=="revision-decision"}function Kh(e){let t=e?.trim()??"";if(!t)return 0;let r=Date.parse(t);return Number.isFinite(r)?r:0}function tO(e,t,r){let o=Kh(e.sortAt),n=Kh(t.sortAt);return o!==n?r==="asc"?o-n:n-o:e.id.localeCompare(t.id)}function _d(e,t,r="desc"){let o=new Map(t.filter(Ei).map(s=>[s.id,s])),n=e.map(s=>Ei(s)?o.get(s.id)??s:s),i=new Set(n.map(s=>s.id));for(let s of t)!Ei(s)||i.has(s.id)||(n.push(s),i.add(s.id));return n.sort((s,a)=>tO(s,a,r))}function rO(e,t){if(e.projectedMode==null)return null;let r={actor:t.actor,enforceVisibilityPolicy:t.enforceVisibilityPolicy},o=e.presentationReadRuntime.documentApi.comments,n=new Map;return(i,s)=>{let a=`${i}\0${s}`;return n.has(a)||n.set(a,o.entryTarget(i,s,r)??o.target(i,r)??o.targetSnapshot(i,r)??null),n.get(a)??null}}function _h(e,t,r){let o=rO(t,r);return o?e.map(n=>{if(!Ei(n))return n;let i=o(n.commentId,n.entryId);return i?{...n,target:i}:n}):e}function oO(e){let t=e.reviewOptions??{},{presentationReadRuntime:r,canonicalReviewRuntime:o}=e.projectionSnapshot,n=r.documentApi,i=o.documentApi,s=i.review.timeline(t);return n===i?s:_d(s,n.review.timeline(t),t.sort??"desc")}function nO(e){let t=e.reviewOptions??{},{presentationReadRuntime:r,canonicalReviewRuntime:o}=e.projectionSnapshot,n=r.documentApi,i=o.documentApi,s=i.review.timelineByObject(e.objectId,t);return n===i?s:_d(s,n.review.timelineByObject(e.objectId,t),t.sort??"desc")}function Ra(e){let t=e.reviewOptions??{};return _h(oO(e),e.projectionSnapshot,t)}function Uh(e){let t=e.reviewOptions??{};return _h(nO(e),e.projectionSnapshot,t)}function je(e){return{allowed:!1,reason:e,matchedPermissionIds:[],authorOwned:!1}}function Mi(e,t){return{...e,toggleInternal:je("Comments are read-only in the current document mode."),reply:je("Comments are read-only in the current document mode."),resolve:je(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:je(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:je("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({...r,edit:je("Comments are read-only in the current document mode."),remove:je("Comments are read-only in the current document mode.")}))}}function Ii(e){let t=je("Tracked changes are read-only in the current document mode.");return{...e,accept:t,reject:t}}function Zh(e){return e&&{...e,edit:je("Comments are read-only in the current document mode."),remove:je("Comments are read-only in the current document mode.")}}function Ud(e,t){return{threadId:e.id,view:{allowed:!0,reason:null,matchedPermissionIds:[],authorOwned:!1},reply:je("Comments are read-only in the current document mode."),resolve:je(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:je(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:je("Comments are read-only in the current document mode."),toggleInternal:je("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({entryId:r.id,edit:je("Comments are read-only in the current document mode."),remove:je("Comments are read-only in the current document mode.")}))}}function Zd(e){return{revisionId:e,accept:je("Tracked changes are read-only in the current document mode."),reject:je("Tracked changes are read-only in the current document mode.")}}function Gh(e,t,r){return e.filter(o=>o.kind==="revision"||o.kind==="revision-decision"?!0:r.enabled&&r.visible)}function Ai(e,t,r){return e.map(o=>o.kind==="revision"?t?o:{...o,permissions:o.permissions?Ii(o.permissions):Zd(o.revisionId)}:o.kind==="revision-decision"?o:r.readOnly?{...o,threadPermissions:o.threadPermissions?Mi(o.threadPermissions,r):Ud(o.comment,r)}:o)}function Xh(e){return{source:e.documentSource,replace(t,r){e.replaceDocument(t,r)}}}function lO(e){let t=Xh(e);return{readDocument(){return e.document},replaceDocument(r,o){t.replace(bt(e.document,r),o)},documentSource:t.source}}function cO(e,t,r,o){return Object.fromEntries(t.map(n=>{let i=r?e.comments.permissions(n.id,r):o.readOnly?Ud(n,o):null;return[n.id,i&&o.readOnly?Mi(i,o):i]}))}function dO(e,t,r,o){let n=r?e.review.permissions(r):o?[]:t.map(i=>Zd(i.id));return Object.fromEntries(n.map(i=>[i.revisionId,o?i:Ii(i)]))}function uO(e,t){return e.length===0?null:e.some(r=>r.hitId===t)?t:e[0]?.hitId??null}function Ta(e,t,r={}){let o=lO(e),n=iO(o,{templates:r.templates??void 0,review:{replacementMode:r.replacementMode??"paired"},selection:yl(e,{reviewReplacementMode:r.replacementMode??"paired"})}),i=n.api,s=e.subscribe(()=>t()),a=Bh(e,i),l=!1,c=()=>{l||(l=!0,a(),s(),n.dispose())};return{surface:e,documentRuntimeKernel:n,documentService:n.service,documentApi:i,replacementMode:r.replacementMode??"paired",templatesAdapter:r.templates??null,unsubscribeSurface:s,uninstallAdvancedOoxmlNodeViewBridge:a,release:c}}function mO(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function $h(e){let{runtime:t,projectionSnapshot:r,preservedRangeSelection:o,actor:n,linkPopover:i,contextMenu:s,search:a,collaboration:l,documentMode:c,zoomPercent:d,zoom:u,viewportSession:m,display:p,activeCommentId:f,activeCommentIds:g,activeRevisionId:v,activeRevisionIds:k}=e,{surface:R,documentApi:h}=t,B=nt(R),{presentationReadApi:S,canonicalReviewApi:b}=Pa(r),P=p.comments.enabled?S.comments.list({includeResolved:p.comments.showResolved,actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,visibility:p.comments.visibility,sort:"desc"}):[],A=p.comments.visible?P:[],O=b.review.list(),j={actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,includeResolvedComments:p.comments.showResolved,commentVisibility:p.comments.visibility},K=Ai(Gh(Ra({projectionSnapshot:r,reviewOptions:j}),p.trackChanges,p.comments),B,p.comments),F=a.query?S.search.query(a.query,a.options):[],se=S.proofing.list(),E=mO(R),N=R.describeSelection(),L=Dr(R,{includeText:!0},t.replacementMode),ne=Xe({selection:N,selectionInfo:L,projectedDocument:We(R),canonicalDocument:r.canonicalDocument,projectedMode:r.projectedMode,revisions:O}),y=So({state:R.state,surfaceEditable:B,surfaceSelectionReliable:E,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:O,projectionSnapshot:r,preservedRangeSelection:o}),x=Pi({state:R.state,surfaceEditable:B,surfaceSelectionReliable:E,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:O,projectionSnapshot:r,preservedRangeSelection:o}),M=yt({liveSelection:ne.selection,liveSelectionInfo:ne.selectionInfo,revisions:O,effectiveSelection:y}),I=!E&&y?y.selection:ne.selection,U=ar(I.trackedChangeIds,M)?I:{...I,trackedChangeIds:[...M]},xe=!E&&y?Rr(y,M):null,me=xe??ne.selectionInfo,Ke=Ti({activeCommentIds:me.activeCommentIds,selection:E?N:U,projectedDocument:We(R),comments:P,readTarget:S.comments.target}),Tt=ki(me,Ke),Ye=ko(R.state,Tt,W(R.state.selection)?"node":"text"),Ce=xe??(ne.selection.empty&&ar(Ye.activeChangeIds,M)?Ye:ne.selection.empty?{...Ye,activeChangeIds:[...M]}:Ye),mt=ww({revisions:O,selectionInfo:Ce,explicitActiveRevisionId:v,explicitActiveRevisionIds:k}),hr=sn({comments:A,selectionInfo:Ce,explicitActiveCommentId:f,explicitActiveCommentIds:g}),jt=aO(U,t.documentRuntimeKernel.readSnapshot().revision,R.documentStory),Vt={toolbar:Ds({selection:jt,editable:B,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:R.canUndo(),canRedo:R.canRedo()}),comments:A,commentPermissions:cO(S,A,n,p.comments),activeCommentId:hr.activeCommentId,activeCommentIds:hr.activeCommentIds,revisions:O,activeRevisionId:mt.activeRevisionId,activeRevisionIds:mt.activeRevisionIds,reviewPermissions:dO(b,O,n,B),reviewTimeline:K,reviewTimelineSummary:sO(K),search:{query:a.query,hits:F,activeHitId:uO(F,a.activeHitId)},proofing:{diagnostics:se},advancedOoxml:{selected:Ba(x,h)},selectionInfo:Ce,selection:jt,editable:B,documentMode:c,flowMode:m.flowMode,layoutMode:m.layoutMode,preferredPaginatedLayoutMode:m.preferredPaginatedLayoutMode,zoomPercent:d,zoom:u,viewport:m.viewport,viewportRequestKey:m.viewportRequestKey,previewNavigationRequest:m.previewNavigationRequest,trackChanges:p.trackChanges,commentsDisplay:p.comments,collaboration:l,linkPopover:xa(i),contextMenu:Ca(s),selectionNodeSelectionTarget:E?null:y?.nodeSelectionTarget??null},Lt=Zn({getState:()=>Vt,readEffectiveSelection:()=>y,surface:R}),yr=Ds({selection:jt,editable:B,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:Lt.commands.undo?.disabled===!1,canRedo:Lt.commands.redo?.disabled===!1,commandStates:Lt.commands});return{...Vt,toolbar:yr}}function pO(e){return e.view.dom.parentElement??null}function fO(e){return e.view.dom.ownerDocument?.createElement?.("div")}function Yh(e){e.view.updateRoot?.call(e.view)}function Jh(e,t){if(t){if(typeof t.replaceChildren=="function"){t.replaceChildren(e.view.dom),Yh(e);return}typeof t.appendChild=="function"&&(t.appendChild(e.view.dom),Yh(e))}}function Qh(e){return!!e}function ey(e){let{canonicalDocument:t,emit:r,projectionMode:o,readPreservedRangeSelection:n,replacementMode:i="paired",sourceRuntime:s,surfaceFactory:a}=e,l=s.surface,c=pO(l),d=bt(t,Me(t,l,o)),u=a({currentSurface:l,collaborative:void 0,documentStory:l.documentStory,editable:!1,element:fO(l),initialContent:d,schema:l.schema,participant:l.participant,trackingEnabled:!1}),m=Ta(u,r,{replacementMode:i});return Jh(u,c),{runtime:m,restore(){Jh(l,c)},sync(p,f){let g=Me(p,l,f);return Ar(m.surface.document,g)?!1:(Cn({surface:m.surface,nextDocument:g,documentApi:m.documentApi,canonicalReviewApi:s.documentApi,canonicalDocument:p,nextProjectionMode:f,preservedRangeSelection:n?.()??null}),!0)}}}function Gd(e,t,r,o={}){let n=Hd(e);return n?t.ooxml.math.appendInline(n,r,o):{changed:!1,reason:"Advanced OOXML math insertion requires an active text block selection."}}function Xd(e,t,r,o={},n={}){let i=Hd(e);return i?t.ooxml.math.appendInlineTracked(i,r,e.participant,o,n):{changed:!1,reason:"Tracked math insertion requires an active text block selection."}}function $d(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.math.replaceModelById(o.objectId,r):J("math")}function Yd(e,t,r,o){let n=Y(e,t,"math");return n?e.trackingEnabled?t.ooxml.math.setPlainTextByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.math.setPlainTextById(n.objectId,r,o):J("math")}function Jd(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.setDisplayModeByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.math.setDisplayModeById(o.objectId,r):J("math")}function Qd(e,t,r,o={}){return t.ooxml.charts.insertBlock(Rn(e,t),r,o)}function eu(e,t,r,o={},n={}){return t.ooxml.charts.insertBlockTracked(Rn(e,t),r,e.participant,o,n)}function tu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.replaceModelById(o.objectId,r):J("chart")}function ru(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setMetadataByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setMetadataById(o.objectId,r):J("chart")}function ou(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTitleByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setTitleById(o.objectId,r):J("chart")}function nu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTextBodyByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setTextBodyById(o.objectId,r):J("chart")}function iu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.appendSeriesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.appendSeriesById(o.objectId,r):J("chart")}function su(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setSeriesListByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setSeriesListById(o.objectId,r):J("chart")}function au(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.setSeriesByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.charts.setSeriesById(n.objectId,r,o):J("chart")}function lu(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertSeriesByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.charts.upsertSeriesById(n.objectId,r,o):J("chart")}function cu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeSeriesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.removeSeriesById(o.objectId,r):J("chart")}function du(e,t,r){return ka(e,t,r)}function uu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setAxesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setAxesById(o.objectId,r):J("chart")}function ka(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertAxisByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.charts.upsertAxisById(n.objectId,r,o):J("chart")}function mu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeAxisByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.removeAxisById(o.objectId,r):J("chart")}function pu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setLegendByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setLegendById(o.objectId,r):J("chart")}function fu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setPlotAreaByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setPlotAreaById(o.objectId,r):J("chart")}function wu(e,t,r,o={}){return t.ooxml.shapes.insertBlock(Rn(e,t),r,o)}function gu(e,t,r,o={},n={}){return t.ooxml.shapes.insertBlockTracked(Rn(e,t),r,e.participant,o,n)}function Su(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.replaceModelById(o.objectId,r):J("shape")}function vu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setMetadataByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setMetadataById(o.objectId,r):J("shape")}function hu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWatermarkByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setWatermarkById(o.objectId,r):J("shape")}function yu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTextBodyByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setTextBodyById(o.objectId,r):J("shape")}function bu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setGeometryByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setGeometryById(o.objectId,r):J("shape")}function Bu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTransformByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setTransformById(o.objectId,r):J("shape")}function xu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setFillByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setFillById(o.objectId,r):J("shape")}function Cu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setStrokeByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setStrokeById(o.objectId,r):J("shape")}function Pu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setAnchorByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setAnchorById(o.objectId,r):J("shape")}function Ru(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setConnectorByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setConnectorById(o.objectId,r):J("shape")}function Tu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setPictureByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setPictureById(o.objectId,r):J("shape")}function ku(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWordArtByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setWordArtById(o.objectId,r):J("shape")}function Eu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setChildrenByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setChildrenById(o.objectId,r):J("shape")}function Mu(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.setChildByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.shapes.setChildById(n.objectId,r,o):J("shape")}function Iu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.appendChildByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.appendChildById(o.objectId,r):J("shape")}function Au(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.appendChildToParentByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.shapes.appendChildToParentById(n.objectId,r,o):J("shape")}function Nu(e,t,r,o={}){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.moveChildByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.shapes.moveChildById(n.objectId,r,o):J("shape")}function Du(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.removeChildByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.removeChildById(o.objectId,r):J("shape")}import{isDocumentNodePathIndex as wO}from"@datalking/begonia-document-model";import{NodeSelection as gO}from"prosemirror-state";function Ou(e,t){return W(e.selection)&&e.selection.node.type.name===`ooxml_${t.family}`&&e.selection.node.attrs.objectId===t.objectId}function SO(e,t){let r=e,o=-1;for(let n of t){if(!wO(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function vO(e,t){let r=SO(e,t.path),o=r==null?null:e.nodeAt(r);if(r!=null&&o?.type.name===`ooxml_${t.family}`&&o.attrs.objectId===t.objectId)return r;let n=null;return e.descendants((i,s)=>n==null&&i.type.name===`ooxml_${t.family}`&&i.attrs.objectId===t.objectId?(n=s,!1):!0),n}function ty(e,t){if(!t||Ou(e,t))return e;let r=vO(e.doc,t);if(r==null)return null;let o=at(e,gO.create(e.doc,r));if(!o)return null;if(qt(e.selection,o))return e;try{return e.apply(e.tr.setSelection(o))}catch{return null}}function hO(e,t){return new Proxy(e,{get(r,o,n){return o==="state"?t:Reflect.get(r,o,n)}})}function yO(e,t){if(!t||Ou(e.surface.state,t))return e;let r=e.surface.view?.state,o=r?ty(r,t):null;if(r&&o&&(o!==r&&e.surface.view.dispatch(r.tr.setSelection(o.selection)),Ou(e.surface.state,t)))return e;let n=ty(e.surface.state,t);return!n||n===e.surface.state?e:{...e,surface:hO(e.surface,n)}}function bO(e){return!!(e&&typeof e=="object"&&"changed"in e&&e.changed===!0)}function ry(e){let t=o=>{let n=e.getRuntime(),i=Jt(n.surface);return i?q(i):e.runAndEmit(()=>o(n))},r=o=>t(n=>o(yO(n,e.readState().advancedOoxml.selected)));return{appendMathToCurrentTextblock(o,n={}){return t(i=>Gd(i.surface,i.documentApi,o,n))},appendMathToCurrentTextblockTracked(o,n={},i={}){return t(s=>Xd(s.surface,s.documentApi,o,n,i))},insertChartAfterCurrentBlock(o,n={}){return t(i=>Qd(i.surface,i.documentApi,o,n))},insertChartAfterCurrentBlockTracked(o,n={},i={}){return t(s=>eu(s.surface,s.documentApi,o,n,i))},insertShapeAfterCurrentBlock(o,n={}){return t(i=>wu(i.surface,i.documentApi,o,n))},insertShapeAfterCurrentBlockTracked(o,n={},i={}){return t(s=>gu(s.surface,s.documentApi,o,n,i))},updateSelectedAdvancedOoxml(o){return r(n=>qd(n.surface,n.documentApi,o))},removeSelectedAdvancedOoxml(){return r(o=>{let n=Wd(o.surface,o.documentApi);return bO(n)&&e.clearPreservedRangeSelection(),n})},replaceSelectedMathModel(o){return r(n=>$d(n.surface,n.documentApi,o))},setSelectedMathPlainText(o,n){return r(i=>Yd(i.surface,i.documentApi,o,n))},setSelectedMathDisplayMode(o){return r(n=>Jd(n.surface,n.documentApi,o))},replaceSelectedChartModel(o){return r(n=>tu(n.surface,n.documentApi,o))},setSelectedChartMetadata(o){return r(n=>ru(n.surface,n.documentApi,o))},setSelectedChartTitle(o){return r(n=>ou(n.surface,n.documentApi,o))},setSelectedChartTextBody(o){return r(n=>nu(n.surface,n.documentApi,o))},appendSelectedChartSeries(o){return r(n=>iu(n.surface,n.documentApi,o))},setSelectedChartSeriesList(o){return r(n=>su(n.surface,n.documentApi,o))},setSelectedChartSeries(o,n){return r(i=>au(i.surface,i.documentApi,o,n))},upsertSelectedChartSeries(o,n){return r(i=>lu(i.surface,i.documentApi,o,n))},removeSelectedChartSeries(o){return r(n=>cu(n.surface,n.documentApi,o))},appendSelectedChartAxis(o){return r(n=>du(n.surface,n.documentApi,o))},setSelectedChartAxes(o){return r(n=>uu(n.surface,n.documentApi,o))},upsertSelectedChartAxis(o,n){return r(i=>ka(i.surface,i.documentApi,o,n))},removeSelectedChartAxis(o){return r(n=>mu(n.surface,n.documentApi,o))},setSelectedChartLegend(o){return r(n=>pu(n.surface,n.documentApi,o))},setSelectedChartPlotArea(o){return r(n=>fu(n.surface,n.documentApi,o))},replaceSelectedShapeModel(o){return r(n=>Su(n.surface,n.documentApi,o))},setSelectedShapeMetadata(o){return r(n=>vu(n.surface,n.documentApi,o))},setSelectedShapeWatermark(o){return r(n=>hu(n.surface,n.documentApi,o))},setSelectedShapeTextBody(o){return r(n=>yu(n.surface,n.documentApi,o))},setSelectedShapeGeometry(o){return r(n=>bu(n.surface,n.documentApi,o))},setSelectedShapeTransform(o){return r(n=>Bu(n.surface,n.documentApi,o))},setSelectedShapeFill(o){return r(n=>xu(n.surface,n.documentApi,o))},setSelectedShapeStroke(o){return r(n=>Cu(n.surface,n.documentApi,o))},setSelectedShapeAnchor(o){return r(n=>Pu(n.surface,n.documentApi,o))},setSelectedShapeConnector(o){return r(n=>Ru(n.surface,n.documentApi,o))},setSelectedShapePicture(o){return r(n=>Tu(n.surface,n.documentApi,o))},setSelectedShapeWordArt(o){return r(n=>ku(n.surface,n.documentApi,o))},setSelectedShapeChildren(o){return r(n=>Eu(n.surface,n.documentApi,o))},setSelectedShapeChild(o,n){return r(i=>Mu(i.surface,i.documentApi,o,n))},appendSelectedShapeChild(o){return r(n=>Iu(n.surface,n.documentApi,o))},appendSelectedShapeChildToParent(o,n){return r(i=>Au(i.surface,i.documentApi,o,n))},moveSelectedShapeChild(o,n={}){return r(i=>Nu(i.surface,i.documentApi,o,n))},removeSelectedShapeChild(o){return r(n=>Du(n.surface,n.documentApi,o))}}}function Ea(e){let t=dn({surface:e.surface,clientX:e.clientX,clientY:e.clientY});if(!t)return null;let r=e.captureSelectionFromState(t.state);return r?{state:t.state,capture:r}:null}function oy(e,t){let r=t.readEffectiveSelection();return{selectionCapture:r,resolvedSelectionCapture:r,stale:!1}}function Ni(e,t,r){if(!r)return{selectionCapture:null,resolvedSelectionCapture:null,stale:!1};let o=t.readSelectionCapture(r);return o?{selectionCapture:r,resolvedSelectionCapture:o,stale:!1}:{selectionCapture:r,resolvedSelectionCapture:null,stale:!0}}function BO(e,t){return e.selectionCapture?Ni(e,t,e.selectionCapture):e.pointSelectionCapture?Ni(e,t,e.pointSelectionCapture):oy(e,t)}function xO(e,t){let r=e.actionSelectionCapture??e.selectionCapture??null;if(!r)return e.pointSelectionCapture?{...Ni(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...oy(e,t),restoreSelection:!1};let o=Ni(e,t,r);return e.pointSelectionCapture===r?{...o,restoreSelection:!1}:o.resolvedSelectionCapture&&!o.resolvedSelectionCapture.selection.empty?{...o,restoreSelection:!0}:e.pointSelectionCapture&&e.pointSelectionCapture!==r?{...Ni(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...o,restoreSelection:!0}}function ju(e,t){let r=t??e.controller;if(!r)throw new Error("Browser context-menu selection policy requires a selection controller.");return{effectiveSelection:BO(e,r),actionSelection:xO(e,r)}}function CO(e=""){return typeof window>"u"?null:window.prompt("Enter link URL",e)}function PO(e,t){let r=new Map(e.map(o=>[o.id,{...o,items:[...o.items]}]));for(let o of t){let n=r.get(o.id);if(n){n.items.push(...o.items);continue}r.set(o.id,{...o,items:[...o.items]})}return[...r.values()]}function RO(e,t){let r=Math.min(e.selection.from,e.selection.to),o=Math.max(e.selection.from,e.selection.to);return(t.segments?.length?t.segments:[t]).every(i=>r<=i.from&&o>=i.to)}function ny(e,t,r){let o=new Set(e.trackedChangeIds),n=t.getState().revisions.filter(i=>o.has(i.id));return n.length===0||n.some(i=>i.relatedKinds.length!==1)?!1:n.some(i=>!RO(r,i))}function TO(e,t,r){if(!t||!e.hasSelection)return r;let o=Math.min(t.selection.from,t.selection.to),n=Math.max(t.selection.from,t.selection.to),i=Math.min(e.selectionStart,e.selectionEnd),s=Math.max(e.selectionStart,e.selectionEnd),a=r?Math.min(r.selection.from,r.selection.to):o,l=r?Math.max(r.selection.from,r.selection.to):n;return(i!==a||s!==l)&&i===o&&s===n?{selection:{...t.selection,from:i,to:s,empty:!1,trackedChangeIds:[...e.trackedChangeIds]}}:r}function iy(e,t,r){let{hasSelection:o,trackedChangeIds:n}=e,i=it(t);if(n.length===0)return;let s=t.readEffectiveSelection({includeText:!0}),a=e.actionSelectionCapture??e.selectionCapture,l=t.getState().revisions,c=Rl(s,a,l),d=!c&&a?t.readSelectionCapture(a,{includeText:!0}):null,u=TO(e,a,d),m=d?Rl(s,d,l):c;if(n.length===1&&!o){let p=n[0];if(!p)return;if(r==="accept"){t.acceptRevision(p);return}t.rejectRevision(p);return}if(i&&(r==="accept"&&typeof i.acceptSelectionRevisions=="function"||r==="reject"&&typeof i.rejectSelectionRevisions=="function")&&u&&!u.selection.empty&&ny(e,t,u)){tt(i,u,p=>r==="accept"?p.acceptSelectionRevisions?.()??!1:p.rejectSelectionRevisions?.()??!1,{restoreSelection:!1});return}if(!(u&&!u.selection.empty&&ny(e,t,u)&&(r==="accept"?t.documentApi.review.accept([...n],t.actor??void 0):t.documentApi.review.reject([...n],t.actor??void 0)).changed)){if(n.length===1&&!c&&!m){let p=n[0];if(!p)return;if(r==="accept"){t.acceptRevision(p);return}t.rejectRevision(p);return}if(a&&!c&&!m){if(r==="accept"){t.documentApi.review.accept([...n],t.actor??void 0);return}t.documentApi.review.reject([...n],t.actor??void 0);return}if(r==="accept"){t.acceptSelection();return}t.rejectSelection()}}function Rt(e,t){let r=ju(e,t).actionSelection;if(r.stale)return"Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.";let o=it(t);return o?ir({editable:e.isEditable},o.state,r.resolvedSelectionCapture):"Live editor surface is unavailable for inline formatting."}function Vu(e){return e.hasAmbiguousPointReviewTarget?"Right-click hit multiple overlapping review targets. Click a specific change or narrow the selection before accepting or rejecting changes.":e.isEditable?null:"Document is read-only in the current document mode."}function sy(e){return Vu(e)==null}function kO(e,t){let r=it(t),{effectiveSelection:o,actionSelection:n}=ju(e,t),i=o.stale?!1:o.resolvedSelectionCapture?.selection.formatting.link??e.activeMarks.includes("link"),s=o.stale?"":o.resolvedSelectionCapture?.selection.formatting.linkHref??"",a=[{id:"formatting",items:[{id:"bold",label:"Bold",action:()=>{n.stale||_t(t,"bold",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"italic",label:"Italic",action:()=>{n.stale||_t(t,"italic",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"underline",label:"Underline",action:()=>{n.stale||_t(t,"underline",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"strikethrough",label:"Strikethrough",action:()=>{n.stale||_t(t,"strike",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)}]},{id:"links",items:[{id:"insert-link",label:i?"Edit link":"Insert link",action:()=>{if(n.stale)return;let l=t.captureSelectionHandleFromCapture(n.selectionCapture);if(!l)return;let c=CO(s);try{c&&t.setLinkFromHandle(l,c,null,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"clear-link",label:"Clear link",showWhen:()=>i,enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t),action:()=>{if(n.stale)return;let l=t.captureSelectionHandleFromCapture(n.selectionCapture);if(l)try{t.clearLinkFromHandle(l,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}}}]},{id:"history",items:[{id:"undo",label:"Undo",action:()=>{r?.undo()},enabledWhen:l=>l.isEditable&&(r?.canUndo()??!1)},{id:"redo",label:"Redo",action:()=>{r?.redo()},enabledWhen:l=>l.isEditable&&(r?.canRedo()??!1)}]}];return e.trackedChangeIds.length>0&&a.unshift({id:"track-changes",items:[{id:"accept-change",label:e.trackedChangeIds.length===1?"Accept change":"Accept changes",tone:"success",enabledWhen:sy,disabledReason:Vu,action:()=>iy(e,t,"accept")},{id:"reject-change",label:e.trackedChangeIds.length===1?"Reject change":"Reject changes",tone:"danger",enabledWhen:sy,disabledReason:Vu,action:()=>iy(e,t,"reject")}]}),a}function EO(e,t,r){return r?null:typeof e.disabledReason=="function"?e.disabledReason(t)??"Action unavailable.":e.disabledReason??"Action unavailable."}function Ma(e,t,r){let o=r??bS(e.host)??e.controller??null,n=t?.includeDefaultItems===!1||!o?[]:kO(e,o),i=PO(n,t?.customItems??[]);return(t?.menuProvider?.(e,i)??i).map(a=>{let l=a.items.filter(c=>c.showWhen?.(e)??!0).map(c=>{let d=c.enabledWhen?.(e)??!0;return{...c,enabled:d,disabledReason:EO(c,e,d)}});return{id:a.id,label:a.label,items:l}}).filter(a=>a.items.length>0)}function MO(e){let t=e.pointSelection?.capture.selection.from??null,r=Mt(e.pointSelection?.capture,e.revisions),o=!!(e.effectiveSelectionRange&&typeof t=="number"&&t>=e.effectiveSelectionRange.from&&t<=e.effectiveSelectionRange.to);return!!(e.pointSelection&&(!e.effectiveSelectionRange||!o)&&(r.length>0||e.pointSelection.capture.selectionKind==="node"||e.pointSelection.capture.selection.formatting.link||e.pointSelection.capture.selection.empty))}function Lu(e){let t=e.controller.getState(),r=e.actionSelectionCapture&&!e.actionSelectionCapture.selection.empty?{from:Math.min(e.actionSelectionCapture.selection.from,e.actionSelectionCapture.selection.to),to:Math.max(e.actionSelectionCapture.selection.from,e.actionSelectionCapture.selection.to)}:null,o=MO({pointSelection:e.pointSelection,effectiveSelectionRange:r,revisions:t.revisions}),n=o?e.pointSelection?.capture??null:e.effectiveSelection,i=o?e.pointSelection?.capture??null:e.actionSelectionCapture,s=i?.selection??n?.selection??null,a=o?Mt(e.pointSelection?.capture,t.revisions):yt({liveSelection:Ms(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:t.revisions,effectiveSelection:i??e.effectiveSelection});return ra(e.controller,e.documentMode,{revisions:t.revisions,reviewActionsEnabled:e.reviewActionsEnabled,selection:n?{from:s?.from??n.selection.from,to:s?.to??n.selection.to,empty:s?.empty??n.selection.empty,trackedChangeIds:a,trackedChangeIdsExplicit:!0}:null,selectionCapture:n,actionSelectionCapture:i,pointSelectionCapture:o?e.pointSelection?.capture??null:null,pointSelectionState:o?e.pointSelection?.state??void 0:void 0,selectionTrackedChangeIds:t.selection.trackedChangeIds,clientX:e.clientX,clientY:e.clientY,selectionState:o?e.pointSelection?.state??void 0:void 0})}function IO(e,t){let r=ve(e).view;if(!r?.state||typeof r.posAtCoords!="function")return null;let o=t.includeText??!0,n=e.readPointSelection({clientX:t.clientX,clientY:t.clientY,includeText:o}),i=e.readEffectiveSelection({includeText:o}),s=e.readEffectiveSelection()??i;if(!n&&!i)return null;let a=e.getState();return Lu({controller:e,documentMode:a.documentMode,reviewActionsEnabled:a.trackChanges.enabled,effectiveSelection:i,actionSelectionCapture:s,pointSelection:n?{capture:n}:null,clientX:t.clientX,clientY:t.clientY})}function AO(e){let{from:t,to:r}=e.selection;if(t>=r)return e;let o=Math.min(r-1,t+Math.max(1,Math.floor((r-t)/2))),n=Z(e,o,o);if(!n)return e;try{return e.apply(e.tr.setSelection(n))}catch{return e}}function ay(e){let{captureSelectionFromState:t,closeContextMenu:r,closeLinkPopover:o,emit:n,getController:i,getDocumentMode:s,getResolvedModules:a,getRuntime:l,setLinkPopover:c}=e;return d=>{let u=a();if(u.links?.enabled===!1)return;let m=d.target?.closest("a[href]");if(!(m instanceof HTMLAnchorElement)){o();return}let p=l(),f=s();d.preventDefault(),d.stopPropagation(),ta(p.surface,m);let g=()=>o(),v=u.links?.popoverResolver?.({host:uo(i()),href:m.getAttribute("href")??"",title:m.getAttribute("title"),target:m.getAttribute("target"),rel:m.getAttribute("rel"),tooltip:m.getAttribute("title"),element:m,clientX:d.clientX,clientY:d.clientY,isAnchorLink:(m.getAttribute("href")??"").startsWith("#"),documentMode:f,position:{left:d.clientX+8,top:d.clientY+12},closePopover:g})??{type:"default"};if(v.type==="none"){o();return}c(VS(uo(i()),p.surface,f,m,d.clientX,d.clientY,v),t(AO(p.surface.state))),r(),n()}}function ly(e){let{closeContextMenu:t,closeLinkPopover:r,emit:o,getController:n,getDocumentMode:i,getResolvedModules:s,readTrackChangesDisplayState:a,captureEffectiveSelectionFromState:l,setContextMenu:c}=e;return d=>{let u=s();if(u.contextMenu?.enabled===!1)return;d.preventDefault(),d.stopPropagation(),r();let m=n(),p=ve(m),f=m.captureEffectiveSelection({includeText:!0}),g=m.captureEffectiveSelection()??f,v=Ea({surface:p,clientX:d.clientX,clientY:d.clientY,captureSelectionFromState:l}),k=a(),R=Lu({controller:m,documentMode:i(),reviewActionsEnabled:k.enabled,effectiveSelection:f,actionSelectionCapture:g,pointSelection:v,clientX:d.clientX,clientY:d.clientY}),h=Ma(R,u.contextMenu,m);if(h.length===0){t();return}c({context:R,sections:h}),o()}}function cy(e){return Ea({surface:e.surface,clientX:e.pointSelectionInput.clientX,clientY:e.pointSelectionInput.clientY,captureSelectionFromState:e.captureSelectionFromState})?.capture??null}function dy(e){let{context:t,readProjectionSnapshot:r,readState:o,selectionCaptureTracker:n}=e,i=(R,h={},B=null)=>{let S=X(t),b=r();return{state:R,surfaceEditable:nt(S.surface),surfaceSelectionReliable:XS(S.surface),selectionInput:h,reviewReplacementMode:S.replacementMode,revisions:b.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:b,preservedRangeSelection:B}},s=(R,h={})=>Mh(i(R,h)),a=(R,h={})=>{let B=X(t);return n.track(B.surface,R,s(R,h))},l=(R,h={},B=null)=>{let S=X(t),b=i(R,h,B);return n.track(S.surface,Pi(b),So(b))},c=(R,h={},B=null)=>So(i(R,h,B)),d=(R={})=>{let h=X(t);return h.surface.consumeHistoryChange?.()&&(t.preservedRangeSelection=null),o(),{selectionInput:R,runtime:h,preservedRangeSelection:t.preservedRangeSelection}};return{captureSelection:(R={})=>a(X(t).surface.state,R),captureEffectiveSelection:(R={})=>{let h=d(R);return l(h.runtime.surface.state,h.selectionInput,h.preservedRangeSelection)},readEffectiveSelection:(R={})=>{let h=d(R);return c(h.runtime.surface.state,h.selectionInput,h.preservedRangeSelection)},captureCurrentSelectionFromState:a,captureEffectiveSelectionFromState:l,capturePointSelection:R=>{let h=d(R);return cy({surface:h.runtime.surface,pointSelectionInput:R,captureSelectionFromState:B=>l(B,h.selectionInput,h.preservedRangeSelection)})},readPointSelection:R=>{let h=d(R);return cy({surface:h.runtime.surface,pointSelectionInput:R,captureSelectionFromState:B=>c(B,h.selectionInput,h.preservedRangeSelection)})},readSelectionCapture:(R,h={})=>{if(!R)return null;let B=X(t),S=n.resolveState(B.surface,R);return S?s(S,h):null},resolveSelectionCapture:(R,h={})=>{if(!R)return null;let B=X(t),S=n.resolveState(B.surface,R);return S?n.track(B.surface,S,s(S,h)):null}}}import{documentWideMutationEffect as jO}from"@datalking/begonia-editor-contracts";function Fu(e,t,r={}){return Ta(e,t,r)}function uy(e,t,r=e.replacementMode){if(e.replacementMode===r)return e;let o=e.surface;return e.release(),Fu(o,t,{replacementMode:r,templates:e.templatesAdapter})}function my(e,t,r){r(e.surface),e.release(),t&&e.surface.destroy()}function py(e){let{canonicalDocument:t,collaborative:r,documentMode:o,nextSurfaceSession:n,sourceRuntime:i,surfaceFactory:s,trackChanges:a}=e;return s({currentSurface:i.surface,collaborative:r??n?.binding,documentStory:i.surface.documentStory,editable:ln(o),initialContent:bt(t,t.copy(t.content)),schema:i.surface.schema,participant:i.surface.participant,trackingEnabled:kr(o,a)})}function fy(e){return ht(e)??Wn}function NO(e){return fy(e)/100}function DO(e){return e.view?.dom??null}function OO(e){if(e.style)return e.style;let t={};return e.style=t,t}function zu(e,t){let r=DO(e);if(!r)return;let o=fy(t),n=String(NO(o)),i=OO(r);r.dataset.aldZoomPercent=String(o),i.zoom=n,i.transformOrigin="top left"}function wy({context:e,templates:t,ownsSurface:r,surfaceFactory:o,allowCollaborativeProjection:n,emit:i,readCurrentDisplayState:s,clearEphemeralOverlays:a,handleLinkClick:l,handleContextMenu:c}){let d=new WeakMap,u=null,m=null,p=()=>{u?.dispose(),u=null,m=null},f=E=>((!u||m!==E)&&(p(),u=bw(()=>e.readModel.canonicalDocument,E,Ie(e).documentRuntimeKernel.documentSource),m=E),u),g=E=>{let N=Ie(e),L=po(e.readModel),ne=L?f(E):N.documentRuntimeKernel.projections;L||p(),e.readModel=pi(e.readModel,ne,E)},v=()=>e.readModel.projectedRuntimeBank?.resolveRuntime("tracked").documentApi??null,k=E=>{E.addEventListener("click",l),E.addEventListener("contextmenu",c)},R=E=>{E.removeEventListener("click",l),E.removeEventListener("contextmenu",c)},h=E=>{let N=E.view?.dom;if(!N)return;let L=d.get(E);L&&L!==N&&R(L),k(N),d.set(E,N);let ne=s();fc(E,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,ne.trackChanges,ne.comments)},B=E=>{let N=d.get(E)??E.view?.dom??null;N&&(R(N),d.delete(E))},S=()=>{let E=e.readModel.collaborativeProjection;if(!E){e.readModel=fi(e.readModel);return}let N=Ie(e),L=go({surface:E.runtime.surface,nextDocument:N.surface.document,documentApi:E.runtime.documentApi,canonicalReviewApi:v(),canonicalDocument:N.surface.document,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection});a(),B(E.runtime.surface),E.restore(),Ci({surface:N.surface,target:L,documentApi:N.documentApi}),E.runtime.release(),E.runtime.surface.destroy(),e.readModel=bn(fi(e.readModel))},b=E=>{let N=Ie(e);if(N.replacementMode!==E){let L=uy(N,P,E);e.readModel=ad(e.readModel,L,E),e.readModel=bn(e.readModel)}g(E),e.readModel.collaborativeProjection&&e.readModel.collaborativeProjection.runtime.replacementMode!==E&&S()},P=()=>{let E=Ie(e);A(E);let N=s(),L=Ns(E.surface,e.documentMode,N.trackChanges,n());if(po(e.readModel)&&L){let ne=Me(e.readModel.canonicalDocument,E.surface,L);if(!Ar(E.surface.document,ne)){e.readModel=ld(e.readModel,E.surface.document);let y=Me(e.readModel.canonicalDocument,E.surface,L);if(!Ar(E.surface.document,y)){Cn({surface:E.surface,nextDocument:y,documentApi:E.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:L,preservedRangeSelection:e.preservedRangeSelection});return}}}else e.readModel=bn(e.readModel);if(e.readModel.collaborativeProjection&&L){e.readModel.collaborativeProjection.sync(e.readModel.canonicalDocument,L)||i();return}e.documentMode==="viewing"&&N.trackChanges.enabled&&N.trackChanges.mode==="review"&&ba({surface:E.surface,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,projectedMode:L})||i()},A=(E=Ie(e))=>{let N=ur(E.documentApi.preferences.get());zu(E.surface,N);let L=e.readModel.activeRuntime;L&&L.surface!==E.surface&&zu(L.surface,N)},O=()=>{let E=s();b(E.trackChanges.replacements);let N=Ie(e),L=Ns(N.surface,e.documentMode,E.trackChanges,n()),ne=ln(e.documentMode),y=kr(e.documentMode,E.trackChanges),x=rn(N.surface)?!1:ne;if(e.readModel=bn(e.readModel),N.surface.editable!==x&&N.surface.setEditable(x),N.surface.trackingEnabled!==y&&N.surface.setTrackingEnabled(y),L&&N.surface.collaborative&&o){if(po(e.readModel)&&(Ar(N.surface.document,e.readModel.canonicalDocument)||N.surface.replaceDocument(bt(N.surface.document,e.readModel.canonicalDocument),{origin:"system",intent:"restore-canonical-projection-document",effects:[jO("review")]}),e.readModel=fi(e.readModel),g(E.trackChanges.replacements)),!e.readModel.collaborativeProjection){a();let U=Me(e.readModel.canonicalDocument,N.surface,L),xe=go({surface:N.surface,nextDocument:U,documentApi:N.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:L,preservedRangeSelection:e.preservedRangeSelection}),me=ey({sourceRuntime:N,surfaceFactory:o,canonicalDocument:e.readModel.canonicalDocument,projectionMode:L,emit:i,readPreservedRangeSelection:()=>e.preservedRangeSelection,replacementMode:E.trackChanges.replacements});Ci({surface:me.runtime.surface,target:xe,documentApi:me.runtime.documentApi}),h(me.runtime.surface),e.readModel=KS(e.readModel,me)}e.readModel.collaborativeProjection?.sync(e.readModel.canonicalDocument,L)}else if(e.readModel.collaborativeProjection&&S(),L){let U=Me(e.readModel.canonicalDocument,N.surface,L);e.readModel=WS(e.readModel),g(E.trackChanges.replacements),Ar(N.surface.document,U)||Cn({surface:N.surface,nextDocument:U,documentApi:N.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:L,preservedRangeSelection:e.preservedRangeSelection})}else po(e.readModel)&&(Ar(N.surface.document,e.readModel.canonicalDocument)||Cn({surface:N.surface,nextDocument:e.readModel.canonicalDocument,documentApi:N.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection}),e.readModel=fi(e.readModel),g(E.trackChanges.replacements));let M=e.readModel.activeRuntime??N;A(N);let I=rn(M.surface)?!1:ne;M.surface.editable!==I&&M.surface.setEditable(I),M.surface.trackingEnabled!==y&&M.surface.setTrackingEnabled(y),fc(M.surface,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,E.trackChanges,E.comments)},j=E=>{let N=an(e.documentMode,e.resolvedModules.trackChanges).replacements;e.readModel=ad(e.readModel,Fu(E,P,{replacementMode:N,templates:t}),N),e.readModel=bn(e.readModel),g(N),h(E),A()},K=E=>{p(),e.readModel=pi(e.readModel,null),my(Ie(e),E,B),e.readModel=_S(e.readModel)};return{destroyCollaborativeProjection:S,handleSourceRuntimeUpdate:P,applySurfaceDisplayState:O,mountSourceRuntime:j,unmountSourceRuntime:K,createReplacementSurface:(E,N)=>{if(!o)throw new Error("Browser editor cannot reconfigure collaboration without a managed surface factory.");let L=s();return py({surfaceFactory:o,sourceRuntime:Ie(e),canonicalDocument:e.readModel.canonicalDocument,documentMode:e.documentMode,trackChanges:L.trackChanges,collaborative:E,nextSurfaceSession:N})},swapSurface:(E,N)=>{let L=s(),ne=Ns(E,e.documentMode,L.trackChanges,n()),y=go({surface:X(e).surface,nextDocument:Me(e.readModel.canonicalDocument,E,ne),documentApi:X(e).documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:ne,preservedRangeSelection:e.preservedRangeSelection});a(),S(),K(r||!!o),e.collaborationSession=N,j(E),O(),Ci({surface:X(e).surface,target:y,documentApi:X(e).documentApi})}}}function gy(e){let t=e.currentState.context,r=t.selectionCapture??null,o=t.actionSelectionCapture??null,n=t.pointSelectionCapture??null,i=de(t.trackedChangeIds),s=de(e.liveSelection.trackedChangeIds),a=de(e.liveSelectionInfo.activeChangeIds),l=e.resolveSelectionCapture(r),c=n===r?l:e.resolveSelectionCapture(n),d=o===r?l:o===n?c:e.resolveSelectionCapture(o);if(r&&!l||n&&!c)return null;let u=n!=null,m=u?n:r,p=u?n:o,f=u?e.resolveSelectionState(n):null,g=u?null:e.resolveSelectionState(r),v=a.length>0||s.length>0,k=u?c:l,R=!u&&v?d??k:k,B=(!u&&v&&i.length>1?p?.selection??null:null)??R?.selection??k?.selection??null,S=u?Mt(c,e.revisions):yt({liveSelection:e.liveSelection,liveSelectionInfo:e.liveSelectionInfo,revisions:e.revisions,effectiveSelection:R}),b=ra(e.controller,e.documentMode,{revisions:e.revisions,reviewActionsEnabled:e.reviewActionsEnabled,selection:m?{from:B?.from??m.selection.from,to:B?.to??m.selection.to,empty:B?.empty??m.selection.empty,trackedChangeIds:S,trackedChangeIdsExplicit:!0}:null,selectionCapture:m,actionSelectionCapture:p,pointSelectionCapture:u?n:null,pointSelectionState:f??void 0,selectionTrackedChangeIds:s,clientX:t.clientX,clientY:t.clientY,selectionState:f??g??void 0}),P=Ma(b,e.contextMenuOptions,e.controller);return P.length>0?{context:b,sections:P}:null}function Sy(e){let t=new Set([e.nextState?.context.selectionCapture,e.nextState?.context.actionSelectionCapture,e.nextState?.context.pointSelectionCapture].filter(o=>o!=null)),r=new Set([e.currentState?.context.selectionCapture,e.currentState?.context.actionSelectionCapture,e.currentState?.context.pointSelectionCapture].filter(o=>o!=null));for(let o of r)o&&!t.has(o)&&e.untrack(o)}function vy(e){return{releaseContextMenuCaptures(t,r=null){Sy({currentState:t,nextState:r,untrack:e})},untrackCapture:e}}function hy(e){return Xe({selection:e.surface.describeSelection(),selectionInfo:e.selectionInfo,projectedDocument:We(e.surface),canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}import{createInvokeBridge as rj}from"@datalking/begonia-document-api/v1";import{createTrackChangesFacade as oj,summarizeReviewTimeline as My}from"@datalking/begonia-document-api/review";import{describeCapability as WO,planStepMode as KO,resolvePlanStepFailureReason as _O,resolveUnsupportedPlanStepReason as UO}from"@datalking/begonia-document-api/core";import{documentWideMutationEffect as ZO}from"@datalking/begonia-editor-contracts";import{preserveNodeSymbolMetadata as VO}from"@datalking/begonia-engine";import{sameCommittedDocument as LO}from"@datalking/begonia-document-model";import{createDocumentChange as FO,createDocumentChangePublisher as zO}from"@datalking/begonia-editor-contracts";function Hu(e){let t=e,r=0,o=zO();return{readDocument(){return t},replaceDocument(n,i={origin:"api"}){let s=VO(t,n);if(LO(t,s)){t=s;return}let a=r;t=s,r+=1,o.publish(FO(a,r,i))},readProjectedDocument(){return t},documentSource:{readSnapshot(){return{document:t,revision:r}},subscribeDocument(n){return o.subscribe(n)}}}}function HO(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Di(e){let t=e.review.list().map(i=>i.id).filter((i,s,a)=>a.indexOf(i)===s).sort((i,s)=>i.localeCompare(s)),r=e.history.get(),o=e.info.text(),n=JSON.stringify(e.info.json());return{summary:e.info.summary(),revisionIds:t,historyRevision:r.currentRevision,textLength:o.length,documentHash:HO(n)}}function qO(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function qu(e,t){return e.summary.blockCount===t.summary.blockCount&&e.summary.wordCount===t.summary.wordCount&&e.summary.revisionCount===t.summary.revisionCount&&e.summary.footnoteCount===t.summary.footnoteCount&&e.summary.endnoteCount===t.summary.endnoteCount&&e.summary.commentCount===t.summary.commentCount&&e.summary.bookmarkCount===t.summary.bookmarkCount&&qO(e.revisionIds,t.revisionIds)&&e.historyRevision===t.historyRevision&&e.textLength===t.textLength&&e.documentHash===t.documentHash}function Wu(e,t){return t.filter(r=>!e.includes(r))}function yy(e){return e==="sequential"?"sequential":"all_or_nothing"}function Oi(e){return e??null}import{createDocumentRuntimeKernel as by}from"@datalking/begonia-document-api/v1";function GO(e,t){let r=Hu(t),o=by(r,{review:{replacementMode:e.replacementMode}});return{surface:{editable:nt(e.surface),get document(){return r.readProjectedDocument()}},documentRuntimeKernel:o,documentService:o.service,documentApi:o.api,replacementMode:e.replacementMode}}function XO(e,t){let r=GO(e,e.surface.document),o=t.canonicalDocument??e.surface.document,n=Hu(o),i=by(n,{review:{replacementMode:r.replacementMode}}),s=pi({...ia(o,r.replacementMode),sourceRuntime:r,activeRuntime:r},i.projections,r.replacementMode);return{detachedRuntime:r,projectionSnapshot:Or(s,t.projectedMode)}}function $O(e){let t=e.getRuntime(),r=e.readCurrentDisplayState(),o=e.readProjectionSnapshot(),{detachedRuntime:n,projectionSnapshot:i}=XO(t,o);return{detachedRuntime:n,api:e.createDocumentApi({getRuntime:()=>n,hasSourceRuntime:()=>!0,readProjectionSnapshot:()=>i,readCurrentDisplayState:()=>r})}}function By(e){let t=o=>{let n=$O(e),{api:i}=n,s=yy(o.commitMode),a=Di(i),l=i.info().revision;if(o.expectedRevision!=null&&o.expectedRevision!==l)return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:!1,changed:!1,committed:!1,commitMode:s,stoppedEarly:!0,error:`Document revision mismatch. Expected ${o.expectedRevision} but found ${l}.`,before:a,after:a,steps:[]}};if(o.expectedDocumentHash&&o.expectedDocumentHash!==a.documentHash)return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:!1,changed:!1,committed:!1,commitMode:s,stoppedEarly:!0,error:`Document hash mismatch. Expected ${o.expectedDocumentHash} but found ${a.documentHash}.`,before:a,after:a,steps:[]}};let c=[],d=!0,u=!1;for(let[p,f]of o.steps.entries()){let g=WO(f.operationId),v=Di(i),k=Oi(f.label),R=UO(f.operationId,g),h=KO(g);if(R){if(d=!1,c.push({index:p,label:k,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:h,ok:!1,changed:!1,error:R,revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}let B=i.operations.invokeDynamic({operationId:f.operationId,input:f.input,options:f.options}),S=Di(i),b=h==="write"&&!qu(v,S),P=B.ok?_O(B.value):null;if(!B.ok||P){if(d=!1,c.push({index:p,label:k,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:h,ok:!1,changed:!1,error:B.ok?P:B.error.message,...B.ok?{result:B.value}:{},revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}c.push({index:p,label:k,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:h,ok:!0,changed:b,result:B.value,revisionIdsCreated:Wu(v.revisionIds,S.revisionIds),revisionIdsRemoved:Wu(S.revisionIds,v.revisionIds)})}let m=Di(i);return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:d,changed:!qu(a,m),committed:!1,commitMode:s,stoppedEarly:u,before:a,after:m,steps:c}}};return{preview:o=>t(o).receipt,apply(o){let{detachedRuntime:n,receipt:i}=t(o),s=i.changed&&(i.commitMode==="sequential"||i.executable);return s&&e.getRuntime().surface.replaceDocument(n.surface.document,{origin:"api",intent:"commit-document-operation-plan",effects:[ZO("structure")]}),{...i,preview:!1,committed:s}}}}function xy(e){let t=e.subscribeStateChange??e.subscribeRawSelectionChange??null;return{onChange(r){if(!t)return()=>{};let o=!1,n=!1,i=An(e.readSelectionInfo()),s=()=>{if(n=!1,o)return;let d=e.readSelectionInfo(),u=An(d);u!==i&&(i=u,r(d))},a=()=>{o||n||(n=!0,queueMicrotask(s))},l;try{l=t(a)}catch(d){throw o=!0,d}let c=!1;return()=>{c||(c=!0,o=!0,l())}}}}function YO(e){let t=e.surface.view;return!!(t?.state&&typeof t.dispatch=="function")}function JO(e,t){let r=[...e??[]],o=[...t??[]];return r.length===o.length&&r.every((n,i)=>n===o[i])}function QO(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Cy(e){return e?.kind==="text"?e.segments.length:0}function ej(e){let t=e.members?.length?e.members:null;return t?t.every(r=>(r.text?.length??0)===0&&r.target?.nodeType!=="text"):(e.text?.length??0)===0&&e.target?.nodeType!=="text"}function Py(e,t){return ce([...e.activeChangeIds,...e.selection.trackedChangeIds??[]],t)}function Ry(e,t){if(e.length===0)return!1;let r=ce(e,t);if(r.length===0)return!1;let o=new Map(t.map(n=>[n.id,n]));return r.every(n=>{let i=o.get(n);return i?ej(i):!1})}function Ty(e){let{getRuntime:t,readProjectionSnapshot:r,readCurrentDisplayState:o,readPresentationComments:n,readCanonicalReviewApi:i,readEffectiveSelection:s,captureEffectiveSelection:a}=e,l=(d,u={})=>{let m=o().comments.enabled?n().list({includeResolved:o().comments.showResolved,enforceVisibilityPolicy:o().comments.enforceVisibilityPolicy,visibility:o().comments.visibility,sort:"desc"}):[],p=s?.(u)??a?.(u)??null,f=t(),g=YO(f),v=f.surface.describeSelection(),k=W(f.surface.state.selection)?"node":"text",R=i().review.list(),h=r(),B=Xe({selection:v,selectionInfo:d,projectedDocument:We(f.surface),canonicalDocument:h.canonicalDocument,projectedMode:h.projectedMode,revisions:R}),S=ki(B.selectionInfo,Ti({activeCommentIds:B.selectionInfo.activeCommentIds,selection:v,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),b=ko(f.surface.state,S,k);if(p){let P=yt({liveSelection:B.selection,liveSelectionInfo:S,revisions:R,effectiveSelection:p}),A=Py(p,R),O=cc({liveSelection:B.selection,liveActiveChangeIds:S.activeChangeIds,effectiveSelection:p}),j=ki(Rr(p,A),Ti({activeCommentIds:p.activeCommentIds,selection:p.selection,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),K=Ry(A,R),F=!K&&p.projectedMode!=null,se=!K&&Cy(p.selectionTarget)>Cy(b.target),E=!K&&((j.text??null)!==(b.text??null)||!QO(j.target,b.target)||!JO(j.activeMarks,b.activeMarks));return B.selection.empty&&!p.selection.empty&&(p.activeCommentIds.length>0||A.length>0)&&(p.activeCommentIds.length>0||F||se||E||!g)?j:g?!O&&B.selection.empty&&!ar(S.activeChangeIds,P)?{...b,activeChangeIds:[...P]}:b:j}return b};return{resolvePublicSelectionInfo:l,readPublicSelectionInfo:(d={includeText:!0})=>{let u=t();return l(Dr(u.surface,d,u.replacementMode),d)}}}function tj(e){return()=>q(e)}function ky(e,t,r,o,n){if(e==null||typeof e!="object"&&typeof e!="function"||typeof e=="function"||t!==""&&!o.deniedMemberPaths.has(t)&&!o.descendantMemberPaths.has(t))return e;let i=e,s=n.get(i)?.get(t);if(s)return s;let a=new Proxy(e,{get(c,d){let u=Reflect.get(c,d,c);if(typeof d!="string")return u;let m=Reflect.getOwnPropertyDescriptor(c,d);if(m&&"value"in m&&!m.configurable&&!m.writable)return m.value;let p=t?`${t}.${d}`:d;return o.deniedMemberPaths.has(p)?typeof u=="function"?tj(r):u:o.descendantMemberPaths.has(p)?ky(u,p,r,o,n):u},apply(c,d,u){return o.deniedMemberPaths.has(t)?q(r):Reflect.apply(c,c,u)}}),l=n.get(i)??new Map;return l.set(t,a),n.set(i,l),a}function Ey(e,t){return ky(e,"",t,Fh(e),new WeakMap)}function Ot(e,t){return Jt(e.surface)??(t.comments.readOnly?"Comments are read-only in the current document mode.":null)}function Iy(e,t){return t.comments.allowResolve?Ot(e,t):"Comment resolution is disabled."}function Ku(e){let{getRuntime:t,hasSourceRuntime:r,readCurrentDisplayState:o,readProjectionSnapshot:n}=e,{readEffectiveSelection:i,captureEffectiveSelection:s,subscribeStateChange:a}=e,l=new WeakMap,c=()=>n(),d=()=>Pa(c()),u=()=>d().presentationReadApi,m=()=>d().canonicalReviewApi,p=()=>d().writableRuntimeApi,f=()=>Jt(t().surface),g=()=>nt(t().surface),v=y=>{let x=c();return x.projectedMode==null||x.projectedRuntimeBank==null?null:y===x.projectedMode?x.presentationReadRuntime.documentApi:y==="tracked"?x.canonicalReviewRuntime.documentApi:x.projectedRuntimeBank.resolveRuntime(y).documentApi},k=()=>{let y=p(),x=f();if(!x)return y;let M=l.get(y)?.get(x);if(M)return M;let I=Ey(y,x),U=l.get(y)??new Map;return U.set(x,I),l.set(y,U),I},R=Wh({readPresentationApi:u,readWritableApi:k,readProjectedApiForMode:v}),h=By({getRuntime:t,readProjectionSnapshot:n,readCurrentDisplayState:o,createDocumentApi:Ku}),B=()=>u().comments,{readPublicSelectionInfo:S}=Ty({getRuntime:t,readProjectionSnapshot:n,readCurrentDisplayState:o,readPresentationComments:B,readCanonicalReviewApi:m,readEffectiveSelection:i,captureEffectiveSelection:s}),b=xy({readSelectionInfo:()=>S({includeText:!0}),subscribeRawSelectionChange:y=>t().documentApi.selection.onChange(()=>y()),subscribeStateChange:a}),P=y=>{let x=i?.()??s?.()??null,M=p(),I=y(M);return I.changed&&mi({capture:x,surface:t().surface,comments:M.comments}),I},A=()=>p().comments,O={list:(y={})=>B().list(y),get:(y,x={})=>B().get(y,x),activity:(y,x={})=>B().activity(y,x),activityTimeline:(y,x={})=>B().activityTimeline(y,x),activitySummary:(y,x={})=>B().activitySummary(y,x),activityEntry:(y,x,M={})=>B().activityEntry(y,x,M),target:(y,x={})=>B().target(y,x),entryTarget:(y,x,M={})=>B().entryTarget(y,x,M),targetSnapshot:(y,x={})=>B().targetSnapshot(y,x),create:y=>{let x=Ot(t(),o());return x?q(x):A().create(y)},permissions:(y,x)=>{let M=B().permissions(y,x);return o().comments.readOnly?M&&Mi(M,o().comments):M},entryPermissions:(y,x,M)=>{let I=B().entryPermissions(y,x,M);return o().comments.readOnly?Zh(I):I},move:(y,x,M)=>{let I=Ot(t(),o());return I?q(I):A().move(y,x,M)},upsert:y=>{let x=Ot(t(),o());return x?q(x):A().upsert(y)},reply:(y,x,M)=>{let I=Ot(t(),o());return I?q(I):A().reply(y,x,M)},patch:(y,x,M)=>{let I=Ot(t(),o());return I?q(I):A().patch(y,x,M)},update:(y,x,M)=>{let I=Ot(t(),o());return I?q(I):A().update(y,x,M)},updateEntry:(y,x,M,I)=>{let U=Ot(t(),o());return U?q(U):A().updateEntry(y,x,M,I)},resolve:(y,x)=>{let M=Iy(t(),o());return M?q(M):A().resolve(y,x)},reopen:(y,x)=>{let M=Iy(t(),o());return M?q(M):A().reopen(y,x)},replaceTargetTextTracked:(y,x,M,I={})=>{let U=Ot(t(),o());return U?q(U):A().replaceTargetTextTracked(y,x,M,I)},removeEntry:(y,x,M)=>{let I=Ot(t(),o());return I?q(I):A().removeEntry(y,x,M)},remove:(y,x)=>{let M=Ot(t(),o());return M?q(M):A().remove(y,x)}},j={query:(y,x={})=>u().search.query(y,x),next:(y,x=null,M={})=>u().search.next(y,x,M),previous:(y,x=null,M={})=>u().search.previous(y,x,M),replace:(y,x,M,I={})=>k().search.replace(y,x,M,I),replaceTracked:(y,x,M,I,U={},xe={})=>k().search.replaceTracked(y,x,M,I,U,xe),replaceAll:(y,x,M={})=>k().search.replaceAll(y,x,M),replaceAllTracked:(y,x,M,I={},U={})=>k().search.replaceAllTracked(y,x,M,I,U),clear:()=>u().search.clear()},K={list:(y={})=>u().proofing.list(y),ignore:y=>k().proofing.ignore(y),acceptSuggestion:y=>k().proofing.acceptSuggestion(y),replaceTracked:(y,x,M,I={})=>k().proofing.replaceTracked(y,x,M,I)},F={current:(y={})=>S(y),onChange:y=>b.onChange(y)},se={list:y=>m().review.list(y),decisionActivity:(y={})=>m().review.decisionActivity(y),decisionActivityEntry:(y,x={})=>m().review.decisionActivityEntry(y,x),decisionActivitySummary:(y={})=>m().review.decisionActivitySummary(y),decisionActivityByObject:(y,x={})=>m().review.decisionActivityByObject(y,x),decisionActivitySummaryByObject:(y,x={})=>m().review.decisionActivitySummaryByObject(y,x),timeline:(y={})=>{let x=o(),M=c();return Ai(Ra({projectionSnapshot:M,reviewOptions:y}),g(),x.comments)},timelineSummary:(y={})=>My(se.timeline(y)),timelineByObject:(y,x={})=>{let M=o(),I=c();return Ai(Uh({projectionSnapshot:I,objectId:y,reviewOptions:x}),g(),M.comments)},timelineSummaryByObject:(y,x={})=>My(se.timelineByObject(y,x)),permissions:(y,x)=>{let M=m().review.permissions(y,x);return f()?M.map(Ii):M},accept:(y,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):P(M=>M.review.accept(y,x)),reject:(y,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):P(M=>M.review.reject(y,x)),acceptMatching:(y,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):P(M=>M.review.acceptMatching(y,x)),rejectMatching:(y,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):P(M=>M.review.rejectMatching(y,x)),decideRange:(y,x,M)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):P(I=>I.review.decideRange(y,x,M))},E=oj({service:null,review:se}),N=Object.assign(((y={})=>{let x=u().info,M=se.list().length,I=x(y);return{...I,counts:{...I.counts,trackedChanges:M}}}),{summary:()=>({...u().info.summary(),revisionCount:se.list().length}),outline:()=>u().info.outline(),json:()=>u().info.json(),text:()=>u().info.text(),html:(y={})=>(v(y.revisionProjection??c().projectedMode??"tracked")??u()).info.html(y),markdown:(y={})=>(v(y.revisionProjection??c().projectedMode??"tracked")??u()).info.markdown(y)}),L,ne=rj(()=>new Proxy({},{get(y,x,M){return x==="service"?t().documentService:Reflect.get(L,x,M)}}));return L=new Proxy({},{get(y,x,M){if(typeof x!="string"||x==="$$typeof")return r()?Reflect.get(u(),x,M):void 0;if(x==="comments")return O;if(x==="review")return se;if(x==="search")return j;if(x==="proofing")return K;if(x==="selection")return F;if(x==="trackChanges")return E;if(x==="operations")return ne;let I=c();return x==="info"&&I.canonicalDocument!=null&&I.projectedMode!=null?N:x==="plans"&&I.canonicalDocument!=null&&I.projectedMode!=null?h:R(x)}}),L}import{emitClonedOrderedListeners as lj,throwOrderedListenerErrors as cj}from"@datalking/begonia-layout-renderer/core";function nj(e){return e==null?e:structuredClone(e)}function ij(e){return{empty:e.empty,target:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[...e.trackedChangeIds]}}function _u(e){let t=structuredClone({...e.selection,trackedChangeIds:ce(e.selection.trackedChangeIds,e.revisions)}),r=e.selectionInfo,o=r?structuredClone({...r,activeChangeIds:ce(r.activeChangeIds,e.revisions)}):ij(t),n=ro({revisions:e.revisions,selectionInfo:o}),i=sn({comments:e.comments,selectionInfo:o,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds});return{toolbar:structuredClone(e.toolbar),comments:structuredClone(e.comments),commentPermissions:structuredClone(e.commentPermissions),activeCommentId:i.activeCommentId,activeCommentIds:structuredClone(i.activeCommentIds),revisions:structuredClone(e.revisions),activeRevisionId:e.activeRevisionId??n.activeRevisionId,activeRevisionIds:structuredClone(e.activeRevisionIds??n.activeRevisionIds),reviewPermissions:structuredClone(e.reviewPermissions),reviewTimeline:structuredClone(e.reviewTimeline),reviewTimelineSummary:nj(e.reviewTimelineSummary),search:structuredClone(e.search),proofing:structuredClone(e.proofing),advancedOoxml:structuredClone(e.advancedOoxml),selectionInfo:o,selection:t,editable:e.editable,documentMode:e.documentMode,flowMode:e.flowMode,layoutMode:e.layoutMode,preferredPaginatedLayoutMode:e.preferredPaginatedLayoutMode,zoomPercent:e.zoomPercent,zoom:structuredClone(e.zoom),viewport:re(e.viewport),viewportRequestKey:e.viewportRequestKey,previewNavigationRequest:be(e.previewNavigationRequest),trackChanges:structuredClone(e.trackChanges),commentsDisplay:structuredClone(e.commentsDisplay),collaboration:structuredClone(e.collaboration),linkPopover:xa(e.linkPopover),contextMenu:Ca(e.contextMenu)}}function sj(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function aj(e){let t=e.view.state.doc,r=Math.max(1,t.content.size);return Math.max(1,Math.min(e.view.state.selection.head,r))}function Ia(e){if(e.allowSelectionInViewMode||e.documentMode!=="viewing"||!sj(e.surface)||e.surface.view.state.selection.empty)return!1;let t=aj(e.surface),r=e.surface.view.state.selection;if(r.from===t&&r.to===t)return!1;let o=Z(e.surface.view.state,t,t);return o?(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(o)),!0):!1}function Ay(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function Ny(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Dy({context:e,allowCollaborativeProjection:t,releaseContextMenuCaptures:r}){let o=!1,n=0,i=!1,s=0,a=!1,l=()=>e.collaborationSession?{...e.collaborationSession.getSnapshot(),mode:"session",reconfigurable:e.reconfigurable}:{collaborative:!1,mode:"none",reconfigurable:e.reconfigurable,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null},c=()=>{if(e.resolvedModules.trackChanges?.enabled===!1)return;let b=Ie(e);if(rn(b.surface))return;let P=b.surface.editable?b.surface.trackingEnabled?"suggesting":"editing":"viewing";P!==e.documentMode&&(e.documentMode=P)},d=()=>AS(Ie(e).surface,e.documentMode,e.resolvedModules,t()),u=()=>e.readModel.sourceRuntime?Qs(e.readModel.sourceRuntime.surface,e.collaborationSession,e.reconfigurable):l(),m=()=>{c(),e.normalizeOverlayState?.();let b=Ie(e),P=X(e);P.surface.consumeHistoryChange?.()&&(e.preservedRangeSelection=null);let A=d(),O=ur(b.documentApi.preferences.get()),j=ca(e,O),K=Or(e.readModel,A.trackChanges.mode),F=$h({runtime:P,projectionSnapshot:K,preservedRangeSelection:e.preservedRangeSelection,actor:e.currentActor,linkPopover:e.linkPopover,contextMenu:e.contextMenu,search:{query:e.searchQuery,options:e.searchOptions,activeHitId:e.activeSearchHitId},collaboration:u(),documentMode:e.documentMode,zoomPercent:O,zoom:j,viewportSession:e.viewportSession,display:{trackChanges:A.trackChanges,comments:A.comments},activeCommentId:e.activeCommentId,activeRevisionId:e.activeRevisionId,activeRevisionIds:e.activeRevisionIds}),se=uc({comments:F.comments,selectionInfo:F.selectionInfo});if(se.activeCommentId)e.activeCommentId!==se.activeCommentId&&(e.activeCommentId=se.activeCommentId);else if(e.activeCommentId!=null){let y=mc({comments:F.comments,selectionInfo:F.selectionInfo,explicitActiveCommentId:e.activeCommentId}),x=y.length===1?y[0]??null:null;e.activeCommentId!==x&&(e.activeCommentId=x)}let E=ro({revisions:F.revisions,selectionInfo:F.selectionInfo});if(E.activeRevisionIds.length>0)(e.activeRevisionId!==E.activeRevisionId||!Ny(e.activeRevisionIds,E.activeRevisionIds))&&(e.activeRevisionId=E.activeRevisionId,e.activeRevisionIds=[...E.activeRevisionIds]);else if(e.activeRevisionIds.length>0&&F.activeRevisionIds){let y=new Set(F.revisions.map(M=>M.id)),x=e.activeRevisionIds.filter(M=>y.has(M));Ny(e.activeRevisionIds,x)?x.length===0&&e.activeRevisionId!=null&&(e.activeRevisionId=null):(e.activeRevisionIds=[...x],e.activeRevisionId=x.length===1?x[0]??null:null)}let N=So({state:P.surface.state,surfaceEditable:P.surface.editable,surfaceSelectionReliable:Ay(P.surface),selectionInput:{includeText:!0},reviewReplacementMode:P.replacementMode,revisions:K.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:K,preservedRangeSelection:e.preservedRangeSelection}),L=!!(K.projectedMode!=null&&N&&F.selection.empty&&!N.empty&&e.preservedRangeSelection?.projectedMode!==K.projectedMode),ne=N&&L?{selection:N.selection,selectionInfo:Rr(N),selectionNodeSelectionTarget:N.nodeSelectionTarget}:{selection:P.surface.describeSelection(),selectionInfo:F.selectionInfo,selectionNodeSelectionTarget:F.selectionNodeSelectionTarget??null};return e.preservedRangeSelection=Fd({selection:ne.selection,selectionInfo:ne.selectionInfo,selectionNodeSelectionTarget:ne.selectionNodeSelectionTarget??null,previous:e.preservedRangeSelection,state:P.surface.state,surfaceSelectionReliable:Ay(P.surface),reviewReplacementMode:P.replacementMode,revisions:K.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:K}),e.activeSearchHitId=F.search.activeHitId,F},p=()=>_u(m()),f=()=>e.readModel.activeRuntime?Ia({surface:e.readModel.activeRuntime.surface,documentMode:e.documentMode,allowSelectionInViewMode:e.allowSelectionInViewMode}):!1,g=()=>{let b=null;do{if(i=!1,f()){i=!0;continue}b=m()}while(i);if(b==null)throw new Error("Browser editor state emission could not stabilize.");return b},v=()=>{if(s>0&&!o){a=!0;return}if(o){i=!0;return}o=!0;let b=[];try{do{let P=g();n+=1,b.push(...lj(e.listeners,P,_u))}while(i)}finally{o=!1,i=!1}cj(b,"Browser editor state listeners failed.")};return{syncDocumentModeFromSurface:c,readCurrentDisplayState:d,readCollaboration:u,readState:p,getEmissionVersion:()=>n,emit:v,runBatchedEmit:b=>{s+=1;try{return b()}finally{s-=1,s===0&&a&&(a=!1,v())}},closeLinkPopover:()=>{e.linkPopover&&(e.linkPopover=null,v())},closeContextMenu:()=>{e.contextMenu&&(r?.(),e.contextMenu=null,v())},clearEphemeralOverlays:()=>{r?.(),e.linkPopover=null,e.contextMenu=null},subscribeCollaborationSession:b=>{e.unsubscribeCollaborationSession?.(),e.unsubscribeCollaborationSession=b?.subscribe?b.subscribe(()=>v()):null}}}function Oy(e){let t=null,r=null,o=!1,n=s=>{r&&r!==s&&e.untrackCapture(r),r=s},i=()=>{n(null)};return{getSelectionCapture(){return r},sync(s){return!t||!r||!o||s(r)?.selection.formatting.link?!1:(t=null,i(),o=!1,e.setState(null),!0)},set(s,a=r){let l=s?a??null:null;e.setState(s),n(l),o=!!(s&&l?.selection.formatting.link),t=s??null},close(){t=null,i(),o=!1,e.closeState()},clearOverlays(){t=null,i(),o=!1,e.clearOverlayState()}}}import{createSelectionTrackingBookmark as Gu}from"@datalking/begonia-engine";import{readSyntheticSideStoryDocOriginPath as mj}from"@datalking/begonia-doc-service/v1";function dj(e){return typeof e.capture.text=="string"&&!e.selection.empty&&ge(e.surface.state.doc,e.surface.state.schema,e.selection)!==e.capture.text}function uj(e){let t=Mt(e.capture);return e.capture.selectionKind!=="text"||t.length===0?!1:!e.selection||e.selection.empty!==e.capture.selection.empty?!0:dj({surface:e.surface,selection:e.selection,capture:e.capture})}function jy(e){return uj(e)?e.resolveSemanticSelection():e.selection}var pj=256;function Ly(e,t){if(!e||!t.docChanged)return e;try{return e.map(t.mapping)}catch{return null}}function Fy(e,t,r){for(let o of r.captures)t.add(o),e.delete(o);r.captures.clear()}function Vy(e,t){for(;t.captures.size>pj;){let r=t.captures.values().next().value;if(!r)return;t.captures.delete(r),e.delete(r)}}function fj(e){return typeof e.view?.dispatch=="function"&&typeof e.subscribe=="function"}function wj(e,t,r){if(r.docChanged){e.pendingDispatchDocChange=!0;for(let o of e.captures){let n=t.get(o);if(!n){e.captures.delete(o);continue}n.bookmark=Ly(n.bookmark,r)}}}function zy(e,t){let r=e.trackedView;if(!r){e.restoreDispatch=()=>{};return}if(e.usesAppliedTransactionStream){e.restoreDispatch=()=>{};return}let o=r.dispatch.bind(r),n=(i=>{if(!i.docChanged)return o(i);let s=r.state.doc,a=e.pendingDispatchDocChange,l=new Map;e.pendingDispatchDocChange=!0;for(let c of e.captures){let d=t.get(c);if(!d){e.captures.delete(c);continue}l.set(c,{tracked:d,bookmark:d.bookmark}),d.bookmark=Ly(d.bookmark,i)}try{return o(i)}catch(c){if(r.state.doc===s){e.pendingDispatchDocChange=a;for(let[d,u]of l)t.get(d)===u.tracked&&(u.tracked.bookmark=u.bookmark)}throw c}});r.dispatch=n,e.restoreDispatch=()=>{r.dispatch===n&&(r.dispatch=o)}}function Hy(e,t,r){e.trackedView!==r.view&&(e.restoreDispatch(),e.trackedView=r.view,zy(e,t))}function Uu(e,t,r,o,n={}){if(!fj(o))return null;let i=e.get(o);if(i)return Hy(i,t,o),i;let s=o.subscribeTransactions?.bind(o)??null,a={captures:new Set,lastDocument:o.document,pendingDispatchDocChange:!1,programmaticDocChangeDepth:0,trackedView:o.view,usesAppliedTransactionStream:s!=null,restoreDispatch(){},unsubscribe(){},unsubscribeTransactions(){}};return s&&(a.unsubscribeTransactions=s(l=>{wj(a,t,l)})),zy(a,t),a.unsubscribe=o.subscribe(()=>{let l=o.document;if(l!==a.lastDocument){if(!a.pendingDispatchDocChange)if(a.programmaticDocChangeDepth===0)Fy(t,r,a);else{let c=[];for(let d of a.captures){let u=t.get(d);if(!u){c.push(d);continue}let m=n.resolveProgrammaticSelection?.(o,d)??cr(o,d);if(!m){c.push(d);continue}u.bookmark=Gu(m)}for(let d of c)r.add(d),t.delete(d),a.captures.delete(d)}a.pendingDispatchDocChange=!1,a.lastDocument=l}}),e.set(o,a),a}function Zu(e,t,r,o,n=!0){let i=e.get(o);i&&(i.unsubscribe(),i.unsubscribeTransactions(),i.restoreDispatch(),i.trackedView=null,n?Fy(t,r,i):i.captures.clear(),e.delete(o))}function gj(e,t,r,o={}){let n=Wy(e,t,r,o);return n?Ht(n):null}function Sj(e,t){if(!t.bookmark)return null;try{let r=t.bookmark.resolve(e.state.doc);return!r||!t.empty&&r.empty?null:r}catch{return null}}function qy(e,t,r,o={}){let n=Sj(e,r),i=n?at(e.state,n):null,s=jy({surface:e,selection:i,capture:t,resolveSemanticSelection:()=>o.resolveProgrammaticSelection?.(e,t)??cr(e,t)});if(s===i)return i;if(!s)return null;let a=at(e.state,s);return a?i&&qt(i,a)?i:(r.bookmark=Gu(a),a):null}function Wy(e,t,r,o={}){let n=qy(e,t,r,o);return n?Al(e.state,n):null}function Ky(e={}){let t=new Map,r=new Map,o=new WeakMap,n=new WeakSet,i=(a,l)=>{if(n.has(l))return!1;let c=o.get(l),d=mj(a.document);return bl(l.storyOriginPath,d)?l.documentIdentity!=null?l.documentIdentity===jn(a.document)&&l.documentHash===Oo(a.document):c?c.surface===a&&c.document===a.document:l.storyOriginPath!=null&&bl(l.storyOriginPath,d):!1},s=a=>{Zu(t,r,n,a)};return{clear(){for(let a of[...t.keys()])s(a);r.clear()},isTracked(a,l){return!l||n.has(l)?!1:r.get(l)?.surface===a},releaseSurface:s,transferSurface(a,l){if(a===l)return!0;let c=t.get(a);if(!c||c.captures.size===0)return Zu(t,r,n,a,!1),!0;let d=Uu(t,r,n,l,e);if(!d)return!1;for(let u of c.captures){let m=r.get(u);m&&(m.surface=l,o.set(u,{surface:l,document:l.document}),n.delete(u),d.captures.delete(u),d.captures.add(u))}return Vy(r,d),Zu(t,r,n,a,!1),!0},runWithProgrammaticDocumentChange(a,l){let c=Uu(t,r,n,a,e);if(!c)return l();c.programmaticDocChangeDepth+=1;try{return l()}finally{c.programmaticDocChangeDepth>0&&(c.programmaticDocChangeDepth-=1),Hy(c,r,a)}},untrack(a){if(!a)return;let l=r.get(a);l&&(t.get(l.surface)?.captures.delete(a),r.delete(a))},resolveSelection(a,l){if(!l)return null;let c=r.get(l);return!c||c.surface!==a?i(a,l)?cr(a,l):null:qy(a,l,c,e)},resolveState(a,l){if(!l)return null;let c=r.get(l);if(!c||c.surface!==a){if(!i(a,l))return null;let d=cr(a,l);return d?Al(a.state,d):null}return Wy(a,l,c,e)},resolveTarget(a,l){if(!l)return null;let c=l.target??l.selectionTarget;if(!c)return null;let d=r.get(l);return!d||d.surface!==a?i(a,l)?c:null:gj(a,l,d,e)},track(a,l,c){if(!c)return c;o.set(c,{surface:a,document:a.document}),n.delete(c);let d=Uu(t,r,n,a,e);if(!d)return c;let u=r.get(c);return u&&u.surface!==a&&t.get(u.surface)?.captures.delete(c),r.set(c,{surface:a,bookmark:Gu(l.selection),empty:c.selection.empty}),d.captures.delete(c),d.captures.add(c),Vy(r,d),c}}}function _y(e,t){return Object.freeze({id:e,kind:t})}function Uy(e){let{captureCurrentSelectionFromState:t,getSurface:r,readSelectionCapture:o,selectionCaptureTracker:n}=e,i=new WeakMap,s=new Map,a=1,l=(c,d)=>{if(!d)return null;let u=_y(a,c);return a+=1,i.set(u,d),s.set(d,(s.get(d)??0)+1),u};return{clear(){for(let c of s.keys())n.untrack(c);i=new WeakMap,s=new Map},capture:l,captureFromCapture(c){if(!c)return null;let d=n.resolveState(r(),c);return d?l("current",t(d)):null},resolve(c,d={}){return c?o(i.get(c)??null,d):null},peek(c){return c?i.get(c)??null:null},release(c){if(!c)return;let d=i.get(c)??null;if(i.delete(c),d){let u=(s.get(d)??0)-1;u>0?s.set(d,u):(s.delete(d),n.untrack(d))}}}}function Zy(e,t,r){return t.resolveSelection(e(),r)}function Gy(e){let{getSurface:t,selectionCaptureTracker:r,captureSelection:o,captureEffectiveSelection:n,captureCurrentSelectionFromState:i,readSelectionCapture:s}=e,a=Uy({getSurface:t,selectionCaptureTracker:r,captureCurrentSelectionFromState:i,readSelectionCapture:s});return{clearDeferredSelectionState(){r.clear(),a.clear()},captureSelectionHandle(l={}){return a.capture("current",o(l))},captureEffectiveSelectionHandle(l={}){return a.capture("effective",n(l))},captureSelectionHandleFromCapture(l){return a.captureFromCapture(l)},resolveSelectionHandle(l,c={}){return a.resolve(l,c)},restoreSelectionCapture(l,c={}){return Tl({surface:t(),capture:l,resolveSelection:d=>Zy(t,r,d),options:{...c,validateDocumentIdentity:!1}})},restoreSelectionHandle(l,c={}){return Tl({surface:t(),capture:a.peek(l),resolveSelection:d=>Zy(t,r,d),options:{...c,validateText:!1,validateDocumentIdentity:!1}})},releaseSelectionHandle(l){a.release(l)},runAndEmit(l,c,d){let u=c(),m=r.runWithProgrammaticDocumentChange(t(),l);return c()===u&&d(),m}}}function Xy(e,t,r,o,n,i,s,a,l,c,d,u,m){let p=Qt(n),f=ES(i,s),g=mo(r,e,p.comments,o),v=As(c,e.trackingEnabled),k=Jr(d),R=dt(u)??"vertical",h=ZS(p,f,l??!0,r,g,v,k,dr(R,k),R,e.document,a??null),B=()=>Qh(s),S=Ky({resolveProgrammaticSelection(_,Se){if(Se.projectedMode!=null&&Se.selectionTarget){let Fe=F(),Qe=ut({state:_.state,target:Se.selectionTarget,projectionSnapshot:{canonicalDocument:Fe.canonicalDocument,projectedMode:Fe.projectedMode},sourceMode:Se.projectedMode,revisions:Fe.canonicalReviewRuntime.documentApi.review.list(),expectedText:Se.text??null});if(Qe&&Se.selectionKind==="text")return Z(_.state,Qe.selection.from,Qe.selection.to)}return null}}),b=vy(_=>S.untrack(_)),P=Dy({context:h,allowCollaborativeProjection:B,releaseContextMenuCaptures:()=>b.releaseContextMenuCaptures(h.contextMenu)}),A=Oy({setState:_=>{h.linkPopover=_},closeState:P.closeLinkPopover,clearOverlayState:P.clearEphemeralOverlays,untrackCapture:b.untrackCapture}),O=ay({getController:m,getDocumentMode:()=>h.documentMode,getRuntime:()=>X(h),getResolvedModules:()=>h.resolvedModules,captureSelectionFromState:_=>x(_),setLinkPopover:A.set,closeContextMenu:P.closeContextMenu,closeLinkPopover:A.close,emit:P.emit}),j=ly({getController:m,getDocumentMode:()=>h.documentMode,getResolvedModules:()=>h.resolvedModules,readTrackChangesDisplayState:()=>P.readCurrentDisplayState().trackChanges,captureEffectiveSelectionFromState:_=>M(_,{includeText:!0}),setContextMenu:_=>{b.releaseContextMenuCaptures(h.contextMenu,_),h.contextMenu=_},closeContextMenu:P.closeContextMenu,closeLinkPopover:A.close,emit:P.emit}),K=wy({context:h,templates:t,ownsSurface:i,surfaceFactory:s,allowCollaborativeProjection:B,emit:P.emit,readCurrentDisplayState:P.readCurrentDisplayState,clearEphemeralOverlays:A.clearOverlays,handleLinkClick:O,handleContextMenu:j}),F=()=>Or(h.readModel,P.readCurrentDisplayState().trackChanges.mode),se=()=>{let _=X(h).surface;S.runWithProgrammaticDocumentChange(_,()=>K.applySurfaceDisplayState());let Se=X(h).surface;_!==Se&&!S.transferSurface(_,Se)&&Tt();let Fe=P.readCurrentDisplayState();if(Ia({surface:X(h).surface,documentMode:h.documentMode,allowSelectionInViewMode:h.allowSelectionInViewMode}),h.documentMode==="viewing"&&Fe.trackChanges.enabled&&Fe.trackChanges.mode==="review"){let Qe=F();ba({surface:X(h).surface,canonicalReviewApi:Qe.canonicalReviewRuntime.documentApi,canonicalDocument:Qe.canonicalDocument,projectedMode:Qe.projectedMode})}},E=Ku({getRuntime:()=>X(h),hasSourceRuntime:()=>h.readModel.sourceRuntime!=null,readProjectionSnapshot:F,readCurrentDisplayState:P.readCurrentDisplayState,readEffectiveSelection:_=>y(_),captureEffectiveSelection:_=>ne(_),subscribeStateChange:_=>{let Se=()=>_();return h.listeners.add(Se),()=>{h.listeners.delete(Se)}}}),N=dy({context:h,readProjectionSnapshot:F,readState:P.readState,selectionCaptureTracker:S}),{captureSelection:L,captureEffectiveSelection:ne,readEffectiveSelection:y,captureCurrentSelectionFromState:x,captureEffectiveSelectionFromState:M,readSelectionCapture:I,resolveSelectionCapture:U}=N,xe=_=>U(_,{includeText:!0}),me=_=>I(_,{includeText:!0});h.normalizeOverlayState=()=>{let _=A.sync(me),Se=h.contextMenu;if(!Se)return _;let Fe=X(h),Qe=F(),Vi=Qe.canonicalReviewRuntime.documentApi.review.list(),Li=hy({surface:Fe.surface,selectionInfo:Dr(Fe.surface,{includeText:!0},Fe.replacementMode),projectionSnapshot:Qe,revisions:Vi}),Fi=gy({currentState:Se,controller:m(),documentMode:h.documentMode,contextMenuOptions:h.resolvedModules.contextMenu,reviewActionsEnabled:P.readCurrentDisplayState().trackChanges.enabled,revisions:Vi,liveSelection:Li.selection,liveSelectionInfo:Li.selectionInfo,resolveSelectionCapture:xe,resolveSelectionState:zi=>S.resolveState(Fe.surface,zi)});return b.releaseContextMenuCaptures(Se,Fi),h.contextMenu=Fi,!0};let Ke=Gy({getSurface:()=>X(h).surface,selectionCaptureTracker:S,captureSelection:L,captureEffectiveSelection:ne,captureCurrentSelectionFromState:x,readSelectionCapture:I}),{clearDeferredSelectionState:Tt,captureSelectionHandle:Ye,captureEffectiveSelectionHandle:Ce,captureSelectionHandleFromCapture:mt,resolveSelectionHandle:hr,restoreSelectionCapture:jt,restoreSelectionHandle:vo,releaseSelectionHandle:Vt}=Ke,Lt=_=>Ke.runAndEmit(_,P.getEmissionVersion,P.emit),yr=ry({getRuntime:()=>X(h),runAndEmit:Lt,readState:()=>P.readState(),clearPreservedRangeSelection:()=>{h.preservedRangeSelection=null}}),V=()=>Es({editable:X(h).surface.editable,document:X(h).surface.document,commentsDisplay:P.readCurrentDisplayState().comments}),Je=()=>Jt(X(h).surface);return K.mountSourceRuntime(e),P.subscribeCollaborationSession(h.collaborationSession),se(),{context:h,permissionResolver:o,stateRuntime:P,lifecycle:K,selectionRuntime:N,linkPopoverRuntime:A,advancedOoxmlMethods:yr,publicDocumentApi:E,commentWriteReason:V,reviewWriteReason:Je,applySurfaceDisplayState:se,clearDeferredSelectionState:Tt,selectionCaptureTracker:S,captureCurrentSelectionFromState:x,runAndEmit:Lt,captureSelectionHandle:Ye,captureEffectiveSelectionHandle:Ce,captureSelectionHandleFromCapture:mt,resolveSelectionHandle:hr,restoreSelectionCapture:jt,restoreSelectionHandle:vo,releaseSelectionHandle:Vt}}function ji(e,t,r,o,n,i,s,a,l,c,d,u){let m,p=Xy(e,t,r,o,n,i,s,a,l,c,d,u,()=>m),{context:f,permissionResolver:g,stateRuntime:v,lifecycle:k,selectionRuntime:R,linkPopoverRuntime:h,advancedOoxmlMethods:B,publicDocumentApi:S,commentWriteReason:b,reviewWriteReason:P,applySurfaceDisplayState:A,clearDeferredSelectionState:O,selectionCaptureTracker:j,captureCurrentSelectionFromState:K,runAndEmit:F,captureSelectionHandle:se,captureEffectiveSelectionHandle:E,captureSelectionHandleFromCapture:N,resolveSelectionHandle:L,restoreSelectionCapture:ne,restoreSelectionHandle:y,releaseSelectionHandle:x}=p,M=g,I=()=>Or(f.readModel,v.readCurrentDisplayState().trackChanges.mode),U=!1,{captureSelection:xe,captureEffectiveSelection:me,readEffectiveSelection:Ke,capturePointSelection:Tt,readPointSelection:Ye,readSelectionCapture:Ce,resolveSelectionCapture:mt}=R,hr=GS({context:f,permissionResolver:M,getSurface:()=>X(f).surface,readState:v.readState,runBatchedEmit:v.runBatchedEmit,clearEphemeralOverlays:h.clearOverlays,applySurfaceDisplayState:A,emit:v.emit}),jt=qS({reconfigurable:f.reconfigurable,getRuntime:()=>X(f),getSourceRuntime:()=>Ie(f),getCurrentActor:()=>f.currentActor,getCollaborationSession:()=>f.collaborationSession,readCollaboration:v.readCollaboration,readCommentResolveState:()=>v.readCurrentDisplayState().comments,commentWriteReason:b,reviewWriteReason:P,createReplacementSurface:k.createReplacementSurface,swapSurface:(V,Je)=>{let _=f.preservedRangeSelection,Se=X(f).surface;f.collaborationSession=Je,v.subscribeCollaborationSession(f.collaborationSession),k.swapSurface(V,Je);let Fe=X(f).surface;j.transferSurface(Se,Fe)||O(),f.currentActor=mo(f.actorInput,Fe,f.resolvedModules.comments,M),f.preservedRangeSelection??=_},emit:v.emit,runAndEmit:F,readEffectiveSelection:Ke,captureEffectiveSelection:me,readSelectionCapture:Ce,resolveSelectionCapture:mt,resolveSelectionHandle:L,resolveCommentTargetFromCapture:V=>{if(!V)return null;let Je=Nr(V)?V.selectionTarget:null,_=V.target??Je;if(!_)return null;if(!Nr(V))return _;let Se=X(f),Fe=j.resolveTarget(Se.surface,V),Qe=Ce(V,{includeText:!0}),Vi=Qe?.target??Qe?.selectionTarget??Fe,Li=j.isTracked(Se.surface,V),Fi="segments"in _?(()=>{let zi=Q(Se.surface.state.doc,_,{strict:!0});return zi?ge(Se.surface.state.doc,Se.surface.state.schema,zi):null})():null;return YS({captureTarget:_,captureText:V.text,originalTargetText:Fi,resolvedTarget:Vi,resolvedText:Qe?.text??null,captureStillTracked:Li})},getPresentationReadApi:()=>I().presentationReadRuntime.documentApi,getWritableRuntimeApi:()=>I().writableRuntime.documentApi,getSearchQuery:()=>f.searchQuery,setSearchQuery:V=>{f.searchQuery=V},getSearchOptions:()=>f.searchOptions,setSearchOptions:V=>{f.searchOptions=V},getActiveSearchHitId:()=>f.activeSearchHitId,setActiveSearchHitId:V=>{f.activeSearchHitId=V},getActiveCommentId:()=>v.readState().activeCommentId??null,setActiveCommentId:V=>{f.activeCommentId=V},readVisibleComments:()=>v.readState().comments,getActiveRevisionId:()=>v.readState().activeRevisionId??null,setActiveRevisionIds:V=>{f.activeRevisionIds=[...V],f.activeRevisionId=V.length===1?V[0]??null:null},getLinkPopover:()=>f.linkPopover,getLinkPopoverSelectionCapture:h.getSelectionCapture,setLinkPopover:h.set,closeLinkPopover:h.close,clearPreservedRangeSelection:()=>{f.preservedRangeSelection=null}}),vo=rv({context:f,emit:v.emit,getEmissionVersion:v.getEmissionVersion,applySurfaceDisplayState:A}),Vt,Lt;m={get surface(){return X(f).surface},get documentService(){return X(f).documentService},get documentApi(){return S},get editorHost(){return Vt},get editor(){return Lt},get modules(){return Qt(f.resolvedModules)},get actor(){return aa(f.currentActor)},get collaboration(){return fd(v.readCollaboration())},getState(){return v.readState()},getCollaborationState(){return fd(v.readCollaboration())},...hr,...vo,setActor(V){f.actorInput=V,f.currentActor=mo(f.actorInput,X(f).surface,f.resolvedModules.comments,M),v.emit()},setParticipant(V){f.currentActor=sd(f.actorInput,V,f.resolvedModules.comments,M);let Je=Ie(f),_=f.readModel.activeRuntime;_&&_.surface!==Je.surface&&_.surface.setParticipant(V),Je.surface.setParticipant(V)},subscribe(V){f.listeners.add(V);try{U||V(v.readState())}catch(Je){throw f.listeners.delete(V),Je}return()=>f.listeners.delete(V)},captureSelection:xe,captureEffectiveSelection:me,readEffectiveSelection:Ke,readSelectionCapture:Ce,captureSelectionHandle:se,captureEffectiveSelectionHandle:E,captureSelectionHandleFromCapture:N,resolveSelectionCapture:mt,resolveSelectionHandle:L,restoreSelectionCapture:ne,restoreSelectionHandle:y,releaseSelectionHandle:x,capturePointSelection(V){return!V||typeof V!="object"||typeof V.clientX!="number"||typeof V.clientY!="number"?null:Tt(V)},readPointSelection(V){return!V||typeof V!="object"||typeof V.clientX!="number"||typeof V.clientY!="number"?null:Ye(V)},...jt,...B,closeLinkPopover:h.close,closeContextMenu:v.closeContextMenu,destroy(){if(U)return;U=!0,O(),f.unsubscribeCollaborationSession?.(),f.unsubscribeCollaborationSession=null,f.listeners.clear(),Lt.destroy(),k.destroyCollaborativeProjection();let V=i||!!s;k.unmountSourceRuntime(V),f.preservedRangeSelection=null,f.collaborationSession=null}};for(let V of["surface","documentService"])Object.defineProperty(m,V,{...Object.getOwnPropertyDescriptor(m,V),enumerable:!1});Vt=ci(m),Lt=vj(Vt);let yr=$s(()=>X(f).surface);return Object.defineProperty(m,Os,{value(V){if(!V||typeof V!="object"||typeof V.clientX!="number"||typeof V.clientY!="number")return null;let Je=dn({surface:X(f).surface,clientX:V.clientX,clientY:V.clientY,mode:"text-only"});return Je?K(Je.state,V):null}}),Object.defineProperties(m,{readLayoutAdapter:{configurable:!1,enumerable:!1,value:yr.readLayoutAdapter},readLayoutSource:{configurable:!1,enumerable:!1,value:yr.readLayoutSource},readDocumentSize:{configurable:!1,enumerable:!1,value:yr.readDocumentSize},selection:{configurable:!1,enumerable:!1,value:yr.selection}}),m}import{createDocumentFontCatalog as $y,createDocumentFontRegistrationManager as hj}from"@datalking/begonia-font-system";function Xu(e){return e.document.attrs.ooxmlPackageResources}function yj(e,t){let r=e.view?.dom;if(r?.querySelectorAll)for(let o of Array.from(r.querySelectorAll("[data-font-family], [data-font-family-resolved]"))){let n=o.getAttribute("data-font-family")??o.getAttribute("data-font-family-resolved");if(!n)continue;let i=t(n),s=o.style;s&&(s.fontFamily=i??n)}}function $u(e,t,r){let o=$y(Xu(t),"browser-document"),n=hj(r,o),i=Xu(t),s=!1,a=()=>{s||yj(e.surface,u=>n.catalog.resolveFamily(u))},l=()=>{if(s)return;let u=e.surface,m=Xu(u);m!==i&&(i=m,n.replace($y(m,"browser-document"))),a(),n.ready.then(a)},c=e.subscribe(l),d=e.destroy.bind(e);return Object.defineProperties(e,{documentFontCatalog:{configurable:!0,enumerable:!0,get:()=>n.catalog},documentFontsReady:{configurable:!0,enumerable:!0,get:()=>n.ready}}),e.destroy=()=>{s||(s=!0,c(),n.dispose(),d())},l(),e}function Yy(e,t){t.fitWidthOptions!==void 0&&e.setFitWidthOptions(t.fitWidthOptions),t.zoomMode&&e.setZoomMode(t.zoomMode);let r=ht(t.zoomPercent);return r!=null&&t.zoomMode!=="fit-width"&&r!==e.getZoomPercent()&&e.setViewState({zoomPercent:r}),e}function Bj(e,t={}){let r=Yy(ji(e,t.templates,t.actor,t.permissionResolver,t.modules,!1,t.surfaceFactory,t.collaborationSession,t.viewSelect,t.documentMode,t.flowMode,t.layoutMode),t);return $u(r,e,t.documentFontProvider)}function Yu(e){let t=e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:_i(e.features??[]),r=As(e.documentMode,e.trackingEnabled),o=an(r,e.modules?.trackChanges),{actor:n,templates:i,collaborationSession:s,documentMode:a,documentFontProvider:l,enableEmbeddedAdvancedOoxmlEditors:c,flowMode:d,layoutMode:u,zoomPercent:m,zoomMode:p,fitWidthOptions:f,modules:g,permissionResolver:v,surfaceFactory:k,viewSelect:R,...h}=e,B=bj({...h,collaborative:e.collaborationSession?.binding??e.collaborative,editable:ln(r),trackingEnabled:kr(r,o),features:t}),S=Yy(ji(B,e.templates,e.actor,e.permissionResolver,e.modules,!0,IS({...e,features:t}),e.collaborationSession,e.viewSelect,e.documentMode,e.flowMode,e.layoutMode),e);return $u(S,B,e.documentFontProvider)}import{DEFAULT_VIEWPORT_FIT_WIDTH_OPTIONS as L3,cloneViewportFitMetrics as F3,cloneViewportFitWidthOptions as z3,computeAppliedViewportFitZoom as H3,computeViewportFitZoom as q3,normalizeViewportFitMetrics as W3,normalizeViewportFitWidthOptions as xj,resolveViewportFitMetricsFromPreview as K3,sameViewportFitMetrics as _3,sameViewportFitWidthOptions as Cj}from"@datalking/begonia-layout-renderer/core";function Ju(e){return xj(e)}function Jy(e,t){return Cj(e,t)}var Pj=Object.freeze([]);function eb(e,t){return e.length===t.length&&e.every((r,o)=>Object.is(r,t[o]))}function Rj(e,t){return e===t?!0:!e||!t?e==null&&t==null:eb(e,t)}function tb(e,t){return e===t?!0:!e||!t?e==null&&t==null:(e.id??null)===(t.id??null)&&(e.name??null)===(t.name??null)&&(e.createdAt??null)===(t.createdAt??null)&&(e.role??null)===(t.role??null)&&(e.bypassPermissions??!1)===(t.bypassPermissions??!1)&&(e.canViewInternalComments??!1)===(t.canViewInternalComments??!1)&&(e.canToggleCommentVisibility??!1)===(t.canToggleCommentVisibility??!1)&&(e.permissionResolver??null)===(t.permissionResolver??null)&&(e.commentPermissionResolver??null)===(t.commentPermissionResolver??null)&&Rj(e.groups,t.groups)}function rb(e,t){return e.id===t.id&&e.name===t.name&&(e.color??null)===(t.color??null)}function Tj(e){return{...e}}function kj(e){return e?.length?[...e]:Pj}function Ej(e){return!e||typeof e!="object"?e:{...e}}function ob(e,t){return Jy(Ju(e),Ju(t))}function Qy(e){return{...e,collaborationSession:e.collaborationSession??null,enableEmbeddedAdvancedOoxmlEditors:e.enableEmbeddedAdvancedOoxmlEditors!==!1,...e.actor!==void 0?{actor:aa(e.actor??null)}:{},features:kj(e.features),...e.fitWidthOptions!==void 0?{fitWidthOptions:Ej(e.fitWidthOptions)}:{},...e.modules!==void 0?{modules:Qt(e.modules)}:{},participant:Tj(e.participant),trackingEnabled:e.trackingEnabled!==!1,viewSelect:e.viewSelect!==!1}}function nb(e,t){return e.room===t.room&&e.collaborative===t.collaborative&&e.collaborationSession===t.collaborationSession&&e.enableEmbeddedAdvancedOoxmlEditors===t.enableEmbeddedAdvancedOoxmlEditors&&eb(e.features,t.features)&&e.initialContent===t.initialContent&&e.schema===t.schema&&e.permissionResolver===t.permissionResolver&&e.surfaceFactory===t.surfaceFactory&&e.trackingEnabled===t.trackingEnabled&&e.viewSelect===t.viewSelect}function Mj(e,t){return tb(e.actor,t.actor)&&nb(e,t)&&e.documentMode===t.documentMode&&e.flowMode===t.flowMode&&e.layoutMode===t.layoutMode&&id(e.modules,t.modules)&&e.onTransaction===t.onTransaction&&e.onUpdate===t.onUpdate&&rb(e.participant,t.participant)&&e.zoomMode===t.zoomMode&&ob(e.fitWidthOptions,t.fitWidthOptions)&&e.zoomPercent===t.zoomPercent}function Ij(e,t){return e.controller===t.controller&&e.state===t.state}function Qu(e){return{controller:e.controller,state:e.state}}function Aj(e,t,r){let{room:o,...n}=e;return{...n,collaborative:e.collaborationSession?.binding??e.collaborative??e.room,element:t,onTransaction:r.onTransaction,onUpdate:r.onUpdate}}function Nj(e){let{controller:t,previous:r,next:o}=e;tb(r.actor,o.actor)||t.setActor(o.actor??null),rb(r.participant,o.participant)||t.setParticipant(o.participant),r.documentMode!==o.documentMode&&o.documentMode!=null&&t.setDocumentMode(o.documentMode),id(r.modules,o.modules)||t.setModules(o.modules),r.zoomMode!==o.zoomMode&&o.zoomMode!=null&&t.setZoomMode(o.zoomMode),!ob(r.fitWidthOptions,o.fitWidthOptions)&&o.fitWidthOptions!==void 0&&t.setFitWidthOptions(o.fitWidthOptions);let n={...r.flowMode!==o.flowMode&&o.flowMode?{flowMode:o.flowMode}:{},...r.layoutMode!==o.layoutMode&&o.layoutMode?{layoutMode:o.layoutMode}:{},...r.zoomPercent!==o.zoomPercent&&o.zoomPercent!=null&&o.zoomMode!=="fit-width"?{zoomPercent:o.zoomPercent}:{}};Object.keys(n).length>0&&t.setViewState(n)}function em(e,t={}){let r=new Set,o=t.createEditor??Yu,n={destroyed:!1,host:null,input:Qy(e),controller:null,state:null,unsubscribeController:null,snapshot:{controller:null,state:null}},i=()=>{let c={controller:n.controller,state:n.state};if(!Ij(n.snapshot,c)){n.snapshot=c;for(let d of[...r])d(Qu(c))}},s=()=>{let c=n.controller,d=n.unsubscribeController;n.unsubscribeController=null,n.controller=null,n.state=null,i(),d?.(),c&&c.destroy()},a=()=>{if(!n.host)return;let c=o(Aj(n.input,n.host,{onTransaction(d){n.input.onTransaction?.(d)},onUpdate(){n.input.onUpdate?.()}}));n.controller=c,n.state=c.getState(),i(),n.unsubscribeController=c.subscribe(d=>{n.controller===c&&(n.state=d,i())})},l=()=>{s(),a()};return{getSnapshot(){return Qu(n.snapshot)},subscribe(c){return r.add(c),c(Qu(n.snapshot)),()=>{r.delete(c)}},setHost(c){if(!(n.destroyed||n.host===c)){if(n.host=c,!c){s();return}if(!n.controller){a();return}l()}},setInput(c){if(n.destroyed)return;let d=n.input,u=Qy(c);if(n.input=u,Mj(d,u)||!n.host)return;let m=!nb(d,u);if(!n.controller||m){l();return}Nj({controller:n.controller,previous:d,next:u})},destroy(){n.destroyed||(n.destroyed=!0,n.host=null,s(),r.clear())}}}function Dj(){return{ui:null,host:null,snapshot:null}}function sb(e){hS(e.host,e.ui),e.ui?.destroy(),e.controller=null,e.host=null,e.ui=null}function Oj(e,t){if(e.controller===t||(sb(e),!t))return;let r=hn(t);e.controller=t,e.host=r,e.ui=ks(r);let o=wr(r);o&&Ys(r,e.ui,o)}function ib(e,t){return Oj(e,t.controller),{ui:e.ui,host:e.host,snapshot:t.state?cn(t.state):null}}function jj(e){let t=em(e),r=new Set,o={controller:null,host:null,ui:null},n=ib(o,t.getSnapshot()),i=t.subscribe(s=>{n=ib(o,s);for(let a of[...r])a(n)});return{getSnapshot(){return n},subscribe(s){return r.add(s),s(n),()=>{r.delete(s)}},setHost(s){t.setHost(s)},setInput(s){t.setInput(s)},destroy(){i(),r.clear(),sb(o),t.destroy(),n=Dj()}}}function Vj(){return{createMount(e){return jj(e)}}}function Lj(e){return Js(e)}import{collectOoxmlMathStructures as Fj,countOoxmlChartCategories as zj,normalizeOoxmlChartModel as Hj,normalizeOoxmlMathModel as qj,normalizeOoxmlShapeModel as Wj}from"@datalking/begonia-engine";function Aa(e){return e.trackingEnabled??e.toolbar?.trackingEnabled??!1}function Na(e){return e.documentMode==="editing"||e.documentMode==="suggesting"||e.documentMode==="viewing"?e.documentMode:"editing"}function Kj(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="math")return null;let r=qj(t.familyData??{plainText:t.text,displayMode:"inline"},t.text,"inline");return{family:"math",record:t,model:r,plainText:t.familyData?.plainText??t.text,displayMode:r.displayMode,structures:t.familyData?.structures?.length?t.familyData.structures:Fj(r),trackingEnabled:Aa(e),documentMode:Na(e)}}function _j(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="chart")return null;let r=Hj(t.familyData?.model??t.familyData??{title:t.label,textBody:{plainText:t.text}},t.label);return{family:"chart",record:t,model:r,series:r.series,seriesCount:r.series.length,categoryCount:zj(r),trackingEnabled:Aa(e),documentMode:Na(e)}}function Uj(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="shape")return null;let r=Wj(t.familyData?.model??t.familyData??{label:t.label,textBody:t.text?{plainText:t.text,paragraphs:[t.text]}:null},t.label);return{family:"shape",record:t,model:r,trackingEnabled:Aa(e),documentMode:Na(e)}}function tm(e="editing",t=!1){return{selected:null,documentMode:e,trackingEnabled:t}}function ab(e){return{selected:Kj(e)??_j(e)??Uj(e),trackingEnabled:Aa(e),documentMode:Na(e)}}function Da(e){return structuredClone(e)}function ee(e){return{changed:!1,reason:e}}function Zj(e){let t=e,r=he(t),o=wr(t),n=yS(t),i=o?.controller.documentApi??{},s=()=>{let m=o?.controller.getState();return m?ab(m):tm()},a=s(),l=new Set,c=()=>{a=s();for(let m of[...l])m(Da(a))},d=r?.session.subscribe(()=>c())??(()=>{}),u="Advanced OOXML editing requires a mounted browser editor backend.";return{actor:o?.controller.actor??null,documentApi:i,getSnapshot(){return a=s(),Da(a)},subscribe(m){return l.add(m),m(Da(a)),()=>{l.delete(m)}},replaceSelectedMathModel(m){return n?n.replaceSelectedMathModel(m):ee(u)},setSelectedMathPlainText(m,p){return n?n.setSelectedMathPlainText(m,p):ee(u)},setSelectedMathDisplayMode(m){return n?n.setSelectedMathDisplayMode(m):ee(u)},replaceSelectedChartModel(m){return n?n.replaceSelectedChartModel(m):ee(u)},setSelectedChartMetadata(m){return n?n.setSelectedChartMetadata(m):ee(u)},appendSelectedChartSeries(m){return n?n.appendSelectedChartSeries(m):ee(u)},setSelectedChartSeriesList(m){return n?n.setSelectedChartSeriesList(m):ee(u)},setSelectedChartTitle(m){return n?n.setSelectedChartTitle(m):ee(u)},setSelectedChartTextBody(m){return n?n.setSelectedChartTextBody(m):ee(u)},setSelectedChartSeries(m,p){return n?n.setSelectedChartSeries(m,p):ee(u)},upsertSelectedChartSeries(m,p){return n?n.upsertSelectedChartSeries(m,p):ee(u)},removeSelectedChartSeries(m){return n?n.removeSelectedChartSeries(m):ee(u)},appendSelectedChartAxis(m){return n?n.appendSelectedChartAxis(m):ee(u)},setSelectedChartAxes(m){return n?n.setSelectedChartAxes(m):ee(u)},upsertSelectedChartAxis(m,p){return n?n.upsertSelectedChartAxis(m,p):ee(u)},removeSelectedChartAxis(m){return n?n.removeSelectedChartAxis(m):ee(u)},setSelectedChartLegend(m){return n?n.setSelectedChartLegend(m):ee(u)},setSelectedChartPlotArea(m){return n?n.setSelectedChartPlotArea(m):ee(u)},replaceSelectedShapeModel(m){return n?n.replaceSelectedShapeModel(m):ee(u)},setSelectedShapeMetadata(m){return n?n.setSelectedShapeMetadata(m):ee(u)},setSelectedShapeWatermark(m){return n?n.setSelectedShapeWatermark(m):ee(u)},setSelectedShapeTextBody(m){return n?n.setSelectedShapeTextBody(m):ee(u)},setSelectedShapeGeometry(m){return n?n.setSelectedShapeGeometry(m):ee(u)},setSelectedShapeTransform(m){return n?n.setSelectedShapeTransform(m):ee(u)},setSelectedShapeFill(m){return n?n.setSelectedShapeFill(m):ee(u)},setSelectedShapeStroke(m){return n?n.setSelectedShapeStroke(m):ee(u)},setSelectedShapeAnchor(m){return n?n.setSelectedShapeAnchor(m):ee(u)},setSelectedShapeConnector(m){return n?n.setSelectedShapeConnector(m):ee(u)},setSelectedShapePicture(m){return n?n.setSelectedShapePicture(m):ee(u)},setSelectedShapeWordArt(m){return n?n.setSelectedShapeWordArt(m):ee(u)},setSelectedShapeChildren(m){return n?n.setSelectedShapeChildren(m):ee(u)},setSelectedShapeChild(m,p){return n?n.setSelectedShapeChild(m,p):ee(u)},appendSelectedShapeChild(m){return n?n.appendSelectedShapeChild(m):ee(u)},appendSelectedShapeChildToParent(m,p){return n?n.appendSelectedShapeChildToParent(m,p):ee(u)},moveSelectedShapeChild(m,p){return n?n.moveSelectedShapeChild(m,p):ee(u)},removeSelectedShapeChild(m){return n?n.removeSelectedShapeChild(m):ee(u)},removeSelected(){return n?n.removeSelectedAdvancedOoxml():ee(u)},destroy(){d(),l.clear(),a=tm()}}}function lb(e){return e?.selection??null}function Gj(e){return lb(e.editor)?.resolvePositionHitEvent?.(e)??e.event}function Xj(e){let t=lb(e.editor);if(!t?.handlePositionHit)return!1;let r=t.resolvePositionHitEvent?.(e)??e.event;return t.handlePositionHit({...e,event:r})}function cb(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function db(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function ub(e){return e==="web"||e==="paginated"?e:null}function mb(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function v7(e){return e.previousEditor!==e.nextEditor?"editor-instance":e.previousPreviewSourceIdentity!==e.previewSourceIdentity?"preview-source":db(e.previousControllerNavigationMode)!==db(e.controllerNavigationMode)?"controller-navigation-mode":ub(e.previousFlowMode)!==ub(e.flowMode)||mb(e.previousLayoutMode)!==mb(e.layoutMode)?"preview-mode":e.previousSyncViewportToEditor!==e.syncViewportToEditor?"sync-viewport-toggle":cb(e.previousExplicitAnchorPageNumber)!==cb(e.explicitAnchorPageNumber)?"explicit-anchor":null}import{resolveProjectionSelectionPageIndexes as $j}from"@datalking/begonia-page-layout";function rm(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>0?t:null}function Yj(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.trunc(e)):null}function fb(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>=0?t:null}function Jj(e,t){if(!e||typeof e!="object")return t;let r=e,o=rm(r.pageNumber),n=fb(r.pageIndex);return o!=null&&n!=null&&n!==o-1?null:o??(n!=null?n+1:t)}function Qj(e){if(!e||typeof e!="object")return null;let t=rm(e.anchorPageNumber),r=e.viewportAnchor==null?t:Jj(e.viewportAnchor,t);return e.viewportAnchor!=null&&r==null||t!=null&&r!=null&&r!==t?null:t??r}function Tn(e,t){let r=new Set([...e].map(o=>rm(o)).filter(o=>o!=null));return!t||t.length===0?[...r].sort((o,n)=>o-n):t.filter(o=>r.has(o))}function pb(e,t){if(!t||t.length===0)return[];let r=new Map(t.map((o,n)=>[o,n]));return Tn(e??[],t).flatMap(o=>{let n=r.get(o);return n==null?[]:[n]})}function eV(e,t){return Tn(e.flatMap(r=>{let o=fb(r),n=o==null?null:t[o]??null;return n==null?[]:[n]}),t)}function b7(e){let t=e.projection?.pages.map(s=>s.pageNumber)??null,r=Tn(e.selectionPageNumbers??[],t),o=new Set(Tn(e.pinnedPageNumbers??[],t));for(let s of r)o.add(s);if(!e.projection||e.sourceMatchesEditorDocument===!1){let s=Tn(o,t);return s.length>0?s:void 0}let n=Qj(e.previewNavigationRequest),i=r.length>0?Tn(n==null?o:[...o,n],t):eV($j(e.projection,e.selection,{docSize:Yj(e.documentSize),preferredPageIndexes:pb(e.pinnedPageNumbers,t),extraPageIndexes:n==null?[]:pb([n],t)}),t??[]);return i.length>0?i:void 0}function tV(e){let t=Cg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,e.syncViewportToEditor?e.lastAppliedViewport??null:e.trackingState.editorViewport,e.trackingState.editorViewportRequestKey,e.modeOptions);return t?{viewport:t,cause:"controller-viewport-request"}:null}function om(e,t){return t?wb({editorViewport:null,editorViewportRequestKey:null,previewNavigationRequestKey:null,previewNavigationRequest:null},e,t):{editorViewport:re(e?.viewport??null),editorViewportRequestKey:De(e?.viewportRequestKey??null),previewNavigationRequestKey:De(e?.previewNavigationRequest?.requestKey??null),previewNavigationRequest:be(e?.previewNavigationRequest??null)}}function wb(e,t,r){let o=Bt(t,r),n=xt(t,r),i=t?.viewport!=null,s=t?.previewNavigationRequest!=null;return{editorViewport:o?re(o):i?re(e.editorViewport):null,editorViewportRequestKey:o?De(t?.viewportRequestKey??null):i?De(e.editorViewportRequestKey):null,previewNavigationRequestKey:n?De(n.requestKey):s?De(e.previewNavigationRequestKey):null,previewNavigationRequest:n?be(n):s?be(e.previewNavigationRequest):null}}function gb(e){let t=xt(e.editorState,e.modeOptions),r=Bg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,Mr(t,e.trackingState.previewNavigationRequest)?e.trackingState.previewNavigationRequestKey:null,e.modeOptions),o=tV(e),n=o?.viewport??null,i=wb(e.trackingState,e.editorState,e.modeOptions);return n&&(i.editorViewport=re(n),i.editorViewportRequestKey=De(e.editorState?.viewportRequestKey??null)),{previewNavigationRequest:r,externalViewportRequest:n,resetCause:r?"preview-navigation-request":o?.cause??null,shouldResetViewport:r!=null||n!=null,nextTrackingState:i}}function rV(e){let t=Ic(e.editorState,e.explicitFlowMode),r=Eg(e.editorState,e.explicitLayoutMode,t);return{flowMode:t,layoutMode:r}}function M7(e){let t=rV(e),{flowMode:r,layoutMode:o}=t;return{scale:Pg(e.editorState,e.explicitScale),flowMode:r,layoutMode:o,modeOptions:t,anchorPageNumber:Rg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),initialViewportAnchor:Tg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),viewportRequestKey:kg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),acknowledgementRequestKey:xg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t)}}function Sb(e){if(!e.syncViewportToEditor)return null;let t=Yt(e.viewport,{flowMode:e.controllerFlowMode,layoutMode:e.controllerLayoutMode});if(!t||e.controllerFlowMode&&!_o(t,e.controllerFlowMode)||e.controllerLayoutMode&&!Uo(t,e.controllerLayoutMode)||e.controllerFlowMode&&e.controllerLayoutMode&&!to(t,e.controllerFlowMode,e.controllerLayoutMode))return null;let r=e.controllerFlowMode??t.flowMode,o=e.controllerLayoutMode??t.layoutMode,n=Yt(e.lastAppliedViewport,{flowMode:r,layoutMode:o}),i=Yt(e.controllerViewport,{flowMode:r,layoutMode:o});return Kn(t,n)||Kn(t,i)?null:t}function vb(e){return e?{requestKey:e.requestKey,viewportResetVersion:e.viewportResetVersion}:null}function oV(e,t){return e?.requestKey===t?.requestKey&&e?.viewportResetVersion===t?.viewportResetVersion}function nV(e,t){return ot(e.editorViewport,t.editorViewport)&&e.editorViewportRequestKey===t.editorViewportRequestKey&&e.previewNavigationRequestKey===t.previewNavigationRequestKey&&Mr(e.previewNavigationRequest,t.previewNavigationRequest)}function hb(e,t){return e.viewportHydrated===t.viewportHydrated&&e.viewportResetVersion===t.viewportResetVersion&&ot(e.lastAppliedViewport,t.lastAppliedViewport)&&e.lastResetCause===t.lastResetCause&&nV(e.trackingState,t.trackingState)&&oV(e.pendingAcknowledgement,t.pendingAcknowledgement)}function iV(e,t){return e==null?null:{requestKey:e,viewportResetVersion:t}}function sV(e){return e.acknowledgementRequestKey!=null?iV(e.acknowledgementRequestKey,e.viewportResetVersion):e.shouldResetViewport?null:e.current!=null&&e.compatiblePreviewNavigationRequestKey===e.current.requestKey?vb(e.current):null}function V7(e,t){return{viewportHydrated:!1,viewportResetVersion:0,lastAppliedViewport:null,lastResetCause:null,trackingState:om(e,t),pendingAcknowledgement:null}}function L7(e,t,r=null,o){return{viewportHydrated:!1,viewportResetVersion:e.viewportResetVersion+1,lastAppliedViewport:null,lastResetCause:r,trackingState:om(t,o),pendingAcknowledgement:null}}function F7(e){let t=gb({editorState:e.editorState,explicitAnchorPageNumber:e.explicitAnchorPageNumber,viewportHydrated:e.state.viewportHydrated,controllerNavigationMode:e.controllerNavigationMode,modeOptions:e.modeOptions,syncViewportToEditor:e.syncViewportToEditor,lastAppliedViewport:e.state.lastAppliedViewport,trackingState:e.state.trackingState}),r=t.shouldResetViewport?e.state.viewportResetVersion+1:e.state.viewportResetVersion,o=xt(e.editorState,e.modeOptions)?.requestKey??null,n={viewportHydrated:t.shouldResetViewport?!1:e.state.viewportHydrated,viewportResetVersion:r,lastAppliedViewport:t.shouldResetViewport?null:re(e.state.lastAppliedViewport),lastResetCause:t.shouldResetViewport?t.resetCause:e.state.lastResetCause,trackingState:t.nextTrackingState,pendingAcknowledgement:sV({current:e.state.pendingAcknowledgement,acknowledgementRequestKey:e.acknowledgementRequestKey,compatiblePreviewNavigationRequestKey:o,shouldResetViewport:t.shouldResetViewport,viewportResetVersion:r})};return{nextState:n,changed:!hb(e.state,n)}}function z7(e){if(e.observedViewportResetVersion!==e.state.viewportResetVersion)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let t=re(e.viewport);if(!t)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let r=Bt({viewport:t},e.modeOptions);if(!r)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let o=Sb({viewport:r,lastAppliedViewport:e.state.lastAppliedViewport,controllerViewport:e.controllerViewport,controllerFlowMode:e.controllerFlowMode,controllerLayoutMode:e.controllerLayoutMode,syncViewportToEditor:e.syncViewportToEditor}),n=vb(e.state.pendingAcknowledgement),i=xt({previewNavigationRequest:e.previewNavigationRequest??null},e.modeOptions)?.requestKey??null,s=n!=null&&n.viewportResetVersion===e.state.viewportResetVersion&&i===n.requestKey,a={viewportHydrated:!0,viewportResetVersion:e.state.viewportResetVersion,lastAppliedViewport:re(r),lastResetCause:e.state.lastResetCause,trackingState:e.state.trackingState,pendingAcknowledgement:s?null:n};return{nextState:a,controllerViewportPatch:o,acknowledgementRequestKey:s?n.requestKey:null,changed:!hb(e.state,a)}}export{Wn as DEFAULT_BROWSER_ZOOM_PERCENT,Vo as applyBrowserInlineFormatPatch,rc as browserViewportStateHasExplicitModeConflict,om as captureBrowserPaginatedPreviewTrackingState,go as captureBrowserSurfaceSelectionRebaseTarget,re as cloneBrowserViewportState,Zj as createBrowserAdvancedOoxmlInspectorController,Yu as createBrowserEditor,Vj as createBrowserEditorBackendAdapter,Bj as createBrowserEditorController,ci as createBrowserEditorHost,em as createBrowserEditorMountController,uo as createBrowserEditorOverlayHost,hI as createBrowserEditorOverlayHostFromController,vI as createBrowserEditorSessionHostFromController,Lj as createBrowserEditorUiController,Js as createBrowserEditorUiFromController,hn as createBrowserEditorUiHost,yI as createBrowserEditorUiHostFromController,Xs as createBrowserPaginatedPreviewSelectionActionsV1,V7 as createBrowserPaginatedPreviewSessionState,zd as createBrowserSelectionCapture,yl as createSurfaceSelectionAdapter,Yt as fillBrowserViewportStateModes,Xj as handleBrowserPaginatedPreviewPositionHit,tc as hasFreshBrowserViewportRequest,_o as isBrowserViewportStateCompatibleWithFlowMode,Uo as isBrowserViewportStateCompatibleWithLayoutMode,to as isBrowserViewportStateCompatibleWithModes,Mc as normalizeBrowserPreviewControllerNavigationMode,ba as normalizeBrowserSurfaceReviewSelection,Go as normalizeBrowserViewportAnchor,$t as normalizeBrowserViewportPageAddress,De as normalizeBrowserViewportRequestKey,ht as normalizeBrowserZoomPercent,Sc as readBrowserEditorAutomation,wc as readBrowserEditorDocument,gc as readBrowserEditorView,ur as readBrowserZoomPercent,Ri as readSelectedAdvancedOoxmlRecord,vc as replaceBrowserEditorDocument,Cn as replaceBrowserSurfaceDocumentPreservingSelection,L7 as resetBrowserPaginatedPreviewSessionState,UI as resolveBrowserCommentReplayTarget,Es as resolveBrowserCommentWriteReason,IO as resolveBrowserEditorContextMenuContextAtPoint,io as resolveBrowserEditorPositionAtPoint,td as resolveBrowserEditorUiController,ir as resolveBrowserInlineFormatDisabledReason,xg as resolveBrowserPaginatedPreviewAcknowledgementRequestKey,Rg as resolveBrowserPaginatedPreviewAnchorPageNumber,gK as resolveBrowserPaginatedPreviewControllerSyncState,Sb as resolveBrowserPaginatedPreviewControllerViewportPatch,Cg as resolveBrowserPaginatedPreviewExternalViewportRequest,Ic as resolveBrowserPaginatedPreviewFlowMode,Eg as resolveBrowserPaginatedPreviewLayoutMode,v7 as resolveBrowserPaginatedPreviewLifecycleResetCause,rV as resolveBrowserPaginatedPreviewModeOptions,Bg as resolveBrowserPaginatedPreviewNavigationRequest,b7 as resolveBrowserPaginatedPreviewPinnedPageNumbers,Gj as resolveBrowserPaginatedPreviewPositionHitEvent,gb as resolveBrowserPaginatedPreviewResetPlan,Pg as resolveBrowserPaginatedPreviewScale,F7 as resolveBrowserPaginatedPreviewSessionUpdate,yg as resolveBrowserPaginatedPreviewSourceBinding,M7 as resolveBrowserPaginatedPreviewViewModel,Tg as resolveBrowserPaginatedPreviewViewportAnchor,Ag as resolveBrowserPaginatedPreviewViewportAnchorFromHit,z7 as resolveBrowserPaginatedPreviewViewportObservation,kg as resolveBrowserPaginatedPreviewViewportRequestKey,ut as resolveBrowserPreservedRangeTargetSelection,ga as resolveBrowserSurfaceProjectionMode,Q as resolveBrowserTextTargetSelection,Ne as resolveBrowserTextTargetSelectionWithExpectedText,xt as resolveCompatibleBrowserPreviewNavigationRequest,Bt as resolveCompatibleBrowserPreviewViewport,Xo as resolveCompatibleBrowserPreviewViewportAnchor,Sr as resolveProjectedSelectionRebaseRange,vi as resolveProjectedSelectionTrackedChangeIds,Ee as resolveSelectionInfo,Ci as restoreBrowserSurfaceSelectionFromRebaseTarget,mi as restoreTrackedCommentSelectionAfterReviewMutation,hg as sameBrowserPaginatedPreviewViewportRequest,aK as sameBrowserPaginatedPreviewViewportSyncState,Zo as sameBrowserViewportAnchor,Ps as sameBrowserViewportRequestKey,ot as sameBrowserViewportState,Kn as sameBrowserViewportStateForControllerSync,no as selectBrowserCommentTarget,El as selectBrowserTextTarget};