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.
- package/dist/Documents-XZ3AZVHI.js +1 -0
- package/dist/Spreadsheet-U35IV6OG.js +1 -0
- package/dist/chunk-3SRMKGQW.js +1 -0
- package/dist/chunk-CED4ECIS.js +1 -0
- package/dist/chunk-ZKFPXX72.js +1 -0
- package/dist/documents/documents.css +14 -0
- package/dist/documents/index.d.ts +16 -2
- package/dist/documents/index.js +1 -1
- package/dist/spreadsheet/index.d.ts +130 -3
- package/dist/spreadsheet/index.js +1 -1
- package/dist/spreadsheet/spreadsheet.css +14 -0
- package/package.json +4 -3
- package/dist/Documents-NVHYOCW6.js +0 -1
- package/dist/Spreadsheet-VKRO6PLB.js +0 -1
- package/dist/chunk-PLRCBFGD.js +0 -1
- package/dist/chunk-SL77RQ7W.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DocumentsConflict as e,useDocumentsHost as t,useDocumentsWords as n}from"./chunk-CED4ECIS.js";import{FileList as r}from"./chunk-3SRMKGQW.js";import{useEffect as o,useRef as a,useState as s}from"react";import{WindowTitle as i,useWindowDirty as l}from"efficient-shell";import{Button as c,EmptyState as d,Input as u,LoadingSpinner as p,confirmDestructive as f,toast as m}from"efficient-shell/ui";var h={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function w(e){return e.includes("&")?e.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g,(e,t)=>{if("#"!==t[0])return h[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 g(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g,"")}var b=/([^\s=]+)\s*=\s*("([^"]*)"|'([^']*)')/g;function y(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+=w(e.slice(r,o))),e.startsWith("\x3c!--",o)){r=v(e,"--\x3e",o);continue}if(e.startsWith("<?",o)){r=v(e,"?>",o);continue}if(e.startsWith("<![CDATA[",o)){const n=v(e,"]]>",o);t.length&&(t[t.length-1].text+=e.slice(o+9,n-3)),r=n;continue}if(e.startsWith("<!",o)){r=v(e,">",o);continue}const a=x(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(b))c.attrs[e[1]]=w(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 v(e,t,n){const r=e.indexOf(t,n);if(r<0)throw new Error("Malformed XML");return r+t.length}function x(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 $=(e,t)=>e?.children.find(e=>e.name===t),k=(e,t)=>e?.children.filter(e=>e.name===t)??[];function C(e,t,n=[]){for(const r of e.children)t.has(r.name)&&n.push(r),C(r,t,n);return n}function N(e){if(!e)return;const t=e.attrs["w:val"];return!("0"===t||"false"===t||"off"===t||"none"===t)}var S='xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"',A="http://schemas.openxmlformats.org/officeDocument/2006/relationships",T={officeDocument:`${A}/officeDocument`,styles:`${A}/styles`,numbering:`${A}/numbering`,theme:`${A}/theme`,comments:`${A}/comments`,footnotes:`${A}/footnotes`,header:`${A}/header`,footer:`${A}/footer`,image:`${A}/image`,hyperlink:`${A}/hyperlink`},L=new TextEncoder,P=new TextDecoder,M=(e,t)=>{const n=e.get(t);return n?P.decode(n):void 0},E=(e,t,n)=>{e.set(t,L.encode(n))},R=e=>{const t=e.lastIndexOf("/");return`${e.slice(0,t+1)}_rels/${e.slice(t+1)}.rels`};function j(e,t){const n=M(e,R(t));return n?y(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 z(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 I(e,t,n,r,o=!1){const a=R(t),s=M(e,a),i=new Set(j(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="${g(r)}"${o?' TargetMode="External"':""}/>`;return E(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 U(e,t,n){const r=M(e,"[Content_Types].xml")??"";r.includes(`PartName="/${t}"`)||E(e,"[Content_Types].xml",r.replace("</Types>",`<Override PartName="/${t}" ContentType="${n}"/></Types>`))}var O={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}},D={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}},F={...O.a4,...D.normal,header:708,footer:708};function B(e,t){const n=O[t];return e.width>e.height?{...e,width:n.height,height:n.width}:{...e,...n}}function H(e,t){return{...e,...D[t]}}function W(e){const t=Math.min(e.width,e.height),n=Math.max(e.width,e.height);for(const[e,r]of Object.entries(O))if(Math.abs(r.width-t)<30&&Math.abs(r.height-n)<30)return e;return null}function q(e){for(const[t,n]of Object.entries(D))if(n.top===e.top&&n.right===e.right&&n.bottom===e.bottom&&n.left===e.left)return t;return null}var K={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 G=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=N($(e,"w:b"));void 0!==r&&(n.b=r);const o=N($(e,"w:i"));void 0!==o&&(n.i=o);const a=$(e,"w:u");a&&(n.u="none"!==a.attrs["w:val"]);const s=N($(e,"w:strike"));void 0!==s&&(n.strike=s);const i=$(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"]}($(e,"w:rFonts"),t);l&&(n.font=l);const c=Number($(e,"w:sz")?.attrs["w:val"]);c&&(n.size=c/2);const d=G($(e,"w:color")?.attrs["w:val"]);d&&(n.color=d);const u=$(e,"w:highlight")?.attrs["w:val"];if(u&&K[u])n.hl=K[u];else{const t=G($(e,"w:shd")?.attrs["w:fill"]);t&&(n.hl=t)}return n}function Q(e){const t={};if(!e)return t;const n=$(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=$(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=$(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 _=e=>Math.round(100*e)/100;function X(e){const t=[];return e.align&&t.push(`text-align:${e.align}`),void 0!==e.indentLeft&&t.push(`margin-left:${_(e.indentLeft)}pt`),void 0!==e.firstLine&&t.push(`text-indent:${_(e.firstLine)}pt`),void 0!==e.before&&t.push(`margin-top:${_(e.before)}pt`),void 0!==e.after&&t.push(`margin-bottom:${_(e.after)}pt`),void 0!==e.lineMultiple&&t.push(`line-height:${_(e.lineMultiple)}`),void 0!==e.linePoints&&t.push(`line-height:${_(e.linePoints)}pt`),t.join(";")}function Y(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:${_(e.size)}pt`),e.color&&t.push(`color:${e.color}`),e.hl&&t.push(`background-color:${e.hl}`),t.join(";")}var Z={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>'}},J='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';function ee(e){const t=new Map;E(t,"[Content_Types].xml",`${J}<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>`),E(t,"_rels/.rels",`${J}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${T.officeDocument}" Target="word/document.xml"/></Relationships>`);const n=F;E(t,"word/document.xml",`${J}<w:document ${S}><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>`),E(t,"word/_rels/document.xml.rels",`${J}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${T.styles}" Target="styles.xml"/><Relationship Id="rId2" Type="${A}/settings" Target="settings.xml"/></Relationships>`),E(t,"word/settings.xml",`${J}<w:settings ${S}><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 E(t,"word/styles.xml",`${J}<w:styles ${S}><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(Z).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 te}from"efficient-shell/ui";var ne=(()=>{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 re(e){let t=4294967295;for(let n=0;n<e.length;n++)t=ne[255&(t^e[n])]^t>>>8;return(4294967295^t)>>>0}async function oe(e,t){const n=t.writable.getWriter();return n.write(e).then(()=>n.close()).catch(()=>{}),new Uint8Array(await new Response(t.readable).arrayBuffer())}var ae={textBox:"Text box",chart:"Chart",diagram:"Diagram",equation:"Equation",picture:"Picture",object:"Object",contents:"Field"},se=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"]),ie=new Set(["w:ins","w:del","w:moveFrom","w:moveTo"]),le={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",svg:"image/svg+xml"},ce=/^(https?:|mailto:|tel:)/i,de=e=>te(e);function ue(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 pe=(e,t)=>`${t}${++e.nextId}`,fe=(e,t)=>e.src.slice(t.start,t.end),me=(e,t)=>t?fe(e,t):void 0;function he(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=$(t,"w:basedOn")?.attrs["w:val"]}return n}var we=e=>`"${e.replace(/["\\\n\r]/g,"")}"`;function ge(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(ge).join("")}function be(e,t,n,r,o=""){const a=pe(e,"x");return e.doc.raw.set(a,t),`<span data-raw="${a}" data-kind="${n}" contenteditable="false"${o}>${te(r)}</span>`}function ye(e,t){const n=pe(e,"x");return e.doc.raw.set(n,t),`<span data-raw="${n}" data-kind="mark"></span>`}function ve(e,t,n){const r=n(fe(e,t)),o=e=>C(t,new Set([e])).length>0,a=$(t,"wp:inline"),s=C(t,new Set(["a:blip"]))[0],i=s&&e.rels.get(s.attrs["r:embed"]),l=i&&!i.external?z(e.doc.docPath,i.target):void 0,c=l?.split(".").pop()?.toLowerCase()??"",d=l?e.doc.parts.get(l):void 0;if(d&&le[c]&&!o("wps:txbx")){const n=pe(e,"x");e.doc.raw.set(n,r);const o=$(a??$(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="${de(e.imageUrl(d,le[c]))}"${l}${u} alt="">`}return e.doc.notices.objects++,o("wps:txbx")||o("w:txbxContent")?be(e,r,"object",`${e.labels.textBox}: ${ge(t).slice(0,80)}`):o("c:chart")?be(e,r,"object",e.labels.chart):o("dgm:relIds")?be(e,r,"object",e.labels.diagram):be(e,r,"object",s?e.labels.picture:e.labels.object)}function xe(e,t){const n=$(t,"w:rPr"),r=V(n,e.theme),o=me(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+=te(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+=be(e,a(fe(e,n)),"mark",""):s+="<br>";break;case"w:drawing":s+=ve(e,n,a);break;case"mc:AlternateContent":case"w:pict":case"w:object":e.doc.notices.objects++,s+=be(e,a(fe(e,n)),"object",C(n,new Set(["wps:txbx","w:txbxContent","v:textbox"])).length?`${e.labels.textBox}: ${ge(C(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+=be(e,a(fe(e,n)),"note",String(t),r?` title="${de(r)}"`:"");break}default:s+=be(e,a(fe(e,n)),"mark","")}if(!s)return"";if(r.vert&&(s=`<${"sub"===r.vert?"sub":"sup"}>${s}</${"sub"===r.vert?"sub":"sup"}>`),n){const t=pe(e,"r");e.doc.runs.set(t,o);const a=Y(r),i=$(n,"w:rStyle")?.attrs["w:val"];s=`<span data-r="${t}"${i?` data-rstyle="${de(i)}"`:""}${a?` style="${de(a)}"`:""}>${s}</span>`}for(const t of e.openComments)s=`<span data-comment="${de(t)}" title="${de(e.comments.get(t)??"")}">${s}</span>`;return s}function $e(e,t){let n="",r=0,o=-1,a=-1,s="",i=!1;const l=()=>{o>=0&&(n+=be(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=k(c,"w:fldChar");if(t.length||r>0){0===r&&(o=c.start,i=!1),i&&(s+=ge(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+=xe(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=ce.test(o)||o.startsWith("#"),s=`${t?` data-rel="${de(c.attrs["r:id"])}"`:""}${r?` data-anchor="${de(r)}"`:""}`;n+=`<a${a?` href="${de(o)}"`:""}${s}>${$e(e,c.children)}</a>`;break}case"w:ins":case"w:moveTo":n+=`<ins>${$e(e,c.children)}</ins>`;break;case"w:del":case"w:moveFrom":n+=`<del>${$e(e,c.children)}</del>`;break;case"w:bookmarkStart":case"w:bookmarkEnd":case"w:permStart":case"w:permEnd":default:n+=ye(e,fe(e,c));break;case"m:oMath":case"m:oMathPara":e.doc.notices.objects++,n+=be(e,fe(e,c),"object",e.labels.equation);break;case"w:fldSimple":case"w:sdt":case"w:smartTag":case"w:customXml":n+=be(e,fe(e,c),"field",ge(c)||e.labels.contents)}}return r>0&&(n+=te(s)),n}function ke(e){return C(e,se).length>0}function Ce(e,t){const n=$(t,"w:pPr"),r=$(n,"w:pStyle")?.attrs["w:val"],o=$(n,"w:numPr")??function(e,t){let n;for(const r of he(e,t))n=$($(r,"w:pPr"),"w:numPr")??n;return n}(e,r),a=$(o,"w:numId")?.attrs["w:val"];if(!a||"0"===a)return null;const s=Number($(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 Ne(e){const t=[],n=$(e,"w:pBdr");for(const e of["top","bottom","left","right"]){const r=$(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=$(e,"w:shd")?.attrs["w:fill"];return r&&/^[0-9a-fA-F]{6}$/.test(r)&&t.push(`background-color:#${r}`),t.join(";")}function Se(e,t,n){const r=$(t,"w:pPr"),o=$(r,"w:pStyle")?.attrs["w:val"],a=e.fieldOpen,s=function(e){let t=0;for(const n of C(e,new Set(["w:fldChar"]))){const e=n.attrs["w:fldCharType"];"begin"===e?t++:"end"===e&&t--}return t}(t),i=ke(t)||a||0!==s;s>0&&(e.fieldOpen=!0),a&&s<0&&(e.fieldOpen=!1);const l=pe(e,"p");e.doc.blocks.set(l,{xml:fe(e,t),fingerprint:"",props:me(e,r),numId:n?.numId,ilvl:n?.ilvl});const c=n?0:function(e,t){if(!t)return 0;const n=$(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=Q(r);n&&delete u.indentLeft,n&&delete u.firstLine;const p=[X(u),Ne(r)].filter(Boolean).join(";");let f=i?Ae(e,t):$e(e,t.children);f&&!/<br>(<\/[^>]+>)*$/.test(f)||(f+="<br>");return`<${d} data-docx="${l}"${$(r,"w:pageBreakBefore")?" data-break-before":""}${o?` data-pstyle="${de(o)}"`:""}${p?` style="${de(p)}"`:""}${i?' data-locked contenteditable="false"':""}>${f}</${d}>`}function Ae(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>${Ae(e,r)}</ins>`:"w:del"===r.name||"w:moveFrom"===r.name?n+=`<del>${Ae(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+=te(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">${te(e.labels.object)}</span>`:n+=Ae(e,r));return n}function Te(e,t){const n=pe(e,"t"),r=$(t,"w:tblPr"),o=$(t,"w:tblGrid"),a=k(t,"w:tr"),s=a.some(e=>$($(e,"w:trPr"),"w:gridBefore")||$($(e,"w:trPr"),"w:gridAfter")),i=ke(t)||s;s&&e.doc.notices.objects++,e.doc.blocks.set(n,{xml:fe(e,t),fingerprint:"",props:me(e,r),tblGrid:me(e,o)});const l=$(r,"w:tblStyle")?.attrs["w:val"],c=k(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 k(e,"w:tc")){const e=$(r,"w:tcPr"),o=Number($(e,"w:gridSpan")?.attrs["w:val"]??1),a=$(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=$(t,"w:tblBorders");if(!r)for(const t of he(e,n))r=$($(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=pe(e,"t");e.doc.blocks.set(r,{xml:"",fingerprint:"",props:me(e,$(t,"w:trPr"))});return`<tr data-docx="${r}">${u[n].map(t=>{const n=pe(e,"t"),r=$(t.node,"w:tcPr");e.doc.blocks.set(n,{xml:"",fingerprint:"",props:me(e,r)});const o=$(r,"w:shd")?.attrs["w:fill"],a=[];o&&/^[0-9a-fA-F]{6}$/.test(o)&&a.push(`background-color:#${o.toLowerCase()}`);const s=$(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(";")}"`:""}>${Le(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="${de(l)}"`:""}${p?"":" data-no-borders"}${i?' data-locked contenteditable="false"':""}>${m}<tbody>${f}</tbody></table>`}function Le(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?Ce(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=Se(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="${de(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(Se(e,a,null));else if("w:tbl"===a.name)n.push(Te(e,a));else if("w:sdt"===a.name){const t=pe(e,"p");e.doc.blocks.set(t,{xml:fe(e,a),fingerprint:""}),e.doc.notices.objects++;const r=Le(e,k($(a,"w:sdtContent"),"w:p"));n.push(`<div data-docx="${t}" data-locked contenteditable="false">${r}</div>`)}else{const t=pe(e,"p");e.doc.blocks.set(t,{xml:fe(e,a),fingerprint:""}),n.push(`<div data-docx="${t}" data-locked data-hidden contenteditable="false"></div>`)}}return o(0),n.join("")}function Pe(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 Me(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=Pe(t))})}function Ee(e,t){const n=t?M(e,t):void 0;if(!n)return{text:"",editable:!0};const r=y(n),o=r.children.filter(e=>"w:p"===e.name),a=r.children.every(e=>"w:p"===e.name)&&0===C(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+=Re(n),n=""),r="separate"===e)}else"w:fldSimple"===a.name?t+=Re(a.attrs["w:instr"]??"")||a.children.map(ge).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 Re(e){const t=e.trim().split(/\s+/)[0]?.toUpperCase();return"PAGE"===t?"{page}":"NUMPAGES"===t?"{pages}":""}async function je(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 oe(m,new DecompressionStream("deflate-raw")))}}return s}(e);return ze(n,e,t)}function ze(e,t,n={}){const r=j(e,"").find(e=>e.type.endsWith("/officeDocument")),o=r?z("",r.target):"word/document.xml",a=M(e,o);if(!a)throw new Error("Not a Word document");const s=y(a),i=$(s,"w:body");if(!i)throw new Error("Not a Word document");const l=j(e,o),c=e=>{const t=(e=>l.find(t=>t.type===e))(e);return t?z(o,t.target):void 0},d=function(e){if(!e)return{};try{const t=y(e),n=$($(t,"a:themeElements"),"a:fontScheme");return{major:$($(n,"a:majorFont"),"a:latin")?.attrs.typeface,minor:$($(n,"a:minorFont"),"a:latin")?.attrs.typeface}}catch{return{}}}(c(T.theme)?M(e,c(T.theme)):void 0),u={parts:e,docPath:o,source:t,html:"",css:"",page:{...F},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??ae,rels:new Map(l.map(e=>[e.id,e])),theme:d,imageUrl:n.imageUrl??ue,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(T.styles),m=f?M(e,f):void 0,h=m?y(m):void 0;for(const e of k(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(Z))w.has(e)||p.styles.set(e,y(t.xml));const g=$(h,"w:docDefaults");u.lang=$($($(g,"w:rPrDefault"),"w:rPr"),"w:lang")?.attrs["w:val"],u.css=function(e,t){const n=[],r=V($($(t,"w:rPrDefault"),"w:rPr"),e.theme),o=Q($($(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 he(e,t))c={...c,...V($(n,"w:rPr"),e.theme)},d={...d,...Q($(n,"w:pPr"))};if("paragraph"===l)n.push(`.docs-page [data-pstyle=${we(t)}]{${[Y(c),X(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=${we(t)}]{${Y(c)}}`);else{const e=X(d);e&&n.push(`.docs-page table[data-tstyle=${we(t)}] p{${e}}`)}}return n.unshift(`.docs-page{${Y(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{${X(s)}}`),n.join("\n")}(p,g);const b=new Set(Object.keys(Z));u.styles=[...p.styles.values()].filter(e=>"paragraph"===e.attrs["w:type"]&&"1"!==e.attrs["w:default"]&&(b.has(e.attrs["w:styleId"])||$(e,"w:qFormat"))&&!$(e,"w:hidden")&&!$(e,"w:semiHidden")).map(e=>({id:e.attrs["w:styleId"],name:$(e,"w:name")?.attrs["w:val"]??e.attrs["w:styleId"]}));const v=c(T.numbering),x=v?M(e,v):void 0;x&&function(e,t){const n=new Map;for(const e of k(t,"w:abstractNum")){const t=new Map;for(const n of k(e,"w:lvl")){const e=$(n,"w:numFmt")?.attrs["w:val"]??"decimal";t.set(Number(n.attrs["w:ilvl"]),{ordered:"bullet"!==e&&"none"!==e,marker:Ie[e]??""})}n.set(e.attrs["w:abstractNumId"],t)}for(const r of k(t,"w:num")){const t=n.get($(r,"w:abstractNumId")?.attrs["w:val"]??"");t&&e.numbering.set(r.attrs["w:numId"],t)}}(p,y(x));const N=c(T.comments),S=N?M(e,N):void 0;if(S){for(const e of k(y(S),"w:comment"))p.comments.set(e.attrs["w:id"],`${e.attrs["w:author"]??""}: ${ge(e)}`);u.notices.comments=p.comments.size}const A=c(T.footnotes),L=A?M(e,A):void 0;if(L)for(const e of k(y(L),"w:footnote"))p.footnotes.set(e.attrs["w:id"],ge(e));u.notices.tracked=C(i,ie).length;const P=$(i,"w:sectPr"),E=$(P,"w:pgSz"),R=$(P,"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",F.width),height:I(E,"w:h",F.height),top:Math.abs(I(R,"w:top",F.top)),right:I(R,"w:right",F.right),bottom:Math.abs(I(R,"w:bottom",F.bottom)),left:I(R,"w:left",F.left),header:I(R,"w:header",F.header),footer:I(R,"w:footer",F.footer)};const U=e=>{const t=k(P,e).find(e=>"default"===e.attrs["w:type"]),n=t&&p.rels.get(t.attrs["r:id"]);return n?z(o,n.target):void 0};return u.header=Ee(e,U("w:headerReference")),u.footer=Ee(e,U("w:footerReference")),u.html=Le(p,i.children),u.html||(u.html="<p><br></p>"),Me(u),u}var Ie={lowerLetter:"lower-alpha",upperLetter:"upper-alpha",lowerRoman:"lower-roman",upperRoman:"upper-roman",decimalZero:"decimal-leading-zero"};var Ue=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","LI","TR","TABLE","UL","OL","TBODY"]);function Oe(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=Ue.has(e.tagName);n(e),o&&!t.endsWith("\n")&&(t+="\n")}};return n(e),t.replace(/\t\n/g,"\n").replace(/\n+$/,"\n")}function De(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&&!Ue.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 Fe(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"]),He=new Set(["SCRIPT","STYLE","TITLE","META","LINK","OBJECT","EMBED","IFRAME","NOSCRIPT","TEMPLATE","SVG","MATH","FORM","INPUT","BUTTON","SELECT","TEXTAREA","VIDEO","AUDIO","CANVAS"]),We=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"]),qe=/^(https?:|mailto:|tel:|#)/i,Ke=/^(data:image\/(png|jpe?g|gif|webp|bmp);base64,|blob:)/i;function Ge(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(He.has(a))continue;if(!Be.has(a)){n(e,t,r);continue}if("IMG"===a&&!Ke.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 We.has(n)&&!/url\(|expression|mso-/i.test(r)?`${n}:${r}`:""}).filter(Boolean).join(";");i&&s.setAttribute("style",i),"A"===a&&qe.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 Qe,useId as _e,useMemo as Xe,useRef as Ye,useState as Ze}from"react";import{saveIndicator as Je,useAutosave as et}from"efficient-easel/autosave";import{useEaselStrings as tt}from"efficient-easel/strings";import{Icon as nt}from"efficient-shell/icons";import{Button as rt,ColorPickerPanel as ot,ContextMenu as at,DropdownMenu as st,IconButton as it,Popover as lt,PopupMenu as ct,PopupMenuDivider as dt,PopupMenuItem as ut,PopupMenuLabel as pt,prompt as ft,registerModalEscapeInterceptor as mt,toast as ht,useShellLocale as wt}from"efficient-shell/ui";import{SettingsColour as gt}from"efficient-easel/panel";import{useEaselStrings as bt}from"efficient-easel/strings";import{Button as yt,Select as vt}from"efficient-shell/ui";import{jsx as xt,jsxs as $t}from"react/jsx-runtime";function kt({page:e,onPage:t,onMorePageSetup:r,colour:o,onColour:a,outline:s,onHeading:i}){const l=n(),c=bt(),d=W(e),u=q(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 $t("aside",{className:"docs-panel",children:[xt("h3",{children:l.documentPanel}),$t("div",{className:"docs-panel-section",children:[xt("p",{className:"docs-panel-label",children:l.pagePanel}),xt(vt,{"aria-label":l.paperSize,value:d??"custom",onChange:n=>{"custom"!==n&&t(B(e,n))},options:[...d?[]:[m],...Object.keys(O).map(e=>({value:e,label:p[e]}))]}),xt(vt,{"aria-label":l.margins,value:u??"custom",onChange:n=>{"custom"!==n&&t(H(e,n))},options:[...u?[]:[m],...Object.keys(D).map(e=>({value:e,label:f[e]}))]}),xt(yt,{variant:"secondary",block:!0,onClick:r,children:l.morePageSetup})]}),xt("div",{className:"docs-panel-section",children:xt(gt,{label:l.textColor,value:o,onChange:a,words:c.colourRow})}),$t("div",{className:"docs-panel-section",children:[xt("p",{className:"docs-panel-label",children:l.outline}),0===s.length?xt("p",{className:"docs-panel-empty",children:l.outlineEmpty}):xt("ul",{className:"docs-outline",children:s.map((e,t)=>xt("li",{style:{paddingLeft:10*(e.level-1)+"px"},children:xt("button",{type:"button",onClick:()=>i(t),children:e.text})},t))})]})]})}import{EaselIconButton as Ct,EaselTopBar as Nt,SaveState as St,TopBarCluster as At,TopBarDivider as Tt}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 Lt}from"efficient-shell/icons";import{DropdownMenu as Pt}from"efficient-shell/ui";import{jsx as Mt,jsxs as Et}from"react/jsx-runtime";function Rt({onClose:e,fileMenu:t,name:r,saveState:o,canUndo:a,canRedo:s,onUndo:i,onRedo:l,exportControl:c}){const d=n();return Et(Nt,{children:[Et(At,{children:[e&&Mt(Ct,{label:d.backToFiles,onClick:e,children:Mt(Lt,{name:"chevron-left",size:16})}),t.length>0&&Mt(Pt,{trigger:d.menuFile,items:t,align:"start",triggerClassName:"docs-menu-trigger"}),r,Mt(St,{...o}),Mt(Tt,{}),Et("span",{className:"docs-history",onMouseDown:e=>e.preventDefault(),children:[Mt(Ct,{label:d.undo,disabled:!a,onClick:i,children:Mt(Lt,{name:"undo",size:16})}),Mt(Ct,{label:d.redo,disabled:!s,onClick:l,children:Mt(Lt,{name:"redo",size:16})})]})]}),Mt(At,{kind:"right",children:c})]})}var jt=["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"],zt=["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"],It=["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"],Ut=["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 Ot(e){if(!e)return[];return y(e).children.map(t=>({name:t.name,xml:e.slice(t.start,t.end)}))}function Dt(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 Ft(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 Ht(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 Wt(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 qt=[10,13,16,18,24,32,48].map(e=>.75*e);var Kt=(e,t)=>void 0===e||void 0===t?e===t:Math.abs(e-t)<.02,Gt=e=>Math.round(20*e);function Vt(e,t){const n=j(e.parts,e.doc.docPath).find(e=>e.type===T.styles),r=n?M(e.parts,z(e.doc.docPath,n.target)):void 0;if(r)for(const e of y(r).children)if("w:style"===e.name&&$(e,"w:name")?.attrs["w:val"]?.toLowerCase()===t)return e.attrs["w:styleId"];return Object.entries(Z).find(([,e])=>e.name===t)?.[0]??null}var Qt=["•","o","▪"],_t=["decimal","lowerLetter","lowerRoman"];function Xt(e){const t=j(e.parts,e.doc.docPath).find(e=>e.type===T.numbering);if(t){const n=z(e.doc.docPath,t.target);return{path:n,text:M(e.parts,n)??`<w:numbering ${S}></w:numbering>`}}const n="word/numbering.xml";return I(e.parts,e.doc.docPath,T.numbering,"numbering.xml"),U(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 ${S}></w:numbering>`}}function Yt(e,t){const{path:n,text:r}=Xt(e),o=y(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?_t[e%3]:"bullet"}"/><w:lvlText w:val="${t?`%${e+1}.`:Qt[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 E(e.parts,n,u),s}function Zt(e,t,n){const{path:r,text:o}=Xt(e),a=y(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 E(e.parts,r,o.slice(0,d)+l+o.slice(d)),i}var Jt={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/bmp":"bmp","image/webp":"webp","image/svg+xml":"svg"};function en(e,t){const n=t.getAttribute("data-raw"),r=function(e,t){const n=Ft(t),r=Wt(n.get("width")),o=Wt(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=Jt[t.mime]??"png";!function(e,t,n){const r=M(e,"[Content_Types].xml")??"";new RegExp(`Extension="${t}"`,"i").test(r)||E(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=I(e.parts,e.doc.docPath,T.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 tn(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?y(r):void 0,e.theme);let a=Ot(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=g(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(K).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=Dt(a,jt);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">${g(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+=en(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=j(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??I(e.parts,e.doc.docPath,T.hyperlink,a,!0),t.setAttribute("data-rel",s));const c=t.querySelector("[data-r]")?n:{color:"#0563c1",u:!0,...n},d=tn(e,Array.from(t.childNodes),r,c);return`<w:hyperlink${o?` w:anchor="${g(o)}"`:s?` r:id="${g(s)}"`:a.startsWith("#")?` w:anchor="${g(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="${g(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=Ht(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=qt[o-1])}const o=Ft(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(/["']|"/g,"").trim());const c=Wt(o.get("font-size"));if(c&&(n.size=Math.round(2*c)/2),o.has("color")){const e=Ht(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=Ht(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="${g(p)}"/><w:r><w:commentReference w:id="${g(p)}"/></w:r>`)};for(const e of t)l(e,r,null);return s(),o}function nn(e,t,n,r,o){const a=Q(n?y(n):void 0),s=function(e){const t=Ft(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=Wt(t.get("margin-left"));void 0!==o&&(n.indentLeft=o);const a=Wt(t.get("text-indent"));void 0!==a&&(n.firstLine=a);const s=Wt(t.get("margin-top"));void 0!==s&&(n.before=s);const i=Wt(t.get("margin-bottom"));void 0!==i&&(n.after=i);const l=t.get("line-height");if(l){const e=Wt(l);e?n.linePoints=e:Number(l)&&(n.lineMultiple=Number(l))}return n}(t);let i=Ot(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="${g(r)}"/>`:null),l("w:numPr",o?`<w:numPr><w:ilvl w:val="${o.ilvl}"/><w:numId w:val="${g(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||Kt(s.indentLeft,a.indentLeft)&&Kt(s.firstLine,a.firstLine))){const e=[];void 0!==s.indentLeft&&e.push(`w:left="${Gt(s.indentLeft)}"`),void 0!==s.firstLine&&e.push(s.firstLine<0?`w:hanging="${Gt(-s.firstLine)}"`:`w:firstLine="${Gt(s.firstLine)}"`),l("w:ind",e.length?`<w:ind ${e.join(" ")}/>`:null)}if(!(Kt(s.before,a.before)&&Kt(s.after,a.after)&&Kt(s.lineMultiple,a.lineMultiple)&&Kt(s.linePoints,a.linePoints))){const e=[];void 0!==s.before&&e.push(`w:before="${Gt(s.before)}"`),void 0!==s.after&&e.push(`w:after="${Gt(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="${Gt(s.linePoints)}" w:lineRule="exact"`),l("w:spacing",e.length?`<w:spacing ${e.join(" ")}/>`:null)}const c=Dt(i,zt);return c?`<w:pPr>${c}</w:pPr>`:""}function rn(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=j(e.parts,e.doc.docPath).find(e=>e.type===T.styles);if(!n)return;const r=z(e.doc.docPath,n.target),o=M(e.parts,r);if(!o||new RegExp(`w:styleId="${t}"`).test(o))return;const a=Z[t];a&&E(e.parts,r,o.replace("</w:styles>",`${a.xml}</w:styles>`))}(e,n),n}function on(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===Pe(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>${nn(0,t,a?.props,rn(e,t),r)}${tn(e,n,t)}</w:p>`}var an=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","LI","HR","SECTION","ARTICLE"]);function sn(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??=Yt(e,!0),o=Zt(e,e.orderedAbstract,!0)):(e.bulletNum??=Zt(e,Yt(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+=sn(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+=on(e,n,Array.from(n.childNodes).filter(e=>!t.includes(e)),{numId:o,ilvl:s});for(const n of t)i+=sn(e,n,o,s)}return i}function ln(e){return Array.from(e.children).some(e=>an.has(e.tagName))}function cn(e,t){let n="",r=[];const o=()=>{r.some(e=>1===e.nodeType||(e.nodeValue??"").trim())&&(n+=`<w:p>${tn(e,r,t)}</w:p>`),r=[]};for(const a of Array.from(t.childNodes)){const t=a;if(1!==a.nodeType||!an.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+=sn(e,t,null,-1):"TABLE"===t.tagName?n+=dn(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>':ln(t)?n+=cn(e,t):n+=on(e,t,Array.from(t.childNodes),null)}return o(),n}function dn(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===Pe(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]?Wt(Ft(l[t]).get("width")):void 0;c.push(void 0!==n&&l.length===s?Gt(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>${un(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=Ht(Ft(t.cell).get("background-color"));let i=cn(e,t.cell);return i.endsWith("</w:p>")||i.endsWith("<w:p/>")||(i+="<w:p/>"),`<w:tc><w:tcPr>${un(o?.props,r,n,a>1?"restart":null,s)}</w:tcPr>${i}</w:tc>`}).join("")}</w:tr>`).join("")}</w:tbl>`}function un(e,t,n,r,o){const a=e?y(e):void 0;let s=Ot(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=$(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()}"/>`})),Dt(s,It)}function pn(e,t,n,r,o){let a=Ot(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?y(t):void 0,s=$(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">${g(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} ${S}><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 E(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`;E(e.parts,c,o),U(e.parts,c,`application/vnd.openxmlformats-officedocument.wordprocessingml.${s}+xml`);const d=I(e.parts,e.doc.docPath,"hdr"===r?T.header:T.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]??"":""}>${Dt(a,Ut)}</w:sectPr>`}async function fn(e,t,n){const r=new Map(e.parts),o=M(r,e.docPath);if(!o)throw new Error("Not a Word document");const a=y(o),s=$(a,"w:body"),i=$(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=cn(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=pn(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 E(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 oe(s,new CompressionStream("deflate-raw")),l=null===i||i.length>=s.length,c=l?s:i,d=re(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 mn(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 hn,useRef as wn}from"react";import{Icon as gn}from"efficient-shell/icons";import{Button as bn,Checkbox as yn,IconButton as vn,Input as xn}from"efficient-shell/ui";import{jsx as $n,jsxs as kn}from"react/jsx-runtime";function Cn({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=wn(null);return hn(()=>{m.current?.focus(),m.current?.select()},[]),kn("div",{className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-line bg-surface-sunken px-2 py-1",children:[$n("div",{className:"w-40",children:$n(xn,{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))}})}),$n("span",{className:"min-w-14 text-xs text-ink-muted","aria-live":"polite",children:e?a?f.matchCount(o+1,a):f.noMatches:""}),$n(vn,{size:"sm",variant:"ghost","aria-label":f.previousMatch,title:f.previousMatch,onClick:()=>c(!1),children:$n(gn,{name:"chevron-up",size:16})}),$n(vn,{size:"sm",variant:"ghost","aria-label":f.nextMatch,title:f.nextMatch,onClick:()=>c(!0),children:$n(gn,{name:"chevron-down",size:16})}),$n("div",{className:"ml-1 w-40",children:$n(xn,{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())}})}),$n(bn,{size:"sm",variant:"secondary",onClick:d,children:f.replace}),$n(bn,{size:"sm",variant:"secondary",onClick:u,children:f.replaceAll}),kn("label",{className:"ml-1 flex items-center gap-1 text-xs text-ink-muted",children:[$n(yn,{checked:r,onChange:l,"aria-label":f.matchCase}),f.matchCase]}),$n(vn,{className:"ml-auto",size:"sm",variant:"ghost","aria-label":f.closeFind,title:f.closeFind,onClick:p,children:$n(gn,{name:"close",size:16})})]})}var Nn=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 Sn(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 An(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 Tn}from"efficient-shell/ui";var Ln="\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 Pn(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 Mn(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 En(e){return Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6")).filter(e=>!e.closest("[data-hidden]")&&""!==(e.textContent??"").trim())}var Rn=["#000000","#404040","#7f7f7f","#c00000","#ff0000","#ffc000","#00b050","#0070c0","#002060","#7030a0"],jn=["#ffff00","#00ff00","#00ffff","#ff00ff","#ff0000","#c0c0c0"],zn=["#d9e2f3","#e2efd9","#fff2cc","#fbe4d5","#ededed","#bfbfbf"];function In(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 Un}from"react";import{Button as On,Dialog as Dn,FormField as Fn,Input as Bn,Select as Hn}from"efficient-shell/ui";import{Fragment as Wn,jsx as qn,jsxs as Kn}from"react/jsx-runtime";function Gn({value:e,headerEditable:t,footerEditable:r,onApply:o,onClose:a}){const s=n(),[i,l]=Un(e.page),[c,d]=Un(e.header),[u,p]=Un(e.footer),f=i.width>i.height,m=W(i),h=q(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 qn(Dn,{open:!0,onClose:a,title:s.pageSetup,size:"sm",footer:Kn(Wn,{children:[qn(On,{variant:"secondary",onClick:a,children:s.cancel}),qn(On,{variant:"primary",onClick:()=>o({page:i,header:c,footer:u}),children:s.ok})]}),children:Kn("div",{className:"space-y-3",children:[qn(Fn,{label:s.paperSize,children:qn(Hn,{value:m??"custom",onChange:e=>{"custom"!==e&&l(t=>B(t,e))},options:[...m?[]:[b],...Object.keys(O).map(e=>({value:e,label:w[e]}))]})}),qn(Fn,{label:s.orientation,children:qn(Hn,{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}]})}),qn(Fn,{label:s.margins,children:qn(Hn,{value:h??"custom",onChange:e=>{"custom"!==e&&l(t=>H(t,e))},options:[...h?[]:[b],...Object.keys(D).map(e=>({value:e,label:g[e]}))]})}),qn(Fn,{label:s.header,hint:t?s.headerFooterHint:s.headerFooterLocked,children:qn(Bn,{value:c,disabled:!t,onChange:e=>d(e.target.value)})}),qn(Fn,{label:s.footer,hint:r?void 0:s.headerFooterLocked,children:qn(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 Qn(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 _n(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 Xn=e=>Array.from(e.querySelectorAll(":scope > tbody > tr, :scope > tr, :scope > thead > tr, :scope > tfoot > tr")),Yn=(e,t)=>Math.max(1,Number(e.getAttribute(t)??1));function Zn(e){const t=Xn(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=Yn(a,"colspan"),s=Yn(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 Jn(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 er(e){const t=e.createElement("td");return t.innerHTML="<p><br></p>",t}function tr(e,t,n){const r=Zn(e),o=Jn(r,t);if(!o)return;const a=Xn(e),s=Yn(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(Yn(n,"rowspan")+1))):l.appendChild(er(e.ownerDocument))}const d=a[i];d?d.parentNode.insertBefore(l,d):a[a.length-1].parentNode.appendChild(l)}function nr(e,t,n){const r=Zn(e),o=Jn(r,t);if(!o)return;const a=n?o.col+Yn(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(Yn(r,"colspan")+1))));if(o&&o.parentElement!==Xn(e)[n])return;const i=Xn(e)[n],l=t.slice(a).find(e=>e.parentElement===i);i.insertBefore(er(e.ownerDocument),l??null)}),rr(e,r.cols+1,a,null)}function rr(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 or,jsx as ar,jsxs as sr}from"react/jsx-runtime";var ir=["Calibri","Arial","Cambria","Courier New","Georgia","Tahoma","Times New Roman","Verdana"],lr=[8,9,10,10.5,11,12,14,16,18,20,22,24,28,32,36,48,72],cr=[1,1.15,1.5,2,2.5,3],dr=[50,75,90,100,110,125,150,200],ur="p,h1,h2,h3,h4,h5,h6,li,blockquote,pre",pr=/^(https?:|mailto:|tel:)/i,fr={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 mr({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=wt(),b=_e().replace(/[^a-zA-Z0-9]/g,""),y=Ye(null),v=Ye(null),x=Ye(null),$=Ye(new Nn),k=Ye(null),C=Ye(null),N=Ye(null),S=Ye(!!l),A=Ye(0),T=Ye(()=>{}),L=Ye(null),P=Ye(0),M=Ye(m?.version??""),E=Ye(null),[R,j]=Ze({page:r.page,header:r.header.text,footer:r.footer.text}),[z,I]=Ze(fr),[U,O]=Ze({undo:!1,redo:!1}),[D,F]=Ze({words:0,pageNow:1}),[B,H]=Ze([0]),[q,K]=Ze([]),[G,V]=Ze(!1),[Q,_]=Ze(100),[X,Y]=Ze(!1),[Z,J]=Ze(!0),[ee,te]=Ze(!1),[ne,re]=Ze({rows:0,cols:0}),[oe,ae]=Ze(null),[se,ie]=Ze(null),[le,ce]=Ze(!1),[de,ue]=Ze(""),[pe,fe]=Ze(""),[me,he]=Ze(!1),[we,ge]=Ze(0),[be,ye]=Ze(0),ve=Ye([]),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=Sn(e,t.startContainer,t.startOffset),r=Sn(e,t.endContainer,t.endOffset);return n&&r?{anchor:n,focus:r}:null}const n=Sn(e,t.anchorNode,t.anchorOffset),r=Sn(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=An(t,e.anchor),o=An(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(ur)).filter(e=>!e.closest("[data-locked]"));var r;return(t.collapsed?[(r=t.startContainer,(1===r.nodeType?r:r.parentElement)?.closest(ur))].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);H(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;F({words:(c=Oe(e),(c.match(/[-ヿ㐀-鿿豈-]/g)?.length??0)+(c.replace(/[-ヿ㐀-鿿豈-]/g," ").match(/\S+/g)?.length??0)),pageNow:l});const d=function(e){return En(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(ur),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:In(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 fn(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=tt(),Me=et({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(),V(!0)):0===n&&ht.error(w.saveFailed)}}),{push:Ee,flush:Re}=Me,je=!!m,ze=Me.state.pending;Qe(()=>{je&&d(ze||G)},[G,je,d,ze]),Qe(()=>()=>{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]),Ue=Ve(()=>({html:v.current?.innerHTML??"",caret:ke()}),[ke]),Be=()=>{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),Be(),Ie(),Te())},[Ce,Ie,Te]),We=Ve(()=>He($.current.undo(Ue())),[He,Ue]),qe=Ve(()=>He($.current.redo(Ue())),[He,Ue]),Ke=Ve(e=>{Ne(),Be(),$.current.record(Ue()),e(),Ie(),Te()},[Ie,Te,Ne,Ue]),gt=Ve((e,t)=>Ke(()=>{document.execCommand(e,!1,t)}),[Ke]),bt=e=>Ke(()=>{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)});Qe(()=>{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(ur);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),Be(),E.current&&clearTimeout(E.current)}},[]),Qe(()=>{Ae()},[Ae]),Qe(()=>{l&&d(!0)},[]);const yt=e=>Ke(()=>{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=>Ke(()=>{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?Qn(t):_n(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]),$t=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 ft({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&>("unlink"));const a=/^[a-z][a-z0-9+.-]*:/i.test(o)?o:`https://${o}`;if(pr.test(a))if(n)Ke(()=>{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 ht.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(er(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=>{$t(e)};const At=e=>{if(!oe)return;const t=oe.el;Ke(()=>{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?De(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]),Et=()=>{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=Ye(Mt);jt.current=Mt;const zt=Ye(le);zt.current=le,Qe(()=>mt(()=>!(!zt.current||!y.current?.contains(document.activeElement))&&(jt.current(),!0)),[]),Qe(()=>()=>Lt(),[]),Qe(()=>{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;mn(await Le(),Ut,"application/vnd.openxmlformats-officedocument.wordprocessingml.document"),m||P.current!==e||d(!1)}catch{ht.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)};${Mn("top",a)}${Mn("bottom",s)}}`;return`<!doctype html><html><head><meta charset="utf-8"><meta name="generator" content="efficient-shell Documents"><title>${Tn(e)}</title><style>${Pn(n,r)}\n${Ln.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}),Ft=()=>{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()},Bt=s.length?[...s,{type:"divider",key:"d1"},{key:"save",label:ar(hr,{label:w.saveDocx,hint:"⌘S"}),onSelect:()=>{Ot()}}]:[],Ht=[{key:"docx",label:w.saveAsWord,onSelect:()=>{Ot()}},{key:"pdf",label:w.saveAsPdf,onSelect:Ft},{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()),mn(Dt(e.innerHTML),`${It}.html`,"text/html")})()}},{key:"txt",label:w.saveAsText,onSelect:()=>{mn(Oe(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:ar(hr,{label:w.link,hint:"⌘K"}),onSelect:()=>{Ct()}},{key:"break",label:ar(hr,{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},Gt=[{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)}))],Vt=Xe(()=>Array.from(new Set([...r.defaultFont?[r.defaultFont]:[],...ir])),[r.defaultFont]).map(e=>({key:e,label:ar("span",{style:{fontFamily:`"${e}"`},children:e}),onSelect:()=>gt("fontName",e)})),Qt=lr.map(e=>({key:String(e),label:String(e),onSelect:()=>(e=>Ke(()=>{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=cr.map(e=>({key:String(e),label:e.toFixed(1.15===e?2:1),onSelect:()=>{return t=e,Ke(()=>{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=ar("div",{className:"mx-1 h-4 w-px bg-line"}),en=(e,t,n,r={})=>ar(it,{"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="")=>ar(st,{"aria-label":e,align:"start",items:n,triggerClassName:Zt,trigger:sr("span",{title:e,className:`flex items-center justify-between gap-1 ${r}`,children:[ar("span",{className:"truncate",children:t}),ar(nt,{name:"chevron-down",size:12})]})}),nn=(e,t,n,r,o)=>ar(lt,{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:sr(or,{children:[t,ar("span",{className:"h-0.5 w-4 rounded-sm",style:{background:n}})]}),children:({close:t})=>ar(ot,{label:e,value:"",presets:r,clearable:!0,dragWrites:"end",onChange:e=>{"hiliteColor"===o?gt("hiliteColor",e||"transparent"):gt("foreColor",e||Rn[0]),on(t=>({...t,[o]:e||("hiliteColor"===o?"var(--line)":"var(--ink)")})),t()}})}),[rn,on]=Ze({foreColor:"var(--ink)",hiliteColor:"var(--line)"}),an=W(R.page),sn=an?{a4:"A4",a3:"A3",a5:"A5",letter:w.paperLetter,legal:w.paperLegal}[an]:w.custom,ln=Xe(()=>{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*/),pn=R.footer.split(/\s*\|\s*/),hn=(e,t)=>e.replace(/\{page\}/g,String(t)).replace(/\{pages\}/g,String(B.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 sr("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 Ft();if("f"===n)return o(),void Et();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&&Ke(()=>tr(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:[ar("style",{children:Pn(r,b)}),ar("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:e=>{e.target.files?.length&&$t(Array.from(e.target.files)),e.target.value=""}}),ar(Rt,{onClose:f,fileMenu:Bt,name:i,saveState:m?Je(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:ar(st,{"aria-label":w.export,align:"end",items:Ht,triggerClassName:"docs-export-trigger",trigger:sr(or,{children:[ar(nt,{name:"download",size:16}),w.export]})})}),G&&sr("div",{className:"docs-conflict",role:"alert",children:[ar("span",{children:w.conflict}),ar(rt,{variant:"secondary",onClick:h,children:w.reload})]}),sr("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[ar(st,{trigger:w.menuInsert,items:Wt,align:"start",triggerClassName:Yt}),ar(lt,{open:ee,onOpenChange:te,align:"start",triggerLabel:w.table,triggerClassName:"h-5 w-0 overflow-hidden",trigger:ar("span",{}),children:sr("div",{className:"p-1",children:[ar("div",{className:"mb-1 text-xs text-ink-muted",children:ne.rows?w.tableSize(ne.cols,ne.rows):w.table}),ar("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 ar("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)})})]})}),ar(st,{trigger:w.menuLayout,items:qt,align:"start",triggerClassName:Yt}),Jt,en(w.print,ar(nt,{name:"print",size:16}),Ft),en(w.find,ar(nt,{name:"search",size:16}),()=>le?Mt():Et(),{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),Gt,"w-20"),tn(w.font,z.font||r.defaultFont||"Calibri",Vt,"w-20"),tn(w.fontSize,z.size??r.defaultSize??11,Qt),Jt,en(w.bold,ar(nt,{name:"bold",size:16}),()=>gt("bold"),{pressed:z.bold}),en(w.italic,ar(nt,{name:"italic",size:16}),()=>gt("italic"),{pressed:z.italic}),en(w.underline,ar(nt,{name:"underline",size:16}),()=>gt("underline"),{pressed:z.underline}),en(w.strikethrough,ar(nt,{name:"strike",size:16}),()=>gt("strikeThrough"),{pressed:z.strike}),en(w.superscript,ar(nt,{name:"superscript",size:16}),()=>gt("superscript"),{pressed:z.sup}),en(w.subscript,ar(nt,{name:"subscript",size:16}),()=>gt("subscript"),{pressed:z.sub}),nn(w.textColor,ar(nt,{name:"text-color",size:14}),rn.foreColor,Rn,"foreColor"),nn(w.highlight,ar(nt,{name:"palette",size:14}),rn.hiliteColor,jn,"hiliteColor"),en(w.clearFormatting,ar(nt,{name:"clear-marks",size:16}),()=>Ke(()=>{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,ar(nt,{name:"list",size:16}),()=>bt("insertUnorderedList"),{pressed:z.ul}),en(w.numberedList,ar(nt,{name:"numbered-list",size:16}),()=>bt("insertOrderedList"),{pressed:z.ol}),en(w.decreaseIndent,ar(nt,{name:"chevron-double-left",size:16}),()=>vt(!1)),en(w.increaseIndent,ar(nt,{name:"chevron-double-right",size:16}),()=>vt(!0)),Jt,en(w.alignLeft,ar(nt,{name:"align-left",size:16}),()=>xt("left"),{pressed:"left"===z.align}),en(w.alignCenter,ar(nt,{name:"align-center",size:16}),()=>xt("center"),{pressed:"center"===z.align}),en(w.alignRight,ar(nt,{name:"align-right",size:16}),()=>xt("right"),{pressed:"right"===z.align}),en(w.justify,ar(nt,{name:"align-justify",size:16}),()=>xt("justify"),{pressed:"justify"===z.align}),ar(st,{"aria-label":w.lineSpacing,align:"start",items:_t,triggerClassName:Zt,trigger:sr("span",{title:w.lineSpacing,className:"flex items-center gap-0.5",children:[ar(nt,{name:"line-spacing",size:16}),ar(nt,{name:"chevron-down",size:12})]})})]}),Z&&gn.length>0&&sr("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:[ar(nt,{name:"info",size:14}),ar("span",{className:"min-w-0 flex-1",children:w.noticeLead(gn)}),ar(it,{size:"sm",variant:"ghost",ink:"inherit","aria-label":w.dismiss,title:w.dismiss,onClick:()=>J(!1),children:ar(nt,{name:"close",size:14})})]}),le&&ar(Cn,{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(Ue()),Fe(e,pe),Ie(),Pt(de,me,we))},onReplaceAll:()=>{const e=ve.current;if(e.length){$.current.record(Ue());for(let t=e.length-1;t>=0;t--)Fe(e[t],pe);Ie(),ht.success(w.replacedCount(e.length)),Pt(de,me,0)}},onClose:Mt}),sr("div",{className:"docs-body",children:[sr("div",{className:"docs-centre",children:[ar("div",{className:"min-h-0 flex-1 overflow-auto bg-surface-sunken px-6 py-6",children:sr("div",{className:"docs-sheet relative mx-auto shadow",style:{width:`${cn}pt`,zoom:Q/100,minHeight:R.page.height/20+"pt"},children:[R.header&&sr("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:[ar("span",{children:hn(un[0],1)}),void 0!==un[1]&&ar("span",{children:hn(un[1],1)})]}),ar("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=Ge(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(),$t(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")??"";pr.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"}}),B.slice(1).map((e,t)=>ar("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:ar("span",{className:"docs-sheet absolute right-1 -top-2 px-1 text-2xs",children:w.pageLabel(t+2)})},e)),R.footer&&sr("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:[ar("span",{children:hn(pn[0],B.length)}),void 0!==pn[1]&&ar("span",{children:hn(pn[1],B.length)})]})]})}),sr("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:[ar("span",{children:w.pageOf(Math.min(D.pageNow,B.length),B.length)}),ar("span",{children:w.wordCount(D.words)}),ar("span",{children:sn}),ln&&ar("span",{children:ln}),sr("span",{className:"ml-auto flex items-center gap-1",children:[ar(rt,{size:"sm",variant:"ghost","aria-label":w.zoomOut,onClick:()=>_(e=>[...dr].reverse().find(t=>t<e)??e),children:"−"}),sr("span",{className:"w-9 text-center tabular-nums",children:[Q,"%"]}),ar(rt,{size:"sm",variant:"ghost","aria-label":w.zoomIn,onClick:()=>_(e=>dr.find(t=>t>e)??e),children:"+"})]})]})]}),ar(kt,{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&&En(t)[e]?.scrollIntoView({block:"start"})}})]}),X&&ar(Gn,{value:R,headerEditable:r.header.editable,footerEditable:r.footer.editable,onClose:()=>Y(!1),onApply:e=>{j(e),Y(!1),Ie()}}),oe&&sr(ct,{minWidth:150,portal:!0,style:{position:"fixed",left:oe.x,top:oe.y},onClose:()=>ae(null),children:[ar(pt,{children:w.imageWidth}),ar(ut,{onClick:()=>At(.25),children:"25%"}),ar(ut,{onClick:()=>At(.5),children:"50%"}),ar(ut,{onClick:()=>At(.75),children:"75%"}),ar(ut,{onClick:()=>At(1),children:"100%"}),ar(ut,{onClick:()=>At(null),children:w.imageOriginalSize}),ar(dt,{}),ar(ut,{danger:!0,onClick:()=>{if(!oe)return;const e=oe.el;Ke(()=>{e.remove()}),ae(null)},children:w.imageRemove})]}),se&&ar(at,{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:()=>Ke(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,()=>tr(t,e,!1)),n("below",w.rowBelow,()=>tr(t,e,!0)),n("left",w.columnLeft,()=>nr(t,e,!1)),n("right",w.columnRight,()=>nr(t,e,!0)),{type:"divider",key:"d1"},n("merge",w.mergeCells,()=>{(function(e,t){if(t.length<2)return!1;const n=Zn(e);let r=1/0,o=1/0,a=-1,s=-1;for(const e of t){const t=Jn(n,e);if(!t)return!1;r=Math.min(r,t.row),o=Math.min(o,t.col),a=Math.max(a,t.row+Yn(e,"rowspan")-1),s=Math.max(s,t.col+Yn(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=Jn(n,e);if(t.row<r||t.col<o||t.row+Yn(e,"rowspan")-1>a||t.col+Yn(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)||ht.error(w.mergeFailed)},{disabled:r.length<2}),{type:"submenu",key:"shade",label:w.cellShading,items:[...zn.map(t=>({key:t,label:sr("span",{className:"flex items-center gap-2",children:[ar("span",{className:"h-3 w-5 rounded-sm border border-line",style:{background:t}}),t.toUpperCase()]}),onSelect:()=>Ke(()=>{for(const n of r.length?r:[e])n.style.backgroundColor=t})})),{key:"none",label:w.noColor,onSelect:()=>Ke(()=>{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=Zn(e),r=Jn(n,t);if(!r)return!1;const o=Xn(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=Yn(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+Yn(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=Zn(e),r=Jn(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=Yn(t,"colspan");n>1?t.setAttribute("colspan",String(n-1)):t.remove()}rr(e,n.cols-1,null,r.col)}(t,e)}),n("delTable",w.deleteTable,()=>{t.remove()},{danger:!0})]})(se.cell)})]})}function hr({label:e,hint:t}){return sr("span",{className:"flex w-full items-center justify-between gap-4",children:[ar("span",{children:e}),ar("span",{className:"text-2xs text-ink-faint",children:t})]})}import{useEffect as wr,useRef as gr,useState as br}from"react";import{Icon as yr}from"efficient-shell/icons";import{Button as vr,IconButton as xr,registerModalEscapeInterceptor as $r,toast as kr}from"efficient-shell/ui";var Cr={LF:"\n",CRLF:"\r\n",CR:"\r"};function Nr(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 Sr(e){let t=1;for(let n=e.indexOf("\n");n>=0;n=e.indexOf("\n",n+1))t++;return t}import{jsx as Ar,jsxs as Tr}from"react/jsx-runtime";function Lr({filename:e,decoded:t,bytes:r,fileEntries:o,title:a,dirty:s,onDirty:i,onOpenFile:l,onClose:c}){const d=n(),u=gr(null),p=gr(null),f=gr(t.text),m=gr(!1),[h,w]=br(!0),[g,b]=br(!1),[y,v]=br({line:1,col:1,lines:Sr(t.text)}),[x,$]=br(!1),[k,C]=br(""),[N,S]=br(""),[A,T]=br(!1),[L,P]=br(0),[M,E]=br([]),R=()=>p.current?.value??"",j=gr(null),[z,I]=br(0),U=()=>{j.current&&p.current&&(j.current.scrollTop=p.current.scrollTop,j.current.scrollLeft=p.current.scrollLeft)};wr(()=>{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({...Nr(e.value,e.selectionStart),lines:Sr(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},F=(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)},B=()=>{mn(m.current?function(e,t,n){const r=e.replace(/\n/g,Cr[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&&kr.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()};wr(()=>{p.current?.focus(),p.current?.setSelectionRange(0,0)},[]);const G=gr(x);G.current=x,wr(()=>$r(()=>!(!G.current||!u.current?.contains(document.activeElement))&&(K(),!0)),[]);const V=[...o,{type:"divider",key:"d1"},{key:"save",label:d.saveKeepType,onSelect:B}],Q=s?d.noStoreEdited:d.noStoreClean;return Tr("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(),B();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:[Ar(Rt,{onClose:c,fileMenu:V,name:a,saveState:{tone:s?"off-unsaved":"off",label:Q},canUndo:g,canRedo:g,onUndo:()=>q("undo"),onRedo:()=>q("redo"),exportControl:Ar(vr,{variant:"secondary",leftIcon:Ar(yr,{name:"download",size:16}),onClick:B,children:d.export})}),Tr("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[Ar(xr,{size:"sm",variant:"ghost","aria-label":d.find,title:d.find,"aria-pressed":x,onClick:()=>$(e=>!e),children:Ar(yr,{name:"search",size:16})}),Ar(xr,{size:"sm",variant:"ghost","aria-label":d.wrapLines,title:d.wrapLines,"aria-pressed":h,onClick:()=>w(e=>!e),children:Ar(yr,{name:"wrap",size:16})})]}),x&&Ar(Cn,{query:k,replacement:N,matchCase:A,current:L,total:M.length,onQuery:e=>{C(e);const t=D(e);P(0),F(t,0,e)},onReplacement:S,onMatchCase:e=>{T(e);const t=D(k,e);P(0),F(t,0)},onStep:e=>F(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();F(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),kr.success(d.replacedCount(t))},onClose:K}),Tr("div",{className:"relative min-h-0 flex-1 bg-surface",children:[x&&k&&M.length>0&&M.length<=2e3&&Ar("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(Ar("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})()}),Ar("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")})]}),Tr("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:[Ar("span",{children:e}),Ar("span",{children:d.lineColumn(y.line,y.col)}),Ar("span",{children:d.lineCount(y.lines)}),Ar("span",{children:t.eol})]})]})}import{jsx as Pr,jsxs as Mr}from"react/jsx-runtime";var Er=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"]),Rr=`${Array.from(Er,e=>`.${e}`).join(",")},.docx,text/*`,jr=/^<!doctype html><meta charset="utf-8"><title>[^<]*<\/title>(?!<body style="font-family:ui-monospace)/,zr=()=>"undefined"!=typeof navigator&&navigator.language||"en-AU";function Ir({value:e,onRename:t}){const r=n(),[a,i]=s(e);return o(()=>i(e),[e]),Pr("div",{className:"docs-title",children:Pr(u,{"aria-label":r.documentName,value:a,onChange:e=>i(e.target.value),onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()},onBlur:()=>{const n=a.trim();i(n||e),n&&n!==e&&t(n)}})})}function Ur({documentId:e,onClose:o}){const a=n(),{store:i,canCreate:l=!0,canDelete:c=!0}=t(),[d,u]=s(null);return!i||e?Pr(Or,{documentId:e,onClose:o}):d?Pr(Or,{documentId:d.id,initialFile:d.file,onClose:()=>u(null)},d.key):Pr(r,{words:{windowTitle:a.filesHeading,heading:a.filesHeading,newFile:a.newFile,openFile:a.openFile,emptyTitle:a.filesEmptyTitle,emptyBody:a.filesEmptyBody,delete:a.deleteFile,deleteConfirm:a.deleteConfirm,createFailed:a.createFailed,deleteFailed:a.deleteFailed},list:i.list,create:()=>i.create(a.untitled),remove:i.remove,canCreate:l,canDelete:c,accept:Rr,onOpen:e=>u({key:Date.now(),id:e}),onOpenFile:e=>u({key:Date.now(),file:e})})}function Or({documentId:e,onClose:r,initialFile:u}){const h=n(),{store:w}=t(),g=w&&e?e:null,b=a([]),y=a(0),v=a(null),x={textBox:h.objectTextBox,chart:h.objectChart,diagram:h.objectDiagram,equation:h.objectEquation,picture:h.objectPicture,object:h.objectOther,contents:h.objectField},$=e=>({labels:x,imageUrl:(t,n)=>{const r=URL.createObjectURL(new Blob([t],{type:n}));return b.current.push(r),e.set(r,{bytes:t,mime:n}),r}}),k=e=>{const t=new Map;return{key:++y.current,kind:"rich",filename:e,images:t,doc:ze(ee(zr()),null,$(t))}},[C,N]=s(()=>g?null:k(h.untitled)),[S,A]=s(!1),[T,L]=s(0),[P,M]=s(!1),[E,R]=s(!1),[j,z]=s(!1);l(j),o(()=>()=>{b.current.forEach(e=>URL.revokeObjectURL(e))},[]),o(()=>{if(!w||!g)return;let e=!0;return A(!1),(async()=>{const t=await w.get(g),n=new Map,r=t.bytes?.length?await je(t.bytes,$(n)):ze(ee(zr()),null,$(n));e&&I({key:++y.current,kind:"rich",doc:r,images:n,filename:t.title,stored:{id:t.id,version:t.version}})})().catch(()=>{e&&A(!0)}),()=>{e=!1}},[w,g,T]);const I=e=>{const t=b.current;if(b.current=[],"rich"===e.kind)for(const t of e.images.keys())b.current.push(t);N(e),z(!1),setTimeout(()=>t.filter(e=>!b.current.includes(e)).forEach(e=>URL.revokeObjectURL(e)),0)},U=async()=>!j||f({title:h.discardTitle(C?.filename??""),message:h.discardMessage,confirmLabel:h.discard,cancelLabel:h.keepEditing}),O=async e=>{if(!await U())return;const t=(e.name.split(".").pop()||"").toLowerCase();M(!0);try{if("docx"===t){const t=new Map,n=new Uint8Array(await e.arrayBuffer());try{const r=await je(n,$(t));I({key:++y.current,kind:"rich",doc:r,filename:e.name,images:t})}catch{m.error(h.cannotRead(e.name))}}else if("doc"===t)m.error(h.legacyDoc);else if(Er.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||!jr.test(r.text))I({key:++y.current,kind:"text",decoded:r,bytes:n,filename:e.name});else{const t=new Map,n=ze(ee(zr()),null,$(t));n.html=Ge(r.text)||n.html,Me(n),I({key:++y.current,kind:"rich",doc:n,images:t,filename:e.name.replace(/\.[^.]+$/,".docx"),imported:!0}),m.info(h.openedOldSave)}}else m.error(h.unsupported(t))}finally{M(!1)}};o(()=>{u&&O(u)},[]);const D=async()=>{await U()&&(z(!1),v.current?.click())},F="rich"===C?.kind&&!!C.stored,B=()=>m.info(h.openFromFiles),H=[{key:"new",label:h.newDocument,onSelect:()=>{(async()=>{await U()&&I(k(h.untitled))})()}},{key:"open",label:Mr("span",{className:"flex w-full items-center justify-between gap-4",children:[Pr("span",{children:h.open}),Pr("span",{className:"text-2xs text-ink-faint",children:"⌘O"})]}),onSelect:()=>{D()}}],W=C&&Pr(Ir,{value:C.filename,onRename:e=>{const t=C?.filename??e;N(t=>t?{...t,filename:e}:t),w&&"rich"===C?.kind&&C.stored&&w.rename(C.stored.id,e).catch(()=>{m.error(h.renameFailed),N(e=>e?{...e,filename:t}:e)})}});return Mr("div",{className:"relative flex h-full flex-col bg-surface text-ink",onDragOver:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),E||R(!0))},onDragLeave:e=>{e.currentTarget===e.target&&R(!1)},onDrop:e=>{if(!e.dataTransfer.types.includes("Files"))return;e.preventDefault(),R(!1);const t=Array.from(e.dataTransfer.files??[]);"rich"===C?.kind&&t.length&&t.every(e=>e.type.startsWith("image/"))?window.dispatchEvent(new CustomEvent("docs-insert-images",{detail:{key:C.key,files:t}})):t[0]&&F?B():t[0]&&O(t[0])},children:[C&&Pr(i,{title:`${q=C.filename,q.length>24?`${q.slice(0,23)}…`:q}${j?" •":""} - Documents`}),Pr("input",{ref:v,type:"file",accept:Rr,className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&O(t),e.target.value=""}}),S?Pr("div",{className:"docs-open-failed",children:Pr(d,{title:h.openFailed,children:r&&Pr(c,{onClick:r,children:h.backToFiles})})}):P||!C?Pr(p,{size:"sm",padding:"",className:"h-full",label:h.loading}):"rich"===C.kind?Pr(mr,{sessionKey:C.key,doc:C.doc,filename:C.filename,images:C.images,fileEntries:F?[]:H,title:W,startsDirty:C.imported,dirty:j,onDirty:z,onOpenFile:()=>{F?B():D()},onNewImageUrl:e=>{b.current.push(e)},onClose:r,stored:w&&C.stored?{store:w,...C.stored}:void 0,onReload:()=>{z(!1),N(null),L(e=>e+1)}},C.key):Pr(Lr,{filename:C.filename,decoded:C.decoded,bytes:C.bytes,fileEntries:H,title:W,dirty:j,onDirty:z,onOpenFile:()=>{D()},onClose:r},C.key),E&&Pr("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:Pr("div",{className:"rounded-md bg-accent-fill px-4 py-2 text-sm font-medium text-on-accent",children:h.dropHint})})]});var q}function Dr({id:e,onClose:t}){return Pr(Ur,{documentId:e,onClose:t})}export{Dr as OpenDocument,Ur as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DEFAULT_COL_WIDTH as e,DEFAULT_FONT_SIZE as t,DEFAULT_ROW_HEIGHT as r,FUNCTION_NAMES as n,FormulaError as o,MAX_COLS as l,MAX_ROWS as i,NUMBER_FORMATS as a,SpreadsheetsConflict as s,adjustDecimals as c,applyBorders as u,cellDisplay as d,cellLabel as f,changeStructure as m,clearValues as h,colIndex as g,colLabel as p,columnValues as w,commitEntry as v,copyClip as b,cycleRefAbsolute as x,dataRegion as y,deleteSheet as C,duplicateSheet as k,editText as $,expandForMerges as N,fillRange as F,filteredRows as A,findCells as S,formatKey as D,formatNumber as R,isFormula as E,makeEvaluator as T,mergeRange as M,mergedAt as z,moveCells as I,newSheet as U,nextSheetName as O,normalizeRange as L,parseCsv as P,parseRangeLabel as B,pasteClip as H,printRef as K,rangeContains as W,rangeLabel as V,rawAt as X,readEntry as j,renameSheet as G,replaceInCell as _,selectionStats as Y,serializeCsv as Z,sheetFromRows as Q,sheetsOf as J,shiftFormula as q,sortRange as ee,tokenize as te,unmergeRange as re,updateFormats as ne,useSpreadsheetWords as oe,useSpreadsheetsHost as le,usedBounds as ie,withFormat as ae,writeCells as se}from"./chunk-ZKFPXX72.js";import{FileList as ce}from"./chunk-3SRMKGQW.js";import{useCallback as ue,useEffect as de,useMemo as fe,useRef as me,useState as he}from"react";import{saveIndicator as ge,useAutosave as pe}from"efficient-easel/autosave";import{SaveState as we}from"efficient-easel/chrome";import"efficient-easel/chrome.css";import{useEaselStrings as ve}from"efficient-easel/strings";import{WindowTitle as be,useBrowserLayoutEffect as xe,useWindowDirty as ye}from"efficient-shell";import{Icon as Ce}from"efficient-shell/icons";import{Button as ke,Checkbox as $e,ColorPickerPanel as Ne,ContextMenu as Fe,DropdownMenu as Ae,EmptyState as Se,IconButton as De,Input as Re,LoadingSpinner as Ee,Popover as Te,PopupMenu as Me,PopupMenuDivider as ze,PopupMenuItem as Ie,confirmDestructive as Ue,registerModalEscapeInterceptor as Oe,toDateKey as Le,toast as Pe,useContextMenu as Be}from"efficient-shell/ui";import{SPREADSHEET_PREVIEW_UPDATE_EVENT as He,peekSpreadsheetPreviewStage as Ke,claimSpreadsheetPreviewStage as We}from"efficient-shell/apps";import{forwardRef as Ve,useCallback as Xe,useEffect as je,useImperativeHandle as Ge,useMemo as _e,useRef as Ye,useState as Ze}from"react";import{Icon as Qe}from"efficient-shell/icons";import{jsx as Je,jsxs as qe}from"react/jsx-runtime";var et,tt=46,rt=24,nt=4/3;function ot(e,t){const r=new Float64Array(e+1);for(let n=0;n<e;n++)r[n+1]=r[n]+t(n);return r}function lt(e,t){let r=0,n=e.length-2;for(;r<n;){const o=r+n+1>>1;e[o]<=t?r=o:n=o-1}return r}function it(e,r){if(void 0===et)try{et=document.createElement("canvas").getContext("2d")}catch{et=null}const n=(r?.fontSize??t)*nt;return et?(et.font=`${r?.italic?"italic ":""}${r?.bold?"bold ":""}${n}px system-ui, sans-serif`,et.measureText(e).width):e.length*n*.55}var at=Ve(function({sheet:n,sheetIndex:o,evaluator:l,filterHidden:i,selection:a,showGridlines:s,showFormulas:c,clipRange:u,highlights:f,pointing:m,onSelect:h,onPoint:g,onEdit:w,onFill:v,onResizeCol:b,onResizeRow:x,onAutoFitCol:y,onAutoFitRow:C,onHeaderMenu:k,onFilterButton:$,renderEditor:F,onKeyDown:A,onCopy:S,onCut:R,onPaste:E},T){const M=oe(),I=Ye(null),[U,O]=Ze({x:0,y:0}),[P,B]=Ze({width:1e3,height:600}),[H,K]=Ze(null),[W,V]=Ze(null),[j,G]=Ze(null);je(()=>{const e=I.current;if(!e)return;const t=()=>{e.clientWidth&&e.clientHeight&&B({width:e.clientWidth,height:e.clientHeight})};if(t(),"undefined"==typeof ResizeObserver)return;const r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]);const _=_e(()=>{const i=new Map;for(const[a,s]of Object.entries(n.formats)){if(!s.fontSize&&!s.wrap)continue;const[c,u]=a.split(":").map(Number);if(void 0!==n.rowHeights[c])continue;const f=(s.fontSize??t)*nt*1.4;let m=1;if(s.wrap&&""!==X(n,c,u)){const t=(n.colWidths[u]??e)-8;m=d(n,o,l,c,u).text.split("\n").reduce((e,r)=>e+Math.max(1,Math.ceil(it(r,s)/Math.max(t,1))),0)}const h=Math.ceil(f*m+6);h>(i.get(c)??r)&&i.set(c,h)}return i},[n,o,l]),Y=_e(()=>new Set(n.hiddenRows),[n.hiddenRows]),Z=_e(()=>new Set(n.hiddenCols),[n.hiddenCols]),Q=_e(()=>ot(n.rowCount,e=>Y.has(e)||i.has(e)?0:W?.row===e?W.height:n.rowHeights[e]??_.get(e)??r),[n.rowCount,n.rowHeights,Y,i,_,W]),J=_e(()=>ot(n.colCount,t=>Z.has(t)?0:H?.col===t?H.width:n.colWidths[t]??e),[n.colCount,n.colWidths,Z,H]),q=Math.min(n.frozenRows,n.rowCount),ee=Math.min(n.frozenCols,n.colCount),te=Q[q],re=J[ee],ne=J[n.colCount],le=Q[n.rowCount],ie=Xe(e=>tt+J[e]-(e>=ee?U.x:0),[J,ee,U.x]),ae=Xe(e=>rt+Q[e]-(e>=q?U.y:0),[Q,q,U.y]),se=Xe(e=>{const t=I.current;if(!t)return;const r=t.clientWidth-tt-re,n=t.clientHeight-rt-te;let{scrollLeft:o,scrollTop:l}=t;if(e.col>=ee){const t=J[e.col]-re,n=J[e.col+1]-re;t<o?o=t:n>o+r&&(o=n-r)}if(e.row>=q){const t=Q[e.row]-te,r=Q[e.row+1]-te;t<l?l=t:r>l+n&&(l=r-n)}t.scrollTo(o,l)},[J,Q,re,te,ee,q]);Ge(T,()=>({focus:()=>I.current?.focus({preventScroll:!0}),scrollTo:se,measureColumn:e=>{let t=0;for(let r=0;r<n.cells.length;r++){if(""===X(n,r,e))continue;const i=n.formats[D(r,e)];t=Math.max(t,it(d(n,o,l,r,e).text,i))}return Math.ceil(t+8+4)}}),[se,n,o,l]);const ce=Xe((e,t)=>{const r=I.current.getBoundingClientRect(),n=e-r.left-tt,o=t-r.top-rt,l=n<re?n:n+I.current.scrollLeft,i=o<te?o:o+I.current.scrollTop;return{row:lt(Q,Math.max(0,Math.min(i,le-1))),col:lt(J,Math.max(0,Math.min(l,ne-1)))}},[J,Q,re,te,ne,le]),ue=Xe((e,t)=>{const r=I.current,n=t=>{const n=r.getBoundingClientRect();t.clientY>n.bottom-4?r.scrollBy(0,24):t.clientY<n.top+rt&&r.scrollBy(0,-24),t.clientX>n.right-4?r.scrollBy(24,0):t.clientX<n.left+tt&&r.scrollBy(-24,0),e(t)},o=e=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),t(e)};window.addEventListener("pointermove",n),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o)},[]),de=Xe((e,t)=>{const r=N(n,L(e,t));h({active:e,range:r})},[n,h]),fe=Math.max(0,P.width-tt-re),me=Math.max(0,P.height-rt-te),he=lt(Q,te+U.y),ge=lt(J,re+U.x),pe=Math.min(n.rowCount-1,lt(Q,te+U.y+me)),we=Math.min(n.colCount-1,lt(J,re+U.x+fe)),ve=(e,r,i,a)=>{const u=[],f=[],m=new Set,h=(e,r,i)=>{const a=D(e,r);if(m.has(a))return;m.add(a);const h=i?i.r2:e,g=i?i.c2:r,p=J[r],w=Q[e],v=J[g+1]-p,b=Q[h+1]-w;if(v<=0||b<=0)return;const x=n.formats[a],y=X(n,e,r),C=c&&"="===y[0]?{text:y,color:null,align:"left",error:!1}:d(n,o,l,e,r),k=x?.border,$="1px solid var(--ink)",N=!!x?.fill||!!k||!!i,F=s?"1px solid var(--line-subtle)":"1px solid transparent",A={position:"absolute",left:p,top:w,width:v,height:b,boxSizing:"border-box",borderRight:k?.right?$:F,borderBottom:k?.bottom?$:F,borderTop:k?.top?$:void 0,borderLeft:k?.left?$:void 0,background:x?.fill??(i?"var(--surface)":void 0)};if((N||s)&&u.push(Je("div",{style:A},`b${a}`)),!C.text)return;const S=x?.align??C.align;let R=C.text;"string"==typeof R&&!C.error&&"right"===C.align&&!x?.wrap&&it(R,x)>v-4&&(R="#".repeat(Math.max(1,Math.floor(v/8))));let E=v,T=0;if(!i&&!x?.wrap&&"left"===C.align&&it(R,x)>v-8){if("left"===S||"center"===S)for(let t=r+1;t<=Math.min(r+40,n.colCount-1)&&(""===X(n,e,t)&&!z(n,e,t));t++)E+=J[t+1]-J[t];if("right"===S||"center"===S)for(let t=r-1;t>=Math.max(r-40,0)&&(""===X(n,e,t)&&!z(n,e,t));t--)T+=J[t+1]-J[t]}const M=x?.vAlign??"bottom",I=C.error?"var(--danger-text)":C.color??x?.color;f.push(Je("div",{"data-cell":a,className:"pointer-events-none",style:{position:"absolute",left:p-T,top:w,width:E+T,height:b,boxSizing:"border-box",padding:"0 4px",overflow:"hidden",display:"flex",alignItems:"top"===M?"flex-start":"middle"===M?"center":"flex-end",justifyContent:x?.wrap?void 0:"right"===S?"flex-end":"center"===S?"center":"flex-start",textAlign:S,whiteSpace:x?.wrap?"pre-wrap":"pre",wordBreak:x?.wrap?"break-word":void 0,fontSize:(x?.fontSize??t)*nt,lineHeight:1.3,paddingBottom:"bottom"===M?2:void 0,fontWeight:x?.bold?700:void 0,fontStyle:x?.italic?"italic":void 0,textDecoration:[x?.underline?"underline":"",x?.strike?"line-through":""].join(" ").trim()||void 0,color:I},children:Je("span",{style:x?.wrap?{width:"100%"}:void 0,children:R})},`t${a}`))};for(let t=e;t<=r;t++)for(let e=i;e<=a;e++){const r=z(n,t,e);(!r||r.r1===t&&r.c1===e)&&h(t,e,r)}for(const t of n.merges)(t.r1<e||t.c1<i)&&t.r2>=e&&t.r1<=r&&t.c2>=i&&t.c1<=a&&h(t.r1,t.c1,t);return[...u,...f]},be=(e,t,r,o)=>{const l=[],i=(n,i,a,s)=>{n.r2<e||n.r1>t||n.c2<r||n.c1>o||l.push(Je("div",{style:{position:"absolute",boxSizing:"border-box",pointerEvents:"none",left:J[n.c1],top:Q[n.r1],width:J[n.c2+1]-J[n.c1],height:Q[n.r2+1]-Q[n.r1],...a},children:s},i))},s=a.range,c=s.r1!==s.r2||s.c1!==s.c2,d=z(n,a.active.row,a.active.col),m=!!d&&d.r1===s.r1&&d.r2===s.r2&&d.c1===s.c1&&d.c2===s.c2;return i(s,"sel",{background:c&&!m?"color-mix(in srgb, var(--accent-fill) 12%, transparent)":void 0,border:"2px solid var(--accent-fill)"}),j&&i(j,"fill",{border:"1px dashed var(--ink-muted)"}),u&&i(u,"clip",{border:"2px dashed var(--accent-fill)"}),f.forEach((e,t)=>i(e.range,`ref${t}`,{border:`2px solid ${e.color}`,background:`color-mix(in srgb, ${e.color} 10%, transparent)`})),l},xe=[];q&&ee&&xe.push({key:"corner",left:tt,top:rt,width:re,height:te,offsetX:0,offsetY:0,r1:0,r2:q-1,c1:0,c2:ee-1}),q&&xe.push({key:"top",left:tt+re,top:rt,width:fe,height:te,offsetX:U.x,offsetY:0,r1:0,r2:q-1,c1:ge,c2:we}),ee&&xe.push({key:"left",left:tt,top:rt+te,width:re,height:me,offsetX:0,offsetY:U.y,r1:he,r2:pe,c1:0,c2:ee-1}),xe.push({key:"main",left:tt+re,top:rt+te,width:fe,height:me,offsetX:U.x,offsetY:U.y,r1:he,r2:pe,c1:ge,c2:we});const ye=a.range,Ce=[];for(let e=0;e<ee;e++)Ce.push(e);for(let e=ge;e<=we;e++)Ce.push(e);const ke=[];for(let e=0;e<q;e++)ke.push(e);for(let e=he;e<=pe;e++)ke.push(e);const $e=0===ye.r1&&ye.r2===n.rowCount-1,Ne=0===ye.c1&&ye.c2===n.colCount-1,Fe="absolute flex items-center justify-center select-none text-xs border-r border-b border-line",Ae="bg-accent-tint text-accent-text",Se="bg-surface-sunken text-ink-muted",De=ye.r2<q||ye.r2>=he,Re=ie(ye.c2+1),Ee=ae(ye.r2+1),Te=De&&!m&&Re>=tt&&Ee>=rt&&Re<=P.width&&Ee<=P.height,Me=z(n,a.active.row,a.active.col)??{r1:a.active.row,c1:a.active.col,r2:a.active.row,c2:a.active.col},ze={x:ie(Me.c1),y:ae(Me.r1),width:J[Me.c2+1]-J[Me.c1],height:Q[Me.r2+1]-Q[Me.r1],viewportWidth:P.width,viewportHeight:P.height},{filter:Ie}=n,Ue=Ie?.range.r1??-1,Oe=[];if(Ie&&(Ue<q||Ue>=he&&Ue<=pe))for(let e=Ie.range.c1;e<=Ie.range.c2;e++)J[e+1]>J[e]&&(e<ee||e>=ge&&e<=we)&&Oe.push(e);return Je("div",{ref:I,tabIndex:0,role:"grid","aria-label":n.name,"aria-rowcount":n.rowCount,"aria-colcount":n.colCount,className:"relative h-full w-full overflow-auto outline-none bg-surface text-ink",onScroll:e=>O({x:e.currentTarget.scrollLeft,y:e.currentTarget.scrollTop}),onKeyDown:A,onCopy:S,onCut:R,onPaste:E,children:Je("div",{style:{width:tt+ne,height:rt+le},children:qe("div",{className:"sticky top-0 left-0 overflow-hidden",style:{width:P.width,height:P.height},children:[qe("div",{className:"absolute inset-0",onPointerDown:e=>{if(0!==e.button)return;const t=ce(e.clientX,e.clientY);if(m)return e.preventDefault(),g(L(t,t),!1),void ue(e=>g(L(t,ce(e.clientX,e.clientY)),!1),e=>g(L(t,ce(e.clientX,e.clientY)),!0));if(I.current?.focus({preventScroll:!0}),e.detail>=2)return e.preventDefault(),void w(t);const r=e.shiftKey?a.active:z(n,t.row,t.col)?{row:z(n,t.row,t.col).r1,col:z(n,t.row,t.col).c1}:t;de(r,t),ue(e=>de(r,ce(e.clientX,e.clientY)),()=>{})},onContextMenu:e=>k(e,"cell",ce(e.clientX,e.clientY)),children:[xe.map(e=>Je("div",{className:"absolute overflow-hidden",style:{left:e.left,top:e.top,width:e.width,height:e.height},children:qe("div",{className:"absolute",style:{left:-e.offsetX,top:-e.offsetY,width:ne,height:le},children:[ve(e.r1,e.r2,e.c1,e.c2),be(e.r1,e.r2,e.c1,e.c2)]})},e.key)),te>0&&Je("div",{className:"absolute bg-line-strong pointer-events-none",style:{left:0,right:0,top:rt+te-1,height:2}}),re>0&&Je("div",{className:"absolute bg-line-strong pointer-events-none",style:{top:0,bottom:0,left:tt+re-1,width:2}})]}),Oe.map(e=>{const t=ie(e+1),r=ae(Ue),n=Q[Ue+1]-Q[Ue],o=(Ie?.excluded[e]?.length??0)>0;return Je("button",{type:"button","aria-label":M.filterColumn(p(e)),onClick:t=>{t.stopPropagation(),$(e,t.currentTarget.getBoundingClientRect())},onPointerDown:e=>e.stopPropagation(),className:`absolute flex items-center justify-center rounded border ${o?"":"border-line"} ${o?"border-accent-fill bg-accent-tint":"bg-surface hover:bg-surface-sunken"}`,style:{left:t-19,top:r+Math.max(0,(n-17)/2),width:17,height:17},children:Je(Qe,{name:"filter",size:11})},e)}),Te&&Je("div",{"aria-label":M.fillHandle,className:"absolute bg-accent-fill border border-surface cursor-crosshair",style:{left:Re-5,top:Ee-5,width:8,height:8},onPointerDown:e=>{e.preventDefault(),e.stopPropagation();const t=a.range;let r=null;ue(e=>{r=(e=>{const r=ce(e.clientX,e.clientY);return(r.row>t.r2?r.row-t.r2:r.row<t.r1?t.r1-r.row:0)>=(r.col>t.c2?r.col-t.c2:r.col<t.c1?t.c1-r.col:0)?{...t,r1:Math.min(t.r1,r.row),r2:Math.max(t.r2,r.row)}:{...t,c1:Math.min(t.c1,r.col),c2:Math.max(t.c2,r.col)}})(e),G(r)},()=>{G(null),!r||r.r1===t.r1&&r.r2===t.r2&&r.c1===t.c1&&r.c2===t.c2||v(r)})}}),Je("div",{className:"absolute top-0 overflow-hidden bg-surface-sunken",style:{left:tt,right:0,height:rt},children:Ce.map(e=>{const t=J[e+1]-J[e];if(t<=0)return null;const r=J[e]-(e>=ee?U.x:0),o=e>=ye.c1&&e<=ye.c2;return qe("div",{className:`${Fe} ${o?Ae:Se} ${o&&$e?"font-semibold":""}`,style:{left:r,top:0,width:t,height:rt},onPointerDown:t=>((e,t)=>{if(0!==e.button)return;I.current?.focus({preventScroll:!0});const r=e.shiftKey?a.active.col:t,o=e=>{const t={r1:0,c1:Math.min(r,e),r2:n.rowCount-1,c2:Math.max(r,e)};h({active:{row:0,col:r},range:t})};o(t),ue(e=>o(ce(e.clientX,e.clientY).col),()=>{})})(t,e),onContextMenu:t=>k(t,"col",{row:0,col:e}),children:[p(e),Je("div",{className:"absolute top-0 bottom-0 cursor-col-resize",style:{right:-3,width:7},onPointerDown:t=>((e,t)=>{e.preventDefault(),e.stopPropagation();const r=e.clientX,n=J[t+1]-J[t],o=e=>Math.max(16,Math.round(n+e.clientX-r));ue(e=>K({col:t,width:o(e)}),e=>{K(null),o(e)!==n&&b(t,o(e))})})(t,e),onDoubleClick:t=>{t.stopPropagation(),y(e)}})]},e)})}),Je("div",{className:"absolute left-0 overflow-hidden bg-surface-sunken",style:{top:rt,bottom:0,width:tt},children:ke.map(e=>{const t=Q[e+1]-Q[e];if(t<=0)return null;const r=Q[e]-(e>=q?U.y:0),o=e>=ye.r1&&e<=ye.r2;return qe("div",{className:`${Fe} ${o?Ae:Se} ${o&&Ne?"font-semibold":""}`,style:{left:0,top:r,width:tt,height:t},onPointerDown:t=>((e,t)=>{if(0!==e.button)return;I.current?.focus({preventScroll:!0});const r=e.shiftKey?a.active.row:t,o=e=>{const t={r1:Math.min(r,e),c1:0,r2:Math.max(r,e),c2:n.colCount-1};h({active:{row:r,col:0},range:t})};o(t),ue(e=>o(ce(e.clientX,e.clientY).row),()=>{})})(t,e),onContextMenu:t=>k(t,"row",{row:e,col:0}),children:[e+1,Je("div",{className:"absolute left-0 right-0 cursor-row-resize",style:{bottom:-3,height:7},onPointerDown:t=>((e,t)=>{e.preventDefault(),e.stopPropagation();const r=e.clientY,n=Q[t+1]-Q[t],o=e=>Math.max(12,Math.round(n+e.clientY-r));ue(e=>V({row:t,height:o(e)}),e=>{V(null),o(e)!==n&&x(t,o(e))})})(t,e),onDoubleClick:t=>{t.stopPropagation(),C(e)}})]},e)})}),Je("div",{role:"button","aria-label":M.selectAll,className:`${Fe} top-0 left-0 cursor-pointer bg-surface-sunken hover:bg-line`,style:{width:tt,height:rt},onPointerDown:e=>{e.preventDefault(),I.current?.focus({preventScroll:!0}),h({active:{row:0,col:0},range:{r1:0,c1:0,r2:n.rowCount-1,c2:n.colCount-1}})},onContextMenu:e=>k(e,"corner",{row:0,col:0})}),F?.(ze)]})})})}),st=["#000000","#434343","#666666","#999999","#cccccc","#efefef","#ffffff","#c00000","#ff0000","#ffc000","#ffff00","#92d050","#00b050","#00b0f0","#0070c0","#002060","#7030a0","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#d9d2e9","#ead1dc"],ct=["#1a73e8","#d93025","#7b1fa2","#188038","#e37400","#c5221f"];function ut(e,t){let r=!1;for(let n=0;n<t;n++)'"'===e[n]&&(r=!r);return r}function dt(e,t){if("="!==e[0]||ut(e,t))return null;const r=/[A-Za-z][A-Za-z0-9.]*$/.exec(e.slice(0,t));if(!r)return null;if("!"===e[r.index-1]||"("===e[t])return null;const o=r[0].toUpperCase(),l=n.filter(e=>e.startsWith(o));return l.length?{start:r.index,prefix:o,matches:l.slice(0,8)}:null}var ft={ABS:"value",AND:"condition1, [condition2, ...]",AVERAGE:"value1, [value2, ...]",AVERAGEIF:"range, criterion, [average_range]",AVERAGEIFS:"average_range, range1, criterion1, ...",CEILING:"value, [factor]","CEILING.MATH":"value, [factor]",CHOOSE:"index, choice1, [choice2, ...]",COLUMN:"[cell]",COLUMNS:"range",CONCAT:"value1, [value2, ...]",CONCATENATE:"value1, [value2, ...]",COS:"angle",COUNT:"value1, [value2, ...]",COUNTA:"value1, [value2, ...]",COUNTBLANK:"range",COUNTIF:"range, criterion",COUNTIFS:"range1, criterion1, ...",DATE:"year, month, day",DATEDIF:"start, end, unit",DAY:"date",DAYS:"end, start",EDATE:"start, months",EOMONTH:"start, months",EXACT:"text1, text2",EXP:"value",FIND:"find, within, [start]",FLOOR:"value, [factor]","FLOOR.MATH":"value, [factor]",FV:"rate, periods, payment, [present], [type]",HLOOKUP:"key, range, row, [approximate]",HOUR:"time",IF:"condition, if_true, [if_false]",IFERROR:"value, [if_error]",IFNA:"value, [if_na]",IFS:"condition1, value1, ...",INDEX:"range, row, [column]",INT:"value",ISBLANK:"value",ISERROR:"value",ISLOGICAL:"value",ISNA:"value",ISNUMBER:"value",ISTEXT:"value",LARGE:"range, k",LEFT:"text, [count]",LEN:"text",LN:"value",LOG:"value, [base]",LOG10:"value",LOWER:"text",MATCH:"key, range, [type]",MAX:"value1, [value2, ...]",MEDIAN:"value1, [value2, ...]",MID:"text, start, count",MIN:"value1, [value2, ...]",MINUTE:"time",MOD:"value, divisor",MODE:"value1, [value2, ...]","MODE.SNGL":"value1, [value2, ...]",MONTH:"date",N:"value",NA:"",NETWORKDAYS:"start, end, [holidays]",NOT:"condition",NOW:"",NPV:"rate, value1, [value2, ...]",OR:"condition1, [condition2, ...]",PI:"",PMT:"rate, periods, present, [future], [type]",POWER:"value, exponent",PRODUCT:"value1, [value2, ...]",PROPER:"text",PV:"rate, periods, payment, [future], [type]",RAND:"",RANDBETWEEN:"low, high",RANK:"value, range, [ascending]","RANK.EQ":"value, range, [ascending]",REPLACE:"text, start, count, new",REPT:"text, count",RIGHT:"text, [count]",ROUND:"value, [places]",ROUNDDOWN:"value, [places]",ROUNDUP:"value, [places]",ROW:"[cell]",ROWS:"range",SEARCH:"find, within, [start]",SECOND:"time",SIGN:"value",SIN:"angle",SMALL:"range, k",SQRT:"value",STDEV:"value1, [value2, ...]","STDEV.P":"value1, [value2, ...]","STDEV.S":"value1, [value2, ...]",STDEVP:"value1, [value2, ...]",SUBSTITUTE:"text, find, new, [occurrence]",SUM:"value1, [value2, ...]",SUMIF:"range, criterion, [sum_range]",SUMIFS:"sum_range, range1, criterion1, ...",SUMPRODUCT:"range1, [range2, ...]",SWITCH:"value, case1, result1, ..., [default]",TAN:"angle",TEXT:"value, format",TEXTJOIN:"delimiter, skip_blank, value1, ...",TIME:"hour, minute, second",TODAY:"",TRIM:"text",TRUNC:"value, [places]",UPPER:"text",VALUE:"text",VAR:"value1, [value2, ...]","VAR.P":"value1, [value2, ...]","VAR.S":"value1, [value2, ...]",VARP:"value1, [value2, ...]",VLOOKUP:"key, range, column, [approximate]",WEEKDAY:"date, [type]",XLOOKUP:"key, lookup_range, result_range, [if_not_found], [match_mode]",XOR:"condition1, [condition2, ...]",YEAR:"date"},mt=(()=>{const e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let e=0;e<8;e++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function ht(e){let t=4294967295;for(let r=0;r<e.length;r++)t=mt[255&(t^e[r])]^t>>>8;return(4294967295^t)>>>0}async function gt(e,t){const r=t.writable.getWriter();return r.write(e).then(()=>r.close()).catch(()=>{}),new Uint8Array(await new Response(t.readable).arrayBuffer())}async function pt(e){return"undefined"==typeof CompressionStream?null:gt(e,new CompressionStream("deflate-raw"))}async function wt(e){return gt(e,new DecompressionStream("deflate-raw"))}var vt=new Set(["CONCAT","IFS","SWITCH","TEXTJOIN","XLOOKUP","XOR","IFNA","DAYS","STDEV.S","STDEV.P","VAR.S","VAR.P","MODE.SNGL","RANK.EQ","CEILING.MATH","FLOOR.MATH"]);function bt(e){const{tokens:t}=te(e);let r="",n=0;for(const o of t){if("ident"!==o.type)continue;const t=o.value.replace(/^_xlfn\.(?:_xlws\.)?/i,"").replace(/^_xlws\./i,"");t!==o.value&&(r+=e.slice(n,o.start)+t,n=o.end)}return`=${r}${e.slice(n)}`}function xt(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var yt='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n',Ct="http://schemas.openxmlformats.org/spreadsheetml/2006/main",kt="http://schemas.openxmlformats.org/officeDocument/2006/relationships";function $t(e){return`FF${e.replace("#","").toUpperCase().padStart(6,"0").slice(0,6)}`}var Nt=class{fonts=[`<font><sz val="${t}"/><name val="Arial"/></font>`];fills=['<fill><patternFill patternType="none"/></fill>','<fill><patternFill patternType="gray125"/></fill>'];borders=["<border><left/><right/><top/><bottom/><diagonal/></border>"];numFmts=[];xfs=['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'];seen=new Map;index(e,t){const r=e.indexOf(t);return r>=0?r:(e.push(t),e.length-1)}add(e){if(!e||!Object.keys(e).length)return 0;const r=JSON.stringify(e),n=this.seen.get(r);if(void 0!==n)return n;const o=this.index(this.fonts,`<font>${e.bold?"<b/>":""}${e.italic?"<i/>":""}${e.strike?"<strike/>":""}${e.underline?"<u/>":""}<sz val="${e.fontSize??t}"/>${e.color?`<color rgb="${$t(e.color)}"/>`:""}<name val="Arial"/></font>`),l=e.fill?this.index(this.fills,`<fill><patternFill patternType="solid"><fgColor rgb="${$t(e.fill)}"/><bgColor indexed="64"/></patternFill></fill>`):0,i=(e,t)=>t?`<${e} style="thin"><color auto="1"/></${e}>`:`<${e}/>`,a=e.border??{},s=this.index(this.borders,`<border>${i("left",a.left)}${i("right",a.right)}${i("top",a.top)}${i("bottom",a.bottom)}<diagonal/></border>`);let c=0;e.numFmt&&"General"!==e.numFmt&&(c="@"===e.numFmt?49:164+this.index(this.numFmts,e.numFmt));const u=e.align||e.vAlign||e.wrap?`<alignment${e.align?` horizontal="${e.align}"`:""}${e.vAlign?` vertical="${"middle"===e.vAlign?"center":e.vAlign}"`:""}${e.wrap?' wrapText="1"':""}/>`:"",d=`<xf numFmtId="${c}" fontId="${o}" fillId="${l}" borderId="${s}" xfId="0" applyFont="1"${l?' applyFill="1"':""}${s?' applyBorder="1"':""}${c?' applyNumberFormat="1"':""}${u?' applyAlignment="1"':""}${u?`>${u}</xf>`:"/>"}`;return this.xfs.push(d),this.seen.set(r,this.xfs.length-1),this.xfs.length-1}toXml(){const e=this.numFmts.length?`<numFmts count="${this.numFmts.length}">${this.numFmts.map((e,t)=>`<numFmt numFmtId="${164+t}" formatCode="${xt(e)}"/>`).join("")}</numFmts>`:"";return`${yt}<styleSheet xmlns="${Ct}">${e}<fonts count="${this.fonts.length}">${this.fonts.join("")}</fonts><fills count="${this.fills.length}">${this.fills.join("")}</fills><borders count="${this.borders.length}">${this.borders.join("")}</borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="${this.xfs.length}">${this.xfs.join("")}</cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`}};function Ft(e,t,r,n,l,i){const a=`${p(l)}${n+1}`,s=e.cells[n]?.[l]??"",c=e.formats[D(n,l)],u=i.add(c),d=u?` s="${u}"`:"";if(""===s)return u?`<c r="${a}"${d}/>`:"";const f=r.value(t,n,l);if(E(s)){const e=`<f>${xt(function(e){const t=e.slice(1),{tokens:r}=te(t);let n="",o=0;for(let e=0;e<r.length;e++){const l=r[e],i=r[e+1];"ident"===l.type&&"op"===i?.type&&"("===i.value&&vt.has(l.value.toUpperCase())&&(n+=`${t.slice(o,l.start)}_xlfn.${l.value.toUpperCase()}`,o=l.end)}return n+t.slice(o)}(s))}</f>`;if("number"==typeof f)return`<c r="${a}"${d}>${e}<v>${f}</v></c>`;if("boolean"==typeof f)return`<c r="${a}"${d} t="b">${e}<v>${f?1:0}</v></c>`;if(f instanceof o){return`<c r="${a}"${d} t="e">${e}<v>${/^#(?:REF!|N\/A|NAME\?|DIV\/0!|VALUE!|NUM!|NULL!)$/.test(f.code)?f.code:"#VALUE!"}</v></c>`}return`<c r="${a}"${d} t="str">${e}<v>${xt(null===f?"":f)}</v></c>`}if("number"==typeof f)return`<c r="${a}"${d}><v>${f}</v></c>`;if("boolean"==typeof f)return`<c r="${a}"${d} t="b"><v>${f?1:0}</v></c>`;const m=String(f??"");return`<c r="${a}"${d} t="inlineStr"><is><t${m!==m.trim()||/\n/.test(m)?' xml:space="preserve"':""}>${xt(m)}</t></is></c>`}function At(t,n,o,l){const i=ie(t);let a=i?.row??0,s=i?.col??0;const c=new Map;for(const e of Object.keys(t.formats)){const[t,r]=e.split(":").map(Number);a=Math.max(a,t),s=Math.max(s,r),c.has(t)||c.set(t,[]),c.get(t).push(r)}const u=new Set(t.hiddenRows);for(const e of[...t.hiddenRows,...Object.keys(t.rowHeights).map(Number)])a=Math.max(a,e);const d=[];for(let e=0;e<=a;e++){const r=t.cells[e]??[],i=new Set(c.get(e)??[]);r.forEach((e,t)=>{""!==e&&i.add(t)});const a=t.rowHeights[e];if(!i.size&&void 0===a&&!u.has(e))continue;const s=[...i].sort((e,t)=>e-t).map(r=>Ft(t,n,o,e,r,l)).join(""),f=`${void 0!==a?` ht="${(.75*a).toFixed(2)}" customHeight="1"`:""}${u.has(e)?' hidden="1"':""}`;d.push(`<row r="${e+1}"${f}>${s}</row>`)}const f=new Set(t.hiddenCols),m=[...new Set([...Object.keys(t.colWidths).map(Number),...f])].sort((e,t)=>e-t),h=m.length?`<cols>${m.map(r=>`<col min="${r+1}" max="${r+1}" width="${(((t.colWidths[r]??e)-5)/7).toFixed(4)}" customWidth="1"${f.has(r)?' hidden="1"':""}/>`).join("")}</cols>`:"",{frozenRows:g,frozenCols:w}=t,v=g||w?`<pane${w?` xSplit="${w}"`:""}${g?` ySplit="${g}"`:""} topLeftCell="${p(w)}${g+1}" activePane="${g&&w?"bottomRight":g?"bottomLeft":"topRight"}" state="frozen"/>`:"",b=t.merges.length?`<mergeCells count="${t.merges.length}">${t.merges.map(e=>`<mergeCell ref="${V(e)}"/>`).join("")}</mergeCells>`:"",x=t.filter?`<autoFilter ref="${V(t.filter.range)}"/>`:"",y=t.tabColor?`<sheetPr><tabColor rgb="${$t(t.tabColor)}"/></sheetPr>`:"";return`${yt}<worksheet xmlns="${Ct}">${y}<dimension ref="A1:${p(s)}${a+1}"/><sheetViews><sheetView${0===n?' tabSelected="1"':""} workbookViewId="0">${v}</sheetView></sheetViews><sheetFormatPr defaultColWidth="${((e-5)/7).toFixed(4)}" defaultRowHeight="${(.75*r).toFixed(2)}" customHeight="1"/>${h}<sheetData>${d.join("")}</sheetData>${x}${b}</worksheet>`}async function St(e,t){const r=new Nt,n=function(e){const t=new Set;return e.map((e,r)=>{const n=e.name.replace(/[[\]:*?/\\]/g," ").trim().slice(0,31)||`Sheet ${r+1}`;let o=n;for(let e=2;t.has(o.toLowerCase());e++)o=`${n.slice(0,28)} ${e}`;return t.add(o.toLowerCase()),o})}(e),o=e.map((e,n)=>({name:`xl/worksheets/sheet${n+1}.xml`,text:At(e,n,t,r)})),l=e.map((e,t)=>{return e.filter?`<definedName name="_xlnm._FilterDatabase" localSheetId="${t}" hidden="1">${xt(`'${n[t].replace(/'/g,"''")}'!${r=e.filter.range,`$${p(r.c1)}$${r.r1+1}:$${p(r.c2)}$${r.r2+1}`}`)}</definedName>`:"";var r}).join("");return async function(e){const t=new TextEncoder,r=[],n=[];let o=0;for(const l of e){const e=t.encode(l.name),i=t.encode(l.text),a=await pt(i),s=null===a||a.length>=i.length,c=s?i:a,u=ht(i),d=new Uint8Array(30+e.length),f=new DataView(d.buffer);f.setUint32(0,67324752,!0),f.setUint16(4,20,!0),f.setUint16(6,2048,!0),f.setUint16(8,s?0:8,!0),f.setUint32(14,u,!0),f.setUint32(18,c.length,!0),f.setUint32(22,i.length,!0),f.setUint16(26,e.length,!0),d.set(e,30);const m=new Uint8Array(46+e.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint16(8,2048,!0),h.setUint16(10,s?0:8,!0),h.setUint32(16,u,!0),h.setUint32(20,c.length,!0),h.setUint32(24,i.length,!0),h.setUint16(28,e.length,!0),h.setUint32(42,o,!0),m.set(e,46),r.push(d,c),n.push(m),o+=d.length+c.length}const l=n.reduce((e,t)=>e+t.length,0),i=new Uint8Array(22),a=new DataView(i.buffer);a.setUint32(0,101010256,!0),a.setUint16(8,e.length,!0),a.setUint16(10,e.length,!0),a.setUint32(12,l,!0),a.setUint32(16,o,!0);const s=new Uint8Array(o+l+22);let c=0;for(const e of[...r,...n,i])s.set(e,c),c+=e.length;return s}([{name:"[Content_Types].xml",text:`${yt}<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="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>${e.map((e,t)=>`<Override PartName="/xl/worksheets/sheet${t+1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join("")}</Types>`},{name:"_rels/.rels",text:`${yt}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${kt}/officeDocument" Target="xl/workbook.xml"/></Relationships>`},{name:"xl/workbook.xml",text:`${yt}<workbook xmlns="${Ct}" xmlns:r="${kt}"><sheets>${n.map((e,t)=>`<sheet name="${xt(e)}" sheetId="${t+1}" r:id="rId${t+1}"/>`).join("")}</sheets>${l?`<definedNames>${l}</definedNames>`:""}<calcPr calcId="0" fullCalcOnLoad="1"/></workbook>`},{name:"xl/_rels/workbook.xml.rels",text:`${yt}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${e.map((e,t)=>`<Relationship Id="rId${t+1}" Type="${kt}/worksheet" Target="worksheets/sheet${t+1}.xml"/>`).join("")}<Relationship Id="rId${e.length+1}" Type="${kt}/styles" Target="styles.xml"/></Relationships>`},{name:"xl/styles.xml",text:r.toXml()},...o])}var Dt={1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",9:"0%",10:"0.00%",11:"0.00E+00",14:"dd/mm/yyyy",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"dd/mm/yyyy h:mm",37:"#,##0;(#,##0)",38:"#,##0;[Red](#,##0)",39:"#,##0.00;(#,##0.00)",40:"#,##0.00;[Red](#,##0.00)",45:"mm:ss",46:"[h]:mm:ss",47:"mm:ss.0",48:"##0.0E+0",49:"@"},Rt=["FFFFFF","000000","E7E6E6","44546A","4472C4","ED7D31","A5A5A5","FFC000","5B9BD5","70AD47","0563C1","954F72"],Et={0:"000000",1:"FFFFFF",2:"FF0000",3:"00FF00",4:"0000FF",5:"FFFF00",6:"FF00FF",7:"00FFFF",8:"000000",9:"FFFFFF",10:"FF0000",11:"00FF00",12:"0000FF",13:"FFFF00",14:"FF00FF",15:"00FFFF"};function Tt(e){if(!e)return;const t=e.getAttribute("rgb");if(t)return`#${t.slice(-6).toLowerCase()}`;const r=Number(e.getAttribute("tint")??0),n=e.getAttribute("theme");if(null!==n){const e=Rt[Number(n)];return e?`#${function(e,t){const r=r=>{const n=parseInt(e.slice(r,r+2),16),o=t<0?n*(1+t):n+(255-n)*t;return Math.round(o).toString(16).padStart(2,"0")};return`${r(0)}${r(2)}${r(4)}`}(e,r)}`.toLowerCase():void 0}const o=e.getAttribute("indexed");if(null!==o){const e=Et[Number(o)];return e?`#${e}`.toLowerCase():void 0}}var Mt=e=>(new DOMParser).parseFromString(e,"application/xml"),zt=(e,t)=>Array.from(e.getElementsByTagNameNS("*",t)),It=(e,t)=>zt(e,t)[0],Ut=(e,t)=>Array.from(e.children).filter(e=>e.localName===t);function Ot(e){const t=/^([A-Z]+)(\d+)$/.exec(e);return{row:Number(t[2])-1,col:g(t[1])}}function Lt(e){const[t,r=t]=e.replace(/\$/g,"").split(":"),n=Ot(t),o=Ot(r);return{r1:n.row,c1:n.col,r2:o.row,c2:o.col}}function Pt(e,t,r,n){const o=Mt(t),l=U(e),i=[],a={},s=new Map;for(const e of zt(o,"c")){const t=e.getAttribute("r");if(!t)continue;const{row:o,col:l}=Ot(t),c=n[Number(e.getAttribute("s")??0)];c&&Object.keys(c).length&&(a[D(o,l)]=c);const u=Ut(e,"f")[0],d=Ut(e,"v")[0]?.textContent??"",f=e.getAttribute("t");let m="";if(u){const e=u.getAttribute("si");if("shared"===u.getAttribute("t")&&null!==e)if(u.textContent)s.set(e,{text:u.textContent,row:o,col:l}),m=bt(u.textContent);else{const t=s.get(e);t&&(m=q(bt(t.text),o-t.row,l-t.col))}else u.textContent&&(m=bt(u.textContent))}if(m||(m="s"===f?r[Number(d)]??"":"inlineStr"===f?zt(e,"t").map(e=>e.textContent??"").join(""):"b"===f?"1"===d?"TRUE":"FALSE":d,"s"!==f&&"inlineStr"!==f&&"str"!==f||!/^(?:=|-?\d|'|true$|false$)/i.test(m)||(m=`'${m}`)),""!==m){for(;i.length<=o;)i.push([]);for(;i[o].length<=l;)i[o].push("");i[o][l]=m}}const c={},u=[];for(const e of zt(o,"col")){const t=Number(e.getAttribute("min"))-1,r=Math.min(Number(e.getAttribute("max"))-1,t+500),n=Number(e.getAttribute("width")??0);for(let o=t;o<=r;o++)n&&"1"===e.getAttribute("customWidth")&&(c[o]=Math.round(7*n+5)),"1"===e.getAttribute("hidden")&&u.push(o)}const d={},f=[];for(const e of zt(o,"row")){const t=Number(e.getAttribute("r"))-1,r=e.getAttribute("ht");r&&"1"===e.getAttribute("customHeight")&&(d[t]=Math.round(Number(r)/.75)),"1"===e.getAttribute("hidden")&&f.push(t)}const m=It(o,"pane"),h="frozen"===m?.getAttribute("state"),g=It(o,"autoFilter")?.getAttribute("ref"),p=Tt(It(o,"tabColor"));return{...l,tabColor:p,cells:i,formats:a,colWidths:c,rowHeights:d,hiddenCols:u,hiddenRows:f,merges:zt(o,"mergeCell").map(e=>Lt(e.getAttribute("ref")??"A1")),frozenRows:h?Number(m?.getAttribute("ySplit")??0):0,frozenCols:h?Number(m?.getAttribute("xSplit")??0):0,filter:g?{range:Lt(g),excluded:{}}:null,rowCount:Math.max(l.rowCount,i.length+100),colCount:Math.max(l.colCount,i.reduce((e,t)=>Math.max(e,t.length),0))}}async function Bt(e){const t=await async function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=-1;for(let n=e.length-22;n>=Math.max(0,e.length-66e3);n--)if(101010256===t.getUint32(n,!0)){r=n;break}if(r<0)throw new Error("Not a zip file");const n=t.getUint16(r+10,!0);let o=t.getUint32(r+16,!0);const l=new TextDecoder,i=new Map;for(let r=0;r<n;r++){const r=t.getUint16(o+10,!0),n=t.getUint32(o+20,!0),a=t.getUint16(o+28,!0),s=t.getUint16(o+30,!0),c=t.getUint16(o+32,!0),u=t.getUint32(o+42,!0),d=l.decode(e.subarray(o+46,o+46+a));if(o+=46+a+s+c,!/\.(xml|rels)$/i.test(d))continue;const f=u+30+t.getUint16(u+26,!0)+t.getUint16(u+28,!0),m=e.subarray(f,f+n);i.set(d,l.decode(8===r?await wt(m):m))}return i}(e),r=t.get("xl/workbook.xml");if(!r)throw new Error("Not a workbook");const n=Mt(t.get("xl/_rels/workbook.xml.rels")??"<Relationships/>"),o=new Map(zt(n,"Relationship").map(e=>[e.getAttribute("Id"),e.getAttribute("Target")??""])),l=t.get("xl/sharedStrings.xml")?zt(Mt(t.get("xl/sharedStrings.xml")),"si").map(e=>zt(e,"t").filter(e=>"rPh"!==e.parentElement?.localName).map(e=>e.textContent??"").join("")):[],i=function(e){if(!e)return[];const t=Mt(e),r=new Map(zt(t,"numFmt").map(e=>[Number(e.getAttribute("numFmtId")),e.getAttribute("formatCode")??""])),n=It(t,"fonts"),o=It(t,"fills"),l=It(t,"borders"),i=It(t,"cellXfs");if(!i)return[];const a=n?Ut(n,"font"):[],s=o?Ut(o,"fill"):[],c=l?Ut(l,"border"):[],u=Number(a[0]?Ut(a[0],"sz")[0]?.getAttribute("val")??0:0);return Ut(i,"xf").map(e=>{const t={},n=Number(e.getAttribute("numFmtId")??0),o=r.get(n)??Dt[n];o&&"General"!==o&&(t.numFmt=o);const l=a[Number(e.getAttribute("fontId")??0)];if(l){Ut(l,"b").length&&(t.bold=!0),Ut(l,"i").length&&(t.italic=!0),Ut(l,"u").length&&(t.underline=!0),Ut(l,"strike").length&&(t.strike=!0);const e=Number(Ut(l,"sz")[0]?.getAttribute("val")??0);e&&e!==u&&(t.fontSize=e);const r=Tt(Ut(l,"color")[0]);r&&"#000000"!==r&&(t.color=r)}const i=s[Number(e.getAttribute("fillId")??0)]?.getElementsByTagNameNS("*","patternFill")[0];if(i&&"solid"===i.getAttribute("patternType")){const e=Tt(Ut(i,"fgColor")[0]);e&&(t.fill=e)}const d=c[Number(e.getAttribute("borderId")??0)];if(d){const e=e=>!!Ut(d,e)[0]?.getAttribute("style"),r={top:e("top"),right:e("right"),bottom:e("bottom"),left:e("left")};(r.top||r.right||r.bottom||r.left)&&(t.border={...r.top?{top:!0}:{},...r.right?{right:!0}:{},...r.bottom?{bottom:!0}:{},...r.left?{left:!0}:{}})}const f=Ut(e,"alignment")[0];if(f){const e=f.getAttribute("horizontal");"left"!==e&&"center"!==e&&"right"!==e||(t.align=e);const r=f.getAttribute("vertical");"top"!==r&&"bottom"!==r||(t.vAlign=r),"center"===r&&(t.vAlign="middle");const n=f.getAttribute("wrapText");"1"!==n&&"true"!==n||(t.wrap=!0)}return t})}(t.get("xl/styles.xml")),a=[];for(const e of zt(Mt(r),"sheet")){const r=e.getAttribute("name")??`Sheet ${a.length+1}`,n=e.getAttributeNS(kt,"id")??e.getAttribute("r:id"),s=o.get(n)??"",c=s.startsWith("/")?s.slice(1):`xl/${s}`,u=t.get(c);u&&a.push(Pt(r,u,l,i))}if(!a.length)throw new Error("No sheets");return a}import{Fragment as Ht,jsx as Kt,jsxs as Wt}from"react/jsx-runtime";var Vt=[8,9,10,11,12,14,16,18,20,24,28,36],Xt="undefined"!=typeof navigator&&/Mac|iPhone|iPad/.test(navigator.platform),jt=Xt?"⌘":"Ctrl+";function Gt(e,t,r){const n=URL.createObjectURL(new Blob([e],{type:t})),o=document.createElement("a");o.href=n,o.download=r,o.click(),URL.revokeObjectURL(n)}var _t=".csv,.tsv,.txt,.xlsx,.xls,.ods";function Yt({spreadsheetId:e,onClose:t}){const r=oe(),{store:n,canCreate:o=!0,canDelete:l=!0}=le(),[i]=he(()=>null!=Ke()),[a,s]=he(null);return!n||i?Kt(Jt,{onClose:t}):e?Kt(Qt,{store:n,id:e,onClose:t}):a?.id?Kt(Qt,{store:n,id:a.id,onClose:()=>s(null)},a.key):a?.file?Kt(Jt,{initialFile:a.file,hasStore:!0,onClose:()=>s(null)},a.key):Kt(ce,{words:{windowTitle:r.filesHeading,heading:r.filesHeading,newFile:r.newFile,openFile:r.openFile,emptyTitle:r.filesEmptyTitle,emptyBody:r.filesEmptyBody,delete:r.deleteFile,deleteConfirm:r.deleteConfirm,createFailed:r.createFailed,deleteFailed:r.deleteFailed},list:n.list,create:()=>n.create(r.untitled),remove:n.remove,canCreate:o,canDelete:l,accept:_t,onOpen:e=>s({key:Date.now(),id:e}),onOpenFile:e=>s({key:Date.now(),file:e})})}function Zt({id:e,onClose:t}){return Kt(Yt,{spreadsheetId:e,onClose:t})}function Qt({store:e,id:t,onClose:r}){const n=oe(),[o,l]=he(null),[i,a]=he(!1),s=ue(()=>{a(!1),e.get(t).then(e=>l(t=>({kept:e,nonce:(t?.nonce??0)+1})),()=>a(!0))},[t,e]);return de(s,[s]),i?Kt("div",{className:"office-open-failed",children:Kt(Se,{title:n.storedOpenFailed,children:r&&Kt(ke,{onClick:r,children:n.backToFiles})})}):o?Kt(Jt,{stored:{store:e,...o.kept},onClose:r,onReload:s},o.nonce):Kt(Ee,{size:"sm",padding:"",className:"h-full",label:n.loading})}function Jt({stored:e,initialFile:r,hasStore:n,onClose:o,onReload:d}){const g=oe(),p=me(void 0);void 0===p.current&&(p.current=e?null:Ke());const le=me(p.current?.data??null),[ce]=he(()=>{const e=p.current;if(!e)return null;const t=qt(e.data,g.sheetName(1));return t?{sheet:t,title:e.data.filename.replace(/\.(csv|tsv|txt)$/i,"")}:null}),[Se,Ee]=he(()=>e?J(e.workbook,g.sheetName(1)):ce?[ce.sheet]:[U(g.sheetName(1))]),[Ve,Xe]=he(0),[je,Ge]=he(e?.title??ce?.title??g.untitled),[_e,Ye]=he(()=>p.current?.data.onEmail),Ze=me(Se),Qe=me([]),Je=me([]),[,qe]=he(0),et=ue(e=>{const t=Ze.current,r=e(t);r!==t&&(Qe.current.push(t),Qe.current.length>100&&Qe.current.shift(),Je.current=[],Ze.current=r,Ee(r),qe(e=>e+1))},[]),tt=ue(e=>{Qe.current=[],Je.current=[],Ze.current=e,Ee(e),Xe(0),qe(e=>e+1)},[]),rt=ue(()=>{const e=Qe.current.pop();e&&(Je.current.push(Ze.current),Ze.current=e,Ee(e),Xe(t=>Math.min(t,e.length-1)),qe(e=>e+1))},[]),nt=ue(()=>{const e=Je.current.pop();e&&(Qe.current.push(Ze.current),Ze.current=e,Ee(e),Xe(t=>Math.min(t,e.length-1)),qe(e=>e+1))},[]),ot=me(Se),lt=me(e?.version??""),it=me(e?.title??""),[mt,ht]=he(!1),gt=ve(),pt=pe({save:async t=>{e&&(lt.current=await e.store.save(e.id,{sheets:t},lt.current))},onFailure:(e,t)=>{e instanceof s?(pt.stop(),ht(!0)):0===t&&Pe.error(g.saveFailed)}}),{push:wt,flush:vt}=pt,bt=me(Se);de(()=>{e&&Se!==bt.current&&(bt.current=Se,wt(Se))},[wt,Se,e]),de(()=>()=>{vt()},[vt]),ye(e?pt.state.pending||mt:Se!==ot.current);const xt=ue(e=>{const t=qt(e,g.sheetName(1));t&&(tt([t]),ot.current=Ze.current,Ge(e.filename.replace(/\.(csv|tsv|txt)$/i,"")),Ye(()=>e.onEmail))},[tt,g]);de(()=>{const e=p.current;null!=e&&(We(e),e.data!==le.current&&xt(e.data))},[]),de(()=>{const e=p.current?.token;if(null==e)return;const t=t=>{const r=t.detail;r&&r.token===e&&xt(r.data)};return window.addEventListener(He,t),()=>window.removeEventListener(He,t)},[]);const yt=Math.min(Ve,Se.length-1),Ct=Se[yt],kt=fe(()=>T(Se),[Se]),$t=fe(()=>A(Ct,yt,kt),[Ct,yt,kt]),Nt=me(null),Ft=me(null),[At,Dt]=he({}),Rt=At[Ct.id]??{active:{row:0,col:0},range:{r1:0,c1:0,r2:0,c2:0}},Et=me(Ve);Et.current=Ve;const Tt=ue(e=>{Dt(t=>({...t,[Ze.current[Math.min(Et.current,Ze.current.length-1)].id]:e}))},[]),Mt=Rt.active,zt=Ct.formats[D(Mt.row,Mt.col)]??{},It=X(Ct,Mt.row,Mt.col),[Ut,Ot]=he(null),Lt=me(Ut);Lt.current=Ut;const[Pt,Yt]=he(null),[Zt,Qt]=he(!0),[Jt,er]=he(!1),[tr,rr]=he(null),[nr,or]=he(null),[lr,ir]=he(!1),[ar,sr]=he(null),[cr,ur]=he(null),[dr,fr]=he(!1),[mr,hr]=he(""),[gr,pr]=he(""),[wr,vr]=he({matchCase:!1,wholeCell:!1,inFormulas:!1}),br=me(null),xr=me(null),yr=me(null),Cr=Be(),kr=Be(),$r=ue(()=>{Nt.current?.focus(),setTimeout(()=>{const e=document.activeElement;e&&e!==document.body&&!e.closest("[aria-haspopup]")||Nt.current?.focus()},0)},[]),Nr=ue(e=>{et(t=>{const r=Math.min(Et.current,t.length-1),n=e(t[r]);return n===t[r]?t:t.map((e,t)=>t===r?n:e)})},[et]),Fr=me(null),Ar=me(()=>!1);de(()=>Oe(()=>!!Fr.current?.contains(document.activeElement)&&Ar.current()),[]);const Sr=ue(e=>Ct.hiddenRows.includes(e)||$t.has(e),[Ct.hiddenRows,$t]),Dr=ue(e=>Ct.hiddenCols.includes(e),[Ct.hiddenCols]),Rr=ue(e=>{const t=z(Ct,e.row,e.col),r=t??{r1:e.row,c1:e.col,r2:e.row,c2:e.col};Tt({active:t?{row:t.r1,col:t.c1}:e,range:r}),Nt.current?.scrollTo(e)},[Ct,Tt]),Er=ue((e,t,r)=>{let{row:n,col:o}=e;const l=z(Ct,n,o);l&&(t>0&&(n=l.r2),t<0&&(n=l.r1),r>0&&(o=l.c2),r<0&&(o=l.c1));do{n+=t,o+=r}while(n>=0&&n<Ct.rowCount&&o>=0&&o<Ct.colCount&&(Sr(n)||Dr(o)));return n<0||n>=Ct.rowCount||o<0||o>=Ct.colCount?e:{row:n,col:o}},[Ct,Sr,Dr]),Tr=ue((e,t,r)=>{const n=e=>""!==X(Ct,e.row,e.col);let o=e,l=Er(o,t,r);if(l===o)return o;if(n(o)&&n(l)){for(;n(l);)if(o=l,l=Er(o,t,r),l===o)return o;return o}for(;!n(l);)if(o=l,l=Er(o,t,r),l===o)return o;return l},[Ct,Er]),Mr=ue(e=>{const t=N(Ct,L(Rt.active,e));Tt({active:Rt.active,range:t}),Nt.current?.scrollTo(e)},[Ct,Rt.active,Tt]),zr=ue(()=>{const{range:e,active:t}=Rt;return{row:t.row===e.r1?e.r2:e.r1,col:t.col===e.c1?e.c2:e.c1}},[Rt]),Ir=me(null),Ur=ue((e,t={})=>{const r=X(Ct,e.row,e.col),n=t.text??$(r,Ct.formats[D(e.row,e.col)]);Yt(e=>e?.cut?null:e),t.inBar||null!==Ir.current||(Ir.current=n.length),Ot({sheetId:Ct.id,row:e.row,col:e.col,text:n,mode:t.mode??(void 0!==t.text?"enter":"edit"),inBar:!!t.inBar,caret:n.length,pick:null,suggestion:0})},[Ct]),Or=ue(e=>{const t=Lt.current;if(!t)return!1;Lt.current=null,Ot(null),et(r=>{const n=r.findIndex(e=>e.id===t.sheetId);if(n<0)return r;const o=r[n];if(t.text===$(X(o,t.row,t.col),o.formats[D(t.row,t.col)])&&!e)return r;let l=o;if(e)for(let r=e.r1;r<=e.r2;r++)for(let n=e.c1;n<=e.c2;n++){const e=E(t.text)?q(j(t.text).raw,r-t.row,n-t.col):t.text;l=v(l,r,n,e)}else l=v(l,t.row,t.col,t.text);return r.map((e,t)=>t===n?l:e)});const r=Ze.current.findIndex(e=>e.id===t.sheetId);return r>=0&&r!==Et.current&&Xe(r),!0},[et]),Lr=ue(()=>{const e=Lt.current;if(Lt.current=null,Ot(null),e){const t=Ze.current.findIndex(t=>t.id===e.sheetId);t>=0&&t!==Et.current&&Xe(t)}$r()},[$r]),Pr=ue((e,t)=>{Rr(Er(Rt.active,e,t)),$r()},[$r,Rr,Rt.active,Er]);xe(()=>{if(!Ut)return;const e=Ut.inBar?br.current:xr.current;e&&(document.activeElement!==e&&e.focus({preventScroll:!0}),null!==Ir.current&&(e.setSelectionRange(Ir.current,Ir.current),Ir.current=null))},[Ut]);const Br=ue((e,t)=>{Ot(r=>r?{...r,text:e,caret:t,pick:null,suggestion:0}:r)},[]),Hr=Ut?.sheetId===Ct.id,Kr=Ut?dt(Ut.text,Ut.caret):null,Wr=Ut?function(e,t){if("="!==e[0])return null;const r=[];let n=!1;for(let o=1;o<t;o++){const t=e[o];if('"'===t&&(n=!n),!n)if("("===t){const t=/([A-Za-z][A-Za-z0-9.]*)$/.exec(e.slice(1,o));r.push({name:t?t[1].toUpperCase():"",argIndex:0})}else")"===t?r.pop():","!==t&&";"!==t||!r.length||r[r.length-1].argIndex++}for(let e=r.length-1;e>=0;e--)if(r[e].name)return r[e];return null}(Ut.text,Ut.caret):null,Vr=!!Ut&&(null!==Ut.pick||function(e,t){if("="!==e[0]||ut(e,t))return!1;const r=e.slice(0,t).trimEnd(),n=e.slice(t).trimStart()[0];return!(void 0!==n&&!/[,;)+\-*/^&=<>%]/.test(n))&&/[=(,;+\-*/^&<>]$/.test(r)}(Ut.text,Ut.caret)),Xr=fe(()=>Ut?function(e,t,r,n,o){if("="!==e[0])return[];const l=[];let i=0;for(const a of te(e.slice(1)).tokens){if("ref"!==a.type)continue;const e=ct[i++%ct.length];if(!(null===a.ref.sheet?r:a.ref.sheet.toLowerCase()===t.toLowerCase()))continue;const s=a.ref.b??a.ref.a,c=L({row:a.ref.a.row??0,col:a.ref.a.col??0},{row:s.row??n-1,col:s.col??o-1});l.push({range:c,color:e})}return l}(Ut.text,Ct.name,Hr,Ct.rowCount,Ct.colCount):[],[Ut,Ct.name,Ct.rowCount,Ct.colCount,Hr]),jr=ue((e,t)=>{const r=Lt.current;if(!r)return;const n=K({sheet:r.sheetId===Ze.current[Et.current].id?null:Ze.current[Et.current].name,a:{row:e.r1,col:e.c1,rowAbs:!1,colAbs:!1},b:e.r1===e.r2&&e.c1===e.c2?null:{row:e.r2,col:e.c2,rowAbs:!1,colAbs:!1}}),o=r.pick?.start??r.caret,l=r.pick?.end??r.caret,i=r.text.slice(0,o)+n+r.text.slice(l),a=o+n.length;Ir.current=a,Ot({...r,text:i,caret:a,pick:t?null:{start:o,end:a}})},[]),Gr=ue(e=>{const t=Lt.current,r=t?dt(t.text,t.caret):null;if(!t||!r)return;const n=function(e,t,r,n){const o=`${n}(`;return{text:e.slice(0,r)+o+e.slice(t),caret:r+o.length}}(t.text,t.caret,r.start,e);Ir.current=n.caret,Ot({...t,text:n.text,caret:n.caret,suggestion:0,pick:null})},[]),_r=e=>{if(Ut){if(e.stopPropagation(),Kr){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t=Kr.matches.length;return void Ot({...Ut,suggestion:(Ut.suggestion+("ArrowDown"===e.key?1:t-1))%t})}if("Tab"===e.key||"Enter"===e.key&&Ut.suggestion>0)return e.preventDefault(),void Gr(Kr.matches[Ut.suggestion])}if("Enter"===e.key){if(e.altKey){e.preventDefault();const{selectionStart:t,selectionEnd:r,value:n}=e.currentTarget,o=`${n.slice(0,t)}\n${n.slice(r)}`;return Ir.current=t+1,void Br(o,t+1)}return e.preventDefault(),e.ctrlKey||e.metaKey?(Or(Rt.range),void $r()):(Or(),void Pr(e.shiftKey?-1:1,0))}if("Tab"===e.key)return e.preventDefault(),Or(),void Pr(0,e.shiftKey?-1:1);if("F4"===e.key){e.preventDefault();const t=function(e,t){if("="!==e[0])return null;const r=t-1;for(const t of te(e.slice(1)).tokens){if("ref"!==t.type||r<t.start||r>t.end)continue;const n={...t.ref,a:x(t.ref.a),b:t.ref.b?x(t.ref.b):null},o=K(n);return{text:`=${e.slice(1,t.start+1)}${o}${e.slice(t.end+1)}`,caret:t.start+1+o.length}}return null}(Ut.text,e.currentTarget.selectionStart);return void(t&&(Ir.current=t.caret,Br(t.text,t.caret)))}"enter"!==Ut.mode||Ut.inBar||E(Ut.text)||!e.key.startsWith("Arrow")||(e.preventDefault(),Or(),Pr("ArrowDown"===e.key?1:"ArrowUp"===e.key?-1:0,"ArrowRight"===e.key?1:"ArrowLeft"===e.key?-1:0))}},Yr=e=>{const t=e.currentTarget.selectionStart;Ot(e=>e&&e.caret!==t?{...e,caret:t,pick:null}:e)},Zr=ue(e=>{Or(),e(),$r()},[Or,$r]),Qr=me(Rt);Qr.current=Rt;const Jr=ue(e=>{Zr(()=>Nr(t=>ne(t,Qr.current.range,e)))},[Zr,Nr]),qr=ue(e=>{const t=!zt[e];Jr(r=>ae(r,e,t||void 0))},[zt,Jr]),en=ue(e=>{Jr(t=>ae(t,"numFmt","General"===e?void 0:e))},[Jr]),tn=ue(e=>{const t=kt.value(yt,Mt.row,Mt.col),r=c(zt.numFmt??"General",e,"number"==typeof t?t:null);en(r)},[Mt,zt.numFmt,kt,yt,en]),rn=ue((e,t)=>{const{range:r}=Rt,[n,o]="row"===e?[r.r1,r.r2]:[r.c1,r.c2],a="row"===e?Ct.rowCount:Ct.colCount,s=o-n+1>=a?1:o-n+1;a+s>("row"===e?i:l)||Zr(()=>et(r=>m(r,yt,e,t?o+1:n,s)))},[Ct.colCount,Ct.rowCount,et,yt,Zr,Rt]),nn=ue(e=>{const{range:t}=Rt,[r,n]="row"===e?[t.r1,t.r2]:[t.c1,t.c2],o="row"===e?Ct.rowCount:Ct.colCount,l=Math.min(n-r+1,o-1);l<1||Zr(()=>{et(t=>m(t,yt,e,r,-l)),Rr({row:"row"===e?Math.min(r,o-l-1):Rt.active.row,col:"col"===e?Math.min(r,o-l-1):Rt.active.col})})},[Ct.colCount,Ct.rowCount,et,yt,Zr,Rr,Rt]),on=ue(e=>{const{range:t}=Rt;Zr(()=>Nr(r=>{if("row"===e){const e=new Set(r.hiddenRows);for(let r=t.r1;r<=t.r2;r++)e.add(r);return{...r,hiddenRows:[...e]}}const n=new Set(r.hiddenCols);for(let e=t.c1;e<=t.c2;e++)n.add(e);return{...r,hiddenCols:[...n]}}))},[Zr,Rt,Nr]),ln=ue(e=>{Zr(()=>Nr(t=>"row"===e?{...t,hiddenRows:[]}:{...t,hiddenCols:[]}))},[Zr,Nr]),an=ue(e=>{Zr(()=>Nr(t=>{const r=Rt.range.r1===Rt.range.r2&&Rt.range.c1===Rt.range.c2,n=0===Rt.range.r1&&Rt.range.r2===t.rowCount-1;let o=r?y(t,Rt.range):Rt.range;return n&&(o={...o,r2:Math.max(o.r1,ie(t)?.row??0)}),t.filter&&W(t.filter.range,Rt.active.row,Rt.active.col)&&(o={...t.filter.range,r1:t.filter.range.r1+1}),ee(t,yt,kt,o,Rt.active.col,e)}))},[kt,yt,Zr,Rt,Nr]),sn=ue(()=>{or(null),Zr(()=>Nr(e=>{if(e.filter)return{...e,filter:null};const t=y(e,Rt.range);return t.r1===t.r2?e:{...e,filter:{range:t,excluded:{}}}}))},[Zr,Rt.range,Nr]),cn=ue(()=>{Zr(()=>Nr(e=>e.merges.some(e=>W(Rt.range,e.r1,e.c1))?re(e,Rt.range):M(e,Rt.range)))},[Zr,Rt.range,Nr]),un=ue((e,t)=>{Zr(()=>Nr(r=>({...r,frozenRows:e??r.frozenRows,frozenCols:t??r.frozenCols})))},[Zr,Nr]),dn=ue(e=>{const{range:t,active:r}=Rt,n=t.r1===t.r2&&t.c1===t.c2;let o="";if(n){const e=(e,t)=>"number"==typeof kt.value(yt,e,t);let t=r.row;for(;t>0&&e(t-1,r.col);)t--;let n=r.col;for(;n>0&&e(r.row,n-1);)n--;t<r.row?o=V({r1:t,c1:r.col,r2:r.row-1,c2:r.col}):n<r.col&&(o=V({r1:r.row,c1:n,r2:r.row,c2:r.col-1}))}else o=V(t);const l=n?r:{row:t.r2+1,col:t.c1};Or(),n||Rr(l);const i=`=${e}(${o})`;Ir.current=i.length-1,Ur(l,{text:i})},[Or,kt,yt,Rr,Rt,Ur]),fn=ue((e,t)=>{const r=Rt.range,n={...r,r2:Math.min(r.r2,Math.max(r.r1,Ct.cells.length-1))},o=b(Ct,yt,kt,n,e);Yt(o),t?(t.preventDefault(),t.clipboardData.setData("text/plain",o.text)):navigator.clipboard?.writeText(o.text).catch(()=>{})},[Ct,kt,yt,Rt.range]),mn=ue((e,t)=>{const{range:r}=Rt;if(Pt&&Pt.text===e){if(Pt.cut){const e=Ze.current.findIndex(e=>e.id===Pt.sheetId);if(e<0)return;let t=null;return et(n=>{const o=I(n,e,Pt,yt,r);return t=o.range,o.sheets}),t&&Tt({active:{row:t.r1,col:t.c1},range:t}),void Yt(null)}return void Nr(e=>{const n=H(e,Pt,r,t);return Tt({active:Rt.active,range:n.range}),n.sheet})}if(!e)return;const n=function(e){const t=e.replace(/\r\n?/g,"\n").replace(/\n$/,"");if(!t.includes("\t")&&!t.includes("\n"))return[[t]];if(!t.includes('"'))return t.split("\n").map(e=>e.split("\t"));const r=P(t.includes("\t")?t:`${t}\t`);return r.length?r:[[t]]}(e);Nr(e=>{let t=e;n.forEach((e,n)=>e.forEach((e,o)=>{t=v(t,r.r1+n,r.c1+o,e)}));const o=n.reduce((e,t)=>Math.max(e,t.length),1);return Tt({active:Rt.active,range:{r1:r.r1,c1:r.c1,r2:r.r1+n.length-1,c2:r.c1+o-1}}),t})},[Pt,et,yt,Rt,Tt,Nr]),hn=ue(e=>{Zr(()=>{const t=navigator.clipboard?.readText?.();t?t.then(t=>mn(t,e)).catch(()=>{Pt&&mn(Pt.text,e)}):Pt&&mn(Pt.text,e)})},[Pt,mn,Zr]);Ar.current=()=>Lt.current?(Lr(),!0):nr?(or(null),$r(),!0):ar?(sr(null),$r(),!0):lr?(ir(!1),$r(),!0):null!==cr?(ur(null),$r(),!0):dr?(fr(!1),$r(),!0):!(!Pt&&!tr)&&(Yt(null),rr(null),!0);const gn=je||g.spreadsheetFile,pn=ue(async()=>{Or();try{const e=Ze.current;Gt(await St(e,T(e)),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",`${gn}.xlsx`),ot.current=e,qe(e=>e+1)}catch{Pe.error(g.saveFailed)}},[Or,gn,g]),wn=()=>{const e=Ze.current,t=Math.min(Et.current,e.length-1);return Z(e[t],t,T(e))},vn=async t=>{const r=t.name.replace(/\.(csv|tsv|txt|xlsx|xls|ods)$/i,"");try{if(Or(),/\.(xlsx|xls|ods)$/i.test(t.name)){const e=new Uint8Array(await t.arrayBuffer()),r=/\.xlsx$/i.test(t.name)&&"undefined"!=typeof DecompressionStream?await Bt(e):await async function(e){const t=await(import("xlsx")),r=t.read(e,{type:"array",cellFormula:!0,cellNF:!0});return r.SheetNames.map(e=>{const n=r.Sheets[e],o=U(e),l=[],i={};if(n["!ref"]){const e=t.utils.decode_range(n["!ref"]);for(let r=e.s.r;r<=e.e.r;r++)for(let o=e.s.c;o<=e.e.c;o++){const e=n[t.utils.encode_cell({r:r,c:o})];if(!e||void 0===e.v&&!e.f)continue;const a=e.f?`=${e.f}`:"b"===e.t?e.v?"TRUE":"FALSE":String(e.v);l.push({row:r,col:o,raw:"s"===e.t&&/^(?:=|-?\d|'|true$|false$)/i.test(a)?`'${a}`:a}),e.z&&"General"!==e.z&&(i[D(r,o)]={numFmt:e.z})}}const a={};(n["!cols"]??[]).forEach((e,t)=>{e?.wpx&&(a[t]=e.wpx)});const s=(n["!merges"]??[]).map(e=>({r1:e.s.r,c1:e.s.c,r2:e.e.r,c2:e.e.c}));return{...se(o,l),formats:i,colWidths:a,merges:s}})}(e);et(()=>r),Xe(0)}else{const e=P(await t.text());if(!e.length)return;Nr(t=>({...Q(t.name,e),id:t.id}))}e||Ge(r)}catch{Pe.error(g.openFailed)}};de(()=>{r&&vn(r)},[]);const bn=fe(()=>dr?S(Ct,yt,kt,mr,wr):[],[Ct,kt,dr,wr,mr,yt]),xn=bn.findIndex(e=>e.row===Rt.active.row&&e.col===Rt.active.col),yn=e=>{if(!bn.length)return;const t=xn<0?e>0?0:bn.length-1:(xn+e+bn.length)%bn.length;Rr(bn[t])},Cn=()=>{Or();const e=yt+1;et(t=>{const r=O(t,g.sheetBase);return[...t.slice(0,e),U(r),...t.slice(e)]}),Xe(e),$r()},kn=()=>{if(!ar)return;const{index:e,name:t}=ar;sr(null);const r=t.trim();r&&r!==Se[e]?.name&&(Se.some((t,n)=>n!==e&&t.name.toLowerCase()===r.toLowerCase())?Pe.error(g.sheetNameTaken):et(t=>G(t,e,r)))},$n=(e,t)=>{const r=e+t;r<0||r>=Se.length||(et(t=>{const n=[...t],[o]=n.splice(e,1);return n.splice(r,0,o),n}),e===yt?Xe(r):r===yt&&Xe(e))},Nn=ue(e=>{Lt.current&&Or(),Tt(e),tr&&(Nr(t=>ne(t,e.range,()=>tr)),rr(null))},[Or,tr,Tt,Nr]),Fn=ue((e,t,r)=>{"cell"!==t||W(Rt.range,r.row,r.col)?"col"!==t||0===Rt.range.r1&&Rt.range.r2===Ct.rowCount-1&&r.col>=Rt.range.c1&&r.col<=Rt.range.c2?"row"!==t||0===Rt.range.c1&&Rt.range.c2===Ct.colCount-1&&r.row>=Rt.range.r1&&r.row<=Rt.range.r2||Tt({active:{row:r.row,col:0},range:{r1:r.row,c1:0,r2:r.row,c2:Ct.colCount-1}}):Tt({active:{row:0,col:r.col},range:{r1:0,c1:r.col,r2:Ct.rowCount-1,c2:r.col}}):Rr(r),Cr.open(e,{kind:t,pos:r})},[Ct.colCount,Ct.rowCount,Cr,Rr,Rt.range,Tt]),An=ue((e,t)=>{if(!Ct.filter)return;const r=w(Ct,yt,kt,Ct.filter.range,e);or({col:e,x:t.left,y:t.bottom+2,values:r,unticked:new Set(Ct.filter.excluded[e]??[]),search:""})},[Ct,kt,yt]),Sn=(e,t)=>{or(null),Zr(()=>Nr(r=>{if(!r.filter)return r;const{range:n}=r.filter;return ee(r,yt,kt,{...n,r1:n.r1+1},e,t)}))},Dn=fe(()=>{const{range:e}=Rt;return e.r1===e.r2&&e.c1===e.c2?null:Y(Ct,yt,kt,e,$t)},[Ct,kt,$t,yt,Rt]),Rn=e=>R(Number(e.toPrecision(12)),Dn?.firstFormat??"#,##0.##").text,En=(e,t)=>Wt("span",{className:"flex w-full items-center justify-between gap-6",children:[Kt("span",{children:e}),Kt("span",{className:"text-xs text-ink-faint",children:t})]}),Tn=(e,t,r,n={})=>({key:e,label:t,onSelect:r,...n}),Mn=e=>({type:"divider",key:e}),zn=[{key:"general",label:g.formatGeneral,code:a.general},{key:"number",label:g.formatNumber,code:a.number},{key:"percent",label:g.formatPercent,code:a.percent},{key:"scientific",label:g.formatScientific,code:a.scientific},{key:"currency",label:g.formatCurrency,code:a.currency},{key:"date",label:g.formatDate,code:a.date},{key:"time",label:g.formatTime,code:a.time},{key:"dateTime",label:g.formatDateTime,code:a.dateTime},{key:"text",label:g.formatText,code:a.text}].map(e=>({type:"radio",key:e.key,label:e.label,checked:(zt.numFmt??"General")===e.code,onSelect:()=>en(e.code)})),In=[["all",g.bordersAll],["outer",g.bordersOuter],["top",g.bordersTop],["bottom",g.bordersBottom],["left",g.bordersLeft],["right",g.bordersRight],["none",g.bordersNone]].map(([e,t])=>Tn(e,t,()=>Zr(()=>Nr(t=>u(t,Rt.range,e))))),Un=[...["left","center","right"].map(e=>({type:"radio",key:e,label:"left"===e?g.alignLeft:"center"===e?g.alignCenter:g.alignRight,checked:zt.align===e,onSelect:()=>Jr(t=>ae(t,"align",e))})),Mn("v"),...["top","middle","bottom"].map(e=>({type:"radio",key:e,label:"top"===e?g.alignTop:"middle"===e?g.alignMiddle:g.alignBottom,checked:(zt.vAlign??"bottom")===e,onSelect:()=>Jr(t=>ae(t,"vAlign",e))}))],On=Vt.map(e=>({type:"radio",key:String(e),label:String(e),checked:(zt.fontSize??t)===e,onSelect:()=>Jr(r=>ae(r,"fontSize",e===t?void 0:e))})),Ln=["SUM","AVERAGE","COUNT","MAX","MIN"].map(e=>Tn(e,e,()=>dn(e))),Pn=[...[0,1,2].map(e=>({type:"radio",key:`r${e}`,label:g.freezeRows(e),checked:Ct.frozenRows===e,onSelect:()=>un(e,null)})),{type:"radio",key:"rUp",label:g.freezeUpToRow(Mt.row+1),checked:Ct.frozenRows===Mt.row+1&&Mt.row>1,onSelect:()=>un(Mt.row+1,null)},Mn("c"),...[0,1,2].map(e=>({type:"radio",key:`c${e}`,label:g.freezeColumns(e),checked:Ct.frozenCols===e,onSelect:()=>un(null,e)})),{type:"radio",key:"cUp",label:g.freezeUpToColumn(f(0,Mt.col).replace(/\d+$/,"")),checked:Ct.frozenCols===Mt.col+1&&Mt.col>1,onSelect:()=>un(null,Mt.col+1)}],Bn=[...e?[]:[Tn("new",g.menuNew,()=>Zr(()=>{et(()=>[U(g.sheetName(1))]),Xe(0),Ge(g.untitled)}))],Tn("open",g.menuOpen,()=>Ft.current?.click()),Mn("a"),Tn("xlsx",En(g.saveExcel,`${jt}S`),()=>{pn()}),Tn("csv",g.saveCsv,()=>Zr(()=>Gt(wn(),"text/csv",`${gn}.csv`))),..._e?[Mn("b"),Tn("email",g.email,()=>Zr(()=>_e(wn(),`${gn}.csv`)))]:[]],Hn=[Tn("undo",En(g.undo,`${jt}Z`),()=>Zr(rt),{disabled:0===Qe.current.length}),Tn("redo",En(g.redo,Xt?"⇧⌘Z":"Ctrl+Y"),()=>Zr(nt),{disabled:0===Je.current.length}),Mn("a"),Tn("cut",En(g.cut,`${jt}X`),()=>Zr(()=>fn(!0))),Tn("copy",En(g.copy,`${jt}C`),()=>Zr(()=>fn(!1))),Tn("paste",En(g.paste,`${jt}V`),()=>hn("all")),Tn("pasteValues",g.pasteValues,()=>hn("values")),Tn("pasteFormats",g.pasteFormats,()=>hn("formats")),Mn("b"),Tn("find",En(g.findReplace,`${jt}F`),()=>{fr(!0),setTimeout(()=>yr.current?.focus(),0)}),Tn("clear",En(g.clearValues,"Delete"),()=>Zr(()=>Nr(e=>h(e,Rt.range))))],Kn=[{type:"submenu",key:"freeze",label:g.freeze,items:Pn},{type:"checkbox",key:"gridlines",label:g.gridlines,checked:Zt,onSelect:()=>Qt(e=>!e)},{type:"checkbox",key:"formulas",label:En(g.showFormulas,`${jt}\``),checked:Jt,onSelect:()=>er(e=>!e)}],Wn=[Tn("rowAbove",g.rowsAbove,()=>rn("row",!1)),Tn("rowBelow",g.rowsBelow,()=>rn("row",!0)),Tn("colLeft",g.columnsLeft,()=>rn("col",!1)),Tn("colRight",g.columnsRight,()=>rn("col",!0)),Mn("a"),Tn("sheet",g.sheet,Cn),{type:"submenu",key:"fn",label:g.function,items:Ln}],Vn=[{type:"submenu",key:"number",label:g.number,items:zn},Mn("a"),Tn("bold",En(g.bold,`${jt}B`),()=>qr("bold")),Tn("italic",En(g.italic,`${jt}I`),()=>qr("italic")),Tn("underline",En(g.underline,`${jt}U`),()=>qr("underline")),Tn("strike",g.strikethrough,()=>qr("strike")),{type:"submenu",key:"size",label:g.fontSize,items:On},Mn("b"),{type:"submenu",key:"align",label:g.alignment,items:Un},{type:"submenu",key:"borders",label:g.borders,items:In},Tn("wrap",g.wrapText,()=>qr("wrap")),Tn("merge",g.mergeCells,cn),Mn("c"),Tn("clearFormat",g.clearFormatting,()=>Zr(()=>Nr(e=>ne(e,Rt.range,()=>({})))))],Xn=[Tn("asc",g.sortAscending,()=>an(!0)),Tn("desc",g.sortDescending,()=>an(!1)),Mn("a"),{type:"checkbox",key:"filter",label:g.filter,checked:!!Ct.filter,onSelect:sn},Mn("b"),Tn("hideRows",g.hideRows,()=>on("row")),Tn("hideCols",g.hideColumns,()=>on("col")),Tn("unhideRows",g.unhideRows,()=>ln("row"),{disabled:!Ct.hiddenRows.length}),Tn("unhideCols",g.unhideColumns,()=>ln("col"),{disabled:!Ct.hiddenCols.length})],jn="rounded px-2 py-0.5 text-xs text-ink-muted hover:bg-line-subtle hover:text-ink",Gn="inline-flex h-7 items-center gap-1 rounded px-2 text-xs text-ink-muted hover:bg-line-subtle hover:text-ink",_n=Kt("div",{className:"mx-1 h-4 w-px bg-line"}),Yn=e=>e.preventDefault(),Zn=(e,t,r,n={})=>Kt(De,{"aria-label":e,title:e,size:"sm",variant:"ghost",onMouseDown:Yn,onClick:r,disabled:n.disabled,...void 0!==n.pressed?{"aria-pressed":n.pressed}:{},children:t}),Qn=(e,t,r)=>Kt(Te,{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:Wt(Ht,{children:[t,Kt("span",{className:"h-0.5 w-4 rounded-sm",style:{background:zt[r]??("color"===r?"var(--ink)":"var(--line)")}})]}),children:({close:t})=>Kt(Ne,{label:e,value:zt[r]??"",presets:st,clearable:!0,dragWrites:"end",onChange:e=>{Jr(t=>ae(t,r,e||void 0)),t()}})}),Jn=e=>{if(!Ut||!Hr||Ut.inBar)return null;const r=Ct.formats[D(Ut.row,Ut.col)],n=(r?.fontSize??t)*(4/3),o=Math.min(Math.max(e.width,Ut.text.length*n*.62+16),e.viewportWidth-e.x-4);return Kt("textarea",{ref:xr,"aria-label":g.cellEditor,value:Ut.text,spellCheck:!1,rows:1,onChange:e=>Br(e.target.value,e.target.selectionStart),onSelect:Yr,onKeyDown:_r,onPointerDown:e=>e.stopPropagation(),className:"absolute resize-none overflow-hidden border-2 border-accent-fill bg-surface text-ink outline-none",style:{left:e.x,top:e.y,width:o,minHeight:e.height,height:Math.max(e.height,Ut.text.split("\n").length*n*1.35+6),padding:"0 2px",fontSize:n,lineHeight:1.3,fontWeight:r?.bold?700:void 0,fontStyle:r?.italic?"italic":void 0,background:r?.fill??void 0,color:r?.color??void 0}})},qn=e=>{if(!Ut||!Hr)return null;const t=e.y+e.height+2,r=Math.max(0,Math.min(e.x,e.viewportWidth-320));if(Kr)return Wt("div",{role:"listbox","aria-label":g.functions,className:"absolute w-80 overflow-hidden rounded-lg border border-line bg-surface shadow-lg",style:{left:r,top:t},onPointerDown:e=>e.preventDefault(),children:[Kr.matches.map((e,t)=>Wt("div",{role:"option","aria-selected":t===Ut.suggestion,onPointerDown:t=>{t.preventDefault(),t.stopPropagation(),Gr(e)},className:"flex cursor-pointer items-center justify-between gap-3 px-2 py-1 text-xs "+(t===Ut.suggestion?"bg-accent-tint text-accent-text":"text-ink hover:bg-surface-sunken"),children:[Kt("span",{className:"font-medium",children:e}),Kt("span",{className:"truncate "+(t===Ut.suggestion?"text-accent-text":"text-ink-muted"),children:g.functionHelp(e)})]},e)),Wt("div",{className:"border-t border-line px-2 py-1 font-mono text-xs text-ink-muted",children:[Kr.matches[Ut.suggestion],"(",ft[Kr.matches[Ut.suggestion]]??"",")"]})]});if(Wr&&void 0!==ft[Wr.name]){const e=ft[Wr.name].split(", ");return Wt("div",{className:"absolute max-w-md rounded-lg border border-line bg-surface px-2 py-1 text-xs text-ink-muted shadow-lg",style:{left:r,top:t},children:[Wt("div",{className:"font-mono",children:[Wr.name,"(",e.map((t,r)=>Wt("span",{children:[r>0?", ":"",Kt("span",{className:r===Math.min(Wr.argIndex,e.length-1)?"font-semibold text-ink":"",children:t})]},t+r)),")"]}),Kt("div",{className:"mt-0.5",children:g.functionHelp(Wr.name)})]})}return null},eo=nr?nr.values.filter(e=>e.toLowerCase().includes(nr.search.toLowerCase())):[];return Wt("div",{ref:Fr,className:"flex h-full flex-col bg-surface text-ink",children:[Kt(be,{title:`${no=je||g.untitled,no.length>24?`${no.slice(0,23)}…`:no} - Spreadsheets`}),Kt("input",{ref:Ft,type:"file",accept:_t,onChange:e=>{const t=e.target.files?.[0];Ft.current&&(Ft.current.value=""),t&&vn(t)},className:"hidden"}),Wt("div",{className:"flex shrink-0 items-center gap-1 border-b border-line bg-surface-sunken px-2 py-1",children:[o&&Kt(De,{"aria-label":g.backToFiles,title:g.backToFiles,size:"sm",variant:"ghost",onClick:()=>{vt(),o()},children:Kt(Ce,{name:"arrow-left",size:16})}),lr?Kt("input",{type:"text",value:je,autoFocus:!0,"aria-label":g.rename,onChange:e=>Ge(e.target.value),onBlur:()=>{ir(!1);const t=je.trim()||g.untitled;if(t!==je&&Ge(t),e&&t!==it.current){const r=it.current;it.current=t,e.store.rename(e.id,t).catch(()=>{Pe.error(g.renameFailed),it.current=r,Ge(r)})}},onKeyDown:e=>{"Enter"===e.key&&(e.currentTarget.blur(),$r())},className:"w-40 rounded border border-line bg-surface px-2 py-0.5 text-sm font-medium text-ink"}):Kt("button",{type:"button",onClick:()=>ir(!0),title:g.rename,className:"max-w-[200px] truncate rounded px-2 py-0.5 text-sm font-medium text-ink hover:bg-line-subtle",children:je||g.untitled}),Kt(Ae,{trigger:g.menuFile,items:Bn,align:"start",triggerClassName:jn}),Kt(Ae,{trigger:g.menuEdit,items:Hn,align:"start",triggerClassName:jn}),Kt(Ae,{trigger:g.menuView,items:Kn,align:"start",triggerClassName:jn}),Kt(Ae,{trigger:g.menuInsert,items:Wn,align:"start",triggerClassName:jn}),Kt(Ae,{trigger:g.menuFormat,items:Vn,align:"start",triggerClassName:jn}),Kt(Ae,{trigger:g.menuData,items:Xn,align:"start",triggerClassName:jn}),(e||n)&&Kt("span",{className:"office-save-state",children:Kt(we,{...e?ge(pt.state,gt.save):{tone:Se!==ot.current?"off-unsaved":"off",label:Se!==ot.current?g.noStoreEdited:g.noStoreClean}})})]}),mt&&Wt("div",{className:"office-conflict",role:"alert",children:[Kt("span",{children:g.conflict}),Kt(ke,{variant:"secondary",onClick:d,children:g.reload})]}),Wt("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[Zn(g.undo,Kt(Ce,{name:"undo",size:16}),()=>Zr(rt),{disabled:0===Qe.current.length}),Zn(g.redo,Kt(Ce,{name:"redo",size:16}),()=>Zr(nt),{disabled:0===Je.current.length}),Zn(g.formatPainter,Kt(Ce,{name:"copy-style",size:16}),()=>rr(e=>e?null:zt),{pressed:!!tr}),_n,Zn(g.formatCurrency,Kt(Ce,{name:"dollar",size:16}),()=>en(zt.numFmt===a.currency?"General":a.currency),{pressed:zt.numFmt===a.currency}),Zn(g.formatPercent,Kt(Ce,{name:"percent",size:16}),()=>en(/%/.test(zt.numFmt??"")?"General":"0%"),{pressed:/%/.test(zt.numFmt??"")}),Zn(g.fewerDecimals,Kt("span",{className:"text-xs",children:".0"}),()=>tn(-1)),Zn(g.moreDecimals,Kt("span",{className:"text-xs",children:".00"}),()=>tn(1)),Kt(Ae,{trigger:Wt("span",{title:g.number,className:"flex items-center gap-0.5",children:["123",Kt(Ce,{name:"chevron-down",size:12})]}),"aria-label":g.number,items:zn,align:"start",triggerClassName:Gn}),_n,Kt(Ae,{trigger:Wt("span",{title:g.fontSize,className:"flex items-center gap-0.5",children:[zt.fontSize??t,Kt(Ce,{name:"chevron-down",size:12})]}),"aria-label":g.fontSize,items:On,align:"start",triggerClassName:Gn}),Zn(g.bold,Kt(Ce,{name:"bold",size:16}),()=>qr("bold"),{pressed:!!zt.bold}),Zn(g.italic,Kt(Ce,{name:"italic",size:16}),()=>qr("italic"),{pressed:!!zt.italic}),Zn(g.underline,Kt(Ce,{name:"underline",size:16}),()=>qr("underline"),{pressed:!!zt.underline}),Zn(g.strikethrough,Kt(Ce,{name:"strike",size:16}),()=>qr("strike"),{pressed:!!zt.strike}),Qn(g.textColor,Kt(Ce,{name:"text-color",size:14}),"color"),Qn(g.fillColor,Kt(Ce,{name:"palette",size:14}),"fill"),_n,Kt(Ae,{trigger:Wt("span",{title:g.borders,className:"flex items-center gap-0.5",children:[Kt(Ce,{name:"border-all",size:16}),Kt(Ce,{name:"chevron-down",size:12})]}),"aria-label":g.borders,items:In,align:"start",triggerClassName:Gn}),Zn(g.mergeCells,Kt(Ce,{name:"grid",size:16}),cn,{pressed:Ct.merges.some(e=>W(e,Mt.row,Mt.col))}),Kt(Ae,{trigger:Wt("span",{title:g.alignment,className:"flex items-center gap-0.5",children:["center"===zt.align?Kt(Ce,{name:"align-center",size:16}):"right"===zt.align?Kt(Ce,{name:"align-right",size:16}):Kt(Ce,{name:"align-left",size:16}),Kt(Ce,{name:"chevron-down",size:12})]}),"aria-label":g.alignment,items:Un,align:"start",triggerClassName:Gn}),Zn(g.wrapText,Kt(Ce,{name:"wrap",size:16}),()=>qr("wrap"),{pressed:!!zt.wrap}),_n,Zn(g.filter,Kt(Ce,{name:"filter",size:16}),sn,{pressed:!!Ct.filter}),Zn(g.sortAscending,Kt(Ce,{name:"sort",size:16}),()=>an(!0)),Kt(Ae,{trigger:Wt("span",{title:g.functions,className:"flex items-center gap-0.5 text-sm",children:["Σ",Kt(Ce,{name:"chevron-down",size:12})]}),"aria-label":g.functions,items:Ln,align:"end",triggerClassName:Gn})]}),Wt("div",{className:"flex shrink-0 items-start gap-1 border-b border-line bg-surface px-2 py-1",children:[Kt("input",{type:"text","aria-label":g.nameBox,spellCheck:!1,value:cr??(Ut&&Hr?f(Ut.row,Ut.col):V(Rt.range)),onFocus:e=>{ur(e.target.value),e.target.select()},onChange:e=>ur(e.target.value),onBlur:()=>ur(null),onKeyDown:e=>{if("Enter"===e.key){const e=B(cr??"");e&&e.r2<Ct.rowCount&&e.c2<Ct.colCount&&(Tt({active:{row:e.r1,col:e.c1},range:N(Ct,e)}),Nt.current?.scrollTo({row:e.r1,col:e.c1})),ur(null),$r()}},className:"w-20 shrink-0 rounded border border-line bg-surface px-2 py-0.5 text-center text-xs text-ink"}),Kt("span",{className:"select-none pt-0.5 font-serif text-sm italic text-ink-faint","aria-hidden":"true",children:"fx"}),Kt("textarea",{ref:br,"aria-label":g.formulaBar,spellCheck:!1,rows:1,value:Ut?Ut.text:$(It,zt),onFocus:()=>{Ut?Ut.inBar||Ot({...Ut,inBar:!0}):Ur(Mt,{inBar:!0,mode:"edit"})},onChange:e=>{Ut&&Br(e.target.value,e.target.selectionStart)},onSelect:Yr,onKeyDown:_r,className:"max-h-24 min-h-[22px] flex-1 resize-y rounded border border-line bg-surface px-2 py-0.5 font-mono text-xs text-ink outline-none focus:border-accent-fill"})]}),dr&&Wt("div",{className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-line bg-surface-sunken px-2 py-1 text-xs",children:[Kt("div",{className:"w-44",children:Kt(Re,{ref:yr,size:"sm","aria-label":g.find,placeholder:g.find,value:mr,onChange:e=>hr(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),yn(e.shiftKey?-1:1))}})}),Kt("span",{className:"w-16 text-center text-ink-muted",children:mr?g.hitCount(xn<0?0:xn+1,bn.length):""}),Zn(g.previous,Kt(Ce,{name:"arrow-up",size:14}),()=>yn(-1)),Zn(g.next,Kt(Ce,{name:"arrow-down",size:14}),()=>yn(1)),Kt("div",{className:"w-44",children:Kt(Re,{size:"sm","aria-label":g.replaceWith,placeholder:g.replaceWith,value:gr,onChange:e=>pr(e.target.value)})}),Kt(ke,{size:"sm",variant:"secondary",disabled:!bn.length,onClick:()=>{if(xn<0)return void yn(1);const{row:e,col:t}=bn[xn];Nr(r=>{const n=_(X(r,e,t),mr,gr,wr);return n===X(r,e,t)?r:se(r,[{row:e,col:t,raw:n}])}),yn(1)},children:g.replace}),Kt(ke,{size:"sm",variant:"secondary",disabled:!bn.length,onClick:()=>{let e=0;Nr(t=>{const r=[];for(const{row:e,col:n}of bn){const o=_(X(t,e,n),mr,gr,wr);o!==X(t,e,n)&&r.push({row:e,col:n,raw:o})}return e=r.length,se(t,r)}),Pe.success(g.replacedCount(e))},children:g.replaceAll}),Kt($e,{label:g.matchCase,checked:wr.matchCase,onChange:e=>vr(t=>({...t,matchCase:e}))}),Kt($e,{label:g.wholeCell,checked:wr.wholeCell,onChange:e=>vr(t=>({...t,wholeCell:e}))}),Kt($e,{label:g.inFormulas,checked:wr.inFormulas,onChange:e=>vr(t=>({...t,inFormulas:e}))}),Kt("div",{className:"ml-auto",children:Zn(g.close,Kt(Ce,{name:"close",size:14}),()=>{fr(!1),$r()})})]}),Kt("div",{className:"min-h-0 flex-1",children:Kt(at,{ref:Nt,sheet:Ct,sheetIndex:yt,evaluator:kt,filterHidden:$t,selection:Rt,showGridlines:Zt,showFormulas:Jt,clipRange:Pt&&Pt.sheetId===Ct.id?Pt.range:null,highlights:Xr,pointing:Vr,onSelect:Nn,onPoint:jr,onEdit:e=>{Or(),Rr(e),Ur(z(Ct,e.row,e.col)?{row:z(Ct,e.row,e.col).r1,col:z(Ct,e.row,e.col).c1}:e)},onFill:e=>{const t=Rt.range;Nr(r=>F(r,t,e)),Tt({active:Rt.active,range:e})},onResizeCol:(e,t)=>Nr(r=>{const{range:n}=Rt,o=0===n.r1&&n.r2===r.rowCount-1&&e>=n.c1&&e<=n.c2,l={...r.colWidths};if(o)for(let e=n.c1;e<=n.c2;e++)l[e]=t;else l[e]=t;return{...r,colWidths:l}}),onResizeRow:(e,t)=>Nr(r=>({...r,rowHeights:{...r.rowHeights,[e]:t}})),onAutoFitCol:e=>{const t=Math.max(40,Nt.current?.measureColumn(e)??0);Nr(r=>({...r,colWidths:{...r.colWidths,[e]:t}}))},onAutoFitRow:e=>Nr(t=>{const r={...t.rowHeights};return delete r[e],{...t,rowHeights:r}}),onHeaderMenu:Fn,onFilterButton:An,renderEditor:e=>Wt(Ht,{children:[Jn(e),qn(e)]}),onKeyDown:t=>{if(Ut)return;const r=t.ctrlKey||t.metaKey,n=t.key,o=n.toLowerCase(),l="ArrowUp"===n?[-1,0]:"ArrowDown"===n?[1,0]:"ArrowLeft"===n?[0,-1]:"ArrowRight"===n?[0,1]:null;if(l){t.preventDefault();const e=t.shiftKey?zr():Rt.active,n=r?Tr(e,l[0],l[1]):Er(e,l[0],l[1]);return void(t.shiftKey?Mr(n):Rr(n))}if("Tab"===n||"Enter"===n){if(t.preventDefault(),"Enter"===n&&r)return;const e=Rt.range.r1!==Rt.range.r2||Rt.range.c1!==Rt.range.c2,o="Enter"===n?t.shiftKey?-1:1:0,l="Tab"===n?t.shiftKey?-1:1:0;if(e){const{range:e}=Rt;let{row:t,col:r}=Rt.active;return t+=o,r+=l,r>e.c2&&(r=e.c1,t=t+1>e.r2?e.r1:t+1),r<e.c1&&(r=e.c2,t=t-1<e.r1?e.r2:t-1),t>e.r2&&(t=e.r1,r=r+1>e.c2?e.c1:r+1),t<e.r1&&(t=e.r2,r=r-1<e.c1?e.c2:r-1),Tt({active:{row:t,col:r},range:e}),void Nt.current?.scrollTo({row:t,col:r})}return void Rr(Er(Rt.active,o,l))}if("Home"===n)return t.preventDefault(),void Rr(r?{row:Ct.frozenRows,col:Ct.frozenCols}:{row:Rt.active.row,col:0});if("End"===n){t.preventDefault();const e=ie(Ct);return void Rr(r?{row:e?.row??0,col:e?.col??0}:{row:Rt.active.row,col:Math.max(0,(Ct.cells[Rt.active.row]?.length??1)-1)})}if("PageDown"===n||"PageUp"===n){t.preventDefault();const e="PageDown"===n?25:-25;return void Rr({row:Math.max(0,Math.min(Ct.rowCount-1,Rt.active.row+e)),col:Rt.active.col})}if("Delete"===n||"Backspace"===n)return t.preventDefault(),void Nr(e=>h(e,Rt.range));if("F2"===n)return t.preventDefault(),void Ur(Rt.active);if(" "===n&&(r||t.shiftKey))return t.preventDefault(),void Tt(r?{active:Rt.active,range:{r1:0,c1:Rt.range.c1,r2:Ct.rowCount-1,c2:Rt.range.c2}}:{active:Rt.active,range:{r1:Rt.range.r1,c1:0,r2:Rt.range.r2,c2:Ct.colCount-1}});if(!r)return!t.altKey||"="!==n&&"≠"!==n?1!==n.length||t.altKey?void("Process"!==n&&229!==t.keyCode||Ur(Rt.active,{text:""})):(t.preventDefault(),void Ur(Rt.active,{text:n})):(t.preventDefault(),void dn("SUM"));switch(o){case"z":return t.preventDefault(),void(t.shiftKey?nt():rt());case"y":return t.preventDefault(),void nt();case"a":return t.preventDefault(),void Tt({active:Rt.active,range:{r1:0,c1:0,r2:Ct.rowCount-1,c2:Ct.colCount-1}});case"b":return t.preventDefault(),void qr("bold");case"i":return t.preventDefault(),void qr("italic");case"u":return t.preventDefault(),void qr("underline");case"f":case"h":return t.preventDefault(),fr(!0),void setTimeout(()=>yr.current?.focus(),0);case"s":return t.preventDefault(),void(e?vt():pn());case"d":{t.preventDefault();const{range:e}=Rt;return void(e.r2>e.r1?Nr(t=>F(t,{...e,r2:e.r1},e)):e.r1>0&&Nr(t=>F(t,{...e,r1:e.r1-1,r2:e.r1-1},{...e,r1:e.r1-1})))}case"r":{t.preventDefault();const{range:e}=Rt;return void(e.c2>e.c1?Nr(t=>F(t,{...e,c2:e.c1},e)):e.c1>0&&Nr(t=>F(t,{...e,c1:e.c1-1,c2:e.c1-1},{...e,c1:e.c1-1})))}case";":return t.preventDefault(),void Nr(e=>v(e,Rt.active.row,Rt.active.col,Le(new Date)));case"`":return t.preventDefault(),void er(e=>!e)}if(t.shiftKey){if("$"===n||"4"===n)return t.preventDefault(),void en(a.currency);if("%"===n||"5"===n)return t.preventDefault(),void en("0%")}},onCopy:e=>{Ut||fn(!1,e)},onCut:e=>{Ut||fn(!0,e)},onPaste:e=>{Ut||(e.preventDefault(),mn(e.clipboardData.getData("text/plain"),"all"))}})}),Wt("div",{className:"flex shrink-0 items-center border-t border-line bg-surface-sunken",children:[Wt("div",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto px-1 py-1",children:[Kt(De,{"aria-label":g.addSheet,title:g.addSheet,size:"sm",variant:"ghost",onClick:Cn,children:Kt(Ce,{name:"add",size:14})}),Se.map((e,t)=>Kt("button",{type:"button",onClick:()=>(e=>{Ut&&!Vr&&Or(),Xe(e),or(null)})(t),onDoubleClick:()=>sr({index:t,name:e.name}),onContextMenu:e=>kr.open(e,t),style:e.tabColor?{boxShadow:`inset 0 -3px 0 ${e.tabColor}`}:void 0,className:"whitespace-nowrap rounded px-3 py-1 text-xs font-medium "+(t===yt?"bg-accent-tint text-accent-text":"text-ink-muted hover:bg-line-subtle hover:text-ink"),children:ar?.index===t?Kt("input",{type:"text",value:ar.name,autoFocus:!0,"aria-label":g.rename,onChange:e=>sr({index:t,name:e.target.value}),onBlur:kn,onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&kn()},onClick:e=>e.stopPropagation(),className:"w-24 rounded border border-accent-fill bg-surface px-1 text-xs text-ink outline-none"}):e.name},e.id))]}),Dn&&Dn.count>0&&Wt("div",{className:"flex shrink-0 items-center gap-3 border-l border-line px-3 py-1 text-xs text-ink-muted",children:[Dn.numbers>0&&Wt("span",{children:[g.statSum,": ",Rn(Dn.sum)]}),null!==Dn.average&&Wt("span",{children:[g.statAverage,": ",Rn(Dn.average)]}),Wt("span",{children:[g.statCount,": ",Dn.count]}),Dn.numbers>0&&Wt("span",{children:[g.statMin,": ",Rn(Dn.min)]}),Dn.numbers>0&&Wt("span",{children:[g.statMax,": ",Rn(Dn.max)]})]})]}),Cr.state&&Kt(Fe,{...Cr.props,items:(ro=Cr.state.data.kind,[Tn("cut",g.cut,()=>Zr(()=>fn(!0))),Tn("copy",g.copy,()=>Zr(()=>fn(!1))),Tn("paste",g.paste,()=>hn("all")),Tn("pasteValues",g.pasteValues,()=>hn("values")),Mn("a"),..."col"!==ro?[Tn("rowAbove",g.rowsAbove,()=>rn("row",!1)),Tn("rowBelow",g.rowsBelow,()=>rn("row",!0))]:[],..."row"!==ro?[Tn("colLeft",g.columnsLeft,()=>rn("col",!1)),Tn("colRight",g.columnsRight,()=>rn("col",!0))]:[],Mn("b"),..."col"!==ro?[Tn("delRows",g.deleteRows,()=>nn("row"),{danger:!0})]:[],..."row"!==ro?[Tn("delCols",g.deleteColumns,()=>nn("col"),{danger:!0})]:[],Tn("clear",g.clearValues,()=>Zr(()=>Nr(e=>h(e,Rt.range)))),Mn("c"),..."col"!==ro?[Tn("hideRows",g.hideRows,()=>on("row"))]:[],..."row"!==ro?[Tn("hideCols",g.hideColumns,()=>on("col"))]:[],..."col"!==ro&&Ct.hiddenRows.length?[Tn("unhideRows",g.unhideRows,()=>ln("row"))]:[],..."row"!==ro&&Ct.hiddenCols.length?[Tn("unhideCols",g.unhideColumns,()=>ln("col"))]:[]])}),kr.state&&Kt(Fe,{...kr.props,items:(to=kr.state.data,[Tn("rename",g.rename,()=>sr({index:to,name:Se[to].name})),Tn("duplicate",g.duplicate,()=>{et(e=>k(e,to,O(e,Se[to].name))),Xe(to+1)}),Tn("left",g.moveLeft,()=>$n(to,-1),{disabled:0===to}),Tn("right",g.moveRight,()=>$n(to,1),{disabled:to===Se.length-1}),{type:"submenu",key:"colour",label:g.tabColor,items:[Tn("none",g.noColor,()=>et(e=>e.map((e,t)=>t===to?{...e,tabColor:void 0}:e))),...st.slice(7,17).map(e=>Tn(e,Wt("span",{className:"flex items-center gap-2",children:[Kt("span",{className:"inline-block h-3 w-3 rounded-sm",style:{background:e}}),e]}),()=>et(t=>t.map((t,r)=>r===to?{...t,tabColor:e}:t))))]},Mn("a"),Tn("delete",g.deleteSheet,()=>{(async e=>{Se.length<=1||(null===ie(Se[e])||await Ue({title:g.deleteSheetTitle,message:g.deleteSheetMessage(Se[e].name),confirmLabel:g.deleteSheet}))&&(et(t=>C(t,e)),Xe(t=>t>e||t>=Se.length-1?Math.max(0,t-1):t))})(to)},{danger:!0,disabled:Se.length<=1})])}),nr&&Wt(Me,{portal:!0,minWidth:230,onClose:()=>or(null),style:{position:"fixed",left:nr.x,top:nr.y},children:[Kt(Ie,{onClick:()=>Sn(nr.col,!0),children:g.sortAscending}),Kt(Ie,{onClick:()=>Sn(nr.col,!1),children:g.sortDescending}),Kt(ze,{}),Kt("div",{className:"px-2 py-1",children:Kt(Re,{size:"sm","aria-label":g.find,placeholder:g.find,value:nr.search,onChange:e=>or({...nr,search:e.target.value})})}),Kt("div",{className:"max-h-52 overflow-y-auto px-2 py-1",children:eo.map(e=>Kt("div",{className:"py-0.5",children:Kt($e,{label:e||g.blank,checked:!nr.unticked.has(e),onChange:t=>{const r=new Set(nr.unticked);t?r.delete(e):r.add(e),or({...nr,unticked:r})}})},e))}),Wt("div",{className:"flex items-center justify-between gap-2 border-t border-line px-2 py-1",children:[Kt(ke,{size:"sm",variant:"ghost",onClick:()=>or({...nr,unticked:new Set}),children:g.clear}),Kt(ke,{size:"sm",variant:"primary",onClick:()=>{if(!nr)return;const{col:e,unticked:t}=nr;or(null),Zr(()=>Nr(r=>{if(!r.filter)return r;const n={...r.filter.excluded};return t.size?n[e]=[...t]:delete n[e],{...r,filter:{...r.filter,excluded:n}}}))},children:g.apply})]})]})]});var to,ro,no}function qt(e,t){const r=e.rows?e.rows.map(e=>e.map(e=>String(e??""))):P(e.csv??"");return 0===r.length?null:Q(t,r)}export{Qt as OpenSpreadsheet,Zt as SpreadsheetById,Yt as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{useCallback as e,useEffect as i,useRef as t,useState as l}from"react";import{WindowTitle as n,confirmDestructive as c,toast as r}from"efficient-shell";import{Icon as a}from"efficient-shell/icons";import{Button as o,EmptyState as s}from"efficient-shell/ui";import{jsx as f,jsxs as d}from"react/jsx-runtime";function m({words:m,list:h,create:p,remove:u,canCreate:g,canDelete:v,accept:w,onOpen:C,onOpenFile:N}){const[k,y]=l(null),F=t(null),D=e(()=>{h().then(y,()=>y([]))},[h]);i(D,[D]);const x=g&&f(o,{onClick:()=>{p().then(({id:e})=>C(e),()=>r.error(m.createFailed))},children:m.newFile}),z=f(o,{variant:"ghost",leftIcon:f(a,{name:"folder-open",size:16}),onClick:()=>F.current?.click(),children:m.openFile});return d("div",{className:"office-filelist",children:[f(n,{title:m.windowTitle}),f("input",{ref:F,type:"file",accept:w,className:"office-filelist-input",onChange:e=>{const i=e.target.files?.[0];e.target.value="",i&&N(i)}}),d("div",{className:"office-filelist-head",children:[f("h2",{children:m.heading}),z,k&&k.length>0&&x]}),0===k?.length?f("div",{className:"office-filelist-empty",children:f(s,{title:m.emptyTitle,description:m.emptyBody,children:x})}):f("ul",{className:"office-filelist-rows",children:k?.map(e=>d("li",{className:"office-filelist-row",children:[f(o,{variant:"link",onClick:()=>C(e.id),children:e.title}),f("span",{className:"office-filelist-date",children:new Date(e.updatedAt).toLocaleDateString()}),v&&f(o,{variant:"ghost",leftIcon:f(a,{name:"trash",size:16}),onClick:async()=>{await c({message:m.deleteConfirm(e.title),confirmWord:m.delete})&&u(e.id).then(D,()=>r.error(m.deleteFailed))},children:m.delete})]},e.id))})]})}export{m as FileList};
|