@datalking/begonia-browser-sdk 0.1.1 → 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 (60) 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-controller.d.ts +6 -0
  19. package/dist/browser-paginated-preview-editor-binding.d.ts +76 -1
  20. package/dist/browser-paginated-preview-key-selection.d.ts +48 -0
  21. package/dist/browser-paginated-preview-position-hit.d.ts +28 -0
  22. package/dist/browser-paginated-preview-ui-controller.d.ts +1 -0
  23. package/dist/browser-table-target-resolution.d.ts +59 -0
  24. package/dist/command.js +5 -5
  25. package/dist/editor.d.ts +8 -0
  26. package/dist/editor.js +5 -4
  27. package/dist/header-footer/header-footer-band-geometry.d.ts +70 -0
  28. package/dist/header-footer/header-footer-band-press.d.ts +51 -0
  29. package/dist/header-footer/header-footer-edit-state.d.ts +44 -0
  30. package/dist/header-footer/header-footer-edit-target.d.ts +54 -0
  31. package/dist/header-footer/header-footer-editing-controller.d.ts +133 -0
  32. package/dist/header-footer/header-footer-exit-press.d.ts +54 -0
  33. package/dist/header-footer/header-footer-slot.d.ts +38 -0
  34. package/dist/header-footer/header-footer-story-blocks.d.ts +71 -0
  35. package/dist/header-footer/section-header-footer-links.d.ts +60 -0
  36. package/dist/header-footer/section-header-footer-variants.d.ts +55 -0
  37. package/dist/index.d.ts +35 -1
  38. package/dist/index.js +60 -5
  39. package/dist/ooxml.js +4 -4
  40. package/dist/paginated-editing/index.d.ts +7 -0
  41. package/dist/paginated-editing/paginated-caret-reveal.d.ts +51 -0
  42. package/dist/paginated-editing/paginated-column-keyboard.d.ts +50 -0
  43. package/dist/paginated-editing/paginated-editing-session.d.ts +8 -0
  44. package/dist/paginated-editing/paginated-editing-types.d.ts +169 -0
  45. package/dist/paginated-editing/paginated-ime-caret-measure.d.ts +26 -0
  46. package/dist/paginated-editing/paginated-input-anchor.d.ts +116 -0
  47. package/dist/paginated-editing/paginated-input-bridge.d.ts +169 -0
  48. package/dist/paginated-editing/paginated-table-boundary-keyboard.d.ts +24 -0
  49. package/dist/paginated-editing/paginated-table-boundary-keys.d.ts +33 -0
  50. package/dist/paginated-preview-selection-table/preview-selection-table-exit.d.ts +61 -0
  51. package/dist/paginated-preview-selection-table/preview-selection-table-resolve.d.ts +7 -2
  52. package/dist/preview.js +1 -1
  53. package/dist/theme/theme-presets.d.ts +14 -0
  54. package/dist/theme/theme-resolve.d.ts +21 -0
  55. package/dist/theme/theme-tokens.d.ts +118 -0
  56. package/dist/theme.js +1 -1
  57. package/dist/v1.d.ts +6 -0
  58. package/dist/v1.js +9 -9
  59. package/package.json +14 -14
  60. package/dist/browser-theme.d.ts +0 -26
package/dist/v1.js CHANGED
@@ -1,9 +1,9 @@
1
- import{createDocumentSurface as yj}from"@datalking/begonia-engine";import{createOoxmlFamilyEnvelope as gm}from"@datalking/begonia-engine";var Hi="ald:advanced-ooxml-nodeview-action";function Lr(e){return typeof e=="object"&&e!==null}function nm(e){if(!Lr(e)||typeof e.family!="string"||typeof e.action!="string"||typeof e.objectId!="string")return!1;switch(e.action){case"replace-math-model":return e.family==="math"&&Lr(e.model);case"set-math-plain-text":return e.family==="math"&&typeof e.text=="string"&&(e.displayMode==="inline"||e.displayMode==="block");case"replace-chart-model":return e.family==="chart"&&Lr(e.model);case"replace-shape-model":return e.family==="shape"&&Lr(e.model);case"apply-math-edits":return e.family==="math"&&Lr(e.model)&&Array.isArray(e.edits);case"apply-chart-edits":return e.family==="chart"&&Lr(e.model)&&Array.isArray(e.edits);case"apply-shape-edits":return e.family==="shape"&&Lr(e.model)&&Array.isArray(e.edits);case"remove-advanced-ooxml":return e.family==="math"||e.family==="chart"||e.family==="shape";default:return!1}}function rr(e,t){e.dispatchEvent(new CustomEvent(Hi,{bubbles:!0,cancelable:!0,detail:t}))}function hb(e,t){e.disabled=!t,e.style.opacity=t?"1":"0.65",e.style.cursor=t?"pointer":"default"}function yb(e,t){e.textContent=t?"Local subtree edits pending. Leave this card or press Cmd/Ctrl+Enter to apply.":"Auto-applies when you leave this card. Apply is still available for an immediate commit.",e.style.color=t?"#0f766e":"#64748b",e.style.fontWeight=t?"600":"400"}function ho(e){let t=!1,r=!1,o=null,n=()=>{o!==null&&(window.clearTimeout(o),o=null)},i=()=>{hb(e.applyButton,r),yb(e.status,r)},s=()=>{if(n(),t||!r)return!1;try{let d=e.onCommit();return r=!1,i(),d}catch(d){throw i(),d}},a=()=>{t||!r||(n(),o=window.setTimeout(()=>{o=null,e.root.contains(document.activeElement)||s()},0))},l=()=>{a()},c=d=>{r&&(d.metaKey||d.ctrlKey)&&d.key==="Enter"&&(d.preventDefault(),s())};return e.root.addEventListener("focusout",l),e.root.addEventListener("keydown",c),i(),{destroy(){t=!0,n(),e.root.removeEventListener("focusout",l),e.root.removeEventListener("keydown",c)},flush:s,markDirty(){t||r||(r=!0,i())},reset(){n(),r=!1,i()}}}function Ft(e,t){return Object.assign(e.style,t),e}function yo(e,t=!1){let r=document.createElement(e);return r.contentEditable="false",Ft(r,{display:t?"inline-flex":"grid",gap:"8px",padding:"10px",border:"1px solid #cbd5e1",borderRadius:"14px",background:"#f8fafc",margin:t?"0 4px":"8px 0",minWidth:t?"280px":"100%",boxSizing:"border-box",verticalAlign:"middle"}),r}function bo(e,t){let r=document.createElement("div");Ft(r,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px"});let o=document.createElement("strong");o.textContent=e,Ft(o,{fontSize:"12px",color:"#0f172a"});let n=document.createElement("span");return n.textContent=t,Ft(n,{fontSize:"11px",fontWeight:"600",color:"#475569",background:"#e2e8f0",borderRadius:"999px",padding:"2px 8px"}),r.append(o,n),{header:r,heading:o}}function Bo(){let e=document.createElement("div");return Ft(e,{fontSize:"11px",color:"#64748b"}),e}function Fr(e){let t=document.createElement("section");Ft(t,{display:"grid",gap:"8px",padding:"10px",borderRadius:"12px",background:"#ffffff",border:"1px solid #e2e8f0"});let r=document.createElement("div");return r.textContent=e,Ft(r,{fontSize:"11px",fontWeight:"700",letterSpacing:"0.08em",textTransform:"uppercase",color:"#475569"}),t.append(r),{section:t,title:r}}function zt(e){let t=document.createElement("div");return t.textContent=e,Ft(t,{fontSize:"11px",color:"#64748b"}),t}function or(){let e=document.createElement("div");return Ft(e,{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}),e}function _e(e,t="default"){let r=document.createElement("button");return r.type="button",r.textContent=e,Ft(r,{padding:"6px 12px",borderRadius:"999px",border:t==="danger"?"1px solid #fecaca":"1px solid #99f6e4",background:t==="danger"?"#fff1f2":"#f0fdfa",color:t==="danger"?"#be123c":"#0f766e",fontSize:"12px",fontWeight:"600",cursor:"pointer"}),r}function xo(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement}import{listOoxmlChartAxisIds as im,listOoxmlChartSeriesIds as sm}from"@datalking/begonia-engine";function pe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function bb(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function br(e){return new Set(e).size===e.length}function kn(e,t){let r=new Set(t),o=e.filter(a=>r.has(a)),n=new Set(e),i=t.filter(a=>n.has(a));if(!bb(o,i))return!1;let s=t.findIndex(a=>!n.has(a));return s===-1||t.slice(s).every(a=>!n.has(a))}function Bb(e,t){if(pe(e.series,t.series))return[];let r=sm(e),o=sm(t);if(!br(r)||!br(o)||!kn(r,o))return[{type:"set-series-list",series:[...t.series]}];let n=new Map(e.series.map((a,l)=>[r[l],a])),i=new Map(t.series.map((a,l)=>[o[l],a])),s=[];for(let a=r.length-1;a>=0;a-=1){let l=r[a];i.has(l)||s.push({type:"remove-series",target:l})}return o.forEach(a=>{let l=i.get(a),c=n.get(a);if(!c){s.push({type:"append-series",series:l});return}pe(c,l)||s.push({type:"set-series",target:a,series:l})}),s}function xb(e,t){if(pe(e.axes,t.axes))return[];let r=im(e),o=im(t);if(!br(r)||!br(o)||!kn(r,o))return[{type:"set-axes",axes:[...t.axes]}];let n=new Map(e.axes.map((a,l)=>[r[l],a])),i=new Map(t.axes.map((a,l)=>[o[l],a])),s=[];for(let a=r.length-1;a>=0;a-=1){let l=r[a];i.has(l)||s.push({type:"remove-axis",axisId:l})}return o.forEach(a=>{let l=i.get(a),c=n.get(a);(!c||!pe(c,l))&&s.push({type:"upsert-axis",axisId:a,axis:l})}),s}function am(e,t){if(pe(e,t))return[];let r=[];return(e.title!==t.title||e.chartType!==t.chartType||e.subtitle!==t.subtitle)&&r.push({type:"set-metadata",title:t.title,chartType:t.chartType,subtitle:t.subtitle}),pe(e.textBody,t.textBody)||r.push({type:"set-text-body",textBody:t.textBody}),pe(e.plotArea,t.plotArea)||r.push({type:"set-plot-area",plotArea:t.plotArea}),pe(e.legend,t.legend)||r.push({type:"set-legend",legend:t.legend}),r.push(...xb(e,t)),r.push(...Bb(e,t)),r}import{Schema as Cb}from"prosemirror-model";import{EditorState as Pb}from"prosemirror-state";import{EditorView as Rb}from"prosemirror-view";var Tb=["display:grid","gap:8px","padding:10px","border:1px solid #dbe3ea","border-radius:12px","background:#f8fafc"].join(";"),kb=["font-size:11px","font-weight:700","letter-spacing:0.08em","text-transform:uppercase","color:#334155"].join(";"),Eb=["display:grid","gap:8px","padding-left:8px"].join(";"),Mb=["display:grid","gap:4px"].join(";"),Ib=["font-size:11px","font-weight:600","letter-spacing:0.06em","text-transform:uppercase","color:#64748b"].join(";"),Ab=["min-height:36px","padding:8px 10px","border:1px solid #cbd5e1","border-radius:10px","background:#ffffff","font-size:12px","color:#0f172a","white-space:pre-wrap"].join(";"),Nb=["display:grid","gap:10px","outline:none"].join(";"),kt=new Cb({nodes:{doc:{content:"entry*"},section:{group:"entry",content:"entry*",attrs:{key:{default:""},label:{default:"Section"}},parseDOM:[{tag:"section[data-ald-structured-section]",getAttrs:e=>{let t=e;return{key:t.dataset.key??"",label:t.dataset.label??"Section"}}}],toDOM(e){return["section",{"data-ald-structured-section":"true","data-key":e.attrs.key,"data-label":e.attrs.label,style:Tb},["div",{style:kb},e.attrs.label],["div",{style:Eb},0]]}},field:{group:"entry",content:"text*",marks:"",parseDOM:[{tag:"div[data-ald-structured-field]",getAttrs:e=>{let t=e;return{key:t.dataset.key??"",label:t.dataset.label??"Field"}}}],toDOM(e){return["div",{"data-ald-structured-field":"true","data-key":e.attrs.key,"data-label":e.attrs.label,style:Mb},["div",{style:Ib},e.attrs.label],["div",{style:Ab},0]]}},text:{}}});function Db(e){return kt.nodes.field.create({key:e.key,label:e.label},e.value?kt.text(e.value):void 0)}function Ob(e){let t=e.children.map(Oa);return kt.nodes.section.create({key:e.key,label:e.label},t)}function Oa(e){return e.type==="field"?Db(e):Ob(e)}function jb(e){return kt.nodes.doc.create(null,e.map(Oa))}function lm(e){return e.content.content.map(t=>um(t)).filter(t=>t!==null)}function um(e){return e.type===kt.nodes.field?{type:"field",key:String(e.attrs.key??""),label:String(e.attrs.label??"Field"),value:e.textContent}:e.type===kt.nodes.section?{type:"section",key:String(e.attrs.key??""),label:String(e.attrs.label??"Section"),children:e.content.content.map(t=>um(t)).filter(t=>t!==null)}:null}function cm(e){return Pb.create({schema:kt,doc:jb(e)})}function Vb(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1)if(t.node(r).type===kt.nodes.section)return t.end(r)-1;return e.doc.content.size}function Lb(e){let{$from:t}=e.selection;for(let r=t.depth;r>0;r-=1){let o=t.node(r);if(o.type===kt.nodes.field||o.type===kt.nodes.section)return{from:t.before(r),to:t.before(r)+o.nodeSize}}return null}function dm(e){let{$from:t}=e.selection,r=[],o=e.doc;for(let n=1;n<=t.depth;n+=1){if(t.node(n).type!==kt.nodes.section)continue;let i=String(t.node(n).attrs.key??"").trim();i.length>0&&r.push(i),o=t.node(n)}return{sectionKeys:r,containerKey:r[r.length-1]??null,childKeys:o.content.content.map(n=>String(n.attrs.key??"").trim()).filter(n=>n.length>0)}}function Fb(e){Object.assign(e.style,{display:"grid",gap:"10px",padding:"10px",borderRadius:"12px",border:"1px solid #dbe3ea",background:"#ffffff",minHeight:"160px",boxSizing:"border-box",overflow:"auto"})}function w(e,t,r=""){return{type:"field",key:e,label:t,value:r}}function T(e,t,r=[]){return{type:"section",key:e,label:t,children:[...r]}}function Co(e,t,r={}){Fb(e);let o,n=()=>{r.onSelectionChange?.(dm(o.state))};return o=new Rb(e,{dispatchTransaction(i){let s=o.state.apply(i);o.updateState(s),i.docChanged&&r.onChange?.({entries:lm(s.doc)}),(i.docChanged||i.selectionSet)&&n()},state:cm(t),attributes:{style:Nb,class:"ald-advanced-ooxml-subtree-editor"}}),n(),{dom:e,appendEntry(i){let s=Oa(i),a=Vb(o.state);o.dispatch(o.state.tr.insert(a,s)),o.focus()},destroy(){o.destroy()},focus(){o.focus()},readEntries(){return lm(o.state.doc)},readSelection(){return dm(o.state)},removeSelectedEntry(){let i=Lb(o.state);return i?(o.dispatch(o.state.tr.delete(i.from,i.to)),o.focus(),!0):!1},setEntries(i){o.updateState(cm(i)),n()}}}import{normalizeOoxmlChartModel as Hb}from"@datalking/begonia-engine";function H(e){let t=e.trim();return t.length>0?t:null}function oe(e){let t=e.trim();if(!t)return null;let r=Number(t);return Number.isFinite(r)?r:null}function fe(e){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:null}function Pe(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Re(e){return e==null?"":JSON.stringify(e,null,2)}function C(e,t){let r=e.find(o=>o.type==="field"&&o.key===t);return r?.type==="field"?r.value:""}function pt(e,t){return e.filter(r=>r.type==="section"&&r.key===t)}function ja(e,t){return pt(e,t)[0]??null}function mm(e){return e.type==="field"?e.value.trim().length>0:e.children.some(t=>mm(t))}function zb(e){return e.some(t=>mm(t))}function Te(e,t){let r=ja(e,t);return r&&zb(r.children)?r:null}function Po(e,t,r){let o=r?.paragraphs?.length?r.paragraphs:r?.plainText?[r.plainText]:[];return T(e,t,(o.length>0?o:[""]).map(n=>w("paragraph","Paragraph",n)))}function qi(e){if(!e)return null;let t=e.children.filter(r=>r.type==="field"&&r.key==="paragraph").map(r=>r.value);return t.length===0?null:{paragraphs:t,plainText:t.join(`
2
- `)}}function Wi(e,t){return T(e,t,[w("paragraph","Paragraph","")])}function qb(e){return T("marker","Marker",[w("symbol","Symbol",e.marker?.symbol??""),w("size","Size",e.marker?.size==null?"":String(e.marker.size))])}function Wb(e){return T("data-labels","Data Labels",[w("show-value","Show Value",e.dataLabels?.showValue==null?"":String(e.dataLabels.showValue)),w("show-category","Show Category",e.dataLabels?.showCategory==null?"":String(e.dataLabels.showCategory)),w("show-series-name","Show Series Name",e.dataLabels?.showSeriesName==null?"":String(e.dataLabels.showSeriesName)),w("show-percentage","Show Percentage",e.dataLabels?.showPercentage==null?"":String(e.dataLabels.showPercentage)),w("position","Position",e.dataLabels?.position??""),w("separator","Separator",e.dataLabels?.separator??"")])}function Kb(e){return T("series","Series",[w("id","Series Id",e.id??""),w("order","Order",e.order==null?"":String(e.order)),w("name","Name",e.name??""),w("categories","Categories",e.categories.join(", ")),w("values","Values",e.values.map(t=>t==null?"":String(t)).join(", ")),w("color","Color",e.color??""),w("smooth","Smooth",e.smooth==null?"":String(e.smooth)),w("explosion","Explosion",e.explosion==null?"":String(e.explosion)),qb(e),Wb(e)])}function _b(e){return T("axis","Axis",[w("id","Axis Id",e.id??""),w("kind","Kind",e.kind??""),w("title","Title",e.title??""),w("format-code","Format Code",e.formatCode??""),w("orientation","Orientation",e.orientation??""),w("visible","Visible",e.visible==null?"":String(e.visible)),w("minimum","Minimum",e.minimum==null?"":String(e.minimum)),w("maximum","Maximum",e.maximum==null?"":String(e.maximum)),w("major-unit","Major Unit",e.majorUnit==null?"":String(e.majorUnit)),w("minor-unit","Minor Unit",e.minorUnit==null?"":String(e.minorUnit)),w("crosses-at","Crosses At",e.crossesAt==null?"":String(e.crossesAt)),w("major-gridlines","Major Gridlines",e.majorGridlines==null?"":String(e.majorGridlines)),w("minor-gridlines","Minor Gridlines",e.minorGridlines==null?"":String(e.minorGridlines))])}function Ub(e){return T("legend","Legend",[w("visible","Visible",e.legend==null?"":String(e.legend.visible)),w("position","Position",e.legend?.position??""),w("overlay","Overlay",e.legend?.overlay==null?"":String(e.legend.overlay))])}function Zb(e){return T("plot-area","Plot Area",[w("stacked","Stacked",e.plotArea?.stacked==null?"":String(e.plotArea.stacked)),w("percent-stacked","Percent Stacked",e.plotArea?.percentStacked==null?"":String(e.plotArea.percentStacked)),w("vary-colors","Vary Colors",e.plotArea?.varyColors==null?"":String(e.plotArea.varyColors)),w("hole-size","Hole Size",e.plotArea?.holeSize==null?"":String(e.plotArea.holeSize))])}function Gb(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Xb(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>{let r=Number(t);return Number.isFinite(r)?r:null})}function $b(e){return e.length>0?e:null}function Yb(e){let t=Te(e,"marker"),r=Te(e,"data-labels");return{id:H(C(e,"id")),order:oe(C(e,"order")),name:H(C(e,"name")),categories:Gb(C(e,"categories")),values:Xb(C(e,"values")),color:H(C(e,"color")),marker:t?{symbol:H(C(t.children,"symbol"))??"unknown",size:oe(C(t.children,"size"))}:null,dataLabels:r?{showValue:fe(C(r.children,"show-value")),showCategory:fe(C(r.children,"show-category")),showSeriesName:fe(C(r.children,"show-series-name")),showPercentage:fe(C(r.children,"show-percentage")),position:H(C(r.children,"position")),separator:$b(C(r.children,"separator"))}:null,smooth:fe(C(e,"smooth")),explosion:oe(C(e,"explosion"))}}function Jb(e){let t=C(e,"kind"),r=C(e,"orientation");return{id:H(C(e,"id")),kind:t==="category"||t==="value"||t==="series"||t==="date"?t:"unknown",title:H(C(e,"title")),formatCode:H(C(e,"format-code")),orientation:r==="minMax"||r==="maxMin"?r:null,visible:fe(C(e,"visible")),minimum:oe(C(e,"minimum")),maximum:oe(C(e,"maximum")),majorUnit:oe(C(e,"major-unit")),minorUnit:oe(C(e,"minor-unit")),crossesAt:oe(C(e,"crosses-at")),majorGridlines:fe(C(e,"major-gridlines")),minorGridlines:fe(C(e,"minor-gridlines"))}}function pm(e){return[w("title","Title",e.title??""),w("chart-type","Chart Type",e.chartType??""),w("subtitle","Subtitle",e.subtitle??""),Po("text-body","Text Body",e.textBody),Zb(e),...e.series.map(t=>Kb(t)),...e.axes.map(t=>_b(t)),Ub(e)]}function fm(e,t){let r=Te(e,"text-body"),o=Te(e,"plot-area"),n=Te(e,"legend");return Hb({...t,title:H(C(e,"title")),chartType:H(C(e,"chart-type")),subtitle:H(C(e,"subtitle")),textBody:qi(r),plotArea:o?{stacked:fe(C(o.children,"stacked")),percentStacked:fe(C(o.children,"percent-stacked")),varyColors:fe(C(o.children,"vary-colors")),holeSize:oe(C(o.children,"hole-size"))}:null,series:pt(e,"series").map(i=>Yb(i.children)),axes:pt(e,"axis").map(i=>Jb(i.children)),legend:n?{visible:fe(C(n.children,"visible"))!==!1,position:H(C(n.children,"position"))??"unknown",overlay:fe(C(n.children,"overlay"))}:null},t.title??"Chart")}function Qb(){return T("series","Series",[w("id","Series Id",""),w("order","Order",""),w("name","Name",""),w("categories","Categories",""),w("values","Values",""),w("color","Color",""),w("smooth","Smooth",""),w("explosion","Explosion",""),T("marker","Marker",[w("symbol","Symbol",""),w("size","Size","")]),T("data-labels","Data Labels",[w("show-value","Show Value",""),w("show-category","Show Category",""),w("show-series-name","Show Series Name",""),w("show-percentage","Show Percentage",""),w("position","Position",""),w("separator","Separator","")])])}function eB(){return T("axis","Axis",[w("id","Axis Id",""),w("kind","Kind","category"),w("title","Title",""),w("format-code","Format Code",""),w("orientation","Orientation",""),w("visible","Visible",""),w("minimum","Minimum",""),w("maximum","Maximum",""),w("major-unit","Major Unit",""),w("minor-unit","Minor Unit",""),w("crosses-at","Crosses At",""),w("major-gridlines","Major Gridlines",""),w("minor-gridlines","Minor Gridlines","")])}function tB(){return T("legend","Legend",[w("visible","Visible","true"),w("position","Position","right"),w("overlay","Overlay","")])}function rB(){return T("plot-area","Plot Area",[w("stacked","Stacked",""),w("percent-stacked","Percent Stacked",""),w("vary-colors","Vary Colors",""),w("hole-size","Hole Size","")])}function oB(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function nB(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function iB(e){return e==null}function wm(e={}){let t=oB(e.containerKey),r=nB(e.childKeys),o=n=>r.has(n);return t==="text-body"?[{label:"Paragraph",createEntry:()=>w("paragraph","Paragraph","")}]:iB(t)?[{label:"Series",createEntry:Qb},{label:"Axis",createEntry:eB},...o("legend")?[]:[{label:"Legend",createEntry:tB}],...o("plot-area")?[]:[{label:"Plot Area",createEntry:rB}],...o("text-body")?[]:[{label:"Text Body",createEntry:()=>Wi("text-body","Text Body")}]]:[]}function Va(e){let t=String(e.attrs.label??"Chart"),r=String(e.attrs.text??""),o=gm("chart",{title:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=gm("chart",e.attrs.familyData,{label:t,text:r})??o;return{objectId:String(e.attrs.objectId??""),label:t,model:n.data.model??o.data.model,evidence:n.evidence}}function sB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function Sm(){return e=>{let t=e,r=yo("div"),{header:o,heading:n}=bo("Chart","chart"),i=Bo(),{section:s}=Fr("Native Subtree"),a=zt("Edit chart metadata, series, axes, legend, and plot area as a structured nested tree. Use insert buttons at the current subtree selection. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),l=or();l.style.justifyContent="flex-start";let c=_e("Remove Selected","danger"),d=sB(),u=or();u.style.justifyContent="space-between",u.style.alignItems="center";let m=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=_e("Apply"),f=_e("Remove Chart","danger");m.style.marginRight="auto",u.append(m,p,f),s.append(a,l,d,c),r.append(o,i,s,u);let g=null,v=(P,h)=>{l.replaceChildren(),wm({containerKey:P,childKeys:h}).forEach(b=>{let x=_e(b.label);x.addEventListener("click",()=>{E.appendEntry(b.createEntry())}),l.append(x)})},E=Co(d,[],{onChange(){g?.markDirty()},onSelectionChange(P){v(P.containerKey,P.childKeys)}});c.addEventListener("click",()=>{E.removeSelectedEntry()}),g=ho({applyButton:p,onCommit:()=>{let P=Va(t),h=fm(E.readEntries(),P.model),b=am(P.model,h);return b.length===0?!1:(rr(r,{family:"chart",action:"apply-chart-edits",objectId:P.objectId,model:h,edits:b}),!0)},root:r,status:m});let S=P=>{t=P;let h=Va(P);n.textContent=h.label,i.textContent=`${h.evidence.chartType??"chart"} | ${h.evidence.seriesCount} series | ${h.evidence.axisCount} axes`,g?.reset(),E.setEntries(pm(h.model))};return p.addEventListener("click",()=>{g?.flush()}),f.addEventListener("click",()=>{g?.reset();let P=Va(t);rr(r,{family:"chart",action:"remove-advanced-ooxml",objectId:P.objectId})}),S(e),{dom:r,destroy(){g?.destroy(),E.destroy()},update(P){return P.type!==t.type?!1:(S(P),!0)},stopEvent(P){return xo(P.target)||P.target instanceof Node&&d.contains(P.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as Bm,normalizeOoxmlMathModel as VB}from"@datalking/begonia-engine";function vm(e,t){if(pe(e,t))return[];if(e.root.type==="text"&&t.root.type==="text"){let r=e.root.value,o=t.root.value;return r!==o?[{type:"set-plain-text",text:o,displayMode:t.displayMode}]:e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[]}return t.root.type==="text"?[{type:"set-plain-text",text:t.root.value,displayMode:t.displayMode}]:pe(e.root,t.root)&&e.displayMode!==t.displayMode?[{type:"set-display-mode",displayMode:t.displayMode}]:[{type:"replace-model",model:t}]}import{normalizeOoxmlMathModel as jB}from"@datalking/begonia-engine";import{createOoxmlMathTextNode as aB}from"@datalking/begonia-engine";var lB=new Set(["numerator","denominator","body","degree","base","superscript-slot","subscript-slot","lower","upper","name","argument","matrix-cell","equation-row"]);function La(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function hm(e){let t=La(e);return t==null||lB.has(t)}function Fa(e){return aB(e)}function za(){return Fa("")}function cB(e=""){return w("text","Text",e)}function ue(e,t){return T(e,t,[cB()])}function ym(e){throw new Error(`Unsupported math node type: ${JSON.stringify(e)}.`)}function ke(e){return hm(e)}function dB(){return T("fraction","Fraction",[ue("numerator","Numerator"),ue("denominator","Denominator")])}function uB(){return T("radical","Radical",[ue("body","Body"),T("degree","Degree",[])])}function mB(){return T("superscript","Superscript",[ue("base","Base"),ue("superscript-slot","Superscript")])}function pB(){return T("subscript","Subscript",[ue("base","Base"),ue("subscript-slot","Subscript")])}function fB(){return T("subsup","Subscript and Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function wB(){return T("preSubSup","Pre-Sub/Superscript",[ue("base","Base"),ue("subscript-slot","Subscript"),ue("superscript-slot","Superscript")])}function gB(){return T("matrix","Matrix",[T("matrix-row","Row",[T("matrix-cell","Cell",[w("text","Text","")])])])}function SB(){return T("equationArray","Equation Array",[T("equation-row","Row",[w("text","Text","")])])}function vB(){return T("delimiter","Delimiter",[w("begin","Begin Delimiter","("),w("end","End Delimiter",")"),ue("body","Body")])}function hB(){return T("operator","Operator",[w("operator-symbol","Operator","sum"),ue("body","Body"),T("lower","Lower",[]),T("upper","Upper",[])])}function yB(){return T("nary","N-ary Operator",[w("operator-symbol","Operator","prod"),ue("body","Body"),T("subscript-slot","Subscript",[]),T("superscript-slot","Superscript",[])])}function bB(){return T("limitLower","Lower Limit",[ue("base","Base"),ue("lower","Lower")])}function BB(){return T("limitUpper","Upper Limit",[ue("base","Base"),ue("upper","Upper")])}function xB(){return T("function","Function",[ue("name","Name"),ue("argument","Argument")])}function CB(){return T("accent","Accent",[w("accent-symbol","Accent","hat"),ue("body","Body")])}function PB(){return T("bar","Bar",[w("bar-position","Position","top"),ue("body","Body")])}function RB(){return T("box","Box",[w("border-box","Border Box","true"),ue("body","Body")])}function TB(){return T("groupCharacter","Group Character",[w("group-character","Character","_"),w("group-position","Position","bottom"),ue("body","Body")])}function kB(){return T("phantom","Phantom",[w("zero-width","Zero Width","false"),w("zero-ascent","Zero Ascent","false"),w("zero-descent","Zero Descent","false"),w("transparent","Transparent","true"),ue("body","Body")])}function EB(){return T("matrix-row","Row",[T("matrix-cell","Cell",[w("text","Text","")])])}function MB(){return T("matrix-cell","Cell",[w("text","Text","")])}function IB(){return T("equation-row","Row",[w("text","Text","")])}var AB=[{label:"Text",createEntry:()=>w("text","Text",""),supportsContainer:ke},{label:"Fraction",createEntry:dB,supportsContainer:ke},{label:"Radical",createEntry:uB,supportsContainer:ke},{label:"Superscript",createEntry:mB,supportsContainer:ke},{label:"Subscript",createEntry:pB,supportsContainer:ke},{label:"Sub+Sup",createEntry:fB,supportsContainer:ke},{label:"Pre-Sub/Sup",createEntry:wB,supportsContainer:ke},{label:"Matrix",createEntry:gB,supportsContainer:ke},{label:"Matrix Row",createEntry:EB,supportsContainer:e=>e==="matrix"},{label:"Matrix Cell",createEntry:MB,supportsContainer:e=>e==="matrix-row"},{label:"Equation Array",createEntry:SB,supportsContainer:ke},{label:"Equation Row",createEntry:IB,supportsContainer:e=>e==="equationArray"},{label:"Delimiter",createEntry:vB,supportsContainer:ke},{label:"Operator",createEntry:hB,supportsContainer:ke},{label:"N-ary",createEntry:yB,supportsContainer:ke},{label:"Lower Limit",createEntry:bB,supportsContainer:ke},{label:"Upper Limit",createEntry:BB,supportsContainer:ke},{label:"Function",createEntry:xB,supportsContainer:ke},{label:"Accent",createEntry:CB,supportsContainer:ke},{label:"Bar",createEntry:PB,supportsContainer:ke},{label:"Box",createEntry:RB,supportsContainer:ke},{label:"Group Char",createEntry:TB,supportsContainer:ke},{label:"Phantom",createEntry:kB,supportsContainer:ke}];function Ha(e={}){let t=La(e.containerKey);return AB.filter(r=>r.supportsContainer(t)).map(({label:r,createEntry:o})=>({label:r,createEntry:o}))}function ie(e,t){return ja(e,t)?.children??[]}function NB(e){let t=e.map(r=>OB(r)).filter(r=>r!==null);return t.length===0?za():t.length===1?t[0]:{type:"sequence",items:t}}function Ki(e){return e.length>0?ne(e):null}function DB(e){let t=pt(e,"matrix-cell").map(r=>ne(r.children));return t.length>0?t:[za()]}function OB(e){if(e.type==="field")return e.key==="text"?Fa(e.value):null;switch(e.key){case"fraction":return{type:"fraction",numerator:ne(ie(e.children,"numerator")),denominator:ne(ie(e.children,"denominator"))};case"radical":{let t=ie(e.children,"degree");return{type:"radical",body:ne(ie(e.children,"body")),degree:t.length>0?ne(t):null}}case"superscript":return{type:"superscript",base:ne(ie(e.children,"base")),superscript:ne(ie(e.children,"superscript-slot"))};case"subscript":return{type:"subscript",base:ne(ie(e.children,"base")),subscript:ne(ie(e.children,"subscript-slot"))};case"subsup":return{type:"subsup",base:ne(ie(e.children,"base")),subscript:ne(ie(e.children,"subscript-slot")),superscript:ne(ie(e.children,"superscript-slot"))};case"preSubSup":return{type:"preSubSup",base:ne(ie(e.children,"base")),subscript:ne(ie(e.children,"subscript-slot")),superscript:ne(ie(e.children,"superscript-slot"))};case"matrix":return{type:"matrix",rows:pt(e.children,"matrix-row").map(t=>DB(t.children))};case"equationArray":return{type:"equationArray",rows:pt(e.children,"equation-row").map(t=>ne(t.children))};case"delimiter":return{type:"delimiter",begin:H(C(e.children,"begin")),end:H(C(e.children,"end")),body:ne(ie(e.children,"body"))};case"operator":return{type:"operator",operator:H(C(e.children,"operator-symbol")),body:ne(ie(e.children,"body")),lower:Ki(ie(e.children,"lower")),upper:Ki(ie(e.children,"upper"))};case"nary":return{type:"nary",operator:H(C(e.children,"operator-symbol")),body:ne(ie(e.children,"body")),subscript:Ki(ie(e.children,"subscript-slot")),superscript:Ki(ie(e.children,"superscript-slot"))};case"limitLower":return{type:"limitLower",base:ne(ie(e.children,"base")),lower:ne(ie(e.children,"lower"))};case"limitUpper":return{type:"limitUpper",base:ne(ie(e.children,"base")),upper:ne(ie(e.children,"upper"))};case"function":return{type:"function",name:ne(ie(e.children,"name")),argument:ne(ie(e.children,"argument"))};case"accent":return{type:"accent",accent:H(C(e.children,"accent-symbol")),body:ne(ie(e.children,"body"))};case"bar":{let t=C(e.children,"bar-position").trim().toLowerCase();return{type:"bar",position:t==="top"||t==="bottom"?t:"unknown",body:ne(ie(e.children,"body"))}}case"box":return{type:"box",body:ne(ie(e.children,"body")),borderBox:fe(C(e.children,"border-box"))};case"groupCharacter":{let t=C(e.children,"group-position").trim().toLowerCase();return{type:"groupCharacter",character:H(C(e.children,"group-character")),position:t==="top"||t==="bottom"?t:"unknown",body:ne(ie(e.children,"body"))}}case"phantom":return{type:"phantom",body:ne(ie(e.children,"body")),zeroWidth:fe(C(e.children,"zero-width")),zeroAscent:fe(C(e.children,"zero-ascent")),zeroDescent:fe(C(e.children,"zero-descent")),transparent:fe(C(e.children,"transparent"))};default:return e.children.length>0?ne(e.children):null}}function ne(e){return NB(e)}function te(e){switch(e.type){case"sequence":return e.items.flatMap(t=>te(t));case"text":return[w("text","Text",e.value)];case"fraction":return[T("fraction","Fraction",[T("numerator","Numerator",te(e.numerator)),T("denominator","Denominator",te(e.denominator))])];case"radical":return[T("radical","Radical",[T("body","Body",te(e.body)),T("degree","Degree",e.degree?te(e.degree):[])])];case"superscript":return[T("superscript","Superscript",[T("base","Base",te(e.base)),T("superscript-slot","Superscript",te(e.superscript))])];case"subscript":return[T("subscript","Subscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript))])];case"subsup":return[T("subsup","Subscript and Superscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript)),T("superscript-slot","Superscript",te(e.superscript))])];case"preSubSup":return[T("preSubSup","Pre-Sub/Superscript",[T("base","Base",te(e.base)),T("subscript-slot","Subscript",te(e.subscript)),T("superscript-slot","Superscript",te(e.superscript))])];case"matrix":return[T("matrix","Matrix",e.rows.map(t=>T("matrix-row","Row",t.map(r=>T("matrix-cell","Cell",te(r))))))];case"equationArray":return[T("equationArray","Equation Array",e.rows.map(t=>T("equation-row","Row",te(t))))];case"delimiter":return[T("delimiter","Delimiter",[w("begin","Begin Delimiter",e.begin??""),w("end","End Delimiter",e.end??""),T("body","Body",te(e.body))])];case"operator":return[T("operator","Operator",[w("operator-symbol","Operator",e.operator??""),T("body","Body",te(e.body)),T("lower","Lower",e.lower?te(e.lower):[]),T("upper","Upper",e.upper?te(e.upper):[])])];case"nary":return[T("nary","N-ary Operator",[w("operator-symbol","Operator",e.operator??""),T("body","Body",te(e.body)),T("subscript-slot","Subscript",e.subscript?te(e.subscript):[]),T("superscript-slot","Superscript",e.superscript?te(e.superscript):[])])];case"limitLower":return[T("limitLower","Lower Limit",[T("base","Base",te(e.base)),T("lower","Lower",te(e.lower))])];case"limitUpper":return[T("limitUpper","Upper Limit",[T("base","Base",te(e.base)),T("upper","Upper",te(e.upper))])];case"function":return[T("function","Function",[T("name","Name",te(e.name)),T("argument","Argument",te(e.argument))])];case"accent":return[T("accent","Accent",[w("accent-symbol","Accent",e.accent??""),T("body","Body",te(e.body))])];case"bar":return[T("bar","Bar",[w("bar-position","Position",e.position),T("body","Body",te(e.body))])];case"box":return[T("box","Box",[w("border-box","Border Box",e.borderBox==null?"":String(e.borderBox)),T("body","Body",te(e.body))])];case"groupCharacter":return[T("groupCharacter","Group Character",[w("group-character","Character",e.character??""),w("group-position","Position",e.position),T("body","Body",te(e.body))])];case"phantom":return[T("phantom","Phantom",[w("zero-width","Zero Width",e.zeroWidth==null?"":String(e.zeroWidth)),w("zero-ascent","Zero Ascent",e.zeroAscent==null?"":String(e.zeroAscent)),w("zero-descent","Zero Descent",e.zeroDescent==null?"":String(e.zeroDescent)),w("transparent","Transparent",e.transparent==null?"":String(e.transparent)),T("body","Body",te(e.body))])]}return ym(e)}function qa(e){return[w("display-mode","Display Mode",e.displayMode),...te(e.root)]}function bm(e){let r=C(e,"display-mode").trim().toLowerCase()==="block"?"block":"inline",o=e.filter(n=>!(n.type==="field"&&n.key==="display-mode"));return jB({displayMode:r,root:ne(o)},"",r)}function Wa(e){let t=String(e.attrs.text??""),r=String(e.attrs.label??"Equation"),o=Bm("math",{plainText:t,displayMode:"inline"},{label:r,text:t}),n=Bm("math",e.attrs.familyData,{label:r,text:t})??o,i=VB(n.data,n.data.plainText??t,n.data.displayMode??"inline");return{objectId:String(e.attrs.objectId??""),label:r,model:i,evidence:n.evidence}}function LB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%",maxWidth:"720px"}),e}function xm(){return e=>{let t=e,r=yo("span",!0);Object.assign(r.style,{display:"inline-grid",width:"min(720px, 100%)",verticalAlign:"top"});let{header:o,heading:n}=bo("Equation","math"),i=Bo(),{section:s}=Fr("Native Subtree"),a=zt("Edit the equation as a nested ProseMirror tree. Insert structures into the selected slot. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),l=or();l.style.justifyContent="flex-start";let c=_e("Remove Selected","danger"),d=LB(),u=or();u.style.justifyContent="space-between",u.style.alignItems="center";let m=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),p=_e("Apply"),f=_e("Remove Equation","danger");m.style.marginRight="auto",u.append(m,p,f),s.append(a,l,d,c),r.append(o,i,s,u);let g=null,v=P=>{l.replaceChildren(),Ha({containerKey:P}).forEach(h=>{let b=_e(h.label);b.addEventListener("click",()=>{E.appendEntry(h.createEntry())}),l.append(b)})},E=Co(d,[],{onChange(){g?.markDirty()},onSelectionChange(P){v(P.containerKey)}});c.addEventListener("click",()=>{E.removeSelectedEntry()}),g=ho({applyButton:p,onCommit:()=>{let P=Wa(t),h=bm(E.readEntries()),b=vm(P.model,h);return b.length===0?!1:(rr(r,{family:"math",action:"apply-math-edits",objectId:P.objectId,model:h,edits:b}),!0)},root:r,status:m});let S=P=>{t=P;let h=Wa(P);n.textContent=h.label,i.textContent=`${h.evidence.displayMode} | root ${h.evidence.rootType} | ${h.evidence.structureCount} structures`,g?.reset(),E.setEntries(qa(h.model))};return p.addEventListener("click",()=>{g?.flush()}),f.addEventListener("click",()=>{g?.reset();let P=Wa(t);rr(r,{family:"math",action:"remove-advanced-ooxml",objectId:P.objectId})}),S(e),{dom:r,destroy(){g?.destroy(),E.destroy()},update(P){return P.type!==t.type?!1:(S(P),!0)},stopEvent(P){return xo(P.target)||P.target instanceof Node&&d.contains(P.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{createOoxmlFamilyEnvelope as qm,createOoxmlShapePreview as YB}from"@datalking/begonia-engine";function Cm(e){return e.map((t,r)=>t.id??`shape-child-${r+1}`)}function Pm(e,t){return pe({...e,children:[]},{...t,children:[]})}function Ka(e,t,r){for(let o=0;o<e.length;o+=1){let n=e[o],i=n.id?.trim(),s=e[o+1]?.id?.trim()??null;if(!i||r.has(i)||e[o+1]&&!s||(r.set(i,{child:n,parentId:t,beforeId:s}),!Ka(n.children,i,r)))return!1}return!0}function FB(e,t){return e.size===t.size&&[...t.keys()].every(r=>e.has(r))}function zB(e,t){return{...t,children:[...e.children]}}function Rm(e,t,r){t.forEach(o=>{let n=o.id?.trim();if(!n)return;let i=e.get(n);i&&!Pm(i.child,o)&&r.push({type:"set-child",target:n,child:zB(i.child,o)}),Rm(e,o.children,r)})}function Tm(e,t,r,o){let n=null;for(let i=t.length-1;i>=0;i-=1){let s=t[i],a=s.id?.trim();if(!a)continue;let l=e.get(a);l&&(l.parentId!==r||l.beforeId!==n)&&o.push({type:"move-child",target:a,parentTarget:r,beforeTarget:n}),Tm(e,s.children,a,o),n=a}}function HB(e,t){let r=new Map,o=new Map;if(!Ka(e,null,r)||!Ka(t,null,o)||!FB(r,o))return null;let n=[];return Rm(r,t,n),Tm(r,t,null,n),n}function qB(e,t,r){return t==null||r==null?[{type:"set-children",children:[...e]}]:[{type:"set-child",target:t,child:r}]}function km(e,t,r,o){if(pe(e,t))return[];let n=Cm(e),i=Cm(t);if(!br(n)||!br(i)||!kn(n,i))return qB(t,r,o);let s=new Map(e.map((c,d)=>[n[d],c])),a=new Map(t.map((c,d)=>[i[d],c])),l=[];for(let c=n.length-1;c>=0;c-=1){let d=n[c];a.has(d)||l.push({type:"remove-child",target:d})}return i.forEach(c=>{let d=a.get(c),u=s.get(c);if(!u){l.push(r==null?{type:"append-child",child:d}:{type:"append-child-to-parent",parentTarget:r,child:d});return}if(!Pm(u,d)){l.push({type:"set-child",target:c,child:d});return}l.push(...km(u.children,d.children,c,d))}),l}function Em(e,t){if(pe(e,t))return[];if(!pe(e.groupTransform,t.groupTransform))return[{type:"replace-model",model:t}];let r=[];(e.label!==t.label||e.shapeType!==t.shapeType||e.groupKind!==t.groupKind)&&r.push({type:"set-metadata",label:t.label,shapeType:t.shapeType,groupKind:t.groupKind}),(e.isWatermark??!1)!==(t.isWatermark??!1)&&r.push({type:"set-watermark",isWatermark:t.isWatermark??!1}),pe(e.textBody,t.textBody)||r.push({type:"set-text-body",paragraphs:t.textBody?.paragraphs?[...t.textBody.paragraphs]:[]}),pe(e.geometry,t.geometry)||r.push({type:"set-geometry",geometry:t.geometry}),pe(e.transform,t.transform)||r.push({type:"set-transform",transform:t.transform}),pe(e.fill,t.fill)||r.push({type:"set-fill",fill:t.fill}),pe(e.stroke,t.stroke)||r.push({type:"set-stroke",stroke:t.stroke}),pe(e.effects,t.effects)||r.push({type:"set-effects",effects:t.effects??null}),pe(e.anchor,t.anchor)||r.push({type:"set-anchor",anchor:t.anchor}),pe(e.connector,t.connector)||r.push({type:"set-connector",connector:t.connector}),pe(e.picture,t.picture)||r.push({type:"set-picture",picture:t.picture}),pe(e.wordArt,t.wordArt)||r.push({type:"set-word-art",wordArt:t.wordArt});let o=HB(e.children,t.children);return o?(r.push(...o),r):(r.push(...km(e.children,t.children,null,null)),r)}function Mm(e){return T("shape-child","Child Object",[w("kind","Kind",e.kind??""),w("id","Id",e.id??""),w("label","Label",e.label??""),Po("text-body","Text Body",e.textBody),_a(e.geometry),Ua(e.transform),Za(e.groupTransform??null),Ga(e.fill??null),Xa(e.stroke??null),$a(e.effects??null),Ya(e.connector),Ja(e.picture),Qa(e.wordArt),...e.children.map(t=>Mm(t))])}function _a(e){return T("geometry","Geometry",[w("preset","Preset",e?.preset??""),w("custom-path-count","Custom Path Count",e?.customPathCount==null?"":String(e.customPathCount)),w("adjustments","Adjustments",e?.adjustments.join(", ")??""),w("custom-geometry-json","Custom Geometry JSON",Re(e?.customGeometry??null))])}function Ua(e){return T("transform","Transform",[w("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),w("height-emu","Height (EMU)",e?.heightEmu==null?"":String(e.heightEmu)),w("offset-x-emu","Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),w("offset-y-emu","Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),w("rotation","Rotation",e?.rotation==null?"":String(e.rotation)),w("flip-h","Flip H",e?.flipH==null?"":String(e.flipH)),w("flip-v","Flip V",e?.flipV==null?"":String(e.flipV))])}function Za(e){return T("group-transform","Group Transform",[w("child-offset-x-emu","Child Offset X (EMU)",e?.childOffsetXEmu==null?"":String(e.childOffsetXEmu)),w("child-offset-y-emu","Child Offset Y (EMU)",e?.childOffsetYEmu==null?"":String(e.childOffsetYEmu)),w("child-width-emu","Child Width (EMU)",e?.childWidthEmu==null?"":String(e.childWidthEmu)),w("child-height-emu","Child Height (EMU)",e?.childHeightEmu==null?"":String(e.childHeightEmu))])}function Ga(e){return T("fill","Fill",[w("kind","Kind",e?.kind??""),w("color","Color",e?.color??""),w("secondary-color","Secondary Color",e?.secondaryColor??""),w("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),w("gradient-angle","Gradient Angle",e?.gradientAngle==null?"":String(e.gradientAngle)),w("gradient-path","Gradient Path",e?.gradientPath??""),w("pattern-preset","Pattern Preset",e?.patternPreset??""),w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("color-source-json","Color Source JSON",Re(e?.colorSource??null)),w("secondary-color-source-json","Secondary Color Source JSON",Re(e?.secondaryColorSource??null)),w("gradient-stops-json","Gradient Stops JSON",e?Re(e.gradientStops??[]):""),w("picture-fill-json","Picture Fill JSON",Re(e?.pictureFill??null))])}function Xa(e){return T("stroke","Stroke",[w("kind","Kind",e?.kind??""),w("color","Color",e?.color??""),w("width-emu","Width (EMU)",e?.widthEmu==null?"":String(e.widthEmu)),w("dash","Dash",e?.dash??""),w("cap","Cap",e?.cap??""),w("join","Join",e?.join??""),w("opacity","Opacity",e?.opacity==null?"":String(e.opacity)),w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("compound","Compound",e?.compound??""),w("color-source-json","Color Source JSON",Re(e?.colorSource??null)),w("head-end-json","Head End JSON",Re(e?.headEnd??null)),w("tail-end-json","Tail End JSON",Re(e?.tailEnd??null))])}function $a(e){return T("effects","Effects",[w("style-ref-index","Style Ref Index",e?.styleRefIndex==null?"":String(e.styleRefIndex)),w("style-ref-color-source-json","Style Ref Color Source JSON",Re(e?.styleRefColorSource??null)),w("effect-nodes-json","Effect Nodes JSON",e?Re(e.effectNodes??[]):""),w("glow-json","Glow JSON",Re(e?.glow??null)),w("outer-shadow-json","Outer Shadow JSON",Re(e?.outerShadow??null)),w("inner-shadow-json","Inner Shadow JSON",Re(e?.innerShadow??null)),w("soft-edge-json","Soft Edge JSON",Re(e?.softEdge??null)),w("blur-json","Blur JSON",Re(e?.blur??null)),w("reflection-json","Reflection JSON",Re(e?.reflection??null)),w("preset-shadow-json","Preset Shadow JSON",Re(e?.presetShadow??null)),w("effect-dag-json","Effect DAG JSON",Re(e?.effectDag??null))])}function WB(e){return T("anchor","Anchor",[w("kind","Kind",e?.kind??""),w("wrap","Wrap",e?.wrap??""),w("behind-doc","Behind Doc",e?.behindDoc==null?"":String(e.behindDoc)),w("allow-overlap","Allow Overlap",e?.allowOverlap==null?"":String(e.allowOverlap)),w("layout-in-cell","Layout In Cell",e?.layoutInCell==null?"":String(e.layoutInCell)),w("relative-height","Relative Height",e?.relativeHeight==null?"":String(e.relativeHeight)),w("dist-top-emu","Dist Top (EMU)",e?.distTopEmu==null?"":String(e.distTopEmu)),w("dist-bottom-emu","Dist Bottom (EMU)",e?.distBottomEmu==null?"":String(e.distBottomEmu)),w("dist-left-emu","Dist Left (EMU)",e?.distLeftEmu==null?"":String(e.distLeftEmu)),w("dist-right-emu","Dist Right (EMU)",e?.distRightEmu==null?"":String(e.distRightEmu)),w("position-h","Position H",e?.positionH??""),w("position-v","Position V",e?.positionV??""),w("offset-x-emu","Anchor Offset X (EMU)",e?.offsetXEmu==null?"":String(e.offsetXEmu)),w("offset-y-emu","Anchor Offset Y (EMU)",e?.offsetYEmu==null?"":String(e.offsetYEmu)),w("align-h","Align H",e?.alignH??""),w("align-v","Align V",e?.alignV??"")])}function Ya(e){return T("connector","Connector",[w("connector-type","Connector Type",e?.connectorType??""),w("begin-shape-id","Begin Shape Id",e?.beginShapeId??""),w("end-shape-id","End Shape Id",e?.endShapeId??"")])}function Ja(e){return T("picture","Picture",[w("src","Source",e?.src??""),w("alt","Alt",e?.alt??""),w("title","Title",e?.title??""),w("relationship-id","Relationship Id",e?.relationshipId??""),w("blip-fill-json","Blip Fill JSON",Re(e?.blipFill??null)),w("hyperlink-url","Hyperlink URL",e?.hyperlink?.url??""),w("hyperlink-tooltip","Hyperlink Tooltip",e?.hyperlink?.tooltip??"")])}function Qa(e){return T("word-art","WordArt",[w("text","Text",e?.text??""),w("preset","Preset",e?.preset??"")])}function el(e){return[w("label","Label",e.label??""),w("shape-type","Shape Type",e.shapeType??""),w("group-kind","Group Kind",e.groupKind??""),w("is-watermark","Is Watermark",e.isWatermark==null?"":String(e.isWatermark)),Po("text-body","Text Body",e.textBody),_a(e.geometry),Ua(e.transform),Za(e.groupTransform??null),Ga(e.fill),Xa(e.stroke),$a(e.effects??null),WB(e.anchor),Ya(e.connector),Ja(e.picture),Qa(e.wordArt),...e.children.map(t=>Mm(t))]}function zr(e){return T("shape-child","Child Object",[w("kind","Kind",e),w("id","Id",""),w("label","Label",""),Po("text-body","Text Body",null),_a(null),Ua(null),Za(null),Ga(null),Xa(null),$a(null),Ya(null),Ja(null),Qa(null)])}function KB(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}function _B(e){return new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))}function UB(){return[{label:"Child Shape",createEntry:()=>zr("shape")},{label:"Child Group",createEntry:()=>zr("group")},{label:"Text Box",createEntry:()=>zr("textBox")},{label:"Connector",createEntry:()=>zr("connector")},{label:"Picture",createEntry:()=>zr("picture")},{label:"WordArt",createEntry:()=>zr("wordArt")}]}function tl(e={}){let t=KB(e.containerKey),r=_B(e.childKeys),o=(t==null||t==="shape-child")&&!r.has("text-body");return t==="text-body"?[{label:"Paragraph",createEntry:()=>w("paragraph","Paragraph","")}]:t!=null&&t!=="shape-child"?[]:[...o?[{label:"Text Body",createEntry:()=>Wi("text-body","Text Body")}]:[],...UB()]}import{normalizeOoxmlShapeModel as ZB}from"@datalking/begonia-engine";function GB(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Im(e){return{kind:H(C(e,"kind"))??"unknown",color:H(C(e,"color")),secondaryColor:H(C(e,"secondary-color")),opacity:oe(C(e,"opacity")),gradientAngle:oe(C(e,"gradient-angle")),gradientPath:H(C(e,"gradient-path")),patternPreset:H(C(e,"pattern-preset")),styleRefIndex:oe(C(e,"style-ref-index")),colorSource:Pe(C(e,"color-source-json")),secondaryColorSource:Pe(C(e,"secondary-color-source-json")),gradientStops:Pe(C(e,"gradient-stops-json"))??[],pictureFill:Pe(C(e,"picture-fill-json"))}}function Am(e){return{kind:H(C(e,"kind"))??"unknown",color:H(C(e,"color")),widthEmu:oe(C(e,"width-emu")),dash:H(C(e,"dash")),cap:H(C(e,"cap")),join:H(C(e,"join")),opacity:oe(C(e,"opacity")),styleRefIndex:oe(C(e,"style-ref-index")),compound:H(C(e,"compound")),colorSource:Pe(C(e,"color-source-json")),headEnd:Pe(C(e,"head-end-json")),tailEnd:Pe(C(e,"tail-end-json"))}}function Nm(e){return{styleRefIndex:oe(C(e,"style-ref-index")),styleRefColorSource:Pe(C(e,"style-ref-color-source-json")),effectNodes:Pe(C(e,"effect-nodes-json"))??[],glow:Pe(C(e,"glow-json")),outerShadow:Pe(C(e,"outer-shadow-json")),innerShadow:Pe(C(e,"inner-shadow-json")),softEdge:Pe(C(e,"soft-edge-json")),blur:Pe(C(e,"blur-json")),reflection:Pe(C(e,"reflection-json")),presetShadow:Pe(C(e,"preset-shadow-json")),effectDag:Pe(C(e,"effect-dag-json"))}}function Dm(e){let t=Te(e,"geometry");return t?{preset:H(C(t.children,"preset")),customPathCount:oe(C(t.children,"custom-path-count")),adjustments:GB(C(t.children,"adjustments")),customGeometry:Pe(C(t.children,"custom-geometry-json"))}:null}function Om(e){let t=Te(e,"transform");return t?{widthEmu:oe(C(t.children,"width-emu")),heightEmu:oe(C(t.children,"height-emu")),offsetXEmu:oe(C(t.children,"offset-x-emu")),offsetYEmu:oe(C(t.children,"offset-y-emu")),rotation:oe(C(t.children,"rotation")),flipH:fe(C(t.children,"flip-h")),flipV:fe(C(t.children,"flip-v"))}:null}function jm(e){let t=Te(e,"group-transform");return t?{childOffsetXEmu:oe(C(t.children,"child-offset-x-emu")),childOffsetYEmu:oe(C(t.children,"child-offset-y-emu")),childWidthEmu:oe(C(t.children,"child-width-emu")),childHeightEmu:oe(C(t.children,"child-height-emu"))}:null}function Vm(e){let t=Te(e,"connector");return t?{connectorType:H(C(t.children,"connector-type")),beginShapeId:H(C(t.children,"begin-shape-id")),endShapeId:H(C(t.children,"end-shape-id"))}:null}function Lm(e){let t=Te(e,"picture");if(!t)return null;let r=H(C(t.children,"hyperlink-url"));return{src:H(C(t.children,"src")),alt:H(C(t.children,"alt")),title:H(C(t.children,"title")),relationshipId:H(C(t.children,"relationship-id")),blipFill:Pe(C(t.children,"blip-fill-json")),hyperlink:r?{url:r,tooltip:H(C(t.children,"hyperlink-tooltip"))}:null}}function Fm(e){let t=Te(e,"word-art");return t?{text:H(C(t.children,"text")),preset:H(C(t.children,"preset"))}:null}function zm(e){return qi(pt(e,"text-body")[0]??null)}function XB(e){let t=Te(e,"anchor");return t?{kind:H(C(t.children,"kind"))??"unknown",wrap:H(C(t.children,"wrap"))??"unknown",behindDoc:fe(C(t.children,"behind-doc")),allowOverlap:fe(C(t.children,"allow-overlap")),layoutInCell:fe(C(t.children,"layout-in-cell")),relativeHeight:oe(C(t.children,"relative-height")),distTopEmu:oe(C(t.children,"dist-top-emu")),distBottomEmu:oe(C(t.children,"dist-bottom-emu")),distLeftEmu:oe(C(t.children,"dist-left-emu")),distRightEmu:oe(C(t.children,"dist-right-emu")),positionH:H(C(t.children,"position-h")),positionV:H(C(t.children,"position-v")),offsetXEmu:oe(C(t.children,"offset-x-emu")),offsetYEmu:oe(C(t.children,"offset-y-emu")),alignH:H(C(t.children,"align-h")),alignV:H(C(t.children,"align-v"))}:null}function $B(e){return e==="shape"||e==="group"||e==="textBox"||e==="connector"||e==="picture"||e==="wordArt"}function Hm(e){let t=Te(e,"fill"),r=Te(e,"stroke"),o=Te(e,"effects"),n=C(e,"kind");return{kind:$B(n)?n:"unknown",id:H(C(e,"id")),label:H(C(e,"label")),textBody:zm(e),geometry:Dm(e),transform:Om(e),groupTransform:jm(e),fill:t?Im(t.children):null,stroke:r?Am(r.children):null,effects:o?Nm(o.children):null,connector:Vm(e),picture:Lm(e),wordArt:Fm(e),children:pt(e,"shape-child").map(i=>Hm(i.children))}}function rl(e,t){let r=Te(e,"fill"),o=Te(e,"stroke"),n=Te(e,"effects");return ZB({...t,label:H(C(e,"label")),shapeType:H(C(e,"shape-type")),groupKind:H(C(e,"group-kind")),isWatermark:fe(C(e,"is-watermark")),textBody:zm(e),geometry:Dm(e),transform:Om(e),groupTransform:jm(e),fill:r?Im(r.children):null,stroke:o?Am(o.children):null,effects:n?Nm(n.children):null,anchor:XB(e),connector:Vm(e),picture:Lm(e),wordArt:Fm(e),children:pt(e,"shape-child").map(i=>Hm(i.children))},t.label??"Shape")}function ol(e){let t=String(e.attrs.label??"Shape"),r=String(e.attrs.text??""),o=qm("shape",{label:t,textBody:r?{plainText:r,paragraphs:[r]}:null},{label:t,text:r}),n=qm("shape",e.attrs.familyData,{label:t,text:r})??o;return{objectId:String(e.attrs.objectId??""),label:t,model:n.data.model??o.data.model,evidence:n.evidence}}function JB(){let e=document.createElement("div");return Object.assign(e.style,{width:"100%"}),e}function QB(){let e=document.createElement("div");return Object.assign(e.style,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"84px",padding:"12px",borderRadius:"12px",background:"linear-gradient(180deg, #ffffff, #f8fafc)",border:"1px solid #e2e8f0"}),e}function ex(e,t,r,o){let n=YB(o,{idPrefix:t||r,maxWidth:280,maxHeight:180});return e.dataset.previewKind=n.kind,e.dataset.previewSupported=String(n.supported),e.innerHTML=n.svg,n}function Wm(){return e=>{let t=e,r=yo("div"),{header:o,heading:n}=bo("Shape","shape"),i=Bo(),{section:s}=Fr("Visual Preview"),a=zt("Preview uses begonia\u2019s clean-room SVG geometry renderer for preset, connector, group, and custom-path shape families."),l=QB(),{section:c}=Fr("Native Subtree"),d=zt("Edit the shape object graph, text boxes, connector data, pictures, and child objects in a nested ProseMirror subtree. Changes auto-apply when you leave the card or press Cmd/Ctrl+Enter."),u=or();u.style.justifyContent="flex-start";let m=_e("Remove Selected","danger"),p=JB(),f=or();f.style.justifyContent="space-between",f.style.alignItems="center";let g=zt("Auto-applies when you leave this card. Apply is still available for an immediate commit."),v=_e("Apply"),E=_e("Remove Shape","danger");g.style.marginRight="auto",f.append(g,v,E),s.append(a,l),c.append(d,u,p,m),r.append(o,i,s,c,f);let R=null,S=(x,A)=>{u.replaceChildren(),tl({containerKey:x,childKeys:A}).forEach(O=>{let j=_e(O.label);j.addEventListener("click",()=>{P.appendEntry(O.createEntry())}),u.append(j)})},P=Co(p,[],{onChange(){R?.markDirty()},onSelectionChange(x){S(x.containerKey,x.childKeys)}});m.addEventListener("click",()=>{P.removeSelectedEntry()}),R=ho({applyButton:v,onCommit:()=>{let x=ol(t),A=rl(P.readEntries(),x.model),O=Em(x.model,A);return O.length===0?!1:(rr(r,{family:"shape",action:"apply-shape-edits",objectId:x.objectId,model:A,edits:O}),!0)},root:r,status:g});let b=x=>{t=x;let A=ol(x);n.textContent=A.label;let O=ex(l,A.objectId,A.label,A.model);i.textContent=`${A.evidence.shapeType??"shape"} | ${A.evidence.childCount} child objects | ${A.evidence.anchorKind} | preview ${O.kind}${O.supported?"":" fallback"}`,R?.reset(),P.setEntries(el(A.model))};return v.addEventListener("click",()=>{R?.flush()}),E.addEventListener("click",()=>{R?.reset();let x=ol(t);rr(r,{family:"shape",action:"remove-advanced-ooxml",objectId:x.objectId})}),b(e),{dom:r,destroy(){R?.destroy(),P.destroy()},update(x){return x.type!==t.type?!1:(b(x),!0)},stopEvent(x){return xo(x.target)||x.target instanceof Node&&p.contains(x.target)},ignoreMutation(){return!0},selectNode(){r.style.borderColor="#0f766e"},deselectNode(){r.style.borderColor="#cbd5e1"}}}}import{inlineOoxmlDrawingMetadata as tx}from"@datalking/begonia-editor-adapters";function Km(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function rx(){let e=document.createElement("span");return e.contentEditable="false",e.className="ald-editor-inline-drawing",Object.assign(e.style,{display:"inline-block",boxSizing:"border-box",margin:"0 2px",lineHeight:"0",maxWidth:"100%",verticalAlign:"baseline"}),e}function _m(e,t){let r=tx(t),o=r?.label||String(t.attrs.label??"Drawing"),n=r?.family??(t.attrs.family==="chart"?"chart":"shape"),i=r?.drawing,s=Km(r?.width??i?.width,80),a=Km(r?.height??i?.height,40);if(e.dataset.family=n,e.dataset.objectId=r?.objectId??String(t.attrs.objectId??""),e.setAttribute("aria-label",o),e.title=o,e.style.width=`${s}px`,e.style.height=`${a}px`,e.style.border=i?"0":"1px solid #94a3b8",e.style.background=i?"transparent":"#f8fafc",!i?.svg){e.replaceChildren();let c=document.createElement("span");c.textContent=o,Object.assign(c.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"#334155",fontSize:"12px",lineHeight:"1.2",overflow:"hidden"}),e.append(c);return}e.innerHTML=i.svg;let l=e.querySelector("svg");l&&(l.setAttribute("width","100%"),l.setAttribute("height","100%"),l.setAttribute("aria-hidden","true"),Object.assign(l.style,{display:"block"}))}function Um(){return e=>{let t=e,r=rx();return _m(r,e),{dom:r,update(o){return o.type!==t.type?!1:(t=o,_m(r,o),!0)},ignoreMutation(){return!0},selectNode(){r.style.outline="2px solid #0f766e",r.style.outlineOffset="2px"},deselectNode(){r.style.outline="",r.style.outlineOffset=""}}}}var nl="browser-advanced-ooxml-nodeviews";function Zm(){return{id:nl,createPlugins(){return[]},createNodeViews(){return{ooxml_math:xm(),ooxml_chart:Sm(),ooxml_shape:Wm(),inline_ooxml_drawing:Um()}}}}function _i(e=[]){return e.some(t=>t.id===nl)?[...e]:[...e,Zm()]}import{createEditorSessionController as Sj}from"@datalking/begonia-editor-ui";function il(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}function Ro(e){return typeof e=="object"&&e!==null}function sl(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.text!="string"?null:{text:e.text,displayMode:e.displayMode==="block"?"block":e.displayMode==="inline"?"inline":void 0}}function Gm(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.title!="string"?null:{title:e.title}}function Xm(e){return typeof e=="string"?e.trim()?e:null:!Ro(e)||typeof e.color!="string"?null:{color:e.color,kind:e.kind==="solid"||e.kind==="scheme"||e.kind==="none"||e.kind==="unknown"?e.kind:void 0}}function $m(e,t=0){if(typeof e=="string")return{id:null,name:e.trim()||`Series ${t+1}`,categories:[],values:[],color:null};if(!Ro(e))return{id:null,name:`Series ${t+1}`,categories:[],values:[],color:null};let r=Array.isArray(e.categories)?e.categories.filter(n=>typeof n=="string"):[],o=Array.isArray(e.values)?e.values.map(n=>typeof n=="number"&&Number.isFinite(n)?n:null):[];return{id:typeof e.id=="string"?e.id:null,name:typeof e.name=="string"?e.name:`Series ${t+1}`,categories:r,values:o,color:typeof e.color=="string"?e.color:null}}function Ym(e,t=0){return typeof e=="string"?{id:null,kind:"category",title:e.trim()||`Axis ${t+1}`,formatCode:null}:Ro(e)?{id:typeof e.id=="string"?e.id:null,kind:e.kind==="category"||e.kind==="value"||e.kind==="series"||e.kind==="date"?e.kind:"category",title:typeof e.title=="string"?e.title:`Axis ${t+1}`,formatCode:typeof e.formatCode=="string"?e.formatCode:null}:{id:null,kind:"category",title:`Axis ${t+1}`,formatCode:null}}function Jm(e,t=0){if(typeof e=="string"){let o=e.trim()||`Child ${t+1}`;return{parentId:null,child:{label:o,kind:"shape",text:o,shapeType:"shape"}}}if(!Ro(e)){let o=`Child ${t+1}`;return{parentId:null,child:{label:o,kind:"shape",text:o,shapeType:"shape"}}}let r=typeof e.label=="string"&&e.label.trim()?e.label.trim():`Child ${t+1}`;return{parentId:typeof e.parentId=="string"&&e.parentId.trim()?e.parentId:null,child:{label:r,kind:e.kind==="shape"||e.kind==="group"||e.kind==="textBox"||e.kind==="connector"||e.kind==="picture"||e.kind==="wordArt"?e.kind:"shape",text:typeof e.text=="string"?e.text:r,shapeType:typeof e.shapeType=="string"?e.shapeType:"shape"}}}function Ue(e){return e?e.surface??null:null}function ve(e){let t=Ue(e);if(!t)throw new Error("Browser editor surface is not available on this controller.");return t}function ox(e,t=!0){return{ok:!0,changed:t,value:e}}function st(e){return{ok:!1,changed:!1,reason:e}}function ft(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?st(e.reason):ox(e)}function En(e){return typeof e=="object"&&e!==null}function nx(e){return e==="block"?"block":"inline"}function al(e){return{chartType:"barChart",styleId:null,styleSource:null,title:e,subtitle:null,series:[],axes:[],legend:null,plotArea:null,textBody:{paragraphs:[e],plainText:e}}}function ll(e){return{shapeType:"shape",label:e,textBody:{paragraphs:[e],plainText:e},geometry:null,transform:null,groupTransform:null,fill:null,stroke:null,anchor:null,connector:null,picture:null,wordArt:null,childCount:0,children:[],groupKind:null,isWatermark:null}}function ix(e,t){return{id:e.id??null,order:t,name:e.name??`Series ${t+1}`,categories:e.categories??[],values:e.values??[],color:e.color??null,marker:null,dataLabels:null,smooth:null,explosion:null}}function sx(e,t){return{id:e.id??null,kind:e.kind??"category",title:e.title??`Axis ${t+1}`,formatCode:e.formatCode??null,orientation:null,visible:null,minimum:null,maximum:null,majorUnit:null,minorUnit:null,crossesAt:null,majorGridlines:null,minorGridlines:null}}function ax(e,t){let r=e.text?.trim()||e.label?.trim()||`Child ${t+1}`;return{kind:e.kind??"shape",id:null,label:e.label??r,textBody:{paragraphs:il(r),plainText:r},geometry:e.shapeType?{preset:e.shapeType,customPathCount:null,adjustments:[]}:null,transform:null,groupTransform:null,fill:null,stroke:null,connector:e.kind==="connector"?{connectorType:e.shapeType??null,beginShapeId:null,endShapeId:null}:null,picture:null,wordArt:e.kind==="wordArt"?{text:r,preset:e.shapeType??null}:null,children:[]}}function lx(e){if(typeof e=="string"){let r=e.trim();return r?{text:r,displayMode:"inline",label:null}:null}if(!En(e)||typeof e.text!="string")return null;let t=e.text.trim();return t?{text:t,displayMode:e.displayMode==="block"?"block":"inline",label:typeof e.label=="string"?e.label:null}:null}function cx(e){if(typeof e=="string"){let o=e.trim()||"Chart";return{model:al(o),options:{label:o}}}if(!En(e))return{model:al("Chart"),options:{label:"Chart"}};let t=typeof e.title=="string"&&e.title.trim()?e.title.trim():"Chart";return{model:En(e.model)?e.model:al(t),options:{label:typeof e.label=="string"?e.label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function dx(e){if(typeof e=="string"){let o=e.trim()||"Shape";return{model:ll(o),options:{label:o}}}if(!En(e))return{model:ll("Shape"),options:{label:"Shape"}};let t=typeof e.label=="string"&&e.label.trim()?e.label.trim():"Shape";return{model:En(e.model)?e.model:ll(t),options:{label:t,objectId:typeof e.objectId=="string"?e.objectId:void 0}}}function Qm(e){let t=e.getState().advancedOoxml.selected;return t?.family==="chart"?e.documentApi.ooxml.charts.getById(t.objectId):null}function ux(e){let t=e.getState().advancedOoxml.selected;return t?.family==="math"?e.documentApi.ooxml.math.getById(t.objectId):null}function mx(e){let t=e.getState().advancedOoxml.selected;return t?.family==="shape"?e.documentApi.ooxml.shapes.getById(t.objectId):null}function ep(e,t,r){let o=ve(e);switch(t){case"insert-math-inline":{let n=lx(r);if(!n)return st("Expected inline math text for advanced OOXML insertion.");let i=e.documentApi.ooxml.math.createModelFromText(n.text,n.displayMode),s=o.trackingEnabled?e.appendMathToCurrentTextblockTracked(i,{source:"browser-ooxml"},{label:n.label??n.text}):e.appendMathToCurrentTextblock(i,{label:n.label??n.text});return ft(s)}case"insert-chart-block":{let n=cx(r),i=o.trackingEnabled?e.insertChartAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertChartAfterCurrentBlock(n.model,n.options);return ft(i)}case"insert-shape-block":{let n=dx(r),i=o.trackingEnabled?e.insertShapeAfterCurrentBlockTracked(n.model,{source:"browser-ooxml"},n.options):e.insertShapeAfterCurrentBlock(n.model,n.options);return ft(i)}case"remove-selected-ooxml":return ft(e.removeSelectedAdvancedOoxml());case"selected-math-set-plain-text":{let n=sl(r);if(!n)return st("Expected math plain text for the selected OOXML equation.");let i=typeof n=="string"?e.setSelectedMathPlainText(n):e.setSelectedMathPlainText(n.text,n.displayMode);return ft(i)}case"selected-math-toggle-display-mode":{let n=ux(e);if(!n)return st("No advanced OOXML math node is selected.");let i=nx(n.familyData?.displayMode)==="block"?"inline":"block";return ft(e.setSelectedMathDisplayMode(i))}case"selected-chart-set-title":{let n=Gm(r);return n?ft(e.setSelectedChartTitle(typeof n=="string"?n:n.title)):st("Expected a chart title for the selected OOXML chart.")}case"selected-chart-add-series":{let n=Qm(e);if(!n)return st("No advanced OOXML chart node is selected.");let i=$m(r,n.familyData?.model?.series.length??0);return i?ft(e.appendSelectedChartSeries(ix(i,n.familyData?.model?.series.length??0))):st("Expected a series payload for the selected OOXML chart.")}case"selected-chart-add-axis":{let n=Qm(e);if(!n)return st("No advanced OOXML chart node is selected.");let i=Ym(r,n.familyData?.model?.axes.length??0);return i?ft(e.appendSelectedChartAxis(sx(i,n.familyData?.model?.axes.length??0))):st("Expected an axis payload for the selected OOXML chart.")}case"selected-shape-set-text-body":{let n=sl(r);if(!n)return st("Expected replacement text for the selected OOXML shape.");let i=typeof n=="string"?n:n.text;return ft(e.setSelectedShapeTextBody(il(i)))}case"selected-shape-set-fill":{let n=Xm(r);if(!n)return st("Expected a fill color for the selected OOXML shape.");let i=e.setSelectedShapeFill(typeof n=="string"?{kind:"solid",color:n.trim()||null,secondaryColor:null,opacity:null}:{kind:n.kind??"solid",color:n.color.trim()||null,secondaryColor:null,opacity:null});return ft(i)}case"selected-shape-add-child":{let n=mx(e);if(!n)return st("No advanced OOXML shape node is selected.");let i=Jm(r,n.familyData?.model?.children.length??0);if(!i)return st("Expected a child payload for the selected OOXML shape.");let s=ax(i.child,n.familyData?.model?.children.length??0);return ft(i.parentId?e.appendSelectedShapeChildToParent(i.parentId,s):e.appendSelectedShapeChild(s))}default:return null}}import{resolveCollapsedSelectionFormattingMarks as TP}from"@datalking/begonia-engine";import{addressableBlockTypeForNodeType as yp,formatAddressableBlockId as mC,formatAddressableBlockIdWithLogicalId as bp}from"@datalking/begonia-doc-service/structure";import{normalizeDocumentStoryLocator as pC,readSyntheticSideStoryDocOriginPath as fC,readSyntheticSideStoryDocStoryLocator as wC}from"@datalking/begonia-doc-service/v1";import{hasVisibleSemanticContent as gC}from"@datalking/begonia-engine";function cl(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function Hr(e,t){return e==="listItem"?cl(t.attrs?.listItemId):e==="paragraph"||e==="heading"?cl(t.attrs?.paraId)??cl(t.attrs?.sdBlockId):null}import{DELETION_MARK_NAME as fx,INSERTION_MARK_NAME as wx,collectRevisionSpans as gx,createRevisionGroupingContext as Sx,listSelectionRevisionRanges as vx,logicalRevisionIdForRange as hx,resolveParagraphLikeBlockInlineRangeAtPath as yx}from"@datalking/begonia-engine";import{groupLogicalRevisions as bx}from"@datalking/begonia-doc-service/v1";import{orderOverlapRevisionIds as px}from"@datalking/begonia-engine";function Mn(e,t){return px(e,t)}function tp(e){return e.threadId}function Ui(e){return`${e.threadId}\0${e.entryId}`}function rp(e,t){let r=Math.min(e,t),o=Math.max(e,t),n=r===o;return{start:r,selectionEnd:n?o+1:o,collapsed:n}}function Bx(e,t){return t<e.selectionEnd&&t+1>e.start}function op(e,t,r){return t<e.selectionEnd&&r>e.start}function dl(e,t,r,o={}){let n=o.includeLeadingBoundary??!0,i=o.includeTrailingBoundary??!0,s=n&&e.collapsed&&r>t&&e.start+1===t,a=i&&e.collapsed&&r>t&&e.start===r;return op(e,t,r)||s||a}function xx(e){return e.marks.some(t=>t.type.name===wx||t.type.name===fx)}function Cx(e,t){return t.target?.nodeType!=="bookmark_anchor"&&t.target?.nodeType!=="structural_revision_carrier"||(t.text??"").length>0||!t.target.blockPath.length?null:yx(e,t.target.blockPath)}function Px(e,t){if(e.type.name!=="comment_range_start"&&e.type.name!=="comment_range_end"&&e.type.name!=="comment_anchor")return null;let r=typeof e.attrs.threadId=="string"?e.attrs.threadId.trim():"";if(r.length===0)return null;let o=typeof e.attrs.entryId=="string"?e.attrs.entryId.trim():"";return{threadId:r,entryId:o||r,kind:e.type.name==="comment_range_start"?"start":e.type.name==="comment_range_end"?"end":"anchor",pos:t,tracked:xx(e)}}function Rx(e){let t=[];return e.nodesBetween(0,e.content.size,(r,o)=>{let n=Px(r,o);return n&&t.push(n),!0}),t}function ul(e,t,r){let o=e.get(t)??[];o.push(r),e.set(t,o)}function Tx(e,t){let r=Ui(t),o=e.get(r)??{hasStart:!1,hasEnd:!1};t.kind==="start"&&(o.hasStart=!0),t.kind==="end"&&(o.hasEnd=!0),e.set(r,o)}function kx(e,t,r){return(e.get(Ui(r))??[]).find(o=>o.pos>=r.pos&&!t.has(o))??null}function Ex(e,t,r){let o=e.get(Ui(r))??[];for(let n=o.length-1;n>=0;n-=1){let i=o[n];if(i&&i.pos<=r.pos&&!t.has(i))return i}return null}function Mx(e,t){let r=rp(t.from,t.to),o=Rx(e),n=new Set,i=new Map,s=new Map,a=new Map,l=new Map,c=new Set;for(let d of o){if(Tx(l,d),d.kind==="anchor"){ul(a,Ui(d),d);continue}if(d.kind==="start"){ul(i,tp(d),d);continue}let u=tp(d),m=i.get(u)??[],p=m.pop()??null;if(m.length>0?i.set(u,m):i.delete(u),!p){ul(s,u,d);continue}dl(r,p.pos+1,d.pos,{includeLeadingBoundary:!p.tracked,includeTrailingBoundary:!d.tracked})&&n.add(p.threadId)}for(let d of i.values())for(let u of d){let m=kx(a,c,u);m&&(c.add(m),dl(r,u.pos+1,m.pos,{includeLeadingBoundary:!u.tracked,includeTrailingBoundary:!m.tracked})&&n.add(u.threadId))}for(let d of s.values())for(let u of d){let m=Ex(a,c,u);m&&(c.add(m),dl(r,m.pos,u.pos,{includeLeadingBoundary:!m.tracked,includeTrailingBoundary:!u.tracked})&&n.add(u.threadId))}for(let[d,u]of a){let m=l.get(d);if(!(m?.hasStart||m?.hasEnd))for(let p of u)!p.tracked&&Bx(r,p.pos)&&n.add(p.threadId)}return[...n]}function Ix(e,t){let r=gx(e.doc,e.schema),o=Sx(r),n=new Set;for(let i of vx(e)){let s=Cx(e.doc,i);(!s||op(rp(e.selection.from,e.selection.to),s.from,s.to))&&n.add(hx(i,o,t))}return Mn([...n],bx(r,t))}function np(e,t={}){return{activeCommentIds:Mx(e.doc,e.selection),activeChangeIds:Ix(e,t.reviewReplacementMode??"paired")}}import{DELETION_MARK_NAME as Nx}from"@datalking/begonia-engine";import{isDocumentNodePathIndex as Dx}from"@datalking/begonia-document-model";import{NodeSelection as Ax}from"prosemirror-state";function K(e){return e instanceof Ax||typeof e=="object"&&e!=null&&"node"in e&&e.node!=null&&"from"in e&&typeof e.from=="number"&&"to"in e&&typeof e.to=="number"&&"$from"in e&&e.$from!=null}function Zi(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function ze(e){return t=>Zi(t.attrs[e])}function ip(...e){return t=>{for(let r of e){let o=Zi(t.attrs[r]);if(o)return o}return null}}function ml(e){let t=Zi(e.attrs.threadId);return t?`${t}\0${Zi(e.attrs.entryId)??t}`:null}function sp(){return null}function ap(e){return e==="paragraph"||e==="heading"}function To(e,t){return e===t||ap(e)&&ap(t)}var pl=Object.freeze({bookmark_anchor:ze("bookmarkId"),bookmark_end:ze("bookmarkId"),comment_anchor:ml,comment_range_end:ml,comment_range_start:ml,column_break:ze("columnBreakId"),endnote_reference:ze("noteId"),heading:ip("paraId","sdBlockId","captionId"),horizontal_rule:sp,image:ze("imageId"),inline_ooxml_drawing:ze("objectId"),ooxml_chart:ze("objectId"),ooxml_math:ze("objectId"),ooxml_shape:ze("objectId"),page_break:ze("pageBreakId"),paragraph:ip("paraId","sdBlockId","captionId"),footnote_reference:ze("noteId"),permission_range_end:ze("rangeId"),permission_range_start:ze("rangeId"),section_break:ze("sectionId"),table:sp,template_block:ze("fieldId"),template_field:ze("fieldId")});function Ox(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function qr(e){try{return Ox(JSON.stringify(e.toJSON()))}catch{return null}}function cp(e,t){let r=e,o=-1;for(let n of t){if(!Dx(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function jx(e,t,r,o,n,i){if(i==null)return null;let s=!1,a=!1;return e.descendants((l,c)=>c===o||!To(l.type.name,t)||n(l)!==r?!0:(s=!0,qr(l)===i?(a=!0,!1):!0)),s&&!a?i:null}function lp(e,t,r){let o=cp(e,t.path);return!o||!To(o.node.type.name,t.nodeType)||r(o.node)!==t.stableIdentity||t.nodeFingerprint!=null&&qr(o.node)!==t.nodeFingerprint?null:o}function Vx(e,t,r){let o=[];return e.descendants((n,i)=>(To(n.type.name,t.nodeType)&&r(n)===t.stableIdentity&&o.push({node:n,position:i}),!0)),o}function Lx(e,t){return t.nodeFingerprint==null?[]:e.filter(r=>qr(r.node)===t.nodeFingerprint)}function dp(e){return!!e?.node.marks.some(t=>t.type.name===Nx)}function Fx(e){return e.filter(t=>!dp(t))}function Ie(e){let t=e?.selection;if(!e||!K(t))return null;let r=t.node.type.name,o=r?pl[r]:null;if(!r||!o)return null;let n=o(t.node),i=[];for(let l=0;l<t.$from.depth;l+=1)i.push(t.$from.index(l));i.push(t.$from.index(t.$from.depth));let s=qr(t.node),a=n?jx(e.doc,r,n,t.from,o,s):s;return{kind:"node",nodeType:r,stableIdentity:n,path:i,...a!=null?{nodeFingerprint:a}:{}}}function Gi(e,t){let r=pl[t.nodeType];if(t.stableIdentity&&r){let i=Vx(e,t,r);if(i.length===0)return null;if(i.length===1){let l=i[0];return t.nodeFingerprint==null||lp(e,t,r)?.position===l.position||qr(l.node)===t.nodeFingerprint?l:null}let s=lp(e,t,r);if(t.nodeFingerprint==null){if(!dp(s))return s;let l=Fx(i);return l.length===1?l[0]:s}let a=Lx(i,t);return a.length!==1?null:s?.position===a[0]?.position?s:null}let o=cp(e,t.path);if(o!=null&&To(o.node.type.name,t.nodeType)&&(t.nodeFingerprint==null||qr(o.node)===t.nodeFingerprint))return o;if(t.nodeFingerprint==null)return null;let n=[];return e.descendants((i,s)=>(To(i.type.name,t.nodeType)&&qr(i)===t.nodeFingerprint&&n.push({node:i,position:s}),n.length<=1)),n.length===1?n[0]:null}function up(e,t,r){if(!r.empty||!t.stableIdentity)return!1;let o=pl[t.nodeType];if(!o)return!1;let n=!1;return e.descendants((i,s)=>To(i.type.name,t.nodeType)&&o(i)===t.stableIdentity&&r.from>=s&&r.from<=s+i.nodeSize?(n=!0,!1):!0),n}import{hasVisibleSemanticContent as zx}from"@datalking/begonia-document-model";function Xi(e){return[...new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0))]}function Hx(e,t){let r=e?.selection;return t!=null&&K(r)&&r.node.isInline&&r.node.isLeaf&&zx(r.node)}function fl(e,t,r=!1){return t!=="node"||e.target==null||r||Xi(e.activeChangeIds).length>0?e:{...e,target:null}}function ko(e,t,r){let o=Ie(e??null);return fl(t,r,r==="node"&&t.target!=null&&Hx(e,o))}import{projectAcceptedTextBetween as rC}from"@datalking/begonia-engine";import{createDocumentNoteAwareTextOffsetOptions as qx}from"@datalking/begonia-doc-service/v1";function se(e,t={}){return qx(e,t)}import{pmPositionToAddressableTextOffset as Wx,readAddressableText as Kx,resolveAddressableTextOffsetPosition as _x,resolveAddressableTextOffsetRange as Ux,resolveCollapsedAddressableTextOffsetPosition as Zx}from"@datalking/begonia-document-model";function In(e){return{includeDeletedText:!0,...e}}function Br(e,t={}){return Kx(e,In(t))}function we(e,t,r,o={}){return Wx(e,t,r,In(o))}function He(e,t,r,o="end",n={}){return _x(e,t,r,o,In(n))}function mp(e,t,r,o,n={}){return Ux(e,t,r,o,In(n))}function Eo(e,t,r,o={}){return Zx(e,t,r,In(o))}import{semanticNodeText as $x}from"@datalking/begonia-document-model";import{isRevisionMarkHiddenInProjection as Gx,isRevisionNodeHiddenInProjection as Xx}from"@datalking/begonia-engine";function pp(e,t){return Gx(e,t)}function wt(e,t,r=!1){return Xx(e,t,r)}function Yx(e,t){return wt(e,"final",t)}function wp(e,t){let r=$x(e),o=t?.resolveLeafText?.(e,r);return typeof o=="string"?o:r}function Jx(e,t,r){return r?"":wp(e,t)}function Qx(e,t){return t?"":e.text??""}function fp(e,t){return e.isText?(e.text??"").length:e.childCount===0?wp(e,t).length:0}function eC(e,t,r,o,n,i,s){if(o.length===0)return r;t.push(o);let a=r+o.length;return e.push({atomic:s,text:o,startOffset:n,endOffset:i,visibleStart:r,visibleEnd:a}),a}function wl(e,t){let r=[],o=[],n=t?.blockSeparator??"",i=0,s=0,a=(c,d,u=!1)=>{let m=i,p=m+d;s=eC(r,o,s,c,m,p,u),i=p},l=(c,d=!1)=>{let u=Yx(c,d);if(c.isText){let p=fp(c,t);a(Qx(c,u),p);return}if(c.childCount===0){let p=fp(c,t);a(Jx(c,t,u),p,!0);return}let m=!0;c.forEach(p=>{p.isBlock&&!m&&n.length>0&&a(n,n.length),l(p,u&&c.isInline),m=!1})};return l(e),{runs:r,text:o.join(""),maxOffset:i}}function tC(e,t,r,o){if(!Number.isInteger(r))return 0;if(r<=0)return o==="start"?e[0]?.startOffset??0:0;for(let[n,i]of e.entries()){if(r<i.visibleStart)return i.startOffset;if(r>i.visibleEnd)continue;if(r===i.visibleEnd){let l=e[n+1];return o==="start"&&l&&l.visibleStart===r?l.startOffset:i.endOffset}let s=i.visibleEnd-i.visibleStart,a=i.endOffset-i.startOffset;return i.atomic?o==="end"&&r>i.visibleStart?i.endOffset:i.startOffset:a===s?i.startOffset+(r-i.visibleStart):o==="end"&&r>i.visibleStart?i.endOffset:i.startOffset}return t}function Mo(e,t={}){let{text:r,maxOffset:o}=wl(e,t);return{text:r,maxOffset:o}}function Io(e,t,r="end",o={}){let{runs:n,text:i,maxOffset:s}=wl(e,o);return!Number.isInteger(t)||t<0||t>i.length?null:tC(n,s,t,r)}function nr(e,t,r="end",o={}){let{runs:n}=wl(e,o);if(!Number.isInteger(t)||t<=0)return 0;let i=0;for(let s of n){if(t<=s.startOffset)return i;if(t<=s.endOffset)return s.atomic&&t<s.endOffset?r==="end"?s.visibleEnd:s.visibleStart:s.visibleStart+(t-s.startOffset);i=s.visibleEnd}return i}var oC=Object.freeze({blockSeparator:" "});function nC(e){return e.empty??e.from===e.to}function iC(e,t){let r=Math.max(0,e.content.size),o=Math.min(r,Math.max(0,Math.min(t.from,t.to))),n=Math.min(r,Math.max(o,Math.max(t.from,t.to))),i=se(e,oC),s=[],a=!1;return e.nodesBetween(o,n,(l,c)=>{if(!l.isTextblock)return!0;a=!0;let d=Math.max(o,c+1),u=Math.min(n,c+l.nodeSize-1),m=we(l,c,d,i),p=Math.max(m,we(l,c,u,i)),f=Mo(l,i),g=nr(l,m,"start",i),v=nr(l,p,"end",i);return s.push(f.text.slice(Math.min(g,v),Math.max(g,v))),!1}),a?s.join(" "):null}function ge(e,t,r){return nC(r)?"":iC(e,r)??rC(e,t,Math.min(r.from,r.to),Math.max(r.from,r.to)," ")}function gp(e){return[...new Set(e)]}function An(e){return JSON.stringify([e.empty,e.target??null,[...new Set(e.activeMarks)].sort(),gp(e.activeCommentIds),gp(e.activeChangeIds),e.text??null])}import{hasVisibleSemanticContent as vp,isInlineFormatMarkEnabled as sC}from"@datalking/begonia-document-model";var aC=new Set(["strong","em","underline","strike"]);function $i(e,t){for(let r of t){if(aC.has(r.type.name)&&!sC(r)){e.delete(r.type.name);continue}e.add(r.type.name)}}function lC(e){let t=new Set;return $i(t,e),t}function Sp(e,t){let r=new Set(e);return $i(r,t.marks),r}function hp(e){return e.isInline&&!e.isText&&vp(e)}function cC(e){return e.isText||e.isInline&&e.isLeaf&&vp(e)}function dC(e,t){return e.isText?{start:t,end:t+(e.text?.length??0)}:{start:t,end:t+e.nodeSize}}function Yi(e,t,r){let o=null,n=(i,s,a)=>{let l=hp(i)?Sp(a,i):new Set(a);if(cC(i)){let d=dC(i,s),u=Math.max(d.start,t);if(Math.min(d.end,r)>u){let p=Sp(l,i);if(o==null)o=p;else for(let f of[...o])p.has(f)||o.delete(f)}return}if(i.childCount===0)return;let c=0;i.forEach(d=>{let u=s+1+c,m=u+d.nodeSize;c+=d.nodeSize,!(m<=t||u>=r)&&n(d,u,l)})};return n(e,-1,new Set),o??new Set}function Ji(e,t=null){if(t!=null)return lC(t);let r=new Set;for(let o=1;o<=e.depth;o+=1){let n=e.node(o);if(!hp(n))continue;let i=e.start(o),s=e.end(o);e.pos<i||e.pos>s||$i(r,n.marks)}return $i(r,e.marks()),r}import{parseAddressableBlockId as uC}from"@datalking/begonia-doc-service/structure";function Ao(e){return uC(e)?.logicalId==null}var Qi=Object.freeze({blockSeparator:`
3
- `});function SC(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function es(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=yp(r.type.name);if(o)return{type:o,path:SC(e,t),node:r,pos:e.start(t)-1}}return null}function vC(e,t,r,o){let n=e[e.length-1];if(n?.blockId===t){n.range.end=Math.max(n.range.end,o),n.range.start=Math.min(n.range.start,r);return}e.push({blockId:t,range:{start:r,end:o}})}function Bp(e,t){let r=fC(e);return r?[...r,...t]:[...t]}function Sl(e,t,r){let o=Bp(e,t.path);return r?mC(t.type,o):bp(t.type,o,Hr(t.type,t.node))}function hC(e,t=null){return e.length===0?null:{kind:"text",segments:e,...t?{story:t}:{}}}function vl(e,t,r,o,n){return Ao(e)?{start:nr(t,r,"start",n),end:nr(t,o,"end",n)}:{start:r,end:o}}function gl(e){return e.node.isLeaf&&e.node.isInline&&e.$from.parent.inlineContent&&gC(e.node)}function xp(e){let t=yp(e.node.type.name);return t==="listItem"?t:null}function yC(e){return"$anchorCell"in e?!1:K(e)?gl(e)||xp(e)!=null:!0}function bC(e,t){let r=t.$from.doc.resolve(t.from+1),o=es(r);if(!o||o.node!==t.node)return null;let n=se(e,Qi),i=Math.max(t.from,o.pos+1),s=Math.min(t.to,o.pos+o.node.nodeSize-1),a=we(o.node,o.pos,i,n),l=Math.max(a,we(o.node,o.pos,s,n)),c=Sl(e,o,!1);return[{blockId:c,range:vl(c,o.node,a,l,n)}]}function BC(e,t){let r=es(t.$from);if(!r||!r.node.isTextblock)return null;let o=se(e,Qi),n=we(r.node,r.pos,t.from,o),i=Math.max(n,we(r.node,r.pos,t.to,o)),s=Sl(e,r,!0);return[{blockId:s,range:vl(s,r.node,n,i,o)}]}function xC(e,t){let r=K(t)&&gl(t),o=se(e,Qi);if(K(t)&&gl(t)){let s=BC(e,t);if(s)return s}if(K(t)&&xp(t)){let s=bC(e,t);if(s)return s}let n=[],i=!1;return e.nodesBetween(t.from,t.to,(s,a)=>{if(i)return!1;if(!s.isTextblock)return!0;let l=e.resolve(a+1),c=es(l);if(!c)return i=!0,!1;let d=Math.max(t.from,a+1),u=Math.min(t.to,a+s.nodeSize-1),m=we(c.node,c.pos,d,o),p=Math.max(m,we(c.node,c.pos,u,o)),f=Sl(e,c,r),g=vl(f,c.node,m,p,o);return vC(n,f,g.start,g.end),!1}),i?null:n}function CC(e,t,r){return Yi(e,t,r)}function PC(e){let t=new Set,{from:r,to:o}=e.selection;if(r===o){for(let n of Ji(e.doc.resolve(r),e.storedMarks))t.add(n);return[...t]}for(let n of CC(e.doc,r,o))t.add(n);return[...t]}function RC(e,t){let{selection:r}=e,o=K(r)?Ie(e):null;return JSON.stringify([r.from,r.to,r.empty,K(r)?"node":"text",An({...t,target:t.target?{...t.target,...t.target.story?{story:pC(t.target.story)??t.target.story}:{}}:null}),K(r)?o??{nodeType:r.node.type.name,position:r.$from.pos,nodeSize:r.node.nodeSize}:null])}function Ee(e,t={},r={}){let o=t??{},n=r??{},{selection:i,doc:s}=e,a=hl(s,i),{activeCommentIds:l,activeChangeIds:c}=np(e,{reviewReplacementMode:n.reviewReplacementMode}),d={empty:i.empty,target:a,activeMarks:PC(e),activeCommentIds:l,activeChangeIds:c};return o.includeText&&!i.empty&&(d.text=ge(s,e.schema,i)),d}function hl(e,t){let r=wC(e);return yC(t)?hC(xC(e,t)??[],r):null}function Ht(e){let t=Ee(e).target;if(t)return t;if(!e.selection.empty)return null;let r=es(e.selection.$from);if(!r)return null;let o=se(e.doc,Qi),n=we(r.node,r.pos,e.selection.from,o);return{kind:"text",blockId:bp(r.type,Bp(e.doc,r.path),Hr(r.type,r.node)),range:{start:n,end:n}}}function yl(e,t={}){let r=n=>K(n.selection)?"node":"text",o=n=>{let i=e.state;return{state:i,info:ko(i,Ee(i,n,t),r(i))}};return{current(n){return o(n).info},onChange(n){let i=!1,s=!1,a=null,l=()=>{if(s=!1,i)return;let m=o({includeText:!0}),p=RC(m.state,m.info);p!==a&&(a=p,n(m.info))},c=()=>{i||s||(s=!0,queueMicrotask(l))},d;try{d=e.subscribe(c)}catch(m){throw i=!0,m}let u=!1;return()=>{u||(u=!0,i=!0,d())}}}}function TC(e){return e?.selectionKind!=="node"&&e?.selectionTarget!=null}function ir(e,t,r=null){return e?e.editable?r?.selectionKind==="node"?"Place the caret in text or select text before applying inline formatting.":TC(r)?null:t&&K(t.selection)?"Place the caret in text or select text before applying inline formatting.":t?Ht(t)?null:"Place the caret in text or select text before applying inline formatting.":r?.selectionTarget?null:"Place the caret in text or select text before applying inline formatting.":"Document is read-only in the current document mode.":"Editor is not ready."}import{createSelectionTrackingBookmark as BP}from"@datalking/begonia-engine";import{NodeSelection as as}from"prosemirror-state";import{NodeSelection as Pp,TextSelection as ts}from"prosemirror-state";function Cp(e,t,r){try{return e.resolve(t).parent.inlineContent&&e.resolve(r).parent.inlineContent}catch{return!1}}function Rp(e){return typeof e=="object"&&e!=null&&"parent"in e&&typeof e.parent=="object"&&e.parent!=null&&"inlineContent"in e.parent&&e.parent.inlineContent===!0}function Wr(e,t){return Math.max(1,Math.min(t,e.content.size))}function rs(e,t){return Math.max(0,Math.min(t,e.content.size))}function Z(e,t,r=t){let o=Wr(e.doc,t),n=Wr(e.doc,r),i=Math.min(o,n),s=Math.max(o,n),a=Tp(e),l=c=>{if(!Kr(c))return null;if(a&&typeof c.toJSON=="function")try{let d=a.fromJSON(e.doc,c.toJSON());return Kr(d)?d:null}catch{}return c};if(Cp(e.doc,i,s))try{return l(ts.create(e.doc,o,n))}catch{}try{return l(ts.between(e.doc.resolve(o),e.doc.resolve(n),n>=o?1:-1))}catch{if(o!==n)return null}try{return l(ts.near(e.doc.resolve(o),n>=o?1:-1))}catch{return null}}function Kr(e){return e instanceof ts||typeof e=="object"&&e!=null&&!("$anchorCell"in e)&&!("node"in e&&e.node!=null)&&"anchor"in e&&typeof e.anchor=="number"&&"head"in e&&typeof e.head=="number"&&"empty"in e&&typeof e.empty=="boolean"&&"$anchor"in e&&"$head"in e&&Rp(e.$anchor)&&Rp(e.$head)}function qt(e,t){let r=K(e),o=K(t);if(r!==o||e.from!==t.from||e.to!==t.to||e.empty!==t.empty)return!1;let n=Kr(e),i=Kr(t);return!n&&!i?!0:n&&i&&e.anchor===t.anchor&&e.head===t.head}function bl(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function Tp(e){let t=e.selection.constructor,r=typeof t=="function"?Object.getPrototypeOf(t):null;return r&&typeof r.fromJSON=="function"?r:null}function kC(e,t){return Kr(e)?Kr(t)?t:null:K(e)?K(t)?t:null:t}function at(e,t){let r=Tp(e);if(r&&typeof t.toJSON=="function")try{return kC(t,r.fromJSON(e.doc,t.toJSON()))}catch{}if(K(t)){let o=rs(e.doc,Math.min(t.from,t.to)),n=e.doc.nodeAt(o);if(!n||!Pp.isSelectable(n))return null;try{return Pp.create(e.doc,o)}catch{return null}}return Kr(t)?Z(e,t.anchor,t.head):t}import{readPreservedSelection as wP}from"@datalking/begonia-engine";import{NodeSelection as gP}from"prosemirror-state";import{isDocumentStoryLocator as nP,readSyntheticSideStoryDocStoryLocator as iP,sameDocumentStoryLocator as sP}from"@datalking/begonia-doc-service/v1";import{resolveAddressableBlockIdPath as NC}from"@datalking/begonia-doc-service/v1";import{parseAddressableBlockId as DC}from"@datalking/begonia-doc-service/structure";import{readSyntheticSideStoryDocOriginPath as EC}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as xl,isDocumentNodePathIndex as Cl}from"@datalking/begonia-document-model";function Bl(e){return Cl(e)}function MC(e){let t=e[0];return t===-101||t===-102||t===-211||t===-212?e.length>=2&&Bl(e[1])&&xl(e.slice(2))?e.slice(2):null:(t===-201||t===-202)&&e.length>=3&&Bl(e[1])&&Bl(e[2])&&xl(e.slice(3))?e.slice(3):null}function IC(e,t){return e.length>=t.length&&t.every((r,o)=>e[o]===r)}function AC(e,t){let r=e,o=-1;for(let n of t){if(!Cl(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function Nn(e,t){if(!Array.isArray(t))return null;if(t.length===0)return[];if(xl(t))return[...t];let r=MC(t);if(!r)return null;let o=EC(e);return o&&IC(t,o)?r:null}function No(e,t){let r=Nn(e,t);if(!r)return null;if(r.length===0)return 0;let o=0,n=e;for(let i of r){if(!Cl(i)||i>=n.childCount)return null;o+=1;for(let s=0;s<i;s+=1)o+=n.child(s).nodeSize;n=n.child(i)}return o}function Ve(e,t){let r=Nn(e,t);return r?AC(e,r):null}function kp(e){return e==="paragraph"||e==="heading"}function OC(e){return{readDocument(){return e},readNode(t){return Ve(e,t)?.node??null}}}function Le(e,t){let r=NC(OC(e),t),o=Nn(e,r);if(o)return o;let n=DC(t);if(!n?.path.length||!kp(n.nodeType))return null;let i=Nn(e,n.path),s=i?Ve(e,i)?.node??null:null;return s?.isBlock&&kp(s.type.name)?[...i]:null}import{hasVisibleSemanticContent as jC,semanticNodeText as VC}from"@datalking/begonia-document-model";var LC=new Set(["structural_revision_carrier","bookmark_anchor","bookmark_end","comment_anchor","comment_range_start","comment_range_end","permission_range_start","permission_range_end"]);function FC(e){if(LC.has(e.type.name))return"";let t=VC(e);return t.length>0?t:jC(e)?"":""}function zC(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.textBetween(o,n,"",FC);if(i.length===0)return!0;if(i.trim().length>0)return!1;let s=e.resolve(o),a=e.resolve(n);for(let l=Math.min(s.depth,a.depth);l>=0;l-=1)if(s.node(l)===a.node(l)&&s.node(l).isTextblock)return!0;return!1}function _r(e,t,r={}){if(t.length===0)return null;let o=t[0],n=o;for(let i of t.slice(1)){if(i.from<n.from||i.from===n.from&&i.to<n.to||i.from<o.to)return null;if(i.from===o.to||zC(e,o.to,i.from)){o={from:o.from,to:Math.max(o.to,i.to)},n=i;continue}return r.strict?null:o}return o}import{readSyntheticSideStoryDocOriginPath as JC}from"@datalking/begonia-doc-service/v1";import{cloneSelectionTextRange as HC}from"@datalking/begonia-document-api/core";import{sameDocumentStoryLocator as Ep}from"@datalking/begonia-doc-service/v1";function Wt(e,t){return e.empty&&e.from>=t.from&&e.from<=t.to}function Kt(e,t){return{kind:"text",segments:t.map(r=>({blockId:r.blockId,range:HC(r.range)})),...e.story?{story:structuredClone(e.story)}:{}}}function Et(e){return Kt(e,e.segments)}function Dn(e){return e?{kind:"node",nodeType:e.nodeType,stableIdentity:e.stableIdentity,path:[...e.path],...e.nodeFingerprint!=null?{nodeFingerprint:e.nodeFingerprint}:{}}:null}function On(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!Ep(e.story,t.story)?!1:e.segments.every((r,o)=>{let n=t.segments[o];return n?.blockId===r.blockId&&n.range.start===r.range.start&&n.range.end===r.range.end&&n.range.startAffinity===r.range.startAffinity&&n.range.endAffinity===r.range.endAffinity})}function os(e,t){return!e||!t||e.segments.length!==t.segments.length||(e.story||t.story)&&!Ep(e.story,t.story)?!1:e.segments.every((r,o)=>{let n=t.segments[o];return!!(n&&r.blockId===n.blockId&&r.range.start===r.range.end&&r.range.start>=n.range.start&&r.range.end<=n.range.end)})}function sr(e,t){return!e||!t?e===t:e.nodeType!==t.nodeType?!1:e.stableIdentity!=null&&t.stableIdentity!=null?e.stableIdentity===t.stableIdentity&&(e.nodeFingerprint==null||t.nodeFingerprint==null||e.nodeFingerprint===t.nodeFingerprint):e.path.length===t.path.length&&e.path.every((r,o)=>r===t.path[o])}import{canonicalizeRevisionIds as qC,normalizeRevisionIds as Pl,selectionOverlapsRevisionRange as WC}from"@datalking/begonia-engine";function KC(e){if("from"in e)return{from:e.from,to:e.to};let{anchor:t,head:r}=e.range.range;return t.story.storyType!=="body"||r.story.storyType!=="body"||t.path.length>0||r.path.length>0?null:{from:Math.min(t.offset,r.offset),to:Math.max(t.offset,r.offset)}}function _C(e,t){return t.length>0?qC(e,t):[]}function le(e,t){let r=Pl(e);return t&&t.length>0?_C(r,t):r}function UC(e){return e==="paragraph"||e==="heading"}function ZC(e){return(e.target?.nodeType==="bookmark_anchor"||e.target?.nodeType==="structural_revision_carrier")&&UC(e.target.blockType)&&e.target.blockPath.length>0&&(e.text??"").trim().length===0}function GC(e,t){let r=KC(e);return r?Mn(Pl(t.filter(o=>WC(r.from,r.to,o)).map(o=>o.id)),t):[]}function ce(e){return Pl(e)}function ar(e,t){let r=ce(e),o=ce(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function lr(e,t){let r=le(e.trackedChangeIds,t),o=GC(e,t),n=new Set(t.filter(ZC).map(a=>a.id));if(o.length===0)return r;if(r.length===0)return o;let i=new Set(o),s=Mn(r.filter(a=>i.has(a)||n.has(a)),t);return s.length>0?s:o}function Do(e,t){let r=lr(e,t),o=e.trackedChangeIds??[];return e.trackedChangeIds!=null&&r.length===o.length&&r.every((n,i)=>n===o[i])?e:{...e,trackedChangeIds:r}}function Ur(e,t,r){let o=e.activeChangeIds??[],n=lr("from"in t?{from:t.from,to:t.to,trackedChangeIds:o}:{range:t.range,trackedChangeIds:o},r);return e.activeChangeIds!=null&&n.length===o.length&&n.every((i,s)=>i===o[s])?e:{...e,activeChangeIds:n}}function XC(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Mt(e,t=[]){return le([...e?.activeChangeIds??[],...e?.selection.trackedChangeIds??[]],t)}function Rl(e,t,r=[]){if(!e||!t)return e===t;let o=XC(Mt(e,r),Mt(t,r));return e.selectionKind!==t.selectionKind||e.projectedMode!==t.projectedMode||e.selection.empty!==t.selection.empty||!o?!1:e.selectionKind==="node"||t.selectionKind==="node"?sr(e.nodeSelectionTarget,t.nodeSelectionTarget):e.selectionTarget||t.selectionTarget?On(e.selectionTarget,t.selectionTarget):e.selection.from!==t.selection.from||e.selection.to!==t.selection.to?!1:e.text==null||t.text==null||e.text===t.text}var Ip=Symbol.for("@datalking/begonia-browser-sdk/selection-capture-document-identity"),Mp=1;function $C(){let e=globalThis.crypto?.randomUUID?.();if(typeof e=="string"&&e.length>0)return e;let t=Mp;return Mp+=1,`browser-selection-capture-document:${t}`}function jn(e){let t=e==null?null:Reflect.get(e,Ip);return typeof t=="string"&&t.length>0?t:null}function Ap(e){let t=jn(e);if(t!=null||e==null||!Object.isExtensible(e))return t;let r=$C();return Object.defineProperty(e,Ip,{configurable:!0,enumerable:!1,value:r,writable:!1}),r}function YC(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Oo(e){if(e==null)return null;try{return YC(JSON.stringify(e.toJSON()))}catch{return null}}var QC=Object.freeze({success:!0}),eP=Object.freeze({success:!1,reason:"read-only"});function jo(){return{success:!1,reason:"stale"}}function tP(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function qe(e,t,r={}){try{let o=at(e.view.state,t);return o?(e.view.dispatch(e.view.state.tr.setSelection(o).scrollIntoView()),r.focus!==!1&&e.focus(),!0):!1}catch{return!1}}function rP(e,t){return e.documentIdentity==null&&e.documentHash==null?!0:e.documentIdentity!=null&&e.documentIdentity!==jn(t)?!1:e.documentHash==null||e.documentHash===Oo(t)}function oP(e){let t=Mt(e);return e.selectionKind==="text"&&typeof e.text=="string"&&(e.text.length>0||t.length>0)}function Tl(e){let{capture:t,options:r={},resolveSelection:o,surface:n}=e;if(!n.view?.state||typeof n.view.dispatch!="function")return{success:!1,reason:"not-ready"};if(!t||!t.target&&!t.selectionTarget&&!t.nodeSelectionTarget)return{success:!1,reason:"missing-target"};if(n.editable===!1)return eP;if(!tP(t.storyOriginPath,JC(n.view.state.doc))||r.validateDocumentIdentity!==!1&&!rP(t,n.view.state.doc))return jo();let i=o(t);return!i||t.selectionKind==="node"&&!K(i)||r.validateText!==!1&&oP(t)&&ge(n.view.state.doc,n.view.state.schema,i)!==t.text?jo():qe(n,i,r)?QC:jo()}var ns=Object.freeze({blockSeparator:`
4
- `});function is(e,t){if(t.story===void 0)return!0;if(!nP(t.story))return!1;let r=iP(e)??{kind:"story",storyType:"body"};return sP(r,t.story)}function aP(e,t,r,o,n){let i=se(e,ns),s=Io(t,o,n,i);return s==null?null:He(t,r,s,n,i)}function lP(e,t,r,o,n){let i=se(e,ns),s=Io(t,o,"start",i),a=Io(t,n,"end",i);if(s==null||a==null)return null;let l=He(t,r,Math.min(s,a),"start",i),c=He(t,r,Math.max(s,a),"end",i);return typeof l=="number"&&typeof c=="number"?{from:Math.min(l,c),to:Math.max(l,c)}:null}function cP(e,t,r,o,n){let i=He(e,t,r,"start",n),s=He(e,t,o,"end",n);return typeof i=="number"&&typeof s=="number"?{from:Math.min(i,s),to:Math.max(i,s)}:null}function dP(e,t){return t.collapsedAcceptedVisibleBias==="hidden-anchor"||e.range.start===0?"end":"start"}function uP(e,t,r={}){let o=Le(e,t.blockId);if(!o)return null;let n=Ve(e,o);if(!n?.node.isBlock)return null;let i=se(e,ns);if(Ao(t.blockId)){if(t.range.start===t.range.end){let l=aP(e,n.node,n.position,t.range.start,dP(t,r));return typeof l=="number"?{from:l,to:l}:null}let a=lP(e,n.node,n.position,t.range.start,t.range.end);return a||null}if(t.range.start===t.range.end){let a=Eo(n.node,n.position,t.range.start,i);return typeof a=="number"?{from:a,to:a}:null}if(r.strict)return cP(n.node,n.position,t.range.start,t.range.end,i);let s=mp(n.node,n.position,t.range.start,t.range.end,i);return s||null}function Np(e,t){return ge(e,e.type.schema,t)}function mP(e,t){let r=Q(e,{kind:"text",segments:[t]},{strict:!0});return r?Np(e,r):null}function pP(e,t){let r=e.indexOf(t);return r<0||e.indexOf(t,r+1)>=0?null:{start:r,end:r+t.length}}function kl(e,t,r){if(!is(e,t)||t.segments.length!==1||r.length===0)return null;let[o]=t.segments,n=Le(e,o.blockId);if(!n)return null;let i=Ve(e,n);if(!i?.node.isBlock)return null;let s=se(e,ns),a=Mo(i.node,s),l=pP(a.text,r);if(!l)return null;let c=Io(i.node,l.start,"start",s),d=Io(i.node,l.end,"end",s);if(c==null||d==null)return null;let u=He(i.node,i.position,c,"start",s),m=He(i.node,i.position,d,"end",s);return typeof u!="number"||typeof m!="number"?null:{selection:{from:Math.min(u,m),to:Math.max(u,m)},target:Kt(t,[{blockId:o.blockId,range:{start:Ao(o.blockId)?Math.min(l.start,l.end):Math.min(c,d),end:Ao(o.blockId)?Math.max(l.start,l.end):Math.max(c,d)}}])}}function fP(e,t,r){return kl(e,t,r)?.selection??null}function Q(e,t,r={}){if(!t||!is(e,t))return null;let o=[];for(let n of t.segments){let i=uP(e,n,r);if(!i)return null;o.push(i)}return _r(e,o,r)}function Ae(e,t,r,o={}){let n=Q(e,t,o);return n&&(typeof r!="string"||r.length===0||Np(e,n)===r)?n:!t||typeof r!="string"||r.length===0?null:fP(e,t,r)}function lt(e,t){if(!t||!is(e,t))return null;let r=[];for(let o of t.segments){let n=mP(e,o);if(n==null)return null;r.push(n)}return r}function tt(e,t,r,o={}){if(!t||!is(e,t)||!r||r.length!==t.segments.length)return null;let n=[];for(let[i,s]of t.segments.entries()){let a=Ae(e,{kind:"text",segments:[s]},r[i]??null,{...o,strict:!0});if(!a)return null;n.push(a)}return _r(e,n,o)}function El(e,t){let r=e.view;if(!r?.state||typeof r.dispatch!="function")return!1;let o=Q(r.state.doc,t,{strict:!0});if(!o)return!1;let n=Z(r.state,o.from,o.to);return n?qe(e,n):!1}function Dp(e){return e.anchor>e.head?"backward":"forward"}function xr(e){return e.anchor!=null&&e.head!=null&&e.anchor>e.head?"backward":"forward"}function gt(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to);return t==="backward"?{anchor:o,head:r}:{anchor:r,head:o}}function Op(e,t){return Math.max(1,Math.min(t,e.content.size))}function Ml(e,t){let r=Op(e.doc,Math.min(t.from,t.to)),o=Op(e.doc,Math.max(t.from,t.to));if(r>=o)return null;let n=gt({from:r,to:o},t.direction),i=Z(e,n.anchor,n.head);if(!i||i.empty)return null;try{return e.apply(e.tr.setSelection(i))}catch{return null}}function SP(e,t,r=null,o=null,n){let i=tt(e.doc,t,r,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"})??Ae(e.doc,t,o,{strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"});if(!i||i.from>=i.to)return null;let s=gt(i,n),a=Z(e,s.anchor,s.head);if(!a||a.empty)return null;try{return e.apply(e.tr.setSelection(a))}catch{return null}}function Zr(e,t){if(!t)return null;let r=Gi(e.doc,t);if(!r)return null;try{return e.apply(e.tr.setSelection(gP.create(e.doc,r.position)))}catch{return null}}function Il(e,t){return Zr(e,t.nodeSelectionTarget)??SP(e,t.target,t.segmentTexts,t.text,t.direction)??Ml(e,t)}function jp(e){let t=wP(e);if(!t||t.empty)return null;let r=at(e,t);if(!r)return null;if(qt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function vP(e,t){if(!t.selectionTarget||!t.segmentTexts||t.selectionTarget.segments.length!==t.segmentTexts.length)return null;let r=t.selectionTarget.segments.map((o,n)=>Ae(e.doc,{kind:"text",segments:[o]},t.segmentTexts?.[n]??null,{strict:!0}));return r.every(o=>o!=null)?r:null}function hP(e,t){let r=vP(e,t);if(!r||r.length===0)return null;let o=r[0].from,n=r[0].to;for(let i of r.slice(1)){if(!i||i.from<n)return null;n=Math.max(n,i.to)}return{from:o,to:n}}function cs(e,t){return t.selectionTarget?tt(e.doc,t.selectionTarget,t.segmentTexts??null,{strict:!0})??Ae(e.doc,t.selectionTarget,t.text??null,{strict:!0})??hP(e,t):null}function ss(e){return Math.max(0,Math.abs(e.to-e.from))}function yP(e,t,r){let o=ce([...ce(t.activeChangeIds),...ce(t.selection.trackedChangeIds)]);return t.selectionKind==="text"&&!t.selection.empty&&o.length>0&&ss(t.selection)>0&&(ss(r??{from:0,to:0})===0||(()=>{if(!r)return!1;let n=ls(e,t);return!n||n.empty||ss(n)<=ss(r)?!1:ge(e.doc,e.schema,n)===ge(e.doc,e.schema,r)})())}function Al(e,t){let r=at(e,t);if(!r)return null;if(qt(e.selection,r))return e;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function ls(e,t){if(t.selectionKind==="node"){let o=rs(e.doc,Math.min(t.selection.from,t.selection.to)),n=e.doc.nodeAt(o);if(n&&as.isSelectable(n))try{return as.create(e.doc,o)}catch{}}let r=gt(t.selection,xr(t.selection));return Z(e,Wr(e.doc,r.anchor),Wr(e.doc,r.head))}function Vp(e,t,r,o){if(r==="node"){let i=rs(e.doc,Math.min(t.from,t.to)),s=e.doc.nodeAt(i);if(s&&as.isSelectable(s))try{return as.create(e.doc,i)}catch{return null}}let n=gt(t,o);return Z(e,Wr(e.doc,n.anchor),Wr(e.doc,n.head))}function bP(e,t){let r=Zr(e,t.nodeSelectionTarget)?.selection;if(K(r))return r;let o=cs(e,t);if(o){let i=Vp(e,o,t.selectionKind,xr(t.selection));if(K(i))return i}let n=ls(e,t);return K(n)?n:null}function cr(e,t){if(t.selectionKind==="node")return bP(e.state,t);let r=cs(e.state,t);return r?yP(e.state,t,r)?ls(e.state,t):Vp(e.state,r,t.selectionKind,xr(t.selection)):ls(e.state,t)}function xP(e,t,r){return Z(e,t,r)}function CP(e){let t=e;return(t.selectionKind==="text"||t.selectionKind==="node")&&"selectionTarget"in e&&"nodeSelectionTarget"in e&&(t.selectionKind==="node"||typeof t.text=="string"||Array.isArray(t.segmentTexts)||Array.isArray(t.activeChangeIds))}function PP(e,t){if(CP(t))return cr({state:e},t);let r=Math.min(t.selection.from,t.selection.to),o=Math.max(t.selection.from,t.selection.to);return xP(e,r,o)}function RP(e){let t=e.view;return t?.state&&typeof t.dispatch=="function"?t:null}function rt(e,t,r,o={}){let n=RP(e);if(!n)return!1;if(!t)return r(e);let i=o.restoreSelection??!0,s=n.state.selection,a=PP(n.state,t);if(!a||qt(s,a))return r(e);let c=BP(s),d=n.dispatch.bind(n);n.dispatch=(u=>{if(u.docChanged&&c)try{c=c.map(u.mapping)}catch{c=null}return d(u)});try{try{n.dispatch(n.state.tr.setSelection(a))}catch{return r(e)}return r(e)}finally{if(n.dispatch=d,i&&c)try{let u=c.resolve(n.state.doc);if(u){let m=at(n.state,u);m&&n.dispatch(n.state.tr.setSelection(m))}}catch{}}}var kP=["color","highlight","fontFamily","fontSize","fontSizeCs","rFonts"];function Gr(e,t){return{ok:!0,changed:t,value:e}}function ot(e){return{ok:!1,changed:!1,reason:e}}function Fp(e,t){let r=ve(e),o=ir({editable:e.getState().editable},r.state,t);return o||(t?null:"Place the caret in text or select text before applying inline formatting.")}function zp(e,t,r){return e.empty&&!t?`Collapsed ${r} formatting requires a live editor surface. Select text to format in headless mode.`:null}function Hp(e){return e.target&&"segments"in e.target?e.target:e.selectionTarget??null}function qp(e,t,r){let o=ve(e),n=e.documentApi.format.apply({target:t,inline:r,participant:o.trackingEnabled?o.participant:void 0,context:o.trackingEnabled?{source:"formatting"}:void 0});return n.success?Gr(n,!0):n.failure.code==="NO_OP"?Gr(n,!1):ot(n.failure.message)}function Wp(e){return e?{...e}:{}}function EP(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t))return!1;let r=e,o=t,n=Object.keys(r).sort(),i=Object.keys(o).sort();return n.length===i.length&&n.every((s,a)=>s===i[a]&&Object.is(r[s],o[s]))}function MP(e,t){let r=Wp(e),o=!1;for(let n of kP){if(t[n]===void 0)continue;let i=n==="fontSize"||n==="fontSizeCs"?typeof t[n]=="number"?t[n]:null:n==="rFonts"?t.rFonts&&typeof t.rFonts=="object"?structuredClone(t.rFonts):null:typeof t[n]=="string"?t[n]:null;(n==="rFonts"?EP(r[n],i):Object.is(r[n],i))||(r[n]=i,o=!0)}return{changed:o,attrs:Object.values(r).some(n=>n!=null)?r:null}}function Lp(e,t){let r=ve(e);if(!r.view)return ot("Collapsed text-style formatting requires a live editor surface. Select text to format in headless mode.");let{state:o,dispatch:n}=r.view,i=o.schema.marks.text_style;if(!i)return ot("Inline text-style marks are not available on this surface.");let a=TP(o).find(d=>d.type===i)??null,l=MP(Wp(a?.attrs),t);if(!l.changed)return Gr(a?.attrs??null,!1);let c=o.tr.removeStoredMark(i);return l.attrs&&(c=c.addStoredMark(i.create(l.attrs))),n(c),Gr(l.attrs,!0)}function Vo(e,t,r=null,o={}){let n=r?e.readSelectionCapture(r):e.readEffectiveSelection();if(r&&!n)return ot("Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.");let i=Fp(e,n);if(i)return ot(i);if(!n)return ot("Place the caret in text or select text before applying inline formatting.");let s=zp(n,ve(e).view!=null,"text-style");if(s)return ot(s);if(n.empty){if(r){let l=null;return rt(ve(e),n,()=>(l=Lp(e,t),l.changed),{restoreSelection:o.restoreSelection??!1}),l??ot("Inline formatting could not be applied.")}return Lp(e,t)}let a=Hp(n);return a?qp(e,a,t):ot("Place the caret in text or select text before applying inline formatting.")}function Nl(e,t){switch(t){case"bold":return e.toggleBold();case"italic":return e.toggleItalic();case"underline":return e.toggleUnderline();case"strike":return e.toggleStrike()}}function IP(e,t){let r=Nl(ve(e),t);return Gr(r,r)}function AP(e,t){return t==="bold"?e.selection.formatting.bold:t==="italic"?e.selection.formatting.italic:t==="underline"?e.selection.formatting.underline:e.selection.formatting.strike}function _t(e,t,r=null,o={}){let n=r?e.readSelectionCapture(r):e.readEffectiveSelection();if(r&&!n)return ot("Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.");let i=Fp(e,n);if(i)return ot(i);if(!n)return ot("Place the caret in text or select text before applying inline formatting.");let s=zp(n,ve(e).view!=null,"inline");if(s)return ot(s);if(n.empty){if(r){let d=rt(ve(e),n,u=>Nl(u,t),{restoreSelection:o.restoreSelection??!1});return Gr(d,d)}return IP(e,t)}let a=ve(e);if(a.view&&!r){let d=rt(a,n,u=>Nl(u,t),{restoreSelection:o.restoreSelection??!1});return Gr(d,d)}let l=Hp(n);if(!l)return ot("Place the caret in text or select text before applying inline formatting.");let c=!AP(n,t);return qp(e,l,{[t]:c})}function ds(e){let t=e?.layoutMode??"vertical";return{flowMode:e?.flowMode??"paginated",layoutMode:t,preferredPaginatedLayoutMode:e?.preferredPaginatedLayoutMode??t,zoomPercent:e?.zoom?.percent??e?.zoomPercent??100,zoomMode:e?.zoom?.mode??"manual"}}function us(e,t){switch(t.type){case"flow":return{flowMode:t.flowMode};case"toggle-pagination":return{flowMode:e.flowMode==="paginated"?"web":"paginated"};case"layout":return{flowMode:"paginated",layoutMode:t.layoutMode};case"zoom":return{zoomPercent:t.zoomPercent}}}import{normalizeHyperlinkHref as Kp}from"@datalking/begonia-document-model";var _p=8,Up=96;function It(e){return typeof e=="object"&&e!==null}function NP(e,t=!0){return typeof e=="boolean"?e:It(e)&&typeof e.changed=="boolean"?e.changed:t}function $(e,t=NP(e)){return{ok:!0,changed:t,value:e}}function ye(e){return{ok:!1,changed:!1,reason:e}}function Zp(e){if(typeof e=="string"){let r=Kp(e);return r?{href:r,title:null}:null}if(!It(e))return null;let t=Kp(e.href);return t?{href:t,title:typeof e.title=="string"?e.title:e.title==null?null:String(e.title)}:null}function Gp(e){return typeof e=="string"?e.trim()?e:null:!It(e)||typeof e.text!="string"||e.text.trim().length===0?null:{text:e.text,isInternal:typeof e.isInternal=="boolean"?e.isInternal:void 0}}function Lo(e){if(e==null)return null;if(typeof e!="string")return;let t=e.trim();if(t)return t.toLowerCase()==="none"?null:t}function Dl(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?Math.min(Up,Math.max(_p,e)):void 0;if(typeof e!="string")return;let t=e.trim();if(!t)return;if(t.toLowerCase()==="none")return null;let r=Number.parseFloat(t);return Number.isFinite(r)?Math.min(Up,Math.max(_p,r)):void 0}function jl(e){let t=Lo(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"color"))return Lo(e.color);if(Object.hasOwn(e,"value"))return Lo(e.value)}}function Xp(e){let t=Lo(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"fontFamily"))return Lo(e.fontFamily);if(Object.hasOwn(e,"value"))return Lo(e.value)}}function $p(e){let t=Dl(e);if(t!==void 0)return t;if(It(e)){if(Object.hasOwn(e,"fontSize"))return Dl(e.fontSize);if(Object.hasOwn(e,"value"))return Dl(e.value)}}function Ol(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?e:null;if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=t.endsWith("%")?t.slice(0,-1).trim():t;if(!r||!/^(?:\d+(?:\.\d+)?|\.\d+)$/u.test(r))return null;let o=Number.parseFloat(r);return Number.isFinite(o)&&o>0?o:null}function Yp(e){let t=Ol(e);if(t!=null)return t;if(!It(e))return null;let r=Ol(e.zoomPercent);if(r!=null)return{zoomPercent:r};let o=Ol(e.zoom);return o!=null?{zoom:o}:null}function Jp(e){return typeof e=="string"?e:!It(e)||typeof e.query!="string"?null:{query:e.query,options:It(e.options)?e.options:void 0}}function Vl(e){return typeof e=="string"?e:!It(e)||typeof e.text!="string"?null:{text:e.text,hitId:typeof e.hitId=="string"?e.hitId:e.hitId==null?null:String(e.hitId)}}function Qp(e){return typeof e=="string"?e:!It(e)||typeof e.text!="string"?null:{text:e.text,diagnosticId:typeof e.diagnosticId=="string"?e.diagnosticId:e.diagnosticId==null?null:String(e.diagnosticId)}}function ms(e){return e.getZoomState().mode}function ef(e){return e.getZoomPercent()}function Ll(e,t){return e.getState().preferredPaginatedLayoutMode!==t}function Fo(e,t){let r=ve(e);return rt(r,e.readEffectiveSelection(),t)}function Ut(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?ye(e.reason):$(e)}function DP(e){return e===!1?ye("Comment could not be created."):Ut(e)}function OP(e,t,r){let o=ve(e);switch(t){case"font-size":{let n=$p(r),i=n===null?null:Number(n);return n===void 0?ye('Expected a font-size payload or "none".'):Vo(e,{fontSize:i,fontSizeCs:i})}case"font-family":{let n=Xp(r);return n===void 0?ye('Expected a font-family payload or "none".'):Vo(e,{fontFamily:n==null?null:String(n),rFonts:null})}case"text-color":{let n=jl(r);return n===void 0?ye('Expected a text-color payload or "none".'):Vo(e,{color:n==null?null:String(n)})}case"highlight-color":{let n=jl(r);return n===void 0?ye('Expected a highlight-color payload or "none".'):Vo(e,{highlight:n==null?null:String(n)})}case"zoom":{let n=Yp(r);if(!n)return ye("Expected a positive zoom percentage payload.");let i=typeof n=="number"?n:n.zoomPercent??n.zoom??null;if(i==null)return ye("Expected a positive zoom percentage payload.");let s=ef(e),a=ms(e);return e.setViewState(us(ds(e.getState()),{type:"zoom",zoomPercent:i})),$(i,ef(e)!==s||ms(e)!==a)}case"zoom-fit-width":{let n=ms(e);e.setZoomMode(n==="fit-width"?"manual":"fit-width");let i=ms(e);return $(i,i!==n)}case"document-mode-editing":{let n=e.getState().documentMode;return e.setDocumentMode("editing"),$("editing",e.getState().documentMode!==n)}case"document-mode-suggesting":{let n=e.getState().documentMode;return e.setDocumentMode("suggesting"),$("suggesting",e.getState().documentMode!==n)}case"document-mode-viewing":{let n=e.getState().documentMode;return e.setDocumentMode("viewing"),$("viewing",e.getState().documentMode!==n)}case"flow-mode-paginated":{let n=e.getFlowMode();return e.setViewState(us(ds(e.getState()),{type:"flow",flowMode:"paginated"})),$("paginated",e.getFlowMode()!==n)}case"flow-mode-web":{let n=e.getFlowMode();return e.setViewState(us(ds(e.getState()),{type:"flow",flowMode:"web"})),$("web",e.getFlowMode()!==n)}case"layout-mode-vertical":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"vertical"}),$("vertical",e.getLayoutMode()!==i||Ll(e,n))}case"layout-mode-horizontal":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"horizontal"}),$("horizontal",e.getLayoutMode()!==i||Ll(e,n))}case"layout-mode-book":{let n=e.getState().preferredPaginatedLayoutMode,i=e.getLayoutMode();return e.setViewState({layoutMode:"book"}),$("book",e.getLayoutMode()!==i||Ll(e,n))}case"track-changes-display-review":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("review"),$("review",e.getState().trackChanges.mode!==n)}case"track-changes-display-original":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("original"),$("original",e.getState().trackChanges.mode!==n)}case"track-changes-display-final":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("final"),$("final",e.getState().trackChanges.mode!==n)}case"track-changes-display-off":{let n=e.getState().trackChanges.mode;return e.setTrackChangesDisplayMode("off"),$("off",e.getState().trackChanges.mode!==n)}case"comments-visible":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!0),$(!0,e.getState().commentsDisplay.visible!==n)}case"comments-hidden":{let n=e.getState().commentsDisplay.visible;return e.setCommentsVisible(!1),$(!1,e.getState().commentsDisplay.visible!==n)}case"comments-show-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!0),$(!0,e.getState().commentsDisplay.showResolved!==n)}case"comments-hide-resolved":{let n=e.getState().commentsDisplay.showResolved;return e.setCommentsShowResolved(!1),$(!1,e.getState().commentsDisplay.showResolved!==n)}case"comments-visibility-all":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("all"),$("all",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-internal":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("internal"),$("internal",e.getState().commentsDisplay.visibility!==n)}case"comments-visibility-external":{let n=e.getState().commentsDisplay.visibility;return e.setCommentsVisibility("external"),$("external",e.getState().commentsDisplay.visibility!==n)}case"undo":return $(o.undo());case"redo":return $(o.redo());case"bold":return _t(e,"bold");case"italic":return _t(e,"italic");case"underline":return _t(e,"underline");case"strikethrough":return _t(e,"strike");case"paragraph":return $(Fo(e,n=>n.setParagraph()));case"heading-1":return $(Fo(e,n=>n.setHeading(1)));case"heading-2":return $(Fo(e,n=>n.setHeading(2)));case"heading-3":return $(Fo(e,n=>n.setHeading(3)));case"bullet-list":return $(Fo(e,n=>n.toggleBulletList()));case"numbered-list":return $(Fo(e,n=>n.toggleOrderedList()));case"link-set":{let n=Zp(r);return n?$(typeof n=="string"?e.setLink(n):e.setLink(n.href,n.title??null)):ye("Expected a non-empty link payload.")}case"link-clear":return $(e.clearLink());case"comment-create":{let n=Gp(r);if(!n)return ye("Expected non-empty comment text for comment creation.");let i=e.readEffectiveSelection();return DP(typeof n=="string"?i?e.createCommentFromCapture(i,n):e.createComment(n):i?e.createCommentFromCapture(i,n.text,{isInternal:n.isInternal??void 0}):e.createComment(n.text,{isInternal:n.isInternal??void 0}))}case"tracking-toggle":return e.setDocumentMode(e.getState().documentMode==="suggesting"?"editing":"suggesting"),$(!0,!0);default:return null}}function tf(e,t,r){let o=OP(e,t,r);if(o)return o;let n=ep(e,t,r);if(n)return n;switch(t){case"search-set-query":{let i=Jp(r);if(!i)return ye("Expected a search query payload.");let s=typeof i=="string"?e.search(i):e.search(i.query,i.options??{});return $(s,!0)}case"search-next":return(()=>{let i=e.nextSearchHit();return $(i,i!=null)})();case"search-previous":return(()=>{let i=e.previousSearchHit();return $(i,i!=null)})();case"search-clear":{let i=e.getState().search.query.length>0;return e.clearSearch(),$(void 0,i)}case"search-replace-active":{let i=Vl(r);if(!i)return ye("Expected replacement text for the active search hit.");let s=e.getState(),a=typeof i=="string"?s.search.activeHitId:i.hitId??s.search.activeHitId;if(!a)return ye("No active search hit is available to replace.");let l=typeof i=="string"?e.replaceSearchHit(a,i):e.replaceSearchHit(a,i.text);return Ut(l)}case"search-replace-all":{let i=Vl(r);if(!i)return ye("Expected replacement text for search replace-all.");let s=typeof i=="string"?e.replaceAllSearchHits(i):e.replaceAllSearchHits(i.text);return Ut(s)}case"review-accept-all":return Ut(e.acceptAll());case"track-changes-accept-selection":return Ut(e.acceptSelection());case"review-reject-all":return Ut(e.rejectAll());case"track-changes-reject-selection":return Ut(e.rejectSelection());case"proofing-ignore-first":{let i=e.getState().proofing.diagnostics[0]?.diagnosticId;return i?Ut(e.ignoreProofingDiagnostic(i)):ye("No proofing diagnostic is available to ignore.")}case"proofing-accept-first":{let i=e.getState().proofing.diagnostics[0]?.diagnosticId;return i?Ut(e.acceptProofingSuggestion(i)):ye("No proofing diagnostic is available to accept.")}case"proofing-replace-first-tracked":{let i=Qp(r),a=e.getState().proofing.diagnostics[0],l=typeof i=="string"?a?.diagnosticId:i?.diagnosticId??a?.diagnosticId,c=typeof i=="string"?i:i?.text??a?.replacementText??a?.suggestion??"";return!l||!c?ye("No tracked proofing replacement could be resolved."):Ut(e.replaceProofingDiagnosticTracked(l,c))}default:return null}}import{createEditorSessionController as LT}from"@datalking/begonia-editor-ui";function ct(e){return e?.trim()??""}function Vn(e,t){let r=ct(e);return r.length===0?"":ct(t?.id)||r}function rf(e){return/(?:^|[-_:])wire(?:[-_:]|$)/i.test(ct(e))}function Ze(e){let t=new Map,r=new Set;for(let n of e??[]){let i=ct(n.id);i.length!==0&&(r.add(i),t.set(i,i))}let o=new Map;for(let n of e??[]){let i=ct(n.id);if(i.length===0)continue;let s=ct(n.wireId);if(s.length===0||r.has(s))continue;let a=o.get(s);a===void 0||a===i?o.set(s,i):o.set(s,null)}for(let[n,i]of o)i&&t.set(n,i);return t}function zo(e,t){let r=ct(e);return t.get(r)??r}function jP(e,t){let r=ct(t);if(r.length===0)return"";let o=e?.get?.(r)??null;if(o)return Vn(r,o);let n=rf(r),i=e?.target?.(r)??null;if(i&&(ct(i.id)===r||n))return Vn(r,i);let s=e?.targetSnapshot?.(r)??null;return s&&(ct(s.id)===r||n)?Vn(r,s):r}function At(e,t){return[...new Set((e??[]).map(r=>zo(r,t)).filter(r=>r.length>0))]}function of(e,t){let r=(e??[]).map(s=>ct(s)).filter(s=>s.length>0),o=t?.get==null&&r.length>1&&r.every(s=>!rf(s)),n=[],i=new Set;for(let s of r){let a=o?s:jP(t,s);a.length===0||i.has(a)||(i.add(a),n.push(a))}return n}function nf(){return{success:!1}}function sf(e,t){try{e.restoreSelectionHandle?.(t,{focus:!1})}catch{return}}function af(e){return e.shouldContinue?.()??!0}async function ps(e,t,r={}){let o=e.captureEffectiveSelectionHandle();try{let n=await t();return af(r)?(n.success||sf(e,o),n):nf()}catch{return af(r)&&sf(e,o),nf()}finally{e.releaseSelectionHandle(o)}}function VP(e){return"host"in e}function he(e){return e?VP(e)?e.host:e:null}function LP(e){return"getState"in e&&typeof e.getState=="function"&&"subscribe"in e&&typeof e.subscribe=="function"&&"readLayoutSource"in e&&typeof e.readLayoutSource=="function"&&"readLayoutAdapter"in e&&typeof e.readLayoutAdapter=="function"&&"requestPreviewNavigation"in e&&typeof e.requestPreviewNavigation=="function"&&"ackPreviewNavigationRequest"in e&&typeof e.ackPreviewNavigationRequest=="function"&&"setViewState"in e&&typeof e.setViewState=="function"&&"setZoomViewportMetrics"in e&&typeof e.setZoomViewportMetrics=="function"}function lf(e){return e?LP(e)?e:he(e)?.preview??null:null}function fs(e={}){return{commentTarget:null,selected:!1,selectionTarget:null,navigationRequest:null,...e}}function cf(e,t){return t?typeof t=="string"?e.documentApi.comments.target(t):t:null}function df(e){return e.documentApi.selection.current({includeText:!0}).target}function FP(e){return e&&"id"in e&&typeof e.id=="string"&&e.id.length>0?e.id:null}function Fl(){return{success:!1}}function uf(e,t){let r=he(e);if(!r)return fs();let o=cf(r,t);if(!o)return fs();if(!r.selectionTargets.selectCommentTarget(o))return fs({commentTarget:o});let i=df(r);return fs({commentTarget:o,selected:!0,selectionTarget:i,navigationRequest:r.browserViewport.requestNavigationForTextTarget(i)})}async function mf(e,t,r={},o={}){let n=he(e);if(!n)return Fl();let i=cf(n,t);return i?ps(n.selectionHandles,async()=>{if(n.selectionTargets.selectCommentTarget(i)){let a=df(n);if(a)return n.browserViewport.scrollIntoView({target:a,timeoutMs:r.timeoutMs,continuation:o.continuation})}let s=FP(i);return s?n.browserViewport.scrollIntoView({target:{type:"comment",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Fl()},{shouldContinue:o.continuation?.shouldContinue}):Fl()}function zP(e,t,r){return{shouldContinue(){return e()===t},subscribe(o){return r(t,o)}}}function ws(){let e=0,t=new Set,r=()=>{let n=[...t];e+=1,t=new Set;for(let i of n)try{i()}catch{continue}return e},o=(n,i)=>n!==e?()=>{}:(t.add(i),()=>{n===e&&t.delete(i)});return{begin(){let n=r();return zP(()=>e,n,o)},invalidate(){r()}}}function HP(e){return e.find(t=>t.type==="comment")??null}function qP(e,t){return[...new Set(e.filter(r=>r.type==="comment").map(r=>zo(r.id,t)).filter(r=>r.length>0))]}function WP(e,t){let r=Ze(e),o=zo(t,r);return e.find(n=>zo(n.id,r)===o||zo(n.wireId,r)===o)??null}function KP(e,t){let r=Ze(e),o=qP(t,r);if(o.length!==1)return null;let n=o[0]??HP(t)?.id??null;if(!n)return null;let i=WP(e,n);return!i||typeof i.id!="string"||i.id.length===0?null:{id:i.id,item:i}}function pf(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=he(e);return o?KP(r,o.browserViewport.entitiesAtPoint(t)):null}import{listProjectionSelectionRects as PR,resolveProjectionCaretRect as RR}from"@datalking/begonia-page-layout";import{isDenseArray as TR}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as _P,INSERTION_MARK_NAME as UP,semanticNodeText as ZP}from"@datalking/begonia-engine";function ff(e){return typeof e=="number"?Math.max(0,e):null}function GP(e){return e.startPath?e.startPath:e.segments?.find(t=>t.kind==="range")?.startPath??null}function XP(e){if(e.endPath)return e.endPath;for(let t=(e.segments?.length??0)-1;t>=0;t-=1){let r=e.segments?.[t];if(r?.kind==="range"&&r.endPath)return r.endPath}return null}function $P(e){return e.anchorPath?e.anchorPath:e.segments?.find(t=>t.kind==="anchor")?.anchorPath??null}function YP(e,t){let r=e,o=Ve(r,t),n=o?.node.type.name==="comment_anchor"?o.position:No(r,t);return ff(n)}function gs(e){return e.marks.some(t=>t.type.name===UP||t.type.name===_P)}function JP(e,t,r){let o=!1;return e.nodesBetween(t,r,(n,i)=>{if(o)return!1;if(!(n.isText||n.isInline&&n.isLeaf&&ZP(n).length>0))return!0;let a=Math.max(t,i);return Math.min(r,i+n.nodeSize)<=a?!1:(o=gs(n),!o)}),o}function wf(e,t){let r=e,o=Ve(r,t);return o?o.node.type.name!=="comment_range_start"?No(r,t):gs(o.node)?No(r,t):o.position:null}function QP(e,t,r={}){if(t?.kind!=="range"||!t.startPath||!t.endPath)return null;let o=e,n=wf(e,t.startPath),i=No(o,t.endPath);if(typeof n!="number"||typeof i!="number"||n>i)return null;let s={from:n,to:i},a=JP(e,s.from,s.to),l=r.allowTrackedContentFallback??!0,c=se(o,{blockSeparator:`
5
- `}),d=t.addressableBlockPath??t.blockPath??null,u=d?Ve(o,d):null,m=u?.node??null,p=t.text;if(!u||!m?.isBlock||typeof p!="string"||p.length===0)return s;let f=Br(m,c),g=we(m,u.position,s.from,c),v=Math.max(g,we(m,u.position,s.to,c)),E=f.slice(g,v);if(E===p)return s;let R=E.indexOf(p);if(R<0||E.indexOf(p,R+1)>=0)return a&&!l?null:s;let S=g+R,P=S+p.length,h=He(m,u.position,S,"start",c),b=He(m,u.position,P,"end",c),x=Ve(o,t.startPath)?.node??null,A=Ve(o,t.endPath)?.node??null,O=R===0&&!(a&&x?.type.name==="comment_range_start"&&!gs(x)),j=P===v&&!(a&&A?.type.name==="comment_range_end"&&!gs(A)),_=O?s.from:h,V=j?s.to:b;return typeof _!="number"||typeof V!="number"||V<=_?a&&!l?null:s:{from:Math.min(_,V),to:Math.max(_,V)}}function eR(e){return e!=null}function tR(e,t){let r=e,o=t.segments??[],n=t.source==="live",i=o.map(a=>QP(e,a,{allowTrackedContentFallback:n}));if(o.length>0&&!n&&i.some(a=>a==null))return null;let s=i.filter(eR);if(s.length===0){let a=GP(t),l=XP(t);if(!a||!l)return null;let c=wf(e,a),d=No(r,l);return typeof c!="number"||typeof d!="number"?null:{from:Math.min(c,d),to:Math.max(c,d)}}return _r(r,s,{strict:!n})}function Ge(e,t){if(!t)return null;if(t.targetKind==="range")return tR(e,t);let r=$P(t);if(!r)return null;let o=YP(e,r);return typeof o!="number"?null:{from:o,to:o}}import{readSyntheticSideStoryDocContext as rR,resolveSyntheticSideStoryPathPosition as oR}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as nR}from"@datalking/begonia-document-model";import{parseAddressableBlockId as iR}from"@datalking/begonia-doc-service/structure";function sR(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function gf(e,t){let r=e,o=-1;for(let n of t){if(!nR(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return{node:r,position:o}}function aR(e,t){let r=gf(e,t);return r?.node.isBlock?{path:[...t],localPath:[...t],document:e,position:r.position,node:r.node,syntheticRootPath:null,positionRoot:null}:null}function lR(e,t){let r=rR(sR(e),t);if(!r)return null;let o=r.localizePath(t),n=r.globalizePath([]),i=oR(e.type.schema,e,n),s=o?gf(r.doc,o):null;return o&&s?.node.isBlock&&typeof i=="number"?{path:[...t],localPath:[...o],document:r.doc,position:s.position,node:s.node,syntheticRootPath:n,positionRoot:i}:null}function Cr(e,t){let r=Le(e,t);if(r)return aR(e,r);let o=iR(t);return o?.path.some(n=>n<0)?lR(e,o.path):null}function Zt(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?t-e.positionRoot:t}import{resolveDocumentStoryLocatorFromPath as cR}from"@datalking/begonia-doc-service/v1";import{addressableBlockTypeForNodeType as dR,formatAddressableBlockId as uR,formatAddressableBlockIdWithLogicalId as mR}from"@datalking/begonia-doc-service/structure";function pR(e,t){return{kind:"text",segments:[{blockId:e,range:{start:0,end:0}}],...t?{story:t}:{}}}function fR(e,t,r){return r?structuredClone(r):cR({listSections:()=>e.sections?.list?.()??[],listFootnotes:()=>e.notes?.footnotes?.list?.()??e.notes?.list?.()??[],listEndnotes:()=>e.notes?.endnotes?.list?.()??[],listHeaderFooterParts:()=>e.headerFooters?.parts?.list?.()?.items??[]},t)}function Ss(e,t,r){if(!e||!Array.isArray(t)||t.length===0)return null;let o=e.blocks.read(t);if(!o)return null;let n=dR(o.type.name);if(!n)return null;let i=Hr(n,o),s=i?mR(n,t,i):uR(n,t);return pR(s,fR(e,t,r)??void 0)}function Ln(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.trunc(e):null}function wR(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Sf(e,t){return!Array.isArray(t)||t.length===0?null:Ss(e,t)}function gR(e,t){let r=Math.max(0,typeof e.text=="string"?e.text.length:typeof t.text=="string"?t.text.length:0),o=Ln(e.startOffset)??Ln(t.startOffset)??0,n=Ln(e.endOffset)??Ln(t.endOffset)??(r>0?o+r:o);return{start:o,end:Math.max(o,n)}}function SR(e){let t=e.segments?.filter(r=>r.kind==="range")??[];return t.length>0?t:[{kind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:e.blockPath??null,addressableBlockPath:e.addressableBlockPath??null,startOffset:e.startOffset??null,endOffset:e.endOffset??null,text:e.text}]}function vR(e){let t=e.segments?.find(r=>r.kind==="anchor");return t?.addressableBlockPath??t?.blockPath??e.addressableBlockPath??e.blockPath??null}function vs(e,t){if(!e||!t)return null;if(t.targetKind==="range"){let n=[],i;for(let s of SR(t)){let a=s.addressableBlockPath??s.blockPath??null,l=Sf(e,a);if(!l)return null;if(i===void 0)i=l.story;else if(!wR(i,l.story))return null;n.push({blockId:l.segments[0].blockId,range:gR(s,t)})}return n.length>0?{kind:"text",segments:n,...i?{story:i}:{}}:null}let r=Sf(e,vR(t));if(!r)return null;let o=Ln(t.anchorOffset)??0;return{kind:"text",segments:[{blockId:r.segments[0].blockId,range:{start:o,end:o}}],...r.story?{story:r.story}:{}}}import{isIntegerPath as hR}from"@datalking/begonia-document-model";var yR=Object.freeze({blockSeparator:`
6
- `});function Ho(e){return typeof e=="number"&&Number.isFinite(e)}function bR(e){return Array.isArray(e)&&e.length>0&&hR(e)}function BR(e){return!!e&&typeof e=="object"&&bR(e.blockPath)}function xR(e){let t=s=>[s.blockPath.join("."),Ho(s.from)?Math.min(s.from,s.to??s.from):"",Ho(s.to)?Math.max(s.from??s.to,s.to):""].join(":"),r=[e?.target??null,...e?.targets??[]].filter(BR),o=s=>Ho(s.from)&&Ho(s.to)?0:1,n=s=>o(s)===0?Math.min(s.from,s.to):Number.POSITIVE_INFINITY,i=s=>o(s)===0?Math.max(s.from,s.to):Number.POSITIVE_INFINITY;return r.map((s,a)=>({target:s,index:a})).sort((s,a)=>o(s.target)-o(a.target)||n(s.target)-n(a.target)||i(s.target)-i(a.target)||s.index-a.index).reduce((s,a)=>{let l=t(a.target);return s.some(c=>t(c)===l)||s.push(a.target),s},[])}function vf(e,t,r){return Math.min(Math.max(e,t),r)}function CR(e,t,r){if(!e||!Ho(r.from)||!Ho(r.to))return null;let o=Cr(e,t);if(!o)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=Zt(o,Math.min(r.from,r.to)),a=Zt(o,Math.max(r.from,r.to)),l=vf(s,n,i),c=vf(a,l,i),d=se(o.document,yR),u=we(o.node,o.position,l,d),m=we(o.node,o.position,c,d);return{start:Math.min(u,m),end:Math.max(u,m)}}function zl(e,t,r){if(!e||!r)return{target:null,selectionTarget:null};let o=null,n=null;for(let i of xR(r)){let s=Ss(e,i.blockPath,r.story);if(!s)continue;let a=s.segments[0]?.blockId;if(!a)continue;n||(o=i,n={kind:"text",segments:[{blockId:a,range:{start:0,end:0}}],...s.story?{story:s.story}:{}});let l=CR(t,a,i);if(l)return{target:i,selectionTarget:{kind:"text",segments:[{blockId:a,range:l}],...s.story?{story:s.story}:{}}}}return{target:o,selectionTarget:n}}function hs(e,t,r){return zl(e,t,r).selectionTarget}function Gt(e){return typeof e?.readLayoutSource=="function"?e.readLayoutSource():null}function qo(e){return e?.getResolvedProjection?.()??null}function Xt(e){return e?.getResolvedProjectionGeometryOptions?.()??null}function St(e){return{success:!1,reason:e}}function kR(e){return!e||typeof e!="object"?!1:!!e&&"kind"in e&&e.kind==="text"&&TR(e.segments)}function hf(e){return typeof e=="number"&&Number.isFinite(e)}function ER(e){return!e||e.segments.length===0?!1:e.segments.every(t=>typeof t?.blockId=="string"&&t.blockId.trim().length>0&&hf(t.range?.start)&&hf(t.range?.end))}function MR(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"id"in e&&typeof e.id=="string"}function IR(e){return e?typeof e.id=="string"&&e.id.trim().length>0:!1}function Hl(e){return!e||typeof e!="object"?!1:!!e&&"type"in e&&"childCount"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function yf(e,t){return typeof e!="number"||!Number.isFinite(e)||typeof t!="number"||!Number.isFinite(t)?null:{from:Math.min(e,t),to:Math.max(e,t)}}function AR(e){return{pageIndex:e.pageIndex,pageNumber:e.pageNumber,sectionId:e.sectionId??null,region:e.region,blockIndex:e.blockIndex,fragmentIndex:e.fragmentIndex,columnIndex:e.columnIndex,lineIndex:e.lineIndex,lineCount:e.lineCount,left:e.left,top:e.top,width:e.width,height:e.height}}function NR(e){return{pageIndex:e.pageIndex,pageNumber:e.pageNumber,sectionId:e.sectionId??null,region:e.region,blockIndex:e.blockIndex,fragmentIndex:e.fragmentIndex,columnIndex:e.columnIndex,lineIndex:e.lineIndex,lineCount:e.lineCount,left:e.left,top:e.top,width:1,height:e.height}}function DR(e){return[e.pageIndex,e.pageNumber,e.sectionId??"",e.region,e.blockIndex,e.fragmentIndex,e.columnIndex,e.lineIndex,e.lineCount,e.left,e.top,e.width,e.height].join(":")}function OR(e){let t=[],r=new Set;for(let o of e){let n=DR(o);r.has(n)||(r.add(n),t.push(o))}return t}function jR(e,t){let r=qo(e),o=Xt(e)??{};if(!r)return[];if(t.from===t.to){let n=RR(r,t.from,o);return n?[NR(n)]:[]}return PR(r,t.from,t.to,o).map(AR)}function ql(e,t){if(t.segments.length===0)return null;let r=[];for(let o of t.segments){let n=LR(e,o);if(!n)return null;r.push(n)}return r}function VR(e,t){return e.syntheticRootPath&&typeof e.positionRoot=="number"?{from:e.positionRoot+t.from,to:e.positionRoot+t.to}:t}function LR(e,t){let r={kind:"text",segments:[t]},o=Q(e,r,{strict:!0});if(o)return o;let n=Cr(e,t.blockId);if(!n||n.document===e)return null;let i=Q(n.document,r,{strict:!0});return i?VR(n,i):null}function FR(e){if(!e)return[];let t=(e.segments??[]).map(o=>yf(o.from,o.to)).filter(o=>o!=null).sort((o,n)=>o.from-n.from||o.to-n.to);if(t.length>0)return t;let r=yf(e.from,e.to);return r?[r]:[]}function zR(e,t,r){if(!r||typeof t?.blocks?.read!="function")return null;let o=hs(t,e,r);return o?ql(e,o):null}function HR(e,t="unresolved"){let[r]=e;return r?{success:!0,rect:r,rects:[...e],pageIndex:r.pageIndex,pageNumber:r.pageNumber}:St(t)}function Fn(e,t){let r=OR(t.flatMap(o=>jR(e,o)));return HR(r,t.length>0?"not-mounted":"unresolved")}function Wo(e,t){let r=e.preview??null;if(!r||!qo(r))return St("not-ready");let o=t.target??null;if(!o)return St("invalid-target");if(kR(o)){if(!ER(o))return St("invalid-target");let n=Gt(r);if(!Hl(n))return St("not-ready");let i=ql(n,o);return i?Fn(r,i):St("unresolved")}if(!MR(o)||!IR(o))return St("invalid-target");if(o.type==="comment"){let n=Gt(r);if(!Hl(n))return St("not-ready");let i=e.documentApi?.comments.target(o.id)??null,s=vs(e.documentApi,i),a=s?ql(n,s):null;if(a)return Fn(r,a);let l=Ge(n,i);return l?Fn(r,[l]):St("unresolved")}if(o.type==="trackedChange"){let n=e.documentApi?.trackChanges.get(o.id)??null,i=Gt(r),s=Hl(i)?zR(i,e.documentApi,n):null;if(s)return Fn(r,s);let a=FR(n);return a.length===0?St("unresolved"):Fn(r,a)}return St("invalid-target")}var qR=Object.freeze([]),WR=[],KR=Object.freeze({});function Wl(e){let t=e?.items??WR,r=e?.permissions??KR;return{items:t,permissions:r,total:typeof e?.total=="number"?Math.max(0,Math.trunc(e.total)):t.length,activeCommentId:e?.activeCommentId??null,activeCommentIds:e?.activeCommentIds??qR,enabled:e?.enabled??!1,visible:e?.visible??!1,readOnly:e?.readOnly??!1,showResolved:e?.showResolved??!1,visibility:e?.visibility??null}}function bf(e){return structuredClone(e)}function Kl(e){return Wl(e?e.session.readState()?.comments??null:null)}function Bf(e,t){return At(typeof t=="string"?[t]:[],Ze(Kl(e).items))[0]??null}function xf(e,t){let r=ws(),o=()=>bf(Wl(t.getSnapshot())),n=i=>t.subscribe(s=>{i(bf(Wl(s)))});return{getSnapshot:o,subscribe:n,observe(i){return n(i)},create(i,s){return e.commentActions.createComment(i,s)},reply(i,s,a=null){return e.commentActions.replyComment(i,s,a)},setInternal(i,s){return e.commentActions.setCommentInternal(i,s)},resolve(i){return e.commentActions.resolveComment(i)},reopen(i){return e.commentActions.reopenComment(i)},setActive(i){return r.invalidate(),e.commentFocus.setActiveComment(i)},reveal(i){r.invalidate();let s=Kl(e).activeCommentId??null,a=typeof i=="string"?Bf(e,i):null;a&&e.commentFocus.setActiveComment(a);let l=uf(e,i);return!l.selected&&a&&e.commentFocus.setActiveComment(s),l},async scrollTo(i,s){let a=r.begin(),l=Kl(e).activeCommentId??null,c=typeof i=="string"?Bf(e,i):null;c&&e.commentFocus.setActiveComment(c);let d=await mf(e,i,s,{continuation:a});return a.shouldContinue()?(!d.success&&c&&e.commentFocus.setActiveComment(l),d):{success:!1}},getAt(i){return pf(e,i,o().items)},getRect({id:i}){return Wo(e,{target:{type:"comment",id:i}})}}}var Cf=["editing","suggesting","viewing"],Pf=["review","original","final","off"],Rf=["paired","independent"],Tf=["all","internal","external"];function ys(e,t){return typeof e=="string"&&t.includes(e)}function _R(e){return e.map(t=>`"${t}"`).join(", ")}function bs(e,t,r){return new TypeError(`[BrowserEditor] ${e} must be one of ${_R(r)}; received ${JSON.stringify(t)}.`)}function _l(e){return ys(e,Cf)?e:null}function Bs(e){let t=_l(e);if(t)return t;throw bs("documentMode",e,Cf)}function Xr(e){return ys(e,Pf)?e:null}function kf(e){let t=Xr(e);if(t)return t;throw bs("trackChanges.mode",e,Pf)}function $r(e){return ys(e,Rf)?e:null}function Ef(e){let t=$r(e);if(t)return t;throw bs("trackChanges.replacements",e,Rf)}function Yr(e){return ys(e,Tf)?e:null}function Mf(e){let t=Yr(e);if(t)return t;throw bs("comments.visibility",e,Tf)}function zn(e,t){if(typeof e=="boolean")return e;throw new TypeError(`[BrowserEditor] ${t} must be a boolean; received ${JSON.stringify(e)}.`)}function Hn(e){return e==="paginated"||e==="web"?e:null}function Jr(e){return Hn(e)??"paginated"}function dt(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function dr(e,t){return t==="web"?"vertical":dt(e)??"vertical"}function Qr(e){let t=Jr(e.flowMode),r=dt(e.preferredPaginatedLayoutMode)??dt(e.layoutMode)??"vertical";return{flowMode:t,layoutMode:dr(dt(e.layoutMode)??r,t),preferredPaginatedLayoutMode:r}}import{resolveEditorSelectionRootOffsets as If}from"@datalking/begonia-editor-contracts";import{listProjectionSelectionRects as UR,resolveProjectionCaretRect as ZR}from"@datalking/begonia-page-layout";function GR(e){return e==="end"||e==="union"?e:"start"}function XR(e){return e?{left:e.left,top:e.top,width:1,height:e.height}:null}function $R(e){if(e.length===0)return null;let t=e[0].left,r=e[0].top,o=e[0].left+e[0].width,n=e[0].top+e[0].height;for(let i of e.slice(1))t=Math.min(t,i.left),r=Math.min(r,i.top),o=Math.max(o,i.left+i.width),n=Math.max(n,i.top+i.height);return{left:t,top:r,width:Math.max(1,o-t),height:Math.max(1,n-r)}}function qn(e,t){let r=qo(e),o=Xt(e)??{};if(!r||!t||t.empty)return[];let n=If(t);return n?UR(r,n.from,n.to,o):[]}function Ul(e,t,r={}){let o=qo(e),n=Xt(e)??{};if(!o||!t||!t.empty)return null;let i=If(t);return i?ZR(o,i.from,{bias:r.bias,measureText:n.measureText,measurementEpoch:n.measurementEpoch}):null}function Af(e,t,r={}){let o=qn(e,t);if(o.length===0)return XR(Ul(e,t));switch(GR(r.placement)){case"end":{let n=o.at(-1)??null;return n?{left:n.left,top:n.top,width:n.width,height:n.height}:null}case"union":return $R(o);default:{let n=o[0]??null;return n?{left:n.left,top:n.top,width:n.width,height:n.height}:null}}}import{cloneEditorSelectionSnapshot as YR}from"@datalking/begonia-editor-contracts";function Ko(e){return e?{empty:e.empty,target:e.target?Et(e.target):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}var Zl=Object.freeze([]);function JR(e){return e?structuredClone(e):void 0}function QR(e){if(!e||!Array.isArray(e.segments))return null;let t=e.segments[0]??null,r=e.segments[e.segments.length-1]??null;if(!t||!r)return null;let o=JR(e.story);return{kind:"selection",start:{kind:"text",blockId:t.blockId,offset:t.range.start,...o?{story:o}:{}},end:{kind:"text",blockId:r.blockId,offset:r.range.end,...o?{story:o}:{}},segments:e.segments.map(n=>({blockId:n.blockId,start:n.range.start,end:n.range.end})),...o?{story:o}:{}}}function xs(e,t){if(!e)return null;let r=YR(e),o=Ko(t),n=o?.target??null;return{...r,target:n,selectionTarget:QR(n),activeMarks:o?.activeMarks??Zl,activeCommentIds:o?.activeCommentIds??Zl,activeChangeIds:o?.activeChangeIds??Zl,quotedText:o?.text??""}}import{clonePageViewportAnchor as Ff,hasFreshViewportRequest as nT,normalizeViewportRequestKey as iT,samePageViewportAnchor as sT,sameViewportRequestKey as aT}from"@datalking/begonia-layout-renderer/core";import{hasLogicalViewportAnchorHint as eT}from"@datalking/begonia-layout-renderer/core";var Wn=100,Nt=1,Df=1e-6;function Xe(e){return typeof e=="number"&&Number.isFinite(e)}function vt(e,t,r=0){return e===t||Math.abs(e-t)<=r}function Of(e,t,r=0){return e==null||t==null?e===t:vt(e,t,r)}function jf(e,t=0){return Xe(e)?Math.max(0,Math.trunc(e)):t}function Xl(e){return Xe(e)&&Number.isInteger(e)&&e>=0?e:null}function eo(e){return Xe(e)&&Number.isInteger(e)&&e>0?e:null}function Gl(e,t){if(!Array.isArray(e))return[];let r=e.filter(o=>Xe(o)&&Number.isInteger(o)&&o>=t);return[...new Set(r)].sort((o,n)=>o-n)}function tT(e){return e.map(t=>t+1)}function Nf(e){return e.map(t=>t-1)}function rT(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function $l(e,t){let r=Gl(t,1);if(r.length>0){let n=Gl(e,0);return n.length>0&&!rT(Nf(r),n)?null:{pageIndexes:Nf(r),pageNumbers:r}}let o=Gl(e,0);return{pageIndexes:o,pageNumbers:tT(o)}}function Yl(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function Jl(e){return e==="paginated"||e==="web"?e:null}function Vf(e){return Xe(e)&&e>0?e:null}function Ql(e,t){let r=Jl(e),o=Yl(t);return e!=null&&r==null||t!=null&&o==null?null:r==="web"?o!=null&&o!=="vertical"?null:{flowMode:r,layoutMode:"vertical"}:{flowMode:r,layoutMode:o}}function oT(e){return e==="header"||e==="body"||e==="footer"}function Lf(e){return oT(e?.region)&&!eT(e)&&e?.fragmentIndex==null&&e?.columnIndex==null&&e?.blockOffsetTopPx==null&&e?.blockOffsetTopRatio==null&&e?.blockOffsetLeftPx==null&&e?.blockOffsetLeftRatio==null}function $t(e,t){let r=eo(t),o=Xl(e);return r!=null&&o!=null&&o!==r-1?{pageIndex:null,pageNumber:null}:{pageIndex:r!=null?r-1:o,pageNumber:r??(o!=null?o+1:null)}}function lT(e){if(e.visiblePageNumbers.length>0){let o=eo(e.firstVisiblePageNumber),n=eo(e.lastVisiblePageNumber);return o!=null&&o!==e.visiblePageNumbers[0]||n!=null&&n!==e.visiblePageNumbers[e.visiblePageNumbers.length-1]?null:{firstVisiblePageNumber:e.visiblePageNumbers[0]??null,lastVisiblePageNumber:e.visiblePageNumbers[e.visiblePageNumbers.length-1]??null}}let t=eo(e.firstVisiblePageNumber),r=eo(e.lastVisiblePageNumber);return t!=null&&r!=null&&t>r?null:{firstVisiblePageNumber:t,lastVisiblePageNumber:r}}function cT(e){return!!(e&&typeof e=="object"&&(Object.hasOwn(e,"pageNumber")||Object.hasOwn(e,"pageIndex")))}function zf(e,t,r){let o=Xe(t)?Math.max(0,t):Math.max(0,(Xe(r)?r:e)-e);return{size:o,end:e+o}}var dT=10,uT=500;function ht(e){return!Xe(e)||e<=0?null:Math.min(uT,Math.max(dT,e))}function Ne(e){return iT(e)}function Ps(e,t){return aT(e,t)}function tc(e,t){return nT(e,t)}function ur(e){return ht(e?.zoomPercent)??Wn}function _o(e,t){return re(e)?.flowMode===t}function Uo(e,t){return re(e)?.layoutMode===t}function to(e,t,r){return _o(e,t)&&Uo(e,r)}function Cs(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Zo(e,t){return sT(e,t)}function ec(e){let t=eo(e?.pageNumber),r=Xl(e?.pageIndex);if(t==null&&r==null||t!=null&&r!=null&&r!==t-1)return null;let o=t??(r??0)+1;return{pageIndex:o-1,pageNumber:o}}function Go(e,t=null){if(e&&typeof e=="object"&&cT(e)&&!ec(e))return null;let r=Ff(e);if(r)return r;if(!e||typeof e!="object")return null;let o=ec(e)??ec(t);return o?Ff({...e,...o}):null}function Xo(e){let t=$t(e?.anchorPageIndex,e?.anchorPageNumber).pageNumber??$t(e?.currentPageIndex,e?.currentPageNumber).pageNumber,r=Go(e?.viewportAnchor??null,{pageNumber:t});return r?t!=null&&r.pageNumber!==t?Lf(r)?r:null:r:null}function rc(e,t,r){let o=Ql(e?.flowMode,e?.layoutMode);if(e&&typeof e=="object"&&o==null)return!0;let n=o?.flowMode??null,i=o?.layoutMode??null;return n!=null&&n!==t||i!=null&&i!==r}function nt(e,t){let r=re(e),o=re(t);return!r||!o?r===o:Kn(r,o)&&Cs(r.mountedPageIndexes,o.mountedPageIndexes)&&Cs(r.mountedPageNumbers,o.mountedPageNumbers)&&vt(r.topSpacer,o.topSpacer,Nt)&&vt(r.bottomSpacer,o.bottomSpacer,Nt)&&vt(r.leftSpacer,o.leftSpacer,Nt)&&vt(r.rightSpacer,o.rightSpacer,Nt)}function Kn(e,t){let r=re(e),o=re(t);return!r||!o?r===o:r.totalPages===o.totalPages&&r.currentPageIndex===o.currentPageIndex&&r.currentPageNumber===o.currentPageNumber&&r.anchorPageIndex===o.anchorPageIndex&&r.anchorPageNumber===o.anchorPageNumber&&Zo(r.viewportAnchor,o.viewportAnchor)&&Cs(r.visiblePageIndexes,o.visiblePageIndexes)&&Cs(r.visiblePageNumbers,o.visiblePageNumbers)&&r.firstVisiblePageNumber===o.firstVisiblePageNumber&&r.lastVisiblePageNumber===o.lastVisiblePageNumber&&vt(r.viewportTop,o.viewportTop,Nt)&&vt(r.viewportBottom,o.viewportBottom,Nt)&&vt(r.viewportHeight,o.viewportHeight,Nt)&&vt(r.viewportLeft,o.viewportLeft,Nt)&&vt(r.viewportRight,o.viewportRight,Nt)&&vt(r.viewportWidth,o.viewportWidth,Nt)&&r.layoutMode===o.layoutMode&&r.flowMode===o.flowMode&&Of(r.scale,o.scale,Df)}function re(e){if(!e||typeof e!="object")return null;let t=Ql(e.flowMode,e.layoutMode);if(!t)return null;let r=$t(e.currentPageIndex,e.currentPageNumber),o=$t(e.anchorPageIndex,e.anchorPageNumber),n=Xe(e.viewportTop)?e.viewportTop:0,i=Xe(e.viewportLeft)?e.viewportLeft:0,s=zf(n,e.viewportHeight,e.viewportBottom),a=zf(i,e.viewportWidth,e.viewportRight),l=$l(e.visiblePageIndexes,e.visiblePageNumbers);if(!l)return null;let c=$l(e.mountedPageIndexes,e.mountedPageNumbers);if(!c)return null;let d=lT({visiblePageNumbers:l.pageNumbers,firstVisiblePageNumber:e.firstVisiblePageNumber,lastVisiblePageNumber:e.lastVisiblePageNumber});if(!d)return null;let u=Go(e.viewportAnchor,{pageIndex:o.pageIndex??r.pageIndex,pageNumber:o.pageNumber??r.pageNumber});return{totalPages:jf(e.totalPages),currentPageIndex:r.pageIndex,currentPageNumber:r.pageNumber,anchorPageIndex:o.pageIndex,anchorPageNumber:o.pageNumber,viewportAnchor:u,visiblePageIndexes:l.pageIndexes,visiblePageNumbers:l.pageNumbers,mountedPageIndexes:c.pageIndexes,mountedPageNumbers:c.pageNumbers,firstVisiblePageNumber:d.firstVisiblePageNumber,lastVisiblePageNumber:d.lastVisiblePageNumber,viewportTop:n,viewportBottom:s.end,viewportHeight:s.size,viewportLeft:i,viewportRight:a.end,viewportWidth:a.size,topSpacer:Xe(e.topSpacer)?Math.max(0,e.topSpacer):0,bottomSpacer:Xe(e.bottomSpacer)?Math.max(0,e.bottomSpacer):0,leftSpacer:Xe(e.leftSpacer)?Math.max(0,e.leftSpacer):0,rightSpacer:Xe(e.rightSpacer)?Math.max(0,e.rightSpacer):0,layoutMode:t.layoutMode,flowMode:t.flowMode,scale:Vf(e.scale)}}function Yt(e,t){let r=re(e);if(!r)return null;let o=r.flowMode??Jl(t.flowMode),n=o==="web"?"vertical":r.layoutMode??Yl(t.layoutMode);return{...r,flowMode:o,layoutMode:n}}var mT=Object.freeze({percent:100,mode:"manual",value:100,fitZoom:null,min:10,max:400,viewportMetrics:null});function $o(e){return{getSnapshot(){return e.get()},subscribe(t){return e.subscribe(t)},observe(t){return e.subscribe(t)}}}function pT(e){let t=Qr(e);return{flowMode:t.flowMode,layoutMode:t.layoutMode,preferredPaginatedLayoutMode:t.preferredPaginatedLayoutMode,zoom:Hf(e)}}function fT(e){return xs(e.selection,e.selectionInfo)}function wT(e){return{editable:e.editable,documentMode:_l(e.documentMode),trackingEnabled:e.trackingEnabled,trackChanges:{enabled:e.review.enabled,visible:e.review.visible,mode:Xr(e.review.mode),replacementMode:$r(e.review.replacementMode)}}}function gT(e){return{enabled:e.comments.enabled,visible:e.comments.visible,readOnly:e.comments.readOnly,allowResolve:e.comments.allowResolve??!1,showResolved:e.comments.showResolved,visibility:Yr(e.comments.visibility),useInternalExternalComments:e.comments.useInternalExternalComments??!1,suppressInternalExternal:e.comments.suppressInternalExternal??!1,enforceVisibilityPolicy:e.comments.enforceVisibilityPolicy??!1,total:e.comments.total??e.comments.items.length}}function Hf(e){return e.zoom?{percent:e.zoom.percent,mode:e.zoom.mode==="fit-width"?"fit-width":"manual",value:typeof e.zoom.value=="number"?e.zoom.value:e.zoom.percent,fitZoom:typeof e.zoom.fitZoom=="number"?e.zoom.fitZoom:null,min:typeof e.zoom.min=="number"?e.zoom.min:10,max:typeof e.zoom.max=="number"?e.zoom.max:400,viewportMetrics:e.zoom.viewportMetrics}:mT}function ST(e){if(!e.viewport)return null;let t=re(e.viewport.value);return{value:t,requestKey:e.viewport.requestKey,previewNavigationRequest:e.viewport.previewNavigationRequest,totalPages:t?.totalPages??null,currentPageIndex:t?.currentPageIndex??null,currentPageNumber:t?.currentPageNumber??null}}function qf(e,t){return{...$o(t.select(pT)),setViewState(o){e.view.setViewState(o)},getZoomState(){return e.view.getZoomState()},setZoomMode(o){e.view.setZoomMode(o)}}}function Wf(e,t){let r=$o(t.select(fT));return{...r,getRects(){return qn(e.preview,r.getSnapshot())},getAnchorRect(o){return Af(e.preview,r.getSnapshot(),o)},getCaretRect(o){return Ul(e.preview,r.getSnapshot(),o)}}}function Kf(e,t){return{...$o(t.select(wT)),setDocumentMode(o){e.documentMode.setDocumentMode(o)},setTrackChangesDisplayMode(o){e.documentMode.setTrackChangesDisplayMode(o)}}}function _f(e,t){return{...$o(t.select(gT)),setCommentsVisible(o){e.commentsDisplay.setCommentsVisible(o)},setCommentsShowResolved(o){e.commentsDisplay.setCommentsShowResolved(o)},setCommentsVisibility(o){e.commentsDisplay.setCommentsVisibility(o)}}}function Uf(e,t){return{...$o(t.select(Hf)),set(o){e.view.setViewState({zoomPercent:o})},setMode(o){e.view.setZoomMode(o)}}}function Zf(e,t){return{...$o(t.select(ST)),getHost(){return e.browserViewport.getHost?.()??null},getScrollContainer(){return e.browserViewport.getScrollContainer?.()??null},observeGeometry(o){return e.browserViewport.observeGeometry(o)},scrollIntoView(o){return e.browserViewport.scrollIntoView(o)},getRect(o){return Wo(e,o)},entitiesAtPoint(o){return e.browserViewport.entitiesAtPoint(o)},contextAtPoint(o){return e.browserViewport.contextAtPoint(o)},positionAtPoint(o){return e.browserViewport.positionAtPoint(o)},requestNavigation(o){return e.browserViewport.requestNavigation(o)},requestNavigationForTextTarget(o){return e.browserViewport.requestNavigationForTextTarget(o)},ackNavigationRequest(o){e.browserViewport.ackNavigationRequest(o)}}}import{isIntegerPath as vT}from"@datalking/begonia-document-model";function Yo(e={}){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,...e}}function hT(e){return Array.isArray(e)&&e.length>0&&vT(e)}function Rs(e){return!!e&&typeof e=="object"&&hT(e.blockPath)}function Xf(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;let t="revisionId"in e?e.revisionId:"id"in e?e.id:null;return typeof t=="string"&&t.length>0?t:null}function yT(e){return e?Rs(e.target)?e.target:(e.targets??[]).find(Rs)??null:null}function bT(e){let t="target"in e?e.target:null,r="targets"in e?e.targets:null;return Rs(t)||(r??[]).some(Rs)}function BT(e,t){if(typeof t!="string"&&bT(t))return t;let r=Xf(t);return r?e.documentApi.trackChanges.get(r):null}function xT(e,t){let r=Gt(lf(e));return zl(e.documentApi,CT(r)?r:null,t)}function CT(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function PT(e,t){return(typeof t?.id=="string"&&t.id.length>0?t.id:typeof t?.revisionId=="string"&&t.revisionId.length>0?t.revisionId:null)??e}function _n(e,t){if(!e||!t)return Yo();let r=he(e);if(!r)return Yo();let o=Xf(t),n=BT(r,t);if(!n)return Yo({revisionId:o});let i=PT(o,n),s=xT(r,n),a=s.target??yT(n);if(!a)return Yo({revisionId:i,trackChange:n});let l=s.selectionTarget;return Yo(l?{revisionId:i,trackChange:n,target:a,selectionTarget:l}:{revisionId:i,trackChange:n,target:a})}function Gf(){return{success:!1}}function RT(e){let t=e.revisionId;if(typeof t=="string"&&t.length>0)return t;let r=e.trackChange?.id;return typeof r=="string"&&r.length>0?r:null}async function Ts(e,t,r={},o={}){let n=_n(e,t),i=he(e);return!i||!n.selectionTarget?Gf():ps(i.selectionHandles,async()=>{if(i.selectionTargets.selectTextTarget(n.selectionTarget))return i.browserViewport.scrollIntoView({target:n.selectionTarget,timeoutMs:r.timeoutMs,continuation:o.continuation});let s=RT(n);return s?i.browserViewport.scrollIntoView({target:{type:"trackedChange",id:s},timeoutMs:r.timeoutMs,continuation:o.continuation}):Gf()},{shouldContinue:o.continuation?.shouldContinue})}function $f(e){if(e==null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jo(e,t){if(Object.is(e,t))return!0;if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Jo(e[n],t[n]))return!1;return!0}if(!$f(e)||!$f(t))return!1;let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let n of r)if(!Object.hasOwn(t,n)||!Jo(e[n],t[n]))return!1;return!0}function oc(e,t,r){let o=e.filter(s=>typeof s.id=="string"&&s.id.length>0);if(o.length===0)return null;let n=t==null?-1:o.findIndex(s=>s.id===t),i=r==="next"?n<0||n>=o.length-1?0:n+1:n<=0?o.length-1:n-1;return o[i]?.id??null}function TT(e){return e.find(t=>t.type==="trackedChange")??null}function kT(e){return[...new Set(e.filter(t=>t.type==="trackedChange").map(t=>t.id))]}function ET(e,t){return e.find(r=>r.id===t)??null}function MT(e,t){let r=kT(t);if(r.length!==1)return null;let o=r[0]??TT(t)?.id??null;if(!o)return null;let n=ET(e,o);return!n||typeof n.id!="string"||n.id.length===0?null:{id:n.id,item:n}}function Yf(e,t,r){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let o=he(e);return o?MT(r,o.browserViewport.entitiesAtPoint(t)):null}var Jf=Object.freeze([]),IT=Object.freeze([]),AT=Object.freeze([]),NT=Object.freeze({});function nc(e){return structuredClone(e)}function DT(){return{items:IT,permissions:NT,timeline:AT,summary:null,total:0,activeRevisionId:null,activeRevisionIds:Jf,enabled:!1,visible:!1,mode:null,replacementMode:null}}function OT(e,t){return Jo(e,t)}function jT(e){return e?{items:e.revisions,permissions:e.permissions,timeline:e.timeline,summary:e.summary,total:e.revisions.length,activeRevisionId:e.activeRevisionId??null,activeRevisionIds:e.activeRevisionIds??Jf,enabled:e.enabled,visible:e.visible,mode:e.mode,replacementMode:e.replacementMode}:DT()}function Pr(e){let r=he(e)?.session.readState();return jT(r?.review)}function sc(){return{revisionId:null,trackChange:null,target:null,selectionTarget:null,navigationRequest:null,selected:!1}}function ic(e,t){let r=he(e);if(!r||!t)return sc();let o=_n(e,t);if(!o.selectionTarget)return{...o,selected:!1};let n=r.selectionTargets.selectTextTarget(o.selectionTarget),i=r.browserViewport.requestNavigationForTextTarget(o.selectionTarget);return{...o,navigationRequest:i,selected:n}}function en(e,t){let r=he(e);return r?r.reviewFocus.setActiveRevision(t):!1}function Qo(e,t){let r=he(e);return r?t==="next"?r.reviewFocus.nextActiveRevision():r.reviewFocus.previousActiveRevision():null}async function VT(e,t,r,o){if(!he(e))return{success:!1};let i=Pr(e).activeRevisionId??null,s=_n(e,t);s.revisionId&&en(e,s.revisionId);let a=await Ts(e,t,r,{continuation:o});return o.shouldContinue()?(!a.success&&s.revisionId&&en(e,i),a):{success:!1}}function Qf(e){let t=he(e);if(!t)throw new Error("createBrowserEditorTrackChangesController requires a valid browser editor UI source.");let r=Pr(e),o=null,n=new Set,i=ws(),s=()=>{o||n.size===0||(o=t.session.subscribe(()=>{let c=Pr(e);if(OT(r,c)){r=c;return}r=c;for(let d of[...n])d(nc(r))}))},a=()=>{n.size>0||!o||(o(),o=null)},l=c=>(r=Pr(e),n.add(c),s(),c(nc(r)),()=>{n.delete(c),a()});return{getSnapshot(){return r=Pr(e),nc(r)},subscribe:l,observe(c){return l(c)},accept(c){return t.reviewActions.acceptRevision(c)},reject(c){return t.reviewActions.rejectRevision(c)},acceptAll(){return t.reviewActions.acceptAll()},rejectAll(){return t.reviewActions.rejectAll()},setActive(c){return i.invalidate(),en(e,c)},next(){return i.invalidate(),Qo(e,"next")},previous(){return i.invalidate(),Qo(e,"previous")},reveal(c){i.invalidate();let d=_n(e,c);return d.revisionId&&en(e,d.revisionId),ic(e,c)},revealNext(){i.invalidate();let c=Qo(e,"next");return c?ic(e,c):sc()},revealPrevious(){i.invalidate();let c=Qo(e,"previous");return c?ic(e,c):sc()},getAt(c){return r=Pr(e),Yf(e,c,r.items)},scrollTo(c,d){return VT(e,c,d,i.begin())},navigateNext(c){let d=i.begin(),u=Pr(e).activeRevisionId??null,m=Qo(e,"next");return m?Ts(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||en(e,u),p):{success:!1}):Promise.resolve({success:!1})},navigatePrevious(c){let d=i.begin(),u=Pr(e).activeRevisionId??null,m=Qo(e,"previous");return m?Ts(e,m,c,{continuation:d}).then(p=>d.shouldContinue()?(p.success||en(e,u),p):{success:!1}):Promise.resolve({success:!1})},getRect({id:c}){return Wo(t,{target:{type:"trackedChange",id:c}})}}}function ks(e){let t=LT(e.session),r=Wf(e,t),o=qf(e,t),n=Kf(e,t),i=_f(e,t),s=Zf(e,t),a=Uf(e,t),l=xf(e,t.comments),c=Qf(e),d=Object.assign(t,{host:e,session:e.session,documentApi:e.documentApi,readCommandSnapshot(u){return e.readCommandSnapshot(u)},selection:r,selectionHandles:e.selectionHandles,linkSelection:e.linkSelection,activeLink:e.activeLink,view:o,documentMode:n,comments:l,commentsDisplay:i,commentActions:e.commentActions,commentFocus:e.commentFocus,reviewActions:e.reviewActions,reviewFocus:e.reviewFocus,trackChanges:c,selectionTargets:e.selectionTargets,viewport:s,zoom:a,browserViewport:e.browserViewport,preview:e.preview,overlayState:e.overlayState,overlays:e.overlays??{}});return Object.defineProperty(d,"actor",{configurable:!1,enumerable:!0,get(){return e.actor}}),d}var FT=["insert-math-inline","insert-chart-block","insert-shape-block","remove-selected-ooxml","selected-math-set-plain-text","selected-math-toggle-display-mode","selected-chart-set-title","selected-chart-add-series","selected-chart-add-axis","selected-shape-set-text-body","selected-shape-set-fill","selected-shape-add-child"],zT=new Set(FT);function ew(e){return zT.has(e)}function D(e,t,r,o,n=[],i=!0){return{id:e,title:t,group:r,description:o,keywords:n,slash:i}}var Un=Object.freeze([D("undo","Undo","history","Revert the latest local editing step.",["history"],!1),D("redo","Redo","history","Re-apply the latest reverted step.",["history"],!1),D("zoom","Zoom","view","Set the document zoom level as a percentage.",["view","scale","percent"],!1),D("zoom-fit-width","Fit Width","view","Toggle fit-width zoom mode for the current viewport.",["view","scale","fit","width"],!1),D("document-mode-editing","Editing Mode","review","Switch the editor into direct editing mode.",["edit","write","author"],!1),D("document-mode-suggesting","Suggesting Mode","review","Switch the editor into suggestion authoring mode.",["suggest","track changes","review"],!1),D("document-mode-viewing","Viewing Mode","review","Switch the editor into read-only viewing mode.",["view","read-only","preview"],!1),D("flow-mode-paginated","Paginated Layout","view","Switch the editor into paginated layout mode.",["pagination","pages","print"],!1),D("flow-mode-web","Web Layout","view","Switch the editor into continuous web layout mode.",["web","continuous","scroll"],!1),D("layout-mode-vertical","Vertical Spread","view","Arrange paginated pages in a vertical stack.",["vertical","stack"],!1),D("layout-mode-horizontal","Horizontal Spread","view","Arrange paginated pages in a horizontal strip.",["horizontal","row"],!1),D("layout-mode-book","Book Spread","view","Arrange paginated pages in facing book spreads.",["book","spread","facing"],!1),D("track-changes-display-review","Review Markup","review","Display the document with review markup visible.",["markup","review mode"],!1),D("track-changes-display-original","Original Document","review","Project the document back to its original review baseline.",["original","projection"],!1),D("track-changes-display-final","Final Document","review","Project the document forward to its final accepted review state.",["final","projection"],!1),D("track-changes-display-off","Hide Review Markup","review","Hide tracked-change markup without switching authoring mode.",["hide markup","off"],!1),D("bold","Bold","format","Toggle bold formatting.",["strong","weight"]),D("italic","Italic","format","Toggle italic formatting.",["emphasis"]),D("underline","Underline","format","Toggle underline formatting.",["decoration"]),D("strikethrough","Strikethrough","format","Toggle strikethrough formatting.",["strike","delete","decoration"]),D("font-size","Font Size","format","Set or clear the font size on the current text selection.",["type","points"],!1),D("font-family","Font Family","format","Set or clear the font family on the current text selection.",["typeface","font"],!1),D("text-color","Text Color","format","Set or clear the text color on the current text selection.",["color","foreground"],!1),D("highlight-color","Highlight Color","format","Set or clear text highlight on the current selection.",["highlight","background"],!1),D("paragraph","Paragraph","block","Reset the current block to body paragraph text.",["body","normal"]),D("heading-1","Heading 1","block","Promote the current block to the top heading level.",["title","h1"]),D("heading-2","Heading 2","block","Promote the current block to a section heading.",["section","h2"]),D("heading-3","Heading 3","block","Promote the current block to a subsection heading.",["subsection","h3"]),D("bullet-list","Bulleted List","block","Toggle a bulleted list around the current block.",["list","bullets","unordered"]),D("numbered-list","Numbered List","block","Toggle a numbered list around the current block.",["list","ordered","numbers"]),D("insert-math-inline","Insert Equation","insert","Append an editable math OOXML node to the active text block.",["equation","math","formula"]),D("insert-chart-block","Insert Chart","insert","Insert an editable chart OOXML block after the current block.",["chart","graph","series"]),D("insert-shape-block","Insert Shape","insert","Insert an editable shape OOXML block after the current block.",["shape","callout","diagram"]),D("remove-selected-ooxml","Remove Selected OOXML","insert","Remove the currently selected advanced OOXML node.",["equation","chart","shape","delete"]),D("selected-math-set-plain-text","Edit Selected Equation","insert","Replace the currently selected math OOXML node with plain-text math content.",["equation","math","formula"],!1),D("selected-math-toggle-display-mode","Toggle Equation Display Mode","insert","Switch the selected OOXML equation between inline and block display mode.",["equation","math","display"],!1),D("selected-chart-set-title","Edit Selected Chart Title","insert","Update the title on the currently selected chart OOXML node.",["chart","title"],!1),D("selected-chart-add-series","Add Selected Chart Series","insert","Append a new data series to the currently selected chart OOXML node.",["chart","series","data"],!1),D("selected-chart-add-axis","Add Selected Chart Axis","insert","Append a new axis to the currently selected chart OOXML node.",["chart","axis","scale"],!1),D("selected-shape-set-text-body","Edit Selected Shape Text","insert","Update the text body on the currently selected shape OOXML node.",["shape","text"],!1),D("selected-shape-set-fill","Edit Selected Shape Fill","insert","Update the fill color on the currently selected shape OOXML node.",["shape","fill","color"],!1),D("selected-shape-add-child","Add Selected Shape Child","insert","Append a child shape node to the currently selected OOXML shape.",["shape","group","child"],!1),D("link-set","Set Link","insert","Apply or update a link on the current selection.",["hyperlink","url"],!1),D("link-clear","Clear Link","insert","Remove link formatting from the current selection.",["unlink"],!1),D("comment-create","Create Comment","review","Create a comment at the current selection or caret.",["comment","annotation","note"],!1),D("comments-visible","Show Comments","review","Show comment highlights and threads in the browser editor.",["comments","visible"],!1),D("comments-hidden","Hide Comments","review","Hide comment highlights and threads in the browser editor.",["comments","hidden"],!1),D("comments-show-resolved","Show Resolved Comments","review","Include resolved comments in the comment list and review timeline.",["comments","resolved"],!1),D("comments-hide-resolved","Hide Resolved Comments","review","Filter resolved comments out of the comment list and review timeline.",["comments","resolved"],!1),D("comments-visibility-all","All Comments","review","Show both internal and external comments.",["comments","all"],!1),D("comments-visibility-internal","Internal Comments","review","Filter the comment display to internal comment threads.",["comments","internal"],!1),D("comments-visibility-external","External Comments","review","Filter the comment display to external comment threads.",["comments","external"],!1),D("tracking-toggle","Toggle Track Changes","review","Switch between direct editing and suggestion mode.",["suggesting","review","changes"]),D("track-changes-accept-selection","Accept Selection Changes","review","Accept tracked revisions that overlap the current selection.",["track changes","selection","accept"],!1),D("track-changes-reject-selection","Reject Selection Changes","review","Reject tracked revisions that overlap the current selection.",["track changes","selection","reject"],!1),D("search-set-query","Search","search","Run a document search query.",["find"],!1),D("search-next","Next Search Result","search","Advance to the next current search hit.",["find","next"],!1),D("search-previous","Previous Search Result","search","Move back to the previous current search hit.",["find","previous"],!1),D("search-clear","Clear Search","search","Clear the current search session.",["find","reset"]),D("search-replace-active","Replace Current Search Result","search","Replace the active current search hit.",["find","replace"],!1),D("search-replace-all","Replace All Search Results","search","Replace every current search hit.",["find","replace","all"],!1),D("review-accept-all","Accept All Changes","review","Accept all tracked revisions in the document.",["track changes","approve"]),D("review-reject-all","Reject All Changes","review","Reject all tracked revisions in the document.",["track changes","discard"]),D("proofing-ignore-first","Ignore First Proofing Issue","proofing","Ignore the first current proofing diagnostic.",["spelling","grammar","ignore"]),D("proofing-accept-first","Accept First Proofing Suggestion","proofing","Apply the first current proofing suggestion without tracking.",["spelling","grammar","fix"]),D("proofing-replace-first-tracked","Track First Proofing Fix","proofing","Apply the first current proofing suggestion with tracked changes.",["spelling","grammar","review"],!1)]),yq=Object.freeze(Un.map(e=>e.id)),tn=Object.freeze(Un.filter(e=>!ew(e.id))),bq=Object.freeze(tn.map(e=>e.id)),Bq=new Map(Un.map(e=>[e.id,e]));function HT(e){let t=e.members?.length?e.members:null;return t?t.every(r=>(r.text?.length??0)===0&&r.target?.nodeType!=="text"):(e.text?.length??0)===0&&e.target?.nodeType!=="text"}function qT(e,t){if(!t||e.length===0)return!1;let r=new Map(t.map(o=>[o.id,o]));return e.every(o=>{let n=r.get(o);return n?HT(n):!1})}function ac(e,t){return le([...e.activeChangeIds??[],...e.selection.trackedChangeIds??[]],t)}function lc(e){let t=le(e.liveSelectionInfo?.activeChangeIds,e.revisions);return t.length>0?t:le(e.liveSelection.trackedChangeIds,e.revisions)}function WT(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&!e.effectiveSelection.selection.empty&&e.liveSelection.from>=e.effectiveSelection.selection.from&&e.liveSelection.from<=e.effectiveSelection.selection.to}function KT(e,t){return e.length>0&&e.length<t.length&&e.every(r=>t.includes(r))}function _T(e){return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.liveReviewChangeIds.length>0&&e.effectiveReviewChangeIds.length>0&&!(WT(e)&&KT(e.liveReviewChangeIds,e.effectiveReviewChangeIds))&&!ar(e.liveReviewChangeIds,e.effectiveReviewChangeIds)}function UT(e){let t=ac(e.effectiveSelection,e.revisions),r=lc({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions});return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&!e.effectiveSelection.selection.empty&&e.liveSelection.from===(e.boundary==="start"?e.effectiveSelection.selection.from:e.effectiveSelection.selection.to)&&e.effectiveSelection.selection.from!==e.effectiveSelection.selection.to&&r.length===0&&t.length>0}function cc(e){return UT({...e,boundary:"end"})}function ZT(e){let t=ac(e.effectiveSelection,e.revisions),r=lc({liveSelection:e.liveSelection,liveSelectionInfo:{activeChangeIds:[...e.liveActiveChangeIds]},revisions:e.revisions}),o=qT(t,e.revisions);return e.liveSelection.empty&&e.liveSelection.from===e.liveSelection.to&&e.effectiveSelection.selection.empty&&e.liveSelection.from===e.effectiveSelection.selection.to&&r.length===0&&t.length>0&&!o}function yt(e){let t=lc(e);if(!e.effectiveSelection)return t;if(cc({liveSelection:e.liveSelection,liveActiveChangeIds:ce(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];if(ZT({liveSelection:e.liveSelection,liveActiveChangeIds:ce(e.liveSelectionInfo?.activeChangeIds),effectiveSelection:e.effectiveSelection,revisions:e.revisions}))return[];let r=ac(e.effectiveSelection,e.revisions);return _T({liveSelection:e.liveSelection,liveReviewChangeIds:t,effectiveReviewChangeIds:r,effectiveSelection:e.effectiveSelection})?t:r.length>0?r:t}import{readSyntheticSideStoryDocOriginPath as GT}from"@datalking/begonia-doc-service/v1";var XT="Detached side-story surfaces are read-only. Route mutations through the host document controller.";function rn(e){return GT(e?.document??null)!=null}function Jt(e){return e?rn(e)?XT:e.editable?null:"Document is read-only in the current document mode.":"Editor is not ready."}function it(e){return Jt(e)==null}function Es(e){if(!e)return"Editor is not ready.";let t=Jt({editable:e.editable,document:e.document});return t||(e.commentsDisplay.enabled?e.commentsDisplay.readOnly?"Comments are read-only in the current document mode.":null:"Comments are disabled for this editor.")}function dc(e,t,r=null){let o=Es(e);return o||(r?.target||r?.selectionTarget||t&&Ht(t)?null:"Place the caret in text or select text before creating a comment.")}function $T(e){return Xi([...e.activeChangeIds??[],...e.selection?.trackedChangeIds??[]])}function Rr(e,t=$T(e)){return fl({empty:e.empty,target:e.selectionTarget,activeMarks:[...e.activeMarks??[]],activeCommentIds:[...e.activeCommentIds??[]],activeChangeIds:[...t],...typeof e.text=="string"?{text:e.text}:{}},e.selectionKind,e.selectionKind==="node"&&e.selectionTarget!=null&&e.nodeSelectionTarget!=null)}import{createEditorSelectionSnapshot as YT}from"@datalking/begonia-editor-contracts";import{resolveEditorSelectionRootOffsets as tw}from"@datalking/begonia-editor-contracts";function Ms(e){let t=tw(e);return t?{...t,empty:e.empty,trackedChangeIds:e.trackedChangeIds}:null}function rw(e){let t=tw(e);return t?{kind:e.kind,...t,empty:e.empty,editable:e.editable,trackedChangeIds:[...e.trackedChangeIds],block:{...e.block},formatting:structuredClone(e.formatting)}:null}function q(e,t=!0,r=!1,o=null,n=!1){return{active:r,disabled:t,...n?{mixed:!0}:{},value:o,title:e.title,description:e.description??null,group:e.group??null}}function on(e){let t=Qr(e);return t.flowMode==="web"?t.preferredPaginatedLayoutMode:t.layoutMode}function ow(e){return e.flowMode==="paginated"||e.flowMode==="web"}function nw(e){return e.zoom?.mode==="fit-width"?"fit-width":"manual"}function iw(e,t,r,o){return e!=null||!t||r?e:`Collapsed ${o} formatting requires a live editor surface. Select text to format in headless mode.`}function sw(e,t){return e||!t}function aw(e){let t=e&&typeof e=="object"?e.nodeType:null;return t==="paragraph"||t==="heading"}function JT(e,t){return t?t.selectionKind==="node"&&aw(t.nodeSelectionTarget):aw(Ie(e??null))}function nn(e){let t=e?.catalog??tn,r=e?.commandIds;if(!r||r.length===0)return t;let o=e?.catalog??Un,n=new Map(o.map(i=>[i.id,i]));return r.map(i=>n.get(i)).filter(i=>i!=null)}function lw(e){return e.revisions}function cw(e,t){let r=Qr(e),o=e.search.activeHitId?e.search.hits.findIndex(l=>l.hitId===e.search.activeHitId):-1,n=lw(e),i=re(e.viewport),s=t?YT(t.selection,e.selection.range.revision,e.selection.range.range.anchor.story):e.toolbar.selection??e.selection,a=t?Rr(t):e.selectionInfo;return{selection:uw(s,a,n),documentMode:e.documentMode,editable:e.editable,trackChanges:e.trackChanges,flowMode:r.flowMode,layoutMode:r.layoutMode,preferredPaginatedLayoutMode:r.preferredPaginatedLayoutMode,zoomPercent:e.zoomPercent,viewport:i,totalPages:i?.totalPages??null,currentPageIndex:i?.currentPageIndex??null,currentPageNumber:i?.currentPageNumber??null,searchQuery:e.search.query,searchHitCount:e.search.hits.length,activeSearchHitId:e.search.activeHitId,activeSearchHitIndex:o,revisionCount:n.length,firstRevisionId:n[0]?.id??null,proofingDiagnosticCount:e.proofing.diagnostics.length,firstProofingDiagnosticId:e.proofing.diagnostics[0]?.diagnosticId??null}}function dw(e,t,r,o,n,i){let s=i?.selection??rw(t.selection)??{from:0,to:0,empty:!0},a=t.trackChanges.enabled,l=lw(t),c=yt({liveSelection:Ms(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:l,effectiveSelection:i}),d=t.editable?ir({editable:t.editable},o,i):"Document is read-only in the current document mode.",u=iw(d,s.empty,n,"inline"),m=iw(d,s.empty,n,"text-style"),p=t.editable?dc({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i):dc({editable:t.editable,commentsDisplay:t.commentsDisplay},o,i),f=JT(o,i),g=sw(!t.editable||!s.editable&&!f,n),v=s.formatting.mixed??{},E=sw(d!=null,n);switch(r.id){case"bold":return q(r,u!=null,s.formatting.bold,s.formatting.bold,v.bold===!0);case"italic":return q(r,u!=null,s.formatting.italic,s.formatting.italic,v.italic===!0);case"underline":return q(r,u!=null,s.formatting.underline,s.formatting.underline,v.underline===!0);case"strikethrough":return q(r,u!=null,s.formatting.strike,s.formatting.strike,v.strike===!0);case"font-size":return q(r,m!=null,s.formatting.fontSize!=null||v.fontSize===!0,s.formatting.fontSize,v.fontSize===!0);case"font-family":return q(r,m!=null,s.formatting.fontFamily!=null||v.fontFamily===!0,s.formatting.fontFamily,v.fontFamily===!0);case"text-color":return q(r,m!=null,s.formatting.color!=null||v.color===!0,s.formatting.color,v.color===!0);case"highlight-color":return q(r,m!=null,s.formatting.highlight!=null||v.highlight===!0,s.formatting.highlight,v.highlight===!0);case"paragraph":return q(r,g,s.block.kind==="paragraph",s.block.kind);case"heading-1":return q(r,g,s.block.kind==="heading"&&s.block.headingLevel===1,s.block.headingLevel);case"heading-2":return q(r,g,s.block.kind==="heading"&&s.block.headingLevel===2,s.block.headingLevel);case"heading-3":return q(r,g,s.block.kind==="heading"&&s.block.headingLevel===3,s.block.headingLevel);case"bullet-list":return q(r,g,s.block.listKind==="bullet_list",s.block.listKind);case"numbered-list":return q(r,g,s.block.listKind==="ordered_list",s.block.listKind);case"zoom":return q(r,!1,!1,t.zoomPercent);case"zoom-fit-width":return q(r,!1,nw(t)==="fit-width",nw(t));case"document-mode-editing":return q(r,!1,t.documentMode==="editing",t.documentMode);case"document-mode-suggesting":return q(r,!t.trackChanges.enabled,t.documentMode==="suggesting",t.documentMode);case"document-mode-viewing":return q(r,!1,t.documentMode==="viewing",t.documentMode);case"flow-mode-paginated":return q(r,!1,t.flowMode==="paginated",t.flowMode);case"flow-mode-web":return q(r,!1,t.flowMode==="web",t.flowMode);case"layout-mode-vertical":return q(r,!1,on(t)==="vertical",on(t));case"layout-mode-horizontal":return q(r,!ow(t),on(t)==="horizontal",on(t));case"layout-mode-book":return q(r,!ow(t),on(t)==="book",on(t));case"track-changes-display-review":return q(r,!1,t.trackChanges.mode==="review",t.trackChanges.mode);case"track-changes-display-original":return q(r,t.documentMode!=="viewing",t.trackChanges.mode==="original",t.trackChanges.mode);case"track-changes-display-final":return q(r,t.documentMode!=="viewing",t.trackChanges.mode==="final",t.trackChanges.mode);case"track-changes-display-off":return q(r,!1,t.trackChanges.mode==="off",t.trackChanges.mode);case"comments-visible":return q(r,!t.commentsDisplay.enabled,t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-hidden":return q(r,!t.commentsDisplay.enabled,!t.commentsDisplay.visible,t.commentsDisplay.visible);case"comments-show-resolved":return q(r,!t.commentsDisplay.enabled,t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-hide-resolved":return q(r,!t.commentsDisplay.enabled,!t.commentsDisplay.showResolved,t.commentsDisplay.showResolved);case"comments-visibility-all":return q(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="all",t.commentsDisplay.visibility);case"comments-visibility-internal":return q(r,!t.commentsDisplay.enabled||t.commentsDisplay.suppressInternalExternal,t.commentsDisplay.visibility==="internal",t.commentsDisplay.visibility);case"comments-visibility-external":return q(r,!t.commentsDisplay.enabled,t.commentsDisplay.visibility==="external",t.commentsDisplay.visibility);case"tracking-toggle":return q(r,!t.editable||!a,a&&t.documentMode==="suggesting",t.documentMode);case"comment-create":return q(r,p!=null,!1,t.comments.length);case"link-set":return q(r,E,s.formatting.link||v.linkHref===!0,s.formatting.linkHref,v.link===!0||v.linkHref===!0);case"link-clear":return q(r,E||!s.formatting.link&&v.linkHref!==!0,s.formatting.link||v.linkHref===!0,s.formatting.linkHref,v.link===!0||v.linkHref===!0);case"track-changes-accept-selection":case"track-changes-reject-selection":return q(r,c.length===0||!t.editable,c.length>0,c);case"review-accept-all":case"review-reject-all":return q(r,l.length===0||!t.editable,!1,l.length)}let S=(t.toolbar.commands??{})[r.id];if(S)return{...S,title:r.title,description:r.description??null,group:r.group??null};switch(r.id){case"search-set-query":return q(r,!1,t.search.query.length>0,t.search.query);case"search-next":case"search-previous":return q(r,t.search.hits.length===0,!1,t.search.activeHitId);case"search-clear":return q(r,t.search.query.length===0,!1,t.search.query);case"search-replace-active":return q(r,t.search.hits.length===0||!t.editable,!1,t.search.activeHitId);case"search-replace-all":return q(r,t.search.hits.length===0||!t.editable,!1,t.search.hits.length);case"proofing-ignore-first":case"proofing-accept-first":case"proofing-replace-first-tracked":return q(r,t.proofing.diagnostics.length===0||!t.editable,!1,t.proofing.diagnostics[0]?.diagnosticId??null);case"insert-math-inline":return q(r,!t.editable||!s.editable||f,!1,s.block.kind);case"insert-chart-block":case"insert-shape-block":return q(r,!t.editable,!1,t.selection.block.kind);case"remove-selected-ooxml":return q(r,t.advancedOoxml.selected==null||!t.editable,t.advancedOoxml.selected!=null,t.advancedOoxml.selected?.objectId??null);case"selected-math-set-plain-text":case"selected-math-toggle-display-mode":return q(r,t.advancedOoxml.selected?.family!=="math"||!t.editable,t.advancedOoxml.selected?.family==="math",t.advancedOoxml.selected?.objectId??null);case"selected-chart-set-title":case"selected-chart-add-series":case"selected-chart-add-axis":return q(r,t.advancedOoxml.selected?.family!=="chart"||!t.editable,t.advancedOoxml.selected?.family==="chart",t.advancedOoxml.selected?.objectId??null);case"selected-shape-set-text-body":case"selected-shape-set-fill":case"selected-shape-add-child":return q(r,t.advancedOoxml.selected?.family!=="shape"||!t.editable,t.advancedOoxml.selected?.family==="shape",t.advancedOoxml.selected?.objectId??null);default:return q(r)}}function uw(e,t,r){if(!e)return null;let o=Do(e,r),n=t?Ur(t,o,r):null;return xs(o,n)}function mw(e,t){let r=Qr(e),o=re(e.viewport?.value??null),n=e.selection?Do(e.selection,e.review.revisions):e.selection,i=n??e.selection,s=e.selectionInfo&&i?Ur(e.selectionInfo,i,e.review.revisions):e.selectionInfo,a=e.advancedOoxml;return{...e,flowMode:r.flowMode,layoutMode:r.layoutMode,preferredPaginatedLayoutMode:r.preferredPaginatedLayoutMode,selection:n,selectionInfo:s,viewport:e.viewport?{...e.viewport,value:o,totalPages:o?.totalPages??null,currentPageIndex:o?.currentPageIndex??null,currentPageNumber:o?.currentPageNumber??null}:e.viewport,trackChanges:t?.trackChanges??{enabled:e.review.enabled,visible:e.review.visible,mode:e.review.mode,replacements:e.review.replacementMode},viewportRequestKey:t?.viewportRequestKey??e.viewport?.requestKey??null,previewNavigationRequest:t?.previewNavigationRequest??e.viewport?.previewNavigationRequest??null,advancedOoxml:t?.advancedOoxml??a}}import{cloneEditorSelectionSnapshot as Cw,deriveEditorUiSnapshot as gk}from"@datalking/begonia-editor-contracts";function QT(e){let t=[],r=new Set;for(let o of e)typeof o!="string"||o.length===0||r.has(o)||(r.add(o),t.push(o));return t}function pw(e,t){if(t==null)return[...e];let r=new Set(Ze(t).values());return e.filter(o=>r.has(o))}function ek(e){return pw(At(e.selectionInfo?.activeCommentIds,Ze(e.comments)),e.comments)}function uc(e){let t=ek(e);return{activeCommentIds:t,activeCommentId:t.length===1?t[0]??null:null}}function mc(e){return pw(At(QT([...e.explicitActiveCommentIds??[],e.explicitActiveCommentId]),Ze(e.comments)),e.comments)}function sn(e){let t=uc(e);if(t.activeCommentIds.length>0)return t;let r=mc(e);return{activeCommentIds:r,activeCommentId:r.length===1?r[0]??null:null}}function pc(e){let t=[],r=new Set;for(let o of e)typeof o!="string"||o.length===0||r.has(o)||(r.add(o),t.push(o));return t}function tk(e){let t=pc(le(e.selectionInfo?.activeChangeIds,e.revisions));if(!e.revisions||e.revisions.length===0)return t;let r=new Set(e.revisions.map(o=>o.id));return t.filter(o=>r.has(o))}function ro(e){let t=tk(e);return{activeRevisionIds:t,activeRevisionId:t.length===1?t[0]??null:null}}function rk(e){let t=pc([...e.explicitActiveRevisionIds??[],e.explicitActiveRevisionId]),r=pc(le(t,e.revisions));if(!e.revisions||e.revisions.length===0)return r;let o=new Set(e.revisions.map(n=>n.id));return r.filter(n=>o.has(n))}function fw(e){let t=ro(e);if(t.activeRevisionIds.length>0)return t;let r=rk(e);return{activeRevisionIds:r,activeRevisionId:r.length===1?r[0]??null:null}}function Tr(e){return Object.freeze([...e])}var oo=Object.freeze({history:Tr(["undo","redo"]),view:Tr(["zoom","zoom-fit-width","flow-mode-paginated","flow-mode-web","layout-mode-vertical","layout-mode-horizontal","layout-mode-book"]),formatting:Tr(["bold","italic","underline","strikethrough","font-size","font-family","text-color","highlight-color","link-set","link-clear"]),blocks:Tr(["paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list"]),review:Tr(["document-mode-editing","document-mode-suggesting","document-mode-viewing","comment-create","comments-visible","comments-hidden","comments-show-resolved","comments-hide-resolved","comments-visibility-all","comments-visibility-internal","comments-visibility-external","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection","track-changes-display-review","track-changes-display-original","track-changes-display-final","track-changes-display-off","review-accept-all","review-reject-all"]),search:Tr(["search-set-query","search-next","search-previous","search-clear","search-replace-active","search-replace-all"]),proofing:Tr(["proofing-ignore-first","proofing-accept-first","proofing-replace-first-tracked"]),advancedOoxml:Tr(["insert-math-inline","insert-chart-block","insert-shape-block","remove-selected-ooxml","selected-math-set-plain-text","selected-math-toggle-display-mode","selected-chart-set-title","selected-chart-add-series","selected-chart-add-axis","selected-shape-set-text-body","selected-shape-set-fill","selected-shape-add-child"])}),Is=Object.freeze([{id:"history",label:"History",commandIds:oo.history},{id:"view",label:"View",commandIds:oo.view},{id:"formatting",label:"Formatting",commandIds:oo.formatting},{id:"blocks",label:"Blocks",commandIds:oo.blocks},{id:"review",label:"Review",commandIds:oo.review},{id:"search",label:"Search",commandIds:oo.search},{id:"proofing",label:"Proofing",commandIds:oo.proofing}]),n1=Object.freeze(Is.flatMap(e=>[...e.commandIds]));function ok(e){return[{id:"commands",label:"Commands",commandIds:e.map(t=>t.id)}]}function nk(e,t){if(t&&t.length>0)return t;if(e.length===0)return[];let r=new Set(Is.flatMap(n=>n.commandIds));return e.every(n=>r.has(n.id))?Is:ok(e)}function ik(e){return e?[...e]:[]}function sk(e,t){return{id:e.id,title:e.title,description:e.description??null,group:e.group??null,keywords:ik(e.keywords),slash:e.slash??!1,state:t}}function ak(e,t,r){return e.flatMap(o=>{let n=t.get(o);return n?[sk(n,r[o]??null)]:[]})}function ww(e){let t=nk(e.catalog,e.sections),r=new Map(e.catalog.map(o=>[o.id,o]));return t.map(o=>({id:o.id,label:o.label,items:ak(o.commandIds,r,e.commands)})).filter(o=>o.items.length>0)}import{normalizeCommittedDocument as dk}from"@datalking/begonia-document-model";import{createDocumentRuntimeKernel as uk}from"@datalking/begonia-document-api/v1";import{resolveRevisionProjectedDocument as mk}from"@datalking/begonia-engine";import{preserveSyntheticSideStoryDocMetadata as lk,readSyntheticSideStoryDocOriginPath as gw}from"@datalking/begonia-doc-service/v1";function ck(e,t){return e==null&&t==null?!0:e==null||t==null?!1:e.length===t.length&&e.every((r,o)=>r===t[o])}function Sw(e){let t=null;for(let r of e){let o=gw(r);if(o){if(t&&!ck(t,o))return null;t=o}}return t}function bt(e,t){return gw(e)?lk(e,t):t}function pk(e,t){let r=null,o=null,n=s=>((s!==r||!o)&&(r=s,o=dk(s)),o),i=()=>n(e());return{readDocument(){return i()},replaceDocument(){throw new Error("Browser projected review runtime is read-only.")},...t?{documentSource:{readSnapshot(){let s=t.readSnapshot();return{document:i(),revision:s.revision}},subscribeDocument(s){return t.subscribeDocument(s)}}}:{}}}function vw(e){return e??null}function hw(e,t,r){return bt(e,mk(e,t,r))}function yw(e,t,r){let o=fk(e,t,r),n=!1,i=()=>{if(n)throw new Error("Browser projected runtime bank is disposed.")};return{resolveRuntime(s="tracked"){return i(),o.projections.resolveRuntime(s)},resolveProjection(s="tracked",a={}){return i(),o.projections.resolveProjection(s,a)},resolveLayout(s="tracked",a={}){return i(),o.projections.resolveLayout(s,a)},invalidate(){i(),o.projections.invalidate()},dispose(){n||(n=!0,o.dispose())}}}function fk(e,t,r){return uk(pk(e,r),{review:{replacementMode:t}})}function bw(e){return e==="final"||e==="original"?e:null}function mr(e,t){return typeof e=="boolean"?e:t}function wk(e,t){return Yr(e)??t}function As(e,t){return e!=null?Bs(e):t===!1?"editing":"suggesting"}function an(e,t){let r=mr(t?.enabled,!0),o=mr(t?.visible,e!=="viewing"),n=e==="viewing"?o?"review":"original":"review";return{enabled:r,visible:o,mode:Xr(t?.mode)??n,replacements:$r(t?.replacements)??"paired"}}function Bw(e,t){let r=mr(t?.enabled,!0),o=mr(t?.visible,e!=="viewing"),n=mr(t?.readOnly,e==="viewing"),i=mr(t?.useInternalExternalComments,!1),s=mr(t?.suppressInternalExternal,!1),a=s?"external":wk(t?.visibility,"all");return{enabled:r,visible:o,readOnly:n,allowResolve:n?!1:mr(t?.allowResolve,!0),showResolved:mr(t?.showResolved,!1),visibility:a,useInternalExternalComments:i,suppressInternalExternal:s,enforceVisibilityPolicy:i||s}}function xw(e,t,r){if(!e)return e??null;let o=t?.suppressInternalExternal?!1:e.canViewInternalComments,n=r??e.permissionResolver,i=t?.permissionResolver??e.commentPermissionResolver;return o===e.canViewInternalComments&&n===e.permissionResolver&&i===e.commentPermissionResolver?e:{...e,canViewInternalComments:o,permissionResolver:n,commentPermissionResolver:i}}function ln(e){return e!=="viewing"}function kr(e,t){return e==="suggesting"&&t.enabled}function Ns(e,t,r,o=!1){return e.collaborative&&!o||t!=="viewing"?null:r.mode==="original"||r.mode==="final"?r.mode:null}function Me(e,t,r){return r==null?e:bt(e,hw(e,t.schema,r))}function fc(e,t,r,o,n,i){let s=e.view?.dom;s&&(s.dataset.aldDocumentMode=t,s.dataset.aldFlowMode=r,s.dataset.aldLayoutMode=o,s.dataset.aldTrackChangesMode=n.mode,s.dataset.aldTrackChangesVisible=String(n.visible),s.dataset.aldTrackChangesEnabled=String(n.enabled),s.dataset.aldCommentsVisible=String(i.visible),s.dataset.aldCommentsReadOnly=String(i.readOnly),s.dataset.aldCommentsShowResolved=String(i.showResolved),s.dataset.aldCommentsVisibility=i.visibility)}var Pw=["undo","redo","bold","italic","underline","strikethrough","paragraph","heading-1","heading-2","heading-3","bullet-list","numbered-list","link-set","link-clear","tracking-toggle","track-changes-accept-selection","track-changes-reject-selection"];function Sk(e){return kr(e.documentMode,e.trackChanges)}function vk(e){return e.collaboration.collaborative??!1}function hk(e){return{selection:Cw(e.selection),editable:e.editable,trackingEnabled:Sk(e),collaborative:vk(e),canUndo:e.canUndo,canRedo:e.canRedo,commandStates:e.commandStates}}function yk(e,t=e.toolbar.commands){return{selection:e.selection,editable:e.editable,documentMode:e.documentMode,trackChanges:e.trackChanges,collaboration:e.collaboration,canUndo:t.undo?.disabled===!1,canRedo:t.redo?.disabled===!1,commandStates:t}}function bk(e,t){return t?.commands??e.toolbar.commands}function Ds(e){return gk(hk(e))}function Bk(e,t){let r=Ds(yk(e,bk(e,t))),o=t?.catalog??[];return{...r,catalog:o,sections:ww({catalog:o,commands:r.commands})}}function cn(e,t){let r=Bk(e,t),o=e.zoom??{mode:"manual",value:e.zoomPercent,fitZoom:null,min:10,max:400,viewportMetrics:null},n=e.commentsDisplay??{enabled:!1,visible:!1,readOnly:!1,showResolved:!1,visibility:"all"},i=e.trackChanges??{enabled:!1,visible:!1,mode:"off",replacements:"paired"},s=e.collaboration??{collaborative:!1,mode:"none",reconfigurable:!1,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null},a=ro({revisions:e.revisions,selectionInfo:e.selectionInfo}),l=sn({comments:e.comments,selectionInfo:e.selectionInfo,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds}),c=e.activeRevisionId??a.activeRevisionId,d=e.activeRevisionIds??a.activeRevisionIds;return{selection:Cw(e.selection),selectionInfo:Ko(e.selectionInfo),trackingEnabled:r.trackingEnabled,collaborative:r.collaborative,commands:r.commands,editable:e.editable,documentMode:e.documentMode,flowMode:e.flowMode,layoutMode:e.layoutMode,preferredPaginatedLayoutMode:e.preferredPaginatedLayoutMode,commandCatalog:r.catalog,toolbar:r,viewport:{value:e.viewport,requestKey:e.viewportRequestKey,previewNavigationRequest:e.previewNavigationRequest,totalPages:e.viewport?.totalPages??null,currentPageIndex:e.viewport?.currentPageIndex??null,currentPageNumber:e.viewport?.currentPageNumber??null},zoom:{percent:e.zoomPercent,mode:o.mode,value:o.value,fitZoom:o.fitZoom,min:o.min,max:o.max,viewportMetrics:o.viewportMetrics},comments:{items:e.comments,permissions:e.commentPermissions,total:e.comments.length,activeCommentId:l.activeCommentId,activeCommentIds:l.activeCommentIds,enabled:n.enabled,visible:n.visible,readOnly:n.readOnly,allowResolve:n.allowResolve,showResolved:n.showResolved,visibility:n.visibility,useInternalExternalComments:n.useInternalExternalComments,suppressInternalExternal:n.suppressInternalExternal,enforceVisibilityPolicy:n.enforceVisibilityPolicy},review:{revisions:e.revisions,permissions:e.reviewPermissions,timeline:e.reviewTimeline,summary:e.reviewTimelineSummary,activeRevisionId:c,activeRevisionIds:d,enabled:i.enabled,visible:i.visible,mode:i.mode,replacementMode:i.replacements},search:{query:e.search.query,hits:e.search.hits,activeHitId:e.search.activeHitId},proofing:{diagnostics:e.proofing.diagnostics},advancedOoxml:{selected:e.advancedOoxml.selected},collaboration:{...s,connected:s.connected??!1}}}function Zn(e,t=nn(void 0)){let r=e.getState(),o=e.surface?.state,n=e.surface?.view!=null,i=e.readEffectiveSelection?.()??e.captureEffectiveSelection?.()??null;return{editor:r,context:cw(r,i),catalog:t,commands:Object.fromEntries(t.map(s=>[s.id,dw(e,r,s,o,n,i)]))}}function Rw(e,t=nn(void 0)){let r=Zn(e,t),o=e.getState();return{editor:mw(cn(o,r),{trackChanges:o.trackChanges,viewportRequestKey:o.viewportRequestKey,previewNavigationRequest:o.previewNavigationRequest,advancedOoxml:{selected:o.advancedOoxml.selected}}),context:r.context,catalog:r.catalog,commands:r.commands}}import{documentWideMutationEffect as xk}from"@datalking/begonia-editor-contracts";function wc(e){return e?e.documentService.readDocument():null}function gc(e){return Ue(e)?.view??null}function Sc(e){return Ue(e)?.automation??null}function vc(e,t){let r=Ue(e);return r?(r.replaceDocument(t,{origin:"api",intent:"replace-browser-document",effects:[xk("content")]}),!0):!1}function Ck(e){return e?"documentApi"in e?Ue(e):e:null}function no(e,t){let r=Ck(e),o=r?.view;if(!o?.state||typeof o.dispatch!="function")return!1;let n=r,i=Ge(o.state.doc,t);if(!i)return!1;let s=Z(o.state,i.from,i.to);return s?qe(n,s):!1}var Os=Symbol("captureBrowserEditorPositionAtPointInternal");import{NodeSelection as kw}from"prosemirror-state";function Pk(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Math.trunc(t),e.doc.content.size))}function Tw(e,t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(Math.trunc(t),e.doc.content.size))}function Rk(e,t,r){let o=e.view.dom,n=e.view.dom.ownerDocument,i=typeof o.getBoundingClientRect=="function"?o.getBoundingClientRect():null;if(i&&Number.isFinite(i.left)&&Number.isFinite(i.right)&&Number.isFinite(i.top)&&Number.isFinite(i.bottom)&&(t<i.left||t>i.right||r<i.top||r>i.bottom))return!1;if(!o||!n||typeof n.elementFromPoint!="function"||typeof o.contains!="function")return!0;let s=n.elementFromPoint(t,r);return!s||o.contains(s)}function Tk(e,t){let r=Z(e,t,t);if(!r)return null;try{return e.apply(e.tr.setSelection(r))}catch{return null}}function kk(e,t){try{return e.apply(e.tr.setSelection(kw.create(e.doc,t)))}catch{return null}}function Ek(e,t){let r=e.doc.nodeAt(t);return!!(r&&kw.isSelectable(r)&&(r.isLeaf||r.isAtom))}function Mk(e,t){return[Tw(e,t?.inside),Tw(e,t?.pos)].filter((o,n,i)=>o!=null&&i.indexOf(o)===n).find(o=>Ek(e,o))??null}function dn(e){let t=e.surface.view;if(!t?.state||typeof t.posAtCoords!="function"||!Rk(e.surface,e.clientX,e.clientY))return null;let r=t.posAtCoords({left:e.clientX,top:e.clientY})??null;if((e.mode??"node-or-text")!=="text-only"){let s=Mk(t.state,r);if(s!=null){let a=kk(t.state,s);if(a)return{pos:s,state:a}}}let n=Pk(t.state,r?.pos);if(n==null)return null;let i=Tk(t.state,n);return i?{pos:n,state:i}:null}function Ik(e){let t=e?.selectionTarget;if(t&&t.segments.length===1&&t.segments[0]?.range.start===t.segments[0]?.range.end){let i=t.segments[0];return{kind:"text",blockId:i.blockId,offset:i.range.start}}let r=e?.target;if(!r||typeof r!="object"||!("blockId"in r)||!("range"in r))return null;let o=typeof r.blockId=="string"?r.blockId:null,n=r.range;return!o||!n||typeof n!="object"||typeof n.start!="number"||typeof n.end!="number"||n.start!==n.end?null:{kind:"text",blockId:o,offset:n.start}}function Ak(e,t){let r=dn({surface:e.surface,clientX:t.clientX,clientY:t.clientY});if(!r?.state.selection.empty)return null;let o=Ee(r.state).target,n=o?.segments[0];return!o||o.segments.length!==1||!n||n.range.start!==n.range.end?null:{point:{kind:"text",blockId:n.blockId,offset:n.range.start},target:{kind:"text",segments:[{blockId:n.blockId,range:{start:n.range.start,end:n.range.end}}]}}}function Nk(e,t){return e&&typeof e=="object"&&"kind"in e&&e.kind==="text"?t:e}function Ew(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Ew(t);return e}function Dk(e,t){let r=e.selectionTarget?.segments[0],o=t.segments[0];return e.selectionTarget?.segments.length===1&&r&&r.blockId===o.blockId&&r.range.start===o.range.start&&r.range.end===o.range.end?e:Ew(structuredClone({...e,selectionTarget:t,target:Nk(e.target,t)}))}function io(e,t){if(!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number")return null;let r=e[Os]?.(t)??null;if(!r||!r.selection.empty)return null;let o=Ak(e,t),n=o?.point??Ik(r),i=o?.target??(n?{kind:"text",segments:[{blockId:n.blockId,range:{start:n.offset,end:n.offset}}],...r.selectionTarget?.story?{story:structuredClone(r.selectionTarget.story)}:{}}:null);if(!n||!i)return null;let s=o?Dk(r,o.target):r;return{point:n,target:i,capture:s}}function Mw(e){return{readDocument(){return wc(e)},replaceDocument(t){return vc(e,t)},readView(){return gc(e)},readAutomation(){return Sc(e)}}}function Ok(e){return{positionAtPoint(t){return io(e,t)},selectTextTarget(t){return El(e.surface,t)},selectCommentTarget(t){return no(e,t)}}}function Iw(e){return{selectionHandles:e,linkSelection:e,activeLink:e,view:e,documentMode:e,commentsDisplay:e,commentActions:e,commentFocus:e,reviewActions:e,reviewFocus:e,selectionTargets:Ok(e)}}import{createCanonicalRevisionIdsByAlias as jk,resolveCanonicalRevisionId as Vk,resolveTrackedOverlapParentIdMap as Lk}from"@datalking/begonia-engine";var js=3,Fk=[[0,0],[-js,0],[js,0],[0,-js],[0,js]];function pr(e,t){if(!e||typeof e.getAttribute!="function")return null;let r=e.getAttribute(t);return typeof r=="string"?r.trim():null}function Nw(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function zk(e,t){return!t||!e.includes(t)?[...e]:[t,...e.filter(r=>r!==t)]}function Hk(e){let t=Nw(pr(e,"data-track-change-ids"));if(t.length>0)return zk(t,pr(e,"data-track-change-preferred-target-id"));let r=pr(e,"data-track-change-id");if(r)return[r];let o=pr(e,"data-change-id");return o?[o]:[]}function qk(e){return!!(pr(e,"data-ald-comment-anchor")||pr(e,"data-ald-comment-range-start")||pr(e,"data-ald-comment-range-end"))}function Wk(e){let t=Nw(pr(e,"data-comment-ids"));if(t.length>0)return t;let r=pr(e,"data-thread-id");return r&&qk(e)?[r]:[]}function Dw(e,t){let r=e??null;for(;r;){if(r===t)return!0;r=r.parentElement??null}return!1}function Kk(e,t,r){if(!e||!Dw(e,t))return[];let o=[],n=e;for(;n;){for(let i of Hk(n)){let s=`trackedChange:${i}`;r.has(s)||(r.add(s),o.push({kind:"trackedChange",id:i}))}for(let i of Wk(n)){let s=`comment:${i}`;r.has(s)||(r.add(s),o.push({kind:"comment",id:i}))}if(n===t)break;n=n.parentElement??null}return o}function _k(e,t,r){let o=e?.ownerDocument??null;if(!o)return[];let n=(()=>{if(typeof o.elementsFromPoint!="function")return[];try{return o.elementsFromPoint(t,r)??[]}catch{return[]}})();if(n.length>0)return n;let i=(()=>{if(typeof o.elementFromPoint!="function")return null;try{return o.elementFromPoint(t,r)}catch{return null}})();return i?[i]:[]}function Uk(e,t){return e.some(r=>Dw(r,t))}function Aw(e,t){let r=Number(t);return Number.isFinite(r)?Math.max(0,Math.min(e,Math.max(0,r-1))):e}function Zk(e,t,r){let o=e.ownerDocument??null,n=o?.defaultView?.innerWidth??null,i=o?.defaultView?.innerHeight??null,s=[],a=new Set;for(let[l,c]of Fk.slice(1)){let d=Aw(t+l,n),u=Aw(r+c,i),m=`${d}:${u}`;a.has(m)||(a.add(m),s.push({x:d,y:u}))}return s}function Ow(e,t,r,o){let n=_k(e,t,r);return{stack:n,candidates:n.flatMap(i=>Kk(i,e,o))}}function Gk(e,t,r,o){let n=[];for(let i of Zk(e,t,r))n.push(...Ow(e,i.x,i.y,o).candidates);return n}function Xk(e,t){let r=le(e,t??[]),o=r.length>0?r:[...e],n=o[0]??null;return!n||o.length>1&&!tE(o,t)?null:{status:"resolved",kind:"trackedChange",trackedChangeIds:[n],commentIds:[]}}function $k(e){return e.relationship==="child"||!!e.overlapParentId||(e.members??[]).some(t=>t.relationship==="child"||!!t.overlapParentId)}function Yk(e){return[e.overlapParentId,...(e.members??[]).map(t=>t.overlapParentId)]}function Jk(e,t,r){let o=new Set;for(let n of Yk(e)){let i=Vk(n,t);i&&i!==e.id&&r.has(i)&&o.add(i)}return o.size===1?[...o][0]:null}function Qk(e){if(!e||e.length===0)return new Map;let t=jk(e),r=new Set(e.map(o=>o.id));return Lk(e.map(o=>({id:o.id,overlapParentId:$k(o)?Jk(o,t,r):null})))}function eE(e,t){let r=[e],o=new Set(r),n=e;for(;;){let i=t.get(n);if(!i||o.has(i))return r;r.push(i),o.add(i),n=i}}function tE(e,t){if(e.length<=1)return!0;if(!t||t.length===0)return!1;let r=le(e,t);if(r.length<=1)return r.length===1;let o=eE(r[0],Qk(t)),n=new Map(o.map((s,a)=>[s,a])),i=-1;for(let s of r){let a=n.get(s);if(a==null||a<=i)return!1;i=a}return!0}function hc(e){let t=e.host??null;if(!t)return[];let r=new Set,o=Ow(t,e.clientX,e.clientY,r),n=o.candidates.length>0?o.candidates:Uk(o.stack,t)?Gk(t,e.clientX,e.clientY,r):[];if(n.length===0)return[];let i=e.revisions??[],s=Ze(e.comments),a=[],l=new Set;for(let c of n){let d=c.kind==="trackedChange"?le([c.id],i)[0]??c.id:At([c.id],s)[0]??null;if(!d)continue;let u=`${c.kind}:${d}`;l.has(u)||(l.add(u),a.push({kind:c.kind,id:d}))}return a}function jw(e){let t=hc(e),r=t.filter(s=>s.kind==="trackedChange").map(s=>s.id),o=t.filter(s=>s.kind==="comment").map(s=>s.id),n=r.length+o.length;if(n===0)return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]};let i=o.length===0?Xk(r,e.revisions):null;return i||(n>1?{status:"ambiguous",kind:null,trackedChangeIds:r,commentIds:o}:{status:"resolved",kind:r.length===1?"trackedChange":"comment",trackedChangeIds:r,commentIds:o})}function rE(e){return e?{empty:e.empty,target:e.selectionTarget?Et(e.selectionTarget):null,activeMarks:[...e.activeMarks],activeCommentIds:[...e.activeCommentIds],activeChangeIds:[...e.activeChangeIds],...typeof e.text=="string"?{text:e.text}:{}}:null}function oE(e,t){let r=e.getState();return hc({host:e.surface.view.dom,clientX:t.clientX,clientY:t.clientY,revisions:r.revisions,comments:r.comments}).map(n=>({type:n.kind,id:n.id}))}function nE(e,t,r,o,n){if(e)return!1;let i=t?.selectionTarget??n;if(t?.selectionKind==="node"||r?.selectionKind==="node")return sr(t?.nodeSelectionTarget,r?.nodeSelectionTarget);let s=r?.empty?r.selectionTarget:null;return os(s??o,i)}function iE(e,t,r){for(let o of r)if(e>=o.left&&e<=o.left+o.width&&t>=o.top&&t<=o.top+o.height)return!0;return!1}function sE(e,t,r,o){if(!e||!t||t.empty)return null;let n=qn(e,t);return n.length===0?null:iE(r,o,n)}function yc(e,t){return!t||typeof t!="object"||typeof t.clientX!="number"||typeof t.clientY!="number"?[]:oE(e,t)}function Vw(e,t,r=null){let o=e.getState(),n=io(e,t),i=e.readEffectiveSelection({includeText:!0}),s=e.readPointSelection({clientX:t?.clientX??0,clientY:t?.clientY??0,includeText:!1}),a=typeof t?.clientX=="number"?t.clientX:0,l=typeof t?.clientY=="number"?t.clientY:0,c=sE(r,o.selection,a,l);return{point:{x:a,y:l},entities:yc(e,t),position:n,selection:Ko(o.selectionInfo??rE(i)),insideSelection:c??nE(o.selection.empty,i,s,n?.target??null,o.selectionInfo?.target??null)}}function Gn(e){return e!=null&&typeof e.contains=="function"}function bc(e){return typeof e=="string"?e.trim().toLowerCase():""}function aE(e){return e.ownerDocument?.defaultView?.getComputedStyle?.(e)??null}function Lw(e){let t=aE(e);if(!t)return{horizontal:"",vertical:""};let r=bc(t.overflow);return{horizontal:bc(t.overflowX)||r,vertical:bc(t.overflowY)||r}}function Vs(e){return e==="auto"||e==="scroll"||e==="overlay"}function lE(e){return{vertical:(e.scrollHeight??0)>(e.clientHeight??0),horizontal:(e.scrollWidth??0)>(e.clientWidth??0)}}function cE(e){let t=Lw(e),r=lE(e);return r.vertical&&Vs(t.vertical)||r.horizontal&&Vs(t.horizontal)}function dE(e){let t=Lw(e);return Vs(t.vertical)||Vs(t.horizontal)}function un(e){let t=Ls(e);return t?(Gn(t.parentElement)?t.parentElement:null)??t:null}function Ls(e){let t=e?.view?.dom??null;return Gn(t)?t:null}function uE(e){let t=e??null;for(;Gn(t);){if(cE(t))return t;t=t.parentElement}return null}function mE(e){let t=[],r=e??null;for(;Gn(r);)dE(r)&&t.push(r),r=r.parentElement;return t}function Xn(e){let t=e?.view?.dom??null;return Gn(t)?uE(t):null}function Fw(e){let t=Ls(e);return t?mE(t):[]}import{createVirtualPagedPreviewAncestorMutationObserver as pE,resolveVirtualPagedPreviewClippingAncestorElements as Ww}from"@datalking/begonia-layout-renderer";var zw={passive:!0};function Hw(e){if(typeof e.getState!="function")return null;let t=e.getState();return t.zoom?.value??t.zoomPercent??null}function $n(e){return typeof e.getState=="function"?e.getState():null}function Bc(e){return e?.commentsDisplay?.enabled===!0&&e.commentsDisplay.visible===!0}function xc(e){return typeof e.getViewportState=="function"?re(e.getViewportState()):null}function fE(e){let t=e;return{request(r){return typeof t?.requestAnimationFrame=="function"?{handle:t.requestAnimationFrame(r),mode:"animation-frame"}:{handle:typeof t?.setTimeout=="function"?t.setTimeout(()=>r(0),0):setTimeout(()=>r(0),0),mode:"timeout"}},cancel(r){if(r){if(r.mode==="animation-frame"&&typeof t?.cancelAnimationFrame=="function"){t.cancelAnimationFrame(r.handle);return}if(typeof t?.clearTimeout=="function"){t.clearTimeout(r.handle);return}clearTimeout(r.handle)}}}}function qw(e){return!e||typeof e!="object"?!1:"ownerDocument"in e}function wE(e){let t=e;return typeof t?.ResizeObserver=="function"?t.ResizeObserver:typeof ResizeObserver=="function"?ResizeObserver:null}function gE(e,t){let r=new Set;if(qw(e)){r.add(e);for(let o of Ww(e))r.add(o)}for(let o of t)qw(o)&&r.add(o);return[...r]}function SE(e,t,r,o){let n=new Set;r&&n.add(r);let i=Ls(t);i&&n.add(i);for(let s of Fw(t))n.add(s);if(e)for(let s of Ww(e))n.add(s);return n.size===0&&o&&n.add(o),[...n]}function vE(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Kw(e,t=null){let r=new Set,o=new Set,n=!1,i=null,s=xc(e),a=$n(e)?.flowMode??null,l=$n(e)?.layoutMode??null,c=Bc($n(e)),d=Hw(e),u=!1,m=null,p=null,f=null,g=[],v=null,E=[],R=null,S=null,P=!1,h=e.surface??null,b=()=>{P=!0,V("scroll")},x=()=>{P=!0,V("resize")},A=()=>{let ae=un(e.surface)?.ownerDocument?.defaultView??null;return fE(ae)},O=()=>{let L=i;i=null,L?.cancel()},j=L=>{if(i?.token!==L)return;i=null;let ae=[...o];if(o.clear(),n=!1,P&&(P=!1,I(),S?.sync()),r.size===0||ae.length===0)return;let je=ae.length===1?ae[0]:"mixed";for(let me of[...r])try{me({reason:je})}catch{}},_=()=>{let L=A(),ae={},je=null;i={token:ae,cancel(){L.cancel(je)}};try{je=L.request(()=>j(ae))}catch(me){throw i?.token===ae&&(i=null),me}},V=L=>{r.size!==0&&((L==="layout"||L==="zoom")&&n&&(o.delete("scroll"),n=!1),L==="scroll"&&(n=!1),o.add(L),!i&&_())},de=()=>{r.size!==0&&(o.has("scroll")||(n=!0),o.add("scroll"),!i&&_())},k=()=>{f?.removeEventListener?.("scroll",b,!0),f?.removeEventListener?.("resize",x);for(let L of g)L!==f&&L.removeEventListener?.("scroll",b,zw);R?.disconnect(),f=null,g=[],v=null,E=[],R=null},I=()=>{let L=un(e.surface),ae=L?.ownerDocument?.defaultView??null,je=Xn(e.surface),me=SE(L,e.surface,je,ae),Ke=gE(L,me);if(L===v&&ae===f&&me.length===g.length&&me.every((Ce,mt)=>Ce===g[mt])&&vE(Ke,E))return;k(),v=L,f=ae,g=me,E=Ke,f?.addEventListener?.("scroll",b,!0),f?.addEventListener?.("resize",x);for(let Ce of me)Ce!==f&&Ce.addEventListener?.("scroll",b,zw);let Tt=wE(f);if(!Tt)return;let Je=new Tt(()=>{I(),S?.sync(),V("resize")});for(let Ce of Ke)Je.observe(Ce);R=Je},F=()=>{S||(S=pE({getPreviewHost:()=>un(e.surface),getAdditionalHosts:()=>[Xn(e.surface)],onMutation(){I(),S?.sync(),V("layout")}})),S.sync()},y=()=>{let L=$n(e);if(!L)return;P=!0;let ae=(e.surface??null)!==h;h=e.surface??null;let je=L.zoom?.value??L.zoomPercent??null;je!==d&&(u=!0,d=je);let me=xc(e),Ke=s,Tt=me?.scale!==Ke?.scale,Je=!nt(Ke,me);s=me;let Ce=L.flowMode,mt=L.layoutMode,hr=Ce!==a||mt!==l;a=Ce,l=mt;let jt=Bc(L),vo=jt!==c;if(c=jt,Tt&&u){u=!1,V("zoom");return}if(u&&Ce==="web"){u=!1,V("zoom");return}if(hr||Je&&me?.totalPages!==Ke?.totalPages){let Vt=u?"zoom":"layout";u=!1,V(Vt);return}if(vo){V("layout");return}if(ae){V("layout");return}Je&&de()},B=()=>{if(P=!0,u){u=!1,V("zoom");return}V("layout")},M=()=>{if(m)return;h=e.surface??null,s=xc(e);let L=$n(e);a=L?.flowMode??null,l=L?.layoutMode??null,c=Bc(L),d=Hw(e),u=!1,I(),F(),m=typeof e.subscribe=="function"?e.subscribe(y):null,p=t?.subscribeResolvedProjection?.(B)??null},N=()=>{m?.(),p?.(),m=null,p=null,k(),S?.cleanup(),S=null,O(),o.clear(),n=!1,u=!1,P=!1};return{observe(L){return r.add(L),r.size===1&&M(),()=>{r.delete(L)&&r.size===0&&N()}}}}import{resolveProjectionCaretRect as hE}from"@datalking/begonia-page-layout";function mn(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Er(e,t){return t>0?e/t:null}function Uw(e){return Array.isArray(e)&&e.length>0?[...e]:null}function Zw(e){return typeof e=="number"&&Number.isInteger(e)?e:null}function yE(e,t){let r=Number.isFinite(e)?Math.max(0,Math.trunc(e)):0;return t==null?r:Math.min(t,r)}function Gw(e,t){let r=e.pages.findIndex(n=>n.pageNumber===t);if(r<0)return null;let o=e.pages[r]??null;return o?{pageIndex:r,page:o}:null}function bE(e){return!e||e.kind!=="text"||!Array.isArray(e.segments)||e.segments.length===0?[]:e.segments.filter(t=>!!t?.blockId)}function BE(e,t){return e.targets?.resolve?.({kind:"block",blockId:t})??null}function xE(e,t){let r=Uw(t?.path??null);if(r)return e.blocks?.ancestorOf?.(r)??null;let o=Zw(t?.anchorFrom);return o==null?null:e.blocks?.byAnchor?.(o)??null}function CE(e,t){let r=BE(e,t.blockId);if(!r)return null;let o=xE(e,r),n=Zw(o?.from??r.anchorFrom);if(n==null)return null;let i=yE(t.range.start,typeof r.text=="string"?r.text.length:null);return{absolutePos:n+i,anchorFrom:n,pathHint:Uw(o?.path??r.path??null)}}function PE(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex}function RE(e,t){return e.pageNumber===t.pageNumber&&e.region===t.region&&e.blockIndex===t.blockIndex&&e.fragmentIndex===t.fragmentIndex&&e.columnIndex===t.columnIndex&&e.lineIndex===t.lineIndex}function _w(e){let t=new Set,r=[];for(let o of e){if(!Number.isFinite(o))continue;let n=o.toFixed(3);t.has(n)||(t.add(n),r.push(o))}return r}function TE(e){return e.left+Math.min(Math.max(0,e.width/2),Math.max(0,e.width-1))}function kE(e){return e.top+Math.min(Math.max(0,e.height/2),Math.max(0,e.height-1))}function EE(e,t,r,o){if(!r||typeof e.pagination.hitTest!="function")return null;let n=_w([TE(r),o.left,r.left,r.left+Math.max(0,r.width-1)]),i=_w([kE(r),o.top+Math.max(0,o.height/2),o.top,r.top]);for(let s of i)for(let a of n){let l=e.pagination.hitTest(o.pageNumber,a,s,t);if(l&&PE(l,r))return l}return null}function ME(e,t){return e.find(r=>RE(r,t))??null}function IE(e,t,r,o,n,i){let s=Gw(e,t.pageNumber);if(!s)return null;let a=Math.max(0,Number(s.page.pageSize.width??0)),l=Math.max(0,Number(s.page.pageSize.height??0)),c=mn(t.top,l),d=mn(t.left,a),u=n??i,m=u?t.top-u.top:null,p=u?t.left-u.left:null,f=m==null?null:mn(m,u?.height??0),g=p==null?null:mn(p,u?.width??0);return{pageIndex:s.pageIndex,pageNumber:t.pageNumber,offsetTopPx:c,offsetTopRatio:Er(c,l),offsetLeftPx:d,offsetLeftRatio:Er(d,a),offsetPx:c,offsetRatio:Er(c,l),region:n?.region??t.region??i?.region??null,sectionId:n?.sectionId??t.sectionId??i?.sectionId??null,anchorFrom:r,pathHint:o,blockIdentity:n?.blockIdentity??i?.blockIdentity??null,fragmentIndex:n?.fragmentIndex??t.fragmentIndex??i?.fragmentIndex??null,columnIndex:n?.columnIndex??t.columnIndex??i?.columnIndex??null,placementOrderHint:n?.blockIndex??t.blockIndex??i?.blockIndex??null,blockOffsetTopPx:f,blockOffsetTopRatio:f==null||!u?null:Er(f,u.height),blockOffsetLeftPx:g,blockOffsetLeftRatio:g==null||!u?null:Er(g,u.width)}}function AE(e,t,r,o={}){let n=CE(e,r);if(!n)return null;let i=hE(t,n.absolutePos,{bias:"start",measureText:o.measureText,measurementEpoch:o.measurementEpoch});if(!i)return null;let s=e.pagination.lines?.(t)??[],a=ME(s,i),l=EE(e,t,a,i),c=typeof e.pagination.locateAnchor=="function"?e.pagination.locateAnchor(n.anchorFrom,t):null,d=IE(t,i,n.anchorFrom,n.pathHint,l,c);return d?{anchorPageNumber:i.pageNumber,viewportAnchor:d}:null}function Xw(e,t,r={}){let o=bE(t);if(o.length===0)return null;let n=e.pagination.project();for(let i of o){let s=AE(e,n,i,r);if(s)return s;let a=e.pagination.locateTarget({kind:"block",blockId:i.blockId},n);if(!a)continue;let l=Gw(n,a.pageNumber);if(!l)continue;let c=Math.max(0,Number(l.page.pageSize.width??0)),d=Math.max(0,Number(l.page.pageSize.height??0)),u=mn(a.top,d),m=mn(a.left,c);return{anchorPageNumber:a.pageNumber,viewportAnchor:{pageIndex:l.pageIndex,pageNumber:a.pageNumber,offsetTopPx:u,offsetTopRatio:Er(u,d),offsetLeftPx:m,offsetLeftRatio:Er(m,c),offsetPx:u,offsetRatio:Er(u,d),region:a.region??null,sectionId:a.sectionId??null,anchorFrom:a.from,pathHint:a.pathHint?[...a.pathHint]:null,blockIdentity:a.blockIdentity??null,fragmentIndex:a.fragmentIndex,columnIndex:a.columnIndex,placementOrderHint:a.blockIndex,blockOffsetTopPx:0,blockOffsetTopRatio:0,blockOffsetLeftPx:0,blockOffsetLeftRatio:0}}}return null}function Cc(e,t,r=null){let o=Xw(e.documentApi,t,Xt(r)??{});if(!o)return null;let n={anchorPageNumber:o.anchorPageNumber,viewportAnchor:o.viewportAnchor};return e.requestPreviewNavigation(n)}import{TextSelection as NE}from"prosemirror-state";var DE=1e3;function OE(e){return typeof e!="number"||!Number.isFinite(e)?DE:Math.max(0,Math.trunc(e))}function jE(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&Array.isArray(e.segments)}function VE(e){return e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"&&"id"in e&&typeof e.id=="string"}function LE(e){return e!=null&&typeof e=="object"&&"type"in e&&"nodesBetween"in e&&typeof e.nodesBetween=="function"}function $w(e){let t=Gt(e);return LE(t)?t:null}function FE(e,t){let r=e.documentApi?.trackChanges.get(t)??null;return hs(e.documentApi,$w(e.preview),r)}function zE(e,t){let r=e.documentApi?.comments.target(t)??null;if(!r)return null;let o=vs(e.documentApi,r);if(o)return o;let n=$w(e.preview);if(!n)return null;let i=Ge(n,r);if(!i)return null;try{return hl(n,NE.create(n,i.from,i.to))}catch{return null}}function HE(e,t){return jE(t)?t:VE(t)?t.type==="comment"?zE(e,t.id):t.type==="trackedChange"?FE(e,t.id):null:null}function qE(e,t){let r=e.readPendingNavigationRequest();return r?r.requestKey===t?"pending":"failed":"success"}function Pc(e){return e?.shouldContinue?.()??!0}function WE(e,t,r,o){return new Promise(n=>{let i=!1,s=()=>{},a=()=>{},l=null,c=m=>{let p=typeof m=="function"?m:()=>{};return i?(p(),()=>{}):p},d=m=>{i||(i=!0,s(),a(),l!=null&&clearTimeout(l),n(m))},u=()=>{if(!Pc(o)){d(!1);return}let m=qE(e,t);m!=="pending"&&d(m==="success")};s=c(e.subscribe(u)),i||(a=c(o?.subscribe?.(u))),i||(l=setTimeout(()=>d(!1),r),u())})}async function Yw(e,t){let r=HE(e,t.target);if(!r)return{success:!1};if(!Pc(t.continuation))return{success:!1};let o=e.requestNavigationForTextTarget(r);return o?Pc(t.continuation)?{success:await WE(e,o.requestKey,OE(t.timeoutMs),t.continuation)}:{success:!1}:{success:!1}}function Yn(e){return re(e.getViewportState())}function Jw(e,t){let r=Yn(e);return e.subscribe(()=>{let o=Yn(e);nt(r,o)||(r=o,t())})}function Qw(e,t=null){let r=null;return{getSnapshot(){return Yn(e)},subscribe(o){return Jw(e,o)},observe(o){return o(Yn(e)),Jw(e,()=>{o(Yn(e))})},observeGeometry(o){return r??=Kw(e,t),r.observe(o)},scrollIntoView(o){return Yw({documentApi:e.documentApi,preview:t,subscribe(n){return e.subscribe(()=>{n()})},readPendingNavigationRequest(){return e.getState().previewNavigationRequest??null},requestNavigationForTextTarget(n){return Cc(e,n,t)}},o)},getHost(){return un(e.surface)},getScrollContainer(){return Xn(e.surface)},entitiesAtPoint(o){return yc(e,o)},contextAtPoint(o){return Vw(e,o,t)},positionAtPoint(o){return io(e,o)},requestNavigation(o){return e.requestPreviewNavigation(o)},requestNavigationForTextTarget(o){return Cc(e,o,t)},ackNavigationRequest(o){e.ackPreviewNavigationRequest(o)}}}import{createProseMirrorLayoutAdapter as uI}from"@datalking/begonia-editor-adapters";import{NodeSelection as cI}from"prosemirror-state";function Fs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function KE(e){let t=e.selectionAnchor;return Fs(t?.resolvedSelectionPos)??Fs(t?.hit?.pos)}function _E(e){return Fs(e.hit?.pos)??Fs(e.resolvedSelectionPos)}function eg(e,t){let r=Math.min(e.from,e.to),o=Math.max(e.from,e.to),n=KE(t),i=_E(t);return n!=null&&i!=null&&i<n?{anchor:o,head:r}:{anchor:r,head:o}}import{readSyntheticSideStoryDocOriginPath as YE}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePath as rg,isDocumentNodePathIndex as JE,isIntegerPath as og}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as QE}from"@datalking/begonia-layout-renderer";import{findProjectionPage as eM,resolveProjectionPageRegionBlocks as tM}from"@datalking/begonia-page-layout";import{findProjectionPage as UE,listProjectionPageBlocks as ZE,pointHitsProjectionPlacement as GE}from"@datalking/begonia-page-layout";function tg(e,t,r,o){let n=UE(e,t);return n?ZE(n).reduce((i,s)=>GE(s,r,o)?s:i,null):null}function De(e){return ve(e)}function XE(e,t){return e.pages.find(r=>r.pageNumber===t)??null}function $E(e,t,r){let o=XE(e,t);return o?r<o.regions.bodyTop?"header":r>=o.regions.footerTop?"footer":null:null}function pn(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=$E(e,r,t.y);if(!o)return t.hit?.region??"body";if(!t.hit||t.hit.region!=="body")return o;let n=t.hit.top,i=t.hit.top+t.hit.height;return(o==="header"?Math.max(0,n-t.y):Math.max(0,t.y-i))>Math.max(12,t.hit.height/2)?o:t.hit.region}function ng(e,t,r){let o=Qn(t,r);if(!Array.isArray(o?.path)||o.path.length===0)return!1;let n=YE(e);return n?og(o.path)&&og(n)&&o.path.length>=n.length&&n.every((i,s)=>o.path?.[s]===i)&&rg(o.path.slice(n.length)):pn(t,r)==="body"&&rg(o.path)}function Qn(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=eM(e,r);if(!o)return null;let n=tg(e,r,t.x,t.y);if(!t.hit)return n;let i=tM(o,t.hit.region)[t.hit.blockIndex]??null;return n??i}function Jn(e){return!!(e&&!e.drawing&&e.type!=="image"&&e.type!=="page_break"&&e.type!=="section_break")}function fn(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function rM(e){let t=QE(e);return t?.nodeType==="ooxml_math"||t?.nodeType==="ooxml_chart"||t?.nodeType==="ooxml_shape"||t?.nodeType==="inline_ooxml_drawing"}function ig(e,t){return t.shiftKey===!0?rM(t.target)||!Jn(e):fn(t.clickCount)<=1?!0:!Jn(e)}function so(e,t){let r=Number(t),o=Number.isNaN(r)?1:Math.round(r);return Math.max(1,Math.min(o,De(e).view.state.doc.content.size))}function sg(e,t){let r=e,o=-1;for(let n of t){if(!JE(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function ao(e,t){let r=so(e,t.from),o=so(e,t.to);return r<=o?{from:r,to:o}:{from:o,to:r}}function ag(e,t){return{from:Math.min(e.from,e.to,t.from,t.to),to:Math.max(e.from,e.to,t.from,t.to)}}function oM(e){if(e.resolvedSelectionPos==null&&e.resolvedSelectionRange==null)return!1;let t=fn(e.clickCount);return e.resolvedSelectionClickCount==null?t<=1:fn(e.resolvedSelectionClickCount)===t}function Rc(e){let t=e.hit;if(!t||!oM(e))return!1;let r=e.resolvedSelectionRange;if(r){let o=Math.min(r.from,r.to),n=Math.max(r.from,r.to);return o===n?t.pos===o&&(e.resolvedSelectionPos==null||e.resolvedSelectionPos===o):t.pos>=o&&t.pos<=n&&(e.resolvedSelectionPos==null||e.resolvedSelectionPos===o)}return e.resolvedSelectionPos!=null&&t.pos===e.resolvedSelectionPos}import{readNodeAtPath as iI}from"@datalking/begonia-document-api/structure";import{NodeSelection as cS}from"prosemirror-state";function lo(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function lg(e){return Object.hasOwn(e,"anchorPageNumber")}function cg(e){return lg(e)&&e.anchorPageNumber!=null&&lo(e.anchorPageNumber)==null}function nM(e,t){let r=e==null?"paginated":e==="web"||e==="paginated"?e:null,o=t==null?"vertical":t==="vertical"||t==="horizontal"||t==="book"?t:null;return!r||!o||r==="web"&&o!=="vertical"?null:{flowMode:r,layoutMode:o}}function iM(e){return`preview-navigation:${Math.max(1,Math.trunc(e))}`}function sM(e,t){return Ne(e)??iM(t)}function aM(e){return $t(e?.anchorPageIndex??e?.currentPageIndex??null,e?.anchorPageNumber??e?.currentPageNumber??null)}function lM(e,t){return e!=null?{pageNumber:e}:t}function cM(e,t){let r=lo(e.anchorPageNumber),o=aM(t);return Object.hasOwn(e,"viewportAnchor")?Go(e.viewportAnchor??null,{...lM(r,o)}):Object.hasOwn(e,"anchorPageNumber")?null:Xo(t)}function dg(e,t){return e==null||t==null||t.pageNumber===e}function dM(e,t,r){return lg(e)?lo(e.anchorPageNumber):lo(t?.pageNumber??r?.anchorPageNumber??r?.currentPageNumber??null)}function zs(e,t){if(!e||typeof e!="object"||cg(e))return null;let r=lo(e.anchorPageNumber),o=cM(e,t.fallbackViewport);if(Object.hasOwn(e,"viewportAnchor")&&e.viewportAnchor!=null&&!o||!dg(r,o))return null;let n=dM(e,o,t.fallbackViewport);return n==null&&!o?null:{requestKey:sM(e.requestKey,t.nextToken),flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:n,viewportAnchor:o}}function be(e){if(!e||typeof e!="object"||cg(e))return null;let t=nM(e.flowMode,e.layoutMode);if(!t)return null;let r=lo(e.anchorPageNumber),o=Go(e.viewportAnchor,{pageNumber:r}),n=Ne(e.requestKey);return n==null||r==null&&!o||e.viewportAnchor!=null&&!o||!dg(r,o)?null:{requestKey:n,flowMode:t.flowMode,layoutMode:t.layoutMode,anchorPageNumber:r??lo(o?.pageNumber),viewportAnchor:o}}function Mr(e,t){let r=be(e),o=be(t);return!r||!o?r===o:r.requestKey===o.requestKey&&r.flowMode===o.flowMode&&r.layoutMode===o.layoutMode&&r.anchorPageNumber===o.anchorPageNumber&&Zo(r.viewportAnchor,o.viewportAnchor)}function ug(e,t,r){let o=be(e);return o!=null&&o.flowMode===t&&o.layoutMode===r}function mg(e,t){let r=be(e),o=Ne(t);return r!=null&&o!=null&&r.requestKey===o}function Tc(e,t){return $t(t,e).pageNumber}function uM(e,t){return qs(e)!=null||wg(t)!=null}function pg(e,t){if(!uM(e,t))return!1;let r=$t(t,e);return r.pageNumber==null&&r.pageIndex==null}function Hs(e,t){let r=Tc(e,t);return r??(typeof t=="number"&&Number.isInteger(t)&&t>=0?t+1:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):null)}function qs(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function wg(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function mM(e,t){let r=Array.isArray(e)?[...new Set(e.map(n=>qs(n)).filter(n=>n!=null))].sort((n,i)=>n-i):[],o=Array.isArray(t)?[...new Set(t.map(n=>wg(n)).filter(n=>n!=null).map(n=>n+1))].sort((n,i)=>n-i):[];return r.length>0?o.length>0&&(o.length!==r.length||o.some((n,i)=>n!==r[i]))?[]:r:o}function fg(e,t){let r=mM(e,t);return r.length===1?r[0]??null:null}function pM(e,t){let r=qs(e),o=qs(t);return r!=null&&o!=null&&r===o?r:null}function gg(e){return fg(e?.visiblePageNumbers,e?.visiblePageIndexes)??pM(e?.firstVisiblePageNumber,e?.lastVisiblePageNumber)??fg(e?.mountedPageNumbers,e?.mountedPageIndexes)??null}function kc(e){return pg(e?.anchorPageNumber,e?.anchorPageIndex)&&pg(e?.currentPageNumber,e?.currentPageIndex)}function wn(e){return Tc(e?.anchorPageNumber,e?.anchorPageIndex)??Tc(e?.currentPageNumber,e?.currentPageIndex)??(kc(e)?null:gg(e))??null}function co(e){let t=gg(e);return{anchorPageNumber:Hs(e?.anchorPageNumber,e?.anchorPageIndex)??Hs(e?.currentPageNumber,e?.currentPageIndex)??t??null,currentPageNumber:Hs(e?.currentPageNumber,e?.currentPageIndex)??Hs(e?.anchorPageNumber,e?.anchorPageIndex)??t??null}}function Ec(e){let t=wn(e);if(t!=null)return t;let r=co(e);return r.anchorPageNumber!=null&&r.currentPageNumber!=null&&r.anchorPageNumber!==r.currentPageNumber?null:r.currentPageNumber??r.anchorPageNumber??null}function ei(e,t){return e.anchorPageNumber===t.anchorPageNumber&&e.currentPageNumber===t.currentPageNumber}function Sg(e,t){if(e.flowMode!==t.flowMode||e.layoutMode!==t.layoutMode)return!1;let r=e.viewportAnchor??null,o=t.viewportAnchor??null,n=ei(co(e),co(t));return!r||!o?n&&r===o:n&&Zo(r,o)}function fM(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:Yt({...e,layoutMode:"vertical"},t)}function wM(e,t){return t.flowMode!=="web"||e.flowMode!=="web"||e.layoutMode!=="horizontal"&&e.layoutMode!=="book"?null:be({...e,layoutMode:"vertical"})}function gM(e){let t=Xo(e),r=t===e.viewportAnchor?e:{...e,viewportAnchor:t};return t!=null||wn(r)!=null?r:null}function Bt(e,t={}){let r=e?.viewport??null;if(!r)return null;let{flowMode:o,layoutMode:n}=t;if(Xo(r)==null&&kc(r))return null;let i=Yt(r,{flowMode:o,layoutMode:n})??fM(r,t);if(!i)return null;let s=gM(i);return s?o&&n?to(s,o,n)?s:null:o?_o(s,o)?s:null:n?Uo(s,n)?s:null:s:null}function xt(e,t={}){let r=be(e?.previewNavigationRequest??null)??(e?.previewNavigationRequest!=null?wM(e.previewNavigationRequest,t):null);if(!r)return null;let{flowMode:o,layoutMode:n}=t;return o&&r.flowMode!==o||n&&r.layoutMode!==n?null:r}function Ws(e,t){if(!e)return null;let r=Bt({viewport:e},t);return r?{kind:"full",viewport:r}:{kind:"page",state:co(e)}}function Ks(e){return e.kind==="full"?co(e.viewport):e.state}function vg(e,t,r={}){let o=Ws(e,r),n=Ws(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?Sg(o.viewport,n.viewport):ei(Ks(o),Ks(n))}function sK(e,t,r={}){let o=Ws(e,r),n=Ws(t,r);return!o||!n?o===n:o.kind==="full"&&n.kind==="full"?nt(o.viewport,n.viewport):ei(Ks(o),Ks(n))}function hg(e){let t=Gt(e.editor),r=e.source==null?null:e.source,o=e.explicitProjection??null,n=e.boundToEditorDocument===!0||!!(t&&(e.source===t||e.source==null&&e.explicitProjection==null)),i=n?null:r!=null?o==null?r:{source:r,projection:o}:t==null?o:null;return{sourceMatchesEditorDocument:n,lifecycleSourceIdentity:i}}function Mc(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function wK(e){let t=Mc(e.controllerNavigationMode);return e.sourceMatchesEditorDocument?{controllerNavigationMode:t,syncViewportToEditor:e.syncViewportToEditor}:{controllerNavigationMode:"ignore",syncViewportToEditor:!1}}function yg(e){return Mc(e)!=="ignore"}function gn(e){return Mc(e)==="consume"}function Sn(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function SM(e,t,r){if(!t||t.viewportAnchor!=null||Bt({viewport:t},r))return!1;let o=Ec(e),n=Ec(t);return o!=null&&o===n}function bg(e,t,r,o,n=null,i={}){if(Sn(t)!=null||!r||!gn(o))return null;let a=xt(e,i);return!a||a.requestKey===n?null:be(a)}function Bg(e,t,r,o,n={}){return Sn(t)!=null||r||!gn(o)?null:xt(e,n)?.requestKey??null}function xg(e,t,r,o,n,i=null,s={}){if(Sn(t)!=null||!r||!gn(o))return null;let l=Bt(e,s);if(!l)return null;if(tc(e?.viewportRequestKey,i))return l;let c=Bt({viewport:n??null},s);return c?vg(l,c,s)?null:l:SM(l,n??null,s)?null:l}function Cg(e,t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let r=ht(e?.zoomPercent)??100;return Math.max(.01,r/100)}function Pg(e,t,r,o,n={}){let i=Sn(t);if(i!=null)return i;if(r)return null;if(gn(o)){let a=xt(e,n);if(a?.viewportAnchor)return null;if(a?.anchorPageNumber!=null)return a.anchorPageNumber}if(!yg(o))return null;let s=Bt(e,n);return s?.viewportAnchor?null:wn(s)??wn(e?.viewport??null)}function Rg(e,t,r,o,n={}){if(Sn(t)!=null||r)return null;if(gn(o)){let s=xt(e,n);if(s)return s.viewportAnchor??null}return yg(o)?Bt(e,n)?.viewportAnchor??null:null}function Tg(e,t,r,o,n={}){if(Sn(t)!=null||!gn(o))return null;let s=xt(e,n);return s?s.requestKey:Bt(e,n)?Ne(e?.viewportRequestKey):null}function Ic(e,t){return Hn(t)??Jr(e?.flowMode)}function kg(e,t,r){let o=Ic(e,r),n=dt(e?.preferredPaginatedLayoutMode),i=e?.flowMode==="paginated"?dt(e?.layoutMode):null;return dr(dt(t)??(o==="paginated"?i??n??e?.layoutMode:e?.layoutMode),o)}import{buildTableGridModel as vM,readNodeAtPath as Ac,resolveRectAtLogicalPosition as hM}from"@datalking/begonia-document-api/structure";import{isDocumentNodePathIndex as yM}from"@datalking/begonia-document-model";import{readVirtualPagedPreviewInlineNodeTarget as bM}from"@datalking/begonia-layout-renderer";import{NodeSelection as BM}from"prosemirror-state";function Eg(e,t){let r=e,o=-1;for(let n of t){if(!yM(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function xM(e){return bM(e)}function CM(e,t,r,o,n={}){return!e.isInline||e.childCount!==0||!BM.isSelectable(e)||e.type.name!==t.nodeType||!n.ignoreObjectId&&t.objectId&&(typeof e.attrs.objectId=="string"?e.attrs.objectId:"")!==t.objectId?!1:t.fromOffset<o&&t.toOffset>r}function Nc(e,t,r,o,n={},i=0,s=[]){if(e.isText)return{positions:s,nextOffset:i+(e.text?.length??0)};if(e.childCount===0){let c=o(e),d=i+c.length;return CM(e,r,i,d,n)&&s.push(t),{positions:s,nextOffset:d}}let a=i,l=0;for(let c=0;c<e.childCount;c+=1){let d=e.child(c);a=Nc(d,t+l+1,r,o,n,a,s).nextOffset,l+=d.nodeSize}return{positions:s,nextOffset:a}}function PM(e,t,r){if(t.type!=="table"||!Array.isArray(t.path)||t.path.length===0||r.tableOriginRow==null||r.tableOriginColumn==null)return null;let o=De(e).view.state.doc,n=Ac(o,t.path);if(!n||n.type.name!=="table")return null;let i=vM(n);if(i.invalidReason)return null;let s=hM(i,r.tableOriginRow,r.tableOriginColumn);if(!s)return null;let a=i.physicalRows[s.originRow]?.find(u=>u.rect===s)??null;if(!a)return null;let l=[...t.path,s.originRow,a.childIndex],c=Ac(o,l),d=Eg(o,l);return!c||d==null?null:{node:c,nodePos:d}}function RM(e,t){if(!Array.isArray(t.path)||t.path.length===0)return null;let r=De(e).view.state.doc,o=Ac(r,t.path),n=Eg(r,t.path);return!o?.isTextblock||n==null?null:{node:o,nodePos:n}}function Dc(e,t,r){if(!t||!Array.isArray(t.path)||t.path.length===0)return null;let o=xM(r.target);if(!o)return null;let n=De(e).view.state.doc,i=se(n),s=d=>Br(d,i),a=PM(e,t,o)??RM(e,t);if(!a)return null;let l=Nc(a.node,a.nodePos,o,s).positions;if(l.length===1)return l[0];if(l.length>1||!o.objectId)return null;let c=Nc(a.node,a.nodePos,o,s,{ignoreObjectId:!0}).positions;return c.length===1?c[0]:null}import{captureProjectionViewportLogicalAnchor as TM}from"@datalking/begonia-page-layout";function Mg(e,t){return Math.max(0,Math.min(Math.max(0,t),e))}function Oc(e,t){return t>0?e/t:0}function jc(e){return e==="header"||e==="body"||e==="footer"}function kM(e,t,r){return jc(e)&&(r.hit==null||r.hit.region!==e)&&(t==null||t.region!==e)}function EM(e,t,r){return r&&(t==null||r.region===t||!jc(t))||!jc(t)?r:{region:t,sectionId:e.sectionId??null,anchorFrom:null,pathHint:null,blockIdentity:null,fragmentIndex:null,columnIndex:null,blockOffsetTopPx:null,blockOffsetTopRatio:null,blockOffsetLeftPx:null,blockOffsetLeftRatio:null}}function MM(e,t){let r=e.pages.findIndex(o=>o.pageNumber===t);return r<0?null:{pageIndex:r,page:e.pages[r]??null}}function Ig(e,t){let r=t.hit?.pageNumber??t.pageNumber,o=MM(e,r);if(!o?.page)return null;let n=Math.max(0,Number(t.frame.page.pageSize.width??t.frame.contentWidth??0)),i=Math.max(0,Number(t.frame.page.pageSize.height??t.frame.contentHeight??0)),s=Number(t.frame.contentTop??0),a=Mg(t.y-s,i),l=TM(o.page,t.x,t.y),c=pn(e,t),d=kM(c,l,t)?t.x:t.pageX,u=Mg(d,n),m=EM(o.page,c,l);return{pageIndex:o.pageIndex,pageNumber:o.page.pageNumber,offsetTopPx:a,offsetTopRatio:Oc(a,i),offsetLeftPx:u,offsetLeftRatio:Oc(u,n),offsetPx:a,offsetRatio:Oc(a,i),...m}}function Vc(e){return e.selectionAnchor?{...e,pageNumber:e.selectionAnchor.pageNumber,x:e.selectionAnchor.x,pageX:e.selectionAnchor.pageX,y:e.selectionAnchor.y,hit:e.selectionAnchor.hit,clickCount:e.selectionAnchor.clickCount??e.clickCount??1,resolvedSelectionPos:e.selectionAnchor.resolvedSelectionPos??null,resolvedSelectionRange:e.selectionAnchor.resolvedSelectionRange??null,resolvedSelectionClickCount:e.selectionAnchor.resolvedSelectionClickCount??null,selectionAnchor:null,target:e.selectionAnchor.target??null}:null}function Ag(e){return{...e,clickCount:e.clickCount??e.selectionAnchor?.clickCount??1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}function Ng(e){return{...e,clickCount:1,shiftKey:!1,resolvedSelectionPos:null,resolvedSelectionRange:null,resolvedSelectionClickCount:null,selectionAnchor:null}}import{buildTableGridModel as eI,readNodeAtPath as tI,resolveRectAtLogicalPosition as rI}from"@datalking/begonia-document-api/structure";import{isDenseArray as oI}from"@datalking/begonia-document-model/contracts";import{PREVIEW_TABLE_CELL_HORIZONTAL_PADDING as ti,PREVIEW_TABLE_CELL_VERTICAL_PADDING as _s}from"@datalking/begonia-layout-renderer";import{readNodeAtPath as AM}from"@datalking/begonia-document-api/structure";import{resolveNodeAnchorPosition as NM}from"@datalking/begonia-doc-service/v1";function Ir(e,t,r,o={}){return we(e,t,r,o)}function Lc(e,t,r,o={}){return Eo(e,t,r,o)}function Fc(e){return e+1}function Og(e,t){return Math.max(Fc(t),t+e.nodeSize-1)}function jg(e,t,r){return Ir(e,t,Og(e,t),r)}function Vg(e,t){return Number.isInteger(e)&&e>=0&&e<=t}function IM(e,t,r,o){let n=Fc(t),i=Og(e,t);for(;n<i;){let s=n+Math.floor((i-n)/2);Ir(e,t,s,o)<r?n=s+1:i=s}return n}function Dg(e,t,r,o="end",n={}){let i=jg(e,t,n);if(!Vg(r,i))return null;let s=He(e,t,r,o,n);if(s!=null)return s;let a=IM(e,t,r,n);return o==="start"?Math.max(Fc(t),a-1):a}function ri(e,t,r,o={}){let n=jg(e,t,o);if(!Vg(r,n))return null;let i=Lc(e,t,r,o);if(i!=null)return i;let s=Dg(e,t,r,"start",o),a=Dg(e,t,r,"end",o);if(s==null||a==null)return s??a;if(s===a)return s;let l=Ir(e,t,s,o),c=Ir(e,t,a,o);return r-l<=c-r?s:a}function DM(e){return e.isBlock&&e.childCount===0}function OM(e,t,r){let o=Math.max(t+1,t+e.nodeSize-1),n=Ir(e,t,o,r);return n>0?n:DM(e)?1:0}function jM(e,t,r,o=[]){let n=(i,s)=>{if(i.isTextblock||!i.firstChild?.isBlock){let a=OM(i,s,r);a>0&&o.push({node:i,from:s,flatLength:a});return}i.forEach((a,l)=>{a.isBlock&&n(a,s+l+1)})};return e.forEach((i,s)=>{i.isBlock&&n(i,t+s+1)}),o}function zc(e,t,r){let o=se(e),n=AM(e,t),i=NM(e,t);if(!n||i==null)return null;let s=jM(n,i,o),a=0,l=null;for(let d of s){let u=Math.max(0,Math.min(d.flatLength,r-a)),m=d.node.isLeaf?d.from+d.node.nodeSize:ri(d.node,d.from,u,o);if(m!=null&&(l=m),r<=a+d.flatLength)return m??l;a+=d.flatLength}let c=Math.max(0,Math.min(r,a));return l??ri(n,i,c,o)}import{resolveTableFragmentRows as VM}from"@datalking/begonia-layout-contracts";function Hc(e,t,r){return e.originRow===t&&e.originColumn===r}function Lg(e,t,r,o){let n=VM(e);if(!(n[t]??null)?.cells.some(l=>Hc(l,r,o)))return null;let s=n.find(l=>l.cells.some(c=>Hc(c,r,o)))??null,a=s?.cells.find(l=>Hc(l,r,o))??null;return!s||!a?null:{cellLayoutChildIndex:a.physicalIndex,cellLayoutIndex:s.fragmentRowIndex,sourceRowIndex:s.sourceRowIndex}}import{segmentTextGraphemes as Fg}from"@datalking/begonia-layout-contracts";function zg(e){let t=Math.round(Number(e??1));return Number.isFinite(t)?Math.max(1,t):1}function vn(e){return{from:e,to:e}}function Hg(e,t){return e<=t?{from:e,to:t}:{from:t,to:e}}function Us(e,t){return Math.max(0,Math.min(Math.round(Number(t)||0),e.content.size))}function oi(e,t,r,o,n){return Lc(e,t,Math.max(0,r),n)??o}function LM(e,t,r){return Us(e,r+Math.max(1,t.nodeSize-1))}function FM(e,t,r){return Math.max(0,Math.min(r,Math.round(Number(e)||0)-t))}function zM(e,t,r,o,n){let i=LM(e,t,r);return ri(t,r,o,n)??i}function qg(e){return/\s/u.test(e)}function HM(e){return/^[\p{L}\p{N}\p{M}\u200c\u200d'\u2018\u2019_~-]+$/u.test(e)}function qM(e){return/\p{Extended_Pictographic}/u.test(e)}function WM(e){return/^[\p{P}]+$/u.test(e)}function KM(e){return/^[\p{S}]+$/u.test(e)}function qc(e){return qg(e)?"whitespace":HM(e)?"word":qM(e)?"emoji":WM(e)?"punctuation":KM(e)?"symbol":"other"}function _M(e,t){let r=Fg(e);if(r.length===0)return null;let o=Math.max(0,Math.min(e.length,t)),n=[Math.max(0,Math.min(e.length-1,o)),Math.max(0,Math.min(e.length-1,o-1))],i=new Set;for(let s of n){let a=r.findIndex(l=>l.fromOffset<=s&&s<l.toOffset);if(!(a<0||i.has(a))&&(i.add(a),!qg(r[a]?.text??"")))return a}return null}function UM(e,t){let r=Fg(e),o=_M(e,t);if(o==null)return null;let n=r[o];if(!n)return null;let i=qc(n.text);if(i==="whitespace")return null;let s=o;for(;s>0&&qc(r[s-1]?.text??"")===i;)s-=1;let a=o+1;for(;a<r.length&&qc(r[a]?.text??"")===i;)a+=1;return{start:r[s]?.fromOffset??n.fromOffset,end:r[a-1]?.toOffset??n.toOffset}}function ZM(e,t,r,o){let n=Br(e,o).length;return n<=0?vn(r):Hg(oi(e,t,0,r,o),oi(e,t,n,r,o))}function GM(e,t,r,o,n){let i=Br(e,n),s=UM(i,r);return s?Hg(oi(e,t,s.start,o,n),oi(e,t,s.end,o,n)):vn(o)}function XM(e,t){let r=Us(e,t),o=e.resolve(r);for(let n=o.depth;n>0;n-=1){let i=o.node(n);if(i.isTextblock)return{blockNode:i,blockPos:o.before(n)}}return null}function Wg(e,t,r,o,n,i){return n>=3?ZM(e,t,o,i):n===2?GM(e,t,r,o,i):vn(o)}function Kg(e){let{doc:t,rawPos:r}=e,o=se(t),n=XM(t,r);if(!n)return vn(Us(t,r));let i=Us(t,r),s=Math.max(0,Ir(n.blockNode,n.blockPos,i,o)),a=oi(n.blockNode,n.blockPos,s,i,o);return Wg(n.blockNode,n.blockPos,s,a,zg(e.clickCount),o)}function _g(e){let{doc:t,block:r,rawPos:o}=e,n=se(t);if(!Array.isArray(r.path)||r.path.length===0)return vn(o);let i=Ve(t,r.path);if(!i?.node.isTextblock)return vn(o);let s=i.node,a=i.position,l=Br(s,n).length,c=FM(o,r.from,l),d=zM(t,s,a,c,n);return Wg(s,a,c,d,zg(e.clickCount),n)}import{readNodeAtPath as Ug,resolvePathToPosition as Zg}from"@datalking/begonia-document-api/structure";import{isDenseArray as fr}from"@datalking/begonia-document-model/contracts";import{resolveMeasuredTextOffsetAtPoint as $M,resolveProjectionTextOffsetAtPoint as YM}from"@datalking/begonia-page-layout";function Be(e){try{let t=Number(e);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function JM(e){try{let t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:null}catch{return null}}function Zs(e){if(!fr(e))return 0;let t=0;for(let r of e)t+=Be(r);return t}function Wc(e,t){if(!fr(e))return 0;let r=Math.min(e.length,Math.max(0,Math.floor(t))),o=0;for(let n=0;n<r;n+=1)o+=Be(e[n]);return o}function Gg(e,t){let r=Array.isArray(e.tableRowSourceIndexes)&&fr(e.tableRowSourceIndexes)?e.tableRowSourceIndexes:null;return Array.from({length:t},(o,n)=>JM(r?.[n])??n)}function QM(e,t){let r=Array.from({length:t},()=>0);return e.forEach(o=>{let n=0;o.forEach(i=>{let s=Math.max(1,Math.round(Be(i.attrs.colSpan)||1)),a=Be(i.attrs.width),l=a>0?a/s:0;for(let c=0;c<s;c+=1){let d=n+c;d<r.length&&(r[d]=Math.max(r[d]??0,l))}n+=s})}),r}function Xg(e,t,r){let o=Array.isArray(t.tableColumnWidths)&&fr(t.tableColumnWidths)?t.tableColumnWidths.map(s=>Be(s)):Array.isArray(e.attrs.columnWidths)&&fr(e.attrs.columnWidths)?e.attrs.columnWidths.map(s=>Be(s)):[],n=QM(e,r),i=Math.max(24,(Be(t.tableWidth)||Be(t.width)||Zs(o)||Zs(n)||r*96)/Math.max(1,r));return Array.from({length:r},(s,a)=>{let l=o[a]??0,c=n[a]??0;return Math.max(24,l||c||i)})}function $g(e,t){if(t.length===0)return 0;let r=0;for(let o=0;o<t.length;o+=1){let n=Math.max(1,Be(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function Yg(e,t){if(t.length===0)return 0;let r=0;for(let o=0;o<t.length;o+=1){let n=Math.max(1,Be(t[o])||1);if(e<r+n)return o;r+=n}return t.length-1}function Jg(e){return fr(e.tableRowHeights)?e.tableRowHeights.map(t=>Math.max(1,Be(t)||1)):[]}function Qg(e,t){if(e.isTextblock)return[...t];for(let r=0;r<e.childCount;r+=1){let o=e.child(r),n=[...t,r],i=Qg(o,n);if(i)return i}return null}function eS(e,t){let r=Ug(e,t);if(!r)return null;let o=Qg(r,t);if(o){let i=Zg(e,o);return i==null?null:Ug(e,o)?.content.size===0?i:i+1}let n=Zg(e,t);return n==null?null:n+1}function tS(e){let{block:t,cellLayout:r,height:o,hit:n,left:i,line:s,lineCount:a,lineIndex:l,measureText:c,measurementEpoch:d,top:u,width:m,x:p}=e,f=nS(oS(r),s.fromOffset),g={pageNumber:n?.pageNumber??0,sectionIndex:n?.sectionIndex??0,sectionPageNumber:n?.sectionPageNumber??0,sectionId:n?.sectionId??null,region:n?.region??"body",blockIndex:n?.blockIndex??t.index,fragmentIndex:n?.fragmentIndex??0,columnIndex:n?.columnIndex??0,lineIndex:l,lineCount:a,from:s.fromOffset,to:s.toOffset,left:i,top:u,width:m,height:o,text:s.text,logicalText:s.text,nodeType:f?.nodeType??n?.nodeType??"table_cell",align:n?.align??t.align??null,direction:n?.direction??t.direction??null,fontSize:f?.fontSize??n?.fontSize??t.fontSize??null,tabs:f?.tabs??null,inlineSpans:f?.inlineSpans??r.inlineSpans??n?.inlineSpans??null,continuesToNext:n?.continuesToNext??!1,label:s.text},v=c?$M(g,p,c,d):YM(g,p);return Math.max(s.fromOffset,Math.min(s.toOffset,v))}function rS(e,t,r){let o=e.lineHeights,n=oS(e);return t.map((i,s)=>{let a=Be(i.lineHeight);if(a>0)return a;let l=fr(o)?Be(o[s]):0;if(l>0)return l;let c=nS(n,i.fromOffset),d=Be(c?.lineHeight);return d>0?d:r})}function oS(e){let t=fr(e.segments)?e.segments:[],r=0;return t.map(o=>{let n={segment:o,fromOffset:r,toOffset:r+o.text.length};return r=n.toOffset,n})}function nS(e,t){return e.find(r=>t<r.toOffset||r.segment.text.length===0&&t===r.fromOffset)?.segment??null}function iS(e,t){if(!fr(e)||e.length===0)return{lineIndex:0,lineTop:0};let r=Be(t),o=0;for(let n=0;n<e.length;n+=1){let i=Math.max(1,Be(e[n])||1);if(r<o+i||n===e.length-1)return{lineIndex:n,lineTop:o};o+=i}return{lineIndex:0,lineTop:0}}function sS(e){return Kc(e)?.resolvedPos??null}function Kc(e){let{doc:t,block:r,x:o,y:n}=e;if(r.type!=="table"||!r.path?.length)return null;let i=tI(t,r.path);if(!i||i.type.name!=="table")return null;let s=eI(i);if(s.invalidReason||s.rows.length===0||s.width<=0)return null;let a=Jg(r),l=Gg(r,a.length);if(l.length===0)return null;let c=Xg(i,r,s.width),d=Math.max(0,o-r.left),u=Math.max(0,n-r.top),m=$g(u,a),p=l[m]??m,f=Yg(d,c),g=rI(s,p,f);if(!g)return null;let v=nI({doc:t,block:r,fragmentRowIndex:m,rowHeights:a,model:s,rect:g});if(!v)return null;let{cellLayoutChildIndex:E,cellLayoutIndex:R,cellPath:S,cellStartPos:P,rowTop:h}=v,b=Wc(c,g.originColumn),x=Zs(c.slice(g.originColumn,g.originColumn+g.colSpan)),A=r.tableCells?.[R]?.[E]??null,O=oI(A?.lineSlices)?A.lineSlices:null;if(!O||O.length===0)return{cellPath:S,cellStartPos:P,cellLeft:b,cellWidth:x,rowTop:h,lineIndex:0,lineCount:1,line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:P,lineTop:0,lineHeight:Math.max(1,Be(r.lineHeight))};let j=Math.max(0,u-h-_s),_=Math.max(1,Be(r.lineHeight)),V=rS(A,O,_),{lineIndex:de,lineTop:k}=iS(V,j),I=O[de]??null,F=Math.max(1,V[de]??_);if(!I)return{cellPath:S,cellStartPos:P,cellLeft:b,cellWidth:x,rowTop:h,lineIndex:de,lineCount:Math.max(1,O.length),line:null,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:P,lineTop:k,lineHeight:F};let y=tS({block:r,cellLayout:A,height:F,line:I,lineCount:Math.max(1,O.length),lineIndex:de,left:r.left+b+ti,top:r.top+h+_s+k,width:Math.max(0,x-ti*2),x:o,measureText:e.measureText,measurementEpoch:e.measurementEpoch});return{cellPath:S,cellStartPos:P,cellLeft:b,cellWidth:x,rowTop:h,lineIndex:de,lineCount:Math.max(1,O.length),line:I,cellText:typeof A?.text=="string"?A.text:"",resolvedPos:zc(t,S,y)??P,lineTop:k,lineHeight:F}}function nI(e){let{doc:t,block:r,fragmentRowIndex:o,rowHeights:n,model:i,rect:s}=e;if(!Array.isArray(r.path)||r.path.length===0)return null;let a=Lg(r,o,s.originRow,s.originColumn);if(!a)return null;let l=i.physicalRows[a.sourceRowIndex]?.find(u=>u.rect===s)??null;if(!l)return null;let c=[...r.path,a.sourceRowIndex,l.childIndex],d=eS(t,c);return d==null?null:{cellLayoutChildIndex:a.cellLayoutChildIndex,cellLayoutIndex:a.cellLayoutIndex,cellPath:c,cellStartPos:d,rowTop:Wc(n,a.cellLayoutIndex)}}function aS(e,t,r,o){return zc(e,t,r)??o}function _c(e){let t=sS(e);return t==null?null:Kg({doc:e.doc,rawPos:t,clickCount:e.clickCount})}function Uc(e){let t=Kc(e);if(!t)return null;let{cellPath:r,cellLeft:o,cellStartPos:n,cellText:i,cellWidth:s,line:a,lineCount:l,lineIndex:c,resolvedPos:d,rowTop:u,lineTop:m,lineHeight:p}=t,f=a?aS(e.doc,r,a.fromOffset,n):d,g=a?aS(e.doc,r,a.toOffset,d):d,v=a?.text??i,E=Math.max(1,p||Be(e.block.lineHeight)||Be(e.hit.height)||1);return{...e.hit,lineIndex:c,lineCount:l,from:Math.min(f,g),to:Math.max(f,g),left:e.block.left+o+ti,top:e.block.top+u+_s+m,width:Math.max(0,s-ti*2),height:E,text:v,label:v.trim()||e.hit.label,pos:d}}function sI(e,t,r,o){return _g({doc:De(e).view.state.doc,block:t,rawPos:r,clickCount:o})}function aI(e,t){if(t.type==="table"||Jn(t)||!Array.isArray(t.path)||t.path.length===0)return null;let r=De(e).view.state.doc,o=iI(r,t.path);return!o||!cS.isSelectable(o)?null:sg(r,t.path)}function ni(e){return hg({editor:e.editor,source:e.previewSource,explicitProjection:e.explicitProjection,boundToEditorDocument:e.boundToEditorDocument}).sourceMatchesEditorDocument}function ii(e,t){return ng(De(e).view.state.doc,t.projection,t)}function Gc(e,t){let r=Ig(t.projection,t);return r?e.requestPreviewNavigation({anchorPageNumber:r.pageNumber,viewportAnchor:r})!=null:!1}function Zc(e,t){if(t==null)return null;try{let r=cS.create(De(e).view.state.doc,t);return{from:r.from,to:r.to}}catch{return null}}function si(e){let{editor:t,event:r}=e;if(!t||!r.hit||!ni(e)||!ii(t,r))return{block:null,nodeSelectionPos:null,nodeSelectionRange:null};let o=Qn(r.projection,r);if(!ig(o,r))return{block:o,nodeSelectionPos:null,nodeSelectionRange:null};let n=Dc(t,o,r);if(n!=null)return{block:o,nodeSelectionPos:n,nodeSelectionRange:Zc(t,n)};let i=o?aI(t,o):null;return{block:o,nodeSelectionPos:i,nodeSelectionRange:Zc(t,i)}}function lI(e,t){let r=ao(e,t),o=so(e,De(e).view.state.selection.anchor);return{from:Math.min(o,r.from),to:Math.max(o,r.to)}}function Xc(e,t){let{editor:r}=e;if(!r||!t.hit||!ni(e)||!ii(r,t))return null;let o=Qn(t.projection,t);if(!o)return null;if(o.type==="table"){let n=Xt(r)??{};return _c({doc:De(r).view.state.doc,block:o,x:t.x,y:t.y,clickCount:t.clickCount,measureText:n.measureText,measurementEpoch:n.measurementEpoch})}if(t.shiftKey){let n=Zc(r,Dc(r,o,t));if(n)return n}return!Jn(o)||!t.hit?null:sI(r,o,t.hit.pos,t.clickCount)}function lS(e,t){if(t.resolvedSelectionRange)return t.resolvedSelectionRange;let r=si({...e,event:t});return r.nodeSelectionRange?r.nodeSelectionRange:Xc(e,t)}function dS(e,t){if(!t.selectionAnchor)return t.selectionAnchor??null;let r=Vc(t);if(!r)return t.selectionAnchor;let o=ai({...e,event:r});return{...t.selectionAnchor,hit:o.hit,clickCount:o.clickCount??t.selectionAnchor.clickCount??1,resolvedSelectionPos:o.resolvedSelectionPos??null,resolvedSelectionRange:o.resolvedSelectionRange??null,resolvedSelectionClickCount:o.resolvedSelectionClickCount??null,pageX:o.pageX,target:o.target??t.selectionAnchor.target??null}}function uS(e){let{editor:t,event:r}=e;if(!t||!r.hit||!ni(e)||!ii(t,r))return r.hit??null;let o=Qn(r.projection,r);if(!o||o.type!=="table")return r.hit;let n=Xt(t)??{};return Uc({doc:De(t).view.state.doc,block:o,x:r.x,y:r.y,hit:r.hit,measureText:n.measureText,measurementEpoch:n.measurementEpoch})??r.hit}function mS(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r.hit?.pos??null;let o=Xc(e,Ng(r));return o?ao(t,o).from:r.hit.pos}function Gs(e){let{editor:t,event:r}=e;if(!t)return null;let o=Vc(r),n=o?(()=>{let i=lS(e,o),s=lS(e,Ag(r));return!i||!s?null:ag(i,s)})():Xc(e,r);return n?r.shiftKey?lI(t,n):n:null}function pS(e,t){return e<=t.from?t.to:e>=t.to||Math.abs(e-t.from)>Math.abs(e-t.to)?t.from:t.to}function fS(e){let{editor:t}=e;if(!t)return null;let r=si(e);if(r.nodeSelectionPos!=null)return r.nodeSelectionPos;let o=Gs(e);return o?ao(t,o).from:null}function ai(e){let{editor:t,event:r}=e;if(!t||!r.hit)return r;let o=uS(e),n=o===r.hit?r:{...r,hit:o},i=dS(e,n),s=i===n.selectionAnchor?n:{...n,selectionAnchor:i},a=s.hit;if(!a||Rc(s))return s;let l={...e,event:s},c=fn(s.clickCount),d=si(l);if(d.nodeSelectionPos!=null)return{...s,resolvedSelectionPos:d.nodeSelectionPos,resolvedSelectionRange:null,resolvedSelectionClickCount:c,hit:{...a,pos:d.nodeSelectionPos}};let u=Gs(l);if(!u)return s;let m=ao(t,u),p=mS(l)??m.from,f=m.from===m.to;return{...s,resolvedSelectionPos:m.from,resolvedSelectionRange:m,resolvedSelectionClickCount:c,hit:{...a,pos:f?m.from:p}}}function wS(e){let{editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n,event:i}=e;if(!t||!ni(e))return!1;let s={editor:t,previewSource:r,explicitProjection:o,boundToEditorDocument:n},a=Rc(i)?i:ai(e),l=pn(a.projection,a);if(!a.hit)return l?Gc(t,a):!1;if(!ii(t,a))return Gc(t,a);let c=si({...s,event:a});if(c.nodeSelectionPos!=null){let m=De(t);return m.view.dispatch(m.view.state.tr.setSelection(cI.create(m.view.state.doc,c.nodeSelectionPos))),m.focus(),!0}let d=a.resolvedSelectionRange?ao(t,a.resolvedSelectionRange):Gs({...s,event:a});if(a.shiftKey&&d){let m=De(t),p=so(t,m.view.state.selection.anchor),f=pS(p,d),g=Z(m.view.state,p,f);return g?(m.view.dispatch(m.view.state.tr.setSelection(g)),m.focus(),!0):!1}if(d){let m=De(t),p=eg(d,a),f=Z(m.view.state,p.anchor,p.head);return f?(m.view.dispatch(m.view.state.tr.setSelection(f)),m.focus(),!0):!1}let u=a.resolvedSelectionPos??fS({...s,event:a});if(u!=null){let m=De(t),p=Z(m.view.state,so(t,u));return p?(m.view.dispatch(m.view.state.tr.setSelection(p)),m.focus(),!0):!1}return!1}var dI={resolvePositionHitEvent(e){return ai(e)},handlePositionHit(e){return wS(e)}};function Xs(){return dI}var mI=uI();function $s(e){let t=null,r=null,o=new Set,n=i=>{for(let s of[...o])s(i)};return{readLayoutAdapter(){return mI},readLayoutSource(){let i=e();return i?.view?.state.doc??i?.document??null},readDocumentSize(){return e()?.view?.state.doc.content.size??null},getResolvedProjection(){return t},getResolvedProjectionGeometryOptions(){return r},setResolvedProjection(i,s=null){t=i??null,r=s??null,n(t)},subscribeResolvedProjection(i){return o.add(i),()=>{o.delete(i)}},selection:Xs()}}function gS(e){let t=()=>Ue(e),o={...$s(t),getState(){return e.getState()},subscribe(n){return e.subscribe(n)},requestPreviewNavigation(n){return e.requestPreviewNavigation(n)},ackPreviewNavigationRequest(n){e.ackPreviewNavigationRequest(n)},setViewState(n){e.setViewState(n)},setZoomViewportMetrics(n){e.setZoomViewportMetrics(n)}};return Object.defineProperty(o,"surface",{configurable:!1,enumerable:!1,get:t}),o}var Jc=Symbol.for("@datalking/begonia-browser-sdk/browser-editor-v1-runtime"),li=new WeakMap,Qc=new WeakMap;function Yc(e,t){Object.defineProperty(e,Jc,{configurable:!0,enumerable:!1,writable:!0,value:t})}function $c(e){return!e||typeof e!="object"?null:e[Jc]??null}function SS(e){!e||typeof e!="object"||delete e[Jc]}function pI(e){return"host"in e}function ed(e,t){li.set(e,t),Yc(e,t)}function Ys(e,t,r){li.set(e,r),Qc.set(t,r),Yc(e,r),Yc(t,r)}function vS(e,t){e&&(li.delete(e),SS(e)),t&&(Qc.delete(t),SS(t))}function wr(e){if(!e)return null;if(pI(e))return Qc.get(e)??$c(e)??li.get(e.host)??$c(e.host)??null;let t=he(e);return t?li.get(t)??$c(t)??null:null}function td(e){return wr(e)?.controller??null}function hS(e){return wr(e)?.advancedOoxmlActions??null}var Q_=nn({commandIds:Pw});function fI(e){let t=e.getState();return{linkPopover:t.linkPopover,contextMenu:t.contextMenu}}function wI(e){let t=null,r=()=>{let o=fI(e);return(t==null||!Jo(t,o))&&(t=o),t};return{getSnapshot:r,subscribe(o){return e.subscribe(()=>{let n=t;n!=null&&r()!==n&&o()})}}}function gI(e,t=tn){let r=e.getState(),o=Zn(e,t);return cn(r,o)}function ci(e){let t=()=>gI(e);return{doc:e.documentApi,readState:t,subscribe(r){return e.subscribe(()=>{r()})},execute(r,o){return t().commands[r]?.disabled?ye("Command is disabled in the current document mode or selection."):tf(e,r,o)??ye(`Unsupported browser command: ${String(r)}`)}}}function hn(e){let t={controller:e,backend:Mw(e),advancedOoxmlActions:e},r=gS(e),o={session:ci(e),actor:null,documentApi:e.documentApi,readCommandSnapshot(n=tn){return Rw(e,n)},...Iw(e),browserViewport:Qw(e,r),preview:r,overlayState:wI(e),overlays:{closeLinkPopover:()=>e.closeLinkPopover(),closeContextMenu:()=>e.closeContextMenu()}};return Object.defineProperty(o,"actor",{configurable:!1,enumerable:!0,get(){return e.actor??null}}),ed(o,t),o}function uo(e){let t=hn(e),r={...t,overlays:t.overlays??{}},o=wr(t);return o&&ed(r,o),r}function yS(e){return td(e)}function Js(e){let t=hn(e),r=ks(t),o=wr(t);return o&&Ys(t,r,o),r}var SI=ci,vI=uo,hI=hn;import{errorBegoniaResult as CS,okBegoniaResult as ea,runBegoniaResult as PS}from"@datalking/begonia-result";import{errorBegoniaResult as rd,okBegoniaResult as od,toBegoniaError as bS}from"@datalking/begonia-result";function BS(e){return!!e&&typeof e=="object"&&"ok"in e}function yI(e){return{collaborative:!0,mode:"binding",reconfigurable:e,providerName:null,roomId:null,status:"disconnected",connected:null,synced:null,awarenessClientCount:null,message:"Collaboration binding attached without session metadata."}}function Qs(e,t,r){return t?{...t.getSnapshot(),mode:"session",reconfigurable:r}:e.collaborative?yI(r):{collaborative:!1,mode:"none",reconfigurable:r,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null}}async function yn(e,t,r){if(!e?.[t])return od(r);try{let o=await e[t]();return BS(o)?o:od(o??r)}catch(o){return rd(bS(o))}}async function xS(e,t){if(!t?.encodeSnapshot)return rd({code:"invalid_request",message:"Collaboration snapshot capture requires a session with encodeSnapshot()."});try{let r=await t.encodeSnapshot();return BS(r)?r:od(r??{document:e.document,documentJson:e.document.toJSON(),update:new Uint8Array,awareness:null,snapshot:t.getSnapshot()})}catch(r){return rd(bS(r))}}function RS(e){let t=async r=>{if(!e.reconfigurable)return CS({code:"invalid_request",message:"This browser controller cannot attach collaboration because it does not own surface reconfiguration."});let o=e.getCollaborationSession(),n=e.readCollaboration(),i=o===r?n:Qs(e.getSourceRuntime().surface,r,e.reconfigurable),s=await yn(r,"connect",i);if(!s.ok)return s;if(o===r&&e.getSourceRuntime().surface.collaborative)return e.emit(),ea(e.readCollaboration());let l=await PS(()=>e.createReplacementSurface(r.binding,r));if(!l.ok)return o!==r&&await yn(r,"disconnect",i),l;if(o&&o!==r){let c=await yn(o,"disconnect",n);if(!c.ok)return l.value.destroy(),await yn(r,"disconnect",i),c}return e.swapSurface(l.value,r),e.emit(),ea(e.readCollaboration())};return{attachCollaboration:t,upgradeToCollaboration:t,async detachCollaboration(r={}){if(!e.reconfigurable)return CS({code:"invalid_request",message:"This browser controller cannot detach collaboration because it does not own surface reconfiguration."});let o=e.getCollaborationSession(),n=e.getSourceRuntime().surface;if(!o&&!n.collaborative)return e.emit(),ea(e.readCollaboration());let i=await PS(()=>e.createReplacementSurface(void 0,null));if(!i.ok)return i;let s=await yn(o,"disconnect",e.readCollaboration());return s.ok?(e.swapSurface(i.value,null),r.destroySession&&await o?.destroy?.(),e.emit(),ea(e.readCollaboration())):(i.value.destroy(),s)},async saveCollaborationSnapshot(){return xS(e.getSourceRuntime().surface,e.getCollaborationSession())}}}import{hasVisibleSemanticContent as bI,isDocumentNodePathIndex as TS}from"@datalking/begonia-document-model";function BI(e){return!!e&&typeof e=="object"&&Array.isArray(e.segments)&&e.segments.length>0}function xI(e,t){let r=e;for(let o of t){if(!r||!TS(o)||o>=r.childCount)return null;r=r.child(o)}return r}function CI(e,t){if(t.length===0)return 0;let r=0,o=e;for(let n of t){if(!TS(n)||n>=o.childCount)return null;r+=1;for(let i=0;i<n;i+=1)r+=o.child(i).nodeSize;o=o.child(n)}return r}function PI(e,t){let r=e.nodeAt(t.from)??null;return!r||t.to!==t.from+r.nodeSize||!r.isLeaf||!r.isInline||!bI(r)?null:r}function nd(e){if(e.selectionKind!=="node"||!BI(e.target))return null;let t=PI(e.doc,e.selection),r=e.target.segments[0];if(!t||!r||e.target.segments.length!==1)return null;let o=Le(e.doc,r.blockId),n=o?xI(e.doc,o):null,i=o?CI(e.doc,o):null,s=i==null?null:Math.max(-1,i-1);if(!o||!n?.isBlock||s==null)return null;let a=se(e.doc),l=we(n,s,e.selection.from,a),c=Math.max(l,we(n,s,e.selection.to,a)),d=typeof e.text=="string"?e.text:"";return{id:"browser-selection",targetKind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:[...o],addressableBlockPath:[...o],addressableBlockId:r.blockId,startOffset:l,endOffset:c,segments:[{kind:"range",startPath:null,endPath:null,anchorPath:null,blockPath:[...o],addressableBlockPath:[...o],startOffset:l,endOffset:c,text:d}],text:d,source:"live",frozenAt:null}}import{createDocumentSurface as RI}from"@datalking/begonia-engine";function Ct(e){return typeof e=="boolean"?e:void 0}function kS(e,t){return e||!!t}function TI(e){return{...e}}function kI(e){return{...e,items:e.items.map(TI)}}function ES(e,t,r){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((o,n)=>r(o,t[n]))}function Qt(e){return{...e??{},links:e?.links?{...e.links,enabled:Ct(e.links.enabled)}:void 0,contextMenu:e?.contextMenu?{...e.contextMenu,enabled:Ct(e.contextMenu.enabled),includeDefaultItems:Ct(e.contextMenu.includeDefaultItems),customItems:e.contextMenu.customItems?.map(kI)}:void 0,trackChanges:e?.trackChanges?{...e.trackChanges,enabled:Ct(e.trackChanges.enabled),visible:Ct(e.trackChanges.visible),mode:Xr(e.trackChanges.mode)??void 0,replacements:$r(e.trackChanges.replacements)??void 0}:void 0,comments:e?.comments?{...e.comments,enabled:Ct(e.comments.enabled),visible:Ct(e.comments.visible),readOnly:Ct(e.comments.readOnly),allowResolve:Ct(e.comments.allowResolve),showResolved:Ct(e.comments.showResolved),visibility:Yr(e.comments.visibility)??void 0,useInternalExternalComments:Ct(e.comments.useInternalExternalComments),suppressInternalExternal:Ct(e.comments.suppressInternalExternal)}:void 0}}function EI(e,t){return e.id===t.id&&e.label===t.label&&e.action===t.action&&e.showWhen===t.showWhen&&e.enabledWhen===t.enabledWhen&&e.disabledReason===t.disabledReason&&e.tone===t.tone}function MI(e,t){return e.id===t.id&&(e.label??null)===(t.label??null)&&ES(e.items,t.items,EI)}function id(e,t){let r=Qt(e),o=Qt(t);return r.links?.enabled===o.links?.enabled&&r.links?.popoverResolver===o.links?.popoverResolver&&r.contextMenu?.enabled===o.contextMenu?.enabled&&r.contextMenu?.includeDefaultItems===o.contextMenu?.includeDefaultItems&&r.contextMenu?.menuProvider===o.contextMenu?.menuProvider&&ES(r.contextMenu?.customItems,o.contextMenu?.customItems,MI)&&r.trackChanges?.enabled===o.trackChanges?.enabled&&r.trackChanges?.visible===o.trackChanges?.visible&&r.trackChanges?.mode===o.trackChanges?.mode&&r.trackChanges?.replacements===o.trackChanges?.replacements&&r.comments?.enabled===o.comments?.enabled&&r.comments?.visible===o.comments?.visible&&r.comments?.readOnly===o.comments?.readOnly&&r.comments?.allowResolve===o.comments?.allowResolve&&r.comments?.showResolved===o.comments?.showResolved&&r.comments?.visibility===o.comments?.visibility&&r.comments?.useInternalExternalComments===o.comments?.useInternalExternalComments&&r.comments?.suppressInternalExternal===o.comments?.suppressInternalExternal&&r.comments?.permissionResolver===o.comments?.permissionResolver}function MS(e){let{actor:t,templates:r,viewSelect:o,collaborationSession:n,documentMode:i,enableEmbeddedAdvancedOoxmlEditors:s,zoomPercent:a,modules:l,permissionResolver:c,surfaceFactory:d,...u}=e;return({collaborative:m,documentStory:p,editable:f,element:g,initialContent:v,participant:E,schema:R,trackingEnabled:S})=>RI({...u,element:g??u.element,collaborative:m,documentStory:p,editable:f,initialContent:v,schema:R??u.schema,participant:E,trackingEnabled:S,features:e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:_i(e.features??[])})}function Ar(e,t){return e.eq(t)}function W(e){return{changed:!1,reason:e}}function IS(e,t,r,o=!1){let n=an(t,r.trackChanges),i=Bw(t,r.comments),s=t!=="viewing"||e.collaborative&&!o,a=it(e),l=s&&(n.mode==="original"||n.mode==="final")?{...n,mode:"review"}:n,c=!a&&!i.readOnly?{...i,readOnly:!0,allowResolve:!1}:i;return{trackChanges:l,comments:c}}function Nr(e){if(!e||typeof e!="object")return!1;let t=e.selection,r=e.selectionKind,o=e.selectionTarget;return t!=null&&typeof t=="object"&&Number.isInteger(t.from)&&Number.isInteger(t.to)&&(r==="text"||r==="node")&&"selectionTarget"in e&&(o==null||typeof o=="object")}function AS(e){let t=o=>At(typeof o=="string"?[o]:[],Ze(e.readVisibleComments()))[0]??null,r=(o,n,i={})=>e.runAndEmit(()=>{let s=e.getRuntime().documentApi.comments.create({text:o,target:structuredClone(n),actor:e.getCurrentActor()??void 0,isInternal:i.isInternal,authorId:e.getCurrentActor()?.id??null,authorName:e.getCurrentActor()?.name??null});if(s.changed&&"id"in s&&typeof s.id=="string"){let a=e.getRuntime().documentApi.comments.target(s.id);a&&no(e.getRuntime().surface,a)}return s});return{createComment(o,n={}){let i=e.commentWriteReason();if(i)return W(i);let s=e.readEffectiveSelection(),a=s?.target??Ht(e.getRuntime().surface.state);if(!a)return W("Place the caret in text or select text before creating a comment.");let l=s?nd({doc:e.getRuntime().surface.state.doc,selection:s.selection,selectionKind:s.selectionKind,target:a,text:s.text??null}):null;return r(o,l??a,n)},createCommentFromCapture(o,n,i={}){let s=e.commentWriteReason();if(s)return W(s);let a=Nr(o)?o.selectionTarget:null;if(!o?.target&&!a)return W("Capture a text selection or caret before creating a comment.");let l=Nr(o)?e.resolveSelectionCapture(o,{includeText:!0})??e.readSelectionCapture(o,{includeText:!0})??o:o,c=e.resolveCommentTargetFromCapture(o);if(!c)return W("Captured selection is no longer available after the document changed. Capture a new text selection or caret before creating a comment.");let u=(Nr(l)?nd({doc:e.getRuntime().surface.state.doc,selection:l.selection,selectionKind:l.selectionKind,target:c,text:l.text??null}):null)??c;if(Nr(l)&&l.target){let m=l.text??null;if(m!=null&&m.length>0)return r(n,u,i)}return r(n,u,i)},replyComment(o,n,i=null){let s=e.commentWriteReason();return s?W(s):e.runAndEmit(()=>e.getRuntime().documentApi.comments.reply(o,{parentEntryId:i,text:n,authorId:e.getCurrentActor()?.id??null,authorName:e.getCurrentActor()?.name??null},e.getCurrentActor()??void 0))},setCommentInternal(o,n){let i=e.commentWriteReason();return i?W(i):e.runAndEmit(()=>e.getRuntime().documentApi.comments.patch(o,{isInternal:n},e.getCurrentActor()??void 0))},resolveComment(o){if(!e.readCommentResolveState().allowResolve)return W("Comment resolution is disabled.");let n=e.commentWriteReason();return n?W(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.resolve(o,e.getCurrentActor()??void 0))},reopenComment(o){if(!e.readCommentResolveState().allowResolve)return W("Comment resolution is disabled.");let n=e.commentWriteReason();return n?W(n):e.runAndEmit(()=>e.getRuntime().documentApi.comments.reopen(o,e.getCurrentActor()??void 0))},setActiveComment(o){if(o==null)return e.setActiveCommentId(null),e.emit(),!0;let n=t(o);return n?(e.setActiveCommentId(n),e.emit(),!0):!1}}}import{normalizeHyperlinkHref as oa}from"@datalking/begonia-document-model";import{NodeSelection as NS}from"prosemirror-state";function OS(e,t){return{left:e+8,top:t+12}}function II(){return{status:"none",kind:null,trackedChangeIds:[],commentIds:[]}}function AI(e){let{selection:t}=e,{$from:r}=t,o=new Set;K(t)&&o.add(t.node.type.name);for(let n=0;n<=r.depth;n+=1)o.add(r.node(n).type.name);return[...o]}function DS(e,t){return Math.max(1,Math.min(t,e.content.size))}function NI(e,t){return Math.max(0,Math.min(t,e.content.size))}function DI(e,t){let r=Math.min(e.selection.from,e.selection.to),o=Math.max(e.selection.from,e.selection.to);return(t.segments?.length?t.segments:[t]).every(i=>r<=i.from&&o>=i.to)}function OI(e){let t=le(e.effectiveTrackedChangeIds,e.revisions);if(!e.selectionCapture||e.selectionCapture.selection.empty)return t;if(t.length===0)return[];let r=lr({from:e.selectionCapture.selection.from,to:e.selectionCapture.selection.to,trackedChangeIds:[]},e.revisions);if(r.length<=t.length)return t;let o=new Set(t),n=new Map(e.revisions.map(s=>[s.id,s]));return r.filter(s=>!o.has(s)).some(s=>{let a=n.get(s);return a?!DI(e.selectionCapture,a):!1})?r:t}function jI(e,t){let{selection:r}=e;return r.from===t.selection.from&&r.to===t.selection.to&&r.empty===t.selection.empty&&(t.selectionKind!=="node"||K(r)&&(!t.nodeSelectionTarget||sr(Ie(e),t.nodeSelectionTarget)))}function VI(e,t){if(t.selectionKind==="node"){let n=Zr(e,t.nodeSelectionTarget);if(n)return n;let i=NI(e.doc,Math.min(t.selection.from,t.selection.to)),s=e.doc.nodeAt(i);if(s&&NS.isSelectable(s))try{return e.apply(e.tr.setSelection(NS.create(e.doc,i)))}catch{}}let r=DS(e.doc,Math.min(t.selection.from,t.selection.to)),o=DS(e.doc,Math.max(t.selection.from,t.selection.to));try{let n=Z(e,r,o);return n?e.apply(e.tr.setSelection(n)):null}catch{return null}}function LI(e,t,r){return t||(!r||jI(e,r)?e:VI(e,r)??e)}function FI(e){return K(e.selection)?e.selection.node.type.name:e.selection.$from.parent.type.name}function zI(e,t){return t?[...t.activeMarks]:Ee(e).activeMarks}function HI(e,t){return t?[...t.activeCommentIds]:Ee(e).activeCommentIds}function qI(e){let t=new Set(Ee(e).activeMarks);if(!e.selection.empty)return[...t];for(let r of e.storedMarks??[])t.add(r.type.name);for(let r of e.selection.$from.marks())t.add(r.type.name);for(let r of e.selection.$from.nodeBefore?.marks??[])t.add(r.type.name);for(let r of e.selection.$from.nodeAfter?.marks??[])t.add(r.type.name);return[...t]}function WI(e){if(!e.pointSelectionCapture)return II();let t=e.surface.view?.dom;return jw({host:t,clientX:e.clientX,clientY:e.clientY,revisions:e.revisions,comments:e.comments})}function ta(e,t){try{let r=e.view.posAtDOM(t,0),o=e.view.posAtDOM(t,t.childNodes.length);if(r>=o)return!1;let n=Z(e.view.state,r,o);return n?qe(e,n):!1}catch{return!1}}function jS(e,t,r,o,n,i,s){return{host:e,href:o.getAttribute("href")??"",title:o.getAttribute("title"),target:o.getAttribute("target"),rel:o.getAttribute("rel"),tooltip:o.getAttribute("title"),element:o,clientX:n,clientY:i,isAnchorLink:(o.getAttribute("href")??"").startsWith("#"),documentMode:r,position:OS(n,i),resolution:s}}function ra(e,t,r){let o=ve(e),n=uo(e),i=r.selectionCapture??null,s=r.actionSelectionCapture??i,a=r.pointSelectionCapture??null,l=r.pointSelectionState??null,c=e.documentApi?.comments?.list?.()??e.getState?.().comments??[],d=WI({surface:o,pointSelectionCapture:a,clientX:r.clientX,clientY:r.clientY,revisions:r.revisions,comments:c}),u=[...d.trackedChangeIds],m=[...d.commentIds],p=LI(o.state,r.selectionState,i),f=l??p,g=r.selection??p.selection,v=AI(f),E=HI(p,i),R=l?qI(f):zI(p,i),S=r.reviewActionsEnabled,P=(()=>{if(!S)return[];let b=ce(r.selection?.trackedChangeIds??r.selectionTrackedChangeIds);if(r.selection?.trackedChangeIdsExplicit===!0)return OI({effectiveTrackedChangeIds:b,selectionCapture:s??i,revisions:r.revisions});let x=ce(o.listSelectionRevisionIds?.());return lr({from:g.from,to:g.to,trackedChangeIds:b.length>0?b:x},r.revisions)})(),h=a&&P.length===0&&d.status==="resolved"&&u.length>0?[...u]:P;return{host:n,trigger:"contextmenu",selectedText:g.empty?"":ge(p.doc,o.schema,g),hasSelection:!g.empty,selectionStart:g.from,selectionEnd:g.to,isInTable:v.some(b=>b==="table"||b==="table_row"||b==="table_cell"),isInList:v.some(b=>b==="bullet_list"||b==="ordered_list"||b==="list_item"),isTrackedChange:h.length>0,trackedChangeIds:[...h],hasAmbiguousPointReviewTarget:a!=null&&d.status==="ambiguous",pointReviewTrackedChangeIds:u,pointReviewCommentIds:m,documentMode:t,currentNodeType:FI(f),activeCommentIds:E,activeMarks:R,selectionCapture:i,actionSelectionCapture:s,pointSelectionCapture:a,isEditable:it(o),pos:l?l.selection.from:g.from,clientX:r.clientX,clientY:r.clientY,position:OS(r.clientX,r.clientY)}}function VS(e){let t=()=>e.reviewWriteReason()==null,r=l=>ir({editable:t()},e.getRuntime().surface.state,l??null),o=l=>{if(!l)return null;let c=e.readSelectionCapture(l,{includeText:!0});return c&&r(c)==null?c:null},n=l=>{let c=e.readEffectiveSelection();return r(c)!=null?!1:rt(e.getRuntime().surface,c,l)},i=(l,c,d={})=>{let u=o(l);return u?rt(e.getRuntime().surface,u,c,d):!1},s=(l,c,d={})=>i(e.resolveSelectionHandle(l,{includeText:!0}),c,d),a=l=>{let c=e.getLinkPopover();if(!c||!t())return!1;let d=e.getLinkPopoverSelectionCapture();if(d){let u=o(d);return u?.selection.formatting.link?rt(e.getRuntime().surface,u,l,{restoreSelection:!1}):(e.setLinkPopover(null),!1)}return ta(e.getRuntime().surface,c.element)?l(e.getRuntime().surface):(e.setLinkPopover(null),!1)};return{search(l,c={}){let d=l.trim();e.setSearchQuery(d),e.setSearchOptions(c);let u=d?e.getPresentationReadApi().search.query(d,c):[];return e.setActiveSearchHitId(u[0]?.hitId??null),e.emit(),u},nextSearchHit(){let l=e.getSearchQuery(),c=l?e.getPresentationReadApi().search.next(l,e.getActiveSearchHitId(),e.getSearchOptions()):null;return e.setActiveSearchHitId(c?.hitId??e.getActiveSearchHitId()),e.emit(),c},previousSearchHit(){let l=e.getSearchQuery(),c=l?e.getPresentationReadApi().search.previous(l,e.getActiveSearchHitId(),e.getSearchOptions()):null;return e.setActiveSearchHitId(c?.hitId??e.getActiveSearchHitId()),e.emit(),c},clearSearch(){e.setSearchQuery(""),e.setSearchOptions({}),e.setActiveSearchHitId(null),e.emit()},replaceSearchHit(l,c){let d=e.reviewWriteReason();return d?W(d):e.runAndEmit(()=>e.getWritableRuntimeApi().search.replace(e.getSearchQuery(),l,c,e.getSearchOptions()))},replaceAllSearchHits(l){let c=e.reviewWriteReason();return c?W(c):e.runAndEmit(()=>e.getWritableRuntimeApi().search.replaceAll(e.getSearchQuery(),l,e.getSearchOptions()))},ignoreProofingDiagnostic(l){let c=e.reviewWriteReason();return c?W(c):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.ignore(l))},acceptProofingSuggestion(l){let c=e.reviewWriteReason();return c?W(c):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.acceptSuggestion(l))},replaceProofingDiagnosticTracked(l,c){let d=e.reviewWriteReason();return d?W(d):e.runAndEmit(()=>e.getWritableRuntimeApi().proofing.replaceTracked(l,c,e.getRuntime().surface.participant,{source:"browser-proofing"}))},setLink(l,c=null){let d=oa(l);if(!t()||!d)return!1;let u=n(p=>p.setLink(d,c)),m=e.getLinkPopover();return u&&m&&e.setLinkPopover({...m,href:d,title:c}),e.emit(),u},setLinkFromCapture(l,c,d=null,u={}){let m=oa(c);if(!t()||!m)return!1;let p=i(l,g=>g.setLink(m,d),u),f=e.getLinkPopover();return p&&f&&e.setLinkPopover({...f,href:m,title:d}),e.emit(),p},setLinkFromHandle(l,c,d=null,u={}){let m=oa(c);if(!t()||!m)return!1;let p=s(l,g=>g.setLink(m,d),u),f=e.getLinkPopover();return p&&f&&e.setLinkPopover({...f,href:m,title:d}),e.emit(),p},clearLink(){if(!t())return!1;let l=n(c=>c.clearLink());return l&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),l},clearLinkFromCapture(l,c={}){if(!t())return!1;let d=i(l,u=>u.clearLink(),c);return d&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),d},clearLinkFromHandle(l,c={}){if(!t())return!1;let d=s(l,u=>u.clearLink(),c);return d&&e.getLinkPopover()&&e.setLinkPopover(null),e.emit(),d},updateActiveLink(l,c=null){let d=e.getLinkPopover(),u=oa(l);if(!d||!t()||!u)return!1;let m=a(p=>p.setLink(u,c));return m&&e.setLinkPopover({...d,href:u,title:c}),e.emit(),m},clearActiveLink(){return!e.getLinkPopover()||!t()?!1:a(c=>c.clearLink())?(e.closeLinkPopover(),!0):(e.emit(),!1)}}}import{preservedSelectionPluginKey as rA}from"@datalking/begonia-engine";function Dr(e,t={},r="paired"){return Ee(e.state,t,{reviewReplacementMode:r})}function KI(e){return e!=null}function LS(e){return[e.comments?.target(e.commentId),e.comments?.targetSnapshot?.(e.commentId),e.fallbackTarget].filter(KI)}function _I(e){return LS(e)[0]??null}function di(e){for(let t of LS(e)){let r=e.resolve(t);if(r!=null)return{target:t,resolution:r}}return null}function UI(e){return e.hasSemanticSelection?e.captureSelectionIsRanged?!e.semanticSelectionIsCollapsed:e.semanticSelectionIsCollapsed:!1}function ZI(e){return e.hasUniqueCommentId&&(e.captureSelectionIsRanged||e.captureSelectionIsCollapsed||!e.hasCaptureSelection)}function FS(e){let t=[];return UI(e)&&t.push("semantic-selection"),ZI(e)&&t.push("comment-target"),e.hasAmbiguousCommentIds||(e.captureSelectionIsCollapsed?t.push("collapsed-absolute"):e.captureSelectionIsRanged&&t.push("ranged-absolute")),t}function GI(e){return e.length===1?e[0]:null}function XI(e,t){return of(e?.activeCommentIds,t)}function ui(e){return!!(e&&e.from===e.to)}function $I(e,t){return e.from===t.from&&e.to===t.to}function na(e){return Math.max(e.to-e.from,0)}function YI(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.targetKind;return t==="range"||t==="anchor"||t==="comment"}function JI(e){return YI(e?.target)?e.target:null}function QI(e){return{get state(){return e.state},view:e}}function eA(e){let t=e.surface.view;if(!t?.state||typeof t.dispatch!="function")return!1;let r=[e.captureSelection?.from,t.state.selection.from,t.state.selection.to].filter(o=>Number.isInteger(o));for(let o of new Set(r)){let n=Z(t.state,o,o);if(n&&qe(e.surface,n))return!0}return!1}function tA(e){let t=e.collapsedSemanticSelection.from,r=e.activeCommentIds.map(a=>di({comments:e.comments,commentId:a,fallbackTarget:null,resolve:l=>Ge(e.doc,l)})).filter(a=>a!=null&&a.resolution.from<a.resolution.to&&a.resolution.from<=t&&t<a.resolution.to).sort((a,l)=>na(a.resolution)-na(l.resolution));if(r.length===0)return null;let[o,...n]=r,i=na(o.resolution);return n.filter(a=>na(a.resolution)===i).every(a=>$I(a.resolution,o.resolution))?o.target:null}function mi(e){let t=e.capture?.selection??null,r=t!=null&&t.from===t.to,o=t!=null&&t.from!==t.to,n=XI(e.capture,e.comments),i=GI(n),s=e.surface.view;if(!s?.state||typeof s.dispatch!="function")return!1;if(e.capture?.selectionKind==="node"){let f=cr(QI(s),e.capture);if(f)return qe(e.surface,f)}let a=e.capture?cs(s.state,{selectionTarget:e.capture.selectionTarget??null,segmentTexts:e.capture.segmentTexts??null,text:e.capture.text??void 0})??Ae(s.state.doc,e.capture.selectionTarget??null,e.capture.text??null,{strict:!0}):null,c=(i?di({comments:e.comments,commentId:i,fallbackTarget:JI(e.capture),resolve:f=>Ge(s.state.doc,f)}):null)?.resolution??null;if(r&&t!=null&&Number.isInteger(t.from)&&t.from>=1&&t.from<=s.state.doc.content.size&&t&&i&&(!a||ui(a)&&a.from!==t.from)){let f=Z(s.state,t.from,t.to);if(f&&qe(e.surface,f))return!0}let m=FS({captureSelectionIsCollapsed:r,captureSelectionIsRanged:o,hasCaptureSelection:t!=null,hasSemanticSelection:a!=null,semanticSelectionIsCollapsed:ui(a),hasUniqueCommentId:i!=null,hasAmbiguousCommentIds:n.length>1});for(let f of m){if(f==="semantic-selection"&&a){let g=Z(s.state,a.from,a.to);if(!g)continue;if(qe(e.surface,g))return!0;continue}if(f==="comment-target"&&i){let g=c?Z(s.state,c.from,c.to):null;if(g&&qe(e.surface,g))return!0;continue}if((f==="collapsed-absolute"||f==="ranged-absolute")&&t){if(f==="ranged-absolute"&&n.length>0&&(!a||ui(a)))continue;let g=Z(s.state,t.from,t.to);if(!g)continue;try{if(qe(e.surface,g))return!0}catch{continue}}}let p=n.length>1&&a&&ui(a)?tA({activeCommentIds:n,comments:e.comments,collapsedSemanticSelection:a,doc:s.state.doc}):null;return p&&no(e.surface,p)?!0:o&&n.length>0&&(!a||ui(a))?eA({captureSelection:t,surface:e.surface}):!1}function zS(e){let t=()=>{let h=e.readEffectiveSelection(),{surface:b,documentApi:x,replacementMode:A}=e.getRuntime(),O=b.describeSelection(),j=Dr(b,{},A);return h?{effectiveSelection:h,liveSelection:O,revisionIds:yt({liveSelection:O,liveSelectionInfo:j,revisions:x.review.list(),effectiveSelection:h})}:{effectiveSelection:null,liveSelection:O,revisionIds:lr(O,x.review.list())}},r=h=>h.revisionIds.length===1&&(h.effectiveSelection?.selection.empty??h.liveSelection.empty),o=(h,b,x=null)=>e.runAndEmit(()=>{let A=h==="accept"?e.getRuntime().documentApi.review.accept(b,e.getCurrentActor()??void 0):e.getRuntime().documentApi.review.reject(b,e.getCurrentActor()??void 0);return A.changed&&x?.(),A}),n=h=>mi({capture:h,surface:e.getRuntime().surface,comments:e.getRuntime().documentApi.comments}),i=(h,b)=>{let x=e.readEffectiveSelection();return o(h,[b],()=>n(x))},s=h=>{let{surface:b}=e.getRuntime();return typeof b.listSelectionRevisionIds!="function"||ar(h,b.listSelectionRevisionIds())},a=(h,b)=>({changed:h,revisionIds:[...b],activityId:null,activityIds:[],decisions:[],activities:[]}),l=()=>e.getRuntime().documentApi.review.decisionActivity({sort:"asc"}),c=()=>new Set(l().map(h=>h.activityId)),d=(h,b,x)=>{let A=l().filter(j=>!x.has(j.activityId));if(A.length===0)return a(h,b);let O=A.map(j=>({activityId:j.activityId,revisionId:j.revisionId,decision:j.decision,relatedKinds:[...j.relatedKinds],memberCount:j.memberCount,memberRevisionIds:[...new Set(j.record.members.map(_=>_.revisionId))],memberEntryIds:[...j.memberEntryIds],createdAt:j.updatedAt??null,authorId:j.authorId??null,authorName:j.authorName??null,revisionAuthorId:j.revisionAuthorId??null,revisionAuthorName:j.revisionAuthorName??null,revisionCreatedAt:j.revisionCreatedAt??null}));return{changed:h,revisionIds:[...new Set([...b,...A.map(j=>j.revisionId)])],activityId:A[0]?.activityId??null,activityIds:A.map(j=>j.activityId),decisions:O,activities:A}},u=h=>rt(e.getRuntime().surface,e.readEffectiveSelection(),h),m=h=>{let b=h.effectiveSelection,x=h.liveSelection,A=e.getRuntime().surface,O=A.view;if(!b||b.selection.empty||b.activeCommentIds.length>0||x.empty||!O?.state||typeof O.dispatch!="function")return!1;let j=Z(O.state,Math.min(x.from,x.to),Math.min(x.from,x.to));return j?qe(A,j):!1},p=h=>{n(h.effectiveSelection),m(h)},f=()=>{let{surface:h}=e.getRuntime(),b=h.view;!b?.state||typeof b.dispatch!="function"||b.dispatch(b.state.tr.setMeta(rA,{preservedSelection:null}))},g=(h,b,x,A)=>{let{revisionIds:O}=b;if(r(b)){let V=O[0];return V?i(h,V):W("No tracked changes overlap the current selection.")}if(O.length===0)return W("No tracked changes overlap the current selection.");let j=c();return(x&&s(O)?u(x):!1)?(A(),d(!0,O,j)):o(h,O,A)},v=()=>e.getPresentationReadApi().review.list(),E=h=>le(typeof h=="string"?[h]:[],v())[0]??null,R=h=>{e.setActiveRevisionIds(h),e.emit()},S=()=>{e.setActiveRevisionIds([]),e.emit()},P=h=>{let b=v(),x=oc(b,e.getActiveRevisionId(),h);return x?(R([x]),x):null};return{acceptRevision(h){let b=e.reviewWriteReason();if(b)return W(b);let x=e.readEffectiveSelection();return o("accept",[h],()=>n(x))},rejectRevision(h){let b=e.reviewWriteReason();if(b)return W(b);let x=e.readEffectiveSelection();return o("reject",[h],()=>n(x))},acceptSelection(){let h=e.reviewWriteReason();if(h)return W(h);let b=t();return g("accept",b,x=>typeof x.acceptSelectionRevisions=="function"?x.acceptSelectionRevisions():!1,()=>p(b))},rejectSelection(){let h=e.reviewWriteReason();if(h)return W(h);let b=t();return g("reject",b,x=>typeof x.rejectSelectionRevisions=="function"?x.rejectSelectionRevisions():!1,()=>{e.clearPreservedRangeSelection(),p(b),f()})},acceptAll(){let h=e.reviewWriteReason();if(h)return W(h);let b=e.readEffectiveSelection();return o("accept",void 0,()=>n(b))},rejectAll(){let h=e.reviewWriteReason();if(h)return W(h);let b=e.readEffectiveSelection();return o("reject",void 0,()=>n(b))},setActiveRevision(h){if(h==null)return S(),!0;let b=E(h);return b?(R([b]),!0):!1},nextActiveRevision(){return P("next")},previousActiveRevision(){return P("previous")}}}function HS(e){return{...RS(e),...AS(e),...zS(e),...VS(e)}}function oA(e){return{id:e.id,name:e.name,role:"reviewer"}}function sd(e,t,r,o){return xw(e===void 0?oA(t):e,r,o??void 0)}function mo(e,t,r,o){return sd(e,t.participant,r,o)}import{createDefaultViewportFitControllerState as pA}from"@datalking/begonia-layout-renderer/core";function ia(e,t="paired"){return{sourceRuntime:null,activeRuntime:null,canonicalDocument:e,projectionKind:"none",projectedRuntimeBank:null,replacementMode:t,collaborativeProjection:null}}function po(e){return e.projectionKind==="inline"}function nA(e){return e.projectionKind==="collaborative"}function ad(e,t,r=t.replacementMode){return{...e,sourceRuntime:t,activeRuntime:nA(e)&&e.activeRuntime?e.activeRuntime:t,replacementMode:r,canonicalDocument:po(e)?e.canonicalDocument:t.surface.document}}function bn(e){if(!e.sourceRuntime||po(e))return e;let t=e.sourceRuntime.surface.document;return ld(e,t)}function ld(e,t){return t===e.canonicalDocument?e:{...e,canonicalDocument:t}}function pi(e,t,r=e.replacementMode){return e.projectedRuntimeBank===t&&e.replacementMode===r?e:{...e,projectedRuntimeBank:t,replacementMode:r}}function qS(e){return e.sourceRuntime?{...e,activeRuntime:e.sourceRuntime,projectionKind:"inline",collaborativeProjection:null}:e}function WS(e,t){return{...e,activeRuntime:t.runtime,projectionKind:"collaborative",collaborativeProjection:t}}function fi(e){return{...e,activeRuntime:e.sourceRuntime,projectionKind:"none",collaborativeProjection:null}}function KS(e){return{...e,sourceRuntime:null,activeRuntime:null,projectedRuntimeBank:null,collaborativeProjection:null,projectionKind:"none"}}function cd(e,t){let r=zs(t,{flowMode:e.flowMode,layoutMode:e.layoutMode,fallbackViewport:re(e.viewport),nextToken:e.nextPreviewNavigationRequestToken});return r?Mr(e.previewNavigationRequest,r)?{nextState:e,request:be(e.previewNavigationRequest),changed:!1}:{nextState:{...e,previewNavigationRequest:r,nextPreviewNavigationRequestToken:e.nextPreviewNavigationRequestToken+1},request:be(r),changed:!0}:{nextState:e,request:null,changed:!1}}function dd(e,t){return!e.previewNavigationRequest||t!=null&&!mg(e.previewNavigationRequest,t)?e:{...e,previewNavigationRequest:null}}function wi(e,t){return Object.hasOwn(e,t)&&e[t]!==void 0}function iA(e,t){return t||(e.flowMode==="paginated"?e.layoutMode:e.preferredPaginatedLayoutMode)}function _S(e,t,r){return!e||!to(e,t,r)||rc(e,t,r)?null:e}function sA(e,t,r,o,n){if(!r)return{viewport:e,ignoredIncompatibleViewport:!1};let i=Yt(t.viewport??null,{flowMode:o,layoutMode:n});if(!i)return{viewport:null,ignoredIncompatibleViewport:!1};let s=_S(i,o,n);return{viewport:s??e,ignoredIncompatibleViewport:s==null}}function aA(e){if(e.hasViewportRequestKey){if(e.hasViewport){if(e.ignoredIncompatibleViewport)return e.currentViewportState!=null?e.state.viewportRequestKey:null;if(e.normalizedViewportState==null)return null}return e.currentViewportState!=null||e.normalizedViewportState!=null?e.requestedViewportRequestKey:null}return e.hasViewport?e.normalizedViewportState==null?null:nt(e.currentViewportState,e.normalizedViewportState)?e.state.viewportRequestKey:null:e.normalizedViewportState!=null?e.requestedViewportRequestKey:e.state.viewport!=null?null:e.requestedViewportRequestKey}function lA(e){return e.previewNavigationRequest?e.appliedViewportRequestKey&&e.nextViewportRequestKey!=null&&!Ps(e.currentViewportRequestKey,e.nextViewportRequestKey)?!0:e.hasViewport&&e.normalizedViewportState!=null&&!nt(e.currentViewportState,e.normalizedViewportState):!1}function cA(e){return be(e)}function dA(e){return re(e)}function uA(e){return e.request?{anchorPageNumber:e.request.anchorPageNumber,viewportAnchor:e.request.viewportAnchor}:e.viewport?{}:null}function mA(e){if(!e.modesChanged||e.normalizedViewportState!=null)return null;let t=uA({request:e.previousPreviewNavigationRequest,viewport:e.previousViewportState});return t?zs(t,{flowMode:e.nextFlowMode,layoutMode:e.nextLayoutMode,fallbackViewport:e.previousViewportState,nextToken:e.state.nextPreviewNavigationRequestToken}):null}function ud(e,t,r){let o=wi(t,"flowMode"),n=wi(t,"layoutMode"),i=wi(t,"zoomPercent"),s=wi(t,"viewport"),a=wi(t,"viewportRequestKey"),l=o?Hn(t.flowMode):null,c=n?dt(t.layoutMode):null,d=a?Ne(t.viewportRequestKey):e.viewportRequestKey,u=l??e.flowMode,m=iA(e,c),p=dr(m,u),f=cA(e.previewNavigationRequest),g=dA(e.viewport),v=_S(g,u,p),{viewport:E,ignoredIncompatibleViewport:R}=sA(v,t,s,u,p),S=aA({state:e,requestedViewportRequestKey:d,hasViewportRequestKey:a,hasViewport:s,currentViewportState:v,normalizedViewportState:E,ignoredIncompatibleViewport:R}),P=i?ht(t.zoomPercent)??r:r,h=u!==e.flowMode||p!==e.layoutMode,b=ug(e.previewNavigationRequest,u,p)?be(e.previewNavigationRequest):null,x=lA({previewNavigationRequest:b,currentViewportRequestKey:e.viewportRequestKey,hasViewport:s,currentViewportState:v,normalizedViewportState:E,appliedViewportRequestKey:a&&(!s||!R&&E!=null),nextViewportRequestKey:S})?null:b,A=x??mA({state:e,nextFlowMode:u,nextLayoutMode:p,normalizedViewportState:E,previousPreviewNavigationRequest:f,previousViewportState:g,modesChanged:h}),j=x==null&&A!=null?e.nextPreviewNavigationRequestToken+1:e.nextPreviewNavigationRequestToken,_=e.previewNavigationRequest!=null&&f==null,V=m!==e.preferredPaginatedLayoutMode,de=!nt(e.viewport,E),k=!Ps(e.viewportRequestKey,S),I=_||!Mr(e.previewNavigationRequest,A);return!h&&!V&&!de&&!k&&!I&&!(P!==r)?{nextState:e,nextZoomPercent:P,changed:!1,modesChanged:!1}:{nextState:{...e,flowMode:u,layoutMode:p,preferredPaginatedLayoutMode:m,viewport:E,viewportRequestKey:S,previewNavigationRequest:A,nextPreviewNavigationRequestToken:j},nextZoomPercent:P,changed:!0,modesChanged:h}}function md(e,t,r=t){return{flowMode:e,layoutMode:t,preferredPaginatedLayoutMode:r,viewport:null,viewportRequestKey:null,previewNavigationRequest:null,nextPreviewNavigationRequestToken:1}}function US(e,t,r,o,n,i,s,a,l,c,d){return{resolvedModules:e,listeners:new Set,reconfigurable:t,allowSelectionInViewMode:r,actorInput:o,currentActor:n,documentMode:i,readModel:ia(c),viewportSession:md(s,a,l),searchQuery:"",activeSearchHitId:null,searchOptions:{},activeCommentId:null,activeRevisionId:null,activeRevisionIds:[],normalizeOverlayState:null,linkPopover:null,contextMenu:null,preservedRangeSelection:null,collaborationSession:d,unsubscribeCollaborationSession:null,viewportFitState:pA()}}function X(e){if(!e.readModel.activeRuntime)throw new Error("Browser editor runtime is not mounted.");return e.readModel.activeRuntime}function xe(e){if(!e.readModel.sourceRuntime)throw new Error("Browser editor source runtime is not mounted.");return e.readModel.sourceRuntime}function fA(e){return!!(e.previous&&e.previous.from!==e.previous.to&&(!e.current||e.current.from===e.current.to))}function gr(e,t,r=!0){let o=(r&&e.readState(),e.context.preservedRangeSelection);t()&&e.runBatchedEmit(()=>{e.clearEphemeralOverlays(),e.applySurfaceDisplayState(),r&&o&&(e.context.preservedRangeSelection=o),e.readState(),r&&fA({current:e.context.preservedRangeSelection,previous:o})&&(e.context.preservedRangeSelection=o,e.readState()),e.emit()})}function pd(e,t){return{...e??{},...t}}function sa(e,t){return{...e??{},...t}}function ZS(e){return{setModules(t){gr(e,()=>(e.context.resolvedModules=Qt(t),e.context.currentActor=mo(e.context.actorInput,e.getSurface(),e.context.resolvedModules.comments,e.permissionResolver),!0))},setDocumentMode(t){let r=Bs(t);gr(e,()=>e.context.documentMode===r?!1:(e.context.documentMode=r,!0))},setTrackChangesDisplayMode(t){let r=kf(t);gr(e,()=>e.context.resolvedModules.trackChanges?.mode===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{mode:r}),!0))},setTrackChangesReplacementMode(t){let r=Ef(t);gr(e,()=>e.context.resolvedModules.trackChanges?.replacements===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{replacements:r}),!0))},setTrackChangesVisible(t){let r=zn(t,"trackChanges.visible");gr(e,()=>e.context.resolvedModules.trackChanges?.visible===r?!1:(e.context.resolvedModules.trackChanges=pd(e.context.resolvedModules.trackChanges,{visible:r}),!0))},setCommentsVisible(t){let r=zn(t,"comments.visible");gr(e,()=>e.context.resolvedModules.comments?.visible===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{visible:r}),!0),!1)},setCommentsReadOnly(t){let r=zn(t,"comments.readOnly");gr(e,()=>e.context.resolvedModules.comments?.readOnly===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{readOnly:r}),!0),!1)},setCommentsShowResolved(t){let r=zn(t,"comments.showResolved");gr(e,()=>e.context.resolvedModules.comments?.showResolved===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{showResolved:r}),!0),!1)},setCommentsVisibility(t){let r=Mf(t);gr(e,()=>e.context.resolvedModules.comments?.visibility===r?!1:(e.context.resolvedModules.comments=sa(e.context.resolvedModules.comments,{visibility:r}),!0),!1)}}}function fd(e){return e==null?e:structuredClone(e)}function aa(e){return e&&{...e,groups:e.groups?[...e.groups]:e.groups}}function GS(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function XS(e){return{...e,zoomPercent:Object.hasOwn(e,"zoomPercent")&&e.zoomPercent!==void 0?ht(e.zoomPercent)??void 0:e.zoomPercent,viewportRequestKey:Object.hasOwn(e,"viewportRequestKey")&&e.viewportRequestKey!==void 0?Ne(e.viewportRequestKey):e.viewportRequestKey}}function wA(e){return e!=null&&typeof e=="object"&&"kind"in e&&e.kind==="text"&&"segments"in e&&Array.isArray(e.segments)}function $S(e){if(!e.captureTarget||!wA(e.captureTarget))return e.resolvedTarget??null;if(e.captureStillTracked&&e.resolvedTarget)return e.resolvedTarget;if(e.originalTargetText!=null&&typeof e.captureText=="string"&&e.originalTargetText===e.captureText){let t=e.resolvedText?.length??-1;if((e.resolvedTarget||e.captureStillTracked)&&e.originalTargetText.length>=t)return e.captureTarget}return e.originalTargetText!=null&&e.resolvedText!=null?e.resolvedTarget??e.captureTarget:e.resolvedTarget??null}function la(e){return"documentService"in e?{documentApi:e.documentApi,documentService:e.documentService}:{documentApi:e.documentApi,documentService:e.service}}function gA(e){return{projectedMode:e.projectedMode,projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,presentationReadRuntime:e.presentationReadRuntime,canonicalReviewRuntime:e.canonicalReviewRuntime,writableRuntime:e.writableRuntime}}function YS(e){let t=bw(e.trackChangesMode),r=vw(e.projectedRuntimeBank),o=la(e.presentationRuntime),n=la(e.writableRuntime??e.presentationRuntime),i=t&&r?la(r.resolveRuntime(t)):o,s=t&&r?la(r.resolveRuntime("tracked")):n;return gA({projectedMode:t,projectedRuntimeBank:r,canonicalDocument:e.canonicalDocument??null,presentationReadRuntime:i,canonicalReviewRuntime:s,writableRuntime:n})}function SA(e){let t=e.activeRuntime??e.sourceRuntime;if(!t)throw new Error("Browser editor presentation runtime is not mounted.");return t}function vA(e){let t=e.sourceRuntime??e.activeRuntime;if(!t)throw new Error("Browser editor writable runtime is not mounted.");return t}function Or(e,t){return YS({presentationRuntime:SA(e),writableRuntime:vA(e),projectedRuntimeBank:e.projectedRuntimeBank,canonicalDocument:e.canonicalDocument,trackChangesMode:t})}import{readViewportFitState as hA,resolveViewportFitZoomPercent as yA,updateViewportFitMetrics as bA,updateViewportFitMode as BA,updateViewportFitWidthOptions as xA}from"@datalking/begonia-layout-renderer/core";function ca(e,t){return hA(e.viewportFitState,{zoomPercent:t,flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function JS(e){return yA(e.viewportFitState,{flowMode:e.viewportSession.flowMode,layoutMode:e.viewportSession.layoutMode})}function wd(e,t){let r=BA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function QS(e,t){let r=xA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function ev(e,t){let r=bA(e.viewportFitState,t);return r===e.viewportFitState?!1:(e.viewportFitState=r,!0)}function tv({context:e,emit:t,getEmissionVersion:r,applySurfaceDisplayState:o}){let n=()=>ur(xe(e).documentApi.preferences.get()),i=l=>{let c=xe(e),d=ur(c.documentApi.preferences.get());return l===d?!1:(c.documentApi.preferences.set({zoomPercent:l}),!0)},s=()=>{let l=JS(e);return l==null?!1:i(l)},a=l=>{r()===l&&t()};return{getFlowMode(){return e.viewportSession.flowMode},getLayoutMode(){return e.viewportSession.layoutMode},getZoomPercent:n,getZoomState(){return ca(e,n())},getViewportState(){return re(e.viewportSession.viewport)},requestPreviewNavigation(l){let c=cd(e.viewportSession,l);return c.request?(e.viewportSession=c.nextState,c.changed&&t(),c.request):null},ackPreviewNavigationRequest(l){let c=dd(e.viewportSession,l);c!==e.viewportSession&&(e.viewportSession=c,t())},setViewState(l){if(!l||typeof l!="object")return;let c=xe(e),d=ur(c.documentApi.preferences.get()),u=XS(l),m=Object.hasOwn(u,"zoomPercent")&&u.zoomPercent!==void 0?wd(e,"manual"):!1,p=ud(e.viewportSession,u,d);if(!p.changed&&!m)return;e.viewportSession=p.nextState,p.modesChanged&&o();let f=r();p.nextZoomPercent!==d&&c.documentApi.preferences.set({zoomPercent:p.nextZoomPercent}),a(f)},setZoomMode(l){if(!wd(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setFitWidthOptions(l){if(!QS(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)},setZoomViewportMetrics(l){if(!ev(e,l))return;let c=r();e.viewportFitState.mode==="fit-width"&&s(),a(c)}}}import{DELETION_MARK_NAME as pD,describeSurfaceSelection as fD,INSERTION_MARK_NAME as wD}from"@datalking/begonia-engine";import{NodeSelection as gD}from"prosemirror-state";import{documentWideMutationEffect as SD}from"@datalking/begonia-editor-contracts";import{cloneSelectionTextRange as dD}from"@datalking/begonia-document-api/core";import{cloneSelectionTextRange as CA}from"@datalking/begonia-document-api/core";import{resolveRevisionProjectedDocument as PA}from"@datalking/begonia-engine";import{collectDocumentNodesIncludingSyntheticSideStories as RA,readSyntheticSideStoryDocOriginPath as TA}from"@datalking/begonia-doc-service/v1";import{formatAddressableBlockIdWithLogicalId as kA,parseAddressableBlockId as EA}from"@datalking/begonia-doc-service/structure";var rv=new WeakMap,ov=new WeakMap;function MA(e){let t=rv.get(e);if(t)return t;let r=RA({schema:e.type.schema,readDocument:()=>e},{include:(o,n)=>o.type.name==="doc"&&n.length>0,map:(o,n)=>({doc:o,path:[...n]})});return rv.set(e,r),r}function IA(e,t){if(!t)return e;let r=ov.get(e)??{},o=r[t];if(o)return o;let n=PA(e,e.type.schema,t);return ov.set(e,{...r,[t]:n}),n}function AA(e,t,r){if(!e||!t||e.eq(t))return null;let o=TA(e);if(o)return o;let n=MA(IA(t,r)).filter(i=>i.doc.eq(e));return n.length===1?n[0].path:null}function er(e){let t=AA(e.projectedDocument,e.canonicalDocument,e.projectedMode);if(!t)return e.blockId;let r=EA(e.blockId);return!r||r.path.some(o=>o<0)?e.blockId:kA(r.blockType,[...t,...r.path],r.logicalId)}function nv(e){if(!e.target)return e.target;let t=e.target.segments.map(o=>({blockId:er({blockId:o.blockId,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),range:CA(o.range)}));return t.some((o,n)=>o.blockId!==e.target?.segments[n]?.blockId)?{kind:"text",segments:t,...e.target.story?{story:structuredClone(e.target.story)}:{}}:e.target}import{readSyntheticSideStoryDocContext as DA}from"@datalking/begonia-doc-service/v1";import{isDocumentNodePathIndex as OA,semanticNodeText as jA}from"@datalking/begonia-document-model";import{isAddressableTextHiddenLeaf as NA}from"@datalking/begonia-document-model";function tr(e){return e.isText?e.text?.length??0:!e.isLeaf||NA(e)?0:1}var VA="\uFFFC";function iv(e){if(e.isText)return e.text??"";if(e.childCount===0){if(tr(e)===0)return"";let o=jA(e);return o.length===1?o:VA}let t=[],r=!0;return e.forEach(o=>{o.isBlock&&!r&&t.push(`
7
- `),t.push(iv(o)),r=!1}),t.join("")}function da(e,t){let r=Le(e,t);if(!r)return null;let o=e;for(let n of r){if(!OA(n)||n>=o.childCount)return null;o=o.child(n)}return o.isBlock?{node:o,path:r}:null}function Pt(e,t){let r=da(e,t);return r?iv(r.node):null}function jr(e){let t=Sw([e.currentDocument,e.expectedProjectedDocument]);return t?DA({schema:e.schema,port:{replaceDocument(){}},readDocument(){return e.expectedProjectedDocument}},t)?.doc??null:e.expectedProjectedDocument}import{isAddressableTextHiddenLeaf as FA,isDocumentNodePathIndex as zA}from"@datalking/begonia-document-model";import{readReviewLedger as LA}from"@datalking/begonia-engine";function gd(e){return e.join(".")}function sv(e,t,r){return e.isInline?!wt(e,t,!r):r}function Sd(e,t){if(e.marks.some(o=>pp(o.type.name,t)&&(o.attrs.blockAttrsBefore!=null||o.attrs.blockAttrsAfter!=null)))return!0;let r=!1;return e.forEach(o=>{!r&&Sd(o,t)&&(r=!0)}),r}function av(e,t){let r=t==="final"?"delete":"insert";return new Set(LA(e).filter(o=>o.entryType==="revision"&&o.kind===r&&o.target?.blockPath.length).map(o=>gd(o.target.blockPath)))}function gi(e){let t=av(e,"final"),r=av(e,"original"),o=new Map,n=(i,s,a,l)=>{let c=sv(i,"final",a),d=sv(i,"original",l);if(i.isText||i.isLeaf){let p=tr(i)>0;return{contentFinal:c&&p,contentOriginal:d&&p}}let u=!1,m=!1;if(i.forEach((p,f,g)=>{let v=n(p,[...s,g],c,d);u||=v.contentFinal,m||=v.contentOriginal}),i.isBlock){let p=gd(s);o.set(p,{final:!(t.has(p)&&!u&&!Sd(i,"final")),original:!(r.has(p)&&!m&&!Sd(i,"original"))})}return{contentFinal:u,contentOriginal:m}};return n(e,[],!0,!0),{isBlockPresent(i,s){return o.get(gd(i))?.[s]??!0}}}var cv=Object.freeze({blockSeparator:`
8
- `});function dv(e,t){let r=Le(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!zA(i)||i>=o.childCount)return null;n+=1;for(let s=0;s<i;s+=1)n+=o.child(s).nodeSize;o=o.child(i)}return o.isBlock?{document:e,node:o,path:r,position:n}:null}function lv(e,t,r){return e.isInline?!wt(e,t,!r):r}function HA(e){return e.isText?e.text?.length??0:!e.isLeaf||FA(e)?0:tr(e)}function fo(e,t,r,o,n,i){let s=t+1;if(r<=s)return 0;let a=0,l=!1,c=(u,m,p,f)=>{let g=0,v=!0,E=!1;for(let R=0;R<u.childCount;R+=1){if(l)return;let S=u.child(R),P=m+g,h=[...f,R],b=!S.isBlock||i.isBlockPresent(h,o);if(S.isBlock&&!v)if(r>=P+1)a+=p&&b&&E?1:0;else{l=!0;return}d(S,P,p&&b,h),g+=S.nodeSize,S.isBlock&&(E||=p&&b),v=!1}},d=(u,m,p,f)=>{if(l)return;let g=lv(u,o,p);if(u.isText){let v=u.text?.length??0,E=m+v;r>=E?a+=g?v:0:(a+=g?Math.max(0,r-m):0,l=!0);return}if(u.isLeaf){r>=m+u.nodeSize?a+=g?HA(u):0:l=!0;return}c(u,m+1,g,f)};return c(e,s,lv(e,o,!0)&&i.isBlockPresent(n,o),n),a}function vd(e,t,r,o,n,i,s){let a=t+1,l=Math.max(a,t+e.nodeSize-1),c=fo(e,t,l,n,i,s);if(!Number.isInteger(r)||r<0||r>c)return null;let d=a,u=l;for(;d<u;){let p=d+Math.floor((u-d)/2);fo(e,t,p,n,i,s)<r?d=p+1:u=p}if(o!=="start")return d;let m=d;for(;m<l&&fo(e,t,m+1,n,i,s)===r;)m+=1;return m}function Vr(e){let t=dv(e.document,e.blockId);if(!t)return null;let r=se(e.document,cv),o=gi(t.document);if(e.range.start===e.range.end){let l=Eo(t.node,t.position,e.range.start,r);return typeof l=="number"?{start:fo(t.node,t.position,l,e.projectedMode,t.path,o),end:fo(t.node,t.position,l,e.projectedMode,t.path,o)}:null}let n=He(t.node,t.position,e.range.start,"start",r),i=He(t.node,t.position,e.range.end,"end",r);if(typeof n!="number"||typeof i!="number")return null;let s=fo(t.node,t.position,n,e.projectedMode,t.path,o),a=fo(t.node,t.position,i,e.projectedMode,t.path,o);return{start:Math.min(s,a),end:Math.max(s,a)}}function ua(e){let t=dv(e.document,e.blockId);if(!t)return null;let r=se(e.document,cv),o=gi(t.document);if(e.range.start===e.range.end){let l=vd(t.node,t.position,e.range.start,"end",e.projectedMode,t.path,o);return typeof l=="number"?{start:we(t.node,t.position,l,r),end:we(t.node,t.position,l,r)}:null}let n=vd(t.node,t.position,e.range.start,"start",e.projectedMode,t.path,o),i=vd(t.node,t.position,e.range.end,"end",e.projectedMode,t.path,o);if(typeof n!="number"||typeof i!="number")return null;let s=we(t.node,t.position,n,r),a=we(t.node,t.position,i,r);return{start:Math.min(s,a),end:Math.max(s,a)}}import{hasVisibleSemanticContent as KA}from"@datalking/begonia-engine";function qA(e,t){let r=Math.min(e.length,t.length),o=0;for(;o<r&&e[o]===t[o];)o+=1;return o}function WA(e,t,r){let o=Math.min(e.length-r,t.length-r),n=0;for(;n<o&&e[e.length-1-n]===t[t.length-1-n];)n+=1;return n}function Si(e,t){if(e===t)return{current:{start:0,end:e.length},next:{start:0,end:t.length}};let r=qA(e,t),o=WA(e,t,r);return{current:{start:r,end:e.length-o},next:{start:r,end:t.length-o}}}function _A(e){return tr(e)}function uv(e){return e.length>0&&e.trim().length===0}function UA(e){return e==="paragraph"||e==="heading"}function mv(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function ZA(e,t){return Cr(e,t)}function GA(e,t,r){let o=Math.min(t,r),n=Math.max(t,r),i=e.position+e.node.nodeSize;return o>=e.position&&n<=i}function XA(e){let t=[],r=(o,n,i,s)=>{let a=o.isInline?wt(o,"final",i):!1,l=o.isInline?wt(o,"original",s):!1,c=o.isText||o.isLeaf&&KA(o)?_A(o):0;if(c>0){t.push({from:n,to:n+(o.isText?c:o.nodeSize),projectedLength:c,visibleFinal:!a,visibleOriginal:!l});return}o.forEach((d,u)=>{r(d,n+1+u,a&&o.isInline,l&&o.isInline)})};return r(e.node,e.position,!1,!1),t}function hv(e){return Math.max(0,e.end-e.start)}function pv(e,t){return!!(e?.precise&&t.length>0&&hv(e.range)!==t.length)}function fv(e,t){return!!(e?.precise&&t.length>0&&hv(e.range)===t.length)}function yd(e,t,r){let o=0;for(let n of e){let i=t==="final"?n.visibleFinal:n.visibleOriginal;if(r<=n.from)break;if(r>=n.to){i&&(o+=n.projectedLength);continue}i&&(o+=n.projectedLength===n.to-n.from?r-n.from:r>n.from?n.projectedLength:0);break}return o}function yv(e,t,r){let o=e.target;if(o&&mv(o.blockPath,r.path)&&typeof o.from=="number"&&typeof o.to=="number")return{range:{start:Zt(r,o.from),end:Zt(r,o.to)},precise:!0};if(typeof e.from=="number"&&typeof e.to=="number")return GA(r,e.from,e.to)?{range:{start:Zt(r,e.from),end:Zt(r,e.to)},precise:!0}:null;let n=t.target;return n&&mv(n.blockPath,r.path)&&typeof n.from=="number"&&typeof n.to=="number"?{range:{start:Zt(r,n.from),end:Zt(r,n.to)},precise:!1}:null}function wv(e,t,r,o,n){let i=yv(n.member,o,t);if(!i)return null;let s=yd(e,r,i.range.start),a=yd(e,r,i.range.end);return{range:{start:Math.min(s,a),end:Math.max(s,a)},precise:i.precise}}function gv(e,t,r,o,n){let i=yv(n.member,o,t);if(!i)return null;let s=yd(e,r,i.range.start);return{start:s,end:s}}function hd(e,t){let r=0;for(let o of e)(t==="final"?o.visibleFinal:o.visibleOriginal)&&(r+=o.projectedLength);return{start:0,end:r}}function Sv(e,t){let r=t?.member.target??e?.target??null;return r&&(r.nodeType==="bookmark_anchor"||r.nodeType==="structural_revision_carrier")&&UA(r.blockType)?r:null}function $A(e){return e.currentText.length>0||e.nextText.length>0?!1:!!(Sv(e.currentRevision,e.currentSide)||Sv(e.nextRevision,e.nextSide))}function vv(e,t,r,o){let n=Si(t,r),i=o==="current"?n.current:n.next;return{start:e.start+i.start,end:e.start+i.end}}function bv(e){let t=ZA(e.canonicalDocument,e.blockId);if(!t)return null;let r=XA(t),o=e.projectedMode==="final"?"original":"final",n=$A({currentRevision:e.currentRevision,currentSide:e.currentSide,nextRevision:e.nextRevision,nextSide:e.nextSide,currentText:e.currentText,nextText:e.nextText}),i=uv(e.currentText)&&uv(e.nextText),s=e.currentSide&&e.currentRevision?wv(r,t,e.projectedMode,e.currentRevision,e.currentSide):null,a=e.nextSide&&e.nextRevision?wv(r,t,o,e.nextRevision,e.nextSide):null,l=pv(s,e.currentText),c=pv(a,e.nextText),d=fv(s,e.currentText),u=fv(a,e.nextText),m=n?hd(r,e.projectedMode):i&&s||d&&s||l&&s?s.range:s?vv(s.range,e.currentText,e.nextText,"current"):e.nextSide&&e.nextRevision?gv(r,t,e.projectedMode,e.nextRevision,e.nextSide):null,p=n?hd(r,e.projectedMode):s?.precise||s&&e.currentText.length>0&&e.currentText.trim().length===0?s.range:m,f=n?hd(r,o):i&&a||u&&a||c&&a?a.range:a?vv(a.range,e.currentText,e.nextText,"next"):e.currentSide&&e.currentRevision?gv(r,t,o,e.currentRevision,e.currentSide):null;return m&&p&&f?{currentRange:m,currentActiveRange:p,nextRange:f}:null}function Bv(e){return typeof e?.member.text=="string"?e.member.text:""}function YA(e){return e==="final"?new Set(["insert","format"]):new Set(["delete","format"])}function xv(e,t){let r=YA(t),o=(e.members??[]).filter(n=>r.has(n.kind)).map(n=>({revisionId:e.id,member:n,sortFrom:n.target?.from??n.from??e.target?.from??e.from}));return o.length>0?o:e.kind&&r.has(e.kind)?[{revisionId:e.id,member:{revisionId:e.id,kind:e.kind,text:"text"in e&&typeof e.text=="string"?e.text:"",from:e.from,to:e.to,target:e.target??null},sortFrom:e.target?.from??e.from}]:[]}function JA(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function QA(e){let t=new Map;return e.forEach((r,o)=>{let n=JA(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...xv(r,"final")),i.originals.push(...xv(r,"original")),t.set(n,i)}),[...t.values()]}function Cv(e,t){return e.sortFrom-t.sortFrom}function Bn(e){let t=[],r=e.revisions,o=new Map(r.map(i=>[i.id,i]));for(let i of QA(r)){let s=[...e.projectedMode==="final"?i.finals:i.originals].sort(Cv),a=[...e.projectedMode==="final"?i.originals:i.finals].sort(Cv),l=Math.max(s.length,a.length);if(l!==0)for(let c=0;c<l;c+=1){let d=s[c]??null,u=a[c]??null;if(!d&&!u)continue;let m=d?o.get(d.revisionId)??null:null,p=u?o.get(u.revisionId)??null:null,f=Bv(d),g=Bv(u),v=bv({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,currentRevision:m,currentSide:d,nextRevision:p,nextSide:u,currentText:f,nextText:g});v&&t.push({revisionId:d?.revisionId??u?.revisionId??"",preservesWholeCurrentSide:!!(d&&(!u||d.revisionId!==u.revisionId)),currentActiveRange:v.currentActiveRange,currentRange:v.currentRange,nextRange:v.nextRange})}}let n=new Map;return t.sort((i,s)=>i.currentRange.start-s.currentRange.start||i.currentRange.end-s.currentRange.end||i.nextRange.start-s.nextRange.start||i.nextRange.end-s.nextRange.end||i.revisionId.localeCompare(s.revisionId)).forEach(i=>{n.set(JSON.stringify([i.revisionId,i.preservesWholeCurrentSide,i.currentActiveRange.start,i.currentActiveRange.end,i.currentRange.start,i.currentRange.end,i.nextRange.start,i.nextRange.end]),i)}),[...n.values()]}function Pv(e){return typeof e=="string"&&e.length>0?e:""}function Rv(e,t){let r=t==="final"?new Set(["insert","format"]):new Set(["delete","format"]),o=(e.members??[]).filter(i=>r.has(i.kind)).map(i=>({revisionId:e.id,text:Pv(i.text)})).filter(i=>i.text.length>0);if(o.length>0)return o;let n=Pv(e.text);return e.kind&&r.has(e.kind)&&n.length>0?[{revisionId:e.id,text:n}]:[]}function Tv(e){let t=new Map;for(let r of e)t.set(JSON.stringify([r.revisionId,r.text]),r);return[...t.values()]}function eN(e,t){let r=e.operationId?.trim();return r&&r.length>0?`operation:${r}`:`revision:${e.id}:${t}`}function kv(e){let t=new Map;return e.forEach((r,o)=>{let n=eN(r,o),i=t.get(n)??{finals:[],originals:[]};i.finals.push(...Rv(r,"final")),i.originals.push(...Rv(r,"original")),t.set(n,i)}),[...t.values()].map(r=>({finals:Tv(r.finals),originals:Tv(r.originals)}))}function Ev(e){let t=new Map;for(let r of e)t.set(`${r.currentText}\0${r.nextText}`,r);return[...t.values()]}function Mv(e){let t=[];for(let r of kv(e)){if(r.finals.length>0&&r.originals.length>0){for(let o of r.finals)for(let n of r.originals)t.push({currentText:o.text,nextText:n.text}),t.push({currentText:n.text,nextText:o.text});continue}for(let o of r.finals)t.push({currentText:o.text,nextText:""});for(let o of r.originals)t.push({currentText:o.text,nextText:""})}return Ev(t)}function Iv(e,t){let r=[];for(let n of kv(e)){let i=t==="final"?n.finals:n.originals,s=Ev((t==="final"?n.originals:n.finals).map(a=>({currentText:a.text,nextText:a.text}))).map(a=>a.currentText);for(let a of i){if(s.length===0){r.push({revisionId:a.revisionId,currentText:a.text,nextText:""});continue}for(let l of s)r.push({revisionId:a.revisionId,currentText:a.text,nextText:l})}}let o=new Map;for(let n of r)o.set(`${n.revisionId}\0${n.currentText}\0${n.nextText}`,n);return[...o.values()]}function ma(e,t){let r=[];if(t.length===0)return r;let o=0;for(;o<=e.length;){let n=e.indexOf(t,o);if(n<0)break;r.push({start:n,end:n+t.length}),o=n+1}return r}function pa(e,t){return t.start===t.end?e.start===e.end?e.start===t.start:e.start<=t.start&&e.end>t.start:e.start===e.end?t.end>t.start&&e.start>=t.start&&e.start<t.end:e.end>t.start&&e.start<t.end}function fa(e,t){return e.end>t.start}function wa(e,t,r){if(e<=t.start)return e;if(e<t.end){let o=t.end-t.start;if(r<=0||o<=0)return t.start;let n=Math.round((e-t.start)/o*r);return t.start+Math.max(0,Math.min(r-1,n))}return t.start+r+(e-t.end)}function tN(e){return e.currentText.length===0&&e.nextText.length>0||e.currentText.length>0&&e.nextText.length===0}function rN(e){return e.filter(tN).length===1}function oN(e){return e.length>0&&e.trim().length===0}function nN(e){return{current:e.occurrence,next:{start:e.occurrence.start,end:e.occurrence.start+e.nextText.length}}}function Bd(e,t){let r=nN(t),o=r.next.end-r.next.start;return{active:pa(e,oN(t.currentText)?t.occurrence:r.current),needsRebase:fa(e,r.current),nextRange:{start:wa(e.start,r.current,o),end:wa(e.end,r.current,o)}}}function iN(e){let t=new Map;for(let r of e)t.set(`${r.start}:${r.end}`,r);return[...t.values()]}function bd(e,t,r){if(t===r)return null;let o=Si(t,r),n=o.next.end-o.next.start;if(!fa(e,o.current))return null;let i=l=>l<=o.current.start?l:l<o.current.end?o.current.start+Math.max(0,Math.min(n,l-o.current.start)):o.current.start+n+(l-o.current.end),s=i(e.start),a=i(e.end);return{start:Math.min(s,a),end:Math.max(s,a)}}function sN(e,t,r){let o=Si(t,r),n=o.current.end-o.current.start,i=o.next.end-o.next.start;return e.currentRange.end-e.currentRange.start===n&&e.nextRange.end-e.nextRange.start===i}function aN(e,t,r){return e.currentRange.start===0&&e.currentRange.end===t.length&&e.nextRange.start===0&&e.nextRange.end===r.length}function Av(e,t){let r=0;for(let o of t){let n=o.currentRange.end-o.currentRange.start,i=o.nextRange.end-o.nextRange.start;if(e<=o.currentRange.start)return e+r;if(e<o.currentRange.end)return o.nextRange.start+wa(e-o.currentRange.start,{start:0,end:n},i);r+=i-n}return e+r}function lN(e,t){let r=[...t].sort((s,a)=>s.currentRange.start-a.currentRange.start||s.currentRange.end-a.currentRange.end||s.nextRange.start-a.nextRange.start||s.nextRange.end-a.nextRange.end||s.revisionId.localeCompare(a.revisionId));if(!r.some(s=>fa(e,s.currentRange)))return null;let n=Av(e.start,r),i=Av(e.end,r);return{start:Math.min(n,i),end:Math.max(n,i)}}function Sr(e){if(e.canonicalDocument&&e.projectedMode&&e.blockId){let o=Bn({blockId:e.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(o.length>0){if(o.length===1&&sN(o[0],e.currentBlockText,e.nextBlockText)){let i=bd(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}if(o.length===1&&aN(o[0],e.currentBlockText,e.nextBlockText)){let i=bd(e.selectionRange,e.currentBlockText,e.nextBlockText);if(i)return i}let n=lN(e.selectionRange,o);return n||null}}let t=Mv(e.revisions),r=iN(t.flatMap(o=>ma(e.currentBlockText,o.currentText).flatMap(n=>{let i=e.currentBlockText.slice(0,n.start),s=e.currentBlockText.slice(n.end);if(e.nextBlockText!==`${i}${o.nextText}${s}`)return[];let a=Bd(e.selectionRange,{occurrence:n,currentText:o.currentText,nextText:o.nextText});return a.needsRebase?[a.nextRange]:[]})));return r.length===1?r[0]:r.length===0&&rN(t)?bd(e.selectionRange,e.currentBlockText,e.nextBlockText):null}function cN(e,t){return t!=="visible"||e.preservesWholeCurrentSide||e.currentActiveRange.start<e.currentRange.start||e.currentActiveRange.end>e.currentRange.end?e.currentActiveRange:e.currentRange}function vi(e){if(!e.projectedMode||!e.projectedDocument||!e.selectionTarget)return lr(e.selection,e.revisions);let t=e.activationScope??"preserved",r=nv({target:e.selectionTarget,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode})??e.selectionTarget;if(e.canonicalDocument){let s=new Set,a=!1;for(let l of r.segments){let c=Bn({blockId:l.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions});if(c.length===0)continue;let d=Vr({document:e.projectedDocument,blockId:l.blockId,projectedMode:e.projectedMode,range:l.range})??l.range;a=!0;for(let u of c)pa(d,cN(u,t))&&s.add(u.revisionId)}if(s.size>0)return le([...s],e.revisions);if(a)return[]}let o=Iv(e.revisions,e.projectedMode),n=!1,i=new Set;for(let s of r.segments){let a=Pt(e.projectedDocument,s.blockId);if(typeof a=="string")for(let l of o){let c=ma(a,l.currentText);if(c.length===0||(n=!0,c.length!==1))continue;Bd(s.range,{occurrence:c[0],currentText:l.currentText,nextText:l.nextText}).active&&i.add(l.revisionId)}}return i.size>0?le([...i],e.revisions):n?[]:le(e.selection.trackedChangeIds,e.revisions)}function We(e){return e.view?.state?.doc??e.state?.doc??e.document}import{readSyntheticSideStoryDocContext as dN,readSyntheticSideStoryDocOriginPath as uN}from"@datalking/begonia-doc-service/v1";import{projectAcceptedTextBetween as mN}from"@datalking/begonia-engine";function pN(e){return{schema:e.type.schema,port:{replaceDocument(){}},readDocument(){return e}}}function xn(e,t){return e.content.size>0?mN(e,t,1,e.content.size,`
9
- `):""}function Nv(e,t,r,o){let n=Me(e,t,r);return dN(pN(n),o)?.doc??null}function fN(e,t){let r=uN(e.document);if(!r)return null;let o=Nv(t,e,"final",r),n=Nv(t,e,"original",r),i=!!o?.eq(e.document),s=!!n?.eq(e.document);if(i!==s)return i?"final":"original";if(!o||!n)return null;let a=xn(e.document,e.schema),l=xn(o,e.schema),c=xn(n,e.schema),d=a===l;return d!==(a===c)?d?"final":"original":null}function ga(e,t){if(!t||e.document.eq(t))return null;let r=fN(e,t);if(r)return r;let o=Me(t,e,"final");if(e.document.eq(o))return"final";let n=Me(t,e,"original");if(e.document.eq(n))return"original";let i=xn(e.document,e.schema),s=xn(o,e.schema),a=xn(n,e.schema),l=i===s;return l===(i===a)?null:l?"final":"original"}import{describeSurfaceSelection as Qv}from"@datalking/begonia-engine";import{formatAddressableBlockIdWithLogicalId as wN,parseAddressableBlockId as Dv}from"@datalking/begonia-doc-service/structure";import{resolveRevisionProjectedDocument as gN}from"@datalking/begonia-engine";function SN(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function vN(e){return e==="final"?"original":"final"}function Ov(e){if(!e.target||!e.sourceTarget||!e.projectedDocument||!e.canonicalDocument||!e.projectedMode)return e.target;let t=gN(e.canonicalDocument,e.canonicalDocument.type.schema,vN(e.projectedMode)),r=e.target.segments.map((n,i)=>{let s=e.sourceTarget?.segments[i],a=Dv(n.blockId),l=s?Dv(s.blockId):null;if(!s||!a||!l?.logicalId)return n;let c=wN(a.blockType,a.path,l.logicalId),d=Q(t,{kind:"text",segments:[n]},{strict:!0}),u=Q(t,{kind:"text",segments:[{blockId:c,range:{start:n.range.start,end:n.range.end}}]},{strict:!0});return!(u&&(!d||!SN([d.from,d.to],[u.from,u.to])))?n:{blockId:c,range:{start:n.range.start,end:n.range.end}}});return r.some((n,i)=>n.blockId!==e.target?.segments[i]?.blockId)?Kt(e.target,r):e.target}import{addressableBlockTypeForNodeType as hN,formatAddressableBlockId as yN}from"@datalking/begonia-doc-service/structure";function hi(e,t){let r=da(e,t);if(!r)return t;let o=hN(r.node.type.name);return o?yN(o,r.path):t}function wo(e,t){if(!t)return t;let r=se(e),o=t.segments.map(i=>{let s=hi(e,i.blockId),a=da(e,i.blockId),l=s===i.blockId||!a?{start:i.range.start,end:i.range.end}:{start:nr(a.node,i.range.start,"start",r),end:nr(a.node,i.range.end,"end",r)};return{blockId:s,range:l}});return o.some((i,s)=>i.blockId!==t.segments[s]?.blockId||i.range.start!==t.segments[s]?.range.start||i.range.end!==t.segments[s]?.range.end)?Kt(t,o):t}function xd(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?ge(e,t,o):null}function jv(e){return e.includes("revision_delete")&&!e.includes("revision_insert")?["original"]:e.includes("revision_insert")&&!e.includes("revision_delete")?["final"]:["original","final"]}function Vv(e,t){return e.from!==t.from||e.to!==t.to||e.text!==t.text||e.target.segments.length!==t.target.segments.length?!1:e.target.segments.every((r,o)=>{let n=t.target.segments[o];return!!(n&&r.blockId===n.blockId&&r.range.start===n.range.start&&r.range.end===n.range.end)})}function Lv(e,t,r){let o=new Set;for(let n of Ji(e.resolve(t)))o.add(n);if(t===r)return[...o];for(let n of Yi(e,t,r))o.add(n);return[...o]}import{parseAddressableBlockId as Wv}from"@datalking/begonia-doc-service/structure";import{DELETION_MARK_NAME as _v,FORMAT_MARK_NAME as DN,INSERTION_MARK_NAME as Uv,resolveRevisionProjectedDocument as Kv}from"@datalking/begonia-engine";function bN(e){return tr(e)}function Sa(e,t){return t==="final"?e.visibleFinal:e.visibleOriginal}function zv(e,t){let r=Cr(e,t);if(!r)return null;let o=r.node;if(!o?.isBlock)return null;let n=[],i=gi(r.document),s=0,a=(l,c,d,u)=>{let m=l.isInline?!wt(l,"final",!c):c,p=l.isInline?!wt(l,"original",!d):d,f=bN(l);if(f>0){n.push({start:s,end:s+f,visibleFinal:m,visibleOriginal:p}),s+=f;return}let g=!0,v=!1,E=!1;l.forEach((R,S,P)=>{let h=[...u,P],b=!R.isBlock||i.isBlockPresent(h,"final"),x=!R.isBlock||i.isBlockPresent(h,"original");R.isBlock&&!g&&(n.push({start:s,end:s+1,visibleFinal:m&&b&&v,visibleOriginal:p&&x&&E}),s+=1),a(R,(l.isInline?m:c)&&b,(l.isInline?p:d)&&x,h),R.isBlock&&(v||=m&&b,E||=p&&x),g=!1})};return a(o,i.isBlockPresent(r.localPath,"final"),i.isBlockPresent(r.localPath,"original"),r.localPath),{runs:n,textLength:s}}function BN(e,t){return e.reduce((r,o)=>r+(Sa(o,t)?o.end-o.start:0),0)}function Cd(e,t,r,o){let n=e.filter(a=>Sa(a,t)),i=BN(e,t);if(!Number.isInteger(r)||r<0||r>i)return null;if(n.length===0)return r===0?0:null;let s=0;for(let a=0;a<n.length;a+=1){let l=n[a],c=l.end-l.start,d=s+c;if(r<d)return l.start+(r-s);if(r===d)return o==="end"||a===n.length-1?l.end:n[a+1].start;s=d}return r===s?n[n.length-1].end:null}function Fv(e,t,r,o){if(!Number.isInteger(r)||r<0||r>o)return null;let n=0;for(let i of e){if(r<=i.start)return n;let s=i.end-i.start,a=Sa(i,t)?s:0;if(r<i.end)return n+(Sa(i,t)?r-i.start:0);n+=a}return n}function Hv(e){let t=zv(e.canonicalDocument,e.blockId);if(!t)return null;if(e.range.start===e.range.end){let n=Cd(t.runs,e.projectedMode,e.range.start,"start");return n==null?null:{start:n,end:n}}let r=Cd(t.runs,e.projectedMode,e.range.start,"start"),o=Cd(t.runs,e.projectedMode,e.range.end,"end");return r==null||o==null?null:{start:Math.min(r,o),end:Math.max(r,o)}}function yi(e){let t=zv(e.canonicalDocument,e.blockId);if(!t)return null;let r=Fv(t.runs,e.projectedMode,e.range.start,t.textLength),o=Fv(t.runs,e.projectedMode,e.range.end,t.textLength);return r==null||o==null?null:{start:Math.min(r,o),end:Math.max(r,o)}}import{addressableBlockTypeForNodeType as xN,formatAddressableBlockIdWithLogicalId as CN}from"@datalking/begonia-doc-service/structure";import{isAddressableTextHiddenLeaf as PN,isDocumentNodePathIndex as RN,semanticNodeText as TN}from"@datalking/begonia-document-model";function kN(e){return e.isText?e.text?.length??0:!e.isLeaf||PN(e)?0:Math.max(1,TN(e).length)}function EN(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.index(o));return r}function MN(e){for(let t=1;t<=e.depth;t+=1){let r=e.node(t),o=xN(r.type.name);if(o)return{type:o,path:EN(e,t),node:r,pos:e.start(t)-1}}return null}function IN(e,t,r,o){let n=e[e.length-1];if(n?.blockId===t){n.range.start=Math.min(n.range.start,r),n.range.end=Math.max(n.range.end,o);return}e.push({blockId:t,range:{start:r,end:o}})}function AN(e,t){let r=Le(e,t);if(!r)return null;let o=e,n=-1;for(let i of r){if(!RN(i)||i>=o.childCount)return null;n+=1;for(let s=0;s<i;s+=1)n+=o.child(s).nodeSize;o=o.child(i)}return o.isBlock?{node:o,position:n}:null}function bi(e,t,r){let o=t+1;if(r<=o)return 0;let n=0,i=!1,s=(l,c)=>{let d=0,u=!0;for(let m=0;m<l.childCount;m+=1){if(i)return;let p=l.child(m),f=c+d;if(p.isBlock&&!u)if(r>=f+1)n+=1;else{i=!0;return}a(p,f),d+=p.nodeSize,u=!1}},a=(l,c)=>{if(!i){if(l.isText){let d=l.text??"",u=c+d.length;r>=u?n+=d.length:(n+=Math.max(0,r-c),i=!0);return}if(l.isLeaf){let d=kN(l);r>=c+l.nodeSize?n+=d:i=!0;return}s(l,c+1)}};return s(e,o),n}function Pd(e,t,r,o="end"){let n=t+1,i=Math.max(n,t+e.nodeSize-1),s=bi(e,t,i);if(!Number.isInteger(r)||r<0||r>s)return null;let a=n,l=i;for(;a<l;){let d=a+Math.floor((l-a)/2);bi(e,t,d)<r?a=d+1:l=d}if(o!=="start")return a;let c=a;for(;c<i&&bi(e,t,c+1)===r;)c+=1;return c}function Bi(e,t){let r=[],o=!1,n=Math.min(t.from,t.to),i=Math.max(t.from,t.to);return e.nodesBetween(n,i,(s,a)=>{if(o)return!1;if(!s.isTextblock)return!0;let l=e.resolve(a+1),c=MN(l);if(!c)return o=!0,!1;let d=Math.max(n,a+1),u=Math.min(i,a+s.nodeSize-1),m=bi(c.node,c.pos,d),p=Math.max(m,bi(c.node,c.pos,u));return IN(r,CN(c.type,c.path,Hr(c.type,c.node)),m,p),!1}),o?null:r}function NN(e,t){let r=AN(e,t.blockId);if(!r)return null;if(t.range.start===t.range.end){let i=Pd(r.node,r.position,t.range.start,"start");return typeof i=="number"?{from:i,to:i}:null}let o=Pd(r.node,r.position,t.range.start,"start"),n=Pd(r.node,r.position,t.range.end,"end");return typeof o!="number"||typeof n!="number"?null:{from:Math.min(o,n),to:Math.max(o,n)}}function qv(e,t){let r=[];for(let o of t){let n=NN(e,o);if(!n)return null;r.push(n)}return _r(e,r,{strict:!0})}function Zv(e,t){let r=Wv(e),o=Wv(t);return!r||!o?e===t:r.blockType===o.blockType&&r.path.length===o.path.length&&r.path.every((n,i)=>n===o.path[i])}function Gv(e,t){return!!(t&&e.range.start===e.range.end&&t.range.start<t.range.end&&Zv(e.blockId,t.blockId))}function ON(e,t){return t?.segments.length===e.length&&e.some((r,o)=>Gv(r,t.segments[o]))}function Xv(e){return(e??[]).some(t=>t===Uv||t===_v||t===DN)}function Rd(e){if(!e.selectionInfo.target||!e.projectedDocument)return!1;let t=Q(e.projectedDocument,e.selectionInfo.target,{strict:!0});return!!(t&&t.from===e.selection.from&&t.to===e.selection.to)}function jN(e){if(!e.selectionInfo.target||!e.projectedDocument)return null;if(Rd(e))return e.selectionInfo.target;let t=wo(e.projectedDocument,e.selectionInfo.target),r=t?Q(e.projectedDocument,t,{strict:!0}):null;return r&&r.from===e.selection.from&&r.to===e.selection.to?t:$v(e)?.target??null}function $v(e){let t=e.selectionInfo.text??"";if(!e.projectedDocument||!e.selectionInfo.target||t.length===0)return null;let r=kl(e.projectedDocument,e.selectionInfo.target,t);if(!r)return null;let o=Rd(e),n=r.selection.from===e.selection.from&&r.selection.to===e.selection.to;if(!o&&!n)return null;let i=ge(e.projectedDocument,e.projectedDocument.type.schema,r.selection);return i!==t?null:{target:r.target,text:i,from:r.selection.from,to:r.selection.to}}function Td(e,t="preserved"){if(e.projectedMode||!e.canonicalDocument||!e.selectionInfo.target)return null;if(e.selection.empty&&e.selection.from===e.selection.to){let o=wo(e.projectedDocument??e.canonicalDocument,e.selectionInfo.target),n=o?Q(e.projectedDocument??e.canonicalDocument,o,{strict:!0}):null;if(n&&(n.from!==e.selection.from||n.to!==e.selection.to))return ce(e.selectionInfo.activeChangeIds).length===0?[]:null}let r=jN(e);return r?vi({selection:e.selection,selectionTarget:r,projectedDocument:e.projectedDocument??e.canonicalDocument,canonicalDocument:e.canonicalDocument,projectedMode:"final",revisions:e.revisions,activationScope:t}):ce(e.selectionInfo.activeChangeIds).length===0?[]:null}function Yv(e){if(e.projectedMode||!e.projectedDocument||!e.selectionInfo.target||!e.selection.empty&&ce(e.selectionInfo.activeChangeIds).length===0||e.selection.empty&&e.selectionInfo.activeMarks.includes(_v)&&!e.selectionInfo.activeMarks.includes(Uv))return null;let t=$v(e);if(t)return{target:t.target,text:t.text};if(!e.canonicalDocument||!e.projectedDocument.eq(e.canonicalDocument))return null;let r=e.selectionInfo.text??"",o=Bi(e.projectedDocument,e.selection);if(!o||o.length===0||r.length>0&&Rd(e)&&o.every(l=>l.range.start===l.range.end)&&!ON(o,e.selectionInfo.target))return null;let n=e.projectedDocument.type.schema,i={final:Kv(e.canonicalDocument,n,"final"),original:Kv(e.canonicalDocument,n,"original")},s=e.selection.empty?["final"]:jv(e.selectionInfo.activeMarks),a=null;for(let l of s){let c=i[l],d=o.map((S,P)=>{let h=e.selectionInfo.target?.segments[P],b=h&&Zv(S.blockId,h.blockId)?h.blockId:S.blockId,x=hi(e.projectedDocument,b),A=hi(i.final,b),O=F=>({review:{blockId:x,range:{start:F.start,end:F.end}},expected:{blockId:A,range:{start:F.start,end:F.end}}}),j=Gv(S,h)?Vr({document:e.projectedDocument,blockId:h.blockId,projectedMode:l,range:h.range}):yi({canonicalDocument:e.canonicalDocument,blockId:S.blockId,projectedMode:l,range:S.range});if(!j)return null;if(l==="final")return O(j);let _=Pt(c,S.blockId),V=Pt(i.final,S.blockId);if(typeof _!="string"||typeof V!="string")return null;let de=Sr({selectionRange:j,currentBlockText:_,nextBlockText:V,blockId:S.blockId,canonicalDocument:e.canonicalDocument,projectedMode:l,revisions:e.revisions});if(de)return O(de);let k=xd(c,n,{blockId:S.blockId,range:j});return k==null||xd(e.projectedDocument,n,{blockId:S.blockId,range:j})!==k?null:O(j)});if(d.some(S=>!S))continue;let u=Kt(e.selectionInfo.target,d.map(S=>S.review)),m=Kt(e.selectionInfo.target,d.map(S=>S.expected)),p=Q(e.projectedDocument,u,{strict:!0});if(!p)continue;let f=jr({currentDocument:e.projectedDocument,expectedProjectedDocument:i.final,schema:n});if(!f)continue;let g=Q(f,m,{strict:!0});if(!g)continue;let v=ge(e.projectedDocument,n,p),E=ge(f,n,g);if(v!==E)continue;let R={target:u,text:v,from:p.from,to:p.to};if(!a){a=R;continue}if(!Vv(a,R))return null}return a?{target:a.target,text:a.text}:null}function kd(e,t){let r=e.trackedChangeIds??[];return e.trackedChangeIds!=null&&t.length===r.length&&t.every((o,n)=>o===r[n])?e:{...e,trackedChangeIds:[...t]}}function Jv(e,t){let r=e.activeChangeIds??[];return e.activeChangeIds!=null&&t.length===r.length&&t.every((o,n)=>o===r[n])?e:{...e,activeChangeIds:[...t]}}function VN(e,t,r,o){if(e.projectedMode!=null||e.selection.empty||o)return!1;let n=Math.max(ce(e.selection.trackedChangeIds).length,ce(e.selectionInfo.activeChangeIds).length),i=Math.max(ce(t).length,ce(r).length);return n>i&&(e.selectionInfo.text??"").length>0}function $e(e){let t=Do(e.selection,e.revisions),r=Td({...e,selection:t})??vi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions}),o=Td({...e,selection:t},"visible")??vi({selection:t,selectionTarget:e.selectionInfo.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.revisions,activationScope:"visible"}),n=Ur(e.selectionInfo,t,e.revisions),i=kd(t,r),s=Yv({...e,selection:i});if(VN(e,r,o,s)){let E=ce(t.trackedChangeIds),R=ce(n.activeChangeIds);return{selection:kd(t,E),selectionInfo:Jv(n,R.length>0?R:E),trackedChangeIds:E}}let a=s?Q(e.projectedDocument,s.target,{strict:!0}):null,l=e.selection.empty&&ce(e.selectionInfo.activeCommentIds).length===0,c=!!a&&(l||(s?.text??"").length>0),d=c&&a?(()=>{let E=gt(a,xr(i));return kd({...i,from:a.from,to:a.to,anchor:E.anchor,head:E.head,empty:a.from===a.to},r)})():i,u=c&&a?Lv(e.projectedDocument,d.from,d.to):e.selectionInfo.activeMarks,m=s&&e.selection.empty&&s.text.length===0?void 0:s?.text,p=Ur(s?{...e.selectionInfo,...s,text:m,activeMarks:u}:e.selectionInfo,d,e.revisions),f=e.projectedDocument&&p.target&&(s!=null||e.projectedMode==null&&ce(o).length>0||e.projectedMode!=null||Xv(e.selectionInfo.activeMarks))?wo(e.projectedDocument,p.target):p.target,g=Ov({target:f,sourceTarget:p.target,projectedDocument:e.projectedDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode}),v=g!==p.target?{...p,target:g}:p;return{selection:d,selectionInfo:Jv(v,o),trackedChangeIds:r}}function Ye(e){return e.view?.state??e.state??null}function va(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function vr(e,t=null){let r=Ye(e);if(!r)return null;let o=Ee(r,{includeText:!0});return t?$e({selection:Qv(r),selectionInfo:o,projectedDocument:r.doc,revisions:t.review.list()}).selectionInfo:o}function ha(e){let t=Ye(e.surface);if(!t)return null;let r=Ee(t,{includeText:!0});return $e({selection:Qv(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}).selectionInfo}function eh(e,t,r){return ge(e,t,r)}function ya(e,t,r){return r!=null&&eh(e.doc,e.schema,t)===r}function LN(e,t){let r=Ye(e);return!!(r&&t&&r.selection.from===t.from&&r.selection.to===t.to)}function FN(e,t){return Vn(e,t)}function zN(e,t,r){let o=[],n=new Set;for(let i of r){let s=t.comments.target(i),a=Ge(We(e),s);if(s&&a&&LN(e,a)){let l=FN(i,s);if(n.has(l))continue;n.add(l),o.push({commentId:l,target:s})}}return o.length===0?null:o.length===1?o[0]:null}function th(e,t,r){if(r.length===0)return null;let o=zN(e,t,r);return o?{kind:"comment",commentId:o.commentId,target:o.target}:null}function Dt(e,t,r){return eh(e,t,r)}import{pmPositionToAddressableTextOffset as nD}from"@datalking/begonia-document-model";import{EditorState as iD,NodeSelection as Sh}from"prosemirror-state";import{cloneSelectionTextRange as qN}from"@datalking/begonia-document-api/core";function HN(e){return e.hasExpectedSegmentTexts?e.expectedSegmentSelection??e.expectedTextSelection:e.hasExpectedText?e.expectedTextSelection:e.strictSelection}function rh(e){return e==="original"?"original":"final"}function oh(e){if(!e.hasExpandedTarget)return e.strictSelection;let t=rh(e.sourceMode),r=rh(e.projectedMode);if(t===r&&!e.hasExpectedSegmentTexts&&!e.hasExpectedText&&!e.expectedSegmentSelection&&!e.expectedTextSelection){if(e.strictSelection&&e.strictSelection.from!==e.strictSelection.to)return e.strictSelection;if(e.anchorSelection)return e.anchorSelection;if(e.strictSelection&&e.strictSelection.from===e.strictSelection.to)return e.strictSelection}return t!==r?e.strictSelection:HN(e)}function nh(e){return e?{kind:"text",segments:e.segments.map(t=>({blockId:t.blockId,range:{start:t.range.start,end:t.range.start,...t.range.startAffinity?{startAffinity:t.range.startAffinity}:{},...t.range.endAffinity?{endAffinity:t.range.endAffinity}:{}}})),...e.story?{story:structuredClone(e.story)}:{}}:null}function WN(e){let{target:t}=e,r=t.segments.map(n=>({blockId:er({blockId:n.blockId,projectedDocument:e.sourceDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode}),range:qN(n.range)}));return r.some((n,i)=>n.blockId!==t.segments[i]?.blockId)?{kind:"text",segments:r,...t.story?{story:structuredClone(t.story)}:{}}:t}function ih(e,t){return e?Me(e,{schema:e.type.schema},t):null}function KN(e,t){return e.start===t.start&&e.end===t.end}function Ed(e){return e.start===e.end}function _N(e){if(!e.canonicalDocument)return!1;let t=e.target.segments.filter(r=>!Ed(r.range));return t.length===0?!1:t.every(r=>Bn({blockId:r.blockId,canonicalDocument:e.canonicalDocument,projectedMode:e.sourceMode,revisions:e.revisions}).some(o=>KN(r.range,o.currentRange)&&!Ed(o.currentRange)&&Ed(o.nextRange)))}function UN(e){let t=e.projectionSnapshot.canonicalDocument;if(!t)return null;let r=ih(t,e.sourceMode),n=(r?wo(r,e.target):null)??Et(e.target);if(!n)return null;let i=WN({target:n,sourceDocument:r,canonicalDocument:t,sourceMode:e.sourceMode}),s=nh(i);if(e.projectionSnapshot.projectedMode===e.sourceMode)return s&&_N({canonicalDocument:t,sourceMode:e.sourceMode,target:i,revisions:e.revisions})?{target:s,anchorTarget:s}:{target:i,anchorTarget:s};let a=e.projectionSnapshot.projectedMode??"final";if(e.projectionSnapshot.projectedMode==null&&e.sourceMode==="final")return{target:i,anchorTarget:s};let l=ih(t,a);if(!l)return{target:i,anchorTarget:s};let c=n.segments.map((m,p)=>{let f=i.segments[p];if(!f)return null;let g=r?Pt(r,m.blockId):null,v=Pt(l,f.blockId),E=Sr({selectionRange:m.range,currentBlockText:g??"",nextBlockText:v??"",blockId:f.blockId,canonicalDocument:t,projectedMode:e.sourceMode,revisions:e.revisions})??{start:f.range.start,end:f.range.end};return{blockId:f.blockId,range:E}});if(c.some(m=>!m))return null;let d={kind:"text",segments:c,...e.target.story?{story:structuredClone(e.target.story)}:{}},u=nh(d);return{target:d,anchorTarget:u}}function sh(e){return e.sourceMode==null?(()=>{let t=Et(e.target);return t?{target:t,anchorTarget:null}:null})():UN({...e,sourceMode:e.sourceMode})}function ut(e){let t=sh(e);if(!t)return null;let{target:r,anchorTarget:o}=t,n=Array.isArray(e.expectedSegmentTexts)&&e.expectedSegmentTexts.length>0,i=typeof e.expectedText=="string"&&e.expectedText.length>0,s=r.segments.some(p=>p.range.start!==p.range.end),a={strict:!0,collapsedAcceptedVisibleBias:"hidden-anchor"},l=Q(e.state.doc,r,a),c=o?Q(e.state.doc,o,a):null,d=n?tt(e.state.doc,r,e.expectedSegmentTexts??null,a):null,u=i?Ae(e.state.doc,r,e.expectedText??null,a):null,m=oh({sourceMode:e.sourceMode,projectedMode:e.projectionSnapshot.projectedMode,hasExpandedTarget:s,hasExpectedText:i,hasExpectedSegmentTexts:n,strictSelection:l,anchorSelection:c,expectedTextSelection:u,expectedSegmentSelection:d});return m?{target:r,selection:{from:Math.min(m.from,m.to),to:Math.max(m.from,m.to)}}:null}function Md(e,t,r){return ge(e,t,r)}function ah(e,t,r){let o=Q(e,{kind:"text",segments:[r]},{strict:!0});return o?Md(e,t,o):null}function ZN(e){let t=Me(e.canonicalDocument,{schema:e.schema},e.projectedMode);return jr({currentDocument:e.referenceDocuments[0]??t,expectedProjectedDocument:t,schema:e.schema})}function Id(e){let t=ZN({canonicalDocument:e.canonicalDocument,schema:e.schema,projectedMode:e.nextProjectionMode,referenceDocuments:[e.nextDocument,e.currentDocument]});if(!t)return null;let r=e.selectionTarget.segments.map(l=>{let c=er({blockId:l.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),d=Vr({document:e.currentDocument,blockId:l.blockId,projectedMode:e.currentProjectionMode,range:l.range})??l.range,u=Pt(e.currentDocument,c),m=Pt(t,c);if(typeof u!="string"||typeof m!="string")return null;let p=Sr({selectionRange:d,currentBlockText:u,nextBlockText:m,blockId:c,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode,revisions:e.canonicalReviewApi.review.list()});if(p){let v=ua({document:t,blockId:c,projectedMode:e.nextProjectionMode,range:p});return v?{blockId:c,range:v}:null}let f=ah(e.currentDocument,e.schema,l);return f==null||ah(t,e.schema,{blockId:c,range:l.range})!==f?null:{blockId:c,range:l.range}});if(r.some(l=>!l))return null;let o={kind:"text",segments:r,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},n=Q(e.nextDocument,o,{strict:!0});if(!n)return null;let i=Q(t,o,{strict:!0});if(!i)return null;let s=Md(e.nextDocument,e.schema,n),a=Md(t,e.schema,i);return s===a?n:null}function lh(e){let t=Vr({document:e.currentDocument,blockId:e.currentBlockId,projectedMode:e.currentProjectionMode,range:e.range});return t?ua({document:e.canonicalDocument,blockId:e.canonicalBlockId,projectedMode:e.currentProjectionMode,range:t}):null}function ch(e){let t=s=>({blockId:er({blockId:s.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),range:structuredClone(s.range)}),[r,...o]=e.selectionTarget.segments,n={kind:"text",segments:[t(r),...o.map(t)],...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},i=lt(e.currentDocument,e.selectionTarget);return tt(e.nextDocument,n,i,{strict:!0})??Ae(e.nextDocument,n,e.expectedText,{strict:!0})}import{buildExtractOverlapParentAliasMap as JN}from"@datalking/begonia-document-api/review";function GN(e,t){return!!(e&&t&&e.length===t.length&&e.every((r,o)=>r===t[o]))}function XN(e,t){let r=e??[],o=t??[],n=Math.min(r.length,o.length);for(let i=0;i<n;i+=1){let s=r[i]-o[i];if(s!==0)return s}return r.length-o.length}function Ad(e){return!!(e&&e.nodeType&&e.objectId)}function $N(e,t){return Ad(e.target)&&e.target?.nodeType===t}function dh(e,t){return typeof e.entryId=="string"&&typeof t.entryId=="string"&&e.entryId===t.entryId?!0:!!(Ad(e.target)&&Ad(t.target)&&e.target?.objectId===t.target?.objectId&&GN(e.target?.path,t.target?.path))}function YN(e){return[...e].sort((t,r)=>XN(t.target?.path,r.target?.path)||(t.from??0)-(r.from??0)||(t.to??0)-(r.to??0)||String(t.entryId??"").localeCompare(String(r.entryId??"")))}function uh(e){let t=e.currentMember.kind==="insert"?new Set(["delete"]):e.currentMember.kind==="delete"?new Set(["insert"]):new Set([e.currentMember.kind]),r=e.nextProjectionMode==="original"?new Set(["delete","format"]):new Set(["insert","format"]),o=YN(e.revisions.flatMap(l=>l.members??[]).filter(l=>$N(l,e.nodeType))),n=o.find(l=>r.has(l.kind)&&dh(l,e.currentMember));if(n)return n;let s=o.filter(l=>l.kind===e.currentMember.kind).findIndex(l=>dh(l,e.currentMember));return s<0?null:o.filter(l=>t.has(l.kind))[s]??null}function QN(e){return!!(e&&e.nodeType&&e.objectId)}function ph(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function eD(e,t){let r=ph(e);return r?t.get(r)?.id??r:null}function mh(e,t){let r=ph(e.operationId);if(!r)return null;let o=eD(e.overlapParentId,t);return o==null?r:`${r}\0${o}`}function tD(e){for(let t of e.revisions)for(let r of t.members??[])if(QN(r.target)&&r.target?.nodeType===e.currentSelectionTarget.nodeType&&r.target?.objectId===e.currentSelectionTarget.stableIdentity)return{revision:t,member:r};return null}function fh(e){let t=e.currentSelectionTarget,r=tD(e);if(!r)return null;let o=JN(e.revisions),n=mh(r.revision,o),i=n==null?[r.revision]:e.revisions.filter(a=>mh(a,o)===n),s=uh({currentMember:r.member,revisions:i,nodeType:t.nodeType,nextProjectionMode:e.nextProjectionMode});return s?.target?.objectId?{kind:"node",nodeType:t.nodeType,stableIdentity:s.target.objectId,path:s.target.path}:null}import{collectRevisionSpans as wh,selectionOverlapsRevisionRange as rD}from"@datalking/begonia-engine";function xi(e,t,r,o){return Dt(e,t,{from:r,to:o}).length}function oD(e){let t=xi(e.doc,e.schema,e.from,e.to);if(!Number.isInteger(e.acceptedOffset)||e.acceptedOffset<0||e.acceptedOffset>t)return null;let r=e.from,o=e.to;for(;r<o;){let n=r+Math.floor((o-r)/2);xi(e.doc,e.schema,e.from,n)<e.acceptedOffset?r=n+1:o=n}return xi(e.doc,e.schema,e.from,r)===e.acceptedOffset?r:null}function gh(e){if(e.selection.from!==e.selection.to)return null;let t=wh(e.currentDocument,e.schema).filter(l=>rD(e.selection.from,e.selection.to,l)),r=t.length===1?t[0]:null;if(!r||xi(e.currentDocument,e.schema,r.from,r.to)===0)return null;let n=wh(e.nextDocument,e.schema).filter(l=>l.id===r.id&&l.kind===r.kind),i=n.length===1?n[0]:null;if(!i)return null;let s=xi(e.currentDocument,e.schema,r.from,e.selection.from),a=oD({doc:e.nextDocument,schema:e.schema,from:i.from,to:i.to,acceptedOffset:s});return typeof a=="number"?{from:a,to:a}:null}function sD(e){if(!K(e.state.selection)||!e.state.selection.node.isInline||e.state.selection.node.childCount!==0||!Ie(e.state))return e.selectionTarget;let t=Bi(e.state.doc,e.state.selection);return t&&t.length>0?{kind:"text",segments:t,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}}:e.selectionTarget}function aD(e){let t=e.selectionTarget.segments.map(d=>{let u=er({blockId:d.blockId,projectedDocument:e.currentDocument,canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode}),m=Hv({canonicalDocument:e.canonicalDocument,blockId:u,projectedMode:e.currentProjectionMode,range:d.range});return m?{blockId:u,range:m}:null});if(t.some(d=>!d))return null;let r=t.map(d=>{let u=d,m=yi({canonicalDocument:e.canonicalDocument,blockId:u.blockId,projectedMode:e.nextProjectionMode,range:u.range});return m?{blockId:u.blockId,range:m}:null});if(r.some(d=>!d))return null;let o={kind:"text",segments:r,...e.selectionTarget.story?{story:structuredClone(e.selectionTarget.story)}:{}},n=Q(e.nextDocument,o,{strict:!0});if(!n)return null;let i=Me(e.canonicalDocument,{schema:e.schema},e.nextProjectionMode),s=jr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:e.schema});if(!s)return null;let a=Q(s,o,{strict:!0});if(!a)return null;let l=Dt(e.nextDocument,e.schema,n),c=Dt(s,e.schema,a);return l===c?n:null}function lD(e){if(e.selection.from!==e.selection.to||e.segments.length!==1)return null;let t=e.segments[0];if(t.range.start!==t.range.end)return null;let r=Le(e.nextDocument,t.blockId),o=r?Ve(e.nextDocument,r):null;if(!o?.node.isBlock)return null;let n=o.position+1,i=Math.max(n,o.position+o.node.nodeSize-1),s=e.selection.from;return s<n||s>i?null:nD(o.node,o.position,s)===t.range.start?{from:s,to:s}:null}function Nd(e){let t=e.currentProjectionMode??null,r=We(e.surface),o=t?ha({surface:e.surface,canonicalReviewApi:e.canonicalReviewApi,canonicalDocument:e.canonicalDocument,projectedMode:t})??e.selectionInfo??vr(e.surface,e.canonicalReviewApi):vr(e.surface,e.canonicalReviewApi);if(!o||!o.target)return null;let n=Ye(e.surface);if(!n)return null;let i=t?sD({state:n,selectionTarget:o.target}):o.target,s=!!e.nextProjectionMode&&K(n.selection)&&n.selection.node.isInline&&n.selection.node.childCount===0,a=!!t&&s,l=s?Ie(n):null;if(l&&e.nextProjectionMode){let u=fh({currentSelectionTarget:l,revisions:e.canonicalReviewApi.review.list(),nextProjectionMode:e.nextProjectionMode});if(u)return u}let c=(()=>{if(a)return aD({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,nextProjectionMode:e.nextProjectionMode});if(!t&&!e.nextProjectionMode&&!n.selection.empty){let g=lt(r,i),v=tt(e.nextDocument,i,g??null,{strict:!0})??Ae(e.nextDocument,i,o.text??null,{strict:!0});if(v)return v}if(t&&e.nextProjectionMode)return Id({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:e.nextProjectionMode});let u=t?i.segments.map(g=>{let v=er({blockId:g.blockId,projectedDocument:r,canonicalDocument:e.canonicalDocument,projectedMode:t}),E=lh({currentDocument:r,canonicalDocument:e.canonicalDocument,currentBlockId:g.blockId,canonicalBlockId:v,currentProjectionMode:t,range:g.range});return E?{blockId:v,range:E}:null}):Bi(n.doc,n.selection);if(!u)return null;let m=u.filter(g=>g!=null);if(m.length!==u.length)return null;if(!e.nextProjectionMode){if(t){let g=lD({nextDocument:e.nextDocument,selection:n.selection,segments:m});if(g)return g;if(!n.selection.empty){let v=ch({currentDocument:r,nextDocument:e.nextDocument,selectionTarget:i,canonicalDocument:e.canonicalDocument,currentProjectionMode:t,expectedText:o.text});if(v)return v;let E=Id({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selectionTarget:i,canonicalDocument:e.canonicalDocument,canonicalReviewApi:e.canonicalReviewApi,currentProjectionMode:t,nextProjectionMode:"final"});if(E)return E}}if(!t){let g=gh({currentDocument:r,nextDocument:e.nextDocument,schema:n.schema,selection:n.selection});if(g)return g}return qv(e.nextDocument,m)}let p=e.nextProjectionMode,f=m.map(g=>{let v=yi({canonicalDocument:e.canonicalDocument,blockId:g.blockId,projectedMode:p,range:g.range});return v?{blockId:g.blockId,range:v}:null});return f.some(g=>!g)?null:Q(e.nextDocument,{kind:"text",segments:f,...i.story?{story:structuredClone(i.story)}:{}},{strict:!0})})();if(!c)return null;let d=K(n.selection)?cD(e.nextDocument,c):null;return d||{kind:"tracked",selection:c,text:Dt(e.nextDocument,n.schema,c)}}function vh(e){if(!e.preservedRangeSelection.target)return null;let t=Ye(e.surface);if(!Dd(e)||!t)return null;let r=e.preservedRangeSelection.target,o=Ae(e.nextDocument,r,e.preservedRangeSelection.text,{strict:!0})??tt(e.nextDocument,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!o)return null;let n=e.nextProjectionMode??e.preservedRangeSelection.projectedMode;if(!n)return null;let i=Me(e.canonicalDocument,{schema:t.schema},n),s=jr({currentDocument:e.nextDocument,expectedProjectedDocument:i,schema:t.schema});if(!s)return null;let a=Ae(s,r,e.preservedRangeSelection.text,{strict:!0})??tt(s,r,e.preservedRangeSelection.segmentTexts??null,{strict:!0});if(!a)return null;let l=Dt(e.nextDocument,t.schema,o),c=Dt(s,t.schema,a);return o.from===a.from&&o.to===a.to&&l===c?{kind:"tracked",selection:o,text:l,...e.preservedRangeSelection.direction?{direction:e.preservedRangeSelection.direction}:{}}:null}function Dd(e){if(!e.preservedRangeSelection.target)return!1;let t=Ye(e.surface);if(!t||!t.selection.empty||e.preservedRangeSelection.projectedMode!==(e.nextProjectionMode??null))return!1;let r=ut({state:t,target:e.preservedRangeSelection.target,projectionSnapshot:{canonicalDocument:e.canonicalDocument,projectedMode:e.currentProjectionMode??null},sourceMode:e.preservedRangeSelection.projectedMode,revisions:e.canonicalReviewApi.review.list(),expectedText:e.preservedRangeSelection.text,expectedSegmentTexts:e.preservedRangeSelection.segmentTexts});return!!(r&&r.selection.from===r.selection.to&&r.selection.from===t.selection.from&&r.selection.to===t.selection.to)}function cD(e,t){let r=e.nodeAt(t.from);if(!r||!r.isInline||r.childCount!==0||!Sh.isSelectable(r))return null;let o;try{o=Sh.create(e,t.from)}catch{return null}if(o.from!==Math.min(t.from,t.to)||o.to!==Math.max(t.from,t.to))return null;let n=iD.create({doc:e,selection:o});return Ie(n)}function hh(e,t){let r=Le(e,t),o=r?Ve(e,r):null;return o?.node.isBlock?Mo(o.node,se(e)).text:null}function uD(e){let t=Ye(e.surface);if(!t||!e.selectionInfo.target)return null;let r=We(e.surface),n={kind:"text",segments:e.selectionInfo.target.segments.map(s=>{let a=hh(r,s.blockId),l=hh(e.nextDocument,s.blockId),c=a!=null&&l!=null?Sr({selectionRange:s.range,currentBlockText:a,nextBlockText:l,revisions:e.canonicalReviewApi.review.list()}):null;return{blockId:s.blockId,range:c??dD(s.range)}})},i=Q(e.nextDocument,n,{strict:!0});return i?{kind:"text",target:n,text:Dt(e.nextDocument,t.schema,i),segmentTexts:lt(e.nextDocument,n)}:null}function mD(e,t,r,o,n,i,s){let a=vr(e),l=vr(e,o),c=!!(o&&n&&(ga(e,i?n:t)||i)),d=c?ga(e,i?n:t):null,u=c&&d?ha({surface:e,canonicalReviewApi:o,canonicalDocument:n,projectedMode:d})??l:l;if(a?.target&&d==="original"&&!i&&u?.activeMarks.length===0&&a.target.segments.every(g=>g.range.start===g.range.end)){let g=Ye(e),v=g?.selection??null;if(v)return{kind:"tracked",selection:{from:v.from,to:v.to},text:Dt(t,g?.schema??t.type.schema,v)}}let p=Ie(Ye(e)),f=u?.target&&r?th(e,r,u.activeCommentIds):null;if(f&&!p)return f;if(c&&u?.target){if(s){let v=Dd({surface:e,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s}),E=vh({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,preservedRangeSelection:s});if(E)return E;if(v)return null}if(d&&!i&&u.activeChangeIds.length===0&&!p){let v=uD({surface:e,nextDocument:t,canonicalReviewApi:o,canonicalDocument:n,currentProjectionMode:d,selectionInfo:u});if(v)return v}let g=Nd({surface:e,nextDocument:t,canonicalDocument:n,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(g)return g}if(o&&u?.target&&u.activeChangeIds.length>0){let g=Nd({surface:e,nextDocument:t,canonicalDocument:n??t,canonicalReviewApi:o,currentProjectionMode:d,nextProjectionMode:i,selectionInfo:u});if(g)return g}return f||p||(u?.target&&u.activeChangeIds.length===0?{kind:"text",target:u.target,text:u.text??null,segmentTexts:lt(We(e),u.target)}:null)}function go(e){let t=mD(e.surface,e.nextDocument,e.documentApi,e.canonicalReviewApi,e.canonicalDocument,e.nextProjectionMode,e.preservedRangeSelection);if(!t||t.kind==="node")return t;let r=Ye(e.surface)?.selection;return r&&Dp(r)==="backward"?{...t,direction:"backward"}:t}function vD(e){return!!(e&&e.activeCommentIds.length===0&&e.activeMarks.includes(pD)&&!e.activeMarks.includes(wD)&&(e.text??"").length===0)}function Ci(e){if(!e.target||!va(e.surface))return;let t=e.surface.view.state.doc,r=e.target.kind==="node"?Gi(t,e.target):null,o=e.target.kind==="node"?null:e.target.kind==="comment"?di({comments:e.documentApi?.comments,commentId:e.target.commentId,fallbackTarget:e.target.target,resolve:l=>Ge(t,l)})?.resolution??null:e.target.kind==="tracked"?e.target.selection:tt(t,e.target.target,e.target.segmentTexts,{strict:!0})??Ae(t,e.target.target,e.target.text,{strict:!0}),n=()=>{let l=e.surface.view?.state;if(!l||typeof e.surface.view?.dispatch!="function")return;let c=l.selection,d=Z(l,c.from,c.from);!d||K(d)||e.surface.view.dispatch(l.tr.setSelection(d))};if(!r&&!o){e.target.kind==="node"&&n();return}if(e.target.kind!=="comment"&&e.target.kind!=="node"&&o&&!ya(e.surface.view.state,o,e.target.text))return;let i=e.surface.view.state.selection,s=o?gt(o,e.target.kind==="node"?void 0:e.target.direction):null;if(r?K(i)&&i.from===r.position:o&&i.from===o.from&&i.to===o.to&&i.anchor===s?.anchor&&i.head===s.head)return;let a=r?gD.create(e.surface.view.state.doc,r.position):Z(e.surface.view.state,s.anchor,s.head);a&&e.surface.view.dispatch(e.surface.view.state.tr.setSelection(a))}function ba(e){if(!va(e.surface))return!1;let t=Ye(e.surface);if(!t||t.selection.empty)return!1;let r=vr(e.surface),o=r&&e.canonicalReviewApi?$e({selection:fD(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.canonicalDocument,projectedMode:e.projectedMode,revisions:e.canonicalReviewApi.review.list()}):null;if(vD(r))return!1;let n=o?.selectionInfo??r;if(!n?.target||n.activeCommentIds.length>0||n.activeChangeIds.length===0||typeof n.text!="string"||n.text.length===0)return!1;let i=o?{from:o.selection.from,to:o.selection.to}:Q(e.surface.view.state.doc,n.target,{strict:!0});if(!i||i.from>=i.to||t.selection.from===i.from&&t.selection.to===i.to||!ya(e.surface.view.state,i,n.text))return!1;let s=Z(e.surface.view.state,i.from,i.to);return!s||s.empty?!1:(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(s)),!0)}function Cn(e){let{surface:t,nextDocument:r,documentApi:o,nextDocumentApi:n}=e,i=go(e);t.replaceDocument(r,{origin:"system",intent:"replace-projected-document-preserving-selection",effects:[SD("review")]}),Ci({surface:t,target:i,documentApi:n??o})}import{createDocumentRuntimeKernel as nO}from"@datalking/begonia-document-api/v1";import{summarizeReviewTimeline as iO}from"@datalking/begonia-document-api/review";import{createEditorSelectionSnapshot as sO}from"@datalking/begonia-editor-contracts";function yh(e,t){return{surface:e,documentApi:t,context:{source:"browser-ooxml-nodeview"},runMutation(o,n){if(it(e)){if(e.trackingEnabled){o();return}n()}}}}function Pn(e,t){e.runMutation(()=>{e.documentApi.ooxml.removeByIdTracked(t,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.removeById(t)})}function Od(e,t){switch(t.action){case"replace-chart-model":e.runMutation(()=>{e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.replaceModelById(t.objectId,t.model)});return;case"apply-chart-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-metadata":e.runMutation(()=>{e.documentApi.ooxml.charts.setMetadataByIdTracked(t.objectId,r,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setMetadataById(t.objectId,r)});return;case"set-text-body":e.runMutation(()=>{e.documentApi.ooxml.charts.setTextBodyByIdTracked(t.objectId,r.textBody,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setTextBodyById(t.objectId,r.textBody)});return;case"set-plot-area":e.runMutation(()=>{e.documentApi.ooxml.charts.setPlotAreaByIdTracked(t.objectId,r.plotArea,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setPlotAreaById(t.objectId,r.plotArea)});return;case"set-legend":e.runMutation(()=>{e.documentApi.ooxml.charts.setLegendByIdTracked(t.objectId,r.legend,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setLegendById(t.objectId,r.legend)});return;case"set-series":e.runMutation(()=>{e.documentApi.ooxml.charts.setSeriesByIdTracked(t.objectId,r.target,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setSeriesById(t.objectId,r.target,r.series)});return;case"set-series-list":e.runMutation(()=>{e.documentApi.ooxml.charts.setSeriesListByIdTracked(t.objectId,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setSeriesListById(t.objectId,r.series)});return;case"upsert-series":e.runMutation(()=>{e.documentApi.ooxml.charts.upsertSeriesByIdTracked(t.objectId,r.series,e.surface.participant,e.context,r.seriesId)},()=>{e.documentApi.ooxml.charts.upsertSeriesById(t.objectId,r.series,r.seriesId)});return;case"append-series":e.runMutation(()=>{e.documentApi.ooxml.charts.appendSeriesByIdTracked(t.objectId,r.series,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.appendSeriesById(t.objectId,r.series)});return;case"remove-series":e.runMutation(()=>{e.documentApi.ooxml.charts.removeSeriesByIdTracked(t.objectId,r.target,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.removeSeriesById(t.objectId,r.target)});return;case"set-axes":e.runMutation(()=>{e.documentApi.ooxml.charts.setAxesByIdTracked(t.objectId,r.axes,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.setAxesById(t.objectId,r.axes)});return;case"upsert-axis":e.runMutation(()=>{e.documentApi.ooxml.charts.upsertAxisByIdTracked(t.objectId,r.axis,e.surface.participant,e.context,r.axisId)},()=>{e.documentApi.ooxml.charts.upsertAxisById(t.objectId,r.axis,r.axisId)});return;case"remove-axis":e.runMutation(()=>{e.documentApi.ooxml.charts.removeAxisByIdTracked(t.objectId,r.axisId,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.removeAxisById(t.objectId,r.axisId)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.charts.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.charts.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function jd(e,t){switch(t.action){case"replace-math-model":e.runMutation(()=>{e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.replaceModelById(t.objectId,t.model)});return;case"set-math-plain-text":e.runMutation(()=>{e.documentApi.ooxml.math.setPlainTextByIdTracked(t.objectId,t.text,e.surface.participant,e.context,t.displayMode)},()=>{e.documentApi.ooxml.math.setPlainTextById(t.objectId,t.text,t.displayMode)});return;case"apply-math-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-display-mode":e.runMutation(()=>{e.documentApi.ooxml.math.setDisplayModeByIdTracked(t.objectId,r.displayMode,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.setDisplayModeById(t.objectId,r.displayMode)});return;case"set-plain-text":e.runMutation(()=>{e.documentApi.ooxml.math.setPlainTextByIdTracked(t.objectId,r.text,e.surface.participant,e.context,r.displayMode)},()=>{e.documentApi.ooxml.math.setPlainTextById(t.objectId,r.text,r.displayMode)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.math.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.math.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function Vd(e,t){switch(t.action){case"replace-shape-model":e.runMutation(()=>{e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.replaceModelById(t.objectId,t.model)});return;case"apply-shape-edits":if(e.surface.trackingEnabled){e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,t.model,e.surface.participant,e.context);return}t.edits.forEach(r=>{switch(r.type){case"set-metadata":e.runMutation(()=>{e.documentApi.ooxml.shapes.setMetadataByIdTracked(t.objectId,r,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setMetadataById(t.objectId,r)});return;case"set-watermark":e.runMutation(()=>{e.documentApi.ooxml.shapes.setWatermarkByIdTracked(t.objectId,r.isWatermark,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setWatermarkById(t.objectId,r.isWatermark)});return;case"set-text-body":e.runMutation(()=>{e.documentApi.ooxml.shapes.setTextBodyByIdTracked(t.objectId,r.paragraphs,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setTextBodyById(t.objectId,r.paragraphs)});return;case"set-geometry":e.runMutation(()=>{e.documentApi.ooxml.shapes.setGeometryByIdTracked(t.objectId,r.geometry,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setGeometryById(t.objectId,r.geometry)});return;case"set-transform":e.runMutation(()=>{e.documentApi.ooxml.shapes.setTransformByIdTracked(t.objectId,r.transform,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setTransformById(t.objectId,r.transform)});return;case"set-fill":e.runMutation(()=>{e.documentApi.ooxml.shapes.setFillByIdTracked(t.objectId,r.fill,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setFillById(t.objectId,r.fill)});return;case"set-stroke":e.runMutation(()=>{e.documentApi.ooxml.shapes.setStrokeByIdTracked(t.objectId,r.stroke,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setStrokeById(t.objectId,r.stroke)});return;case"set-effects":e.runMutation(()=>{e.documentApi.ooxml.shapes.setEffectsByIdTracked(t.objectId,r.effects,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setEffectsById(t.objectId,r.effects)});return;case"set-anchor":e.runMutation(()=>{e.documentApi.ooxml.shapes.setAnchorByIdTracked(t.objectId,r.anchor,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setAnchorById(t.objectId,r.anchor)});return;case"set-children":e.runMutation(()=>{e.documentApi.ooxml.shapes.setChildrenByIdTracked(t.objectId,r.children,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setChildrenById(t.objectId,r.children)});return;case"set-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.setChildByIdTracked(t.objectId,r.target,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setChildById(t.objectId,r.target,r.child)});return;case"append-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.appendChildByIdTracked(t.objectId,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.appendChildById(t.objectId,r.child)});return;case"append-child-to-parent":e.runMutation(()=>{e.documentApi.ooxml.shapes.appendChildToParentByIdTracked(t.objectId,r.parentTarget,r.child,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.appendChildToParentById(t.objectId,r.parentTarget,r.child)});return;case"move-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.moveChildByIdTracked(t.objectId,r.target,e.surface.participant,e.context,{parentId:r.parentTarget,beforeId:r.beforeTarget})},()=>{e.documentApi.ooxml.shapes.moveChildById(t.objectId,r.target,{parentId:r.parentTarget,beforeId:r.beforeTarget})});return;case"remove-child":e.runMutation(()=>{e.documentApi.ooxml.shapes.removeChildByIdTracked(t.objectId,r.target,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.removeChildById(t.objectId,r.target)});return;case"set-connector":e.runMutation(()=>{e.documentApi.ooxml.shapes.setConnectorByIdTracked(t.objectId,r.connector,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setConnectorById(t.objectId,r.connector)});return;case"set-picture":e.runMutation(()=>{e.documentApi.ooxml.shapes.setPictureByIdTracked(t.objectId,r.picture,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setPictureById(t.objectId,r.picture)});return;case"set-word-art":e.runMutation(()=>{e.documentApi.ooxml.shapes.setWordArtByIdTracked(t.objectId,r.wordArt,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.setWordArtById(t.objectId,r.wordArt)});return;case"replace-model":e.runMutation(()=>{e.documentApi.ooxml.shapes.replaceModelByIdTracked(t.objectId,r.model,e.surface.participant,e.context)},()=>{e.documentApi.ooxml.shapes.replaceModelById(t.objectId,r.model)});return}});return;case"remove-advanced-ooxml":Pn(e,t.objectId);return}}function bh(e,t){let r=yh(e,t),o=e.view?.dom??null;if(!o)return()=>{};let n=i=>{let s=i instanceof CustomEvent?i.detail:null;if(nm(s))switch(i.preventDefault(),i.stopPropagation(),s.family){case"math":if(s.action==="remove-advanced-ooxml"){jd(r,{family:"math",action:s.action,objectId:s.objectId});return}jd(r,s);return;case"chart":if(s.action==="remove-advanced-ooxml"){Od(r,{family:"chart",action:s.action,objectId:s.objectId});return}Od(r,s);return;case"shape":if(s.action==="remove-advanced-ooxml"){Vd(r,{family:"shape",action:s.action,objectId:s.objectId});return}Vd(r,s);return}};return o.addEventListener(Hi,n),()=>{o.removeEventListener(Hi,n)}}import{describeSurfaceSelection as Th}from"@datalking/begonia-engine";import{describeSurfaceSelection as hD}from"@datalking/begonia-engine";function yD(e,t,r){if(!r.target){if(Wt(t,r))return!0;let i=e.preservedRangeSelection;return!!(r.nodeSelectionTarget&&i?.nodeSelectionTarget&&sr(r.nodeSelectionTarget,i.nodeSelectionTarget)&&Wt(t,i))||!!(r.nodeSelectionTarget&&up(e.state.doc,r.nodeSelectionTarget,t))}if(Wt(t,r))return!0;let o=e.preservedRangeSelection;if(!o||!o.target||e.projectionSnapshot.projectedMode!==null||o.projectedMode==null||r.projectedMode!==null)return!1;if(Wt(t,o))return!0;let n=ut({state:e.state,target:o.target,projectionSnapshot:e.projectionSnapshot,sourceMode:o.projectedMode,revisions:e.revisions,expectedText:o.text,expectedSegmentTexts:o.segmentTexts});return!!(n&&Wt(t,n.selection))}function bD(e,t,r,o,n=null){if(t.empty)return null;let i=Dn(n??Ie(e));return!r.target&&!i?null:{from:Math.min(t.from,t.to),to:Math.max(t.from,t.to),...xr(t)==="backward"?{direction:"backward"}:{},target:r.target?Et(r.target):null,text:r.text??null,segmentTexts:r.target?lt(e.doc,r.target):null,projectedMode:o,nodeSelectionTarget:i}}function BD(e,t){return On(e.target,t.target)&&(e.text??null)===t.text}function xD(e,t){return!e.selection.empty&&e.selection.from===t.from&&e.selection.to===t.to&&(e.selectionInfo.text??null)===t.text}function CD(e){if(!e.preserved.nodeSelectionTarget)return null;let t=Zr(e.state,e.preserved.nodeSelectionTarget);return t?{from:Math.min(t.selection.from,t.selection.to),to:Math.max(t.selection.from,t.selection.to),target:null,text:Ee(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode}).text??null,segmentTexts:null,projectedMode:e.projectedMode,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}:null}function xh(e,t){let r=Ee(t,{includeText:!0},{reviewReplacementMode:e.reviewReplacementMode});return $e({selection:hD(t),selectionInfo:r,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}function Ld(e){if(!e.preserved.target)return null;let t=e.context.projectionSnapshot.projectedMode,r=ut({state:e.context.state,target:e.preserved.target,projectionSnapshot:e.context.projectionSnapshot,sourceMode:e.sourceMode,revisions:e.context.revisions,expectedText:e.preserved.text,expectedSegmentTexts:e.preserved.segmentTexts});if(!r)return null;let o=Il(e.context.state,{...e.preserved,from:r.selection.from,to:r.selection.to,target:r.target});if(!o)return null;if(e.sourceMode!==t){let i=Ml(e.context.state,{...r.selection,...e.preserved.direction?{direction:e.preserved.direction}:{}})??o,s=Ee(i,{includeText:!0},{reviewReplacementMode:e.context.reviewReplacementMode});return{from:r.selection.from,to:r.selection.to,...e.preserved.direction?{direction:e.preserved.direction}:{},target:Et(r.target),text:s.text??e.preserved.text??null,segmentTexts:lt(i.doc,r.target),projectedMode:t,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}}let n=xh(e.context,o);return n.selection.empty||!n.selectionInfo.target?null:{from:Math.min(n.selection.from,n.selection.to),to:Math.max(n.selection.from,n.selection.to),...e.preserved.direction?{direction:e.preserved.direction}:{},target:Et(n.selectionInfo.target),text:n.selectionInfo.text??null,segmentTexts:lt(o.doc,n.selectionInfo.target),projectedMode:t,nodeSelectionTarget:Dn(e.preserved.nodeSelectionTarget)}}function Ch(e){let t="previous"in e?e.previous:e.preservedRangeSelection;if(!t)return[];if(t.nodeSelectionTarget){let r=CD({state:e.state,preserved:t,projectedMode:e.projectionSnapshot.projectedMode,reviewReplacementMode:e.reviewReplacementMode});if(r&&t.target==null)return[r];let o=[];return r&&o.push(r),[...o,...Bh(e,t)]}return Bh(e,t)}function Bh(e,t){let r=[],o=e.projectionSnapshot.projectedMode;if(!t.projectedMode&&!o)r.push(t);else if(t.projectedMode&&!o){let n=Ld({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else if(t.projectedMode)if(t.projectedMode===o)r.push(t);else{let n=Ld({context:e,preserved:t,sourceMode:t.projectedMode});n&&r.push(n)}else{let n=Ld({context:e,preserved:t,sourceMode:null});n&&r.push(n)}return r}function Fd(e){let t=bD(e.state,e.selection,e.selectionInfo,e.projectionSnapshot.projectedMode,e.selectionNodeSelectionTarget??null);if(t)return e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&e.selectionInfo.empty&&!e.selection.empty&&t.text==null&&os(t.target,e.previous.target)||e.surfaceSelectionReliable===!1&&e.previous?.nodeSelectionTarget&&!t.nodeSelectionTarget&&On(t.target,e.previous.target)&&t.text===e.previous.text?e.previous:t;let r=Ch(e),o=r.find(i=>Wt(e.selection,i));if(o)return o;let n=e.previous?.projectedMode!==e.projectionSnapshot.projectedMode&&e.selection.empty&&e.selectionInfo.activeChangeIds.length>0&&e.previous?.target?ut({state:e.state,target:e.previous.target,projectionSnapshot:e.projectionSnapshot,sourceMode:e.previous.projectedMode,revisions:e.revisions,expectedText:e.previous.text,expectedSegmentTexts:e.previous.segmentTexts}):null;return n&&n.selection.from===n.selection.to&&e.selection.from===n.selection.from&&e.selection.to===n.selection.to||e.surfaceSelectionReliable===!1&&e.selection.empty&&e.previous?.projectedMode!=null&&r.length>0||e.previous&&Wt(e.selection,e.previous)?e.previous:null}function Ph(e,t){let r=e.surfaceSelectionReliable===!1&&t.empty,o=t.empty&&e.preservedRangeSelection?.target!=null&&e.preservedRangeSelection.projectedMode!==e.projectionSnapshot.projectedMode;for(let n of Ch(e)){if(!r&&!yD(e,t,n))continue;let i=Il(e.state,n);if(!i)continue;let s=xh(e,i);if(n.target==null&&sr(Ie(i),n.nodeSelectionTarget)||BD(s.selectionInfo,n)||n.target!=null&&n.projectedMode===e.projectionSnapshot.projectedMode&&xD(s,n)&&(r||e.projectionSnapshot.projectedMode==null)||o&&n.target)return i}if(t.empty){let n=jp(e.state);if(n)return n}return e.state}function Rh(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Rh(t);return e}function zd(e,t,r,o,n,i=null,s=null,a=null){let l=e.target??null;if(!t&&!l&&!r)return null;let{target:c,...d}=e,u={...d,selection:o,selectionTarget:l,segmentTexts:l&&a?lt(a,l):null,nodeSelectionTarget:r??null,selectionKind:n,projectedMode:i,storyOriginPath:s,documentIdentity:Ap(a),documentHash:Oo(a),target:t??null};return Rh(structuredClone(u))}import{readSyntheticSideStoryDocOriginPath as PD}from"@datalking/begonia-doc-service/v1";function kh(e,t,r){let o=Ee(t,r,{reviewReplacementMode:e.reviewReplacementMode}),n=Th(t),i=$e({selection:{...n,editable:n.editable&&e.surfaceEditable},selectionInfo:o,projectedDocument:t.doc,canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions}),s=t!==e.state?le([...n.trackedChangeIds,...i.selection.trackedChangeIds],e.revisions):i.selection.trackedChangeIds,a=s.length===i.selection.trackedChangeIds.length&&s.every((m,p)=>m===i.selection.trackedChangeIds[p])?i.selection:{...i.selection,trackedChangeIds:[...s]},l=t!==e.state&&e.preservedRangeSelection?.target?ut({state:t,target:e.preservedRangeSelection.target,projectionSnapshot:e.projectionSnapshot,sourceMode:e.preservedRangeSelection.projectedMode,revisions:e.revisions,expectedText:e.preservedRangeSelection.text,expectedSegmentTexts:e.preservedRangeSelection.segmentTexts}):null,c=l&&l.selection.from===a.from&&l.selection.to===a.to?{...i.selectionInfo,target:l.target}:i.selectionInfo,d=c.target??Ht(t),u=zd(c,d,Ie(t),a,K(t.selection)?"node":"text",e.projectionSnapshot.projectedMode,PD(t.doc),t.doc);return u||null}function RD(e,t){let r=e.preservedRangeSelection;if(!r||!t.empty||e.projectionSnapshot.projectedMode!==null||r.projectedMode==null||!r.target||!Wt(t,r))return null;let o=ut({state:e.state,target:r.target,projectionSnapshot:e.projectionSnapshot,sourceMode:r.projectedMode,revisions:e.revisions,expectedText:r.text,expectedSegmentTexts:r.segmentTexts});if(!o)return null;let n=gt(o.selection,r.direction),i=Z(e.state,n.anchor,n.head);if(!i)return null;try{return e.state.apply(e.state.tr.setSelection(i))}catch{return null}}function Pi(e){let t=Th(e.state),r=Ph(e,t);return r===e.state?RD(e,t)??r:r}function Eh(e){return kh(e,e.state,e.selectionInput??{})}function So(e){return kh(e,Pi(e),e.selectionInput??{})}import{isDocumentNodePathIndex as TD}from"@datalking/begonia-document-model";import{DELETION_MARK_NAME as kD}from"@datalking/begonia-engine";function Ih(e){return e==="ooxml_math"||e==="ooxml_chart"||e==="ooxml_shape"||e==="inline_ooxml_drawing"}function Ah(e,t){let r=[];for(let o=0;o<t;o+=1)r.push(e.$from.index(o));return r}function ED(e){if(!K(e)||!Ih(e.node.type.name))return null;let t=Ah(e,e.$from.depth);return t.push(e.$from.index(e.$from.depth)),t}function MD(e,t){let r=e;for(let o of t){if(!TD(o)||o>=r.childCount)return null;r=r.child(o)}return r}function Mh(e,t){let r=MD(e.doc,t);return!!(r&&Ih(r.type.name)&&r.marks.some(o=>o.type.name===kD))}function Hd(e){let{selection:t}=e.state;for(let r=t.$from.depth;r>0;r-=1)if(t.$from.node(r).isTextblock)return Ah(t,r);return null}function Rn(e,t){let r=t.blocks.topLevel(),o=e.state.selection.from,n=r.find(i=>o>=i.from&&o<=i.from+i.nodeSize);return n?n.index+1:r.length}function G(){return{source:"browser-ooxml"}}function Ba(e,t){let r=ED(e.selection);if(!r)return null;let o=t.ooxml.get(r);if(!o)return null;let n=Mh(e,o.path),i=t.ooxml.getById(o.objectId);if(!i)return n?null:o;let s=Mh(e,i.path);return n?s?null:i:s?o:i}function Ri(e,t){if(t)return Ba(e.state,t);let r=e,o=Ue(r);return o?Ba(o.state,r.documentApi):null}function Y(e,t,r){let o=Ri(e,t);return o?.family===r?o:null}function J(e){return{changed:!1,reason:`No advanced OOXML ${e} node is selected.`}}function qd(e,t,r){let o=Ri(e,t);return o?e.trackingEnabled?t.ooxml.updateTracked(o.path,r,e.participant,G()):t.ooxml.update(o.path,r):{changed:!1,reason:"No advanced OOXML node is selected."}}function Wd(e,t){let r=Ri(e,t);return r?e.trackingEnabled?t.ooxml.removeTracked(r.path,e.participant,G()):t.ooxml.remove(r.path):{changed:!1,reason:"No advanced OOXML node is selected."}}function Kd(e){return[...new Set((e??[]).map(t=>ct(t)).filter(t=>t.length>0))]}function ID(e,t){let r=Kd(e),o=Kd(t);return r.length===o.length&&r.every((n,i)=>n===o[i])}function AD(e){let t=Math.min(e.from,e.to),r=Math.max(e.from,e.to);return{start:t,selectionEnd:t===r?r+1:r}}function ND(e,t){if(!e||!t)return!1;let r=AD(e),o=Math.min(t.from,t.to),n=Math.max(t.from,t.to);return o===n?o<r.selectionEnd&&o>=r.start:o<r.selectionEnd&&n>r.start}function Ti(e){let t=Ze(e.comments),r=At(e.activeCommentIds,t);if(r.length>0||!e.selection||!e.projectedDocument)return r;let o=Kd((e.comments??[]).map(n=>{let i=e.readTarget(n.id),s=Ge(e.projectedDocument,i);return ND(e.selection,s)?n.id:null}).filter(n=>typeof n=="string"));return o.length===1?o:r}function ki(e,t){return ID(e.activeCommentIds,t)?e:{...e,activeCommentIds:[...t]}}function Nh(e){return{left:e.left,top:e.top}}function DD(e){return e.type==="external"?{...e}:{...e}}function xa(e){return e?{...e,position:Nh(e.position),resolution:DD(e.resolution)}:null}function OD(e){return{...e}}function jD(e){return{...e,items:e.items.map(OD)}}function VD(e){return{...e,trackedChangeIds:[...e.trackedChangeIds],pointReviewTrackedChangeIds:[...e.pointReviewTrackedChangeIds],pointReviewCommentIds:[...e.pointReviewCommentIds],activeCommentIds:[...e.activeCommentIds],activeMarks:[...e.activeMarks],position:Nh(e.position)}}function Ca(e){return e?{context:VD(e.context),sections:e.sections.map(jD)}:null}import{listCapabilities as GD}from"@datalking/begonia-document-api/core";import{listCapabilities as LD}from"@datalking/begonia-document-api/core";var Dh=Object.freeze([...LD()].filter(e=>e.mode==="write"&&e.memberPath).map(e=>e.memberPath)),FD=new Set(Dh),zD=Object.freeze(["controls.create","controls.text.setValueTracked","fields.refreshGroup","layout.replaceFooterTextTracked","layout.replaceFooters","layout.replaceHeaderTextTracked","layout.replaceHeaders","mergeFields.sources.remove","mergeFields.sources.set","mergeFields.update","mergeFields.updateAll","formulas.update","formulas.updateAll","sequences.update","sequences.updateAll","notes.remove","notes.replaceTextTracked","notes.upsert","styles.replaceAll"]),HD=new Set(["byFamily","get","getById","list"]),qD=new Set(["createNode","get","getById","getModel","getModelById","list"]),WD=new Set(["createModelFromText","createNode","get","getById","getModel","getModelById","list"]);function KD(e){return e[e.length-1]??null}function _D(e){return e!=null&&(e==="createNode"||e.startsWith("find")||e.startsWith("get")||e.startsWith("list")||e.startsWith("read"))}function UD(e){let t=e.split(".");if(t[0]!=="ooxml")return!1;let r=t[1]??null;if(r==null)return!1;if(t.length===2)return!HD.has(r);let o=t[2]??null,n=KD(t);return o==="commands"?!1:r==="chart"?n!=null&&!qD.has(n):r==="math"?n!=null&&!WD.has(n):r==="shape"?!_D(n):!1}function Oh(e,t="",r=new WeakSet,o=[]){if(e==null||typeof e!="object"&&typeof e!="function")return o;let n=e;if(r.has(n))return o;r.add(n);for(let i of Object.keys(e)){let s=e[i],a=t?`${t}.${i}`:i;typeof s=="function"&&o.push(a),s!=null&&(typeof s=="object"||typeof s=="function")&&Oh(s,a,r,o)}return o}function ZD(e){let t=new Set;for(let r of e){let o=r.split("."),n="";for(let i=0;i<o.length-1;i+=1)n=n?`${n}.${o[i]}`:o[i],t.add(n)}return t}function jh(e){return zD.includes(e)||UD(e)}function Vh(e){return FD.has(e)||jh(e)}function Lh(e){let t=new Set(Dh);for(let r of Oh(e))jh(r)&&t.add(r);return{deniedMemberPaths:t,descendantMemberPaths:ZD(t)}}var Hh=new Map([...GD()].filter(e=>e.memberPath).map(e=>[e.memberPath,e.mode])),XD=(()=>{let e=new Set;for(let t of Hh.keys()){let r=t.split("."),o="";for(let n=0;n<r.length-1;n+=1)o=o?`${o}.${r[n]}`:r[n],e.add(o)}return e})();function Fh(e,t){if(!t)return{owner:null,value:e};let r=t.split("."),o=null,n=e;for(let i of r)o=n,n=n?.[i];return{owner:o,value:n}}function $D(e){return XD.has(e)}function zh(e){return Vh(e)?"write":Hh.get(e)??null}function YD(e){return e==="final"||e==="original"||e==="tracked"?e:null}function JD(e){return!e||typeof e!="object"?null:YD(e.revisionProjection)}function QD(e){for(let t of e){let r=JD(t);if(r)return r}return null}function Pa(e){return{presentationReadApi:e.presentationReadRuntime.documentApi,canonicalReviewApi:e.canonicalReviewRuntime.documentApi,writableRuntimeApi:e.writableRuntime.documentApi}}function qh(e){let t=new Map,r=(i,s=[])=>{if(zh(i)==="write")return e.readWritableApi();let a=QD(s);return a?e.readProjectedApiForMode(a)??e.readPresentationApi():e.readPresentationApi()},o=(i,s=[])=>{let a=Fh(r(i,s),i);return a.value!==void 0||zh(i)==="write"?a:Fh(e.readWritableApi(),i)},n=i=>{if(t.has(i))return t.get(i);let s=o(i),{value:a}=s;if(a==null||typeof a!="object"&&typeof a!="function")return a;let l=$D(i);if(typeof a=="function"&&!l){let d=(...u)=>{let m=o(i,u);return Reflect.apply(m.value,m.owner,u)};return t.set(i,d),d}let c=new Proxy(a,{get(d,u){if(typeof u!="string"){let p=o(i);return Reflect.get(p.value,u,p.owner)}let m=i?`${i}.${u}`:u;return n(m)},apply(d,u,m){let p=o(i,m);return Reflect.apply(p.value,p.owner,m)}});return t.set(i,c),c};return n}function Ei(e){return e.kind!=="revision"&&e.kind!=="revision-decision"}function Wh(e){let t=e?.trim()??"";if(!t)return 0;let r=Date.parse(t);return Number.isFinite(r)?r:0}function eO(e,t,r){let o=Wh(e.sortAt),n=Wh(t.sortAt);return o!==n?r==="asc"?o-n:n-o:e.id.localeCompare(t.id)}function _d(e,t,r="desc"){let o=new Map(t.filter(Ei).map(s=>[s.id,s])),n=e.map(s=>Ei(s)?o.get(s.id)??s:s),i=new Set(n.map(s=>s.id));for(let s of t)!Ei(s)||i.has(s.id)||(n.push(s),i.add(s.id));return n.sort((s,a)=>eO(s,a,r))}function tO(e,t){if(e.projectedMode==null)return null;let r={actor:t.actor,enforceVisibilityPolicy:t.enforceVisibilityPolicy},o=e.presentationReadRuntime.documentApi.comments,n=new Map;return(i,s)=>{let a=`${i}\0${s}`;return n.has(a)||n.set(a,o.entryTarget(i,s,r)??o.target(i,r)??o.targetSnapshot(i,r)??null),n.get(a)??null}}function Kh(e,t,r){let o=tO(t,r);return o?e.map(n=>{if(!Ei(n))return n;let i=o(n.commentId,n.entryId);return i?{...n,target:i}:n}):e}function rO(e){let t=e.reviewOptions??{},{presentationReadRuntime:r,canonicalReviewRuntime:o}=e.projectionSnapshot,n=r.documentApi,i=o.documentApi,s=i.review.timeline(t);return n===i?s:_d(s,n.review.timeline(t),t.sort??"desc")}function oO(e){let t=e.reviewOptions??{},{presentationReadRuntime:r,canonicalReviewRuntime:o}=e.projectionSnapshot,n=r.documentApi,i=o.documentApi,s=i.review.timelineByObject(e.objectId,t);return n===i?s:_d(s,n.review.timelineByObject(e.objectId,t),t.sort??"desc")}function Ra(e){let t=e.reviewOptions??{};return Kh(rO(e),e.projectionSnapshot,t)}function _h(e){let t=e.reviewOptions??{};return Kh(oO(e),e.projectionSnapshot,t)}function Oe(e){return{allowed:!1,reason:e,matchedPermissionIds:[],authorOwned:!1}}function Mi(e,t){return{...e,toggleInternal:Oe("Comments are read-only in the current document mode."),reply:Oe("Comments are read-only in the current document mode."),resolve:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:Oe("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({...r,edit:Oe("Comments are read-only in the current document mode."),remove:Oe("Comments are read-only in the current document mode.")}))}}function Ii(e){let t=Oe("Tracked changes are read-only in the current document mode.");return{...e,accept:t,reject:t}}function Uh(e){return e&&{...e,edit:Oe("Comments are read-only in the current document mode."),remove:Oe("Comments are read-only in the current document mode.")}}function Ud(e,t){return{threadId:e.id,view:{allowed:!0,reason:null,matchedPermissionIds:[],authorOwned:!1},reply:Oe("Comments are read-only in the current document mode."),resolve:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),reopen:Oe(t.allowResolve?"Comments are read-only in the current document mode.":"Comment resolution is disabled."),remove:Oe("Comments are read-only in the current document mode."),toggleInternal:Oe("Comments are read-only in the current document mode."),entries:e.entries.map(r=>({entryId:r.id,edit:Oe("Comments are read-only in the current document mode."),remove:Oe("Comments are read-only in the current document mode.")}))}}function Zd(e){return{revisionId:e,accept:Oe("Tracked changes are read-only in the current document mode."),reject:Oe("Tracked changes are read-only in the current document mode.")}}function Zh(e,t,r){return e.filter(o=>o.kind==="revision"||o.kind==="revision-decision"?!0:r.enabled&&r.visible)}function Ai(e,t,r){return e.map(o=>o.kind==="revision"?t?o:{...o,permissions:o.permissions?Ii(o.permissions):Zd(o.revisionId)}:o.kind==="revision-decision"?o:r.readOnly?{...o,threadPermissions:o.threadPermissions?Mi(o.threadPermissions,r):Ud(o.comment,r)}:o)}function Gh(e){return{source:e.documentSource,replace(t,r){e.replaceDocument(t,r)}}}function aO(e){let t=Gh(e);return{readDocument(){return e.document},replaceDocument(r,o){t.replace(bt(e.document,r),o)},documentSource:t.source}}function lO(e,t,r,o){return Object.fromEntries(t.map(n=>{let i=r?e.comments.permissions(n.id,r):o.readOnly?Ud(n,o):null;return[n.id,i&&o.readOnly?Mi(i,o):i]}))}function cO(e,t,r,o){let n=r?e.review.permissions(r):o?[]:t.map(i=>Zd(i.id));return Object.fromEntries(n.map(i=>[i.revisionId,o?i:Ii(i)]))}function dO(e,t){return e.length===0?null:e.some(r=>r.hitId===t)?t:e[0]?.hitId??null}function Ta(e,t,r={}){let o=aO(e),n=nO(o,{templates:r.templates??void 0,review:{replacementMode:r.replacementMode??"paired"},selection:yl(e,{reviewReplacementMode:r.replacementMode??"paired"})}),i=n.api,s=e.subscribe(()=>t()),a=bh(e,i),l=!1,c=()=>{l||(l=!0,a(),s(),n.dispose())};return{surface:e,documentRuntimeKernel:n,documentService:n.service,documentApi:i,replacementMode:r.replacementMode??"paired",templatesAdapter:r.templates??null,unsubscribeSurface:s,uninstallAdvancedOoxmlNodeViewBridge:a,release:c}}function uO(e){let t=e.view;return!!(t?.state&&typeof t.dispatch=="function")}function Xh(e){let{runtime:t,projectionSnapshot:r,preservedRangeSelection:o,actor:n,linkPopover:i,contextMenu:s,search:a,collaboration:l,documentMode:c,zoomPercent:d,zoom:u,viewportSession:m,display:p,activeCommentId:f,activeCommentIds:g,activeRevisionId:v,activeRevisionIds:E}=e,{surface:R,documentApi:S}=t,P=it(R),{presentationReadApi:h,canonicalReviewApi:b}=Pa(r),x=p.comments.enabled?h.comments.list({includeResolved:p.comments.showResolved,actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,visibility:p.comments.visibility,sort:"desc"}):[],A=p.comments.visible?x:[],O=b.review.list(),j={actor:n,enforceVisibilityPolicy:p.comments.enforceVisibilityPolicy,includeResolvedComments:p.comments.showResolved,commentVisibility:p.comments.visibility},_=Ai(Zh(Ra({projectionSnapshot:r,reviewOptions:j}),p.trackChanges,p.comments),P,p.comments),V=a.query?h.search.query(a.query,a.options):[],de=h.proofing.list(),k=uO(R),I=R.describeSelection(),F=Dr(R,{includeText:!0},t.replacementMode),y=$e({selection:I,selectionInfo:F,projectedDocument:We(R),canonicalDocument:r.canonicalDocument,projectedMode:r.projectedMode,revisions:O}),B=So({state:R.state,surfaceEditable:P,surfaceSelectionReliable:k,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:O,projectionSnapshot:r,preservedRangeSelection:o}),M=Pi({state:R.state,surfaceEditable:P,surfaceSelectionReliable:k,selectionInput:{includeText:!0},reviewReplacementMode:t.replacementMode,revisions:O,projectionSnapshot:r,preservedRangeSelection:o}),N=yt({liveSelection:y.selection,liveSelectionInfo:y.selectionInfo,revisions:O,effectiveSelection:B}),L=!k&&B?B.selection:y.selection,ae=ar(L.trackedChangeIds,N)?L:{...L,trackedChangeIds:[...N]},je=!k&&B?Rr(B,N):null,me=je??y.selectionInfo,Ke=Ti({activeCommentIds:me.activeCommentIds,selection:k?I:ae,projectedDocument:We(R),comments:x,readTarget:h.comments.target}),Tt=ki(me,Ke),Je=ko(R.state,Tt,K(R.state.selection)?"node":"text"),Ce=je??(y.selection.empty&&ar(Je.activeChangeIds,N)?Je:y.selection.empty?{...Je,activeChangeIds:[...N]}:Je),mt=fw({revisions:O,selectionInfo:Ce,explicitActiveRevisionId:v,explicitActiveRevisionIds:E}),hr=sn({comments:A,selectionInfo:Ce,explicitActiveCommentId:f,explicitActiveCommentIds:g}),jt=sO(ae,t.documentRuntimeKernel.readSnapshot().revision,R.documentStory),Vt={toolbar:Ds({selection:jt,editable:P,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:R.canUndo(),canRedo:R.canRedo()}),comments:A,commentPermissions:lO(h,A,n,p.comments),activeCommentId:hr.activeCommentId,activeCommentIds:hr.activeCommentIds,revisions:O,activeRevisionId:mt.activeRevisionId,activeRevisionIds:mt.activeRevisionIds,reviewPermissions:cO(b,O,n,P),reviewTimeline:_,reviewTimelineSummary:iO(_),search:{query:a.query,hits:V,activeHitId:dO(V,a.activeHitId)},proofing:{diagnostics:de},advancedOoxml:{selected:Ba(M,S)},selectionInfo:Ce,selection:jt,editable:P,documentMode:c,flowMode:m.flowMode,layoutMode:m.layoutMode,preferredPaginatedLayoutMode:m.preferredPaginatedLayoutMode,zoomPercent:d,zoom:u,viewport:m.viewport,viewportRequestKey:m.viewportRequestKey,previewNavigationRequest:m.previewNavigationRequest,trackChanges:p.trackChanges,commentsDisplay:p.comments,collaboration:l,linkPopover:xa(i),contextMenu:Ca(s),selectionNodeSelectionTarget:k?null:B?.nodeSelectionTarget??null},Lt=Zn({getState:()=>Vt,readEffectiveSelection:()=>B,surface:R}),yr=Ds({selection:jt,editable:P,documentMode:c,trackChanges:p.trackChanges,collaboration:l,canUndo:Lt.commands.undo?.disabled===!1,canRedo:Lt.commands.redo?.disabled===!1,commandStates:Lt.commands});return{...Vt,toolbar:yr}}function mO(e){return e.view.dom.parentElement??null}function pO(e){return e.view.dom.ownerDocument?.createElement?.("div")}function $h(e){e.view.updateRoot?.call(e.view)}function Yh(e,t){if(t){if(typeof t.replaceChildren=="function"){t.replaceChildren(e.view.dom),$h(e);return}typeof t.appendChild=="function"&&(t.appendChild(e.view.dom),$h(e))}}function Jh(e){return!!e}function Qh(e){let{canonicalDocument:t,emit:r,projectionMode:o,readPreservedRangeSelection:n,replacementMode:i="paired",sourceRuntime:s,surfaceFactory:a}=e,l=s.surface,c=mO(l),d=bt(t,Me(t,l,o)),u=a({currentSurface:l,collaborative:void 0,documentStory:l.documentStory,editable:!1,element:pO(l),initialContent:d,schema:l.schema,participant:l.participant,trackingEnabled:!1}),m=Ta(u,r,{replacementMode:i});return Yh(u,c),{runtime:m,restore(){Yh(l,c)},sync(p,f){let g=Me(p,l,f);return Ar(m.surface.document,g)?!1:(Cn({surface:m.surface,nextDocument:g,documentApi:m.documentApi,canonicalReviewApi:s.documentApi,canonicalDocument:p,nextProjectionMode:f,preservedRangeSelection:n?.()??null}),!0)}}}function Gd(e,t,r,o={}){let n=Hd(e);return n?t.ooxml.math.appendInline(n,r,o):{changed:!1,reason:"Advanced OOXML math insertion requires an active text block selection."}}function Xd(e,t,r,o={},n={}){let i=Hd(e);return i?t.ooxml.math.appendInlineTracked(i,r,e.participant,o,n):{changed:!1,reason:"Tracked math insertion requires an active text block selection."}}function $d(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.math.replaceModelById(o.objectId,r):J("math")}function Yd(e,t,r,o){let n=Y(e,t,"math");return n?e.trackingEnabled?t.ooxml.math.setPlainTextByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.math.setPlainTextById(n.objectId,r,o):J("math")}function Jd(e,t,r){let o=Y(e,t,"math");return o?e.trackingEnabled?t.ooxml.math.setDisplayModeByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.math.setDisplayModeById(o.objectId,r):J("math")}function Qd(e,t,r,o={}){return t.ooxml.charts.insertBlock(Rn(e,t),r,o)}function eu(e,t,r,o={},n={}){return t.ooxml.charts.insertBlockTracked(Rn(e,t),r,e.participant,o,n)}function tu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.replaceModelById(o.objectId,r):J("chart")}function ru(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setMetadataByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setMetadataById(o.objectId,r):J("chart")}function ou(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTitleByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setTitleById(o.objectId,r):J("chart")}function nu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setTextBodyByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setTextBodyById(o.objectId,r):J("chart")}function iu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.appendSeriesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.appendSeriesById(o.objectId,r):J("chart")}function su(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setSeriesListByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setSeriesListById(o.objectId,r):J("chart")}function au(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.setSeriesByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.charts.setSeriesById(n.objectId,r,o):J("chart")}function lu(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertSeriesByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.charts.upsertSeriesById(n.objectId,r,o):J("chart")}function cu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeSeriesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.removeSeriesById(o.objectId,r):J("chart")}function du(e,t,r){return ka(e,t,r)}function uu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setAxesByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setAxesById(o.objectId,r):J("chart")}function ka(e,t,r,o){let n=Y(e,t,"chart");return n?e.trackingEnabled?t.ooxml.charts.upsertAxisByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.charts.upsertAxisById(n.objectId,r,o):J("chart")}function mu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.removeAxisByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.removeAxisById(o.objectId,r):J("chart")}function pu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setLegendByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setLegendById(o.objectId,r):J("chart")}function fu(e,t,r){let o=Y(e,t,"chart");return o?e.trackingEnabled?t.ooxml.charts.setPlotAreaByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.charts.setPlotAreaById(o.objectId,r):J("chart")}function wu(e,t,r,o={}){return t.ooxml.shapes.insertBlock(Rn(e,t),r,o)}function gu(e,t,r,o={},n={}){return t.ooxml.shapes.insertBlockTracked(Rn(e,t),r,e.participant,o,n)}function Su(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.replaceModelByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.replaceModelById(o.objectId,r):J("shape")}function vu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setMetadataByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setMetadataById(o.objectId,r):J("shape")}function hu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWatermarkByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setWatermarkById(o.objectId,r):J("shape")}function yu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTextBodyByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setTextBodyById(o.objectId,r):J("shape")}function bu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setGeometryByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setGeometryById(o.objectId,r):J("shape")}function Bu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setTransformByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setTransformById(o.objectId,r):J("shape")}function xu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setFillByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setFillById(o.objectId,r):J("shape")}function Cu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setStrokeByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setStrokeById(o.objectId,r):J("shape")}function Pu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setAnchorByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setAnchorById(o.objectId,r):J("shape")}function Ru(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setConnectorByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setConnectorById(o.objectId,r):J("shape")}function Tu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setPictureByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setPictureById(o.objectId,r):J("shape")}function ku(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setWordArtByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setWordArtById(o.objectId,r):J("shape")}function Eu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.setChildrenByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.setChildrenById(o.objectId,r):J("shape")}function Mu(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.setChildByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.shapes.setChildById(n.objectId,r,o):J("shape")}function Iu(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.appendChildByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.appendChildById(o.objectId,r):J("shape")}function Au(e,t,r,o){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.appendChildToParentByIdTracked(n.objectId,r,o,e.participant,G()):t.ooxml.shapes.appendChildToParentById(n.objectId,r,o):J("shape")}function Nu(e,t,r,o={}){let n=Y(e,t,"shape");return n?e.trackingEnabled?t.ooxml.shapes.moveChildByIdTracked(n.objectId,r,e.participant,G(),o):t.ooxml.shapes.moveChildById(n.objectId,r,o):J("shape")}function Du(e,t,r){let o=Y(e,t,"shape");return o?e.trackingEnabled?t.ooxml.shapes.removeChildByIdTracked(o.objectId,r,e.participant,G()):t.ooxml.shapes.removeChildById(o.objectId,r):J("shape")}import{isDocumentNodePathIndex as fO}from"@datalking/begonia-document-model";import{NodeSelection as wO}from"prosemirror-state";function Ou(e,t){return K(e.selection)&&e.selection.node.type.name===`ooxml_${t.family}`&&e.selection.node.attrs.objectId===t.objectId}function gO(e,t){let r=e,o=-1;for(let n of t){if(!fO(n)||n>=r.childCount)return null;o+=1;for(let i=0;i<n;i+=1)o+=r.child(i).nodeSize;r=r.child(n)}return o}function SO(e,t){let r=gO(e,t.path),o=r==null?null:e.nodeAt(r);if(r!=null&&o?.type.name===`ooxml_${t.family}`&&o.attrs.objectId===t.objectId)return r;let n=null;return e.descendants((i,s)=>n==null&&i.type.name===`ooxml_${t.family}`&&i.attrs.objectId===t.objectId?(n=s,!1):!0),n}function ey(e,t){if(!t||Ou(e,t))return e;let r=SO(e.doc,t);if(r==null)return null;let o=at(e,wO.create(e.doc,r));if(!o)return null;if(qt(e.selection,o))return e;try{return e.apply(e.tr.setSelection(o))}catch{return null}}function vO(e,t){return new Proxy(e,{get(r,o,n){return o==="state"?t:Reflect.get(r,o,n)}})}function hO(e,t){if(!t||Ou(e.surface.state,t))return e;let r=e.surface.view?.state,o=r?ey(r,t):null;if(r&&o&&(o!==r&&e.surface.view.dispatch(r.tr.setSelection(o.selection)),Ou(e.surface.state,t)))return e;let n=ey(e.surface.state,t);return!n||n===e.surface.state?e:{...e,surface:vO(e.surface,n)}}function yO(e){return!!(e&&typeof e=="object"&&"changed"in e&&e.changed===!0)}function ty(e){let t=o=>{let n=e.getRuntime(),i=Jt(n.surface);return i?W(i):e.runAndEmit(()=>o(n))},r=o=>t(n=>o(hO(n,e.readState().advancedOoxml.selected)));return{appendMathToCurrentTextblock(o,n={}){return t(i=>Gd(i.surface,i.documentApi,o,n))},appendMathToCurrentTextblockTracked(o,n={},i={}){return t(s=>Xd(s.surface,s.documentApi,o,n,i))},insertChartAfterCurrentBlock(o,n={}){return t(i=>Qd(i.surface,i.documentApi,o,n))},insertChartAfterCurrentBlockTracked(o,n={},i={}){return t(s=>eu(s.surface,s.documentApi,o,n,i))},insertShapeAfterCurrentBlock(o,n={}){return t(i=>wu(i.surface,i.documentApi,o,n))},insertShapeAfterCurrentBlockTracked(o,n={},i={}){return t(s=>gu(s.surface,s.documentApi,o,n,i))},updateSelectedAdvancedOoxml(o){return r(n=>qd(n.surface,n.documentApi,o))},removeSelectedAdvancedOoxml(){return r(o=>{let n=Wd(o.surface,o.documentApi);return yO(n)&&e.clearPreservedRangeSelection(),n})},replaceSelectedMathModel(o){return r(n=>$d(n.surface,n.documentApi,o))},setSelectedMathPlainText(o,n){return r(i=>Yd(i.surface,i.documentApi,o,n))},setSelectedMathDisplayMode(o){return r(n=>Jd(n.surface,n.documentApi,o))},replaceSelectedChartModel(o){return r(n=>tu(n.surface,n.documentApi,o))},setSelectedChartMetadata(o){return r(n=>ru(n.surface,n.documentApi,o))},setSelectedChartTitle(o){return r(n=>ou(n.surface,n.documentApi,o))},setSelectedChartTextBody(o){return r(n=>nu(n.surface,n.documentApi,o))},appendSelectedChartSeries(o){return r(n=>iu(n.surface,n.documentApi,o))},setSelectedChartSeriesList(o){return r(n=>su(n.surface,n.documentApi,o))},setSelectedChartSeries(o,n){return r(i=>au(i.surface,i.documentApi,o,n))},upsertSelectedChartSeries(o,n){return r(i=>lu(i.surface,i.documentApi,o,n))},removeSelectedChartSeries(o){return r(n=>cu(n.surface,n.documentApi,o))},appendSelectedChartAxis(o){return r(n=>du(n.surface,n.documentApi,o))},setSelectedChartAxes(o){return r(n=>uu(n.surface,n.documentApi,o))},upsertSelectedChartAxis(o,n){return r(i=>ka(i.surface,i.documentApi,o,n))},removeSelectedChartAxis(o){return r(n=>mu(n.surface,n.documentApi,o))},setSelectedChartLegend(o){return r(n=>pu(n.surface,n.documentApi,o))},setSelectedChartPlotArea(o){return r(n=>fu(n.surface,n.documentApi,o))},replaceSelectedShapeModel(o){return r(n=>Su(n.surface,n.documentApi,o))},setSelectedShapeMetadata(o){return r(n=>vu(n.surface,n.documentApi,o))},setSelectedShapeWatermark(o){return r(n=>hu(n.surface,n.documentApi,o))},setSelectedShapeTextBody(o){return r(n=>yu(n.surface,n.documentApi,o))},setSelectedShapeGeometry(o){return r(n=>bu(n.surface,n.documentApi,o))},setSelectedShapeTransform(o){return r(n=>Bu(n.surface,n.documentApi,o))},setSelectedShapeFill(o){return r(n=>xu(n.surface,n.documentApi,o))},setSelectedShapeStroke(o){return r(n=>Cu(n.surface,n.documentApi,o))},setSelectedShapeAnchor(o){return r(n=>Pu(n.surface,n.documentApi,o))},setSelectedShapeConnector(o){return r(n=>Ru(n.surface,n.documentApi,o))},setSelectedShapePicture(o){return r(n=>Tu(n.surface,n.documentApi,o))},setSelectedShapeWordArt(o){return r(n=>ku(n.surface,n.documentApi,o))},setSelectedShapeChildren(o){return r(n=>Eu(n.surface,n.documentApi,o))},setSelectedShapeChild(o,n){return r(i=>Mu(i.surface,i.documentApi,o,n))},appendSelectedShapeChild(o){return r(n=>Iu(n.surface,n.documentApi,o))},appendSelectedShapeChildToParent(o,n){return r(i=>Au(i.surface,i.documentApi,o,n))},moveSelectedShapeChild(o,n={}){return r(i=>Nu(i.surface,i.documentApi,o,n))},removeSelectedShapeChild(o){return r(n=>Du(n.surface,n.documentApi,o))}}}function Ea(e){let t=dn({surface:e.surface,clientX:e.clientX,clientY:e.clientY});if(!t)return null;let r=e.captureSelectionFromState(t.state);return r?{state:t.state,capture:r}:null}function ry(e,t){let r=t.readEffectiveSelection();return{selectionCapture:r,resolvedSelectionCapture:r,stale:!1}}function Ni(e,t,r){if(!r)return{selectionCapture:null,resolvedSelectionCapture:null,stale:!1};let o=t.readSelectionCapture(r);return o?{selectionCapture:r,resolvedSelectionCapture:o,stale:!1}:{selectionCapture:r,resolvedSelectionCapture:null,stale:!0}}function bO(e,t){return e.selectionCapture?Ni(e,t,e.selectionCapture):e.pointSelectionCapture?Ni(e,t,e.pointSelectionCapture):ry(e,t)}function BO(e,t){let r=e.actionSelectionCapture??e.selectionCapture??null;if(!r)return e.pointSelectionCapture?{...Ni(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...ry(e,t),restoreSelection:!1};let o=Ni(e,t,r);return e.pointSelectionCapture===r?{...o,restoreSelection:!1}:o.resolvedSelectionCapture&&!o.resolvedSelectionCapture.selection.empty?{...o,restoreSelection:!0}:e.pointSelectionCapture&&e.pointSelectionCapture!==r?{...Ni(e,t,e.pointSelectionCapture),restoreSelection:!1}:{...o,restoreSelection:!0}}function ju(e,t){let r=t??e.controller;if(!r)throw new Error("Browser context-menu selection policy requires a selection controller.");return{effectiveSelection:bO(e,r),actionSelection:BO(e,r)}}function xO(e=""){return typeof window>"u"?null:window.prompt("Enter link URL",e)}function CO(e,t){let r=new Map(e.map(o=>[o.id,{...o,items:[...o.items]}]));for(let o of t){let n=r.get(o.id);if(n){n.items.push(...o.items);continue}r.set(o.id,{...o,items:[...o.items]})}return[...r.values()]}function PO(e,t){let r=Math.min(e.selection.from,e.selection.to),o=Math.max(e.selection.from,e.selection.to);return(t.segments?.length?t.segments:[t]).every(i=>r<=i.from&&o>=i.to)}function oy(e,t,r){let o=new Set(e.trackedChangeIds),n=t.getState().revisions.filter(i=>o.has(i.id));return n.length===0||n.some(i=>i.relatedKinds.length!==1)?!1:n.some(i=>!PO(r,i))}function RO(e,t,r){if(!t||!e.hasSelection)return r;let o=Math.min(t.selection.from,t.selection.to),n=Math.max(t.selection.from,t.selection.to),i=Math.min(e.selectionStart,e.selectionEnd),s=Math.max(e.selectionStart,e.selectionEnd),a=r?Math.min(r.selection.from,r.selection.to):o,l=r?Math.max(r.selection.from,r.selection.to):n;return(i!==a||s!==l)&&i===o&&s===n?{selection:{...t.selection,from:i,to:s,empty:!1,trackedChangeIds:[...e.trackedChangeIds]}}:r}function ny(e,t,r){let{hasSelection:o,trackedChangeIds:n}=e,i=Ue(t);if(n.length===0)return;let s=t.readEffectiveSelection({includeText:!0}),a=e.actionSelectionCapture??e.selectionCapture,l=t.getState().revisions,c=Rl(s,a,l),d=!c&&a?t.readSelectionCapture(a,{includeText:!0}):null,u=RO(e,a,d),m=d?Rl(s,d,l):c;if(n.length===1&&!o){let p=n[0];if(!p)return;if(r==="accept"){t.acceptRevision(p);return}t.rejectRevision(p);return}if(i&&(r==="accept"&&typeof i.acceptSelectionRevisions=="function"||r==="reject"&&typeof i.rejectSelectionRevisions=="function")&&u&&!u.selection.empty&&oy(e,t,u)){rt(i,u,p=>r==="accept"?p.acceptSelectionRevisions?.()??!1:p.rejectSelectionRevisions?.()??!1,{restoreSelection:!1});return}if(!(u&&!u.selection.empty&&oy(e,t,u)&&(r==="accept"?t.documentApi.review.accept([...n],t.actor??void 0):t.documentApi.review.reject([...n],t.actor??void 0)).changed)){if(n.length===1&&!c&&!m){let p=n[0];if(!p)return;if(r==="accept"){t.acceptRevision(p);return}t.rejectRevision(p);return}if(a&&!c&&!m){if(r==="accept"){t.documentApi.review.accept([...n],t.actor??void 0);return}t.documentApi.review.reject([...n],t.actor??void 0);return}if(r==="accept"){t.acceptSelection();return}t.rejectSelection()}}function Rt(e,t){let r=ju(e,t).actionSelection;if(r.stale)return"Captured selection is no longer available after the document changed. Capture a new text selection or caret before applying inline formatting.";let o=Ue(t);return o?ir({editable:e.isEditable},o.state,r.resolvedSelectionCapture):"Live editor surface is unavailable for inline formatting."}function Vu(e){return e.hasAmbiguousPointReviewTarget?"Right-click hit multiple overlapping review targets. Click a specific change or narrow the selection before accepting or rejecting changes.":e.isEditable?null:"Document is read-only in the current document mode."}function iy(e){return Vu(e)==null}function TO(e,t){let r=Ue(t),{effectiveSelection:o,actionSelection:n}=ju(e,t),i=o.stale?!1:o.resolvedSelectionCapture?.selection.formatting.link??e.activeMarks.includes("link"),s=o.stale?"":o.resolvedSelectionCapture?.selection.formatting.linkHref??"",a=[{id:"formatting",items:[{id:"bold",label:"Bold",action:()=>{n.stale||_t(t,"bold",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"italic",label:"Italic",action:()=>{n.stale||_t(t,"italic",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"underline",label:"Underline",action:()=>{n.stale||_t(t,"underline",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"strikethrough",label:"Strikethrough",action:()=>{n.stale||_t(t,"strike",n.selectionCapture,{restoreSelection:n.restoreSelection})},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)}]},{id:"links",items:[{id:"insert-link",label:i?"Edit link":"Insert link",action:()=>{if(n.stale)return;let l=t.captureSelectionHandleFromCapture(n.selectionCapture);if(!l)return;let c=xO(s);try{c&&t.setLinkFromHandle(l,c,null,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}},enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t)},{id:"clear-link",label:"Clear link",showWhen:()=>i,enabledWhen:()=>Rt(e,t)==null,disabledReason:()=>Rt(e,t),action:()=>{if(n.stale)return;let l=t.captureSelectionHandleFromCapture(n.selectionCapture);if(l)try{t.clearLinkFromHandle(l,{restoreSelection:n.restoreSelection})}finally{t.releaseSelectionHandle(l)}}}]},{id:"history",items:[{id:"undo",label:"Undo",action:()=>{r?.undo()},enabledWhen:l=>l.isEditable&&(r?.canUndo()??!1)},{id:"redo",label:"Redo",action:()=>{r?.redo()},enabledWhen:l=>l.isEditable&&(r?.canRedo()??!1)}]}];return e.trackedChangeIds.length>0&&a.unshift({id:"track-changes",items:[{id:"accept-change",label:e.trackedChangeIds.length===1?"Accept change":"Accept changes",tone:"success",enabledWhen:iy,disabledReason:Vu,action:()=>ny(e,t,"accept")},{id:"reject-change",label:e.trackedChangeIds.length===1?"Reject change":"Reject changes",tone:"danger",enabledWhen:iy,disabledReason:Vu,action:()=>ny(e,t,"reject")}]}),a}function kO(e,t,r){return r?null:typeof e.disabledReason=="function"?e.disabledReason(t)??"Action unavailable.":e.disabledReason??"Action unavailable."}function Ma(e,t,r){let o=r??yS(e.host)??e.controller??null,n=t?.includeDefaultItems===!1||!o?[]:TO(e,o),i=CO(n,t?.customItems??[]);return(t?.menuProvider?.(e,i)??i).map(a=>{let l=a.items.filter(c=>c.showWhen?.(e)??!0).map(c=>{let d=c.enabledWhen?.(e)??!0;return{...c,enabled:d,disabledReason:kO(c,e,d)}});return{id:a.id,label:a.label,items:l}}).filter(a=>a.items.length>0)}function EO(e){let t=e.pointSelection?.capture.selection.from??null,r=Mt(e.pointSelection?.capture,e.revisions),o=!!(e.effectiveSelectionRange&&typeof t=="number"&&t>=e.effectiveSelectionRange.from&&t<=e.effectiveSelectionRange.to);return!!(e.pointSelection&&(!e.effectiveSelectionRange||!o)&&(r.length>0||e.pointSelection.capture.selectionKind==="node"||e.pointSelection.capture.selection.formatting.link||e.pointSelection.capture.selection.empty))}function Lu(e){let t=e.controller.getState(),r=e.actionSelectionCapture&&!e.actionSelectionCapture.selection.empty?{from:Math.min(e.actionSelectionCapture.selection.from,e.actionSelectionCapture.selection.to),to:Math.max(e.actionSelectionCapture.selection.from,e.actionSelectionCapture.selection.to)}:null,o=EO({pointSelection:e.pointSelection,effectiveSelectionRange:r,revisions:t.revisions}),n=o?e.pointSelection?.capture??null:e.effectiveSelection,i=o?e.pointSelection?.capture??null:e.actionSelectionCapture,s=i?.selection??n?.selection??null,a=o?Mt(e.pointSelection?.capture,t.revisions):yt({liveSelection:Ms(t.selection)??{from:0,to:0,empty:!0,trackedChangeIds:t.selection.trackedChangeIds},liveSelectionInfo:t.selectionInfo,revisions:t.revisions,effectiveSelection:i??e.effectiveSelection});return ra(e.controller,e.documentMode,{revisions:t.revisions,reviewActionsEnabled:e.reviewActionsEnabled,selection:n?{from:s?.from??n.selection.from,to:s?.to??n.selection.to,empty:s?.empty??n.selection.empty,trackedChangeIds:a,trackedChangeIdsExplicit:!0}:null,selectionCapture:n,actionSelectionCapture:i,pointSelectionCapture:o?e.pointSelection?.capture??null:null,pointSelectionState:o?e.pointSelection?.state??void 0:void 0,selectionTrackedChangeIds:t.selection.trackedChangeIds,clientX:e.clientX,clientY:e.clientY,selectionState:o?e.pointSelection?.state??void 0:void 0})}function MO(e,t){let r=ve(e).view;if(!r?.state||typeof r.posAtCoords!="function")return null;let o=t.includeText??!0,n=e.readPointSelection({clientX:t.clientX,clientY:t.clientY,includeText:o}),i=e.readEffectiveSelection({includeText:o}),s=e.readEffectiveSelection()??i;if(!n&&!i)return null;let a=e.getState();return Lu({controller:e,documentMode:a.documentMode,reviewActionsEnabled:a.trackChanges.enabled,effectiveSelection:i,actionSelectionCapture:s,pointSelection:n?{capture:n}:null,clientX:t.clientX,clientY:t.clientY})}function IO(e){let{from:t,to:r}=e.selection;if(t>=r)return e;let o=Math.min(r-1,t+Math.max(1,Math.floor((r-t)/2))),n=Z(e,o,o);if(!n)return e;try{return e.apply(e.tr.setSelection(n))}catch{return e}}function sy(e){let{captureSelectionFromState:t,closeContextMenu:r,closeLinkPopover:o,emit:n,getController:i,getDocumentMode:s,getResolvedModules:a,getRuntime:l,setLinkPopover:c}=e;return d=>{let u=a();if(u.links?.enabled===!1)return;let m=d.target?.closest("a[href]");if(!(m instanceof HTMLAnchorElement)){o();return}let p=l(),f=s();d.preventDefault(),d.stopPropagation(),ta(p.surface,m);let g=()=>o(),v=u.links?.popoverResolver?.({host:uo(i()),href:m.getAttribute("href")??"",title:m.getAttribute("title"),target:m.getAttribute("target"),rel:m.getAttribute("rel"),tooltip:m.getAttribute("title"),element:m,clientX:d.clientX,clientY:d.clientY,isAnchorLink:(m.getAttribute("href")??"").startsWith("#"),documentMode:f,position:{left:d.clientX+8,top:d.clientY+12},closePopover:g})??{type:"default"};if(v.type==="none"){o();return}c(jS(uo(i()),p.surface,f,m,d.clientX,d.clientY,v),t(IO(p.surface.state))),r(),n()}}function ay(e){let{closeContextMenu:t,closeLinkPopover:r,emit:o,getController:n,getDocumentMode:i,getResolvedModules:s,readTrackChangesDisplayState:a,captureEffectiveSelectionFromState:l,setContextMenu:c}=e;return d=>{let u=s();if(u.contextMenu?.enabled===!1)return;d.preventDefault(),d.stopPropagation(),r();let m=n(),p=ve(m),f=m.captureEffectiveSelection({includeText:!0}),g=m.captureEffectiveSelection()??f,v=Ea({surface:p,clientX:d.clientX,clientY:d.clientY,captureSelectionFromState:l}),E=a(),R=Lu({controller:m,documentMode:i(),reviewActionsEnabled:E.enabled,effectiveSelection:f,actionSelectionCapture:g,pointSelection:v,clientX:d.clientX,clientY:d.clientY}),S=Ma(R,u.contextMenu,m);if(S.length===0){t();return}c({context:R,sections:S}),o()}}function ly(e){return Ea({surface:e.surface,clientX:e.pointSelectionInput.clientX,clientY:e.pointSelectionInput.clientY,captureSelectionFromState:e.captureSelectionFromState})?.capture??null}function cy(e){let{context:t,readProjectionSnapshot:r,readState:o,selectionCaptureTracker:n}=e,i=(R,S={},P=null)=>{let h=X(t),b=r();return{state:R,surfaceEditable:it(h.surface),surfaceSelectionReliable:GS(h.surface),selectionInput:S,reviewReplacementMode:h.replacementMode,revisions:b.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:b,preservedRangeSelection:P}},s=(R,S={})=>Eh(i(R,S)),a=(R,S={})=>{let P=X(t);return n.track(P.surface,R,s(R,S))},l=(R,S={},P=null)=>{let h=X(t),b=i(R,S,P);return n.track(h.surface,Pi(b),So(b))},c=(R,S={},P=null)=>So(i(R,S,P)),d=(R={})=>{let S=X(t);return S.surface.consumeHistoryChange?.()&&(t.preservedRangeSelection=null),o(),{selectionInput:R,runtime:S,preservedRangeSelection:t.preservedRangeSelection}};return{captureSelection:(R={})=>a(X(t).surface.state,R),captureEffectiveSelection:(R={})=>{let S=d(R);return l(S.runtime.surface.state,S.selectionInput,S.preservedRangeSelection)},readEffectiveSelection:(R={})=>{let S=d(R);return c(S.runtime.surface.state,S.selectionInput,S.preservedRangeSelection)},captureCurrentSelectionFromState:a,captureEffectiveSelectionFromState:l,capturePointSelection:R=>{let S=d(R);return ly({surface:S.runtime.surface,pointSelectionInput:R,captureSelectionFromState:P=>l(P,S.selectionInput,S.preservedRangeSelection)})},readPointSelection:R=>{let S=d(R);return ly({surface:S.runtime.surface,pointSelectionInput:R,captureSelectionFromState:P=>c(P,S.selectionInput,S.preservedRangeSelection)})},readSelectionCapture:(R,S={})=>{if(!R)return null;let P=X(t),h=n.resolveState(P.surface,R);return h?s(h,S):null},resolveSelectionCapture:(R,S={})=>{if(!R)return null;let P=X(t),h=n.resolveState(P.surface,R);return h?n.track(P.surface,h,s(h,S)):null}}}import{documentWideMutationEffect as OO}from"@datalking/begonia-editor-contracts";function Fu(e,t,r={}){return Ta(e,t,r)}function dy(e,t,r=e.replacementMode){if(e.replacementMode===r)return e;let o=e.surface;return e.release(),Fu(o,t,{replacementMode:r,templates:e.templatesAdapter})}function uy(e,t,r){r(e.surface),e.release(),t&&e.surface.destroy()}function my(e){let{canonicalDocument:t,collaborative:r,documentMode:o,nextSurfaceSession:n,sourceRuntime:i,surfaceFactory:s,trackChanges:a}=e;return s({currentSurface:i.surface,collaborative:r??n?.binding,documentStory:i.surface.documentStory,editable:ln(o),initialContent:bt(t,t.copy(t.content)),schema:i.surface.schema,participant:i.surface.participant,trackingEnabled:kr(o,a)})}function py(e){return ht(e)??Wn}function AO(e){return py(e)/100}function NO(e){return e.view?.dom??null}function DO(e){if(e.style)return e.style;let t={};return e.style=t,t}function zu(e,t){let r=NO(e);if(!r)return;let o=py(t),n=String(AO(o)),i=DO(r);r.dataset.aldZoomPercent=String(o),i.zoom=n,i.transformOrigin="top left"}function fy({context:e,templates:t,ownsSurface:r,surfaceFactory:o,allowCollaborativeProjection:n,emit:i,readCurrentDisplayState:s,clearEphemeralOverlays:a,handleLinkClick:l,handleContextMenu:c}){let d=new WeakMap,u=null,m=null,p=()=>{u?.dispose(),u=null,m=null},f=k=>((!u||m!==k)&&(p(),u=yw(()=>e.readModel.canonicalDocument,k,xe(e).documentRuntimeKernel.documentSource),m=k),u),g=k=>{let I=xe(e),F=po(e.readModel),y=F?f(k):I.documentRuntimeKernel.projections;F||p(),e.readModel=pi(e.readModel,y,k)},v=()=>e.readModel.projectedRuntimeBank?.resolveRuntime("tracked").documentApi??null,E=k=>{k.addEventListener("click",l),k.addEventListener("contextmenu",c)},R=k=>{k.removeEventListener("click",l),k.removeEventListener("contextmenu",c)},S=k=>{let I=k.view?.dom;if(!I)return;let F=d.get(k);F&&F!==I&&R(F),E(I),d.set(k,I);let y=s();fc(k,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,y.trackChanges,y.comments)},P=k=>{let I=d.get(k)??k.view?.dom??null;I&&(R(I),d.delete(k))},h=()=>{let k=e.readModel.collaborativeProjection;if(!k){e.readModel=fi(e.readModel);return}let I=xe(e),F=go({surface:k.runtime.surface,nextDocument:I.surface.document,documentApi:k.runtime.documentApi,canonicalReviewApi:v(),canonicalDocument:I.surface.document,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection});a(),P(k.runtime.surface),k.restore(),Ci({surface:I.surface,target:F,documentApi:I.documentApi}),k.runtime.release(),k.runtime.surface.destroy(),e.readModel=bn(fi(e.readModel))},b=k=>{let I=xe(e);if(I.replacementMode!==k){let F=dy(I,x,k);e.readModel=ad(e.readModel,F,k),e.readModel=bn(e.readModel)}g(k),e.readModel.collaborativeProjection&&e.readModel.collaborativeProjection.runtime.replacementMode!==k&&h()},x=()=>{let k=xe(e);A(k);let I=s(),F=Ns(k.surface,e.documentMode,I.trackChanges,n());if(po(e.readModel)&&F){let y=Me(e.readModel.canonicalDocument,k.surface,F);if(!Ar(k.surface.document,y)){e.readModel=ld(e.readModel,k.surface.document);let B=Me(e.readModel.canonicalDocument,k.surface,F);if(!Ar(k.surface.document,B)){Cn({surface:k.surface,nextDocument:B,documentApi:k.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:F,preservedRangeSelection:e.preservedRangeSelection});return}}}else e.readModel=bn(e.readModel);if(e.readModel.collaborativeProjection&&F){e.readModel.collaborativeProjection.sync(e.readModel.canonicalDocument,F)||i();return}e.documentMode==="viewing"&&I.trackChanges.enabled&&I.trackChanges.mode==="review"&&ba({surface:k.surface,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,projectedMode:F})||i()},A=(k=xe(e))=>{let I=ur(k.documentApi.preferences.get());zu(k.surface,I);let F=e.readModel.activeRuntime;F&&F.surface!==k.surface&&zu(F.surface,I)},O=()=>{let k=s();b(k.trackChanges.replacements);let I=xe(e),F=Ns(I.surface,e.documentMode,k.trackChanges,n()),y=ln(e.documentMode),B=kr(e.documentMode,k.trackChanges),M=rn(I.surface)?!1:y;if(e.readModel=bn(e.readModel),I.surface.editable!==M&&I.surface.setEditable(M),I.surface.trackingEnabled!==B&&I.surface.setTrackingEnabled(B),F&&I.surface.collaborative&&o){if(po(e.readModel)&&(Ar(I.surface.document,e.readModel.canonicalDocument)||I.surface.replaceDocument(bt(I.surface.document,e.readModel.canonicalDocument),{origin:"system",intent:"restore-canonical-projection-document",effects:[OO("review")]}),e.readModel=fi(e.readModel),g(k.trackChanges.replacements)),!e.readModel.collaborativeProjection){a();let ae=Me(e.readModel.canonicalDocument,I.surface,F),je=go({surface:I.surface,nextDocument:ae,documentApi:I.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:F,preservedRangeSelection:e.preservedRangeSelection}),me=Qh({sourceRuntime:I,surfaceFactory:o,canonicalDocument:e.readModel.canonicalDocument,projectionMode:F,emit:i,readPreservedRangeSelection:()=>e.preservedRangeSelection,replacementMode:k.trackChanges.replacements});Ci({surface:me.runtime.surface,target:je,documentApi:me.runtime.documentApi}),S(me.runtime.surface),e.readModel=WS(e.readModel,me)}e.readModel.collaborativeProjection?.sync(e.readModel.canonicalDocument,F)}else if(e.readModel.collaborativeProjection&&h(),F){let ae=Me(e.readModel.canonicalDocument,I.surface,F);e.readModel=qS(e.readModel),g(k.trackChanges.replacements),Ar(I.surface.document,ae)||Cn({surface:I.surface,nextDocument:ae,documentApi:I.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:F,preservedRangeSelection:e.preservedRangeSelection})}else po(e.readModel)&&(Ar(I.surface.document,e.readModel.canonicalDocument)||Cn({surface:I.surface,nextDocument:e.readModel.canonicalDocument,documentApi:I.documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:null,preservedRangeSelection:e.preservedRangeSelection}),e.readModel=fi(e.readModel),g(k.trackChanges.replacements));let N=e.readModel.activeRuntime??I;A(I);let L=rn(N.surface)?!1:y;N.surface.editable!==L&&N.surface.setEditable(L),N.surface.trackingEnabled!==B&&N.surface.setTrackingEnabled(B),fc(N.surface,e.documentMode,e.viewportSession.flowMode,e.viewportSession.layoutMode,k.trackChanges,k.comments)},j=k=>{let I=an(e.documentMode,e.resolvedModules.trackChanges).replacements;e.readModel=ad(e.readModel,Fu(k,x,{replacementMode:I,templates:t}),I),e.readModel=bn(e.readModel),g(I),S(k),A()},_=k=>{p(),e.readModel=pi(e.readModel,null),uy(xe(e),k,P),e.readModel=KS(e.readModel)};return{destroyCollaborativeProjection:h,handleSourceRuntimeUpdate:x,applySurfaceDisplayState:O,mountSourceRuntime:j,unmountSourceRuntime:_,createReplacementSurface:(k,I)=>{if(!o)throw new Error("Browser editor cannot reconfigure collaboration without a managed surface factory.");let F=s();return my({surfaceFactory:o,sourceRuntime:xe(e),canonicalDocument:e.readModel.canonicalDocument,documentMode:e.documentMode,trackChanges:F.trackChanges,collaborative:k,nextSurfaceSession:I})},swapSurface:(k,I)=>{let F=s(),y=Ns(k,e.documentMode,F.trackChanges,n()),B=go({surface:X(e).surface,nextDocument:Me(e.readModel.canonicalDocument,k,y),documentApi:X(e).documentApi,canonicalReviewApi:v(),canonicalDocument:e.readModel.canonicalDocument,nextProjectionMode:y,preservedRangeSelection:e.preservedRangeSelection});a(),h(),_(r||!!o),e.collaborationSession=I,j(k),O(),Ci({surface:X(e).surface,target:B,documentApi:X(e).documentApi})}}}function wy(e){let t=e.currentState.context,r=t.selectionCapture??null,o=t.actionSelectionCapture??null,n=t.pointSelectionCapture??null,i=ce(t.trackedChangeIds),s=ce(e.liveSelection.trackedChangeIds),a=ce(e.liveSelectionInfo.activeChangeIds),l=e.resolveSelectionCapture(r),c=n===r?l:e.resolveSelectionCapture(n),d=o===r?l:o===n?c:e.resolveSelectionCapture(o);if(r&&!l||n&&!c)return null;let u=n!=null,m=u?n:r,p=u?n:o,f=u?e.resolveSelectionState(n):null,g=u?null:e.resolveSelectionState(r),v=a.length>0||s.length>0,E=u?c:l,R=!u&&v?d??E:E,P=(!u&&v&&i.length>1?p?.selection??null:null)??R?.selection??E?.selection??null,h=u?Mt(c,e.revisions):yt({liveSelection:e.liveSelection,liveSelectionInfo:e.liveSelectionInfo,revisions:e.revisions,effectiveSelection:R}),b=ra(e.controller,e.documentMode,{revisions:e.revisions,reviewActionsEnabled:e.reviewActionsEnabled,selection:m?{from:P?.from??m.selection.from,to:P?.to??m.selection.to,empty:P?.empty??m.selection.empty,trackedChangeIds:h,trackedChangeIdsExplicit:!0}:null,selectionCapture:m,actionSelectionCapture:p,pointSelectionCapture:u?n:null,pointSelectionState:f??void 0,selectionTrackedChangeIds:s,clientX:t.clientX,clientY:t.clientY,selectionState:f??g??void 0}),x=Ma(b,e.contextMenuOptions,e.controller);return x.length>0?{context:b,sections:x}:null}function gy(e){let t=new Set([e.nextState?.context.selectionCapture,e.nextState?.context.actionSelectionCapture,e.nextState?.context.pointSelectionCapture].filter(o=>o!=null)),r=new Set([e.currentState?.context.selectionCapture,e.currentState?.context.actionSelectionCapture,e.currentState?.context.pointSelectionCapture].filter(o=>o!=null));for(let o of r)o&&!t.has(o)&&e.untrack(o)}function Sy(e){return{releaseContextMenuCaptures(t,r=null){gy({currentState:t,nextState:r,untrack:e})},untrackCapture:e}}function vy(e){return $e({selection:e.surface.describeSelection(),selectionInfo:e.selectionInfo,projectedDocument:We(e.surface),canonicalDocument:e.projectionSnapshot.canonicalDocument,projectedMode:e.projectionSnapshot.projectedMode,revisions:e.revisions})}import{createInvokeBridge as tj}from"@datalking/begonia-document-api/v1";import{createTrackChangesFacade as rj,summarizeReviewTimeline as Ey}from"@datalking/begonia-document-api/review";import{describeCapability as qO,planStepMode as WO,resolvePlanStepFailureReason as KO,resolveUnsupportedPlanStepReason as _O}from"@datalking/begonia-document-api/core";import{documentWideMutationEffect as UO}from"@datalking/begonia-editor-contracts";import{preserveNodeSymbolMetadata as jO}from"@datalking/begonia-engine";import{sameCommittedDocument as VO}from"@datalking/begonia-document-model";import{createDocumentChange as LO,createDocumentChangePublisher as FO}from"@datalking/begonia-editor-contracts";function Hu(e){let t=e,r=0,o=FO();return{readDocument(){return t},replaceDocument(n,i={origin:"api"}){let s=jO(t,n);if(VO(t,s)){t=s;return}let a=r;t=s,r+=1,o.publish(LO(a,r,i))},readProjectedDocument(){return t},documentSource:{readSnapshot(){return{document:t,revision:r}},subscribeDocument(n){return o.subscribe(n)}}}}function zO(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Di(e){let t=e.review.list().map(i=>i.id).filter((i,s,a)=>a.indexOf(i)===s).sort((i,s)=>i.localeCompare(s)),r=e.history.get(),o=e.info.text(),n=JSON.stringify(e.info.json());return{summary:e.info.summary(),revisionIds:t,historyRevision:r.currentRevision,textLength:o.length,documentHash:zO(n)}}function HO(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function qu(e,t){return e.summary.blockCount===t.summary.blockCount&&e.summary.wordCount===t.summary.wordCount&&e.summary.revisionCount===t.summary.revisionCount&&e.summary.footnoteCount===t.summary.footnoteCount&&e.summary.endnoteCount===t.summary.endnoteCount&&e.summary.commentCount===t.summary.commentCount&&e.summary.bookmarkCount===t.summary.bookmarkCount&&HO(e.revisionIds,t.revisionIds)&&e.historyRevision===t.historyRevision&&e.textLength===t.textLength&&e.documentHash===t.documentHash}function Wu(e,t){return t.filter(r=>!e.includes(r))}function hy(e){return e==="sequential"?"sequential":"all_or_nothing"}function Oi(e){return e??null}import{createDocumentRuntimeKernel as yy}from"@datalking/begonia-document-api/v1";function ZO(e,t){let r=Hu(t),o=yy(r,{review:{replacementMode:e.replacementMode}});return{surface:{editable:it(e.surface),get document(){return r.readProjectedDocument()}},documentRuntimeKernel:o,documentService:o.service,documentApi:o.api,replacementMode:e.replacementMode}}function GO(e,t){let r=ZO(e,e.surface.document),o=t.canonicalDocument??e.surface.document,n=Hu(o),i=yy(n,{review:{replacementMode:r.replacementMode}}),s=pi({...ia(o,r.replacementMode),sourceRuntime:r,activeRuntime:r},i.projections,r.replacementMode);return{detachedRuntime:r,projectionSnapshot:Or(s,t.projectedMode)}}function XO(e){let t=e.getRuntime(),r=e.readCurrentDisplayState(),o=e.readProjectionSnapshot(),{detachedRuntime:n,projectionSnapshot:i}=GO(t,o);return{detachedRuntime:n,api:e.createDocumentApi({getRuntime:()=>n,readProjectionSnapshot:()=>i,readCurrentDisplayState:()=>r})}}function by(e){let t=o=>{let n=XO(e),{api:i}=n,s=hy(o.commitMode),a=Di(i),l=i.info().revision;if(o.expectedRevision!=null&&o.expectedRevision!==l)return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:!1,changed:!1,committed:!1,commitMode:s,stoppedEarly:!0,error:`Document revision mismatch. Expected ${o.expectedRevision} but found ${l}.`,before:a,after:a,steps:[]}};if(o.expectedDocumentHash&&o.expectedDocumentHash!==a.documentHash)return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:!1,changed:!1,committed:!1,commitMode:s,stoppedEarly:!0,error:`Document hash mismatch. Expected ${o.expectedDocumentHash} but found ${a.documentHash}.`,before:a,after:a,steps:[]}};let c=[],d=!0,u=!1;for(let[p,f]of o.steps.entries()){let g=qO(f.operationId),v=Di(i),E=Oi(f.label),R=_O(f.operationId,g),S=WO(g);if(R){if(d=!1,c.push({index:p,label:E,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:S,ok:!1,changed:!1,error:R,revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}let P=i.operations.invokeDynamic({operationId:f.operationId,input:f.input,options:f.options}),h=Di(i),b=S==="write"&&!qu(v,h),x=P.ok?KO(P.value):null;if(!P.ok||x){if(d=!1,c.push({index:p,label:E,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:S,ok:!1,changed:!1,error:P.ok?x:P.error.message,...P.ok?{result:P.value}:{},revisionIdsCreated:[],revisionIdsRemoved:[]}),o.stopOnFailure!==!1){u=!0;break}continue}c.push({index:p,label:E,operationId:f.operationId,resolvedOperationId:g?.id??null,mode:S,ok:!0,changed:b,result:P.value,revisionIdsCreated:Wu(v.revisionIds,h.revisionIds),revisionIdsRemoved:Wu(h.revisionIds,v.revisionIds)})}let m=Di(i);return{detachedRuntime:n.detachedRuntime,receipt:{label:Oi(o.label),preview:!0,executable:d,changed:!qu(a,m),committed:!1,commitMode:s,stoppedEarly:u,before:a,after:m,steps:c}}};return{preview:o=>t(o).receipt,apply(o){let{detachedRuntime:n,receipt:i}=t(o),s=i.changed&&(i.commitMode==="sequential"||i.executable);return s&&e.getRuntime().surface.replaceDocument(n.surface.document,{origin:"api",intent:"commit-document-operation-plan",effects:[UO("structure")]}),{...i,preview:!1,committed:s}}}}function By(e){let t=e.subscribeStateChange??e.subscribeRawSelectionChange??null;return{onChange(r){if(!t)return()=>{};let o=!1,n=!1,i=An(e.readSelectionInfo()),s=()=>{if(n=!1,o)return;let d=e.readSelectionInfo(),u=An(d);u!==i&&(i=u,r(d))},a=()=>{o||n||(n=!0,queueMicrotask(s))},l;try{l=t(a)}catch(d){throw o=!0,d}let c=!1;return()=>{c||(c=!0,o=!0,l())}}}}function $O(e){let t=e.surface.view;return!!(t?.state&&typeof t.dispatch=="function")}function YO(e,t){let r=[...e??[]],o=[...t??[]];return r.length===o.length&&r.every((n,i)=>n===o[i])}function JO(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function xy(e){return e?.kind==="text"?e.segments.length:0}function QO(e){let t=e.members?.length?e.members:null;return t?t.every(r=>(r.text?.length??0)===0&&r.target?.nodeType!=="text"):(e.text?.length??0)===0&&e.target?.nodeType!=="text"}function Cy(e,t){return le([...e.activeChangeIds,...e.selection.trackedChangeIds??[]],t)}function Py(e,t){if(e.length===0)return!1;let r=le(e,t);if(r.length===0)return!1;let o=new Map(t.map(n=>[n.id,n]));return r.every(n=>{let i=o.get(n);return i?QO(i):!1})}function Ry(e){let{getRuntime:t,readProjectionSnapshot:r,readCurrentDisplayState:o,readPresentationComments:n,readCanonicalReviewApi:i,readEffectiveSelection:s,captureEffectiveSelection:a}=e,l=(d,u={})=>{let m=o().comments.enabled?n().list({includeResolved:o().comments.showResolved,enforceVisibilityPolicy:o().comments.enforceVisibilityPolicy,visibility:o().comments.visibility,sort:"desc"}):[],p=s?.(u)??a?.(u)??null,f=t(),g=$O(f),v=f.surface.describeSelection(),E=K(f.surface.state.selection)?"node":"text",R=i().review.list(),S=r(),P=$e({selection:v,selectionInfo:d,projectedDocument:We(f.surface),canonicalDocument:S.canonicalDocument,projectedMode:S.projectedMode,revisions:R}),h=ki(P.selectionInfo,Ti({activeCommentIds:P.selectionInfo.activeCommentIds,selection:v,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),b=ko(f.surface.state,h,E);if(p){let x=yt({liveSelection:P.selection,liveSelectionInfo:h,revisions:R,effectiveSelection:p}),A=Cy(p,R),O=cc({liveSelection:P.selection,liveActiveChangeIds:h.activeChangeIds,effectiveSelection:p}),j=ki(Rr(p,A),Ti({activeCommentIds:p.activeCommentIds,selection:p.selection,projectedDocument:We(f.surface),comments:m,readTarget:n().target})),_=Py(A,R),V=!_&&p.projectedMode!=null,de=!_&&xy(p.selectionTarget)>xy(b.target),k=!_&&((j.text??null)!==(b.text??null)||!JO(j.target,b.target)||!YO(j.activeMarks,b.activeMarks));return P.selection.empty&&!p.selection.empty&&(p.activeCommentIds.length>0||A.length>0)&&(p.activeCommentIds.length>0||V||de||k||!g)?j:g?!O&&P.selection.empty&&!ar(h.activeChangeIds,x)?{...b,activeChangeIds:[...x]}:b:j}return b};return{resolvePublicSelectionInfo:l,readPublicSelectionInfo:(d={includeText:!0})=>{let u=t();return l(Dr(u.surface,d,u.replacementMode),d)}}}function ej(e){return()=>W(e)}function Ty(e,t,r,o,n){if(e==null||typeof e!="object"&&typeof e!="function"||typeof e=="function"||t!==""&&!o.deniedMemberPaths.has(t)&&!o.descendantMemberPaths.has(t))return e;let i=e,s=n.get(i)?.get(t);if(s)return s;let a=new Proxy(e,{get(c,d){let u=Reflect.get(c,d,c);if(typeof d!="string")return u;let m=Reflect.getOwnPropertyDescriptor(c,d);if(m&&"value"in m&&!m.configurable&&!m.writable)return m.value;let p=t?`${t}.${d}`:d;return o.deniedMemberPaths.has(p)?typeof u=="function"?ej(r):u:o.descendantMemberPaths.has(p)?Ty(u,p,r,o,n):u},apply(c,d,u){return o.deniedMemberPaths.has(t)?W(r):Reflect.apply(c,c,u)}}),l=n.get(i)??new Map;return l.set(t,a),n.set(i,l),a}function ky(e,t){return Ty(e,"",t,Lh(e),new WeakMap)}function Ot(e,t){return Jt(e.surface)??(t.comments.readOnly?"Comments are read-only in the current document mode.":null)}function My(e,t){return t.comments.allowResolve?Ot(e,t):"Comment resolution is disabled."}function Ku(e){let{getRuntime:t,readCurrentDisplayState:r,readProjectionSnapshot:o}=e,{readEffectiveSelection:n,captureEffectiveSelection:i,subscribeStateChange:s}=e,a=new WeakMap,l=()=>o(),c=()=>Pa(l()),d=()=>c().presentationReadApi,u=()=>c().canonicalReviewApi,m=()=>c().writableRuntimeApi,p=()=>Jt(t().surface),f=()=>it(t().surface),g=y=>{let B=l();return B.projectedMode==null||B.projectedRuntimeBank==null?null:y===B.projectedMode?B.presentationReadRuntime.documentApi:y==="tracked"?B.canonicalReviewRuntime.documentApi:B.projectedRuntimeBank.resolveRuntime(y).documentApi},v=()=>{let y=m(),B=p();if(!B)return y;let M=a.get(y)?.get(B);if(M)return M;let N=ky(y,B),L=a.get(y)??new Map;return L.set(B,N),a.set(y,L),N},E=qh({readPresentationApi:d,readWritableApi:v,readProjectedApiForMode:g}),R=by({getRuntime:t,readProjectionSnapshot:o,readCurrentDisplayState:r,createDocumentApi:Ku}),S=()=>d().comments,{readPublicSelectionInfo:P}=Ry({getRuntime:t,readProjectionSnapshot:o,readCurrentDisplayState:r,readPresentationComments:S,readCanonicalReviewApi:u,readEffectiveSelection:n,captureEffectiveSelection:i}),h=By({readSelectionInfo:()=>P({includeText:!0}),subscribeRawSelectionChange:y=>t().documentApi.selection.onChange(()=>y()),subscribeStateChange:s}),b=y=>{let B=n?.()??i?.()??null,M=m(),N=y(M);return N.changed&&mi({capture:B,surface:t().surface,comments:M.comments}),N},x=()=>m().comments,A={list:(y={})=>S().list(y),get:(y,B={})=>S().get(y,B),activity:(y,B={})=>S().activity(y,B),activityTimeline:(y,B={})=>S().activityTimeline(y,B),activitySummary:(y,B={})=>S().activitySummary(y,B),activityEntry:(y,B,M={})=>S().activityEntry(y,B,M),target:(y,B={})=>S().target(y,B),entryTarget:(y,B,M={})=>S().entryTarget(y,B,M),targetSnapshot:(y,B={})=>S().targetSnapshot(y,B),create:y=>{let B=Ot(t(),r());return B?W(B):x().create(y)},permissions:(y,B)=>{let M=S().permissions(y,B);return r().comments.readOnly?M&&Mi(M,r().comments):M},entryPermissions:(y,B,M)=>{let N=S().entryPermissions(y,B,M);return r().comments.readOnly?Uh(N):N},move:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().move(y,B,M)},upsert:y=>{let B=Ot(t(),r());return B?W(B):x().upsert(y)},reply:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().reply(y,B,M)},patch:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().patch(y,B,M)},update:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().update(y,B,M)},updateEntry:(y,B,M,N)=>{let L=Ot(t(),r());return L?W(L):x().updateEntry(y,B,M,N)},resolve:(y,B)=>{let M=My(t(),r());return M?W(M):x().resolve(y,B)},reopen:(y,B)=>{let M=My(t(),r());return M?W(M):x().reopen(y,B)},replaceTargetTextTracked:(y,B,M,N={})=>{let L=Ot(t(),r());return L?W(L):x().replaceTargetTextTracked(y,B,M,N)},removeEntry:(y,B,M)=>{let N=Ot(t(),r());return N?W(N):x().removeEntry(y,B,M)},remove:(y,B)=>{let M=Ot(t(),r());return M?W(M):x().remove(y,B)}},O={query:(y,B={})=>d().search.query(y,B),next:(y,B=null,M={})=>d().search.next(y,B,M),previous:(y,B=null,M={})=>d().search.previous(y,B,M),replace:(y,B,M,N={})=>v().search.replace(y,B,M,N),replaceTracked:(y,B,M,N,L={},ae={})=>v().search.replaceTracked(y,B,M,N,L,ae),replaceAll:(y,B,M={})=>v().search.replaceAll(y,B,M),replaceAllTracked:(y,B,M,N={},L={})=>v().search.replaceAllTracked(y,B,M,N,L),clear:()=>d().search.clear()},j={list:(y={})=>d().proofing.list(y),ignore:y=>v().proofing.ignore(y),acceptSuggestion:y=>v().proofing.acceptSuggestion(y),replaceTracked:(y,B,M,N={})=>v().proofing.replaceTracked(y,B,M,N)},_={current:(y={})=>P(y),onChange:y=>h.onChange(y)},V={list:y=>u().review.list(y),decisionActivity:(y={})=>u().review.decisionActivity(y),decisionActivityEntry:(y,B={})=>u().review.decisionActivityEntry(y,B),decisionActivitySummary:(y={})=>u().review.decisionActivitySummary(y),decisionActivityByObject:(y,B={})=>u().review.decisionActivityByObject(y,B),decisionActivitySummaryByObject:(y,B={})=>u().review.decisionActivitySummaryByObject(y,B),timeline:(y={})=>{let B=r(),M=l();return Ai(Ra({projectionSnapshot:M,reviewOptions:y}),f(),B.comments)},timelineSummary:(y={})=>Ey(V.timeline(y)),timelineByObject:(y,B={})=>{let M=r(),N=l();return Ai(_h({projectionSnapshot:N,objectId:y,reviewOptions:B}),f(),M.comments)},timelineSummaryByObject:(y,B={})=>Ey(V.timelineByObject(y,B)),permissions:(y,B)=>{let M=u().review.permissions(y,B);return p()?M.map(Ii):M},accept:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.accept(y,B)),reject:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.reject(y,B)),acceptMatching:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.acceptMatching(y,B)),rejectMatching:(y,B)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(M=>M.review.rejectMatching(y,B)),decideRange:(y,B,M)=>p()?W(p()??"Tracked changes are read-only in the current document mode."):b(N=>N.review.decideRange(y,B,M))},de=rj({service:null,review:V}),k=Object.assign(((y={})=>{let B=d().info,M=V.list().length,N=B(y);return{...N,counts:{...N.counts,trackedChanges:M}}}),{summary:()=>({...d().info.summary(),revisionCount:V.list().length}),outline:()=>d().info.outline(),json:()=>d().info.json(),text:()=>d().info.text(),html:(y={})=>(g(y.revisionProjection??l().projectedMode??"tracked")??d()).info.html(y),markdown:(y={})=>(g(y.revisionProjection??l().projectedMode??"tracked")??d()).info.markdown(y)}),I,F=tj(()=>new Proxy({},{get(y,B,M){return B==="service"?t().documentService:Reflect.get(I,B,M)}}));return I=new Proxy({},{get(y,B,M){let N=l();return B==="comments"?A:B==="review"?V:B==="search"?O:B==="proofing"?j:B==="selection"?_:B==="trackChanges"?de:B==="info"&&N.canonicalDocument!=null&&N.projectedMode!=null?k:B==="operations"?F:B==="plans"&&N.canonicalDocument!=null&&N.projectedMode!=null?R:typeof B=="string"?E(B):Reflect.get(d(),B,M)}}),I}import{emitClonedOrderedListeners as aj,throwOrderedListenerErrors as lj}from"@datalking/begonia-layout-renderer/core";function oj(e){return e==null?e:structuredClone(e)}function nj(e){return{empty:e.empty,target:null,activeMarks:[],activeCommentIds:[],activeChangeIds:[...e.trackedChangeIds]}}function _u(e){let t=structuredClone({...e.selection,trackedChangeIds:le(e.selection.trackedChangeIds,e.revisions)}),r=e.selectionInfo,o=r?structuredClone({...r,activeChangeIds:le(r.activeChangeIds,e.revisions)}):nj(t),n=ro({revisions:e.revisions,selectionInfo:o}),i=sn({comments:e.comments,selectionInfo:o,explicitActiveCommentId:e.activeCommentId,explicitActiveCommentIds:e.activeCommentIds});return{toolbar:structuredClone(e.toolbar),comments:structuredClone(e.comments),commentPermissions:structuredClone(e.commentPermissions),activeCommentId:i.activeCommentId,activeCommentIds:structuredClone(i.activeCommentIds),revisions:structuredClone(e.revisions),activeRevisionId:e.activeRevisionId??n.activeRevisionId,activeRevisionIds:structuredClone(e.activeRevisionIds??n.activeRevisionIds),reviewPermissions:structuredClone(e.reviewPermissions),reviewTimeline:structuredClone(e.reviewTimeline),reviewTimelineSummary:oj(e.reviewTimelineSummary),search:structuredClone(e.search),proofing:structuredClone(e.proofing),advancedOoxml:structuredClone(e.advancedOoxml),selectionInfo:o,selection:t,editable:e.editable,documentMode:e.documentMode,flowMode:e.flowMode,layoutMode:e.layoutMode,preferredPaginatedLayoutMode:e.preferredPaginatedLayoutMode,zoomPercent:e.zoomPercent,zoom:structuredClone(e.zoom),viewport:re(e.viewport),viewportRequestKey:e.viewportRequestKey,previewNavigationRequest:be(e.previewNavigationRequest),trackChanges:structuredClone(e.trackChanges),commentsDisplay:structuredClone(e.commentsDisplay),collaboration:structuredClone(e.collaboration),linkPopover:xa(e.linkPopover),contextMenu:Ca(e.contextMenu)}}function ij(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function sj(e){let t=e.view.state.doc,r=Math.max(1,t.content.size);return Math.max(1,Math.min(e.view.state.selection.head,r))}function Ia(e){if(e.allowSelectionInViewMode||e.documentMode!=="viewing"||!ij(e.surface)||e.surface.view.state.selection.empty)return!1;let t=sj(e.surface),r=e.surface.view.state.selection;if(r.from===t&&r.to===t)return!1;let o=Z(e.surface.view.state,t,t);return o?(e.surface.view.dispatch(e.surface.view.state.tr.setSelection(o)),!0):!1}function Iy(e){return!!(e.view?.state&&typeof e.view.dispatch=="function")}function Ay(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Ny({context:e,allowCollaborativeProjection:t,releaseContextMenuCaptures:r}){let o=!1,n=0,i=!1,s=0,a=!1,l=()=>e.collaborationSession?{...e.collaborationSession.getSnapshot(),mode:"session",reconfigurable:e.reconfigurable}:{collaborative:!1,mode:"none",reconfigurable:e.reconfigurable,providerName:null,roomId:null,status:"disconnected",connected:!1,synced:null,awarenessClientCount:null,message:null},c=()=>{if(e.resolvedModules.trackChanges?.enabled===!1)return;let b=xe(e);if(rn(b.surface))return;let x=b.surface.editable?b.surface.trackingEnabled?"suggesting":"editing":"viewing";x!==e.documentMode&&(e.documentMode=x)},d=()=>IS(xe(e).surface,e.documentMode,e.resolvedModules,t()),u=()=>e.readModel.sourceRuntime?Qs(e.readModel.sourceRuntime.surface,e.collaborationSession,e.reconfigurable):l(),m=()=>{c(),e.normalizeOverlayState?.();let b=xe(e),x=X(e);x.surface.consumeHistoryChange?.()&&(e.preservedRangeSelection=null);let A=d(),O=ur(b.documentApi.preferences.get()),j=ca(e,O),_=Or(e.readModel,A.trackChanges.mode),V=Xh({runtime:x,projectionSnapshot:_,preservedRangeSelection:e.preservedRangeSelection,actor:e.currentActor,linkPopover:e.linkPopover,contextMenu:e.contextMenu,search:{query:e.searchQuery,options:e.searchOptions,activeHitId:e.activeSearchHitId},collaboration:u(),documentMode:e.documentMode,zoomPercent:O,zoom:j,viewportSession:e.viewportSession,display:{trackChanges:A.trackChanges,comments:A.comments},activeCommentId:e.activeCommentId,activeRevisionId:e.activeRevisionId,activeRevisionIds:e.activeRevisionIds}),de=uc({comments:V.comments,selectionInfo:V.selectionInfo});if(de.activeCommentId)e.activeCommentId!==de.activeCommentId&&(e.activeCommentId=de.activeCommentId);else if(e.activeCommentId!=null){let B=mc({comments:V.comments,selectionInfo:V.selectionInfo,explicitActiveCommentId:e.activeCommentId}),M=B.length===1?B[0]??null:null;e.activeCommentId!==M&&(e.activeCommentId=M)}let k=ro({revisions:V.revisions,selectionInfo:V.selectionInfo});if(k.activeRevisionIds.length>0)(e.activeRevisionId!==k.activeRevisionId||!Ay(e.activeRevisionIds,k.activeRevisionIds))&&(e.activeRevisionId=k.activeRevisionId,e.activeRevisionIds=[...k.activeRevisionIds]);else if(e.activeRevisionIds.length>0&&V.activeRevisionIds){let B=new Set(V.revisions.map(N=>N.id)),M=e.activeRevisionIds.filter(N=>B.has(N));Ay(e.activeRevisionIds,M)?M.length===0&&e.activeRevisionId!=null&&(e.activeRevisionId=null):(e.activeRevisionIds=[...M],e.activeRevisionId=M.length===1?M[0]??null:null)}let I=So({state:x.surface.state,surfaceEditable:x.surface.editable,surfaceSelectionReliable:Iy(x.surface),selectionInput:{includeText:!0},reviewReplacementMode:x.replacementMode,revisions:_.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:_,preservedRangeSelection:e.preservedRangeSelection}),F=!!(_.projectedMode!=null&&I&&V.selection.empty&&!I.empty&&e.preservedRangeSelection?.projectedMode!==_.projectedMode),y=I&&F?{selection:I.selection,selectionInfo:Rr(I),selectionNodeSelectionTarget:I.nodeSelectionTarget}:{selection:x.surface.describeSelection(),selectionInfo:V.selectionInfo,selectionNodeSelectionTarget:V.selectionNodeSelectionTarget??null};return e.preservedRangeSelection=Fd({selection:y.selection,selectionInfo:y.selectionInfo,selectionNodeSelectionTarget:y.selectionNodeSelectionTarget??null,previous:e.preservedRangeSelection,state:x.surface.state,surfaceSelectionReliable:Iy(x.surface),reviewReplacementMode:x.replacementMode,revisions:_.canonicalReviewRuntime.documentApi.review.list(),projectionSnapshot:_}),e.activeSearchHitId=V.search.activeHitId,V},p=()=>_u(m()),f=()=>e.readModel.activeRuntime?Ia({surface:e.readModel.activeRuntime.surface,documentMode:e.documentMode,allowSelectionInViewMode:e.allowSelectionInViewMode}):!1,g=()=>{let b=null;do{if(i=!1,f()){i=!0;continue}b=m()}while(i);if(b==null)throw new Error("Browser editor state emission could not stabilize.");return b},v=()=>{if(s>0&&!o){a=!0;return}if(o){i=!0;return}o=!0;let b=[];try{do{let x=g();n+=1,b.push(...aj(e.listeners,x,_u))}while(i)}finally{o=!1,i=!1}lj(b,"Browser editor state listeners failed.")};return{syncDocumentModeFromSurface:c,readCurrentDisplayState:d,readCollaboration:u,readState:p,getEmissionVersion:()=>n,emit:v,runBatchedEmit:b=>{s+=1;try{return b()}finally{s-=1,s===0&&a&&(a=!1,v())}},closeLinkPopover:()=>{e.linkPopover&&(e.linkPopover=null,v())},closeContextMenu:()=>{e.contextMenu&&(r?.(),e.contextMenu=null,v())},clearEphemeralOverlays:()=>{r?.(),e.linkPopover=null,e.contextMenu=null},subscribeCollaborationSession:b=>{e.unsubscribeCollaborationSession?.(),e.unsubscribeCollaborationSession=b?.subscribe?b.subscribe(()=>v()):null}}}function Dy(e){let t=null,r=null,o=!1,n=s=>{r&&r!==s&&e.untrackCapture(r),r=s},i=()=>{n(null)};return{getSelectionCapture(){return r},sync(s){return!t||!r||!o||s(r)?.selection.formatting.link?!1:(t=null,i(),o=!1,e.setState(null),!0)},set(s,a=r){let l=s?a??null:null;e.setState(s),n(l),o=!!(s&&l?.selection.formatting.link),t=s??null},close(){t=null,i(),o=!1,e.closeState()},clearOverlays(){t=null,i(),o=!1,e.clearOverlayState()}}}import{createSelectionTrackingBookmark as Gu}from"@datalking/begonia-engine";import{readSyntheticSideStoryDocOriginPath as uj}from"@datalking/begonia-doc-service/v1";function cj(e){return typeof e.capture.text=="string"&&!e.selection.empty&&ge(e.surface.state.doc,e.surface.state.schema,e.selection)!==e.capture.text}function dj(e){let t=Mt(e.capture);return e.capture.selectionKind!=="text"||t.length===0?!1:!e.selection||e.selection.empty!==e.capture.selection.empty?!0:cj({surface:e.surface,selection:e.selection,capture:e.capture})}function Oy(e){return dj(e)?e.resolveSemanticSelection():e.selection}var mj=256;function Vy(e,t){if(!e||!t.docChanged)return e;try{return e.map(t.mapping)}catch{return null}}function Ly(e,t,r){for(let o of r.captures)t.add(o),e.delete(o);r.captures.clear()}function jy(e,t){for(;t.captures.size>mj;){let r=t.captures.values().next().value;if(!r)return;t.captures.delete(r),e.delete(r)}}function pj(e){return typeof e.view?.dispatch=="function"&&typeof e.subscribe=="function"}function fj(e,t,r){if(r.docChanged){e.pendingDispatchDocChange=!0;for(let o of e.captures){let n=t.get(o);if(!n){e.captures.delete(o);continue}n.bookmark=Vy(n.bookmark,r)}}}function Fy(e,t){let r=e.trackedView;if(!r){e.restoreDispatch=()=>{};return}if(e.usesAppliedTransactionStream){e.restoreDispatch=()=>{};return}let o=r.dispatch.bind(r),n=(i=>{if(!i.docChanged)return o(i);let s=r.state.doc,a=e.pendingDispatchDocChange,l=new Map;e.pendingDispatchDocChange=!0;for(let c of e.captures){let d=t.get(c);if(!d){e.captures.delete(c);continue}l.set(c,{tracked:d,bookmark:d.bookmark}),d.bookmark=Vy(d.bookmark,i)}try{return o(i)}catch(c){if(r.state.doc===s){e.pendingDispatchDocChange=a;for(let[d,u]of l)t.get(d)===u.tracked&&(u.tracked.bookmark=u.bookmark)}throw c}});r.dispatch=n,e.restoreDispatch=()=>{r.dispatch===n&&(r.dispatch=o)}}function zy(e,t,r){e.trackedView!==r.view&&(e.restoreDispatch(),e.trackedView=r.view,Fy(e,t))}function Uu(e,t,r,o,n={}){if(!pj(o))return null;let i=e.get(o);if(i)return zy(i,t,o),i;let s=o.subscribeTransactions?.bind(o)??null,a={captures:new Set,lastDocument:o.document,pendingDispatchDocChange:!1,programmaticDocChangeDepth:0,trackedView:o.view,usesAppliedTransactionStream:s!=null,restoreDispatch(){},unsubscribe(){},unsubscribeTransactions(){}};return s&&(a.unsubscribeTransactions=s(l=>{fj(a,t,l)})),Fy(a,t),a.unsubscribe=o.subscribe(()=>{let l=o.document;if(l!==a.lastDocument){if(!a.pendingDispatchDocChange)if(a.programmaticDocChangeDepth===0)Ly(t,r,a);else{let c=[];for(let d of a.captures){let u=t.get(d);if(!u){c.push(d);continue}let m=n.resolveProgrammaticSelection?.(o,d)??cr(o,d);if(!m){c.push(d);continue}u.bookmark=Gu(m)}for(let d of c)r.add(d),t.delete(d),a.captures.delete(d)}a.pendingDispatchDocChange=!1,a.lastDocument=l}}),e.set(o,a),a}function Zu(e,t,r,o,n=!0){let i=e.get(o);i&&(i.unsubscribe(),i.unsubscribeTransactions(),i.restoreDispatch(),i.trackedView=null,n?Ly(t,r,i):i.captures.clear(),e.delete(o))}function wj(e,t,r,o={}){let n=qy(e,t,r,o);return n?Ht(n):null}function gj(e,t){if(!t.bookmark)return null;try{let r=t.bookmark.resolve(e.state.doc);return!r||!t.empty&&r.empty?null:r}catch{return null}}function Hy(e,t,r,o={}){let n=gj(e,r),i=n?at(e.state,n):null,s=Oy({surface:e,selection:i,capture:t,resolveSemanticSelection:()=>o.resolveProgrammaticSelection?.(e,t)??cr(e,t)});if(s===i)return i;if(!s)return null;let a=at(e.state,s);return a?i&&qt(i,a)?i:(r.bookmark=Gu(a),a):null}function qy(e,t,r,o={}){let n=Hy(e,t,r,o);return n?Al(e.state,n):null}function Wy(e={}){let t=new Map,r=new Map,o=new WeakMap,n=new WeakSet,i=(a,l)=>{if(n.has(l))return!1;let c=o.get(l),d=uj(a.document);return bl(l.storyOriginPath,d)?l.documentIdentity!=null?l.documentIdentity===jn(a.document)&&l.documentHash===Oo(a.document):c?c.surface===a&&c.document===a.document:l.storyOriginPath!=null&&bl(l.storyOriginPath,d):!1},s=a=>{Zu(t,r,n,a)};return{clear(){for(let a of[...t.keys()])s(a);r.clear()},isTracked(a,l){return!l||n.has(l)?!1:r.get(l)?.surface===a},releaseSurface:s,transferSurface(a,l){if(a===l)return!0;let c=t.get(a);if(!c||c.captures.size===0)return Zu(t,r,n,a,!1),!0;let d=Uu(t,r,n,l,e);if(!d)return!1;for(let u of c.captures){let m=r.get(u);m&&(m.surface=l,o.set(u,{surface:l,document:l.document}),n.delete(u),d.captures.delete(u),d.captures.add(u))}return jy(r,d),Zu(t,r,n,a,!1),!0},runWithProgrammaticDocumentChange(a,l){let c=Uu(t,r,n,a,e);if(!c)return l();c.programmaticDocChangeDepth+=1;try{return l()}finally{c.programmaticDocChangeDepth>0&&(c.programmaticDocChangeDepth-=1),zy(c,r,a)}},untrack(a){if(!a)return;let l=r.get(a);l&&(t.get(l.surface)?.captures.delete(a),r.delete(a))},resolveSelection(a,l){if(!l)return null;let c=r.get(l);return!c||c.surface!==a?i(a,l)?cr(a,l):null:Hy(a,l,c,e)},resolveState(a,l){if(!l)return null;let c=r.get(l);if(!c||c.surface!==a){if(!i(a,l))return null;let d=cr(a,l);return d?Al(a.state,d):null}return qy(a,l,c,e)},resolveTarget(a,l){if(!l)return null;let c=l.target??l.selectionTarget;if(!c)return null;let d=r.get(l);return!d||d.surface!==a?i(a,l)?c:null:wj(a,l,d,e)},track(a,l,c){if(!c)return c;o.set(c,{surface:a,document:a.document}),n.delete(c);let d=Uu(t,r,n,a,e);if(!d)return c;let u=r.get(c);return u&&u.surface!==a&&t.get(u.surface)?.captures.delete(c),r.set(c,{surface:a,bookmark:Gu(l.selection),empty:c.selection.empty}),d.captures.delete(c),d.captures.add(c),jy(r,d),c}}}function Ky(e,t){return Object.freeze({id:e,kind:t})}function _y(e){let{captureCurrentSelectionFromState:t,getSurface:r,readSelectionCapture:o,selectionCaptureTracker:n}=e,i=new WeakMap,s=new Map,a=1,l=(c,d)=>{if(!d)return null;let u=Ky(a,c);return a+=1,i.set(u,d),s.set(d,(s.get(d)??0)+1),u};return{clear(){for(let c of s.keys())n.untrack(c);i=new WeakMap,s=new Map},capture:l,captureFromCapture(c){if(!c)return null;let d=n.resolveState(r(),c);return d?l("current",t(d)):null},resolve(c,d={}){return c?o(i.get(c)??null,d):null},peek(c){return c?i.get(c)??null:null},release(c){if(!c)return;let d=i.get(c)??null;if(i.delete(c),d){let u=(s.get(d)??0)-1;u>0?s.set(d,u):(s.delete(d),n.untrack(d))}}}}function Uy(e,t,r){return t.resolveSelection(e(),r)}function Zy(e){let{getSurface:t,selectionCaptureTracker:r,captureSelection:o,captureEffectiveSelection:n,captureCurrentSelectionFromState:i,readSelectionCapture:s}=e,a=_y({getSurface:t,selectionCaptureTracker:r,captureCurrentSelectionFromState:i,readSelectionCapture:s});return{clearDeferredSelectionState(){r.clear(),a.clear()},captureSelectionHandle(l={}){return a.capture("current",o(l))},captureEffectiveSelectionHandle(l={}){return a.capture("effective",n(l))},captureSelectionHandleFromCapture(l){return a.captureFromCapture(l)},resolveSelectionHandle(l,c={}){return a.resolve(l,c)},restoreSelectionCapture(l,c={}){return Tl({surface:t(),capture:l,resolveSelection:d=>Uy(t,r,d),options:{...c,validateDocumentIdentity:!1}})},restoreSelectionHandle(l,c={}){return Tl({surface:t(),capture:a.peek(l),resolveSelection:d=>Uy(t,r,d),options:{...c,validateText:!1,validateDocumentIdentity:!1}})},releaseSelectionHandle(l){a.release(l)},runAndEmit(l,c,d){let u=c(),m=r.runWithProgrammaticDocumentChange(t(),l);return c()===u&&d(),m}}}function Gy(e,t,r,o,n,i,s,a,l,c,d,u,m){let p=Qt(n),f=kS(i,s),g=mo(r,e,p.comments,o),v=As(c,e.trackingEnabled),E=Jr(d),R=dt(u)??"vertical",S=US(p,f,l??!0,r,g,v,E,dr(R,E),R,e.document,a??null),P=()=>Jh(s),h=Wy({resolveProgrammaticSelection(U,Se){if(Se.projectedMode!=null&&Se.selectionTarget){let Fe=V(),et=ut({state:U.state,target:Se.selectionTarget,projectionSnapshot:{canonicalDocument:Fe.canonicalDocument,projectedMode:Fe.projectedMode},sourceMode:Se.projectedMode,revisions:Fe.canonicalReviewRuntime.documentApi.review.list(),expectedText:Se.text??null});if(et&&Se.selectionKind==="text")return Z(U.state,et.selection.from,et.selection.to)}return null}}),b=Sy(U=>h.untrack(U)),x=Ny({context:S,allowCollaborativeProjection:P,releaseContextMenuCaptures:()=>b.releaseContextMenuCaptures(S.contextMenu)}),A=Dy({setState:U=>{S.linkPopover=U},closeState:x.closeLinkPopover,clearOverlayState:x.clearEphemeralOverlays,untrackCapture:b.untrackCapture}),O=sy({getController:m,getDocumentMode:()=>S.documentMode,getRuntime:()=>X(S),getResolvedModules:()=>S.resolvedModules,captureSelectionFromState:U=>M(U),setLinkPopover:A.set,closeContextMenu:x.closeContextMenu,closeLinkPopover:A.close,emit:x.emit}),j=ay({getController:m,getDocumentMode:()=>S.documentMode,getResolvedModules:()=>S.resolvedModules,readTrackChangesDisplayState:()=>x.readCurrentDisplayState().trackChanges,captureEffectiveSelectionFromState:U=>N(U,{includeText:!0}),setContextMenu:U=>{b.releaseContextMenuCaptures(S.contextMenu,U),S.contextMenu=U},closeContextMenu:x.closeContextMenu,closeLinkPopover:A.close,emit:x.emit}),_=fy({context:S,templates:t,ownsSurface:i,surfaceFactory:s,allowCollaborativeProjection:P,emit:x.emit,readCurrentDisplayState:x.readCurrentDisplayState,clearEphemeralOverlays:A.clearOverlays,handleLinkClick:O,handleContextMenu:j}),V=()=>Or(S.readModel,x.readCurrentDisplayState().trackChanges.mode),de=()=>{let U=X(S).surface;h.runWithProgrammaticDocumentChange(U,()=>_.applySurfaceDisplayState());let Se=X(S).surface;U!==Se&&!h.transferSurface(U,Se)&&Tt();let Fe=x.readCurrentDisplayState();if(Ia({surface:X(S).surface,documentMode:S.documentMode,allowSelectionInViewMode:S.allowSelectionInViewMode}),S.documentMode==="viewing"&&Fe.trackChanges.enabled&&Fe.trackChanges.mode==="review"){let et=V();ba({surface:X(S).surface,canonicalReviewApi:et.canonicalReviewRuntime.documentApi,canonicalDocument:et.canonicalDocument,projectedMode:et.projectedMode})}},k=Ku({getRuntime:()=>X(S),readProjectionSnapshot:V,readCurrentDisplayState:x.readCurrentDisplayState,readEffectiveSelection:U=>B(U),captureEffectiveSelection:U=>y(U),subscribeStateChange:U=>{let Se=()=>U();return S.listeners.add(Se),()=>{S.listeners.delete(Se)}}}),I=cy({context:S,readProjectionSnapshot:V,readState:x.readState,selectionCaptureTracker:h}),{captureSelection:F,captureEffectiveSelection:y,readEffectiveSelection:B,captureCurrentSelectionFromState:M,captureEffectiveSelectionFromState:N,readSelectionCapture:L,resolveSelectionCapture:ae}=I,je=U=>ae(U,{includeText:!0}),me=U=>L(U,{includeText:!0});S.normalizeOverlayState=()=>{let U=A.sync(me),Se=S.contextMenu;if(!Se)return U;let Fe=X(S),et=V(),Vi=et.canonicalReviewRuntime.documentApi.review.list(),Li=vy({surface:Fe.surface,selectionInfo:Dr(Fe.surface,{includeText:!0},Fe.replacementMode),projectionSnapshot:et,revisions:Vi}),Fi=wy({currentState:Se,controller:m(),documentMode:S.documentMode,contextMenuOptions:S.resolvedModules.contextMenu,reviewActionsEnabled:x.readCurrentDisplayState().trackChanges.enabled,revisions:Vi,liveSelection:Li.selection,liveSelectionInfo:Li.selectionInfo,resolveSelectionCapture:je,resolveSelectionState:zi=>h.resolveState(Fe.surface,zi)});return b.releaseContextMenuCaptures(Se,Fi),S.contextMenu=Fi,!0};let Ke=Zy({getSurface:()=>X(S).surface,selectionCaptureTracker:h,captureSelection:F,captureEffectiveSelection:y,captureCurrentSelectionFromState:M,readSelectionCapture:L}),{clearDeferredSelectionState:Tt,captureSelectionHandle:Je,captureEffectiveSelectionHandle:Ce,captureSelectionHandleFromCapture:mt,resolveSelectionHandle:hr,restoreSelectionCapture:jt,restoreSelectionHandle:vo,releaseSelectionHandle:Vt}=Ke,Lt=U=>Ke.runAndEmit(U,x.getEmissionVersion,x.emit),yr=ty({getRuntime:()=>X(S),runAndEmit:Lt,readState:()=>x.readState(),clearPreservedRangeSelection:()=>{S.preservedRangeSelection=null}}),z=()=>Es({editable:X(S).surface.editable,document:X(S).surface.document,commentsDisplay:x.readCurrentDisplayState().comments}),Qe=()=>Jt(X(S).surface);return _.mountSourceRuntime(e),x.subscribeCollaborationSession(S.collaborationSession),de(),{context:S,permissionResolver:o,stateRuntime:x,lifecycle:_,selectionRuntime:I,linkPopoverRuntime:A,advancedOoxmlMethods:yr,publicDocumentApi:k,commentWriteReason:z,reviewWriteReason:Qe,applySurfaceDisplayState:de,clearDeferredSelectionState:Tt,selectionCaptureTracker:h,captureCurrentSelectionFromState:M,runAndEmit:Lt,captureSelectionHandle:Je,captureEffectiveSelectionHandle:Ce,captureSelectionHandleFromCapture:mt,resolveSelectionHandle:hr,restoreSelectionCapture:jt,restoreSelectionHandle:vo,releaseSelectionHandle:Vt}}function ji(e,t,r,o,n,i,s,a,l,c,d,u){let m,p=Gy(e,t,r,o,n,i,s,a,l,c,d,u,()=>m),{context:f,permissionResolver:g,stateRuntime:v,lifecycle:E,selectionRuntime:R,linkPopoverRuntime:S,advancedOoxmlMethods:P,publicDocumentApi:h,commentWriteReason:b,reviewWriteReason:x,applySurfaceDisplayState:A,clearDeferredSelectionState:O,selectionCaptureTracker:j,captureCurrentSelectionFromState:_,runAndEmit:V,captureSelectionHandle:de,captureEffectiveSelectionHandle:k,captureSelectionHandleFromCapture:I,resolveSelectionHandle:F,restoreSelectionCapture:y,restoreSelectionHandle:B,releaseSelectionHandle:M}=p,N=g,L=()=>Or(f.readModel,v.readCurrentDisplayState().trackChanges.mode),ae=!1,{captureSelection:je,captureEffectiveSelection:me,readEffectiveSelection:Ke,capturePointSelection:Tt,readPointSelection:Je,readSelectionCapture:Ce,resolveSelectionCapture:mt}=R,hr=ZS({context:f,permissionResolver:N,getSurface:()=>X(f).surface,readState:v.readState,runBatchedEmit:v.runBatchedEmit,clearEphemeralOverlays:S.clearOverlays,applySurfaceDisplayState:A,emit:v.emit}),jt=HS({reconfigurable:f.reconfigurable,getRuntime:()=>X(f),getSourceRuntime:()=>xe(f),getCurrentActor:()=>f.currentActor,getCollaborationSession:()=>f.collaborationSession,readCollaboration:v.readCollaboration,readCommentResolveState:()=>v.readCurrentDisplayState().comments,commentWriteReason:b,reviewWriteReason:x,createReplacementSurface:E.createReplacementSurface,swapSurface:(z,Qe)=>{let U=f.preservedRangeSelection,Se=X(f).surface;f.collaborationSession=Qe,v.subscribeCollaborationSession(f.collaborationSession),E.swapSurface(z,Qe);let Fe=X(f).surface;j.transferSurface(Se,Fe)||O(),f.currentActor=mo(f.actorInput,Fe,f.resolvedModules.comments,N),f.preservedRangeSelection??=U},emit:v.emit,runAndEmit:V,readEffectiveSelection:Ke,captureEffectiveSelection:me,readSelectionCapture:Ce,resolveSelectionCapture:mt,resolveSelectionHandle:F,resolveCommentTargetFromCapture:z=>{if(!z)return null;let Qe=Nr(z)?z.selectionTarget:null,U=z.target??Qe;if(!U)return null;if(!Nr(z))return U;let Se=X(f),Fe=j.resolveTarget(Se.surface,z),et=Ce(z,{includeText:!0}),Vi=et?.target??et?.selectionTarget??Fe,Li=j.isTracked(Se.surface,z),Fi="segments"in U?(()=>{let zi=Q(Se.surface.state.doc,U,{strict:!0});return zi?ge(Se.surface.state.doc,Se.surface.state.schema,zi):null})():null;return $S({captureTarget:U,captureText:z.text,originalTargetText:Fi,resolvedTarget:Vi,resolvedText:et?.text??null,captureStillTracked:Li})},getPresentationReadApi:()=>L().presentationReadRuntime.documentApi,getWritableRuntimeApi:()=>L().writableRuntime.documentApi,getSearchQuery:()=>f.searchQuery,setSearchQuery:z=>{f.searchQuery=z},getSearchOptions:()=>f.searchOptions,setSearchOptions:z=>{f.searchOptions=z},getActiveSearchHitId:()=>f.activeSearchHitId,setActiveSearchHitId:z=>{f.activeSearchHitId=z},getActiveCommentId:()=>v.readState().activeCommentId??null,setActiveCommentId:z=>{f.activeCommentId=z},readVisibleComments:()=>v.readState().comments,getActiveRevisionId:()=>v.readState().activeRevisionId??null,setActiveRevisionIds:z=>{f.activeRevisionIds=[...z],f.activeRevisionId=z.length===1?z[0]??null:null},getLinkPopover:()=>f.linkPopover,getLinkPopoverSelectionCapture:S.getSelectionCapture,setLinkPopover:S.set,closeLinkPopover:S.close,clearPreservedRangeSelection:()=>{f.preservedRangeSelection=null}}),vo=tv({context:f,emit:v.emit,getEmissionVersion:v.getEmissionVersion,applySurfaceDisplayState:A}),Vt,Lt;m={get surface(){return X(f).surface},get documentService(){return X(f).documentService},get documentApi(){return h},get editorHost(){return Vt},get editor(){return Lt},get modules(){return Qt(f.resolvedModules)},get actor(){return aa(f.currentActor)},get collaboration(){return fd(v.readCollaboration())},getState(){return v.readState()},getCollaborationState(){return fd(v.readCollaboration())},...hr,...vo,setActor(z){f.actorInput=z,f.currentActor=mo(f.actorInput,X(f).surface,f.resolvedModules.comments,N),v.emit()},setParticipant(z){f.currentActor=sd(f.actorInput,z,f.resolvedModules.comments,N);let Qe=xe(f),U=f.readModel.activeRuntime;U&&U.surface!==Qe.surface&&U.surface.setParticipant(z),Qe.surface.setParticipant(z)},subscribe(z){f.listeners.add(z);try{ae||z(v.readState())}catch(Qe){throw f.listeners.delete(z),Qe}return()=>f.listeners.delete(z)},captureSelection:je,captureEffectiveSelection:me,readEffectiveSelection:Ke,readSelectionCapture:Ce,captureSelectionHandle:de,captureEffectiveSelectionHandle:k,captureSelectionHandleFromCapture:I,resolveSelectionCapture:mt,resolveSelectionHandle:F,restoreSelectionCapture:y,restoreSelectionHandle:B,releaseSelectionHandle:M,capturePointSelection(z){return!z||typeof z!="object"||typeof z.clientX!="number"||typeof z.clientY!="number"?null:Tt(z)},readPointSelection(z){return!z||typeof z!="object"||typeof z.clientX!="number"||typeof z.clientY!="number"?null:Je(z)},...jt,...P,closeLinkPopover:S.close,closeContextMenu:v.closeContextMenu,destroy(){if(ae)return;ae=!0,O(),f.unsubscribeCollaborationSession?.(),f.unsubscribeCollaborationSession=null,f.listeners.clear(),Lt.destroy(),E.destroyCollaborativeProjection();let z=i||!!s;E.unmountSourceRuntime(z),f.preservedRangeSelection=null,f.collaborationSession=null}},Vt=ci(m),Lt=Sj(Vt);let yr=$s(()=>X(f).surface);return Object.defineProperty(m,Os,{value(z){if(!z||typeof z!="object"||typeof z.clientX!="number"||typeof z.clientY!="number")return null;let Qe=dn({surface:X(f).surface,clientX:z.clientX,clientY:z.clientY,mode:"text-only"});return Qe?_(Qe.state,z):null}}),Object.defineProperties(m,{readLayoutAdapter:{configurable:!1,enumerable:!1,value:yr.readLayoutAdapter},readLayoutSource:{configurable:!1,enumerable:!1,value:yr.readLayoutSource},readDocumentSize:{configurable:!1,enumerable:!1,value:yr.readDocumentSize},selection:{configurable:!1,enumerable:!1,value:yr.selection}}),m}import{createDocumentFontCatalog as Xy,createDocumentFontRegistrationManager as vj}from"@datalking/begonia-font-system";function Xu(e){return e.document.attrs.ooxmlPackageResources}function hj(e,t){let r=e.view?.dom;if(r?.querySelectorAll)for(let o of Array.from(r.querySelectorAll("[data-font-family], [data-font-family-resolved]"))){let n=o.getAttribute("data-font-family")??o.getAttribute("data-font-family-resolved");if(!n)continue;let i=t(n),s=o.style;s&&(s.fontFamily=i??n)}}function $u(e,t,r){let o=Xy(Xu(t),"browser-document"),n=vj(r,o),i=Xu(t),s=!1,a=()=>{s||hj(e.surface,u=>n.catalog.resolveFamily(u))},l=()=>{if(s)return;let u=e.surface,m=Xu(u);m!==i&&(i=m,n.replace(Xy(m,"browser-document"))),a(),n.ready.then(a)},c=e.subscribe(l),d=e.destroy.bind(e);return Object.defineProperties(e,{documentFontCatalog:{configurable:!0,enumerable:!0,get:()=>n.catalog},documentFontsReady:{configurable:!0,enumerable:!0,get:()=>n.ready}}),e.destroy=()=>{s||(s=!0,c(),n.dispose(),d())},l(),e}function $y(e,t){t.fitWidthOptions!==void 0&&e.setFitWidthOptions(t.fitWidthOptions),t.zoomMode&&e.setZoomMode(t.zoomMode);let r=ht(t.zoomPercent);return r!=null&&t.zoomMode!=="fit-width"&&r!==e.getZoomPercent()&&e.setViewState({zoomPercent:r}),e}function bj(e,t={}){let r=$y(ji(e,t.templates,t.actor,t.permissionResolver,t.modules,!1,t.surfaceFactory,t.collaborationSession,t.viewSelect,t.documentMode,t.flowMode,t.layoutMode),t);return $u(r,e,t.documentFontProvider)}function Yu(e){let t=e.enableEmbeddedAdvancedOoxmlEditors===!1?e.features??[]:_i(e.features??[]),r=As(e.documentMode,e.trackingEnabled),o=an(r,e.modules?.trackChanges),{actor:n,templates:i,collaborationSession:s,documentMode:a,documentFontProvider:l,enableEmbeddedAdvancedOoxmlEditors:c,flowMode:d,layoutMode:u,zoomPercent:m,zoomMode:p,fitWidthOptions:f,modules:g,permissionResolver:v,surfaceFactory:E,viewSelect:R,...S}=e,P=yj({...S,collaborative:e.collaborationSession?.binding??e.collaborative,editable:ln(r),trackingEnabled:kr(r,o),features:t}),h=$y(ji(P,e.templates,e.actor,e.permissionResolver,e.modules,!0,MS({...e,features:t}),e.collaborationSession,e.viewSelect,e.documentMode,e.flowMode,e.layoutMode),e);return $u(h,P,e.documentFontProvider)}import{DEFAULT_VIEWPORT_FIT_WIDTH_OPTIONS as V3,cloneViewportFitMetrics as L3,cloneViewportFitWidthOptions as F3,computeAppliedViewportFitZoom as z3,computeViewportFitZoom as H3,normalizeViewportFitMetrics as q3,normalizeViewportFitWidthOptions as Bj,resolveViewportFitMetricsFromPreview as W3,sameViewportFitMetrics as K3,sameViewportFitWidthOptions as xj}from"@datalking/begonia-layout-renderer/core";function Ju(e){return Bj(e)}function Yy(e,t){return xj(e,t)}var Cj=Object.freeze([]);function Qy(e,t){return e.length===t.length&&e.every((r,o)=>Object.is(r,t[o]))}function Pj(e,t){return e===t?!0:!e||!t?e==null&&t==null:Qy(e,t)}function eb(e,t){return e===t?!0:!e||!t?e==null&&t==null:(e.id??null)===(t.id??null)&&(e.name??null)===(t.name??null)&&(e.createdAt??null)===(t.createdAt??null)&&(e.role??null)===(t.role??null)&&(e.bypassPermissions??!1)===(t.bypassPermissions??!1)&&(e.canViewInternalComments??!1)===(t.canViewInternalComments??!1)&&(e.canToggleCommentVisibility??!1)===(t.canToggleCommentVisibility??!1)&&(e.permissionResolver??null)===(t.permissionResolver??null)&&(e.commentPermissionResolver??null)===(t.commentPermissionResolver??null)&&Pj(e.groups,t.groups)}function tb(e,t){return e.id===t.id&&e.name===t.name&&(e.color??null)===(t.color??null)}function Rj(e){return{...e}}function Tj(e){return e?.length?[...e]:Cj}function kj(e){return!e||typeof e!="object"?e:{...e}}function rb(e,t){return Yy(Ju(e),Ju(t))}function Jy(e){return{...e,collaborationSession:e.collaborationSession??null,enableEmbeddedAdvancedOoxmlEditors:e.enableEmbeddedAdvancedOoxmlEditors!==!1,...e.actor!==void 0?{actor:aa(e.actor??null)}:{},features:Tj(e.features),...e.fitWidthOptions!==void 0?{fitWidthOptions:kj(e.fitWidthOptions)}:{},...e.modules!==void 0?{modules:Qt(e.modules)}:{},participant:Rj(e.participant),trackingEnabled:e.trackingEnabled!==!1,viewSelect:e.viewSelect!==!1}}function ob(e,t){return e.room===t.room&&e.collaborative===t.collaborative&&e.collaborationSession===t.collaborationSession&&e.enableEmbeddedAdvancedOoxmlEditors===t.enableEmbeddedAdvancedOoxmlEditors&&Qy(e.features,t.features)&&e.initialContent===t.initialContent&&e.schema===t.schema&&e.permissionResolver===t.permissionResolver&&e.surfaceFactory===t.surfaceFactory&&e.trackingEnabled===t.trackingEnabled&&e.viewSelect===t.viewSelect}function Ej(e,t){return eb(e.actor,t.actor)&&ob(e,t)&&e.documentMode===t.documentMode&&e.flowMode===t.flowMode&&e.layoutMode===t.layoutMode&&id(e.modules,t.modules)&&e.onTransaction===t.onTransaction&&e.onUpdate===t.onUpdate&&tb(e.participant,t.participant)&&e.zoomMode===t.zoomMode&&rb(e.fitWidthOptions,t.fitWidthOptions)&&e.zoomPercent===t.zoomPercent}function Mj(e,t){return e.controller===t.controller&&e.state===t.state}function Qu(e){return{controller:e.controller,state:e.state}}function Ij(e,t,r){let{room:o,...n}=e;return{...n,collaborative:e.collaborationSession?.binding??e.collaborative??e.room,element:t,onTransaction:r.onTransaction,onUpdate:r.onUpdate}}function Aj(e){let{controller:t,previous:r,next:o}=e;eb(r.actor,o.actor)||t.setActor(o.actor??null),tb(r.participant,o.participant)||t.setParticipant(o.participant),r.documentMode!==o.documentMode&&o.documentMode!=null&&t.setDocumentMode(o.documentMode),id(r.modules,o.modules)||t.setModules(o.modules),r.zoomMode!==o.zoomMode&&o.zoomMode!=null&&t.setZoomMode(o.zoomMode),!rb(r.fitWidthOptions,o.fitWidthOptions)&&o.fitWidthOptions!==void 0&&t.setFitWidthOptions(o.fitWidthOptions);let n={...r.flowMode!==o.flowMode&&o.flowMode?{flowMode:o.flowMode}:{},...r.layoutMode!==o.layoutMode&&o.layoutMode?{layoutMode:o.layoutMode}:{},...r.zoomPercent!==o.zoomPercent&&o.zoomPercent!=null&&o.zoomMode!=="fit-width"?{zoomPercent:o.zoomPercent}:{}};Object.keys(n).length>0&&t.setViewState(n)}function em(e,t={}){let r=new Set,o=t.createEditor??Yu,n={destroyed:!1,host:null,input:Jy(e),controller:null,state:null,unsubscribeController:null,snapshot:{controller:null,state:null}},i=()=>{let c={controller:n.controller,state:n.state};if(!Mj(n.snapshot,c)){n.snapshot=c;for(let d of[...r])d(Qu(c))}},s=()=>{let c=n.controller,d=n.unsubscribeController;n.unsubscribeController=null,n.controller=null,n.state=null,i(),d?.(),c&&c.destroy()},a=()=>{if(!n.host)return;let c=o(Ij(n.input,n.host,{onTransaction(d){n.input.onTransaction?.(d)},onUpdate(){n.input.onUpdate?.()}}));n.controller=c,n.state=c.getState(),i(),n.unsubscribeController=c.subscribe(d=>{n.controller===c&&(n.state=d,i())})},l=()=>{s(),a()};return{getSnapshot(){return Qu(n.snapshot)},subscribe(c){return r.add(c),c(Qu(n.snapshot)),()=>{r.delete(c)}},setHost(c){if(!(n.destroyed||n.host===c)){if(n.host=c,!c){s();return}if(!n.controller){a();return}l()}},setInput(c){if(n.destroyed)return;let d=n.input,u=Jy(c);if(n.input=u,Ej(d,u)||!n.host)return;let m=!ob(d,u);if(!n.controller||m){l();return}Aj({controller:n.controller,previous:d,next:u})},destroy(){n.destroyed||(n.destroyed=!0,n.host=null,s(),r.clear())}}}function Nj(){return{ui:null,host:null,snapshot:null}}function ib(e){vS(e.host,e.ui),e.ui?.destroy(),e.controller=null,e.host=null,e.ui=null}function Dj(e,t){if(e.controller===t||(ib(e),!t))return;let r=hn(t);e.controller=t,e.host=r,e.ui=ks(r);let o=wr(r);o&&Ys(r,e.ui,o)}function nb(e,t){return Dj(e,t.controller),{ui:e.ui,host:e.host,snapshot:t.state?cn(t.state):null}}function Oj(e){let t=em(e),r=new Set,o={controller:null,host:null,ui:null},n=nb(o,t.getSnapshot()),i=t.subscribe(s=>{n=nb(o,s);for(let a of[...r])a(n)});return{getSnapshot(){return n},subscribe(s){return r.add(s),s(n),()=>{r.delete(s)}},setHost(s){t.setHost(s)},setInput(s){t.setInput(s)},destroy(){i(),r.clear(),ib(o),t.destroy(),n=Nj()}}}function jj(){return{createMount(e){return Oj(e)}}}function Vj(e){return Js(e)}import{collectOoxmlMathStructures as Lj,countOoxmlChartCategories as Fj,normalizeOoxmlChartModel as zj,normalizeOoxmlMathModel as Hj,normalizeOoxmlShapeModel as qj}from"@datalking/begonia-engine";function Aa(e){return e.trackingEnabled??e.toolbar?.trackingEnabled??!1}function Na(e){return e.documentMode==="editing"||e.documentMode==="suggesting"||e.documentMode==="viewing"?e.documentMode:"editing"}function Wj(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="math")return null;let r=Hj(t.familyData??{plainText:t.text,displayMode:"inline"},t.text,"inline");return{family:"math",record:t,model:r,plainText:t.familyData?.plainText??t.text,displayMode:r.displayMode,structures:t.familyData?.structures?.length?t.familyData.structures:Lj(r),trackingEnabled:Aa(e),documentMode:Na(e)}}function Kj(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="chart")return null;let r=zj(t.familyData?.model??t.familyData??{title:t.label,textBody:{plainText:t.text}},t.label);return{family:"chart",record:t,model:r,series:r.series,seriesCount:r.series.length,categoryCount:Fj(r),trackingEnabled:Aa(e),documentMode:Na(e)}}function _j(e){let t=e.advancedOoxml.selected;if(!t||t.family!=="shape")return null;let r=qj(t.familyData?.model??t.familyData??{label:t.label,textBody:t.text?{plainText:t.text,paragraphs:[t.text]}:null},t.label);return{family:"shape",record:t,model:r,trackingEnabled:Aa(e),documentMode:Na(e)}}function tm(e="editing",t=!1){return{selected:null,documentMode:e,trackingEnabled:t}}function sb(e){return{selected:Wj(e)??Kj(e)??_j(e),trackingEnabled:Aa(e),documentMode:Na(e)}}function Da(e){return structuredClone(e)}function ee(e){return{changed:!1,reason:e}}function Uj(e){let t=e,r=he(t),o=wr(t),n=hS(t),i=o?.controller.documentApi??{},s=()=>{let m=o?.controller.getState();return m?sb(m):tm()},a=s(),l=new Set,c=()=>{a=s();for(let m of[...l])m(Da(a))},d=r?.session.subscribe(()=>c())??(()=>{}),u="Advanced OOXML editing requires a mounted browser editor backend.";return{actor:o?.controller.actor??null,documentApi:i,getSnapshot(){return a=s(),Da(a)},subscribe(m){return l.add(m),m(Da(a)),()=>{l.delete(m)}},replaceSelectedMathModel(m){return n?n.replaceSelectedMathModel(m):ee(u)},setSelectedMathPlainText(m,p){return n?n.setSelectedMathPlainText(m,p):ee(u)},setSelectedMathDisplayMode(m){return n?n.setSelectedMathDisplayMode(m):ee(u)},replaceSelectedChartModel(m){return n?n.replaceSelectedChartModel(m):ee(u)},setSelectedChartMetadata(m){return n?n.setSelectedChartMetadata(m):ee(u)},appendSelectedChartSeries(m){return n?n.appendSelectedChartSeries(m):ee(u)},setSelectedChartSeriesList(m){return n?n.setSelectedChartSeriesList(m):ee(u)},setSelectedChartTitle(m){return n?n.setSelectedChartTitle(m):ee(u)},setSelectedChartTextBody(m){return n?n.setSelectedChartTextBody(m):ee(u)},setSelectedChartSeries(m,p){return n?n.setSelectedChartSeries(m,p):ee(u)},upsertSelectedChartSeries(m,p){return n?n.upsertSelectedChartSeries(m,p):ee(u)},removeSelectedChartSeries(m){return n?n.removeSelectedChartSeries(m):ee(u)},appendSelectedChartAxis(m){return n?n.appendSelectedChartAxis(m):ee(u)},setSelectedChartAxes(m){return n?n.setSelectedChartAxes(m):ee(u)},upsertSelectedChartAxis(m,p){return n?n.upsertSelectedChartAxis(m,p):ee(u)},removeSelectedChartAxis(m){return n?n.removeSelectedChartAxis(m):ee(u)},setSelectedChartLegend(m){return n?n.setSelectedChartLegend(m):ee(u)},setSelectedChartPlotArea(m){return n?n.setSelectedChartPlotArea(m):ee(u)},replaceSelectedShapeModel(m){return n?n.replaceSelectedShapeModel(m):ee(u)},setSelectedShapeMetadata(m){return n?n.setSelectedShapeMetadata(m):ee(u)},setSelectedShapeWatermark(m){return n?n.setSelectedShapeWatermark(m):ee(u)},setSelectedShapeTextBody(m){return n?n.setSelectedShapeTextBody(m):ee(u)},setSelectedShapeGeometry(m){return n?n.setSelectedShapeGeometry(m):ee(u)},setSelectedShapeTransform(m){return n?n.setSelectedShapeTransform(m):ee(u)},setSelectedShapeFill(m){return n?n.setSelectedShapeFill(m):ee(u)},setSelectedShapeStroke(m){return n?n.setSelectedShapeStroke(m):ee(u)},setSelectedShapeAnchor(m){return n?n.setSelectedShapeAnchor(m):ee(u)},setSelectedShapeConnector(m){return n?n.setSelectedShapeConnector(m):ee(u)},setSelectedShapePicture(m){return n?n.setSelectedShapePicture(m):ee(u)},setSelectedShapeWordArt(m){return n?n.setSelectedShapeWordArt(m):ee(u)},setSelectedShapeChildren(m){return n?n.setSelectedShapeChildren(m):ee(u)},setSelectedShapeChild(m,p){return n?n.setSelectedShapeChild(m,p):ee(u)},appendSelectedShapeChild(m){return n?n.appendSelectedShapeChild(m):ee(u)},appendSelectedShapeChildToParent(m,p){return n?n.appendSelectedShapeChildToParent(m,p):ee(u)},moveSelectedShapeChild(m,p){return n?n.moveSelectedShapeChild(m,p):ee(u)},removeSelectedShapeChild(m){return n?n.removeSelectedShapeChild(m):ee(u)},removeSelected(){return n?n.removeSelectedAdvancedOoxml():ee(u)},destroy(){d(),l.clear(),a=tm()}}}function ab(e){return e?.selection??null}function Zj(e){return ab(e.editor)?.resolvePositionHitEvent?.(e)??e.event}function Gj(e){let t=ab(e.editor);if(!t?.handlePositionHit)return!1;let r=t.resolvePositionHitEvent?.(e)??e.event;return t.handlePositionHit({...e,event:r})}function lb(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}function cb(e){return e==="bootstrap"||e==="ignore"?e:"consume"}function db(e){return e==="web"||e==="paginated"?e:null}function ub(e){return e==="vertical"||e==="horizontal"||e==="book"?e:null}function S7(e){return e.previousEditor!==e.nextEditor?"editor-instance":e.previousPreviewSourceIdentity!==e.previewSourceIdentity?"preview-source":cb(e.previousControllerNavigationMode)!==cb(e.controllerNavigationMode)?"controller-navigation-mode":db(e.previousFlowMode)!==db(e.flowMode)||ub(e.previousLayoutMode)!==ub(e.layoutMode)?"preview-mode":e.previousSyncViewportToEditor!==e.syncViewportToEditor?"sync-viewport-toggle":lb(e.previousExplicitAnchorPageNumber)!==lb(e.explicitAnchorPageNumber)?"explicit-anchor":null}import{resolveProjectionSelectionPageIndexes as Xj}from"@datalking/begonia-page-layout";function rm(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>0?t:null}function $j(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.trunc(e)):null}function pb(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>=0?t:null}function Yj(e,t){if(!e||typeof e!="object")return t;let r=e,o=rm(r.pageNumber),n=pb(r.pageIndex);return o!=null&&n!=null&&n!==o-1?null:o??(n!=null?n+1:t)}function Jj(e){if(!e||typeof e!="object")return null;let t=rm(e.anchorPageNumber),r=e.viewportAnchor==null?t:Yj(e.viewportAnchor,t);return e.viewportAnchor!=null&&r==null||t!=null&&r!=null&&r!==t?null:t??r}function Tn(e,t){let r=new Set([...e].map(o=>rm(o)).filter(o=>o!=null));return!t||t.length===0?[...r].sort((o,n)=>o-n):t.filter(o=>r.has(o))}function mb(e,t){if(!t||t.length===0)return[];let r=new Map(t.map((o,n)=>[o,n]));return Tn(e??[],t).flatMap(o=>{let n=r.get(o);return n==null?[]:[n]})}function Qj(e,t){return Tn(e.flatMap(r=>{let o=pb(r),n=o==null?null:t[o]??null;return n==null?[]:[n]}),t)}function y7(e){let t=e.projection?.pages.map(s=>s.pageNumber)??null,r=Tn(e.selectionPageNumbers??[],t),o=new Set(Tn(e.pinnedPageNumbers??[],t));for(let s of r)o.add(s);if(!e.projection||e.sourceMatchesEditorDocument===!1){let s=Tn(o,t);return s.length>0?s:void 0}let n=Jj(e.previewNavigationRequest),i=r.length>0?Tn(n==null?o:[...o,n],t):Qj(Xj(e.projection,e.selection,{docSize:$j(e.documentSize),preferredPageIndexes:mb(e.pinnedPageNumbers,t),extraPageIndexes:n==null?[]:mb([n],t)}),t??[]);return i.length>0?i:void 0}function eV(e){let t=xg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,e.syncViewportToEditor?e.lastAppliedViewport??null:e.trackingState.editorViewport,e.trackingState.editorViewportRequestKey,e.modeOptions);return t?{viewport:t,cause:"controller-viewport-request"}:null}function om(e,t){return t?fb({editorViewport:null,editorViewportRequestKey:null,previewNavigationRequestKey:null,previewNavigationRequest:null},e,t):{editorViewport:re(e?.viewport??null),editorViewportRequestKey:Ne(e?.viewportRequestKey??null),previewNavigationRequestKey:Ne(e?.previewNavigationRequest?.requestKey??null),previewNavigationRequest:be(e?.previewNavigationRequest??null)}}function fb(e,t,r){let o=Bt(t,r),n=xt(t,r),i=t?.viewport!=null,s=t?.previewNavigationRequest!=null;return{editorViewport:o?re(o):i?re(e.editorViewport):null,editorViewportRequestKey:o?Ne(t?.viewportRequestKey??null):i?Ne(e.editorViewportRequestKey):null,previewNavigationRequestKey:n?Ne(n.requestKey):s?Ne(e.previewNavigationRequestKey):null,previewNavigationRequest:n?be(n):s?be(e.previewNavigationRequest):null}}function wb(e){let t=xt(e.editorState,e.modeOptions),r=bg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,Mr(t,e.trackingState.previewNavigationRequest)?e.trackingState.previewNavigationRequestKey:null,e.modeOptions),o=eV(e),n=o?.viewport??null,i=fb(e.trackingState,e.editorState,e.modeOptions);return n&&(i.editorViewport=re(n),i.editorViewportRequestKey=Ne(e.editorState?.viewportRequestKey??null)),{previewNavigationRequest:r,externalViewportRequest:n,resetCause:r?"preview-navigation-request":o?.cause??null,shouldResetViewport:r!=null||n!=null,nextTrackingState:i}}function tV(e){let t=Ic(e.editorState,e.explicitFlowMode),r=kg(e.editorState,e.explicitLayoutMode,t);return{flowMode:t,layoutMode:r}}function E7(e){let t=tV(e),{flowMode:r,layoutMode:o}=t;return{scale:Cg(e.editorState,e.explicitScale),flowMode:r,layoutMode:o,modeOptions:t,anchorPageNumber:Pg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),initialViewportAnchor:Rg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),viewportRequestKey:Tg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t),acknowledgementRequestKey:Bg(e.editorState,e.explicitAnchorPageNumber,e.viewportHydrated,e.controllerNavigationMode,t)}}function gb(e){if(!e.syncViewportToEditor)return null;let t=Yt(e.viewport,{flowMode:e.controllerFlowMode,layoutMode:e.controllerLayoutMode});if(!t||e.controllerFlowMode&&!_o(t,e.controllerFlowMode)||e.controllerLayoutMode&&!Uo(t,e.controllerLayoutMode)||e.controllerFlowMode&&e.controllerLayoutMode&&!to(t,e.controllerFlowMode,e.controllerLayoutMode))return null;let r=e.controllerFlowMode??t.flowMode,o=e.controllerLayoutMode??t.layoutMode,n=Yt(e.lastAppliedViewport,{flowMode:r,layoutMode:o}),i=Yt(e.controllerViewport,{flowMode:r,layoutMode:o});return Kn(t,n)||Kn(t,i)?null:t}function Sb(e){return e?{requestKey:e.requestKey,viewportResetVersion:e.viewportResetVersion}:null}function rV(e,t){return e?.requestKey===t?.requestKey&&e?.viewportResetVersion===t?.viewportResetVersion}function oV(e,t){return nt(e.editorViewport,t.editorViewport)&&e.editorViewportRequestKey===t.editorViewportRequestKey&&e.previewNavigationRequestKey===t.previewNavigationRequestKey&&Mr(e.previewNavigationRequest,t.previewNavigationRequest)}function vb(e,t){return e.viewportHydrated===t.viewportHydrated&&e.viewportResetVersion===t.viewportResetVersion&&nt(e.lastAppliedViewport,t.lastAppliedViewport)&&e.lastResetCause===t.lastResetCause&&oV(e.trackingState,t.trackingState)&&rV(e.pendingAcknowledgement,t.pendingAcknowledgement)}function nV(e,t){return e==null?null:{requestKey:e,viewportResetVersion:t}}function iV(e){return e.acknowledgementRequestKey!=null?nV(e.acknowledgementRequestKey,e.viewportResetVersion):e.shouldResetViewport?null:e.current!=null&&e.compatiblePreviewNavigationRequestKey===e.current.requestKey?Sb(e.current):null}function j7(e,t){return{viewportHydrated:!1,viewportResetVersion:0,lastAppliedViewport:null,lastResetCause:null,trackingState:om(e,t),pendingAcknowledgement:null}}function V7(e,t,r=null,o){return{viewportHydrated:!1,viewportResetVersion:e.viewportResetVersion+1,lastAppliedViewport:null,lastResetCause:r,trackingState:om(t,o),pendingAcknowledgement:null}}function L7(e){let t=wb({editorState:e.editorState,explicitAnchorPageNumber:e.explicitAnchorPageNumber,viewportHydrated:e.state.viewportHydrated,controllerNavigationMode:e.controllerNavigationMode,modeOptions:e.modeOptions,syncViewportToEditor:e.syncViewportToEditor,lastAppliedViewport:e.state.lastAppliedViewport,trackingState:e.state.trackingState}),r=t.shouldResetViewport?e.state.viewportResetVersion+1:e.state.viewportResetVersion,o=xt(e.editorState,e.modeOptions)?.requestKey??null,n={viewportHydrated:t.shouldResetViewport?!1:e.state.viewportHydrated,viewportResetVersion:r,lastAppliedViewport:t.shouldResetViewport?null:re(e.state.lastAppliedViewport),lastResetCause:t.shouldResetViewport?t.resetCause:e.state.lastResetCause,trackingState:t.nextTrackingState,pendingAcknowledgement:iV({current:e.state.pendingAcknowledgement,acknowledgementRequestKey:e.acknowledgementRequestKey,compatiblePreviewNavigationRequestKey:o,shouldResetViewport:t.shouldResetViewport,viewportResetVersion:r})};return{nextState:n,changed:!vb(e.state,n)}}function F7(e){if(e.observedViewportResetVersion!==e.state.viewportResetVersion)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let t=re(e.viewport);if(!t)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let r=Bt({viewport:t},e.modeOptions);if(!r)return{nextState:e.state,controllerViewportPatch:null,acknowledgementRequestKey:null,changed:!1};let o=gb({viewport:r,lastAppliedViewport:e.state.lastAppliedViewport,controllerViewport:e.controllerViewport,controllerFlowMode:e.controllerFlowMode,controllerLayoutMode:e.controllerLayoutMode,syncViewportToEditor:e.syncViewportToEditor}),n=Sb(e.state.pendingAcknowledgement),i=xt({previewNavigationRequest:e.previewNavigationRequest??null},e.modeOptions)?.requestKey??null,s=n!=null&&n.viewportResetVersion===e.state.viewportResetVersion&&i===n.requestKey,a={viewportHydrated:!0,viewportResetVersion:e.state.viewportResetVersion,lastAppliedViewport:re(r),lastResetCause:e.state.lastResetCause,trackingState:e.state.trackingState,pendingAcknowledgement:s?null:n};return{nextState:a,controllerViewportPatch:o,acknowledgementRequestKey:s?n.requestKey:null,changed:!vb(e.state,a)}}export{Wn as DEFAULT_BROWSER_ZOOM_PERCENT,Vo as applyBrowserInlineFormatPatch,rc as browserViewportStateHasExplicitModeConflict,om as captureBrowserPaginatedPreviewTrackingState,go as captureBrowserSurfaceSelectionRebaseTarget,re as cloneBrowserViewportState,Uj as createBrowserAdvancedOoxmlInspectorController,Yu as createBrowserEditor,jj as createBrowserEditorBackendAdapter,bj as createBrowserEditorController,ci as createBrowserEditorHost,em as createBrowserEditorMountController,uo as createBrowserEditorOverlayHost,vI as createBrowserEditorOverlayHostFromController,SI as createBrowserEditorSessionHostFromController,Vj as createBrowserEditorUiController,Js as createBrowserEditorUiFromController,hn as createBrowserEditorUiHost,hI as createBrowserEditorUiHostFromController,Xs as createBrowserPaginatedPreviewSelectionActionsV1,j7 as createBrowserPaginatedPreviewSessionState,zd as createBrowserSelectionCapture,yl as createSurfaceSelectionAdapter,Yt as fillBrowserViewportStateModes,Gj as handleBrowserPaginatedPreviewPositionHit,tc as hasFreshBrowserViewportRequest,_o as isBrowserViewportStateCompatibleWithFlowMode,Uo as isBrowserViewportStateCompatibleWithLayoutMode,to as isBrowserViewportStateCompatibleWithModes,Mc as normalizeBrowserPreviewControllerNavigationMode,ba as normalizeBrowserSurfaceReviewSelection,Go as normalizeBrowserViewportAnchor,$t as normalizeBrowserViewportPageAddress,Ne as normalizeBrowserViewportRequestKey,ht as normalizeBrowserZoomPercent,Sc as readBrowserEditorAutomation,wc as readBrowserEditorDocument,gc as readBrowserEditorView,ur as readBrowserZoomPercent,Ri as readSelectedAdvancedOoxmlRecord,vc as replaceBrowserEditorDocument,Cn as replaceBrowserSurfaceDocumentPreservingSelection,V7 as resetBrowserPaginatedPreviewSessionState,_I as resolveBrowserCommentReplayTarget,Es as resolveBrowserCommentWriteReason,MO as resolveBrowserEditorContextMenuContextAtPoint,io as resolveBrowserEditorPositionAtPoint,td as resolveBrowserEditorUiController,ir as resolveBrowserInlineFormatDisabledReason,Bg as resolveBrowserPaginatedPreviewAcknowledgementRequestKey,Pg as resolveBrowserPaginatedPreviewAnchorPageNumber,wK as resolveBrowserPaginatedPreviewControllerSyncState,gb as resolveBrowserPaginatedPreviewControllerViewportPatch,xg as resolveBrowserPaginatedPreviewExternalViewportRequest,Ic as resolveBrowserPaginatedPreviewFlowMode,kg as resolveBrowserPaginatedPreviewLayoutMode,S7 as resolveBrowserPaginatedPreviewLifecycleResetCause,tV as resolveBrowserPaginatedPreviewModeOptions,bg as resolveBrowserPaginatedPreviewNavigationRequest,y7 as resolveBrowserPaginatedPreviewPinnedPageNumbers,Zj as resolveBrowserPaginatedPreviewPositionHitEvent,wb as resolveBrowserPaginatedPreviewResetPlan,Cg as resolveBrowserPaginatedPreviewScale,L7 as resolveBrowserPaginatedPreviewSessionUpdate,hg as resolveBrowserPaginatedPreviewSourceBinding,E7 as resolveBrowserPaginatedPreviewViewModel,Rg as resolveBrowserPaginatedPreviewViewportAnchor,Ig as resolveBrowserPaginatedPreviewViewportAnchorFromHit,F7 as resolveBrowserPaginatedPreviewViewportObservation,Tg as resolveBrowserPaginatedPreviewViewportRequestKey,ut as resolveBrowserPreservedRangeTargetSelection,ga as resolveBrowserSurfaceProjectionMode,Q as resolveBrowserTextTargetSelection,Ae as resolveBrowserTextTargetSelectionWithExpectedText,xt as resolveCompatibleBrowserPreviewNavigationRequest,Bt as resolveCompatibleBrowserPreviewViewport,Xo as resolveCompatibleBrowserPreviewViewportAnchor,Sr as resolveProjectedSelectionRebaseRange,vi as resolveProjectedSelectionTrackedChangeIds,Ee as resolveSelectionInfo,Ci as restoreBrowserSurfaceSelectionFromRebaseTarget,mi as restoreTrackedCommentSelectionAfterReviewMutation,vg as sameBrowserPaginatedPreviewViewportRequest,sK as sameBrowserPaginatedPreviewViewportSyncState,Zo as sameBrowserViewportAnchor,Ps as sameBrowserViewportRequestKey,nt as sameBrowserViewportState,Kn as sameBrowserViewportStateForControllerSync,no as selectBrowserCommentTarget,El as selectBrowserTextTarget};
1
+ import{createDocumentSurface as 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};