@panphora/clayjs 1.18.1 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/all.js +1 -1
- package/dist/clay-dom.js +1 -1
- package/dist/clay-events.js +1 -1
- package/dist/clay-internals.js +1 -1
- package/dist/clay-options.js +1 -1
- package/dist/clay-router.js +1 -1
- package/dist/clay-ui.js +1 -1
- package/dist/clay-utils.js +1 -1
- package/dist/clay.js +1 -1
- package/dist/clay.standalone.js +618 -399
- package/dist/m/{c-6DB2OLRJ.js → c-2RARVIAK.js} +1 -1
- package/dist/m/{c-UORXLSD3.js → c-2Y4DOHSY.js} +1 -1
- package/dist/m/{c-4TXNLX4K.js → c-4FJTBE6I.js} +3 -3
- package/dist/m/{c-6UGWFMQC.js → c-7PYNAULW.js} +1 -1
- package/dist/m/{c-AMU3BPPR.js → c-AIWN4QN4.js} +2 -2
- package/dist/m/{c-COPTL5WB.js → c-AXGY2WTB.js} +1 -1
- package/dist/m/{c-IMZCWYHR.js → c-BAUBNYXK.js} +1 -1
- package/dist/m/{c-MWXFLW4J.js → c-CQQDL6O4.js} +1 -1
- package/dist/m/{c-KP64LT2A.js → c-DHUCEMXE.js} +1 -1
- package/dist/m/{c-VILENZTD.js → c-EXEDYU4H.js} +1 -1
- package/dist/m/{c-2GRUM77Q.js → c-F6G2OGYG.js} +2 -2
- package/dist/m/{c-SPZPGD3R.js → c-FCNAO2MI.js} +1 -1
- package/dist/m/{c-372N6H3B.js → c-FOOE4GML.js} +1 -1
- package/dist/m/{c-AMYEFA2E.js → c-FTQKI7SP.js} +1 -1
- package/dist/m/{c-URSMSFCB.js → c-GWNC3UGL.js} +1 -1
- package/dist/m/{c-BUAYFEV5.js → c-HUISJXHF.js} +1 -1
- package/dist/m/{c-K3ADYNLU.js → c-HXPHZN7Q.js} +1 -1
- package/dist/m/{c-OTMKN2OO.js → c-I4MQHOEY.js} +1 -1
- package/dist/m/{c-HHGJBU4D.js → c-JCP3XDSJ.js} +1 -1
- package/dist/m/{c-JNLX3RJB.js → c-JDARJDOT.js} +1 -1
- package/dist/m/{c-TTB5EK4S.js → c-JK3PHE7J.js} +1 -1
- package/dist/m/{c-B5UJQT7W.js → c-K72SY2TL.js} +1 -1
- package/dist/m/{c-5ONTYIUI.js → c-L6FLIUXP.js} +1 -1
- package/dist/m/{c-5OOVFCJM.js → c-LACAAQFB.js} +1 -1
- package/dist/m/{c-U7SHNWDH.js → c-LPCZOYTX.js} +1 -1
- package/dist/m/{c-X5TSXZYJ.js → c-MIKZEG5I.js} +1 -1
- package/dist/m/{c-EVYAISP3.js → c-MMXKAX2W.js} +1 -1
- package/dist/m/{c-PLN76GF3.js → c-O4JMKN6U.js} +2 -2
- package/dist/m/{c-RND3G2S2.js → c-P3CK66NT.js} +1 -1
- package/dist/m/{c-YBKHUAK7.js → c-QINHDETP.js} +1 -1
- package/dist/m/{c-OPLUZR3A.js → c-RRZJWFLE.js} +1 -1
- package/dist/m/{c-HMV6P4RX.js → c-UXFUJEZO.js} +1 -1
- package/dist/m/{c-SW4YEG2D.js → c-V52FE5FI.js} +1 -1
- package/dist/m/{c-D5IKEKXW.js → c-VE7RKNKZ.js} +1 -1
- package/dist/m/{c-CCQ25GFY.js → c-WKNRJX3C.js} +1 -1
- package/dist/m/{c-C6IPRG34.js → c-XSZKP646.js} +1 -1
- package/dist/m/{c-ZK4GIZH2.js → c-ZGDYHKG3.js} +1 -1
- package/dist/m/{c-T637T7SN.js → c-ZKNBMNN3.js} +1 -1
- package/dist/m/{c-W6DQSHXI.js → c-ZRUQ5FSU.js} +1 -1
- package/dist/m/{c-4YU3BR4D.js → c-ZS4US2XV.js} +1 -1
- package/dist/m/core/{autosave-S6OMNDCK.js → autosave-RVJPYLRT.js} +1 -1
- package/dist/m/core/{conflict-notice-IWHMHH43.js → conflict-notice-2WGT52LH.js} +1 -1
- package/dist/m/core/{recovery-DRFZRJED.js → recovery-ZOUOJVIX.js} +1 -1
- package/dist/m/core/{save-LYY7K6U7.js → save-A5JXV6ME.js} +1 -1
- package/dist/m/core/{unsaved-warning-7QTKEN7Z.js → unsaved-warning-4ZPEV7BF.js} +1 -1
- package/dist/m/loader-34YPFKOH.js +1 -0
- package/dist/m/manifest-0D166F4F.js +1 -0
- package/dist/m/manifest-edit-3877153E.js +1 -0
- package/dist/m/manifest.json +566 -555
- package/dist/m/page/{editor-6LRB3GE4.js → editor-WRQGHDSG.js} +2 -2
- package/dist/m/plugins/{ai-edit-UTV7YO2I.js → ai-edit-X2L2KIEP.js} +1 -1
- package/dist/m/plugins/like-EV7MTZ56.js +1 -0
- package/dist/m/plugins/{live-AD4H6XSL.js → live-7C36XEI2.js} +1 -1
- package/dist/m/plugins/{menu-M5WW7DBF.js → menu-MFC4DI5E.js} +1 -1
- package/dist/m/plugins/{page-MD3T2ZX3.js → page-BSW6MGDO.js} +2 -2
- package/dist/m/plugins/{page-view-PAWVZNFY.js → page-view-WFZVTPQK.js} +1 -1
- package/dist/m/plugins/{wire-VBWXEXU2.js → wire-6OSIL3I7.js} +1 -1
- package/dist/m/{reader-core-4W2KYEWQ.js → reader-core-PLZYLYLT.js} +2 -2
- package/dist/m/sync/{live-sync-MO5DH33W.js → live-sync-UXNI6ZF6.js} +1 -1
- package/dist/offline-manifest.json +312 -300
- package/docs/guide.md +1 -0
- package/package.json +2 -1
- package/src/loader-logic.js +5 -1
- package/src/loader.js +2 -0
- package/src/plugins/like.js +254 -0
- package/dist/m/loader-3BBNZZGM.js +0 -1
- package/dist/m/manifest-26C55578.js +0 -1
- package/dist/m/manifest-edit-4396A009.js +0 -1
- /package/dist/m/{c-X5LNHET5.js → c-5JLFROUB.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as M,g as _,h as A,w as q}from"./c-4TXNLX4K.js";import{B as G}from"./c-AMU3BPPR.js";import{D as O,G as $,I as y,J as B,M as R,Z as j,_ as U,b as z,m as p,na as F}from"./c-QIXT3Q7C.js";import{a as x}from"./c-WCXLG3MV.js";import{a as K}from"./c-I2SCCUEW.js";var{TextSelection:J}=z,S=new WeakMap,D=new Set;function g(n,t){let e=null;return n.forEach(s=>{s.type===p.nodes.table&&s.attrs.id===t&&(e=s)}),e}function N(n){return n?F({[n.attrs.id]:R(n)})[0]:null}function Q(n,t,e){let s=y(n.attrs.cols);if(!s.length)return null;let i=M(n),a=s.filter(r=>r!==s[0]&&i[r]==="number");return a.length?{id:B(),pos:t,parent:e,source:n.attrs.id,kind:"bar",x:s[0],series:a,title:"",highlight:null}:null}function wt(n,t){let e=n.state.doc,s=e.nodeAt(t);if(s?.type!==p.nodes.table)return!1;let i=t+s.nodeSize,a=e.maybeChild(e.resolve(i).index(0)),r=Q(s,$(s.attrs.pos,a?.attrs.pos??null),s.attrs.parent);return r?(D.add(r.id),n.dispatch(n.state.tr.insert(i,p.nodes.chart.create(r))),!0):(x("This table has no number column to chart yet."),!0)}function W(n,t,e,s){let i=n.state.tr;if(s&&i.delete(s.from,s.to),!g(i.doc,e.attrs.id)||t>=i.doc.childCount)return!1;let a=0;for(let m=0;m<t;m++)a+=i.doc.child(m).nodeSize;let r=i.doc.child(t),c=r.isTextblock&&r.content.size===0,h=i.doc.maybeChild(t+1),f=c?r.attrs.pos:$(r.attrs.pos,h?.attrs.pos??null),d=Q(e,f,r.attrs.parent??null);if(!d)return s&&n.dispatch(n.state.tr.delete(s.from,s.to)),x("This table has no number column to chart yet."),!0;let w=p.nodes.chart.create(d);return i=c?i.replaceWith(a,a+r.nodeSize,w):i.insert(a+r.nodeSize,w),D.add(d.id),n.dispatch(i.scrollIntoView()),!0}var X=n=>y(n.attrs.cols).map(t=>n.attrs.cols[t].name||"Untitled").join(", ");function kt(n,t,e=null){let s=_(n.state.doc);if(!s.length)return e&&n.dispatch(n.state.tr.delete(e.from,e.to)),x("Add a table first: a chart plots the numbers in a table on this page."),!0;if(s.length===1)return W(n,t,s[0],e);let i=n.state.doc,a=n.nodeDOM(i.resolve(n.state.selection.head).before(1))??n.dom;return q(n,a,s.map(r=>({label:A(i,r.attrs.id)??"",description:`${r.childCount} ${r.childCount===1?"row":"rows"} \xB7 ${X(r)}`,icon:"\u25A6",run:()=>W(n,t,r,e)})))}var V=n=>`<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${n}</svg>`,Z=V('<rect x="2.5" y="3" width="11" height="10" rx="1.5"/><path d="M2.5 6.5h11M6 6.5V13"/>'),tt=V('<g transform="scale(0.6667)" stroke-width="2.25"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></g>'),et=V('<path d="M2.75 4.5h10.5M6.25 4.5V2.75h3.5V4.5M4.25 4.5l.6 8.75h6.3l.6-8.75"/>'),st=[["bar","Bar"],["line","Line"],["pie","Pie"]],it="Untitled chart";function nt(n,t){let e=null;return n.forEach((s,i)=>{e===null&&s.type===p.nodes.table&&s.attrs.id===t&&(e=i)}),e}function E(n){let t=[];return n.forEach(e=>{e.type===p.nodes.table&&y(e.attrs.cols).length>1&&t.push(e)}),t.map(e=>({id:e.attrs.id,name:A(n,e.attrs.id),rows:e.childCount}))}function at(n){let t=y(n.attrs.cols);if(!t.length)return null;let e=M(n),s=t.find(a=>e[a]!=="number")??t[0],i=t.filter(a=>a!==s&&e[a]==="number");return{x:s,series:i.length?i:t.filter(a=>a!==s).slice(0,1)}}function l(n,t,e,s=null){let i=n.createElement(t);return e&&(i.className=e),s!==null&&(i.textContent=s),i}function C(n,t,e,s=!1){let i=l(n,"option","",e);return i.value=t,i.selected=s,i}function T(n,t,e){let s=l(n,"select","page-chart-select");return s.dataset.field=t,s.setAttribute("aria-label",e),s}var Y=class{constructor(t,e,s){this.node=t,this.view=e,this.getPos=s,this.source=void 0,this.tables=null,this.frame=null,this.unsaved=null,this.titleInput=null;let i=e.dom.ownerDocument;this.doc=i,this.dom=i.createElement("figure"),this.dom.className="page-chart",this.dom.dataset.id=t.attrs.id??"",this.dom.dataset.type="chart",this.head=l(i,"div","page-chart-head"),this.head.contentEditable="false",this.title=l(i,"span","page-chart-title"),this.chip=l(i,"button","page-chart-source"),this.chip.type="button",this.chip.contentEditable="false",this.chip.setAttribute("aria-label","Go to source table"),this.chip.innerHTML=Z,this.chipName=l(i,"span","page-chart-source-name"),this.chip.append(this.chipName),this.chip.addEventListener("click",()=>this.goToSource()),this.edit=l(i,"button","page-chart-edit"),this.edit.type="button",this.edit.contentEditable="false",this.edit.setAttribute("aria-haspopup","dialog"),this.edit.setAttribute("aria-expanded","false"),this.edit.innerHTML=tt,this.edit.append("Edit chart"),this.edit.addEventListener("click",()=>this.panel.isConnected?this.closePanel(!0):this.openPanel()),this.head.append(this.title,this.chip,this.edit),this.plot=l(i,"div","page-chart-plot"),this.broken=l(i,"div","page-chart-broken"),this.broken.hidden=!0,this.broken.contentEditable="false",this.brokenKey=null,this.brokenSelect=null,this.broken.addEventListener("click",a=>this.brokenClick(a)),this.panel=l(i,"div","page-chart-panel"),this.panel.tabIndex=-1,this.panel.contentEditable="false",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label","Chart settings"),this.panel.addEventListener("click",a=>this.panelClick(a)),this.panel.addEventListener("change",a=>this.panelChange(a)),this.panel.addEventListener("mousedown",a=>{a.target.closest?.("button")&&a.preventDefault()}),this.outside=a=>{!this.panel.isConnected||this.dom.contains(a.target)||(this.commitTitle(),this.closePanel())},this.escape=a=>{!this.panel.isConnected||a.key!=="Escape"||(a.preventDefault(),a.stopPropagation(),this.closePanel(!0))},i.addEventListener("mousedown",this.outside,!0),i.addEventListener("keydown",this.escape,!0),this.dom.append(this.head,this.plot,this.broken),S.has(e)||S.set(e,new Set),S.get(e).add(this),this.refresh(),D.delete(t.attrs.id)&&this.openSoon()}refresh(){this.renderHead(),this.panel.isConnected&&this.panelKey()!==this.renderedKey&&this.redrawPanel();let t=this.view.state.doc,e=g(t,this.node.attrs.source),s=E(t).map(i=>`${i.id}:${i.name}:${i.rows}`).join("|");e===this.source&&s===this.tables||(this.source=e,this.tables=s,this.schedule())}schedule(){if(this.frame!==null)return;let t=this.dom.ownerDocument.defaultView,e=t.requestAnimationFrame?.bind(t)??(s=>t.setTimeout(s,0));this.frame=e(()=>{this.frame=null,this.draw()})}draw(){let t=this.node.attrs,e=j({id:t.id,type:t.kind,x:t.x,series:t.series,title:t.title,highlight:t.highlight},N(this.source));this.plot.innerHTML=U(e,{width:640,height:320,narrow:this.dom.getBoundingClientRect().width<480}),this.renderBroken(e)}renderBroken(t){let e=t.state==="missing"&&t.reason==="table";if(this.plot.hidden=e,this.broken.hidden=!e,!e){this.brokenKey!==null&&(this.broken.textContent="",this.brokenKey=null,this.brokenSelect=null);return}let s=E(this.view.state.doc),i=s.map(h=>`${h.id}:${h.name}:${h.rows}`).join("|");if(this.brokenKey===i)return;this.brokenKey=i,this.brokenSelect=null;let a=this.doc;this.broken.textContent="",this.broken.append(l(a,"div","page-chart-broken-head","This chart's table was deleted"),l(a,"p","page-chart-broken-text","Pick another table in this document, or delete the chart. Undo brings the table back."));let r=l(a,"div","page-chart-broken-actions");if(s.length){let h=T(a,"rescue","Source table");for(let d of s)h.append(C(a,d.id,`${d.name} (${d.rows} ${d.rows===1?"row":"rows"})`));this.brokenSelect=h;let f=l(a,"button","page-chart-use","Use this table");f.type="button",f.dataset.action="use",r.append(h,f)}let c=l(a,"button","page-chart-delete","Delete chart");c.type="button",c.dataset.action="delete",r.append(c),this.broken.append(r)}brokenClick(t){let e=t.target.closest?.("button[data-action]");e&&(e.dataset.action==="delete"?this.removeChart():e.dataset.action==="use"&&this.switchSource(this.brokenSelect?.value??""))}openSoon(){let t=this.dom.ownerDocument.defaultView;(t.requestAnimationFrame?.bind(t)??(s=>t.setTimeout(s,0)))(()=>{!this.view.isDestroyed&&this.dom.isConnected&&this.openPanel()})}renderHead(){let t=this.node.attrs,e=A(this.view.state.doc,t.source),s=!g(this.view.state.doc,t.source);this.title.textContent=t.title||it,this.title.classList.toggle("is-empty",!t.title),this.chipName.textContent=s?"No table":e??"",this.chip.disabled=s}setAttrs(t){let e=this.getPos();if(e==null)return;let s=this.view.state.doc.nodeAt(e);s?.type===p.nodes.chart&&this.view.dispatch(this.view.state.tr.setNodeMarkup(e,null,{...s.attrs,...t}))}row(t,...e){let s=l(this.doc,"div","page-chart-row");return t&&s.append(l(this.doc,"span","page-chart-label",t)),s.append(...e),s}panelKey(){let t=this.view.state.doc,e=E(t).map(s=>`${s.id}:${s.name}:${s.rows}`).join("|");return JSON.stringify([this.node.attrs,e,N(g(t,this.node.attrs.source))])}redrawPanel(){let t=this.doc.activeElement,e=t&&this.panel.contains(t)?t.dataset??{}:null,s=this.titleInput,i=s&&s.value!==this.renderedTitle?{value:s.value,start:s.selectionStart,end:s.selectionEnd}:null;if(this.renderPanel(),i&&this.titleInput&&(this.titleInput.value=i.value),!e)return;let a=[...this.panel.querySelectorAll("button, input, select")].find(r=>["field","kind","col","action"].every(c=>r.dataset[c]===e[c]));if(!a)return this.panel.focus();a.focus(),i&&a===this.titleInput&&a.setSelectionRange?.(i.start,i.end)}renderPanel(){let t=this.doc;this.renderedKey=this.panelKey(),this.renderedTitle=this.node.attrs.title??"";let e=this.node.attrs,s=N(this.source),i=s?.cols??[],a=s?.rows??[],r=e.kind==="pie";this.unsaved?.dispose(),this.unsaved=null,this.titleInput=null,this.panel.textContent="";let c=l(t,"div","page-chart-types");for(let[o,P]of st){let b=l(t,"button","page-chart-type",P);b.type="button",b.dataset.kind=o,b.setAttribute("aria-pressed",String(e.kind===o)),c.append(b)}this.panel.append(this.row("Chart type",c));let h=T(t,"source","Source table");for(let o of E(this.view.state.doc))h.append(C(t,o.id,`${o.name} (${o.rows} ${o.rows===1?"row":"rows"})`,o.id===e.source));this.panel.append(this.row("Source table",h));let f=T(t,"labels","Labels column");for(let o of i)f.append(C(t,o.id,o.name||o.id,o.id===e.x));this.panel.append(this.row("Labels column",f));let d=l(t,"div","page-chart-values");i.filter(o=>o.id!==e.x).forEach((o,P)=>{let b=l(t,"label","page-chart-value"),v=l(t,"input");v.type="checkbox",v.dataset.field="series",v.dataset.col=o.id,v.checked=e.series.includes(o.id);let I=l(t,"span","page-chart-swatch");I.style.background=`var(--chart-${P%6+1})`,I.setAttribute("aria-hidden","true"),b.append(v,I,l(t,"span","page-chart-value-name",o.name||o.id)),d.append(b)});let w=this.row(r?"Value column":"Value columns",d);r&&w.append(l(t,"span","page-chart-hint","Pie charts plot the first value column across rows.")),this.panel.append(w);let m=T(t,"highlight","Highlight row");m.append(C(t,"","None",!e.highlight));for(let o of a)m.append(C(t,o.id,O(o.cells?.[e.x])||o.id,o.id===e.highlight));this.panel.append(this.row("Highlight row",m));let u=l(t,"input","page-chart-title-input");u.type="text",u.dataset.field="title",u.setAttribute("aria-label","Chart title"),u.value=e.title??"",u.addEventListener("keydown",o=>{o.isComposing||o.keyCode===229||o.key==="Enter"&&(o.preventDefault(),o.stopPropagation(),this.commitTitle())}),u.addEventListener("change",()=>this.commitTitle()),u.addEventListener("blur",()=>this.commitTitle()),this.titleInput=u,this.panel.append(this.row("Chart title",u));let H=l(t,"div","page-chart-foot"),k=l(t,"button","page-chart-remove");k.type="button",k.dataset.action="remove",k.innerHTML=et,k.append("Remove");let L=l(t,"button","page-chart-done","Done");L.type="button",L.dataset.action="done",H.append(k,L),this.panel.append(H),this.unsaved=K({id:"chart-title",isPending:()=>u.isConnected&&u.value!==(this.node.attrs.title??"")})}openPanel(){this.panel.isConnected||(this.renderPanel(),this.dom.append(this.panel),this.edit.setAttribute("aria-expanded","true"),this.panel.focus())}closePanel(t=!1){this.panel.isConnected&&(this.unsaved?.dispose(),this.unsaved=null,this.titleInput=null,this.panel.remove(),this.edit.setAttribute("aria-expanded","false"),t&&this.edit.focus())}panelClick(t){let e=t.target.closest?.("button");e&&(e.dataset.action==="done"?(this.commitTitle(),this.closePanel(!0)):e.dataset.action==="remove"?this.removeChart():e.dataset.kind&&this.setAttrs({kind:e.dataset.kind}))}panelChange(t){let e=t.target;if(e?.dataset){if(e.dataset.field==="source")this.switchSource(e.value);else if(e.dataset.field==="labels")this.setAttrs({x:e.value,series:this.node.attrs.series.filter(s=>s!==e.value)});else if(e.dataset.field==="highlight")this.setAttrs({highlight:e.value||null});else if(e.dataset.field==="series"){let s=this.node.attrs.series.filter(i=>i!==e.dataset.col);this.setAttrs({series:e.checked?[...s,e.dataset.col]:s})}}}switchSource(t){let e=g(this.view.state.doc,t),s=e?at(e):null;s&&this.setAttrs({source:t,x:s.x,series:s.series})}commitTitle(){let t=this.titleInput;!t||t.value===(this.node.attrs.title??"")||this.setAttrs({title:t.value})}goToSource(){let t=this.view.state.doc,e=nt(t,this.node.attrs.source),s=e===null?null:t.nodeAt(e);if(!s?.childCount||!s.child(0).childCount)return;let i=e+3;this.view.dispatch(this.view.state.tr.setSelection(J.create(t,i)).scrollIntoView()),this.view.focus?.()}removeChart(){let t=this.getPos();if(t==null)return;let e=this.view.state.doc.nodeAt(t);if(e?.type!==p.nodes.chart)return;this.closePanel();let s=this.view.state.tr.delete(t,t+e.nodeSize);s.setSelection(J.near(s.doc.resolve(Math.min(t,s.doc.content.size)),-1)),this.view.dispatch(G(s).scrollIntoView())}update(t){if(t.type!==p.nodes.chart)return!1;let e=!t.sameMarkup(this.node);return this.node=t,this.dom.dataset.id=t.attrs.id??"",e&&(this.source=g(this.view.state.doc,t.attrs.source),this.renderHead(),this.schedule()),!0}stopEvent(t){return!!t.target.closest?.(".page-chart-head, .page-chart-panel")}destroy(){if(this.unsaved?.dispose(),this.unsaved=null,this.doc.removeEventListener("mousedown",this.outside,!0),this.doc.removeEventListener("keydown",this.escape,!0),S.get(this.view)?.delete(this),this.frame!==null){let t=this.dom.ownerDocument.defaultView;t.cancelAnimationFrame?t.cancelAnimationFrame(this.frame):t.clearTimeout(this.frame)}}};function vt(n){for(let t of S.get(n)??[])t.refresh()}export{wt as a,X as b,kt as c,Y as d,vt as e};
|
|
1
|
+
import{c as M,g as _,h as A,w as q}from"./c-4FJTBE6I.js";import{B as G}from"./c-AIWN4QN4.js";import{D as O,G as $,I as y,J as B,M as R,Z as j,_ as U,b as z,m as p,na as F}from"./c-QIXT3Q7C.js";import{a as x}from"./c-WCXLG3MV.js";import{a as K}from"./c-I2SCCUEW.js";var{TextSelection:J}=z,S=new WeakMap,D=new Set;function g(n,t){let e=null;return n.forEach(s=>{s.type===p.nodes.table&&s.attrs.id===t&&(e=s)}),e}function N(n){return n?F({[n.attrs.id]:R(n)})[0]:null}function Q(n,t,e){let s=y(n.attrs.cols);if(!s.length)return null;let i=M(n),a=s.filter(r=>r!==s[0]&&i[r]==="number");return a.length?{id:B(),pos:t,parent:e,source:n.attrs.id,kind:"bar",x:s[0],series:a,title:"",highlight:null}:null}function wt(n,t){let e=n.state.doc,s=e.nodeAt(t);if(s?.type!==p.nodes.table)return!1;let i=t+s.nodeSize,a=e.maybeChild(e.resolve(i).index(0)),r=Q(s,$(s.attrs.pos,a?.attrs.pos??null),s.attrs.parent);return r?(D.add(r.id),n.dispatch(n.state.tr.insert(i,p.nodes.chart.create(r))),!0):(x("This table has no number column to chart yet."),!0)}function W(n,t,e,s){let i=n.state.tr;if(s&&i.delete(s.from,s.to),!g(i.doc,e.attrs.id)||t>=i.doc.childCount)return!1;let a=0;for(let m=0;m<t;m++)a+=i.doc.child(m).nodeSize;let r=i.doc.child(t),c=r.isTextblock&&r.content.size===0,h=i.doc.maybeChild(t+1),f=c?r.attrs.pos:$(r.attrs.pos,h?.attrs.pos??null),d=Q(e,f,r.attrs.parent??null);if(!d)return s&&n.dispatch(n.state.tr.delete(s.from,s.to)),x("This table has no number column to chart yet."),!0;let w=p.nodes.chart.create(d);return i=c?i.replaceWith(a,a+r.nodeSize,w):i.insert(a+r.nodeSize,w),D.add(d.id),n.dispatch(i.scrollIntoView()),!0}var X=n=>y(n.attrs.cols).map(t=>n.attrs.cols[t].name||"Untitled").join(", ");function kt(n,t,e=null){let s=_(n.state.doc);if(!s.length)return e&&n.dispatch(n.state.tr.delete(e.from,e.to)),x("Add a table first: a chart plots the numbers in a table on this page."),!0;if(s.length===1)return W(n,t,s[0],e);let i=n.state.doc,a=n.nodeDOM(i.resolve(n.state.selection.head).before(1))??n.dom;return q(n,a,s.map(r=>({label:A(i,r.attrs.id)??"",description:`${r.childCount} ${r.childCount===1?"row":"rows"} \xB7 ${X(r)}`,icon:"\u25A6",run:()=>W(n,t,r,e)})))}var V=n=>`<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${n}</svg>`,Z=V('<rect x="2.5" y="3" width="11" height="10" rx="1.5"/><path d="M2.5 6.5h11M6 6.5V13"/>'),tt=V('<g transform="scale(0.6667)" stroke-width="2.25"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></g>'),et=V('<path d="M2.75 4.5h10.5M6.25 4.5V2.75h3.5V4.5M4.25 4.5l.6 8.75h6.3l.6-8.75"/>'),st=[["bar","Bar"],["line","Line"],["pie","Pie"]],it="Untitled chart";function nt(n,t){let e=null;return n.forEach((s,i)=>{e===null&&s.type===p.nodes.table&&s.attrs.id===t&&(e=i)}),e}function E(n){let t=[];return n.forEach(e=>{e.type===p.nodes.table&&y(e.attrs.cols).length>1&&t.push(e)}),t.map(e=>({id:e.attrs.id,name:A(n,e.attrs.id),rows:e.childCount}))}function at(n){let t=y(n.attrs.cols);if(!t.length)return null;let e=M(n),s=t.find(a=>e[a]!=="number")??t[0],i=t.filter(a=>a!==s&&e[a]==="number");return{x:s,series:i.length?i:t.filter(a=>a!==s).slice(0,1)}}function l(n,t,e,s=null){let i=n.createElement(t);return e&&(i.className=e),s!==null&&(i.textContent=s),i}function C(n,t,e,s=!1){let i=l(n,"option","",e);return i.value=t,i.selected=s,i}function T(n,t,e){let s=l(n,"select","page-chart-select");return s.dataset.field=t,s.setAttribute("aria-label",e),s}var Y=class{constructor(t,e,s){this.node=t,this.view=e,this.getPos=s,this.source=void 0,this.tables=null,this.frame=null,this.unsaved=null,this.titleInput=null;let i=e.dom.ownerDocument;this.doc=i,this.dom=i.createElement("figure"),this.dom.className="page-chart",this.dom.dataset.id=t.attrs.id??"",this.dom.dataset.type="chart",this.head=l(i,"div","page-chart-head"),this.head.contentEditable="false",this.title=l(i,"span","page-chart-title"),this.chip=l(i,"button","page-chart-source"),this.chip.type="button",this.chip.contentEditable="false",this.chip.setAttribute("aria-label","Go to source table"),this.chip.innerHTML=Z,this.chipName=l(i,"span","page-chart-source-name"),this.chip.append(this.chipName),this.chip.addEventListener("click",()=>this.goToSource()),this.edit=l(i,"button","page-chart-edit"),this.edit.type="button",this.edit.contentEditable="false",this.edit.setAttribute("aria-haspopup","dialog"),this.edit.setAttribute("aria-expanded","false"),this.edit.innerHTML=tt,this.edit.append("Edit chart"),this.edit.addEventListener("click",()=>this.panel.isConnected?this.closePanel(!0):this.openPanel()),this.head.append(this.title,this.chip,this.edit),this.plot=l(i,"div","page-chart-plot"),this.broken=l(i,"div","page-chart-broken"),this.broken.hidden=!0,this.broken.contentEditable="false",this.brokenKey=null,this.brokenSelect=null,this.broken.addEventListener("click",a=>this.brokenClick(a)),this.panel=l(i,"div","page-chart-panel"),this.panel.tabIndex=-1,this.panel.contentEditable="false",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label","Chart settings"),this.panel.addEventListener("click",a=>this.panelClick(a)),this.panel.addEventListener("change",a=>this.panelChange(a)),this.panel.addEventListener("mousedown",a=>{a.target.closest?.("button")&&a.preventDefault()}),this.outside=a=>{!this.panel.isConnected||this.dom.contains(a.target)||(this.commitTitle(),this.closePanel())},this.escape=a=>{!this.panel.isConnected||a.key!=="Escape"||(a.preventDefault(),a.stopPropagation(),this.closePanel(!0))},i.addEventListener("mousedown",this.outside,!0),i.addEventListener("keydown",this.escape,!0),this.dom.append(this.head,this.plot,this.broken),S.has(e)||S.set(e,new Set),S.get(e).add(this),this.refresh(),D.delete(t.attrs.id)&&this.openSoon()}refresh(){this.renderHead(),this.panel.isConnected&&this.panelKey()!==this.renderedKey&&this.redrawPanel();let t=this.view.state.doc,e=g(t,this.node.attrs.source),s=E(t).map(i=>`${i.id}:${i.name}:${i.rows}`).join("|");e===this.source&&s===this.tables||(this.source=e,this.tables=s,this.schedule())}schedule(){if(this.frame!==null)return;let t=this.dom.ownerDocument.defaultView,e=t.requestAnimationFrame?.bind(t)??(s=>t.setTimeout(s,0));this.frame=e(()=>{this.frame=null,this.draw()})}draw(){let t=this.node.attrs,e=j({id:t.id,type:t.kind,x:t.x,series:t.series,title:t.title,highlight:t.highlight},N(this.source));this.plot.innerHTML=U(e,{width:640,height:320,narrow:this.dom.getBoundingClientRect().width<480}),this.renderBroken(e)}renderBroken(t){let e=t.state==="missing"&&t.reason==="table";if(this.plot.hidden=e,this.broken.hidden=!e,!e){this.brokenKey!==null&&(this.broken.textContent="",this.brokenKey=null,this.brokenSelect=null);return}let s=E(this.view.state.doc),i=s.map(h=>`${h.id}:${h.name}:${h.rows}`).join("|");if(this.brokenKey===i)return;this.brokenKey=i,this.brokenSelect=null;let a=this.doc;this.broken.textContent="",this.broken.append(l(a,"div","page-chart-broken-head","This chart's table was deleted"),l(a,"p","page-chart-broken-text","Pick another table in this document, or delete the chart. Undo brings the table back."));let r=l(a,"div","page-chart-broken-actions");if(s.length){let h=T(a,"rescue","Source table");for(let d of s)h.append(C(a,d.id,`${d.name} (${d.rows} ${d.rows===1?"row":"rows"})`));this.brokenSelect=h;let f=l(a,"button","page-chart-use","Use this table");f.type="button",f.dataset.action="use",r.append(h,f)}let c=l(a,"button","page-chart-delete","Delete chart");c.type="button",c.dataset.action="delete",r.append(c),this.broken.append(r)}brokenClick(t){let e=t.target.closest?.("button[data-action]");e&&(e.dataset.action==="delete"?this.removeChart():e.dataset.action==="use"&&this.switchSource(this.brokenSelect?.value??""))}openSoon(){let t=this.dom.ownerDocument.defaultView;(t.requestAnimationFrame?.bind(t)??(s=>t.setTimeout(s,0)))(()=>{!this.view.isDestroyed&&this.dom.isConnected&&this.openPanel()})}renderHead(){let t=this.node.attrs,e=A(this.view.state.doc,t.source),s=!g(this.view.state.doc,t.source);this.title.textContent=t.title||it,this.title.classList.toggle("is-empty",!t.title),this.chipName.textContent=s?"No table":e??"",this.chip.disabled=s}setAttrs(t){let e=this.getPos();if(e==null)return;let s=this.view.state.doc.nodeAt(e);s?.type===p.nodes.chart&&this.view.dispatch(this.view.state.tr.setNodeMarkup(e,null,{...s.attrs,...t}))}row(t,...e){let s=l(this.doc,"div","page-chart-row");return t&&s.append(l(this.doc,"span","page-chart-label",t)),s.append(...e),s}panelKey(){let t=this.view.state.doc,e=E(t).map(s=>`${s.id}:${s.name}:${s.rows}`).join("|");return JSON.stringify([this.node.attrs,e,N(g(t,this.node.attrs.source))])}redrawPanel(){let t=this.doc.activeElement,e=t&&this.panel.contains(t)?t.dataset??{}:null,s=this.titleInput,i=s&&s.value!==this.renderedTitle?{value:s.value,start:s.selectionStart,end:s.selectionEnd}:null;if(this.renderPanel(),i&&this.titleInput&&(this.titleInput.value=i.value),!e)return;let a=[...this.panel.querySelectorAll("button, input, select")].find(r=>["field","kind","col","action"].every(c=>r.dataset[c]===e[c]));if(!a)return this.panel.focus();a.focus(),i&&a===this.titleInput&&a.setSelectionRange?.(i.start,i.end)}renderPanel(){let t=this.doc;this.renderedKey=this.panelKey(),this.renderedTitle=this.node.attrs.title??"";let e=this.node.attrs,s=N(this.source),i=s?.cols??[],a=s?.rows??[],r=e.kind==="pie";this.unsaved?.dispose(),this.unsaved=null,this.titleInput=null,this.panel.textContent="";let c=l(t,"div","page-chart-types");for(let[o,P]of st){let b=l(t,"button","page-chart-type",P);b.type="button",b.dataset.kind=o,b.setAttribute("aria-pressed",String(e.kind===o)),c.append(b)}this.panel.append(this.row("Chart type",c));let h=T(t,"source","Source table");for(let o of E(this.view.state.doc))h.append(C(t,o.id,`${o.name} (${o.rows} ${o.rows===1?"row":"rows"})`,o.id===e.source));this.panel.append(this.row("Source table",h));let f=T(t,"labels","Labels column");for(let o of i)f.append(C(t,o.id,o.name||o.id,o.id===e.x));this.panel.append(this.row("Labels column",f));let d=l(t,"div","page-chart-values");i.filter(o=>o.id!==e.x).forEach((o,P)=>{let b=l(t,"label","page-chart-value"),v=l(t,"input");v.type="checkbox",v.dataset.field="series",v.dataset.col=o.id,v.checked=e.series.includes(o.id);let I=l(t,"span","page-chart-swatch");I.style.background=`var(--chart-${P%6+1})`,I.setAttribute("aria-hidden","true"),b.append(v,I,l(t,"span","page-chart-value-name",o.name||o.id)),d.append(b)});let w=this.row(r?"Value column":"Value columns",d);r&&w.append(l(t,"span","page-chart-hint","Pie charts plot the first value column across rows.")),this.panel.append(w);let m=T(t,"highlight","Highlight row");m.append(C(t,"","None",!e.highlight));for(let o of a)m.append(C(t,o.id,O(o.cells?.[e.x])||o.id,o.id===e.highlight));this.panel.append(this.row("Highlight row",m));let u=l(t,"input","page-chart-title-input");u.type="text",u.dataset.field="title",u.setAttribute("aria-label","Chart title"),u.value=e.title??"",u.addEventListener("keydown",o=>{o.isComposing||o.keyCode===229||o.key==="Enter"&&(o.preventDefault(),o.stopPropagation(),this.commitTitle())}),u.addEventListener("change",()=>this.commitTitle()),u.addEventListener("blur",()=>this.commitTitle()),this.titleInput=u,this.panel.append(this.row("Chart title",u));let H=l(t,"div","page-chart-foot"),k=l(t,"button","page-chart-remove");k.type="button",k.dataset.action="remove",k.innerHTML=et,k.append("Remove");let L=l(t,"button","page-chart-done","Done");L.type="button",L.dataset.action="done",H.append(k,L),this.panel.append(H),this.unsaved=K({id:"chart-title",isPending:()=>u.isConnected&&u.value!==(this.node.attrs.title??"")})}openPanel(){this.panel.isConnected||(this.renderPanel(),this.dom.append(this.panel),this.edit.setAttribute("aria-expanded","true"),this.panel.focus())}closePanel(t=!1){this.panel.isConnected&&(this.unsaved?.dispose(),this.unsaved=null,this.titleInput=null,this.panel.remove(),this.edit.setAttribute("aria-expanded","false"),t&&this.edit.focus())}panelClick(t){let e=t.target.closest?.("button");e&&(e.dataset.action==="done"?(this.commitTitle(),this.closePanel(!0)):e.dataset.action==="remove"?this.removeChart():e.dataset.kind&&this.setAttrs({kind:e.dataset.kind}))}panelChange(t){let e=t.target;if(e?.dataset){if(e.dataset.field==="source")this.switchSource(e.value);else if(e.dataset.field==="labels")this.setAttrs({x:e.value,series:this.node.attrs.series.filter(s=>s!==e.value)});else if(e.dataset.field==="highlight")this.setAttrs({highlight:e.value||null});else if(e.dataset.field==="series"){let s=this.node.attrs.series.filter(i=>i!==e.dataset.col);this.setAttrs({series:e.checked?[...s,e.dataset.col]:s})}}}switchSource(t){let e=g(this.view.state.doc,t),s=e?at(e):null;s&&this.setAttrs({source:t,x:s.x,series:s.series})}commitTitle(){let t=this.titleInput;!t||t.value===(this.node.attrs.title??"")||this.setAttrs({title:t.value})}goToSource(){let t=this.view.state.doc,e=nt(t,this.node.attrs.source),s=e===null?null:t.nodeAt(e);if(!s?.childCount||!s.child(0).childCount)return;let i=e+3;this.view.dispatch(this.view.state.tr.setSelection(J.create(t,i)).scrollIntoView()),this.view.focus?.()}removeChart(){let t=this.getPos();if(t==null)return;let e=this.view.state.doc.nodeAt(t);if(e?.type!==p.nodes.chart)return;this.closePanel();let s=this.view.state.tr.delete(t,t+e.nodeSize);s.setSelection(J.near(s.doc.resolve(Math.min(t,s.doc.content.size)),-1)),this.view.dispatch(G(s).scrollIntoView())}update(t){if(t.type!==p.nodes.chart)return!1;let e=!t.sameMarkup(this.node);return this.node=t,this.dom.dataset.id=t.attrs.id??"",e&&(this.source=g(this.view.state.doc,t.attrs.source),this.renderHead(),this.schedule()),!0}stopEvent(t){return!!t.target.closest?.(".page-chart-head, .page-chart-panel")}destroy(){if(this.unsaved?.dispose(),this.unsaved=null,this.doc.removeEventListener("mousedown",this.outside,!0),this.doc.removeEventListener("keydown",this.escape,!0),S.get(this.view)?.delete(this),this.frame!==null){let t=this.dom.ownerDocument.defaultView;t.cancelAnimationFrame?t.cancelAnimationFrame(this.frame):t.clearTimeout(this.frame)}}};function vt(n){for(let t of S.get(n)??[])t.refresh()}export{wt as a,X as b,kt as c,Y as d,vt as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as h}from"./c-KBS3UV6B.js";import{i as k,j as y}from"./c-
|
|
1
|
+
import{c as h}from"./c-KBS3UV6B.js";import{i as k,j as y}from"./c-4FJTBE6I.js";import"./c-EXKHPOVC.js";import"./c-L5VFATT6.js";import"./c-CQQDL6O4.js";import"./c-ZGDYHKG3.js";import"./c-W4JCVLAB.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import{B as g}from"./c-AIWN4QN4.js";import{b as m,m as d}from"./c-QIXT3Q7C.js";import"./c-WCXLG3MV.js";import"./c-57XDY6HC.js";import"./c-VHNSBD2M.js";var b=e=>String(e).padStart(2,"0");function A(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let s=new Date(`${e}T12:00:00Z`);return Number.isFinite(s.valueOf())&&s.toISOString().slice(0,10)===e}var $=(e=new Date)=>`${e.getFullYear()}-${b(e.getMonth()+1)}-${b(e.getDate())}`,E=(e,s)=>{let a=new Date(`${e}T12:00:00Z`);return a.setUTCDate(a.getUTCDate()+s),a.toISOString().slice(0,10)},I=e=>{let s=E(e,1);return[{id:"today",name:`Today (${e})`,date:e},{id:"tomorrow",name:`Tomorrow (${s})`,date:s}]};function L({view:e=null}={}){if(!e)return{run:()=>({ok:!1,code:"not-editing"}),dispose(){}};let s=e.dom.ownerDocument,a=null;function l(t){let o=e.state;if(!o.selection.empty||o.selection.from!==t.from||t.from<0||t.from>o.doc.content.size)return null;let r=o.doc.resolve(t.from);return!r.parent.isTextblock||r.parent.type.spec.code||!r.parent.type.allowsMarkType(d.marks.date)?null:t.from}function D(t){try{let o=e.dom.parentElement?.getBoundingClientRect?.()??{left:0,top:0},r=e.coordsAtPos(t.from);return{x:Math.max(8,r.left-o.left),y:r.bottom+6-o.top}}catch{return null}}function u(t){let o=t.picker.activeId();o?e.dom.setAttribute("aria-activedescendant",o):e.dom.getAttribute("aria-activedescendant")?.startsWith(t.picker.el.id)&&e.dom.removeAttribute("aria-activedescendant")}function c(){let t=a;if(t){a=null;for(let[o,r,n,i]of t.listen)o.removeEventListener(r,n,i);e.dom.getAttribute("aria-activedescendant")?.startsWith(`${t.picker.el.id}-`)&&e.dom.removeAttribute("aria-activedescendant"),t.picker.destroy()}}function x(t,o){let r=String(o),n=e.state.tr.insertText(r,t,t);return n.addMark(t,t+r.length,d.marks.date.create({date:r})),n.insertText(" ",t+r.length),n.setSelection(m.TextSelection.create(n.doc,t+r.length+1)),e.dispatch(g(n)),e.focus(),{ok:!0,date:r}}async function f(t){let o=a;if(!o)return{ok:!1,code:"not-editing"};let r=o.picker.personAt(t),n=l(o);return n===null||!r||!A(r.date)?(c(),r?n===null?{ok:!1,code:"stale-target"}:{ok:!1,code:"invalid-date"}:{ok:!1,code:"no-date"}):(c(),k(e,()=>{let i=l(o);return i===null?{ok:!1,code:"stale-target"}:x(i,r.date)}))}function S(t){let o=a;if(!o||y(t,e))return;let r=()=>{t.preventDefault(),t.stopPropagation()};t.key==="ArrowDown"||t.key==="ArrowUp"?(r(),o.picker.move(t.key==="ArrowDown"?1:-1),u(o)):t.key==="Enter"?(r(),f(o.picker.index())):(t.key==="Escape"||t.key==="Tab")&&(r(),c())}function T(){c();let t={from:e.state.selection.from,days:I($()),picker:null,listen:[]};t.picker=h({document:s,label:"Insert a date",empty:"No date to insert",onPick:r=>f(r)}),a=t;let o=(r,n,i,p)=>{r.addEventListener(n,i,p),t.listen.push([r,n,i,p])};return o(s,"keydown",r=>S(r),!0),o(e.dom,"input",()=>c()),o(s,"mousedown",r=>{t.picker.el.contains(r.target)||c()},!0),(e.dom.parentElement??s.body).appendChild(t.picker.el),l(t)===null?(c(),{ok:!1,code:"stale-target"}):(t.picker.show(t.days,D(t)),u(t),{ok:!0,picker:!0})}return{async run(){return T()},dispose(){c()}}}export{L as createFeature,I as earlyDays,A as isISODate,$ as localISODate};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as A,e as I}from"./c-XGH4GS2T.js";import{f as b,j as T}from"./c-3O7OBDCM.js";import{c as M}from"./c-BPF2NSPV.js";var B=15e3,P=12e4,K=15e3,V=4e3,W=5e3,U=50,y=new Set(["sent","acked"]),R=new Set(["done","error","cancelled"]),j="wire",i=new Map,k=new Set,f=null,g=null,D=0,h=null;function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now()}-${Math.random().toString(16).slice(2)}`}function H(e){return new URL(e,window.location.origin).href}function N(){let e=M();return typeof e=="string"&&e!==""?e:null}function w(e){return{id:e.id,type:e.type,state:e.state,helper:e.helper,text:e.text,result:e.result,error:e.error,errorCode:e.errorCode,errorDetails:e.errorDetails,errorSource:e.errorSource,startedAt:e.startedAt}}function m(e,t){let n=w(e);for(let r of k)try{r(n,t||null)}catch(s){console.error("clay.wire: a listener threw",s)}document.dispatchEvent(new CustomEvent("clay:wire-state",{detail:n}))}function Y(e,t){e.state!==t&&(e.state=t,m(e))}function v(e,t,n,{cancelFirst:r=!1,errorCode:s=null}={}){clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,r&&z(e),l(e,"error",n,{errorCode:s,errorSource:"client"})},t)}function q(e){clearTimeout(e.timer),e.timer=null}function Z(){if(!(i.size<=U))for(let[e,t]of i){if(i.size<=U)break;!y.has(t.state)&&t.state!=="landing"&&i.delete(e)}}function ee(){if(g)return g;let e=N(),t=`/_/wire/subscribe?page-url=${encodeURIComponent(window.location.href)}`+(e?`&token=${encodeURIComponent(e)}`:"");return f=new EventSource(H(t)),f.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{return}te(r)},f.onerror=()=>{},g=new Promise(n=>{let r=!1,s=()=>{r||(r=!0,n())};f.onopen=s,setTimeout(s,2e3)}),g}function L(){for(let e of i.values())if(y.has(e.state))return;f&&(f.close(),f=null,g=null)}function te(e){if(!e||typeof e.id!="string")return;let t=i.get(e.id);if(!(!t||!y.has(t.state)))switch(e.type){case"wire/ack":e.payload?.mode==="jsonl"&&Number.isFinite(e.payload.budgetMs)&&e.payload.budgetMs>0?(t.structured=!0,v(t,e.payload.budgetMs+K,"the helper did not finish within its execution budget",{cancelFirst:!0,errorCode:"helper_timeout"})):v(t,P,"the agent stopped responding"),Y(t,"acked");break;case"wire/status":t.structured||v(t,P,"the agent stopped responding"),t.text=typeof e.text=="string"?e.text:"",t.state="acked",ne(t,e),m(t,e);break;case"wire/done":t.result=Object.prototype.hasOwnProperty.call(e,"payload")?e.payload:null,t.document==="edit"?ae(t):l(t,"done",null);break;case"wire/error":re(t,e);break;default:break}}function ne(e,t){if(!e.onStatus||typeof t.text!="string")return;let n={text:t.text};t.payload&&typeof t.payload=="object"&&Object.prototype.hasOwnProperty.call(t.payload,"progress")&&(n.progress=t.payload.progress);try{e.onStatus(n)}catch(r){console.error("clay.wire: an onStatus listener threw",r)}}function re(e,t){let n=t.payload,r=n&&typeof n=="object"&&!Array.isArray(n)&&(n.source==="application"||n.source==="host")&&typeof n.code=="string"&&n.code,s=typeof t.text=="string"&&t.text?t.text:"the handler reported an error";if(!r){l(e,"error",s);return}let a=n.source==="host"&&n.code==="helper_cancelled"?"cancelled":"error";l(e,a,s,{errorCode:n.code,errorDetails:Object.prototype.hasOwnProperty.call(n,"details")?n.details:null,errorSource:n.source})}function oe(){h||(h=e=>{if(e.detail?.source!=="peer"){for(let t of i.values())if(t.state==="landing"){l(t,"done",null);return}}},document.addEventListener("clay:sync-applied",h))}function se(){D>0||!h||(document.removeEventListener("clay:sync-applied",h),h=null)}function ae(e){R.has(e.state)||e.state==="landing"||(q(e),e.state="landing",D++,oe(),e.landingTimer=setTimeout(()=>{l(e,"done",null)},V),m(e),L())}function l(e,t,n,r={}){if(R.has(e.state))return;let s=e.state==="landing";if(q(e),clearTimeout(e.landingTimer),e.landingTimer=null,e.abort?.abort(),s&&(D--,se()),e.error=n,Object.prototype.hasOwnProperty.call(r,"errorCode")&&(e.errorCode=r.errorCode),Object.prototype.hasOwnProperty.call(r,"errorDetails")&&(e.errorDetails=r.errorDetails),Object.prototype.hasOwnProperty.call(r,"errorSource")&&(e.errorSource=r.errorSource),e.state=t,e.signal&&e.signalHandler&&(e.signal.removeEventListener("abort",e.signalHandler),e.signalHandler=null),ue(e),m(e),L(),Z(),e.settle){let a=e.settle;e.settle=null,a(w(e))}}var C=0,$=null,E=null;function ie(){return E||(E=import("./core/save-
|
|
1
|
+
import{d as A,e as I}from"./c-XGH4GS2T.js";import{f as b,j as T}from"./c-3O7OBDCM.js";import{c as M}from"./c-BPF2NSPV.js";var B=15e3,P=12e4,K=15e3,V=4e3,W=5e3,U=50,y=new Set(["sent","acked"]),R=new Set(["done","error","cancelled"]),j="wire",i=new Map,k=new Set,f=null,g=null,D=0,h=null;function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now()}-${Math.random().toString(16).slice(2)}`}function H(e){return new URL(e,window.location.origin).href}function N(){let e=M();return typeof e=="string"&&e!==""?e:null}function w(e){return{id:e.id,type:e.type,state:e.state,helper:e.helper,text:e.text,result:e.result,error:e.error,errorCode:e.errorCode,errorDetails:e.errorDetails,errorSource:e.errorSource,startedAt:e.startedAt}}function m(e,t){let n=w(e);for(let r of k)try{r(n,t||null)}catch(s){console.error("clay.wire: a listener threw",s)}document.dispatchEvent(new CustomEvent("clay:wire-state",{detail:n}))}function Y(e,t){e.state!==t&&(e.state=t,m(e))}function v(e,t,n,{cancelFirst:r=!1,errorCode:s=null}={}){clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,r&&z(e),l(e,"error",n,{errorCode:s,errorSource:"client"})},t)}function q(e){clearTimeout(e.timer),e.timer=null}function Z(){if(!(i.size<=U))for(let[e,t]of i){if(i.size<=U)break;!y.has(t.state)&&t.state!=="landing"&&i.delete(e)}}function ee(){if(g)return g;let e=N(),t=`/_/wire/subscribe?page-url=${encodeURIComponent(window.location.href)}`+(e?`&token=${encodeURIComponent(e)}`:"");return f=new EventSource(H(t)),f.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{return}te(r)},f.onerror=()=>{},g=new Promise(n=>{let r=!1,s=()=>{r||(r=!0,n())};f.onopen=s,setTimeout(s,2e3)}),g}function L(){for(let e of i.values())if(y.has(e.state))return;f&&(f.close(),f=null,g=null)}function te(e){if(!e||typeof e.id!="string")return;let t=i.get(e.id);if(!(!t||!y.has(t.state)))switch(e.type){case"wire/ack":e.payload?.mode==="jsonl"&&Number.isFinite(e.payload.budgetMs)&&e.payload.budgetMs>0?(t.structured=!0,v(t,e.payload.budgetMs+K,"the helper did not finish within its execution budget",{cancelFirst:!0,errorCode:"helper_timeout"})):v(t,P,"the agent stopped responding"),Y(t,"acked");break;case"wire/status":t.structured||v(t,P,"the agent stopped responding"),t.text=typeof e.text=="string"?e.text:"",t.state="acked",ne(t,e),m(t,e);break;case"wire/done":t.result=Object.prototype.hasOwnProperty.call(e,"payload")?e.payload:null,t.document==="edit"?ae(t):l(t,"done",null);break;case"wire/error":re(t,e);break;default:break}}function ne(e,t){if(!e.onStatus||typeof t.text!="string")return;let n={text:t.text};t.payload&&typeof t.payload=="object"&&Object.prototype.hasOwnProperty.call(t.payload,"progress")&&(n.progress=t.payload.progress);try{e.onStatus(n)}catch(r){console.error("clay.wire: an onStatus listener threw",r)}}function re(e,t){let n=t.payload,r=n&&typeof n=="object"&&!Array.isArray(n)&&(n.source==="application"||n.source==="host")&&typeof n.code=="string"&&n.code,s=typeof t.text=="string"&&t.text?t.text:"the handler reported an error";if(!r){l(e,"error",s);return}let a=n.source==="host"&&n.code==="helper_cancelled"?"cancelled":"error";l(e,a,s,{errorCode:n.code,errorDetails:Object.prototype.hasOwnProperty.call(n,"details")?n.details:null,errorSource:n.source})}function oe(){h||(h=e=>{if(e.detail?.source!=="peer"){for(let t of i.values())if(t.state==="landing"){l(t,"done",null);return}}},document.addEventListener("clay:sync-applied",h))}function se(){D>0||!h||(document.removeEventListener("clay:sync-applied",h),h=null)}function ae(e){R.has(e.state)||e.state==="landing"||(q(e),e.state="landing",D++,oe(),e.landingTimer=setTimeout(()=>{l(e,"done",null)},V),m(e),L())}function l(e,t,n,r={}){if(R.has(e.state))return;let s=e.state==="landing";if(q(e),clearTimeout(e.landingTimer),e.landingTimer=null,e.abort?.abort(),s&&(D--,se()),e.error=n,Object.prototype.hasOwnProperty.call(r,"errorCode")&&(e.errorCode=r.errorCode),Object.prototype.hasOwnProperty.call(r,"errorDetails")&&(e.errorDetails=r.errorDetails),Object.prototype.hasOwnProperty.call(r,"errorSource")&&(e.errorSource=r.errorSource),e.state=t,e.signal&&e.signalHandler&&(e.signal.removeEventListener("abort",e.signalHandler),e.signalHandler=null),ue(e),m(e),L(),Z(),e.settle){let a=e.settle;e.settle=null,a(w(e))}}var C=0,$=null,E=null;function ie(){return E||(E=import("./core/save-A5JXV6ME.js")),E}async function le(e){if(!b||e.holdsSave)return;let t=await ie();e.state==="sent"&&($=t,e.holdsSave=!0,!(C++>0)&&t.suspendAutosave())}function ue(e){e.holdsSave&&(e.holdsSave=!1,!(--C>0)&&(C=0,$?.resumeAutosave()))}var c=null,de=()=>!c||c.admitted,ce=(e,t,n)=>Object.assign(new Error(`clay.wire: ${e}`),{code:t,pending:n});function O(e){return e.document!=="edit"||e.generation===T().generation&&de()?!0:(l(e,"error","the page changed mode before this request went out",{errorCode:"stale-document",errorSource:"client"}),!1)}function _e(){return{id:"clay:wire",order:900,prepare(e={}){let t={admitted:e.initial===!0};return c=t,{enable(){c===t&&(t.admitted=!0)},quiesce(){if(c!==t)return;t.admitted=!1;let n=[...i.values()].filter(r=>r.document==="edit"&&(r.holdsSave||y.has(r.state))).map(r=>r.id);if(n.length)throw ce("a request on this page has not settled","pending-input",n)},resume(){c===t&&(t.admitted=!0)},dispose(){c===t&&(c=null)}}}}}function fe(e,t){return new Promise(n=>{let r=!1,s=()=>{r||(r=!0,document.removeEventListener(e,s),n())};document.addEventListener(e,s),setTimeout(s,t)})}async function pe(){if(!b)return;let e=window.clay;if(!e||typeof e.save!="function")return;let{isSaveInProgress:t}=await import("./core/save-core-MKRPSEEO.js"),{savesHeld:n,saveHoldReason:r}=await import("./core/save-A5JXV6ME.js");if(n())throw new Error(r());let s=Date.now()+W;for(let a=0;a<3;a++){t()&&await fe("clay:save-saved",Math.max(0,s-Date.now()));let u=await e.save();if(u?.ok||u?.msgType==="skipped"&&!t())return;if(u?.msgType==="error"||u?.msgType==="unknown")throw new Error(`could not save this page first: ${u.msg||u.msgType}`);if(Date.now()>=s)break}throw new Error("could not save this page before sending")}async function F(e,t){let n={"Content-Type":"application/json","Page-URL":window.location.href},r=N();r&&(n["Save-Token"]=r);let s=await fetch(H("/_/wire/send"),{method:"POST",headers:n,body:JSON.stringify(e),signal:t}),a=null;try{a=await s.json()}catch{a=null}return{ok:s.ok,status:s.status,reply:a}}function he(e,t={}){let n=typeof t.id=="string"&&t.id?t.id:Q(),r=typeof t.type=="string"&&t.type?t.type:"wire/request",s=Object.prototype.hasOwnProperty.call(t,"helper"),a=s&&typeof t.helper=="string"&&t.helper?t.helper:null,u=t.document===void 0?a?"none":"edit":t.document;if(s&&!a)return _(n,r,null,"helper must be a nonempty string","invalid_helper");if(u!=="edit"&&u!=="none")return _(n,r,a,'document must be "edit" or "none"',"invalid_document");if(i.has(n))return _(n,r,a,"a request with this id is already on the wire","duplicate_request");let o={id:n,type:r,state:"sent",helper:a,document:u,structured:!1,onStatus:typeof t.onStatus=="function"?t.onStatus:null,text:"",result:null,error:null,errorCode:null,errorDetails:null,errorSource:null,startedAt:Date.now(),timer:null,landingTimer:null,abort:typeof AbortController=="function"?new AbortController:null,holdsSave:!1,generation:T().generation,settle:null,signal:t.signal&&typeof t.signal.addEventListener=="function"?t.signal:null,signalHandler:null};return o.done=new Promise(d=>{o.settle=d}),i.set(n,o),m(o),o.signal&&(o.signalHandler=()=>x(n),o.signal.addEventListener("abort",o.signalHandler,{once:!0}),o.signal.aborted&&o.signalHandler()),(async()=>{if(o.state!=="sent")return;if(o.helper){let X=await I(j);if(o.state!=="sent")return;if(!X){l(o,"error","this host does not support named wire helpers",{errorCode:"helper_protocol_unsupported",errorSource:"client"});return}}if(!O(o)||o.document==="edit"&&(await le(o),o.state!=="sent"||!O(o)||(await pe(),o.state!=="sent")||!O(o)))return;if(await ee(),o.state!=="sent"){L();return}v(o,B,"the agent never answered",o.helper?{cancelFirst:!0,errorCode:"ack_timeout"}:void 0);let d={type:o.type,id:o.id,text:t.text,payload:e};o.helper&&(d.helper=o.helper),(o.helper||t.document!==void 0)&&(d.document=o.document);let{ok:G,status:J,reply:S}=await F(d,o.abort?.signal);if(o.state!=="sent")return;if(!G){l(o,"error",`the wire refused this request (${J})`);return}let p=S&&S.refused;if(p&&typeof p.code=="string"&&p.code){l(o,"error",p.message||"the handler refused this request",{errorCode:p.code,errorSource:p.source==="application"?"application":"host",errorDetails:null});return}(!S||S.delivered===0)&&l(o,"error","no agent is attached to this file")})().catch(d=>{l(o,"error",d&&d.message?d.message:String(d))}),{id:n,get state(){return o.state},done:o.done,cancel:()=>x(n)}}function _(e,t,n,r,s){let a={id:e,type:t,state:"error",helper:n,text:"",result:null,error:r,errorCode:s,errorDetails:null,errorSource:"client",startedAt:Date.now()};return{id:e,get state(){return a.state},done:Promise.resolve(w(a)),cancel:()=>!1}}function x(e){let t=i.get(e);return!t||!y.has(t.state)?!1:(z(t),l(t,"cancelled",null),!0)}function z(e){F({type:"wire/cancel",id:e.id}).catch(()=>{})}function ye(e){let t=i.get(e);return t?w(t):void 0}function ge(){return[...i.values()].map(w)}function we(){for(let e of i.values())if(y.has(e.state))return!0;return!1}function me(e){return typeof e!="function"?()=>{}:(k.add(e),()=>k.delete(e))}async function Se(){let e=await A({fresh:!0});if(!e.extensions.includes(j))return[];let t=e.document?.helpers;return Array.isArray(t)?t.filter(n=>n&&typeof n.name=="string"&&["ready","denied","unavailable"].includes(n.state)).map(({name:n,state:r})=>({name:n,state:r})):[]}var ve={send:he,cancel:x,get:ye,list:ge,isBusy:we,on:me,helpers:Se},ke=ve;export{_e as a,ve as b,ke as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d}from"./c-KQ7E3PYY.js";import{d as h,h as p,v as g}from"./c-
|
|
1
|
+
import{a as d}from"./c-KQ7E3PYY.js";import{d as h,h as p,v as g}from"./c-AIWN4QN4.js";import{N as u,b as l,ea as c,m,na as f}from"./c-QIXT3Q7C.js";import"./c-VHNSBD2M.js";var{TextSelection:b}=l;function T(r,t){let e=p(r.state.doc),n=e.findIndex(o=>o.node.attrs.id===t);if(n<0)return h(r,"That link's block is gone"),null;let s=[];for(let o=e[n].up;o>=0;o=e[o].up)e[o].node.type===m.nodes.toggle&&!e[o].open&&s.push(e[o].node.attrs.id);let i=r.state.tr.setSelection(b.create(r.state.doc,e[n].at+1)).setMeta("addToHistory",!1);return r.dispatch(g(i,s).scrollIntoView()),e[n]}var a=class{constructor(t,e){this.node=t,this.view=e,this.doc=e.state.doc;let n=e.dom.ownerDocument;this.dom=n.createElement("div"),this.dom.className="page-toc",this.dom.contentEditable="false",this.dom.setAttribute("role","group"),this.dom.setAttribute("aria-label","Table of contents"),this.dom.addEventListener("mousedown",s=>{s.target.closest?.("a")&&s.preventDefault()}),this.dom.addEventListener("click",s=>{let i=s.target.closest?.("a");if(!i)return;s.preventDefault();let o=d(i.getAttribute("href"));o!==null&&T(this.view,o)}),this.render()}update(t){return this.node=t,this.view.state.doc!==this.doc&&(this.doc=this.view.state.doc,this.render()),!0}render(){let t=c(this.node.attrs,f(u(this.doc)));this.dom.innerHTML!==t&&(this.dom.innerHTML=t)}stopEvent(t){return!!t.target.closest?.("a")}ignoreMutation(){return!0}};function I(){return{id:"toc",nodeViews:{toc:(r,t)=>new a(r,t)},css:null,dispose(){}}}export{a as TocView,I as createFeature,T as followTocLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as j}from"./c-UGNV5MFB.js";import{b as S,c as A,f as C,i as l,j as P,l as L,n as B}from"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-HA6INT6J.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var y=0,x=[],b=[],d=null,I=!1,E=!1,v=null,M=null,$=15e3,u=()=>P().mode,p=(e,t)=>Object.assign(new Error(`clay.modeLifecycle: ${e}`),{code:t});function U(){document.dispatchEvent(new Event("clay:modechange"))}function h(e,t="idle",o={}){return l({phase:t,reason:e}),{ok:!1,mode:u(),code:e,...o}}function k(e){for(let t of[...e].reverse())try{t.dispose?.()}catch{}}function D(e){try{e?.reclaimArticle?.()}catch{}try{e?.resume?.()}catch{}}function O(e){document.documentElement.setAttribute("editmode",e?"true":"false")}function G(){try{let e=new URL(window.location.href);if(!e.searchParams.has("editmode"))return;e.searchParams.delete("editmode"),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`)}catch(e){console.warn("clayjs: the URL could not be rewritten after the mode switch",e)}}var N=e=>[...e?.edit?.core??[],...e?.edit?.plugins??[],...e?.edit?.late??[]];function X(e){let t=[];for(let o of N(e)){let n=j(o);if(n!=="export"&&typeof n!="function")continue;let r=e.loaded?.[o];r&&t.push(typeof n=="function"?n(r):r.modeParticipant?.())}return t}async function _(e){let t=new Set(b.map(({id:n})=>n)),o=n=>{if(typeof n?.id!="string"||typeof n.prepare!="function")throw p("a participant needs an id and a prepare()","unsupported-plugin");t.has(n.id)||(t.add(n.id),b.push(n))};if(e)for(let n of X(e))o(await n);for(let n of B())o(await n);return[...b].sort((n,r)=>(n.order??0)-(r.order??0))}function z(e){let t=b.findIndex(o=>o.id===e);t!==-1&&b.splice(t,1)}L(z);function H(e,t){if(!e||e.bytes===null)return!1;let o=t??{};return typeof e.seq=="number"&&typeof o.seq=="number"&&e.seq!==o.seq?e.seq>o.seq:(e.etag??null)!==(o.etag??null)}async function V(e=null){let t=u(),o=C,n=new AbortController,r={generation:++y,destination:P().destination,signal:n.signal,represented:null,reader:null,initial:!1,isCurrent:()=>r.generation===y&&!n.signal.aborted};l({phase:"entering",generation:r.generation,reason:null}),e||(I=!0,E=!1,v=null);let s=[],c=[],f=null,i=null,w=!1,m=(async()=>{try{if(e){let a=await import("./c-KJJPV77R.js");i=await a.prepareReader(e,r),c.push(...await a.importPlan(e,e.edit,{signal:n.signal})),await i?.reconcile(),r.represented=i?i.represented:null,r.reader=i,M=r.represented}f=e?.loaded?.["core/save.js"]??await import("./core/save-
|
|
1
|
+
import{a as j}from"./c-UGNV5MFB.js";import{b as S,c as A,f as C,i as l,j as P,l as L,n as B}from"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-HA6INT6J.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var y=0,x=[],b=[],d=null,I=!1,E=!1,v=null,M=null,$=15e3,u=()=>P().mode,p=(e,t)=>Object.assign(new Error(`clay.modeLifecycle: ${e}`),{code:t});function U(){document.dispatchEvent(new Event("clay:modechange"))}function h(e,t="idle",o={}){return l({phase:t,reason:e}),{ok:!1,mode:u(),code:e,...o}}function k(e){for(let t of[...e].reverse())try{t.dispose?.()}catch{}}function D(e){try{e?.reclaimArticle?.()}catch{}try{e?.resume?.()}catch{}}function O(e){document.documentElement.setAttribute("editmode",e?"true":"false")}function G(){try{let e=new URL(window.location.href);if(!e.searchParams.has("editmode"))return;e.searchParams.delete("editmode"),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`)}catch(e){console.warn("clayjs: the URL could not be rewritten after the mode switch",e)}}var N=e=>[...e?.edit?.core??[],...e?.edit?.plugins??[],...e?.edit?.late??[]];function X(e){let t=[];for(let o of N(e)){let n=j(o);if(n!=="export"&&typeof n!="function")continue;let r=e.loaded?.[o];r&&t.push(typeof n=="function"?n(r):r.modeParticipant?.())}return t}async function _(e){let t=new Set(b.map(({id:n})=>n)),o=n=>{if(typeof n?.id!="string"||typeof n.prepare!="function")throw p("a participant needs an id and a prepare()","unsupported-plugin");t.has(n.id)||(t.add(n.id),b.push(n))};if(e)for(let n of X(e))o(await n);for(let n of B())o(await n);return[...b].sort((n,r)=>(n.order??0)-(r.order??0))}function z(e){let t=b.findIndex(o=>o.id===e);t!==-1&&b.splice(t,1)}L(z);function H(e,t){if(!e||e.bytes===null)return!1;let o=t??{};return typeof e.seq=="number"&&typeof o.seq=="number"&&e.seq!==o.seq?e.seq>o.seq:(e.etag??null)!==(o.etag??null)}async function V(e=null){let t=u(),o=C,n=new AbortController,r={generation:++y,destination:P().destination,signal:n.signal,represented:null,reader:null,initial:!1,isCurrent:()=>r.generation===y&&!n.signal.aborted};l({phase:"entering",generation:r.generation,reason:null}),e||(I=!0,E=!1,v=null);let s=[],c=[],f=null,i=null,w=!1,m=(async()=>{try{if(e){let a=await import("./c-KJJPV77R.js");i=await a.prepareReader(e,r),c.push(...await a.importPlan(e,e.edit,{signal:n.signal})),await i?.reconcile(),r.represented=i?i.represented:null,r.reader=i,M=r.represented}f=e?.loaded?.["core/save.js"]??await import("./core/save-A5JXV6ME.js");for(let a of await _(e)){w=!0;let g=await a.prepare(r);if(g){if(s.push(g),!r.isCurrent())throw p(`"${a.id}" prepared for a stale generation`,"stale-document");if(g.ready&&await g.ready,!r.isCurrent())throw p(`"${a.id}" became ready for a stale generation`,"stale-document")}}if(e||!o){let a=f.adoptEntryBaseline({represented:r.represented});if(a&&a.ok===!1)throw Object.assign(p("the page moved since the last session",a.code||"pending-input"),a);if(H(i?.held??i?.represented,r.represented))throw p("the reader holds a newer file than the session was built from","stale-document")}return!0}catch(a){throw k(s),a}})(),q=null,W=new Promise(a=>{q=setTimeout(()=>{n.abort(),a(!1)},$)}),T;try{T=await Promise.race([m,W])}catch(a){return clearTimeout(q),n.abort(),w?(D(i),h(a?.code||"load-failed","blocked",{message:a?.message})):(D(i),l({phase:"idle",reason:null}),null)}if(clearTimeout(q),!T)return m.catch(()=>{}),k(s.splice(0)),D(i),h("timeout");i?.commit(),l({mode:S?"draft":"edit",isEditMode:!0}),e&&G(),O(!0),f?.setSaveGeneration(r.generation);try{for(let a of s)a.enable()}catch(a){return l({mode:t,isEditMode:o}),O(!1),k(s),n.abort(),e&&(await import("./c-KJJPV77R.js").catch(()=>null))?.startReader(e,M),h(a?.code||"load-failed","blocked",{message:a?.message})}x=s,l({phase:"idle",reason:null}),U();for(let a of c)e?.announce?.(a);return{ok:!0,mode:u(),changed:t!==u()}}async function J(e){if(!e)return[];let t=[];for(let r of N(e)){let s=j(r);if(s!=="export"&&typeof s!="function")continue;let c=e.loaded?.[r];if(!c)continue;let f=await(typeof s=="function"?s(c):c.modeParticipant?.());if(typeof f?.id!="string"||typeof f.prepare!="function")return null;t.push(f)}t.sort((r,s)=>(r.order??0)-(s.order??0));let o=[],n={generation:y,destination:P().destination,signal:void 0,represented:null,reader:null,initial:!0,isCurrent:()=>!0};for(let r of t){let s=null;try{s=await r.prepare(n)}catch{return null}s&&o.push(s)}return o}async function K(e){return(e?.loaded?.["core/save.js"]??await import("./core/save-A5JXV6ME.js").catch(()=>null))?.acceptedReceipt?.(y)??null}var R=Symbol("the exit deadline passed");function Q(){let e=null,t=Date.now()+$;return{expired:new Promise(n=>{e=setTimeout(()=>n(R),$)}),remaining:()=>Math.max(0,t-Date.now()),clear:()=>clearTimeout(e)}}async function Y(e,t){if(!e)return;let n=(await import("./c-KJJPV77R.js")).importPlan(e,e.view);n.catch(()=>{});let r=await Promise.race([n.then(()=>null,s=>s),t]);if(r&&r!==R)throw r}async function Z(e=null){let t=Q();try{return await ee(e,t)}finally{t.clear()}}async function ee(e,t){let o=I;l({phase:"leaving"});let n=await import("./c-LPCZOYTX.js").catch(()=>null);if(!n)return h("load-failed");let r=x;if(o&&!E){v??=J(e);let i=await Promise.race([v,t.expired]);if(i===R)return h("timeout");if(!i)return v=null,l({phase:"idle",reason:null}),null;E=!0,r=[...i,...r],x=r}try{await Y(e,t.expired)}catch(i){return h(i?.code||"load-failed","idle",{message:i?.message})}let s=[],c=null;try{if(c=n.claimOperation("mode"),!c)throw p("another document operation is in progress","busy");for(let w of[...r].reverse()){s.push(w);let m=await Promise.race([Promise.resolve(w.quiesce?.()),t.expired]);if(m===R)throw p("the exit deadline passed while a lease quiesced","timeout");if(m&&m.ok===!1)throw Object.assign(p("a lease refused the exit",m.code||"pending-input"),m)}let i=await n.runSaveBarrier({operation:c,timeoutMs:t.remaining()});if(!i.ok)throw Object.assign(p("the exit barrier refused",i.code||"save-failed"),i)}catch(i){for(let w of[...s].reverse())try{w.resume?.()}catch{}return l({phase:"idle",reason:i?.code||"save-failed"}),{ok:!1,mode:u(),code:i?.code||"save-failed",state:i?.state,pending:i?.pending}}finally{c&&n.releaseOperation(c)}k(r),x=[],I=!1,E=!1,v=null;let f=await K(e)??M;return M=null,e&&(await import("./c-KJJPV77R.js").catch(()=>null))?.startReader(e,f),y++,O(!1),l({mode:"view",isEditMode:!1,phase:"idle",generation:y,reason:null}),G(),U(),{ok:!0,mode:"view",changed:!0}}function F(e,t=null){if(e!=="edit"&&e!=="view")throw new TypeError(`clay.modeLifecycle: unknown mode "${e}"`);if(d)return d.target===e?d.promise:{ok:!1,mode:u(),code:"busy"};if(e===u())return{ok:!0,mode:u(),changed:!1};if(S||e==="edit"&&!A)return{ok:!1,mode:u(),code:"not-allowed"};let o=(e==="edit"?V(t):Z(t)).finally(()=>{d=null});return d={target:e,promise:o},o}async function re(e,t){let o=await import("./c-KJJPV77R.js").catch(()=>null);return!o||!o.liveAllowed(t)?null:(d||e===u()||e==="edit"&&o.openResources(),F(e,t))}async function oe(){if(u()==="view")return{ok:!0,mode:"view",changed:!1};if(d)return d.promise;let e=V().finally(()=>{d=null});return d={target:"edit",promise:e},e}export{oe as activateInitial,z as forgetParticipant,F as requestMode,re as switchMode};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as z}from"./c-W4JCVLAB.js";import{B as J}from"./c-AMU3BPPR.js";import{d as _,m as F}from"./c-QIXT3Q7C.js";import"./c-VHNSBD2M.js";var{Decoration:ee,DecorationSet:te}=_,c=(t,n,a,e={},o=null)=>{let l=t.createElement(n);a&&(l.className=a);for(let[s,i]of Object.entries(e))i!=null&&i!==!1&&l.setAttribute(s,i===!0?"":String(i));return o!==null&&(l.textContent=o),l},ne=(t,n)=>c(t,"span","page-board-face",{"aria-hidden":"true"},([...String(n).trim()][0]??"?").toUpperCase());function I(t,n){let a=null;return t.state.doc.forEach((e,o)=>{e.attrs.id===n&&e.type===F.nodes.list_item&&e.attrs.kind==="check"&&(a={node:e,pos:o})}),a}function X(t,n,a,e){let o=I(t,n);o&&t.dispatch(J(t.state.tr.setNodeMarkup(o.pos,null,{...o.node.attrs,[a]:e||null})))}var L={person:'<circle cx="8" cy="5.4" r="2.3"/><path d="M3.6 13.2c.6-2.1 2.2-3.3 4.4-3.3s3.8 1.2 4.4 3.3"/>',calendar:'<rect x="2.5" y="3.5" width="11" height="10"/><path d="M2.5 6.8h11M5.5 2v2.4M10.5 2v2.4"/>',clock:'<circle cx="8" cy="8" r="5.5"/><path d="M8 4.8v3.4l2.3 1.4"/>',tick:'<path d="M3.5 8.3l3 3 6-6.2"/>',plus:'<path d="M8 3.5v9M3.5 8h9"/>',clear:'<path d="M4.8 4.8l6.4 6.4M11.2 4.8l-6.4 6.4"/>',"chevron-left":'<path d="M9.8 3.6L5.4 8l4.4 4.4"/>',"chevron-right":'<path d="M6.2 3.6L10.6 8l-4.4 4.4"/>'};function q(t,n){let a=t.createElementNS("http://www.w3.org/2000/svg","svg");return a.setAttribute("viewBox","0 0 16 16"),a.setAttribute("width","14"),a.setAttribute("height","14"),a.setAttribute("fill","none"),a.setAttribute("stroke","currentColor"),a.setAttribute("stroke-width","1.5"),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),a.innerHTML=n,a}var Z=t=>String(t).padStart(2,"0"),B=/^\d{4}-\d{2}-\d{2}$/,S=(t=new Date)=>`${t.getFullYear()}-${Z(t.getMonth()+1)}-${Z(t.getDate())}`,ae=t=>{let n=new Date(`${t}T00:00:00Z`);return n.setUTCDate(n.getUTCDate()+1),n.toISOString().slice(0,10)};function oe(t,n){if(!t)return"No date";if(!B.test(t))return t;if(t===n)return"Today";if(t===ae(n))return"Tomorrow";let a=t.slice(0,4)===n.slice(0,4);return new Date(`${t}T00:00:00Z`).toLocaleDateString("en-US",{month:"short",day:"numeric",...a?{}:{year:"numeric"},timeZone:"UTC"})}function j(t,{name:n,paths:a,label:e,aria:o,filled:l,overdue:s=!1}){let i=c(t,"button","page-check-chip",{type:"button","data-check":n,"data-filled":String(l),"data-overdue":s?"true":null,"aria-expanded":"false","aria-label":o});return i.append(q(t,a),c(t,"span","page-check-chip-label",{},e)),i}var N=null;function G(t,n,{className:a,label:e,check:o,onKey:l=null}){let s=n.ownerDocument,i=s.defaultView;N&&N.close();for(let d of s.querySelectorAll(".page-check-popup"))d.remove();let y=t.dom.parentNode,h=["relative","absolute","fixed","sticky"].includes(i?.getComputedStyle?.(y)?.position??""),g=y&&h?y:s.body,f=c(s,"div",`page-check-popup ${a}`,{role:"dialog","aria-label":e,"data-check":o}),A=!1,E=()=>{let d=n.getBoundingClientRect(),r=g===s.body?{top:-(i?.scrollY??0),left:-(i?.scrollX??0)}:g.getBoundingClientRect(),u=f.getBoundingClientRect(),p=u.width||Math.min(264,(i?.innerWidth||292)-28),k=(i?.innerHeight??0)-d.bottom-2,b=u.height>0&&k<u.height;f.style.left=`${Math.round(d.right-p-r.left)}px`,f.style.top=`${Math.round((b?d.top-u.height-2:d.bottom+2)-r.top)}px`},C=d=>{if(!f.isConnected)return w();f.contains(d.target)||n.contains(d.target)||w()},w=({focusAnchor:d=!1}={})=>{if(A)return;A=!0,s.removeEventListener("mousedown",C,!0),i?.removeEventListener("resize",E),i?.removeEventListener("scroll",E,!0),N?.panel===f&&(N=null),f.remove(),n.setAttribute("aria-expanded","false");let r=n.dataset.fromKeys==="true";delete n.dataset.fromKeys,d&&r?t.focus():d&&n.focus()};return f.addEventListener("keydown",d=>{if(d.stopPropagation(),d.key==="Escape"){d.preventDefault(),w({focusAnchor:!0});return}l?.(d,f)}),g.append(f),n.setAttribute("aria-expanded","true"),N={panel:f,close:()=>w()},s.addEventListener("mousedown",C,!0),i?.addEventListener("resize",E),i?.addEventListener("scroll",E,!0),{panel:f,close:w,place:E}}function re(t,n){let a=new Map;t.state.doc.forEach(e=>{if(e.type!==F.nodes.list_item||e.attrs.kind!=="check")return;let o=String(e.attrs.owner??"").trim();if(!o)return;let l=o.toLowerCase(),s=a.get(l)??{name:o,count:0};s.count+=1,a.set(l,s)});for(let e of n??[]){let o=String((typeof e=="string"?e:e?.name)??"").trim();o&&!a.has(o.toLowerCase())&&a.set(o.toLowerCase(),{name:o,count:0})}return[...a.values()].sort((e,o)=>e.name.localeCompare(o.name))}function ce(t,n,a){let e=a.ownerDocument,o=I(t,n)?.node.attrs.owner||"",{panel:l,close:s,place:i}=G(t,a,{className:"page-check-owner",label:"Assignee",check:"owner-panel",onKey:(r,u)=>{if(r.key!=="ArrowDown"&&r.key!=="ArrowUp")return;r.preventDefault();let p=[...u.querySelectorAll("input, button:not([disabled])")],k=p.indexOf(e.activeElement),b=r.key==="ArrowDown"?1:-1;(k<0?b>0?p[0]:p[p.length-1]:p[(k+b+p.length)%p.length])?.focus()}}),y=c(e,"input","page-check-search",{type:"text",placeholder:"Find or type a name","aria-label":"Find or type a name"}),h=c(e,"div","page-check-people"),g=c(e,"button","page-check-person page-check-danger",{type:"button","data-check":"clear-owner"});g.append(q(e,L.clear),c(e,"span","page-check-person-name",{},"Remove assignee")),g.disabled=!o,g.addEventListener("click",()=>A(null)),l.append(y,c(e,"div","page-check-subhead",{},"People in this document"),h,c(e,"div","page-check-divider"),g);let f=[],A=r=>{s(),X(t,n,"owner",r)},E=(r,u)=>{let p=r.toLowerCase()===String(o).toLowerCase(),k=c(e,"button","page-check-person",{type:"button","data-check":"owner-option","data-name":r,"aria-pressed":String(p)});return k.append(ne(e,r),c(e,"span","page-check-person-name",{},r),c(e,"span","page-check-person-meta",{},`${u} ${u===1?"item":"items"}`)),p&&k.append(q(e,L.tick)),k.addEventListener("click",()=>A(r)),k},C=r=>{let u=c(e,"button","page-check-person",{type:"button","data-check":"owner-new","data-name":r}),p=c(e,"span","page-check-person-name",{},"Assign to ");return p.append(c(e,"strong",null,{},r)),u.append(q(e,L.plus),p,c(e,"span","page-check-person-meta",{},"New")),u.addEventListener("click",()=>A(r)),u},w=()=>{let r=y.value.trim(),u=r.toLowerCase(),p=re(t,f),k=[];r&&!p.some(b=>b.name.toLowerCase()===u)&&k.push(C(r));for(let b of p)u&&!b.name.toLowerCase().includes(u)||k.push(E(b.name,b.count));h.replaceChildren(...k)};y.addEventListener("keydown",r=>{if(r.stopPropagation(),r.key==="Escape"){r.preventDefault(),s({focusAnchor:!0});return}r.key==="Enter"&&(r.preventDefault(),h.querySelector("button[data-check]")?.click())}),y.addEventListener("input",w),w(),i(),y.focus();let d=globalThis.clay?.people?.available;d&&Promise.resolve().then(()=>d()).then(r=>{!N||N.panel!==l||(f=Array.isArray(r)?r:[],w())}).catch(()=>{})}var se=["January","February","March","April","May","June","July","August","September","October","November","December"],$=(t,n,a)=>new Date(t,n,a),ie=t=>t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),le=t=>t.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"}),W=t=>{if(!t||!B.test(t))return null;let[n,a,e]=t.split("-").map(Number);return $(n,a-1,e)};function de(t,n,a){let e=a.ownerDocument,o=I(t,n)?.node.attrs.due||null,l=S(),s=new Date,i=$(s.getFullYear(),s.getMonth(),s.getDate()),y=W(o)??i,h=y.getFullYear(),g=y.getMonth(),{panel:f,close:A,place:E}=G(t,a,{className:"page-check-date",label:"Due date",check:"date-panel",onKey:(m,D)=>Q(m,D)}),C=m=>{A(),X(t,n,"due",m)},w=c(e,"div","page-check-quick"),d=(m,D)=>{let M=$(i.getFullYear(),i.getMonth(),i.getDate()+D),x=c(e,"button","page-check-quick-row",{type:"button","data-check":"date-quick","data-date":S(M)});return x.append(q(e,L.calendar),c(e,"span","page-check-quick-label",{},m),c(e,"span","page-check-quick-meta",{},ie(M))),x.addEventListener("click",()=>C(S(M))),x};w.append(d("Today",0),d("Tomorrow",1),d("Next week",7));let r=c(e,"div","page-check-cal"),u=c(e,"div","page-check-cal-head"),p=c(e,"span","page-check-cal-month"),k=c(e,"span","page-check-cal-nav"),b=m=>{let D=$(h,g+m,1);h=D.getFullYear(),g=D.getMonth(),H()},U=c(e,"button","page-check-cal-btn",{type:"button","aria-label":"Previous month"}),O=c(e,"button","page-check-cal-btn",{type:"button","aria-label":"Next month"});U.append(q(e,L["chevron-left"])),O.append(q(e,L["chevron-right"])),U.addEventListener("click",()=>b(-1)),O.addEventListener("click",()=>b(1)),k.append(U,O),u.append(p,k);let Y=c(e,"div","page-check-cal-grid");r.append(u,Y);let H=()=>{p.replaceChildren(c(e,"span",null,{},`${se[g]} `),c(e,"span","page-check-cal-year",{},String(h)));let m=$(h,g,1),D=$(h,g+1,0).getDate(),M=Math.ceil((m.getDay()+D)/7)*7,x=["S","M","T","W","T","F","S"].map(v=>c(e,"span","page-check-cal-dow",{},v)),T=[];for(let v=0;v<M;v+=1){let P=$(h,g,1-m.getDay()+v),R=S(P),V=c(e,"button","page-check-cal-day",{type:"button","data-check":"date-day","data-date":R,"data-outside":String(P.getMonth()!==g),"data-today":String(R===l),"aria-pressed":String(R===o),"aria-label":le(P)},String(P.getDate()));V.addEventListener("click",()=>C(R)),T.push(V)}Y.replaceChildren(...x,...T)},Q=(m,D)=>{let M=e.activeElement?.closest?.('[data-check="date-day"]');if(!M)return;if(m.key==="Enter"||m.key===" "){m.preventDefault(),M.click();return}let x={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7}[m.key];if(!x)return;m.preventDefault();let T=W(M.dataset.date),v=$(T.getFullYear(),T.getMonth(),T.getDate()+x);(v.getMonth()!==g||v.getFullYear()!==h)&&(h=v.getFullYear(),g=v.getMonth(),H()),D.querySelector(`[data-check="date-day"][data-date="${S(v)}"]`)?.focus()},K=c(e,"button","page-check-quick-row page-check-danger",{type:"button","data-check":"clear-date"});K.append(q(e,L.clear),c(e,"span","page-check-quick-label",{},"Clear date")),K.disabled=!o,K.addEventListener("click",()=>C(null)),f.append(w,r,c(e,"div","page-check-divider"),K),H(),E(),(Y.querySelector('[data-check="date-day"][aria-pressed="true"]')??Y.querySelector('[data-check="date-day"][data-today="true"]'))?.focus()}function pe(t,n){let a=t.dom.ownerDocument,e=a.createElement("span");e.className="page-check-controls",e.contentEditable="false",e.dataset.empty=String(!n.attrs.owner&&!n.attrs.due);let o=S(),l=n.attrs.owner||"Unassigned",s=j(a,{name:"owner",paths:L.person,label:l,aria:`Assignee: ${l}`,filled:!!n.attrs.owner}),i=oe(n.attrs.due,o),y=!!n.attrs.due&&!n.attrs.checked&&B.test(n.attrs.due)&&n.attrs.due<o,h=j(a,{name:"date",paths:y?L.clock:L.calendar,label:i,aria:`Due date: ${i}`,filled:!!n.attrs.due,overdue:y});return s.addEventListener("click",()=>ce(t,n.attrs.id,s)),h.addEventListener("click",()=>de(t,n.attrs.id,h)),e.append(s,h),e}function ue(t,n){let a=t.state.selection.$head;if(a.depth!==1||a.parent.type!==F.nodes.list_item||a.parent.attrs.kind!=="check")return!1;let e=a.parent.attrs.id,l=[...t.dom.querySelectorAll(".page-check-controls")].find(s=>s.dataset.item===e)?.querySelector(`[data-check="${n}"]`);return l?(l.dataset.fromKeys="true",l.click(),!0):!1}function he(t){let n=[],a=S();return t.doc.forEach((e,o)=>{e.type!==F.nodes.list_item||e.attrs.kind!=="check"||n.push(ee.widget(o+e.nodeSize-1,l=>{let s=pe(l,e);return s.dataset.item=e.attrs.id,s},{key:`${e.attrs.id}:${e.attrs.owner}:${e.attrs.due}:${e.attrs.checked}:${a}`,side:-1,stopEvent:l=>!!l.target.closest?.(".page-check-chip, .page-check-popup"),ignoreSelection:!0}))}),te.create(t.doc,n)}function ge(t){let n=S(),a=()=>{t.isDestroyed||S()===n||(n=S(),t.dispatch(t.state.tr.setMeta("addToHistory",!1)))},e=t.dom.ownerDocument.defaultView,o=e.setInterval(a,6e4);return e.document.addEventListener("visibilitychange",a),()=>{e.clearInterval(o),e.document.removeEventListener("visibilitychange",a)}}function be({view:t=null}={}){let n=t?z(t,{decorations:he,focusControl:ue}):()=>{},a=t?ge(t):()=>{};return t&&!t.isDestroyed&&t.dispatch(t.state.tr.setMeta("addToHistory",!1)),{id:"checklist",dispose(){n(),a()}}}export{be as createFeature,he as decorations,ue as focusControl};
|
|
1
|
+
import{c as z}from"./c-W4JCVLAB.js";import{B as J}from"./c-AIWN4QN4.js";import{d as _,m as F}from"./c-QIXT3Q7C.js";import"./c-VHNSBD2M.js";var{Decoration:ee,DecorationSet:te}=_,c=(t,n,a,e={},o=null)=>{let l=t.createElement(n);a&&(l.className=a);for(let[s,i]of Object.entries(e))i!=null&&i!==!1&&l.setAttribute(s,i===!0?"":String(i));return o!==null&&(l.textContent=o),l},ne=(t,n)=>c(t,"span","page-board-face",{"aria-hidden":"true"},([...String(n).trim()][0]??"?").toUpperCase());function I(t,n){let a=null;return t.state.doc.forEach((e,o)=>{e.attrs.id===n&&e.type===F.nodes.list_item&&e.attrs.kind==="check"&&(a={node:e,pos:o})}),a}function X(t,n,a,e){let o=I(t,n);o&&t.dispatch(J(t.state.tr.setNodeMarkup(o.pos,null,{...o.node.attrs,[a]:e||null})))}var L={person:'<circle cx="8" cy="5.4" r="2.3"/><path d="M3.6 13.2c.6-2.1 2.2-3.3 4.4-3.3s3.8 1.2 4.4 3.3"/>',calendar:'<rect x="2.5" y="3.5" width="11" height="10"/><path d="M2.5 6.8h11M5.5 2v2.4M10.5 2v2.4"/>',clock:'<circle cx="8" cy="8" r="5.5"/><path d="M8 4.8v3.4l2.3 1.4"/>',tick:'<path d="M3.5 8.3l3 3 6-6.2"/>',plus:'<path d="M8 3.5v9M3.5 8h9"/>',clear:'<path d="M4.8 4.8l6.4 6.4M11.2 4.8l-6.4 6.4"/>',"chevron-left":'<path d="M9.8 3.6L5.4 8l4.4 4.4"/>',"chevron-right":'<path d="M6.2 3.6L10.6 8l-4.4 4.4"/>'};function q(t,n){let a=t.createElementNS("http://www.w3.org/2000/svg","svg");return a.setAttribute("viewBox","0 0 16 16"),a.setAttribute("width","14"),a.setAttribute("height","14"),a.setAttribute("fill","none"),a.setAttribute("stroke","currentColor"),a.setAttribute("stroke-width","1.5"),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),a.innerHTML=n,a}var Z=t=>String(t).padStart(2,"0"),B=/^\d{4}-\d{2}-\d{2}$/,S=(t=new Date)=>`${t.getFullYear()}-${Z(t.getMonth()+1)}-${Z(t.getDate())}`,ae=t=>{let n=new Date(`${t}T00:00:00Z`);return n.setUTCDate(n.getUTCDate()+1),n.toISOString().slice(0,10)};function oe(t,n){if(!t)return"No date";if(!B.test(t))return t;if(t===n)return"Today";if(t===ae(n))return"Tomorrow";let a=t.slice(0,4)===n.slice(0,4);return new Date(`${t}T00:00:00Z`).toLocaleDateString("en-US",{month:"short",day:"numeric",...a?{}:{year:"numeric"},timeZone:"UTC"})}function j(t,{name:n,paths:a,label:e,aria:o,filled:l,overdue:s=!1}){let i=c(t,"button","page-check-chip",{type:"button","data-check":n,"data-filled":String(l),"data-overdue":s?"true":null,"aria-expanded":"false","aria-label":o});return i.append(q(t,a),c(t,"span","page-check-chip-label",{},e)),i}var N=null;function G(t,n,{className:a,label:e,check:o,onKey:l=null}){let s=n.ownerDocument,i=s.defaultView;N&&N.close();for(let d of s.querySelectorAll(".page-check-popup"))d.remove();let y=t.dom.parentNode,h=["relative","absolute","fixed","sticky"].includes(i?.getComputedStyle?.(y)?.position??""),g=y&&h?y:s.body,f=c(s,"div",`page-check-popup ${a}`,{role:"dialog","aria-label":e,"data-check":o}),A=!1,E=()=>{let d=n.getBoundingClientRect(),r=g===s.body?{top:-(i?.scrollY??0),left:-(i?.scrollX??0)}:g.getBoundingClientRect(),u=f.getBoundingClientRect(),p=u.width||Math.min(264,(i?.innerWidth||292)-28),k=(i?.innerHeight??0)-d.bottom-2,b=u.height>0&&k<u.height;f.style.left=`${Math.round(d.right-p-r.left)}px`,f.style.top=`${Math.round((b?d.top-u.height-2:d.bottom+2)-r.top)}px`},C=d=>{if(!f.isConnected)return w();f.contains(d.target)||n.contains(d.target)||w()},w=({focusAnchor:d=!1}={})=>{if(A)return;A=!0,s.removeEventListener("mousedown",C,!0),i?.removeEventListener("resize",E),i?.removeEventListener("scroll",E,!0),N?.panel===f&&(N=null),f.remove(),n.setAttribute("aria-expanded","false");let r=n.dataset.fromKeys==="true";delete n.dataset.fromKeys,d&&r?t.focus():d&&n.focus()};return f.addEventListener("keydown",d=>{if(d.stopPropagation(),d.key==="Escape"){d.preventDefault(),w({focusAnchor:!0});return}l?.(d,f)}),g.append(f),n.setAttribute("aria-expanded","true"),N={panel:f,close:()=>w()},s.addEventListener("mousedown",C,!0),i?.addEventListener("resize",E),i?.addEventListener("scroll",E,!0),{panel:f,close:w,place:E}}function re(t,n){let a=new Map;t.state.doc.forEach(e=>{if(e.type!==F.nodes.list_item||e.attrs.kind!=="check")return;let o=String(e.attrs.owner??"").trim();if(!o)return;let l=o.toLowerCase(),s=a.get(l)??{name:o,count:0};s.count+=1,a.set(l,s)});for(let e of n??[]){let o=String((typeof e=="string"?e:e?.name)??"").trim();o&&!a.has(o.toLowerCase())&&a.set(o.toLowerCase(),{name:o,count:0})}return[...a.values()].sort((e,o)=>e.name.localeCompare(o.name))}function ce(t,n,a){let e=a.ownerDocument,o=I(t,n)?.node.attrs.owner||"",{panel:l,close:s,place:i}=G(t,a,{className:"page-check-owner",label:"Assignee",check:"owner-panel",onKey:(r,u)=>{if(r.key!=="ArrowDown"&&r.key!=="ArrowUp")return;r.preventDefault();let p=[...u.querySelectorAll("input, button:not([disabled])")],k=p.indexOf(e.activeElement),b=r.key==="ArrowDown"?1:-1;(k<0?b>0?p[0]:p[p.length-1]:p[(k+b+p.length)%p.length])?.focus()}}),y=c(e,"input","page-check-search",{type:"text",placeholder:"Find or type a name","aria-label":"Find or type a name"}),h=c(e,"div","page-check-people"),g=c(e,"button","page-check-person page-check-danger",{type:"button","data-check":"clear-owner"});g.append(q(e,L.clear),c(e,"span","page-check-person-name",{},"Remove assignee")),g.disabled=!o,g.addEventListener("click",()=>A(null)),l.append(y,c(e,"div","page-check-subhead",{},"People in this document"),h,c(e,"div","page-check-divider"),g);let f=[],A=r=>{s(),X(t,n,"owner",r)},E=(r,u)=>{let p=r.toLowerCase()===String(o).toLowerCase(),k=c(e,"button","page-check-person",{type:"button","data-check":"owner-option","data-name":r,"aria-pressed":String(p)});return k.append(ne(e,r),c(e,"span","page-check-person-name",{},r),c(e,"span","page-check-person-meta",{},`${u} ${u===1?"item":"items"}`)),p&&k.append(q(e,L.tick)),k.addEventListener("click",()=>A(r)),k},C=r=>{let u=c(e,"button","page-check-person",{type:"button","data-check":"owner-new","data-name":r}),p=c(e,"span","page-check-person-name",{},"Assign to ");return p.append(c(e,"strong",null,{},r)),u.append(q(e,L.plus),p,c(e,"span","page-check-person-meta",{},"New")),u.addEventListener("click",()=>A(r)),u},w=()=>{let r=y.value.trim(),u=r.toLowerCase(),p=re(t,f),k=[];r&&!p.some(b=>b.name.toLowerCase()===u)&&k.push(C(r));for(let b of p)u&&!b.name.toLowerCase().includes(u)||k.push(E(b.name,b.count));h.replaceChildren(...k)};y.addEventListener("keydown",r=>{if(r.stopPropagation(),r.key==="Escape"){r.preventDefault(),s({focusAnchor:!0});return}r.key==="Enter"&&(r.preventDefault(),h.querySelector("button[data-check]")?.click())}),y.addEventListener("input",w),w(),i(),y.focus();let d=globalThis.clay?.people?.available;d&&Promise.resolve().then(()=>d()).then(r=>{!N||N.panel!==l||(f=Array.isArray(r)?r:[],w())}).catch(()=>{})}var se=["January","February","March","April","May","June","July","August","September","October","November","December"],$=(t,n,a)=>new Date(t,n,a),ie=t=>t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),le=t=>t.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"}),W=t=>{if(!t||!B.test(t))return null;let[n,a,e]=t.split("-").map(Number);return $(n,a-1,e)};function de(t,n,a){let e=a.ownerDocument,o=I(t,n)?.node.attrs.due||null,l=S(),s=new Date,i=$(s.getFullYear(),s.getMonth(),s.getDate()),y=W(o)??i,h=y.getFullYear(),g=y.getMonth(),{panel:f,close:A,place:E}=G(t,a,{className:"page-check-date",label:"Due date",check:"date-panel",onKey:(m,D)=>Q(m,D)}),C=m=>{A(),X(t,n,"due",m)},w=c(e,"div","page-check-quick"),d=(m,D)=>{let M=$(i.getFullYear(),i.getMonth(),i.getDate()+D),x=c(e,"button","page-check-quick-row",{type:"button","data-check":"date-quick","data-date":S(M)});return x.append(q(e,L.calendar),c(e,"span","page-check-quick-label",{},m),c(e,"span","page-check-quick-meta",{},ie(M))),x.addEventListener("click",()=>C(S(M))),x};w.append(d("Today",0),d("Tomorrow",1),d("Next week",7));let r=c(e,"div","page-check-cal"),u=c(e,"div","page-check-cal-head"),p=c(e,"span","page-check-cal-month"),k=c(e,"span","page-check-cal-nav"),b=m=>{let D=$(h,g+m,1);h=D.getFullYear(),g=D.getMonth(),H()},U=c(e,"button","page-check-cal-btn",{type:"button","aria-label":"Previous month"}),O=c(e,"button","page-check-cal-btn",{type:"button","aria-label":"Next month"});U.append(q(e,L["chevron-left"])),O.append(q(e,L["chevron-right"])),U.addEventListener("click",()=>b(-1)),O.addEventListener("click",()=>b(1)),k.append(U,O),u.append(p,k);let Y=c(e,"div","page-check-cal-grid");r.append(u,Y);let H=()=>{p.replaceChildren(c(e,"span",null,{},`${se[g]} `),c(e,"span","page-check-cal-year",{},String(h)));let m=$(h,g,1),D=$(h,g+1,0).getDate(),M=Math.ceil((m.getDay()+D)/7)*7,x=["S","M","T","W","T","F","S"].map(v=>c(e,"span","page-check-cal-dow",{},v)),T=[];for(let v=0;v<M;v+=1){let P=$(h,g,1-m.getDay()+v),R=S(P),V=c(e,"button","page-check-cal-day",{type:"button","data-check":"date-day","data-date":R,"data-outside":String(P.getMonth()!==g),"data-today":String(R===l),"aria-pressed":String(R===o),"aria-label":le(P)},String(P.getDate()));V.addEventListener("click",()=>C(R)),T.push(V)}Y.replaceChildren(...x,...T)},Q=(m,D)=>{let M=e.activeElement?.closest?.('[data-check="date-day"]');if(!M)return;if(m.key==="Enter"||m.key===" "){m.preventDefault(),M.click();return}let x={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7}[m.key];if(!x)return;m.preventDefault();let T=W(M.dataset.date),v=$(T.getFullYear(),T.getMonth(),T.getDate()+x);(v.getMonth()!==g||v.getFullYear()!==h)&&(h=v.getFullYear(),g=v.getMonth(),H()),D.querySelector(`[data-check="date-day"][data-date="${S(v)}"]`)?.focus()},K=c(e,"button","page-check-quick-row page-check-danger",{type:"button","data-check":"clear-date"});K.append(q(e,L.clear),c(e,"span","page-check-quick-label",{},"Clear date")),K.disabled=!o,K.addEventListener("click",()=>C(null)),f.append(w,r,c(e,"div","page-check-divider"),K),H(),E(),(Y.querySelector('[data-check="date-day"][aria-pressed="true"]')??Y.querySelector('[data-check="date-day"][data-today="true"]'))?.focus()}function pe(t,n){let a=t.dom.ownerDocument,e=a.createElement("span");e.className="page-check-controls",e.contentEditable="false",e.dataset.empty=String(!n.attrs.owner&&!n.attrs.due);let o=S(),l=n.attrs.owner||"Unassigned",s=j(a,{name:"owner",paths:L.person,label:l,aria:`Assignee: ${l}`,filled:!!n.attrs.owner}),i=oe(n.attrs.due,o),y=!!n.attrs.due&&!n.attrs.checked&&B.test(n.attrs.due)&&n.attrs.due<o,h=j(a,{name:"date",paths:y?L.clock:L.calendar,label:i,aria:`Due date: ${i}`,filled:!!n.attrs.due,overdue:y});return s.addEventListener("click",()=>ce(t,n.attrs.id,s)),h.addEventListener("click",()=>de(t,n.attrs.id,h)),e.append(s,h),e}function ue(t,n){let a=t.state.selection.$head;if(a.depth!==1||a.parent.type!==F.nodes.list_item||a.parent.attrs.kind!=="check")return!1;let e=a.parent.attrs.id,l=[...t.dom.querySelectorAll(".page-check-controls")].find(s=>s.dataset.item===e)?.querySelector(`[data-check="${n}"]`);return l?(l.dataset.fromKeys="true",l.click(),!0):!1}function he(t){let n=[],a=S();return t.doc.forEach((e,o)=>{e.type!==F.nodes.list_item||e.attrs.kind!=="check"||n.push(ee.widget(o+e.nodeSize-1,l=>{let s=pe(l,e);return s.dataset.item=e.attrs.id,s},{key:`${e.attrs.id}:${e.attrs.owner}:${e.attrs.due}:${e.attrs.checked}:${a}`,side:-1,stopEvent:l=>!!l.target.closest?.(".page-check-chip, .page-check-popup"),ignoreSelection:!0}))}),te.create(t.doc,n)}function ge(t){let n=S(),a=()=>{t.isDestroyed||S()===n||(n=S(),t.dispatch(t.state.tr.setMeta("addToHistory",!1)))},e=t.dom.ownerDocument.defaultView,o=e.setInterval(a,6e4);return e.document.addEventListener("visibilitychange",a),()=>{e.clearInterval(o),e.document.removeEventListener("visibilitychange",a)}}function be({view:t=null}={}){let n=t?z(t,{decorations:he,focusControl:ue}):()=>{},a=t?ge(t):()=>{};return t&&!t.isDestroyed&&t.dispatch(t.state.tr.setMeta("addToHistory",!1)),{id:"checklist",dispose(){n(),a()}}}export{be as createFeature,he as decorations,ue as focusControl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./c-VHNSBD2M.js";var l=(e,n)=>Object.assign(new Error(`clayjs: ${e}`),{code:n}),u=(e,n)=>!e||n.seq===null||e.seq===null||n.seq>e.seq?n:e;function a({stream:e,apply:n,retire:f,yieldArticle:i=()=>!1,reclaimArticle:s=()=>!1}){let t=null,r=!1;e.adopt({onSnapshot:o=>(t=u(t,o),!0)});let d=()=>{let o=t;return t=null,o};return{get represented(){return e.represented},get held(){return t??e.represented},yieldArticle(){return r||!i()?!1:(r=!0,!0)},reclaimArticle(){return!r||!s()?!1:(r=!1,!0)},reconcile(){let o=d();return o&&!n(o)?Promise.reject(l("the switch could not apply the saved file","load-failed")):Promise.resolve()},resume(){e.adopt({onSnapshot:n});let o=d();o&&n(o)},commit(){if(!r){let o=d();if(o&&!n(o))return!1}return e.represented.bytes===null?!1:(e.stop(),f())}}}async function c({stream:e,options:n,apply:f,retire:i,yieldArticle:s=()=>!1,reclaimArticle:t=()=>!1}){if(e)return a({stream:e,apply:f,retire:i,yieldArticle:s,reclaimArticle:t});let r=await import("./sync/live-sync-
|
|
1
|
+
import"./c-VHNSBD2M.js";var l=(e,n)=>Object.assign(new Error(`clayjs: ${e}`),{code:n}),u=(e,n)=>!e||n.seq===null||e.seq===null||n.seq>e.seq?n:e;function a({stream:e,apply:n,retire:f,yieldArticle:i=()=>!1,reclaimArticle:s=()=>!1}){let t=null,r=!1;e.adopt({onSnapshot:o=>(t=u(t,o),!0)});let d=()=>{let o=t;return t=null,o};return{get represented(){return e.represented},get held(){return t??e.represented},yieldArticle(){return r||!i()?!1:(r=!0,!0)},reclaimArticle(){return!r||!s()?!1:(r=!1,!0)},reconcile(){let o=d();return o&&!n(o)?Promise.reject(l("the switch could not apply the saved file","load-failed")):Promise.resolve()},resume(){e.adopt({onSnapshot:n});let o=d();o&&n(o)},commit(){if(!r){let o=d();if(o&&!n(o))return!1}return e.represented.bytes===null?!1:(e.stop(),f())}}}async function c({stream:e,options:n,apply:f,retire:i,yieldArticle:s=()=>!1,reclaimArticle:t=()=>!1}){if(e)return a({stream:e,apply:f,retire:i,yieldArticle:s,reclaimArticle:t});let r=await import("./sync/live-sync-UXNI6ZF6.js").then(({liveSync:d})=>d.prepareHandoff(n));return{get represented(){return r.represented},get held(){return r.held},yieldArticle:s,reclaimArticle:t,reconcile:()=>r.reconcile(),resume:()=>r.resume(),commit:()=>r.commit()&&i()}}async function p(e,{signal:n,deadline:f=15e3}={}){let i=Date.now()+f;for(;e._morphInFlight;){if(n?.aborted)throw e._handoffHeld=!1,l("the switch was cancelled","aborted");if(Date.now()>=i)throw e._handoffHeld=!1,l("the apply did not settle","timeout");await new Promise(t=>setTimeout(t,1))}let s=()=>e._pendingHtml!=null||e._pendingExternal!=null;return{get represented(){return e._represented},get held(){let t=e._represented;return e._pendingHtml!=null&&(t=u(t,{bytes:e._pendingHtml,etag:e._pendingEtag??null,seq:e._pendingSeq??null})),e._pendingExternal&&(t=u(t,{bytes:e._pendingExternal.html,etag:e._pendingExternal.etag??null,seq:e._pendingExternal.seq??null})),t},async reconcile(){if(!(!e._handoff||e.isDestroyed)){for(let t=0;t<8;t++){if(e._morphInFlight){await new Promise(r=>setTimeout(r,1));continue}if(!s())return;await e._runPending()}if(s())throw l("the held frame could not be applied","load-failed")}},resume(){e._handoff&&(e._handoff=null,e._handoffHeld=!1,e._scheduleNextFrame())},commit(){return e._represented.bytes?(e._handoff=null,e._handoffHeld=!1,e.stop(),!0):!1}}}export{p as engineHandoff,c as readerHandoff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as g}from"./c-
|
|
1
|
+
import{B as g}from"./c-AIWN4QN4.js";import"./c-QIXT3Q7C.js";import"./c-VHNSBD2M.js";var p=(t,r)=>{let s=-1;return t.forEach((n,l,c)=>{n.attrs.id===r&&(s=c)}),s};function y(t,r,s){let n=t.state,l=p(n.doc,r);if(l<0)return!1;let c=0;for(let e=0;e<l;e++)c+=n.doc.child(e).nodeSize;let a=n.doc.child(l);return t.dispatch(g(n.tr.setNodeMarkup(c,null,{...a.attrs,...s}))),!0}function b(t,r){let s=p(t.state.doc,r);if(s<0)return!1;let n=t.dom.parentElement,l=n.ownerDocument,c=0;for(let o=0;o<s;o++)c+=t.state.doc.child(o).nodeSize;let a=l.createElement("div");a.className="page-link",a.dataset.mode="alt";let e=l.createElement("input");e.className="page-link-input",e.type="text",e.value=t.state.doc.child(s).attrs.alt||"",e.placeholder="Describe the image",e.setAttribute("aria-label","Alt text"),a.append(e);let d=t.nodeDOM(c)?.getBoundingClientRect?.(),u=n.getBoundingClientRect();d&&(a.style.setProperty("--page-pop-x",`${d.left-u.left}px`),a.style.setProperty("--page-pop-y",`${d.bottom-u.top+6}px`)),n.append(a);let f=!1,i=(o,h=!0)=>{if(f)return;f=!0;let m=e.value.trim();a.remove();let x=p(t.state.doc,r);o&&x>=0&&m!==t.state.doc.child(x).attrs.alt&&y(t,r,{alt:m}),h&&t.focus()};return e.addEventListener("keydown",o=>{o.key==="Enter"?(o.preventDefault(),i(!0)):o.key==="Escape"&&(o.preventDefault(),o.stopPropagation(),i(!1))}),e.addEventListener("blur",()=>i(!0,!1)),e.focus(),!0}export{b as openAltEditor,y as setImageAttrs};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./c-VHNSBD2M.js";var M="data-write",E="Waiting for the page data write to finish";function n(e,t,r){let a=new Error(t);return a.code=e,a.details=r,a}async function U(e){if(typeof e.json=="function")return e.json();let t=await e.text();return t?JSON.parse(t):null}async function R(e){let t={};try{t=await U(e)||{}}catch{}let r=t.message||t.error||e.statusText||`Request failed (${e.status})`,a=new Error(r);return a.status=e.status,a.error=t.error,a.details=t.details,a}function F(e){let t=e.headers?.get?.("ETag");return typeof t=="string"&&t?t:null}function q(e,t){let r=`${t.origin}${t.pathname}`;return e!==void 0?`${r}?data=${encodeURIComponent(JSON.stringify(e))}`:`${t.origin}/_/api${t.pathname}`}function D(e){return!!e&&!e.isDestroyed&&e.sse?.readyState===1}function x(e,t){let r=[],a=null,o=null,c=null,p=i=>i?.source==="disk"&&(a===null||i.etag===a),P=i=>i?.source==="disk"&&(i.etag==null||a===null||i.etag===a),d=()=>{clearTimeout(c),e.removeEventListener("clay:sync-applied",w)},w=i=>{if(r.push(i.detail),!o||!P(i.detail))return;let u=o;o=null,d(),u(!0)};return e.addEventListener("clay:sync-applied",w),{waitFor(i){return a=i,r.some(p)?(d(),Promise.resolve(!0)):new Promise(u=>{o=u,c=setTimeout(()=>{o=null,d(),u(!1)},t)})},cancel:d}}function $(e){let t=new AbortController,r,a=new Promise((c,p)=>{r=p}),o=setTimeout(()=>{let c=new Error("The page data write timed out.");c.name="TimeoutError",t.abort(c),r(c)},e);return{signal:t.signal,waitFor(c){return Promise.race([c,a])},cancel(){clearTimeout(o)}}}async function j(){let[e,t,r,a,o]=await Promise.all([import("./core/save-
|
|
1
|
+
import"./c-VHNSBD2M.js";var M="data-write",E="Waiting for the page data write to finish";function n(e,t,r){let a=new Error(t);return a.code=e,a.details=r,a}async function U(e){if(typeof e.json=="function")return e.json();let t=await e.text();return t?JSON.parse(t):null}async function R(e){let t={};try{t=await U(e)||{}}catch{}let r=t.message||t.error||e.statusText||`Request failed (${e.status})`,a=new Error(r);return a.status=e.status,a.error=t.error,a.details=t.details,a}function F(e){let t=e.headers?.get?.("ETag");return typeof t=="string"&&t?t:null}function q(e,t){let r=`${t.origin}${t.pathname}`;return e!==void 0?`${r}?data=${encodeURIComponent(JSON.stringify(e))}`:`${t.origin}/_/api${t.pathname}`}function D(e){return!!e&&!e.isDestroyed&&e.sse?.readyState===1}function x(e,t){let r=[],a=null,o=null,c=null,p=i=>i?.source==="disk"&&(a===null||i.etag===a),P=i=>i?.source==="disk"&&(i.etag==null||a===null||i.etag===a),d=()=>{clearTimeout(c),e.removeEventListener("clay:sync-applied",w)},w=i=>{if(r.push(i.detail),!o||!P(i.detail))return;let u=o;o=null,d(),u(!0)};return e.addEventListener("clay:sync-applied",w),{waitFor(i){return a=i,r.some(p)?(d(),Promise.resolve(!0)):new Promise(u=>{o=u,c=setTimeout(()=>{o=null,d(),u(!1)},t)})},cancel:d}}function $(e){let t=new AbortController,r,a=new Promise((c,p)=>{r=p}),o=setTimeout(()=>{let c=new Error("The page data write timed out.");c.name="TimeoutError",t.abort(c),r(c)},e);return{signal:t.signal,waitFor(c){return Promise.race([c,a])},cancel(){clearTimeout(o)}}}async function j(){let[e,t,r,a,o]=await Promise.all([import("./core/save-A5JXV6ME.js"),import("./core/save-core-MKRPSEEO.js"),import("./c-R27DWQKX.js"),import("./core/unsaved-warning-4ZPEV7BF.js"),import("./core/is-edit-mode-GCX6767E.js")]);return{...e,...t,...r,...a,...o}}async function H(){let{isDraftMode:e}=await import("./core/is-edit-mode-GCX6767E.js");return e?n("DataUnavailableInDraft","Page data is kept in this browser for this visitor."):null}function N({supports:e,token:t,fetchImpl:r,getLocation:a,eventTarget:o,getLiveSync:c,loadWriteModules:p=j,syncTimeoutMs:P=12e3,httpTimeoutMs:d=3e4}){let w=!1,i=!1;function u(l,{checkHold:m=!0}={}){if(l.savesAdmitted&&!l.savesAdmitted())throw n("ModeTransition","The page is switching modes. Write page data again when it has settled.");if(i)throw n("DataWriteOutcomeUnknown","A previous page data write has an unknown outcome. Reload before writing again.");if(w)throw n("DataWriteInProgress","Another page data write is already running.");if(l.isSaveInProgress())throw n("SaveInProgress","The page is already being saved.");if(l.saveFateIsUnknown())throw n("SaveOutcomeUnknown","The page's last save has an unknown outcome.");if(m&&(l.savesHeld()||l.isSaveConflicted()))throw n("SavesHeld","The page cannot write data while another save hold is active.");if(l.hasUnsavedChanges())throw n("UnsavedChanges","Save or discard the page's unsaved changes before writing data.");if(!D(c()))throw n("SyncRequired","Page data writes require the sync plugin to be connected.")}async function A(l){l.baselineSettled()||await new Promise(m=>o.addEventListener("clay:baseline-settled",m,{once:!0}))}async function I(l,{rules:m,ifMatch:O}={}){let b=await H();if(b)throw b;if(!await e(M))throw n("DataWriteUnsupported","This host does not support writing page data.");let s=await p();if(!s.isEditMode)throw n("DataWriteUnavailable","Page data writes require an editable page.");await A(s),u(s);let v=O;if(v==null&&(v=s.lastSeenEtag()||await s.seedEtag()),typeof v!="string"||v==="")throw n("DataWriteVersionRequired","Page data writes require a trustworthy document ETag.");u(s),w=!0,s.holdAllSaves(E);let g=null;try{if(s.isSaveInProgress())throw n("SaveInProgress","The page is already being saved.");if(s.saveFateIsUnknown())throw n("SaveOutcomeUnknown","The page's last save has an unknown outcome.");if(s.isSaveConflicted())throw n("SavesHeld","The page cannot write data while another save hold is active.");if(s.hasUnsavedChanges())throw n("UnsavedChanges","Save or discard the page's unsaved changes before writing data.");if(s.savesAdmitted&&!s.savesAdmitted())throw n("ModeTransition","The page is switching modes. Write page data again when it has settled.");if(!D(c()))throw n("SyncRequired","Page data writes require the sync plugin to be connected.");let W={"Content-Type":"application/json","If-Match":v},k=t();k&&(W["Save-Token"]=k);let _=JSON.stringify(l);g=x(o,P);let h=$(d),y;try{y=await h.waitFor(r(q(m,a()),{method:"POST",credentials:"same-origin",redirect:"error",headers:W,body:_,signal:h.signal}))}catch(T){throw h.cancel(),i=!0,Object.assign(n("DataWriteOutcomeUnknown","The page data write has an unknown outcome. Do not retry automatically."),{cause:T,unknownOutcome:!0})}let S;try{if(!y.ok)throw await h.waitFor(R(y));S=await h.waitFor(U(y))}catch(T){throw T?.status?T:(i=!0,Object.assign(n("DataWriteOutcomeUnknown","The page data was written, but its response could not be read."),{cause:T,unknownOutcome:!0}))}finally{h.cancel()}let f=F(y);if(f&&f===s.lastSeenEtag())return g.cancel(),g=null,{data:S,etag:f};let C=await g.waitFor(f);return g=null,C?{data:S,etag:f}:{data:S,etag:f,pageUpdatePending:!0,message:"Written, page update pending."}}finally{g?.cancel(),w=!1,s.releaseAllSaves({reason:E})}}return{writeData:I}}export{N as createPageDataWrite};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as v,B as P,C as x,D as T,E as A,F as k,G as E,H as z,I as C,J as O,K as tt,L as et,M as nt,N as B,O as D,R as it,S as K,c as M,d as L,e as f,n as J,s as $,w as g,x as Q,z as Z}from"./c-
|
|
1
|
+
import{A as v,B as P,C as x,D as T,E as A,F as k,G as E,H as z,I as C,J as O,K as tt,L as et,M as nt,N as B,O as D,R as it,S as K,c as M,d as L,e as f,n as J,s as $,w as g,x as Q,z as Z}from"./c-4FJTBE6I.js";import"./c-EXKHPOVC.js";import"./c-L5VFATT6.js";import"./c-CQQDL6O4.js";import"./c-ZGDYHKG3.js";import"./c-W4JCVLAB.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import{B as Y,d as N}from"./c-AIWN4QN4.js";import{I as X,W as G,m as V}from"./c-QIXT3Q7C.js";import"./c-WCXLG3MV.js";import"./c-57XDY6HC.js";import{a as j}from"./c-I2SCCUEW.js";import"./c-VHNSBD2M.js";var ot=`
|
|
2
2
|
.page-editor .page-table { position: relative; }
|
|
3
3
|
.page-table td { position: relative; }
|
|
4
4
|
.page-table th { position: relative; }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./c-LKSL4AUJ.js";import{b as s,d as c,f as p,h as l}from"./c-EK63G3CG.js";import{f as i}from"./c-XGH4GS2T.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-HA6INT6J.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var u="page-format-activation-failed";function d(){let e=document.querySelector(`meta[name="${s}"]`);return e?p(e.outerHTML):0}var F=async e=>(await import("./core/save-
|
|
1
|
+
import"./c-LKSL4AUJ.js";import{b as s,d as c,f as p,h as l}from"./c-EK63G3CG.js";import{f as i}from"./c-XGH4GS2T.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-HA6INT6J.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var u="page-format-activation-failed";function d(){let e=document.querySelector(`meta[name="${s}"]`);return e?p(e.outerHTML):0}var F=async e=>(await import("./core/save-A5JXV6ME.js")).savePageForce(()=>{},e),P=4,g=1e4,f=e=>e?.ok===!1&&e?.msgType==="skipped"&&/in progress/i.test(e?.msg??""),w=async()=>{let{isSaveInProgress:e}=await import("./core/save-core-MKRPSEEO.js"),r=Date.now()+g;for(;e()&&Date.now()<r;)await new Promise(n=>setTimeout(n,50))};function v({save:e=F,settles:r=w,supported:n=()=>i().then(a=>a===1)}={}){return{read(){return{floor:Math.max(l(),d()),revision:null}},capabilities(){return[]},supported:n,async activate({floor:a=1}={}){let t;try{t=await e({pageFormatFloor:a});for(let o=1;o<P&&f(t);o+=1)await r(),t=await e({pageFormatFloor:a})}catch(o){return{accepted:!1,code:o?.code??u}}return t?.ok?{accepted:!0,revision:null,receipt:t.receipt??t.etag??null}:t?.code===c?{accepted:!1,code:c}:{accepted:!1,code:t?.code??u}}}}export{v as createFormatHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as t,e as o}from"./c-
|
|
1
|
+
import{d as t,e as o}from"./c-FCNAO2MI.js";import"./c-4FJTBE6I.js";import"./c-EXKHPOVC.js";import"./c-L5VFATT6.js";import"./c-CQQDL6O4.js";import"./c-ZGDYHKG3.js";import{c as e}from"./c-W4JCVLAB.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import"./c-AIWN4QN4.js";import"./c-QIXT3Q7C.js";import"./c-WCXLG3MV.js";import"./c-57XDY6HC.js";import"./c-I2SCCUEW.js";import"./c-VHNSBD2M.js";function c({view:r=null}={}){let a=r?e(r,{update:o}):()=>{};return{id:"chart",nodeViews:{chart:(i,n,d)=>new t(i,n,d)},dispose(){a()}}}export{c as createFeature};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Xe,b as ce,d as de,e as ue,f as et}from"./c-6DB2OLRJ.js";import{a as Ke,b as Qe,c as he,d as Ze}from"./c-LZJPNR2W.js";import{a as R,b as Y}from"./c-QTTJYJMA.js";import{b as Ve}from"./c-5VYOWDTI.js";import{b as le,c as oe,d as x,f as ae,g as Ye,h as Je}from"./c-FWKHM4E7.js";import{a as q}from"./c-ZWIOJGMT.js";import{a as Ne}from"./c-ATKAOH23.js";import{a as $e,f as je,g as ze,h as We}from"./c-EK63G3CG.js";import{a as ie,b as Ge,c as M,d as se,e as re,h as Ue}from"./c-NQJRVJ56.js";import{e as Oe}from"./c-XGH4GS2T.js";import{d as qe}from"./c-IJUK2GPW.js";import{f as $,j as ee}from"./c-3O7OBDCM.js";import{a as Ie}from"./c-BPF2NSPV.js";import{D as W,E as Me,G as T,H as Be,b as D,j as ne,s as P,y as Pe}from"./c-7MG5RU63.js";import{a as Fe,b as Re,c as He,e as j,g as z,h as te}from"./c-VG5XIN4T.js";import{m as be,n as De}from"./c-HA6INT6J.js";import{a as Te,b as Le,l as Ce,m as Ae}from"./c-DCFSEJZG.js";function tt(s){let e=new WeakMap,t=0,i=r=>e.get(r)||null,n=r=>{let l=e.get(r);return l||(l=`${s}:${++t}`,e.set(r,l)),l};return{idOf:i,ensure:n,adopt:(r,l)=>{r&&typeof l=="string"&&l&&e.set(r,l)},exportMap:(r,l)=>{let o={},a=[],h=[],c=(d,_)=>{let g=l(d);g&&(o[_]=n(g));let E=d.children;a.push(E.length),h.push(d.tagName.toLowerCase());for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(r,""),o["~"]=a.join(","),o["^"]=h.join(","),o}}}function nt(s,e){let t=new WeakMap;if(!s||!e||typeof e!="object"||Array.isArray(e))return t;let i=e["~"],n=typeof i=="string"?i.split(",").map(Number):null,r=n&&typeof e["^"]=="string"?e["^"].split(","):null,l=d=>Number.isInteger(d)&&d>=0,o=0,a=!1,h=d=>{let _=d;for(;_>0;){let g=n[o++];if(o>n.length||!l(g))return!1;_+=g-1}return!0},c=(d,_)=>{if(a)return;if(n){let f=o++,u=n[f];if(f>=n.length||!l(u)){a=!0;return}let S=!r||r[f]===d.tagName.toLowerCase();if(!S||u!==d.children.length){let w=S&&e[_];typeof w=="string"&&w&&t.set(d,w),h(u)||(a=!0);return}}let g=e[_];typeof g=="string"&&g&&t.set(d,g);let E=d.children;for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(s,""),t}function yt(s){return e=>{for(let t of s){let i=t(e);if(typeof i=="string"&&i!=="")return i}return null}}var Pt=yt([s=>s.getAttribute("data-id"),s=>s.getAttribute("id")]);var mt=/^page(\.[0-9]+)?$/,it=s=>[...s.querySelectorAll('script[merge][clay~="live"]')].filter(e=>mt.test(e.getAttribute("merge")));function st(s,e,t){if(!s.html.includes("data-page"))return s;let i=u=>new DOMParser().parseFromString(u,"text/html"),n=i(s.html),r=n.querySelector("article[data-page]");if(!r)return s;let l=i(e),o=l.querySelector("article[data-page]");if(!o)return null;let a=nt(n.documentElement,s.identityMap),h=(u,S)=>{let w=n.importNode(S,!0),b=a.get(u);return b&&a.set(w,b),u.replaceWith(w),w},c=h(r,o),d=new Map(it(n).map(u=>[u.getAttribute("merge"),u]));for(let u of it(l)){let S=u.getAttribute("merge"),w=d.get(S);w?h(w,u):c.before(n.importNode(u,!0)),d.delete(S)}for(let u of d.values())u.remove();let _=n.querySelector("head > title"),g=l.querySelector("head > title");_&&g?h(_,g):g?n.head.append(n.importNode(g,!0)):_?.remove();let E=n.documentElement,f=t.exportMap(E,u=>{let S=a.get(u);return S?(t.adopt(u,S),u):null});return{...s,html:T(E),identityMap:f}}var vt={"merge-tokens":"tokens","merge-max":"max"};function rt(s,e){if(!e.startsWith("data-")||e==="data-id"||!s?.closest)return null;for(let[t,i]of Object.entries(vt)){let n=s.closest(`[${t}]`);if(n&&n.getAttribute(t).split(/\s+/).includes(e))return i}return null}var m=null,lt=null,B=new Map;function J(){return lt??=Promise.all([import("./c-5T6NZHNM.js"),import("./c-EJTGYSLN.js")]).then(([s,e])=>{m={...s,beginLineageCapture:e.beginLineageCapture};for(let t of[...B.keys()])B.set(t,s.registerContext(t));return m}),lt}var ot=()=>m,I={get size(){return m?m.conflicts.size:0},list(){return m?m.conflicts.list():[]},get(s){return m?m.conflicts.get(s):null},acknowledge(s,e={}){if(m)return m.conflicts.acknowledge(s,e);if(!Array.isArray(s))throw new TypeError("clay.conflicts.acknowledge needs an array of ids");return{removedIds:[],remainingIds:[]}},claim(s,e={}){if(m)return m.conflicts.claim(s,e);if(!e.owner)throw new TypeError("clay.conflicts.claim needs an owner");return{release(){}}},registerContext(s){if(m)return m.conflicts.registerContext(s);if(typeof s!="function")throw new TypeError("clay.conflicts.registerContext needs a resolver function");return B.set(s,null),()=>{let e=B.get(s);B.delete(s),e&&e()}},contextFor(s,e){return m?m.conflicts.contextFor(s,e):null},recoveryOf(s){return m?m.conflicts.recoveryOf(s):null},hasPendingApply(){return m?m.conflicts.hasPendingApply():!1}};var y=null,fe=null;function H(){return fe??=new Promise(s=>setTimeout(s,0)).then(()=>import("./c-RND3G2S2.js")).then(s=>y=s).catch(s=>{throw fe=null,s}),fe}var ye=null,pe=null;function Et(){return pe??=import("./c-VR2BJ4AN.js").then(s=>ye=s.presence).catch(s=>{throw pe=null,s}),pe}var ct=ee().phase==="entering";$&&!ct&&H().catch(()=>{});$&&J().catch(()=>{});var L=null,_e=null,K=[];function dt(s){L.presence.update(s),L.editingMarker.update(s)}function wt(){return _e??=Promise.all([import("./c-BHZYSHW4.js"),import("./c-P3OFYUMA.js")]).then(([s,e])=>{L={presence:s.presence,editingMarker:e.editingMarker};let t=K;K=[];for(let i of t)dt(i);return L}).catch(s=>{throw _e=null,s}),_e}function kt(s){if(L){dt(s);return}K.push(s),wt().catch(()=>{})}var at=Object.freeze({bytes:null,etag:null,seq:null}),xt=()=>({msg:"Not in edit mode",msgType:"skipped",code:null,etag:null}),ut=["[editor-ui]",'[clay~="editor-ui"]',"[save-ignore]","[snapshot-remove]","[no-snapshot]","[no-save]","[save-remove]","[freeze] *","[save-freeze] *",'[clay~="no-save"]','[clay~="no-snapshot"]','[clay~="freeze"] *',Ce,Te].join(","),ft='[clay~="freeze"], [freeze], [save-freeze]';function V(s){for(let e of s.querySelectorAll(ft))e.replaceChildren();return z()&&He(s),s}function ht(s){if(s==null)return s;let e=typeof s=="string"?new DOMParser().parseFromString(s,"text/html"):s;return ne(e),V(e),e}var bt=[Ae,'[clay~="no-watch"]',"[no-watch]","[mutations-ignore]"].join(","),Dt=(s,e,t)=>be(s,e,t)||Le.test(e.toLowerCase()),pt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function It(s){let e=new Map,t=n=>{if(n.matches(ut))return;let r=pt(n);r&&e.set(r,(e.get(r)||0)+1);let l=n.localName==="template"&&n.content?n.content.children:n.children;for(let o of l)t(o)},i=s.nodeType===9?[s.documentElement]:s.nodeType===11?s.children:[s];for(let n of i)n&&n.nodeType===1&&t(n);return e}var Tt=s=>e=>{let t=pt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=It(i)),n.get(t)===1?t:null},ge=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function Lt(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Ct(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function At(){let{forComparison:s,forDirty:e}=Pe({flushUndo:!1});return[s,e]}var Ft=1024*1024;function Rt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Ft?JSON.stringify({[s.snapshotKey]:e,...r}):new Blob([`{${JSON.stringify(s.snapshotKey)}:`,JSON.stringify(e),`,${JSON.stringify(r).slice(1)}`],{type:"application/json"})}var me=class{constructor(){this.sse=null,this.currentFile=null,this.lastHtml=null,this._diskBase=null,this._diskBaseTicket=0,this._agreeSeq=0,this._saveTicket=0,this._peerBaseTicket=0,this._acceptedSaveTicket=0,this._morphTicket=0,this.clientId=this.generateClientId(),this.resumeId=null,this._savedSnapshot?.abort?.abort(),this._savedSnapshot=null,this._sendInFlight=!1,this._queuedSend=null,this._profile=null,this._profilePromise=null,this._sharedData=!1,this._sharedSync=!1,this._liveData=!1,this._editing=null,this._presenceLease=null,this._presenceQuiesced=!1,this._ready=null,this._startGen=0,this.isPaused=!1,this.isDestroyed=!1,this.debug=!1,this._lane=$?"live":"saved",this._laneChosen=!1,this._snapshotHandler=null,this.lastSeenSeq=0,this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingEtag=null,this._pendingBy=null,this._morphInFlight=!1,this._rafHandle=null,this._represented=at,this._handoff=null,this._handoffHeld=!1,this._pendingExternal=null,this._lastExternalSeq=0,this._saveEpoch=0,this._saveSavedHandler=null,this._saveConflictHandler=null,this._settledHandler=null,this._lastIdentityMap=null,this._applyGen=0,this._holdRetryPeer=null,this._holdRetryExt=null,this._servedFetchId=0,this._startupRetry=null,this._engineRetry=null,this._heldLive=!1,this._heldExt=!1,this.identity=tt(this.clientId),this.onConnect=null,this.onDisconnect=null,this.onUpdate=null,this.onError=null,this.onNotification=null}get unresolvedConflicts(){return I.list().filter(e=>e.kind!=="apply-incomplete")}_log(e,t=null){if(!this.debug)return;let i=`[LiveSync ${new Date().toISOString()}]`;t!==null?console.log(i,e,t):console.log(i,e)}generateClientId(){return Math.random().toString(36).slice(2,11)+Date.now().toString(36)}generateResumeId(){try{let e=new Uint8Array(16);return(globalThis.crypto||window.crypto).getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}catch{return Math.random().toString(36).slice(2)+Date.now().toString(36)}}_seedBases(){if(x())return;let e=P({flushUndo:!1});this._setPeerBase(T(e),this.identity.exportMap(e,D),this._ticket()),this._setDiskBase(W({emitForSync:!1}).forSave,this._ticket())}get lane(){return this._lane}set lane(e){this._lane=e,this._laneChosen=!0}start(e=null,{lane:t,represented:i}={}){if(this.isDestroyed=!1,(this.sse||this._snapshotHandler)&&this.cleanup(),this.currentFile=e||this.detectCurrentFile(),!this.currentFile){console.warn("[LiveSync] No file detected");return}let n=ee().mode==="edit"?"live":"saved",r=this.lane==="live";this._lane=t||(this._laneChosen?this._lane:n),this.lastHtml=null,this._lastIdentityMap=null,this._peerBaseTicket=this._ticket(),this._diskBase=null,this._diskBaseTicket=this._ticket(),this._saveTicket=0,this._savedSnapshot?.abort?.abort(),this._savedSnapshot=null,this._applyGen++,this.lastSeenSeq=0,this._lastExternalSeq=0,this._represented=i?Object.freeze({bytes:i.bytes??null,etag:i.etag??null,seq:i.seq??null}):at,this._acquireEmptySaved=r&&this.lane==="saved"&&this._represented.bytes===null,this._pendingExternal=null,this.resumeId=this.generateResumeId(),this.lane==="live"&&this._seedBases(),this.lane==="live"&&J().catch(()=>{}),console.log(`[LiveSync] Starting for: ${this.currentFile} (lane=${this.lane})`);let l=++this._startGen;if(this.lane==="live"&&!(y&&y.baselineSettled())){let o=this._applyGen,a=this._morphTicket,h=this._saveEpoch,c=this.lastHtml,d=this._diskBaseTicket,_=this._diskBase!==null;this._settledHandler=()=>{if(this._settledHandler=null,!(this.isDestroyed||this._startGen!==l)&&!qe()&&!x()&&this._saveTicket===0&&this._morphTicket===a){if(c!==null&&this._applyGen===o&&this._saveEpoch===h&&this.lastHtml===c){let g=P({flushUndo:!1});this._setPeerBase(T(g),this.identity.exportMap(g,D),this._ticket())}_&&this._diskBaseTicket===d&&this._setDiskBase(W({emitForSync:!1}).forSave,this._ticket())}},document.addEventListener("clay:baseline-settled",this._settledHandler,{once:!0})}this._ready=Promise.all([this.lane==="live"?H():null,this._resolveProfile()]).then(()=>{this.isDestroyed||this._startGen!==l||this.connect()}),this.lane==="live"&&(this.listenForSnapshots(),Et().then(o=>this._startPresence(o,l),()=>{}),this._saveSavedHandler=o=>{this._saveEpoch++;let a=this._saveTicket||this._ticket();this._saveTicket=0,a>this._acceptedSaveTicket&&(this._acceptedSaveTicket=a);let h=y?y.getLastSavedBytes():null;h!=null&&this._setDiskBase(h,a),this._relayCommit(o?.detail?.captureId,h)},document.addEventListener("clay:save-saved",this._saveSavedHandler),this._saveConflictHandler=o=>{let a=o.detail&&o.detail.etag;a&&queueMicrotask(()=>{this.isDestroyed||a===ie()&&(y?.conflictResolvedBySync(a),this._saveAfterMerge(x(),!1))})},document.addEventListener("clay:save-conflict",this._saveConflictHandler))}cleanup(){if(this.sse&&(this.sse.close(),this.sse=null),he(),K=[],L&&(L.presence.clear(),L.editingMarker.clear()),this._editing&&(this._editing.stop(),this._editing=null),this._presenceLease){let e=this._presenceLease;this._presenceLease=null,typeof e.stop=="function"?e.stop():e.detach()}this._lastRoster=null,this._snapshotHandler&&(document.removeEventListener("clay:snapshot-ready",this._snapshotHandler),this._snapshotHandler=null),this._saveSavedHandler&&(document.removeEventListener("clay:save-saved",this._saveSavedHandler),this._saveSavedHandler=null),this._saveConflictHandler&&(document.removeEventListener("clay:save-conflict",this._saveConflictHandler),this._saveConflictHandler=null),this._settledHandler&&(document.removeEventListener("clay:baseline-settled",this._settledHandler),this._settledHandler=null),this._queuedSend=null,this._rafHandle!=null&&(this._cancelFrame(this._rafHandle),this._rafHandle=null),this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingBy=null,this._pendingExternal=null,this._handoff=null,this._handoffHeld=!1,clearTimeout(this._holdRetryPeer),clearTimeout(this._holdRetryExt),this._holdRetryPeer=null,this._holdRetryExt=null,clearTimeout(this._startupRetry),this._startupRetry=null,clearTimeout(this._engineRetry),this._engineRetry=null,this._servedFetchId++}detectCurrentFile(){let e=window.location.pathname;if(e==="/")return"index.html";e=e.replace(/^\//,"");let t=e.match(/^(.*?\.html(?:clay)?)/);return t?t[1]:e}_resolveProfile(){return this._profilePromise||(this._profilePromise=et().then(e=>(this._sharedData=e.sharedData,this._sharedSync=e.sharedSync,this._liveData=e.liveData,this._profile=e.profile,this._log(`Wire profile: ${e.profile.name}`),e.profile))),this._profilePromise}_setHeld(e,t,i){let n=e==="live"?"_heldLive":"_heldExt";this[n]!==t&&(this[n]=t,!t&&!this._heldLive&&!this._heldExt&&Ue({fresh:!0,clearIfMissing:!1}),document.dispatchEvent(new CustomEvent(t?"clay:sync-held":"clay:sync-resumed",{detail:{lane:e,el:i||null}})))}_applyEtagFrame(e){return typeof e.etag!="string"||typeof e.html=="string"?!1:(this._log("Dropping a stamp that arrived with no document: nothing proves this tab holds those bytes"),!0)}connect(){if(this.isDestroyed)return;let t=(this._profile||ue.legacy).streamPath(window.location.href,this.lane,this.resumeId,this.clientId);this.sse=new Xe(new URL(t,window.location.origin).href,{shared:this._sharedSync,sharedData:this._sharedData,documentURL:window.location.href,lane:this.lane,clientId:this.clientId,keepAliveWhenHidden:this._liveData&&this.lane==="live",startupCheck:!!Ie}),this._acquireEmptySaved&&(this._acquireEmptySaved=!1,this._fetchServedDocument(void 0,{repair:!0})),this.sse.onopen=()=>{console.log("[LiveSync] Connected"),this._editing&&this._editing.reconnected(),ye&&ye.reconnect(),this.onConnect&&this.onConnect()},this.sse.addEventListener("open",()=>Qe({clientId:this.clientId,lane:this.lane})),this.sse.addEventListener("error",()=>he());for(let i of Ke)this.sse.addEventListener(i,n=>{let r;try{r=JSON.parse(n.data)}catch{return}Ze(i,r)});this.sse.addEventListener("cursor",i=>{let n;try{n=JSON.parse(i.data)}catch{return}if(!n||n.resync!==!0&&n.startup!==!0)return;let r=n.resync===!0,l=n.startup===!0&&!r;console.log(r?"[LiveSync] Server could not replay everything; refetching the document":"[LiveSync] Checking the served document against the version this tab was served"),this._fetchServedDocument(typeof n.seq=="number"?n.seq:void 0,{repair:r,startup:l})}),this.sse.addEventListener("presence",i=>{let n;try{n=JSON.parse(i.data)}catch{return}kt(n),this._lastRoster=n,this._editing&&this._editing.roster(n)}),this.sse.onmessage=i=>{let n=JSON.parse(i.data),{seq:r}=n;if(typeof r=="number"&&r<=this.lastSeenSeq){this._log(`Dropping stale message: seq=${r}, lastSeen=${this.lastSeenSeq}`);return}if(typeof r=="number"&&(this.lastSeenSeq=r),n.type==="notification"){if(this._maybeAcceptExternalChange(n))return;this.handleNotification(n);return}if(n.error){console.error("[LiveSync] Server error:",n.error),this.onError&&this.onError(new Error(n.error));return}if(this._applyEtagFrame(n))return;let{html:l,sender:o,identityMap:a}=n;if(o===this.clientId){this._log("Ignoring own message (sender matches clientId)");return}if(typeof l!="string"){console.error("[LiveSync] Received invalid html, ignoring");return}let h=typeof n.etag=="string"&&n.etag?n.etag:null;if(this.lane==="live"&&!h&&Ge()){this._log(`Dropping an unstamped live frame on a stamping host (seq=${r})`);return}if(this.lane==="saved"&&l===this._represented.bytes){this._represented=Object.freeze({bytes:l,etag:h||null,seq:r??null}),M(h);return}if(h&&l===this.lastHtml){this._log(`Taking the stamp from a peer save of content already applied (seq=${r})`),M(h),y&&y.isSaveConflicted()&&(y.conflictResolvedBySync(h),this._saveAfterMerge(x(),!1));return}this._log(`Received update from: ${o} (my clientId: ${this.clientId}, seq=${r})`),this.applyUpdate(l,r,a,h,n.by),this.onUpdate&&this.onUpdate({html:l,sender:o,seq:r,identityMap:a,etag:h})},this.sse.onerror=()=>{this.sse.readyState===EventSource.CONNECTING?console.log("[LiveSync] Reconnecting..."):this.sse.readyState===EventSource.CLOSED&&(console.log("[LiveSync] Connection closed"),this.onError&&this.onError(new Error("Connection closed"))),this.onDisconnect&&this.onDisconnect()}}listenForSnapshots(){this._snapshotHandler=e=>{if(!e.detail||e.detail.forSave!==!0)return;this._saveTicket=this._ticket();let{documentElement:t}=e.detail;if(!t)return;this._log("snapshot-ready received, preparing to send");let i=this.identity.exportMap(t,D);this._savedSnapshot?.abort?.abort();let n={html:null,steps:null,copy:null,abort:null,identityMap:i,ticket:this._saveTicket,captureId:e.detail.captureId??null};if(e.detail.sliced){n.copy=Be(t),n.abort=new AbortController;let{signal:r}=n.abort;Promise.all([import("./c-2KIEGNC4.js"),import("./c-ZWBI4HYK.js")]).then(([{serializeForSyncSteps:l},{runSliced:o}])=>{if(r.aborted||typeof n.html=="string")return;let a=(function*(){let h=yield*l(n.copy);n.html=h,n.steps=null})();return n.steps=a,o(a,{signal:r})}).catch(()=>{})}else n.html=T(t);this._savedSnapshot=n},document.addEventListener("clay:snapshot-ready",this._snapshotHandler)}_enqueueSend(e,t,i=null){if(!this._profile){this._queuedSend={html:e,identityMap:t,etag:i},this._resolveProfile().then(()=>this._flushQueuedSend());return}if(this._sendInFlight){this._queuedSend={html:e,identityMap:t,etag:i};return}this._postUpdate(e,t,i)}_flushQueuedSend(){if(this.isDestroyed||this._sendInFlight)return;let e=this._queuedSend;e&&(this._queuedSend=null,this._postUpdate(e.html,e.identityMap,e.etag))}_relayCommit(e=null,t=null){if(this.isDestroyed)return;let i=ie(),n=this._savedSnapshot;if(n&&(n.captureId??null)!==(e??null)){this._log("Skipping send - snapshot belongs to a different capture");return}let r=n;if(this._savedSnapshot=null,r?.copy&&typeof r.html!="string")if(r.abort?.abort(),r.steps)for(let c=r.steps.next();!c.done;c=r.steps.next());else r.html=T(r.copy);if(!r||typeof r.html!="string")return;let l=r;if(typeof t=="string"){try{l=st(r,t,this.identity)}catch(c){this._log(`Skipping send - page relay failed: ${c&&c.message}`);return}if(!l){this._log("Skipping send - accepted capture has no page article");return}}let o=Ht(e)??t,a=typeof o=="string"?je(o):0;l={...l,html:qt(ze(l.html,Math.max(We(),a)),o)};let h=!i&&l.html===this.lastHtml;if(this._setPeerBase(l.html,l.identityMap,l.ticket),h){this._log("Skipping send - HTML unchanged");return}this._enqueueSend(l.html,l.identityMap,i||null)}_postUpdate(e,t,i=null,n=0){this._log(`Sending update (HTML length: ${e.length})`),this._sendInFlight=!0;let r=!1,l=this._profile||ue.legacy;fetch(new URL(l.relayPath,window.location.origin).href,{method:"POST",headers:{"Content-Type":"application/json",[l.documentHeader]:window.location.href,[$e]:String(1)},body:Rt(l,e,this.clientId,t,i)}).then(o=>{o.ok||(console.warn("[LiveSync] Save returned status:",o.status),r=o.status>=500||o.status===408||o.status===429)}).catch(o=>{console.error("[LiveSync] Save failed:",o),this.onError&&this.onError(o),r=!0}).finally(()=>{this._sendInFlight=!1;let o=this._queuedSend;if(this._queuedSend=null,o){this._postUpdate(o.html,o.identityMap,o.etag);return}!r||!i||n>=3||this.isDestroyed||(this._sendInFlight=!0,setTimeout(()=>{if(this._sendInFlight=!1,this.isDestroyed)return;let a=this._queuedSend;this._queuedSend=null,a?this._postUpdate(a.html,a.identityMap,a.etag):this._postUpdate(e,t,i,n+1)},500*2**n))})}_startPresence(e,t){return this.isDestroyed||this._startGen!==t||this._presenceLease?null:e.connect({send:i=>this._postPresence(i)}).then(i=>this.isDestroyed||this._startGen!==t?(typeof i?.stop=="function"?i.stop():i?.detach(),null):(this._presenceLease=i||null,Oe("presence-editing")),()=>!1).then(i=>{if(!(!i||this.isDestroyed||this._startGen!==t||this._editing))return H().then(n=>{this.isDestroyed||this._startGen!==t||this._editing||(this._editing=new n.EditingSender({}),this._presenceQuiesced?this._editing.stop():(this._editing.start(),this._editing.roster(this._lastRoster)))})})}_postPresence(e){let t=new URL("/_/presence",window.location.origin);return t.searchParams.set("client-id",this.clientId),fetch(t.href,{method:"POST",headers:{"Content-Type":"application/json","Document-URL":window.location.href},body:JSON.stringify(e)}).then(i=>i.ok,()=>!1)}_maybeAcceptExternalChange(e){if(this.lane!=="live")return!1;let t=e.data;return t&&t.kind==="external-change"?(typeof t.html=="string"?this._enqueueExternal(t.html,e.seq,t.etag,t.by):this._fetchExternalChange(e.seq),!0):typeof e.msg=="string"&&e.msg.endsWith("changed on disk outside this tab")?(this._fetchExternalChange(e.seq),!0):!1}_enqueueExternal(e,t,i,n){if(typeof t=="number"){if(t<=this._lastExternalSeq){this._log(`Dropping replayed external change: seq=${t}`);return}this._lastExternalSeq=t}this._pendingExternal={html:e,seq:t,saveEpoch:this._saveEpoch,etag:typeof i=="string"&&i?i:null,by:n??null},this._scheduleNextFrame()}_fetchExternalChange(e){if(typeof e=="number"){if(e<=this._lastExternalSeq)return;this._lastExternalSeq=e}this._fetchServedDocument(e)}_fetchServedDocument(e,{attempt:t=0,repair:i=!1,startup:n=!1}={}){if(n&&(this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null)){this._retryStartup(t);return}let r=this._saveEpoch,l=this._startGen,o=this.lastSeenSeq,a=this._applyGen,h=++this._servedFetchId;i&&typeof e!="number"&&(e=this._lastExternalSeq),fetch(new URL(window.location.href),{cache:"no-store"}).then(c=>c.ok?c.text():null).then(c=>{if(this.isDestroyed||c==null||this._startGen!==l)return;let d=Lt(c),_=n||i&&!!d;if(_){if(h!==this._servedFetchId){i&&this._retryStartup(t+1,{repair:i,startup:n},typeof e=="number"?Math.max(e,this._lastExternalSeq):e);return}if(r!==this._saveEpoch||o!==this.lastSeenSeq||a!==this._applyGen||this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null){this._retryStartup(t+1,{repair:i,startup:n},e);return}if(d){if(d===se()){(i||n)&&this.lane==="saved"&&(this._represented=Object.freeze({bytes:c,etag:d,seq:e??null}));return}}else if(!i)return}else if(typeof e=="number"&&e<this._lastExternalSeq){i&&t<3&&this._fetchServedDocument(this._lastExternalSeq,{attempt:t+1,repair:i,startup:n});return}else if(this._saveEpoch>r){t<3&&(console.log("[LiveSync] Refetching external change: own save landed mid-fetch"),this._fetchServedDocument(e,{attempt:t+1,repair:i,startup:n}));return}this._pendingExternal={html:c,seq:e,saveEpoch:r,etag:d,by:null,fetchOptions:{repair:i,startup:n,attempt:t,versionCheck:_},startGen:l,seenSeq:o,applyGen:a,fetchId:h},this._scheduleNextFrame()}).catch(c=>{this._log("External-change fetch failed",c),typeof e=="number"&&this._lastExternalSeq===e&&(this._lastExternalSeq=e-1)})}_retryStartup(e=0,t={startup:!0},i){this.isDestroyed||e>3||(clearTimeout(this._startupRetry),this._startupRetry=setTimeout(()=>{if(this._startupRetry=null,!this.isDestroyed){if(this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null){this._retryStartup(e,t,i);return}this._fetchServedDocument(i,{...t,attempt:e})}},16))}applyUpdate(e,t,i,n,r){this.isDestroyed||(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingEtag=n??null,this._pendingBy=r??null,this._scheduleNextFrame())}prepareHandoff(e={}){return this._handoff?Promise.resolve(this._handoff):this.isDestroyed?Promise.reject(new Error("LiveSync: stopped")):(this._handoffHeld=!0,this._rafHandle!=null&&(this._cancelFrame(this._rafHandle),this._rafHandle=null),import("./c-OTMKN2OO.js").then(({engineHandoff:t})=>t(this,e)).then(t=>this._handoff=t))}_scheduleNextFrame(){this.isDestroyed||this._handoffHeld||this._rafHandle==null&&(this._morphInFlight||(this._rafHandle=this._requestFrame(()=>this._runPending())))}async _runPending(){if(this._rafHandle=null,this.isDestroyed)return;if(!R()){this._morphInFlight=!0;try{await Y()}catch(r){this._log("Merge engine failed to load",r),this._engineRetry=setTimeout(()=>this._scheduleNextFrame(),2e3);return}finally{this._morphInFlight=!1}if(this.isDestroyed)return}let e=this._pendingExternal,t=e?.fetchOptions||null,i=!!(t?.startup||t?.versionCheck),n=!1;if(e!=null&&(i&&this._pendingHtml!=null?n=!1:this._pendingHtml==null?n=!0:n=!(typeof e.seq=="number"&&typeof this._pendingSeq=="number"&&this._pendingSeq<e.seq)),n)if(this._pendingExternal=null,typeof e.seq=="number"&&e.seq<this._lastExternalSeq)i&&t?.repair?this._retryStartup((t.attempt||0)+1,t,this._lastExternalSeq):this._log("Dropping superseded external change at drain");else if(i&&e.startGen!==this._startGen)this._log("Dropping superseded startup check at drain");else if(i&&e.fetchId!==this._servedFetchId)t?.repair?this._retryStartup((t.attempt||0)+1,t,this._lastExternalSeq):this._log("Dropping superseded startup check at drain");else if(i&&(e.saveEpoch!==this._saveEpoch||e.seenSeq!==this.lastSeenSeq||e.applyGen!==this._applyGen))this._retryStartup((t.attempt||0)+1,t,e.seq);else if(i&&e.etag!=null&&e.etag===se())this._log("Startup check found the same version: nothing to apply");else if(!i&&e.saveEpoch!==this._saveEpoch)console.log("[LiveSync] Refetching external change: own save landed after queue"),this._fetchServedDocument(e.seq,t||{});else{this._morphInFlight=!0;try{await this._doApplyExternal(e.html,e.seq,e.etag,e.by,t)}catch(r){console.error("[LiveSync] applyExternal failed:",r)}finally{this._morphInFlight=!1}}else{let r=this._pendingHtml,l=this._pendingSeq,o=this._pendingIdentityMap,a=this._pendingEtag,h=this._pendingBy;if(this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingEtag=null,this._pendingBy=null,r==null)return;this._morphInFlight=!0;try{await this._doApplyUpdate(r,l,o,a,h)}catch(c){console.error("[LiveSync] applyUpdate failed:",c)}finally{this._morphInFlight=!1}}!this.isDestroyed&&(this._pendingHtml!=null||this._pendingExternal!=null)&&this._scheduleNextFrame()}_ticket(){return++this._agreeSeq}_setDiskBase(e,t){t<=this._diskBaseTicket||(this._diskBase=e,this._diskBaseTicket=t)}_setPeerBase(e,t,i){return i<this._peerBaseTicket?!1:(this._peerBaseTicket=i,this.lastHtml=e,this._lastIdentityMap=t&&typeof t=="object"&&!Array.isArray(t)?t:null,!0)}_requestFrame(e){return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(e):setTimeout(e,16)}_cancelFrame(e){if(typeof window<"u"&&typeof window.cancelAnimationFrame=="function"){window.cancelAnimationFrame(e);return}clearTimeout(e)}async _mergeIncoming(e,t,{base:i,baseIdentityMap:n=null,captureLocal:r,synthetic:l,source:o="peer",seq:a=null,etag:h=null,extra:c={}}){R()||await Y();let{beginApply:d,completeApply:_,failApply:g,beginLineageCapture:E}=ot()||await J(),f,u=p=>{f=E(I.list());try{let v=R().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),v}catch(v){throw f.invalidate(I.list()),f.finish(I.list()),v}},S=this.identity,w=De,b=Tt(new WeakMap),N=p=>ge(p)?{first:b,map:p,then:b}:b,O=l?p=>b(p)||S.idOf(D(p)||p)||null:b,C=e,Se=new Map;if(ge(t)){C=new DOMParser().parseFromString(e,"text/html"),ne(C);let p=R().HyperMorph.importMap(C.documentElement,t);for(let v of C.querySelectorAll("[data-id], [id]")){let k=b(v),xe=k&&p.get(v);xe&&Se.set(k,xe)}}C=ht(C);let Q={live:document,remote:C,ignore:p=>p.matches(ut),opaque:p=>p.matches(ft)||z()&&Re(p),remoteWins:p=>p.matches(bt),ignoreAttribute:(p,v,k)=>Dt(p,v,k)||z()&&Fe(k||p,v),attributeMerge:rt,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:R().mergeTagRecognizers},hooks:{beforeAttributeUpdated:w},...c},Ee=this.lane==="live"&&x(),we=ae(),G,Z=null,F=null;if(i==null)G=u({...Q,base:null,local:{root:V(r()),toLive:D},identity:{local:O,remote:N(t)}});else if(Ee){let p=r(),v=p.cloneNode(!0);Z=V(p),F=d({source:o,seq:a,etag:h,root:Z,recoveryRoot:v,domain:o==="disk"?"save":"sync"});try{G=u({...Q,base:ht(i),local:{root:Z,toLive:D},identity:{base:N(n),local:O,remote:N(t)}})}catch(k){throw g(F,k),k}}else{let p=V(r()),v=p.ownerDocument;v.documentElement!==p&&v.replaceChild(p,v.documentElement),G=u({...Q,base:v,local:{root:p,toLive:D},fastPath:!0,identity:{base:O,local:O,remote:N(t)}})}let U=this._ticket();this._morphTicket=U;let A;try{A=await G}catch(p){f.invalidate(I.list());try{F&&g(F,p,{ticket:U})}finally{f.finish(I.list())}throw p}let _t=ae().gen!==we.gen,ke;try{f.prepareComplete(A,I.list()),ke=F?_(F,A.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&A.localDiverged?Ye():Ee&&!A.localDiverged&&Je(we);let gt=new Set(ge(t)?Object.values(t):[]);for(let[p,v]of A.identities){let k=gt.has(v)?v:Se.get(v);k&&S.adopt(p,k)}return{report:A,ticket:U,typedDuringWait:_t,conflictIds:ke}}_saveAfterMerge(e,t){(e||t)&&Ve()&&(y?y.savePageThrottled():xt())}async _doApplyUpdate(e,t,i,n,r=null){if(ce(e)){await de();return}this.lane==="live"&&!y&&await H(),this._log("applyUpdate - pausing mutations and morphing"),this.isPaused=!0;let l=window.scrollX,o=window.scrollY;q.pause(),le();let a=!1,h=!1,c=!1;try{if(this.lane==="live"&&x()&&this.lastHtml===null){console.log("[LiveSync] Holding incoming update: unsaved local edits and no baseline to merge against"),this._setHeld("live",!0,null);let f=this._saveEpoch,u=this.lastSeenSeq;clearTimeout(this._holdRetryPeer),this._holdRetryPeer=setTimeout(()=>{this._holdRetryPeer=null,!(this.isDestroyed||this._pendingHtml!=null)&&this._saveEpoch===f&&this.lastSeenSeq===u&&(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingBy=r,this._scheduleNextFrame())},3e3);return}this._setHeld("live",!1);let{report:d,ticket:_,typedDuringWait:g,conflictIds:E}=await this._mergeIncoming(e,i,{base:this.lastHtml,baseIdentityMap:this._lastIdentityMap,captureLocal:()=>P({flushUndo:!1}),synthetic:!0,source:"peer",seq:t,etag:n});if(a=d.localDiverged,h=g,te(),window.scrollTo(l,o),this._setPeerBase(e,i,_),this._applyGen++,this._acceptedSaveTicket>_||(typeof n=="string"&&n?(M(n),c=!0):re()),this.lane==="live"&&!a&&!x()){let{forSave:f,forComparison:u,forDirty:S}=W({emitForSync:!1,flushUndo:!1});y.setLastSavedBaselines(u,S),this._setDiskBase(f,this._ticket())}this.lane==="saved"&&(this._represented=Object.freeze({bytes:e,etag:n||null,seq:t??null})),document.dispatchEvent(new CustomEvent("clay:sync-applied",{detail:{seq:t,source:this.lane==="saved"?"disk":"peer",lane:this.lane,by:r||null,html:e,report:d,unresolved:this.unresolvedConflicts,conflictIds:E}}))}finally{this._log("applyUpdate - morph complete, resuming mutations"),q.resume(),oe(),await new Promise(d=>setTimeout(d,0)),this.isPaused=!1}c&&y?.conflictResolvedBySync(n),this._saveAfterMerge(a,h)}async _doApplyExternal(e,t,i=null,n=null,r=null){if(ce(e)){await de();return}this.lane==="live"&&!y&&await H();let l=this._diskBase;this._log(`applyExternal - external disk change (seq=${t})`),this.isPaused=!0;let o=window.scrollX,a=window.scrollY;q.pause(),le();let h=!1,c=!1,d=!1;try{if(this.lane==="live"&&x()&&this._diskBase===null){if(console.log("[LiveSync] Holding external change: unsaved local edits and no baseline to merge against"),this._setHeld("external",!0,null),r?.startup||r?.versionCheck){clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{if(this._holdRetryExt=null,this.isDestroyed)return;let S=typeof t=="number"?Math.max(t,this._lastExternalSeq):t;this._retryStartup(0,r,S)},3e3);return}let u=this._saveEpoch;clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{this._holdRetryExt=null,!(this.isDestroyed||this._pendingExternal!=null)&&(this._pendingExternal={html:e,seq:t,saveEpoch:u,etag:i,by:n},this._scheduleNextFrame())},3e3);return}this._setHeld("external",!1);let{report:_,ticket:g,typedDuringWait:E,conflictIds:f}=await this._mergeIncoming(e,null,{base:this._diskBase,captureLocal:()=>Me().saveClone,synthetic:!1,source:"disk",seq:t,etag:i,extra:{beforeApply:u=>Ct(u.documentElement,this.lane)}});if(h=_.localDiverged,c=E,te(),this._setDiskBase(e,g),window.scrollTo(o,a),this._acceptedSaveTicket>g||(typeof i=="string"&&i?(M(i),d=!0):re()),this.lane==="live"&&!h&&!x()){y.setLastSavedBaselines(...At()),y.setUnsavedChanges(!1);let u=P({flushUndo:!1});this._setPeerBase(T(u),this.identity.exportMap(u,D),g),this._applyGen++}this.lane==="saved"&&(this._represented=Object.freeze({bytes:e,etag:i||null,seq:t??null})),document.dispatchEvent(new CustomEvent("clay:sync-applied",{detail:{seq:t,source:"disk",etag:typeof i=="string"&&i?i:null,by:n||null,html:e,report:_,conflictIds:f,unresolved:this.unresolvedConflicts}}))}finally{this._log("applyExternal - morph complete, resuming mutations"),q.resume(),oe(),await new Promise(_=>setTimeout(_,0)),this.isPaused=!1}d&&y?.conflictResolvedBySync(i),this._saveAfterMerge(h,c),l!=null&&j(l)===j(e)&&y&&y.schedulePaintHeal(()=>this._diskBase==null?null:j(this._diskBase))}handleNotification({msgType:e,msg:t,action:i,persistent:n,data:r}){this._log(`Notification received: ${e} - ${t}`),e==="data-loss"||(n&&window.toastPersistent?window.toastPersistent(t,e):window.toast?window.toast(t,e):console.log(`[LiveSync] Notification: ${t}`)),document.dispatchEvent(new CustomEvent("clay:notification",{detail:{msgType:e,msg:t,action:i,persistent:n,data:r}})),this.onNotification&&this.onNotification({msgType:e,msg:t,action:i,persistent:n,data:r})}stop(){this.cleanup(),this.isDestroyed=!0,console.log("[LiveSync] Stopped")}editParticipant(){return H().then(e=>e.syncParticipant(this))}},X=null;Ne((s,e)=>{X=typeof s=="string"?{html:s,captureId:e?.captureId??null}:null});var Ht=s=>X&&(X.captureId??null)===(s??null)?X.html:null;function qt(s,e){if(typeof e!="string"||e===s)return s;let t=i=>new DOMParser().parseFromString(i,"text/html").documentElement;return t(s).isEqualNode(t(e))?e:s}var ve=new me;typeof window<"u"&&!ct&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>ve.start()):ve.start());var _n=(s,e,t)=>Y().then(({morph:i})=>i(s,e,t));var gn=ve;export{I as a,ut as b,bt as c,me as d,ve as e,_n as f,gn as g};
|
|
1
|
+
import{a as Xe,b as ce,d as de,e as ue,f as et}from"./c-2RARVIAK.js";import{a as Ke,b as Qe,c as he,d as Ze}from"./c-LZJPNR2W.js";import{a as R,b as Y}from"./c-QTTJYJMA.js";import{b as Ve}from"./c-5VYOWDTI.js";import{b as le,c as oe,d as x,f as ae,g as Ye,h as Je}from"./c-FWKHM4E7.js";import{a as q}from"./c-ZWIOJGMT.js";import{a as Ne}from"./c-ATKAOH23.js";import{a as $e,f as je,g as ze,h as We}from"./c-EK63G3CG.js";import{a as ie,b as Ge,c as M,d as se,e as re,h as Ue}from"./c-NQJRVJ56.js";import{e as Oe}from"./c-XGH4GS2T.js";import{d as qe}from"./c-IJUK2GPW.js";import{f as $,j as ee}from"./c-3O7OBDCM.js";import{a as Ie}from"./c-BPF2NSPV.js";import{D as W,E as Me,G as T,H as Be,b as D,j as ne,s as P,y as Pe}from"./c-7MG5RU63.js";import{a as Fe,b as Re,c as He,e as j,g as z,h as te}from"./c-VG5XIN4T.js";import{m as be,n as De}from"./c-HA6INT6J.js";import{a as Te,b as Le,l as Ce,m as Ae}from"./c-DCFSEJZG.js";function tt(s){let e=new WeakMap,t=0,i=r=>e.get(r)||null,n=r=>{let l=e.get(r);return l||(l=`${s}:${++t}`,e.set(r,l)),l};return{idOf:i,ensure:n,adopt:(r,l)=>{r&&typeof l=="string"&&l&&e.set(r,l)},exportMap:(r,l)=>{let o={},a=[],h=[],c=(d,_)=>{let g=l(d);g&&(o[_]=n(g));let E=d.children;a.push(E.length),h.push(d.tagName.toLowerCase());for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(r,""),o["~"]=a.join(","),o["^"]=h.join(","),o}}}function nt(s,e){let t=new WeakMap;if(!s||!e||typeof e!="object"||Array.isArray(e))return t;let i=e["~"],n=typeof i=="string"?i.split(",").map(Number):null,r=n&&typeof e["^"]=="string"?e["^"].split(","):null,l=d=>Number.isInteger(d)&&d>=0,o=0,a=!1,h=d=>{let _=d;for(;_>0;){let g=n[o++];if(o>n.length||!l(g))return!1;_+=g-1}return!0},c=(d,_)=>{if(a)return;if(n){let f=o++,u=n[f];if(f>=n.length||!l(u)){a=!0;return}let S=!r||r[f]===d.tagName.toLowerCase();if(!S||u!==d.children.length){let w=S&&e[_];typeof w=="string"&&w&&t.set(d,w),h(u)||(a=!0);return}}let g=e[_];typeof g=="string"&&g&&t.set(d,g);let E=d.children;for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(s,""),t}function yt(s){return e=>{for(let t of s){let i=t(e);if(typeof i=="string"&&i!=="")return i}return null}}var Pt=yt([s=>s.getAttribute("data-id"),s=>s.getAttribute("id")]);var mt=/^page(\.[0-9]+)?$/,it=s=>[...s.querySelectorAll('script[merge][clay~="live"]')].filter(e=>mt.test(e.getAttribute("merge")));function st(s,e,t){if(!s.html.includes("data-page"))return s;let i=u=>new DOMParser().parseFromString(u,"text/html"),n=i(s.html),r=n.querySelector("article[data-page]");if(!r)return s;let l=i(e),o=l.querySelector("article[data-page]");if(!o)return null;let a=nt(n.documentElement,s.identityMap),h=(u,S)=>{let w=n.importNode(S,!0),b=a.get(u);return b&&a.set(w,b),u.replaceWith(w),w},c=h(r,o),d=new Map(it(n).map(u=>[u.getAttribute("merge"),u]));for(let u of it(l)){let S=u.getAttribute("merge"),w=d.get(S);w?h(w,u):c.before(n.importNode(u,!0)),d.delete(S)}for(let u of d.values())u.remove();let _=n.querySelector("head > title"),g=l.querySelector("head > title");_&&g?h(_,g):g?n.head.append(n.importNode(g,!0)):_?.remove();let E=n.documentElement,f=t.exportMap(E,u=>{let S=a.get(u);return S?(t.adopt(u,S),u):null});return{...s,html:T(E),identityMap:f}}var vt={"merge-tokens":"tokens","merge-max":"max"};function rt(s,e){if(!e.startsWith("data-")||e==="data-id"||!s?.closest)return null;for(let[t,i]of Object.entries(vt)){let n=s.closest(`[${t}]`);if(n&&n.getAttribute(t).split(/\s+/).includes(e))return i}return null}var m=null,lt=null,B=new Map;function J(){return lt??=Promise.all([import("./c-5T6NZHNM.js"),import("./c-EJTGYSLN.js")]).then(([s,e])=>{m={...s,beginLineageCapture:e.beginLineageCapture};for(let t of[...B.keys()])B.set(t,s.registerContext(t));return m}),lt}var ot=()=>m,I={get size(){return m?m.conflicts.size:0},list(){return m?m.conflicts.list():[]},get(s){return m?m.conflicts.get(s):null},acknowledge(s,e={}){if(m)return m.conflicts.acknowledge(s,e);if(!Array.isArray(s))throw new TypeError("clay.conflicts.acknowledge needs an array of ids");return{removedIds:[],remainingIds:[]}},claim(s,e={}){if(m)return m.conflicts.claim(s,e);if(!e.owner)throw new TypeError("clay.conflicts.claim needs an owner");return{release(){}}},registerContext(s){if(m)return m.conflicts.registerContext(s);if(typeof s!="function")throw new TypeError("clay.conflicts.registerContext needs a resolver function");return B.set(s,null),()=>{let e=B.get(s);B.delete(s),e&&e()}},contextFor(s,e){return m?m.conflicts.contextFor(s,e):null},recoveryOf(s){return m?m.conflicts.recoveryOf(s):null},hasPendingApply(){return m?m.conflicts.hasPendingApply():!1}};var y=null,fe=null;function H(){return fe??=new Promise(s=>setTimeout(s,0)).then(()=>import("./c-P3CK66NT.js")).then(s=>y=s).catch(s=>{throw fe=null,s}),fe}var ye=null,pe=null;function Et(){return pe??=import("./c-VR2BJ4AN.js").then(s=>ye=s.presence).catch(s=>{throw pe=null,s}),pe}var ct=ee().phase==="entering";$&&!ct&&H().catch(()=>{});$&&J().catch(()=>{});var L=null,_e=null,K=[];function dt(s){L.presence.update(s),L.editingMarker.update(s)}function wt(){return _e??=Promise.all([import("./c-BHZYSHW4.js"),import("./c-P3OFYUMA.js")]).then(([s,e])=>{L={presence:s.presence,editingMarker:e.editingMarker};let t=K;K=[];for(let i of t)dt(i);return L}).catch(s=>{throw _e=null,s}),_e}function kt(s){if(L){dt(s);return}K.push(s),wt().catch(()=>{})}var at=Object.freeze({bytes:null,etag:null,seq:null}),xt=()=>({msg:"Not in edit mode",msgType:"skipped",code:null,etag:null}),ut=["[editor-ui]",'[clay~="editor-ui"]',"[save-ignore]","[snapshot-remove]","[no-snapshot]","[no-save]","[save-remove]","[freeze] *","[save-freeze] *",'[clay~="no-save"]','[clay~="no-snapshot"]','[clay~="freeze"] *',Ce,Te].join(","),ft='[clay~="freeze"], [freeze], [save-freeze]';function V(s){for(let e of s.querySelectorAll(ft))e.replaceChildren();return z()&&He(s),s}function ht(s){if(s==null)return s;let e=typeof s=="string"?new DOMParser().parseFromString(s,"text/html"):s;return ne(e),V(e),e}var bt=[Ae,'[clay~="no-watch"]',"[no-watch]","[mutations-ignore]"].join(","),Dt=(s,e,t)=>be(s,e,t)||Le.test(e.toLowerCase()),pt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function It(s){let e=new Map,t=n=>{if(n.matches(ut))return;let r=pt(n);r&&e.set(r,(e.get(r)||0)+1);let l=n.localName==="template"&&n.content?n.content.children:n.children;for(let o of l)t(o)},i=s.nodeType===9?[s.documentElement]:s.nodeType===11?s.children:[s];for(let n of i)n&&n.nodeType===1&&t(n);return e}var Tt=s=>e=>{let t=pt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=It(i)),n.get(t)===1?t:null},ge=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function Lt(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Ct(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function At(){let{forComparison:s,forDirty:e}=Pe({flushUndo:!1});return[s,e]}var Ft=1024*1024;function Rt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Ft?JSON.stringify({[s.snapshotKey]:e,...r}):new Blob([`{${JSON.stringify(s.snapshotKey)}:`,JSON.stringify(e),`,${JSON.stringify(r).slice(1)}`],{type:"application/json"})}var me=class{constructor(){this.sse=null,this.currentFile=null,this.lastHtml=null,this._diskBase=null,this._diskBaseTicket=0,this._agreeSeq=0,this._saveTicket=0,this._peerBaseTicket=0,this._acceptedSaveTicket=0,this._morphTicket=0,this.clientId=this.generateClientId(),this.resumeId=null,this._savedSnapshot?.abort?.abort(),this._savedSnapshot=null,this._sendInFlight=!1,this._queuedSend=null,this._profile=null,this._profilePromise=null,this._sharedData=!1,this._sharedSync=!1,this._liveData=!1,this._editing=null,this._presenceLease=null,this._presenceQuiesced=!1,this._ready=null,this._startGen=0,this.isPaused=!1,this.isDestroyed=!1,this.debug=!1,this._lane=$?"live":"saved",this._laneChosen=!1,this._snapshotHandler=null,this.lastSeenSeq=0,this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingEtag=null,this._pendingBy=null,this._morphInFlight=!1,this._rafHandle=null,this._represented=at,this._handoff=null,this._handoffHeld=!1,this._pendingExternal=null,this._lastExternalSeq=0,this._saveEpoch=0,this._saveSavedHandler=null,this._saveConflictHandler=null,this._settledHandler=null,this._lastIdentityMap=null,this._applyGen=0,this._holdRetryPeer=null,this._holdRetryExt=null,this._servedFetchId=0,this._startupRetry=null,this._engineRetry=null,this._heldLive=!1,this._heldExt=!1,this.identity=tt(this.clientId),this.onConnect=null,this.onDisconnect=null,this.onUpdate=null,this.onError=null,this.onNotification=null}get unresolvedConflicts(){return I.list().filter(e=>e.kind!=="apply-incomplete")}_log(e,t=null){if(!this.debug)return;let i=`[LiveSync ${new Date().toISOString()}]`;t!==null?console.log(i,e,t):console.log(i,e)}generateClientId(){return Math.random().toString(36).slice(2,11)+Date.now().toString(36)}generateResumeId(){try{let e=new Uint8Array(16);return(globalThis.crypto||window.crypto).getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}catch{return Math.random().toString(36).slice(2)+Date.now().toString(36)}}_seedBases(){if(x())return;let e=P({flushUndo:!1});this._setPeerBase(T(e),this.identity.exportMap(e,D),this._ticket()),this._setDiskBase(W({emitForSync:!1}).forSave,this._ticket())}get lane(){return this._lane}set lane(e){this._lane=e,this._laneChosen=!0}start(e=null,{lane:t,represented:i}={}){if(this.isDestroyed=!1,(this.sse||this._snapshotHandler)&&this.cleanup(),this.currentFile=e||this.detectCurrentFile(),!this.currentFile){console.warn("[LiveSync] No file detected");return}let n=ee().mode==="edit"?"live":"saved",r=this.lane==="live";this._lane=t||(this._laneChosen?this._lane:n),this.lastHtml=null,this._lastIdentityMap=null,this._peerBaseTicket=this._ticket(),this._diskBase=null,this._diskBaseTicket=this._ticket(),this._saveTicket=0,this._savedSnapshot?.abort?.abort(),this._savedSnapshot=null,this._applyGen++,this.lastSeenSeq=0,this._lastExternalSeq=0,this._represented=i?Object.freeze({bytes:i.bytes??null,etag:i.etag??null,seq:i.seq??null}):at,this._acquireEmptySaved=r&&this.lane==="saved"&&this._represented.bytes===null,this._pendingExternal=null,this.resumeId=this.generateResumeId(),this.lane==="live"&&this._seedBases(),this.lane==="live"&&J().catch(()=>{}),console.log(`[LiveSync] Starting for: ${this.currentFile} (lane=${this.lane})`);let l=++this._startGen;if(this.lane==="live"&&!(y&&y.baselineSettled())){let o=this._applyGen,a=this._morphTicket,h=this._saveEpoch,c=this.lastHtml,d=this._diskBaseTicket,_=this._diskBase!==null;this._settledHandler=()=>{if(this._settledHandler=null,!(this.isDestroyed||this._startGen!==l)&&!qe()&&!x()&&this._saveTicket===0&&this._morphTicket===a){if(c!==null&&this._applyGen===o&&this._saveEpoch===h&&this.lastHtml===c){let g=P({flushUndo:!1});this._setPeerBase(T(g),this.identity.exportMap(g,D),this._ticket())}_&&this._diskBaseTicket===d&&this._setDiskBase(W({emitForSync:!1}).forSave,this._ticket())}},document.addEventListener("clay:baseline-settled",this._settledHandler,{once:!0})}this._ready=Promise.all([this.lane==="live"?H():null,this._resolveProfile()]).then(()=>{this.isDestroyed||this._startGen!==l||this.connect()}),this.lane==="live"&&(this.listenForSnapshots(),Et().then(o=>this._startPresence(o,l),()=>{}),this._saveSavedHandler=o=>{this._saveEpoch++;let a=this._saveTicket||this._ticket();this._saveTicket=0,a>this._acceptedSaveTicket&&(this._acceptedSaveTicket=a);let h=y?y.getLastSavedBytes():null;h!=null&&this._setDiskBase(h,a),this._relayCommit(o?.detail?.captureId,h)},document.addEventListener("clay:save-saved",this._saveSavedHandler),this._saveConflictHandler=o=>{let a=o.detail&&o.detail.etag;a&&queueMicrotask(()=>{this.isDestroyed||a===ie()&&(y?.conflictResolvedBySync(a),this._saveAfterMerge(x(),!1))})},document.addEventListener("clay:save-conflict",this._saveConflictHandler))}cleanup(){if(this.sse&&(this.sse.close(),this.sse=null),he(),K=[],L&&(L.presence.clear(),L.editingMarker.clear()),this._editing&&(this._editing.stop(),this._editing=null),this._presenceLease){let e=this._presenceLease;this._presenceLease=null,typeof e.stop=="function"?e.stop():e.detach()}this._lastRoster=null,this._snapshotHandler&&(document.removeEventListener("clay:snapshot-ready",this._snapshotHandler),this._snapshotHandler=null),this._saveSavedHandler&&(document.removeEventListener("clay:save-saved",this._saveSavedHandler),this._saveSavedHandler=null),this._saveConflictHandler&&(document.removeEventListener("clay:save-conflict",this._saveConflictHandler),this._saveConflictHandler=null),this._settledHandler&&(document.removeEventListener("clay:baseline-settled",this._settledHandler),this._settledHandler=null),this._queuedSend=null,this._rafHandle!=null&&(this._cancelFrame(this._rafHandle),this._rafHandle=null),this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingBy=null,this._pendingExternal=null,this._handoff=null,this._handoffHeld=!1,clearTimeout(this._holdRetryPeer),clearTimeout(this._holdRetryExt),this._holdRetryPeer=null,this._holdRetryExt=null,clearTimeout(this._startupRetry),this._startupRetry=null,clearTimeout(this._engineRetry),this._engineRetry=null,this._servedFetchId++}detectCurrentFile(){let e=window.location.pathname;if(e==="/")return"index.html";e=e.replace(/^\//,"");let t=e.match(/^(.*?\.html(?:clay)?)/);return t?t[1]:e}_resolveProfile(){return this._profilePromise||(this._profilePromise=et().then(e=>(this._sharedData=e.sharedData,this._sharedSync=e.sharedSync,this._liveData=e.liveData,this._profile=e.profile,this._log(`Wire profile: ${e.profile.name}`),e.profile))),this._profilePromise}_setHeld(e,t,i){let n=e==="live"?"_heldLive":"_heldExt";this[n]!==t&&(this[n]=t,!t&&!this._heldLive&&!this._heldExt&&Ue({fresh:!0,clearIfMissing:!1}),document.dispatchEvent(new CustomEvent(t?"clay:sync-held":"clay:sync-resumed",{detail:{lane:e,el:i||null}})))}_applyEtagFrame(e){return typeof e.etag!="string"||typeof e.html=="string"?!1:(this._log("Dropping a stamp that arrived with no document: nothing proves this tab holds those bytes"),!0)}connect(){if(this.isDestroyed)return;let t=(this._profile||ue.legacy).streamPath(window.location.href,this.lane,this.resumeId,this.clientId);this.sse=new Xe(new URL(t,window.location.origin).href,{shared:this._sharedSync,sharedData:this._sharedData,documentURL:window.location.href,lane:this.lane,clientId:this.clientId,keepAliveWhenHidden:this._liveData&&this.lane==="live",startupCheck:!!Ie}),this._acquireEmptySaved&&(this._acquireEmptySaved=!1,this._fetchServedDocument(void 0,{repair:!0})),this.sse.onopen=()=>{console.log("[LiveSync] Connected"),this._editing&&this._editing.reconnected(),ye&&ye.reconnect(),this.onConnect&&this.onConnect()},this.sse.addEventListener("open",()=>Qe({clientId:this.clientId,lane:this.lane})),this.sse.addEventListener("error",()=>he());for(let i of Ke)this.sse.addEventListener(i,n=>{let r;try{r=JSON.parse(n.data)}catch{return}Ze(i,r)});this.sse.addEventListener("cursor",i=>{let n;try{n=JSON.parse(i.data)}catch{return}if(!n||n.resync!==!0&&n.startup!==!0)return;let r=n.resync===!0,l=n.startup===!0&&!r;console.log(r?"[LiveSync] Server could not replay everything; refetching the document":"[LiveSync] Checking the served document against the version this tab was served"),this._fetchServedDocument(typeof n.seq=="number"?n.seq:void 0,{repair:r,startup:l})}),this.sse.addEventListener("presence",i=>{let n;try{n=JSON.parse(i.data)}catch{return}kt(n),this._lastRoster=n,this._editing&&this._editing.roster(n)}),this.sse.onmessage=i=>{let n=JSON.parse(i.data),{seq:r}=n;if(typeof r=="number"&&r<=this.lastSeenSeq){this._log(`Dropping stale message: seq=${r}, lastSeen=${this.lastSeenSeq}`);return}if(typeof r=="number"&&(this.lastSeenSeq=r),n.type==="notification"){if(this._maybeAcceptExternalChange(n))return;this.handleNotification(n);return}if(n.error){console.error("[LiveSync] Server error:",n.error),this.onError&&this.onError(new Error(n.error));return}if(this._applyEtagFrame(n))return;let{html:l,sender:o,identityMap:a}=n;if(o===this.clientId){this._log("Ignoring own message (sender matches clientId)");return}if(typeof l!="string"){console.error("[LiveSync] Received invalid html, ignoring");return}let h=typeof n.etag=="string"&&n.etag?n.etag:null;if(this.lane==="live"&&!h&&Ge()){this._log(`Dropping an unstamped live frame on a stamping host (seq=${r})`);return}if(this.lane==="saved"&&l===this._represented.bytes){this._represented=Object.freeze({bytes:l,etag:h||null,seq:r??null}),M(h);return}if(h&&l===this.lastHtml){this._log(`Taking the stamp from a peer save of content already applied (seq=${r})`),M(h),y&&y.isSaveConflicted()&&(y.conflictResolvedBySync(h),this._saveAfterMerge(x(),!1));return}this._log(`Received update from: ${o} (my clientId: ${this.clientId}, seq=${r})`),this.applyUpdate(l,r,a,h,n.by),this.onUpdate&&this.onUpdate({html:l,sender:o,seq:r,identityMap:a,etag:h})},this.sse.onerror=()=>{this.sse.readyState===EventSource.CONNECTING?console.log("[LiveSync] Reconnecting..."):this.sse.readyState===EventSource.CLOSED&&(console.log("[LiveSync] Connection closed"),this.onError&&this.onError(new Error("Connection closed"))),this.onDisconnect&&this.onDisconnect()}}listenForSnapshots(){this._snapshotHandler=e=>{if(!e.detail||e.detail.forSave!==!0)return;this._saveTicket=this._ticket();let{documentElement:t}=e.detail;if(!t)return;this._log("snapshot-ready received, preparing to send");let i=this.identity.exportMap(t,D);this._savedSnapshot?.abort?.abort();let n={html:null,steps:null,copy:null,abort:null,identityMap:i,ticket:this._saveTicket,captureId:e.detail.captureId??null};if(e.detail.sliced){n.copy=Be(t),n.abort=new AbortController;let{signal:r}=n.abort;Promise.all([import("./c-2KIEGNC4.js"),import("./c-ZWBI4HYK.js")]).then(([{serializeForSyncSteps:l},{runSliced:o}])=>{if(r.aborted||typeof n.html=="string")return;let a=(function*(){let h=yield*l(n.copy);n.html=h,n.steps=null})();return n.steps=a,o(a,{signal:r})}).catch(()=>{})}else n.html=T(t);this._savedSnapshot=n},document.addEventListener("clay:snapshot-ready",this._snapshotHandler)}_enqueueSend(e,t,i=null){if(!this._profile){this._queuedSend={html:e,identityMap:t,etag:i},this._resolveProfile().then(()=>this._flushQueuedSend());return}if(this._sendInFlight){this._queuedSend={html:e,identityMap:t,etag:i};return}this._postUpdate(e,t,i)}_flushQueuedSend(){if(this.isDestroyed||this._sendInFlight)return;let e=this._queuedSend;e&&(this._queuedSend=null,this._postUpdate(e.html,e.identityMap,e.etag))}_relayCommit(e=null,t=null){if(this.isDestroyed)return;let i=ie(),n=this._savedSnapshot;if(n&&(n.captureId??null)!==(e??null)){this._log("Skipping send - snapshot belongs to a different capture");return}let r=n;if(this._savedSnapshot=null,r?.copy&&typeof r.html!="string")if(r.abort?.abort(),r.steps)for(let c=r.steps.next();!c.done;c=r.steps.next());else r.html=T(r.copy);if(!r||typeof r.html!="string")return;let l=r;if(typeof t=="string"){try{l=st(r,t,this.identity)}catch(c){this._log(`Skipping send - page relay failed: ${c&&c.message}`);return}if(!l){this._log("Skipping send - accepted capture has no page article");return}}let o=Ht(e)??t,a=typeof o=="string"?je(o):0;l={...l,html:qt(ze(l.html,Math.max(We(),a)),o)};let h=!i&&l.html===this.lastHtml;if(this._setPeerBase(l.html,l.identityMap,l.ticket),h){this._log("Skipping send - HTML unchanged");return}this._enqueueSend(l.html,l.identityMap,i||null)}_postUpdate(e,t,i=null,n=0){this._log(`Sending update (HTML length: ${e.length})`),this._sendInFlight=!0;let r=!1,l=this._profile||ue.legacy;fetch(new URL(l.relayPath,window.location.origin).href,{method:"POST",headers:{"Content-Type":"application/json",[l.documentHeader]:window.location.href,[$e]:String(1)},body:Rt(l,e,this.clientId,t,i)}).then(o=>{o.ok||(console.warn("[LiveSync] Save returned status:",o.status),r=o.status>=500||o.status===408||o.status===429)}).catch(o=>{console.error("[LiveSync] Save failed:",o),this.onError&&this.onError(o),r=!0}).finally(()=>{this._sendInFlight=!1;let o=this._queuedSend;if(this._queuedSend=null,o){this._postUpdate(o.html,o.identityMap,o.etag);return}!r||!i||n>=3||this.isDestroyed||(this._sendInFlight=!0,setTimeout(()=>{if(this._sendInFlight=!1,this.isDestroyed)return;let a=this._queuedSend;this._queuedSend=null,a?this._postUpdate(a.html,a.identityMap,a.etag):this._postUpdate(e,t,i,n+1)},500*2**n))})}_startPresence(e,t){return this.isDestroyed||this._startGen!==t||this._presenceLease?null:e.connect({send:i=>this._postPresence(i)}).then(i=>this.isDestroyed||this._startGen!==t?(typeof i?.stop=="function"?i.stop():i?.detach(),null):(this._presenceLease=i||null,Oe("presence-editing")),()=>!1).then(i=>{if(!(!i||this.isDestroyed||this._startGen!==t||this._editing))return H().then(n=>{this.isDestroyed||this._startGen!==t||this._editing||(this._editing=new n.EditingSender({}),this._presenceQuiesced?this._editing.stop():(this._editing.start(),this._editing.roster(this._lastRoster)))})})}_postPresence(e){let t=new URL("/_/presence",window.location.origin);return t.searchParams.set("client-id",this.clientId),fetch(t.href,{method:"POST",headers:{"Content-Type":"application/json","Document-URL":window.location.href},body:JSON.stringify(e)}).then(i=>i.ok,()=>!1)}_maybeAcceptExternalChange(e){if(this.lane!=="live")return!1;let t=e.data;return t&&t.kind==="external-change"?(typeof t.html=="string"?this._enqueueExternal(t.html,e.seq,t.etag,t.by):this._fetchExternalChange(e.seq),!0):typeof e.msg=="string"&&e.msg.endsWith("changed on disk outside this tab")?(this._fetchExternalChange(e.seq),!0):!1}_enqueueExternal(e,t,i,n){if(typeof t=="number"){if(t<=this._lastExternalSeq){this._log(`Dropping replayed external change: seq=${t}`);return}this._lastExternalSeq=t}this._pendingExternal={html:e,seq:t,saveEpoch:this._saveEpoch,etag:typeof i=="string"&&i?i:null,by:n??null},this._scheduleNextFrame()}_fetchExternalChange(e){if(typeof e=="number"){if(e<=this._lastExternalSeq)return;this._lastExternalSeq=e}this._fetchServedDocument(e)}_fetchServedDocument(e,{attempt:t=0,repair:i=!1,startup:n=!1}={}){if(n&&(this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null)){this._retryStartup(t);return}let r=this._saveEpoch,l=this._startGen,o=this.lastSeenSeq,a=this._applyGen,h=++this._servedFetchId;i&&typeof e!="number"&&(e=this._lastExternalSeq),fetch(new URL(window.location.href),{cache:"no-store"}).then(c=>c.ok?c.text():null).then(c=>{if(this.isDestroyed||c==null||this._startGen!==l)return;let d=Lt(c),_=n||i&&!!d;if(_){if(h!==this._servedFetchId){i&&this._retryStartup(t+1,{repair:i,startup:n},typeof e=="number"?Math.max(e,this._lastExternalSeq):e);return}if(r!==this._saveEpoch||o!==this.lastSeenSeq||a!==this._applyGen||this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null){this._retryStartup(t+1,{repair:i,startup:n},e);return}if(d){if(d===se()){(i||n)&&this.lane==="saved"&&(this._represented=Object.freeze({bytes:c,etag:d,seq:e??null}));return}}else if(!i)return}else if(typeof e=="number"&&e<this._lastExternalSeq){i&&t<3&&this._fetchServedDocument(this._lastExternalSeq,{attempt:t+1,repair:i,startup:n});return}else if(this._saveEpoch>r){t<3&&(console.log("[LiveSync] Refetching external change: own save landed mid-fetch"),this._fetchServedDocument(e,{attempt:t+1,repair:i,startup:n}));return}this._pendingExternal={html:c,seq:e,saveEpoch:r,etag:d,by:null,fetchOptions:{repair:i,startup:n,attempt:t,versionCheck:_},startGen:l,seenSeq:o,applyGen:a,fetchId:h},this._scheduleNextFrame()}).catch(c=>{this._log("External-change fetch failed",c),typeof e=="number"&&this._lastExternalSeq===e&&(this._lastExternalSeq=e-1)})}_retryStartup(e=0,t={startup:!0},i){this.isDestroyed||e>3||(clearTimeout(this._startupRetry),this._startupRetry=setTimeout(()=>{if(this._startupRetry=null,!this.isDestroyed){if(this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null){this._retryStartup(e,t,i);return}this._fetchServedDocument(i,{...t,attempt:e})}},16))}applyUpdate(e,t,i,n,r){this.isDestroyed||(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingEtag=n??null,this._pendingBy=r??null,this._scheduleNextFrame())}prepareHandoff(e={}){return this._handoff?Promise.resolve(this._handoff):this.isDestroyed?Promise.reject(new Error("LiveSync: stopped")):(this._handoffHeld=!0,this._rafHandle!=null&&(this._cancelFrame(this._rafHandle),this._rafHandle=null),import("./c-I4MQHOEY.js").then(({engineHandoff:t})=>t(this,e)).then(t=>this._handoff=t))}_scheduleNextFrame(){this.isDestroyed||this._handoffHeld||this._rafHandle==null&&(this._morphInFlight||(this._rafHandle=this._requestFrame(()=>this._runPending())))}async _runPending(){if(this._rafHandle=null,this.isDestroyed)return;if(!R()){this._morphInFlight=!0;try{await Y()}catch(r){this._log("Merge engine failed to load",r),this._engineRetry=setTimeout(()=>this._scheduleNextFrame(),2e3);return}finally{this._morphInFlight=!1}if(this.isDestroyed)return}let e=this._pendingExternal,t=e?.fetchOptions||null,i=!!(t?.startup||t?.versionCheck),n=!1;if(e!=null&&(i&&this._pendingHtml!=null?n=!1:this._pendingHtml==null?n=!0:n=!(typeof e.seq=="number"&&typeof this._pendingSeq=="number"&&this._pendingSeq<e.seq)),n)if(this._pendingExternal=null,typeof e.seq=="number"&&e.seq<this._lastExternalSeq)i&&t?.repair?this._retryStartup((t.attempt||0)+1,t,this._lastExternalSeq):this._log("Dropping superseded external change at drain");else if(i&&e.startGen!==this._startGen)this._log("Dropping superseded startup check at drain");else if(i&&e.fetchId!==this._servedFetchId)t?.repair?this._retryStartup((t.attempt||0)+1,t,this._lastExternalSeq):this._log("Dropping superseded startup check at drain");else if(i&&(e.saveEpoch!==this._saveEpoch||e.seenSeq!==this.lastSeenSeq||e.applyGen!==this._applyGen))this._retryStartup((t.attempt||0)+1,t,e.seq);else if(i&&e.etag!=null&&e.etag===se())this._log("Startup check found the same version: nothing to apply");else if(!i&&e.saveEpoch!==this._saveEpoch)console.log("[LiveSync] Refetching external change: own save landed after queue"),this._fetchServedDocument(e.seq,t||{});else{this._morphInFlight=!0;try{await this._doApplyExternal(e.html,e.seq,e.etag,e.by,t)}catch(r){console.error("[LiveSync] applyExternal failed:",r)}finally{this._morphInFlight=!1}}else{let r=this._pendingHtml,l=this._pendingSeq,o=this._pendingIdentityMap,a=this._pendingEtag,h=this._pendingBy;if(this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingEtag=null,this._pendingBy=null,r==null)return;this._morphInFlight=!0;try{await this._doApplyUpdate(r,l,o,a,h)}catch(c){console.error("[LiveSync] applyUpdate failed:",c)}finally{this._morphInFlight=!1}}!this.isDestroyed&&(this._pendingHtml!=null||this._pendingExternal!=null)&&this._scheduleNextFrame()}_ticket(){return++this._agreeSeq}_setDiskBase(e,t){t<=this._diskBaseTicket||(this._diskBase=e,this._diskBaseTicket=t)}_setPeerBase(e,t,i){return i<this._peerBaseTicket?!1:(this._peerBaseTicket=i,this.lastHtml=e,this._lastIdentityMap=t&&typeof t=="object"&&!Array.isArray(t)?t:null,!0)}_requestFrame(e){return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(e):setTimeout(e,16)}_cancelFrame(e){if(typeof window<"u"&&typeof window.cancelAnimationFrame=="function"){window.cancelAnimationFrame(e);return}clearTimeout(e)}async _mergeIncoming(e,t,{base:i,baseIdentityMap:n=null,captureLocal:r,synthetic:l,source:o="peer",seq:a=null,etag:h=null,extra:c={}}){R()||await Y();let{beginApply:d,completeApply:_,failApply:g,beginLineageCapture:E}=ot()||await J(),f,u=p=>{f=E(I.list());try{let v=R().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),v}catch(v){throw f.invalidate(I.list()),f.finish(I.list()),v}},S=this.identity,w=De,b=Tt(new WeakMap),N=p=>ge(p)?{first:b,map:p,then:b}:b,O=l?p=>b(p)||S.idOf(D(p)||p)||null:b,C=e,Se=new Map;if(ge(t)){C=new DOMParser().parseFromString(e,"text/html"),ne(C);let p=R().HyperMorph.importMap(C.documentElement,t);for(let v of C.querySelectorAll("[data-id], [id]")){let k=b(v),xe=k&&p.get(v);xe&&Se.set(k,xe)}}C=ht(C);let Q={live:document,remote:C,ignore:p=>p.matches(ut),opaque:p=>p.matches(ft)||z()&&Re(p),remoteWins:p=>p.matches(bt),ignoreAttribute:(p,v,k)=>Dt(p,v,k)||z()&&Fe(k||p,v),attributeMerge:rt,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:R().mergeTagRecognizers},hooks:{beforeAttributeUpdated:w},...c},Ee=this.lane==="live"&&x(),we=ae(),G,Z=null,F=null;if(i==null)G=u({...Q,base:null,local:{root:V(r()),toLive:D},identity:{local:O,remote:N(t)}});else if(Ee){let p=r(),v=p.cloneNode(!0);Z=V(p),F=d({source:o,seq:a,etag:h,root:Z,recoveryRoot:v,domain:o==="disk"?"save":"sync"});try{G=u({...Q,base:ht(i),local:{root:Z,toLive:D},identity:{base:N(n),local:O,remote:N(t)}})}catch(k){throw g(F,k),k}}else{let p=V(r()),v=p.ownerDocument;v.documentElement!==p&&v.replaceChild(p,v.documentElement),G=u({...Q,base:v,local:{root:p,toLive:D},fastPath:!0,identity:{base:O,local:O,remote:N(t)}})}let U=this._ticket();this._morphTicket=U;let A;try{A=await G}catch(p){f.invalidate(I.list());try{F&&g(F,p,{ticket:U})}finally{f.finish(I.list())}throw p}let _t=ae().gen!==we.gen,ke;try{f.prepareComplete(A,I.list()),ke=F?_(F,A.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&A.localDiverged?Ye():Ee&&!A.localDiverged&&Je(we);let gt=new Set(ge(t)?Object.values(t):[]);for(let[p,v]of A.identities){let k=gt.has(v)?v:Se.get(v);k&&S.adopt(p,k)}return{report:A,ticket:U,typedDuringWait:_t,conflictIds:ke}}_saveAfterMerge(e,t){(e||t)&&Ve()&&(y?y.savePageThrottled():xt())}async _doApplyUpdate(e,t,i,n,r=null){if(ce(e)){await de();return}this.lane==="live"&&!y&&await H(),this._log("applyUpdate - pausing mutations and morphing"),this.isPaused=!0;let l=window.scrollX,o=window.scrollY;q.pause(),le();let a=!1,h=!1,c=!1;try{if(this.lane==="live"&&x()&&this.lastHtml===null){console.log("[LiveSync] Holding incoming update: unsaved local edits and no baseline to merge against"),this._setHeld("live",!0,null);let f=this._saveEpoch,u=this.lastSeenSeq;clearTimeout(this._holdRetryPeer),this._holdRetryPeer=setTimeout(()=>{this._holdRetryPeer=null,!(this.isDestroyed||this._pendingHtml!=null)&&this._saveEpoch===f&&this.lastSeenSeq===u&&(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingBy=r,this._scheduleNextFrame())},3e3);return}this._setHeld("live",!1);let{report:d,ticket:_,typedDuringWait:g,conflictIds:E}=await this._mergeIncoming(e,i,{base:this.lastHtml,baseIdentityMap:this._lastIdentityMap,captureLocal:()=>P({flushUndo:!1}),synthetic:!0,source:"peer",seq:t,etag:n});if(a=d.localDiverged,h=g,te(),window.scrollTo(l,o),this._setPeerBase(e,i,_),this._applyGen++,this._acceptedSaveTicket>_||(typeof n=="string"&&n?(M(n),c=!0):re()),this.lane==="live"&&!a&&!x()){let{forSave:f,forComparison:u,forDirty:S}=W({emitForSync:!1,flushUndo:!1});y.setLastSavedBaselines(u,S),this._setDiskBase(f,this._ticket())}this.lane==="saved"&&(this._represented=Object.freeze({bytes:e,etag:n||null,seq:t??null})),document.dispatchEvent(new CustomEvent("clay:sync-applied",{detail:{seq:t,source:this.lane==="saved"?"disk":"peer",lane:this.lane,by:r||null,html:e,report:d,unresolved:this.unresolvedConflicts,conflictIds:E}}))}finally{this._log("applyUpdate - morph complete, resuming mutations"),q.resume(),oe(),await new Promise(d=>setTimeout(d,0)),this.isPaused=!1}c&&y?.conflictResolvedBySync(n),this._saveAfterMerge(a,h)}async _doApplyExternal(e,t,i=null,n=null,r=null){if(ce(e)){await de();return}this.lane==="live"&&!y&&await H();let l=this._diskBase;this._log(`applyExternal - external disk change (seq=${t})`),this.isPaused=!0;let o=window.scrollX,a=window.scrollY;q.pause(),le();let h=!1,c=!1,d=!1;try{if(this.lane==="live"&&x()&&this._diskBase===null){if(console.log("[LiveSync] Holding external change: unsaved local edits and no baseline to merge against"),this._setHeld("external",!0,null),r?.startup||r?.versionCheck){clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{if(this._holdRetryExt=null,this.isDestroyed)return;let S=typeof t=="number"?Math.max(t,this._lastExternalSeq):t;this._retryStartup(0,r,S)},3e3);return}let u=this._saveEpoch;clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{this._holdRetryExt=null,!(this.isDestroyed||this._pendingExternal!=null)&&(this._pendingExternal={html:e,seq:t,saveEpoch:u,etag:i,by:n},this._scheduleNextFrame())},3e3);return}this._setHeld("external",!1);let{report:_,ticket:g,typedDuringWait:E,conflictIds:f}=await this._mergeIncoming(e,null,{base:this._diskBase,captureLocal:()=>Me().saveClone,synthetic:!1,source:"disk",seq:t,etag:i,extra:{beforeApply:u=>Ct(u.documentElement,this.lane)}});if(h=_.localDiverged,c=E,te(),this._setDiskBase(e,g),window.scrollTo(o,a),this._acceptedSaveTicket>g||(typeof i=="string"&&i?(M(i),d=!0):re()),this.lane==="live"&&!h&&!x()){y.setLastSavedBaselines(...At()),y.setUnsavedChanges(!1);let u=P({flushUndo:!1});this._setPeerBase(T(u),this.identity.exportMap(u,D),g),this._applyGen++}this.lane==="saved"&&(this._represented=Object.freeze({bytes:e,etag:i||null,seq:t??null})),document.dispatchEvent(new CustomEvent("clay:sync-applied",{detail:{seq:t,source:"disk",etag:typeof i=="string"&&i?i:null,by:n||null,html:e,report:_,conflictIds:f,unresolved:this.unresolvedConflicts}}))}finally{this._log("applyExternal - morph complete, resuming mutations"),q.resume(),oe(),await new Promise(_=>setTimeout(_,0)),this.isPaused=!1}d&&y?.conflictResolvedBySync(i),this._saveAfterMerge(h,c),l!=null&&j(l)===j(e)&&y&&y.schedulePaintHeal(()=>this._diskBase==null?null:j(this._diskBase))}handleNotification({msgType:e,msg:t,action:i,persistent:n,data:r}){this._log(`Notification received: ${e} - ${t}`),e==="data-loss"||(n&&window.toastPersistent?window.toastPersistent(t,e):window.toast?window.toast(t,e):console.log(`[LiveSync] Notification: ${t}`)),document.dispatchEvent(new CustomEvent("clay:notification",{detail:{msgType:e,msg:t,action:i,persistent:n,data:r}})),this.onNotification&&this.onNotification({msgType:e,msg:t,action:i,persistent:n,data:r})}stop(){this.cleanup(),this.isDestroyed=!0,console.log("[LiveSync] Stopped")}editParticipant(){return H().then(e=>e.syncParticipant(this))}},X=null;Ne((s,e)=>{X=typeof s=="string"?{html:s,captureId:e?.captureId??null}:null});var Ht=s=>X&&(X.captureId??null)===(s??null)?X.html:null;function qt(s,e){if(typeof e!="string"||e===s)return s;let t=i=>new DOMParser().parseFromString(i,"text/html").documentElement;return t(s).isEqualNode(t(e))?e:s}var ve=new me;typeof window<"u"&&!ct&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>ve.start()):ve.start());var _n=(s,e,t)=>Y().then(({morph:i})=>i(s,e,t));var gn=ve;export{I as a,ut as b,bt as c,me as d,ve as e,_n as f,gn as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{F as x,c as b,q as f,s as p,u as h,v as k}from"./c-
|
|
1
|
+
import{F as x,c as b,q as f,s as p,u as h,v as k}from"./c-ZKNBMNN3.js";import"./c-4ASQPRQL.js";import"./c-GQ6F6IDK.js";import{b as c,d as S}from"./c-I2SCCUEW.js";import"./c-5VYOWDTI.js";import"./c-FWKHM4E7.js";import"./c-5JLFROUB.js";import"./c-WYFDLITL.js";import"./c-UGHH4MB3.js";import"./c-ZWIOJGMT.js";import{l as s,o as D,p as y,q as E}from"./c-B7J4K2AE.js";import"./c-ATKAOH23.js";import"./c-EK63G3CG.js";import"./c-NQJRVJ56.js";import"./c-XGH4GS2T.js";import"./c-IJUK2GPW.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-7MG5RU63.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-DCFSEJZG.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var A=15e3,M=Symbol("the barrier deadline passed"),I=2,e=(i,r={})=>({ok:!1,code:i,...r});async function O(i,r){let u=null,l=new Promise(a=>{u=setTimeout(()=>a(M),Math.max(0,r-Date.now()))});try{return await Promise.race([Promise.resolve(i),l])}finally{clearTimeout(u)}}async function _({generation:i=p(),keepalive:r=!1,timeoutMs:u=A,operation:l=null}={}){let a=l?null:D("mode");if(!l&&!a)return e("busy");let n=Date.now()+u,d=h(i),m=new AbortController;try{for(let g=0;;g++){if(i!==p())return e("stale-document");if(Date.now()>=n)return e("timeout");let P={permit:d,deadline:n,keepalive:r,signal:m.signal,timeoutMs:Math.max(0,n-Date.now())},t=await O(S(P),n);if(t===M)return e("timeout",{pending:c()});if(!t.ok)return f()?e("conflict",{pending:t.pending}):s()?e("save-unknown",{pending:t.pending}):e("pending-input",{pending:t.pending});if(t.pending.length)return e("pending-input",{pending:t.pending});if(f())return e("conflict");if(s())return e("save-unknown");let o;try{o=await x({keepalive:r,timeoutMs:Math.max(0,n-Date.now()),permit:d})}catch(v){return v?.state==="conflict"?e("conflict"):v?.state==="blocked"?e("pending-input",{pending:c()}):s()?e("save-unknown"):Date.now()>=n?e("timeout"):e("save-failed")}if(o.state!=="clean"&&o.state!=="saved")return e("save-failed");if(f())return e("conflict");if(s())return e("save-unknown");let w=c();if(w.length)return e("pending-input",{pending:w});if(b()){if(g+1<I&&Date.now()<n)continue;return e("pending-input")}return{ok:!0,state:o.state,etag:o.etag??null}}}finally{m.abort(),k(d),a&&y(a)}}export{D as claimOperation,E as operationKind,y as releaseOperation,_ as runSaveBarrier};
|