@datalking/begonia-browser-sdk 0.2.0 → 0.3.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.
Files changed (55) hide show
  1. package/dist/browser-command-table-state.d.ts +5 -0
  2. package/dist/browser-command-types.d.ts +3 -1
  3. package/dist/browser-comment-range-point.d.ts +56 -0
  4. package/dist/browser-editor-comments-controller.d.ts +2 -1
  5. package/dist/browser-editor-context-menu-open-at.d.ts +15 -0
  6. package/dist/browser-editor-contracts.d.ts +6 -0
  7. package/dist/browser-editor-domain-types.d.ts +48 -1
  8. package/dist/browser-editor-host.d.ts +0 -2
  9. package/dist/browser-editor-selection-geometry.d.ts +135 -1
  10. package/dist/browser-editor-types-controller.d.ts +46 -1
  11. package/dist/browser-editor-types-shared.d.ts +17 -0
  12. package/dist/browser-editor-viewport/browser-editor-viewport-bounds.d.ts +1 -1
  13. package/dist/browser-editor-viewport-session-state-types.d.ts +15 -0
  14. package/dist/browser-history-shortcut.d.ts +31 -0
  15. package/dist/browser-image-command-types.d.ts +28 -0
  16. package/dist/browser-insert-command-types.d.ts +5 -0
  17. package/dist/browser-page-review-target.d.ts +44 -0
  18. package/dist/browser-paginated-preview-editor-binding.d.ts +76 -1
  19. package/dist/browser-paginated-preview-key-selection.d.ts +48 -0
  20. package/dist/browser-paginated-preview-position-hit.d.ts +28 -0
  21. package/dist/browser-table-target-resolution.d.ts +59 -0
  22. package/dist/command.js +5 -5
  23. package/dist/editor.d.ts +8 -0
  24. package/dist/editor.js +5 -4
  25. package/dist/header-footer/header-footer-band-geometry.d.ts +70 -0
  26. package/dist/header-footer/header-footer-band-press.d.ts +51 -0
  27. package/dist/header-footer/header-footer-edit-state.d.ts +44 -0
  28. package/dist/header-footer/header-footer-edit-target.d.ts +54 -0
  29. package/dist/header-footer/header-footer-editing-controller.d.ts +133 -0
  30. package/dist/header-footer/header-footer-exit-press.d.ts +54 -0
  31. package/dist/header-footer/header-footer-slot.d.ts +38 -0
  32. package/dist/header-footer/header-footer-story-blocks.d.ts +71 -0
  33. package/dist/header-footer/section-header-footer-links.d.ts +60 -0
  34. package/dist/header-footer/section-header-footer-variants.d.ts +55 -0
  35. package/dist/index.d.ts +31 -0
  36. package/dist/index.js +60 -5
  37. package/dist/ooxml.js +4 -4
  38. package/dist/paginated-editing/index.d.ts +7 -0
  39. package/dist/paginated-editing/paginated-caret-reveal.d.ts +51 -0
  40. package/dist/paginated-editing/paginated-column-keyboard.d.ts +50 -0
  41. package/dist/paginated-editing/paginated-editing-session.d.ts +8 -0
  42. package/dist/paginated-editing/paginated-editing-types.d.ts +169 -0
  43. package/dist/paginated-editing/paginated-ime-caret-measure.d.ts +26 -0
  44. package/dist/paginated-editing/paginated-input-anchor.d.ts +116 -0
  45. package/dist/paginated-editing/paginated-input-bridge.d.ts +169 -0
  46. package/dist/paginated-editing/paginated-table-boundary-keyboard.d.ts +24 -0
  47. package/dist/paginated-editing/paginated-table-boundary-keys.d.ts +33 -0
  48. package/dist/paginated-preview-selection-table/preview-selection-table-exit.d.ts +61 -0
  49. package/dist/paginated-preview-selection-table/preview-selection-table-resolve.d.ts +7 -2
  50. package/dist/preview.js +1 -1
  51. package/dist/theme/theme-tokens.d.ts +35 -1
  52. package/dist/theme.js +1 -1
  53. package/dist/v1.d.ts +6 -0
  54. package/dist/v1.js +9 -9
  55. package/package.json +14 -14
package/dist/v1.js CHANGED
@@ -1,9 +1,9 @@
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};
1
+ import{createDocumentSurface as h0}from"@datalking/begonia-engine";import{createOoxmlFamilyEnvelope as Bp}from"@datalking/begonia-engine";var os="ald:advanced-ooxml-nodeview-action";function Yr(e){return typeof e=="object"&&e!==null}function ap(e){if(!Yr(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"&&Yr(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"&&Yr(e.model);case"replace-shape-model":return e.family==="shape"&&Yr(e.model);case"apply-math-edits":return e.family==="math"&&Yr(e.model)&&Array.isArray(e.edits);case"apply-chart-edits":return e.family==="chart"&&Yr(e.model)&&Array.isArray(e.edits);case"apply-shape-edits":return e.family==="shape"&&Yr(e.model)&&Array.isArray(e.edits);case"remove-advanced-ooxml":return e.family==="math"||e.family==="chart"||e.family==="shape";default:return!1}}function sr(e,t){e.dispatchEvent(new CustomEvent(os,{bubbles:!0,cancelable:!0,detail:t}))}function Mr(){return{Element:typeof Element<"u"?Element:void 0,Node:typeof Node<"u"?Node:void 0,HTMLAnchorElement:typeof HTMLAnchorElement<"u"?HTMLAnchorElement:void 0,HTMLInputElement:typeof HTMLInputElement<"u"?HTMLInputElement:void 0,HTMLTextAreaElement:typeof HTMLTextAreaElement<"u"?HTMLTextAreaElement:void 0,HTMLSelectElement:typeof HTMLSelectElement<"u"?HTMLSelectElement:void 0,HTMLButtonElement:typeof HTMLButtonElement<"u"?HTMLButtonElement:void 0}}function ml(e,t){if(!t)return!1;try{return e instanceof t}catch{return!1}}function lp(e){if(typeof e!="object"||e===null)return null;try{let t=e.nodeType;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return null}}function hx(e){if(typeof e!="object"||e===null)return null;try{let t=e.localName;if(typeof t=="string"&&t.length>0)return t.toLowerCase();let r=e.tagName;return typeof r=="string"&&r.length>0?r.toLowerCase():null}catch{return null}}function Do(e,t=Mr()){if(ml(e,t.Node))return!0;let r=lp(e);return r!==null&&r>=1&&r<=12}function jo(e,t=Mr()){return ml(e,t.Element)?!0:lp(e)===1}function qn(e,t,r,o){return ml(e,r)?!0:jo(e,o)&&hx(e)===t}function cp(e,t=Mr()){return qn(e,"a",t.HTMLAnchorElement,t)}function vx(e,t=Mr()){return qn(e,"input",t.HTMLInputElement,t)}function bx(e,t=Mr()){return qn(e,"textarea",t.HTMLTextAreaElement,t)}function yx(e,t=Mr()){return qn(e,"select",t.HTMLSelectElement,t)}function Bx(e,t=Mr()){return qn(e,"button",t.HTMLButtonElement,t)}function dp(e,t=Mr()){return vx(e,t)||bx(e,t)||yx(e,t)||Bx(e,t)}function xx(e,t){e.disabled=!t,e.style.opacity=t?"1":"0.65",e.style.cursor=t?"pointer":"default"}function Cx(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 Vo(e){let t=!1,r=!1,o=null,n=()=>{o!==null&&(window.clearTimeout(o),o=null)},i=()=>{xx(e.applyButton,r),Cx(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 zt(e,t){return Object.assign(e.style,t),e}function Lo(e,t=!1){let r=document.createElement(e);return r.contentEditable="false",zt(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 Fo(e,t){let r=document.createElement("div");zt(r,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px"});let o=document.createElement("strong");o.textContent=e,zt(o,{fontSize:"12px",color:"#0f172a"});let n=document.createElement("span");return n.textContent=t,zt(n,{fontSize:"11px",fontWeight:"600",color:"#475569",background:"#e2e8f0",borderRadius:"999px",padding:"2px 8px"}),r.append(o,n),{header:r,heading:o}}function Ho(){let e=document.createElement("div");return zt(e,{fontSize:"11px",color:"#64748b"}),e}function Jr(e){let t=document.createElement("section");zt(t,{display:"grid",gap:"8px",padding:"10px",borderRadius:"12px",background:"#ffffff",border:"1px solid #e2e8f0"});let r=document.createElement("div");return r.textContent=e,zt(r,{fontSize:"11px",fontWeight:"700",letterSpacing:"0.08em",textTransform:"uppercase",color:"#475569"}),t.append(r),{section:t,title:r}}function qt(e){let t=document.createElement("div");return t.textContent=e,zt(t,{fontSize:"11px",color:"#64748b"}),t}function ar(){let e=document.createElement("div");return zt(e,{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}),e}function Ue(e,t="default"){let r=document.createElement("button");return r.type="button",r.textContent=e,zt(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 zo(e){return dp(e)}import{listOoxmlChartAxisIds as up,listOoxmlChartSeriesIds as mp}from"@datalking/begonia-engine";function me(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Px(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Ir(e){return new Set(e).size===e.length}function Wn(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(!Px(o,i))return!1;let s=t.findIndex(a=>!n.has(a));return s===-1||t.slice(s).every(a=>!n.has(a))}function Rx(e,t){if(me(e.series,t.series))return[];let r=mp(e),o=mp(t);if(!Ir(r)||!Ir(o)||!Wn(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}me(c,l)||s.push({type:"set-series",target:a,series:l})}),s}function Tx(e,t){if(me(e.axes,t.axes))return[];let r=up(e),o=up(t);if(!Ir(r)||!Ir(o)||!Wn(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||!me(c,l))&&s.push({type:"upsert-axis",axisId:a,axis:l})}),s}function pp(e,t){if(me(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}),me(e.textBody,t.textBody)||r.push({type:"set-text-body",textBody:t.textBody}),me(e.plotArea,t.plotArea)||r.push({type:"set-plot-area",plotArea:t.plotArea}),me(e.legend,t.legend)||r.push({type:"set-legend",legend:t.legend}),r.push(...Tx(e,t)),r.push(...Rx(e,t)),r}import{Schema as kx}from"prosemirror-model";import{EditorState as Ex}from"prosemirror-state";import{EditorView as Mx}from"prosemirror-view";var Ix=["display:grid","gap:8px","padding:10px","border:1px solid #dbe3ea","border-radius:12px","background:#f8fafc"].join(";"),Ax=["font-size:11px","font-weight:700","letter-spacing:0.08em","text-transform:uppercase","color:#334155"].join(";"),Nx=["display:grid","gap:8px","padding-left:8px"].join(";"),Ox=["display:grid","gap:4px"].join(";"),Dx=["font-size:11px","font-weight:600","letter-spacing:0.06em","text-transform:uppercase","color:#64748b"].join(";"),jx=["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(";"),Vx=["display:grid","gap:10px","outline:none"].join(";"),At=new kx({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:Ix},["div",{style:Ax},e.attrs.label],["div",{style:Nx},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:Ox},["div",{style:Dx},e.attrs.label],["div",{style:jx},0]]}},text:{}}});function Lx(e){return At.nodes.field.create({key:e.key,label:e.label},e.value?At.text(e.value):void 0)}function Fx(e){let t=e.children.map(pl);return At.nodes.section.create({key:e.key,label:e.label},t)}function pl(e){return e.type==="field"?Lx(e):Fx(e)}function Hx(e){return At.nodes.doc.create(null,e.map(pl))}function fp(e){return e.content.content.map(t=>Sp(t)).filter(t=>t!==null)}function Sp(e){return e.type===At.nodes.field?{type:"field",key:String(e.attrs.key??""),label:String(e.attrs.label??"Field"),value:e.textContent}:e.type===At.nodes.section?{type:"section",key:String(e.attrs.key??""),label:String(e.attrs.label??"Section"),children:e.content.content.map(t=>Sp(t)).filter(t=>t!==null)}:null}function wp(e){return Ex.create({schema:At,doc:Hx(e)})}function zx(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1)if(t.node(r).type===At.nodes.section)return t.end(r)-1;return e.doc.content.size}function qx(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1){let o=t.node(r);if(o.type===At.nodes.field||o.type===At.nodes.section)return{from:t.before(r),to:t.before(r)+o.nodeSize}}return null}function gp(e){let{$from:t}=e.selection,r=[],o=e.doc;for(let n=1;n<=t.depth;n+=1){if(t.node(n).type!==At.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 Wx(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 g(e,t,r=""){return{type:"field",key:e,label:t,value:r}}function k(e,t,r=[]){return{type:"section",key:e,label:t,children:[...r]}}function qo(e,t,r={}){Wx(e);let o,n=()=>{r.onSelectionChange?.(gp(o.state))};return o=new Mx(e,{dispatchTransaction(i){let s=o.state.apply(i);o.updateState(s),i.docChanged&&r.onChange?.({entries:fp(s.doc)}),(i.docChanged||i.selectionSet)&&n()},state:wp(t),attributes:{style:Vx,class:"ald-advanced-ooxml-subtree-editor"}}),n(),{dom:e,appendEntry(i){let s=pl(i),a=zx(o.state);o.dispatch(o.state.tr.insert(a,s)),o.focus()},destroy(){o.destroy()},focus(){o.focus()},readEntries(){return fp(o.state.doc)},readSelection(){return gp(o.state)},removeSelectedEntry(){let i=qx(o.state);return i?(o.dispatch(o.state.tr.delete(i.from,i.to)),o.focus(),!0):!1},setEntries(i){o.updateState(wp(i)),n()}}}import{normalizeOoxmlChartModel as _x}from"@datalking/begonia-engine";function z(e){let t=e.trim();return t.length>0?t:null}function ie(e){let t=e.trim();if(!t)return null;let r=Number(t);return Number.isFinite(r)?r:null}function pe(e){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:null}function Re(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Te(e){return e==null?"":JSON.stringify(e,null,2)}function P(e,t){let r=e.find(o=>o.type==="field"&&o.key===t);return r?.type==="field"?r.value:""}function gt(e,t){return e.filter(r=>r.type==="section"&&r.key===t)}function fl(e,t){return gt(e,t)[0]??null}function hp(e){return e.type==="field"?e.value.trim().length>0:e.children.some(t=>hp(t))}function Kx(e){return e.some(t=>hp(t))}function ke(e,t){let r=fl(e,t);return r&&Kx(r.children)?r:null}function Wo(e,t,r){let o=r?.paragraphs?.length?r.paragraphs:r?.plainText?[r.plainText]:[];return k(e,t,(o.length>0?o:[""]).map(n=>g("paragraph","Paragraph",n)))}function ns(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 is(e,t){return k(e,t,[g("paragraph","Paragraph","")])}function Ux(e){return k("marker","Marker",[g("symbol","Symbol",e.marker?.symbol??""),g("size","Size",e.marker?.size==null?"":String(e.marker.size))])}function Xx(e){return k("data-labels","Data Labels",[g("show-value","Show Value",e.dataLabels?.showValue==null?"":String(e.dataLabels.showValue)),g("show-category","Show Category",e.dataLabels?.showCategory==null?"":String(e.dataLabels.showCategory)),g("show-series-name","Show Series Name",e.dataLabels?.showSeriesName==null?"":String(e.dataLabels.showSeriesName)),g("show-percentage","Show Percentage",e.dataLabels?.showPercentage==null?"":String(e.dataLabels.showPercentage)),g("position","Position",e.dataLabels?.position??""),g("separator","Separator",e.dataLabels?.separator??"")])}function Zx(e){return k("series","Series",[g("id","Series Id",e.id??""),g("order","Order",e.order==null?"":String(e.order)),g("name","Name",e.name??""),g("categories","Categories",e.categories.join(", ")),g("values","Values",e.values.map(t=>t==null?"":String(t)).join(", ")),g("color","Color",e.color??""),g("smooth","Smooth",e.smooth==null?"":String(e.smooth)),g("explosion","Explosion",e.explosion==null?"":String(e.explosion)),Ux(e),Xx(e)])}function Gx(e){return k("axis","Axis",[g("id","Axis Id",e.id??""),g("kind","Kind",e.kind??""),g("title","Title",e.title??""),g("format-code","Format Code",e.formatCode??""),g("orientation","Orientation",e.orientation??""),g("visible","Visible",e.visible==null?"":String(e.visible)),g("minimum","Minimum",e.minimum==null?"":String(e.minimum)),g("maximum","Maximum",e.maximum==null?"":String(e.maximum)),g("major-unit","Major Unit",e.majorUnit==null?"":String(e.majorUnit)),g("minor-unit","Minor Unit",e.minorUnit==null?"":String(e.minorUnit)),g("crosses-at","Crosses At",e.crossesAt==null?"":String(e.crossesAt)),g("major-gridlines","Major Gridlines",e.majorGridlines==null?"":String(e.majorGridlines)),g("minor-gridlines","Minor Gridlines",e.minorGridlines==null?"":String(e.minorGridlines))])}function $x(e){return k("legend","Legend",[g("visible","Visible",e.legend==null?"":String(e.legend.visible)),g("position","Position",e.legend?.position??""),g("overlay","Overlay",e.legend?.overlay==null?"":String(e.legend.overlay))])}function Yx(e){return k("plot-area","Plot Area",[g("stacked","Stacked",e.plotArea?.stacked==null?"":String(e.plotArea.stacked)),g("percent-stacked","Percent Stacked",e.plotArea?.percentStacked==null?"":String(e.plotArea.percentStacked)),g("vary-colors","Vary Colors",e.plotArea?.varyColors==null?"":String(e.plotArea.varyColors)),g("hole-size","Hole Size",e.plotArea?.holeSize==null?"":String(e.plotArea.holeSize))])}function Jx(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Qx(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 eC(e){return e.length>0?e:null}function tC(e){let t=ke(e,"marker"),r=ke(e,"data-labels");return{id:z(P(e,"id")),order:ie(P(e,"order")),name:z(P(e,"name")),categories:Jx(P(e,"categories")),values:Qx(P(e,"values")),color:z(P(e,"color")),marker:t?{symbol:z(P(t.children,"symbol"))??"unknown",size:ie(P(t.children,"size"))}:null,dataLabels:r?{showValue:pe(P(r.children,"show-value")),showCategory:pe(P(r.children,"show-category")),showSeriesName:pe(P(r.children,"show-series-name")),showPercentage:pe(P(r.children,"show-percentage")),position:z(P(r.children,"position")),separator:eC(P(r.children,"separator"))}:null,smooth:pe(P(e,"smooth")),explosion:ie(P(e,"explosion"))}}function rC(e){let t=P(e,"kind"),r=P(e,"orientation");return{id:z(P(e,"id")),kind:t==="category"||t==="value"||t==="series"||t==="date"?t:"unknown",title:z(P(e,"title")),formatCode:z(P(e,"format-code")),orientation:r==="minMax"||r==="maxMin"?r:null,visible:pe(P(e,"visible")),minimum:ie(P(e,"minimum")),maximum:ie(P(e,"maximum")),majorUnit:ie(P(e,"major-unit")),minorUnit:ie(P(e,"minor-unit")),crossesAt:ie(P(e,"crosses-at")),majorGridlines:pe(P(e,"major-gridlines")),minorGridlines:pe(P(e,"minor-gridlines"))}}function vp(e){return[g("title","Title",e.title??""),g("chart-type","Chart Type",e.chartType??""),g("subtitle","Subtitle",e.subtitle??""),Wo("text-body","Text Body",e.textBody),Yx(e),...e.series.map(t=>Zx(t)),...e.axes.map(t=>Gx(t)),$x(e)]}function bp(e,t){let r=ke(e,"text-body"),o=ke(e,"plot-area"),n=ke(e,"legend");return _x({...t,title:z(P(e,"title")),chartType:z(P(e,"chart-type")),subtitle:z(P(e,"subtitle")),textBody:ns(r),plotArea:o?{stacked:pe(P(o.children,"stacked")),percentStacked:pe(P(o.children,"percent-stacked")),varyColors:pe(P(o.children,"vary-colors")),holeSize:ie(P(o.children,"hole-size"))}:null,series:gt(e,"series").map(i=>tC(i.children)),axes:gt(e,"axis").map(i=>rC(i.children)),legend:n?{visible:pe(P(n.children,"visible"))!==!1,position:z(P(n.children,"position"))??"unknown",overlay:pe(P(n.children,"overlay"))}:null},t.title??"Chart")}function oC(){return k("series","Series",[g("id","Series Id",""),g("order","Order",""),g("name","Name",""),g("categories","Categories",""),g("values","Values",""),g("color","Color",""),g("smooth","Smooth",""),g("explosion","Explosion",""),k("marker","Marker",[g("symbol","Symbol",""),g("size","Size","")]),k("data-labels","Data Labels",[g("show-value","Show Value",""),g("show-category","Show Category",""),g("show-series-name","Show Series Name",""),g("show-percentage","Show Percentage",""),g("position","Position",""),g("separator","Separator","")])])}function nC(){return k("axis","Axis",[g("id","Axis Id",""),g("kind","Kind","category"),g("title","Title",""),g("format-code","Format Code",""),g("orientation","Orientation",""),g("visible","Visible",""),g("minimum","Minimum",""),g("maximum","Maximum",""),g("major-unit","Major Unit",""),g("minor-unit","Minor Unit",""),g("crosses-at","Crosses At",""),g("major-gridlines","Major Gridlines",""),g("minor-gridlines","Minor Gridlines","")])}function iC(){return k("legend","Legend",[g("visible","Visible","true"),g("position","Position","right"),g("overlay","Overlay","")])}function sC(){return k("plot-area","Plot Area",[g("stacked","Stacked",""),g("percent-stacked","Percent Stacked",""),g("vary-colors","Vary Colors",""),g("hole-size","Hole Size","")])}function aC(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function lC(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function cC(e){return e==null}function yp(e={}){let t=aC(e.containerKey),r=lC(e.childKeys),o=n=>r.has(n);return t==="text-body"?[{label:"Paragraph",createEntry:()=>g("paragraph","Paragraph","")}]:cC(t)?[{label:"Series",createEntry:oC},{label:"Axis",createEntry:nC},...o("legend")?[]:[{label:"Legend",createEntry:iC}],...o("plot-area")?[]:[{label:"Plot Area",createEntry:sC}],...o("text-body")?[]:[{label:"Text Body",createEntry:()=>is("text-body","Text Body")}]]:[]}function wl(e){let t=String(e.attrs.label??"Chart"),r=String(e.attrs.text??""),o=Bp("chart",{title:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=Bp("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 dC(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function xp(){return e=>{let t=e,r=Lo("div"),{header:o,heading:n}=Fo("Chart","chart"),i=Ho(),{section:s}=Jr("Native Subtree"),a=qt("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=ar();l.style.justifyContent="flex-start";let c=Ue("Remove Selected","danger"),d=dC(),u=ar();u.style.justifyContent="space-between",u.style.alignItems="center";let m=qt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=Ue("Apply"),f=Ue("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 w=null,v=(B,h)=>{l.replaceChildren(),yp({containerKey:B,childKeys:h}).forEach(y=>{let T=Ue(y.label);T.addEventListener("click",()=>{C.appendEntry(y.createEntry())}),l.append(T)})},C=qo(d,[],{onChange(){w?.markDirty()},onSelectionChange(B){v(B.containerKey,B.childKeys)}});c.addEventListener("click",()=>{C.removeSelectedEntry()}),w=Vo({applyButton:p,onCommit:()=>{let B=wl(t),h=bp(C.readEntries(),B.model),y=pp(B.model,h);return y.length===0?!1:(sr(r,{family:"chart",action:"apply-chart-edits",objectId:B.objectId,model:h,edits:y}),!0)},root:r,status:m});let S=B=>{t=B;let h=wl(B);n.textContent=h.label,i.textContent=`${h.evidence.chartType??"chart"} | ${h.evidence.seriesCount} series | ${h.evidence.axisCount} axes`,w?.reset(),C.setEntries(vp(h.model))};return p.addEventListener("click",()=>{w?.flush()}),f.addEventListener("click",()=>{w?.reset();let B=wl(t);sr(r,{family:"chart",action:"remove-advanced-ooxml",objectId:B.objectId})}),S(e),{dom:r,destroy(){w?.destroy(),C.destroy()},update(B){return B.type!==t.type?!1:(S(B),!0)},stopEvent(B){return zo(B.target)||Do(B.target)&&d.contains(B.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as kp,normalizeOoxmlMathModel as zC}from"@datalking/begonia-engine";function Cp(e,t){if(me(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}]:me(e.root,t.root)&&e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[{type:"replace-model",model:t}]}import{normalizeOoxmlMathModel as HC}from"@datalking/begonia-engine";import{createOoxmlMathTextNode as uC}from"@datalking/begonia-engine";var mC=new Set(["numerator","denominator","body","degree","base","superscript-slot","subscript-slot","lower","upper","name","argument","matrix-cell","equation-row"]);function gl(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function Pp(e){let t=gl(e);return t==null||mC.has(t)}function Sl(e){return uC(e)}function hl(){return Sl("")}function pC(e=""){return g("text","Text",e)}function ue(e,t){return k(e,t,[pC()])}function Rp(e){throw new Error(`Unsupported math node type: ${JSON.stringify(e)}.`)}function Ee(e){return Pp(e)}function fC(){return k("fraction","Fraction",[ue("numerator","Numerator"),ue("denominator","Denominator")])}function wC(){return k("radical","Radical",[ue("body","Body"),k("degree","Degree",[])])}function gC(){return k("superscript","Superscript",[ue("base","Base"),ue("superscript-slot","Superscript")])}function SC(){return k("subscript","Subscript",[ue("base","Base"),ue("subscript-slot","Subscript")])}function hC(){return k("subsup","Subscript and Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function vC(){return k("preSubSup","Pre-Sub/Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function bC(){return k("matrix","Matrix",[k("matrix-row","Row",[k("matrix-cell","Cell",[g("text","Text","")])])])}function yC(){return k("equationArray","Equation Array",[k("equation-row","Row",[g("text","Text","")])])}function BC(){return k("delimiter","Delimiter",[g("begin","Begin Delimiter","("),g("end","End Delimiter",")"),ue("body","Body")])}function xC(){return k("operator","Operator",[g("operator-symbol","Operator","sum"),ue("body","Body"),k("lower","Lower",[]),k("upper","Upper",[])])}function CC(){return k("nary","N-ary Operator",[g("operator-symbol","Operator","prod"),ue("body","Body"),k("subscript-slot","Subscript",[]),k("superscript-slot","Superscript",[])])}function PC(){return k("limitLower","Lower Limit",[ue("base","Base"),ue("lower","Lower")])}function RC(){return k("limitUpper","Upper Limit",[ue("base","Base"),ue("upper","Upper")])}function TC(){return k("function","Function",[ue("name","Name"),ue("argument","Argument")])}function kC(){return k("accent","Accent",[g("accent-symbol","Accent","hat"),ue("body","Body")])}function EC(){return k("bar","Bar",[g("bar-position","Position","top"),ue("body","Body")])}function MC(){return k("box","Box",[g("border-box","Border Box","true"),ue("body","Body")])}function IC(){return k("groupCharacter","Group Character",[g("group-character","Character","_"),g("group-position","Position","bottom"),ue("body","Body")])}function AC(){return k("phantom","Phantom",[g("zero-width","Zero Width","false"),g("zero-ascent","Zero Ascent","false"),g("zero-descent","Zero Descent","false"),g("transparent","Transparent","true"),ue("body","Body")])}function NC(){return k("matrix-row","Row",[k("matrix-cell","Cell",[g("text","Text","")])])}function OC(){return k("matrix-cell","Cell",[g("text","Text","")])}function DC(){return k("equation-row","Row",[g("text","Text","")])}var jC=[{label:"Text",createEntry:()=>g("text","Text",""),supportsContainer:Ee},{label:"Fraction",createEntry:fC,supportsContainer:Ee},{label:"Radical",createEntry:wC,supportsContainer:Ee},{label:"Superscript",createEntry:gC,supportsContainer:Ee},{label:"Subscript",createEntry:SC,supportsContainer:Ee},{label:"Sub+Sup",createEntry:hC,supportsContainer:Ee},{label:"Pre-Sub/Sup",createEntry:vC,supportsContainer:Ee},{label:"Matrix",createEntry:bC,supportsContainer:Ee},{label:"Matrix Row",createEntry:NC,supportsContainer:e=>e==="matrix"},{label:"Matrix Cell",createEntry:OC,supportsContainer:e=>e==="matrix-row"},{label:"Equation Array",createEntry:yC,supportsContainer:Ee},{label:"Equation Row",createEntry:DC,supportsContainer:e=>e==="equationArray"},{label:"Delimiter",createEntry:BC,supportsContainer:Ee},{label:"Operator",createEntry:xC,supportsContainer:Ee},{label:"N-ary",createEntry:CC,supportsContainer:Ee},{label:"Lower Limit",createEntry:PC,supportsContainer:Ee},{label:"Upper Limit",createEntry:RC,supportsContainer:Ee},{label:"Function",createEntry:TC,supportsContainer:Ee},{label:"Accent",createEntry:kC,supportsContainer:Ee},{label:"Bar",createEntry:EC,supportsContainer:Ee},{label:"Box",createEntry:MC,supportsContainer:Ee},{label:"Group Char",createEntry:IC,supportsContainer:Ee},{label:"Phantom",createEntry:AC,supportsContainer:Ee}];function vl(e={}){let t=gl(e.containerKey);return jC.filter(r=>r.supportsContainer(t)).map(({label:r,createEntry:o})=>({label:r,createEntry:o}))}function ae(e,t){return fl(e,t)?.children??[]}function VC(e){let t=e.map(r=>FC(r)).filter(r=>r!==null);return t.length===0?hl():t.length===1?t[0]:{type:"sequence",items:t}}function ss(e){return e.length>0?se(e):null}function LC(e){let t=gt(e,"matrix-cell").map(r=>se(r.children));return t.length>0?t:[hl()]}function FC(e){if(e.type==="field")return e.key==="text"?Sl(e.value):null;switch(e.key){case"fraction":return{type:"fraction",numerator:se(ae(e.children,"numerator")),denominator:se(ae(e.children,"denominator"))};case"radical":{let t=ae(e.children,"degree");return{type:"radical",body:se(ae(e.children,"body")),degree:t.length>0?se(t):null}}case"superscript":return{type:"superscript",base:se(ae(e.children,"base")),superscript:se(ae(e.children,"superscript-slot"))};case"subscript":return{type:"subscript",base:se(ae(e.children,"base")),subscript:se(ae(e.children,"subscript-slot"))};case"subsup":return{type:"subsup",base:se(ae(e.children,"base")),subscript:se(ae(e.children,"subscript-slot")),superscript:se(ae(e.children,"superscript-slot"))};case"preSubSup":return{type:"preSubSup",base:se(ae(e.children,"base")),subscript:se(ae(e.children,"subscript-slot")),superscript:se(ae(e.children,"superscript-slot"))};case"matrix":return{type:"matrix",rows:gt(e.children,"matrix-row").map(t=>LC(t.children))};case"equationArray":return{type:"equationArray",rows:gt(e.children,"equation-row").map(t=>se(t.children))};case"delimiter":return{type:"delimiter",begin:z(P(e.children,"begin")),end:z(P(e.children,"end")),body:se(ae(e.children,"body"))};case"operator":return{type:"operator",operator:z(P(e.children,"operator-symbol")),body:se(ae(e.children,"body")),lower:ss(ae(e.children,"lower")),upper:ss(ae(e.children,"upper"))};case"nary":return{type:"nary",operator:z(P(e.children,"operator-symbol")),body:se(ae(e.children,"body")),subscript:ss(ae(e.children,"subscript-slot")),superscript:ss(ae(e.children,"superscript-slot"))};case"limitLower":return{type:"limitLower",base:se(ae(e.children,"base")),lower:se(ae(e.children,"lower"))};case"limitUpper":return{type:"limitUpper",base:se(ae(e.children,"base")),upper:se(ae(e.children,"upper"))};case"function":return{type:"function",name:se(ae(e.children,"name")),argument:se(ae(e.children,"argument"))};case"accent":return{type:"accent",accent:z(P(e.children,"accent-symbol")),body:se(ae(e.children,"body"))};case"bar":{let t=P(e.children,"bar-position").trim().toLowerCase();return{type:"bar",position:t==="top"||t==="bottom"?t:"unknown",body:se(ae(e.children,"body"))}}case"box":return{type:"box",body:se(ae(e.children,"body")),borderBox:pe(P(e.children,"border-box"))};case"groupCharacter":{let t=P(e.children,"group-position").trim().toLowerCase();return{type:"groupCharacter",character:z(P(e.children,"group-character")),position:t==="top"||t==="bottom"?t:"unknown",body:se(ae(e.children,"body"))}}case"phantom":return{type:"phantom",body:se(ae(e.children,"body")),zeroWidth:pe(P(e.children,"zero-width")),zeroAscent:pe(P(e.children,"zero-ascent")),zeroDescent:pe(P(e.children,"zero-descent")),transparent:pe(P(e.children,"transparent"))};default:return e.children.length>0?se(e.children):null}}function se(e){return VC(e)}function te(e){switch(e.type){case"sequence":return e.items.flatMap(t=>te(t));case"text":return[g("text","Text",e.value)];case"fraction":return[k("fraction","Fraction",[k("numerator","Numerator",te(e.numerator)),k("denominator","Denominator",te(e.denominator))])];case"radical":return[k("radical","Radical",[k("body","Body",te(e.body)),k("degree","Degree",e.degree?te(e.degree):[])])];case"superscript":return[k("superscript","Superscript",[k("base","Base",te(e.base)),k("superscript-slot","Superscript",te(e.superscript))])];case"subscript":return[k("subscript","Subscript",[k("base","Base",te(e.base)),k("subscript-slot","Subscript",te(e.subscript))])];case"subsup":return[k("subsup","Subscript and Superscript",[k("base","Base",te(e.base)),k("subscript-slot","Subscript",te(e.subscript)),k("superscript-slot","Superscript",te(e.superscript))])];case"preSubSup":return[k("preSubSup","Pre-Sub/Superscript",[k("base","Base",te(e.base)),k("subscript-slot","Subscript",te(e.subscript)),k("superscript-slot","Superscript",te(e.superscript))])];case"matrix":return[k("matrix","Matrix",e.rows.map(t=>k("matrix-row","Row",t.map(r=>k("matrix-cell","Cell",te(r))))))];case"equationArray":return[k("equationArray","Equation Array",e.rows.map(t=>k("equation-row","Row",te(t))))];case"delimiter":return[k("delimiter","Delimiter",[g("begin","Begin Delimiter",e.begin??""),g("end","End Delimiter",e.end??""),k("body","Body",te(e.body))])];case"operator":return[k("operator","Operator",[g("operator-symbol","Operator",e.operator??""),k("body","Body",te(e.body)),k("lower","Lower",e.lower?te(e.lower):[]),k("upper","Upper",e.upper?te(e.upper):[])])];case"nary":return[k("nary","N-ary Operator",[g("operator-symbol","Operator",e.operator??""),k("body","Body",te(e.body)),k("subscript-slot","Subscript",e.subscript?te(e.subscript):[]),k("superscript-slot","Superscript",e.superscript?te(e.superscript):[])])];case"limitLower":return[k("limitLower","Lower Limit",[k("base","Base",te(e.base)),k("lower","Lower",te(e.lower))])];case"limitUpper":return[k("limitUpper","Upper Limit",[k("base","Base",te(e.base)),k("upper","Upper",te(e.upper))])];case"function":return[k("function","Function",[k("name","Name",te(e.name)),k("argument","Argument",te(e.argument))])];case"accent":return[k("accent","Accent",[g("accent-symbol","Accent",e.accent??""),k("body","Body",te(e.body))])];case"bar":return[k("bar","Bar",[g("bar-position","Position",e.position),k("body","Body",te(e.body))])];case"box":return[k("box","Box",[g("border-box","Border Box",e.borderBox==null?"":String(e.borderBox)),k("body","Body",te(e.body))])];case"groupCharacter":return[k("groupCharacter","Group Character",[g("group-character","Character",e.character??""),g("group-position","Position",e.position),k("body","Body",te(e.body))])];case"phantom":return[k("phantom","Phantom",[g("zero-width","Zero Width",e.zeroWidth==null?"":String(e.zeroWidth)),g("zero-ascent","Zero Ascent",e.zeroAscent==null?"":String(e.zeroAscent)),g("zero-descent","Zero Descent",e.zeroDescent==null?"":String(e.zeroDescent)),g("transparent","Transparent",e.transparent==null?"":String(e.transparent)),k("body","Body",te(e.body))])]}return Rp(e)}function bl(e){return[g("display-mode","Display Mode",e.displayMode),...te(e.root)]}function Tp(e){let r=P(e,"display-mode").trim().toLowerCase()==="block"?"block":"inline",o=e.filter(n=>!(n.type==="field"&&n.key==="display-mode"));return HC({displayMode:r,root:se(o)},"",r)}function yl(e){let t=String(e.attrs.text??""),r=String(e.attrs.label??"Equation"),o=kp("math",{plainText:t,displayMode:"inline"},{label:r,text:t}),n=kp("math",e.attrs.familyData,{label:r,text:t})??o,i=zC(n.data,n.data.plainText??t,n.data.displayMode??"inline");return{objectId:String(e.attrs.objectId??""),label:r,model:i,evidence:n.evidence}}function qC(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%",maxWidth:"720px"}),e}function Ep(){return e=>{let t=e,r=Lo("span",!0);Object.assign(r.style,{display:"inline-grid",width:"min(720px, 100%)",verticalAlign:"top"});let{header:o,heading:n}=Fo("Equation","math"),i=Ho(),{section:s}=Jr("Native Subtree"),a=qt("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=ar();l.style.justifyContent="flex-start";let c=Ue("Remove Selected","danger"),d=qC(),u=ar();u.style.justifyContent="space-between",u.style.alignItems="center";let m=qt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=Ue("Apply"),f=Ue("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 w=null,v=B=>{l.replaceChildren(),vl({containerKey:B}).forEach(h=>{let y=Ue(h.label);y.addEventListener("click",()=>{C.appendEntry(h.createEntry())}),l.append(y)})},C=qo(d,[],{onChange(){w?.markDirty()},onSelectionChange(B){v(B.containerKey)}});c.addEventListener("click",()=>{C.removeSelectedEntry()}),w=Vo({applyButton:p,onCommit:()=>{let B=yl(t),h=Tp(C.readEntries()),y=Cp(B.model,h);return y.length===0?!1:(sr(r,{family:"math",action:"apply-math-edits",objectId:B.objectId,model:h,edits:y}),!0)},root:r,status:m});let S=B=>{t=B;let h=yl(B);n.textContent=h.label,i.textContent=`${h.evidence.displayMode} | root ${h.evidence.rootType} | ${h.evidence.structureCount} structures`,w?.reset(),C.setEntries(bl(h.model))};return p.addEventListener("click",()=>{w?.flush()}),f.addEventListener("click",()=>{w?.reset();let B=yl(t);sr(r,{family:"math",action:"remove-advanced-ooxml",objectId:B.objectId})}),S(e),{dom:r,destroy(){w?.destroy(),C.destroy()},update(B){return B.type!==t.type?!1:(S(B),!0)},stopEvent(B){return zo(B.target)||Do(B.target)&&d.contains(B.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as Zp,createOoxmlShapePreview as tP}from"@datalking/begonia-engine";function Mp(e){return e.map((t,r)=>t.id??`shape-child-${r+1}`)}function Ip(e,t){return me({...e,children:[]},{...t,children:[]})}function Bl(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}),!Bl(n.children,i,r)))return!1}return!0}function WC(e,t){return e.size===t.size&&[...t.keys()].every(r=>e.has(r))}function KC(e,t){return{...t,children:[...e.children]}}function Ap(e,t,r){t.forEach(o=>{let n=o.id?.trim();if(!n)return;let i=e.get(n);i&&!Ip(i.child,o)&&r.push({type:"set-child",target:n,child:KC(i.child,o)}),Ap(e,o.children,r)})}function Np(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}),Np(e,s.children,a,o),n=a}}function _C(e,t){let r=new Map,o=new Map;if(!Bl(e,null,r)||!Bl(t,null,o)||!WC(r,o))return null;let n=[];return Ap(r,t,n),Np(r,t,null,n),n}function UC(e,t,r){return t==null||r==null?[{type:"set-children",children:[...e]}]:[{type:"set-child",target:t,child:r}]}function Op(e,t,r,o){if(me(e,t))return[];let n=Mp(e),i=Mp(t);if(!Ir(n)||!Ir(i)||!Wn(n,i))return UC(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(!Ip(u,d)){l.push({type:"set-child",target:c,child:d});return}l.push(...Op(u.children,d.children,c,d))}),l}function Dp(e,t){if(me(e,t))return[];if(!me(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}),me(e.textBody,t.textBody)||r.push({type:"set-text-body",paragraphs:t.textBody?.paragraphs?[...t.textBody.paragraphs]:[]}),me(e.geometry,t.geometry)||r.push({type:"set-geometry",geometry:t.geometry}),me(e.transform,t.transform)||r.push({type:"set-transform",transform:t.transform}),me(e.fill,t.fill)||r.push({type:"set-fill",fill:t.fill}),me(e.stroke,t.stroke)||r.push({type:"set-stroke",stroke:t.stroke}),me(e.effects,t.effects)||r.push({type:"set-effects",effects:t.effects??null}),me(e.anchor,t.anchor)||r.push({type:"set-anchor",anchor:t.anchor}),me(e.connector,t.connector)||r.push({type:"set-connector",connector:t.connector}),me(e.picture,t.picture)||r.push({type:"set-picture",picture:t.picture}),me(e.wordArt,t.wordArt)||r.push({type:"set-word-art",wordArt:t.wordArt});let o=_C(e.children,t.children);return o?(r.push(...o),r):(r.push(...Op(e.children,t.children,null,null)),r)}function jp(e){return k("shape-child","Child Object",[g("kind","Kind",e.kind??""),g("id","Id",e.id??""),g("label","Label",e.label??""),Wo("text-body","Text Body",e.textBody),xl(e.geometry),Cl(e.transform),Pl(e.groupTransform??null),Rl(e.fill??null),Tl(e.stroke??null),kl(e.effects??null),El(e.connector),Ml(e.picture),Il(e.wordArt),...e.children.map(t=>jp(t))])}function xl(e){return k("geometry","Geometry",[g("preset","Preset",e?.preset??""),g("custom-path-count","Custom Path Count",e?.customPathCount==null?"":String(e.customPathCount)),g("adjustments","Adjustments",e?.adjustments.join(", ")??""),g("custom-geometry-json","Custom Geometry JSON",Te(e?.customGeometry??null))])}function Cl(e){return k("transform","Transform",[g("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),g("height-emu","Height (EMU)",e?.heightEmu==null?"":String(e.heightEmu)),g("offset-x-emu","Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),g("offset-y-emu","Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),g("rotation","Rotation",e?.rotation==null?"":String(e.rotation)),g("flip-h","Flip H",e?.flipH==null?"":String(e.flipH)),g("flip-v","Flip V",e?.flipV==null?"":String(e.flipV))])}function Pl(e){return k("group-transform","Group Transform",[g("child-offset-x-emu","Child Offset X (EMU)",e?.childOffsetXEmu==null?"":String(e.childOffsetXEmu)),g("child-offset-y-emu","Child Offset Y (EMU)",e?.childOffsetYEmu==null?"":String(e.childOffsetYEmu)),g("child-width-emu","Child Width (EMU)",e?.childWidthEmu==null?"":String(e.childWidthEmu)),g("child-height-emu","Child Height (EMU)",e?.childHeightEmu==null?"":String(e.childHeightEmu))])}function Rl(e){return k("fill","Fill",[g("kind","Kind",e?.kind??""),g("color","Color",e?.color??""),g("secondary-color","Secondary Color",e?.secondaryColor??""),g("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),g("gradient-angle","Gradient Angle",e?.gradientAngle==null?"":String(e.gradientAngle)),g("gradient-path","Gradient Path",e?.gradientPath??""),g("pattern-preset","Pattern Preset",e?.patternPreset??""),g("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),g("color-source-json","Color Source JSON",Te(e?.colorSource??null)),g("secondary-color-source-json","Secondary Color Source JSON",Te(e?.secondaryColorSource??null)),g("gradient-stops-json","Gradient Stops JSON",e?Te(e.gradientStops??[]):""),g("picture-fill-json","Picture Fill JSON",Te(e?.pictureFill??null))])}function Tl(e){return k("stroke","Stroke",[g("kind","Kind",e?.kind??""),g("color","Color",e?.color??""),g("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),g("dash","Dash",e?.dash??""),g("cap","Cap",e?.cap??""),g("join","Join",e?.join??""),g("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),g("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),g("compound","Compound",e?.compound??""),g("color-source-json","Color Source JSON",Te(e?.colorSource??null)),g("head-end-json","Head End JSON",Te(e?.headEnd??null)),g("tail-end-json","Tail End JSON",Te(e?.tailEnd??null))])}function kl(e){return k("effects","Effects",[g("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),g("style-ref-color-source-json","Style Ref Color Source JSON",Te(e?.styleRefColorSource??null)),g("effect-nodes-json","Effect Nodes JSON",e?Te(e.effectNodes??[]):""),g("glow-json","Glow JSON",Te(e?.glow??null)),g("outer-shadow-json","Outer Shadow JSON",Te(e?.outerShadow??null)),g("inner-shadow-json","Inner Shadow JSON",Te(e?.innerShadow??null)),g("soft-edge-json","Soft Edge JSON",Te(e?.softEdge??null)),g("blur-json","Blur JSON",Te(e?.blur??null)),g("reflection-json","Reflection JSON",Te(e?.reflection??null)),g("preset-shadow-json","Preset Shadow JSON",Te(e?.presetShadow??null)),g("effect-dag-json","Effect DAG JSON",Te(e?.effectDag??null))])}function XC(e){return k("anchor","Anchor",[g("kind","Kind",e?.kind??""),g("wrap","Wrap",e?.wrap??""),g("behind-doc","Behind Doc",e?.behindDoc==null?"":String(e.behindDoc)),g("allow-overlap","Allow Overlap",e?.allowOverlap==null?"":String(e.allowOverlap)),g("layout-in-cell","Layout In Cell",e?.layoutInCell==null?"":String(e.layoutInCell)),g("relative-height","Relative Height",e?.relativeHeight==null?"":String(e.relativeHeight)),g("dist-top-emu","Dist Top (EMU)",e?.distTopEmu==null?"":String(e.distTopEmu)),g("dist-bottom-emu","Dist Bottom (EMU)",e?.distBottomEmu==null?"":String(e.distBottomEmu)),g("dist-left-emu","Dist Left (EMU)",e?.distLeftEmu==null?"":String(e.distLeftEmu)),g("dist-right-emu","Dist Right (EMU)",e?.distRightEmu==null?"":String(e.distRightEmu)),g("position-h","Position H",e?.positionH??""),g("position-v","Position V",e?.positionV??""),g("offset-x-emu","Anchor Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),g("offset-y-emu","Anchor Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),g("align-h","Align H",e?.alignH??""),g("align-v","Align V",e?.alignV??"")])}function El(e){return k("connector","Connector",[g("connector-type","Connector Type",e?.connectorType??""),g("begin-shape-id","Begin Shape Id",e?.beginShapeId??""),g("end-shape-id","End Shape Id",e?.endShapeId??"")])}function Ml(e){return k("picture","Picture",[g("src","Source",e?.src??""),g("alt","Alt",e?.alt??""),g("title","Title",e?.title??""),g("relationship-id","Relationship Id",e?.relationshipId??""),g("blip-fill-json","Blip Fill JSON",Te(e?.blipFill??null)),g("hyperlink-url","Hyperlink URL",e?.hyperlink?.url??""),g("hyperlink-tooltip","Hyperlink Tooltip",e?.hyperlink?.tooltip??"")])}function Il(e){return k("word-art","WordArt",[g("text","Text",e?.text??""),g("preset","Preset",e?.preset??"")])}function Al(e){return[g("label","Label",e.label??""),g("shape-type","Shape Type",e.shapeType??""),g("group-kind","Group Kind",e.groupKind??""),g("is-watermark","Is Watermark",e.isWatermark==null?"":String(e.isWatermark)),Wo("text-body","Text Body",e.textBody),xl(e.geometry),Cl(e.transform),Pl(e.groupTransform??null),Rl(e.fill),Tl(e.stroke),kl(e.effects??null),XC(e.anchor),El(e.connector),Ml(e.picture),Il(e.wordArt),...e.children.map(t=>jp(t))]}function Qr(e){return k("shape-child","Child Object",[g("kind","Kind",e),g("id","Id",""),g("label","Label",""),Wo("text-body","Text Body",null),xl(null),Cl(null),Pl(null),Rl(null),Tl(null),kl(null),El(null),Ml(null),Il(null)])}function ZC(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function GC(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function $C(){return[{label:"Child Shape",createEntry:()=>Qr("shape")},{label:"Child Group",createEntry:()=>Qr("group")},{label:"Text Box",createEntry:()=>Qr("textBox")},{label:"Connector",createEntry:()=>Qr("connector")},{label:"Picture",createEntry:()=>Qr("picture")},{label:"WordArt",createEntry:()=>Qr("wordArt")}]}function Nl(e={}){let t=ZC(e.containerKey),r=GC(e.childKeys),o=(t==null||t==="shape-child")&&!r.has("text-body");return t==="text-body"?[{label:"Paragraph",createEntry:()=>g("paragraph","Paragraph","")}]:t!=null&&t!=="shape-child"?[]:[...o?[{label:"Text Body",createEntry:()=>is("text-body","Text Body")}]:[],...$C()]}import{normalizeOoxmlShapeModel as YC}from"@datalking/begonia-engine";function JC(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Vp(e){return{kind:z(P(e,"kind"))??"unknown",color:z(P(e,"color")),secondaryColor:z(P(e,"secondary-color")),opacity:ie(P(e,"opacity")),gradientAngle:ie(P(e,"gradient-angle")),gradientPath:z(P(e,"gradient-path")),patternPreset:z(P(e,"pattern-preset")),styleRefIndex:ie(P(e,"style-ref-index")),colorSource:Re(P(e,"color-source-json")),secondaryColorSource:Re(P(e,"secondary-color-source-json")),gradientStops:Re(P(e,"gradient-stops-json"))??[],pictureFill:Re(P(e,"picture-fill-json"))}}function Lp(e){return{kind:z(P(e,"kind"))??"unknown",color:z(P(e,"color")),widthEmu:ie(P(e,"width-emu")),dash:z(P(e,"dash")),cap:z(P(e,"cap")),join:z(P(e,"join")),opacity:ie(P(e,"opacity")),styleRefIndex:ie(P(e,"style-ref-index")),compound:z(P(e,"compound")),colorSource:Re(P(e,"color-source-json")),headEnd:Re(P(e,"head-end-json")),tailEnd:Re(P(e,"tail-end-json"))}}function Fp(e){return{styleRefIndex:ie(P(e,"style-ref-index")),styleRefColorSource:Re(P(e,"style-ref-color-source-json")),effectNodes:Re(P(e,"effect-nodes-json"))??[],glow:Re(P(e,"glow-json")),outerShadow:Re(P(e,"outer-shadow-json")),innerShadow:Re(P(e,"inner-shadow-json")),softEdge:Re(P(e,"soft-edge-json")),blur:Re(P(e,"blur-json")),reflection:Re(P(e,"reflection-json")),presetShadow:Re(P(e,"preset-shadow-json")),effectDag:Re(P(e,"effect-dag-json"))}}function Hp(e){let t=ke(e,"geometry");return t?{preset:z(P(t.children,"preset")),customPathCount:ie(P(t.children,"custom-path-count")),adjustments:JC(P(t.children,"adjustments")),customGeometry:Re(P(t.children,"custom-geometry-json"))}:null}function zp(e){let t=ke(e,"transform");return t?{widthEmu:ie(P(t.children,"width-emu")),heightEmu:ie(P(t.children,"height-emu")),offsetXEmu:ie(P(t.children,"offset-x-emu")),offsetYEmu:ie(P(t.children,"offset-y-emu")),rotation:ie(P(t.children,"rotation")),flipH:pe(P(t.children,"flip-h")),flipV:pe(P(t.children,"flip-v"))}:null}function qp(e){let t=ke(e,"group-transform");return t?{childOffsetXEmu:ie(P(t.children,"child-offset-x-emu")),childOffsetYEmu:ie(P(t.children,"child-offset-y-emu")),childWidthEmu:ie(P(t.children,"child-width-emu")),childHeightEmu:ie(P(t.children,"child-height-emu"))}:null}function Wp(e){let t=ke(e,"connector");return t?{connectorType:z(P(t.children,"connector-type")),beginShapeId:z(P(t.children,"begin-shape-id")),endShapeId:z(P(t.children,"end-shape-id"))}:null}function Kp(e){let t=ke(e,"picture");if(!t)return null;let r=z(P(t.children,"hyperlink-url"));return{src:z(P(t.children,"src")),alt:z(P(t.children,"alt")),title:z(P(t.children,"title")),relationshipId:z(P(t.children,"relationship-id")),blipFill:Re(P(t.children,"blip-fill-json")),hyperlink:r?{url:r,tooltip:z(P(t.children,"hyperlink-tooltip"))}:null}}function _p(e){let t=ke(e,"word-art");return t?{text:z(P(t.children,"text")),preset:z(P(t.children,"preset"))}:null}function Up(e){return ns(gt(e,"text-body")[0]??null)}function QC(e){let t=ke(e,"anchor");return t?{kind:z(P(t.children,"kind"))??"unknown",wrap:z(P(t.children,"wrap"))??"unknown",behindDoc:pe(P(t.children,"behind-doc")),allowOverlap:pe(P(t.children,"allow-overlap")),layoutInCell:pe(P(t.children,"layout-in-cell")),relativeHeight:ie(P(t.children,"relative-height")),distTopEmu:ie(P(t.children,"dist-top-emu")),distBottomEmu:ie(P(t.children,"dist-bottom-emu")),distLeftEmu:ie(P(t.children,"dist-left-emu")),distRightEmu:ie(P(t.children,"dist-right-emu")),positionH:z(P(t.children,"position-h")),positionV:z(P(t.children,"position-v")),offsetXEmu:ie(P(t.children,"offset-x-emu")),offsetYEmu:ie(P(t.children,"offset-y-emu")),alignH:z(P(t.children,"align-h")),alignV:z(P(t.children,"align-v"))}:null}function eP(e){return e==="shape"||e==="group"||e==="textBox"||e==="connector"||e==="picture"||e==="wordArt"}function Xp(e){let t=ke(e,"fill"),r=ke(e,"stroke"),o=ke(e,"effects"),n=P(e,"kind");return{kind:eP(n)?n:"unknown",id:z(P(e,"id")),label:z(P(e,"label")),textBody:Up(e),geometry:Hp(e),transform:zp(e),groupTransform:qp(e),fill:t?Vp(t.children):null,stroke:r?Lp(r.children):null,effects:o?Fp(o.children):null,connector:Wp(e),picture:Kp(e),wordArt:_p(e),children:gt(e,"shape-child").map(i=>Xp(i.children))}}function Ol(e,t){let r=ke(e,"fill"),o=ke(e,"stroke"),n=ke(e,"effects");return YC({...t,label:z(P(e,"label")),shapeType:z(P(e,"shape-type")),groupKind:z(P(e,"group-kind")),isWatermark:pe(P(e,"is-watermark")),textBody:Up(e),geometry:Hp(e),transform:zp(e),groupTransform:qp(e),fill:r?Vp(r.children):null,stroke:o?Lp(o.children):null,effects:n?Fp(n.children):null,anchor:QC(e),connector:Wp(e),picture:Kp(e),wordArt:_p(e),children:gt(e,"shape-child").map(i=>Xp(i.children))},t.label??"Shape")}function Dl(e){let t=String(e.attrs.label??"Shape"),r=String(e.attrs.text??""),o=Zp("shape",{label:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=Zp("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 rP(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function oP(){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 nP(e,t,r,o){let n=tP(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 Gp(){return e=>{let t=e,r=Lo("div"),{header:o,heading:n}=Fo("Shape","shape"),i=Ho(),{section:s}=Jr("Visual Preview"),a=qt("Preview uses begonia\u2019s clean-room SVG geometry renderer for preset, connector, group, and custom-path shape families."),l=oP(),{section:c}=Jr("Native Subtree"),d=qt("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=ar();u.style.justifyContent="flex-start";let m=Ue("Remove Selected","danger"),p=rP(),f=ar();f.style.justifyContent="space-between",f.style.alignItems="center";let w=qt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),v=Ue("Apply"),C=Ue("Remove Shape","danger");w.style.marginRight="auto",f.append(w,v,C),s.append(a,l),c.append(d,u,p,m),r.append(o,i,s,c,f);let R=null,S=(T,A)=>{u.replaceChildren(),Nl({containerKey:T,childKeys:A}).forEach(D=>{let O=Ue(D.label);O.addEventListener("click",()=>{B.appendEntry(D.createEntry())}),u.append(O)})},B=qo(p,[],{onChange(){R?.markDirty()},onSelectionChange(T){S(T.containerKey,T.childKeys)}});m.addEventListener("click",()=>{B.removeSelectedEntry()}),R=Vo({applyButton:v,onCommit:()=>{let T=Dl(t),A=Ol(B.readEntries(),T.model),D=Dp(T.model,A);return D.length===0?!1:(sr(r,{family:"shape",action:"apply-shape-edits",objectId:T.objectId,model:A,edits:D}),!0)},root:r,status:w});let y=T=>{t=T;let A=Dl(T);n.textContent=A.label;let D=nP(l,A.objectId,A.label,A.model);i.textContent=`${A.evidence.shapeType??"shape"} | ${A.evidence.childCount} child objects | ${A.evidence.anchorKind} | preview ${D.kind}${D.supported?"":" fallback"}`,R?.reset(),B.setEntries(Al(A.model))};return v.addEventListener("click",()=>{R?.flush()}),C.addEventListener("click",()=>{R?.reset();let T=Dl(t);sr(r,{family:"shape",action:"remove-advanced-ooxml",objectId:T.objectId})}),y(e),{dom:r,destroy(){R?.destroy(),B.destroy()},update(T){return T.type!==t.type?!1:(y(T),!0)},stopEvent(T){return zo(T.target)||Do(T.target)&&p.contains(T.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{inlineOoxmlDrawingMetadata as iP}from"@datalking/begonia-editor-adapters";function $p(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function sP(){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 Yp(e,t){let r=iP(t),o=r?.label||String(t.attrs.label??"Drawing"),n=r?.family??(t.attrs.family==="chart"?"chart":"shape"),i=r?.drawing,s=$p(r?.width??i?.width,80),a=$p(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 Jp(){return e=>{let t=e,r=sP();return Yp(r,e),{dom:r,update(o){return o.type!==t.type?!1:(t=o,Yp(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 jl="browser-advanced-ooxml-nodeviews";function Qp(){return{id:jl,createPlugins(){return[]},createNodeViews(){return{ooxml_math:Ep(),ooxml_chart:xp(),ooxml_shape:Gp(),inline_ooxml_drawing:Jp()}}}}function as(e=[]){return e.some(t=>t.id===jl)?[...e]:[...e,Qp()]}import{createEditorSessionController as w0}from"@datalking/begonia-editor-ui";function Vl(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}function Ko(e){return typeof e=="object"&&e!==null}function Ll(e){return typeof e=="string"?e.trim()?e:null:!Ko(e)||typeof e.text!="string"?null:{text:e.text,displayMode:e.displayMode==="block"?"block":e.displayMode==="inline"?"inline":void 0}}function ef(e){return typeof e=="string"?e.trim()?e:null:!Ko(e)||typeof e.title!="string"?null:{title:e.title}}function tf(e){return typeof e=="string"?e.trim()?e:null:!Ko(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 rf(e,t=0){if(typeof e=="string")return{id:null,name:e.trim()||`Series ${t+1}`,categories:[],values:[],color:null};if(!Ko(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 of(e,t=0){return typeof e=="string"?{id:null,kind:"category",title:e.trim()||`Axis ${t+1}`,formatCode:null}:Ko(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 nf(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(!Ko(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 Xe(e){return e?e.surface??null:null}function ls(e){if(!e)return null;try{return e.surface??null}catch{return null}}function be(e){let t=Xe(e);if(!t)throw new Error("Browser editor surface is not available on this controller.");return t}function aP(e,t=!0){return{ok:!0,changed:t,value:e}}function lt(e){return{ok:!1,changed:!1,reason:e}}function St(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?lt(e.reason):aP(e)}function Kn(e){return typeof e=="object"&&e!==null}function lP(e){return e==="block"?"block":"inline"}function Fl(e){return{chartType:"barChart",styleId:null,styleSource:null,title:e,subtitle:null,series:[],axes:[],legend:null,plotArea:null,textBody:{paragraphs:[e],plainText:e}}}function Hl(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 cP(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 dP(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 uP(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:Vl(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 mP(e){if(typeof e=="string"){let r=e.trim();return r?{text:r,displayMode:"inline",label:null}:null}if(!Kn(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 pP(e){if(typeof e=="string"){let o=e.trim()||"Chart";return{model:Fl(o),options:{label:o}}}if(!Kn(e))return{model:Fl("Chart"),options:{label:"Chart"}};let t=typeof e.title=="string"&&e.title.trim()?e.title.trim():"Chart";return{model:Kn(e.model)?e.model:Fl(t),options:{label:typeof e.label=="string"?e.label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function fP(e){if(typeof e=="string"){let o=e.trim()||"Shape";return{model:Hl(o),options:{label:o}}}if(!Kn(e))return{model:Hl("Shape"),options:{label:"Shape"}};let t=typeof e.label=="string"&&e.label.trim()?e.label.trim():"Shape";return{model:Kn(e.model)?e.model:Hl(t),options:{label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function sf(e){let t=e.getState().advancedOoxml.selected;return t?.family==="chart"?e.documentApi.ooxml.charts.getById(t.objectId):null}function wP(e){let t=e.getState().advancedOoxml.selected;return t?.family==="math"?e.documentApi.ooxml.math.getById(t.objectId):null}function gP(e){let t=e.getState().advancedOoxml.selected;return t?.family==="shape"?e.documentApi.ooxml.shapes.getById(t.objectId):null}function af(e,t,r){let o=be(e);switch(t){case"insert-math-inline":{let n=mP(r);if(!n)return lt("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 St(s)}case"insert-chart-block":{let n=pP(r),i=o.trackingEnabled?e.insertChartAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertChartAfterCurrentBlock(n.model,n.options);return St(i)}case"insert-shape-block":{let n=fP(r),i=o.trackingEnabled?e.insertShapeAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertShapeAfterCurrentBlock(n.model,n.options);return St(i)}case"remove-selected-ooxml":return St(e.removeSelectedAdvancedOoxml());case"selected-math-set-plain-text":{let n=Ll(r);if(!n)return lt("Expected math plain text for the selected OOXML equation.");let i=typeof n=="string"?e.setSelectedMathPlainText(n):e.setSelectedMathPlainText(n.text,n.displayMode);return St(i)}case"selected-math-toggle-display-mode":{let n=wP(e);if(!n)return lt("No advanced OOXML math node is selected.");let i=lP(n.familyData?.displayMode)==="block"?"inline":"block";return St(e.setSelectedMathDisplayMode(i))}case"selected-chart-set-title":{let n=ef(r);return n?St(e.setSelectedChartTitle(typeof n=="string"?n:n.title)):lt("Expected a chart title for the selected OOXML chart.")}case"selected-chart-add-series":{let n=sf(e);if(!n)return lt("No advanced OOXML chart node is selected.");let i=rf(r,n.familyData?.model?.series.length??0);return i?St(e.appendSelectedChartSeries(cP(i,n.familyData?.model?.series.length??0))):lt("Expected a series payload for the selected OOXML chart.")}case"selected-chart-add-axis":{let n=sf(e);if(!n)return lt("No advanced OOXML chart node is selected.");let i=of(r,n.familyData?.model?.axes.length??0);return i?St(e.appendSelectedChartAxis(dP(i,n.familyData?.model?.axes.length??0))):lt("Expected an axis payload for the selected OOXML chart.")}case"selected-shape-set-text-body":{let n=Ll(r);if(!n)return lt("Expected replacement text for the selected OOXML shape.");let i=typeof n=="string"?n:n.text;return St(e.setSelectedShapeTextBody(Vl(i)))}case"selected-shape-set-fill":{let n=tf(r);if(!n)return lt("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 St(i)}case"selected-shape-add-child":{let n=gP(e);if(!n)return lt("No advanced OOXML shape node is selected.");let i=nf(r,n.familyData?.model?.children.length??0);if(!i)return lt("Expected a child payload for the selected OOXML shape.");let s=uP(i.child,n.familyData?.model?.children.length??0);return St(i.parentId?e.appendSelectedShapeChildToParent(i.parentId,s):e.appendSelectedShapeChild(s))}default:return null}}import{DELETION_MARK_NAME as hP}from"@datalking/begonia-engine";import{isDocumentNodePathIndex as vP}from"@datalking/begonia-document-model";import{NodeSelection as SP}from"prosemirror-state";function W(e){return e instanceof SP||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 cs(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function He(e){return t=>cs(t.attrs[e])}function lf(...e){return t=>{for(let r of e){let o=cs(t.attrs[r]);if(o)return o}return null}}function zl(e){let t=cs(e.attrs.threadId);return t?`${t}\0${cs(e.attrs.entryId)??t}`:null}function cf(){return null}function df(e){return e==="paragraph"||e==="heading"}function _o(e,t){return e===t||df(e)&&df(t)}var ql=Object.freeze({bookmark_anchor:He("bookmarkId"),bookmark_end:He("bookmarkId"),comment_anchor:zl,comment_range_end:zl,comment_range_start:zl,column_break:He("columnBreakId"),endnote_reference:He("noteId"),heading:lf("paraId","sdBlockId","captionId"),horizontal_rule:cf,image:He("imageId"),inline_ooxml_drawing:He("objectId"),ooxml_chart:He("objectId"),ooxml_math:He("objectId"),ooxml_shape:He("objectId"),page_break:He("pageBreakId"),paragraph:lf("paraId","sdBlockId","captionId"),footnote_reference:He("noteId"),permission_range_end:He("rangeId"),permission_range_start:He("rangeId"),section_break:He("sectionId"),table:cf,template_block:He("fieldId"),template_field:He("fieldId")});function bP(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 eo(e){try{return bP(JSON.stringify(e.toJSON()))}catch{return null}}function mf(e,t){let r=e,o=-1;for(let n of t){if(!vP(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 yP(e,t,r,o,n,i){if(i==null)return null;let s=!1,a=!1;return e.descendants((l,c)=>c===o||!_o(l.type.name,t)||n(l)!==r?!0:(s=!0,eo(l)===i?(a=!0,!1):!0)),s&&!a?i:null}function uf(e,t,r){let o=mf(e,t.path);return!o||!_o(o.node.type.name,t.nodeType)||r(o.node)!==t.stableIdentity||t.nodeFingerprint!=null&&eo(o.node)!==t.nodeFingerprint?null:o}function BP(e,t,r){let o=[];return e.descendants((n,i)=>(_o(n.type.name,t.nodeType)&&r(n)===t.stableIdentity&&o.push({node:n,position:i}),!0)),o}function xP(e,t){return t.nodeFingerprint==null?[]:e.filter(r=>eo(r.node)===t.nodeFingerprint)}function pf(e){return!!e?.node.marks.some(t=>t.type.name===hP)}function CP(e){return e.filter(t=>!pf(t))}function Ce(e){let t=e?.selection;if(!e||!W(t))return null;let r=t.node.type.name,o=r?ql[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=eo(t.node),a=n?yP(e.doc,r,n,t.from,o,s):s;return{kind:"node",nodeType:r,stableIdentity:n,path:i,...a!=null?{nodeFingerprint:a}:{}}}function ds(e,t){let r=ql[t.nodeType];if(t.stableIdentity&&r){let i=BP(e,t,r);if(i.length===0)return null;if(i.length===1){let l=i[0];return t.nodeFingerprint==null||uf(e,t,r)?.position===l.position||eo(l.node)===t.nodeFingerprint?l:null}let s=uf(e,t,r);if(t.nodeFingerprint==null){if(!pf(s))return s;let l=CP(i);return l.length===1?l[0]:s}let a=xP(i,t);return a.length!==1?null:s?.position===a[0]?.position?s:null}let o=mf(e,t.path);if(o!=null&&_o(o.node.type.name,t.nodeType)&&(t.nodeFingerprint==null||eo(o.node)===t.nodeFingerprint))return o;if(t.nodeFingerprint==null)return null;let n=[];return e.descendants((i,s)=>(_o(i.type.name,t.nodeType)&&eo(i)===t.nodeFingerprint&&n.push({node:i,position:s}),n.length<=1)),n.length===1?n[0]:null}function ff(e,t,r){if(!r.empty||!t.stableIdentity)return!1;let o=ql[t.nodeType];if(!o)return!1;let n=!1;return e.descendants((i,s)=>_o(i.type.name,t.nodeType)&&o(i)===t.stableIdentity&&r.from>=s&&r.from<=s+i.nodeSize?(n=!0,!1):!0),n}function PP(e){let t=e.documentApi?.images;if(!t?.list)return[];let r=t.list({});return Array.isArray(r)?r:r?.items??[]}function RP(e,t){return PP(e).find(r=>r.id===t)??null}function Wt(e,t=null){return{ok:e,changed:e,reason:t}}function TP(e,t,r){let o=e.documentApi?.images;if(!o?.setSize)return Wt(!1,"This host cannot resize images.");let n=RP(e,t);if(!n)return Wt(!1,"No image with that id is in the document.");let i=us(r.width),s=us(r.height);if(i==null&&s==null)return Wt(!1,"Expected a positive width or height.");let a=us(n.width),l=us(n.height),c=i,d=s;if(c!=null&&d==null){if(a==null||l==null)return Wt(!1,"The image has no stored size to keep its proportions.");d=Math.round(c*l/a)}else if(d!=null&&c==null){if(a==null||l==null)return Wt(!1,"The image has no stored size to keep its proportions.");c=Math.round(d*a/l)}if(c==null||d==null)return Wt(!1,"Expected a positive width or height.");let u=r.unit==="pt"||r.unit==="twip"?r.unit:"px",m=o.setSize(t,{width:c,height:d,unit:u});return m?.success===!1?Wt(!1,m.failure.message):Wt(!0)}function us(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function wf(e,t,r){if(t!=="set-image-size")return null;if(typeof r!="object"||r===null)return Wt(!1,"Expected an image id and size.");let o=r,n=typeof o.imageId=="string"?o.imageId:"";return n?TP(e,n,{width:o.width,height:o.height,unit:o.unit}):Wt(!1,"Expected an image id.")}var gf=["selected-image-resize","selected-image-set-wrap","selected-image-set-alt","set-image-size"],kP=new Set(gf);function Wl(e){return kP.has(e)}var Sf=["inline","square","tight","through","topAndBottom","behind","inFront"],EP=new Set(Sf);function Kl(e){return typeof e=="string"&&EP.has(e)}function _l(e){let t=Xe(e);if(!t)return null;let r=Ce(t.view.state);return!r||r.nodeType!=="image"?null:Array.isArray(r.path)&&r.path.length>0?{path:r.path}:null}function Ul(){return{ok:!0,changed:!0,reason:null}}function lr(e){return{ok:!1,changed:!1,reason:e}}function ms(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function Xl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function MP(e,t){let r=_l(e);if(!r)return lr("No image is selected.");let o=Xl(t),n=ms(o.width),i=ms(o.height);if(n==null&&i==null)return lr("Expected a positive width or height for the image.");let s={};if(n!=null&&(s.width=n),i!=null&&(s.height=i),o.lockAspectRatio===!0&&(n==null||i==null)){let l=e.documentApi.media.get(r.path),c=ms(l?.width),d=ms(l?.height);if(c!=null&&d!=null){let u=c/d;n!=null?s.height=Math.round(n/u):i!=null&&(s.width=Math.round(i*u))}}return e.documentApi.media.update(r.path,s)?.changed?Ul():lr("The image size was unchanged.")}function IP(e,t){let r=_l(e);if(!r)return lr("No image is selected.");let o=Xl(t),n=o.mode??o.wrapMode;if(!Kl(n))return lr("Expected a supported image wrap mode.");let i=n==="inline"?{displayMode:"inline",wrapMode:null}:n==="behind"||n==="inFront"?{displayMode:"float",wrapMode:n}:{displayMode:"float",wrapMode:n};return e.documentApi.media.update(r.path,i)?.changed?Ul():lr("The image wrapping was unchanged.")}function AP(e,t){let r=_l(e);if(!r)return lr("No image is selected.");let n=Xl(t).alt;return typeof n!="string"&&n!==null?lr("Expected alternative text for the image."):e.documentApi.media.update(r.path,{alt:n})?.changed?Ul():lr("The image description was unchanged.")}function hf(e,t,r){let o=wf(e,t,r);if(o)return o;switch(t){case"selected-image-resize":return MP(e,r);case"selected-image-set-wrap":return IP(e,r);case"selected-image-set-alt":return AP(e,r);default:return null}}var vf=new Set(["table_cell","table_header"]);function ps(e,t){let r=[];for(let o=1;o<=t;o+=1)r.push(e.index(o-1));return r}function fs(e,t){for(let r=e.depth;r>0;r-=1)if(t(e.node(r)))return r;return null}function Zl(e,t){let r=e.selection.$from,o=fs(r,c=>vf.has(c.type.name));if(o==null)return null;let n=fs(r,c=>c.type.name==="table");if(n==null||n>=o)return null;let i=ps(r,n),s=ps(r,o),a=t.find(c=>c.path.join(".")===i.join("."));if(!a)return null;let l=s.join(".");for(let c of a.rows)for(let d of c.cells)if(d.path.join(".")===l)return{tablePath:i,cellPath:s,rowIndex:d.rowIndex,columnIndex:d.columnIndex,rowCount:a.rowCount,columnCount:a.columnCount,colSpan:d.colSpan,rowSpan:d.rowSpan};return null}function bf(e,t){let r=Zl(e,t);if(!r)return null;let o=e.selection.$to,n=fs(o,d=>vf.has(d.type.name)),i=fs(o,d=>d.type.name==="table");if(n==null||i==null||i>=n)return{start:r,end:r};let s=ps(o,i);if(s.join(".")!==r.tablePath.join("."))return{start:r,end:r};let a=ps(o,n),l=t.find(d=>d.path.join(".")===s.join(".")),c=a.join(".");for(let d of l?.rows??[])for(let u of d.cells)if(u.path.join(".")===c)return{start:r,end:{...r,cellPath:a,rowIndex:u.rowIndex,columnIndex:u.columnIndex,colSpan:u.colSpan,rowSpan:u.rowSpan}};return{start:r,end:r}}var Gl=e=>({changed:!1,reason:e});function yf(e){return e.tables.list()}function NP(e,t){return Zl(t,yf(e))??Gl("Place the caret inside a table first.")}function OP(e){return"changed"in e}function DP(e){return e.rowCount<=1}function jP(e){return e.columnCount<=1}function cr(e){return e.success?{changed:!0,reason:null}:{changed:!1,reason:e.reason??"The table command failed."}}function Bf(e,t,r){if(!r.startsWith("table-"))return null;let o=NP(e,t);if(OP(o))return o;let n=o,{tablePath:i,rowIndex:s,columnIndex:a}=n;switch(r){case"table-insert-row-above":return cr(e.tables.insertRow(i,s,[],{}));case"table-insert-row-below":return cr(e.tables.insertRow(i,s+1,[],{}));case"table-insert-column-left":return cr(e.tables.insertColumn(i,a,[]));case"table-insert-column-right":return cr(e.tables.insertColumn(i,a+1,[]));case"table-delete-row":return cr(DP(n)?e.tables.delete(i):e.tables.removeRow(i,s));case"table-delete-column":return cr(jP(n)?e.tables.delete(i):e.tables.removeColumn(i,a));case"table-delete":return cr(e.tables.delete(i));case"table-merge-cells":{let l=bf(t,yf(e));return l?l.start.rowIndex===l.end.rowIndex&&l.start.columnIndex===l.end.columnIndex?Gl("Select at least two cells to merge."):cr(e.tables.mergeCells({tablePath:i,start:{rowIndex:l.start.rowIndex,columnIndex:l.start.columnIndex},end:{rowIndex:l.end.rowIndex,columnIndex:l.end.columnIndex}})):Gl("Select the cells to merge first.")}case"table-split-cell":return cr(e.tables.unmergeCells({tablePath:i,rowIndex:s,columnIndex:a}));default:return null}}import{normalizeHyperlinkHref as If}from"@datalking/begonia-document-model";import{clonePageViewportAnchor as Ef,hasFreshViewportRequest as zP,normalizeViewportRequestKey as qP,samePageViewportAnchor as WP,sameViewportRequestKey as KP}from"@datalking/begonia-layout-renderer/core";import{hasLogicalViewportAnchorHint as VP}from"@datalking/begonia-layout-renderer/core";var _n=100,Nt=1,Cf=1e-6;function Ze(e){return typeof e=="number"&&Number.isFinite(e)}function ht(e,t,r=0){return e===t||Math.abs(e-t)<=r}function Pf(e,t,r=0){return e==null||t==null?e===t:ht(e,t,r)}function Rf(e,t=0){return Ze(e)?Math.max(0,Math.trunc(e)):t}function Yl(e){return Ze(e)&&Number.isInteger(e)&&e>=0?e:null}function dr(e){return Ze(e)&&Number.isInteger(e)&&e>0?e:null}function $l(e,t){if(!Array.isArray(e))return[];let r=e.filter(o=>Ze(o)&&Number.isInteger(o)&&o>=t);return[...new Set(r)].sort((o,n)=>o-n)}function LP(e){return e.map(t=>t+1)}function xf(e){return e.map(t=>t-1)}function FP(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Jl(e,t){let r=$l(t,1);if(r.length>0){let n=$l(e,0);return n.length>0&&!FP(xf(r),n)?null:{pageIndexes:xf(r),pageNumbers:r}}let o=$l(e,0);return{pageIndexes:o,pageNumbers:LP(o)}}function ws(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function gs(e){return e==="paginated"||e==="web"?e:null}function Tf(e){return Ze(e)&&e>0?e:null}function Ql(e,t){let r=gs(e),o=ws(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 HP(e){return e==="header"||e==="body"||e==="footer"}function kf(e){return HP(e?.region)&&!VP(e)&&e?.fragmentIndex==null&&e?.columnIndex==null&&e?.blockOffsetTopPx==null&&e?.blockOffsetTopRatio==null&&e?.blockOffsetLeftPx==null&&e?.blockOffsetLeftRatio==null}function Kt(e,t){let r=dr(t),o=Yl(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 _P(e){if(e.visiblePageNumbers.length>0){let o=dr(e.firstVisiblePageNumber),n=dr(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=dr(e.firstVisiblePageNumber),r=dr(e.lastVisiblePageNumber);return t!=null&&r!=null&&t>r?null:{firstVisiblePageNumber:t,lastVisiblePageNumber:r}}function UP(e){return!!(e&&typeof e=="object"&&(Object.hasOwn(e,"pageNumber")||Object.hasOwn(e,"pageIndex")))}function Mf(e,t,r){let o=Ze(t)?Math.max(0,t):Math.max(0,(Ze(r)?r:e)-e);return{size:o,end:e+o}}var hs=10,vs=500;function vt(e){return!Ze(e)||e<=0?null:Math.min(vs,Math.max(hs,e))}function De(e){return qP(e)}function bs(e,t){return KP(e,t)}function tc(e,t){return zP(e,t)}function ur(e){return vt(e?.zoomPercent)??_n}function Uo(e,t){return re(e)?.flowMode===t}function Xo(e,t){return re(e)?.layoutMode===t}function to(e,t,r){return Uo(e,t)&&Xo(e,r)}function Ss(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Zo(e,t){return WP(e,t)}function ec(e){let t=dr(e?.pageNumber),r=Yl(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"&&UP(e)&&!ec(e))return null;let r=Ef(e);if(r)return r;if(!e||typeof e!="object")return null;let o=ec(e)??ec(t);return o?Ef({...e,...o}):null}function XP(e,t){if(!e)return!1;let r=e.visiblePageNumbers??e.mountedPageNumbers;if(Array.isArray(r)&&r.includes(t))return!0;let o=dr(e.firstVisiblePageNumber),n=dr(e.lastVisiblePageNumber);return o!=null&&n!=null&&t>=o&&t<=n}function $o(e){let t=Kt(e?.anchorPageIndex,e?.anchorPageNumber).pageNumber??Kt(e?.currentPageIndex,e?.currentPageNumber).pageNumber,r=Go(e?.viewportAnchor??null,{pageNumber:t});return r?t!=null&&r.pageNumber!==t?kf(r)||r.region!=null&&XP(e,r.pageNumber)?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 et(e,t){let r=re(e),o=re(t);return!r||!o?r===o:Un(r,o)&&Ss(r.mountedPageIndexes,o.mountedPageIndexes)&&Ss(r.mountedPageNumbers,o.mountedPageNumbers)&&ht(r.topSpacer,o.topSpacer,Nt)&&ht(r.bottomSpacer,o.bottomSpacer,Nt)&&ht(r.leftSpacer,o.leftSpacer,Nt)&&ht(r.rightSpacer,o.rightSpacer,Nt)}function Un(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)&&Ss(r.visiblePageIndexes,o.visiblePageIndexes)&&Ss(r.visiblePageNumbers,o.visiblePageNumbers)&&r.firstVisiblePageNumber===o.firstVisiblePageNumber&&r.lastVisiblePageNumber===o.lastVisiblePageNumber&&ht(r.viewportTop,o.viewportTop,Nt)&&ht(r.viewportBottom,o.viewportBottom,Nt)&&ht(r.viewportHeight,o.viewportHeight,Nt)&&ht(r.viewportLeft,o.viewportLeft,Nt)&&ht(r.viewportRight,o.viewportRight,Nt)&&ht(r.viewportWidth,o.viewportWidth,Nt)&&r.layoutMode===o.layoutMode&&r.flowMode===o.flowMode&&Pf(r.scale,o.scale,Cf)}function re(e){if(!e||typeof e!="object")return null;let t=Ql(e.flowMode,e.layoutMode);if(!t)return null;let r=Kt(e.currentPageIndex,e.currentPageNumber),o=Kt(e.anchorPageIndex,e.anchorPageNumber),n=Ze(e.viewportTop)?e.viewportTop:0,i=Ze(e.viewportLeft)?e.viewportLeft:0,s=Mf(n,e.viewportHeight,e.viewportBottom),a=Mf(i,e.viewportWidth,e.viewportRight),l=Jl(e.visiblePageIndexes,e.visiblePageNumbers);if(!l)return null;let c=Jl(e.mountedPageIndexes,e.mountedPageNumbers);if(!c)return null;let d=_P({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:Rf(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:Ze(e.topSpacer)?Math.max(0,e.topSpacer):0,bottomSpacer:Ze(e.bottomSpacer)?Math.max(0,e.bottomSpacer):0,leftSpacer:Ze(e.leftSpacer)?Math.max(0,e.leftSpacer):0,rightSpacer:Ze(e.rightSpacer)?Math.max(0,e.rightSpacer):0,layoutMode:t.layoutMode,flowMode:t.flowMode,scale:Tf(e.scale)}}function _t(e,t){let r=gs(e?.flowMode),o=ws(e?.layoutMode),n=e&&r==="web"&&o!=null&&o!=="vertical"?{...e,layoutMode:"vertical"}:e,i=re(n);if(!i)return null;let s=i.flowMode??gs(t.flowMode),a=s==="web"?"vertical":i.layoutMode??ws(t.layoutMode);return{...i,flowMode:s,layoutMode:a}}var Af=8,Nf=96;function ct(e){return typeof e=="object"&&e!==null}function ZP(e,t=!0){return typeof e=="boolean"?e:ct(e)&&typeof e.changed=="boolean"?e.changed:t}function X(e,t=ZP(e)){return{ok:!0,changed:t,value:e}}function ye(e){return{ok:!1,changed:!1,reason:e}}function Df(e){if(typeof e=="string"){let r=If(e);return r?{href:r,title:null}:null}if(!ct(e))return null;let t=If(e.href);return t?{href:t,title:typeof e.title=="string"?e.title:e.title==null?null:String(e.title)}:null}function jf(e){return typeof e=="string"?e.trim()?e:null:!ct(e)||typeof e.text!="string"||e.text.trim().length===0?null:{text:e.text,isInternal:typeof e.isInternal=="boolean"?e.isInternal:void 0}}function Yo(e){if(e==null)return null;if(typeof e!="string")return;let t=e.trim();if(t)return t.toLowerCase()==="none"?null:t}function oc(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?Math.min(Nf,Math.max(Af,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(Nf,Math.max(Af,r)):void 0}function ic(e){let t=Yo(e);if(t!==void 0)return t;if(ct(e)){if(Object.hasOwn(e,"color"))return Yo(e.color);if(Object.hasOwn(e,"value"))return Yo(e.value)}}function Vf(e){let t=Yo(e);if(t!==void 0)return t;if(ct(e)){if(Object.hasOwn(e,"fontFamily"))return Yo(e.fontFamily);if(Object.hasOwn(e,"value"))return Yo(e.value)}}function Lf(e){let t=oc(e);if(t!==void 0)return t;if(ct(e)){if(Object.hasOwn(e,"fontSize"))return oc(e.fontSize);if(Object.hasOwn(e,"value"))return oc(e.value)}}function Of(e){return Math.min(vs,Math.max(hs,e))}function nc(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?Of(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?Of(o):null}function Ff(e){let t=nc(e);if(t!=null)return t;if(!ct(e))return null;let r=nc(e.zoomPercent);if(r!=null)return{zoomPercent:r};let o=nc(e.zoom);return o!=null?{zoom:o}:null}function Hf(e){return typeof e=="string"?e:!ct(e)||typeof e.query!="string"?null:{query:e.query,options:ct(e.options)?e.options:void 0}}function sc(e){return typeof e=="string"?e:!ct(e)||typeof e.text!="string"?null:{text:e.text,hitId:typeof e.hitId=="string"?e.hitId:e.hitId==null?null:String(e.hitId)}}function zf(e){return typeof e=="string"?e:!ct(e)||typeof e.text!="string"?null:{text:e.text,diagnosticId:typeof e.diagnosticId=="string"?e.diagnosticId:e.diagnosticId==null?null:String(e.diagnosticId)}}function qf(e){if(typeof e=="string"){let n=e.trim();return n?{src:n}:null}if(!ct(e))return null;let t=typeof e.src=="string"?e.src.trim():"";if(!t)return null;let r=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?n:null,o=n=>typeof n=="string"&&n.trim()?n.trim():null;return{src:t,alt:o(e.alt),name:o(e.name),title:o(e.title),width:r(e.width),height:r(e.height),mime:o(e.mime)}}function Wf(e,t,r){let o=e.structure.createImage({src:r.src,alt:r.alt??null,name:r.name??null,title:r.title??null,width:r.width??null,height:r.height??null,mime:r.mime??null,displayMode:"block"});return t.insertBlock(o)?{changed:!0,reason:null}:{changed:!1,reason:"The image cannot be inserted at the current selection."}}var GP=3,$P=3;function Kf(e,t){let r=Array.from({length:GP},()=>Array.from({length:$P},()=>"")),o=e.structure.createTable(r,{});return t.insertBlock(o)?{changed:!0,reason:null}:{changed:!1,reason:"The table cannot be inserted at the current selection."}}import{resolveCollapsedSelectionFormattingMarks as sk}from"@datalking/begonia-engine";import{addressableBlockTypeForNodeType as ow,formatAddressableBlockId as qR,formatAddressableBlockIdWithLogicalId as nw}from"@datalking/begonia-doc-service/structure";import{normalizeDocumentStoryLocator as WR,readSyntheticSideStoryDocOriginPath as KR,readSyntheticSideStoryDocStoryLocator as _R}from"@datalking/begonia-doc-service/v1";import{hasVisibleSemanticContent as UR}from"@datalking/begonia-engine";function ac(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function ro(e,t){return e==="listItem"?ac(t.attrs?.listItemId):e==="paragraph"||e==="heading"?ac(t.attrs?.paraId)??ac(t.attrs?.sdBlockId):null}import{DELETION_MARK_NAME as JP,INSERTION_MARK_NAME as QP,collectRevisionSpans as eR,createRevisionGroupingContext as tR,listSelectionRevisionRanges as rR,logicalRevisionIdForRange as oR,resolveParagraphLikeBlockInlineRangeAtPath as nR}from"@datalking/begonia-engine";import{groupLogicalRevisions as iR}from"@datalking/begonia-doc-service/v1";import{orderOverlapRevisionIds as YP}from"@datalking/begonia-engine";function Xn(e,t){return YP(e,t)}function _f(e){return e.threadId}function ys(e){return`${e.threadId}\0${e.entryId}`}function Uf(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 sR(e,t){return t<e.selectionEnd&&t+1>e.start}function Xf(e,t,r){return t<e.selectionEnd&&r>e.start}function lc(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 Xf(e,t,r)||s||a}function aR(e){return e.marks.some(t=>t.type.name===QP||t.type.name===JP)}function lR(e,t){return t.target?.nodeType!=="bookmark_anchor"&&t.target?.nodeType!=="structural_revision_carrier"||(t.text??"").length>0||!t.target.blockPath.length?null:nR(e,t.target.blockPath)}function cR(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:aR(e)}}function dR(e){let t=[];return e.nodesBetween(0,e.content.size,(r,o)=>{let n=cR(r,o);return n&&t.push(n),!0}),t}function cc(e,t,r){let o=e.get(t)??[];o.push(r),e.set(t,o)}function uR(e,t){let r=ys(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 mR(e,t,r){return(e.get(ys(r))??[]).find(o=>o.pos>=r.pos&&!t.has(o))??null}function pR(e,t,r){let o=e.get(ys(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 fR(e,t){let r=Uf(t.from,t.to),o=dR(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(uR(l,d),d.kind==="anchor"){cc(a,ys(d),d);continue}if(d.kind==="start"){cc(i,_f(d),d);continue}let u=_f(d),m=i.get(u)??[],p=m.pop()??null;if(m.length>0?i.set(u,m):i.delete(u),!p){cc(s,u,d);continue}lc(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=mR(a,c,u);m&&(c.add(m),lc(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=pR(a,c,u);m&&(c.add(m),lc(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&&sR(r,p.pos)&&n.add(p.threadId)}return[...n]}function wR(e,t){let r=eR(e.doc,e.schema),o=tR(r),n=new Set;for(let i of rR(e)){let s=lR(e.doc,i);(!s||Xf(Uf(e.selection.from,e.selection.to),s.from,s.to))&&n.add(oR(i,o,t))}return Xn([...n],iR(r,t))}function Zf(e,t={}){return{activeCommentIds:fR(e.doc,e.selection),activeChangeIds:wR(e,t.reviewReplacementMode??"paired")}}import{hasVisibleSemanticContent as gR}from"@datalking/begonia-document-model";function Bs(e){return[...new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0))]}function SR(e,t){let r=e?.selection;return t!=null&&W(r)&&r.node.isInline&&r.node.isLeaf&&gR(r.node)}function dc(e,t,r=!1){return t!=="node"||e.target==null||r||Bs(e.activeChangeIds).length>0?e:{...e,target:null}}function Jo(e,t,r){let o=Ce(e??null);return dc(t,r,r==="node"&&t.target!=null&&SR(e,o))}import{projectAcceptedTextBetween as AR}from"@datalking/begonia-engine";import{createDocumentNoteAwareTextOffsetOptions as hR}from"@datalking/begonia-doc-service/v1";function oe(e,t={}){return hR(e,t)}import{pmPositionToAddressableTextOffset as vR,readAddressableText as bR,resolveAddressableTextOffsetPosition as yR,resolveAddressableTextOffsetRange as BR,resolveCollapsedAddressableTextOffsetPosition as xR}from"@datalking/begonia-document-model";function Zn(e){return{includeDeletedText:!0,...e}}function Ar(e,t={}){return bR(e,Zn(t))}function fe(e,t,r,o={}){return vR(e,t,r,Zn(o))}function ze(e,t,r,o="end",n={}){return yR(e,t,r,o,Zn(n))}function Gf(e,t,r,o,n={}){return BR(e,t,r,o,Zn(n))}function Nr(e,t,r,o={}){return xR(e,t,r,Zn(o))}import{semanticNodeText as RR}from"@datalking/begonia-document-model";import{isRevisionMarkHiddenInProjection as CR,isRevisionNodeHiddenInProjection as PR}from"@datalking/begonia-engine";function $f(e,t){return CR(e,t)}function bt(e,t,r=!1){return PR(e,t,r)}function TR(e,t){return bt(e,"final",t)}function Jf(e,t){let r=RR(e),o=t?.resolveLeafText?.(e,r);return typeof o=="string"?o:r}function kR(e,t,r){return r?"":Jf(e,t)}function ER(e,t){return t?"":e.text??""}function Yf(e,t){return e.isText?(e.text??"").length:e.childCount===0?Jf(e,t).length:0}function MR(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 uc(e,t){let r=[],o=[],n=t?.blockSeparator??"",i=0,s=0,a=(c,d,u=!1)=>{let m=i,p=m+d;s=MR(r,o,s,c,m,p,u),i=p},l=(c,d=!1)=>{let u=TR(c,d);if(c.isText){let p=Yf(c,t);a(ER(c,u),p);return}if(c.childCount===0){let p=Yf(c,t);a(kR(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 IR(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 Qo(e,t={}){let{text:r,maxOffset:o}=uc(e,t);return{text:r,maxOffset:o}}function en(e,t,r="end",o={}){let{runs:n,text:i,maxOffset:s}=uc(e,o);return!Number.isInteger(t)||t<0||t>i.length?null:IR(n,s,t,r)}function mr(e,t,r="end",o={}){let{runs:n}=uc(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 NR=Object.freeze({blockSeparator:" "});function OR(e){return e.empty??e.from===e.to}function DR(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=oe(e,NR),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=fe(l,c,d,i),p=Math.max(m,fe(l,c,u,i)),f=Qo(l,i),w=mr(l,m,"start",i),v=mr(l,p,"end",i);return s.push(f.text.slice(Math.min(w,v),Math.max(w,v))),!1}),a?s.join(" "):null}function ge(e,t,r){return OR(r)?"":DR(e,r)??AR(e,t,Math.min(r.from,r.to),Math.max(r.from,r.to)," ")}function Qf(e){return[...new Set(e)]}function Gn(e){return JSON.stringify([e.empty,e.target??null,[...new Set(e.activeMarks)].sort(),Qf(e.activeCommentIds),Qf(e.activeChangeIds),e.text??null])}import{hasVisibleSemanticContent as tw,isInlineFormatMarkEnabled as jR}from"@datalking/begonia-document-model";var VR=new Set(["strong","em","underline","strike"]);function xs(e,t){for(let r of t){if(VR.has(r.type.name)&&!jR(r)){e.delete(r.type.name);continue}e.add(r.type.name)}}function LR(e){let t=new Set;return xs(t,e),t}function ew(e,t){let r=new Set(e);return xs(r,t.marks),r}function rw(e){return e.isInline&&!e.isText&&tw(e)}function FR(e){return e.isText||e.isInline&&e.isLeaf&&tw(e)}function HR(e,t){return e.isText?{start:t,end:t+(e.text?.length??0)}:{start:t,end:t+e.nodeSize}}function Cs(e,t,r){let o=null,n=(i,s,a)=>{let l=rw(i)?ew(a,i):new Set(a);if(FR(i)){let d=HR(i,s),u=Math.max(d.start,t);if(Math.min(d.end,r)>u){let p=ew(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 Ps(e,t=null){if(t!=null)return LR(t);let r=new Set;for(let o=1;o<=e.depth;o+=1){let n=e.node(o);if(!rw(n))continue;let i=e.start(o),s=e.end(o);e.pos<i||e.pos>s||xs(r,n.marks)}return xs(r,e.marks()),r}import{parseAddressableBlockId as zR}from"@datalking/begonia-doc-service/structure";function tn(e){return zR(e)?.logicalId==null}var Rs=Object.freeze({blockSeparator:`
3
+ `});function XR(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function Ts(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=ow(r.type.name);if(o)return{type:o,path:XR(e,t),node:r,pos:e.start(t)-1}}return null}function ZR(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 iw(e,t){let r=KR(e);return r?[...r,...t]:[...t]}function pc(e,t,r){let o=iw(e,t.path);return r?qR(t.type,o):nw(t.type,o,ro(t.type,t.node))}function GR(e,t=null){return e.length===0?null:{kind:"text",segments:e,...t?{story:t}:{}}}function fc(e,t,r,o,n){return tn(e)?{start:mr(t,r,"start",n),end:mr(t,o,"end",n)}:{start:r,end:o}}function mc(e){return e.node.isLeaf&&e.node.isInline&&e.$from.parent.inlineContent&&UR(e.node)}function sw(e){let t=ow(e.node.type.name);return t==="listItem"?t:null}function $R(e){return"$anchorCell"in e?!1:W(e)?mc(e)||sw(e)!=null:!0}function YR(e,t){let r=t.$from.doc.resolve(t.from+1),o=Ts(r);if(!o||o.node!==t.node)return null;let n=oe(e,Rs),i=Math.max(t.from,o.pos+1),s=Math.min(t.to,o.pos+o.node.nodeSize-1),a=fe(o.node,o.pos,i,n),l=Math.max(a,fe(o.node,o.pos,s,n)),c=pc(e,o,!1);return[{blockId:c,range:fc(c,o.node,a,l,n)}]}function JR(e,t){let r=Ts(t.$from);if(!r||!r.node.isTextblock)return null;let o=oe(e,Rs),n=fe(r.node,r.pos,t.from,o),i=Math.max(n,fe(r.node,r.pos,t.to,o)),s=pc(e,r,!0);return[{blockId:s,range:fc(s,r.node,n,i,o)}]}function QR(e,t){let r=W(t)&&mc(t),o=oe(e,Rs);if(W(t)&&mc(t)){let s=JR(e,t);if(s)return s}if(W(t)&&sw(t)){let s=YR(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=Ts(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=fe(c.node,c.pos,d,o),p=Math.max(m,fe(c.node,c.pos,u,o)),f=pc(e,c,r),w=fc(f,c.node,m,p,o);return ZR(n,f,w.start,w.end),!1}),i?null:n}function eT(e,t,r){return Cs(e,t,r)}function tT(e){let t=new Set,{from:r,to:o}=e.selection;if(r===o){for(let n of Ps(e.doc.resolve(r),e.storedMarks))t.add(n);return[...t]}for(let n of eT(e.doc,r,o))t.add(n);return[...t]}function rT(e,t){let{selection:r}=e,o=W(r)?Ce(e):null;return JSON.stringify([r.from,r.to,r.empty,W(r)?"node":"text",Gn({...t,target:t.target?{...t.target,...t.target.story?{story:WR(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 Me(e,t={},r={}){let o=t??{},n=r??{},{selection:i,doc:s}=e,a=wc(s,i),{activeCommentIds:l,activeChangeIds:c}=Zf(e,{reviewReplacementMode:n.reviewReplacementMode}),d={empty:i.empty,target:a,activeMarks:tT(e),activeCommentIds:l,activeChangeIds:c};return o.includeText&&!i.empty&&(d.text=ge(s,e.schema,i)),d}function wc(e,t){let r=_R(e);return $R(t)?GR(QR(e,t)??[],r):null}function Ut(e){let t=Me(e).target;if(t)return t;if(!e.selection.empty)return null;let r=Ts(e.selection.$from);if(!r)return null;let o=oe(e.doc,Rs),n=fe(r.node,r.pos,e.selection.from,o);return{kind:"text",blockId:nw(r.type,iw(e.doc,r.path),ro(r.type,r.node)),range:{start:n,end:n}}}function gc(e,t={}){let r=n=>W(n.selection)?"node":"text",o=n=>{let i=e.state;return{state:i,info:Jo(i,Me(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=rT(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 oT(e){return e?.selectionKind!=="node"&&e?.selectionTarget!=null}function pr(e,t,r=null){return e?e.editable?r?.selectionKind==="node"?"Place the caret in text or select text before applying inline formatting.":oT(r)?null:t&&W(t.selection)?"Place the caret in text or select text before applying inline formatting.":t?Ut(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 tk}from"@datalking/begonia-engine";import{NodeSelection as Os}from"prosemirror-state";import{NodeSelection as lw,TextSelection as ks}from"prosemirror-state";function aw(e,t,r){try{return e.resolve(t).parent.inlineContent&&e.resolve(r).parent.inlineContent}catch{return!1}}function cw(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 oo(e,t){return Math.max(1,Math.min(t,e.content.size))}function Es(e,t){return Math.max(0,Math.min(t,e.content.size))}function K(e,t,r=t){let o=oo(e.doc,t),n=oo(e.doc,r),i=Math.min(o,n),s=Math.max(o,n),a=dw(e),l=c=>{if(!no(c))return null;if(a&&typeof c.toJSON=="function")try{let d=a.fromJSON(e.doc,c.toJSON());return no(d)?d:null}catch{}return c};if(aw(e.doc,i,s))try{return l(ks.create(e.doc,o,n))}catch{}try{return l(ks.between(e.doc.resolve(o),e.doc.resolve(n),n>=o?1:-1))}catch{if(o!==n)return null}try{return l(ks.near(e.doc.resolve(o),n>=o?1:-1))}catch{return null}}function no(e){return e instanceof ks||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&&cw(e.$anchor)&&cw(e.$head)}function Xt(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=no(e),i=no(t);return!n&&!i?!0:n&&i&&e.anchor===t.anchor&&e.head===t.head}function Sc(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 dw(e){let t=e.selection.constructor,r=typeof t=="function"?Object.getPrototypeOf(t):null;return r&&typeof r.fromJSON=="function"?r:null}function nT(e,t){return no(e)?no(t)?t:null:W(e)?W(t)?t:null:t}function dt(e,t){let r=dw(e);if(r&&typeof t.toJSON=="function")try{return nT(t,r.fromJSON(e.doc,t.toJSON()))}catch{}if(W(t)){let o=Es(e.doc,Math.min(t.from,t.to)),n=e.doc.nodeAt(o);if(!n||!lw.isSelectable(n))return null;try{return lw.create(e.doc,o)}catch{return null}}return no(t)?K(e,t.anchor,t.head):t}import{readPreservedSelection as ZT}from"@datalking/begonia-engine";import{NodeSelection as GT}from"prosemirror-state";import{isDocumentStoryLocator as VT,readSyntheticSideStoryDocStoryLocator as LT,sameDocumentStoryLocator as FT}from"@datalking/begonia-doc-service/v1";import{resolveAddressableBlockIdPath as cT}from"@datalking/begonia-doc-service/v1";import{parseAddressableBlockId as dT}from"@datalking/begonia-doc-service/structure";import{readSyntheticSideStoryDocOriginPath as iT}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as vc,isDocumentNodePathIndex as bc}from"@datalking/begonia-document-model";function hc(e){return bc(e)}function sT(e){let t=e[0];return t===-101||t===-102||t===-211||t===-212?e.length>=2&&hc(e[1])&&vc(e.slice(2))?e.slice(2):null:(t===-201||t===-202)&&e.length>=3&&hc(e[1])&&hc(e[2])&&vc(e.slice(3))?e.slice(3):null}function aT(e,t){return e.length>=t.length&&t.every((r,o)=>e[o]===r)}function lT(e,t){let r=e,o=-1;for(let n of t){if(!bc(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 $n(e,t){if(!Array.isArray(t))return null;if(t.length===0)return[];if(vc(t))return[...t];let r=sT(t);if(!r)return null;let o=iT(e);return o&&aT(t,o)?r:null}function rn(e,t){let r=$n(e,t);if(!r)return null;if(r.length===0)return 0;let o=0,n=e;for(let i of r){if(!bc(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 Le(e,t){let r=$n(e,t);return r?lT(e,r):null}function uw(e){return e==="paragraph"||e==="heading"}function uT(e){return{readDocument(){return e},readNode(t){return Le(e,t)?.node??null}}}function Fe(e,t){let r=cT(uT(e),t),o=$n(e,r);if(o)return o;let n=dT(t);if(!n?.path.length||!uw(n.nodeType))return null;let i=$n(e,n.path),s=i?Le(e,i)?.node??null:null;return s?.isBlock&&uw(s.type.name)?[...i]:null}import{hasVisibleSemanticContent as mT,semanticNodeText as pT}from"@datalking/begonia-document-model";var fT=new Set(["structural_revision_carrier","bookmark_anchor","bookmark_end","comment_anchor","comment_range_start","comment_range_end","permission_range_start","permission_range_end"]);function wT(e){if(fT.has(e.type.name))return"";let t=pT(e);return t.length>0?t:mT(e)?"":""}function gT(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.textBetween(o,n,"",wT);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 io(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||gT(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 IT}from"@datalking/begonia-doc-service/v1";import{cloneSelectionTextRange as ST}from"@datalking/begonia-document-api/core";import{sameDocumentStoryLocator as mw}from"@datalking/begonia-doc-service/v1";function Zt(e,t){return e.empty&&e.from>=t.from&&e.from<=t.to}function Gt(e,t){return{kind:"text",segments:t.map(r=>({blockId:r.blockId,range:ST(r.range)})),...e.story?{story:structuredClone(e.story)}:{}}}function Ot(e){return Gt(e,e.segments)}function Yn(e){return e?{kind:"node",nodeType:e.nodeType,stableIdentity:e.stableIdentity,path:[...e.path],...e.nodeFingerprint!=null?{nodeFingerprint:e.nodeFingerprint}:{}}:null}function Jn(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!mw(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 Ms(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!mw(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 fr(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 hT,normalizeRevisionIds as yc,selectionOverlapsRevisionRange as vT}from"@datalking/begonia-engine";function bT(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 yT(e,t){return t.length>0?hT(e,t):[]}function ce(e,t){let r=yc(e);return t&&t.length>0?yT(r,t):r}function BT(e){return e==="paragraph"||e==="heading"}function xT(e){return(e.target?.nodeType==="bookmark_anchor"||e.target?.nodeType==="structural_revision_carrier")&&BT(e.target.blockType)&&e.target.blockPath.length>0&&(e.text??"").trim().length===0}function CT(e,t){let r=bT(e);return r?Xn(yc(t.filter(o=>vT(r.from,r.to,o)).map(o=>o.id)),t):[]}function de(e){return yc(e)}function wr(e,t){let r=de(e),o=de(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function gr(e,t){let r=ce(e.trackedChangeIds,t),o=CT(e,t),n=new Set(t.filter(xT).map(a=>a.id));if(o.length===0)return r;if(r.length===0)return o;let i=new Set(o),s=Xn(r.filter(a=>i.has(a)||n.has(a)),t);return s.length>0?s:o}function on(e,t){let r=gr(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 so(e,t,r){let o=e.activeChangeIds??[],n=gr("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 PT(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Dt(e,t=[]){return ce([...e?.activeChangeIds??[],...e?.selection.trackedChangeIds??[]],t)}function Bc(e,t,r=[]){if(!e||!t)return e===t;let o=PT(Dt(e,r),Dt(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"?fr(e.nodeSelectionTarget,t.nodeSelectionTarget):e.selectionTarget||t.selectionTarget?Jn(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}import{createDocumentScopedMemo as RT}from"@datalking/begonia-engine";var fw=Symbol.for("@datalking/begonia-browser-sdk/selection-capture-document-identity"),pw=1;function TT(){let e=globalThis.crypto?.randomUUID?.();if(typeof e=="string"&&e.length>0)return e;let t=pw;return pw+=1,`browser-selection-capture-document:${t}`}function Qn(e){let t=e==null?null:Reflect.get(e,fw);return typeof t=="string"&&t.length>0?t:null}function ww(e){let t=Qn(e);if(t!=null||e==null||!Object.isExtensible(e))return t;let r=TT();return Object.defineProperty(e,fw,{configurable:!0,enumerable:!1,value:r,writable:!1}),r}function kT(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 ET(e){try{return kT(JSON.stringify(e.toJSON()))}catch{return null}}var MT=RT({compute:(e,t)=>ET(e)});function nn(e){return e==null?null:MT.read(e,void 0)}var AT=Object.freeze({success:!0}),NT=Object.freeze({success:!1,reason:"read-only"});function sn(){return{success:!1,reason:"stale"}}function OT(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=dt(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 DT(e,t){return e.documentIdentity==null&&e.documentHash==null?!0:e.documentIdentity!=null&&e.documentIdentity!==Qn(t)?!1:e.documentHash==null||e.documentHash===nn(t)}function jT(e){let t=Dt(e);return e.selectionKind==="text"&&typeof e.text=="string"&&(e.text.length>0||t.length>0)}function xc(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 NT;if(!OT(t.storyOriginPath,IT(n.view.state.doc))||r.validateDocumentIdentity!==!1&&!DT(t,n.view.state.doc))return sn();let i=o(t);return!i||t.selectionKind==="node"&&!W(i)||r.validateText!==!1&&jT(t)&&ge(n.view.state.doc,n.view.state.schema,i)!==t.text?sn():qe(n,i,r)?AT:sn()}var Is=Object.freeze({blockSeparator:`
4
+ `});function As(e,t){if(t.story===void 0)return!0;if(!VT(t.story))return!1;let r=LT(e)??{kind:"story",storyType:"body"};return FT(r,t.story)}function HT(e,t,r,o,n){let i=oe(e,Is),s=en(t,o,n,i);return s==null?null:ze(t,r,s,n,i)}function zT(e,t,r,o,n){let i=oe(e,Is),s=en(t,o,"start",i),a=en(t,n,"end",i);if(s==null||a==null)return null;let l=ze(t,r,Math.min(s,a),"start",i),c=ze(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 qT(e,t,r,o,n){let i=ze(e,t,r,"start",n),s=ze(e,t,o,"end",n);return typeof i=="number"&&typeof s=="number"?{from:Math.min(i,s),to:Math.max(i,s)}:null}function WT(e,t){return t.collapsedAcceptedVisibleBias==="hidden-anchor"||e.range.start===0?"end":"start"}function KT(e,t,r={}){let o=Fe(e,t.blockId);if(!o)return null;let n=Le(e,o);if(!n?.node.isBlock)return null;let i=oe(e,Is);if(tn(t.blockId)){if(t.range.start===t.range.end){let l=HT(e,n.node,n.position,t.range.start,WT(t,r));return typeof l=="number"?{from:l,to:l}:null}let a=zT(e,n.node,n.position,t.range.start,t.range.end);return a||null}if(t.range.start===t.range.end){let a=Nr(n.node,n.position,t.range.start,i);return typeof a=="number"?{from:a,to:a}:null}if(r.strict)return qT(n.node,n.position,t.range.start,t.range.end,i);let s=Gf(n.node,n.position,t.range.start,t.range.end,i);return s||null}function gw(e,t){return ge(e,e.type.schema,t)}function _T(e,t){let r=Q(e,{kind:"text",segments:[t]},{strict:!0});return r?gw(e,r):null}function UT(e,t){let r=e.indexOf(t);return r<0||e.indexOf(t,r+1)>=0?null:{start:r,end:r+t.length}}function Cc(e,t,r){if(!As(e,t)||t.segments.length!==1||r.length===0)return null;let[o]=t.segments,n=Fe(e,o.blockId);if(!n)return null;let i=Le(e,n);if(!i?.node.isBlock)return null;let s=oe(e,Is),a=Qo(i.node,s),l=UT(a.text,r);if(!l)return null;let c=en(i.node,l.start,"start",s),d=en(i.node,l.end,"end",s);if(c==null||d==null)return null;let u=ze(i.node,i.position,c,"start",s),m=ze(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:Gt(t,[{blockId:o.blockId,range:{start:tn(o.blockId)?Math.min(l.start,l.end):Math.min(c,d),end:tn(o.blockId)?Math.max(l.start,l.end):Math.max(c,d)}}])}}function XT(e,t,r){return Cc(e,t,r)?.selection??null}function Q(e,t,r={}){if(!t||!As(e,t))return null;let o=[];for(let n of t.segments){let i=KT(e,n,r);if(!i)return null;o.push(i)}return io(e,o,r)}function je(e,t,r,o={}){let n=Q(e,t,o);return n&&(typeof r!="string"||r.length===0||gw(e,n)===r)?n:!t||typeof r!="string"||r.length===0?null:XT(e,t,r)}function ut(e,t){if(!t||!As(e,t))return null;let r=[];for(let o of t.segments){let n=_T(e,o);if(n==null)return null;r.push(n)}return r}function tt(e,t,r,o={}){if(!t||!As(e,t)||!r||r.length!==t.segments.length)return null;let n=[];for(let[i,s]of t.segments.entries()){let a=je(e,{kind:"text",segments:[s]},r[i]??null,{...o,strict:!0});if(!a)return null;n.push(a)}return io(e,n,o)}function Pc(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=K(r.state,o.from,o.to);return n?qe(e,n):!1}function Sw(e){return e.anchor>e.head?"backward":"forward"}function Or(e){return e.anchor!=null&&e.head!=null&&e.anchor>e.head?"backward":"forward"}function yt(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 hw(e,t){return Math.max(1,Math.min(t,e.content.size))}function Rc(e,t){let r=hw(e.doc,Math.min(t.from,t.to)),o=hw(e.doc,Math.max(t.from,t.to));if(r>=o)return null;let n=yt({from:r,to:o},t.direction),i=K(e,n.anchor,n.head);if(!i||i.empty)return null;try{return e.apply(e.tr.setSelection(i))}catch{return null}}function $T(e,t,r=null,o=null,n){let i=tt(e.doc,t,r,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"})??je(e.doc,t,o,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"});if(!i||i.from>=i.to)return null;let s=yt(i,n),a=K(e,s.anchor,s.head);if(!a||a.empty)return null;try{return e.apply(e.tr.setSelection(a))}catch{return null}}function ao(e,t){if(!t)return null;let r=ds(e.doc,t);if(!r)return null;try{return e.apply(e.tr.setSelection(GT.create(e.doc,r.position)))}catch{return null}}function Tc(e,t){return ao(e,t.nodeSelectionTarget)??$T(e,t.target,t.segmentTexts,t.text,t.direction)??Rc(e,t)}function vw(e){let t=ZT(e);if(!t||t.empty)return null;let r=dt(e,t);if(!r)return null;if(Xt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function YT(e,t){if(!t.selectionTarget||!t.segmentTexts||t.selectionTarget.segments.length!==t.segmentTexts.length)return null;let r=t.selectionTarget.segments.map((o,n)=>je(e.doc,{kind:"text",segments:[o]},t.segmentTexts?.[n]??null,{strict:!0}));return r.every(o=>o!=null)?r:null}function JT(e,t){let r=YT(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 js(e,t){return t.selectionTarget?tt(e.doc,t.selectionTarget,t.segmentTexts??null,{strict:!0})??je(e.doc,t.selectionTarget,t.text??null,{strict:!0})??JT(e,t):null}function Ns(e){return Math.max(0,Math.abs(e.to-e.from))}function QT(e,t,r){let o=de([...de(t.activeChangeIds),...de(t.selection.trackedChangeIds)]);return t.selectionKind==="text"&&!t.selection.empty&&o.length>0&&Ns(t.selection)>0&&(Ns(r??{from:0,to:0})===0||(()=>{if(!r)return!1;let n=Ds(e,t);return!n||n.empty||Ns(n)<=Ns(r)?!1:ge(e.doc,e.schema,n)===ge(e.doc,e.schema,r)})())}function kc(e,t){let r=dt(e,t);if(!r)return null;if(Xt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function Ds(e,t){if(t.selectionKind==="node"){let o=Es(e.doc,Math.min(t.selection.from,t.selection.to)),n=e.doc.nodeAt(o);if(n&&Os.isSelectable(n))try{return Os.create(e.doc,o)}catch{}}let r=yt(t.selection,Or(t.selection));return K(e,oo(e.doc,r.anchor),oo(e.doc,r.head))}function bw(e,t,r,o){if(r==="node"){let i=Es(e.doc,Math.min(t.from,t.to)),s=e.doc.nodeAt(i);if(s&&Os.isSelectable(s))try{return Os.create(e.doc,i)}catch{return null}}let n=yt(t,o);return K(e,oo(e.doc,n.anchor),oo(e.doc,n.head))}function ek(e,t){let r=ao(e,t.nodeSelectionTarget)?.selection;if(W(r))return r;let o=js(e,t);if(o){let i=bw(e,o,t.selectionKind,Or(t.selection));if(W(i))return i}let n=Ds(e,t);return W(n)?n:null}function Sr(e,t){if(t.selectionKind==="node")return ek(e.state,t);let r=js(e.state,t);return r?QT(e.state,t,r)?Ds(e.state,t):bw(e.state,r,t.selectionKind,Or(t.selection)):Ds(e.state,t)}function rk(e,t,r){return K(e,t,r)}function ok(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 nk(e,t){if(ok(t))return Sr({state:e},t);let r=Math.min(t.selection.from,t.selection.to),o=Math.max(t.selection.from,t.selection.to);return rk(e,r,o)}function ik(e){let t=e.view;return t?.state&&typeof t.dispatch=="function"?t:null}function rt(e,t,r,o={}){let n=ik(e);if(!n)return!1;if(!t)return r(e);let i=o.restoreSelection??!0,s=n.state.selection,a=nk(n.state,t);if(!a||Xt(s,a))return r(e);let c=tk(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=dt(n.state,u);m&&n.dispatch(n.state.tr.setSelection(m))}}catch{}}}var ak=["color","highlight","fontFamily","fontSize","fontSizeCs","rFonts"];function lo(e,t){return{ok:!0,changed:t,value:e}}function ot(e){return{ok:!1,changed:!1,reason:e}}function Bw(e,t){let r=be(e),o=pr({editable:e.getState().editable},r.state,t);return o||(t?null:"Place the caret in text or select text before applying inline formatting.")}function xw(e,t,r){return e.empty&&!t?`Collapsed ${r} formatting requires a live editor surface. Select text to format in headless mode.`:null}function Cw(e){return e.target&&"segments"in e.target?e.target:e.selectionTarget??null}function Pw(e,t,r){let o=be(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?lo(n,!0):n.failure.code==="NO_OP"?lo(n,!1):ot(n.failure.message)}function Rw(e){return e?{...e}:{}}function lk(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 ck(e,t){let r=Rw(e),o=!1;for(let n of ak){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"?lk(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 yw(e,t){let r=be(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=sk(o).find(d=>d.type===i)??null,l=ck(Rw(a?.attrs),t);if(!l.changed)return lo(a?.attrs??null,!1);let c=o.tr.removeStoredMark(i);return l.attrs&&(c=c.addStoredMark(i.create(l.attrs))),n(c),lo(l.attrs,!0)}function an(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=Bw(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=xw(n,be(e).view!=null,"text-style");if(s)return ot(s);if(n.empty){if(r){let l=null;return rt(be(e),n,()=>(l=yw(e,t),l.changed),{restoreSelection:o.restoreSelection??!1}),l??ot("Inline formatting could not be applied.")}return yw(e,t)}let a=Cw(n);return a?Pw(e,a,t):ot("Place the caret in text or select text before applying inline formatting.")}function Ec(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 dk(e,t){let r=Ec(be(e),t);return lo(r,r)}function uk(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=Bw(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=xw(n,be(e).view!=null,"inline");if(s)return ot(s);if(n.empty){if(r){let d=rt(be(e),n,u=>Ec(u,t),{restoreSelection:o.restoreSelection??!1});return lo(d,d)}return dk(e,t)}let a=be(e);if(a.view&&!r){let d=rt(a,n,u=>Ec(u,t),{restoreSelection:o.restoreSelection??!1});return lo(d,d)}let l=Cw(n);if(!l)return ot("Place the caret in text or select text before applying inline formatting.");let c=!uk(n,t);return Pw(e,l,{[t]:c})}function Vs(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 Ls(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,preferredPaginatedLayoutMode:t.layoutMode};case"zoom":return{zoomPercent:t.zoomPercent}}}function Fs(e){return e.getZoomState().mode}function Tw(e){return e.getZoomPercent()}function Mc(e,t){return e.getState().preferredPaginatedLayoutMode!==t}function Dr(e,t){let r=be(e);return rt(r,e.readEffectiveSelection(),t)}function Yt(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?ye(e.reason):X(e)}function mk(e){return e===!1?ye("Comment could not be created."):Yt(e)}function pk(e,t,r){let o=ls(e),n=o?.view??null;if(!o||!n)return null;if(t==="insert-table")return Ic(Kf(e.documentApi,o));if(t==="insert-image"){let s=qf(r);return s?Ic(Wf(e.documentApi,o,s)):ye("Expected an image source for image insertion.")}let i=Bf(e.documentApi,n.state,t);return i?Ic(i):null}function Ic(e){return e.changed?X({changed:!0}):ye(e.reason??"The command failed.")}function fk(e,t,r){let o=be(e);switch(t){case"font-size":{let n=Lf(r),i=n===null?null:Number(n);return n===void 0?ye('Expected a font-size payload or "none".'):an(e,{fontSize:i,fontSizeCs:i})}case"font-family":{let n=Vf(r);return n===void 0?ye('Expected a font-family payload or "none".'):an(e,{fontFamily:n==null?null:String(n),rFonts:null})}case"text-color":{let n=ic(r);return n===void 0?ye('Expected a text-color payload or "none".'):an(e,{color:n==null?null:String(n)})}case"highlight-color":{let n=ic(r);return n===void 0?ye('Expected a highlight-color payload or "none".'):an(e,{highlight:n==null?null:String(n)})}case"zoom":{let n=Ff(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=Tw(e),a=Fs(e);return e.setViewState(Ls(Vs(e.getState()),{type:"zoom",zoomPercent:i})),X(i,Tw(e)!==s||Fs(e)!==a)}case"zoom-fit-width":{let n=Fs(e);e.setZoomMode(n==="fit-width"?"manual":"fit-width");let i=Fs(e);return X(i,i!==n)}case"document-mode-editing":{let n=e.getState().documentMode;return e.setDocumentMode("editing"),X("editing",e.getState().documentMode!==n)}case"document-mode-suggesting":{let n=e.getState().documentMode;return e.setDocumentMode("suggesting"),X("suggesting",e.getState().documentMode!==n)}case"document-mode-viewing":{let n=e.getState().documentMode;return e.setDocumentMode("viewing"),X("viewing",e.getState().documentMode!==n)}case"flow-mode-paginated":{let n=e.getFlowMode();return e.setViewState(Ls(Vs(e.getState()),{type:"flow",flowMode:"paginated"})),X("paginated",e.getFlowMode()!==n)}case"flow-mode-web":{let n=e.getFlowMode();return e.setViewState(Ls(Vs(e.getState()),{type:"flow",flowMode:"web"})),X("web",e.getFlowMode()!==n)}case"layout-mode-vertical":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"vertical"}),X("vertical",e.getLayoutMode()!==i||Mc(e,n))}case"layout-mode-horizontal":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"horizontal"}),X("horizontal",e.getLayoutMode()!==i||Mc(e,n))}case"layout-mode-book":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"book"}),X("book",e.getLayoutMode()!==i||Mc(e,n))}case"track-changes-display-review":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("review"),X("review",e.getState().trackChanges.mode!==n)}case"track-changes-display-original":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("original"),X("original",e.getState().trackChanges.mode!==n)}case"track-changes-display-final":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("final"),X("final",e.getState().trackChanges.mode!==n)}case"track-changes-display-off":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("off"),X("off",e.getState().trackChanges.mode!==n)}case"comments-visible":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!0),X(!0,e.getState().commentsDisplay.visible!==n)}case"comments-hidden":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!1),X(!1,e.getState().commentsDisplay.visible!==n)}case"comments-show-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!0),X(!0,e.getState().commentsDisplay.showResolved!==n)}case"comments-hide-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!1),X(!1,e.getState().commentsDisplay.showResolved!==n)}case"comments-visibility-all":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("all"),X("all",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-internal":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("internal"),X("internal",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-external":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("external"),X("external",e.getState().commentsDisplay.visibility!==n)}case"undo":return X(o.undo());case"redo":return X(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 X(Dr(e,n=>n.setParagraph()));case"heading-1":return X(Dr(e,n=>n.setHeading(1)));case"heading-2":return X(Dr(e,n=>n.setHeading(2)));case"heading-3":return X(Dr(e,n=>n.setHeading(3)));case"bullet-list":return X(Dr(e,n=>n.toggleBulletList()));case"numbered-list":return X(Dr(e,n=>n.toggleOrderedList()));case"align-left":case"align-center":case"align-right":case"align-justify":{let n=t.slice(6);return X(Dr(e,i=>i.setAlignment(n)))}case"indent-increase":case"indent-decrease":return X(Dr(e,n=>n.adjustIndent(t==="indent-increase"?"increase":"decrease")));case"link-set":{let n=Df(r);return n?X(typeof n=="string"?e.setLink(n):e.setLink(n.href,n.title??null)):ye("Expected a non-empty link payload.")}case"link-clear":return X(e.clearLink());case"comment-create":{let n=jf(r);if(!n)return ye("Expected non-empty comment text for comment creation.");let i=e.readEffectiveSelection();return mk(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"),X(!0,!0);default:return null}}function kw(e,t,r){let o=fk(e,t,r);if(o)return o;let n=af(e,t,r);if(n)return n;let i=hf(e,t,r);if(i)return i;let s=pk(e,t,r);if(s)return s;switch(t){case"search-set-query":{let a=Hf(r);if(!a)return ye("Expected a search query payload.");let l=typeof a=="string"?e.search(a):e.search(a.query,a.options??{});return X(l,!0)}case"search-next":return(()=>{let a=e.nextSearchHit();return X(a,a!=null)})();case"search-previous":return(()=>{let a=e.previousSearchHit();return X(a,a!=null)})();case"search-clear":{let a=e.getState().search.query.length>0;return e.clearSearch(),X(void 0,a)}case"search-replace-active":{let a=sc(r);if(!a)return ye("Expected replacement text for the active search hit.");let l=e.getState(),c=typeof a=="string"?l.search.activeHitId:a.hitId??l.search.activeHitId;if(!c)return ye("No active search hit is available to replace.");let d=typeof a=="string"?e.replaceSearchHit(c,a):e.replaceSearchHit(c,a.text);return Yt(d)}case"search-replace-all":{let a=sc(r);if(!a)return ye("Expected replacement text for search replace-all.");let l=typeof a=="string"?e.replaceAllSearchHits(a):e.replaceAllSearchHits(a.text);return Yt(l)}case"review-accept-all":return Yt(e.acceptAll());case"track-changes-accept-selection":return Yt(e.acceptSelection());case"review-reject-all":return Yt(e.rejectAll());case"track-changes-reject-selection":return Yt(e.rejectSelection());case"proofing-ignore-first":{let a=e.getState().proofing.diagnostics[0]?.diagnosticId;return a?Yt(e.ignoreProofingDiagnostic(a)):ye("No proofing diagnostic is available to ignore.")}case"proofing-accept-first":{let a=e.getState().proofing.diagnostics[0]?.diagnosticId;return a?Yt(e.acceptProofingSuggestion(a)):ye("No proofing diagnostic is available to accept.")}case"proofing-replace-first-tracked":{let a=zf(r),c=e.getState().proofing.diagnostics[0],d=typeof a=="string"?c?.diagnosticId:a?.diagnosticId??c?.diagnosticId,u=typeof a=="string"?a:a?.text??c?.replacementText??c?.suggestion??"";return!d||!u?ye("No tracked proofing replacement could be resolved."):Yt(e.replaceProofingDiagnosticTracked(d,u))}default:return null}}import{createEditorSessionController as cM}from"@datalking/begonia-editor-ui";function mt(e){return e?.trim()??""}function ei(e,t){let r=mt(e);return r.length===0?"":mt(t?.id)||r}function Ew(e){return/(?:^|[-_:])wire(?:[-_:]|$)/i.test(mt(e))}function Ge(e){let t=new Map,r=new Set;for(let n of e??[]){let i=mt(n.id);i.length!==0&&(r.add(i),t.set(i,i))}let o=new Map;for(let n of e??[]){let i=mt(n.id);if(i.length===0)continue;let s=mt(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 ln(e,t){let r=mt(e);return t.get(r)??r}function wk(e,t){let r=mt(t);if(r.length===0)return"";let o=e?.get?.(r)??null;if(o)return ei(r,o);let n=Ew(r),i=e?.target?.(r)??null;if(i&&(mt(i.id)===r||n))return ei(r,i);let s=e?.targetSnapshot?.(r)??null;return s&&(mt(s.id)===r||n)?ei(r,s):r}function jt(e,t){return[...new Set((e??[]).map(r=>ln(r,t)).filter(r=>r.length>0))]}function Mw(e,t){let r=(e??[]).map(s=>mt(s)).filter(s=>s.length>0),o=t?.get==null&&r.length>1&&r.every(s=>!Ew(s)),n=[],i=new Set;for(let s of r){let a=o?s:wk(t,s);a.length===0||i.has(a)||(i.add(a),n.push(a))}return n}function Iw(){return{success:!1}}function Aw(e,t){try{e.restoreSelectionHandle?.(t,{focus:!1})}catch{return}}function Nw(e){return e.shouldContinue?.()??!0}async function Hs(e,t,r={}){let o=e.captureEffectiveSelectionHandle();try{let n=await t();return Nw(r)?(n.success||Aw(e,o),n):Iw()}catch{return Nw(r)&&Aw(e,o),Iw()}finally{e.releaseSelectionHandle(o)}}function gk(e){return"host"in e}function Be(e){return e?gk(e)?e.host:e:null}function Sk(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 Ow(e){return e?Sk(e)?e:Be(e)?.preview??null:null}function zs(e={}){return{commentTarget:null,selected:!1,selectionTarget:null,navigationRequest:null,...e}}function Dw(e,t){return t?typeof t=="string"?e.documentApi.comments.target(t):t:null}function jw(e){return e.documentApi.selection.current({includeText:!0}).target}function hk(e){return e&&"id"in e&&typeof e.id=="string"&&e.id.length>0?e.id:null}function Ac(){return{success:!1}}function Vw(e,t){let r=Be(e);if(!r)return zs();let o=Dw(r,t);if(!o)return zs();if(!r.selectionTargets.selectCommentTarget(o))return zs({commentTarget:o});let i=jw(r);return zs({commentTarget:o,selected:!0,selectionTarget:i,navigationRequest:r.browserViewport.requestNavigationForTextTarget(i)})}async function Lw(e,t,r={},o={}){let n=Be(e);if(!n)return Ac();let i=Dw(n,t);return i?Hs(n.selectionHandles,async()=>{if(n.selectionTargets.selectCommentTarget(i)){let a=jw(n);if(a)return n.browserViewport.scrollIntoView({target:a,timeoutMs:r.timeoutMs,continuation:o.continuation})}let s=hk(i);return s?n.browserViewport.scrollIntoView({target:{type:"comment",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Ac()},{shouldContinue:o.continuation?.shouldContinue}):Ac()}function vk(e,t,r){return{shouldContinue(){return e()===t},subscribe(o){return r(t,o)}}}function qs(){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 vk(()=>e,n,o)},invalidate(){r()}}}function bk(e){return e.find(t=>t.type==="comment")??null}function yk(e,t){return[...new Set(e.filter(r=>r.type==="comment").map(r=>ln(r.id,t)).filter(r=>r.length>0))]}function Bk(e,t){let r=Ge(e),o=ln(t,r);return e.find(n=>ln(n.id,r)===o||ln(n.wireId,r)===o)??null}function xk(e,t){let r=Ge(e),o=yk(t,r);if(o.length!==1)return null;let n=o[0]??bk(t)?.id??null;if(!n)return null;let i=Bk(e,n);return!i||typeof i.id!="string"||i.id.length===0?null:{id:i.id,item:i}}function Fw(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=Be(e);return o?xk(r,o.browserViewport.entitiesAtPoint(t)):null}import{listProjectionSelectionRects as nE,resolveProjectionCaretRect as iE}from"@datalking/begonia-page-layout";import{isDenseArray as sE}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as Ck,INSERTION_MARK_NAME as Pk,semanticNodeText as Rk}from"@datalking/begonia-engine";function Hw(e){return typeof e=="number"?Math.max(0,e):null}function Tk(e){return e.startPath?e.startPath:e.segments?.find(t=>t.kind==="range")?.startPath??null}function kk(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 Ek(e){return e.anchorPath?e.anchorPath:e.segments?.find(t=>t.kind==="anchor")?.anchorPath??null}function Mk(e,t){let r=e,o=Le(r,t),n=o?.node.type.name==="comment_anchor"?o.position:rn(r,t);return Hw(n)}function Ws(e){return e.marks.some(t=>t.type.name===Pk||t.type.name===Ck)}function Ik(e,t,r){let o=!1;return e.nodesBetween(t,r,(n,i)=>{if(o)return!1;if(!(n.isText||n.isInline&&n.isLeaf&&Rk(n).length>0))return!0;let a=Math.max(t,i);return Math.min(r,i+n.nodeSize)<=a?!1:(o=Ws(n),!o)}),o}function zw(e,t){let r=e,o=Le(r,t);return o?o.node.type.name!=="comment_range_start"?rn(r,t):Ws(o.node)?rn(r,t):o.position:null}function Ak(e,t,r={}){if(t?.kind!=="range"||!t.startPath||!t.endPath)return null;let o=e,n=zw(e,t.startPath),i=rn(o,t.endPath);if(typeof n!="number"||typeof i!="number"||n>i)return null;let s={from:n,to:i},a=Ik(e,s.from,s.to),l=r.allowTrackedContentFallback??!0,c=oe(o,{blockSeparator:`
5
+ `}),d=t.addressableBlockPath??t.blockPath??null,u=d?Le(o,d):null,m=u?.node??null,p=t.text;if(!u||!m?.isBlock||typeof p!="string"||p.length===0)return s;let f=Ar(m,c),w=fe(m,u.position,s.from,c),v=Math.max(w,fe(m,u.position,s.to,c)),C=f.slice(w,v);if(C===p)return s;let R=C.indexOf(p);if(R<0||C.indexOf(p,R+1)>=0)return a&&!l?null:s;let S=w+R,B=S+p.length,h=ze(m,u.position,S,"start",c),y=ze(m,u.position,B,"end",c),T=Le(o,t.startPath)?.node??null,A=Le(o,t.endPath)?.node??null,D=R===0&&!(a&&T?.type.name==="comment_range_start"&&!Ws(T)),O=B===v&&!(a&&A?.type.name==="comment_range_end"&&!Ws(A)),U=D?s.from:h,H=O?s.to:y;return typeof U!="number"||typeof H!="number"||H<=U?a&&!l?null:s:{from:Math.min(U,H),to:Math.max(U,H)}}function Nk(e){return e!=null}function Ok(e,t){let r=e,o=t.segments??[],n=t.source==="live",i=o.map(a=>Ak(e,a,{allowTrackedContentFallback:n}));if(o.length>0&&!n&&i.some(a=>a==null))return null;let s=i.filter(Nk);if(s.length===0){let a=Tk(t),l=kk(t);if(!a||!l)return null;let c=zw(e,a),d=rn(r,l);return typeof c!="number"||typeof d!="number"?null:{from:Math.min(c,d),to:Math.max(c,d)}}return io(r,s,{strict:!n})}function $e(e,t){if(!t)return null;if(t.targetKind==="range")return Ok(e,t);let r=Ek(t);if(!r)return null;let o=Mk(e,r);return typeof o!="number"?null:{from:o,to:o}}import{readSyntheticSideStoryDocContext as Dk,resolveSyntheticSideStoryPathPosition as jk}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as Vk}from"@datalking/begonia-document-model";import{parseAddressableBlockId as Lk}from"@datalking/begonia-doc-service/structure";function Fk(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function qw(e,t){let r=e,o=-1;for(let n of t){if(!Vk(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 Hk(e,t){let r=qw(e,t);return r?.node.isBlock?{path:[...t],localPath:[...t],document:e,position:r.position,node:r.node,syntheticRootPath:null,positionRoot:null}:null}function zk(e,t){let r=Dk(Fk(e),t);if(!r)return null;let o=r.localizePath(t),n=r.globalizePath([]),i=jk(e.type.schema,e,n),s=o?qw(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 jr(e,t){let r=Fe(e,t);if(r)return Hk(e,r);let o=Lk(t);return o?.path.some(n=>n<0)?zk(e,o.path):null}function Jt(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?t-e.positionRoot:t}import{resolveDocumentStoryLocatorFromPath as qk}from"@datalking/begonia-doc-service/v1";import{addressableBlockTypeForNodeType as Wk,formatAddressableBlockId as Kk,formatAddressableBlockIdWithLogicalId as _k}from"@datalking/begonia-doc-service/structure";function Uk(e,t){return{kind:"text",segments:[{blockId:e,range:{start:0,end:0}}],...t?{story:t}:{}}}function Xk(e,t,r){return r?structuredClone(r):qk({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 Ks(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=Wk(o.type.name);if(!n)return null;let i=ro(n,o),s=i?_k(n,t,i):Kk(n,t);return Uk(s,Xk(e,t,r)??void 0)}function ti(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.trunc(e):null}function Zk(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Ww(e,t){return!Array.isArray(t)||t.length===0?null:Ks(e,t)}function Gk(e,t){let r=Math.max(0,typeof e.text=="string"?e.text.length:typeof t.text=="string"?t.text.length:0),o=ti(e.startOffset)??ti(t.startOffset)??0,n=ti(e.endOffset)??ti(t.endOffset)??(r>0?o+r:o);return{start:o,end:Math.max(o,n)}}function $k(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 Yk(e){let t=e.segments?.find(r=>r.kind==="anchor");return t?.addressableBlockPath??t?.blockPath??e.addressableBlockPath??e.blockPath??null}function _s(e,t){if(!e||!t)return null;if(t.targetKind==="range"){let n=[],i;for(let s of $k(t)){let a=s.addressableBlockPath??s.blockPath??null,l=Ww(e,a);if(!l)return null;if(i===void 0)i=l.story;else if(!Zk(i,l.story))return null;n.push({blockId:l.segments[0].blockId,range:Gk(s,t)})}return n.length>0?{kind:"text",segments:n,...i?{story:i}:{}}:null}let r=Ww(e,Yk(t));if(!r)return null;let o=ti(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 Jk}from"@datalking/begonia-document-model";var Qk=Object.freeze({blockSeparator:`
6
+ `});function cn(e){return typeof e=="number"&&Number.isFinite(e)}function eE(e){return Array.isArray(e)&&e.length>0&&Jk(e)}function tE(e){return!!e&&typeof e=="object"&&eE(e.blockPath)}function rE(e){let t=s=>[s.blockPath.join("."),cn(s.from)?Math.min(s.from,s.to??s.from):"",cn(s.to)?Math.max(s.from??s.to,s.to):""].join(":"),r=[e?.target??null,...e?.targets??[]].filter(tE),o=s=>cn(s.from)&&cn(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 Kw(e,t,r){return Math.min(Math.max(e,t),r)}function oE(e,t,r){if(!e||!cn(r.from)||!cn(r.to))return null;let o=jr(e,t);if(!o)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=Jt(o,Math.min(r.from,r.to)),a=Jt(o,Math.max(r.from,r.to)),l=Kw(s,n,i),c=Kw(a,l,i),d=oe(o.document,Qk),u=fe(o.node,o.position,l,d),m=fe(o.node,o.position,c,d);return{start:Math.min(u,m),end:Math.max(u,m)}}function Nc(e,t,r){if(!e||!r)return{target:null,selectionTarget:null};let o=null,n=null;for(let i of rE(r)){let s=Ks(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=oE(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 Us(e,t,r){return Nc(e,t,r).selectionTarget}function nt(e){return typeof e?.readLayoutSource=="function"?e.readLayoutSource():null}function _w(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let r=e,o=t;return r.type!==o.type?!1:typeof r.eq=="function"&&r.eq(o)===!0}function hr(e){return e?.getResolvedProjection?.()??null}function Bt(e){return e?.getResolvedProjectionGeometryOptions?.()??null}function Uw(e){return e?.getPointerCaretOrigin?.()??null}function xt(e){return{success:!1,reason:e}}function aE(e){return!e||typeof e!="object"?!1:!!e&&"kind"in e&&e.kind==="text"&&sE(e.segments)}function Xw(e){return typeof e=="number"&&Number.isFinite(e)}function lE(e){return!e||e.segments.length===0?!1:e.segments.every(t=>typeof t?.blockId=="string"&&t.blockId.trim().length>0&&Xw(t.range?.start)&&Xw(t.range?.end))}function cE(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"id"in e&&typeof e.id=="string"}function dE(e){return e?typeof e.id=="string"&&e.id.trim().length>0:!1}function Oc(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"childCount"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function Zw(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 uE(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 mE(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 pE(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 fE(e){let t=[],r=new Set;for(let o of e){let n=pE(o);r.has(n)||(r.add(n),t.push(o))}return t}function wE(e,t){let r=hr(e),o=Bt(e)??{};if(!r)return[];if(t.from===t.to){let n=iE(r,t.from,o);return n?[mE(n)]:[]}return nE(r,t.from,t.to,o).map(uE)}function Dc(e,t){if(t.segments.length===0)return null;let r=[];for(let o of t.segments){let n=SE(e,o);if(!n)return null;r.push(n)}return r}function gE(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?{from:e.positionRoot+t.from,to:e.positionRoot+t.to}:t}function SE(e,t){let r={kind:"text",segments:[t]},o=Q(e,r,{strict:!0});if(o)return o;let n=jr(e,t.blockId);if(!n||n.document===e)return null;let i=Q(n.document,r,{strict:!0});return i?gE(n,i):null}function hE(e){if(!e)return[];let t=(e.segments??[]).map(o=>Zw(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=Zw(e.from,e.to);return r?[r]:[]}function vE(e,t,r){if(!r||typeof t?.blocks?.read!="function")return null;let o=Us(t,e,r);return o?Dc(e,o):null}function bE(e,t="unresolved"){let[r]=e;return r?{success:!0,rect:r,rects:[...e],pageIndex:r.pageIndex,pageNumber:r.pageNumber}:xt(t)}function ri(e,t){let r=fE(t.flatMap(o=>wE(e,o)));return bE(r,t.length>0?"not-mounted":"unresolved")}function dn(e,t){let r=e.preview??null;if(!r||!hr(r))return xt("not-ready");let o=t.target??null;if(!o)return xt("invalid-target");if(aE(o)){if(!lE(o))return xt("invalid-target");let n=nt(r);if(!Oc(n))return xt("not-ready");let i=Dc(n,o);return i?ri(r,i):xt("unresolved")}if(!cE(o)||!dE(o))return xt("invalid-target");if(o.type==="comment"){let n=nt(r);if(!Oc(n))return xt("not-ready");let i=e.documentApi?.comments.target(o.id)??null,s=_s(e.documentApi,i),a=s?Dc(n,s):null;if(a)return ri(r,a);let l=$e(n,i);return l?ri(r,[l]):xt("unresolved")}if(o.type==="trackedChange"){let n=e.documentApi?.trackChanges.get(o.id)??null,i=nt(r),s=Oc(i)?vE(i,e.documentApi,n):null;if(s)return ri(r,s);let a=hE(n);return a.length===0?xt("unresolved"):ri(r,a)}return xt("invalid-target")}var yE=Object.freeze([]),BE=[],xE=Object.freeze({});function jc(e){let t=e?.items??BE,r=e?.permissions??xE;return{items:t,permissions:r,total:typeof e?.total=="number"&&Number.isFinite(e.total)?Math.max(0,Math.trunc(e.total)):t.length,activeCommentId:e?.activeCommentId??null,activeCommentIds:e?.activeCommentIds??yE,enabled:e?.enabled??!1,visible:e?.visible??!1,readOnly:e?.readOnly??!1,showResolved:e?.showResolved??!1,visibility:e?.visibility??null}}function Gw(e){return structuredClone(e)}function Vc(e){return jc(e?e.session.readState()?.comments??null:null)}function $w(e,t){return jt(typeof t=="string"?[t]:[],Ge(Vc(e).items))[0]??null}function Yw(e,t){let r=qs(),o=()=>Gw(jc(t.getSnapshot())),n=i=>t.subscribe(s=>{i(Gw(jc(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=Vc(e).activeCommentId??null,a=typeof i=="string"?$w(e,i):null;a&&e.commentFocus.setActiveComment(a);let l=Vw(e,i);return!l.selected&&a&&e.commentFocus.setActiveComment(s),l},async scrollTo(i,s){let a=r.begin(),l=Vc(e).activeCommentId??null,c=typeof i=="string"?$w(e,i):null;c&&e.commentFocus.setActiveComment(c);let d=await Lw(e,i,s,{continuation:a});return a.shouldContinue()?(!d.success&&c&&e.commentFocus.setActiveComment(l),d):{success:!1}},getAt(i){return Fw(e,i,o().items)},getRect({id:i}){return dn(e,{target:{type:"comment",id:i}})}}}var Jw=["editing","suggesting","viewing"],Qw=["review","original","final","off"],eg=["paired","independent"],tg=["all","internal","external"];function Xs(e,t){return typeof e=="string"&&t.includes(e)}function CE(e){return e.map(t=>`"${t}"`).join(", ")}function Zs(e,t,r){return new TypeError(`[BrowserEditor] ${e} must be one of ${CE(r)}; received ${JSON.stringify(t)}.`)}function Lc(e){return Xs(e,Jw)?e:null}function Gs(e){let t=Lc(e);if(t)return t;throw Zs("documentMode",e,Jw)}function co(e){return Xs(e,Qw)?e:null}function Fc(e){let t=co(e);if(t)return t;throw Zs("trackChanges.mode",e,Qw)}function uo(e){return Xs(e,eg)?e:null}function rg(e){let t=uo(e);if(t)return t;throw Zs("trackChanges.replacements",e,eg)}function mo(e){return Xs(e,tg)?e:null}function og(e){let t=mo(e);if(t)return t;throw Zs("comments.visibility",e,tg)}function po(e,t){if(typeof e=="boolean")return e;throw new TypeError(`[BrowserEditor] ${t} must be a boolean; received ${JSON.stringify(e)}.`)}function oi(e){return e==="paginated"||e==="web"?e:null}function fo(e){return oi(e)??"paginated"}function pt(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function vr(e,t){return t==="web"?"vertical":pt(e)??"vertical"}function Vr(e){let t=fo(e.flowMode),r=pt(e.preferredPaginatedLayoutMode)??pt(e.layoutMode)??"vertical";return{flowMode:t,layoutMode:vr(pt(e.layoutMode)??r,t),preferredPaginatedLayoutMode:r}}import{resolveEditorSelectionRootOffsets as Uc}from"@datalking/begonia-editor-contracts";import{listProjectionRangeCellBoxes as EE,listProjectionSelectionRects as ug,resolveProjectionCaretRect as mg}from"@datalking/begonia-page-layout";function Qt(e,t,r,o={}){return fe(e,t,r,o)}function Hc(e,t,r,o={}){return Nr(e,t,r,o)}function zc(e){return e+1}function ig(e,t){return Math.max(zc(t),t+e.nodeSize-1)}function sg(e,t,r){return Qt(e,t,ig(e,t),r)}function ag(e,t){return Number.isInteger(e)&&e>=0&&e<=t}function PE(e,t,r,o){let n=zc(t),i=ig(e,t);for(;n<i;){let s=n+Math.floor((i-n)/2);Qt(e,t,s,o)<r?n=s+1:i=s}return n}function ng(e,t,r,o="end",n={}){let i=sg(e,t,n);if(!ag(r,i))return null;let s=ze(e,t,r,o,n);if(s!=null)return s;let a=PE(e,t,r,n);return o==="start"?Math.max(zc(t),a-1):a}function ni(e,t,r,o={}){let n=sg(e,t,o);if(!ag(r,n))return null;let i=Hc(e,t,r,o);if(i!=null)return i;let s=ng(e,t,r,"start",o),a=ng(e,t,r,"end",o);if(s==null||a==null)return s??a;if(s===a)return s;let l=Qt(e,t,s,o),c=Qt(e,t,a,o);return r-l<=c-r?s:a}import{semanticNodeText as RE}from"@datalking/begonia-document-model";function lg(e){return e.isInline&&e.isAtom?RE(e):""}var TE=" | ";function qc(e){if(e.type.name!=="table")return null;let t=[],r=0;return e.forEach((o,n)=>{let i=r,s=0;o.forEach((a,l)=>{let c=s===0?0:TE.length,d=i+c,u=a.textBetween(0,a.content.size,"",lg),m=u.trimEnd().length,p=0,f=0;a.forEach((w,v)=>{if(!w.isTextblock)return;let R=w.textBetween(0,w.content.size,"",lg).length,S=Math.max(0,Math.min(R,m-p));t.push({contentStart:n+l+v+4,textLength:S,flattenedStart:d+f}),p+=R,f+=Math.max(1,R)}),i=d+f+Math.max(0,u.length-p),s+=1}),r=i+1}),t.length>0?t:null}function cg(e,t,r){let o=qc(e);if(!o)return null;let n=r-t;for(let i of o){if(n<i.contentStart-1)continue;let s=n-i.contentStart;if(!(s>i.textLength))return t+i.flattenedStart+Math.max(0,s)}return null}function $s(e){return typeof e=="object"&&e!==null&&"resolve"in e&&"descendants"in e&&"content"in e}function Wc(e,t){let r=e.resolve(Math.max(0,Math.min(t,e.content.size)));for(let o=r.depth;o>0;o-=1){let n=r.node(o);if(n.isTextblock)return{node:n,blockPos:r.before(o)}}return null}function dg(e,t){if(!$s(e)||!Number.isFinite(t?.from))return null;let r=Math.round(t.from),o=Wc(e,r)??Wc(e,r+1);return o?{doc:e,...o}:null}function kE(e,t){let r=e.resolve(Math.max(0,Math.min(t,e.content.size)));for(let o=r.depth;o>0;o-=1){let n=r.node(o);if(n.type.name==="table")return cg(n,r.before(o),t)}return null}function Ys(e,t){if(!$s(e)||!Number.isFinite(t))return!1;let r=e.resolve(Math.max(0,Math.min(t,e.content.size)));for(let o=r.depth;o>0;o-=1)if(r.node(o).type.name==="table")return!0;return!1}function Kc(e,t){if(!$s(e)||!Number.isFinite(t))return!1;let r=Math.round(t),o=e.resolve(Math.max(0,Math.min(r,e.content.size)));return!o.parent.isTextblock||o.parentOffset!==0?!1:Ys(e,r)}function Js(e,t){if(!$s(e)||!Number.isFinite(t))return null;let r=Math.round(t),o=kE(e,r);if(o!=null)return o;if(Ys(e,r))return null;let n=Wc(e,r);if(!n)return null;let i=Qt(n.node,n.blockPos,r,oe(e));return Number.isFinite(i)?n.blockPos+Math.max(0,i):null}function ME(e){let t=new Set;for(let r of e)t.add([r.blockIndex,r.originRow,r.originColumn,r.rowSpan,r.colSpan].join(":"));return t.size}function IE(e,t={}){return t.paintSingleCellBox===!0?e.length>0:ME(e)>1}function AE(e){return e==="end"||e==="union"?e:"start"}function _c(e,t,r,o){for(let n=1;n<=8;n+=1){let i=Js(e,t+n*o);if(i!=null)return i}return r}function ii(e,t){let r=nt(e),o=Js(r,t.from),n=Js(r,t.to);if(o!=null&&n!=null)return o<=n?{from:o,to:n}:{from:n,to:o};if(o==null&&n==null){if(Ys(r,t.from)){if(t.from===t.to){let l=_c(r,t.from,0,-1);if(l!=null)return{from:l,to:l}}return null}return t.from<=t.to?{from:t.from,to:t.to}:{from:t.to,to:t.from}}let i=o??n,s=o??_c(r,Math.min(t.from,t.to),i,1),a=n??_c(r,Math.max(t.from,t.to),i,-1);return s==null||a==null?{from:i,to:i}:s<=a?{from:s,to:a}:{from:a,to:s}}function NE(e){return e?{left:e.left,top:e.top,width:1,height:e.height}:null}function pg(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 si(e,t){let r=hr(e),o=Bt(e)??{};if(!r||!t||t.empty)return[];let n=Uc(t);if(!n)return[];let i=ii(e,n);return i?ug(r,i.from,i.to,{...o,documentRegionsOnly:!0}):[]}function Xc(e,t){let r=hr(e),o=Bt(e)??{};if(!r||!t)return[];if(!Number.isFinite(t.from)||!Number.isFinite(t.to))return[];let n=ii(e,t);return n?ug(r,n.from,n.to,o):[]}function fg(e,t){let r=Xc(e,t),o=pg(r);return o?{bounds:o,rects:r,pageIndex:r[0].pageIndex}:null}function wg(e,t,r={}){let o=hr(e);if(!o||!t||t.empty)return[];let n=Uc(t);if(!n)return[];let i=ii(e,n);if(!i)return[];let s=EE(o,i.from,i.to);return IE(s,r)?s:[]}function Zc(e,t,r={}){let o=hr(e),n=Bt(e)??{};if(!o||!t||!t.empty)return null;let i=Uc(t);if(!i)return null;let s=ii(e,{...i,to:i.from});if(!s)return null;let a=Uw(e),l=a?.selectionOffset===i.from?a:null;return mg(o,s.from,{bias:r.bias,pointer:l,preferredPageNumber:a?.pageNumber??null,cellLineBias:Kc(nt(e),i.from)?"start":void 0,measureText:n.measureText,measurementEpoch:n.measurementEpoch,documentRegionsOnly:!0})}function gg(e,t,r={}){let o=hr(e),n=Bt(e)??{};if(!o||!Number.isFinite(t))return null;let i=ii(e,{from:t,to:t});return i?mg(o,i.from,{bias:r.bias,cellLineBias:Kc(nt(e),t)?"start":void 0,measureText:n.measureText,measurementEpoch:n.measurementEpoch}):null}function Sg(e,t,r={}){let o=si(e,t);if(o.length===0)return NE(Zc(e,t));switch(AE(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 pg(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 OE}from"@datalking/begonia-editor-contracts";function un(e){return e?{empty:e.empty,target:e.target?Ot(e.target):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}var Gc=Object.freeze([]);function DE(e){return e?structuredClone(e):void 0}function jE(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=DE(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 Qs(e,t){if(!e)return null;let r=OE(e),o=un(t),n=o?.target??null;return{...r,target:n,selectionTarget:jE(n),activeMarks:o?.activeMarks??Gc,activeCommentIds:o?.activeCommentIds??Gc,activeChangeIds:o?.activeChangeIds??Gc,quotedText:o?.text??""}}var VE=Object.freeze({percent:100,mode:"manual",value:100,fitZoom:null,min:10,max:400,viewportMetrics:null});function mn(e){return{getSnapshot(){return e.get()},subscribe(t){return e.subscribe(t)},observe(t){return e.subscribe(t)}}}function LE(e){let t=Vr(e);return{flowMode:t.flowMode,layoutMode:t.layoutMode,preferredPaginatedLayoutMode:t.preferredPaginatedLayoutMode,zoom:hg(e)}}function FE(e){return Qs(e.selection,e.selectionInfo)}function HE(e){return{editable:e.editable,documentMode:Lc(e.documentMode),trackingEnabled:e.trackingEnabled,trackChanges:{enabled:e.review.enabled,visible:e.review.visible,mode:co(e.review.mode),replacementMode:uo(e.review.replacementMode)}}}function zE(e){return{enabled:e.comments.enabled,visible:e.comments.visible,readOnly:e.comments.readOnly,allowResolve:e.comments.allowResolve??!1,showResolved:e.comments.showResolved,visibility:mo(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 hg(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}:VE}function qE(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 vg(e,t){return{...mn(t.select(LE)),setViewState(o){e.view.setViewState(o)},getZoomState(){return e.view.getZoomState()},setZoomMode(o){e.view.setZoomMode(o)}}}function bg(e,t){let r=mn(t.select(FE));return{...r,getRects(){return si(e.preview,r.getSnapshot())},getCellSelectionRects(o){return wg(e.preview,r.getSnapshot(),o)},getAnchorRect(o){return Sg(e.preview,r.getSnapshot(),o)},getCaretRect(o){return Zc(e.preview,r.getSnapshot(),o)},getRangeRects(o){return Xc(e.preview,o)},getCaretRectAtPosition(o,n){return gg(e.preview,o,n)},getRangeBounds(o){return fg(e.preview,o)}}}function yg(e,t){return{...mn(t.select(HE)),setDocumentMode(o){e.documentMode.setDocumentMode(o)},setTrackChangesDisplayMode(o){e.documentMode.setTrackChangesDisplayMode(o)}}}function Bg(e,t){return{...mn(t.select(zE)),setCommentsVisible(o){e.commentsDisplay.setCommentsVisible(o)},setCommentsShowResolved(o){e.commentsDisplay.setCommentsShowResolved(o)},setCommentsVisibility(o){e.commentsDisplay.setCommentsVisibility(o)}}}function xg(e,t){return{...mn(t.select(hg)),set(o){e.view.setViewState({zoomPercent:o})},setMode(o){e.view.setZoomMode(o)}}}function Cg(e,t){return{...mn(t.select(qE)),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 dn(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 WE}from"@datalking/begonia-document-model";function pn(e={}){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,...e}}function KE(e){return Array.isArray(e)&&e.length>0&&WE(e)}function ea(e){return!!e&&typeof e=="object"&&KE(e.blockPath)}function Rg(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 _E(e){return e?ea(e.target)?e.target:(e.targets??[]).find(ea)??null:null}function UE(e){let t="target"in e?e.target:null,r="targets"in e?e.targets:null;return ea(t)||(r??[]).some(ea)}function XE(e,t){if(typeof t!="string"&&UE(t))return t;let r=Rg(t);return r?e.documentApi.trackChanges.get(r):null}function ZE(e,t){let r=nt(Ow(e));return Nc(e.documentApi,GE(r)?r:null,t)}function GE(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function $E(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 ai(e,t){if(!e||!t)return pn();let r=Be(e);if(!r)return pn();let o=Rg(t),n=XE(r,t);if(!n)return pn({revisionId:o});let i=$E(o,n),s=ZE(r,n),a=s.target??_E(n);if(!a)return pn({revisionId:i,trackChange:n});let l=s.selectionTarget;return pn(l?{revisionId:i,trackChange:n,target:a,selectionTarget:l}:{revisionId:i,trackChange:n,target:a})}function Pg(){return{success:!1}}function YE(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 ta(e,t,r={},o={}){let n=ai(e,t),i=Be(e);return!i||!n.selectionTarget?Pg():Hs(i.selectionHandles,async()=>{if(i.selectionTargets.selectTextTarget(n.selectionTarget))return i.browserViewport.scrollIntoView({target:n.selectionTarget,timeoutMs:r.timeoutMs,continuation:o.continuation});let s=YE(n);return s?i.browserViewport.scrollIntoView({target:{type:"trackedChange",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Pg()},{shouldContinue:o.continuation?.shouldContinue})}function Tg(e){if(e==null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function fn(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(!fn(e[n],t[n]))return!1;return!0}if(!Tg(e)||!Tg(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)||!fn(e[n],t[n]))return!1;return!0}function $c(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 JE(e){return e.find(t=>t.type==="trackedChange")??null}function QE(e){return[...new Set(e.filter(t=>t.type==="trackedChange").map(t=>t.id))]}function eM(e,t){return e.find(r=>r.id===t)??null}function tM(e,t){let r=QE(t);if(r.length!==1)return null;let o=r[0]??JE(t)?.id??null;if(!o)return null;let n=eM(e,o);return!n||typeof n.id!="string"||n.id.length===0?null:{id:n.id,item:n}}function kg(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=Be(e);return o?tM(r,o.browserViewport.entitiesAtPoint(t)):null}var Eg=Object.freeze([]),rM=Object.freeze([]),oM=Object.freeze([]),nM=Object.freeze({});function Yc(e){return structuredClone(e)}function iM(){return{items:rM,permissions:nM,timeline:oM,summary:null,total:0,activeRevisionId:null,activeRevisionIds:Eg,enabled:!1,visible:!1,mode:null,replacementMode:null}}function sM(e,t){return fn(e,t)}function aM(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??Eg,enabled:e.enabled,visible:e.visible,mode:e.mode,replacementMode:e.replacementMode}:iM()}function Lr(e){let r=Be(e)?.session.readState();return aM(r?.review)}function Qc(){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,selected:!1}}function Jc(e,t){let r=Be(e);if(!r||!t)return Qc();let o=ai(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 gn(e,t){let r=Be(e);return r?r.reviewFocus.setActiveRevision(t):!1}function wn(e,t){let r=Be(e);return r?t==="next"?r.reviewFocus.nextActiveRevision():r.reviewFocus.previousActiveRevision():null}async function lM(e,t,r,o){if(!Be(e))return{success:!1};let i=Lr(e).activeRevisionId??null,s=ai(e,t);s.revisionId&&gn(e,s.revisionId);let a=await ta(e,t,r,{continuation:o});return o.shouldContinue()?(!a.success&&s.revisionId&&gn(e,i),a):{success:!1}}function Mg(e){let t=Be(e);if(!t)throw new Error("createBrowserEditorTrackChangesController requires a valid browser editor UI source.");let r=Lr(e),o=null,n=new Set,i=qs(),s=()=>{o||n.size===0||(o=t.session.subscribe(()=>{let c=Lr(e);if(sM(r,c)){r=c;return}r=c;for(let d of[...n])d(Yc(r))}))},a=()=>{n.size>0||!o||(o(),o=null)},l=c=>(r=Lr(e),n.add(c),s(),c(Yc(r)),()=>{n.delete(c),a()});return{getSnapshot(){return r=Lr(e),Yc(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(),gn(e,c)},next(){return i.invalidate(),wn(e,"next")},previous(){return i.invalidate(),wn(e,"previous")},reveal(c){i.invalidate();let d=ai(e,c);return d.revisionId&&gn(e,d.revisionId),Jc(e,c)},revealNext(){i.invalidate();let c=wn(e,"next");return c?Jc(e,c):Qc()},revealPrevious(){i.invalidate();let c=wn(e,"previous");return c?Jc(e,c):Qc()},getAt(c){return r=Lr(e),kg(e,c,r.items)},scrollTo(c,d){return lM(e,c,d,i.begin())},navigateNext(c){let d=i.begin(),u=Lr(e).activeRevisionId??null,m=wn(e,"next");return m?ta(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||gn(e,u),p):{success:!1}):Promise.resolve({success:!1})},navigatePrevious(c){let d=i.begin(),u=Lr(e).activeRevisionId??null,m=wn(e,"previous");return m?ta(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||gn(e,u),p):{success:!1}):Promise.resolve({success:!1})},getRect({id:c}){return dn(t,{target:{type:"trackedChange",id:c}})}}}function ra(e){let t=cM(e.session),r=bg(e,t),o=vg(e,t),n=yg(e,t),i=Bg(e,t),s=Cg(e,t),a=xg(e,t),l=Yw(e,t.comments),c=Mg(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 dM=["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"],uM=new Set(dM);function Ig(e){return uM.has(e)}var Ag=Object.freeze([{id:"align-left",title:"Align Left",group:"block",description:"Align the selected blocks to the left edge of the text column.",keywords:["alignment","paragraph","start"],slash:!0},{id:"align-center",title:"Align Center",group:"block",description:"Center the selected blocks between the text column margins.",keywords:["alignment","paragraph","centre"],slash:!0},{id:"align-right",title:"Align Right",group:"block",description:"Align the selected blocks to the right edge of the text column.",keywords:["alignment","paragraph","end"],slash:!0},{id:"align-justify",title:"Justify",group:"block",description:"Stretch the selected blocks so both edges meet the text column.",keywords:["alignment","paragraph","both","full"],slash:!0},{id:"indent-increase",title:"Increase Indent",group:"block",description:"Push the selected blocks one indent step further from the margin.",keywords:["indent","paragraph","increase"],slash:!0},{id:"indent-decrease",title:"Decrease Indent",group:"block",description:"Pull the selected blocks one indent step back toward the margin.",keywords:["indent","paragraph","decrease"],slash:!0}]);var Ng=Object.freeze([{id:"insert-table",title:"Insert Table",group:"insert",description:"Insert a three by three table after the current block.",keywords:["table","grid","insert"],slash:!0},{id:"insert-image",title:"Insert Image",group:"insert",description:"Insert a picture after the current block.",keywords:["image","picture","photo","insert"],slash:!0},{id:"table-insert-row-above",title:"Insert Row Above",group:"table",description:"Insert an empty row above the row the caret is in.",keywords:["table","row","insert"],slash:!1},{id:"table-insert-row-below",title:"Insert Row Below",group:"table",description:"Insert an empty row below the row the caret is in.",keywords:["table","row","insert"],slash:!1},{id:"table-insert-column-left",title:"Insert Column Left",group:"table",description:"Insert an empty column to the left of the caret column.",keywords:["table","column","insert"],slash:!1},{id:"table-insert-column-right",title:"Insert Column Right",group:"table",description:"Insert an empty column to the right of the caret column.",keywords:["table","column","insert"],slash:!1},{id:"table-delete-row",title:"Delete Row",group:"table",description:"Delete the row the caret is in, or the whole table if it is the last row.",keywords:["table","row","delete"],slash:!1},{id:"table-delete-column",title:"Delete Column",group:"table",description:"Delete the caret column, or the whole table if it is the last column.",keywords:["table","column","delete"],slash:!1},{id:"table-delete",title:"Delete Table",group:"table",description:"Delete the whole table the caret is in.",keywords:["table","delete"],slash:!1},{id:"table-merge-cells",title:"Merge Cells",group:"table",description:"Merge the selected cells into one cell spanning their rectangle.",keywords:["table","cell","merge"],slash:!1},{id:"table-split-cell",title:"Split Cell",group:"table",description:"Split the merged cell at the caret back into its parts.",keywords:["table","cell","split","unmerge"],slash:!1}]);function j(e,t,r,o,n=[],i=!0){return{id:e,title:t,group:r,description:o,keywords:n,slash:i}}var li=Object.freeze([j("undo","Undo","history","Revert the latest local editing step.",["history"],!1),j("redo","Redo","history","Re-apply the latest reverted step.",["history"],!1),j("zoom","Zoom","view","Set the document zoom level as a percentage.",["view","scale","percent"],!1),j("zoom-fit-width","Fit Width","view","Toggle fit-width zoom mode for the current viewport.",["view","scale","fit","width"],!1),j("document-mode-editing","Editing Mode","review","Switch the editor into direct editing mode.",["edit","write","author"],!1),j("document-mode-suggesting","Suggesting Mode","review","Switch the editor into suggestion authoring mode.",["suggest","track changes","review"],!1),j("document-mode-viewing","Viewing Mode","review","Switch the editor into read-only viewing mode.",["view","read-only","preview"],!1),j("flow-mode-paginated","Paginated Layout","view","Switch the editor into paginated layout mode.",["pagination","pages","print"],!1),j("flow-mode-web","Web Layout","view","Switch the editor into continuous web layout mode.",["web","continuous","scroll"],!1),j("layout-mode-vertical","Vertical Spread","view","Arrange paginated pages in a vertical stack.",["vertical","stack"],!1),j("layout-mode-horizontal","Horizontal Spread","view","Arrange paginated pages in a horizontal strip.",["horizontal","row"],!1),j("layout-mode-book","Book Spread","view","Arrange paginated pages in facing book spreads.",["book","spread","facing"],!1),j("track-changes-display-review","Review Markup","review","Display the document with review markup visible.",["markup","review mode"],!1),j("track-changes-display-original","Original Document","review","Project the document back to its original review baseline.",["original","projection"],!1),j("track-changes-display-final","Final Document","review","Project the document forward to its final accepted review state.",["final","projection"],!1),j("track-changes-display-off","Hide Review Markup","review","Hide tracked-change markup without switching authoring mode.",["hide markup","off"],!1),j("bold","Bold","format","Toggle bold formatting.",["strong","weight"]),j("italic","Italic","format","Toggle italic formatting.",["emphasis"]),j("underline","Underline","format","Toggle underline formatting.",["decoration"]),j("strikethrough","Strikethrough","format","Toggle strikethrough formatting.",["strike","delete","decoration"]),j("font-size","Font Size","format","Set or clear the font size on the current text selection.",["type","points"],!1),j("font-family","Font Family","format","Set or clear the font family on the current text selection.",["typeface","font"],!1),j("text-color","Text Color","format","Set or clear the text color on the current text selection.",["color","foreground"],!1),j("highlight-color","Highlight Color","format","Set or clear text highlight on the current selection.",["highlight","background"],!1),j("paragraph","Paragraph","block","Reset the current block to body paragraph text.",["body","normal"]),j("heading-1","Heading 1","block","Promote the current block to the top heading level.",["title","h1"]),j("heading-2","Heading 2","block","Promote the current block to a section heading.",["section","h2"]),j("heading-3","Heading 3","block","Promote the current block to a subsection heading.",["subsection","h3"]),j("bullet-list","Bulleted List","block","Toggle a bulleted list around the current block.",["list","bullets","unordered"]),j("numbered-list","Numbered List","block","Toggle a numbered list around the current block.",["list","ordered","numbers"]),...Ag,...Ng,j("insert-math-inline","Insert Equation","insert","Append an editable math OOXML node to the active text block.",["equation","math","formula"]),j("insert-chart-block","Insert Chart","insert","Insert an editable chart OOXML block after the current block.",["chart","graph","series"]),j("insert-shape-block","Insert Shape","insert","Insert an editable shape OOXML block after the current block.",["shape","callout","diagram"]),j("remove-selected-ooxml","Remove Selected OOXML","insert","Remove the currently selected advanced OOXML node.",["equation","chart","shape","delete"]),j("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),j("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),j("selected-chart-set-title","Edit Selected Chart Title","insert","Update the title on the currently selected chart OOXML node.",["chart","title"],!1),j("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),j("selected-chart-add-axis","Add Selected Chart Axis","insert","Append a new axis to the currently selected chart OOXML node.",["chart","axis","scale"],!1),j("selected-shape-set-text-body","Edit Selected Shape Text","insert","Update the text body on the currently selected shape OOXML node.",["shape","text"],!1),j("selected-shape-set-fill","Edit Selected Shape Fill","insert","Update the fill color on the currently selected shape OOXML node.",["shape","fill","color"],!1),j("selected-shape-add-child","Add Selected Shape Child","insert","Append a child shape node to the currently selected OOXML shape.",["shape","group","child"],!1),j("link-set","Set Link","insert","Apply or update a link on the current selection.",["hyperlink","url"],!1),j("link-clear","Clear Link","insert","Remove link formatting from the current selection.",["unlink"],!1),j("comment-create","Create Comment","review","Create a comment at the current selection or caret.",["comment","annotation","note"],!1),j("comments-visible","Show Comments","review","Show comment highlights and threads in the browser editor.",["comments","visible"],!1),j("comments-hidden","Hide Comments","review","Hide comment highlights and threads in the browser editor.",["comments","hidden"],!1),j("comments-show-resolved","Show Resolved Comments","review","Include resolved comments in the comment list and review timeline.",["comments","resolved"],!1),j("comments-hide-resolved","Hide Resolved Comments","review","Filter resolved comments out of the comment list and review timeline.",["comments","resolved"],!1),j("comments-visibility-all","All Comments","review","Show both internal and external comments.",["comments","all"],!1),j("comments-visibility-internal","Internal Comments","review","Filter the comment display to internal comment threads.",["comments","internal"],!1),j("comments-visibility-external","External Comments","review","Filter the comment display to external comment threads.",["comments","external"],!1),j("tracking-toggle","Toggle Track Changes","review","Switch between direct editing and suggestion mode.",["suggesting","review","changes"]),j("track-changes-accept-selection","Accept Selection Changes","review","Accept tracked revisions that overlap the current selection.",["track changes","selection","accept"],!1),j("track-changes-reject-selection","Reject Selection Changes","review","Reject tracked revisions that overlap the current selection.",["track changes","selection","reject"],!1),j("search-set-query","Search","search","Run a document search query.",["find"],!1),j("search-next","Next Search Result","search","Advance to the next current search hit.",["find","next"],!1),j("search-previous","Previous Search Result","search","Move back to the previous current search hit.",["find","previous"],!1),j("search-clear","Clear Search","search","Clear the current search session.",["find","reset"]),j("search-replace-active","Replace Current Search Result","search","Replace the active current search hit.",["find","replace"],!1),j("search-replace-all","Replace All Search Results","search","Replace every current search hit.",["find","replace","all"],!1),j("review-accept-all","Accept All Changes","review","Accept all tracked revisions in the document.",["track changes","approve"]),j("review-reject-all","Reject All Changes","review","Reject all tracked revisions in the document.",["track changes","discard"]),j("proofing-ignore-first","Ignore First Proofing Issue","proofing","Ignore the first current proofing diagnostic.",["spelling","grammar","ignore"]),j("proofing-accept-first","Accept First Proofing Suggestion","proofing","Apply the first current proofing suggestion without tracking.",["spelling","grammar","fix"]),j("proofing-replace-first-tracked","Track First Proofing Fix","proofing","Apply the first current proofing suggestion with tracked changes.",["spelling","grammar","review"],!1)]),o_=Object.freeze(li.map(e=>e.id)),Sn=Object.freeze(li.filter(e=>!Ig(e.id)&&!Wl(e.id))),n_=Object.freeze(Sn.map(e=>e.id)),i_=new Map(li.map(e=>[e.id,e]));function mM(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 pM(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?mM(n):!1})}function ed(e,t){return ce([...e.activeChangeIds??[],...e.selection.trackedChangeIds??[]],t)}function td(e){let t=ce(e.liveSelectionInfo?.activeChangeIds,e.revisions);return t.length>0?t:ce(e.liveSelection.trackedChangeIds,e.revisions)}function fM(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 wM(e,t){return e.length>0&&e.length<t.length&&e.every(r=>t.includes(r))}function gM(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.liveReviewChangeIds.length>0&&e.effectiveReviewChangeIds.length>0&&!(fM(e)&&wM(e.liveReviewChangeIds,e.effectiveReviewChangeIds))&&!wr(e.liveReviewChangeIds,e.effectiveReviewChangeIds)}function SM(e){let t=ed(e.effectiveSelection,e.revisions),r=td({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 rd(e){return SM({...e,boundary:"end"})}function hM(e){let t=ed(e.effectiveSelection,e.revisions),r=td({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions}),o=pM(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 Ct(e){let t=td(e);if(!e.effectiveSelection)return t;if(rd({liveSelection:e.liveSelection,liveActiveChangeIds:de(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];if(hM({liveSelection:e.liveSelection,liveActiveChangeIds:de(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];let r=ed(e.effectiveSelection,e.revisions);return gM({liveSelection:e.liveSelection,liveReviewChangeIds:t,effectiveReviewChangeIds:r,effectiveSelection:e.effectiveSelection})?t:r.length>0?r:t}import{readSyntheticSideStoryDocOriginPath as vM}from"@datalking/begonia-doc-service/v1";var bM="Detached side-story surfaces are read-only. Route mutations through the host document controller.";function hn(e){return vM(e?.document??null)!=null}function er(e){return e?hn(e)?bM:e.editable?null:"Document is read-only in the current document mode.":"Editor is not ready."}function it(e){return er(e)==null}function oa(e){if(!e)return"Editor is not ready.";let t=er({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 od(e,t,r=null){let o=oa(e);return o||(r?.target||r?.selectionTarget||t&&Ut(t)?null:"Place the caret in text or select text before creating a comment.")}import{resolveTrackingToggleState as RM}from"@datalking/begonia-editor-contracts";function yM(e){return Bs([...e.activeChangeIds??[],...e.selection?.trackedChangeIds??[]])}function Fr(e,t=yM(e)){return dc({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 TM}from"@datalking/begonia-editor-contracts";import{resolveEditorSelectionRootOffsets as Og}from"@datalking/begonia-editor-contracts";function na(e){let t=Og(e);return t?{...t,empty:e.empty,trackedChangeIds:e.trackedChangeIds}:null}function Dg(e){let t=Og(e);return t?{kind:e.kind,...t,empty:e.empty,editable:e.editable,trackedChangeIds:[...e.trackedChangeIds],block:{...e.block},formatting:structuredClone(e.formatting)}:null}var jg=Object.freeze({canUndo:!1,canRedo:!1});function Vg(e){if(typeof e!="function")return!1;try{return e()===!0}catch{return!1}}function Lg(e){if(!e)return jg;let t=Vg(e.canUndo),r=Vg(e.canRedo);return!t&&!r?jg:{canUndo:t,canRedo:r}}var BM=["align-left","align-center","align-right","align-justify"],Fg=["indent-increase","indent-decrease"];function xM(e){return BM.includes(e)||Fg.includes(e)}function Hg(e,t,r,o){if(!xM(e.id))return null;if(Fg.includes(e.id)){let s=t.indentLeft??0;return o(e,r||e.id==="indent-decrease"&&s<=0,!1,s)}let n=e.id.slice(6),i=t.align??null;return o(e,r,i===n,i,t.mixedAttributes?.includes("align")===!0)}function zg(e){if(!e)return!1;let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1){let o=t.node(r).type.name;if(o==="table_cell"||o==="table_header")return!0}return!1}function qg(e){if(!e||e.selection.empty)return!1;let t=(()=>{let{$from:o}=e.selection;for(let n=o.depth;n>0;n-=1){let i=o.node(n).type.name;if(i==="table_cell"||i==="table_header")return i}return null})(),r=(()=>{let{$to:o}=e.selection;for(let n=o.depth;n>0;n-=1){let i=o.node(n).type.name;if(i==="table_cell"||i==="table_header")return i}return null})();return t==null||r==null?!1:e.selection.$from.pos!==e.selection.$to.pos}var CM=["insert-table","insert-image"],PM=["table-insert-row-above","table-insert-row-below","table-insert-column-left","table-insert-column-right","table-delete-row","table-delete-column","table-delete","table-split-cell"];function Wg(e,t,r,o){if(CM.includes(e.id))return o(e,!t.editable,!1,t.selection.block.kind);if(PM.includes(e.id)){let n=zg(r);return o(e,!t.editable||!n,n,null)}if(e.id==="table-merge-cells"){let n=qg(r);return o(e,!t.editable||!n,n,null)}return null}function wo(e){let t=Vr(e);return t.flowMode==="web"?t.preferredPaginatedLayoutMode:t.layoutMode}function nd(e){return e.flowMode==="paginated"||e.flowMode==="web"}function id(e){return e.zoom?.mode==="fit-width"?"fit-width":"manual"}function sd(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 ad(e,t){return e||!t}function Kg(e){let t=e&&typeof e=="object"?e.nodeType:null;return t==="paragraph"||t==="heading"}function _g(e,t){return t?t.selectionKind==="node"&&Kg(t.nodeSelectionTarget):Kg(Ce(e??null))}function F(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 vn(e){let t=e?.catalog??Sn,r=e?.commandIds;if(!r||r.length===0)return t;let o=e?.catalog??li,n=new Map(o.map(i=>[i.id,i]));return r.map(i=>n.get(i)).filter(i=>i!=null)}function Ug(e){return e.revisions}function Xg(e,t){let r=Vr(e),o=e.search.activeHitId?e.search.hits.findIndex(l=>l.hitId===e.search.activeHitId):-1,n=Ug(e),i=re(e.viewport),s=t?TM(t.selection,e.selection.range.revision,e.selection.range.range.anchor.story):e.toolbar.selection??e.selection,a=t?Fr(t):e.selectionInfo;return{selection:Gg(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 Zg(e,t,r,o,n,i){let s=i?.selection??Dg(t.selection)??{from:0,to:0,empty:!0},a=t.trackChanges.enabled,l=Lg(e?.surface),c=Ug(t),d=Ct({liveSelection:na(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:c,effectiveSelection:i}),u=t.editable?pr({editable:t.editable},o,i):"Document is read-only in the current document mode.",m=sd(u,s.empty,n,"inline"),p=sd(u,s.empty,n,"text-style"),f=t.editable?od({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i):od({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i),w=_g(o,i),v=ad(!t.editable||!s.editable&&!w,n),C=s.formatting.mixed??{},R=ad(u!=null,n);switch(r.id){case"bold":return F(r,m!=null,s.formatting.bold,s.formatting.bold,C.bold===!0);case"italic":return F(r,m!=null,s.formatting.italic,s.formatting.italic,C.italic===!0);case"underline":return F(r,m!=null,s.formatting.underline,s.formatting.underline,C.underline===!0);case"strikethrough":return F(r,m!=null,s.formatting.strike,s.formatting.strike,C.strike===!0);case"font-size":return F(r,p!=null,s.formatting.fontSize!=null||C.fontSize===!0,s.formatting.fontSize,C.fontSize===!0);case"font-family":return F(r,p!=null,s.formatting.fontFamily!=null||C.fontFamily===!0,s.formatting.fontFamily,C.fontFamily===!0);case"text-color":return F(r,p!=null,s.formatting.color!=null||C.color===!0,s.formatting.color,C.color===!0);case"highlight-color":return F(r,p!=null,s.formatting.highlight!=null||C.highlight===!0,s.formatting.highlight,C.highlight===!0);case"paragraph":return F(r,v,s.block.kind==="paragraph",s.block.kind);case"heading-1":return F(r,v,s.block.kind==="heading"&&s.block.headingLevel===1,s.block.headingLevel);case"heading-2":return F(r,v,s.block.kind==="heading"&&s.block.headingLevel===2,s.block.headingLevel);case"heading-3":return F(r,v,s.block.kind==="heading"&&s.block.headingLevel===3,s.block.headingLevel);case"bullet-list":return F(r,v,s.block.listKind==="bullet_list",s.block.listKind);case"numbered-list":return F(r,v,s.block.listKind==="ordered_list",s.block.listKind);case"zoom":return F(r,!1,!1,t.zoomPercent);case"zoom-fit-width":return F(r,!1,id(t)==="fit-width",id(t));case"document-mode-editing":return F(r,!1,t.documentMode==="editing",t.documentMode);case"document-mode-suggesting":return F(r,!t.trackChanges.enabled,t.documentMode==="suggesting",t.documentMode);case"document-mode-viewing":return F(r,!1,t.documentMode==="viewing",t.documentMode);case"flow-mode-paginated":return F(r,!1,t.flowMode==="paginated",t.flowMode);case"flow-mode-web":return F(r,!1,t.flowMode==="web",t.flowMode);case"layout-mode-vertical":return F(r,!1,wo(t)==="vertical",wo(t));case"layout-mode-horizontal":return F(r,!nd(t),wo(t)==="horizontal",wo(t));case"layout-mode-book":return F(r,!nd(t),wo(t)==="book",wo(t));case"track-changes-display-review":return F(r,!1,t.trackChanges.mode==="review",t.trackChanges.mode);case"track-changes-display-original":return F(r,t.documentMode!=="viewing",t.trackChanges.mode==="original",t.trackChanges.mode);case"track-changes-display-final":return F(r,t.documentMode!=="viewing",t.trackChanges.mode==="final",t.trackChanges.mode);case"track-changes-display-off":return F(r,!1,t.trackChanges.mode==="off",t.trackChanges.mode);case"comments-visible":return F(r,!t.commentsDisplay.enabled,t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-hidden":return F(r,!t.commentsDisplay.enabled,!t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-show-resolved":return F(r,!t.commentsDisplay.enabled,t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-hide-resolved":return F(r,!t.commentsDisplay.enabled,!t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-visibility-all":return F(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="all",t.commentsDisplay.visibility);case"comments-visibility-internal":return F(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="internal",t.commentsDisplay.visibility);case"comments-visibility-external":return F(r,!t.commentsDisplay.enabled,t.commentsDisplay.visibility==="external",t.commentsDisplay.visibility);case"tracking-toggle":{let h=RM({editable:t.editable,documentMode:t.documentMode,trackingEnabled:a,trackChangesAvailable:a});return F(r,h.disabled,h.active,t.documentMode)}case"comment-create":return F(r,f!=null,!1,t.comments.length);case"link-set":return F(r,R,s.formatting.link||C.linkHref===!0,s.formatting.linkHref,C.link===!0||C.linkHref===!0);case"link-clear":return F(r,R||!s.formatting.link&&C.linkHref!==!0,s.formatting.link||C.linkHref===!0,s.formatting.linkHref,C.link===!0||C.linkHref===!0);case"track-changes-accept-selection":case"track-changes-reject-selection":return F(r,d.length===0||!t.editable,d.length>0,d);case"review-accept-all":case"review-reject-all":return F(r,c.length===0||!t.editable,!1,c.length)}let B=(t.toolbar.commands??{})[r.id];if(B)return{...B,title:r.title,description:r.description??null,group:r.group??null};switch(r.id){case"search-set-query":return F(r,!1,t.search.query.length>0,t.search.query);case"search-next":case"search-previous":return F(r,t.search.hits.length===0,!1,t.search.activeHitId);case"search-clear":return F(r,t.search.query.length===0,!1,t.search.query);case"search-replace-active":return F(r,t.search.hits.length===0||!t.editable,!1,t.search.activeHitId);case"search-replace-all":return F(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 F(r,t.proofing.diagnostics.length===0||!t.editable,!1,t.proofing.diagnostics[0]?.diagnosticId??null);case"insert-math-inline":return F(r,!t.editable||!s.editable||w,!1,s.block.kind);case"insert-chart-block":case"insert-shape-block":return F(r,!t.editable,!1,t.selection.block.kind);case"remove-selected-ooxml":return F(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 F(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 F(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 F(r,t.advancedOoxml.selected?.family!=="shape"||!t.editable,t.advancedOoxml.selected?.family==="shape",t.advancedOoxml.selected?.objectId??null);case"undo":return F(r,!t.editable||!l.canUndo);case"redo":return F(r,!t.editable||!l.canRedo);default:{let h=Hg(r,s.block,v,F);return h||(Wg(r,t,o,F)??F(r))}}}function Gg(e,t,r){if(!e)return null;let o=on(e,r),n=t?so(t,o,r):null;return Qs(o,n)}function $g(e,t){let r=Vr(e),o=re(e.viewport?.value??null),n=e.selection?on(e.selection,e.review.revisions):e.selection,i=n??e.selection,s=e.selectionInfo&&i?so(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 cS,deriveEditorUiSnapshot as ZM}from"@datalking/begonia-editor-contracts";function kM(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 Yg(e,t){if(t==null)return[...e];let r=new Set(Ge(t).values());return e.filter(o=>r.has(o))}function EM(e){return Yg(jt(e.selectionInfo?.activeCommentIds,Ge(e.comments)),e.comments)}function ld(e){let t=EM(e);return{activeCommentIds:t,activeCommentId:t.length===1?t[0]??null:null}}function cd(e){return Yg(jt(kM([...e.explicitActiveCommentIds??[],e.explicitActiveCommentId]),Ge(e.comments)),e.comments)}function bn(e){let t=ld(e);if(t.activeCommentIds.length>0)return t;let r=cd(e);return{activeCommentIds:r,activeCommentId:r.length===1?r[0]??null:null}}function dd(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 MM(e){let t=dd(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 go(e){let t=MM(e);return{activeRevisionIds:t,activeRevisionId:t.length===1?t[0]??null:null}}function IM(e){let t=dd([...e.explicitActiveRevisionIds??[],e.explicitActiveRevisionId]),r=dd(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 Jg(e){let t=go(e);if(t.activeRevisionIds.length>0)return t;let r=IM(e);return{activeRevisionIds:r,activeRevisionId:r.length===1?r[0]??null:null}}function br(e){return Object.freeze([...e])}var Hr=Object.freeze({history:br(["undo","redo"]),view:br(["zoom","zoom-fit-width","flow-mode-paginated","flow-mode-web","layout-mode-vertical","layout-mode-horizontal","layout-mode-book"]),formatting:br(["bold","italic","underline","strikethrough","font-size","font-family","text-color","highlight-color","link-set","link-clear"]),blocks:br(["paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list","align-left","align-center","align-right","align-justify","indent-increase","indent-decrease"]),review:br(["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:br(["search-set-query","search-next","search-previous","search-clear","search-replace-active","search-replace-all"]),proofing:br(["proofing-ignore-first","proofing-accept-first","proofing-replace-first-tracked"]),insert:br(["insert-table","insert-image","table-insert-row-above","table-insert-row-below","table-insert-column-left","table-insert-column-right","table-delete-row","table-delete-column","table-delete","table-merge-cells","table-split-cell"]),advancedOoxml:br(["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"])}),ia=Object.freeze([{id:"history",label:"History",commandIds:Hr.history},{id:"view",label:"View",commandIds:Hr.view},{id:"formatting",label:"Formatting",commandIds:Hr.formatting},{id:"blocks",label:"Blocks",commandIds:Hr.blocks},{id:"insert",label:"Insert",commandIds:Hr.insert},{id:"review",label:"Review",commandIds:Hr.review},{id:"search",label:"Search",commandIds:Hr.search},{id:"proofing",label:"Proofing",commandIds:Hr.proofing}]),Q_=Object.freeze(ia.flatMap(e=>[...e.commandIds]));function AM(e){return[{id:"commands",label:"Commands",commandIds:e.map(t=>t.id)}]}function NM(e,t){if(t&&t.length>0)return t;if(e.length===0)return[];let r=new Set(ia.flatMap(n=>n.commandIds));return e.every(n=>r.has(n.id))?ia:AM(e)}function OM(e){return e?[...e]:[]}function DM(e,t){return{id:e.id,title:e.title,description:e.description??null,group:e.group??null,keywords:OM(e.keywords),slash:e.slash??!1,state:t}}function jM(e,t,r){return e.flatMap(o=>{let n=t.get(o);return n?[DM(n,r[o]??null)]:[]})}function Qg(e){let t=NM(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:jM(o.commandIds,r,e.commands)})).filter(o=>o.items.length>0)}import{normalizeCommittedDocument as FM}from"@datalking/begonia-document-model";import{createDocumentRuntimeKernel as HM}from"@datalking/begonia-document-api/v1";import{createDocumentScopedMemo as zM,resolveRevisionProjectedDocument as qM}from"@datalking/begonia-engine";import{preserveSyntheticSideStoryDocMetadata as VM,readSyntheticSideStoryDocOriginPath as eS}from"@datalking/begonia-doc-service/v1";function LM(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 tS(e){let t=null;for(let r of e){let o=eS(r);if(o){if(t&&!LM(t,o))return null;t=o}}return t}function Pt(e,t){return eS(e)?VM(e,t):t}function WM(e,t){let r=null,o=null,n=s=>((s!==r||!o)&&(r=s,o=FM(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 oS(e){return e??null}function KM(e,t){return Pt(e,qM(e,t.schema,t.mode))}var rS=new WeakMap;function _M(e){let t=rS.get(e);if(t)return t;let r=zM({compute:(o,n)=>KM(o,{schema:e,mode:n})});return rS.set(e,r),r}function nS(e,t,r){return _M(t).read(e,r)}function iS(e,t,r){let o=UM(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 UM(e,t,r){return HM(WM(e,r),{review:{replacementMode:t}})}function sS(e){return e==="final"||e==="original"?e:null}function yr(e,t){return typeof e=="boolean"?e:t}function XM(e,t){return mo(e)??t}function sa(e,t){return e!=null?Gs(e):t===!1?"editing":"suggesting"}function yn(e,t){let r=yr(t?.enabled,!0),o=yr(t?.visible,e!=="viewing"),n=e==="viewing"?o?"review":"original":"review";return{enabled:r,visible:o,mode:co(t?.mode)??n,replacements:uo(t?.replacements)??"paired"}}function aS(e,t){let r=yr(t?.enabled,!0),o=yr(t?.visible,e!=="viewing"),n=yr(t?.readOnly,e==="viewing"),i=yr(t?.useInternalExternalComments,!1),s=yr(t?.suppressInternalExternal,!1),a=s?"external":XM(t?.visibility,"all");return{enabled:r,visible:o,readOnly:n,allowResolve:n?!1:yr(t?.allowResolve,!0),showResolved:yr(t?.showResolved,!1),visibility:a,useInternalExternalComments:i,suppressInternalExternal:s,enforceVisibilityPolicy:i||s}}function lS(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 Bn(e){return e!=="viewing"}function zr(e,t){return e==="suggesting"&&t.enabled}function aa(e,t,r,o=!1){return e.collaborative&&!o||t!=="viewing"?null:r.mode==="original"||r.mode==="final"?r.mode:null}function Ie(e,t,r){return r==null?e:Pt(e,nS(e,t.schema,r))}function ud(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 dS=["undo","redo","bold","italic","underline","strikethrough","paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list","link-set","link-clear","align-left","align-center","align-right","align-justify","indent-increase","indent-decrease","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection"];function GM(e){return zr(e.documentMode,e.trackChanges)}function $M(e){return e.collaboration.collaborative??!1}function YM(e){return{selection:cS(e.selection),editable:e.editable,trackingEnabled:GM(e),trackingAuthoringAvailable:e.trackChanges.enabled,documentMode:e.documentMode,collaborative:$M(e),canUndo:e.canUndo,canRedo:e.canRedo,commandStates:e.commandStates}}function JM(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 QM(e,t){return t?.commands??e.toolbar.commands}function la(e){return ZM(YM(e))}function eI(e,t){let r=la(JM(e,QM(e,t))),o=t?.catalog??[];return{...r,catalog:o,sections:Qg({catalog:o,commands:r.commands})}}function xn(e,t){let r=eI(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=go({revisions:e.revisions,selectionInfo:e.selectionInfo}),l=bn({comments:e.comments,selectionInfo:e.selectionInfo,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds}),c=e.activeRevisionId??a.activeRevisionId,d=e.activeRevisionIds??a.activeRevisionIds;return{selection:cS(e.selection),selectionInfo:un(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 ci(e,t=vn(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:Xg(r,i),catalog:t,commands:Object.fromEntries(t.map(s=>[s.id,Zg(e,r,s,o,n,i)]))}}function uS(e,t=vn(void 0)){let r=ci(e,t),o=e.getState();return{editor:$g(xn(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 tI}from"@datalking/begonia-editor-contracts";function md(e){return e?e.documentService.readDocument():null}function pd(e){return Xe(e)?.view??null}function fd(e){return Xe(e)?.automation??null}function wd(e,t){let r=Xe(e);return r?(r.replaceDocument(t,{origin:"api",intent:"replace-browser-document",effects:[tI("content")]}),!0):!1}function rI(e){return e?"documentApi"in e?Xe(e):e:null}function So(e,t){let r=rI(e),o=r?.view;if(!o?.state||typeof o.dispatch!="function")return!1;let n=r,i=$e(o.state.doc,t);if(!i)return!1;let s=K(o.state,i.from,i.to);return s?qe(n,s):!1}var ca=Symbol("captureBrowserEditorPositionAtPointInternal");import{NodeSelection as pS}from"prosemirror-state";function oI(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Math.trunc(t),e.doc.content.size))}function mS(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(Math.trunc(t),e.doc.content.size))}function nI(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 iI(e,t){let r=K(e,t,t);if(!r)return null;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function sI(e,t){try{return e.apply(e.tr.setSelection(pS.create(e.doc,t)))}catch{return null}}function aI(e,t){let r=e.doc.nodeAt(t);return!!(r&&pS.isSelectable(r)&&(r.isLeaf||r.isAtom))}function lI(e,t){return[mS(e,t?.inside),mS(e,t?.pos)].filter((o,n,i)=>o!=null&&i.indexOf(o)===n).find(o=>aI(e,o))??null}function Cn(e){let t=e.surface.view;if(!t?.state||typeof t.posAtCoords!="function"||!nI(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=lI(t.state,r);if(s!=null){let a=sI(t.state,s);if(a)return{pos:s,state:a}}}let n=oI(t.state,r?.pos);if(n==null)return null;let i=iI(t.state,n);return i?{pos:n,state:i}:null}function cI(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 dI(e,t){let r=Cn({surface:e.surface,clientX:t.clientX,clientY:t.clientY});if(!r?.state.selection.empty)return null;let o=Me(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 uI(e,t){return e&&typeof e=="object"&&"kind"in e&&e.kind==="text"?t:e}function fS(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))fS(t);return e}function mI(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:fS(structuredClone({...e,selectionTarget:t,target:uI(e.target,t)}))}function ho(e,t){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let r=e[ca]?.(t)??null;if(!r||!r.selection.empty)return null;let o=dI(e,t),n=o?.point??cI(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?mI(r,o.target):r;return{point:n,target:i,capture:s}}function wS(e){return{readDocument(){return md(e)},replaceDocument(t){return wd(e,t)},readView(){return pd(e)},readAutomation(){return fd(e)}}}function pI(e){return{positionAtPoint(t){return ho(e,t)},selectTextTarget(t){return Pc(e.surface,t)},selectCommentTarget(t){return So(e,t)}}}function gS(e){return{selectionHandles:e,linkSelection:e,activeLink:e,view:e,documentMode:e,commentsDisplay:e,commentActions:e,commentFocus:e,reviewActions:e,reviewFocus:e,selectionTargets:pI(e)}}import{createCanonicalRevisionIdsByAlias as fI,resolveCanonicalRevisionId as wI,resolveTrackedOverlapParentIdMap as gI}from"@datalking/begonia-engine";var da=3,SI=[[0,0],[-da,0],[da,0],[0,-da],[0,da]];function Br(e,t){if(!e||typeof e.getAttribute!="function")return null;let r=e.getAttribute(t);return typeof r=="string"?r.trim():null}function hS(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function hI(e,t){return!t||!e.includes(t)?[...e]:[t,...e.filter(r=>r!==t)]}function vI(e){let t=hS(Br(e,"data-track-change-ids"));if(t.length>0)return hI(t,Br(e,"data-track-change-preferred-target-id"));let r=Br(e,"data-track-change-id");if(r)return[r];let o=Br(e,"data-change-id");return o?[o]:[]}function bI(e){return!!(Br(e,"data-ald-comment-anchor")||Br(e,"data-ald-comment-range-start")||Br(e,"data-ald-comment-range-end"))}function yI(e){let t=hS(Br(e,"data-comment-ids"));if(t.length>0)return t;let r=Br(e,"data-thread-id");return r&&bI(e)?[r]:[]}function vS(e,t){let r=e??null;for(;r;){if(r===t)return!0;r=r.parentElement??null}return!1}function BI(e,t,r){if(!e||!vS(e,t))return[];let o=[],n=e;for(;n;){for(let i of vI(n)){let s=`trackedChange:${i}`;r.has(s)||(r.add(s),o.push({kind:"trackedChange",id:i}))}for(let i of yI(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 xI(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 CI(e,t){return e.some(r=>vS(r,t))}function SS(e,t){let r=Number(t);return Number.isFinite(r)?Math.max(0,Math.min(e,Math.max(0,r-1))):e}function PI(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 SI.slice(1)){let d=SS(t+l,n),u=SS(r+c,i),m=`${d}:${u}`;a.has(m)||(a.add(m),s.push({x:d,y:u}))}return s}function bS(e,t,r,o){let n=xI(e,t,r);return{stack:n,candidates:n.flatMap(i=>BI(i,e,o))}}function RI(e,t,r,o){let n=[];for(let i of PI(e,t,r))n.push(...bS(e,i.x,i.y,o).candidates);return n}function TI(e,t){let r=ce(e,t??[]),o=r.length>0?r:[...e],n=o[0]??null;return!n||o.length>1&&!NI(o,t)?null:{status:"resolved",kind:"trackedChange",trackedChangeIds:[n],commentIds:[]}}function kI(e){return e.relationship==="child"||!!e.overlapParentId||(e.members??[]).some(t=>t.relationship==="child"||!!t.overlapParentId)}function EI(e){return[e.overlapParentId,...(e.members??[]).map(t=>t.overlapParentId)]}function MI(e,t,r){let o=new Set;for(let n of EI(e)){let i=wI(n,t);i&&i!==e.id&&r.has(i)&&o.add(i)}return o.size===1?[...o][0]:null}function II(e){if(!e||e.length===0)return new Map;let t=fI(e),r=new Set(e.map(o=>o.id));return gI(e.map(o=>({id:o.id,overlapParentId:kI(o)?MI(o,t,r):null})))}function AI(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 NI(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=AI(r[0],II(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 gd(e){let t=e.host??null;if(!t)return[];let r=new Set,o=bS(t,e.clientX,e.clientY,r),n=o.candidates.length>0?o.candidates:CI(o.stack,t)?RI(t,e.clientX,e.clientY,r):[];if(n.length===0)return[];let i=e.revisions??[],s=Ge(e.comments),a=[],l=new Set;for(let c of n){let d=c.kind==="trackedChange"?ce([c.id],i)[0]??c.id:jt([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 yS(e){let t=gd(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?TI(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 OI(e){return e?{empty:e.empty,target:e.selectionTarget?Ot(e.selectionTarget):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}function DI(e,t){let r=e.getState();return gd({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 jI(e,t,r,o,n){if(e)return!1;let i=t?.selectionTarget??n;if(t?.selectionKind==="node"||r?.selectionKind==="node")return fr(t?.nodeSelectionTarget,r?.nodeSelectionTarget);let s=r?.empty?r.selectionTarget:null;return Ms(s??o,i)}function VI(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 LI(e,t,r,o){if(!e||!t||t.empty)return null;let n=si(e,t);return n.length===0?null:VI(r,o,n)}function Sd(e,t){return!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number"?[]:DI(e,t)}function BS(e,t,r=null){let o=e.getState(),n=ho(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=LI(r,o.selection,a,l);return{point:{x:a,y:l},entities:Sd(e,t),position:n,selection:un(o.selectionInfo??OI(i)),insideSelection:c??jI(o.selection.empty,i,s,n?.target??null,o.selectionInfo?.target??null)}}function di(e){return e!=null&&typeof e.contains=="function"}function hd(e){return typeof e=="string"?e.trim().toLowerCase():""}function FI(e){return e.ownerDocument?.defaultView?.getComputedStyle?.(e)??null}function xS(e){let t=FI(e);if(!t)return{horizontal:"",vertical:""};let r=hd(t.overflow);return{horizontal:hd(t.overflowX)||r,vertical:hd(t.overflowY)||r}}function ua(e){return e==="auto"||e==="scroll"||e==="overlay"}function HI(e){return{vertical:(e.scrollHeight??0)>(e.clientHeight??0),horizontal:(e.scrollWidth??0)>(e.clientWidth??0)}}function zI(e){let t=xS(e),r=HI(e);return r.vertical&&ua(t.vertical)||r.horizontal&&ua(t.horizontal)}function qI(e){let t=xS(e);return ua(t.vertical)||ua(t.horizontal)}function Pn(e){let t=ma(e);return t?(di(t.parentElement)?t.parentElement:null)??t:null}function ma(e){let t=e?.view?.dom??null;return di(t)?t:null}function WI(e){let t=e??null;for(;di(t);){if(zI(t))return t;t=t.parentElement}return null}function KI(e){let t=[],r=e??null;for(;di(r);)qI(r)&&t.push(r),r=r.parentElement;return t}function ui(e){let t=e?.view?.dom??null;return di(t)?WI(t):null}function CS(e){let t=ma(e);return t?KI(t):[]}import{createVirtualPagedPreviewAncestorMutationObserver as _I,resolveVirtualPagedPreviewClippingAncestorElements as TS}from"@datalking/begonia-layout-renderer";var PS={passive:!0};function RS(e){if(typeof e.getState!="function")return null;let t=e.getState();return t.zoom?.value??t.zoomPercent??null}function mi(e){return typeof e.getState=="function"?e.getState():null}function vd(e){return e?.commentsDisplay?.enabled===!0&&e.commentsDisplay.visible===!0}function bd(e){return typeof e.getViewportState=="function"?re(e.getViewportState()):null}function UI(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 XI(e){let t=e;return typeof t?.ResizeObserver=="function"?t.ResizeObserver:null}function ZI(e,t){let r=new Set;if(jo(e)){r.add(e);for(let o of TS(e))r.add(o)}for(let o of t)jo(o)&&r.add(o);return[...r]}function GI(e,t,r,o){let n=new Set;r&&n.add(r);let i=ma(t);i&&n.add(i);for(let s of CS(t))n.add(s);if(e)for(let s of TS(e))n.add(s);return n.size===0&&o&&n.add(o),[...n]}function $I(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function kS(e,t=null){let r=new Set,o=new Set,n=!1,i=null,s=bd(e),a=mi(e)?.flowMode??null,l=mi(e)?.layoutMode??null,c=vd(mi(e)),d=RS(e),u=!1,m=null,p=null,f=null,w=[],v=null,C=[],R=null,S=null,B=!1,h=e.surface??null,y=()=>{B=!0,H("scroll")},T=()=>{B=!0,H("resize")},A=()=>{let G=Pn(e.surface)?.ownerDocument?.defaultView??null;return UI(G)},D=()=>{let E=i;i=null,E?.cancel()},O=E=>{if(i?.token!==E)return;i=null;let G=[...o];if(o.clear(),n=!1,B&&(B=!1,M(),S?.sync()),r.size===0||G.length===0)return;let we=G.length===1?G[0]:"mixed";for(let ve of[...r])try{ve({reason:we})}catch{}},U=()=>{let E=A(),G={},we=null;i={token:G,cancel(){E.cancel(we)}};try{we=E.request(()=>O(G))}catch(ve){throw i?.token===G&&(i=null),ve}},H=E=>{r.size!==0&&((E==="layout"||E==="zoom")&&n&&(o.delete("scroll"),n=!1),E==="scroll"&&(n=!1),o.add(E),!i&&U())},le=()=>{r.size!==0&&(o.has("scroll")||(n=!0),o.add("scroll"),!i&&U())},ne=()=>{f?.removeEventListener?.("scroll",y,!0),f?.removeEventListener?.("resize",T);for(let E of w)E!==f&&E.removeEventListener?.("scroll",y,PS);R?.disconnect(),f=null,w=[],v=null,C=[],R=null},M=()=>{let E=Pn(e.surface),G=E?.ownerDocument?.defaultView??null,we=ui(e.surface),ve=GI(E,e.surface,we,G),Ne=ZI(E,ve);if(E===v&&G===f&&ve.length===w.length&&ve.every((Oe,st)=>Oe===w[st])&&$I(Ne,C))return;ne(),v=E,f=G,w=ve,C=Ne,f?.addEventListener?.("scroll",y,!0),f?.addEventListener?.("resize",T);for(let Oe of ve)Oe!==f&&Oe.addEventListener?.("scroll",y,PS);let It=XI(f);if(!It)return;let Ke=new It(()=>{M(),S?.sync(),H("resize")});for(let Oe of Ne)Ke.observe(Oe);R=Ke},N=()=>{S||(S=_I({getPreviewHost:()=>Pn(e.surface),getAdditionalHosts:()=>[ui(e.surface)],onMutation(){M(),S?.sync(),H("layout")}})),S.sync()},V=()=>{let E=mi(e);if(!E)return;B=!0;let G=(e.surface??null)!==h;h=e.surface??null;let we=E.zoom?.value??E.zoomPercent??null;we!==d&&(u=!0,d=we);let ve=bd(e),Ne=s,It=ve?.scale!==Ne?.scale,Ke=!et(Ne,ve);s=ve;let Oe=E.flowMode,st=E.layoutMode,nr=Oe!==a||st!==l;a=Oe,l=st;let Ht=vd(E),Tr=Ht!==c;if(c=Ht,It&&u){u=!1,H("zoom");return}if(u&&Oe==="web"){u=!1,H("zoom");return}if(nr||Ke&&ve?.totalPages!==Ne?.totalPages){let kr=u?"zoom":"layout";u=!1,H(kr);return}if(Tr){H("layout");return}if(G){H("layout");return}Ke&&le()},b=()=>{if(B=!0,u){u=!1,H("zoom");return}H("layout")},x=()=>{if(m)return;h=e.surface??null,s=bd(e);let E=mi(e);a=E?.flowMode??null,l=E?.layoutMode??null,c=vd(E),d=RS(e),u=!1,M(),N(),m=typeof e.subscribe=="function"?e.subscribe(V):null,p=t?.subscribeResolvedProjection?.(b)??null},I=()=>{m?.(),p?.(),m=null,p=null,ne(),S?.cleanup(),S=null,D(),o.clear(),n=!1,u=!1,B=!1};return{observe(E){return r.add(E),r.size===1&&x(),()=>{r.delete(E)&&r.size===0&&I()}}}}import{resolveProjectionCaretRect as YI}from"@datalking/begonia-page-layout";function Rn(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function qr(e,t){return t>0?e/t:null}function MS(e){return Array.isArray(e)&&e.length>0?[...e]:null}function IS(e){return typeof e=="number"&&Number.isInteger(e)?e:null}function JI(e,t){let r=Number.isFinite(e)?Math.max(0,Math.trunc(e)):0;return t==null?r:Math.min(t,r)}function AS(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 QI(e){return!e||e.kind!=="text"||!Array.isArray(e.segments)||e.segments.length===0?[]:e.segments.filter(t=>!!t?.blockId)}function eA(e,t){return e.targets?.resolve?.({kind:"block",blockId:t})??null}function tA(e,t){let r=MS(t?.path??null);if(r)return e.blocks?.ancestorOf?.(r)??null;let o=IS(t?.anchorFrom);return o==null?null:e.blocks?.byAnchor?.(o)??null}function rA(e,t){let r=eA(e,t.blockId);if(!r)return null;let o=tA(e,r),n=IS(o?.from??r.anchorFrom);if(n==null)return null;let i=JI(t.range.start,typeof r.text=="string"?r.text.length:null);return{absolutePos:n+i,anchorFrom:n,pathHint:MS(o?.path??r.path??null)}}function oA(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex}function nA(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 ES(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 iA(e){return e.left+Math.min(Math.max(0,e.width/2),Math.max(0,e.width-1))}function sA(e){return e.top+Math.min(Math.max(0,e.height/2),Math.max(0,e.height-1))}function aA(e,t,r,o){if(!r||typeof e.pagination.hitTest!="function")return null;let n=ES([iA(r),o.left,r.left,r.left+Math.max(0,r.width-1)]),i=ES([sA(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&&oA(l,r))return l}return null}function lA(e,t){return e.find(r=>nA(r,t))??null}function cA(e,t,r,o,n,i){let s=AS(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=Rn(t.top,l),d=Rn(t.left,a),u=n??i,m=u?t.top-u.top:null,p=u?t.left-u.left:null,f=m==null?null:Rn(m,u?.height??0),w=p==null?null:Rn(p,u?.width??0);return{pageIndex:s.pageIndex,pageNumber:t.pageNumber,offsetTopPx:c,offsetTopRatio:qr(c,l),offsetLeftPx:d,offsetLeftRatio:qr(d,a),offsetPx:c,offsetRatio:qr(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:qr(f,u.height),blockOffsetLeftPx:w,blockOffsetLeftRatio:w==null||!u?null:qr(w,u.width)}}function dA(e,t,r,o={}){let n=rA(e,r);if(!n)return null;let i=YI(t,n.absolutePos,{bias:"start",measureText:o.measureText,measurementEpoch:o.measurementEpoch});if(!i)return null;let s=e.pagination.lines?.(t)??[],a=lA(s,i),l=aA(e,t,a,i),c=typeof e.pagination.locateAnchor=="function"?e.pagination.locateAnchor(n.anchorFrom,t):null,d=cA(t,i,n.anchorFrom,n.pathHint,l,c);return d?{anchorPageNumber:i.pageNumber,viewportAnchor:d}:null}function NS(e,t,r={}){let o=QI(t);if(o.length===0)return null;let n=e.pagination.project();for(let i of o){let s=dA(e,n,i,r);if(s)return s;let a=e.pagination.locateTarget({kind:"block",blockId:i.blockId},n);if(!a)continue;let l=AS(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=Rn(a.top,d),m=Rn(a.left,c);return{anchorPageNumber:a.pageNumber,viewportAnchor:{pageIndex:l.pageIndex,pageNumber:a.pageNumber,offsetTopPx:u,offsetTopRatio:qr(u,d),offsetLeftPx:m,offsetLeftRatio:qr(m,c),offsetPx:u,offsetRatio:qr(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 yd(e,t,r=null){let o=NS(e.documentApi,t,Bt(r)??{});if(!o)return null;let n={anchorPageNumber:o.anchorPageNumber,viewportAnchor:o.viewportAnchor};return e.requestPreviewNavigation(n)}import{TextSelection as uA}from"prosemirror-state";var mA=1e3;function pA(e){return typeof e!="number"||!Number.isFinite(e)?mA:Math.max(0,Math.trunc(e))}function fA(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&Array.isArray(e.segments)}function wA(e){return e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"&&"id"in e&&typeof e.id=="string"}function gA(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function OS(e){let t=nt(e);return gA(t)?t:null}function SA(e,t){let r=e.documentApi?.trackChanges.get(t)??null;return Us(e.documentApi,OS(e.preview),r)}function hA(e,t){let r=e.documentApi?.comments.target(t)??null;if(!r)return null;let o=_s(e.documentApi,r);if(o)return o;let n=OS(e.preview);if(!n)return null;let i=$e(n,r);if(!i)return null;try{return wc(n,uA.create(n,i.from,i.to))}catch{return null}}function vA(e,t){return fA(t)?t:wA(t)?t.type==="comment"?hA(e,t.id):t.type==="trackedChange"?SA(e,t.id):null:null}function bA(e,t){let r=e.readPendingNavigationRequest();return r?r.requestKey===t?"pending":"failed":"success"}function Bd(e){return e?.shouldContinue?.()??!0}function yA(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(!Bd(o)){d(!1);return}let m=bA(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 DS(e,t){let r=vA(e,t.target);if(!r)return{success:!1};if(!Bd(t.continuation))return{success:!1};let o=e.requestNavigationForTextTarget(r);return o?Bd(t.continuation)?{success:await yA(e,o.requestKey,pA(t.timeoutMs),t.continuation)}:{success:!1}:{success:!1}}function pi(e){return re(e.getViewportState())}function jS(e,t){let r=pi(e);return e.subscribe(()=>{let o=pi(e);et(r,o)||(r=o,t())})}function VS(e,t=null){let r=null;return{getSnapshot(){return pi(e)},subscribe(o){return jS(e,o)},observe(o){return o(pi(e)),jS(e,()=>{o(pi(e))})},observeGeometry(o){return r??=kS(e,t),r.observe(o)},scrollIntoView(o){return DS({documentApi:e.documentApi,preview:t,subscribe(n){return e.subscribe(()=>{n()})},readPendingNavigationRequest(){return e.getState().previewNavigationRequest??null},requestNavigationForTextTarget(n){return yd(e,n,t)}},o)},getHost(){return Pn(e.surface)},getScrollContainer(){return ui(e.surface)},entitiesAtPoint(o){return Sd(e,o)},contextAtPoint(o){return BS(e,o,t)},positionAtPoint(o){return ho(e,o)},requestNavigation(o){return e.requestPreviewNavigation(o)},requestNavigationForTextTarget(o){return yd(e,o,t)},ackNavigationRequest(o){e.ackPreviewNavigationRequest(o)}}}import{createProseMirrorLayoutAdapter as lO}from"@datalking/begonia-editor-adapters";function LS(e){let t=e?.pages;if(!t||t.length===0)return[];let r=new Map;for(let o of t){let n=r.get(o.sectionIndex);n?n.push(o):r.set(o.sectionIndex,[o])}return Array.from(r.entries()).sort(([o],[n])=>o-n).map(([o,n])=>BA(o,n))}function BA(e,t){let r=t[0];return{sectionIndex:e,sectionId:r.sectionId,pageNumberStart:r.sectionPageNumber,pageCount:t.length,pageSize:r.pageSize,margins:r.margins,columnCount:r.columnCount,columnWidths:r.columnWidths}}import{NodeSelection as iO}from"prosemirror-state";function pa(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xA(e){let t=e.selectionAnchor;return pa(t?.resolvedSelectionPos)??pa(t?.hit?.pos)}function CA(e){return pa(e.hit?.pos)??pa(e.resolvedSelectionPos)}function FS(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to),n=xA(t),i=CA(t);return n!=null&&i!=null&&i<n?{anchor:o,head:r}:{anchor:r,head:o}}import{readSyntheticSideStoryDocOriginPath as AA}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as WS,isDocumentNodePathIndex as NA,isIntegerPath as KS}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as OA}from"@datalking/begonia-layout-renderer";import{findProjectionPage as DA,isProjectionDocumentTextRegion as jA,resolveProjectionPageRegionBlocks as _S}from"@datalking/begonia-page-layout";import{findProjectionPage as PA,isProjectionDocumentTextRegion as RA,listProjectionPagePlacements as TA,pointHitsProjectionPlacement as kA}from"@datalking/begonia-page-layout";function HS(e,t,r,o){let n=PA(e,t);return n?TA(n).reduce((i,s)=>RA(s.region)&&kA(s.block,r,o)?s.block:i,null):null}function Se(e){return be(e)}function fa(e){return Math.max(28,e)}function zS(e){let t=Math.max(0,e.margins.top);if(!(t>0))return null;let r=Math.max(0,Math.min(t,e.regions.headerTop??t)),o=Math.max(0,e.regions.headerHeight??0),n=t-r,i=fa(o),s=o>n,a=fa(s?i:n),l=s?r:Math.max(0,t-a);return{kind:"header",top:l,left:e.margins.left,width:e.contentWidth,height:a,contentTop:s?0:r-l,contentHeight:i,marginDistance:r}}function qS(e){let t=e.pageSize.height;if(!(t>0))return null;let r=Math.max(0,e.margins.bottom);if(!(r>0))return{kind:"footer",top:Math.max(0,t-28),left:e.margins.left,width:e.contentWidth,height:28,contentTop:0,contentHeight:28,marginDistance:0};let o=Math.max(0,Math.min(r,e.footerDistance??r)),n=Math.max(0,t-r),i=Math.max(0,t-o),s=i-n,a=Math.max(0,e.regions.footerHeight??0),l=fa(a),c=a>s,d=fa(c?l:s);return{kind:"footer",top:c?Math.max(0,i-d):n,left:e.margins.left,width:e.contentWidth,height:d,contentTop:c?0:Math.max(0,d-a),contentHeight:l,marginDistance:o}}var EA=12;function xd(e,t){return e.pages.find(r=>r.pageNumber===t)??null}function MA(e,t,r){let o=xd(e,t);return o?r<o.regions.bodyTop?"header":r>=o.regions.footerTop?"footer":null:null}function vo(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=MA(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(EA,t.hit.height/2)?o:t.hit.region}function fi(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=xd(e,r);if(!o)return!1;let n=t.y<o.regions.bodyTop,i=t.y>=o.regions.footerTop;return!n&&!i?!1:!IA(n?o.headerBlocks:o.footerBlocks)}function Cd(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=xd(e,r);if(!o)return!1;let n=zS(o);if(n!=null&&t.y<n.top)return!0;let i=qS(o);return i!=null&&t.y>i.top+i.height}function IA(e){return Array.isArray(e)&&e.length>0}function wa(e){return e?.selectionAnchor!=null}function US(e,t,r){let o=bo(t,r);if(!Array.isArray(o?.path)||o.path.length===0)return!1;let n=AA(e);return n?KS(o.path)&&KS(n)&&o.path.length>=n.length&&n.every((s,a)=>o.path?.[a]===s)&&WS(o.path.slice(n.length)):WS(o.path)?vo(t,r)==="body"?!0:fi(t,r):!1}function bo(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=DA(e,r);if(!o)return null;let n=HS(e,r,t.x,t.y);if(!t.hit)return n;if(!jA(t.hit.region))return _S(o,t.hit.region)[t.hit.blockIndex]??n;let i=_S(o,t.hit.region)[t.hit.blockIndex]??null;return n??i}function wi(e){return!!(e&&!e.drawing&&e.type!=="image"&&e.type!=="page_break"&&e.type!=="section_break")}function yo(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function VA(e){let t=OA(e);return t?.nodeType==="ooxml_math"||t?.nodeType==="ooxml_chart"||t?.nodeType==="ooxml_shape"||t?.nodeType==="inline_ooxml_drawing"}function XS(e,t){return t.shiftKey===!0?VA(t.target)||!wi(e):yo(t.clickCount)<=1?!0:!wi(e)}function Wr(e,t){let r=Number(t),o=Number.isNaN(r)?1:Math.round(r);return Math.max(1,Math.min(o,Se(e).view.state.doc.content.size))}function ZS(e,t){let r=e,o=-1;for(let n of t){if(!NA(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 Bo(e,t){let r=Wr(e,t.from),o=Wr(e,t.to);return r<=o?{from:r,to:o}:{from:o,to:r}}function GS(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)}}import{buildTableGridModel as lN,readNodeAtPath as cN,resolveRectAtLogicalPosition as dN}from"@datalking/begonia-document-api/structure";import{isDenseArray as uN}from"@datalking/begonia-document-model/contracts";import{resolveLayoutTableBlockMetrics as Od,resolveTableCellVerticalOffset as mN}from"@datalking/begonia-layout-contracts";import{PREVIEW_TABLE_CELL_HORIZONTAL_PADDING as Pd,PREVIEW_TABLE_CELL_VERTICAL_PADDING as Rd,resolvePreviewTableCellPadding as Td}from"@datalking/begonia-layout-renderer";import{readNodeAtPath as LA}from"@datalking/begonia-document-api/structure";import{resolveNodeAnchorPosition as FA}from"@datalking/begonia-doc-service/v1";function HA(e){return e.isBlock&&e.childCount===0}function zA(e,t,r){let o=Math.max(t+1,t+e.nodeSize-1),n=Qt(e,t,o,r);return n>0?n:HA(e)?1:0}function qA(e,t,r,o=[]){let n=(i,s)=>{if(i.isTextblock||!i.firstChild?.isBlock){let a=zA(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 kd(e,t,r){let o=oe(e),n=LA(e,t),i=FA(e,t);if(!n||i==null)return null;let s=qA(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:ni(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??ni(n,i,c,o)}import{resolveTableFragmentRows as WA}from"@datalking/begonia-layout-contracts";function Ed(e,t,r){return e.originRow===t&&e.originColumn===r}function $S(e,t,r,o){let n=WA(e);if(!(n[t]??null)?.cells.some(l=>Ed(l,r,o)))return null;let s=n.find(l=>l.cells.some(c=>Ed(c,r,o)))??null,a=s?.cells.find(l=>Ed(l,r,o))??null;return!s||!a?null:{cellLayoutChildIndex:a.physicalIndex,cellLayoutIndex:s.fragmentRowIndex,sourceRowIndex:s.sourceRowIndex}}import{segmentTextGraphemes as YS}from"@datalking/begonia-layout-contracts";function Id(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function Tn(e){return{from:e,to:e}}function JS(e,t){return e<=t?{from:e,to:t}:{from:t,to:e}}function gi(e,t){return Math.max(0,Math.min(Math.round(Number(t)||0),e.content.size))}function Si(e,t,r,o,n){return Hc(e,t,Math.max(0,r),n)??o}function KA(e,t,r){return gi(e,r+Math.max(1,t.nodeSize-1))}function _A(e,t,r){return Math.max(0,Math.min(r,Math.round(Number(e)||0)-t))}function UA(e,t,r,o,n){let i=KA(e,t,r);return ni(t,r,o,n)??i}function QS(e){return/\s/u.test(e)}function XA(e){return/^[\p{L}\p{N}\p{M}\u200c\u200d'\u2018\u2019_~-]+$/u.test(e)}function ZA(e){return/\p{Extended_Pictographic}/u.test(e)}function GA(e){return/^[\p{P}]+$/u.test(e)}function $A(e){return/^[\p{S}]+$/u.test(e)}function Md(e){return QS(e)?"whitespace":XA(e)?"word":ZA(e)?"emoji":GA(e)?"punctuation":$A(e)?"symbol":"other"}function YA(e,t){let r=YS(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),!QS(r[a]?.text??"")))return a}return null}function JA(e,t){let r=YS(e),o=YA(e,t);if(o==null)return null;let n=r[o];if(!n)return null;let i=Md(n.text);if(i==="whitespace")return null;let s=o;for(;s>0&&Md(r[s-1]?.text??"")===i;)s-=1;let a=o+1;for(;a<r.length&&Md(r[a]?.text??"")===i;)a+=1;return{start:r[s]?.fromOffset??n.fromOffset,end:r[a-1]?.toOffset??n.toOffset}}function QA(e,t,r,o){let n=Ar(e,o).length;return n<=0?Tn(r):JS(Si(e,t,0,r,o),Si(e,t,n,r,o))}function eN(e,t,r,o,n){let i=Ar(e,n),s=JA(i,r);return s?JS(Si(e,t,s.start,o,n),Si(e,t,s.end,o,n)):Tn(o)}function tN(e,t){let r=gi(e,t),o=e.resolve(r);for(let n=o.depth;n>0;n-=1){let i=o.node(n);if(i.type.name==="table_cell"||i.type.name==="table_header"){let s=rN(o,n,i);if(s)return s;let a=o.before(n);return{cellFrom:a,cellTo:a+i.nodeSize-1}}}return null}function rN(e,t,r){if(r.childCount===0)return null;let o=e.start(t),n=e.end(t),i=r.firstChild,s=r.lastChild;if(!i||!s||n<=o)return null;let a=i.isTextblock?o+1:o,l=s.isTextblock?n-1:n;return l<a?null:{cellFrom:a,cellTo:l}}function oN(e,t){let r=gi(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 eh(e,t,r,o,n,i){return n>=3?QA(e,t,o,i):n===2?eN(e,t,r,o,i):Tn(o)}function ga(e){let{doc:t,rawPos:r}=e,o=oe(t);if(Id(e.clickCount)>=3){let l=tN(t,r);if(l)return{from:l.cellFrom,to:l.cellTo}}let n=oN(t,r);if(!n)return Tn(gi(t,r));let i=gi(t,r),s=Math.max(0,Qt(n.blockNode,n.blockPos,i,o)),a=Si(n.blockNode,n.blockPos,s,i,o);return eh(n.blockNode,n.blockPos,s,a,Id(e.clickCount),o)}function th(e){let{doc:t,block:r,rawPos:o}=e,n=oe(t);if(!Array.isArray(r.path)||r.path.length===0)return Tn(o);let i=Le(t,r.path);if(!i?.node.isTextblock)return Tn(o);let s=i.node,a=i.position,l=Ar(s,n).length,c=_A(o,r.from,l),d=UA(t,s,a,c,n);return eh(s,a,c,d,Id(e.clickCount),n)}import{readNodeAtPath as rh,resolvePathToPosition as oh}from"@datalking/begonia-document-api/structure";import{isDenseArray as xr}from"@datalking/begonia-document-model/contracts";import{resolveLayoutTableBlockMetrics as Sa}from"@datalking/begonia-layout-contracts";import{resolveMeasuredTextOffsetAtPoint as nN,resolveProjectionTextOffsetAtPoint as iN}from"@datalking/begonia-page-layout";function he(e){try{let t=Number(e);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function sN(e){try{let t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:null}catch{return null}}function xo(e){if(!xr(e))return 0;let t=0;for(let r of e)t+=he(r);return t}function Ad(e,t){if(!xr(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+=he(e[n]);return o}function ha(e,t){let r=Sa(e)?.rowSourceIndexes,o=Array.isArray(r)&&xr(r)?r:null;return Array.from({length:t},(n,i)=>sN(o?.[i])??i)}function aN(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(he(i.attrs.colSpan)||1)),a=he(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 nh(e,t,r){let o=Sa(t)?.columnWidths,n=Array.isArray(o)&&xr(o)?o.map(a=>he(a)):Array.isArray(e.attrs.columnWidths)&&xr(e.attrs.columnWidths)?e.attrs.columnWidths.map(a=>he(a)):[],i=aN(e,r),s=Math.max(24,(he(Sa(t)?.width)||he(t.width)||xo(n)||xo(i)||r*96)/Math.max(1,r));return Array.from({length:r},(a,l)=>{let c=n[l]??0,d=i[l]??0;return Math.max(24,c||d||s)})}function va(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,he(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function ih(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,he(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function ba(e){let t=Sa(e)?.rowHeights;return xr(t)?t.map(r=>Math.max(1,he(r)||1)):[]}function sh(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=sh(o,n);if(i)return i}return null}function ah(e,t){let r=rh(e,t);if(!r)return null;let o=sh(r,t);if(o){let i=oh(e,o);return i==null?null:rh(e,o)?.content.size===0?i:i+1}let n=oh(e,t);return n==null?null:n+1}function lh(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=uh(dh(r),s.fromOffset),w={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?nN(w,p,c,d):iN(w,p);return Math.max(s.fromOffset,Math.min(s.toOffset,v))}function ch(e,t,r){let o=e.lineHeights,n=dh(e);return t.map((i,s)=>{let a=he(i.lineHeight);if(a>0)return a;let l=xr(o)?he(o[s]):0;if(l>0)return l;let c=uh(n,i.fromOffset),d=he(c?.lineHeight);return d>0?d:r})}function dh(e){let t=xr(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 uh(e,t){return e.find(r=>t<r.toOffset||r.segment.text.length===0&&t===r.fromOffset)?.segment??null}function mh(e,t){if(!xr(e)||e.length===0)return{lineIndex:0,lineTop:0};let r=he(t),o=0;for(let n=0;n<e.length;n+=1){let i=Math.max(1,he(e[n])||1);if(r<o+i||n===e.length-1)return{lineIndex:n,lineTop:o};o+=i}return{lineIndex:0,lineTop:0}}function ph(e){return Nd(e)?.resolvedPos??null}function Nd(e){let{doc:t,block:r,x:o,y:n}=e;if(r.type!=="table"||!r.path?.length)return null;let i=cN(t,r.path);if(!i||i.type.name!=="table")return null;let s=lN(i);if(s.invalidReason||s.rows.length===0||s.width<=0)return null;let a=ba(r),l=ha(r,a.length);if(l.length===0)return null;let c=nh(i,r,s.width),d=Math.max(0,o-r.left),u=Math.max(0,n-r.top),m=va(u,a),p=l[m]??m,f=ih(d,c),w=dN(s,p,f);if(!w)return null;let v=pN({doc:t,block:r,fragmentRowIndex:m,rowHeights:a,model:s,rect:w});if(!v)return null;let{cellLayoutChildIndex:C,cellLayoutIndex:R,cellPath:S,cellStartPos:B,rowTop:h}=v,y=Ad(c,w.originColumn),T=xo(c.slice(w.originColumn,w.originColumn+w.colSpan)),A=Od(r)?.cells?.[R]?.[C]??null,D=uN(A?.lineSlices)?A.lineSlices:null;if(!D||D.length===0)return{cellPath:S,cellStartPos:B,cellLeft:y,cellWidth:T,rowTop:h,lineIndex:0,lineCount:1,line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:B,lineTop:0,lineHeight:Math.max(1,he(r.lineHeight)),cellContentTop:0};let O=Td(Od(r)?.cellMargins,{vertical:Rd,horizontal:Pd}),U=Math.max(1,he(r.lineHeight)),H=ch(A,D,U),le=Math.max(0,he(a[R])),ne=mN(A?.verticalAlign,le,xo(H)+O.top+O.bottom),M=O.top+ne,N=Math.max(0,u-h-M),{lineIndex:V,lineTop:b}=mh(H,N),x=D[V]??null,I=Math.max(1,H[V]??U);if(!x)return{cellPath:S,cellStartPos:B,cellLeft:y,cellWidth:T,rowTop:h,lineIndex:V,lineCount:Math.max(1,D.length),line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:B,lineTop:b,lineHeight:I,cellContentTop:M};let E=lh({block:r,cellLayout:A,height:I,line:x,lineCount:Math.max(1,D.length),lineIndex:V,left:r.left+y+O.left,top:r.top+h+M+b,width:Math.max(0,T-O.left-O.right),x:o,measureText:e.measureText,measurementEpoch:e.measurementEpoch});return{cellPath:S,cellStartPos:B,cellLeft:y,cellWidth:T,rowTop:h,lineIndex:V,lineCount:Math.max(1,D.length),line:x,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:kd(t,S,E)??B,lineTop:b,lineHeight:I,cellContentTop:M}}function pN(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=$S(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=ah(t,c);return d==null?null:{cellLayoutChildIndex:a.cellLayoutChildIndex,cellLayoutIndex:a.cellLayoutIndex,cellPath:c,cellStartPos:d,rowTop:Ad(n,a.cellLayoutIndex)}}function fh(e,t,r,o){return kd(e,t,r)??o}function Dd(e){let t=ph(e);return t==null?null:ga({doc:e.doc,rawPos:t,clickCount:e.clickCount})}function jd(e){let t=Nd(e);if(!t)return null;let r=Td(Od(e.block)?.cellMargins,{vertical:Rd,horizontal:Pd}),{cellPath:o,cellLeft:n,cellStartPos:i,cellText:s,cellWidth:a,line:l,lineCount:c,lineIndex:d,resolvedPos:u,rowTop:m,lineTop:p,lineHeight:f,cellContentTop:w}=t,v=l?fh(e.doc,o,l.fromOffset,i):u,C=l?fh(e.doc,o,l.toOffset,u):u,R=Math.max(0,w-r.top),S=l?.text??s,B=Math.max(1,f||he(e.block.lineHeight)||he(e.hit.height)||1);return{...e.hit,lineIndex:d,lineCount:c,from:Math.min(v,C),to:Math.max(v,C),left:e.block.left+n+r.left,top:e.block.top+m+r.top+R+p,width:Math.max(0,a-r.left-r.right),height:B,text:S,label:S.trim()||e.hit.label,pos:u}}import{readNodeAtPath as fN,resolvePathToPosition as wN}from"@datalking/begonia-document-api/structure";import{resolveLayoutTableBlockMetrics as wh}from"@datalking/begonia-layout-contracts";function Vd(e){let{block:t,doc:r,x:o,y:n}=e;if(t.type!=="table"||!Array.isArray(t.path)||t.path.length!==1)return null;let i=fN(r,t.path);if(!i||i.type.name!=="table"||i.childCount===0)return null;let s=ba(t);if(s.length===0)return null;let a=ha(t,s.length);if(a.length===0||n<t.top)return null;let l=Math.max(0,n-t.top),c=va(l,s);if((a[c]??c)!==i.childCount-1)return null;let u=he(wh(t)?.width)||xo(wh(t)?.columnWidths??[])||he(t.width);if(u<=0||o<=t.left+u)return null;let m=wN(r,t.path);return m==null?null:gh(r,m-1)}function gh(e,t){let r=e.nodeAt(t);if(!r||r.type.name!=="table")return null;let o=t+r.nodeSize;return e.resolve(o).nodeAfter?.isTextblock?{caretPos:o+1,insertAt:null}:{caretPos:o+1,insertAt:o}}function gN(e){if(e.resolvedSelectionPos==null&&e.resolvedSelectionRange==null)return!1;let t=yo(e.clickCount);return e.resolvedSelectionClickCount==null?t<=1:yo(e.resolvedSelectionClickCount)===t}function Ld(e){let t=e.hit;if(!t||!gN(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 tO}from"@datalking/begonia-document-api/structure";import{NodeSelection as Jh}from"prosemirror-state";import{BEGONIA_BLOCK_POS_ATTRIBUTE as VZ,BEGONIA_CELL_LINE_OFFSET_ATTRIBUTE as LZ,BEGONIA_CELL_TEXT_START_ATTRIBUTE as FZ,BEGONIA_PIECE_OFFSET_ATTRIBUTE as HZ,BEGONIA_PROJECTION_OFFSET_ATTRIBUTE as zZ}from"@datalking/begonia-layout-renderer";import{BEGONIA_CELL_LINE_OFFSET_ATTRIBUTE as BN,BEGONIA_CELL_TEXT_START_ATTRIBUTE as xN,BEGONIA_PIECE_OFFSET_ATTRIBUTE as CN,BEGONIA_PROJECTION_OFFSET_ATTRIBUTE as hh}from"@datalking/begonia-layout-renderer";function SN(){let e=typeof document>"u"?null:document;return e&&(typeof e.caretPositionFromPoint=="function"||typeof e.caretRangeFromPoint=="function")?e:globalThis}function hN(e){return typeof e.caretPositionFromPoint=="function"?{kind:"position",read:(t,r)=>{let o=e.caretPositionFromPoint?.(t,r);return o?{offsetNode:o.offsetNode,offset:o.offset}:null}}:typeof e.caretRangeFromPoint=="function"?{kind:"range",read:(t,r)=>{let o=e.caretRangeFromPoint?.(t,r);return o?{offsetNode:o.startContainer,offset:o.startOffset}:null}}:null}function vN(e){if(!e)return!1;let{offsetNode:t,offset:r}=e;return t.nodeType===3&&Number.isFinite(r)&&r>=0&&r<=(t.textContent?.length??0)}function bN(e){let t=e?.ownerDocument;if(t&&typeof t.createRange=="function")return t;let r=typeof document>"u"?null:document;return r&&typeof r.createRange=="function"?r:null}function yN(e,t){let r=bN(e);if(!r)return null;let o=e.textContent?.length??0,n=Math.max(0,Math.min(t,o)),i;try{i=r.createRange(),i.setStart(e,n),i.setEnd(e,n)}catch{return null}let s=i.getBoundingClientRect();return i.detach?.(),!Number.isFinite(s?.left)||!Number.isFinite(s?.top)?null:{left:s.left,top:s.top,height:s.height}}function Sh(e,t,r=SN()){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let o=hN(r);if(!o)return null;let n=o.read(e,t);return vN(n)?{node:n.offsetNode,offset:n.offset,rect:yN(n.offsetNode,n.offset)}:null}function hi(e,t){if(!e)return null;let r=e.getAttribute(t);if(r==null||r==="")return null;let o=Number(r);return Number.isFinite(o)?o:null}function vh(e,t){if(!Number.isFinite(t)||t<0)return null;let r=e.parentElement;if(!r)return null;let o=null,n=null,i=null,s=r,a=0;for(;s&&a<32&&(o==null&&(o=hi(s,xN)),i==null&&(i=hi(s,BN)),n==null&&(n=hi(s,hh)),!(o!=null&&n!=null&&i!=null));)s=s.parentElement,a+=1;if(n==null)return null;let l=hi(r,CN);if(l!=null)return(o??0)+n+l+t;let c=PN(r,n);return(o??0)+n+(i??0)+c+t}function PN(e,t){let r=0,o=e,n=0;for(;o&&n<64;){let i=hi(o,hh);if(i!=null&&i===t)break;let s=o.previousSibling;for(;s;){let a=s.textContent;typeof a=="string"&&(r+=a.length),s=s.previousSibling}o=o.parentElement,n+=1}return r}import{readNodeAtPath as RN}from"@datalking/begonia-document-api/structure";function bh(e,t,r){if(!Number.isFinite(r))return null;let o=qc(e);if(!o||o.length===0)return null;let n=Math.round(r)-t;for(let i of o){let s=n-i.flattenedStart;if(!(s<0||s>i.textLength))return t+i.contentStart+s}return null}function yh(e,t,r){if(!Number.isFinite(r))return null;if(t.type==="table"&&t.path?.length){let a=RN(e,t.path);return a&&a.type.name==="table"?bh(a,t.from,r):null}let o=dg(e,t);if(!o)return null;let n=o.node,i=Math.max(0,Math.round(r)-o.blockPos);if(i>n.content.size)return null;let s=Nr(n,o.blockPos,i,oe(o.doc));return Number.isFinite(s)?s:null}function Bh(e){let{clientX:t,clientY:r,block:o,doc:n}=e;if(typeof t!="number"||typeof r!="number")return null;let i=Sh(t,r);if(!i)return null;let s=vh(i.node,i.offset);if(s==null)return null;let a=yh(n,o,s);return a==null?null:{projectionOffset:s,documentPosition:a}}function xh(e){return Bh(e)?.documentPosition??null}function Ch(e){return Bh(e)?.projectionOffset??null}function Co(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function Ph(e){return Object.hasOwn(e,"anchorPageNumber")}function Rh(e){return Ph(e)&&e.anchorPageNumber!=null&&Co(e.anchorPageNumber)==null}function TN(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 kN(e){return`preview-navigation:${Math.max(1,Math.trunc(e))}`}function EN(e,t){return De(e)??kN(t)}function MN(e){return Kt(e?.anchorPageIndex??e?.currentPageIndex??null,e?.anchorPageNumber??e?.currentPageNumber??null)}function IN(e,t){return e!=null?{pageNumber:e}:t}function AN(e,t){let r=Co(e.anchorPageNumber),o=MN(t);return Object.hasOwn(e,"viewportAnchor")?Go(e.viewportAnchor??null,{...IN(r,o)}):Object.hasOwn(e,"anchorPageNumber")?null:$o(t)}function Th(e,t){return e==null||t==null||t.pageNumber===e}function NN(e,t,r){return Ph(e)?Co(e.anchorPageNumber):Co(t?.pageNumber??r?.anchorPageNumber??r?.currentPageNumber??null)}function ya(e,t){if(!e||typeof e!="object"||Rh(e))return null;let r=Co(e.anchorPageNumber),o=AN(e,t.fallbackViewport);if(Object.hasOwn(e,"viewportAnchor")&&e.viewportAnchor!=null&&!o||!Th(r,o))return null;let n=NN(e,o,t.fallbackViewport);return n==null&&!o?null:{requestKey:EN(e.requestKey,t.nextToken),flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:n,viewportAnchor:o}}function Pe(e){if(!e||typeof e!="object"||Rh(e))return null;let t=TN(e.flowMode,e.layoutMode);if(!t)return null;let r=Co(e.anchorPageNumber),o=Go(e.viewportAnchor,{pageNumber:r}),n=De(e.requestKey);return n==null||r==null&&!o||e.viewportAnchor!=null&&!o||!Th(r,o)?null:{requestKey:n,flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:r??Co(o?.pageNumber),viewportAnchor:o}}function Kr(e,t){let r=Pe(e),o=Pe(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 kh(e,t,r){let o=Pe(e);return o!=null&&o.flowMode===t&&o.layoutMode===r}function Eh(e,t){let r=Pe(e),o=De(t);return r!=null&&o!=null&&r.requestKey===o}function Fd(e,t){return Kt(t,e).pageNumber}function ON(e,t){return xa(e)!=null||Ah(t)!=null}function Mh(e,t){if(!ON(e,t))return!1;let r=Kt(t,e);return r.pageNumber==null&&r.pageIndex==null}function Ba(e,t){let r=Fd(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 xa(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function Ah(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function DN(e,t){let r=Array.isArray(e)?[...new Set(e.map(n=>xa(n)).filter(n=>n!=null))].sort((n,i)=>n-i):[],o=Array.isArray(t)?[...new Set(t.map(n=>Ah(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 Ih(e,t){let r=DN(e,t);return r.length===1?r[0]??null:null}function jN(e,t){let r=xa(e),o=xa(t);return r!=null&&o!=null&&r===o?r:null}function Nh(e){return Ih(e?.visiblePageNumbers,e?.visiblePageIndexes)??jN(e?.firstVisiblePageNumber,e?.lastVisiblePageNumber)??Ih(e?.mountedPageNumbers,e?.mountedPageIndexes)??null}function Hd(e){return Mh(e?.anchorPageNumber,e?.anchorPageIndex)&&Mh(e?.currentPageNumber,e?.currentPageIndex)}function kn(e){return Fd(e?.anchorPageNumber,e?.anchorPageIndex)??Fd(e?.currentPageNumber,e?.currentPageIndex)??(Hd(e)?null:Nh(e))??null}function Po(e){let t=Nh(e);return{anchorPageNumber:Ba(e?.anchorPageNumber,e?.anchorPageIndex)??Ba(e?.currentPageNumber,e?.currentPageIndex)??t??null,currentPageNumber:Ba(e?.currentPageNumber,e?.currentPageIndex)??Ba(e?.anchorPageNumber,e?.anchorPageIndex)??t??null}}function zd(e){let t=kn(e);if(t!=null)return t;let r=Po(e);return r.anchorPageNumber!=null&&r.currentPageNumber!=null&&r.anchorPageNumber!==r.currentPageNumber?null:r.currentPageNumber??r.anchorPageNumber??null}function vi(e,t){return e.anchorPageNumber===t.anchorPageNumber&&e.currentPageNumber===t.currentPageNumber}function Oh(e,t){if(e.flowMode!==t.flowMode||e.layoutMode!==t.layoutMode)return!1;let r=e.viewportAnchor??null,o=t.viewportAnchor??null,n=vi(Po(e),Po(t));return!r||!o?n&&r===o:n&&Zo(r,o)}function VN(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:_t({...e,layoutMode:"vertical"},t)}function LN(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:Pe({...e,layoutMode:"vertical"})}function FN(e){let t=$o(e),r=t===e.viewportAnchor?e:{...e,viewportAnchor:t};return t!=null||kn(r)!=null?r:null}function Rt(e,t={}){let r=e?.viewport??null;if(!r)return null;let{flowMode:o,layoutMode:n}=t;if($o(r)==null&&Hd(r))return null;let i=_t(r,{flowMode:o,layoutMode:n})??VN(r,t);if(!i)return null;let s=FN(i);return s?o&&n?to(s,o,n)?s:null:o?Uo(s,o)?s:null:n?Xo(s,n)?s:null:s:null}function Tt(e,t={}){let r=Pe(e?.previewNavigationRequest??null)??(e?.previewNavigationRequest!=null?LN(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 Ca(e,t){if(!e)return null;let r=Rt({viewport:e},t);return r?{kind:"full",viewport:r}:{kind:"page",state:Po(e)}}function Pa(e){return e.kind==="full"?Po(e.viewport):e.state}function Dh(e,t,r={}){let o=Ca(e,r),n=Ca(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?Oh(o.viewport,n.viewport):vi(Pa(o),Pa(n))}function uG(e,t,r={}){let o=Ca(e,r),n=Ca(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?et(o.viewport,n.viewport):vi(Pa(o),Pa(n))}function jh(e){let t=nt(e.editor),r=e.source==null?null:e.source,o=e.explicitProjection??null,n=e.boundToEditorDocument===!0||!!(t&&(_w(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 qd(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function bG(e){let t=qd(e.controllerNavigationMode);return e.sourceMatchesEditorDocument?{controllerNavigationMode:t,syncViewportToEditor:e.syncViewportToEditor}:{controllerNavigationMode:"ignore",syncViewportToEditor:!1}}function Vh(e){return qd(e)!=="ignore"}function En(e){return qd(e)==="consume"}function Mn(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function HN(e,t,r){if(!t||t.viewportAnchor!=null||Rt({viewport:t},r))return!1;let o=zd(e),n=zd(t);return o!=null&&o===n}function Lh(e,t,r,o,n=null,i={}){if(Mn(t)!=null||!r||!En(o))return null;let a=Tt(e,i);return!a||a.requestKey===n?null:Pe(a)}function Fh(e,t,r,o,n={}){return Mn(t)!=null||r||!En(o)?null:Tt(e,n)?.requestKey??null}function Hh(e,t,r,o,n,i=null,s={}){if(Mn(t)!=null||!r||!En(o))return null;let l=Rt(e,s);if(!l)return null;if(tc(e?.viewportRequestKey,i))return l;let c=Rt({viewport:n??null},s);return c?Dh(l,c,s)?null:l:HN(l,n??null,s)?null:l}function zh(e,t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let r=vt(e?.zoomPercent)??100;return Math.max(.01,r/100)}function qh(e,t,r,o,n={}){let i=Mn(t);if(i!=null)return i;if(r)return null;if(En(o)){let a=Tt(e,n);if(a?.viewportAnchor)return null;if(a?.anchorPageNumber!=null)return a.anchorPageNumber}if(!Vh(o))return null;let s=Rt(e,n);return s?.viewportAnchor?null:kn(s)??kn(e?.viewport??null)}function Wh(e,t,r,o,n={}){if(Mn(t)!=null||r)return null;if(En(o)){let s=Tt(e,n);if(s)return s.viewportAnchor??null}return Vh(o)?Rt(e,n)?.viewportAnchor??null:null}function Kh(e,t,r,o,n={}){if(Mn(t)!=null||!En(o))return null;let s=Tt(e,n);return s?s.requestKey:Rt(e,n)?De(e?.viewportRequestKey):null}function Wd(e,t){return oi(t)??fo(e?.flowMode)}function _h(e,t,r){let o=Wd(e,r),n=pt(e?.preferredPaginatedLayoutMode),i=e?.flowMode==="paginated"?pt(e?.layoutMode):null;return vr(pt(t)??(o==="paginated"?i??n??e?.layoutMode:e?.layoutMode),o)}import{buildTableGridModel as zN,readNodeAtPath as Kd,resolveRectAtLogicalPosition as qN}from"@datalking/begonia-document-api/structure";import{isDocumentNodePathIndex as WN}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as KN}from"@datalking/begonia-layout-renderer";import{NodeSelection as _N}from"prosemirror-state";function Uh(e,t){let r=e,o=-1;for(let n of t){if(!WN(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 UN(e){return KN(e)}function XN(e,t,r,o,n={}){return!e.isInline||e.childCount!==0||!_N.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 _d(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 XN(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=_d(d,t+l+1,r,o,n,a,s).nextOffset,l+=d.nodeSize}return{positions:s,nextOffset:a}}function ZN(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=Se(e).view.state.doc,n=Kd(o,t.path);if(!n||n.type.name!=="table")return null;let i=zN(n);if(i.invalidReason)return null;let s=qN(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=Kd(o,l),d=Uh(o,l);return!c||d==null?null:{node:c,nodePos:d}}function GN(e,t){if(!Array.isArray(t.path)||t.path.length===0)return null;let r=Se(e).view.state.doc,o=Kd(r,t.path),n=Uh(r,t.path);return!o?.isTextblock||n==null?null:{node:o,nodePos:n}}function Ud(e,t,r){if(!t||!Array.isArray(t.path)||t.path.length===0)return null;let o=UN(r.target);if(!o)return null;let n=Se(e).view.state.doc,i=oe(n),s=d=>Ar(d,i),a=ZN(e,t,o)??GN(e,t);if(!a)return null;let l=_d(a.node,a.nodePos,o,s).positions;if(l.length===1)return l[0];if(l.length>1||!o.objectId)return null;let c=_d(a.node,a.nodePos,o,s,{ignoreObjectId:!0}).positions;return c.length===1?c[0]:null}import{captureProjectionViewportLogicalAnchor as $N}from"@datalking/begonia-page-layout";function Xh(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Xd(e,t){return t>0?e/t:0}function Zd(e){return e==="header"||e==="body"||e==="footer"}function YN(e,t,r){return Zd(e)&&(r.hit==null||r.hit.region!==e)&&(t==null||t.region!==e)}function JN(e,t,r){return r&&(t==null||r.region===t||!Zd(t))||!Zd(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 QN(e,t){let r=e.pages.findIndex(o=>o.pageNumber===t);return r<0?null:{pageIndex:r,page:e.pages[r]??null}}function Zh(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=QN(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=Xh(t.y-s,i),l=$N(o.page,t.x,t.y),c=vo(e,t),d=YN(c,l,t)?t.x:t.pageX,u=Xh(d,n),m=JN(o.page,c,l);return{pageIndex:o.pageIndex,pageNumber:o.page.pageNumber,offsetTopPx:a,offsetTopRatio:Xd(a,i),offsetLeftPx:u,offsetLeftRatio:Xd(u,n),offsetPx:a,offsetRatio:Xd(a,i),...m}}function Gd(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,...eO(e.selectionAnchor,e)}:null}function eO(e,t){return e.hit?{clientX:null,clientY:null}:{clientX:e.clientX??t.clientX??null,clientY:e.clientY??t.clientY??null}}function Gh(e){return{...e,clickCount:e.clickCount??e.selectionAnchor?.clickCount??1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}function $h(e){return{...e,clickCount:1,shiftKey:!1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}function rO(e,t,r,o){return th({doc:Se(e).view.state.doc,block:t,rawPos:r,clickCount:o})}function oO(e,t){if(t.type==="table"||wi(t)||!Array.isArray(t.path)||t.path.length===0)return null;let r=Se(e).view.state.doc,o=tO(r,t.path);return!o||!Jh.isSelectable(o)?null:ZS(r,t.path)}function bi(e){return jh({editor:e.editor,source:e.previewSource,explicitProjection:e.explicitProjection,boundToEditorDocument:e.boundToEditorDocument}).sourceMatchesEditorDocument}function yi(e,t){return US(Se(e).view.state.doc,t.projection,t)}function Yd(e,t){let r=Zh(t.projection,t);return r?e.requestPreviewNavigation({anchorPageNumber:r.pageNumber,viewportAnchor:r})!=null:!1}function $d(e,t){if(t==null)return null;try{let r=Jh.create(Se(e).view.state.doc,t);return{from:r.from,to:r.to}}catch{return null}}function Bi(e){let{editor:t,event:r}=e;if(!t||!r.hit||!bi(e)||!yi(t,r))return{block:null,nodeSelectionPos:null,nodeSelectionRange:null};let o=bo(r.projection,r);if(!XS(o,r))return{block:o,nodeSelectionPos:null,nodeSelectionRange:null};let n=Ud(t,o,r);if(n!=null)return{block:o,nodeSelectionPos:n,nodeSelectionRange:$d(t,n)};let i=o?oO(t,o):null;return{block:o,nodeSelectionPos:i,nodeSelectionRange:$d(t,i)}}function nO(e,t){let r=Bo(e,t),o=Wr(e,Se(e).view.state.selection.anchor);return{from:Math.min(o,r.from),to:Math.max(o,r.to)}}function Jd(e,t){let{editor:r}=e;if(!r||!t.hit||!bi(e)||!yi(r,t))return null;let o=bo(t.projection,t);if(!o)return null;if(o.type==="table"){let i=xh({clientX:t.clientX,clientY:t.clientY,block:o,doc:Se(r).view.state.doc});if(i!=null)return ga({doc:Se(r).view.state.doc,rawPos:i,clickCount:t.clickCount});let s=Bt(r)??{};return Dd({doc:Se(r).view.state.doc,block:o,x:t.x,y:t.y,clickCount:t.clickCount,measureText:s.measureText,measurementEpoch:s.measurementEpoch})}if(t.shiftKey){let i=$d(r,Ud(r,o,t));if(i)return i}if(!wi(o)||!t.hit)return null;let n=Ch({clientX:t.clientX,clientY:t.clientY,block:o,doc:Se(r).view.state.doc});return rO(r,o,n??t.hit.pos,t.clickCount)}function Yh(e,t){if(t.resolvedSelectionRange)return t.resolvedSelectionRange;let r=Bi({...e,event:t});return r.nodeSelectionRange?r.nodeSelectionRange:Jd(e,t)}function Qh(e,t){if(!t.selectionAnchor)return t.selectionAnchor??null;let r=Gd(t);if(!r)return t.selectionAnchor;let o=xi({...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 ev(e){let{editor:t,event:r}=e;if(!t||!r.hit||!bi(e)||!yi(t,r))return r.hit??null;let o=bo(r.projection,r);if(!o||o.type!=="table")return r.hit;let n=Bt(t)??{};return jd({doc:Se(t).view.state.doc,block:o,x:r.x,y:r.y,hit:r.hit,measureText:n.measureText,measurementEpoch:n.measurementEpoch})??r.hit}function tv(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r.hit?.pos??null;let o=Jd(e,$h(r));return o?Bo(t,o).from:r.hit.pos}function Ra(e){let{editor:t,event:r}=e;if(!t)return null;let o=Gd(r),n=o?(()=>{let i=Yh(e,o),s=Yh(e,Gh(r));return!i||!s?null:GS(i,s)})():Jd(e,r);return n?r.shiftKey?nO(t,n):n:null}function rv(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 ov(e){let{editor:t}=e;if(!t)return null;let r=Bi(e);if(r.nodeSelectionPos!=null)return r.nodeSelectionPos;let o=Ra(e);return o?Bo(t,o).from:null}function xi(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r;let o=vo(r.projection,r);if((o==="header"||o==="footer")&&r.hit.region==="body"&&!fi(r.projection,r))return{...r,resolvedSelectionPos:null,resolvedSelectionRange:null};let n=ev(e),i=n===r.hit?r:{...r,hit:n},s=Qh(e,i),a=s===i.selectionAnchor?i:{...i,selectionAnchor:s},l=a.hit;if(!l||Ld(a))return a;let c=bo(a.projection,a),d=yo(a.clickCount)<=1&&!a.shiftKey&&a.selectionAnchor==null;if(c&&d){let R=Vd({doc:Se(t).view.state.doc,block:c,x:a.x,y:a.y});if(R)return{...a,resolvedSelectionPos:R.caretPos,resolvedSelectionRange:null,resolvedSelectionClickCount:1,resolvedTableExitInsertAt:R.insertAt,hit:{...l,pos:R.caretPos}}}let u={...e,event:a},m=yo(a.clickCount),p=Bi(u);if(p.nodeSelectionPos!=null)return{...a,resolvedSelectionPos:p.nodeSelectionPos,resolvedSelectionRange:null,resolvedSelectionClickCount:m,hit:{...l,pos:p.nodeSelectionPos}};let f=Ra(u);if(!f)return a;let w=Bo(t,f),v=tv(u)??w.from,C=w.from===w.to;return{...a,resolvedSelectionPos:w.from,resolvedSelectionRange:w,resolvedSelectionClickCount:m,hit:{...l,pos:C?w.from:v}}}function sO(e){return e==="header"||e==="footer"}function nv(e){let{editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n,event:i}=e;if(!t||!bi(e))return!1;let s={editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n},a=Ld(i)?i:xi(e);if(Cd(a.projection,a))return t.setPointerCaretOrigin?.(null),!0;let l=a.selectionAnchor;if(l!=null&&Cd(a.projection,l))return!1;let c=a.resolvedTableExitInsertAt;if(c!=null&&!a.shiftKey&&!wa(a)){let w=Se(t),v=w.view.state;if(c<0||c>v.doc.content.size)return!1;let C=v.schema.nodes.paragraph;if(!C)return!1;let R=v.tr.insert(c,C.create()),S=v.apply(R),B=K(S,c+1);return B?(t.setPointerCaretOrigin?.({pageNumber:a.pageNumber,x:a.x,y:a.y,selectionOffset:c+1}),R.setSelection(B),w.view.dispatch(R),w.focus(),!0):!1}if(a.resolvedTableExitInsertAt===null&&a.resolvedSelectionPos!=null&&!a.shiftKey&&!wa(a)){let w=Se(t),v=Wr(t,a.resolvedSelectionPos),C=K(w.view.state,v);return C?(t.setPointerCaretOrigin?.({pageNumber:a.pageNumber,x:a.x,y:a.y,selectionOffset:v}),w.view.dispatch(w.view.state.tr.setSelection(C)),w.focus(),!0):!1}let d=vo(a.projection,a),u=wa(a);if(!a.hit||sO(d)&&a.hit.region==="body"&&!fi(a.projection,a))return d&&!u?Yd(t,a):!1;if(!yi(t,a))return u?!1:Yd(t,a);let m=Bi({...s,event:a});if(m.nodeSelectionPos!=null){let w=Se(t);return t.setPointerCaretOrigin?.(null),w.view.dispatch(w.view.state.tr.setSelection(iO.create(w.view.state.doc,m.nodeSelectionPos))),w.focus(),!0}let p=a.resolvedSelectionRange?Bo(t,a.resolvedSelectionRange):Ra({...s,event:a});if(a.shiftKey&&p){t.setPointerCaretOrigin?.(null);let w=Se(t),v=Wr(t,w.view.state.selection.anchor),C=rv(v,p),R=K(w.view.state,v,C);return R?(w.view.dispatch(w.view.state.tr.setSelection(R)),w.focus(),!0):!1}if(p){let w=Se(t),v=FS(p,a),C=K(w.view.state,v.anchor,v.head);return C?(t.setPointerCaretOrigin?.(p.from===p.to?{pageNumber:a.pageNumber,x:a.x,y:a.y,selectionOffset:p.from}:null),w.view.dispatch(w.view.state.tr.setSelection(C)),w.focus(),!0):!1}let f=a.resolvedSelectionPos??ov({...s,event:a});if(f!=null){let w=Se(t),v=Wr(t,f),C=K(w.view.state,v);return C?(t.setPointerCaretOrigin?.({pageNumber:a.pageNumber,x:a.x,y:a.y,selectionOffset:v}),w.view.dispatch(w.view.state.tr.setSelection(C)),w.focus(),!0):!1}return!1}var aO={resolvePositionHitEvent(e){return xi(e)},handlePositionHit(e){return nv(e)}};function Ta(){return aO}var cO=lO();function ka(e){let t=null,r=null,o=null,n=new Set,i=s=>{for(let a of[...n])a(s)};return{readLayoutAdapter(){return cO},readLayoutSource(){let s=e();return s?.view?.state.doc??s?.document??null},readDocumentSize(){return e()?.view?.state.doc.content.size??null},getResolvedProjection(){return t},getPages(){return t?.pages??[]},getSectionMetadata(){return LS(t)},getResolvedProjectionGeometryOptions(){return r},setResolvedProjection(s,a=null){t=s??null,r=a??null,i(t)},subscribeResolvedProjection(s){return n.add(s),()=>{n.delete(s)}},getPointerCaretOrigin(){return o},setPointerCaretOrigin(s){o=s??null},selection:Ta()}}function iv(e){let t=()=>ls(e),o={...ka(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 tu=Symbol.for("@datalking/begonia-browser-sdk/browser-editor-v1-runtime"),Ci=new WeakMap,ru=new WeakMap;function eu(e,t){Object.defineProperty(e,tu,{configurable:!0,enumerable:!1,writable:!0,value:t})}function Qd(e){return!e||typeof e!="object"?null:e[tu]??null}function sv(e){!e||typeof e!="object"||delete e[tu]}function dO(e){return"host"in e}function ou(e,t){Ci.set(e,t),eu(e,t)}function Ea(e,t,r){Ci.set(e,r),ru.set(t,r),eu(e,r),eu(t,r)}function av(e,t){e&&(Ci.delete(e),sv(e)),t&&(ru.delete(t),sv(t))}function Cr(e){if(!e)return null;if(dO(e))return ru.get(e)??Qd(e)??Ci.get(e.host)??Qd(e.host)??null;let t=Be(e);return t?Ci.get(t)??Qd(t)??null:null}function nu(e){return Cr(e)?.controller??null}function lv(e){return Cr(e)?.advancedOoxmlActions??null}var k$=vn({commandIds:dS});function uO(e){let t=e.getState();return{linkPopover:t.linkPopover,contextMenu:t.contextMenu}}function mO(e){let t=null,r=()=>{let o=uO(e);return(t==null||!fn(t,o))&&(t=o),t};return{getSnapshot:r,subscribe(o){return e.subscribe(()=>{let n=t;n!=null&&r()!==n&&o()})}}}function pO(e,t=Sn){let r=e.getState(),o=ci(e,t);return xn(r,o)}function Pi(e){let t=()=>pO(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."):kw(e,r,o)??ye(`Unsupported browser command: ${String(r)}`)}}}function In(e){let t={controller:e,backend:wS(e),advancedOoxmlActions:e},r=iv(e),o={session:Pi(e),actor:null,documentApi:e.documentApi,readCommandSnapshot(n=Sn){return uS(e,n)},...gS(e),browserViewport:VS(e,r),preview:r,overlayState:mO(e),overlays:{closeLinkPopover:()=>e.closeLinkPopover(),closeContextMenu:()=>e.closeContextMenu()}};return Object.defineProperty(o,"actor",{configurable:!1,enumerable:!0,get(){return e.actor??null}}),ou(o,t),o}function Ro(e){let t=In(e),r={...t,overlays:t.overlays??{}},o=Cr(t);return o&&ou(r,o),r}function cv(e){return nu(e)}function Ma(e){let t=In(e),r=ra(t),o=Cr(t);return o&&Ea(t,r,o),r}var fO=Pi,wO=Ro,gO=In;import{errorBegoniaResult as pv,okBegoniaResult as Aa,runBegoniaResult as fv}from"@datalking/begonia-result";import{errorBegoniaResult as iu,okBegoniaResult as su,toBegoniaError as dv}from"@datalking/begonia-result";function uv(e){return!!e&&typeof e=="object"&&"ok"in e}function SO(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 Ia(e,t,r){return t?{...t.getSnapshot(),mode:"session",reconfigurable:r}:e.collaborative?SO(r):{collaborative:!1,mode:"none",reconfigurable:r,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null}}async function An(e,t,r){if(!e?.[t])return su(r);try{let o=await e[t]();return uv(o)?o:su(o??r)}catch(o){return iu(dv(o))}}async function mv(e,t){if(!t?.encodeSnapshot)return iu({code:"invalid_request",message:"Collaboration snapshot capture requires a session with encodeSnapshot()."});try{let r=await t.encodeSnapshot();return uv(r)?r:su(r??{document:e.document,documentJson:e.document.toJSON(),update:new Uint8Array,awareness:null,snapshot:t.getSnapshot()})}catch(r){return iu(dv(r))}}function wv(e){let t=async r=>{if(!e.reconfigurable)return pv({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:Ia(e.getSourceRuntime().surface,r,e.reconfigurable),s=await An(r,"connect",i);if(!s.ok)return s;if(o===r&&e.getSourceRuntime().surface.collaborative)return e.emit(),Aa(e.readCollaboration());let l=await fv(()=>e.createReplacementSurface(r.binding,r));if(!l.ok)return o!==r&&await An(r,"disconnect",i),l;if(o&&o!==r){let c=await An(o,"disconnect",n);if(!c.ok)return l.value.destroy(),await An(r,"disconnect",i),c}return e.swapSurface(l.value,r),e.emit(),Aa(e.readCollaboration())};return{attachCollaboration:t,upgradeToCollaboration:t,async detachCollaboration(r={}){if(!e.reconfigurable)return pv({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(),Aa(e.readCollaboration());let i=await fv(()=>e.createReplacementSurface(void 0,null));if(!i.ok)return i;let s=await An(o,"disconnect",e.readCollaboration());return s.ok?(e.swapSurface(i.value,null),r.destroySession&&await o?.destroy?.(),e.emit(),Aa(e.readCollaboration())):(i.value.destroy(),s)},async saveCollaborationSnapshot(){return mv(e.getSourceRuntime().surface,e.getCollaborationSession())}}}import{hasVisibleSemanticContent as hO,isDocumentNodePathIndex as gv}from"@datalking/begonia-document-model";function vO(e){return!!e&&typeof e=="object"&&Array.isArray(e.segments)&&e.segments.length>0}function bO(e,t){let r=e;for(let o of t){if(!r||!gv(o)||o>=r.childCount)return null;r=r.child(o)}return r}function yO(e,t){if(t.length===0)return 0;let r=0,o=e;for(let n of t){if(!gv(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 BO(e,t){let r=e.nodeAt(t.from)??null;return!r||t.to!==t.from+r.nodeSize||!r.isLeaf||!r.isInline||!hO(r)?null:r}function au(e){if(e.selectionKind!=="node"||!vO(e.target))return null;let t=BO(e.doc,e.selection),r=e.target.segments[0];if(!t||!r||e.target.segments.length!==1)return null;let o=Fe(e.doc,r.blockId),n=o?bO(e.doc,o):null,i=o?yO(e.doc,o):null,s=i==null?null:Math.max(-1,i-1);if(!o||!n?.isBlock||s==null)return null;let a=oe(e.doc),l=fe(n,s,e.selection.from,a),c=Math.max(l,fe(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 xO}from"@datalking/begonia-engine";function kt(e){return typeof e=="boolean"?e:void 0}function Sv(e,t){return e||!!t}function CO(e){return{...e}}function PO(e){return{...e,items:e.items.map(CO)}}function hv(e,t,r){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((o,n)=>r(o,t[n]))}function tr(e){return{...e??{},links:e?.links?{...e.links,enabled:kt(e.links.enabled)}:void 0,contextMenu:e?.contextMenu?{...e.contextMenu,enabled:kt(e.contextMenu.enabled),includeDefaultItems:kt(e.contextMenu.includeDefaultItems),customItems:e.contextMenu.customItems?.map(PO)}:void 0,trackChanges:e?.trackChanges?{...e.trackChanges,enabled:kt(e.trackChanges.enabled),visible:kt(e.trackChanges.visible),mode:co(e.trackChanges.mode)??void 0,replacements:uo(e.trackChanges.replacements)??void 0}:void 0,comments:e?.comments?{...e.comments,enabled:kt(e.comments.enabled),visible:kt(e.comments.visible),readOnly:kt(e.comments.readOnly),allowResolve:kt(e.comments.allowResolve),showResolved:kt(e.comments.showResolved),visibility:mo(e.comments.visibility)??void 0,useInternalExternalComments:kt(e.comments.useInternalExternalComments),suppressInternalExternal:kt(e.comments.suppressInternalExternal)}:void 0}}function RO(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 TO(e,t){return e.id===t.id&&(e.label??null)===(t.label??null)&&hv(e.items,t.items,RO)}function lu(e,t){let r=tr(e),o=tr(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&&hv(r.contextMenu?.customItems,o.contextMenu?.customItems,TO)&&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 vv(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:w,initialContent:v,participant:C,schema:R,trackingEnabled:S})=>xO({...u,element:w??u.element,collaborative:m,documentStory:p,editable:f,initialContent:v,schema:R??u.schema,participant:C,trackingEnabled:S,features:e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:as(e.features??[])})}function _r(e,t){return e.eq(t)}function q(e){return{changed:!1,reason:e}}function bv(e,t,r,o=!1){let n=yn(t,r.trackChanges),i=aS(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 Ur(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 yv(e){let t=o=>jt(typeof o=="string"?[o]:[],Ge(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&&So(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??Ut(e.getRuntime().surface.state);if(!a)return q("Place the caret in text or select text before creating a comment.");let l=s?au({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=Ur(o)?o.selectionTarget:null;if(!o?.target&&!a)return q("Capture a text selection or caret before creating a comment.");let l=Ur(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=(Ur(l)?au({doc:e.getRuntime().surface.state.doc,selection:l.selection,selectionKind:l.selectionKind,target:c,text:l.text??null}):null)??c;if(Ur(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))},removeComment(o){let n=e.commentWriteReason();return n?q(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.remove(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 Da}from"@datalking/begonia-document-model";import{NodeSelection as Bv}from"prosemirror-state";function Cv(e,t){return{left:e+8,top:t+12}}function kO(){return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]}}function EO(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 xv(e,t){return Math.max(1,Math.min(t,e.content.size))}function MO(e,t){return Math.max(0,Math.min(t,e.content.size))}function IO(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 AO(e){let t=ce(e.effectiveTrackedChangeIds,e.revisions);if(!e.selectionCapture||e.selectionCapture.selection.empty)return t;if(t.length===0)return[];let r=gr({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?!IO(e.selectionCapture,a):!1})?r:t}function NO(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||fr(Ce(e),t.nodeSelectionTarget)))}function OO(e,t){if(t.selectionKind==="node"){let n=ao(e,t.nodeSelectionTarget);if(n)return n;let i=MO(e.doc,Math.min(t.selection.from,t.selection.to)),s=e.doc.nodeAt(i);if(s&&Bv.isSelectable(s))try{return e.apply(e.tr.setSelection(Bv.create(e.doc,i)))}catch{}}let r=xv(e.doc,Math.min(t.selection.from,t.selection.to)),o=xv(e.doc,Math.max(t.selection.from,t.selection.to));try{let n=K(e,r,o);return n?e.apply(e.tr.setSelection(n)):null}catch{return null}}function DO(e,t,r){return t||(!r||NO(e,r)?e:OO(e,r)??e)}function jO(e){return W(e.selection)?e.selection.node.type.name:e.selection.$from.parent.type.name}function VO(e,t){return t?[...t.activeMarks]:Me(e).activeMarks}function LO(e,t){return t?[...t.activeCommentIds]:Me(e).activeCommentIds}function FO(e){let t=new Set(Me(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 HO(e){if(!e.pointSelectionCapture)return kO();let t=e.surface.view?.dom;return yS({host:t,clientX:e.clientX,clientY:e.clientY,revisions:e.revisions,comments:e.comments})}function Na(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=K(e.view.state,r,o);return n?qe(e,n):!1}catch{return!1}}function Pv(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:Cv(n,i),resolution:s}}function Oa(e,t,r){let o=be(e),n=Ro(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=HO({surface:o,pointSelectionCapture:a,clientX:r.clientX,clientY:r.clientY,revisions:r.revisions,comments:c}),u=[...d.trackedChangeIds],m=[...d.commentIds],p=DO(o.state,r.selectionState,i),f=l??p,w=r.selection??p.selection,v=EO(f),C=LO(p,i),R=l?FO(f):VO(p,i),S=r.reviewActionsEnabled,B=(()=>{if(!S)return[];let y=de(r.selection?.trackedChangeIds??r.selectionTrackedChangeIds);if(r.selection?.trackedChangeIdsExplicit===!0)return AO({effectiveTrackedChangeIds:y,selectionCapture:s??i,revisions:r.revisions});let T=de(o.listSelectionRevisionIds?.());return gr({from:w.from,to:w.to,trackedChangeIds:y.length>0?y:T},r.revisions)})(),h=a&&B.length===0&&d.status==="resolved"&&u.length>0?[...u]:B;return{host:n,trigger:"contextmenu",selectedText:w.empty?"":ge(p.doc,o.schema,w),hasSelection:!w.empty,selectionStart:w.from,selectionEnd:w.to,isInTable:v.some(y=>y==="table"||y==="table_row"||y==="table_cell"),isInList:v.some(y=>y==="bullet_list"||y==="ordered_list"||y==="list_item"),isTrackedChange:h.length>0,trackedChangeIds:[...h],hasAmbiguousPointReviewTarget:a!=null&&d.status==="ambiguous",pointReviewTrackedChangeIds:u,pointReviewCommentIds:m,documentMode:t,currentNodeType:jO(f),activeCommentIds:C,activeMarks:R,selectionCapture:i,actionSelectionCapture:s,pointSelectionCapture:a,isEditable:it(o),pos:l?l.selection.from:w.from,clientX:r.clientX,clientY:r.clientY,position:Cv(r.clientX,r.clientY)}}function Rv(e){let t=()=>e.reviewWriteReason()==null,r=l=>pr({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 Na(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()))},updateProofingConfig(l){return e.runAndEmit(()=>e.getRuntime().documentApi.proofing.updateConfig(l))},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=Da(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=Da(c);if(!t()||!m)return!1;let p=i(l,w=>w.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=Da(c);if(!t()||!m)return!1;let p=s(l,w=>w.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=Da(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 QO}from"@datalking/begonia-engine";function Xr(e,t={},r="paired"){return Me(e.state,t,{reviewReplacementMode:r})}function zO(e){return e!=null}function Tv(e){return[e.comments?.target(e.commentId),e.comments?.targetSnapshot?.(e.commentId),e.fallbackTarget].filter(zO)}function qO(e){return Tv(e)[0]??null}function Ri(e){for(let t of Tv(e)){let r=e.resolve(t);if(r!=null)return{target:t,resolution:r}}return null}function WO(e){return e.hasSemanticSelection?e.captureSelectionIsRanged?!e.semanticSelectionIsCollapsed:e.semanticSelectionIsCollapsed:!1}function KO(e){return e.hasUniqueCommentId&&(e.captureSelectionIsRanged||e.captureSelectionIsCollapsed||!e.hasCaptureSelection)}function kv(e){let t=[];return WO(e)&&t.push("semantic-selection"),KO(e)&&t.push("comment-target"),e.hasAmbiguousCommentIds||(e.captureSelectionIsCollapsed?t.push("collapsed-absolute"):e.captureSelectionIsRanged&&t.push("ranged-absolute")),t}function _O(e){return e.length===1?e[0]:null}function UO(e,t){return Mw(e?.activeCommentIds,t)}function Ti(e){return!!(e&&e.from===e.to)}function XO(e,t){return e.from===t.from&&e.to===t.to}function ja(e){return Math.max(e.to-e.from,0)}function ZO(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.targetKind;return t==="range"||t==="anchor"||t==="comment"}function GO(e){return ZO(e?.target)?e.target:null}function $O(e){return{get state(){return e.state},view:e}}function YO(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=K(t.state,o,o);if(n&&qe(e.surface,n))return!0}return!1}function JO(e){let t=e.collapsedSemanticSelection.from,r=e.activeCommentIds.map(a=>Ri({comments:e.comments,commentId:a,fallbackTarget:null,resolve:l=>$e(e.doc,l)})).filter(a=>a!=null&&a.resolution.from<a.resolution.to&&a.resolution.from<=t&&t<a.resolution.to).sort((a,l)=>ja(a.resolution)-ja(l.resolution));if(r.length===0)return null;let[o,...n]=r,i=ja(o.resolution);return n.filter(a=>ja(a.resolution)===i).every(a=>XO(a.resolution,o.resolution))?o.target:null}function ki(e){let t=e.capture?.selection??null,r=t!=null&&t.from===t.to,o=t!=null&&t.from!==t.to,n=UO(e.capture,e.comments),i=_O(n),s=e.surface.view;if(!s?.state||typeof s.dispatch!="function")return!1;if(e.capture?.selectionKind==="node"){let f=Sr($O(s),e.capture);if(f)return qe(e.surface,f)}let a=e.capture?js(s.state,{selectionTarget:e.capture.selectionTarget??null,segmentTexts:e.capture.segmentTexts??null,text:e.capture.text??void 0})??je(s.state.doc,e.capture.selectionTarget??null,e.capture.text??null,{strict:!0}):null,c=(i?Ri({comments:e.comments,commentId:i,fallbackTarget:GO(e.capture),resolve:f=>$e(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||Ti(a)&&a.from!==t.from)){let f=K(s.state,t.from,t.to);if(f&&qe(e.surface,f))return!0}let m=kv({captureSelectionIsCollapsed:r,captureSelectionIsRanged:o,hasCaptureSelection:t!=null,hasSemanticSelection:a!=null,semanticSelectionIsCollapsed:Ti(a),hasUniqueCommentId:i!=null,hasAmbiguousCommentIds:n.length>1});for(let f of m){if(f==="semantic-selection"&&a){let w=K(s.state,a.from,a.to);if(!w)continue;if(qe(e.surface,w))return!0;continue}if(f==="comment-target"&&i){let w=c?K(s.state,c.from,c.to):null;if(w&&qe(e.surface,w))return!0;continue}if((f==="collapsed-absolute"||f==="ranged-absolute")&&t){if(f==="ranged-absolute"&&n.length>0&&(!a||Ti(a)))continue;let w=K(s.state,t.from,t.to);if(!w)continue;try{if(qe(e.surface,w))return!0}catch{continue}}}let p=n.length>1&&a&&Ti(a)?JO({activeCommentIds:n,comments:e.comments,collapsedSemanticSelection:a,doc:s.state.doc}):null;return p&&So(e.surface,p)?!0:o&&n.length>0&&(!a||Ti(a))?YO({captureSelection:t,surface:e.surface}):!1}function Ev(e){let t=()=>{let h=e.readEffectiveSelection(),{surface:y,documentApi:T,replacementMode:A}=e.getRuntime(),D=y.describeSelection(),O=Xr(y,{},A);return h?{effectiveSelection:h,liveSelection:D,revisionIds:Ct({liveSelection:D,liveSelectionInfo:O,revisions:T.review.list(),effectiveSelection:h})}:{effectiveSelection:null,liveSelection:D,revisionIds:gr(D,T.review.list())}},r=h=>h.revisionIds.length===1&&(h.effectiveSelection?.selection.empty??h.liveSelection.empty),o=(h,y,T=null)=>e.runAndEmit(()=>{let A=h==="accept"?e.getRuntime().documentApi.review.accept(y,e.getCurrentActor()??void 0):e.getRuntime().documentApi.review.reject(y,e.getCurrentActor()??void 0);return A.changed&&T?.(),A}),n=h=>ki({capture:h,surface:e.getRuntime().surface,comments:e.getRuntime().documentApi.comments}),i=(h,y)=>{let T=e.readEffectiveSelection();return o(h,[y],()=>n(T))},s=h=>{let{surface:y}=e.getRuntime();return typeof y.listSelectionRevisionIds!="function"||wr(h,y.listSelectionRevisionIds())},a=(h,y)=>({changed:h,revisionIds:[...y],activityId:null,activityIds:[],decisions:[],activities:[]}),l=()=>e.getRuntime().documentApi.review.decisionActivity({sort:"asc"}),c=()=>new Set(l().map(h=>h.activityId)),d=(h,y,T)=>{let A=l().filter(O=>!T.has(O.activityId));if(A.length===0)return a(h,y);let D=A.map(O=>({activityId:O.activityId,revisionId:O.revisionId,decision:O.decision,relatedKinds:[...O.relatedKinds],memberCount:O.memberCount,memberRevisionIds:[...new Set(O.record.members.map(U=>U.revisionId))],memberEntryIds:[...O.memberEntryIds],createdAt:O.updatedAt??null,authorId:O.authorId??null,authorName:O.authorName??null,revisionAuthorId:O.revisionAuthorId??null,revisionAuthorName:O.revisionAuthorName??null,revisionCreatedAt:O.revisionCreatedAt??null}));return{changed:h,revisionIds:[...new Set([...y,...A.map(O=>O.revisionId)])],activityId:A[0]?.activityId??null,activityIds:A.map(O=>O.activityId),decisions:D,activities:A}},u=h=>rt(e.getRuntime().surface,e.readEffectiveSelection(),h),m=h=>{let y=h.effectiveSelection,T=h.liveSelection,A=e.getRuntime().surface,D=A.view;if(!y||y.selection.empty||y.activeCommentIds.length>0||T.empty||!D?.state||typeof D.dispatch!="function")return!1;let O=K(D.state,Math.min(T.from,T.to),Math.min(T.from,T.to));return O?qe(A,O):!1},p=h=>{n(h.effectiveSelection),m(h)},f=()=>{let{surface:h}=e.getRuntime(),y=h.view;!y?.state||typeof y.dispatch!="function"||y.dispatch(y.state.tr.setMeta(QO,{preservedSelection:null}))},w=(h,y,T,A)=>{let{revisionIds:D}=y;if(r(y)){let H=D[0];return H?i(h,H):q("No tracked changes overlap the current selection.")}if(D.length===0)return q("No tracked changes overlap the current selection.");let O=c();return(T&&s(D)?u(T):!1)?(A(),d(!0,D,O)):o(h,D,A)},v=()=>e.getPresentationReadApi().review.list(),C=h=>ce(typeof h=="string"?[h]:[],v())[0]??null,R=h=>{e.setActiveRevisionIds(h),e.emit()},S=()=>{e.setActiveRevisionIds([]),e.emit()},B=h=>{let y=v(),T=$c(y,e.getActiveRevisionId(),h);return T?(R([T]),T):null};return{acceptRevision(h){let y=e.reviewWriteReason();if(y)return q(y);let T=e.readEffectiveSelection();return o("accept",[h],()=>n(T))},rejectRevision(h){let y=e.reviewWriteReason();if(y)return q(y);let T=e.readEffectiveSelection();return o("reject",[h],()=>n(T))},acceptSelection(){let h=e.reviewWriteReason();if(h)return q(h);let y=t();return w("accept",y,T=>typeof T.acceptSelectionRevisions=="function"?T.acceptSelectionRevisions():!1,()=>p(y))},rejectSelection(){let h=e.reviewWriteReason();if(h)return q(h);let y=t();return w("reject",y,T=>typeof T.rejectSelectionRevisions=="function"?T.rejectSelectionRevisions():!1,()=>{e.clearPreservedRangeSelection(),p(y),f()})},acceptAll(){let h=e.reviewWriteReason();if(h)return q(h);let y=e.readEffectiveSelection();return o("accept",void 0,()=>n(y))},rejectAll(){let h=e.reviewWriteReason();if(h)return q(h);let y=e.readEffectiveSelection();return o("reject",void 0,()=>n(y))},setActiveRevision(h){if(h==null)return S(),!0;let y=C(h);return y?(R([y]),!0):!1},nextActiveRevision(){return B("next")},previousActiveRevision(){return B("previous")}}}function Mv(e){return{...wv(e),...yv(e),...Ev(e),...Rv(e)}}function eD(e){return{id:e.id,name:e.name,role:"reviewer"}}function cu(e,t,r,o){return lS(e===void 0?eD(t):e,r,o??void 0)}function To(e,t,r,o){return cu(e,t.participant,r,o)}import{createDefaultViewportFitControllerState as dD}from"@datalking/begonia-layout-renderer/core";function Va(e,t="paired"){return{sourceRuntime:null,activeRuntime:null,canonicalDocument:e,projectionKind:"none",projectedRuntimeBank:null,replacementMode:t,collaborativeProjection:null}}function ko(e){return e.projectionKind==="inline"}function tD(e){return e.projectionKind==="collaborative"}function du(e,t,r=t.replacementMode){return{...e,sourceRuntime:t,activeRuntime:tD(e)&&e.activeRuntime?e.activeRuntime:t,replacementMode:r,canonicalDocument:ko(e)?e.canonicalDocument:t.surface.document}}function Nn(e){if(!e.sourceRuntime||ko(e))return e;let t=e.sourceRuntime.surface.document;return uu(e,t)}function uu(e,t){return t===e.canonicalDocument?e:{...e,canonicalDocument:t}}function Ei(e,t,r=e.replacementMode){return e.projectedRuntimeBank===t&&e.replacementMode===r?e:{...e,projectedRuntimeBank:t,replacementMode:r}}function Iv(e){return e.sourceRuntime?{...e,activeRuntime:e.sourceRuntime,projectionKind:"inline",collaborativeProjection:null}:e}function Av(e,t){return{...e,activeRuntime:t.runtime,projectionKind:"collaborative",collaborativeProjection:t}}function Mi(e){return{...e,activeRuntime:e.sourceRuntime,projectionKind:"none",collaborativeProjection:null}}function Nv(e){return{...e,sourceRuntime:null,activeRuntime:null,projectedRuntimeBank:null,collaborativeProjection:null,projectionKind:"none"}}function mu(e,t){let r=ya(t,{flowMode:e.flowMode,layoutMode:e.layoutMode,fallbackViewport:re(e.viewport),nextToken:e.nextPreviewNavigationRequestToken});return r?Kr(e.previewNavigationRequest,r)?{nextState:e,request:Pe(e.previewNavigationRequest),changed:!1}:{nextState:{...e,previewNavigationRequest:r,nextPreviewNavigationRequestToken:e.nextPreviewNavigationRequestToken+1},request:Pe(r),changed:!0}:{nextState:e,request:null,changed:!1}}function pu(e,t){return!e.previewNavigationRequest||t!=null&&!Eh(e.previewNavigationRequest,t)?e:{...e,previewNavigationRequest:null}}function Eo(e,t){return Object.hasOwn(e,t)&&e[t]!==void 0}function rD(e,t){return t||(e.flowMode==="paginated"?e.layoutMode:e.preferredPaginatedLayoutMode)}function Ov(e,t,r){return!e||!to(e,t,r)||rc(e,t,r)?null:e}function oD(e,t,r,o,n){if(!r)return{viewport:e,ignoredIncompatibleViewport:!1};let i=_t(t.viewport??null,{flowMode:o,layoutMode:n});if(!i)return{viewport:null,ignoredIncompatibleViewport:!1};let s=Ov(i,o,n);return{viewport:s??e,ignoredIncompatibleViewport:s==null}}function nD(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:et(e.currentViewportState,e.normalizedViewportState)?e.state.viewportRequestKey:null:e.normalizedViewportState!=null?e.requestedViewportRequestKey:e.state.viewport!=null?null:e.requestedViewportRequestKey}function iD(e){return e.previewNavigationRequest?e.appliedViewportRequestKey&&e.nextViewportRequestKey!=null&&!bs(e.currentViewportRequestKey,e.nextViewportRequestKey)?!0:e.hasViewport&&e.normalizedViewportState!=null&&!et(e.currentViewportState,e.normalizedViewportState):!1}function sD(e){return Pe(e)}function aD(e){return re(e)}function lD(e){return e.request?{anchorPageNumber:e.request.anchorPageNumber,viewportAnchor:e.request.viewportAnchor}:e.viewport?{}:null}function cD(e){if(!e.modesChanged||e.normalizedViewportState!=null)return null;let t=lD({request:e.previousPreviewNavigationRequest,viewport:e.previousViewportState});return t?ya(t,{flowMode:e.nextFlowMode,layoutMode:e.nextLayoutMode,fallbackViewport:e.previousViewportState,nextToken:e.state.nextPreviewNavigationRequestToken}):null}function fu(e,t,r){let o=Eo(t,"flowMode"),n=Eo(t,"layoutMode"),i=Eo(t,"zoomPercent"),s=Eo(t,"viewport"),a=Eo(t,"viewportRequestKey"),l=Eo(t,"showFormattingMarks"),c=Eo(t,"showBookmarks"),d=o?oi(t.flowMode):null,u=n?pt(t.layoutMode):null,m=a?De(t.viewportRequestKey):e.viewportRequestKey,p=d??e.flowMode,f=rD(e,u),w=vr(f,p),v=sD(e.previewNavigationRequest),C=aD(e.viewport),R=Ov(C,p,w),{viewport:S,ignoredIncompatibleViewport:B}=oD(R,t,s,p,w),h=nD({state:e,requestedViewportRequestKey:m,hasViewportRequestKey:a,hasViewport:s,currentViewportState:R,normalizedViewportState:S,ignoredIncompatibleViewport:B}),y=i?vt(t.zoomPercent)??r:r,T=p!==e.flowMode||w!==e.layoutMode,A=kh(e.previewNavigationRequest,p,w)?Pe(e.previewNavigationRequest):null,D=iD({previewNavigationRequest:A,currentViewportRequestKey:e.viewportRequestKey,hasViewport:s,currentViewportState:R,normalizedViewportState:S,appliedViewportRequestKey:a&&(!s||!B&&S!=null),nextViewportRequestKey:h})?null:A,O=D??cD({state:e,nextFlowMode:p,nextLayoutMode:w,normalizedViewportState:S,previousPreviewNavigationRequest:v,previousViewportState:C,modesChanged:T}),H=D==null&&O!=null?e.nextPreviewNavigationRequestToken+1:e.nextPreviewNavigationRequestToken,le=e.previewNavigationRequest!=null&&v==null,ne=f!==e.preferredPaginatedLayoutMode,M=!et(e.viewport,S),N=!bs(e.viewportRequestKey,h),V=le||!Kr(e.previewNavigationRequest,O),b=y!==r,x=l&&typeof t.showFormattingMarks=="boolean"?t.showFormattingMarks:e.display?.showFormattingMarks??!1,I=c&&typeof t.showBookmarks=="boolean"?t.showBookmarks:e.display?.showBookmarks??!1,E=x!==(e.display?.showFormattingMarks??!1)||I!==(e.display?.showBookmarks??!1);return!T&&!ne&&!M&&!N&&!V&&!b&&!E?{nextState:e,nextZoomPercent:y,changed:!1,modesChanged:!1}:{nextState:{...e,flowMode:p,layoutMode:w,preferredPaginatedLayoutMode:f,viewport:S,viewportRequestKey:h,previewNavigationRequest:O,nextPreviewNavigationRequestToken:H,display:{...e.display,showFormattingMarks:x,showBookmarks:I}},nextZoomPercent:y,changed:!0,modesChanged:T}}function wu(e,t,r=t){return{flowMode:e,layoutMode:t,preferredPaginatedLayoutMode:r,viewport:null,viewportRequestKey:null,previewNavigationRequest:null,nextPreviewNavigationRequestToken:1,display:{}}}function Dv(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:Va(c),viewportSession:wu(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:dD()}}function $(e){if(!e.readModel.activeRuntime)throw new Error("Browser editor runtime is not mounted.");return e.readModel.activeRuntime}function Ae(e){if(!e.readModel.sourceRuntime)throw new Error("Browser editor source runtime is not mounted.");return e.readModel.sourceRuntime}function uD(e){return!!(e.previous&&e.previous.from!==e.previous.to&&(!e.current||e.current.from===e.current.to))}function jv(e,t){let r={};t?.mode!==void 0&&(r.mode=Fc(t.mode)),t?.enabled!==void 0&&(r.enabled=po(t.enabled,"trackChanges.enabled")),Object.keys(r).length!==0&&Vt(e,()=>{let o=e.context.resolvedModules.trackChanges;return Object.entries(r).every(([i,s])=>o?.[i]===s)?!1:(e.context.resolvedModules.trackChanges=Ii(o,r),!0)})}function Vt(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&&uD({current:e.context.preservedRangeSelection,previous:o})&&(e.context.preservedRangeSelection=o,e.readState()),e.emit()})}function Ii(e,t){return{...e??{},...t}}function La(e,t){return{...e??{},...t}}function Vv(e){return{setModules(t){Vt(e,()=>(e.context.resolvedModules=tr(t),e.context.currentActor=To(e.context.actorInput,e.getSurface(),e.context.resolvedModules.comments,e.permissionResolver),!0))},setDocumentMode(t){let r=Gs(t);Vt(e,()=>e.context.documentMode===r?!1:(e.context.documentMode=r,!0))},setTrackChangesDisplayMode(t){let r=Fc(t);Vt(e,()=>e.context.resolvedModules.trackChanges?.mode===r?!1:(e.context.resolvedModules.trackChanges=Ii(e.context.resolvedModules.trackChanges,{mode:r}),!0))},setTrackChangesReplacementMode(t){let r=rg(t);Vt(e,()=>e.context.resolvedModules.trackChanges?.replacements===r?!1:(e.context.resolvedModules.trackChanges=Ii(e.context.resolvedModules.trackChanges,{replacements:r}),!0))},setTrackChangesEnabled(t){let r=po(t,"trackChanges.enabled");Vt(e,()=>e.context.resolvedModules.trackChanges?.enabled===r?!1:(e.context.resolvedModules.trackChanges=Ii(e.context.resolvedModules.trackChanges,{enabled:r}),!0))},setTrackChangesOverrides(t){jv(e,t)},setTrackedChangesOverrides(t){jv(e,t)},setTrackChangesVisible(t){let r=po(t,"trackChanges.visible");Vt(e,()=>e.context.resolvedModules.trackChanges?.visible===r?!1:(e.context.resolvedModules.trackChanges=Ii(e.context.resolvedModules.trackChanges,{visible:r}),!0))},setCommentsVisible(t){let r=po(t,"comments.visible");Vt(e,()=>e.context.resolvedModules.comments?.visible===r?!1:(e.context.resolvedModules.comments=La(e.context.resolvedModules.comments,{visible:r}),!0),!1)},setCommentsReadOnly(t){let r=po(t,"comments.readOnly");Vt(e,()=>e.context.resolvedModules.comments?.readOnly===r?!1:(e.context.resolvedModules.comments=La(e.context.resolvedModules.comments,{readOnly:r}),!0),!1)},setCommentsShowResolved(t){let r=po(t,"comments.showResolved");Vt(e,()=>e.context.resolvedModules.comments?.showResolved===r?!1:(e.context.resolvedModules.comments=La(e.context.resolvedModules.comments,{showResolved:r}),!0),!1)},setCommentsVisibility(t){let r=og(t);Vt(e,()=>e.context.resolvedModules.comments?.visibility===r?!1:(e.context.resolvedModules.comments=La(e.context.resolvedModules.comments,{visibility:r}),!0),!1)}}}function gu(e){return e==null?e:structuredClone(e)}function Fa(e){return e&&{...e,groups:e.groups?[...e.groups]:e.groups}}function Lv(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function Fv(e){return{...e,zoomPercent:Object.hasOwn(e,"zoomPercent")&&e.zoomPercent!==void 0?vt(e.zoomPercent)??void 0:e.zoomPercent,viewportRequestKey:Object.hasOwn(e,"viewportRequestKey")&&e.viewportRequestKey!==void 0?De(e.viewportRequestKey):e.viewportRequestKey}}function mD(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&"segments"in e&&Array.isArray(e.segments)}function Hv(e){if(!e.captureTarget||!mD(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 Ha(e){return"documentService"in e?{documentApi:e.documentApi,documentService:e.documentService}:{documentApi:e.documentApi,documentService:e.service}}function pD(e){return{projectedMode:e.projectedMode,projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,presentationReadRuntime:e.presentationReadRuntime,canonicalReviewRuntime:e.canonicalReviewRuntime,writableRuntime:e.writableRuntime}}function zv(e){let t=sS(e.trackChangesMode),r=oS(e.projectedRuntimeBank),o=Ha(e.presentationRuntime),n=Ha(e.writableRuntime??e.presentationRuntime),i=t&&r?Ha(r.resolveRuntime(t)):o,s=t&&r?Ha(r.resolveRuntime("tracked")):n;return pD({projectedMode:t,projectedRuntimeBank:r,canonicalDocument:e.canonicalDocument??null,presentationReadRuntime:i,canonicalReviewRuntime:s,writableRuntime:n})}function fD(e){let t=e.activeRuntime??e.sourceRuntime;if(!t)throw new Error("Browser editor presentation runtime is not mounted.");return t}function wD(e){let t=e.sourceRuntime??e.activeRuntime;if(!t)throw new Error("Browser editor writable runtime is not mounted.");return t}function Zr(e,t){return zv({presentationRuntime:fD(e),writableRuntime:wD(e),projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,trackChangesMode:t})}import{readViewportFitState as gD,resolveViewportFitZoomPercent as SD,updateViewportFitMetrics as hD,updateViewportFitMode as vD,updateViewportFitWidthOptions as bD}from"@datalking/begonia-layout-renderer/core";function za(e,t){return gD(e.viewportFitState,{zoomPercent:t,flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function qv(e){return SD(e.viewportFitState,{flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function Su(e,t){let r=vD(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function Wv(e,t){let r=bD(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function Kv(e,t){let r=hD(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function _v({context:e,emit:t,getEmissionVersion:r,applySurfaceDisplayState:o}){let n=()=>ur(Ae(e).documentApi.preferences.get()),i=l=>{let c=Ae(e),d=ur(c.documentApi.preferences.get());return l===d?!1:(c.documentApi.preferences.set({zoomPercent:l}),!0)},s=()=>{let l=qv(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 za(e,n())},getViewportState(){return re(e.viewportSession.viewport)},requestPreviewNavigation(l){if(e.readModel.sourceRuntime==null)return null;let c=mu(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=pu(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=Fv(l),m=Object.hasOwn(u,"zoomPercent")&&u.zoomPercent!==void 0?Su(e,"manual"):!1,p=fu(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(!Su(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setFitWidthOptions(l){if(!Wv(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setZoomViewportMetrics(l){if(!Kv(e,l)||e.readModel.sourceRuntime==null)return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)}}}import{DELETION_MARK_NAME as dV,describeSurfaceSelection as uV,INSERTION_MARK_NAME as mV}from"@datalking/begonia-engine";import{NodeSelection as pV}from"prosemirror-state";import{documentWideMutationEffect as fV}from"@datalking/begonia-editor-contracts";import{cloneSelectionTextRange as aV}from"@datalking/begonia-document-api/core";import{cloneSelectionTextRange as yD}from"@datalking/begonia-document-api/core";import{resolveRevisionProjectedDocument as BD}from"@datalking/begonia-engine";import{collectDocumentNodesIncludingSyntheticSideStories as xD,readSyntheticSideStoryDocOriginPath as CD}from"@datalking/begonia-doc-service/v1";import{formatAddressableBlockIdWithLogicalId as PD,parseAddressableBlockId as RD}from"@datalking/begonia-doc-service/structure";var Uv=new WeakMap,Xv=new WeakMap;function TD(e){let t=Uv.get(e);if(t)return t;let r=xD({schema:e.type.schema,readDocument:()=>e},{include:(o,n)=>o.type.name==="doc"&&n.length>0,map:(o,n)=>({doc:o,path:[...n]})});return Uv.set(e,r),r}function kD(e,t){if(!t)return e;let r=Xv.get(e)??{},o=r[t];if(o)return o;let n=BD(e,e.type.schema,t);return Xv.set(e,{...r,[t]:n}),n}function ED(e,t,r){if(!e||!t||e.eq(t))return null;let o=CD(e);if(o)return o;let n=TD(kD(t,r)).filter(i=>i.doc.eq(e));return n.length===1?n[0].path:null}function rr(e){let t=ED(e.projectedDocument,e.canonicalDocument,e.projectedMode);if(!t)return e.blockId;let r=RD(e.blockId);return!r||r.path.some(o=>o<0)?e.blockId:PD(r.blockType,[...t,...r.path],r.logicalId)}function Zv(e){if(!e.target)return e.target;let t=e.target.segments.map(o=>({blockId:rr({blockId:o.blockId,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),range:yD(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 ID}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as AD,semanticNodeText as ND}from"@datalking/begonia-document-model";import{isAddressableTextHiddenLeaf as MD}from"@datalking/begonia-document-model";function or(e){return e.isText?e.text?.length??0:!e.isLeaf||MD(e)?0:1}var OD="\uFFFC";function Gv(e){if(e.isText)return e.text??"";if(e.childCount===0){if(or(e)===0)return"";let o=ND(e);return o.length===1?o:OD}let t=[],r=!0;return e.forEach(o=>{o.isBlock&&!r&&t.push(`
7
+ `),t.push(Gv(o)),r=!1}),t.join("")}function qa(e,t){let r=Fe(e,t);if(!r)return null;let o=e;for(let n of r){if(!AD(n)||n>=o.childCount)return null;o=o.child(n)}return o.isBlock?{node:o,path:r}:null}function Et(e,t){let r=qa(e,t);return r?Gv(r.node):null}function Gr(e){let t=tS([e.currentDocument,e.expectedProjectedDocument]);return t?ID({schema:e.schema,port:{replaceDocument(){}},readDocument(){return e.expectedProjectedDocument}},t)?.doc??null:e.expectedProjectedDocument}import{isAddressableTextHiddenLeaf as jD,isDocumentNodePathIndex as VD}from"@datalking/begonia-document-model";import{readReviewLedger as DD}from"@datalking/begonia-engine";function hu(e){return e.join(".")}function $v(e,t,r){return e.isInline?!bt(e,t,!r):r}function vu(e,t){if(e.marks.some(o=>$f(o.type.name,t)&&(o.attrs.blockAttrsBefore!=null||o.attrs.blockAttrsAfter!=null)))return!0;let r=!1;return e.forEach(o=>{!r&&vu(o,t)&&(r=!0)}),r}function Yv(e,t){let r=t==="final"?"delete":"insert";return new Set(DD(e).filter(o=>o.entryType==="revision"&&o.kind===r&&o.target?.blockPath.length).map(o=>hu(o.target.blockPath)))}function Ai(e){let t=Yv(e,"final"),r=Yv(e,"original"),o=new Map,n=(i,s,a,l)=>{let c=$v(i,"final",a),d=$v(i,"original",l);if(i.isText||i.isLeaf){let p=or(i)>0;return{contentFinal:c&&p,contentOriginal:d&&p}}let u=!1,m=!1;if(i.forEach((p,f,w)=>{let v=n(p,[...s,w],c,d);u||=v.contentFinal,m||=v.contentOriginal}),i.isBlock){let p=hu(s);o.set(p,{final:!(t.has(p)&&!u&&!vu(i,"final")),original:!(r.has(p)&&!m&&!vu(i,"original"))})}return{contentFinal:u,contentOriginal:m}};return n(e,[],!0,!0),{isBlockPresent(i,s){return o.get(hu(i))?.[s]??!0}}}var Qv=Object.freeze({blockSeparator:`
8
+ `});function eb(e,t){let r=Fe(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!VD(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 Jv(e,t,r){return e.isInline?!bt(e,t,!r):r}function LD(e){return e.isText?e.text?.length??0:!e.isLeaf||jD(e)?0:or(e)}function Mo(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 w=0,v=!0,C=!1;for(let R=0;R<u.childCount;R+=1){if(l)return;let S=u.child(R),B=m+w,h=[...f,R],y=!S.isBlock||i.isBlockPresent(h,o);if(S.isBlock&&!v)if(r>=B+1)a+=p&&y&&C?1:0;else{l=!0;return}d(S,B,p&&y,h),w+=S.nodeSize,S.isBlock&&(C||=p&&y),v=!1}},d=(u,m,p,f)=>{if(l)return;let w=Jv(u,o,p);if(u.isText){let v=u.text?.length??0,C=m+v;r>=C?a+=w?v:0:(a+=w?Math.max(0,r-m):0,l=!0);return}if(u.isLeaf){r>=m+u.nodeSize?a+=w?LD(u):0:l=!0;return}c(u,m+1,w,f)};return c(e,s,Jv(e,o,!0)&&i.isBlockPresent(n,o),n),a}function bu(e,t,r,o,n,i,s){let a=t+1,l=Math.max(a,t+e.nodeSize-1),c=Mo(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);Mo(e,t,p,n,i,s)<r?d=p+1:u=p}if(o!=="start")return d;let m=d;for(;m<l&&Mo(e,t,m+1,n,i,s)===r;)m+=1;return m}function $r(e){let t=eb(e.document,e.blockId);if(!t)return null;let r=oe(e.document,Qv),o=Ai(t.document);if(e.range.start===e.range.end){let l=Nr(t.node,t.position,e.range.start,r);return typeof l=="number"?{start:Mo(t.node,t.position,l,e.projectedMode,t.path,o),end:Mo(t.node,t.position,l,e.projectedMode,t.path,o)}:null}let n=ze(t.node,t.position,e.range.start,"start",r),i=ze(t.node,t.position,e.range.end,"end",r);if(typeof n!="number"||typeof i!="number")return null;let s=Mo(t.node,t.position,n,e.projectedMode,t.path,o),a=Mo(t.node,t.position,i,e.projectedMode,t.path,o);return{start:Math.min(s,a),end:Math.max(s,a)}}function Wa(e){let t=eb(e.document,e.blockId);if(!t)return null;let r=oe(e.document,Qv),o=Ai(t.document);if(e.range.start===e.range.end){let l=bu(t.node,t.position,e.range.start,"end",e.projectedMode,t.path,o);return typeof l=="number"?{start:fe(t.node,t.position,l,r),end:fe(t.node,t.position,l,r)}:null}let n=bu(t.node,t.position,e.range.start,"start",e.projectedMode,t.path,o),i=bu(t.node,t.position,e.range.end,"end",e.projectedMode,t.path,o);if(typeof n!="number"||typeof i!="number")return null;let s=fe(t.node,t.position,n,r),a=fe(t.node,t.position,i,r);return{start:Math.min(s,a),end:Math.max(s,a)}}import{hasVisibleSemanticContent as zD}from"@datalking/begonia-engine";function FD(e,t){let r=Math.min(e.length,t.length),o=0;for(;o<r&&e[o]===t[o];)o+=1;return o}function HD(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 Ni(e,t){if(e===t)return{current:{start:0,end:e.length},next:{start:0,end:t.length}};let r=FD(e,t),o=HD(e,t,r);return{current:{start:r,end:e.length-o},next:{start:r,end:t.length-o}}}function qD(e){return or(e)}function tb(e){return e.length>0&&e.trim().length===0}function WD(e){return e==="paragraph"||e==="heading"}function rb(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function KD(e,t){return jr(e,t)}function _D(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 UD(e){let t=[],r=(o,n,i,s)=>{let a=o.isInline?bt(o,"final",i):!1,l=o.isInline?bt(o,"original",s):!1,c=o.isText||o.isLeaf&&zD(o)?qD(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 cb(e){return Math.max(0,e.end-e.start)}function ob(e,t){return!!(e?.precise&&t.length>0&&cb(e.range)!==t.length)}function nb(e,t){return!!(e?.precise&&t.length>0&&cb(e.range)===t.length)}function Bu(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 db(e,t,r){let o=e.target;if(o&&rb(o.blockPath,r.path)&&typeof o.from=="number"&&typeof o.to=="number")return{range:{start:Jt(r,o.from),end:Jt(r,o.to)},precise:!0};if(typeof e.from=="number"&&typeof e.to=="number")return _D(r,e.from,e.to)?{range:{start:Jt(r,e.from),end:Jt(r,e.to)},precise:!0}:null;let n=t.target;return n&&rb(n.blockPath,r.path)&&typeof n.from=="number"&&typeof n.to=="number"?{range:{start:Jt(r,n.from),end:Jt(r,n.to)},precise:!1}:null}function ib(e,t,r,o,n){let i=db(n.member,o,t);if(!i)return null;let s=Bu(e,r,i.range.start),a=Bu(e,r,i.range.end);return{range:{start:Math.min(s,a),end:Math.max(s,a)},precise:i.precise}}function sb(e,t,r,o,n){let i=db(n.member,o,t);if(!i)return null;let s=Bu(e,r,i.range.start);return{start:s,end:s}}function yu(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 ab(e,t){let r=t?.member.target??e?.target??null;return r&&(r.nodeType==="bookmark_anchor"||r.nodeType==="structural_revision_carrier")&&WD(r.blockType)?r:null}function XD(e){return e.currentText.length>0||e.nextText.length>0?!1:!!(ab(e.currentRevision,e.currentSide)||ab(e.nextRevision,e.nextSide))}function lb(e,t,r,o){let n=Ni(t,r),i=o==="current"?n.current:n.next;return{start:e.start+i.start,end:e.start+i.end}}function ub(e){let t=KD(e.canonicalDocument,e.blockId);if(!t)return null;let r=UD(t),o=e.projectedMode==="final"?"original":"final",n=XD({currentRevision:e.currentRevision,currentSide:e.currentSide,nextRevision:e.nextRevision,nextSide:e.nextSide,currentText:e.currentText,nextText:e.nextText}),i=tb(e.currentText)&&tb(e.nextText),s=e.currentSide&&e.currentRevision?ib(r,t,e.projectedMode,e.currentRevision,e.currentSide):null,a=e.nextSide&&e.nextRevision?ib(r,t,o,e.nextRevision,e.nextSide):null,l=ob(s,e.currentText),c=ob(a,e.nextText),d=nb(s,e.currentText),u=nb(a,e.nextText),m=n?yu(r,e.projectedMode):i&&s||d&&s||l&&s?s.range:s?lb(s.range,e.currentText,e.nextText,"current"):e.nextSide&&e.nextRevision?sb(r,t,e.projectedMode,e.nextRevision,e.nextSide):null,p=n?yu(r,e.projectedMode):s?.precise||s&&e.currentText.length>0&&e.currentText.trim().length===0?s.range:m,f=n?yu(r,o):i&&a||u&&a||c&&a?a.range:a?lb(a.range,e.currentText,e.nextText,"next"):e.currentSide&&e.currentRevision?sb(r,t,o,e.currentRevision,e.currentSide):null;return m&&p&&f?{currentRange:m,currentActiveRange:p,nextRange:f}:null}function mb(e){return typeof e?.member.text=="string"?e.member.text:""}function ZD(e){return e==="final"?new Set(["insert","format"]):new Set(["delete","format"])}function pb(e,t){let r=ZD(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 GD(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function $D(e){let t=new Map;return e.forEach((r,o)=>{let n=GD(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...pb(r,"final")),i.originals.push(...pb(r,"original")),t.set(n,i)}),[...t.values()]}function fb(e,t){return e.sortFrom-t.sortFrom}function On(e){let t=[],r=e.revisions,o=new Map(r.map(i=>[i.id,i]));for(let i of $D(r)){let s=[...e.projectedMode==="final"?i.finals:i.originals].sort(fb),a=[...e.projectedMode==="final"?i.originals:i.finals].sort(fb),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=mb(d),w=mb(u),v=ub({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,currentRevision:m,currentSide:d,nextRevision:p,nextSide:u,currentText:f,nextText:w});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 wb(e){return typeof e=="string"&&e.length>0?e:""}function gb(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:wb(i.text)})).filter(i=>i.text.length>0);if(o.length>0)return o;let n=wb(e.text);return e.kind&&r.has(e.kind)&&n.length>0?[{revisionId:e.id,text:n}]:[]}function Sb(e){let t=new Map;for(let r of e)t.set(JSON.stringify([r.revisionId,r.text]),r);return[...t.values()]}function YD(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function hb(e){let t=new Map;return e.forEach((r,o)=>{let n=YD(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...gb(r,"final")),i.originals.push(...gb(r,"original")),t.set(n,i)}),[...t.values()].map(r=>({finals:Sb(r.finals),originals:Sb(r.originals)}))}function vb(e){let t=new Map;for(let r of e)t.set(`${r.currentText}\0${r.nextText}`,r);return[...t.values()]}function bb(e){let t=[];for(let r of hb(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 vb(t)}function yb(e,t){let r=[];for(let n of hb(e)){let i=t==="final"?n.finals:n.originals,s=vb((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 Ka(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 _a(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 Ua(e,t){return e.end>t.start}function Xa(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 JD(e){return e.currentText.length===0&&e.nextText.length>0||e.currentText.length>0&&e.nextText.length===0}function QD(e){return e.filter(JD).length===1}function ej(e){return e.length>0&&e.trim().length===0}function tj(e){return{current:e.occurrence,next:{start:e.occurrence.start,end:e.occurrence.start+e.nextText.length}}}function Cu(e,t){let r=tj(t),o=r.next.end-r.next.start;return{active:_a(e,ej(t.currentText)?t.occurrence:r.current),needsRebase:Ua(e,r.current),nextRange:{start:Xa(e.start,r.current,o),end:Xa(e.end,r.current,o)}}}function rj(e){let t=new Map;for(let r of e)t.set(`${r.start}:${r.end}`,r);return[...t.values()]}function xu(e,t,r){if(t===r)return null;let o=Ni(t,r),n=o.next.end-o.next.start;if(!Ua(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 oj(e,t,r){let o=Ni(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 nj(e,t,r){return e.currentRange.start===0&&e.currentRange.end===t.length&&e.nextRange.start===0&&e.nextRange.end===r.length}function Bb(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+Xa(e-o.currentRange.start,{start:0,end:n},i);r+=i-n}return e+r}function ij(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=>Ua(e,s.currentRange)))return null;let n=Bb(e.start,r),i=Bb(e.end,r);return{start:Math.min(n,i),end:Math.max(n,i)}}function Pr(e){if(e.canonicalDocument&&e.projectedMode&&e.blockId){let o=On({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(o.length>0){if(o.length===1&&oj(o[0],e.currentBlockText,e.nextBlockText)){let i=xu(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}if(o.length===1&&nj(o[0],e.currentBlockText,e.nextBlockText)){let i=xu(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}let n=ij(e.selectionRange,o);return n||null}}let t=bb(e.revisions),r=rj(t.flatMap(o=>Ka(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=Cu(e.selectionRange,{occurrence:n,currentText:o.currentText,nextText:o.nextText});return a.needsRebase?[a.nextRange]:[]})));return r.length===1?r[0]:r.length===0&&QD(t)?xu(e.selectionRange,e.currentBlockText,e.nextBlockText):null}function sj(e,t){return t!=="visible"||e.preservesWholeCurrentSide||e.currentActiveRange.start<e.currentRange.start||e.currentActiveRange.end>e.currentRange.end?e.currentActiveRange:e.currentRange}function Oi(e){if(!e.projectedMode||!e.projectedDocument||!e.selectionTarget)return gr(e.selection,e.revisions);let t=e.activationScope??"preserved",r=Zv({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=On({blockId:l.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(c.length===0)continue;let d=$r({document:e.projectedDocument,blockId:l.blockId,projectedMode:e.projectedMode,range:l.range})??l.range;a=!0;for(let u of c)_a(d,sj(u,t))&&s.add(u.revisionId)}if(s.size>0)return ce([...s],e.revisions);if(a)return[]}let o=yb(e.revisions,e.projectedMode),n=!1,i=new Set;for(let s of r.segments){let a=Et(e.projectedDocument,s.blockId);if(typeof a=="string")for(let l of o){let c=Ka(a,l.currentText);if(c.length===0||(n=!0,c.length!==1))continue;Cu(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 aj,readSyntheticSideStoryDocOriginPath as lj}from"@datalking/begonia-doc-service/v1";import{projectAcceptedTextBetween as cj}from"@datalking/begonia-engine";function dj(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function Dn(e,t){return e.content.size>0?cj(e,t,1,e.content.size,`
9
+ `):""}function xb(e,t,r,o){let n=Ie(e,t,r);return aj(dj(n),o)?.doc??null}function uj(e,t){let r=lj(e.document);if(!r)return null;let o=xb(t,e,"final",r),n=xb(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=Dn(e.document,e.schema),l=Dn(o,e.schema),c=Dn(n,e.schema),d=a===l;return d!==(a===c)?d?"final":"original":null}function Za(e,t){if(!t||e.document.eq(t))return null;let r=uj(e,t);if(r)return r;let o=Ie(t,e,"final");if(e.document.eq(o))return"final";let n=Ie(t,e,"original");if(e.document.eq(n))return"original";let i=Dn(e.document,e.schema),s=Dn(o,e.schema),a=Dn(n,e.schema),l=i===s;return l===(i===a)?null:l?"final":"original"}import{describeSurfaceSelection as Wb}from"@datalking/begonia-engine";import{formatAddressableBlockIdWithLogicalId as mj,parseAddressableBlockId as Cb}from"@datalking/begonia-doc-service/structure";import{resolveRevisionProjectedDocument as pj}from"@datalking/begonia-engine";function fj(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function wj(e){return e==="final"?"original":"final"}function Pb(e){if(!e.target||!e.sourceTarget||!e.projectedDocument||!e.canonicalDocument||!e.projectedMode)return e.target;let t=pj(e.canonicalDocument,e.canonicalDocument.type.schema,wj(e.projectedMode)),r=e.target.segments.map((n,i)=>{let s=e.sourceTarget?.segments[i],a=Cb(n.blockId),l=s?Cb(s.blockId):null;if(!s||!a||!l?.logicalId)return n;let c=mj(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||!fj([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)?Gt(e.target,r):e.target}import{addressableBlockTypeForNodeType as gj,formatAddressableBlockId as Sj}from"@datalking/begonia-doc-service/structure";function Di(e,t){let r=qa(e,t);if(!r)return t;let o=gj(r.node.type.name);return o?Sj(o,r.path):t}function Io(e,t){if(!t)return t;let r=oe(e),o=t.segments.map(i=>{let s=Di(e,i.blockId),a=qa(e,i.blockId),l=s===i.blockId||!a?{start:i.range.start,end:i.range.end}:{start:mr(a.node,i.range.start,"start",r),end:mr(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)?Gt(t,o):t}function Pu(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?ge(e,t,o):null}function Rb(e){return e.includes("revision_delete")&&!e.includes("revision_insert")?["original"]:e.includes("revision_insert")&&!e.includes("revision_delete")?["final"]:["original","final"]}function Tb(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 kb(e,t,r){let o=new Set;for(let n of Ps(e.resolve(t)))o.add(n);if(t===r)return[...o];for(let n of Cs(e,t,r))o.add(n);return[...o]}import{parseAddressableBlockId as Nb}from"@datalking/begonia-doc-service/structure";import{DELETION_MARK_NAME as Db,FORMAT_MARK_NAME as Ij,INSERTION_MARK_NAME as jb,resolveRevisionProjectedDocument as Ob}from"@datalking/begonia-engine";function hj(e){return or(e)}function Ga(e,t){return t==="final"?e.visibleFinal:e.visibleOriginal}function Mb(e,t){let r=jr(e,t);if(!r)return null;let o=r.node;if(!o?.isBlock)return null;let n=[],i=Ai(r.document),s=0,a=(l,c,d,u)=>{let m=l.isInline?!bt(l,"final",!c):c,p=l.isInline?!bt(l,"original",!d):d,f=hj(l);if(f>0){n.push({start:s,end:s+f,visibleFinal:m,visibleOriginal:p}),s+=f;return}let w=!0,v=!1,C=!1;l.forEach((R,S,B)=>{let h=[...u,B],y=!R.isBlock||i.isBlockPresent(h,"final"),T=!R.isBlock||i.isBlockPresent(h,"original");R.isBlock&&!w&&(n.push({start:s,end:s+1,visibleFinal:m&&y&&v,visibleOriginal:p&&T&&C}),s+=1),a(R,(l.isInline?m:c)&&y,(l.isInline?p:d)&&T,h),R.isBlock&&(v||=m&&y,C||=p&&T),w=!1})};return a(o,i.isBlockPresent(r.localPath,"final"),i.isBlockPresent(r.localPath,"original"),r.localPath),{runs:n,textLength:s}}function vj(e,t){return e.reduce((r,o)=>r+(Ga(o,t)?o.end-o.start:0),0)}function Ru(e,t,r,o){let n=e.filter(a=>Ga(a,t)),i=vj(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 Eb(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=Ga(i,t)?s:0;if(r<i.end)return n+(Ga(i,t)?r-i.start:0);n+=a}return n}function Ib(e){let t=Mb(e.canonicalDocument,e.blockId);if(!t)return null;if(e.range.start===e.range.end){let n=Ru(t.runs,e.projectedMode,e.range.start,"start");return n==null?null:{start:n,end:n}}let r=Ru(t.runs,e.projectedMode,e.range.start,"start"),o=Ru(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 ji(e){let t=Mb(e.canonicalDocument,e.blockId);if(!t)return null;let r=Eb(t.runs,e.projectedMode,e.range.start,t.textLength),o=Eb(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 bj,formatAddressableBlockIdWithLogicalId as yj}from"@datalking/begonia-doc-service/structure";import{isAddressableTextHiddenLeaf as Bj,isDocumentNodePathIndex as xj,semanticNodeText as Cj}from"@datalking/begonia-document-model";function Pj(e){return e.isText?e.text?.length??0:!e.isLeaf||Bj(e)?0:Math.max(1,Cj(e).length)}function Rj(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function Tj(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=bj(r.type.name);if(o)return{type:o,path:Rj(e,t),node:r,pos:e.start(t)-1}}return null}function kj(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 Ej(e,t){let r=Fe(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!xj(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 Vi(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=Pj(l);r>=c+l.nodeSize?n+=d:i=!0;return}s(l,c+1)}};return s(e,o),n}function Tu(e,t,r,o="end"){let n=t+1,i=Math.max(n,t+e.nodeSize-1),s=Vi(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);Vi(e,t,d)<r?a=d+1:l=d}if(o!=="start")return a;let c=a;for(;c<i&&Vi(e,t,c+1)===r;)c+=1;return c}function Li(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=Tj(l);if(!c)return o=!0,!1;let d=Math.max(n,a+1),u=Math.min(i,a+s.nodeSize-1),m=Vi(c.node,c.pos,d),p=Math.max(m,Vi(c.node,c.pos,u));return kj(r,yj(c.type,c.path,ro(c.type,c.node)),m,p),!1}),o?null:r}function Mj(e,t){let r=Ej(e,t.blockId);if(!r)return null;if(t.range.start===t.range.end){let i=Tu(r.node,r.position,t.range.start,"start");return typeof i=="number"?{from:i,to:i}:null}let o=Tu(r.node,r.position,t.range.start,"start"),n=Tu(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 Ab(e,t){let r=[];for(let o of t){let n=Mj(e,o);if(!n)return null;r.push(n)}return io(e,r,{strict:!0})}function Vb(e,t){let r=Nb(e),o=Nb(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 Lb(e,t){return!!(t&&e.range.start===e.range.end&&t.range.start<t.range.end&&Vb(e.blockId,t.blockId))}function Aj(e,t){return t?.segments.length===e.length&&e.some((r,o)=>Lb(r,t.segments[o]))}function Fb(e){return(e??[]).some(t=>t===jb||t===Db||t===Ij)}function ku(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 Nj(e){if(!e.selectionInfo.target||!e.projectedDocument)return null;if(ku(e))return e.selectionInfo.target;let t=Io(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:Hb(e)?.target??null}function Hb(e){let t=e.selectionInfo.text??"";if(!e.projectedDocument||!e.selectionInfo.target||t.length===0)return null;let r=Cc(e.projectedDocument,e.selectionInfo.target,t);if(!r)return null;let o=ku(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 Eu(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=Io(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=Nj(e);return r?Oi({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 zb(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(Db)&&!e.selectionInfo.activeMarks.includes(jb))return null;let t=Hb(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=Li(e.projectedDocument,e.selection);if(!o||o.length===0||r.length>0&&ku(e)&&o.every(l=>l.range.start===l.range.end)&&!Aj(o,e.selectionInfo.target))return null;let n=e.projectedDocument.type.schema,i={final:Ob(e.canonicalDocument,n,"final"),original:Ob(e.canonicalDocument,n,"original")},s=e.selection.empty?["final"]:Rb(e.selectionInfo.activeMarks),a=null;for(let l of s){let c=i[l],d=o.map((S,B)=>{let h=e.selectionInfo.target?.segments[B],y=h&&Vb(S.blockId,h.blockId)?h.blockId:S.blockId,T=Di(e.projectedDocument,y),A=Di(i.final,y),D=N=>({review:{blockId:T,range:{start:N.start,end:N.end}},expected:{blockId:A,range:{start:N.start,end:N.end}}}),O=Lb(S,h)?$r({document:e.projectedDocument,blockId:h.blockId,projectedMode:l,range:h.range}):ji({canonicalDocument:e.canonicalDocument,blockId:S.blockId,projectedMode:l,range:S.range});if(!O)return null;if(l==="final")return D(O);let U=Et(c,S.blockId),H=Et(i.final,S.blockId);if(typeof U!="string"||typeof H!="string")return null;let le=Pr({selectionRange:O,currentBlockText:U,nextBlockText:H,blockId:S.blockId,canonicalDocument:e.canonicalDocument,projectedMode:l,revisions:e.revisions});if(le)return D(le);let ne=Pu(c,n,{blockId:S.blockId,range:O});return ne==null||Pu(e.projectedDocument,n,{blockId:S.blockId,range:O})!==ne?null:D(O)});if(d.some(S=>!S))continue;let u=Gt(e.selectionInfo.target,d.map(S=>S.review)),m=Gt(e.selectionInfo.target,d.map(S=>S.expected)),p=Q(e.projectedDocument,u,{strict:!0});if(!p)continue;let f=Gr({currentDocument:e.projectedDocument,expectedProjectedDocument:i.final,schema:n});if(!f)continue;let w=Q(f,m,{strict:!0});if(!w)continue;let v=ge(e.projectedDocument,n,p),C=ge(f,n,w);if(v!==C)continue;let R={target:u,text:v,from:p.from,to:p.to};if(!a){a=R;continue}if(!Tb(a,R))return null}return a?{target:a.target,text:a.text}:null}function Mu(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 qb(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 Oj(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 Ye(e){let t=on(e.selection,e.revisions),r=Eu({...e,selection:t})??Oi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions}),o=Eu({...e,selection:t},"visible")??Oi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions,activationScope:"visible"}),n=so(e.selectionInfo,t,e.revisions),i=Mu(t,r),s=zb({...e,selection:i});if(Oj(e,r,o,s)){let C=de(t.trackedChangeIds),R=de(n.activeChangeIds);return{selection:Mu(t,C),selectionInfo:qb(n,R.length>0?R:C),trackedChangeIds:C}}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 C=yt(a,Or(i));return Mu({...i,from:a.from,to:a.to,anchor:C.anchor,head:C.head,empty:a.from===a.to},r)})():i,u=c&&a?kb(e.projectedDocument,d.from,d.to):e.selectionInfo.activeMarks,m=s&&e.selection.empty&&s.text.length===0?void 0:s?.text,p=so(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||Fb(e.selectionInfo.activeMarks))?Io(e.projectedDocument,p.target):p.target,w=Pb({target:f,sourceTarget:p.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),v=w!==p.target?{...p,target:w}:p;return{selection:d,selectionInfo:qb(v,o),trackedChangeIds:r}}function Je(e){return e.view?.state??e.state??null}function $a(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function Rr(e,t=null){let r=Je(e);if(!r)return null;let o=Me(r,{includeText:!0});return t?Ye({selection:Wb(r),selectionInfo:o,projectedDocument:r.doc,revisions:t.review.list()}).selectionInfo:o}function Ya(e){let t=Je(e.surface);if(!t)return null;let r=Me(t,{includeText:!0});return Ye({selection:Wb(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}).selectionInfo}function Kb(e,t,r){return ge(e,t,r)}function Ja(e,t,r){return r!=null&&Kb(e.doc,e.schema,t)===r}function Dj(e,t){let r=Je(e);return!!(r&&t&&r.selection.from===t.from&&r.selection.to===t.to)}function jj(e,t){return ei(e,t)}function Vj(e,t,r){let o=[],n=new Set;for(let i of r){let s=t.comments.target(i),a=$e(We(e),s);if(s&&a&&Dj(e,a)){let l=jj(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 _b(e,t,r){if(r.length===0)return null;let o=Vj(e,t,r);return o?{kind:"comment",commentId:o.commentId,target:o.target}:null}function Lt(e,t,r){return Kb(e,t,r)}import{pmPositionToAddressableTextOffset as tV}from"@datalking/begonia-document-model";import{EditorState as rV,NodeSelection as ay}from"prosemirror-state";import{cloneSelectionTextRange as Fj}from"@datalking/begonia-document-api/core";function Lj(e){return e.hasExpectedSegmentTexts?e.expectedSegmentSelection??e.expectedTextSelection:e.hasExpectedText?e.expectedTextSelection:e.strictSelection}function Ub(e){return e==="original"?"original":"final"}function Xb(e){if(!e.hasExpandedTarget)return e.strictSelection;let t=Ub(e.sourceMode),r=Ub(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:Lj(e)}function Zb(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 Hj(e){let{target:t}=e,r=t.segments.map(n=>({blockId:rr({blockId:n.blockId,projectedDocument:e.sourceDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode}),range:Fj(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 Gb(e,t){return e?Ie(e,{schema:e.type.schema},t):null}function zj(e,t){return e.start===t.start&&e.end===t.end}function Iu(e){return e.start===e.end}function qj(e){if(!e.canonicalDocument)return!1;let t=e.target.segments.filter(r=>!Iu(r.range));return t.length===0?!1:t.every(r=>On({blockId:r.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode,revisions:e.revisions}).some(o=>zj(r.range,o.currentRange)&&!Iu(o.currentRange)&&Iu(o.nextRange)))}function Wj(e){let t=e.projectionSnapshot.canonicalDocument;if(!t)return null;let r=Gb(t,e.sourceMode),n=(r?Io(r,e.target):null)??Ot(e.target);if(!n)return null;let i=Hj({target:n,sourceDocument:r,canonicalDocument:t,sourceMode:e.sourceMode}),s=Zb(i);if(e.projectionSnapshot.projectedMode===e.sourceMode)return s&&qj({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=Gb(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 w=r?Et(r,m.blockId):null,v=Et(l,f.blockId),C=Pr({selectionRange:m.range,currentBlockText:w??"",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:C}});if(c.some(m=>!m))return null;let d={kind:"text",segments:c,...e.target.story?{story:structuredClone(e.target.story)}:{}},u=Zb(d);return{target:d,anchorTarget:u}}function $b(e){return e.sourceMode==null?(()=>{let t=Ot(e.target);return t?{target:t,anchorTarget:null}:null})():Wj({...e,sourceMode:e.sourceMode})}function ft(e){let t=$b(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?je(e.state.doc,r,e.expectedText??null,a):null,m=Xb({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 Au(e,t,r){return ge(e,t,r)}function Yb(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?Au(e,t,o):null}function Kj(e){let t=Ie(e.canonicalDocument,{schema:e.schema},e.projectedMode);return Gr({currentDocument:e.referenceDocuments[0]??t,expectedProjectedDocument:t,schema:e.schema})}function Nu(e){let t=Kj({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=rr({blockId:l.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),d=$r({document:e.currentDocument,blockId:l.blockId,projectedMode:e.currentProjectionMode,range:l.range})??l.range,u=Et(e.currentDocument,c),m=Et(t,c);if(typeof u!="string"||typeof m!="string")return null;let p=Pr({selectionRange:d,currentBlockText:u,nextBlockText:m,blockId:c,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode,revisions:e.canonicalReviewApi.review.list()});if(p){let v=Wa({document:t,blockId:c,projectedMode:e.nextProjectionMode,range:p});return v?{blockId:c,range:v}:null}let f=Yb(e.currentDocument,e.schema,l);return f==null||Yb(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=Au(e.nextDocument,e.schema,n),a=Au(t,e.schema,i);return s===a?n:null}function Jb(e){let t=$r({document:e.currentDocument,blockId:e.currentBlockId,projectedMode:e.currentProjectionMode,range:e.range});return t?Wa({document:e.canonicalDocument,blockId:e.canonicalBlockId,projectedMode:e.currentProjectionMode,range:t}):null}function Qb(e){let t=s=>({blockId:rr({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=ut(e.currentDocument,e.selectionTarget);return tt(e.nextDocument,n,i,{strict:!0})??je(e.nextDocument,n,e.expectedText,{strict:!0})}import{buildExtractOverlapParentAliasMap as Gj}from"@datalking/begonia-document-api/review";function _j(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function Uj(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 Ou(e){return!!(e&&e.nodeType&&e.objectId)}function Xj(e,t){return Ou(e.target)&&e.target?.nodeType===t}function ey(e,t){return typeof e.entryId=="string"&&typeof t.entryId=="string"&&e.entryId===t.entryId?!0:!!(Ou(e.target)&&Ou(t.target)&&e.target?.objectId===t.target?.objectId&&_j(e.target?.path,t.target?.path))}function Zj(e){return[...e].sort((t,r)=>Uj(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 ty(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=Zj(e.revisions.flatMap(l=>l.members??[]).filter(l=>Xj(l,e.nodeType))),n=o.find(l=>r.has(l.kind)&&ey(l,e.currentMember));if(n)return n;let s=o.filter(l=>l.kind===e.currentMember.kind).findIndex(l=>ey(l,e.currentMember));return s<0?null:o.filter(l=>t.has(l.kind))[s]??null}function $j(e){return!!(e&&e.nodeType&&e.objectId)}function oy(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function Yj(e,t){let r=oy(e);return r?t.get(r)?.id??r:null}function ry(e,t){let r=oy(e.operationId);if(!r)return null;let o=Yj(e.overlapParentId,t);return o==null?r:`${r}\0${o}`}function Jj(e){for(let t of e.revisions)for(let r of t.members??[])if($j(r.target)&&r.target?.nodeType===e.currentSelectionTarget.nodeType&&r.target?.objectId===e.currentSelectionTarget.stableIdentity)return{revision:t,member:r};return null}function ny(e){let t=e.currentSelectionTarget,r=Jj(e);if(!r)return null;let o=Gj(e.revisions),n=ry(r.revision,o),i=n==null?[r.revision]:e.revisions.filter(a=>ry(a,o)===n),s=ty({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 iy,selectionOverlapsRevisionRange as Qj}from"@datalking/begonia-engine";function Fi(e,t,r,o){return Lt(e,t,{from:r,to:o}).length}function eV(e){let t=Fi(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);Fi(e.doc,e.schema,e.from,n)<e.acceptedOffset?r=n+1:o=n}return Fi(e.doc,e.schema,e.from,r)===e.acceptedOffset?r:null}function sy(e){if(e.selection.from!==e.selection.to)return null;let t=iy(e.currentDocument,e.schema).filter(l=>Qj(e.selection.from,e.selection.to,l)),r=t.length===1?t[0]:null;if(!r||Fi(e.currentDocument,e.schema,r.from,r.to)===0)return null;let n=iy(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=Fi(e.currentDocument,e.schema,r.from,e.selection.from),a=eV({doc:e.nextDocument,schema:e.schema,from:i.from,to:i.to,acceptedOffset:s});return typeof a=="number"?{from:a,to:a}:null}function oV(e){if(!W(e.state.selection)||!e.state.selection.node.isInline||e.state.selection.node.childCount!==0||!Ce(e.state))return e.selectionTarget;let t=Li(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 nV(e){let t=e.selectionTarget.segments.map(d=>{let u=rr({blockId:d.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),m=Ib({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=ji({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=Ie(e.canonicalDocument,{schema:e.schema},e.nextProjectionMode),s=Gr({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=Lt(e.nextDocument,e.schema,n),c=Lt(s,e.schema,a);return l===c?n:null}function iV(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=Fe(e.nextDocument,t.blockId),o=r?Le(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:tV(o.node,o.position,s)===t.range.start?{from:s,to:s}:null}function Du(e){let t=e.currentProjectionMode??null,r=We(e.surface),o=t?Ya({surface:e.surface,canonicalReviewApi:e.canonicalReviewApi,canonicalDocument:e.canonicalDocument,projectedMode:t})??e.selectionInfo??Rr(e.surface,e.canonicalReviewApi):Rr(e.surface,e.canonicalReviewApi);if(!o||!o.target)return null;let n=Je(e.surface);if(!n)return null;let i=t?oV({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?Ce(n):null;if(l&&e.nextProjectionMode){let u=ny({currentSelectionTarget:l,revisions:e.canonicalReviewApi.review.list(),nextProjectionMode:e.nextProjectionMode});if(u)return u}let c=(()=>{if(a)return nV({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 w=ut(r,i),v=tt(e.nextDocument,i,w??null,{strict:!0})??je(e.nextDocument,i,o.text??null,{strict:!0});if(v)return v}if(t&&e.nextProjectionMode)return Nu({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(w=>{let v=rr({blockId:w.blockId,projectedDocument:r,canonicalDocument:e.canonicalDocument,projectedMode:t}),C=Jb({currentDocument:r,canonicalDocument:e.canonicalDocument,currentBlockId:w.blockId,canonicalBlockId:v,currentProjectionMode:t,range:w.range});return C?{blockId:v,range:C}:null}):Li(n.doc,n.selection);if(!u)return null;let m=u.filter(w=>w!=null);if(m.length!==u.length)return null;if(!e.nextProjectionMode){if(t){let w=iV({nextDocument:e.nextDocument,selection:n.selection,segments:m});if(w)return w;if(!n.selection.empty){let v=Qb({currentDocument:r,nextDocument:e.nextDocument,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,expectedText:o.text});if(v)return v;let C=Nu({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:"final"});if(C)return C}}if(!t){let w=sy({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selection:n.selection});if(w)return w}return Ab(e.nextDocument,m)}let p=e.nextProjectionMode,f=m.map(w=>{let v=ji({canonicalDocument:e.canonicalDocument,blockId:w.blockId,projectedMode:p,range:w.range});return v?{blockId:w.blockId,range:v}:null});return f.some(w=>!w)?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)?sV(e.nextDocument,c):null;return d||{kind:"tracked",selection:c,text:Lt(e.nextDocument,n.schema,c)}}function ly(e){if(!e.preservedRangeSelection.target)return null;let t=Je(e.surface);if(!ju(e)||!t)return null;let r=e.preservedRangeSelection.target,o=je(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=Ie(e.canonicalDocument,{schema:t.schema},n),s=Gr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:t.schema});if(!s)return null;let a=je(s,r,e.preservedRangeSelection.text,{strict:!0})??tt(s,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!a)return null;let l=Lt(e.nextDocument,t.schema,o),c=Lt(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 ju(e){if(!e.preservedRangeSelection.target)return!1;let t=Je(e.surface);if(!t||!t.selection.empty||e.preservedRangeSelection.projectedMode!==(e.nextProjectionMode??null))return!1;let r=ft({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 sV(e,t){let r=e.nodeAt(t.from);if(!r||!r.isInline||r.childCount!==0||!ay.isSelectable(r))return null;let o;try{o=ay.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=rV.create({doc:e,selection:o});return Ce(n)}function cy(e,t){let r=Fe(e,t),o=r?Le(e,r):null;return o?.node.isBlock?Qo(o.node,oe(e)).text:null}function lV(e){let t=Je(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=cy(r,s.blockId),l=cy(e.nextDocument,s.blockId),c=a!=null&&l!=null?Pr({selectionRange:s.range,currentBlockText:a,nextBlockText:l,revisions:e.canonicalReviewApi.review.list()}):null;return{blockId:s.blockId,range:c??aV(s.range)}})},i=Q(e.nextDocument,n,{strict:!0});return i?{kind:"text",target:n,text:Lt(e.nextDocument,t.schema,i),segmentTexts:ut(e.nextDocument,n)}:null}function cV(e,t,r,o,n,i,s){let a=Rr(e),l=Rr(e,o),c=!!(o&&n&&(Za(e,i?n:t)||i)),d=c?Za(e,i?n:t):null,u=c&&d?Ya({surface:e,canonicalReviewApi:o,canonicalDocument:n,projectedMode:d})??l:l;if(a?.target&&d==="original"&&!i&&u?.activeMarks.length===0&&a.target.segments.every(w=>w.range.start===w.range.end)){let w=Je(e),v=w?.selection??null;if(v)return{kind:"tracked",selection:{from:v.from,to:v.to},text:Lt(t,w?.schema??t.type.schema,v)}}let p=Ce(Je(e)),f=u?.target&&r?_b(e,r,u.activeCommentIds):null;if(f&&!p)return f;if(c&&u?.target){if(s){let v=ju({surface:e,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s}),C=ly({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s});if(C)return C;if(v)return null}if(d&&!i&&u.activeChangeIds.length===0&&!p){let v=lV({surface:e,nextDocument:t,canonicalReviewApi:o,canonicalDocument:n,currentProjectionMode:d,selectionInfo:u});if(v)return v}let w=Du({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(w)return w}if(o&&u?.target&&u.activeChangeIds.length>0){let w=Du({surface:e,nextDocument:t,canonicalDocument:n??t,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(w)return w}return f||p||(u?.target&&u.activeChangeIds.length===0?{kind:"text",target:u.target,text:u.text??null,segmentTexts:ut(We(e),u.target)}:null)}function Ao(e){let t=cV(e.surface,e.nextDocument,e.documentApi,e.canonicalReviewApi,e.canonicalDocument,e.nextProjectionMode,e.preservedRangeSelection);if(!t||t.kind==="node")return t;let r=Je(e.surface)?.selection;return r&&Sw(r)==="backward"?{...t,direction:"backward"}:t}function wV(e){return!!(e&&e.activeCommentIds.length===0&&e.activeMarks.includes(dV)&&!e.activeMarks.includes(mV)&&(e.text??"").length===0)}function Hi(e){if(!e.target||!$a(e.surface))return;let t=e.surface.view.state.doc,r=e.target.kind==="node"?ds(t,e.target):null,o=e.target.kind==="node"?null:e.target.kind==="comment"?Ri({comments:e.documentApi?.comments,commentId:e.target.commentId,fallbackTarget:e.target.target,resolve:l=>$e(t,l)})?.resolution??null:e.target.kind==="tracked"?e.target.selection:tt(t,e.target.target,e.target.segmentTexts,{strict:!0})??je(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=K(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&&!Ja(e.surface.view.state,o,e.target.text))return;let i=e.surface.view.state.selection,s=o?yt(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?pV.create(e.surface.view.state.doc,r.position):K(e.surface.view.state,s.anchor,s.head);a&&e.surface.view.dispatch(e.surface.view.state.tr.setSelection(a))}function Qa(e){if(!$a(e.surface))return!1;let t=Je(e.surface);if(!t||t.selection.empty)return!1;let r=Rr(e.surface),o=r&&e.canonicalReviewApi?Ye({selection:uV(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}):null;if(wV(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||!Ja(e.surface.view.state,i,n.text))return!1;let s=K(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 jn(e){let{surface:t,nextDocument:r,documentApi:o,nextDocumentApi:n}=e,i=Ao(e);t.replaceDocument(r,{origin:"system",intent:"replace-projected-document-preserving-selection",effects:[fV("review")]}),Hi({surface:t,target:i,documentApi:n??o})}import{createDocumentRuntimeKernel as tL}from"@datalking/begonia-document-api/v1";import{summarizeReviewTimeline as rL}from"@datalking/begonia-document-api/review";import{createEditorSelectionSnapshot as oL}from"@datalking/begonia-editor-contracts";function dy(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 Vn(e,t){e.runMutation(()=>{e.documentApi.ooxml.removeByIdTracked(t,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.removeById(t)})}function Vu(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":Vn(e,t.objectId);return}}function Lu(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":Vn(e,t.objectId);return}}function Fu(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":Vn(e,t.objectId);return}}function uy(e,t){let r=dy(e,t),o=e.view?.dom??null;if(!o)return()=>{};let n=i=>{let s=i instanceof CustomEvent?i.detail:null;if(ap(s))switch(i.preventDefault(),i.stopPropagation(),s.family){case"math":if(s.action==="remove-advanced-ooxml"){Lu(r,{family:"math",action:s.action,objectId:s.objectId});return}Lu(r,s);return;case"chart":if(s.action==="remove-advanced-ooxml"){Vu(r,{family:"chart",action:s.action,objectId:s.objectId});return}Vu(r,s);return;case"shape":if(s.action==="remove-advanced-ooxml"){Fu(r,{family:"shape",action:s.action,objectId:s.objectId});return}Fu(r,s);return}};return o.addEventListener(os,n),()=>{o.removeEventListener(os,n)}}import{describeSurfaceSelection as Sy}from"@datalking/begonia-engine";import{describeSurfaceSelection as gV}from"@datalking/begonia-engine";function SV(e,t,r){if(!r.target){if(Zt(t,r))return!0;let i=e.preservedRangeSelection;return!!(r.nodeSelectionTarget&&i?.nodeSelectionTarget&&fr(r.nodeSelectionTarget,i.nodeSelectionTarget)&&Zt(t,i))||!!(r.nodeSelectionTarget&&ff(e.state.doc,r.nodeSelectionTarget,t))}if(Zt(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(Zt(t,o))return!0;let n=ft({state:e.state,target:o.target,projectionSnapshot:e.projectionSnapshot,sourceMode:o.projectedMode,revisions:e.revisions,expectedText:o.text,expectedSegmentTexts:o.segmentTexts});return!!(n&&Zt(t,n.selection))}function hV(e,t,r,o,n=null){if(t.empty)return null;let i=Yn(n??Ce(e));return!r.target&&!i?null:{from:Math.min(t.from,t.to),to:Math.max(t.from,t.to),...Or(t)==="backward"?{direction:"backward"}:{},target:r.target?Ot(r.target):null,text:r.text??null,segmentTexts:r.target?ut(e.doc,r.target):null,projectedMode:o,nodeSelectionTarget:i}}function vV(e,t){return Jn(e.target,t.target)&&(e.text??null)===t.text}function bV(e,t){return!e.selection.empty&&e.selection.from===t.from&&e.selection.to===t.to&&(e.selectionInfo.text??null)===t.text}function yV(e){if(!e.preserved.nodeSelectionTarget)return null;let t=ao(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:Me(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode}).text??null,segmentTexts:null,projectedMode:e.projectedMode,nodeSelectionTarget:Yn(e.preserved.nodeSelectionTarget)}:null}function py(e,t){let r=Me(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode});return Ye({selection:gV(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}function Hu(e){if(!e.preserved.target)return null;let t=e.context.projectionSnapshot.projectedMode,r=ft({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=Tc(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=Rc(e.context.state,{...r.selection,...e.preserved.direction?{direction:e.preserved.direction}:{}})??o,s=Me(i,{includeText:!0},{reviewReplacementMode:e.context.reviewReplacementMode});return{from:r.selection.from,to:r.selection.to,...e.preserved.direction?{direction:e.preserved.direction}:{},target:Ot(r.target),text:s.text??e.preserved.text??null,segmentTexts:ut(i.doc,r.target),projectedMode:t,nodeSelectionTarget:Yn(e.preserved.nodeSelectionTarget)}}let n=py(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:Ot(n.selectionInfo.target),text:n.selectionInfo.text??null,segmentTexts:ut(o.doc,n.selectionInfo.target),projectedMode:t,nodeSelectionTarget:Yn(e.preserved.nodeSelectionTarget)}}function fy(e){let t="previous"in e?e.previous:e.preservedRangeSelection;if(!t)return[];if(t.nodeSelectionTarget){let r=yV({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,...my(e,t)]}return my(e,t)}function my(e,t){let r=[],o=e.projectionSnapshot.projectedMode;if(!t.projectedMode&&!o)r.push(t);else if(t.projectedMode&&!o){let n=Hu({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=Hu({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else{let n=Hu({context:e,preserved:t,sourceMode:null});n&&r.push(n)}return r}function zu(e){let t=hV(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&&Ms(t.target,e.previous.target)||e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&Jn(t.target,e.previous.target)&&t.text===e.previous.text?e.previous:t;let r=fy(e),o=r.find(i=>Zt(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?ft({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&&Zt(e.selection,e.previous)?e.previous:null}function wy(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 fy(e)){if(!r&&!SV(e,t,n))continue;let i=Tc(e.state,n);if(!i)continue;let s=py(e,i);if(n.target==null&&fr(Ce(i),n.nodeSelectionTarget)||vV(s.selectionInfo,n)||n.target!=null&&n.projectedMode===e.projectionSnapshot.projectedMode&&bV(s,n)&&(r||e.projectionSnapshot.projectedMode==null)||o&&n.target)return i}if(t.empty){let n=vw(e.state);if(n)return n}return e.state}function gy(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))gy(t);return e}function qu(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?ut(a,l):null,nodeSelectionTarget:r??null,selectionKind:n,projectedMode:i,storyOriginPath:s,documentIdentity:ww(a),documentHash:nn(a),target:t??null};return gy(structuredClone(u))}import{readSyntheticSideStoryDocOriginPath as BV}from"@datalking/begonia-doc-service/v1";function hy(e,t,r){let o=Me(t,r,{reviewReplacementMode:e.reviewReplacementMode}),n=Sy(t),i=Ye({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?ft({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??Ut(t),u=qu(c,d,Ce(t),a,W(t.selection)?"node":"text",e.projectionSnapshot.projectedMode,BV(t.doc),t.doc);return u||null}function xV(e,t){let r=e.preservedRangeSelection;if(!r||!t.empty||e.projectionSnapshot.projectedMode!==null||r.projectedMode==null||!r.target||!Zt(t,r))return null;let o=ft({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=yt(o.selection,r.direction),i=K(e.state,n.anchor,n.head);if(!i)return null;try{return e.state.apply(e.state.tr.setSelection(i))}catch{return null}}function zi(e){let t=Sy(e.state),r=wy(e,t);return r===e.state?xV(e,t)??r:r}function vy(e){return hy(e,e.state,e.selectionInput??{})}function No(e){return hy(e,zi(e),e.selectionInput??{})}import{isDocumentNodePathIndex as CV}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as PV}from"@datalking/begonia-engine";function yy(e){return e==="ooxml_math"||e==="ooxml_chart"||e==="ooxml_shape"||e==="inline_ooxml_drawing"}function By(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.$from.index(o));return r}function RV(e){if(!W(e)||!yy(e.node.type.name))return null;let t=By(e,e.$from.depth);return t.push(e.$from.index(e.$from.depth)),t}function TV(e,t){let r=e;for(let o of t){if(!CV(o)||o>=r.childCount)return null;r=r.child(o)}return r}function by(e,t){let r=TV(e.doc,t);return!!(r&&yy(r.type.name)&&r.marks.some(o=>o.type.name===PV))}function Wu(e){let{selection:t}=e.state;for(let r=t.$from.depth;r>0;r-=1)if(t.$from.node(r).isTextblock)return By(t,r);return null}function Ln(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 Z(){return{source:"browser-ooxml"}}function el(e,t){let r=RV(e.selection);if(!r)return null;let o=t.ooxml.get(r);if(!o)return null;let n=by(e,o.path),i=t.ooxml.getById(o.objectId);if(!i)return n?null:o;let s=by(e,i.path);return n?s?null:i:s?o:i}function qi(e,t){if(t)return el(e.state,t);let r=e,o=Xe(r);return o?el(o.state,r.documentApi):null}function Y(e,t,r){let o=qi(e,t);return o?.family===r?o:null}function J(e){return{changed:!1,reason:`No advanced OOXML ${e} node is selected.`}}function Ku(e,t,r){let o=qi(e,t);return o?e.trackingEnabled?t.ooxml.updateTracked(o.path,r,e.participant,Z()):t.ooxml.update(o.path,r):{changed:!1,reason:"No advanced OOXML node is selected."}}function _u(e,t){let r=qi(e,t);return r?e.trackingEnabled?t.ooxml.removeTracked(r.path,e.participant,Z()):t.ooxml.remove(r.path):{changed:!1,reason:"No advanced OOXML node is selected."}}function Uu(e){return[...new Set((e??[]).map(t=>mt(t)).filter(t=>t.length>0))]}function kV(e,t){let r=Uu(e),o=Uu(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function EV(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 MV(e,t){if(!e||!t)return!1;let r=EV(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 Wi(e){let t=Ge(e.comments),r=jt(e.activeCommentIds,t);if(r.length>0||!e.selection||!e.projectedDocument)return r;let o=Uu((e.comments??[]).map(n=>{let i=e.readTarget(n.id),s=$e(e.projectedDocument,i);return MV(e.selection,s)?n.id:null}).filter(n=>typeof n=="string"));return o.length===1?o:r}function Ki(e,t){return kV(e.activeCommentIds,t)?e:{...e,activeCommentIds:[...t]}}function xy(e){return{left:e.left,top:e.top}}function IV(e){return e.type==="external"?{...e}:{...e}}function tl(e){return e?{...e,position:xy(e.position),resolution:IV(e.resolution)}:null}function AV(e){return{...e}}function NV(e){return{...e,items:e.items.map(AV)}}function OV(e){return{...e,trackedChangeIds:[...e.trackedChangeIds],pointReviewTrackedChangeIds:[...e.pointReviewTrackedChangeIds],pointReviewCommentIds:[...e.pointReviewCommentIds],activeCommentIds:[...e.activeCommentIds],activeMarks:[...e.activeMarks],position:xy(e.position)}}function rl(e){return e?{context:OV(e.context),sections:e.sections.map(NV)}:null}import{listCapabilities as _V}from"@datalking/begonia-document-api/core";import{listCapabilities as DV}from"@datalking/begonia-document-api/core";var Cy=Object.freeze([...DV()].filter(e=>e.mode==="write"&&e.memberPath).map(e=>e.memberPath)),jV=new Set(Cy),VV=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"]),LV=new Set(["byFamily","get","getById","list"]),FV=new Set(["createNode","get","getById","getModel","getModelById","list"]),HV=new Set(["createModelFromText","createNode","get","getById","getModel","getModelById","list"]);function zV(e){return e[e.length-1]??null}function qV(e){return e!=null&&(e==="createNode"||e.startsWith("find")||e.startsWith("get")||e.startsWith("list")||e.startsWith("read"))}function WV(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!LV.has(r);let o=t[2]??null,n=zV(t);return o==="commands"?!1:r==="chart"?n!=null&&!FV.has(n):r==="math"?n!=null&&!HV.has(n):r==="shape"?!qV(n):!1}function Py(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")&&Py(s,a,r,o)}return o}function KV(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 Ry(e){return VV.includes(e)||WV(e)}function Ty(e){return jV.has(e)||Ry(e)}function ky(e){let t=new Set(Cy);for(let r of Py(e))Ry(r)&&t.add(r);return{deniedMemberPaths:t,descendantMemberPaths:KV(t)}}var Iy=new Map([..._V()].filter(e=>e.memberPath).map(e=>[e.memberPath,e.mode])),UV=(()=>{let e=new Set;for(let t of Iy.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 Ey(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 XV(e){return UV.has(e)}function My(e){return Ty(e)?"write":Iy.get(e)??null}function ZV(e){return e==="final"||e==="original"||e==="tracked"?e:null}function GV(e){return!e||typeof e!="object"?null:ZV(e.revisionProjection)}function $V(e){for(let t of e){let r=GV(t);if(r)return r}return null}function ol(e){return{presentationReadApi:e.presentationReadRuntime.documentApi,canonicalReviewApi:e.canonicalReviewRuntime.documentApi,writableRuntimeApi:e.writableRuntime.documentApi}}function Ay(e){let t=new Map,r=(i,s=[])=>{if(My(i)==="write")return e.readWritableApi();let a=$V(s);return a?e.readProjectedApiForMode(a)??e.readPresentationApi():e.readPresentationApi()},o=(i,s=[])=>{let a=Ey(r(i,s),i);return a.value!==void 0||My(i)==="write"?a:Ey(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=XV(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 _i(e){return e.kind!=="revision"&&e.kind!=="revision-decision"}function Ny(e){let t=e?.trim()??"";if(!t)return 0;let r=Date.parse(t);return Number.isFinite(r)?r:0}function YV(e,t,r){let o=Ny(e.sortAt),n=Ny(t.sortAt);return o!==n?r==="asc"?o-n:n-o:e.id.localeCompare(t.id)}function Xu(e,t,r="desc"){let o=new Map(t.filter(_i).map(s=>[s.id,s])),n=e.map(s=>_i(s)?o.get(s.id)??s:s),i=new Set(n.map(s=>s.id));for(let s of t)!_i(s)||i.has(s.id)||(n.push(s),i.add(s.id));return n.sort((s,a)=>YV(s,a,r))}function JV(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 Oy(e,t,r){let o=JV(t,r);return o?e.map(n=>{if(!_i(n))return n;let i=o(n.commentId,n.entryId);return i?{...n,target:i}:n}):e}function QV(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:Xu(s,n.review.timeline(t),t.sort??"desc")}function eL(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:Xu(s,n.review.timelineByObject(e.objectId,t),t.sort??"desc")}function nl(e){let t=e.reviewOptions??{};return Oy(QV(e),e.projectionSnapshot,t)}function Dy(e){let t=e.reviewOptions??{};return Oy(eL(e),e.projectionSnapshot,t)}function Ve(e){return{allowed:!1,reason:e,matchedPermissionIds:[],authorOwned:!1}}function Ui(e,t){return{...e,toggleInternal:Ve("Comments are read-only in the current document mode."),reply:Ve("Comments are read-only in the current document mode."),resolve:Ve(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:Ve(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:Ve("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({...r,edit:Ve("Comments are read-only in the current document mode."),remove:Ve("Comments are read-only in the current document mode.")}))}}function Xi(e){let t=Ve("Tracked changes are read-only in the current document mode.");return{...e,accept:t,reject:t}}function jy(e){return e&&{...e,edit:Ve("Comments are read-only in the current document mode."),remove:Ve("Comments are read-only in the current document mode.")}}function Zu(e,t){return{threadId:e.id,view:{allowed:!0,reason:null,matchedPermissionIds:[],authorOwned:!1},reply:Ve("Comments are read-only in the current document mode."),resolve:Ve(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:Ve(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:Ve("Comments are read-only in the current document mode."),toggleInternal:Ve("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({entryId:r.id,edit:Ve("Comments are read-only in the current document mode."),remove:Ve("Comments are read-only in the current document mode.")}))}}function Gu(e){return{revisionId:e,accept:Ve("Tracked changes are read-only in the current document mode."),reject:Ve("Tracked changes are read-only in the current document mode.")}}function Vy(e,t,r){return e.filter(o=>o.kind==="revision"||o.kind==="revision-decision"?!0:r.enabled&&r.visible)}function Zi(e,t,r){return e.map(o=>o.kind==="revision"?t?o:{...o,permissions:o.permissions?Xi(o.permissions):Gu(o.revisionId)}:o.kind==="revision-decision"?o:r.readOnly?{...o,threadPermissions:o.threadPermissions?Ui(o.threadPermissions,r):Zu(o.comment,r)}:o)}function Ly(e){return{source:e.documentSource,replace(t,r){e.replaceDocument(t,r)}}}function nL(e){let t=Ly(e);return{readDocument(){return e.document},replaceDocument(r,o){t.replace(Pt(e.document,r),o)},documentSource:t.source}}function iL(e,t,r,o){return Object.fromEntries(t.map(n=>{let i=r?e.comments.permissions(n.id,r):o.readOnly?Zu(n,o):null;return[n.id,i&&o.readOnly?Ui(i,o):i]}))}function sL(e,t,r,o){let n=r?e.review.permissions(r):o?[]:t.map(i=>Gu(i.id));return Object.fromEntries(n.map(i=>[i.revisionId,o?i:Xi(i)]))}function aL(e,t){return e.length===0?null:e.some(r=>r.hitId===t)?t:e[0]?.hitId??null}function il(e,t,r={}){let o=nL(e),n=tL(o,{templates:r.templates??void 0,review:{replacementMode:r.replacementMode??"paired"},selection:gc(e,{reviewReplacementMode:r.replacementMode??"paired"})}),i=n.api,s=e.subscribe(()=>t()),a=uy(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 lL(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function Fy(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:w,activeRevisionId:v,activeRevisionIds:C}=e,{surface:R,documentApi:S}=t,B=it(R),{presentationReadApi:h,canonicalReviewApi:y}=ol(r),T=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?T:[],D=y.review.list(),O={actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,includeResolvedComments:p.comments.showResolved,commentVisibility:p.comments.visibility},U=Zi(Vy(nl({projectionSnapshot:r,reviewOptions:O}),p.trackChanges,p.comments),B,p.comments),H=a.query?h.search.query(a.query,a.options):[],le=h.proofing.list(),ne=lL(R),M=R.describeSelection(),N=Xr(R,{includeText:!0},t.replacementMode),V=Ye({selection:M,selectionInfo:N,projectedDocument:We(R),canonicalDocument:r.canonicalDocument,projectedMode:r.projectedMode,revisions:D}),b=No({state:R.state,surfaceEditable:B,surfaceSelectionReliable:ne,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:D,projectionSnapshot:r,preservedRangeSelection:o}),x=zi({state:R.state,surfaceEditable:B,surfaceSelectionReliable:ne,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:D,projectionSnapshot:r,preservedRangeSelection:o}),I=Ct({liveSelection:V.selection,liveSelectionInfo:V.selectionInfo,revisions:D,effectiveSelection:b}),E=!ne&&b?b.selection:V.selection,G=wr(E.trackedChangeIds,I)?E:{...E,trackedChangeIds:[...I]},we=!ne&&b?Fr(b,I):null,ve=we??V.selectionInfo,Ne=Wi({activeCommentIds:ve.activeCommentIds,selection:ne?M:G,projectedDocument:We(R),comments:T,readTarget:h.comments.target}),It=Ki(ve,Ne),Ke=Jo(R.state,It,W(R.state.selection)?"node":"text"),Oe=we??(V.selection.empty&&wr(Ke.activeChangeIds,I)?Ke:V.selection.empty?{...Ke,activeChangeIds:[...I]}:Ke),st=Jg({revisions:D,selectionInfo:Oe,explicitActiveRevisionId:v,explicitActiveRevisionIds:C}),nr=bn({comments:A,selectionInfo:Oe,explicitActiveCommentId:f,explicitActiveCommentIds:w}),Ht=oL(G,t.documentRuntimeKernel.readSnapshot().revision,R.documentStory),Tr=R.canUndo(),kr=R.canRedo(),Er={toolbar:la({selection:Ht,editable:B,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:Tr,canRedo:kr}),comments:A,commentPermissions:iL(h,A,n,p.comments),activeCommentId:nr.activeCommentId,activeCommentIds:nr.activeCommentIds,revisions:D,activeRevisionId:st.activeRevisionId,activeRevisionIds:st.activeRevisionIds,reviewPermissions:sL(y,D,n,B),reviewTimeline:U,reviewTimelineSummary:rL(U),search:{query:a.query,hits:H,activeHitId:aL(H,a.activeHitId)},proofing:{diagnostics:le},advancedOoxml:{selected:el(x,S)},selectionInfo:Oe,selection:Ht,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:tl(i),contextMenu:rl(s),selectionNodeSelectionTarget:ne?null:b?.nodeSelectionTarget??null},ir=ci({getState:()=>Er,readEffectiveSelection:()=>b,surface:R}),L=la({selection:Ht,editable:B,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:Tr,canRedo:kr,commandStates:ir.commands});return{...Er,toolbar:L}}function cL(e){return e.view.dom.parentElement??null}function dL(e){return e.view.dom.ownerDocument?.createElement?.("div")}function Hy(e){e.view.updateRoot?.call(e.view)}function zy(e,t){if(t){if(typeof t.replaceChildren=="function"){t.replaceChildren(e.view.dom),Hy(e);return}typeof t.appendChild=="function"&&(t.appendChild(e.view.dom),Hy(e))}}function qy(e){return!!e}function Wy(e){let{canonicalDocument:t,emit:r,projectionMode:o,readPreservedRangeSelection:n,replacementMode:i="paired",sourceRuntime:s,surfaceFactory:a}=e,l=s.surface,c=cL(l),d=Pt(t,Ie(t,l,o)),u=a({currentSurface:l,collaborative:void 0,documentStory:l.documentStory,editable:!1,element:dL(l),initialContent:d,schema:l.schema,participant:l.participant,trackingEnabled:!1}),m=il(u,r,{replacementMode:i});return zy(u,c),{runtime:m,restore(){zy(l,c)},sync(p,f){let w=Ie(p,l,f);return _r(m.surface.document,w)?!1:(jn({surface:m.surface,nextDocument:w,documentApi:m.documentApi,canonicalReviewApi:s.documentApi,canonicalDocument:p,nextProjectionMode:f,preservedRangeSelection:n?.()??null}),!0)}}}function uL(e,t,r){return r.x>=e.x-1&&r.x<=t.x+1&&r.y>=e.top-1&&r.y<=e.bottom+1}function Ky(e,t){if(!e||e.length===0||!t)return null;let r=new Map;for(let n of e){let i=r.get(n.threadId)??{starts:[],ends:[]};n.edge==="start"?i.starts.push(n):i.ends.push(n),r.set(n.threadId,i)}let o=null;for(let[n,i]of r)for(let s of i.starts)for(let a of i.ends){if(a.x<s.x||!uL(s,a,t))continue;let l=a.x-s.x;(o==null||l<o.width||l===o.width&&s.x>o.startX)&&(o={threadId:n,width:l,startX:s.x})}return o?.threadId??null}function _y(e){if(!e)return[];let t=[],r=(o,n)=>{let i=e.querySelectorAll(o);for(let s=0;s<i.length;s+=1){let a=i[s];if(!a)continue;let l=a.getAttribute("data-thread-id");if(typeof l!="string"||l.length===0)continue;let c=a.getBoundingClientRect();t.push({threadId:l,edge:n,x:c.left,top:c.top,bottom:c.bottom})}};return r("[data-ald-comment-range-start]","start"),r("[data-ald-comment-range-end]","end"),t}function Uy(e){return t=>{let r=t.target;if(!jo(r))return;let n=r.closest("[data-thread-id]")?.getAttribute("data-thread-id");if(typeof n=="string"&&n.length>0){e.getController().setActiveComment(n);return}let i=r.closest("p, li, td, th, h1, h2, h3, h4, h5, h6");if(!i)return;let s=_y(i);if(s.length===0)return;let a=Ky(s,{x:t.clientX,y:t.clientY});a&&e.getController().setActiveComment(a)}}function $u(e,t,r,o={}){let n=Wu(e);return n?t.ooxml.math.appendInline(n,r,o):{changed:!1,reason:"Advanced OOXML math insertion requires an active text block selection."}}function Yu(e,t,r,o={},n={}){let i=Wu(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 Ju(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.replaceModelByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.math.replaceModelById(o.objectId,r):J("math")}function Qu(e,t,r,o){let n=Y(e,t,"math");return n?e.trackingEnabled?t.ooxml.math.setPlainTextByIdTracked(n.objectId,r,e.participant,Z(),o):t.ooxml.math.setPlainTextById(n.objectId,r,o):J("math")}function em(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.setDisplayModeByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.math.setDisplayModeById(o.objectId,r):J("math")}function tm(e,t,r,o={}){return t.ooxml.charts.insertBlock(Ln(e,t),r,o)}function rm(e,t,r,o={},n={}){return t.ooxml.charts.insertBlockTracked(Ln(e,t),r,e.participant,o,n)}function om(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.replaceModelByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.replaceModelById(o.objectId,r):J("chart")}function nm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setMetadataByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setMetadataById(o.objectId,r):J("chart")}function im(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTitleByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setTitleById(o.objectId,r):J("chart")}function sm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTextBodyByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setTextBodyById(o.objectId,r):J("chart")}function am(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.appendSeriesByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.appendSeriesById(o.objectId,r):J("chart")}function lm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setSeriesListByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setSeriesListById(o.objectId,r):J("chart")}function cm(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.setSeriesByIdTracked(n.objectId,r,o,e.participant,Z()):t.ooxml.charts.setSeriesById(n.objectId,r,o):J("chart")}function dm(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertSeriesByIdTracked(n.objectId,r,e.participant,Z(),o):t.ooxml.charts.upsertSeriesById(n.objectId,r,o):J("chart")}function um(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeSeriesByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.removeSeriesById(o.objectId,r):J("chart")}function mm(e,t,r){return sl(e,t,r)}function pm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setAxesByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setAxesById(o.objectId,r):J("chart")}function sl(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertAxisByIdTracked(n.objectId,r,e.participant,Z(),o):t.ooxml.charts.upsertAxisById(n.objectId,r,o):J("chart")}function fm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeAxisByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.removeAxisById(o.objectId,r):J("chart")}function wm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setLegendByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setLegendById(o.objectId,r):J("chart")}function gm(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setPlotAreaByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.charts.setPlotAreaById(o.objectId,r):J("chart")}function Sm(e,t,r,o={}){return t.ooxml.shapes.insertBlock(Ln(e,t),r,o)}function hm(e,t,r,o={},n={}){return t.ooxml.shapes.insertBlockTracked(Ln(e,t),r,e.participant,o,n)}function vm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.replaceModelByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.replaceModelById(o.objectId,r):J("shape")}function bm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setMetadataByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setMetadataById(o.objectId,r):J("shape")}function ym(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWatermarkByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setWatermarkById(o.objectId,r):J("shape")}function Bm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTextBodyByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setTextBodyById(o.objectId,r):J("shape")}function xm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setGeometryByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setGeometryById(o.objectId,r):J("shape")}function Cm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTransformByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setTransformById(o.objectId,r):J("shape")}function Pm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setFillByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setFillById(o.objectId,r):J("shape")}function Rm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setStrokeByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setStrokeById(o.objectId,r):J("shape")}function Tm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setAnchorByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setAnchorById(o.objectId,r):J("shape")}function km(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setConnectorByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setConnectorById(o.objectId,r):J("shape")}function Em(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setPictureByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setPictureById(o.objectId,r):J("shape")}function Mm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWordArtByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setWordArtById(o.objectId,r):J("shape")}function Im(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setChildrenByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.setChildrenById(o.objectId,r):J("shape")}function Am(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.setChildByIdTracked(n.objectId,r,o,e.participant,Z()):t.ooxml.shapes.setChildById(n.objectId,r,o):J("shape")}function Nm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.appendChildByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.appendChildById(o.objectId,r):J("shape")}function Om(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.appendChildToParentByIdTracked(n.objectId,r,o,e.participant,Z()):t.ooxml.shapes.appendChildToParentById(n.objectId,r,o):J("shape")}function Dm(e,t,r,o={}){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.moveChildByIdTracked(n.objectId,r,e.participant,Z(),o):t.ooxml.shapes.moveChildById(n.objectId,r,o):J("shape")}function jm(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.removeChildByIdTracked(o.objectId,r,e.participant,Z()):t.ooxml.shapes.removeChildById(o.objectId,r):J("shape")}import{isDocumentNodePathIndex as mL}from"@datalking/begonia-document-model";import{NodeSelection as pL}from"prosemirror-state";function Vm(e,t){return W(e.selection)&&e.selection.node.type.name===`ooxml_${t.family}`&&e.selection.node.attrs.objectId===t.objectId}function fL(e,t){let r=e,o=-1;for(let n of t){if(!mL(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 wL(e,t){let r=fL(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 Xy(e,t){if(!t||Vm(e,t))return e;let r=wL(e.doc,t);if(r==null)return null;let o=dt(e,pL.create(e.doc,r));if(!o)return null;if(Xt(e.selection,o))return e;try{return e.apply(e.tr.setSelection(o))}catch{return null}}function gL(e,t){return new Proxy(e,{get(r,o,n){return o==="state"?t:Reflect.get(r,o,n)}})}function SL(e,t){if(!t||Vm(e.surface.state,t))return e;let r=e.surface.view?.state,o=r?Xy(r,t):null;if(r&&o&&(o!==r&&e.surface.view.dispatch(r.tr.setSelection(o.selection)),Vm(e.surface.state,t)))return e;let n=Xy(e.surface.state,t);return!n||n===e.surface.state?e:{...e,surface:gL(e.surface,n)}}function hL(e){return!!(e&&typeof e=="object"&&"changed"in e&&e.changed===!0)}function Zy(e){let t=o=>{let n=e.getRuntime(),i=er(n.surface);return i?q(i):e.runAndEmit(()=>o(n))},r=o=>t(n=>o(SL(n,e.readState().advancedOoxml.selected)));return{appendMathToCurrentTextblock(o,n={}){return t(i=>$u(i.surface,i.documentApi,o,n))},appendMathToCurrentTextblockTracked(o,n={},i={}){return t(s=>Yu(s.surface,s.documentApi,o,n,i))},insertChartAfterCurrentBlock(o,n={}){return t(i=>tm(i.surface,i.documentApi,o,n))},insertChartAfterCurrentBlockTracked(o,n={},i={}){return t(s=>rm(s.surface,s.documentApi,o,n,i))},insertShapeAfterCurrentBlock(o,n={}){return t(i=>Sm(i.surface,i.documentApi,o,n))},insertShapeAfterCurrentBlockTracked(o,n={},i={}){return t(s=>hm(s.surface,s.documentApi,o,n,i))},updateSelectedAdvancedOoxml(o){return r(n=>Ku(n.surface,n.documentApi,o))},removeSelectedAdvancedOoxml(){return r(o=>{let n=_u(o.surface,o.documentApi);return hL(n)&&e.clearPreservedRangeSelection(),n})},replaceSelectedMathModel(o){return r(n=>Ju(n.surface,n.documentApi,o))},setSelectedMathPlainText(o,n){return r(i=>Qu(i.surface,i.documentApi,o,n))},setSelectedMathDisplayMode(o){return r(n=>em(n.surface,n.documentApi,o))},replaceSelectedChartModel(o){return r(n=>om(n.surface,n.documentApi,o))},setSelectedChartMetadata(o){return r(n=>nm(n.surface,n.documentApi,o))},setSelectedChartTitle(o){return r(n=>im(n.surface,n.documentApi,o))},setSelectedChartTextBody(o){return r(n=>sm(n.surface,n.documentApi,o))},appendSelectedChartSeries(o){return r(n=>am(n.surface,n.documentApi,o))},setSelectedChartSeriesList(o){return r(n=>lm(n.surface,n.documentApi,o))},setSelectedChartSeries(o,n){return r(i=>cm(i.surface,i.documentApi,o,n))},upsertSelectedChartSeries(o,n){return r(i=>dm(i.surface,i.documentApi,o,n))},removeSelectedChartSeries(o){return r(n=>um(n.surface,n.documentApi,o))},appendSelectedChartAxis(o){return r(n=>mm(n.surface,n.documentApi,o))},setSelectedChartAxes(o){return r(n=>pm(n.surface,n.documentApi,o))},upsertSelectedChartAxis(o,n){return r(i=>sl(i.surface,i.documentApi,o,n))},removeSelectedChartAxis(o){return r(n=>fm(n.surface,n.documentApi,o))},setSelectedChartLegend(o){return r(n=>wm(n.surface,n.documentApi,o))},setSelectedChartPlotArea(o){return r(n=>gm(n.surface,n.documentApi,o))},replaceSelectedShapeModel(o){return r(n=>vm(n.surface,n.documentApi,o))},setSelectedShapeMetadata(o){return r(n=>bm(n.surface,n.documentApi,o))},setSelectedShapeWatermark(o){return r(n=>ym(n.surface,n.documentApi,o))},setSelectedShapeTextBody(o){return r(n=>Bm(n.surface,n.documentApi,o))},setSelectedShapeGeometry(o){return r(n=>xm(n.surface,n.documentApi,o))},setSelectedShapeTransform(o){return r(n=>Cm(n.surface,n.documentApi,o))},setSelectedShapeFill(o){return r(n=>Pm(n.surface,n.documentApi,o))},setSelectedShapeStroke(o){return r(n=>Rm(n.surface,n.documentApi,o))},setSelectedShapeAnchor(o){return r(n=>Tm(n.surface,n.documentApi,o))},setSelectedShapeConnector(o){return r(n=>km(n.surface,n.documentApi,o))},setSelectedShapePicture(o){return r(n=>Em(n.surface,n.documentApi,o))},setSelectedShapeWordArt(o){return r(n=>Mm(n.surface,n.documentApi,o))},setSelectedShapeChildren(o){return r(n=>Im(n.surface,n.documentApi,o))},setSelectedShapeChild(o,n){return r(i=>Am(i.surface,i.documentApi,o,n))},appendSelectedShapeChild(o){return r(n=>Nm(n.surface,n.documentApi,o))},appendSelectedShapeChildToParent(o,n){return r(i=>Om(i.surface,i.documentApi,o,n))},moveSelectedShapeChild(o,n={}){return r(i=>Dm(i.surface,i.documentApi,o,n))},removeSelectedShapeChild(o){return r(n=>jm(n.surface,n.documentApi,o))}}}function al(e){let t=Cn({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 Gy(e,t){let r=t.readEffectiveSelection();return{selectionCapture:r,resolvedSelectionCapture:r,stale:!1}}function Gi(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 vL(e,t){return e.selectionCapture?Gi(e,t,e.selectionCapture):e.pointSelectionCapture?Gi(e,t,e.pointSelectionCapture):Gy(e,t)}function bL(e,t){let r=e.actionSelectionCapture??e.selectionCapture??null;if(!r)return e.pointSelectionCapture?{...Gi(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...Gy(e,t),restoreSelection:!1};let o=Gi(e,t,r);return e.pointSelectionCapture===r?{...o,restoreSelection:!1}:o.resolvedSelectionCapture&&!o.resolvedSelectionCapture.selection.empty?{...o,restoreSelection:!0}:e.pointSelectionCapture&&e.pointSelectionCapture!==r?{...Gi(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...o,restoreSelection:!0}}function Lm(e,t){let r=t??e.controller;if(!r)throw new Error("Browser context-menu selection policy requires a selection controller.");return{effectiveSelection:vL(e,r),actionSelection:bL(e,r)}}function yL(e=""){return typeof window>"u"?null:window.prompt("Enter link URL",e)}function BL(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 xL(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 $y(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=>!xL(r,i))}function CL(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 Yy(e,t,r){let{hasSelection:o,trackedChangeIds:n}=e,i=Xe(t);if(n.length===0)return;let s=t.readEffectiveSelection({includeText:!0}),a=e.actionSelectionCapture??e.selectionCapture,l=t.getState().revisions,c=Bc(s,a,l),d=!c&&a?t.readSelectionCapture(a,{includeText:!0}):null,u=CL(e,a,d),m=d?Bc(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&&$y(e,t,u)){rt(i,u,p=>r==="accept"?p.acceptSelectionRevisions?.()??!1:p.rejectSelectionRevisions?.()??!1,{restoreSelection:!1});return}if(!(u&&!u.selection.empty&&$y(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 Mt(e,t){let r=Lm(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=Xe(t);return o?pr({editable:e.isEditable},o.state,r.resolvedSelectionCapture):"Live editor surface is unavailable for inline formatting."}function Fm(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 Jy(e){return Fm(e)==null}function PL(e,t){let r=Xe(t),{effectiveSelection:o,actionSelection:n}=Lm(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:()=>Mt(e,t)==null,disabledReason:()=>Mt(e,t)},{id:"italic",label:"Italic",action:()=>{n.stale||$t(t,"italic",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Mt(e,t)==null,disabledReason:()=>Mt(e,t)},{id:"underline",label:"Underline",action:()=>{n.stale||$t(t,"underline",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Mt(e,t)==null,disabledReason:()=>Mt(e,t)},{id:"strikethrough",label:"Strikethrough",action:()=>{n.stale||$t(t,"strike",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Mt(e,t)==null,disabledReason:()=>Mt(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=yL(s);try{c&&t.setLinkFromHandle(l,c,null,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}},enabledWhen:()=>Mt(e,t)==null,disabledReason:()=>Mt(e,t)},{id:"clear-link",label:"Clear link",showWhen:()=>i,enabledWhen:()=>Mt(e,t)==null,disabledReason:()=>Mt(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:Jy,disabledReason:Fm,action:()=>Yy(e,t,"accept")},{id:"reject-change",label:e.trackedChangeIds.length===1?"Reject change":"Reject changes",tone:"danger",enabledWhen:Jy,disabledReason:Fm,action:()=>Yy(e,t,"reject")}]}),a}function RL(e,t,r){return r?null:typeof e.disabledReason=="function"?e.disabledReason(t)??"Action unavailable.":e.disabledReason??"Action unavailable."}function Fn(e,t,r){let o=r??cv(e.host)??e.controller??null,n=t?.includeDefaultItems===!1||!o?[]:PL(e,o),i=BL(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:RL(c,e,d)}});return{id:a.id,label:a.label,items:l}}).filter(a=>a.items.length>0)}function TL(e){let t=e.pointSelection?.capture.selection.from??null,r=Dt(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 $i(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=TL({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?Dt(e.pointSelection?.capture,t.revisions):Ct({liveSelection:na(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:t.revisions,effectiveSelection:i??e.effectiveSelection});return Oa(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 kL(e,t){let r=be(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 $i({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 EL(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=K(e,o,o);if(!n)return e;try{return e.apply(e.tr.setSelection(n))}catch{return e}}function Qy(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(!cp(m)){o();return}let p=l(),f=s();d.preventDefault(),d.stopPropagation(),Na(p.surface,m);let w=()=>o(),v=u.links?.popoverResolver?.({host:Ro(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:w})??{type:"default"};if(v.type==="none"){o();return}c(Pv(Ro(i()),p.surface,f,m,d.clientX,d.clientY,v),t(EL(p.surface.state))),r(),n()}}function eB(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=be(m),f=m.captureEffectiveSelection({includeText:!0}),w=m.captureEffectiveSelection()??f,v=al({surface:p,clientX:d.clientX,clientY:d.clientY,captureSelectionFromState:l}),C=a(),R=$i({controller:m,documentMode:i(),reviewActionsEnabled:C.enabled,effectiveSelection:f,actionSelectionCapture:w,pointSelection:v,clientX:d.clientX,clientY:d.clientY}),S=Fn(R,u.contextMenu,m);if(S.length===0){t();return}c({context:R,sections:S}),o()}}function tB(e){return al({surface:e.surface,clientX:e.pointSelectionInput.clientX,clientY:e.pointSelectionInput.clientY,captureSelectionFromState:e.captureSelectionFromState})?.capture??null}function rB(e){let{context:t,readProjectionSnapshot:r,readState:o,selectionCaptureTracker:n}=e,i=(R,S={},B=null)=>{let h=$(t),y=r();return{state:R,surfaceEditable:it(h.surface),surfaceSelectionReliable:Lv(h.surface),selectionInput:S,reviewReplacementMode:h.replacementMode,revisions:y.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:y,preservedRangeSelection:B}},s=(R,S={})=>vy(i(R,S)),a=(R,S={})=>{let B=$(t);return n.track(B.surface,R,s(R,S))},l=(R,S={},B=null)=>{let h=$(t),y=i(R,S,B);return n.track(h.surface,zi(y),No(y))},c=(R,S={},B=null)=>No(i(R,S,B)),d=(R={})=>{let S=$(t);return S.surface.consumeHistoryChange?.()&&(t.preservedRangeSelection=null),o(),{selectionInput:R,runtime:S,preservedRangeSelection:t.preservedRangeSelection}};return{captureSelection:(R={})=>a($(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 tB({surface:S.runtime.surface,pointSelectionInput:R,captureSelectionFromState:B=>l(B,S.selectionInput,S.preservedRangeSelection)})},readPointSelection:R=>{let S=d(R);return tB({surface:S.runtime.surface,pointSelectionInput:R,captureSelectionFromState:B=>c(B,S.selectionInput,S.preservedRangeSelection)})},readSelectionCapture:(R,S={})=>{if(!R)return null;let B=$(t),h=n.resolveState(B.surface,R);return h?s(h,S):null},resolveSelectionCapture:(R,S={})=>{if(!R)return null;let B=$(t),h=n.resolveState(B.surface,R);return h?n.track(B.surface,h,s(h,S)):null}}}import{documentWideMutationEffect as NL}from"@datalking/begonia-editor-contracts";function Hm(e,t,r={}){return il(e,t,r)}function oB(e,t,r=e.replacementMode){if(e.replacementMode===r)return e;let o=e.surface;return e.release(),Hm(o,t,{replacementMode:r,templates:e.templatesAdapter})}function nB(e,t,r){r(e.surface),e.release(),t&&e.surface.destroy()}function iB(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:Bn(o),initialContent:Pt(t,t.copy(t.content)),schema:i.surface.schema,participant:i.surface.participant,trackingEnabled:zr(o,a)})}function sB(e){return vt(e)??_n}function ML(e){return sB(e)/100}function IL(e){return e.view?.dom??null}function AL(e){if(e.style)return e.style;let t={};return e.style=t,t}function zm(e,t){let r=IL(e);if(!r)return;let o=sB(t),n=String(ML(o)),i=AL(r);r.dataset.aldZoomPercent=String(o),i.zoom=n,i.transformOrigin="top left"}function aB({context:e,templates:t,ownsSurface:r,surfaceFactory:o,allowCollaborativeProjection:n,emit:i,readCurrentDisplayState:s,clearEphemeralOverlays:a,handleLinkClick:l,handleCommentClick:c,handleContextMenu:d}){let u=new WeakMap,m=null,p=null,f=()=>{m?.dispose(),m=null,p=null},w=M=>((!m||p!==M)&&(f(),m=iS(()=>e.readModel.canonicalDocument,M,Ae(e).documentRuntimeKernel.documentSource),p=M),m),v=M=>{let N=Ae(e),V=ko(e.readModel),b=V?w(M):N.documentRuntimeKernel.projections;V||f(),e.readModel=Ei(e.readModel,b,M)},C=()=>e.readModel.projectedRuntimeBank?.resolveRuntime("tracked").documentApi??null,R=M=>{M.addEventListener("click",l),M.addEventListener("click",c),M.addEventListener("contextmenu",d)},S=M=>{M.removeEventListener("click",l),M.removeEventListener("click",c),M.removeEventListener("contextmenu",d)},B=M=>{let N=M.view?.dom;if(!N)return;let V=u.get(M);V&&V!==N&&S(V),R(N),u.set(M,N);let b=s();ud(M,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,b.trackChanges,b.comments)},h=M=>{let N=u.get(M)??M.view?.dom??null;N&&(S(N),u.delete(M))},y=()=>{let M=e.readModel.collaborativeProjection;if(!M){e.readModel=Mi(e.readModel);return}let N=Ae(e),V=Ao({surface:M.runtime.surface,nextDocument:N.surface.document,documentApi:M.runtime.documentApi,canonicalReviewApi:C(),canonicalDocument:N.surface.document,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection});a(),h(M.runtime.surface),M.restore(),Hi({surface:N.surface,target:V,documentApi:N.documentApi}),M.runtime.release(),M.runtime.surface.destroy(),e.readModel=Nn(Mi(e.readModel))},T=M=>{let N=Ae(e);if(N.replacementMode!==M){let V=oB(N,A,M);e.readModel=du(e.readModel,V,M),e.readModel=Nn(e.readModel)}v(M),e.readModel.collaborativeProjection&&e.readModel.collaborativeProjection.runtime.replacementMode!==M&&y()},A=()=>{let M=Ae(e);D(M);let N=s(),V=aa(M.surface,e.documentMode,N.trackChanges,n());if(ko(e.readModel)&&V){let b=Ie(e.readModel.canonicalDocument,M.surface,V);if(!_r(M.surface.document,b)){e.readModel=uu(e.readModel,M.surface.document);let x=Ie(e.readModel.canonicalDocument,M.surface,V);if(!_r(M.surface.document,x)){jn({surface:M.surface,nextDocument:x,documentApi:M.documentApi,canonicalReviewApi:C(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:V,preservedRangeSelection:e.preservedRangeSelection});return}}}else e.readModel=Nn(e.readModel);if(e.readModel.collaborativeProjection&&V){e.readModel.collaborativeProjection.sync(e.readModel.canonicalDocument,V)||i();return}e.documentMode==="viewing"&&N.trackChanges.enabled&&N.trackChanges.mode==="review"&&Qa({surface:M.surface,canonicalReviewApi:C(),canonicalDocument:e.readModel.canonicalDocument,projectedMode:V})||i()},D=(M=Ae(e))=>{let N=ur(M.documentApi.preferences.get());zm(M.surface,N);let V=e.readModel.activeRuntime;V&&V.surface!==M.surface&&zm(V.surface,N)},O=()=>{let M=s();T(M.trackChanges.replacements);let N=Ae(e),V=aa(N.surface,e.documentMode,M.trackChanges,n()),b=Bn(e.documentMode),x=zr(e.documentMode,M.trackChanges),I=hn(N.surface)?!1:b;if(e.readModel=Nn(e.readModel),N.surface.editable!==I&&N.surface.setEditable(I),N.surface.trackingEnabled!==x&&N.surface.setTrackingEnabled(x),V&&N.surface.collaborative&&o){if(ko(e.readModel)&&(_r(N.surface.document,e.readModel.canonicalDocument)||N.surface.replaceDocument(Pt(N.surface.document,e.readModel.canonicalDocument),{origin:"system",intent:"restore-canonical-projection-document",effects:[NL("review")]}),e.readModel=Mi(e.readModel),v(M.trackChanges.replacements)),!e.readModel.collaborativeProjection){a();let we=Ie(e.readModel.canonicalDocument,N.surface,V),ve=Ao({surface:N.surface,nextDocument:we,documentApi:N.documentApi,canonicalReviewApi:C(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:V,preservedRangeSelection:e.preservedRangeSelection}),Ne=Wy({sourceRuntime:N,surfaceFactory:o,canonicalDocument:e.readModel.canonicalDocument,projectionMode:V,emit:i,readPreservedRangeSelection:()=>e.preservedRangeSelection,replacementMode:M.trackChanges.replacements});Hi({surface:Ne.runtime.surface,target:ve,documentApi:Ne.runtime.documentApi}),B(Ne.runtime.surface),e.readModel=Av(e.readModel,Ne)}e.readModel.collaborativeProjection?.sync(e.readModel.canonicalDocument,V)}else if(e.readModel.collaborativeProjection&&y(),V){let we=Ie(e.readModel.canonicalDocument,N.surface,V);e.readModel=Iv(e.readModel),v(M.trackChanges.replacements),_r(N.surface.document,we)||jn({surface:N.surface,nextDocument:we,documentApi:N.documentApi,canonicalReviewApi:C(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:V,preservedRangeSelection:e.preservedRangeSelection})}else ko(e.readModel)&&(_r(N.surface.document,e.readModel.canonicalDocument)||jn({surface:N.surface,nextDocument:e.readModel.canonicalDocument,documentApi:N.documentApi,canonicalReviewApi:C(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection}),e.readModel=Mi(e.readModel),v(M.trackChanges.replacements));let E=e.readModel.activeRuntime??N;D(N);let G=hn(E.surface)?!1:b;E.surface.editable!==G&&E.surface.setEditable(G),E.surface.trackingEnabled!==x&&E.surface.setTrackingEnabled(x),ud(E.surface,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,M.trackChanges,M.comments)},U=M=>{let N=yn(e.documentMode,e.resolvedModules.trackChanges).replacements;e.readModel=du(e.readModel,Hm(M,A,{replacementMode:N,templates:t}),N),e.readModel=Nn(e.readModel),v(N),B(M),D()},H=M=>{f(),e.readModel=Ei(e.readModel,null),nB(Ae(e),M,h),e.readModel=Nv(e.readModel)};return{destroyCollaborativeProjection:y,handleSourceRuntimeUpdate:A,applySurfaceDisplayState:O,mountSourceRuntime:U,unmountSourceRuntime:H,createReplacementSurface:(M,N)=>{if(!o)throw new Error("Browser editor cannot reconfigure collaboration without a managed surface factory.");let V=s();return iB({surfaceFactory:o,sourceRuntime:Ae(e),canonicalDocument:e.readModel.canonicalDocument,documentMode:e.documentMode,trackChanges:V.trackChanges,collaborative:M,nextSurfaceSession:N})},swapSurface:(M,N)=>{let V=s(),b=aa(M,e.documentMode,V.trackChanges,n()),x=Ao({surface:$(e).surface,nextDocument:Ie(e.readModel.canonicalDocument,M,b),documentApi:$(e).documentApi,canonicalReviewApi:C(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:b,preservedRangeSelection:e.preservedRangeSelection});a(),y(),H(r||!!o),e.collaborationSession=N,U(M),O(),Hi({surface:$(e).surface,target:x,documentApi:$(e).documentApi})}}}function lB(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,w=u?null:e.resolveSelectionState(r),v=a.length>0||s.length>0,C=u?c:l,R=!u&&v?d??C:C,B=(!u&&v&&i.length>1?p?.selection??null:null)??R?.selection??C?.selection??null,h=u?Dt(c,e.revisions):Ct({liveSelection:e.liveSelection,liveSelectionInfo:e.liveSelectionInfo,revisions:e.revisions,effectiveSelection:R}),y=Oa(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: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??w??void 0}),T=Fn(y,e.contextMenuOptions,e.controller);return T.length>0?{context:y,sections:T}:null}function cB(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 dB(e){return{releaseContextMenuCaptures(t,r=null){cB({currentState:t,nextState:r,untrack:e})},untrackCapture:e}}function uB(e){let{closeContextMenu:t,closeLinkPopover:r,emit:o,getController:n,getDocumentMode:i,getResolvedModules:s,readTrackChangesDisplayState:a,setContextMenu:l}=e;return c=>{if(!c||typeof c.clientX!="number"||typeof c.clientY!="number")return!1;let d=s();if(d.contextMenu?.enabled===!1)return!1;r();let u=n(),m=u.captureEffectiveSelection({includeText:!0}),p=u.captureEffectiveSelection()??m;if(!m&&!p)return t(),!1;let f=$i({controller:u,documentMode:i(),reviewActionsEnabled:a().enabled,effectiveSelection:m,actionSelectionCapture:p,pointSelection:null,clientX:c.clientX,clientY:c.clientY}),w=Fn(f,d.contextMenu,u);return w.length===0?(t(),!1):(l({context:f,sections:w}),o(),!0)}}function mB(e){return Ye({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 QL}from"@datalking/begonia-document-api/v1";import{createTrackChangesFacade as e0,summarizeReviewTimeline as xB}from"@datalking/begonia-document-api/review";import{describeCapability as HL,planStepMode as zL,resolvePlanStepFailureReason as qL,resolveUnsupportedPlanStepReason as WL}from"@datalking/begonia-document-api/core";import{documentWideMutationEffect as KL}from"@datalking/begonia-editor-contracts";import{preserveNodeSymbolMetadata as OL}from"@datalking/begonia-engine";import{sameCommittedDocument as DL}from"@datalking/begonia-document-model";import{createDocumentChange as jL,createDocumentChangePublisher as VL}from"@datalking/begonia-editor-contracts";function qm(e){let t=e,r=0,o=VL();return{readDocument(){return t},replaceDocument(n,i={origin:"api"}){let s=OL(t,n);if(DL(t,s)){t=s;return}let a=r;t=s,r+=1,o.publish(jL(a,r,i))},readProjectedDocument(){return t},documentSource:{readSnapshot(){return{document:t,revision:r}},subscribeDocument(n){return o.subscribe(n)}}}}function LL(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 Yi(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:LL(n)}}function FL(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Wm(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&&FL(e.revisionIds,t.revisionIds)&&e.historyRevision===t.historyRevision&&e.textLength===t.textLength&&e.documentHash===t.documentHash}function Km(e,t){return t.filter(r=>!e.includes(r))}function pB(e){return e==="sequential"?"sequential":"all_or_nothing"}function Ji(e){return e??null}import{createDocumentRuntimeKernel as fB}from"@datalking/begonia-document-api/v1";function _L(e,t){let r=qm(t),o=fB(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 UL(e,t){let r=_L(e,e.surface.document),o=t.canonicalDocument??e.surface.document,n=qm(o),i=fB(n,{review:{replacementMode:r.replacementMode}}),s=Ei({...Va(o,r.replacementMode),sourceRuntime:r,activeRuntime:r},i.projections,r.replacementMode);return{detachedRuntime:r,projectionSnapshot:Zr(s,t.projectedMode)}}function XL(e){let t=e.getRuntime(),r=e.readCurrentDisplayState(),o=e.readProjectionSnapshot(),{detachedRuntime:n,projectionSnapshot:i}=UL(t,o);return{detachedRuntime:n,api:e.createDocumentApi({getRuntime:()=>n,hasSourceRuntime:()=>!0,readProjectionSnapshot:()=>i,readCurrentDisplayState:()=>r})}}function wB(e){let t=o=>{let n=XL(e),{api:i}=n,s=pB(o.commitMode),a=Yi(i),l=i.info().revision;if(o.expectedRevision!=null&&o.expectedRevision!==l)return{detachedRuntime:n.detachedRuntime,receipt:{label:Ji(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:Ji(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 w=HL(f.operationId),v=Yi(i),C=Ji(f.label),R=WL(f.operationId,w),S=zL(w);if(R){if(d=!1,c.push({index:p,label:C,operationId:f.operationId,resolvedOperationId:w?.id??null,mode:S,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}),h=Yi(i),y=S==="write"&&!Wm(v,h),T=B.ok?qL(B.value):null;if(!B.ok||T){if(d=!1,c.push({index:p,label:C,operationId:f.operationId,resolvedOperationId:w?.id??null,mode:S,ok:!1,changed:!1,error:B.ok?T:B.error.message,...B.ok?{result:B.value}:{},revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}c.push({index:p,label:C,operationId:f.operationId,resolvedOperationId:w?.id??null,mode:S,ok:!0,changed:y,result:B.value,revisionIdsCreated:Km(v.revisionIds,h.revisionIds),revisionIdsRemoved:Km(h.revisionIds,v.revisionIds)})}let m=Yi(i);return{detachedRuntime:n.detachedRuntime,receipt:{label:Ji(o.label),preview:!0,executable:d,changed:!Wm(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:[KL("structure")]}),{...i,preview:!1,committed:s}}}}function gB(e){let t=e.subscribeStateChange??e.subscribeRawSelectionChange??null;return{onChange(r){if(!t)return()=>{};let o=!1,n=!1,i=Gn(e.readSelectionInfo()),s=()=>{if(n=!1,o)return;let d=e.readSelectionInfo(),u=Gn(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 ZL(e){let t=e.surface.view;return!!(t?.state&&typeof t.dispatch=="function")}function GL(e,t){let r=[...e??[]],o=[...t??[]];return r.length===o.length&&r.every((n,i)=>n===o[i])}function $L(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function SB(e){return e?.kind==="text"?e.segments.length:0}function YL(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 hB(e,t){return ce([...e.activeChangeIds,...e.selection.trackedChangeIds??[]],t)}function vB(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?YL(i):!1})}function bB(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(),w=ZL(f),v=f.surface.describeSelection(),C=W(f.surface.state.selection)?"node":"text",R=i().review.list(),S=r(),B=Ye({selection:v,selectionInfo:d,projectedDocument:We(f.surface),canonicalDocument:S.canonicalDocument,projectedMode:S.projectedMode,revisions:R}),h=Ki(B.selectionInfo,Wi({activeCommentIds:B.selectionInfo.activeCommentIds,selection:v,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),y=Jo(f.surface.state,h,C);if(p){let T=Ct({liveSelection:B.selection,liveSelectionInfo:h,revisions:R,effectiveSelection:p}),A=hB(p,R),D=rd({liveSelection:B.selection,liveActiveChangeIds:h.activeChangeIds,effectiveSelection:p}),O=Ki(Fr(p,A),Wi({activeCommentIds:p.activeCommentIds,selection:p.selection,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),U=vB(A,R),H=!U&&p.projectedMode!=null,le=!U&&SB(p.selectionTarget)>SB(y.target),ne=!U&&((O.text??null)!==(y.text??null)||!$L(O.target,y.target)||!GL(O.activeMarks,y.activeMarks));return B.selection.empty&&!p.selection.empty&&(p.activeCommentIds.length>0||A.length>0)&&(p.activeCommentIds.length>0||H||le||ne||!w)?O:w?!D&&B.selection.empty&&!wr(h.activeChangeIds,T)?{...y,activeChangeIds:[...T]}:y:O}return y};return{resolvePublicSelectionInfo:l,readPublicSelectionInfo:(d={includeText:!0})=>{let u=t();return l(Xr(u.surface,d,u.replacementMode),d)}}}function JL(e){return()=>q(e)}function yB(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"?JL(r):u:o.descendantMemberPaths.has(p)?yB(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 BB(e,t){return yB(e,"",t,ky(e),new WeakMap)}function Ft(e,t){return er(e.surface)??(t.comments.readOnly?"Comments are read-only in the current document mode.":null)}function CB(e,t){return t.comments.allowResolve?Ft(e,t):"Comment resolution is disabled."}function _m(e){let{getRuntime:t,hasSourceRuntime:r,readCurrentDisplayState:o,readProjectionSnapshot:n}=e,{readEffectiveSelection:i,captureEffectiveSelection:s,subscribeStateChange:a}=e,l=new WeakMap,c=()=>n(),d=()=>ol(c()),u=()=>d().presentationReadApi,m=()=>d().canonicalReviewApi,p=()=>d().writableRuntimeApi,f=()=>er(t().surface),w=()=>it(t().surface),v=b=>{let x=c();return x.projectedMode==null||x.projectedRuntimeBank==null?null:b===x.projectedMode?x.presentationReadRuntime.documentApi:b==="tracked"?x.canonicalReviewRuntime.documentApi:x.projectedRuntimeBank.resolveRuntime(b).documentApi},C=()=>{let b=p(),x=f();if(!x)return b;let I=l.get(b)?.get(x);if(I)return I;let E=BB(b,x),G=l.get(b)??new Map;return G.set(x,E),l.set(b,G),E},R=Ay({readPresentationApi:u,readWritableApi:C,readProjectedApiForMode:v}),S=wB({getRuntime:t,readProjectionSnapshot:n,readCurrentDisplayState:o,createDocumentApi:_m}),B=()=>u().comments,{readPublicSelectionInfo:h}=bB({getRuntime:t,readProjectionSnapshot:n,readCurrentDisplayState:o,readPresentationComments:B,readCanonicalReviewApi:m,readEffectiveSelection:i,captureEffectiveSelection:s}),y=gB({readSelectionInfo:()=>h({includeText:!0}),subscribeRawSelectionChange:b=>t().documentApi.selection.onChange(()=>b()),subscribeStateChange:a}),T=b=>{let x=i?.()??s?.()??null,I=p(),E=b(I);return E.changed&&ki({capture:x,surface:t().surface,comments:I.comments}),E},A=()=>p().comments,D={list:(b={})=>B().list(b),get:(b,x={})=>B().get(b,x),activity:(b,x={})=>B().activity(b,x),activityTimeline:(b,x={})=>B().activityTimeline(b,x),activitySummary:(b,x={})=>B().activitySummary(b,x),activityEntry:(b,x,I={})=>B().activityEntry(b,x,I),target:(b,x={})=>B().target(b,x),entryTarget:(b,x,I={})=>B().entryTarget(b,x,I),targetSnapshot:(b,x={})=>B().targetSnapshot(b,x),create:b=>{let x=Ft(t(),o());return x?q(x):A().create(b)},permissions:(b,x)=>{let I=B().permissions(b,x);return o().comments.readOnly?I&&Ui(I,o().comments):I},entryPermissions:(b,x,I)=>{let E=B().entryPermissions(b,x,I);return o().comments.readOnly?jy(E):E},move:(b,x,I)=>{let E=Ft(t(),o());return E?q(E):A().move(b,x,I)},upsert:b=>{let x=Ft(t(),o());return x?q(x):A().upsert(b)},reply:(b,x,I)=>{let E=Ft(t(),o());return E?q(E):A().reply(b,x,I)},patch:(b,x,I)=>{let E=Ft(t(),o());return E?q(E):A().patch(b,x,I)},update:(b,x,I)=>{let E=Ft(t(),o());return E?q(E):A().update(b,x,I)},updateEntry:(b,x,I,E)=>{let G=Ft(t(),o());return G?q(G):A().updateEntry(b,x,I,E)},resolve:(b,x)=>{let I=CB(t(),o());return I?q(I):A().resolve(b,x)},reopen:(b,x)=>{let I=CB(t(),o());return I?q(I):A().reopen(b,x)},replaceTargetTextTracked:(b,x,I,E={})=>{let G=Ft(t(),o());return G?q(G):A().replaceTargetTextTracked(b,x,I,E)},removeEntry:(b,x,I)=>{let E=Ft(t(),o());return E?q(E):A().removeEntry(b,x,I)},remove:(b,x)=>{let I=Ft(t(),o());return I?q(I):A().remove(b,x)}},O={query:(b,x={})=>u().search.query(b,x),next:(b,x=null,I={})=>u().search.next(b,x,I),previous:(b,x=null,I={})=>u().search.previous(b,x,I),replace:(b,x,I,E={})=>C().search.replace(b,x,I,E),replaceTracked:(b,x,I,E,G={},we={})=>C().search.replaceTracked(b,x,I,E,G,we),replaceAll:(b,x,I={})=>C().search.replaceAll(b,x,I),replaceAllTracked:(b,x,I,E={},G={})=>C().search.replaceAllTracked(b,x,I,E,G),clear:()=>u().search.clear()},U={getConfig:()=>t().documentApi.proofing.getConfig(),updateConfig:b=>t().documentApi.proofing.updateConfig(b),list:(b={})=>u().proofing.list(b),ignore:b=>C().proofing.ignore(b),acceptSuggestion:b=>C().proofing.acceptSuggestion(b),replaceTracked:(b,x,I,E={})=>C().proofing.replaceTracked(b,x,I,E)},H={current:(b={})=>h(b),onChange:b=>y.onChange(b)},le={list:b=>m().review.list(b),decisionActivity:(b={})=>m().review.decisionActivity(b),decisionActivityEntry:(b,x={})=>m().review.decisionActivityEntry(b,x),decisionActivitySummary:(b={})=>m().review.decisionActivitySummary(b),decisionActivityByObject:(b,x={})=>m().review.decisionActivityByObject(b,x),decisionActivitySummaryByObject:(b,x={})=>m().review.decisionActivitySummaryByObject(b,x),timeline:(b={})=>{let x=o(),I=c();return Zi(nl({projectionSnapshot:I,reviewOptions:b}),w(),x.comments)},timelineSummary:(b={})=>xB(le.timeline(b)),timelineByObject:(b,x={})=>{let I=o(),E=c();return Zi(Dy({projectionSnapshot:E,objectId:b,reviewOptions:x}),w(),I.comments)},timelineSummaryByObject:(b,x={})=>xB(le.timelineByObject(b,x)),permissions:(b,x)=>{let I=m().review.permissions(b,x);return f()?I.map(Xi):I},accept:(b,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):T(I=>I.review.accept(b,x)),reject:(b,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):T(I=>I.review.reject(b,x)),acceptMatching:(b,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):T(I=>I.review.acceptMatching(b,x)),rejectMatching:(b,x)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):T(I=>I.review.rejectMatching(b,x)),decideRange:(b,x,I)=>f()?q(f()??"Tracked changes are read-only in the current document mode."):T(E=>E.review.decideRange(b,x,I))},ne=e0({service:null,review:le}),M=Object.assign(((b={})=>{let x=u().info,I=le.list().length,E=x(b);return{...E,counts:{...E.counts,trackedChanges:I}}}),{summary:()=>({...u().info.summary(),revisionCount:le.list().length}),outline:()=>u().info.outline(),json:()=>u().info.json(),text:()=>u().info.text(),html:(b={})=>(v(b.revisionProjection??c().projectedMode??"tracked")??u()).info.html(b),markdown:(b={})=>(v(b.revisionProjection??c().projectedMode??"tracked")??u()).info.markdown(b)}),N,V=QL(()=>new Proxy({},{get(b,x,I){return x==="service"?t().documentService:Reflect.get(N,x,I)}}));return N=new Proxy({},{get(b,x,I){if(typeof x!="string"||x==="$$typeof")return r()?Reflect.get(u(),x,I):void 0;if(x==="comments")return D;if(x==="review")return le;if(x==="search")return O;if(x==="proofing")return U;if(x==="selection")return H;if(x==="trackChanges")return ne;if(x==="operations")return V;let E=c();return x==="info"&&E.canonicalDocument!=null&&E.projectedMode!=null?M:x==="plans"&&E.canonicalDocument!=null&&E.projectedMode!=null?S:R(x)}}),N}import{emitClonedOrderedListeners as i0,throwOrderedListenerErrors as s0}from"@datalking/begonia-layout-renderer/core";function t0(e){return e==null?e:structuredClone(e)}function r0(e){return{empty:e.empty,target:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[...e.trackedChangeIds]}}function Um(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)}):r0(t),n=go({revisions:e.revisions,selectionInfo:o}),i=bn({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:t0(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:Pe(e.previewNavigationRequest),trackChanges:structuredClone(e.trackChanges),commentsDisplay:structuredClone(e.commentsDisplay),collaboration:structuredClone(e.collaboration),linkPopover:tl(e.linkPopover),contextMenu:rl(e.contextMenu)}}function o0(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function n0(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 ll(e){if(e.allowSelectionInViewMode||e.documentMode!=="viewing"||!o0(e.surface)||e.surface.view.state.selection.empty)return!1;let t=n0(e.surface),r=e.surface.view.state.selection;if(r.from===t&&r.to===t)return!1;let o=K(e.surface.view.state,t,t);return o?(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(o)),!0):!1}function PB(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function RB(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 TB({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 y=Ae(e);if(hn(y.surface))return;let T=y.surface.editable?y.surface.trackingEnabled?"suggesting":"editing":"viewing";T!==e.documentMode&&(e.documentMode=T)},d=()=>bv(Ae(e).surface,e.documentMode,e.resolvedModules,t()),u=()=>e.readModel.sourceRuntime?Ia(e.readModel.sourceRuntime.surface,e.collaborationSession,e.reconfigurable):l(),m=()=>{c(),e.normalizeOverlayState?.();let y=Ae(e),T=$(e);T.surface.consumeHistoryChange?.()&&(e.preservedRangeSelection=null);let A=d(),D=ur(y.documentApi.preferences.get()),O=za(e,D),U=Zr(e.readModel,A.trackChanges.mode),H=Fy({runtime:T,projectionSnapshot:U,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:D,zoom:O,viewportSession:e.viewportSession,display:{trackChanges:A.trackChanges,comments:A.comments},activeCommentId:e.activeCommentId,activeRevisionId:e.activeRevisionId,activeRevisionIds:e.activeRevisionIds}),le=ld({comments:H.comments,selectionInfo:H.selectionInfo});if(le.activeCommentId)e.activeCommentId!==le.activeCommentId&&(e.activeCommentId=le.activeCommentId);else if(e.activeCommentId!=null){let b=cd({comments:H.comments,selectionInfo:H.selectionInfo,explicitActiveCommentId:e.activeCommentId}),x=b.length===1?b[0]??null:null;e.activeCommentId!==x&&(e.activeCommentId=x)}let ne=go({revisions:H.revisions,selectionInfo:H.selectionInfo});if(ne.activeRevisionIds.length>0)(e.activeRevisionId!==ne.activeRevisionId||!RB(e.activeRevisionIds,ne.activeRevisionIds))&&(e.activeRevisionId=ne.activeRevisionId,e.activeRevisionIds=[...ne.activeRevisionIds]);else if(e.activeRevisionIds.length>0&&H.activeRevisionIds){let b=new Set(H.revisions.map(I=>I.id)),x=e.activeRevisionIds.filter(I=>b.has(I));RB(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 M=No({state:T.surface.state,surfaceEditable:T.surface.editable,surfaceSelectionReliable:PB(T.surface),selectionInput:{includeText:!0},reviewReplacementMode:T.replacementMode,revisions:U.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:U,preservedRangeSelection:e.preservedRangeSelection}),N=!!(U.projectedMode!=null&&M&&H.selection.empty&&!M.empty&&e.preservedRangeSelection?.projectedMode!==U.projectedMode),V=M&&N?{selection:M.selection,selectionInfo:Fr(M),selectionNodeSelectionTarget:M.nodeSelectionTarget}:{selection:T.surface.describeSelection(),selectionInfo:H.selectionInfo,selectionNodeSelectionTarget:H.selectionNodeSelectionTarget??null};return e.preservedRangeSelection=zu({selection:V.selection,selectionInfo:V.selectionInfo,selectionNodeSelectionTarget:V.selectionNodeSelectionTarget??null,previous:e.preservedRangeSelection,state:T.surface.state,surfaceSelectionReliable:PB(T.surface),reviewReplacementMode:T.replacementMode,revisions:U.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:U}),e.activeSearchHitId=H.search.activeHitId,H},p=()=>Um(m()),f=()=>e.readModel.activeRuntime?ll({surface:e.readModel.activeRuntime.surface,documentMode:e.documentMode,allowSelectionInViewMode:e.allowSelectionInViewMode}):!1,w=()=>{let y=null;do{if(i=!1,f()){i=!0;continue}y=m()}while(i);if(y==null)throw new Error("Browser editor state emission could not stabilize.");return y},v=()=>{if(s>0&&!o){a=!0;return}if(o){i=!0;return}o=!0;let y=[];try{do{let T=w();n+=1,y.push(...i0(e.listeners,T,Um))}while(i)}finally{o=!1,i=!1}s0(y,"Browser editor state listeners failed.")};return{syncDocumentModeFromSurface:c,readCurrentDisplayState:d,readCollaboration:u,readState:p,getEmissionVersion:()=>n,emit:v,runBatchedEmit:y=>{s+=1;try{return y()}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:y=>{e.unsubscribeCollaborationSession?.(),e.unsubscribeCollaborationSession=y?.subscribe?y.subscribe(()=>v()):null}}}function kB(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 Gm}from"@datalking/begonia-engine";import{readSyntheticSideStoryDocOriginPath as c0}from"@datalking/begonia-doc-service/v1";function a0(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 l0(e){let t=Dt(e.capture);return e.capture.selectionKind!=="text"||t.length===0?!1:!e.selection||e.selection.empty!==e.capture.selection.empty?!0:a0({surface:e.surface,selection:e.selection,capture:e.capture})}function EB(e){return l0(e)?e.resolveSemanticSelection():e.selection}var d0=256;function IB(e,t){if(!e||!t.docChanged)return e;try{return e.map(t.mapping)}catch{return null}}function AB(e,t,r){for(let o of r.captures)t.add(o),e.delete(o);r.captures.clear()}function MB(e,t){for(;t.captures.size>d0;){let r=t.captures.values().next().value;if(!r)return;t.captures.delete(r),e.delete(r)}}function u0(e){return typeof e.view?.dispatch=="function"&&typeof e.subscribe=="function"}function m0(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=IB(n.bookmark,r)}}}function NB(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=IB(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 OB(e,t,r){e.trackedView!==r.view&&(e.restoreDispatch(),e.trackedView=r.view,NB(e,t))}function Xm(e,t,r,o,n={}){if(!u0(o))return null;let i=e.get(o);if(i)return OB(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=>{m0(a,t,l)})),NB(a,t),a.unsubscribe=o.subscribe(()=>{let l=o.document;if(l!==a.lastDocument){if(!a.pendingDispatchDocChange)if(a.programmaticDocChangeDepth===0)AB(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)??Sr(o,d);if(!m){c.push(d);continue}u.bookmark=Gm(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 Zm(e,t,r,o,n=!0){let i=e.get(o);i&&(i.unsubscribe(),i.unsubscribeTransactions(),i.restoreDispatch(),i.trackedView=null,n?AB(t,r,i):i.captures.clear(),e.delete(o))}function p0(e,t,r,o={}){let n=jB(e,t,r,o);return n?Ut(n):null}function f0(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 DB(e,t,r,o={}){let n=f0(e,r),i=n?dt(e.state,n):null,s=EB({surface:e,selection:i,capture:t,resolveSemanticSelection:()=>o.resolveProgrammaticSelection?.(e,t)??Sr(e,t)});if(s===i)return i;if(!s)return null;let a=dt(e.state,s);return a?i&&Xt(i,a)?i:(r.bookmark=Gm(a),a):null}function jB(e,t,r,o={}){let n=DB(e,t,r,o);return n?kc(e.state,n):null}function VB(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=c0(a.document);return Sc(l.storyOriginPath,d)?l.documentIdentity!=null?l.documentIdentity===Qn(a.document)&&l.documentHash===nn(a.document):c?c.surface===a&&c.document===a.document:l.storyOriginPath!=null&&Sc(l.storyOriginPath,d):!1},s=a=>{Zm(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 Zm(t,r,n,a,!1),!0;let d=Xm(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 MB(r,d),Zm(t,r,n,a,!1),!0},runWithProgrammaticDocumentChange(a,l){let c=Xm(t,r,n,a,e);if(!c)return l();c.programmaticDocChangeDepth+=1;try{return l()}finally{c.programmaticDocChangeDepth>0&&(c.programmaticDocChangeDepth-=1),OB(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)?Sr(a,l):null:DB(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=Sr(a,l);return d?kc(a.state,d):null}return jB(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:p0(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=Xm(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:Gm(l.selection),empty:c.selection.empty}),d.captures.delete(c),d.captures.add(c),MB(r,d),c}}}function LB(e,t){return Object.freeze({id:e,kind:t})}function FB(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=LB(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 HB(e,t,r){return t.resolveSelection(e(),r)}function zB(e){let{getSurface:t,selectionCaptureTracker:r,captureSelection:o,captureEffectiveSelection:n,captureCurrentSelectionFromState:i,readSelectionCapture:s}=e,a=FB({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 xc({surface:t(),capture:l,resolveSelection:d=>HB(t,r,d),options:{...c,validateDocumentIdentity:!1}})},restoreSelectionHandle(l,c={}){return xc({surface:t(),capture:a.peek(l),resolveSelection:d=>HB(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 qB(e,t,r,o,n,i,s,a,l,c,d,u,m){let p=tr(n),f=Sv(i,s),w=To(r,e,p.comments,o),v=sa(c,e.trackingEnabled),C=fo(d),R=pt(u)??"vertical",S=Dv(p,f,l??!0,r,w,v,C,vr(R,C),R,e.document,a??null),B=()=>qy(s),h=VB({resolveProgrammaticSelection(_,xe){if(xe.projectedMode!=null&&xe.selectionTarget){let _e=ne(),wt=ft({state:_.state,target:xe.selectionTarget,projectionSnapshot:{canonicalDocument:_e.canonicalDocument,projectedMode:_e.projectedMode},sourceMode:xe.projectedMode,revisions:_e.canonicalReviewRuntime.documentApi.review.list(),expectedText:xe.text??null});if(wt&&xe.selectionKind==="text")return K(_.state,wt.selection.from,wt.selection.to)}return null}}),y=dB(_=>h.untrack(_)),T=TB({context:S,allowCollaborativeProjection:B,releaseContextMenuCaptures:()=>y.releaseContextMenuCaptures(S.contextMenu)}),A=kB({setState:_=>{S.linkPopover=_},closeState:T.closeLinkPopover,clearOverlayState:T.clearEphemeralOverlays,untrackCapture:y.untrackCapture}),D=Qy({getController:m,getDocumentMode:()=>S.documentMode,getRuntime:()=>$(S),getResolvedModules:()=>S.resolvedModules,captureSelectionFromState:_=>E(_),setLinkPopover:A.set,closeContextMenu:T.closeContextMenu,closeLinkPopover:A.close,emit:T.emit}),O=Uy({getController:m}),U=eB({getController:m,getDocumentMode:()=>S.documentMode,getResolvedModules:()=>S.resolvedModules,readTrackChangesDisplayState:()=>T.readCurrentDisplayState().trackChanges,captureEffectiveSelectionFromState:_=>G(_,{includeText:!0}),setContextMenu:_=>{y.releaseContextMenuCaptures(S.contextMenu,_),S.contextMenu=_},closeContextMenu:T.closeContextMenu,closeLinkPopover:A.close,emit:T.emit}),H=uB({getController:m,getDocumentMode:()=>S.documentMode,getResolvedModules:()=>S.resolvedModules,readTrackChangesDisplayState:()=>T.readCurrentDisplayState().trackChanges,setContextMenu:_=>{y.releaseContextMenuCaptures(S.contextMenu,_),S.contextMenu=_},closeContextMenu:T.closeContextMenu,closeLinkPopover:A.close,emit:T.emit}),le=aB({context:S,templates:t,ownsSurface:i,surfaceFactory:s,allowCollaborativeProjection:B,emit:T.emit,readCurrentDisplayState:T.readCurrentDisplayState,clearEphemeralOverlays:A.clearOverlays,handleLinkClick:D,handleCommentClick:O,handleContextMenu:U}),ne=()=>Zr(S.readModel,T.readCurrentDisplayState().trackChanges.mode),M=()=>{let _=$(S).surface;h.runWithProgrammaticDocumentChange(_,()=>le.applySurfaceDisplayState());let xe=$(S).surface;_!==xe&&!h.transferSurface(_,xe)&&Oe();let _e=T.readCurrentDisplayState();if(ll({surface:$(S).surface,documentMode:S.documentMode,allowSelectionInViewMode:S.allowSelectionInViewMode}),S.documentMode==="viewing"&&_e.trackChanges.enabled&&_e.trackChanges.mode==="review"){let wt=ne();Qa({surface:$(S).surface,canonicalReviewApi:wt.canonicalReviewRuntime.documentApi,canonicalDocument:wt.canonicalDocument,projectedMode:wt.projectedMode})}},N=_m({getRuntime:()=>$(S),hasSourceRuntime:()=>S.readModel.sourceRuntime!=null,readProjectionSnapshot:ne,readCurrentDisplayState:T.readCurrentDisplayState,readEffectiveSelection:_=>I(_),captureEffectiveSelection:_=>x(_),subscribeStateChange:_=>{let xe=()=>_();return S.listeners.add(xe),()=>{S.listeners.delete(xe)}}}),V=rB({context:S,readProjectionSnapshot:ne,readState:T.readState,selectionCaptureTracker:h}),{captureSelection:b,captureEffectiveSelection:x,readEffectiveSelection:I,captureCurrentSelectionFromState:E,captureEffectiveSelectionFromState:G,readSelectionCapture:we,resolveSelectionCapture:ve}=V,Ne=_=>ve(_,{includeText:!0}),It=_=>we(_,{includeText:!0});S.normalizeOverlayState=()=>{let _=A.sync(It),xe=S.contextMenu;if(!xe)return _;let _e=$(S),wt=ne(),ts=wt.canonicalReviewRuntime.documentApi.review.list(),rs=mB({surface:_e.surface,selectionInfo:Xr(_e.surface,{includeText:!0},_e.replacementMode),projectionSnapshot:wt,revisions:ts}),zn=lB({currentState:xe,controller:m(),documentMode:S.documentMode,contextMenuOptions:S.resolvedModules.contextMenu,reviewActionsEnabled:T.readCurrentDisplayState().trackChanges.enabled,revisions:ts,liveSelection:rs.selection,liveSelectionInfo:rs.selectionInfo,resolveSelectionCapture:Ne,resolveSelectionState:Sx=>h.resolveState(_e.surface,Sx)});return y.releaseContextMenuCaptures(xe,zn),S.contextMenu=zn,!0};let Ke=zB({getSurface:()=>$(S).surface,selectionCaptureTracker:h,captureSelection:b,captureEffectiveSelection:x,captureCurrentSelectionFromState:E,readSelectionCapture:we}),{clearDeferredSelectionState:Oe,captureSelectionHandle:st,captureEffectiveSelectionHandle:nr,captureSelectionHandleFromCapture:Ht,resolveSelectionHandle:Tr,restoreSelectionCapture:kr,restoreSelectionHandle:Oo,releaseSelectionHandle:Er}=Ke,ir=_=>Ke.runAndEmit(_,T.getEmissionVersion,T.emit),L=Zy({getRuntime:()=>$(S),runAndEmit:ir,readState:()=>T.readState(),clearPreservedRangeSelection:()=>{S.preservedRangeSelection=null}}),Qe=()=>oa({editable:$(S).surface.editable,document:$(S).surface.document,commentsDisplay:T.readCurrentDisplayState().comments}),at=()=>er($(S).surface);return le.mountSourceRuntime(e),T.subscribeCollaborationSession(S.collaborationSession),M(),{context:S,permissionResolver:o,stateRuntime:T,lifecycle:le,selectionRuntime:V,linkPopoverRuntime:A,advancedOoxmlMethods:L,publicDocumentApi:N,commentWriteReason:Qe,reviewWriteReason:at,applySurfaceDisplayState:M,clearDeferredSelectionState:Oe,selectionCaptureTracker:h,captureCurrentSelectionFromState:E,runAndEmit:ir,openContextMenuAt:H,captureSelectionHandle:st,captureEffectiveSelectionHandle:nr,captureSelectionHandleFromCapture:Ht,resolveSelectionHandle:Tr,restoreSelectionCapture:kr,restoreSelectionHandle:Oo,releaseSelectionHandle:Er}}function Qi(e,t,r,o,n,i,s,a,l,c,d,u){let m,p=qB(e,t,r,o,n,i,s,a,l,c,d,u,()=>m),{context:f,permissionResolver:w,stateRuntime:v,lifecycle:C,selectionRuntime:R,linkPopoverRuntime:S,advancedOoxmlMethods:B,publicDocumentApi:h,commentWriteReason:y,reviewWriteReason:T,applySurfaceDisplayState:A,clearDeferredSelectionState:D,selectionCaptureTracker:O,captureCurrentSelectionFromState:U,runAndEmit:H,openContextMenuAt:le,captureSelectionHandle:ne,captureEffectiveSelectionHandle:M,captureSelectionHandleFromCapture:N,resolveSelectionHandle:V,restoreSelectionCapture:b,restoreSelectionHandle:x,releaseSelectionHandle:I}=p,E=w,G=()=>Zr(f.readModel,v.readCurrentDisplayState().trackChanges.mode),we=!1,{captureSelection:ve,captureEffectiveSelection:Ne,readEffectiveSelection:It,capturePointSelection:Ke,readPointSelection:Oe,readSelectionCapture:st,resolveSelectionCapture:nr}=R,Ht=Vv({context:f,permissionResolver:E,getSurface:()=>$(f).surface,readState:v.readState,runBatchedEmit:v.runBatchedEmit,clearEphemeralOverlays:S.clearOverlays,applySurfaceDisplayState:A,emit:v.emit}),Tr=Mv({reconfigurable:f.reconfigurable,getRuntime:()=>$(f),getSourceRuntime:()=>Ae(f),getCurrentActor:()=>f.currentActor,getCollaborationSession:()=>f.collaborationSession,readCollaboration:v.readCollaboration,readCommentResolveState:()=>v.readCurrentDisplayState().comments,commentWriteReason:y,reviewWriteReason:T,createReplacementSurface:C.createReplacementSurface,swapSurface:(L,Qe)=>{let at=f.preservedRangeSelection,_=$(f).surface;f.collaborationSession=Qe,v.subscribeCollaborationSession(f.collaborationSession),C.swapSurface(L,Qe);let xe=$(f).surface;O.transferSurface(_,xe)||D(),f.currentActor=To(f.actorInput,xe,f.resolvedModules.comments,E),f.preservedRangeSelection??=at},emit:v.emit,runAndEmit:H,readEffectiveSelection:It,captureEffectiveSelection:Ne,readSelectionCapture:st,resolveSelectionCapture:nr,resolveSelectionHandle:V,resolveCommentTargetFromCapture:L=>{if(!L)return null;let Qe=Ur(L)?L.selectionTarget:null,at=L.target??Qe;if(!at)return null;if(!Ur(L))return at;let _=$(f),xe=O.resolveTarget(_.surface,L),_e=st(L,{includeText:!0}),wt=_e?.target??_e?.selectionTarget??xe,ts=O.isTracked(_.surface,L),rs="segments"in at?(()=>{let zn=Q(_.surface.state.doc,at,{strict:!0});return zn?ge(_.surface.state.doc,_.surface.state.schema,zn):null})():null;return Hv({captureTarget:at,captureText:L.text,originalTargetText:rs,resolvedTarget:wt,resolvedText:_e?.text??null,captureStillTracked:ts})},getPresentationReadApi:()=>G().presentationReadRuntime.documentApi,getWritableRuntimeApi:()=>G().writableRuntime.documentApi,getSearchQuery:()=>f.searchQuery,setSearchQuery:L=>{f.searchQuery=L},getSearchOptions:()=>f.searchOptions,setSearchOptions:L=>{f.searchOptions=L},getActiveSearchHitId:()=>f.activeSearchHitId,setActiveSearchHitId:L=>{f.activeSearchHitId=L},getActiveCommentId:()=>v.readState().activeCommentId??null,setActiveCommentId:L=>{f.activeCommentId=L},readVisibleComments:()=>v.readState().comments,getActiveRevisionId:()=>v.readState().activeRevisionId??null,setActiveRevisionIds:L=>{f.activeRevisionIds=[...L],f.activeRevisionId=L.length===1?L[0]??null:null},getLinkPopover:()=>f.linkPopover,getLinkPopoverSelectionCapture:S.getSelectionCapture,setLinkPopover:S.set,closeLinkPopover:S.close,clearPreservedRangeSelection:()=>{f.preservedRangeSelection=null}}),kr=_v({context:f,emit:v.emit,getEmissionVersion:v.getEmissionVersion,applySurfaceDisplayState:A}),Oo,Er;m={get surface(){return $(f).surface},get documentService(){return $(f).documentService},get documentApi(){return h},get editorHost(){return Oo},get editor(){return Er},get modules(){return tr(f.resolvedModules)},get actor(){return Fa(f.currentActor)},get collaboration(){return gu(v.readCollaboration())},getState(){return v.readState()},getCollaborationState(){return gu(v.readCollaboration())},...Ht,...kr,setActor(L){f.actorInput=L,f.currentActor=To(f.actorInput,$(f).surface,f.resolvedModules.comments,E),v.emit()},setParticipant(L){f.currentActor=cu(f.actorInput,L,f.resolvedModules.comments,E);let Qe=Ae(f),at=f.readModel.activeRuntime;at&&at.surface!==Qe.surface&&at.surface.setParticipant(L),Qe.surface.setParticipant(L)},subscribe(L){f.listeners.add(L);try{we||L(v.readState())}catch(Qe){throw f.listeners.delete(L),Qe}return()=>f.listeners.delete(L)},captureSelection:ve,captureEffectiveSelection:Ne,readEffectiveSelection:It,readSelectionCapture:st,captureSelectionHandle:ne,captureEffectiveSelectionHandle:M,captureSelectionHandleFromCapture:N,resolveSelectionCapture:nr,resolveSelectionHandle:V,restoreSelectionCapture:b,restoreSelectionHandle:x,releaseSelectionHandle:I,capturePointSelection(L){return!L||typeof L!="object"||typeof L.clientX!="number"||typeof L.clientY!="number"?null:Ke(L)},readPointSelection(L){return!L||typeof L!="object"||typeof L.clientX!="number"||typeof L.clientY!="number"?null:Oe(L)},...Tr,...B,closeLinkPopover:S.close,closeContextMenu:v.closeContextMenu,openContextMenuAt:le,destroy(){if(we)return;we=!0,D(),f.unsubscribeCollaborationSession?.(),f.unsubscribeCollaborationSession=null,f.listeners.clear(),Er.destroy(),C.destroyCollaborativeProjection();let L=i||!!s;C.unmountSourceRuntime(L),f.preservedRangeSelection=null,f.collaborationSession=null}};for(let L of["surface","documentService"])Object.defineProperty(m,L,{...Object.getOwnPropertyDescriptor(m,L),enumerable:!1});Oo=Pi(m),Er=w0(Oo);let ir=ka(()=>$(f).surface);return Object.defineProperty(m,ca,{value(L){if(!L||typeof L!="object"||typeof L.clientX!="number"||typeof L.clientY!="number")return null;let Qe=Cn({surface:$(f).surface,clientX:L.clientX,clientY:L.clientY,mode:"text-only"});return Qe?U(Qe.state,L):null}}),Object.defineProperties(m,{readLayoutAdapter:{configurable:!1,enumerable:!1,value:ir.readLayoutAdapter},readLayoutSource:{configurable:!1,enumerable:!1,value:ir.readLayoutSource},readDocumentSize:{configurable:!1,enumerable:!1,value:ir.readDocumentSize},selection:{configurable:!1,enumerable:!1,value:ir.selection}}),m}import{collectMissingDocumentFontFamilies as WB,createDocumentFontCatalog as KB,createDocumentFontRegistrationManager as g0}from"@datalking/begonia-font-system";function $m(e){return e.document.attrs.ooxmlPackageResources}function S0(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 Ym(e,t,r){let o=KB($m(t),"browser-document"),n=g0(r,o),i=$m(t),s=!1,a=WB(n.catalog),l=()=>{s||(a=WB(n.catalog),S0(e.surface,m=>n.catalog.resolveFamily(m)))},c=()=>{if(s)return;let m=e.surface,p=$m(m);p!==i&&(i=p,n.replace(KB(p,"browser-document"))),l(),n.ready.then(l)},d=e.subscribe(c),u=e.destroy.bind(e);return Object.defineProperties(e,{documentFontCatalog:{configurable:!0,enumerable:!0,get:()=>n.catalog},documentMissingFonts:{configurable:!0,enumerable:!0,get:()=>a},documentFontsReady:{configurable:!0,enumerable:!0,get:()=>n.ready}}),e.destroy=()=>{s||(s=!0,d(),n.dispose(),u())},c(),e}function _B(e,t){t.fitWidthOptions!==void 0&&e.setFitWidthOptions(t.fitWidthOptions),t.zoomMode&&e.setZoomMode(t.zoomMode);let r=vt(t.zoomPercent);return r!=null&&t.zoomMode!=="fit-width"&&r!==e.getZoomPercent()&&e.setViewState({zoomPercent:r}),e}function v0(e,t={}){let r=_B(Qi(e,t.templates,t.actor,t.permissionResolver,t.modules,!1,t.surfaceFactory,t.collaborationSession,t.viewSelect,t.documentMode,t.flowMode,t.layoutMode),t);return Ym(r,e,t.documentFontProvider)}function Jm(e){let t=e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:as(e.features??[]),r=sa(e.documentMode,e.trackingEnabled),o=yn(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:w,permissionResolver:v,surfaceFactory:C,viewSelect:R,...S}=e,B=h0({...S,collaborative:e.collaborationSession?.binding??e.collaborative,editable:Bn(r),trackingEnabled:zr(r,o),features:t}),h=_B(Qi(B,e.templates,e.actor,e.permissionResolver,e.modules,!0,vv({...e,features:t}),e.collaborationSession,e.viewSelect,e.documentMode,e.flowMode,e.layoutMode),e);return Ym(h,B,e.documentFontProvider)}import{DEFAULT_VIEWPORT_FIT_WIDTH_OPTIONS as Bee,cloneViewportFitMetrics as xee,cloneViewportFitWidthOptions as Cee,computeAppliedViewportFitZoom as Pee,computeViewportFitZoom as Ree,normalizeViewportFitMetrics as Tee,normalizeViewportFitWidthOptions as b0,resolveViewportFitMetricsFromPreview as kee,sameViewportFitMetrics as Eee,sameViewportFitWidthOptions as y0}from"@datalking/begonia-layout-renderer/core";function Qm(e){return b0(e)}function UB(e,t){return y0(e,t)}var B0=Object.freeze([]);function ZB(e,t){return e.length===t.length&&e.every((r,o)=>Object.is(r,t[o]))}function x0(e,t){return e===t?!0:!e||!t?e==null&&t==null:ZB(e,t)}function GB(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)&&x0(e.groups,t.groups)}function $B(e,t){return e.id===t.id&&e.name===t.name&&(e.color??null)===(t.color??null)}function C0(e){return{...e}}function P0(e){return e?.length?[...e]:B0}function R0(e){return!e||typeof e!="object"?e:{...e}}function YB(e,t){return UB(Qm(e),Qm(t))}function XB(e){return{...e,collaborationSession:e.collaborationSession??null,enableEmbeddedAdvancedOoxmlEditors:e.enableEmbeddedAdvancedOoxmlEditors!==!1,...e.actor!==void 0?{actor:Fa(e.actor??null)}:{},features:P0(e.features),...e.fitWidthOptions!==void 0?{fitWidthOptions:R0(e.fitWidthOptions)}:{},...e.modules!==void 0?{modules:tr(e.modules)}:{},participant:C0(e.participant),trackingEnabled:e.trackingEnabled!==!1,viewSelect:e.viewSelect!==!1}}function JB(e,t){return e.room===t.room&&e.collaborative===t.collaborative&&e.collaborationSession===t.collaborationSession&&e.enableEmbeddedAdvancedOoxmlEditors===t.enableEmbeddedAdvancedOoxmlEditors&&ZB(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 T0(e,t){return GB(e.actor,t.actor)&&JB(e,t)&&e.documentMode===t.documentMode&&e.flowMode===t.flowMode&&e.layoutMode===t.layoutMode&&lu(e.modules,t.modules)&&e.onTransaction===t.onTransaction&&e.onUpdate===t.onUpdate&&$B(e.participant,t.participant)&&e.zoomMode===t.zoomMode&&YB(e.fitWidthOptions,t.fitWidthOptions)&&e.zoomPercent===t.zoomPercent}function k0(e,t){return e.controller===t.controller&&e.state===t.state}function ep(e){return{controller:e.controller,state:e.state}}function E0(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 M0(e){let{controller:t,previous:r,next:o}=e;GB(r.actor,o.actor)||t.setActor(o.actor??null),$B(r.participant,o.participant)||t.setParticipant(o.participant),r.documentMode!==o.documentMode&&o.documentMode!=null&&t.setDocumentMode(o.documentMode),lu(r.modules,o.modules)||t.setModules(o.modules),r.zoomMode!==o.zoomMode&&o.zoomMode!=null&&t.setZoomMode(o.zoomMode),!YB(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 tp(e,t={}){let r=new Set,o=t.createEditor??Jm,n={destroyed:!1,host:null,input:XB(e),controller:null,state:null,unsubscribeController:null,snapshot:{controller:null,state:null}},i=()=>{let c={controller:n.controller,state:n.state};if(!k0(n.snapshot,c)){n.snapshot=c;for(let d of[...r])d(ep(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(E0(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 ep(n.snapshot)},subscribe(c){return r.add(c),c(ep(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=XB(c);if(n.input=u,T0(d,u)||!n.host)return;let m=!JB(d,u);if(!n.controller||m){l();return}M0({controller:n.controller,previous:d,next:u})},destroy(){n.destroyed||(n.destroyed=!0,n.host=null,s(),r.clear())}}}function I0(){return{ui:null,host:null,snapshot:null}}function ex(e){av(e.host,e.ui),e.ui?.destroy(),e.controller=null,e.host=null,e.ui=null}function A0(e,t){if(e.controller===t||(ex(e),!t))return;let r=In(t);e.controller=t,e.host=r,e.ui=ra(r);let o=Cr(r);o&&Ea(r,e.ui,o)}function QB(e,t){return A0(e,t.controller),{ui:e.ui,host:e.host,snapshot:t.state?xn(t.state):null}}function N0(e){let t=tp(e),r=new Set,o={controller:null,host:null,ui:null},n=QB(o,t.getSnapshot()),i=t.subscribe(s=>{n=QB(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(),ex(o),t.destroy(),n=I0()}}}function O0(){return{createMount(e){return N0(e)}}}function tx(e,t={}){let r=e.documentApi?.sections?.list?.()??[],o=t.sectionIndex==null?null:r[t.sectionIndex]??null;return o?{titlePage:o.sectionMetadata?.titlePage===!0,oddEven:o.sectionMetadata?.oddEvenHeadersFooters===!0}:{titlePage:r.some(n=>n.sectionMetadata?.titlePage===!0),oddEven:r.some(n=>n.sectionMetadata?.oddEvenHeadersFooters===!0)}}function rp(e,t,r={}){let o=e.documentApi?.sections;return!o?.setTitlePage||r.sectionIndex==null?!1:o.setTitlePage({target:r.sectionIndex,enabled:t}).changed}function op(e,t){let r=e.documentApi?.sections;return r?.setOddEvenHeadersFooters?r.setOddEvenHeadersFooters({enabled:t}).changed:!1}function D0(e,t={}){let r=()=>tx(e,t);return{read:r,setTitlePage:o=>rp(e,o,t),setOddEven:o=>op(e,o),toggleTitlePage:()=>rp(e,!r().titlePage,t),toggleOddEven:()=>op(e,!r().oddEven)}}function rx(e){return{kind:"headerFooterSlot",section:e.sectionIndex,headerFooterKind:e.kind,variant:e.slot}}function ox(e,t){let r=e.documentApi?.headerFooters;if(!r?.resolve)return{linked:!0,available:!1};let o=r.resolve({target:rx(t)});return o.status==="none"?{linked:!0,available:!0}:{linked:o.status!=="explicit",available:!0}}function es(e,t,r){let o=e.documentApi?.headerFooters?.refs;return o?.setLinkedToPrevious?o.setLinkedToPrevious({target:rx(r),linked:t})?.changed===!0:!1}function j0(e,t){let r=()=>ox(e,t);return{read:r,setLinked:o=>es(e,o,t),linkToPrevious:()=>es(e,!0,t),unlinkFromPrevious:()=>es(e,!1,t),toggle:()=>es(e,!r().linked,t)}}function V0(e){return Ma(e)}import{collectOoxmlMathStructures as L0,countOoxmlChartCategories as F0,normalizeOoxmlChartModel as H0,normalizeOoxmlMathModel as z0,normalizeOoxmlShapeModel as q0}from"@datalking/begonia-engine";function cl(e){return e.trackingEnabled??e.toolbar?.trackingEnabled??!1}function dl(e){return e.documentMode==="editing"||e.documentMode==="suggesting"||e.documentMode==="viewing"?e.documentMode:"editing"}function W0(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="math")return null;let r=z0(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:L0(r),trackingEnabled:cl(e),documentMode:dl(e)}}function K0(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="chart")return null;let r=H0(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:F0(r),trackingEnabled:cl(e),documentMode:dl(e)}}function _0(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="shape")return null;let r=q0(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:cl(e),documentMode:dl(e)}}function np(e="editing",t=!1){return{selected:null,documentMode:e,trackingEnabled:t}}function nx(e){return{selected:W0(e)??K0(e)??_0(e),trackingEnabled:cl(e),documentMode:dl(e)}}function ul(e){return structuredClone(e)}function ee(e){return{changed:!1,reason:e}}function U0(e){let t=e,r=Be(t),o=Cr(t),n=lv(t),i=o?.controller.documentApi??{},s=()=>{let m=o?.controller.getState();return m?nx(m):np()},a=s(),l=new Set,c=()=>{a=s();for(let m of[...l])m(ul(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(),ul(a)},subscribe(m){return l.add(m),m(ul(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=np()}}}function ix(e){return e?.selection??null}function X0(e){return ix(e.editor)?.resolvePositionHitEvent?.(e)??e.event}function Z0(e){let t=ix(e.editor);if(!t?.handlePositionHit)return!1;let r=t.resolvePositionHitEvent?.(e)??e.event;return t.handlePositionHit({...e,event:r})}function sx(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function ax(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function lx(e){return e==="web"||e==="paginated"?e:null}function cx(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function nte(e){return e.previousEditor!==e.nextEditor?"editor-instance":e.previousPreviewSourceIdentity!==e.previewSourceIdentity?"preview-source":ax(e.previousControllerNavigationMode)!==ax(e.controllerNavigationMode)?"controller-navigation-mode":lx(e.previousFlowMode)!==lx(e.flowMode)||cx(e.previousLayoutMode)!==cx(e.layoutMode)?"preview-mode":e.previousSyncViewportToEditor!==e.syncViewportToEditor?"sync-viewport-toggle":sx(e.previousExplicitAnchorPageNumber)!==sx(e.explicitAnchorPageNumber)?"explicit-anchor":null}import{resolveProjectionSelectionPageIndexes as G0}from"@datalking/begonia-page-layout";function ip(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>0?t:null}function $0(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.trunc(e)):null}function ux(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>=0?t:null}function Y0(e,t){if(!e||typeof e!="object")return t;let r=e,o=ip(r.pageNumber),n=ux(r.pageIndex);return o!=null&&n!=null&&n!==o-1?null:o??(n!=null?n+1:t)}function J0(e){if(!e||typeof e!="object")return null;let t=ip(e.anchorPageNumber),r=e.viewportAnchor==null?t:Y0(e.viewportAnchor,t);return e.viewportAnchor!=null&&r==null||t!=null&&r!=null&&r!==t?null:t??r}function Hn(e,t){let r=new Set([...e].map(o=>ip(o)).filter(o=>o!=null));return!t||t.length===0?[...r].sort((o,n)=>o-n):t.filter(o=>r.has(o))}function dx(e,t){if(!t||t.length===0)return[];let r=new Map(t.map((o,n)=>[o,n]));return Hn(e??[],t).flatMap(o=>{let n=r.get(o);return n==null?[]:[n]})}function Q0(e,t){return Hn(e.flatMap(r=>{let o=ux(r),n=o==null?null:t[o]??null;return n==null?[]:[n]}),t)}function ate(e){let t=e.projection?.pages.map(s=>s.pageNumber)??null,r=Hn(e.selectionPageNumbers??[],t),o=new Set(Hn(e.pinnedPageNumbers??[],t));for(let s of r)o.add(s);if(!e.projection||e.sourceMatchesEditorDocument===!1){let s=Hn(o,t);return s.length>0?s:void 0}let n=J0(e.previewNavigationRequest),i=r.length>0?Hn(n==null?o:[...o,n],t):Q0(G0(e.projection,e.selection,{docSize:$0(e.documentSize),preferredPageIndexes:dx(e.pinnedPageNumbers,t),extraPageIndexes:n==null?[]:dx([n],t)}),t??[]);return i.length>0?i:void 0}function eF(e){let t=Hh(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 sp(e,t){return t?mx({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:Pe(e?.previewNavigationRequest??null)}}function mx(e,t,r){let o=Rt(t,r),n=Tt(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?Pe(n):s?Pe(e.previewNavigationRequest):null}}function px(e){let t=Tt(e.editorState,e.modeOptions),r=Lh(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,Kr(t,e.trackingState.previewNavigationRequest)?e.trackingState.previewNavigationRequestKey:null,e.modeOptions),o=eF(e),n=o?.viewport??null,i=mx(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 tF(e){let t=Wd(e.editorState,e.explicitFlowMode),r=_h(e.editorState,e.explicitLayoutMode,t);return{flowMode:t,layoutMode:r}}function gte(e){let t=tF(e),{flowMode:r,layoutMode:o}=t;return{scale:zh(e.editorState,e.explicitScale),flowMode:r,layoutMode:o,modeOptions:t,anchorPageNumber:qh(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),initialViewportAnchor:Wh(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),viewportRequestKey:Kh(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),acknowledgementRequestKey:Fh(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t)}}function fx(e){if(!e.syncViewportToEditor)return null;let t=_t(e.viewport,{flowMode:e.controllerFlowMode,layoutMode:e.controllerLayoutMode});if(!t||e.controllerFlowMode&&!Uo(t,e.controllerFlowMode)||e.controllerLayoutMode&&!Xo(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=_t(e.lastAppliedViewport,{flowMode:r,layoutMode:o}),i=_t(e.controllerViewport,{flowMode:r,layoutMode:o});return Un(t,n)||Un(t,i)?null:t}function wx(e){return e?{requestKey:e.requestKey,viewportResetVersion:e.viewportResetVersion}:null}function rF(e,t){return e?.requestKey===t?.requestKey&&e?.viewportResetVersion===t?.viewportResetVersion}function oF(e,t){return et(e.editorViewport,t.editorViewport)&&e.editorViewportRequestKey===t.editorViewportRequestKey&&e.previewNavigationRequestKey===t.previewNavigationRequestKey&&Kr(e.previewNavigationRequest,t.previewNavigationRequest)}function gx(e,t){return e.viewportHydrated===t.viewportHydrated&&e.viewportResetVersion===t.viewportResetVersion&&et(e.lastAppliedViewport,t.lastAppliedViewport)&&e.lastResetCause===t.lastResetCause&&oF(e.trackingState,t.trackingState)&&rF(e.pendingAcknowledgement,t.pendingAcknowledgement)}function nF(e,t){return e==null?null:{requestKey:e,viewportResetVersion:t}}function iF(e){return e.acknowledgementRequestKey!=null?nF(e.acknowledgementRequestKey,e.viewportResetVersion):e.shouldResetViewport?null:e.current!=null&&e.compatiblePreviewNavigationRequestKey===e.current.requestKey?wx(e.current):null}function xte(e,t){return{viewportHydrated:!1,viewportResetVersion:0,lastAppliedViewport:null,lastResetCause:null,trackingState:sp(e,t),pendingAcknowledgement:null}}function Cte(e,t,r=null,o){return{viewportHydrated:!1,viewportResetVersion:e.viewportResetVersion+1,lastAppliedViewport:null,lastResetCause:r,trackingState:sp(t,o),pendingAcknowledgement:null}}function Pte(e){let t=px({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=Tt(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:iF({current:e.state.pendingAcknowledgement,acknowledgementRequestKey:e.acknowledgementRequestKey,compatiblePreviewNavigationRequestKey:o,shouldResetViewport:t.shouldResetViewport,viewportResetVersion:r})};return{nextState:n,changed:!gx(e.state,n)}}function Rte(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=Rt({viewport:t},e.modeOptions);if(!r)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let o=fx({viewport:r,lastAppliedViewport:e.state.lastAppliedViewport,controllerViewport:e.controllerViewport,controllerFlowMode:e.controllerFlowMode,controllerLayoutMode:e.controllerLayoutMode,syncViewportToEditor:e.syncViewportToEditor}),n=wx(e.state.pendingAcknowledgement),i=Tt({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:!gx(e.state,a)}}export{_n as DEFAULT_BROWSER_ZOOM_PERCENT,an as applyBrowserInlineFormatPatch,gf as browserImageCommandIds,Sf as browserImageWrapModes,rc as browserViewportStateHasExplicitModeConflict,sp as captureBrowserPaginatedPreviewTrackingState,Ao as captureBrowserSurfaceSelectionRebaseTarget,re as cloneBrowserViewportState,U0 as createBrowserAdvancedOoxmlInspectorController,Jm as createBrowserEditor,O0 as createBrowserEditorBackendAdapter,v0 as createBrowserEditorController,Pi as createBrowserEditorHost,tp as createBrowserEditorMountController,Ro as createBrowserEditorOverlayHost,wO as createBrowserEditorOverlayHostFromController,fO as createBrowserEditorSessionHostFromController,V0 as createBrowserEditorUiController,Ma as createBrowserEditorUiFromController,In as createBrowserEditorUiHost,gO as createBrowserEditorUiHostFromController,Ta as createBrowserPaginatedPreviewSelectionActionsV1,xte as createBrowserPaginatedPreviewSessionState,qu as createBrowserSelectionCapture,j0 as createSectionLinkActions,D0 as createSectionVariantActions,gc as createSurfaceSelectionAdapter,_t as fillBrowserViewportStateModes,Z0 as handleBrowserPaginatedPreviewPositionHit,tc as hasFreshBrowserViewportRequest,Wl as isBrowserImageCommandId,Kl as isBrowserImageWrapMode,Uo as isBrowserViewportStateCompatibleWithFlowMode,Xo as isBrowserViewportStateCompatibleWithLayoutMode,to as isBrowserViewportStateCompatibleWithModes,qd as normalizeBrowserPreviewControllerNavigationMode,Qa as normalizeBrowserSurfaceReviewSelection,Go as normalizeBrowserViewportAnchor,Kt as normalizeBrowserViewportPageAddress,De as normalizeBrowserViewportRequestKey,vt as normalizeBrowserZoomPercent,fd as readBrowserEditorAutomation,md as readBrowserEditorDocument,pd as readBrowserEditorView,ur as readBrowserZoomPercent,ox as readSectionLinkState,tx as readSectionVariants,qi as readSelectedAdvancedOoxmlRecord,wd as replaceBrowserEditorDocument,jn as replaceBrowserSurfaceDocumentPreservingSelection,Cte as resetBrowserPaginatedPreviewSessionState,qO as resolveBrowserCommentReplayTarget,oa as resolveBrowserCommentWriteReason,kL as resolveBrowserEditorContextMenuContextAtPoint,ho as resolveBrowserEditorPositionAtPoint,nu as resolveBrowserEditorUiController,pr as resolveBrowserInlineFormatDisabledReason,Fh as resolveBrowserPaginatedPreviewAcknowledgementRequestKey,qh as resolveBrowserPaginatedPreviewAnchorPageNumber,bG as resolveBrowserPaginatedPreviewControllerSyncState,fx as resolveBrowserPaginatedPreviewControllerViewportPatch,Hh as resolveBrowserPaginatedPreviewExternalViewportRequest,Wd as resolveBrowserPaginatedPreviewFlowMode,_h as resolveBrowserPaginatedPreviewLayoutMode,nte as resolveBrowserPaginatedPreviewLifecycleResetCause,tF as resolveBrowserPaginatedPreviewModeOptions,Lh as resolveBrowserPaginatedPreviewNavigationRequest,ate as resolveBrowserPaginatedPreviewPinnedPageNumbers,X0 as resolveBrowserPaginatedPreviewPositionHitEvent,px as resolveBrowserPaginatedPreviewResetPlan,zh as resolveBrowserPaginatedPreviewScale,Pte as resolveBrowserPaginatedPreviewSessionUpdate,jh as resolveBrowserPaginatedPreviewSourceBinding,gte as resolveBrowserPaginatedPreviewViewModel,Wh as resolveBrowserPaginatedPreviewViewportAnchor,Zh as resolveBrowserPaginatedPreviewViewportAnchorFromHit,Rte as resolveBrowserPaginatedPreviewViewportObservation,Kh as resolveBrowserPaginatedPreviewViewportRequestKey,ft as resolveBrowserPreservedRangeTargetSelection,Za as resolveBrowserSurfaceProjectionMode,Q as resolveBrowserTextTargetSelection,je as resolveBrowserTextTargetSelectionWithExpectedText,Tt as resolveCompatibleBrowserPreviewNavigationRequest,Rt as resolveCompatibleBrowserPreviewViewport,$o as resolveCompatibleBrowserPreviewViewportAnchor,Pr as resolveProjectedSelectionRebaseRange,Oi as resolveProjectedSelectionTrackedChangeIds,Me as resolveSelectionInfo,Hi as restoreBrowserSurfaceSelectionFromRebaseTarget,ki as restoreTrackedCommentSelectionAfterReviewMutation,Dh as sameBrowserPaginatedPreviewViewportRequest,uG as sameBrowserPaginatedPreviewViewportSyncState,Zo as sameBrowserViewportAnchor,bs as sameBrowserViewportRequestKey,et as sameBrowserViewportState,Un as sameBrowserViewportStateForControllerSync,So as selectBrowserCommentTarget,Pc as selectBrowserTextTarget,es as setSectionLinkedToPrevious,op as setSectionOddEvenHeadersFooters,rp as setSectionTitlePage};