efficient-office 0.3.0 → 0.4.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.
@@ -1 +0,0 @@
1
- import{DocumentsConflict as e,useDocumentsHost as t,useDocumentsWords as n}from"./chunk-SL77RQ7W.js";import{useEffect as r,useRef as o,useState as a}from"react";import{WindowTitle as s,useWindowDirty as i}from"efficient-shell";import{Button as l,EmptyState as c,Input as d,LoadingSpinner as u,confirmDestructive as p,toast as f}from"efficient-shell/ui";var m={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function h(e){return e.includes("&")?e.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g,(e,t)=>{if("#"!==t[0])return m[t]??e;const n="x"===t[1]?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return n<=1114111?String.fromCodePoint(n):e}):e}function w(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f￾￿]/g,"")}var g=/([^\s=]+)\s*=\s*("([^"]*)"|'([^']*)')/g;function b(e){const t=[];let n=null,r=0;for(;r<e.length;){const o=e.indexOf("<",r);if(o<0)break;if(o>r&&t.length&&(t[t.length-1].text+=h(e.slice(r,o))),e.startsWith("\x3c!--",o)){r=y(e,"--\x3e",o);continue}if(e.startsWith("<?",o)){r=y(e,"?>",o);continue}if(e.startsWith("<![CDATA[",o)){const n=y(e,"]]>",o);t.length&&(t[t.length-1].text+=e.slice(o+9,n-3)),r=n;continue}if(e.startsWith("<!",o)){r=y(e,">",o);continue}const a=v(e,o);if("/"===e[o+1]){const n=t.pop();if(!n||n.name!==e.slice(o+2,a).trim())throw new Error("Malformed XML");n.innerEnd=o,n.end=a+1,r=a+1;continue}const s="/"===e[a-1],i=e.slice(o+1,s?a-1:a),l=i.search(/\s/),c={name:l<0?i:i.slice(0,l),attrs:{},children:[],text:"",start:o,end:a+1,innerStart:a+1,innerEnd:a+1};if(l>=0)for(const e of i.slice(l).matchAll(g))c.attrs[e[1]]=h(e[3]??e[4]??"");t.length?t[t.length-1].children.push(c):n||(n=c),s||t.push(c),r=a+1}if(!n||t.length)throw new Error("Malformed XML");return n}function y(e,t,n){const r=e.indexOf(t,n);if(r<0)throw new Error("Malformed XML");return r+t.length}function v(e,t){let n="";for(let r=t+1;r<e.length;r++){const t=e[r];if(n)t===n&&(n="");else if('"'===t||"'"===t)n=t;else if(">"===t)return r}throw new Error("Malformed XML")}var x=(e,t)=>e?.children.find(e=>e.name===t),$=(e,t)=>e?.children.filter(e=>e.name===t)??[];function k(e,t,n=[]){for(const r of e.children)t.has(r.name)&&n.push(r),k(r,t,n);return n}function C(e){if(!e)return;const t=e.attrs["w:val"];return!("0"===t||"false"===t||"off"===t||"none"===t)}var N='xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"',S="http://schemas.openxmlformats.org/officeDocument/2006/relationships",A={officeDocument:`${S}/officeDocument`,styles:`${S}/styles`,numbering:`${S}/numbering`,theme:`${S}/theme`,comments:`${S}/comments`,footnotes:`${S}/footnotes`,header:`${S}/header`,footer:`${S}/footer`,image:`${S}/image`,hyperlink:`${S}/hyperlink`},T=new TextEncoder,L=new TextDecoder,P=(e,t)=>{const n=e.get(t);return n?L.decode(n):void 0},M=(e,t,n)=>{e.set(t,T.encode(n))},E=e=>{const t=e.lastIndexOf("/");return`${e.slice(0,t+1)}_rels/${e.slice(t+1)}.rels`};function R(e,t){const n=P(e,E(t));return n?b(n).children.filter(e=>"Relationship"===e.name).map(e=>({id:e.attrs.Id,type:e.attrs.Type,target:e.attrs.Target,external:"External"===e.attrs.TargetMode})):[]}function j(e,t){if(t.startsWith("/"))return t.slice(1);const n=e.split("/").slice(0,-1);for(const e of t.split("/"))".."===e?n.pop():"."!==e&&n.push(e);return n.join("/")}function z(e,t,n,r,o=!1){const a=E(t),s=P(e,a),i=new Set(R(e,t).map(e=>e.id));let l=i.size+1;for(;i.has(`rId${l}`);)l++;const c=`rId${l}`,d=`<Relationship Id="${c}" Type="${n}" Target="${w(r)}"${o?' TargetMode="External"':""}/>`;return M(e,a,s?s.replace(/(<\/Relationships>\s*)$/,`${d}$1`).replace(/<Relationships([^>]*)\/>\s*$/,`<Relationships$1>${d}</Relationships>`):`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${d}</Relationships>`),c}function I(e,t,n){const r=P(e,"[Content_Types].xml")??"";r.includes(`PartName="/${t}"`)||M(e,"[Content_Types].xml",r.replace("</Types>",`<Override PartName="/${t}" ContentType="${n}"/></Types>`))}var U={a4:{width:11906,height:16838},letter:{width:12240,height:15840},legal:{width:12240,height:20160},a3:{width:16838,height:23811},a5:{width:8391,height:11906}},O={normal:{top:1440,right:1440,bottom:1440,left:1440},narrow:{top:720,right:720,bottom:720,left:720},moderate:{top:1440,right:1080,bottom:1440,left:1080},wide:{top:1440,right:2880,bottom:1440,left:2880}},D={...U.a4,...O.normal,header:708,footer:708};function B(e,t){const n=U[t];return e.width>e.height?{...e,width:n.height,height:n.width}:{...e,...n}}function F(e,t){return{...e,...O[t]}}function H(e){const t=Math.min(e.width,e.height),n=Math.max(e.width,e.height);for(const[e,r]of Object.entries(U))if(Math.abs(r.width-t)<30&&Math.abs(r.height-n)<30)return e;return null}function W(e){for(const[t,n]of Object.entries(O))if(n.top===e.top&&n.right===e.right&&n.bottom===e.bottom&&n.left===e.left)return t;return null}var q={yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",magenta:"#ff00ff",blue:"#0000ff",red:"#ff0000",darkBlue:"#000080",darkCyan:"#008080",darkGreen:"#008000",darkMagenta:"#800080",darkRed:"#800000",darkYellow:"#808000",darkGray:"#808080",lightGray:"#c0c0c0",black:"#000000",white:"#ffffff"};var K=e=>e&&/^[0-9a-fA-F]{6}$/.test(e)?`#${e.toLowerCase()}`:void 0;function V(e,t){const n={};if(!e)return n;const r=C(x(e,"w:b"));void 0!==r&&(n.b=r);const o=C(x(e,"w:i"));void 0!==o&&(n.i=o);const a=x(e,"w:u");a&&(n.u="none"!==a.attrs["w:val"]);const s=C(x(e,"w:strike"));void 0!==s&&(n.strike=s);const i=x(e,"w:vertAlign")?.attrs["w:val"];"subscript"===i&&(n.vert="sub"),"superscript"===i&&(n.vert="super");const l=function(e,t){if(!e)return;const n=e.attrs["w:ascii"]??e.attrs["w:hAnsi"];if(n)return n;const r=e.attrs["w:asciiTheme"]??e.attrs["w:hAnsiTheme"];return r?r.startsWith("major")?t.major:t.minor:e.attrs["w:eastAsia"]??e.attrs["w:cs"]}(x(e,"w:rFonts"),t);l&&(n.font=l);const c=Number(x(e,"w:sz")?.attrs["w:val"]);c&&(n.size=c/2);const d=K(x(e,"w:color")?.attrs["w:val"]);d&&(n.color=d);const u=x(e,"w:highlight")?.attrs["w:val"];if(u&&q[u])n.hl=q[u];else{const t=K(x(e,"w:shd")?.attrs["w:fill"]);t&&(n.hl=t)}return n}function G(e){const t={};if(!e)return t;const n=x(e,"w:jc")?.attrs["w:val"];"left"===n||"start"===n?t.align="left":"center"===n?t.align="center":"right"===n||"end"===n?t.align="right":"both"!==n&&"distribute"!==n||(t.align="justify");const r=x(e,"w:ind");if(r){const e=r.attrs["w:left"]??r.attrs["w:start"];void 0!==e&&(t.indentLeft=Number(e)/20),void 0!==r.attrs["w:firstLine"]&&(t.firstLine=Number(r.attrs["w:firstLine"])/20),void 0!==r.attrs["w:hanging"]&&(t.firstLine=-Number(r.attrs["w:hanging"])/20)}const o=x(e,"w:spacing");if(o){void 0!==o.attrs["w:before"]&&(t.before=Number(o.attrs["w:before"])/20),void 0!==o.attrs["w:after"]&&(t.after=Number(o.attrs["w:after"])/20);const e=Number(o.attrs["w:line"]);e&&("exact"===o.attrs["w:lineRule"]||"atLeast"===o.attrs["w:lineRule"]?t.linePoints=e/20:t.lineMultiple=e/240)}return t}var Q=e=>Math.round(100*e)/100;function _(e){const t=[];return e.align&&t.push(`text-align:${e.align}`),void 0!==e.indentLeft&&t.push(`margin-left:${Q(e.indentLeft)}pt`),void 0!==e.firstLine&&t.push(`text-indent:${Q(e.firstLine)}pt`),void 0!==e.before&&t.push(`margin-top:${Q(e.before)}pt`),void 0!==e.after&&t.push(`margin-bottom:${Q(e.after)}pt`),void 0!==e.lineMultiple&&t.push(`line-height:${Q(e.lineMultiple)}`),void 0!==e.linePoints&&t.push(`line-height:${Q(e.linePoints)}pt`),t.join(";")}function X(e){const t=[];void 0!==e.b&&t.push("font-weight:"+(e.b?700:400)),void 0!==e.i&&t.push("font-style:"+(e.i?"italic":"normal"));const n=[e.u&&"underline",e.strike&&"line-through"].filter(Boolean);return n.length&&t.push(`text-decoration-line:${n.join(" ")}`),e.font&&t.push(`font-family:${function(e){const t=e.replace(/["\\<>;]/g,"");return/mono|courier|consolas|menlo/i.test(t)?`"${t}",monospace`:/times|georgia|cambria|garamond|palatino|serif|song|ming/i.test(t)&&!/sans/i.test(t)?`"${t}",Caladea,serif`:`"${t}",Carlito,Arial,sans-serif`}(e.font)}`),e.size&&t.push(`font-size:${Q(e.size)}pt`),e.color&&t.push(`color:${e.color}`),e.hl&&t.push(`background-color:${e.hl}`),t.join(";")}var Y={Title:{name:"Title",xml:'<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:after="80" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:sz w:val="56"/><w:szCs w:val="56"/></w:rPr></w:style>'},Heading1:{name:"heading 1",xml:'<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="360" w:after="80"/><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:color w:val="0F4761"/><w:sz w:val="40"/><w:szCs w:val="40"/></w:rPr></w:style>'},Heading2:{name:"heading 2",xml:'<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="160" w:after="80"/><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:color w:val="0F4761"/><w:sz w:val="32"/><w:szCs w:val="32"/></w:rPr></w:style>'},Heading3:{name:"heading 3",xml:'<w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="160" w:after="80"/><w:outlineLvl w:val="2"/></w:pPr><w:rPr><w:color w:val="0F4761"/><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr></w:style>'},Quote:{name:"Quote",xml:'<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:before="160"/><w:jc w:val="center"/></w:pPr><w:rPr><w:i/><w:iCs/><w:color w:val="404040"/></w:rPr></w:style>'}},Z='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';function J(e){const t=new Map;M(t,"[Content_Types].xml",`${Z}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/></Types>`),M(t,"_rels/.rels",`${Z}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${A.officeDocument}" Target="word/document.xml"/></Relationships>`);const n=D;M(t,"word/document.xml",`${Z}<w:document ${N}><w:body><w:p/><w:sectPr><w:pgSz w:w="${n.width}" w:h="${n.height}"/><w:pgMar w:top="${n.top}" w:right="${n.right}" w:bottom="${n.bottom}" w:left="${n.left}" w:header="${n.header}" w:footer="${n.footer}" w:gutter="0"/></w:sectPr></w:body></w:document>`),M(t,"word/_rels/document.xml.rels",`${Z}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${A.styles}" Target="styles.xml"/><Relationship Id="rId2" Type="${S}/settings" Target="settings.xml"/></Relationships>`),M(t,"word/settings.xml",`${Z}<w:settings ${N}><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat></w:settings>`);const r=/^[A-Za-z]{2,3}(-[A-Za-z0-9]+)*$/.test(e)?e:"en-AU";return M(t,"word/styles.xml",`${Z}<w:styles ${N}><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Calibri" w:cs="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="${r}"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="160" w:line="259" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>${Object.values(Y).map(e=>e.xml).join("")}<w:style w:type="table" w:default="1" w:styleId="TableNormal"><w:name w:val="Normal Table"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/><w:tblCellMar><w:top w:w="0" w:type="dxa"/><w:left w:w="108" w:type="dxa"/><w:bottom w:w="0" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style></w:styles>`),t}import{escapeHtml as ee}from"efficient-shell/ui";var te=(()=>{const e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=1&n?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function ne(e){let t=4294967295;for(let n=0;n<e.length;n++)t=te[255&(t^e[n])]^t>>>8;return(4294967295^t)>>>0}async function re(e,t){const n=t.writable.getWriter();return n.write(e).then(()=>n.close()).catch(()=>{}),new Uint8Array(await new Response(t.readable).arrayBuffer())}var oe={textBox:"Text box",chart:"Chart",diagram:"Diagram",equation:"Equation",picture:"Picture",object:"Object",contents:"Field"},ae=new Set(["w:ins","w:del","w:moveFrom","w:moveTo","w:rPrChange","w:pPrChange","w:tcPrChange","w:trPrChange","w:tblPrChange","w:sectPrChange","w:cellIns","w:cellDel"]),se=new Set(["w:ins","w:del","w:moveFrom","w:moveTo"]),ie={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",svg:"image/svg+xml"},le=/^(https?:|mailto:|tel:)/i,ce=e=>ee(e);function de(e,t){let n="";for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return`data:${t};base64,${btoa(n)}`}var ue=(e,t)=>`${t}${++e.nextId}`,pe=(e,t)=>e.src.slice(t.start,t.end),fe=(e,t)=>t?pe(e,t):void 0;function me(e,t){const n=[],r=new Set;let o=t;for(;o&&!r.has(o);){r.add(o);const t=e.styles.get(o);if(!t)break;n.unshift(t),o=x(t,"w:basedOn")?.attrs["w:val"]}return n}var he=e=>`"${e.replace(/["\\\n\r]/g,"")}"`;function we(e){return"w:t"===e.name||"w:delText"===e.name?e.text:"w:tab"===e.name?"\t":"w:instrText"===e.name||"w:instrDelText"===e.name?"":e.children.map(we).join("")}function ge(e,t,n,r,o=""){const a=ue(e,"x");return e.doc.raw.set(a,t),`<span data-raw="${a}" data-kind="${n}" contenteditable="false"${o}>${ee(r)}</span>`}function be(e,t){const n=ue(e,"x");return e.doc.raw.set(n,t),`<span data-raw="${n}" data-kind="mark"></span>`}function ye(e,t,n){const r=n(pe(e,t)),o=e=>k(t,new Set([e])).length>0,a=x(t,"wp:inline"),s=k(t,new Set(["a:blip"]))[0],i=s&&e.rels.get(s.attrs["r:embed"]),l=i&&!i.external?j(e.doc.docPath,i.target):void 0,c=l?.split(".").pop()?.toLowerCase()??"",d=l?e.doc.parts.get(l):void 0;if(d&&ie[c]&&!o("wps:txbx")){const n=ue(e,"x");e.doc.raw.set(n,r);const o=x(a??x(t,"wp:anchor"),"wp:extent"),s=Number(o?.attrs.cx)/12700,i=Number(o?.attrs.cy)/12700,l=s&&i?` style="width:${Math.round(100*s)/100}pt;height:${Math.round(100*i)/100}pt"`:"",u=a?"":' contenteditable="false"';return a||e.doc.notices.objects++,`<img data-raw="${n}" src="${ce(e.imageUrl(d,ie[c]))}"${l}${u} alt="">`}return e.doc.notices.objects++,o("wps:txbx")||o("w:txbxContent")?ge(e,r,"object",`${e.labels.textBox}: ${we(t).slice(0,80)}`):o("c:chart")?ge(e,r,"object",e.labels.chart):o("dgm:relIds")?ge(e,r,"object",e.labels.diagram):ge(e,r,"object",s?e.labels.picture:e.labels.object)}function ve(e,t){const n=x(t,"w:rPr"),r=V(n,e.theme),o=fe(e,n)??"",a=e=>`<w:r>${o}${e}</w:r>`;let s="";for(const n of t.children)switch(n.name){case"w:rPr":case"w:lastRenderedPageBreak":case"w:commentReference":case"w:fldChar":case"w:instrText":case"w:delInstrText":break;case"w:t":case"w:delText":s+=ee(n.text);break;case"w:tab":s+="\t";break;case"w:noBreakHyphen":s+="‑";break;case"w:softHyphen":s+="­";break;case"w:br":case"w:cr":"page"===n.attrs["w:type"]?s+='<span data-page-break contenteditable="false"></span>':"column"===n.attrs["w:type"]?s+=ge(e,a(pe(e,n)),"mark",""):s+="<br>";break;case"w:drawing":s+=ye(e,n,a);break;case"mc:AlternateContent":case"w:pict":case"w:object":e.doc.notices.objects++,s+=ge(e,a(pe(e,n)),"object",k(n,new Set(["wps:txbx","w:txbxContent","v:textbox"])).length?`${e.labels.textBox}: ${we(k(n,new Set(["wps:txbx","w:txbxContent","v:textbox"]))[0]).slice(0,80)}`:e.labels.object);break;case"w:footnoteReference":case"w:endnoteReference":{const t=++e.footnoteCount;e.doc.notices.footnotes++;const r=e.footnotes.get(n.attrs["w:id"]);s+=ge(e,a(pe(e,n)),"note",String(t),r?` title="${ce(r)}"`:"");break}default:s+=ge(e,a(pe(e,n)),"mark","")}if(!s)return"";if(r.vert&&(s=`<${"sub"===r.vert?"sub":"sup"}>${s}</${"sub"===r.vert?"sub":"sup"}>`),n){const t=ue(e,"r");e.doc.runs.set(t,o);const a=X(r),i=x(n,"w:rStyle")?.attrs["w:val"];s=`<span data-r="${t}"${i?` data-rstyle="${ce(i)}"`:""}${a?` style="${ce(a)}"`:""}>${s}</span>`}for(const t of e.openComments)s=`<span data-comment="${ce(t)}" title="${ce(e.comments.get(t)??"")}">${s}</span>`;return s}function xe(e,t){let n="",r=0,o=-1,a=-1,s="",i=!1;const l=()=>{o>=0&&(n+=ge(e,e.src.slice(o,a),"field",s||e.labels.contents)),o=-1,s="",i=!1};for(const c of t){if("w:r"===c.name){const t=$(c,"w:fldChar");if(t.length||r>0){0===r&&(o=c.start,i=!1),i&&(s+=we(c));for(const e of t){const t=e.attrs["w:fldCharType"];"begin"===t?r++:"separate"===t&&1===r?i=!0:"end"===t&&r--}a=c.end,0===r&&l();continue}n+=ve(e,c);continue}if(r>0)a=c.end;else switch(c.name){case"w:pPr":case"w:proofErr":break;case"w:commentRangeStart":e.openComments.add(c.attrs["w:id"]);break;case"w:commentRangeEnd":e.openComments.delete(c.attrs["w:id"]);break;case"w:hyperlink":{const t=c.attrs["r:id"]?e.rels.get(c.attrs["r:id"]):void 0,r=c.attrs["w:anchor"],o=t?.target??(r?`#${r}`:""),a=le.test(o)||o.startsWith("#"),s=`${t?` data-rel="${ce(c.attrs["r:id"])}"`:""}${r?` data-anchor="${ce(r)}"`:""}`;n+=`<a${a?` href="${ce(o)}"`:""}${s}>${xe(e,c.children)}</a>`;break}case"w:ins":case"w:moveTo":n+=`<ins>${xe(e,c.children)}</ins>`;break;case"w:del":case"w:moveFrom":n+=`<del>${xe(e,c.children)}</del>`;break;case"w:bookmarkStart":case"w:bookmarkEnd":case"w:permStart":case"w:permEnd":default:n+=be(e,pe(e,c));break;case"m:oMath":case"m:oMathPara":e.doc.notices.objects++,n+=ge(e,pe(e,c),"object",e.labels.equation);break;case"w:fldSimple":case"w:sdt":case"w:smartTag":case"w:customXml":n+=ge(e,pe(e,c),"field",we(c)||e.labels.contents)}}return r>0&&(n+=ee(s)),n}function $e(e){return k(e,ae).length>0}function ke(e,t){const n=x(t,"w:pPr"),r=x(n,"w:pStyle")?.attrs["w:val"],o=x(n,"w:numPr")??function(e,t){let n;for(const r of me(e,t))n=x(x(r,"w:pPr"),"w:numPr")??n;return n}(e,r),a=x(o,"w:numId")?.attrs["w:val"];if(!a||"0"===a)return null;const s=Number(x(o,"w:ilvl")?.attrs["w:val"]??0),i=e.numbering.get(a)?.get(s);return{numId:a,ilvl:s,ordered:i?.ordered??!1,marker:i?.marker??""}}function Ce(e){const t=[],n=x(e,"w:pBdr");for(const e of["top","bottom","left","right"]){const r=x(n,`w:${e}`);if(!r||"nil"===r.attrs["w:val"]||"none"===r.attrs["w:val"])continue;const o=/^[0-9a-fA-F]{6}$/.test(r.attrs["w:color"]??"")?`#${r.attrs["w:color"]}`:"currentcolor";t.push(`border-${e}:${(Number(r.attrs["w:sz"])||4)/8}pt solid ${o}`)}const r=x(e,"w:shd")?.attrs["w:fill"];return r&&/^[0-9a-fA-F]{6}$/.test(r)&&t.push(`background-color:#${r}`),t.join(";")}function Ne(e,t,n){const r=x(t,"w:pPr"),o=x(r,"w:pStyle")?.attrs["w:val"],a=e.fieldOpen,s=function(e){let t=0;for(const n of k(e,new Set(["w:fldChar"]))){const e=n.attrs["w:fldCharType"];"begin"===e?t++:"end"===e&&t--}return t}(t),i=$e(t)||a||0!==s;s>0&&(e.fieldOpen=!0),a&&s<0&&(e.fieldOpen=!1);const l=ue(e,"p");e.doc.blocks.set(l,{xml:pe(e,t),fingerprint:"",props:fe(e,r),numId:n?.numId,ilvl:n?.ilvl});const c=n?0:function(e,t){if(!t)return 0;const n=x(e.styles.get(t),"w:name")?.attrs["w:val"]??"",r=/^heading ([1-6])$/i.exec(n);return r?Number(r[1]):0}(e,o),d=n?"li":c?`h${c}`:"p",u=G(r);n&&delete u.indentLeft,n&&delete u.firstLine;const p=[_(u),Ce(r)].filter(Boolean).join(";");let f=i?Se(e,t):xe(e,t.children);f&&!/<br>(<\/[^>]+>)*$/.test(f)||(f+="<br>");return`<${d} data-docx="${l}"${x(r,"w:pageBreakBefore")?" data-break-before":""}${o?` data-pstyle="${ce(o)}"`:""}${p?` style="${ce(p)}"`:""}${i?' data-locked contenteditable="false"':""}>${f}</${d}>`}function Se(e,t){let n="";for(const r of t.children)"w:pPr"!==r.name&&"w:rPr"!==r.name&&"w:instrText"!==r.name&&"w:delInstrText"!==r.name&&("w:ins"===r.name||"w:moveTo"===r.name?n+=`<ins>${Se(e,r)}</ins>`:"w:del"===r.name||"w:moveFrom"===r.name?n+=`<del>${Se(e,r)}</del>`:"w:commentRangeStart"===r.name?e.openComments.add(r.attrs["w:id"]):"w:commentRangeEnd"===r.name?e.openComments.delete(r.attrs["w:id"]):"w:t"===r.name||"w:delText"===r.name?n+=ee(r.text):"w:tab"===r.name?n+="\t":"w:br"===r.name?n+="<br>":"w:drawing"===r.name||"mc:AlternateContent"===r.name||"w:pict"===r.name?n+=`<span data-kind="object">${ee(e.labels.object)}</span>`:n+=Se(e,r));return n}function Ae(e,t){const n=ue(e,"t"),r=x(t,"w:tblPr"),o=x(t,"w:tblGrid"),a=$(t,"w:tr"),s=a.some(e=>x(x(e,"w:trPr"),"w:gridBefore")||x(x(e,"w:trPr"),"w:gridAfter")),i=$e(t)||s;s&&e.doc.notices.objects++,e.doc.blocks.set(n,{xml:pe(e,t),fingerprint:"",props:fe(e,r),tblGrid:fe(e,o)});const l=x(r,"w:tblStyle")?.attrs["w:val"],c=$(o,"w:gridCol").map(e=>Number(e.attrs["w:w"])/20),d=new Map,u=a.map(e=>{const t=[];let n=0;for(const r of $(e,"w:tc")){const e=x(r,"w:tcPr"),o=Number(x(e,"w:gridSpan")?.attrs["w:val"]??1),a=x(e,"w:vMerge");if(a&&"restart"!==a.attrs["w:val"]&&d.has(n))d.get(n).rowSpan++;else{const e={node:r,rowSpan:1,col:n,span:o};t.push(e),a?d.set(n,e):d.delete(n)}n+=o}return t}),p=function(e,t,n){let r=x(t,"w:tblBorders");if(!r)for(const t of me(e,n))r=x(x(t,"w:tblPr"),"w:tblBorders")??r;return!!r&&r.children.some(e=>!["nil","none"].includes(e.attrs["w:val"]))}(e,r,l),f=a.map((t,n)=>{const r=ue(e,"t");e.doc.blocks.set(r,{xml:"",fingerprint:"",props:fe(e,x(t,"w:trPr"))});return`<tr data-docx="${r}">${u[n].map(t=>{const n=ue(e,"t"),r=x(t.node,"w:tcPr");e.doc.blocks.set(n,{xml:"",fingerprint:"",props:fe(e,r)});const o=x(r,"w:shd")?.attrs["w:fill"],a=[];o&&/^[0-9a-fA-F]{6}$/.test(o)&&a.push(`background-color:#${o.toLowerCase()}`);const s=x(r,"w:vAlign")?.attrs["w:val"];return"center"===s&&a.push("vertical-align:middle"),"bottom"===s&&a.push("vertical-align:bottom"),`<td data-docx="${n}"${t.span>1?` colspan="${t.span}"`:""}${t.rowSpan>1?` rowspan="${t.rowSpan}"`:""}${a.length?` style="${a.join(";")}"`:""}>${Te(e,t.node.children)}</td>`}).join("")}</tr>`}).join(""),m=c.length?`<colgroup>${c.map(e=>`<col style="width:${Math.round(100*e)/100}pt">`).join("")}</colgroup>`:"";return`<table data-docx="${n}"${l?` data-tstyle="${ce(l)}"`:""}${p?"":" data-no-borders"}${i?' data-locked contenteditable="false"':""}>${m}<tbody>${f}</tbody></table>`}function Te(e,t){const n=[],r=[],o=e=>{for(;r.length>e;){const e=r.pop();n.push(`</li></${e.tag}>`)}};for(const a of t){const t="w:p"===a.name?ke(e,a):null;if(t){for(;r.length&&r[r.length-1].ilvl>t.ilvl;)o(r.length-1);const s=r[r.length-1];!s||s.ilvl!==t.ilvl||s.numId===t.numId&&s.tag===(t.ordered?"ol":"ul")||o(r.length-1);const i=`${t.numId}:${t.ilvl}`,l=e.listCounters.get(i)??0;e.listCounters.set(i,l+1);const c=Ne(e,a,t),d=r[r.length-1];if(d&&d.ilvl===t.ilvl)n.push(`</li>${c.slice(0,c.lastIndexOf("</li>"))}`);else{const e=t.ordered?"ol":"ul",o=t.marker?` style="list-style-type:${t.marker}"`:"",a=t.ordered&&l?` start="${l+1}"`:"";n.push(`<${e} data-num-id="${ce(t.numId)}" data-ilvl="${t.ilvl}"${a}${o}>${c.slice(0,c.lastIndexOf("</li>"))}`),r.push({tag:e,numId:t.numId,ilvl:t.ilvl})}continue}if("w:tcPr"!==a.name&&"w:sectPr"!==a.name)if(o(0),"w:p"===a.name)n.push(Ne(e,a,null));else if("w:tbl"===a.name)n.push(Ae(e,a));else if("w:sdt"===a.name){const t=ue(e,"p");e.doc.blocks.set(t,{xml:pe(e,a),fingerprint:""}),e.doc.notices.objects++;const r=Te(e,$(x(a,"w:sdtContent"),"w:p"));n.push(`<div data-docx="${t}" data-locked contenteditable="false">${r}</div>`)}else{const t=ue(e,"p");e.doc.blocks.set(t,{xml:pe(e,a),fingerprint:""}),n.push(`<div data-docx="${t}" data-locked data-hidden contenteditable="false"></div>`)}}return o(0),n.join("")}function Le(e){if("LI"!==e.tagName)return e.outerHTML;const t=e.cloneNode(!0);return Array.from(t.children).forEach(e=>{"UL"!==e.tagName&&"OL"!==e.tagName||e.remove()}),t.outerHTML}function Pe(e){const t=document.createElement("div");t.innerHTML=e.html,t.querySelectorAll("[data-docx]").forEach(t=>{const n=e.blocks.get(t.getAttribute("data-docx"));n&&(n.fingerprint=Le(t))})}function Me(e,t){const n=t?P(e,t):void 0;if(!n)return{text:"",editable:!0};const r=b(n),o=r.children.filter(e=>"w:p"===e.name),a=r.children.every(e=>"w:p"===e.name)&&0===k(r,new Set(["w:drawing","w:pict","mc:AlternateContent","w:sdt"])).length,s=o.map(e=>{let t="",n="",r=!1;const o=e=>{for(const a of e.children)if("w:t"===a.name)r||(t+=a.text);else if("w:tab"===a.name)r||(t+=" | ");else if("w:instrText"===a.name)n+=a.text;else if("w:fldChar"===a.name){const e=a.attrs["w:fldCharType"];"separate"!==e&&"end"!==e||(n&&(t+=Ee(n),n=""),r="separate"===e)}else"w:fldSimple"===a.name?t+=Ee(a.attrs["w:instr"]??"")||a.children.map(we).join(""):"w:pPr"!==a.name&&"w:rPr"!==a.name&&o(a)};return o(e),t}).filter(Boolean);return{text:s.join(" "),editable:a&&s.length<=1,part:t}}function Ee(e){const t=e.trim().split(/\s+/)[0]?.toUpperCase();return"PAGE"===t?"{page}":"NUMPAGES"===t?"{pages}":""}async function Re(e,t={}){const n=await async function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=-1;for(let r=e.length-22;r>=Math.max(0,e.length-66e3);r--)if(101010256===t.getUint32(r,!0)){n=r;break}if(n<0)throw new Error("Not a zip file");const r=t.getUint16(n+10,!0);let o=t.getUint32(n+16,!0);const a=new TextDecoder,s=new Map;let i=0;for(let n=0;n<r;n++){if(33639248!==t.getUint32(o,!0))throw new Error("Damaged zip file");const n=t.getUint16(o+10,!0),r=t.getUint32(o+20,!0);if(i+=t.getUint32(o+24,!0),i>1073741824)throw new Error("Zip file too large");const l=t.getUint16(o+28,!0),c=t.getUint16(o+30,!0),d=t.getUint16(o+32,!0),u=t.getUint32(o+42,!0),p=a.decode(e.subarray(o+46,o+46+l));if(o+=46+l+c+d,p.endsWith("/"))continue;const f=u+30+t.getUint16(u+26,!0)+t.getUint16(u+28,!0),m=e.subarray(f,f+r);if(0===n)s.set(p,m.slice());else{if(8!==n)throw new Error("Unsupported zip compression");s.set(p,await re(m,new DecompressionStream("deflate-raw")))}}return s}(e);return je(n,e,t)}function je(e,t,n={}){const r=R(e,"").find(e=>e.type.endsWith("/officeDocument")),o=r?j("",r.target):"word/document.xml",a=P(e,o);if(!a)throw new Error("Not a Word document");const s=b(a),i=x(s,"w:body");if(!i)throw new Error("Not a Word document");const l=R(e,o),c=e=>{const t=(e=>l.find(t=>t.type===e))(e);return t?j(o,t.target):void 0},d=function(e){if(!e)return{};try{const t=b(e),n=x(x(t,"a:themeElements"),"a:fontScheme");return{major:x(x(n,"a:majorFont"),"a:latin")?.attrs.typeface,minor:x(x(n,"a:minorFont"),"a:latin")?.attrs.typeface}}catch{return{}}}(c(A.theme)?P(e,c(A.theme)):void 0),u={parts:e,docPath:o,source:t,html:"",css:"",page:{...D},header:{text:"",editable:!0},footer:{text:"",editable:!0},blocks:new Map,runs:new Map,raw:new Map,notices:{comments:0,tracked:0,objects:0,footnotes:0},styles:[],theme:d},p={src:a,doc:u,labels:n.labels??oe,rels:new Map(l.map(e=>[e.id,e])),theme:d,imageUrl:n.imageUrl??de,styles:new Map,numbering:new Map,listCounters:new Map,comments:new Map,footnotes:new Map,nextId:0,footnoteCount:0,openComments:new Set,fieldOpen:!1},f=c(A.styles),m=f?P(e,f):void 0,h=m?b(m):void 0;for(const e of $(h,"w:style"))p.styles.set(e.attrs["w:styleId"],e);const w=new Set(p.styles.keys());for(const[e,t]of Object.entries(Y))w.has(e)||p.styles.set(e,b(t.xml));const g=x(h,"w:docDefaults");u.lang=x(x(x(g,"w:rPrDefault"),"w:rPr"),"w:lang")?.attrs["w:val"],u.css=function(e,t){const n=[],r=V(x(x(t,"w:rPrDefault"),"w:rPr"),e.theme),o=G(x(x(t,"w:pPrDefault"),"w:pPr"));e.doc.defaultFont=r.font,e.doc.defaultSize=r.size;let a=r,s=o;for(const[t,i]of e.styles){const l=i.attrs["w:type"];if("paragraph"!==l&&"character"!==l&&"table"!==l)continue;let c={},d={};for(const n of me(e,t))c={...c,...V(x(n,"w:rPr"),e.theme)},d={...d,...G(x(n,"w:pPr"))};if("paragraph"===l)n.push(`.docs-page [data-pstyle=${he(t)}]{${[X(c),_(d)].filter(Boolean).join(";")}}`),"1"===i.attrs["w:default"]&&(a={...r,...c},s={...o,...d});else if("character"===l)n.push(`.docs-page [data-rstyle=${he(t)}]{${X(c)}}`);else{const e=_(d);e&&n.push(`.docs-page table[data-tstyle=${he(t)}] p{${e}}`)}}return n.unshift(`.docs-page{${X(a)}}`,`.docs-page p,.docs-page h1,.docs-page h2,.docs-page h3,.docs-page h4,.docs-page h5,.docs-page h6,.docs-page li{${_(s)}}`),n.join("\n")}(p,g);const y=new Set(Object.keys(Y));u.styles=[...p.styles.values()].filter(e=>"paragraph"===e.attrs["w:type"]&&"1"!==e.attrs["w:default"]&&(y.has(e.attrs["w:styleId"])||x(e,"w:qFormat"))&&!x(e,"w:hidden")&&!x(e,"w:semiHidden")).map(e=>({id:e.attrs["w:styleId"],name:x(e,"w:name")?.attrs["w:val"]??e.attrs["w:styleId"]}));const v=c(A.numbering),C=v?P(e,v):void 0;C&&function(e,t){const n=new Map;for(const e of $(t,"w:abstractNum")){const t=new Map;for(const n of $(e,"w:lvl")){const e=x(n,"w:numFmt")?.attrs["w:val"]??"decimal";t.set(Number(n.attrs["w:ilvl"]),{ordered:"bullet"!==e&&"none"!==e,marker:ze[e]??""})}n.set(e.attrs["w:abstractNumId"],t)}for(const r of $(t,"w:num")){const t=n.get(x(r,"w:abstractNumId")?.attrs["w:val"]??"");t&&e.numbering.set(r.attrs["w:numId"],t)}}(p,b(C));const N=c(A.comments),S=N?P(e,N):void 0;if(S){for(const e of $(b(S),"w:comment"))p.comments.set(e.attrs["w:id"],`${e.attrs["w:author"]??""}: ${we(e)}`);u.notices.comments=p.comments.size}const T=c(A.footnotes),L=T?P(e,T):void 0;if(L)for(const e of $(b(L),"w:footnote"))p.footnotes.set(e.attrs["w:id"],we(e));u.notices.tracked=k(i,se).length;const M=x(i,"w:sectPr"),E=x(M,"w:pgSz"),z=x(M,"w:pgMar"),I=(e,t,n)=>{const r=Number(e?.attrs[t]);return Number.isFinite(r)&&void 0!==e?.attrs[t]?r:n};u.page={width:I(E,"w:w",D.width),height:I(E,"w:h",D.height),top:Math.abs(I(z,"w:top",D.top)),right:I(z,"w:right",D.right),bottom:Math.abs(I(z,"w:bottom",D.bottom)),left:I(z,"w:left",D.left),header:I(z,"w:header",D.header),footer:I(z,"w:footer",D.footer)};const U=e=>{const t=$(M,e).find(e=>"default"===e.attrs["w:type"]),n=t&&p.rels.get(t.attrs["r:id"]);return n?j(o,n.target):void 0};return u.header=Me(e,U("w:headerReference")),u.footer=Me(e,U("w:footerReference")),u.html=Te(p,i.children),u.html||(u.html="<p><br></p>"),Pe(u),u}var ze={lowerLetter:"lower-alpha",upperLetter:"upper-alpha",lowerRoman:"lower-roman",upperRoman:"upper-roman",decimalZero:"decimal-leading-zero"};var Ie=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","LI","TR","TABLE","UL","OL","TBODY"]);function Ue(e){let t="";const n=e=>{for(const r of Array.from(e.childNodes)){if(3===r.nodeType){t+=(r.nodeValue??"").replace(/​/g,"");continue}if(1!==r.nodeType)continue;const e=r;if("BR"===e.tagName){t+="\n";continue}if("DEL"===e.tagName||e.hasAttribute("data-hidden"))continue;if("object"===e.getAttribute("data-kind")||"mark"===e.getAttribute("data-kind"))continue;if("TD"===e.tagName||"TH"===e.tagName){n(e),t=`${t.replace(/\n+$/,"")}\t`;continue}const o=Ie.has(e.tagName);n(e),o&&!t.endsWith("\n")&&(t+="\n")}};return n(e),t.replace(/\t\n/g,"\n").replace(/\n+$/,"\n")}function Oe(e,t,n){if(!t)return[];const r=function(e){const t=[],n=e=>{for(const r of Array.from(e.childNodes))if(3===r.nodeType)t.push(r);else if(1===r.nodeType){const e=r;if("false"===e.getAttribute("contenteditable")||e.hasAttribute("data-raw"))continue;n(e)}};return n(e),t}(e),o=t=>{let n=t.parentNode;for(;n&&n!==e&&!Ie.has(n.tagName)&&"TD"!==n.tagName;)n=n.parentNode;return n},a=[];let s=0;for(;s<r.length;){const e=o(r[s]);let i=s;const l=[];for(;i<r.length&&o(r[i])===e;)l.push(r[i++]);const c=l.map(e=>e.nodeValue??"").join(""),d=n?c:c.toLowerCase(),u=n?t:t.toLowerCase(),p=d.length===c.length?d:c;for(let e=p.indexOf(u);e>=0;e=p.indexOf(u,e+u.length)){const t=[];let n=0;for(const r of l){const o=(r.nodeValue??"").length,a=Math.max(e,n),s=Math.min(e+u.length,n+o);a<s&&t.push({node:r,start:a-n,end:s-n}),n+=o}a.push(t)}s=i}return a}function De(e,t){e.forEach((e,n)=>{const r=e.node.nodeValue??"";e.node.nodeValue=r.slice(0,e.start)+(0===n?t:"")+r.slice(e.end)})}var Be=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","UL","OL","LI","TABLE","THEAD","TBODY","TFOOT","TR","TD","TH","COLGROUP","COL","B","STRONG","I","EM","U","S","STRIKE","SUB","SUP","SPAN","FONT","A","BR","IMG","PRE","HR"]),Fe=new Set(["SCRIPT","STYLE","TITLE","META","LINK","OBJECT","EMBED","IFRAME","NOSCRIPT","TEMPLATE","SVG","MATH","FORM","INPUT","BUTTON","SELECT","TEXTAREA","VIDEO","AUDIO","CANVAS"]),He=new Set(["color","background-color","font-weight","font-style","text-decoration-line","text-decoration","font-family","font-size","text-align","margin-left","line-height","width","height","list-style-type"]),We=/^(https?:|mailto:|tel:|#)/i,qe=/^(data:image\/(png|jpe?g|gif|webp|bmp);base64,|blob:)/i;function Ke(e){const t=document.implementation.createHTMLDocument("");t.body.innerHTML=e;const n=(e,t,r)=>{for(const o of Array.from(e.childNodes)){if(3===o.nodeType){t.appendChild(r.createTextNode(o.nodeValue??""));continue}if(1!==o.nodeType)continue;const e=o,a=e.tagName.toUpperCase();if(Fe.has(a))continue;if(!Be.has(a)){n(e,t,r);continue}if("IMG"===a&&!qe.test(e.getAttribute("src")??""))continue;const s=r.createElement(a),i=(e.getAttribute("style")??"").split(";").map(e=>{const t=e.indexOf(":");if(t<0)return"";const n=e.slice(0,t).trim().toLowerCase(),r=e.slice(t+1).trim();return He.has(n)&&!/url\(|expression|mso-/i.test(r)?`${n}:${r}`:""}).filter(Boolean).join(";");i&&s.setAttribute("style",i),"A"===a&&We.test(e.getAttribute("href")??"")&&s.setAttribute("href",e.getAttribute("href")),"IMG"===a&&s.setAttribute("src",e.getAttribute("src"));for(const t of["colspan","rowspan","start","color","face","size"]){const n=e.getAttribute(t);null!==n&&s.setAttribute(t,n)}n(e,s,r),t.appendChild(s)}},r=document.createElement("div");return n(t.body,r,document),r.innerHTML}import{useCallback as Ve,useEffect as Ge,useId as Qe,useMemo as _e,useRef as Xe,useState as Ye}from"react";import{saveIndicator as Ze,useAutosave as Je}from"efficient-easel/autosave";import{useEaselStrings as et}from"efficient-easel/strings";import{Icon as tt}from"efficient-shell/icons";import{Button as nt,ColorPickerPanel as rt,ContextMenu as ot,DropdownMenu as at,IconButton as st,Popover as it,PopupMenu as lt,PopupMenuDivider as ct,PopupMenuItem as dt,PopupMenuLabel as ut,prompt as pt,registerModalEscapeInterceptor as ft,toast as mt,useShellLocale as ht}from"efficient-shell/ui";import{SettingsColour as wt}from"efficient-easel/panel";import{useEaselStrings as gt}from"efficient-easel/strings";import{Button as bt,Select as yt}from"efficient-shell/ui";import{jsx as vt,jsxs as xt}from"react/jsx-runtime";function $t({page:e,onPage:t,onMorePageSetup:r,colour:o,onColour:a,outline:s,onHeading:i}){const l=n(),c=gt(),d=H(e),u=W(e),p={a4:"A4",a3:"A3",a5:"A5",letter:l.paperLetter,legal:l.paperLegal},f={normal:l.marginsNormal,narrow:l.marginsNarrow,moderate:l.marginsModerate,wide:l.marginsWide},m={value:"custom",label:l.custom};return xt("aside",{className:"docs-panel",children:[vt("h3",{children:l.documentPanel}),xt("div",{className:"docs-panel-section",children:[vt("p",{className:"docs-panel-label",children:l.pagePanel}),vt(yt,{"aria-label":l.paperSize,value:d??"custom",onChange:n=>{"custom"!==n&&t(B(e,n))},options:[...d?[]:[m],...Object.keys(U).map(e=>({value:e,label:p[e]}))]}),vt(yt,{"aria-label":l.margins,value:u??"custom",onChange:n=>{"custom"!==n&&t(F(e,n))},options:[...u?[]:[m],...Object.keys(O).map(e=>({value:e,label:f[e]}))]}),vt(bt,{variant:"secondary",block:!0,onClick:r,children:l.morePageSetup})]}),vt("div",{className:"docs-panel-section",children:vt(wt,{label:l.textColor,value:o,onChange:a,words:c.colourRow})}),xt("div",{className:"docs-panel-section",children:[vt("p",{className:"docs-panel-label",children:l.outline}),0===s.length?vt("p",{className:"docs-panel-empty",children:l.outlineEmpty}):vt("ul",{className:"docs-outline",children:s.map((e,t)=>vt("li",{style:{paddingLeft:10*(e.level-1)+"px"},children:vt("button",{type:"button",onClick:()=>i(t),children:e.text})},t))})]})]})}import{EaselIconButton as kt,EaselTopBar as Ct,SaveState as Nt,TopBarCluster as St,TopBarDivider as At}from"efficient-easel/chrome";import"efficient-easel/shell.css";import"efficient-easel/chrome.css";import"efficient-easel/panel.css";import"efficient-easel/fields.css";import{Icon as Tt}from"efficient-shell/icons";import{DropdownMenu as Lt}from"efficient-shell/ui";import{jsx as Pt,jsxs as Mt}from"react/jsx-runtime";function Et({onClose:e,fileMenu:t,name:r,saveState:o,canUndo:a,canRedo:s,onUndo:i,onRedo:l,exportControl:c}){const d=n();return Mt(Ct,{children:[Mt(St,{children:[e&&Pt(kt,{label:d.backToFiles,onClick:e,children:Pt(Tt,{name:"chevron-left",size:16})}),t.length>0&&Pt(Lt,{trigger:d.menuFile,items:t,align:"start",triggerClassName:"docs-menu-trigger"}),r,Pt(Nt,{...o}),Pt(At,{}),Mt("span",{className:"docs-history",onMouseDown:e=>e.preventDefault(),children:[Pt(kt,{label:d.undo,disabled:!a,onClick:i,children:Pt(Tt,{name:"undo",size:16})}),Pt(kt,{label:d.redo,disabled:!s,onClick:l,children:Pt(Tt,{name:"redo",size:16})})]})]}),Pt(St,{kind:"right",children:c})]})}var Rt=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"],jt=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"],zt=["w:cnfStyle","w:tcW","w:gridSpan","w:hMerge","w:vMerge","w:tcBorders","w:shd","w:noWrap","w:tcMar","w:textDirection","w:tcFitText","w:vAlign","w:hideMark","w:headers","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"],It=["w:headerReference","w:footerReference","w:footnotePr","w:endnotePr","w:type","w:pgSz","w:pgMar","w:paperSrc","w:pgBorders","w:lnNumType","w:pgNumType","w:cols","w:formProt","w:vAlign","w:noEndnote","w:titlePg","w:textDirection","w:bidi","w:rtlGutter","w:docGrid","w:printerSettings","w:sectPrChange"];function Ut(e){if(!e)return[];return b(e).children.map(t=>({name:t.name,xml:e.slice(t.start,t.end)}))}function Ot(e,t){const n=e=>{const n=t.indexOf(e);return n<0?t.length:n};return e.map((e,t)=>({p:e,i:t})).sort((e,t)=>n(e.p.name)-n(t.p.name)||e.i-t.i).map(e=>e.p.xml).join("")}function Dt(e){const t=new Map;for(const n of(e.getAttribute("style")??"").split(";")){const e=n.indexOf(":");e>0&&t.set(n.slice(0,e).trim().toLowerCase(),n.slice(e+1).trim())}return t}var Bt={black:"#000000",white:"#ffffff",red:"#ff0000",blue:"#0000ff",green:"#008000",yellow:"#ffff00"};function Ft(e){if(!e)return;const t=e.trim().toLowerCase();if("transparent"===t||"inherit"===t||"initial"===t||"auto"===t)return;if(Bt[t])return Bt[t];if(/^#[0-9a-f]{6}$/.test(t))return t;if(/^#[0-9a-f]{3}$/.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`;const n=/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+))?\s*\)$/.exec(t);return!n||void 0!==n[4]&&0===Number(n[4])?void 0:`#${[n[1],n[2],n[3]].map(e=>Math.round(Number(e)).toString(16).padStart(2,"0")).join("")}`}function Ht(e){if(!e)return;const t=/^(-?[\d.]+)(pt|px|in|cm|mm|em)?$/.exec(e.trim());if(!t)return;const n=Number(t[1]);switch(t[2]){case"pt":return n;case"px":return.75*n;case"in":return 72*n;case"cm":return 72*n/2.54;case"mm":return 72*n/25.4;default:return"0"===t[1]?0:void 0}}var Wt=[10,13,16,18,24,32,48].map(e=>.75*e);var qt=(e,t)=>void 0===e||void 0===t?e===t:Math.abs(e-t)<.02,Kt=e=>Math.round(20*e);function Vt(e,t){const n=R(e.parts,e.doc.docPath).find(e=>e.type===A.styles),r=n?P(e.parts,j(e.doc.docPath,n.target)):void 0;if(r)for(const e of b(r).children)if("w:style"===e.name&&x(e,"w:name")?.attrs["w:val"]?.toLowerCase()===t)return e.attrs["w:styleId"];return Object.entries(Y).find(([,e])=>e.name===t)?.[0]??null}var Gt=["•","o","▪"],Qt=["decimal","lowerLetter","lowerRoman"];function _t(e){const t=R(e.parts,e.doc.docPath).find(e=>e.type===A.numbering);if(t){const n=j(e.doc.docPath,t.target);return{path:n,text:P(e.parts,n)??`<w:numbering ${N}></w:numbering>`}}const n="word/numbering.xml";return z(e.parts,e.doc.docPath,A.numbering,"numbering.xml"),I(e.parts,n,"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"),{path:n,text:`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:numbering ${N}></w:numbering>`}}function Xt(e,t){const{path:n,text:r}=_t(e),o=b(r),a=o.children.filter(e=>"w:abstractNum"===e.name).map(e=>Number(e.attrs["w:abstractNumId"])),s=String((a.length?Math.max(...a):-1)+1);let i="";for(let e=0;e<9;e++){i+=`<w:lvl w:ilvl="${e}"><w:start w:val="1"/><w:numFmt w:val="${t?Qt[e%3]:"bullet"}"/><w:lvlText w:val="${t?`%${e+1}.`:Gt[e%3]}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720*(e+1)}" w:hanging="360"/></w:pPr></w:lvl>`}const l=`<w:abstractNum w:abstractNumId="${s}"><w:multiLevelType w:val="hybridMultilevel"/>${i}</w:abstractNum>`,c=o.children.find(e=>"w:num"===e.name),d=c?c.start:o.innerEnd>o.innerStart||r.includes("</w:numbering>")?r.lastIndexOf("</w:numbering>"):-1,u=d>=0?r.slice(0,d)+l+r.slice(d):r.replace(/\/>\s*$/,`>${l}</w:numbering>`);return M(e.parts,n,u),s}function Yt(e,t,n){const{path:r,text:o}=_t(e),a=b(o),s=a.children.filter(e=>"w:num"===e.name).map(e=>Number(e.attrs["w:numId"])),i=String((s.length?Math.max(...s):0)+1),l=`<w:num w:numId="${i}"><w:abstractNumId w:val="${t}"/>${n?'<w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride>':""}</w:num>`,c=[...a.children].reverse().find(e=>"w:num"===e.name),d=c?c.end:o.lastIndexOf("</w:numbering>");return M(e.parts,r,o.slice(0,d)+l+o.slice(d)),i}var Zt={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/bmp":"bmp","image/webp":"webp","image/svg+xml":"svg"};function Jt(e,t){const n=t.getAttribute("data-raw"),r=function(e,t){const n=Dt(t),r=Ht(n.get("width")),o=Ht(n.get("height")),a=t.naturalWidth?.75*t.naturalWidth:0,s=t.naturalHeight?.75*t.naturalHeight:0,i=a&&s?s/a:o&&r?o/r:.75;let l=r??(a||e.contentWidth);return l>2*e.contentWidth&&(l=e.contentWidth),{width:l,height:o??l*i}}(e,t),o=Math.round(12700*r.width),a=Math.round(12700*r.height),s=n?e.doc.raw.get(n):void 0;if(s)return s.replace(/(<wp:extent\b[^>]*?\bcx=")\d+("[^>]*?\bcy=")\d+/,`$1${o}$2${a}`).replace(/(<a:xfrm\b[^>]*>\s*<a:off\b[^>]*\/>\s*<a:ext\b[^>]*?\bcx=")\d+("[^>]*?\bcy=")\d+/,`$1${o}$2${a}`);const i=t.getAttribute("src")??"";let l=e.mediaBySrc.get(i);if(!l){const t=e.images.get(i)??function(e){const t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(!t)return null;const n=atob(t[2]),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return{bytes:r,mime:t[1]}}(i);if(!t)return"";const n=Zt[t.mime]??"png";!function(e,t,n){const r=P(e,"[Content_Types].xml")??"";new RegExp(`Extension="${t}"`,"i").test(r)||M(e,"[Content_Types].xml",r.replace(/(<Types[^>]*>)/,`$1<Default Extension="${t}" ContentType="${n}"/>`))}(e.parts,n,t.mime);let r=1;for(;e.parts.has(`word/media/inserted${r}.${n}`);)r++;e.parts.set(`word/media/inserted${r}.${n}`,t.bytes),l=z(e.parts,e.doc.docPath,A.image,`media/inserted${r}.${n}`),e.mediaBySrc.set(i,l)}const c=++e.drawingId;return`<w:r><w:drawing><wp:inline xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="${o}" cy="${a}"/><wp:docPr id="${c}" name="Picture ${c}"/><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="${c}" name="Picture ${c}"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="${l}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${o}" cy="${a}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`}function en(e,t,n,r={}){let o="",a=null;const s=()=>{a?.body&&(o+=`<w:r>${function(e,t,n){const r=n?e.runs.get(n):void 0,o=V(r?b(r):void 0,e.theme);let a=Ut(r);const s=(e,t)=>{a=a.filter(t=>!e.includes(t.name)),a.push(...t)},i=(e,t)=>void 0===t?[]:[{name:e,xml:t?`<${e}/>`:`<${e} w:val="0"/>`}];if(t.b!==o.b&&s(["w:b","w:bCs"],[...i("w:b",t.b),...i("w:bCs",t.b)]),t.i!==o.i&&s(["w:i","w:iCs"],[...i("w:i",t.i),...i("w:iCs",t.i)]),!!t.u!=!!o.u&&s(["w:u"],t.u?[{name:"w:u",xml:'<w:u w:val="single"/>'}]:o.u?[{name:"w:u",xml:'<w:u w:val="none"/>'}]:[]),t.strike!==o.strike&&!!t.strike!=!!o.strike&&s(["w:strike"],i("w:strike",t.strike)),t.vert!==o.vert&&s(["w:vertAlign"],t.vert?[{name:"w:vertAlign",xml:`<w:vertAlign w:val="${"sub"===t.vert?"subscript":"superscript"}"/>`}]:[]),t.font!==o.font){const e=w(t.font??"");s(["w:rFonts"],t.font?[{name:"w:rFonts",xml:`<w:rFonts w:ascii="${e}" w:hAnsi="${e}" w:eastAsia="${e}" w:cs="${e}"/>`}]:[])}if(t.size!==o.size){const e=t.size?Math.round(2*t.size):0;s(["w:sz","w:szCs"],e?[{name:"w:sz",xml:`<w:sz w:val="${e}"/>`},{name:"w:szCs",xml:`<w:szCs w:val="${e}"/>`}]:[])}if(t.color!==o.color&&s(["w:color"],t.color?[{name:"w:color",xml:`<w:color w:val="${t.color.slice(1).toUpperCase()}"/>`}]:[]),t.hl!==o.hl){const e=t.hl?Object.entries(q).find(([,e])=>e===t.hl)?.[0]:void 0;s(["w:highlight","w:shd"],t.hl?e?[{name:"w:highlight",xml:`<w:highlight w:val="${e}"/>`}]:[{name:"w:shd",xml:`<w:shd w:val="clear" w:color="auto" w:fill="${t.hl.slice(1).toUpperCase()}"/>`}]:[])}const l=Ot(a,Rt);return l?`<w:rPr>${l}</w:rPr>`:""}(e.doc,a.format,a.runId)}${a.body}</w:r>`),a=null},i=(e,t,n)=>{n&&(a&&a.runId===t&&JSON.stringify(a.format)===JSON.stringify(e)?a.body+=n:(s(),a={format:e,runId:t,body:n}))},l=(t,r,a)=>{if(3===t.nodeType)return void i(r,a,function(e){let t="",n="";const r=()=>{n&&(t+=`<w:t xml:space="preserve">${w(n)}</w:t>`),n=""};for(const o of e)"\t"===o?(r(),t+="<w:tab/>"):"\n"===o?(r(),t+="<w:br/>"):"‑"===o?(r(),t+="<w:noBreakHyphen/>"):"­"===o?(r(),t+="<w:softHyphen/>"):"​"!==o&&"\ufeff"!==o&&(n+=o);return r(),t}(t.nodeValue??""));if(1!==t.nodeType)return;const c=t,d=c.tagName;if("IMG"===d)return s(),void(o+=Jt(e,c));const u=c.getAttribute("data-raw");if(u){const t=e.doc.raw.get(u);return void(t&&(s(),o+=t))}if(c.hasAttribute("data-page-break"))return void i(r,a,'<w:br w:type="page"/>');if("BR"===d)return void(function(e,t){let n=e;for(;n!==t;){let e=n.nextSibling;for(;e&&3===e.nodeType&&!e.nodeValue;)e=e.nextSibling;if(e)return!1;if(!n.parentNode)return!0;n=n.parentNode}return!0}(c,n)||i(r,a,"<w:br/>"));if("A"===d)return s(),void(o+=function(e,t,n,r){const o=t.getAttribute("data-anchor"),a=t.getAttribute("href")??"";let s=t.getAttribute("data-rel");const i=R(e.parts,e.doc.docPath),l=s?i.find(e=>e.id===s):void 0;a&&!a.startsWith("#")&&l?.target!==a&&(s=i.find(e=>e.external&&e.target===a)?.id??z(e.parts,e.doc.docPath,A.hyperlink,a,!0),t.setAttribute("data-rel",s));const c=t.querySelector("[data-r]")?n:{color:"#0563c1",u:!0,...n},d=en(e,Array.from(t.childNodes),r,c);return`<w:hyperlink${o?` w:anchor="${w(o)}"`:s?` r:id="${w(s)}"`:a.startsWith("#")?` w:anchor="${w(a.slice(1))}"`:""} w:history="1">${d}</w:hyperlink>`}(e,c,r,n));const p=c.getAttribute("data-comment");p&&e.firstComment.get(p)===c&&(s(),o+=`<w:commentRangeStart w:id="${w(p)}"/>`);const f=c.getAttribute("data-r"),m=function(e,t){const n={...t},r=e.tagName;if("B"!==r&&"STRONG"!==r||(n.b=!0),"I"!==r&&"EM"!==r||(n.i=!0),"U"===r&&(n.u=!0),"S"!==r&&"STRIKE"!==r||(n.strike=!0),"SUB"===r&&(n.vert="sub"),"SUP"===r&&(n.vert="super"),"FONT"===r){const t=Ft(e.getAttribute("color")??void 0);t&&(n.color=t);const r=e.getAttribute("face");r&&(n.font=r.split(",")[0].replace(/["']/g,"").trim());const o=Number(e.getAttribute("size"));o>=1&&o<=7&&(n.size=Wt[o-1])}const o=Dt(e),a=o.get("font-weight");a&&(n.b="bold"===a||"bolder"===a||Number(a)>=600);const s=o.get("font-style");s&&(n.i="italic"===s||"oblique"===s);const i=o.get("text-decoration-line")??o.get("text-decoration");i&&(/none/.test(i)?(n.u=!1,n.strike=!1):(/underline/.test(i)&&(n.u=!0),/line-through/.test(i)&&(n.strike=!0)));const l=o.get("font-family");l&&(n.font=l.split(",")[0].replace(/["']|&quot;/g,"").trim());const c=Ht(o.get("font-size"));if(c&&(n.size=Math.round(2*c)/2),o.has("color")){const e=Ft(o.get("color"));e?n.color=e:delete n.color}const d=o.get("background-color")??o.get("background");if(void 0!==d){const e=Ft(d);e?n.hl=e:delete n.hl}return n}(c,r);for(const e of Array.from(c.childNodes))l(e,m,f??a);p&&e.lastComment.get(p)===c&&(s(),o+=`<w:commentRangeEnd w:id="${w(p)}"/><w:r><w:commentReference w:id="${w(p)}"/></w:r>`)};for(const e of t)l(e,r,null);return s(),o}function tn(e,t,n,r,o){const a=G(n?b(n):void 0),s=function(e){const t=Dt(e),n={},r=t.get("text-align")??e.getAttribute("align")??void 0;"left"===r||"start"===r?n.align="left":"center"!==r&&"right"!==r&&"justify"!==r||(n.align=r);const o=Ht(t.get("margin-left"));void 0!==o&&(n.indentLeft=o);const a=Ht(t.get("text-indent"));void 0!==a&&(n.firstLine=a);const s=Ht(t.get("margin-top"));void 0!==s&&(n.before=s);const i=Ht(t.get("margin-bottom"));void 0!==i&&(n.after=i);const l=t.get("line-height");if(l){const e=Ht(l);e?n.linePoints=e:Number(l)&&(n.lineMultiple=Number(l))}return n}(t);let i=Ut(n);const l=(e,t)=>{i=i.filter(t=>t.name!==e),t&&i.push({name:e,xml:t})};if(l("w:pStyle",r?`<w:pStyle w:val="${w(r)}"/>`:null),l("w:numPr",o?`<w:numPr><w:ilvl w:val="${o.ilvl}"/><w:numId w:val="${w(o.numId)}"/></w:numPr>`:null),s.align!==a.align&&l("w:jc",s.align?`<w:jc w:val="${"justify"===s.align?"both":s.align}"/>`:null),!(o||qt(s.indentLeft,a.indentLeft)&&qt(s.firstLine,a.firstLine))){const e=[];void 0!==s.indentLeft&&e.push(`w:left="${Kt(s.indentLeft)}"`),void 0!==s.firstLine&&e.push(s.firstLine<0?`w:hanging="${Kt(-s.firstLine)}"`:`w:firstLine="${Kt(s.firstLine)}"`),l("w:ind",e.length?`<w:ind ${e.join(" ")}/>`:null)}if(!(qt(s.before,a.before)&&qt(s.after,a.after)&&qt(s.lineMultiple,a.lineMultiple)&&qt(s.linePoints,a.linePoints))){const e=[];void 0!==s.before&&e.push(`w:before="${Kt(s.before)}"`),void 0!==s.after&&e.push(`w:after="${Kt(s.after)}"`),void 0!==s.lineMultiple&&e.push(`w:line="${Math.round(240*s.lineMultiple)}" w:lineRule="auto"`),void 0!==s.linePoints&&e.push(`w:line="${Kt(s.linePoints)}" w:lineRule="exact"`),l("w:spacing",e.length?`<w:spacing ${e.join(" ")}/>`:null)}const c=Ot(i,jt);return c?`<w:pPr>${c}</w:pPr>`:""}function nn(e,t){let n=t.getAttribute("data-pstyle");if(!n){const r=/^H([1-6])$/.exec(t.tagName);r?n=Vt(e,`heading ${r[1]}`)??`Heading${r[1]}`:"BLOCKQUOTE"===t.tagName&&(n=Vt(e,"quote"))}return n&&function(e,t){const n=R(e.parts,e.doc.docPath).find(e=>e.type===A.styles);if(!n)return;const r=j(e.doc.docPath,n.target),o=P(e.parts,r);if(!o||new RegExp(`w:styleId="${t}"`).test(o))return;const a=Y[t];a&&M(e.parts,r,o.replace("</w:styles>",`${a.xml}</w:styles>`))}(e,n),n}function rn(e,t,n,r){const o=t.getAttribute("data-docx"),a=o?e.doc.blocks.get(o):void 0;if(a?.xml&&a.xml.startsWith("<w:p")&&(a.fingerprint===Le(t)||t.hasAttribute("data-locked"))&&(t.hasAttribute("data-locked")||(a.numId??null)===(r?.numId??null)&&(a.ilvl??null)===(r?.ilvl??null)))return a.xml;return`<w:p>${tn(0,t,a?.props,nn(e,t),r)}${en(e,n,t)}</w:p>`}var on=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","LI","HR","SECTION","ARTICLE"]);function an(e,t,n,r){const o=function(e,t,n){const r=t.getAttribute("data-num-id");if(r)return r;if(n)return t.setAttribute("data-num-id",n),n;let o;return"OL"===t.tagName?(e.orderedAbstract??=Xt(e,!0),o=Yt(e,e.orderedAbstract,!0)):(e.bulletNum??=Yt(e,Xt(e,!1),!1),o=e.bulletNum),t.setAttribute("data-num-id",o),o}(e,t,n),a=t.getAttribute("data-ilvl"),s=null!==a&&Number(a)>r?Number(a):r+1;let i="";for(const n of Array.from(t.children)){if("UL"===n.tagName||"OL"===n.tagName){i+=an(e,n,o,s);continue}if("LI"!==n.tagName)continue;const t=Array.from(n.children).filter(e=>"UL"===e.tagName||"OL"===e.tagName);i+=rn(e,n,Array.from(n.childNodes).filter(e=>!t.includes(e)),{numId:o,ilvl:s});for(const n of t)i+=an(e,n,o,s)}return i}function sn(e){return Array.from(e.children).some(e=>on.has(e.tagName))}function ln(e,t){let n="",r=[];const o=()=>{r.some(e=>1===e.nodeType||(e.nodeValue??"").trim())&&(n+=`<w:p>${en(e,r,t)}</w:p>`),r=[]};for(const a of Array.from(t.childNodes)){const t=a;if(1!==a.nodeType||!on.has(t.tagName)){r.push(a);continue}o();const s=t.getAttribute("data-docx"),i=s?e.doc.blocks.get(s):void 0;"UL"===t.tagName||"OL"===t.tagName?n+=an(e,t,null,-1):"TABLE"===t.tagName?n+=cn(e,t):t.hasAttribute("data-locked")&&i?.xml?n+=i.xml:"HR"===t.tagName?n+='<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/></w:pBdr></w:pPr></w:p>':sn(t)?n+=ln(e,t):n+=rn(e,t,Array.from(t.childNodes),null)}return o(),n}function cn(e,t){const n=t.getAttribute("data-docx"),r=n?e.doc.blocks.get(n):void 0;if(r?.xml&&(t.hasAttribute("data-locked")||r.fingerprint===Le(t)))return r.xml;const o=Array.from(t.querySelectorAll(":scope > tbody > tr, :scope > tr, :scope > thead > tr, :scope > tfoot > tr")),a=[];let s=0;const i=o.map(t=>{const n=[];let r=0;const o=()=>{for(;a[r]?.left>0;){const e=a[r];e.left--,n.push({continuation:!0,span:e.span,col:r,props:e.props}),r+=e.span}};for(const s of Array.from(t.children).filter(e=>"TD"===e.tagName||"TH"===e.tagName)){o();const t=Math.max(1,Number(s.getAttribute("colspan")??1)),i=Math.max(1,Number(s.getAttribute("rowspan")??1));n.push({cell:s,span:t,col:r}),i>1&&(a[r]={left:i-1,span:t,props:e.doc.blocks.get(s.getAttribute("data-docx")??"")?.props}),r+=t}return o(),s=Math.max(s,r),n}),l=Array.from(t.querySelectorAll(":scope > colgroup > col")),c=[];for(let t=0;t<s;t++){const n=l[t]?Ht(Dt(l[t]).get("width")):void 0;c.push(void 0!==n&&l.length===s?Kt(n):Math.round(20*e.contentWidth/Math.max(s,1)))}return`<w:tbl>${r?.props??'<w:tblPr><w:tblW w:w="5000" w:type="pct"/><w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="auto"/></w:tblBorders><w:tblLook w:val="04A0"/></w:tblPr>'}${`<w:tblGrid>${c.map(e=>`<w:gridCol w:w="${e}"/>`).join("")}</w:tblGrid>`}${o.map((t,n)=>`<w:tr>${e.doc.blocks.get(t.getAttribute("data-docx")??"")?.props??""}${i[n].map(t=>{const n=t.span,r=c.slice(t.col,t.col+n).reduce((e,t)=>e+t,0);if("continuation"in t)return`<w:tc><w:tcPr>${dn(t.props,r,n,"continue",void 0)}</w:tcPr><w:p/></w:tc>`;const o=e.doc.blocks.get(t.cell.getAttribute("data-docx")??""),a=Number(t.cell.getAttribute("rowspan")??1),s=Ft(Dt(t.cell).get("background-color"));let i=ln(e,t.cell);return i.endsWith("</w:p>")||i.endsWith("<w:p/>")||(i+="<w:p/>"),`<w:tc><w:tcPr>${dn(o?.props,r,n,a>1?"restart":null,s)}</w:tcPr>${i}</w:tc>`}).join("")}</w:tr>`).join("")}</w:tbl>`}function dn(e,t,n,r,o){const a=e?b(e):void 0;let s=Ut(e).filter(e=>!["w:tcW","w:gridSpan","w:vMerge"].includes(e.name));s.push({name:"w:tcW",xml:`<w:tcW w:w="${t}" w:type="dxa"/>`}),n>1&&s.push({name:"w:gridSpan",xml:`<w:gridSpan w:val="${n}"/>`}),r&&s.push({name:"w:vMerge",xml:"restart"===r?'<w:vMerge w:val="restart"/>':"<w:vMerge/>"});const i=x(a,"w:shd")?.attrs["w:fill"]?.toLowerCase();return"continue"!==r&&(o?.slice(1)??void 0)!==(i&&/^[0-9a-f]{6}$/.test(i)?i:void 0)&&(s=s.filter(e=>"w:shd"!==e.name),o&&s.push({name:"w:shd",xml:`<w:shd w:val="clear" w:color="auto" w:fill="${o.slice(1).toUpperCase()}"/>`})),Ot(s,zt)}function un(e,t,n,r,o){let a=Ut(t);const s=e.doc.page;if(Object.keys(n).some(e=>n[e]!==s[e])||!t){const e=n.width>n.height,r=`<w:pgSz w:w="${n.width}" w:h="${n.height}"${e?' w:orient="landscape"':""}/>`,o=t?b(t):void 0,s=x(o,"w:pgMar")?.attrs["w:gutter"]??"0",i=`<w:pgMar w:top="${n.top}" w:right="${n.right}" w:bottom="${n.bottom}" w:left="${n.left}" w:header="${n.header}" w:footer="${n.footer}" w:gutter="${s}"/>`;a=a.filter(e=>"w:pgSz"!==e.name&&"w:pgMar"!==e.name),a.push({name:"w:pgSz",xml:r},{name:"w:pgMar",xml:i})}const i=n.width-n.left-n.right,l=(t,n,r)=>{if(!t.editable||n===t.text)return;const o=function(e,t,n){const r=t.split(/\s*\|\s*/),o=r.length>1,a=r.map(e=>e.split(/(\{page\}|\{pages\})/).map(e=>"{page}"===e?'<w:fldSimple w:instr=" PAGE "><w:r><w:t>1</w:t></w:r></w:fldSimple>':"{pages}"===e?'<w:fldSimple w:instr=" NUMPAGES "><w:r><w:t>1</w:t></w:r></w:fldSimple>':e?`<w:r><w:t xml:space="preserve">${w(e)}</w:t></w:r>`:"").join("")).join("<w:r><w:tab/></w:r>");return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:${e} ${N}><w:p>${o?`<w:pPr><w:tabs><w:tab w:val="right" w:pos="${n}"/></w:tabs></w:pPr>`:""}${a}</w:p></w:${e}>`}(r,n,i);if(t.part)return void M(e.parts,t.part,o);const s="hdr"===r?"header":"footer";let l=1;for(;e.parts.has(`word/${s}${l}.xml`);)l++;const c=`word/${s}${l}.xml`;M(e.parts,c,o),I(e.parts,c,`application/vnd.openxmlformats-officedocument.wordprocessingml.${s}+xml`);const d=z(e.parts,e.doc.docPath,"hdr"===r?A.header:A.footer,`${s}${l}.xml`);a.push({name:`w:${s}Reference`,xml:`<w:${s}Reference w:type="default" r:id="${d}"/>`}),t.part=c};l(e.doc.header,r,"hdr"),l(e.doc.footer,o,"ftr");return`<w:sectPr${t?/^<w:sectPr\b([^>]*?)\/?>/.exec(t)?.[1]??"":""}>${Ot(a,It)}</w:sectPr>`}async function pn(e,t,n){const r=new Map(e.parts),o=P(r,e.docPath);if(!o)throw new Error("Not a Word document");const a=b(o),s=x(a,"w:body"),i=x(s,"w:sectPr"),l={doc:e,parts:r,images:n.images??new Map,firstComment:new Map,lastComment:new Map,drawingId:9e4,mediaBySrc:e.insertedMedia??=new Map,contentWidth:(n.page.width-n.page.left-n.page.right)/20,bulletNum:null,orderedAbstract:null};t.querySelectorAll("[data-comment]").forEach(e=>{const t=e.getAttribute("data-comment");l.firstComment.has(t)||l.firstComment.set(t,e),l.lastComment.set(t,e)});let c=ln(l,t);/<\/w:p>\s*$|<w:p\/>\s*$/.test(c)||(c+="<w:p/>"),c=function(e){const t=new Set,n=e.replace(/<w:commentRangeStart\b[^>]*w:id="([^"]+)"[^>]*\/>/g,(e,n)=>t.has(n)?"":(t.add(n),e)),r=new Set,o=[],a=n.split(/(<w:commentRangeEnd\b[^>]*\/>|<w:r>(?:<w:rPr>(?:(?!<\/w:rPr>).)*<\/w:rPr>)?<w:commentReference\b[^>]*\/><\/w:r>)/s);for(let e=a.length-1;e>=0;e--){const t=a[e],n=/^<w:commentRangeEnd\b[^>]*w:id="([^"]+)"/.exec(t)??/^<w:r>.*<w:commentReference\b[^>]*w:id="([^"]+)"/s.exec(t);if(n&&e%2==1){const e=`${t.includes("commentRangeEnd")?"e":"r"}${n[1]}`;if(r.has(e))continue;r.add(e)}o.push(t)}return o.reverse().join("")}(c);const d=un(l,i?o.slice(i.start,i.end):void 0,n.page,n.headerText,n.footerText),u=o.slice(a.start,a.innerStart),p=[!/\bxmlns:r=/.test(u)&&/\br:(id|embed)=/.test(c+d)?' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"':""].join(""),f=(p?o.slice(0,a.innerStart-1)+p+">":o.slice(0,a.innerStart))+o.slice(a.innerStart,s.innerStart)+c+d+o.slice(s.innerEnd);return M(r,e.docPath,f),e.parts=r,e.page={...n.page},e.header={...e.header,text:e.header.editable?n.headerText:e.header.text},e.footer={...e.footer,text:e.footer.editable?n.footerText:e.footer.text},async function(e){const t=new TextEncoder,n=[],r=[];let o=0;for(const[a,s]of e){const e=t.encode(a),i="undefined"==typeof CompressionStream?null:await re(s,new CompressionStream("deflate-raw")),l=null===i||i.length>=s.length,c=l?s:i,d=ne(s),u=new Uint8Array(30+e.length),p=new DataView(u.buffer);p.setUint32(0,67324752,!0),p.setUint16(4,20,!0),p.setUint16(6,2048,!0),p.setUint16(8,l?0:8,!0),p.setUint16(12,33,!0),p.setUint32(14,d,!0),p.setUint32(18,c.length,!0),p.setUint32(22,s.length,!0),p.setUint16(26,e.length,!0),u.set(e,30);const f=new Uint8Array(46+e.length),m=new DataView(f.buffer);m.setUint32(0,33639248,!0),m.setUint16(4,20,!0),m.setUint16(6,20,!0),m.setUint16(8,2048,!0),m.setUint16(10,l?0:8,!0),m.setUint16(14,33,!0),m.setUint32(16,d,!0),m.setUint32(20,c.length,!0),m.setUint32(24,s.length,!0),m.setUint16(28,e.length,!0),m.setUint32(42,o,!0),f.set(e,46),n.push(u,c),r.push(f),o+=u.length+c.length}const a=r.reduce((e,t)=>e+t.length,0),s=new Uint8Array(22),i=new DataView(s.buffer);i.setUint32(0,101010256,!0),i.setUint16(8,e.size,!0),i.setUint16(10,e.size,!0),i.setUint32(12,a,!0),i.setUint32(16,o,!0);const l=new Uint8Array(o+a+22);let c=0;for(const e of[...n,...r,s])l.set(e,c),c+=e.length;return l}(r)}function fn(e,t,n){const r=new Blob([e],{type:n}),o=URL.createObjectURL(r),a=document.createElement("a");a.href=o,a.download=t,a.click(),setTimeout(()=>URL.revokeObjectURL(o),1e4)}import{useEffect as mn,useRef as hn}from"react";import{Icon as wn}from"efficient-shell/icons";import{Button as gn,Checkbox as bn,IconButton as yn,Input as vn}from"efficient-shell/ui";import{jsx as xn,jsxs as $n}from"react/jsx-runtime";function kn({query:e,replacement:t,matchCase:r,current:o,total:a,onQuery:s,onReplacement:i,onMatchCase:l,onStep:c,onReplace:d,onReplaceAll:u,onClose:p}){const f=n(),m=hn(null);return mn(()=>{m.current?.focus(),m.current?.select()},[]),$n("div",{className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-line bg-surface-sunken px-2 py-1",children:[xn("div",{className:"w-40",children:xn(vn,{ref:m,size:"sm","aria-label":f.find,placeholder:f.find,value:e,onChange:e=>s(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),c(!e.shiftKey))}})}),xn("span",{className:"min-w-14 text-xs text-ink-muted","aria-live":"polite",children:e?a?f.matchCount(o+1,a):f.noMatches:""}),xn(yn,{size:"sm",variant:"ghost","aria-label":f.previousMatch,title:f.previousMatch,onClick:()=>c(!1),children:xn(wn,{name:"chevron-up",size:16})}),xn(yn,{size:"sm",variant:"ghost","aria-label":f.nextMatch,title:f.nextMatch,onClick:()=>c(!0),children:xn(wn,{name:"chevron-down",size:16})}),xn("div",{className:"ml-1 w-40",children:xn(vn,{size:"sm","aria-label":f.replaceWith,placeholder:f.replaceWith,value:t,onChange:e=>i(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),d())}})}),xn(gn,{size:"sm",variant:"secondary",onClick:d,children:f.replace}),xn(gn,{size:"sm",variant:"secondary",onClick:u,children:f.replaceAll}),$n("label",{className:"ml-1 flex items-center gap-1 text-xs text-ink-muted",children:[xn(bn,{checked:r,onChange:l,"aria-label":f.matchCase}),f.matchCase]}),xn(yn,{className:"ml-auto",size:"sm",variant:"ghost","aria-label":f.closeFind,title:f.closeFind,onClick:p,children:xn(wn,{name:"close",size:16})})]})}var Cn=class{past=[];future=[];get canUndo(){return this.past.length>0}get canRedo(){return this.future.length>0}record(e){if(this.past[this.past.length-1]?.html===e.html)return;this.past.push(e),this.future=[];let t=this.past.reduce((e,t)=>e+t.html.length,0);for(;this.past.length>1&&(this.past.length>200||t>67108864);)t-=this.past.shift().html.length}undo(e){const t=this.past.pop();return t?(this.future.push(e),t):null}redo(e){const t=this.future.pop();return t?(this.past.push(e),t):null}};function Nn(e,t,n){const r=[];let o=t;for(;o&&o!==e;){const e=o.parentNode;if(!e)return null;r.unshift(Array.prototype.indexOf.call(e.childNodes,o)),o=e}return o===e?{path:r,offset:n}:null}function Sn(e,t){let n=e;for(const e of t.path){const t=n.childNodes[e];if(!t)return null;n=t}const r=3===n.nodeType?(n.nodeValue??"").length:n.childNodes.length;return{node:n,offset:Math.min(t.offset,r)}}import{escapeHtml as An}from"efficient-shell/ui";var Tn="\nhtml,body{margin:0;background:#fff}\n.docs-page [data-comment]{background:none;border:0}\n.docs-page [data-locked]{background:none;box-shadow:none}\n.docs-page [data-page-break]{break-after:page;border:0;margin:0}\n.docs-page [data-break-before]{break-before:page}\n.docs-page tr,.docs-page img{break-inside:avoid}\n";function Ln(e,t){return`\n.docs-sheet{background:#fff;color:#777}\n.docs-sheet-line{border-color:#aaa}\n\n${`\n.docs-page{color:#000;background:#fff;white-space:pre-wrap;overflow-wrap:break-word;outline:none;line-height:1.08;tab-size:36pt;font-family:Calibri,Carlito,Arial,sans-serif;font-size:11pt}\n.docs-page p,.docs-page h1,.docs-page h2,.docs-page h3,.docs-page h4,.docs-page h5,.docs-page h6{margin:0;font:inherit;font-weight:400}\n.docs-page ul,.docs-page ol{margin:0;padding-left:24pt}\n.docs-page ul{list-style-type:disc}.docs-page ol{list-style-type:decimal}\n.docs-page ul ul{list-style-type:circle}.docs-page ul ul ul{list-style-type:square}\n.docs-page a{color:#0563c1;text-decoration:underline}\n.docs-page sub,.docs-page sup{font-size:.66em}\n.docs-page img{max-width:100%}\n.docs-page table{border-collapse:collapse;table-layout:fixed;width:100%}\n.docs-page td,.docs-page th{border:.5pt solid #000;padding:0 5.4pt;vertical-align:top}\n.docs-page table[data-no-borders] td,.docs-page table[data-no-borders] th{border:.5pt dotted #bbb}\n.docs-page td p{margin-bottom:0}\n.docs-page blockquote{margin:0 0 8pt 24pt;font-style:italic}\n.docs-page hr{border:0;border-top:.75pt solid #000;margin:6pt 0}\n.docs-page [data-hidden]{display:none}\n.docs-page [data-page-break]{display:block;height:0;border-top:1pt dashed #999;margin:6pt 0;user-select:none}\n.docs-page [data-comment]{background:#fff2cc;border-bottom:1.5pt solid #e0b000}\n.docs-page [data-locked]{background:#f4f4f4;box-shadow:-5pt 0 0 #bbb;cursor:not-allowed}\n.docs-page ins{color:#c00000;text-decoration:underline}\n.docs-page del{color:#c00000;text-decoration:line-through}\n.docs-page [data-kind="object"]{display:inline-block;background:#f4f4f4;border:.75pt dashed #999;color:#555;padding:1pt 5pt;cursor:not-allowed;white-space:normal}\n.docs-page [data-kind="field"]{background:#ededed}\n.docs-page [data-kind="note"]{vertical-align:super;font-size:.66em}\n.docs-page ::highlight(docs-find){background:#ffe680}\n.docs-page ::highlight(docs-find-current){background:#ff9f1a}\n\n${e.css}`.replaceAll(".docs-page",`.docs-page[data-doc="${t}"]`)}`}function Pn(e,t){const[n,r]=function(e){return e.split(/\s*\|\s*/).map(e=>e.split(/(\{page\}|\{pages\})/).map(e=>"{page}"===e?"counter(page)":"{pages}"===e?"counter(pages)":e?`"${e.replace(/["\\\n\r]/g,"")}"`:"").filter(Boolean).join(" "))}(t),o="font:9pt Calibri,Carlito,Arial,sans-serif;color:#555";return`${n?`@${e}-left{content:${n};${o}}`:""}${r?`@${e}-right{content:${r};${o}}`:""}`}function Mn(e){return Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6")).filter(e=>!e.closest("[data-hidden]")&&""!==(e.textContent??"").trim())}var En=["#000000","#404040","#7f7f7f","#c00000","#ff0000","#ffc000","#00b050","#0070c0","#002060","#7030a0"],Rn=["#ffff00","#00ff00","#00ffff","#ff00ff","#ff0000","#c0c0c0"],jn=["#d9e2f3","#e2efd9","#fff2cc","#fbe4d5","#ededed","#bfbfbf"];function zn(e){if(/^#[0-9a-f]{6}$/i.test(e))return e.toLowerCase();const t=/^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)/i.exec(e);return t?`#${[t[1],t[2],t[3]].map(e=>Number(e).toString(16).padStart(2,"0")).join("")}`:""}import{useState as In}from"react";import{Button as Un,Dialog as On,FormField as Dn,Input as Bn,Select as Fn}from"efficient-shell/ui";import{Fragment as Hn,jsx as Wn,jsxs as qn}from"react/jsx-runtime";function Kn({value:e,headerEditable:t,footerEditable:r,onApply:o,onClose:a}){const s=n(),[i,l]=In(e.page),[c,d]=In(e.header),[u,p]=In(e.footer),f=i.width>i.height,m=H(i),h=W(i),w={a4:"A4",a3:"A3",a5:"A5",letter:s.paperLetter,legal:s.paperLegal},g={normal:s.marginsNormal,narrow:s.marginsNarrow,moderate:s.marginsModerate,wide:s.marginsWide},b={value:"custom",label:s.custom};return Wn(On,{open:!0,onClose:a,title:s.pageSetup,size:"sm",footer:qn(Hn,{children:[Wn(Un,{variant:"secondary",onClick:a,children:s.cancel}),Wn(Un,{variant:"primary",onClick:()=>o({page:i,header:c,footer:u}),children:s.ok})]}),children:qn("div",{className:"space-y-3",children:[Wn(Dn,{label:s.paperSize,children:Wn(Fn,{value:m??"custom",onChange:e=>{"custom"!==e&&l(t=>B(t,e))},options:[...m?[]:[b],...Object.keys(U).map(e=>({value:e,label:w[e]}))]})}),Wn(Dn,{label:s.orientation,children:Wn(Fn,{value:f?"landscape":"portrait",onChange:e=>{"landscape"===e!==f&&l(e=>({...e,width:e.height,height:e.width}))},options:[{value:"portrait",label:s.portrait},{value:"landscape",label:s.landscape}]})}),Wn(Dn,{label:s.margins,children:Wn(Fn,{value:h??"custom",onChange:e=>{"custom"!==e&&l(t=>F(t,e))},options:[...h?[]:[b],...Object.keys(O).map(e=>({value:e,label:g[e]}))]})}),Wn(Dn,{label:s.header,hint:t?s.headerFooterHint:s.headerFooterLocked,children:Wn(Bn,{value:c,disabled:!t,onChange:e=>d(e.target.value)})}),Wn(Dn,{label:s.footer,hint:r?void 0:s.headerFooterLocked,children:Wn(Bn,{value:u,disabled:!r,onChange:e=>p(e.target.value)})})]})})}var Vn=e=>e.querySelectorAll("ul,ol").forEach(e=>e.removeAttribute("data-ilvl"));function Gn(e){const t=e.previousElementSibling,n=e.parentElement;if(!t||"LI"!==t.tagName||!n)return!1;const r=t.lastElementChild;let o;var a;return a=r,"UL"===a?.tagName||"OL"===a?.tagName?o=r:(o=e.ownerDocument.createElement(n.tagName),t.appendChild(o)),o.appendChild(e),Vn(e),!0}function Qn(e){const t=e.parentElement,n=t?.parentElement;if(!t||"LI"!==n?.tagName)return!1;const r=[];for(let t=e.nextElementSibling;t;t=t.nextElementSibling)r.push(t);if(r.length){const n=e.ownerDocument.createElement(t.tagName),o=t.getAttribute("data-num-id");o&&n.setAttribute("data-num-id",o),r.forEach(e=>n.appendChild(e)),e.appendChild(n)}return n.parentElement.insertBefore(e,n.nextSibling),Vn(e),t.children.length||t.remove(),!0}var _n=e=>Array.from(e.querySelectorAll(":scope > tbody > tr, :scope > tr, :scope > thead > tr, :scope > tfoot > tr")),Xn=(e,t)=>Math.max(1,Number(e.getAttribute(t)??1));function Yn(e){const t=_n(e),n=t.map(()=>[]);return t.forEach((e,r)=>{let o=0;for(const a of(e=>Array.from(e.children).filter(e=>"TD"===e.tagName||"TH"===e.tagName))(e)){for(;n[r][o];)o++;const e=Xn(a,"colspan"),s=Xn(a,"rowspan");for(let i=r;i<Math.min(r+s,t.length);i++)for(let t=o;t<o+e;t++)n[i][t]=a;o+=e}}),{table:e,slots:n,cols:Math.max(0,...n.map(e=>e.length))}}function Zn(e,t){for(let n=0;n<e.slots.length;n++){const r=e.slots[n].indexOf(t);if(r>=0)return{row:n,col:r}}return null}function Jn(e){const t=e.createElement("td");return t.innerHTML="<p><br></p>",t}function er(e,t,n){const r=Yn(e),o=Zn(r,t);if(!o)return;const a=_n(e),s=Xn(t,"rowspan"),i=n?o.row+s:o.row,l=e.ownerDocument.createElement("tr"),c=new Set;for(let t=0;t<r.cols;t++){const n=i>0?r.slots[i-1]?.[t]:void 0,o=r.slots[i]?.[t];n&&n===o?c.has(n)||(c.add(n),n.setAttribute("rowspan",String(Xn(n,"rowspan")+1))):l.appendChild(Jn(e.ownerDocument))}const d=a[i];d?d.parentNode.insertBefore(l,d):a[a.length-1].parentNode.appendChild(l)}function tr(e,t,n){const r=Yn(e),o=Zn(r,t);if(!o)return;const a=n?o.col+Xn(t,"colspan"):o.col,s=new Set;r.slots.forEach((t,n)=>{const r=a>0?t[a-1]:void 0,o=t[a];if(r&&r===o)return void(s.has(r)||(s.add(r),r.setAttribute("colspan",String(Xn(r,"colspan")+1))));if(o&&o.parentElement!==_n(e)[n])return;const i=_n(e)[n],l=t.slice(a).find(e=>e.parentElement===i);i.insertBefore(Jn(e.ownerDocument),l??null)}),nr(e,r.cols+1,a,null)}function nr(e,t,n,r){const o=e.querySelector(":scope > colgroup");if(!o)return;const a=Array.from(o.children);if(null!==r&&a[r]?.remove(),null!==n){const t=e.ownerDocument.createElement("col"),r=a[Math.min(n,a.length-1)];r?.getAttribute("style")&&t.setAttribute("style",r.getAttribute("style")),o.insertBefore(t,a[n]??null)}o.children.length!==t&&o.remove()}import{Fragment as rr,jsx as or,jsxs as ar}from"react/jsx-runtime";var sr=["Calibri","Arial","Cambria","Courier New","Georgia","Tahoma","Times New Roman","Verdana"],ir=[8,9,10,10.5,11,12,14,16,18,20,22,24,28,32,36,48,72],lr=[1,1.15,1.5,2,2.5,3],cr=[50,75,90,100,110,125,150,200],dr="p,h1,h2,h3,h4,h5,h6,li,blockquote,pre",ur=/^(https?:|mailto:|tel:)/i,pr={bold:!1,italic:!1,underline:!1,strike:!1,sub:!1,sup:!1,ul:!1,ol:!1,align:"left",font:"",size:null,styleId:null,color:""};function fr({sessionKey:t,doc:r,filename:o,images:a,fileEntries:s,title:i,startsDirty:l,dirty:c,onDirty:d,onOpenFile:u,onNewImageUrl:p,onClose:f,stored:m,onReload:h}){const w=n(),g=ht(),b=Qe().replace(/[^a-zA-Z0-9]/g,""),y=Xe(null),v=Xe(null),x=Xe(null),$=Xe(new Cn),k=Xe(null),C=Xe(null),N=Xe(null),S=Xe(!!l),A=Xe(0),T=Xe(()=>{}),L=Xe(null),P=Xe(0),M=Xe(m?.version??""),E=Xe(null),[R,j]=Ye({page:r.page,header:r.header.text,footer:r.footer.text}),[z,I]=Ye(pr),[U,O]=Ye({undo:!1,redo:!1}),[D,B]=Ye({words:0,pageNow:1}),[F,W]=Ye([0]),[q,K]=Ye([]),[V,G]=Ye(!1),[Q,_]=Ye(100),[X,Y]=Ye(!1),[Z,J]=Ye(!0),[ee,te]=Ye(!1),[ne,re]=Ye({rows:0,cols:0}),[oe,ae]=Ye(null),[se,ie]=Ye(null),[le,ce]=Ye(!1),[de,ue]=Ye(""),[pe,fe]=Ye(""),[me,he]=Ye(!1),[we,ge]=Ye(0),[be,ye]=Ye(0),ve=Xe([]),xe=(R.page.width-R.page.left-R.page.right)/20,$e=e=>!!e&&!!v.current?.contains(e),ke=Ve(()=>{const e=v.current,t=document.getSelection();if(!(e&&t?.anchorNode&&t.focusNode&&$e(t.anchorNode))){const t=k.current;if(!e||!t)return null;const n=Nn(e,t.startContainer,t.startOffset),r=Nn(e,t.endContainer,t.endOffset);return n&&r?{anchor:n,focus:r}:null}const n=Nn(e,t.anchorNode,t.anchorOffset),r=Nn(e,t.focusNode,t.focusOffset);return n&&r?{anchor:n,focus:r}:null},[]),Ce=Ve(e=>{const t=v.current,n=document.getSelection();if(!t||!n||!e)return;const r=Sn(t,e.anchor),o=Sn(t,e.focus);r&&o&&n.setBaseAndExtent(r.node,r.offset,o.node,o.offset)},[]),Ne=Ve(e=>{const t=v.current;if(!t)return;const n=document.getSelection(),r=!e&&!!n&&$e(n.anchorNode);if(document.activeElement!==t&&t.focus({preventScroll:!0}),r&&n?.rangeCount)return void(k.current=n.getRangeAt(0).cloneRange());const o=e??k.current;n&&o&&(n.removeAllRanges(),n.addRange(o),k.current=o.cloneRange())},[]),Se=Ve(()=>{const e=v.current,t=k.current;if(!e||!t)return[];const n=Array.from(e.querySelectorAll(dr)).filter(e=>!e.closest("[data-locked]"));var r;return(t.collapsed?[(r=t.startContainer,(1===r.nodeType?r:r.parentElement)?.closest(dr))].filter(Boolean):n.filter(e=>t.intersectsNode(e))).filter(e=>$e(e)&&!e.closest("[data-locked]"))},[]),Ae=Ve(()=>{cancelAnimationFrame(A.current),A.current=requestAnimationFrame(()=>{const e=v.current;if(!e)return;const t=e.getBoundingClientRect().height/(e.offsetHeight||1)||1,n=e.getBoundingClientRect().top+R.page.top/20*(4/3)*t,r=(R.page.height-R.page.top-R.page.bottom)/20*(4/3),o=[],a=e=>{const r=e.getBoundingClientRect();o.push({top:(r.top-n)/t,height:r.height/t,breakBefore:e.hasAttribute("data-break-before")})};for(const r of Array.from(e.children))"TABLE"===r.tagName?r.querySelectorAll("tr").forEach(a):"UL"===r.tagName||"OL"===r.tagName?r.querySelectorAll("li").forEach(a):a(r),r.querySelectorAll("[data-page-break]").forEach(e=>{const r=e.getBoundingClientRect();o.push({top:(r.bottom-n)/t,height:0,breakBefore:!0})});const s=function(e,t){const n=[0];if(t<=0)return n;let r=0;for(const o of e)if(o.breakBefore&&o.top>r&&(r=o.top,n.push(r)),!(o.top+o.height-r<=t))if(o.height<=t)o.top>r&&(r=o.top,n.push(r));else for(;o.top+o.height-r>t;)r+=t,n.push(r);return n}(o,r);W(e=>e.length===s.length&&e.every((e,t)=>e===s[t])?e:s);const i=document.getSelection();let l=1;if(i?.rangeCount&&$e(i.anchorNode)){const e=i.getRangeAt(0).getClientRects()[0]??i.anchorNode?.getBoundingClientRect?.();if(e){const r=(e.top-n)/t;for(let e=0;e<s.length;e++)s[e]<=r+1&&(l=e+1)}}var c;B({words:(c=Ue(e),(c.match(/[぀-ヿ㐀-鿿豈-﫿]/g)?.length??0)+(c.replace(/[぀-ヿ㐀-鿿豈-﫿]/g," ").match(/\S+/g)?.length??0)),pageNow:l});const d=function(e){return Mn(e).map(e=>({level:Number(e.tagName[1]),text:(e.textContent??"").trim().replace(/\s+/g," ")}))}(e);K(e=>{return n=d,(t=e).length===n.length&&t.every((e,t)=>e.level===n[t].level&&e.text===n[t].text)?e:d;var t,n})})},[R.page]),Te=Ve(()=>{const e=document.getSelection();if(!e?.anchorNode||!$e(e.anchorNode))return;const t=1===e.anchorNode.nodeType?e.anchorNode:e.anchorNode.parentElement;if(!t)return;const n=getComputedStyle(t),r=t.closest(dr),o=e=>{try{return document.queryCommandState(e)}catch{return!1}},a=n.textAlign,s=.75*parseFloat(n.fontSize);I({bold:o("bold"),italic:o("italic"),underline:o("underline"),strike:o("strikeThrough"),sub:o("subscript"),sup:o("superscript"),ul:o("insertUnorderedList"),ol:o("insertOrderedList"),align:"center"===a||"right"===a||"justify"===a?a:"left",font:n.fontFamily.split(",")[0].replace(/["']/g,"").trim(),size:s?Math.round(2*s)/2:null,styleId:r?.getAttribute("data-pstyle")??null,color:zn(n.color)})},[]),Le=async()=>{const e=L.current;if(!e)throw new Error("No page");if(!S.current&&R.page===r.page&&r.source)return r.source;const t=P.current,n=await pn(r,e,{page:R.page,headerText:R.header,footerText:R.footer,images:a});return S.current&&P.current===t&&(r.source=n,S.current=!1,j(e=>({...e,page:r.page}))),n},Pe=et(),Me=Je({debounceMs:1500,maxWaitMs:4e3,save:async()=>{m&&(M.current=await m.store.save(m.id,await Le(),M.current))},onFailure:(t,n)=>{t instanceof e?(Me.stop(),G(!0)):0===n&&mt.error(w.saveFailed)}}),{push:Ee,flush:Re}=Me,je=!!m,ze=Me.state.pending;Ge(()=>{je&&d(ze||V)},[V,je,d,ze]),Ge(()=>()=>{Re()},[Re]);const Ie=Ve(()=>{S.current=!0,P.current+=1,d(!0),je&&Ee(P.current),Ae(),O({undo:$.current.canUndo,redo:$.current.canRedo})},[je,Ae,d,Ee]),Be=Ve(()=>({html:v.current?.innerHTML??"",caret:ke()}),[ke]),Fe=()=>{C.current&&clearTimeout(C.current),C.current=null},He=Ve(e=>{e&&v.current&&(v.current.innerHTML=e.html,v.current.focus({preventScroll:!0}),Ce(e.caret),Fe(),Ie(),Te())},[Ce,Ie,Te]),We=Ve(()=>He($.current.undo(Be())),[He,Be]),qe=Ve(()=>He($.current.redo(Be())),[He,Be]),wt=Ve(e=>{Ne(),Fe(),$.current.record(Be()),e(),Ie(),Te()},[Ie,Te,Ne,Be]),gt=Ve((e,t)=>wt(()=>{document.execCommand(e,!1,t)}),[wt]),bt=e=>wt(()=>{document.execCommand(e);const t=v.current;if(!t)return;const n=document.getSelection(),r=n?.anchorNode??null,o=n?.anchorOffset??0;let a=!1;t.querySelectorAll("p > ul, p > ol").forEach(e=>{const t=e.parentElement;Array.from(t.childNodes).some(t=>t!==e&&(1===t.nodeType||(t.nodeValue??"").trim()))||(t.replaceWith(e),a=!0)}),a&&r&&n?.collapse(r,o)});Ge(()=>{const e=v.current;if(!e)return;L.current=e,e.innerHTML=r.html;try{document.execCommand("defaultParagraphSeparator",!1,"p"),document.execCommand("styleWithCSS",!1,"true")}catch{}e.focus({preventScroll:!0});const t=e.querySelector(dr);t&&document.getSelection()?.collapse(t,0),Ae();const n=t=>"historyUndo"===t.inputType?(t.preventDefault(),void We()):"historyRedo"===t.inputType?(t.preventDefault(),void qe()):(C.current?clearTimeout(C.current):$.current.record({html:e.innerHTML,caret:ke()}),void(C.current=setTimeout(()=>{C.current=null},600))),o=()=>{(()=>{const t=N.current;e.querySelectorAll('font[size="7"]').forEach(e=>{const n=document.createElement("span");for(n.setAttribute("style",`font-size:${t??11}pt`);e.firstChild;)n.appendChild(e.firstChild);e.replaceWith(n),3===n.lastChild?.nodeType&&document.getSelection()?.collapse(n.lastChild,(n.lastChild.nodeValue??"").length)})})(),Ie(),Te()},a=()=>{const e=document.getSelection();e?.rangeCount&&$e(e.anchorNode)&&(k.current=e.getRangeAt(0).cloneRange(),Te(),Ae())};e.addEventListener("beforeinput",n),e.addEventListener("input",o),document.addEventListener("selectionchange",a);const s=new ResizeObserver(()=>Ae());return s.observe(e),()=>{e.removeEventListener("beforeinput",n),e.removeEventListener("input",o),document.removeEventListener("selectionchange",a),s.disconnect(),cancelAnimationFrame(A.current),Fe(),E.current&&clearTimeout(E.current)}},[]),Ge(()=>{Ae()},[Ae]),Ge(()=>{l&&d(!0)},[]);const yt=e=>wt(()=>{const t=ke(),n=e?/^heading ([1-6])$/i.exec(r.styles.find(t=>t.id===e)?.name??"")?.[1]:void 0,o=n?`H${n}`:"P";for(const t of Se()){if("LI"===t.tagName){e?t.setAttribute("data-pstyle",e):t.removeAttribute("data-pstyle");continue}let n=t;if(t.tagName!==o){n=document.createElement(o);for(const e of Array.from(t.attributes))n.setAttribute(e.name,e.value);for(;t.firstChild;)n.appendChild(t.firstChild);t.replaceWith(n)}e?n.setAttribute("data-pstyle",e):n.removeAttribute("data-pstyle")}Ce(t)}),vt=e=>wt(()=>{const t=Se(),n=t.filter(e=>"LI"===e.tagName);if(n.length){const t=document.getSelection(),r=t?.anchorNode??null,o=t?.anchorOffset??0;for(const t of e?n:[...n].reverse())e?Gn(t):Qn(t);return void(r&&t?.collapse(r,o))}for(const n of t){const t=parseFloat(n.style.marginLeft)||0,r=Math.max(0,t+(e?36:-36));n.style.marginLeft=r?`${r}pt`:""}}),xt=e=>gt({left:"justifyLeft",center:"justifyCenter",right:"justifyRight",justify:"justifyFull"}[e]),kt=async e=>{for(const t of e){if(!t.type.startsWith("image/"))continue;const e=new Uint8Array(await t.arrayBuffer()),n=URL.createObjectURL(new Blob([e],{type:t.type}));p(n),a.set(n,{bytes:e,mime:t.type});const r=new Image;r.src=n,await r.decode().catch(()=>{});const o=.75*r.naturalWidth,s=Math.min(o||xe,xe),i=o?s*(r.naturalHeight/r.naturalWidth):0;gt("insertHTML",`<img src="${n}" alt="" style="width:${Math.round(100*s)/100}pt${i?`;height:${Math.round(100*i)/100}pt`:""}">`)}},Ct=async()=>{Ne();const e=k.current?.cloneRange()??null,t=e?.startContainer?1===e.startContainer.nodeType?e.startContainer:e.startContainer.parentElement:null,n=t?.closest("a")??null,r=await pt({title:w.link,message:w.linkPrompt,placeholder:"https://example.com",defaultValue:n?.getAttribute("href")??"",confirmLabel:w.ok,cancelLabel:w.cancel,allowEmpty:!0});if(await new Promise(e=>setTimeout(e,0)),Ne(e),null===r)return;const o=r.trim();if(!o)return void(n&&gt("unlink"));const a=/^[a-z][a-z0-9+.-]*:/i.test(o)?o:`https://${o}`;if(ur.test(a))if(n)wt(()=>{n.setAttribute("href",a)});else if(e?.collapsed){const e=document.createElement("a");e.href=a,e.textContent=o,gt("insertHTML",e.outerHTML)}else gt("createLink",a);else mt.error(w.linkInvalid)},Nt=()=>gt("insertHTML",'<span data-page-break="" contenteditable="false"></span>​'),St=(e,t)=>{te(!1);const n=function(e,t,n,r){const o=e.createElement("table"),a=e.createElement("colgroup");for(let t=0;t<n;t++){const t=e.createElement("col");t.setAttribute("style",`width:${Math.round(r/n*100)/100}pt`),a.appendChild(t)}o.appendChild(a);const s=e.createElement("tbody");for(let r=0;r<t;r++){const t=e.createElement("tr");for(let r=0;r<n;r++)t.appendChild(Jn(e));s.appendChild(t)}return o.appendChild(s),o}(document,e,t,xe);n.setAttribute("data-new",""),gt("insertHTML",`${n.outerHTML}<p><br></p>`);const r=v.current?.querySelector("table[data-new]");if(r){r.removeAttribute("data-new");const e=r.querySelector("td p");e&&document.getSelection()?.collapse(e,0)}};T.current=e=>{kt(e)};const At=e=>{if(!oe)return;const t=oe.el;wt(()=>{const n=.75*t.naturalWidth,r=null===e?n:xe*e,o=t.naturalWidth?t.naturalHeight/t.naturalWidth:.75;t.removeAttribute("width"),t.removeAttribute("height"),t.style.width=Math.round(100*r)/100+"pt",t.style.height=Math.round(r*o*100)/100+"pt"}),ae(null)},Tt=Ve((e,t)=>{const n=ve.current,r=e=>{const t=document.createRange();return t.setStart(e[0].node,e[0].start),t.setEnd(e[e.length-1].node,e[e.length-1].end),t},o=globalThis.CSS?.highlights,a=globalThis.Highlight;o&&a&&(o.set("docs-find",new a(...n.map(r))),o.set("docs-find-current",new a(...n[e]?[r(n[e])]:[]))),t&&n[e]&&n[e][0].node.parentElement?.scrollIntoView({block:"center"})},[]),Lt=()=>{const e=globalThis.CSS?.highlights;e?.delete("docs-find"),e?.delete("docs-find-current")},Pt=Ve((e,t,n)=>{const r=v.current,o=r?Oe(r,e,t):[];ve.current=o,ye(o.length);const a=o.length?Math.min(n,o.length-1):0;ge(a),Tt(a,!0)},[Tt]),Mt=Ve(()=>{const e=ve.current[we];ce(!1),Lt();const t=v.current;t?.focus({preventScroll:!0}),e&&document.getSelection()?.setBaseAndExtent(e[0].node,e[0].start,e[e.length-1].node,e[e.length-1].end),ve.current=[]},[we]),Rt=()=>{const e=document.getSelection(),t=e&&$e(e.anchorNode)?e.toString():"";ce(!0);const n=t&&!t.includes("\n")?t:de;ue(n),setTimeout(()=>Pt(n,me,0),0)},jt=Xe(Mt);jt.current=Mt;const zt=Xe(le);zt.current=le,Ge(()=>ft(()=>!(!zt.current||!y.current?.contains(document.activeElement))&&(jt.current(),!0)),[]),Ge(()=>()=>Lt(),[]),Ge(()=>{const e=e=>{const{key:n,files:r}=e.detail;n===t&&T.current(r)};return window.addEventListener("docs-insert-images",e),()=>window.removeEventListener("docs-insert-images",e)},[t]);const It=m?o:(e=>e.replace(/\.[^.]+$/,"")||e)(o),Ut=`${It}.docx`,Ot=async()=>{try{const e=P.current;fn(await Le(),Ut,"application/vnd.openxmlformats-officedocument.wordprocessingml.document"),m||P.current!==e||d(!1)}catch{mt.error(w.saveFailed)}},Dt=e=>function({title:e,html:t,doc:n,scope:r,page:o,header:a,footer:s}){const i=e=>Math.round(e)/20+"pt",l=`@page{size:${i(o.width)} ${i(o.height)};margin:${i(o.top)} ${i(o.right)} ${i(o.bottom)} ${i(o.left)};${Pn("top",a)}${Pn("bottom",s)}}`;return`<!doctype html><html><head><meta charset="utf-8"><meta name="generator" content="efficient-shell Documents"><title>${An(e)}</title><style>${Ln(n,r)}\n${Tn.replaceAll(".docs-page",`.docs-page[data-doc="${r}"]`)}\n${l}</style></head><body><div class="docs-page" data-doc="${r}">${t}</div></body></html>`}({title:It,html:e,doc:r,scope:b,page:R.page,header:R.header,footer:R.footer}),Bt=()=>{const e=document.createElement("iframe");e.setAttribute("aria-hidden","true"),e.style.cssText="position:fixed;width:0;height:0;border:0;left:-10px;top:-10px",document.body.appendChild(e);const t=e.contentWindow;if(!t)return void e.remove();t.document.open(),t.document.write(Dt(v.current?.innerHTML??"")),t.document.close();const n=()=>{t.focus(),t.print(),setTimeout(()=>e.remove(),6e4)},r=Array.from(t.document.images).filter(e=>!e.complete);r.length?Promise.all(r.map(e=>e.decode().catch(()=>{}))).then(n):n()},Ft=s.length?[...s,{type:"divider",key:"d1"},{key:"save",label:or(mr,{label:w.saveDocx,hint:"⌘S"}),onSelect:()=>{Ot()}}]:[],Ht=[{key:"docx",label:w.saveAsWord,onSelect:()=>{Ot()}},{key:"pdf",label:w.saveAsPdf,onSelect:Bt},{key:"html",label:w.saveAsWeb,onSelect:()=>{(async()=>{const e=document.createElement("div");e.innerHTML=v.current?.innerHTML??"";for(const t of Array.from(e.querySelectorAll("img"))){const e=a.get(t.getAttribute("src")??"");if(!e)continue;let n="";for(let t=0;t<e.bytes.length;t+=32768)n+=String.fromCharCode(...e.bytes.subarray(t,t+32768));t.setAttribute("src",`data:${e.mime};base64,${btoa(n)}`)}e.querySelectorAll("[data-hidden]").forEach(e=>e.remove()),fn(Dt(e.innerHTML),`${It}.html`,"text/html")})()}},{key:"txt",label:w.saveAsText,onSelect:()=>{fn(Ue(v.current),`${It}.txt`,"text/plain")}}],Wt=[{key:"table",label:w.table,onSelect:()=>te(!0)},{key:"image",label:w.image,onSelect:()=>x.current?.click()},{key:"link",label:or(mr,{label:w.link,hint:"⌘K"}),onSelect:()=>{Ct()}},{key:"break",label:or(mr,{label:w.pageBreak,hint:"⌘↵"}),onSelect:Nt},{key:"number",label:w.pageNumber,onSelect:()=>Y(!0)},{key:"line",label:w.horizontalLine,onSelect:()=>gt("insertHorizontalRule")}],qt=[{key:"setup",label:w.pageSetup,onSelect:()=>Y(!0)}],Kt={Title:w.styleTitle,"heading 1":w.styleHeading1,"heading 2":w.styleHeading2,"heading 3":w.styleHeading3,Quote:w.styleQuote},Vt=[{key:"normal",label:w.styleNormal,onSelect:()=>yt(null)},...r.styles.map(e=>({key:e.id,label:Kt[e.name]??e.name,onSelect:()=>yt(e.id)}))],Gt=_e(()=>Array.from(new Set([...r.defaultFont?[r.defaultFont]:[],...sr])),[r.defaultFont]).map(e=>({key:e,label:or("span",{style:{fontFamily:`"${e}"`},children:e}),onSelect:()=>gt("fontName",e)})),Qt=ir.map(e=>({key:String(e),label:String(e),onSelect:()=>(e=>wt(()=>{N.current=e,document.execCommand("styleWithCSS",!1,"false"),document.execCommand("fontSize",!1,"7"),document.execCommand("styleWithCSS",!1,"true");const t=v.current,n=[];if(t.querySelectorAll('font[size="7"]').forEach(t=>{const r=document.createElement("span");for(r.setAttribute("style",`font-size:${e}pt`);t.firstChild;)r.appendChild(t.firstChild);t.replaceWith(r),n.push(r)}),n.length){const e=document.getSelection();e?.setBaseAndExtent(n[0],0,n[n.length-1],n[n.length-1].childNodes.length)}}))(e)})),_t=lr.map(e=>({key:String(e),label:e.toFixed(1.15===e?2:1),onSelect:()=>{return t=e,wt(()=>{for(const e of Se())e.style.lineHeight=String(t)});var t}})),Xt=e=>e.preventDefault(),Yt="rounded px-2 py-0.5 text-xs text-ink-muted hover:bg-line-subtle hover:text-ink",Zt="inline-flex h-7 items-center gap-1 rounded px-2 text-xs text-ink-muted hover:bg-line-subtle hover:text-ink",Jt=or("div",{className:"mx-1 h-4 w-px bg-line"}),en=(e,t,n,r={})=>or(st,{"aria-label":e,title:e,size:"sm",variant:"ghost",onMouseDown:Xt,onClick:n,disabled:r.disabled,...void 0!==r.pressed?{"aria-pressed":r.pressed}:{},children:t}),tn=(e,t,n,r="")=>or(at,{"aria-label":e,align:"start",items:n,triggerClassName:Zt,trigger:ar("span",{title:e,className:`flex items-center justify-between gap-1 ${r}`,children:[or("span",{className:"truncate",children:t}),or(tt,{name:"chevron-down",size:12})]})}),nn=(e,t,n,r,o)=>or(it,{triggerLabel:e,align:"start",triggerClassName:"inline-flex h-7 w-7 flex-col items-center justify-center rounded text-ink-muted hover:bg-line-subtle hover:text-ink",trigger:ar(rr,{children:[t,or("span",{className:"h-0.5 w-4 rounded-sm",style:{background:n}})]}),children:({close:t})=>or(rt,{label:e,value:"",presets:r,clearable:!0,dragWrites:"end",onChange:e=>{"hiliteColor"===o?gt("hiliteColor",e||"transparent"):gt("foreColor",e||En[0]),on(t=>({...t,[o]:e||("hiliteColor"===o?"var(--line)":"var(--ink)")})),t()}})}),[rn,on]=Ye({foreColor:"var(--ink)",hiliteColor:"var(--line)"}),an=H(R.page),sn=an?{a4:"A4",a3:"A3",a5:"A5",letter:w.paperLetter,legal:w.paperLegal}[an]:w.custom,ln=_e(()=>{if(!r.lang)return"";try{return new Intl.DisplayNames(g?[g]:void 0,{type:"language"}).of(r.lang)??r.lang}catch{return r.lang}},[r.lang,g]),cn=R.page.width/20,dn=R.page.top/20,un=R.header.split(/\s*\|\s*/),mn=R.footer.split(/\s*\|\s*/),hn=(e,t)=>e.replace(/\{page\}/g,String(t)).replace(/\{pages\}/g,String(F.length)),wn=r.notices,gn=[wn.comments&&w.noticeComments(wn.comments),wn.tracked&&w.noticeTracked(wn.tracked),wn.objects&&w.noticeObjects(wn.objects),wn.footnotes&&w.noticeFootnotes(wn.footnotes)].filter(Boolean);return ar("div",{ref:y,className:"es-editor docs-frame",onKeyDown:e=>{const t=e.metaKey||e.ctrlKey,n=e.key.toLowerCase(),r=$e(e.target),o=()=>{e.preventDefault(),e.stopPropagation()};if(t&&!e.altKey){if("s"===n)return o(),void(m?Re():Ot());if("o"===n)return o(),void u();if("p"===n)return o(),void Bt();if("f"===n)return o(),void Rt();if("k"===n)return o(),void Ct();if(r){if("z"===n&&!e.shiftKey)return o(),void We();if("z"===n&&e.shiftKey||"y"===n)return o(),void qe();if("b"===n)return o(),void gt("bold");if("i"===n)return o(),void gt("italic");if("u"===n)return o(),void gt("underline");if("Enter"===e.key)return o(),void Nt()}}if(r&&"Tab"===e.key&&!t&&!e.altKey){const t=document.getSelection(),n=t?.anchorNode?1===t.anchorNode.nodeType?t.anchorNode:t.anchorNode.parentElement:null,r=n?.closest("td,th");if(r)return o(),void((e,t)=>{const n=Array.from(e.closest("table").querySelectorAll("td,th")),r=n[n.indexOf(e)+(t?1:-1)];if(r){const e=document.createRange();e.selectNodeContents(r);const t=document.getSelection();t?.removeAllRanges(),t?.addRange(e)}else t&&wt(()=>er(e.closest("table"),e,!0))})(r,!e.shiftKey);if(n?.closest("li"))return o(),void vt(!e.shiftKey);if(!e.shiftKey)return o(),void gt("insertText","\t")}},children:[or("style",{children:Ln(r,b)}),or("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:e=>{e.target.files?.length&&kt(Array.from(e.target.files)),e.target.value=""}}),or(Et,{onClose:f,fileMenu:Ft,name:i,saveState:m?Ze(Me.state,Pe.save):{tone:c?"off-unsaved":"off",label:c?w.noStoreEdited:w.noStoreClean},canUndo:U.undo,canRedo:U.redo,onUndo:We,onRedo:qe,exportControl:or(at,{"aria-label":w.export,align:"end",items:Ht,triggerClassName:"docs-export-trigger",trigger:ar(rr,{children:[or(tt,{name:"download",size:16}),w.export]})})}),V&&ar("div",{className:"docs-conflict",role:"alert",children:[or("span",{children:w.conflict}),or(nt,{variant:"secondary",onClick:h,children:w.reload})]}),ar("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[or(at,{trigger:w.menuInsert,items:Wt,align:"start",triggerClassName:Yt}),or(it,{open:ee,onOpenChange:te,align:"start",triggerLabel:w.table,triggerClassName:"h-5 w-0 overflow-hidden",trigger:or("span",{}),children:ar("div",{className:"p-1",children:[or("div",{className:"mb-1 text-xs text-ink-muted",children:ne.rows?w.tableSize(ne.cols,ne.rows):w.table}),or("div",{className:"grid gap-0.5",style:{gridTemplateColumns:"repeat(8, 1fr)"},onMouseLeave:()=>re({rows:0,cols:0}),children:Array.from({length:48},(e,t)=>{const n=Math.floor(t/8)+1,r=t%8+1,o=n<=ne.rows&&r<=ne.cols;return or("button",{type:"button","aria-label":w.tableSize(r,n),onMouseEnter:()=>re({rows:n,cols:r}),onFocus:()=>re({rows:n,cols:r}),onClick:()=>St(n,r),className:"h-4 w-4 rounded-sm border "+(o?"border-accent-fill bg-accent-tint-strong":"border-line bg-surface")},t)})})]})}),or(at,{trigger:w.menuLayout,items:qt,align:"start",triggerClassName:Yt}),Jt,en(w.print,or(tt,{name:"print",size:16}),Bt),en(w.find,or(tt,{name:"search",size:16}),()=>le?Mt():Rt(),{pressed:le}),Jt,tn(w.paragraphStyle,(e=>{if(!e)return w.styleNormal;const t=r.styles.find(t=>t.id===e);return t?Kt[t.name]??t.name:e})(z.styleId),Vt,"w-20"),tn(w.font,z.font||r.defaultFont||"Calibri",Gt,"w-20"),tn(w.fontSize,z.size??r.defaultSize??11,Qt),Jt,en(w.bold,or(tt,{name:"bold",size:16}),()=>gt("bold"),{pressed:z.bold}),en(w.italic,or(tt,{name:"italic",size:16}),()=>gt("italic"),{pressed:z.italic}),en(w.underline,or(tt,{name:"underline",size:16}),()=>gt("underline"),{pressed:z.underline}),en(w.strikethrough,or(tt,{name:"strike",size:16}),()=>gt("strikeThrough"),{pressed:z.strike}),en(w.superscript,or(tt,{name:"superscript",size:16}),()=>gt("superscript"),{pressed:z.sup}),en(w.subscript,or(tt,{name:"subscript",size:16}),()=>gt("subscript"),{pressed:z.sub}),nn(w.textColor,or(tt,{name:"text-color",size:14}),rn.foreColor,En,"foreColor"),nn(w.highlight,or(tt,{name:"palette",size:14}),rn.hiliteColor,Rn,"hiliteColor"),en(w.clearFormatting,or(tt,{name:"clear-marks",size:16}),()=>wt(()=>{document.execCommand("removeFormat");for(const e of Se())e.style.removeProperty("text-align"),e.style.removeProperty("line-height"),e.style.removeProperty("margin-left")})),Jt,en(w.bulletedList,or(tt,{name:"list",size:16}),()=>bt("insertUnorderedList"),{pressed:z.ul}),en(w.numberedList,or(tt,{name:"numbered-list",size:16}),()=>bt("insertOrderedList"),{pressed:z.ol}),en(w.decreaseIndent,or(tt,{name:"chevron-double-left",size:16}),()=>vt(!1)),en(w.increaseIndent,or(tt,{name:"chevron-double-right",size:16}),()=>vt(!0)),Jt,en(w.alignLeft,or(tt,{name:"align-left",size:16}),()=>xt("left"),{pressed:"left"===z.align}),en(w.alignCenter,or(tt,{name:"align-center",size:16}),()=>xt("center"),{pressed:"center"===z.align}),en(w.alignRight,or(tt,{name:"align-right",size:16}),()=>xt("right"),{pressed:"right"===z.align}),en(w.justify,or(tt,{name:"align-justify",size:16}),()=>xt("justify"),{pressed:"justify"===z.align}),or(at,{"aria-label":w.lineSpacing,align:"start",items:_t,triggerClassName:Zt,trigger:ar("span",{title:w.lineSpacing,className:"flex items-center gap-0.5",children:[or(tt,{name:"line-spacing",size:16}),or(tt,{name:"chevron-down",size:12})]})})]}),Z&&gn.length>0&&ar("div",{role:"status",className:"flex shrink-0 items-center gap-2 border-b border-status-warning-line bg-status-warning-soft px-3 py-1 text-xs text-status-warning-soft-ink",children:[or(tt,{name:"info",size:14}),or("span",{className:"min-w-0 flex-1",children:w.noticeLead(gn)}),or(st,{size:"sm",variant:"ghost",ink:"inherit","aria-label":w.dismiss,title:w.dismiss,onClick:()=>J(!1),children:or(tt,{name:"close",size:14})})]}),le&&or(kn,{query:de,replacement:pe,matchCase:me,current:we,total:be,onQuery:e=>{ue(e),Pt(e,me,0)},onReplacement:fe,onMatchCase:e=>{he(e),Pt(de,e,0)},onStep:e=>{const t=ve.current.length;if(!t)return;const n=(we+(e?1:-1)+t)%t;ge(n),Tt(n,!0)},onReplace:()=>{const e=ve.current[we];e&&($.current.record(Be()),De(e,pe),Ie(),Pt(de,me,we))},onReplaceAll:()=>{const e=ve.current;if(e.length){$.current.record(Be());for(let t=e.length-1;t>=0;t--)De(e[t],pe);Ie(),mt.success(w.replacedCount(e.length)),Pt(de,me,0)}},onClose:Mt}),ar("div",{className:"docs-body",children:[ar("div",{className:"docs-centre",children:[or("div",{className:"min-h-0 flex-1 overflow-auto bg-surface-sunken px-6 py-6",children:ar("div",{className:"docs-sheet relative mx-auto shadow",style:{width:`${cn}pt`,zoom:Q/100,minHeight:R.page.height/20+"pt"},children:[R.header&&ar("div",{className:"pointer-events-none absolute flex justify-between gap-4 text-xs","aria-hidden":"true",style:{top:R.page.header/20+"pt",left:R.page.left/20+"pt",right:R.page.right/20+"pt"},children:[or("span",{children:hn(un[0],1)}),void 0!==un[1]&&or("span",{children:hn(un[1],1)})]}),or("div",{ref:v,contentEditable:!0,suppressContentEditableWarning:!0,spellCheck:!0,lang:r.lang,role:"textbox","aria-multiline":"true","aria-label":o,"data-doc":b,onPaste:e=>{(async e=>{const t=Array.from(e.clipboardData?.items??[]).filter(e=>"file"===e.kind&&e.type.startsWith("image/")).map(e=>e.getAsFile()).filter(e=>!!e),n=e.clipboardData?.getData("text/html");if(n){e.preventDefault();const t=document.createElement("div");t.innerHTML=Ke(n);for(const e of Array.from(t.querySelectorAll("img"))){const t=e.getAttribute("src")??"";if(t.startsWith("blob:")&&!a.has(t))try{const e=await(await fetch(t)).blob();a.set(t,{bytes:new Uint8Array(await e.arrayBuffer()),mime:e.type})}catch{e.remove()}}return void gt("insertHTML",t.innerHTML)}t.length&&(e.preventDefault(),kt(t))})(e)},onClick:e=>{const t=e.target;if("IMG"===t.tagName&&null===t.closest('[contenteditable="false"]')&&!t.getAttribute("contenteditable"))return e.preventDefault(),void ae({x:e.clientX,y:e.clientY,el:t});const n=t.closest("a");if(n&&(e.metaKey||e.ctrlKey)){const e=n.getAttribute("href")??"";ur.test(e)&&window.open(e,"_blank","noopener,noreferrer")}},onContextMenu:e=>{const t=e.target.closest?.("td,th");t&&!e.shiftKey&&!t.closest("[data-locked]")&&$e(t)&&(e.preventDefault(),ie({x:e.clientX,y:e.clientY,cell:t}))},className:"docs-page",style:{paddingTop:`${dn}pt`,paddingRight:R.page.right/20+"pt",paddingBottom:R.page.bottom/20+"pt",paddingLeft:R.page.left/20+"pt",minHeight:R.page.height/20+"pt",boxSizing:"border-box"}}),F.slice(1).map((e,t)=>or("div",{className:"docs-sheet-line pointer-events-none absolute left-0 right-0 border-t border-dashed","aria-hidden":"true",style:{top:`calc(${dn}pt + ${e}px)`},children:or("span",{className:"docs-sheet absolute right-1 -top-2 px-1 text-2xs",children:w.pageLabel(t+2)})},e)),R.footer&&ar("div",{className:"pointer-events-none absolute flex justify-between gap-4 text-xs","aria-hidden":"true",style:{bottom:R.page.footer/20+"pt",left:R.page.left/20+"pt",right:R.page.right/20+"pt"},children:[or("span",{children:hn(mn[0],F.length)}),void 0!==mn[1]&&or("span",{children:hn(mn[1],F.length)})]})]})}),ar("div",{className:"flex shrink-0 items-center gap-2 border-t border-line bg-surface-sunken px-3 py-1 text-xs text-ink-muted",children:[or("span",{children:w.pageOf(Math.min(D.pageNow,F.length),F.length)}),or("span",{children:w.wordCount(D.words)}),or("span",{children:sn}),ln&&or("span",{children:ln}),ar("span",{className:"ml-auto flex items-center gap-1",children:[or(nt,{size:"sm",variant:"ghost","aria-label":w.zoomOut,onClick:()=>_(e=>[...cr].reverse().find(t=>t<e)??e),children:"−"}),ar("span",{className:"w-9 text-center tabular-nums",children:[Q,"%"]}),or(nt,{size:"sm",variant:"ghost","aria-label":w.zoomIn,onClick:()=>_(e=>cr.find(t=>t>e)??e),children:"+"})]})]})]}),or($t,{page:R.page,onPage:e=>{j(t=>({...t,page:e})),Ie()},onMorePageSetup:()=>Y(!0),colour:z.color,onColour:e=>{I(t=>({...t,color:e})),on(t=>({...t,foreColor:e})),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{E.current=null,gt("foreColor",e)},150)},outline:q,onHeading:e=>{const t=v.current;t&&Mn(t)[e]?.scrollIntoView({block:"start"})}})]}),X&&or(Kn,{value:R,headerEditable:r.header.editable,footerEditable:r.footer.editable,onClose:()=>Y(!1),onApply:e=>{j(e),Y(!1),Ie()}}),oe&&ar(lt,{minWidth:150,portal:!0,style:{position:"fixed",left:oe.x,top:oe.y},onClose:()=>ae(null),children:[or(ut,{children:w.imageWidth}),or(dt,{onClick:()=>At(.25),children:"25%"}),or(dt,{onClick:()=>At(.5),children:"50%"}),or(dt,{onClick:()=>At(.75),children:"75%"}),or(dt,{onClick:()=>At(1),children:"100%"}),or(dt,{onClick:()=>At(null),children:w.imageOriginalSize}),or(ct,{}),or(dt,{danger:!0,onClick:()=>{if(!oe)return;const e=oe.el;wt(()=>{e.remove()}),ae(null)},children:w.imageRemove})]}),se&&or(ot,{at:{x:se.x,y:se.y},owner:se.cell,onClose:()=>ie(null),items:(e=>{const t=e.closest("table"),n=(e,t,n,r={})=>({key:e,label:t,onSelect:()=>wt(n),...r}),r=(e=>{const t=k.current;return t?Array.from(e.querySelectorAll("td,th")).filter(n=>n.closest("table")===e&&t.intersectsNode(n)):[]})(t);return[n("above",w.rowAbove,()=>er(t,e,!1)),n("below",w.rowBelow,()=>er(t,e,!0)),n("left",w.columnLeft,()=>tr(t,e,!1)),n("right",w.columnRight,()=>tr(t,e,!0)),{type:"divider",key:"d1"},n("merge",w.mergeCells,()=>{(function(e,t){if(t.length<2)return!1;const n=Yn(e);let r=1/0,o=1/0,a=-1,s=-1;for(const e of t){const t=Zn(n,e);if(!t)return!1;r=Math.min(r,t.row),o=Math.min(o,t.col),a=Math.max(a,t.row+Xn(e,"rowspan")-1),s=Math.max(s,t.col+Xn(e,"colspan")-1)}const i=new Set;for(let e=r;e<=a;e++)for(let t=o;t<=s;t++){const r=n.slots[e]?.[t];r&&i.add(r)}for(const e of i){const t=Zn(n,e);if(t.row<r||t.col<o||t.row+Xn(e,"rowspan")-1>a||t.col+Xn(e,"colspan")-1>s)return!1}const l=n.slots[r][o];for(const e of i)if(e!==l){if((e.textContent??"").trim())for(;e.firstChild;)l.appendChild(e.firstChild);e.remove()}return l.setAttribute("colspan",String(s-o+1)),l.setAttribute("rowspan",String(a-r+1)),s===o&&l.removeAttribute("colspan"),a===r&&l.removeAttribute("rowspan"),!0})(t,r)||mt.error(w.mergeFailed)},{disabled:r.length<2}),{type:"submenu",key:"shade",label:w.cellShading,items:[...jn.map(t=>({key:t,label:ar("span",{className:"flex items-center gap-2",children:[or("span",{className:"h-3 w-5 rounded-sm border border-line",style:{background:t}}),t.toUpperCase()]}),onSelect:()=>wt(()=>{for(const n of r.length?r:[e])n.style.backgroundColor=t})})),{key:"none",label:w.noColor,onSelect:()=>wt(()=>{for(const t of r.length?r:[e])t.style.removeProperty("background-color")})}]},{type:"divider",key:"d2"},n("delRow",w.deleteRow,()=>{!function(e,t){const n=Yn(e),r=Zn(n,t);if(!r)return!1;const o=_n(e);if(1===o.length)return e.remove(),!1;const a=new Set;for(let e=0;e<n.cols;e++){const t=n.slots[r.row][e];if(!t||a.has(t))continue;a.add(t);const s=Xn(t,"rowspan");if(1!==s)if(t.parentElement===o[r.row]){const a=o[r.row+1],i=n.slots[r.row+1].slice(e+Xn(t,"colspan")).find(e=>e.parentElement===a);t.setAttribute("rowspan",String(s-1)),a.insertBefore(t,i??null)}else t.setAttribute("rowspan",String(s-1))}o[r.row].remove()}(t,e)}),n("delCol",w.deleteColumn,()=>{!function(e,t){const n=Yn(e),r=Zn(n,t);if(!r)return!1;if(1===n.cols)return e.remove(),!1;const o=new Set;for(const e of n.slots){const t=e[r.col];if(!t||o.has(t))continue;o.add(t);const n=Xn(t,"colspan");n>1?t.setAttribute("colspan",String(n-1)):t.remove()}nr(e,n.cols-1,null,r.col)}(t,e)}),n("delTable",w.deleteTable,()=>{t.remove()},{danger:!0})]})(se.cell)})]})}function mr({label:e,hint:t}){return ar("span",{className:"flex w-full items-center justify-between gap-4",children:[or("span",{children:e}),or("span",{className:"text-2xs text-ink-faint",children:t})]})}import{useEffect as hr,useRef as wr,useState as gr}from"react";import{Icon as br}from"efficient-shell/icons";import{Button as yr,IconButton as vr,registerModalEscapeInterceptor as xr,toast as $r}from"efficient-shell/ui";var kr={LF:"\n",CRLF:"\r\n",CR:"\r"};function Cr(e,t){let n=1,r=-1;for(let o=e.indexOf("\n");o>=0&&o<t;o=e.indexOf("\n",o+1))n++,r=o;return{line:n,col:t-r}}function Nr(e){let t=1;for(let n=e.indexOf("\n");n>=0;n=e.indexOf("\n",n+1))t++;return t}import{jsx as Sr,jsxs as Ar}from"react/jsx-runtime";function Tr({filename:e,decoded:t,bytes:r,fileEntries:o,title:a,dirty:s,onDirty:i,onOpenFile:l,onClose:c}){const d=n(),u=wr(null),p=wr(null),f=wr(t.text),m=wr(!1),[h,w]=gr(!0),[g,b]=gr(!1),[y,v]=gr({line:1,col:1,lines:Nr(t.text)}),[x,$]=gr(!1),[k,C]=gr(""),[N,S]=gr(""),[A,T]=gr(!1),[L,P]=gr(0),[M,E]=gr([]),R=()=>p.current?.value??"",j=wr(null),[z,I]=gr(0),U=()=>{j.current&&p.current&&(j.current.scrollTop=p.current.scrollTop,j.current.scrollLeft=p.current.scrollLeft)};hr(()=>{const e=j.current?.querySelector("[data-current]"),t=p.current;if(!e||!t)return;const n=e.offsetTop-t.clientHeight/3;(e.offsetTop<t.scrollTop||e.offsetTop>t.scrollTop+t.clientHeight-42)&&(t.scrollTop=Math.max(0,n)),h||(t.scrollLeft=Math.max(0,e.offsetLeft-t.clientWidth/2)),U()},[z,L,M,h]);const O=()=>{const e=p.current;e&&v({...Cr(e.value,e.selectionStart),lines:Nr(e.value)})},D=(e=k,t=A)=>{const n=function(e,t,n){if(!t)return[];const r=n?e:e.toLowerCase(),o=n?t:t.toLowerCase(),a=r.length===e.length?r:e,s=[];for(let e=a.indexOf(o);e>=0;e=a.indexOf(o,e+Math.max(o.length,1)))s.push(e);return s}(R(),e,t);return E(n),n},B=(e,t,n=k)=>{const r=p.current;if(!r||!e.length)return;const o=(t%e.length+e.length)%e.length;P(o),r.setSelectionRange(e[o],e[o]+n.length),I(e=>e+1)},F=()=>{fn(m.current?function(e,t,n){const r=e.replace(/\n/g,kr[n]);if("utf-16le"===t||"utf-16be"===t){const e=new Uint8Array(2+2*r.length),n=new DataView(e.buffer),o="utf-16le"===t;n.setUint16(0,65279,o);for(let e=0;e<r.length;e++)n.setUint16(2+2*e,r.charCodeAt(e),o);return e}const o=(new TextEncoder).encode(r);if("utf-8-bom"!==t)return o;const a=new Uint8Array(o.length+3);return a.set([239,187,191]),a.set(o,3),a}(R(),t.encoding,t.eol):r,e,"text/plain"),m.current&&"windows-1252"===t.encoding&&$r.info(d.savedAsUtf8),f.current=R(),i(!1)},H=()=>{m.current=!0,b(!0),i(R()!==f.current),O(),x&&D()},W=e=>{document.execCommand("insertText",!1,e)||p.current?.setRangeText(e,p.current.selectionStart,p.current.selectionEnd,"end"),H()},q=e=>{p.current?.focus(),document.execCommand(e)},K=()=>{$(!1),p.current?.focus()};hr(()=>{p.current?.focus(),p.current?.setSelectionRange(0,0)},[]);const V=wr(x);V.current=x,hr(()=>xr(()=>!(!V.current||!u.current?.contains(document.activeElement))&&(K(),!0)),[]);const G=[...o,{type:"divider",key:"d1"},{key:"save",label:d.saveKeepType,onSelect:F}],Q=s?d.noStoreEdited:d.noStoreClean;return Ar("div",{ref:u,className:"es-editor docs-frame",onKeyDown:e=>{const t=e.metaKey||e.ctrlKey,n=e.key.toLowerCase();if(t&&"s"===n)e.preventDefault(),F();else if(t&&"o"===n)e.preventDefault(),l();else if(t&&"f"===n){e.preventDefault(),$(!0);const t=p.current,n=t?t.value.slice(t.selectionStart,t.selectionEnd):"";n&&!n.includes("\n")&&(C(n),D(n))}else"Tab"!==e.key||t||e.shiftKey||e.target!==p.current||(e.preventDefault(),W("\t"))},children:[Sr(Et,{onClose:c,fileMenu:G,name:a,saveState:{tone:s?"off-unsaved":"off",label:Q},canUndo:g,canRedo:g,onUndo:()=>q("undo"),onRedo:()=>q("redo"),exportControl:Sr(yr,{variant:"secondary",leftIcon:Sr(br,{name:"download",size:16}),onClick:F,children:d.export})}),Ar("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[Sr(vr,{size:"sm",variant:"ghost","aria-label":d.find,title:d.find,"aria-pressed":x,onClick:()=>$(e=>!e),children:Sr(br,{name:"search",size:16})}),Sr(vr,{size:"sm",variant:"ghost","aria-label":d.wrapLines,title:d.wrapLines,"aria-pressed":h,onClick:()=>w(e=>!e),children:Sr(br,{name:"wrap",size:16})})]}),x&&Sr(kn,{query:k,replacement:N,matchCase:A,current:L,total:M.length,onQuery:e=>{C(e);const t=D(e);P(0),B(t,0,e)},onReplacement:S,onMatchCase:e=>{T(e);const t=D(k,e);P(0),B(t,0)},onStep:e=>B(M,L+(e?1:-1)),onReplace:()=>{const e=p.current;if(!e||!M.length)return;e.focus(),e.setSelectionRange(M[L],M[L]+k.length),W(N);const t=D();B(t,L)},onReplaceAll:()=>{const e=p.current;if(!e||!M.length)return;const t=M.length;e.focus();for(let t=M.length-1;t>=0;t--)e.setSelectionRange(M[t],M[t]+k.length),W(N);D(),P(0),$r.success(d.replacedCount(t))},onClose:K}),Ar("div",{className:"relative min-h-0 flex-1 bg-surface",children:[x&&k&&M.length>0&&M.length<=2e3&&Sr("div",{ref:j,"aria-hidden":"true",style:{lineHeight:"21px",scrollbarGutter:"stable"},className:"pointer-events-none absolute inset-0 overflow-hidden p-4 font-mono text-sm text-transparent "+(h?"whitespace-pre-wrap break-words":"whitespace-pre"),children:(()=>{const e=R(),t=[];let n=0;return M.forEach((r,o)=>{t.push(e.slice(n,r)),n=r+k.length,t.push(Sr("mark",{...o===L?{"data-current":""}:{},className:"rounded-sm text-transparent "+(o===L?"bg-status-warning-line":"bg-status-warning-soft"),children:e.slice(r,n)},r))}),t.push(e.slice(n)),t})()}),Sr("textarea",{ref:p,defaultValue:t.text,"aria-label":e,spellCheck:!1,wrap:h?"soft":"off",onInput:H,onSelect:O,onKeyUp:O,onClick:O,onScroll:U,style:{lineHeight:"21px",scrollbarGutter:"stable"},className:"absolute inset-0 h-full w-full resize-none bg-transparent p-4 font-mono text-sm text-ink outline-none "+(h?"whitespace-pre-wrap break-words":"overflow-x-auto whitespace-pre")})]}),Ar("div",{className:"flex shrink-0 items-center gap-2 border-t border-line bg-surface-sunken px-3 py-1 text-xs text-ink-muted",children:[Sr("span",{children:e}),Sr("span",{children:d.lineColumn(y.line,y.col)}),Sr("span",{children:d.lineCount(y.lines)}),Sr("span",{children:t.eol})]})]})}import{jsx as Lr,jsxs as Pr}from"react/jsx-runtime";var Mr=new Set(["txt","md","markdown","csv","tsv","log","json","xml","html","htm","css","js","jsx","ts","tsx","py","rb","go","rs","java","c","h","cpp","hpp","sh","bash","yml","yaml","toml","ini","conf","env","sql"]),Er=`${Array.from(Mr,e=>`.${e}`).join(",")},.docx,text/*`,Rr=/^<!doctype html><meta charset="utf-8"><title>[^<]*<\/title>(?!<body style="font-family:ui-monospace)/,jr=()=>"undefined"!=typeof navigator&&navigator.language||"en-AU";function zr({value:e,onRename:t}){const o=n(),[s,i]=a(e);return r(()=>i(e),[e]),Lr("div",{className:"docs-title",children:Lr(d,{"aria-label":o.documentName,value:s,onChange:e=>i(e.target.value),onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()},onBlur:()=>{const n=s.trim();i(n||e),n&&n!==e&&t(n)}})})}function Ir({documentId:e,onClose:d}){const m=n(),{store:h}=t(),w=h&&e?e:null,g=o([]),b=o(0),y=o(null),v={textBox:m.objectTextBox,chart:m.objectChart,diagram:m.objectDiagram,equation:m.objectEquation,picture:m.objectPicture,object:m.objectOther,contents:m.objectField},x=e=>({labels:v,imageUrl:(t,n)=>{const r=URL.createObjectURL(new Blob([t],{type:n}));return g.current.push(r),e.set(r,{bytes:t,mime:n}),r}}),$=e=>{const t=new Map;return{key:++b.current,kind:"rich",filename:e,images:t,doc:je(J(jr()),null,x(t))}},[k,C]=a(()=>w?null:$(m.untitled)),[N,S]=a(!1),[A,T]=a(0),[L,P]=a(!1),[M,E]=a(!1),[R,j]=a(!1);i(R),r(()=>()=>{g.current.forEach(e=>URL.revokeObjectURL(e))},[]),r(()=>{if(!h||!w)return;let e=!0;return S(!1),(async()=>{const t=await h.get(w),n=new Map,r=t.bytes?.length?await Re(t.bytes,x(n)):je(J(jr()),null,x(n));e&&z({key:++b.current,kind:"rich",doc:r,images:n,filename:t.title,stored:{id:t.id,version:t.version}})})().catch(()=>{e&&S(!0)}),()=>{e=!1}},[h,w,A]);const z=e=>{const t=g.current;if(g.current=[],"rich"===e.kind)for(const t of e.images.keys())g.current.push(t);C(e),j(!1),setTimeout(()=>t.filter(e=>!g.current.includes(e)).forEach(e=>URL.revokeObjectURL(e)),0)},I=async()=>!R||p({title:m.discardTitle(k?.filename??""),message:m.discardMessage,confirmLabel:m.discard,cancelLabel:m.keepEditing}),U=async e=>{if(!await I())return;const t=(e.name.split(".").pop()||"").toLowerCase();P(!0);try{if("docx"===t){const t=new Map,n=new Uint8Array(await e.arrayBuffer());try{const r=await Re(n,x(t));z({key:++b.current,kind:"rich",doc:r,filename:e.name,images:t})}catch{f.error(m.cannotRead(e.name))}}else if("doc"===t)f.error(m.legacyDoc);else if(Mr.has(t)||e.type.startsWith("text/")){const n=new Uint8Array(await e.arrayBuffer()),r=function(e){let t,n="utf-8";if(239===e[0]&&187===e[1]&&191===e[2])n="utf-8-bom",t=new TextDecoder("utf-8").decode(e.subarray(3));else if(255===e[0]&&254===e[1])n="utf-16le",t=new TextDecoder("utf-16le").decode(e.subarray(2));else if(254===e[0]&&255===e[1])n="utf-16be",t=new TextDecoder("utf-16be").decode(e.subarray(2));else try{t=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{n="windows-1252",t=new TextDecoder("windows-1252").decode(e)}const r=t.match(/\r\n/g)?.length??0,o=(t.match(/\n/g)?.length??0)-r,a=(t.match(/\r/g)?.length??0)-r,s=r>o&&r>=a?"CRLF":a>o?"CR":"LF";return{text:t.replace(/\r\n?/g,"\n"),encoding:n,eol:s}}(n);if("html"!==t&&"htm"!==t||!Rr.test(r.text))z({key:++b.current,kind:"text",decoded:r,bytes:n,filename:e.name});else{const t=new Map,n=je(J(jr()),null,x(t));n.html=Ke(r.text)||n.html,Pe(n),z({key:++b.current,kind:"rich",doc:n,images:t,filename:e.name.replace(/\.[^.]+$/,".docx"),imported:!0}),f.info(m.openedOldSave)}}else f.error(m.unsupported(t))}finally{P(!1)}},O=async()=>{await I()&&(j(!1),y.current?.click())},D="rich"===k?.kind&&!!k.stored,B=()=>f.info(m.openFromFiles),F=[{key:"new",label:m.newDocument,onSelect:()=>{(async()=>{await I()&&z($(m.untitled))})()}},{key:"open",label:Pr("span",{className:"flex w-full items-center justify-between gap-4",children:[Lr("span",{children:m.open}),Lr("span",{className:"text-2xs text-ink-faint",children:"⌘O"})]}),onSelect:()=>{O()}}],H=k&&Lr(zr,{value:k.filename,onRename:e=>{const t=k?.filename??e;C(t=>t?{...t,filename:e}:t),h&&"rich"===k?.kind&&k.stored&&h.rename(k.stored.id,e).catch(()=>{f.error(m.renameFailed),C(e=>e?{...e,filename:t}:e)})}});return Pr("div",{className:"relative flex h-full flex-col bg-surface text-ink",onDragOver:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),M||E(!0))},onDragLeave:e=>{e.currentTarget===e.target&&E(!1)},onDrop:e=>{if(!e.dataTransfer.types.includes("Files"))return;e.preventDefault(),E(!1);const t=Array.from(e.dataTransfer.files??[]);"rich"===k?.kind&&t.length&&t.every(e=>e.type.startsWith("image/"))?window.dispatchEvent(new CustomEvent("docs-insert-images",{detail:{key:k.key,files:t}})):t[0]&&D?B():t[0]&&U(t[0])},children:[k&&Lr(s,{title:`${W=k.filename,W.length>24?`${W.slice(0,23)}…`:W}${R?" •":""} - Documents`}),Lr("input",{ref:y,type:"file",accept:Er,className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&U(t),e.target.value=""}}),N?Lr("div",{className:"docs-open-failed",children:Lr(c,{title:m.openFailed,children:d&&Lr(l,{onClick:d,children:m.backToFiles})})}):L||!k?Lr(u,{size:"sm",padding:"",className:"h-full",label:m.loading}):"rich"===k.kind?Lr(fr,{sessionKey:k.key,doc:k.doc,filename:k.filename,images:k.images,fileEntries:D?[]:F,title:H,startsDirty:k.imported,dirty:R,onDirty:j,onOpenFile:()=>{D?B():O()},onNewImageUrl:e=>{g.current.push(e)},onClose:d,stored:h&&k.stored?{store:h,...k.stored}:void 0,onReload:()=>{j(!1),C(null),T(e=>e+1)}},k.key):Lr(Tr,{filename:k.filename,decoded:k.decoded,bytes:k.bytes,fileEntries:F,title:H,dirty:R,onDirty:j,onOpenFile:()=>{O()},onClose:d},k.key),M&&Lr("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center border-4 border-dashed border-accent-fill bg-accent-tint",children:Lr("div",{className:"rounded-md bg-accent-fill px-4 py-2 text-sm font-medium text-on-accent",children:m.dropHint})})]});var W}function Ur({id:e,onClose:t}){return Lr(Ir,{documentId:e,onClose:t})}export{Ur as OpenDocument,Ir as default};