efficient-office 0.11.0 → 0.12.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.
@@ -0,0 +1 @@
1
+ import{BUILTIN_STYLES as t,CHECK_BULLETS as e,DEFAULT_PAGE as a,REL as n,child as r,childrenOf as o,descendants as s,paraCss as c,parseParaProps as l,parseRunProps as d,parseXml as i,partText as w,readRels as m,readThemeFonts as p,readZip as f,resolveTarget as u,runCss as h,tabCss as b,tabsAttr as g}from"./chunk-D3JKD7KW.js";import{escapeHtml as $}from"efficient-shell/ui";var v={textBox:"Text box",chart:"Chart",diagram:"Diagram",equation:"Equation",picture:"Picture",object:"Object",contents:"Field"},x={text:"",html:"",editable:!0},k=()=>({default:{...x},first:{...x},even:{...x}}),y=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"]),P=new Set(["w:ins","w:del","w:moveFrom","w:moveTo"]),j={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",svg:"image/svg+xml"},C=/^(https?:|mailto:|tel:)/i,S=t=>$(t);function M(t,e){let a="";for(let e=0;e<t.length;e+=32768)a+=String.fromCharCode(...t.subarray(e,e+32768));return`data:${e};base64,${btoa(a)}`}var I=(t,e)=>`${e}${++t.nextId}`,T=(t,e)=>t.src.slice(e.start,e.end),N=(t,e)=>e?T(t,e):void 0;function A(t,e){const a=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const e=t.styles.get(o);if(!e)break;a.unshift(e),o=r(e,"w:basedOn")?.attrs["w:val"]}return a}var E=t=>`"${t.replace(/["\\\n\r]/g,"")}"`;function O(t){return"w:t"===t.name||"w:delText"===t.name?t.text:"w:tab"===t.name?"\t":"w:instrText"===t.name||"w:instrDelText"===t.name?"":t.children.map(O).join("")}function B(t,e,a,n,r=""){const o=I(t,"x");return t.doc.raw.set(o,e),`<span data-raw="${o}" data-kind="${a}" contenteditable="false"${r}>${$(n)}</span>`}function L(t,e){const a=I(t,"x");return t.doc.raw.set(a,e),`<span data-raw="${a}" data-kind="mark"></span>`}function R(t,e,a){const n=a(T(t,e)),o=t=>s(e,new Set([t])).length>0,c=r(e,"wp:inline"),l=s(e,new Set(["a:blip"]))[0],d=l&&t.rels.get(l.attrs["r:embed"]),i=d&&!d.external?u(t.doc.docPath,d.target):void 0,w=i?.split(".").pop()?.toLowerCase()??"",m=i?t.doc.parts.get(i):void 0;if(m&&j[w]&&!o("wps:txbx")){const a=I(t,"x");t.doc.raw.set(a,n);const o=r(c??r(e,"wp:anchor"),"wp:extent"),s=Number(o?.attrs.cx)/12700,l=Number(o?.attrs.cy)/12700,d=s&&l?` style="width:${Math.round(100*s)/100}pt;height:${Math.round(100*l)/100}pt"`:"",i=c?"":' contenteditable="false"';return c||t.doc.notices.objects++,`<img data-raw="${a}" src="${S(t.imageUrl(m,j[w]))}"${d}${i} alt="">`}return t.doc.notices.objects++,o("wps:txbx")||o("w:txbxContent")?B(t,n,"object",`${t.labels.textBox}: ${O(e).slice(0,80)}`):o("c:chart")?B(t,n,"object",t.labels.chart):o("dgm:relIds")?B(t,n,"object",t.labels.diagram):B(t,n,"object",l?t.labels.picture:t.labels.object)}function F(t,e){const a=r(e,"w:rPr"),n=d(a,t.theme),o=N(t,a)??"",c=t=>`<w:r>${o}${t}</w:r>`;let l="";for(const a of e.children)switch(a.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":l+=$(a.text);break;case"w:tab":l+="\t";break;case"w:noBreakHyphen":l+="‑";break;case"w:softHyphen":l+="­";break;case"w:br":case"w:cr":"page"===a.attrs["w:type"]?l+='<span data-page-break contenteditable="false"></span>':"column"===a.attrs["w:type"]?l+=B(t,c(T(t,a)),"mark",""):l+="<br>";break;case"w:drawing":l+=R(t,a,c);break;case"mc:AlternateContent":case"w:pict":case"w:object":t.doc.notices.objects++,l+=B(t,c(T(t,a)),"object",s(a,new Set(["wps:txbx","w:txbxContent","v:textbox"])).length?`${t.labels.textBox}: ${O(s(a,new Set(["wps:txbx","w:txbxContent","v:textbox"]))[0]).slice(0,80)}`:t.labels.object);break;case"w:footnoteReference":{const e=a.attrs["w:id"],n=I(t,"x");t.doc.raw.set(n,c(T(t,a))),l+=`<span data-raw="${n}" data-kind="note" data-note="${S(e)}" contenteditable="false"></span>`;break}case"w:endnoteReference":{const e=++t.footnoteCount;t.doc.notices.footnotes++;const n=t.footnotes.get(a.attrs["w:id"]);l+=B(t,c(T(t,a)),"endnote",String(e),n?` title="${S(n)}"`:"");break}default:l+=B(t,c(T(t,a)),"mark","")}if(!l)return"";if(n.vert&&(l=`<${"sub"===n.vert?"sub":"sup"}>${l}</${"sub"===n.vert?"sub":"sup"}>`),a){const e=I(t,"r");t.doc.runs.set(e,o);const s=h(n),c=r(a,"w:rStyle")?.attrs["w:val"];l=`<span data-r="${e}"${c?` data-rstyle="${S(c)}"`:""}${s?` style="${S(s)}"`:""}>${l}</span>`}for(const e of t.openComments)l=`<span data-comment="${S(e)}" title="${S(t.comments.get(e)??"")}">${l}</span>`;return l}function D(t,e){let a="",n=0,r=-1,s=-1,c="",l="",d=!1;const i=()=>{if(r>=0){const e=J(l);a+=B(t,t.src.slice(r,s),"field",c||t.labels.contents,e?` data-field="${e}"`:"")}l="",r=-1,c="",d=!1};for(const w of e){if("w:r"===w.name){const e=o(w,"w:fldChar");if(e.length||n>0){if(0===n&&(r=w.start,d=!1),d)c+=O(w);else for(const t of o(w,"w:instrText"))l+=t.text;for(const t of e){const e=t.attrs["w:fldCharType"];"begin"===e?n++:"separate"===e&&1===n?d=!0:"end"===e&&n--}s=w.end,0===n&&i();continue}a+=F(t,w);continue}if(n>0)s=w.end;else switch(w.name){case"w:pPr":case"w:proofErr":break;case"w:commentRangeStart":t.openComments.add(w.attrs["w:id"]);break;case"w:commentRangeEnd":t.openComments.delete(w.attrs["w:id"]);break;case"w:hyperlink":{const e=w.attrs["r:id"]?t.rels.get(w.attrs["r:id"]):void 0,n=w.attrs["w:anchor"],r=e?.target??(n?`#${n}`:""),o=C.test(r)||r.startsWith("#"),s=`${e?` data-rel="${S(w.attrs["r:id"])}"`:""}${n?` data-anchor="${S(n)}"`:""}`;a+=`<a${o?` href="${S(r)}"`:""}${s}>${D(t,w.children)}</a>`;break}case"w:ins":case"w:moveTo":a+=`<ins>${D(t,w.children)}</ins>`;break;case"w:del":case"w:moveFrom":a+=`<del>${D(t,w.children)}</del>`;break;case"w:bookmarkStart":{const e=w.attrs["w:name"]??"",n=I(t,"x");t.doc.raw.set(n,T(t,w)),a+=e&&!e.startsWith("_")?`<span data-raw="${n}" data-kind="mark" data-bookmark="${S(e)}" contenteditable="false"></span>`:`<span data-raw="${n}" data-kind="mark"${e.startsWith("_Toc")?` data-toc-anchor="${S(e)}"`:""}></span>`;break}case"w:bookmarkEnd":case"w:permStart":case"w:permEnd":default:a+=L(t,T(t,w));break;case"m:oMath":case"m:oMathPara":t.doc.notices.objects++,a+=B(t,T(t,w),"object",t.labels.equation);break;case"w:fldSimple":case"w:sdt":case"w:smartTag":case"w:customXml":{const e="w:fldSimple"===w.name?J(w.attrs["w:instr"]??""):"";a+=B(t,T(t,w),"field",O(w)||t.labels.contents,e?` data-field="${e}"`:"");break}}}return n>0&&(a+=$(c)),a}function q(t){return s(t,y).length>0}function W(t,e){const a=r(e,"w:pPr"),n=r(a,"w:pStyle")?.attrs["w:val"],o=r(a,"w:numPr")??function(t,e){let a;for(const n of A(t,e))a=r(r(n,"w:pPr"),"w:numPr")??a;return a}(t,n),s=r(o,"w:numId")?.attrs["w:val"];if(!s||"0"===s)return null;const c=Number(r(o,"w:ilvl")?.attrs["w:val"]??0),l=t.numbering.get(s)?.get(c);return{numId:s,ilvl:c,ordered:l?.ordered??!1,marker:l?.marker??"",check:l?.check}}function H(t){const e=[],a=r(t,"w:pBdr");for(const t of["top","bottom","left","right"]){const n=r(a,`w:${t}`);if(!n||"nil"===n.attrs["w:val"]||"none"===n.attrs["w:val"])continue;const o=/^[0-9a-fA-F]{6}$/.test(n.attrs["w:color"]??"")?`#${n.attrs["w:color"]}`:"currentcolor";e.push(`border-${t}:${(Number(n.attrs["w:sz"])||4)/8}pt solid ${o}`)}const n=r(t,"w:shd")?.attrs["w:fill"];return n&&/^[0-9a-fA-F]{6}$/.test(n)&&e.push(`background-color:#${n}`),e.join(";")}function z(t,e,a){const n=r(e,"w:pPr"),o=r(n,"w:pStyle")?.attrs["w:val"],d=t.fieldOpen,i=function(t){let e=0;for(const a of s(t,new Set(["w:fldChar"]))){const t=a.attrs["w:fldCharType"];"begin"===t?e++:"end"===t&&e--}return e}(e),w=q(e)||d||0!==i;i>0&&(t.fieldOpen=!0),d&&i<0&&(t.fieldOpen=!1);const m=I(t,"p");t.doc.blocks.set(m,{xml:T(t,e),fingerprint:"",props:N(t,n),numId:a?.numId,ilvl:a?.ilvl});const p=a?0:function(t,e){if(!e)return 0;const a=r(t.styles.get(e),"w:name")?.attrs["w:val"]??"",n=/^heading ([1-6])$/i.exec(a);return n?Number(n[1]):0}(t,o),f=a?"li":p?`h${p}`:"p",u=l(n);a&&delete u.indentLeft,a&&delete u.firstLine;const h=[c(u),b(u),H(n)].filter(Boolean).join(";");let $=w?G(t,e):D(t,e.children);$&&!/<br>(<\/[^>]+>)*$/.test($)||($+="<br>");const v=r(n,"w:pageBreakBefore")?" data-break-before":"",x=u.tabs?` data-tabs="${g(u.tabs)}"`:"",k=e.attrs["w14:paraId"]?` data-pid="${S(e.attrs["w14:paraId"])}"`:"",y=r(n,"w:sectPr");let P="";if(y){const e=t.sectionTypes[++t.sectionIndex]??"nextPage",a=Number(r(y,"w:cols")?.attrs["w:num"]??1);P=` data-section="${S(e)}"${a>1?` data-cols="${a}"`:""}`}const j=/<span data-raw="[^"]+" data-kind="mark" data-toc-anchor="([^"]+)"/.exec($)?.[1];return`<${f} data-docx="${m}"${k}${v}${P}${p&&j?` data-bm="${j}"`:""}${o?` data-pstyle="${S(o)}"`:""}${x}${h?` style="${S(h)}"`:""}${w?' data-locked contenteditable="false"':""}>${$}</${f}>`}function G(t,e){let a="";for(const n of e.children)"w:pPr"!==n.name&&"w:rPr"!==n.name&&"w:instrText"!==n.name&&"w:delInstrText"!==n.name&&("w:ins"===n.name||"w:moveTo"===n.name?a+=`<ins>${G(t,n)}</ins>`:"w:del"===n.name||"w:moveFrom"===n.name?a+=`<del>${G(t,n)}</del>`:"w:commentRangeStart"===n.name?t.openComments.add(n.attrs["w:id"]):"w:commentRangeEnd"===n.name?t.openComments.delete(n.attrs["w:id"]):"w:t"===n.name||"w:delText"===n.name?a+=$(n.text):"w:tab"===n.name?a+="\t":"w:br"===n.name?a+="<br>":"w:drawing"===n.name||"mc:AlternateContent"===n.name||"w:pict"===n.name?a+=`<span data-kind="object">${$(t.labels.object)}</span>`:a+=G(t,n));return a}function U(t,e){const a=I(t,"t"),n=r(e,"w:tblPr"),s=r(e,"w:tblGrid"),c=o(e,"w:tr"),l=c.some(t=>r(r(t,"w:trPr"),"w:gridBefore")||r(r(t,"w:trPr"),"w:gridAfter")),d=q(e)||l;l&&t.doc.notices.objects++,t.doc.blocks.set(a,{xml:T(t,e),fingerprint:"",props:N(t,n),tblGrid:N(t,s)});const i=r(n,"w:tblStyle")?.attrs["w:val"],w=o(s,"w:gridCol").map(t=>Number(t.attrs["w:w"])/20),m=new Map,p=c.map(t=>{const e=[];let a=0;for(const n of o(t,"w:tc")){const t=r(n,"w:tcPr"),o=Number(r(t,"w:gridSpan")?.attrs["w:val"]??1),s=r(t,"w:vMerge");if(s&&"restart"!==s.attrs["w:val"]&&m.has(a))m.get(a).rowSpan++;else{const t={node:n,rowSpan:1,col:a,span:o};e.push(t),s?m.set(a,t):m.delete(a)}a+=o}return e}),f=function(t,e,a){let n=r(e,"w:tblBorders");if(!n)for(const e of A(t,a))n=r(r(e,"w:tblPr"),"w:tblBorders")??n;return!!n&&n.children.some(t=>!["nil","none"].includes(t.attrs["w:val"]))}(t,n,i),u=c.map((e,a)=>{const n=I(t,"t");t.doc.blocks.set(n,{xml:"",fingerprint:"",props:N(t,r(e,"w:trPr"))});return`<tr data-docx="${n}">${p[a].map(e=>{const a=I(t,"t"),n=r(e.node,"w:tcPr");t.doc.blocks.set(a,{xml:"",fingerprint:"",props:N(t,n)});const o=r(n,"w:shd")?.attrs["w:fill"],s=[];o&&/^[0-9a-fA-F]{6}$/.test(o)&&s.push(`background-color:#${o.toLowerCase()}`);const c=r(n,"w:vAlign")?.attrs["w:val"];return"center"===c&&s.push("vertical-align:middle"),"bottom"===c&&s.push("vertical-align:bottom"),`<td data-docx="${a}"${e.span>1?` colspan="${e.span}"`:""}${e.rowSpan>1?` rowspan="${e.rowSpan}"`:""}${s.length?` style="${s.join(";")}"`:""}>${_(t,e.node.children)}</td>`}).join("")}</tr>`}).join(""),h=w.length?`<colgroup>${w.map(t=>`<col style="width:${Math.round(100*t)/100}pt">`).join("")}</colgroup>`:"";return`<table data-docx="${a}"${i?` data-tstyle="${S(i)}"`:""}${f?"":" data-no-borders"}${d?' data-locked contenteditable="false"':""}>${h}<tbody>${u}</tbody></table>`}function _(t,e){const a=[],n=[],c=t=>{for(;n.length>t;){const t=n.pop();a.push(`</li></${t.tag}>`)}};for(const l of e){const e="w:p"===l.name?W(t,l):null;if(e){for(;n.length&&n[n.length-1].ilvl>e.ilvl;)c(n.length-1);const r=n[n.length-1],o=r&&(!(!r.check||!e.check)||r.numId===e.numId&&r.tag===(e.ordered?"ol":"ul"));r&&r.ilvl===e.ilvl&&!o&&c(n.length-1);const s=`${e.numId}:${e.ilvl}`,d=t.listCounters.get(s)??0;t.listCounters.set(s,d+1);let i=z(t,l,e);"done"===e.check&&(i=i.replace(/^<li /,"<li data-checked "));const w=n[n.length-1];if(w&&w.ilvl===e.ilvl)a.push(`</li>${i.slice(0,i.lastIndexOf("</li>"))}`);else{const t=e.ordered?"ol":"ul",r=e.marker?` style="list-style-type:${e.marker}"`:"",o=e.ordered&&d?` start="${d+1}"`:"",s=e.check?" data-checklist":` data-num-id="${S(e.numId)}"`;a.push(`<${t}${s} data-ilvl="${e.ilvl}"${o}${r}>${i.slice(0,i.lastIndexOf("</li>"))}`),n.push({tag:t,numId:e.numId,ilvl:e.ilvl,check:!!e.check})}continue}if("w:tcPr"!==l.name&&"w:sectPr"!==l.name)if(c(0),"w:p"===l.name)a.push(z(t,l,null));else if("w:tbl"===l.name)a.push(U(t,l));else if("w:sdt"===l.name&&K(l)){const e=I(t,"p");t.doc.blocks.set(e,{xml:T(t,l),fingerprint:""});const n=o(r(l,"w:sdtContent"),"w:p").map(t=>{const e=Number(/(\d)$/.exec(r(r(t,"w:pPr"),"w:pStyle")?.attrs["w:val"]??"")?.[1]??1),a=s(t,new Set(["w:hyperlink"]))[0]?.attrs["w:anchor"]??"",n=O(t).replace(/\s+/g," ").trim();return Z(e,a,n.replace(/\t?\s*\d+$/,""),/(\d+)$/.exec(n)?.[1]??"")}).join("");a.push(`<div data-docx="${e}" data-toc contenteditable="false">${n}</div>`)}else if("w:sdt"===l.name){const e=I(t,"p");t.doc.blocks.set(e,{xml:T(t,l),fingerprint:""}),t.doc.notices.objects++;const n=_(t,o(r(l,"w:sdtContent"),"w:p"));a.push(`<div data-docx="${e}" data-locked contenteditable="false">${n}</div>`)}else{const e=I(t,"p");t.doc.blocks.set(e,{xml:T(t,l),fingerprint:""}),a.push(`<div data-docx="${e}" data-locked data-hidden contenteditable="false"></div>`)}}return c(0),a.join("")}function K(t){const e=r(r(r(t,"w:sdtPr"),"w:docPartObj"),"w:docPartGallery")?.attrs["w:val"]??"";return/table of contents/i.test(e)}function Z(t,e,a,n){const r=/^[A-Za-z0-9_]+$/.test(e)?e:"";return`<p data-toc-level="${Math.min(Math.max(t,1),9)}">${r?`<a href="#${r}" data-anchor="${r}">${$(a)}</a>`:$(a)}<span data-toc-page>${$(n)}</span></p>`}function J(t){const e=t.trim().split(/\s+/)[0]?.toUpperCase();return"PAGE"===e?"page":"NUMPAGES"===e||"SECTIONPAGES"===e?"pages":""}function X(t){if("LI"!==t.tagName)return t.outerHTML;const e=t.cloneNode(!0);return Array.from(e.children).forEach(t=>{"UL"!==t.tagName&&"OL"!==t.tagName||t.remove()}),e.outerHTML}function Q(t,e=t.html){const a=document.createElement("div");a.innerHTML=e,a.querySelectorAll("[data-docx]").forEach(e=>{const a=t.blocks.get(e.getAttribute("data-docx"));a&&(a.fingerprint=X(e))})}function V(t,e){const a=e?w(t.doc.parts,e):void 0;if(!e||!a)return{text:"",html:"",editable:!0};const n=i(a),r=0===s(n,new Set(["w:sdt","mc:AlternateContent","w:pict","w:txbxContent"])).length,o={src:t.src,rels:t.rels,notices:{...t.doc.notices}};t.src=a,t.rels=new Map(m(t.doc.parts,e).map(t=>[t.id,t]));let c="";try{c=_(t,n.children)}finally{t.src=o.src,t.rels=o.rels,t.doc.notices=o.notices}return{text:Y(n),html:r?c:`<div data-locked contenteditable="false">${c}</div>`,editable:r,part:e}}function Y(t){return t.children.filter(t=>"w:p"===t.name).map(t=>{let e="",a="",n=!1;const r=t=>{for(const o of t.children)if("w:t"===o.name)n||(e+=o.text);else if("w:tab"===o.name)n||(e+=" | ");else if("w:instrText"===o.name)a+=o.text;else if("w:fldChar"===o.name){const t=o.attrs["w:fldCharType"];"separate"!==t&&"end"!==t||(a&&(e+=tt(a),a=""),n="separate"===t)}else"w:fldSimple"===o.name?e+=tt(o.attrs["w:instr"]??"")||o.children.map(O).join(""):"w:pPr"!==o.name&&"w:rPr"!==o.name&&r(o)};return r(t),e}).filter(Boolean).join(" ")}function tt(t){const e=J(t);return e?`{${e}}`:""}function et(t,e,a){return 1===t&&e?"first":t%2==0&&a?"even":"default"}function at(t){const e=document.createElement("div");e.innerHTML=t,e.querySelectorAll('[data-field="page"]').forEach(t=>t.replaceWith("{page}")),e.querySelectorAll('[data-field="pages"]').forEach(t=>t.replaceWith("{pages}")),e.querySelectorAll('img,[data-kind="object"],[data-hidden]').forEach(t=>t.remove());const a=Array.from(e.querySelectorAll("p,h1,h2,h3,h4,h5,h6,li")).map(t=>(t.textContent??"").replace(/\t/g," | ").trim()).filter(Boolean);return a.length?a.join(" "):(e.textContent??"").trim()}async function nt(t,e={}){return rt(await f(t),t,e)}function rt(f,b,g={}){const $=m(f,"").find(t=>t.type.endsWith("/officeDocument")),x=$?u("",$.target):"word/document.xml",y=w(f,x);if(!y)throw new Error("Not a Word document");const j=i(y),C=r(j,"w:body");if(!C)throw new Error("Not a Word document");const S=m(f,x),I=t=>{const e=(t=>S.find(e=>e.type===t))(t);return e?u(x,e.target):void 0},T=p(I(n.theme)?w(f,I(n.theme)):void 0),N={parts:f,docPath:x,source:b,html:"",css:"",page:{...a},headers:k(),footers:k(),titlePage:!1,evenOdd:!1,columns:1,footnotes:new Map,blocks:new Map,runs:new Map,raw:new Map,notices:{comments:0,tracked:0,objects:0,footnotes:0},styles:[],theme:T},B={src:y,doc:N,labels:g.labels??v,rels:new Map(S.map(t=>[t.id,t])),theme:T,imageUrl:g.imageUrl??M,styles:new Map,numbering:new Map,listCounters:new Map,comments:new Map,footnotes:new Map,nextId:0,footnoteCount:0,openComments:new Set,fieldOpen:!1,sectionTypes:[],sectionIndex:0},L=I(n.styles),R=L?w(f,L):void 0,F=R?i(R):void 0;for(const t of o(F,"w:style"))B.styles.set(t.attrs["w:styleId"],t);const D=new Set(B.styles.keys());for(const[e,a]of Object.entries(t))D.has(e)||B.styles.set(e,i(a.xml));const q=r(F,"w:docDefaults");N.lang=r(r(r(q,"w:rPrDefault"),"w:rPr"),"w:lang")?.attrs["w:val"],N.css=function(t,e){const a=[],n=d(r(r(e,"w:rPrDefault"),"w:rPr"),t.theme),o=l(r(r(e,"w:pPrDefault"),"w:pPr"));t.doc.defaultFont=n.font,t.doc.defaultSize=n.size;let s=n,i=o;for(const[e,w]of t.styles){const m=w.attrs["w:type"];if("paragraph"!==m&&"character"!==m&&"table"!==m)continue;let p={},f={};for(const a of A(t,e))p={...p,...d(r(a,"w:rPr"),t.theme)},f={...f,...l(r(a,"w:pPr"))};if("paragraph"===m)a.push(`.docs-page [data-pstyle=${E(e)}]{${[h(p),c(f)].filter(Boolean).join(";")}}`),"1"===w.attrs["w:default"]&&(s={...n,...p},i={...o,...f});else if("character"===m)a.push(`.docs-page [data-rstyle=${E(e)}]{${h(p)}}`);else{const t=c(f);t&&a.push(`.docs-page table[data-tstyle=${E(e)}] p{${t}}`)}}return a.unshift(`.docs-page{${h(s)}}`,`.docs-page p,.docs-page h1,.docs-page h2,.docs-page h3,.docs-page h4,.docs-page h5,.docs-page h6,.docs-page li{${c(i)}}`),a.join("\n")}(B,q);const W=new Set(Object.keys(t));N.styles=[...B.styles.values()].filter(t=>"paragraph"===t.attrs["w:type"]&&"1"!==t.attrs["w:default"]&&(W.has(t.attrs["w:styleId"])||r(t,"w:qFormat"))&&!r(t,"w:hidden")&&!r(t,"w:semiHidden")).map(t=>({id:t.attrs["w:styleId"],name:r(t,"w:name")?.attrs["w:val"]??t.attrs["w:styleId"]}));const H=I(n.numbering),z=H?w(f,H):void 0;z&&function(t,a){const n=new Map;for(const t of o(a,"w:abstractNum")){const a=new Map;for(const n of o(t,"w:lvl")){const t=r(n,"w:numFmt")?.attrs["w:val"]??"decimal",o=r(n,"w:lvlText")?.attrs["w:val"],s="bullet"===t&&o===e.open?"open":"bullet"===t&&o===e.done?"done":void 0;a.set(Number(n.attrs["w:ilvl"]),{ordered:"bullet"!==t&&"none"!==t,marker:ot[t]??"",check:s})}n.set(t.attrs["w:abstractNumId"],a)}for(const e of o(a,"w:num")){const a=n.get(r(e,"w:abstractNumId")?.attrs["w:val"]??"");a&&t.numbering.set(e.attrs["w:numId"],a)}}(B,i(z));const G=I(n.comments),U=G?w(f,G):void 0;if(U){for(const t of o(i(U),"w:comment"))B.comments.set(t.attrs["w:id"],`${t.attrs["w:author"]??""}: ${O(t)}`);N.notices.comments=B.comments.size}const K=I(n.footnotes),Z=K?w(f,K):void 0;if(Z)for(const t of o(i(Z),"w:footnote")){const e=t.attrs["w:id"];if(B.footnotes.set(e,O(t)),t.attrs["w:type"]&&"normal"!==t.attrs["w:type"])continue;const a=0===s(t,new Set(["w:tbl","w:drawing","w:pict","mc:AlternateContent","w:sdt","m:oMath"])).length;N.footnotes.set(e,{text:O(t).trim(),xml:Z.slice(t.start,t.end),editable:a})}N.notices.tracked=s(C,P).length;const J=r(C,"w:sectPr"),X=[...s(C,new Set(["w:sectPr"])).filter(t=>t!==J),...J?[J]:[]];B.sectionTypes=X.map(t=>r(t,"w:type")?.attrs["w:val"]??"nextPage"),B.sectionIndex=0,N.columns=Math.max(1,Number(r(J,"w:cols")?.attrs["w:num"]??1)||1),N.titlePage=!!r(J,"w:titlePg")&&"0"!==r(J,"w:titlePg")?.attrs["w:val"];const Y=I(n.settings),tt=Y?w(f,Y):void 0;N.evenOdd=!!tt&&/<w:evenAndOddHeaders(?![^>]*w:val="(?:0|false)")[^>]*\/?>/.test(tt);const et=r(J,"w:pgSz"),at=r(J,"w:pgMar"),nt=(t,e,a)=>{const n=Number(t?.attrs[e]);return Number.isFinite(n)&&void 0!==t?.attrs[e]?n:a};N.page={width:nt(et,"w:w",a.width),height:nt(et,"w:h",a.height),top:Math.abs(nt(at,"w:top",a.top)),right:nt(at,"w:right",a.right),bottom:Math.abs(nt(at,"w:bottom",a.bottom)),left:nt(at,"w:left",a.left),header:nt(at,"w:header",a.header),footer:nt(at,"w:footer",a.footer)};const rt=(t,e)=>{const a=o(J,t).find(t=>(t.attrs["w:type"]??"default")===e),n=a&&B.rels.get(a.attrs["r:id"]);return n?u(x,n.target):void 0};N.html=_(B,C.children);for(const t of["default","first","even"])N.headers[t]=V(B,rt("w:headerReference",t)),N.footers[t]=V(B,rt("w:footerReference",t));N.html||(N.html="<p><br></p>"),Q(N),N.footnotesRead=new Map([...N.footnotes].map(([t,e])=>[t,e.text]));for(const t of[N.headers,N.footers])for(const e of Object.values(t))e.html&&Q(N,e.html);return N}var ot={lowerLetter:"lower-alpha",upperLetter:"upper-alpha",lowerRoman:"lower-roman",upperRoman:"upper-roman",decimalZero:"decimal-leading-zero"};export{Z as tocEntryHtml,X as fingerprintOf,Q as stampFingerprints,et as headerKindFor,at as marginTextOfHtml,nt as readDocx,rt as readParts};
@@ -31,6 +31,45 @@
31
31
  .docs-outline { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 2px; }
32
32
  .docs-outline button { display: block; width: 100%; padding: 4px; border-radius: 4px; text-align: left; font-size: 12px; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
33
33
  .docs-outline button:hover { background: var(--line-subtle); }
34
+
35
+ /* Documents parity (2026-11-16): ruler, header/footer, footnotes, dialogs. The ruler
36
+ and the header and footer previews sit on the white sheet, so they keep its colours. */
37
+ .docs-ruler-row { position: sticky; top: 0; z-index: 2; display: flex; justify-content: center; padding: 6px 0 4px; background: var(--surface-sunken); }
38
+ .docs-ruler { position: relative; height: 18px; background: #fff; border-bottom: 1px solid #ccc; cursor: copy; user-select: none; touch-action: none; }
39
+ .docs-ruler-margin { position: absolute; top: 0; bottom: 0; background: #e8e8e8; pointer-events: none; }
40
+ .docs-ruler-tick { position: absolute; top: 2px; transform: translateX(-50%); font-size: 9px; line-height: 1; color: #777; pointer-events: none; }
41
+ .docs-ruler-tick::after { content: ""; position: absolute; left: 50%; top: 11px; width: 1px; height: 4px; background: #aaa; }
42
+ .docs-ruler button { position: absolute; padding: 0; border: 0; background: none; cursor: ew-resize; transform: translateX(-50%); }
43
+ .docs-ruler-first { top: 0; width: 0; height: 0; border-left: 5px solid transparent !important; border-right: 5px solid transparent !important; border-top: 7px solid #1a73e8 !important; }
44
+ .docs-ruler-left, .docs-ruler-right { bottom: 0; width: 0; height: 0; border-left: 5px solid transparent !important; border-right: 5px solid transparent !important; border-bottom: 7px solid #1a73e8 !important; }
45
+ .docs-ruler-tab { top: 9px; width: 9px; height: 9px; }
46
+ .docs-ruler-tab::before { content: ""; position: absolute; inset: 0; border-left: 2px solid #333; border-bottom: 2px solid #333; }
47
+ .docs-ruler-tab-center::before { left: 3px; right: auto; width: 0; border-left: 2px solid #333; border-bottom: 0; }
48
+ .docs-ruler-tab-center::after { content: ""; position: absolute; left: 0; right: 0; bottom: 0; border-bottom: 2px solid #333; }
49
+ .docs-ruler-tab-right::before { border-left: 0; border-right: 2px solid #333; }
50
+
51
+ .docs-hf-preview { position: absolute; display: block; overflow: hidden; padding: 0; border: 1px dashed transparent; background: transparent; text-align: left; cursor: pointer; min-height: 12px; }
52
+ .docs-hf-preview:hover, .docs-hf-preview:focus-visible { border-color: #9ab; outline: none; }
53
+ .docs-hf-preview:empty:hover::before, .docs-hf-preview:empty:focus-visible::before { content: attr(data-hint); color: #999; font: 9pt Calibri, Carlito, Arial, sans-serif; }
54
+ .docs-hf { display: flex; flex-direction: column; gap: 16px; }
55
+ .docs-hf-options { display: flex; flex-wrap: wrap; gap: 16px; }
56
+ .docs-hf-kind { display: flex; flex-direction: column; gap: 8px; }
57
+ .docs-hf-kind h4 { margin: 0; font-size: 13px; font-weight: 600; }
58
+ .docs-hf-region { border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
59
+ .docs-hf-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 2px 6px; border-bottom: 1px solid var(--line); background: var(--surface-sunken); }
60
+ .docs-hf-label { margin-right: auto; font-size: 12px; color: var(--ink-muted); }
61
+ .docs-hf-edit { min-height: 48px; padding: 8px 12px; }
62
+ .docs-hf-note { margin: 0; padding: 4px 12px 8px; font-size: 12px; color: var(--ink-muted); }
63
+
64
+ .docs-footnotes { position: relative; margin-top: 12pt; padding-top: 6pt; border-top: 0.75pt solid #999; color: #000; font: 9pt Calibri, Carlito, Arial, sans-serif; }
65
+ .docs-footnote { display: flex; align-items: baseline; gap: 4pt; margin-bottom: 3pt; }
66
+ .docs-footnote sup { min-width: 10pt; color: #0563c1; }
67
+ .docs-footnote input { flex: 1; min-width: 0; padding: 1pt 2pt; border: 1px solid transparent; border-radius: 2px; background: transparent; color: #000; font: inherit; }
68
+ .docs-footnote input:hover, .docs-footnote input:focus { border-color: #bbb; outline: none; }
69
+ .docs-footnote input::placeholder { color: #999; }
70
+
71
+ .docs-para-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
72
+ .docs-para-error { margin: 8px 0 0; font-size: 12px; color: var(--status-danger-ink, #b42318); }
34
73
  /* The file list Documents and Spreadsheet share (./FileList.tsx), laid out as
35
74
  Slides' deck list is. The build appends this to documents.css and
36
75
  spreadsheet.css, so a host loads it with the app's own stylesheet. */
@@ -9,7 +9,8 @@ export { E as ENGLISH_FILE_WORDS, O as OfficeFileChoice, a as OfficeFileRequest,
9
9
  *
10
10
  * The zh-Hans words for the Easel frame (`backToFiles` to `openFromFiles`) are
11
11
  * machine-written, and no person has read them yet. Nor have the file list's
12
- * (`filesHeading` to `deleteConfirm`).
12
+ * (`filesHeading` to `deleteConfirm`), nor the parity words of 2026-11-16 (`styleHeading4`
13
+ * to `wordFonts`).
13
14
  */
14
15
 
15
16
  interface DocumentsWords {
@@ -129,7 +130,6 @@ interface DocumentsWords {
129
130
  marginsWide: string;
130
131
  header: string;
131
132
  footer: string;
132
- headerFooterHint: string;
133
133
  headerFooterLocked: string;
134
134
  ok: string;
135
135
  cancel: string;
@@ -169,6 +169,67 @@ interface DocumentsWords {
169
169
  cannotRead: (name: string) => string;
170
170
  unsupported: (ext: string) => string;
171
171
  pdfPageFailed: (page: number) => string;
172
+ styleHeading4: string;
173
+ styleHeading5: string;
174
+ styleHeading6: string;
175
+ applyStyle: (name: string) => string;
176
+ updateStyle: (name: string) => string;
177
+ styleUpdated: (name: string) => string;
178
+ paintFormat: string;
179
+ paintFormatHint: string;
180
+ checklist: string;
181
+ paragraphSpacing: string;
182
+ addSpaceBefore: string;
183
+ removeSpaceBefore: string;
184
+ addSpaceAfter: string;
185
+ removeSpaceAfter: string;
186
+ customSpacing: string;
187
+ lineSpacingCustom: string;
188
+ spacingBefore: string;
189
+ spacingAfter: string;
190
+ indentLeft: string;
191
+ indentRight: string;
192
+ indentSpecial: string;
193
+ indentNone: string;
194
+ indentFirstLine: string;
195
+ indentHanging: string;
196
+ indentBy: string;
197
+ spacingInvalid: string;
198
+ ruler: string;
199
+ tabStop: string;
200
+ tabStopHint: string;
201
+ columns: string;
202
+ columnsCount: (n: number) => string;
203
+ tableOfContents: string;
204
+ tocRefresh: string;
205
+ tocDelete: string;
206
+ footnote: string;
207
+ footnotes: string;
208
+ footnotePlaceholder: string;
209
+ footnoteLocked: string;
210
+ bookmark: string;
211
+ bookmarkPrompt: string;
212
+ bookmarkInvalid: string;
213
+ bookmarkTaken: string;
214
+ linkToHeading: string;
215
+ linkToBookmark: string;
216
+ noHeadings: string;
217
+ noBookmarks: string;
218
+ breakMenu: string;
219
+ sectionBreakNext: string;
220
+ sectionBreakContinuous: string;
221
+ removeSectionBreak: string;
222
+ headersFooters: string;
223
+ headersFootersHint: string;
224
+ differentFirst: string;
225
+ differentOddEven: string;
226
+ headerDefault: string;
227
+ headerOdd: string;
228
+ headerFirst: string;
229
+ headerEven: string;
230
+ pageCount: string;
231
+ webFonts: string;
232
+ wordFonts: string;
172
233
  /** The file list's shared words: Open, Rename and the rest. */
173
234
  files: FileWords;
174
235
  /** The kind of file Open takes from the drive, as the drive names it. */
@@ -1 +1 @@
1
- import{DocumentsConflict as t,DocumentsProvider as o,DocumentsWordsProvider as n}from"../chunk-HU4RI2OM.js";import{ENGLISH_WORDS as m,ZH_HANS_WORDS as r}from"../chunk-I3AC6PYR.js";import{ENGLISH_FILE_WORDS as c,ZH_HANS_FILE_WORDS as e}from"../chunk-B32ASXHM.js";import{hasExtension as i}from"../chunk-XYVQTQ6N.js";import{lazy as s}from"react";var u=s(()=>import("../Documents-ISV66NLW.js")),p=s(()=>import("../Documents-ISV66NLW.js").then(t=>({default:t.OpenDocument}))),a={"/documents":{component:u,label:"Documents",size:"xl",appStyle:!0,multiInstance:!0}};async function f(t,o){const{docxToPdf:n}=await(import("../docxPdf-EW5I5JR3.js"));return n(t,o)}async function j(t,o){const{importDocumentFile:n}=await(import("../importDocument-274VK7OM.js"));return n(t,o)}export{p as DocumentEditor,u as Documents,t as DocumentsConflict,o as DocumentsProvider,n as DocumentsWordsProvider,c as ENGLISH_FILE_WORDS,m as ENGLISH_WORDS,e as ZH_HANS_FILE_WORDS,r as ZH_HANS_WORDS,a as documentsApp,f as docxToPdf,i as hasExtension,j as importDocumentFile};
1
+ import{DocumentsConflict as t,DocumentsProvider as o,DocumentsWordsProvider as n}from"../chunk-HNNYUGDU.js";import{ENGLISH_WORDS as m,ZH_HANS_WORDS as r}from"../chunk-POH6OTTR.js";import{ENGLISH_FILE_WORDS as c,ZH_HANS_FILE_WORDS as e}from"../chunk-B32ASXHM.js";import{hasExtension as i}from"../chunk-XYVQTQ6N.js";import{lazy as s}from"react";var u=s(()=>import("../Documents-2ZU5D3ZI.js")),p=s(()=>import("../Documents-2ZU5D3ZI.js").then(t=>({default:t.OpenDocument}))),a={"/documents":{component:u,label:"Documents",size:"xl",appStyle:!0,multiInstance:!0}};async function f(t,o){const{docxToPdf:n}=await(import("../docxPdf-QSMEFCUF.js"));return n(t,o)}async function D(t,o){const{importDocumentFile:n}=await(import("../importDocument-34WALCTG.js"));return n(t,o)}export{p as DocumentEditor,u as Documents,t as DocumentsConflict,o as DocumentsProvider,n as DocumentsWordsProvider,c as ENGLISH_FILE_WORDS,m as ENGLISH_WORDS,e as ZH_HANS_FILE_WORDS,r as ZH_HANS_WORDS,a as documentsApp,f as docxToPdf,i as hasExtension,D as importDocumentFile};
@@ -0,0 +1 @@
1
+ import{marginText as t,pageBlocks as e,pageStarts as o,pageStyles as n,printStyles as i}from"./chunk-EC6D54MM.js";import{boxesInWindow as r,pageWindows as s}from"./chunk-PWF37Y2N.js";import{ENGLISH_WORDS as a}from"./chunk-POH6OTTR.js";import{drawJpeg as p,embeddedFonts as c,jpegPdf as l,openStage as h,settled as d}from"./chunk-JKYJGXJE.js";import"./chunk-B32ASXHM.js";import{headerKindFor as f,readDocx as u}from"./chunk-YKQ5UKYZ.js";import"./chunk-D3JKD7KW.js";var g="pdf",m=t=>t/20*(4/3);function x(t){const e=t.getBoundingClientRect().top;return Array.from(t.children,t=>{const o=t.getBoundingClientRect();return{top:o.top-e,height:o.height}})}function w(e,o,n,i,r){const s=document.createElement("div");s.style.cssText=`position:absolute;display:flex;justify-content:space-between;font:9pt Calibri,Carlito,Arial,sans-serif;color:#555;white-space:pre;left:${m(o.left)}px;right:${m(o.right)}px;${r}`;for(const o of t(e,n,i))s.append(Object.assign(document.createElement("span"),{textContent:o}));return s}function y(t,e,o,n){const{page:i,headers:s,footers:a,titlePage:p,evenOdd:c}=t.doc,l=f(o,p,c),h=s[l],d=a[l],u=document.createElement("div");u.style.cssText=`position:relative;overflow:hidden;background:#fff;width:${m(i.width)}px;height:${m(i.height)}px`;const g=document.createElement("div");return g.style.cssText=`position:absolute;overflow:hidden;left:${m(i.left)}px;top:${m(i.top)}px;right:${m(i.right)}px;height:${e.height}px`,g.append(function({body:t,boxes:e},o){const n=t.cloneNode(!1),i=r(e,o);if(!i)return n;for(let e=i.first;e<=i.last;e+=1)n.append(t.children[e].cloneNode(!0));const s=parseFloat(getComputedStyle(t.children[i.first]).marginTop)||0;return n.style.position="absolute",n.style.left="0",n.style.top=e[i.first].top-s-o.top+"px",n}(t,e)),u.append(g),h.text&&u.append(w(h.text,i,o,n,`top:${m(i.header)}px`)),d.text&&u.append(w(d.text,i,o,n,`bottom:${m(i.footer)}px`)),u}async function b(t,e,o,n,i){e.append(t);try{await d(t);return{jpeg:await p(t,{width:m(o.width),height:m(o.height),pixelRatio:2,quality:i,fontCss:n}),width:o.width/20,height:o.height/20}}finally{t.remove()}}async function $(t,r={}){const{signal:p,onProgress:f,quality:w}=r;p?.throwIfAborted();const $=await u(new Uint8Array(await t.arrayBuffer())),C=h();try{const t=function(t,e){const o=document.createElement("style");o.textContent=`${n(t,g)}\n${i(g)}`;const r=document.createElement("div");return r.className="docs-page",r.dataset.doc=g,r.style.cssText=`display:flow-root;width:${m(t.page.width-t.page.left-t.page.right)}px`,r.innerHTML=t.html,e.append(o,r),r}($,C.root);await d(t);const r={doc:$,body:t,boxes:x(t)},h=function(t,n){const i=m(t.page.height-t.page.top-t.page.bottom),r=o(e(n,n.getBoundingClientRect().top),i);return s(r,i,n.getBoundingClientRect().height)}($,t),u=await c(t),j=[];for(const[t,e]of h.entries()){p?.throwIfAborted();const o=y(r,e,t+1,h.length);j.push(await b(o,C.root,$.page,u,w).catch(e=>{throw new Error(a.pdfPageFailed(t+1),{cause:e})})),f?.(t+1,h.length)}return l(j)}finally{C.close()}}export{$ as docxToPdf};
@@ -0,0 +1 @@
1
+ import{importDocumentFile as o}from"./chunk-O35VT6BD.js";import"./chunk-YKQ5UKYZ.js";import"./chunk-D3JKD7KW.js";import"./chunk-XYVQTQ6N.js";export{o as importDocumentFile};
@@ -1 +1 @@
1
- import{PptxPasswordError as t,PptxUnreadableError as e}from"./chunk-MDG2ADZ7.js";import{DECK_FONT as n,ENGLISH_WORDS as r,MIN_SIZE as a,NO_FILL as o,SLIDE_H as s,SLIDE_W as i,newId as l,newSlide as c}from"./chunk-PXOQN7D6.js";import"./chunk-B32ASXHM.js";import{child as p,childrenOf as f,descendants as u,openZip as d,parseXml as m,partText as h,readRels as y,readThemeFonts as g,resolveTarget as w}from"./chunk-RHW2M2UY.js";var x=2097152;function b(t){if(Array.isArray(t))return t.reduce((t,e)=>t+b(e)+2,t.length?0:2);if(t&&"object"==typeof t){const e=Object.entries(t).filter(([,t])=>void 0!==t);return e.reduce((t,[e,n])=>t+b(e)+2+b(n)+2,e.length?0:2)}const e=JSON.stringify(t)??"null";return e.length+5*(e.match(/[^\x20-\x7e]/g)?.length??0)}var v=[208,207,17,224],M=Array.from("EncryptedPackage").flatMap(t=>[t.charCodeAt(0),0]),k=4194304;function P(t){for(let e=t.indexOf(M[0]);e>=0;e=t.indexOf(M[0],e+1))if(M.every((n,r)=>t[e+r]===n))return!0;return!1}var S={black:"000000",white:"ffffff",red:"ff0000",green:"008000",blue:"0000ff",yellow:"ffff00",gray:"808080",grey:"808080"},N={bg1:"lt1",tx1:"dk1",bg2:"lt2",tx2:"dk2"};function C(t){const e=t.children[0];return e?.attrs.lastClr??e?.attrs.val}function A(t,e){const n=new Map,r=p(p(t,"a:themeElements"),"a:clrScheme")?.children??[];for(const t of r){const e=C(t);e&&n.set(t.name.replace(/^a:/,""),e)}return{scheme:n,map:{...N,...e?.attrs}}}function B(t,e){const n=p(p(e,"p:clrMapOvr"),"a:overrideClrMapping");return n?{...t,map:{...t.map,...n.attrs}}:t}var I=t=>[0,2,4].map(e=>parseInt(t.slice(e,e+2),16)),F=t=>t.map(t=>{return(e=t,Math.max(0,Math.min(255,Math.round(e)))).toString(16).padStart(2,"0");var e}).join("");function T(t,e,n){const[r,a,o]=function([t,e,n]){const[r,a,o]=[t/255,e/255,n/255],s=Math.max(r,a,o),i=Math.min(r,a,o),l=(s+i)/2;if(s===i)return[0,0,l];const c=s-i;return[(s===r?(a-o)/c+(a<o?6:0):s===a?(o-r)/c+2:(r-a)/c+4)/6,l>.5?c/(2-s-i):c/(s+i),l]}(I(t));return F(function([t,e,n]){if(0===e)return[255*n,255*n,255*n];const r=n<.5?n*(1+e):n+e-n*e,a=2*n-r,o=t=>{const e=(t+1)%1;return e<1/6?a+6*(r-a)*e:e<.5?r:e<2/3?a+(r-a)*(2/3-e)*6:a};return[o(t+1/3),o(t),o(t-1/3)].map(t=>255*t)}([r,a,Math.max(0,Math.min(1,o*e+n))]))}function $(t,e){const n=Number(e.attrs.val)/1e5;if(!Number.isFinite(n))return t;switch(e.name){case"a:lumMod":return T(t,n,0);case"a:lumOff":return T(t,1,n);case"a:tint":return F(I(t).map(t=>t+(255-t)*(1-n)));case"a:shade":return F(I(t).map(t=>t*n));default:return t}}function j(t,e){const n=e.scheme.get(e.map[t]??t);return n?`#${n.toLowerCase()}`:void 0}function z(t,e){const n=t&&function(t,e){switch(t.name){case"a:srgbClr":return t.attrs.val;case"a:sysClr":return t.attrs.lastClr;case"a:prstClr":return S[t.attrs.val];case"a:schemeClr":return e.scheme.get(e.map[t.attrs.val]??t.attrs.val);default:return}}(t,e);if(t&&n&&/^[0-9a-f]{6}$/i.test(n)&&"0"!==p(t,"a:alpha")?.attrs.val)return`#${t.children.reduce($,n).toLowerCase()}`}function O(t,e){return z(p(t,"a:solidFill")?.children[0],e)}var R=t=>"1"===t||"true"===t,D=t=>Math.round(100*t)/100+0,H=(t,e)=>D(12700*t*e.scale),L=t=>t*Math.PI/180;function E(t){const e=p(t,"a:off")?.attrs,n=p(t,"a:ext")?.attrs;if(t&&e&&n)return{x:Number(e.x)||0,y:Number(e.y)||0,w:Number(n.cx)||0,h:Number(n.cy)||0,rotation:(Number(t.attrs.rot)||0)/6e4}}function V(t){const e=p(p(t,"p:grpSpPr"),"a:xfrm"),n=E(e),r=p(e,"a:chOff")?.attrs,a=p(e,"a:chExt")?.attrs;if(n&&r&&a)return{box:n,childX:Number(r.x)||0,childY:Number(r.y)||0,scaleX:Number(a.cx)?n.w/Number(a.cx):1,scaleY:Number(a.cy)?n.h/Number(a.cy):1,flipH:R(e?.attrs.flipH),flipV:R(e?.attrs.flipV)}}function X(t,e){const{box:n}=e,r=n.x+n.w/2,a=n.y+n.h/2;let o=n.x+(t.x-e.childX)*e.scaleX,s=n.y+(t.y-e.childY)*e.scaleY;e.flipH&&(o=2*r-o),e.flipV&&(s=2*a-s);const i=L(n.rotation),l=o-r,c=s-a;return{x:r+l*Math.cos(i)-c*Math.sin(i),y:a+l*Math.sin(i)+c*Math.cos(i)}}function W(t,e){const n=X({x:t.x+t.w/2,y:t.y+t.h/2},e),r=t.w*e.scaleX,a=t.h*e.scaleY,o=e.flipH!==e.flipV;return{x:n.x-r/2,y:n.y-a/2,w:r,h:a,rotation:(o?-t.rotation:t.rotation)+e.box.rotation}}var Y=t=>D((t%360+360)%360);function G(t,e,n){const r=e.reduce(W,t);return{id:l(),x:D(n.left+r.x*n.scale),y:D(n.top+r.y*n.scale),w:D(r.w*n.scale),h:D(r.h*n.scale),rotation:Y(r.rotation)}}function U(t,e,n,r){const o=t.x+t.w/2,s=t.y+t.h/2,i=L(t.rotation),c=a=>{const l=a*(e.flipH?-1:1)*t.w/2,c=a*(e.flipV?-1:1)*t.h/2,p={x:o+l*Math.cos(i)-c*Math.sin(i),y:s+l*Math.sin(i)+c*Math.cos(i)},f=n.reduce(X,p);return{x:r.left+f.x*r.scale,y:r.top+f.y*r.scale}},p=c(-1),f=c(1),u=Math.hypot(f.x-p.x,f.y-p.y);return{id:l(),x:D((p.x+f.x-u)/2),y:D((p.y+f.y-a)/2),w:D(u),h:a,rotation:Y(180*Math.atan2(f.y-p.y,f.x-p.x)/Math.PI)}}var q={scheme:new Map,map:{}},Q=(t,e)=>[...t.rels.values()].find(t=>t.type.endsWith(e)),J=t=>p(p(t,"p:cSld"),"p:spTree");function Z(t,e){const n=h(t,e);if(n)return{part:e,root:m(n),rels:new Map(y(t,e).map(t=>[t.id,t]))}}function _(t,e,n){const r=Z(t,e);if(!r)return;const a=Q(r,"/slideMaster"),o=a&&w(e,a.target);return o&&!n.has(o)&&n.set(o,function(t,e){const n=Z(t,e);if(!n)return;const r=Q(n,"/theme"),a=r?h(t,w(e,r.target)):void 0;return{...n,palette:A(a?m(a):void 0,p(n.root,"p:clrMap")),fonts:g(a)}}(t,o)),{...r,master:o?n.get(o):void 0}}var K={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",bmp:"image/bmp"};var tt=t=>p(p(p(t,"p:nvSpPr"),"p:nvPr"),"p:ph")??p(p(p(t,"p:nvPicPr"),"p:nvPr"),"p:ph"),et=t=>!!tt(t),nt=t=>(J(t.root)?.children??[]).filter(t=>"p:sp"===t.name&&tt(t)),rt=new Set(["title","ctrTitle"]),at=new Set(["dt","ftr","sldNum"]);function ot(t){return t&&rt.has(t)?"title":t&&at.has(t)?t:"body"}function st(t,e){const n=tt(t);if(!n)return{shapes:[],style:"p:otherStyle",isPlaceholder:!1};const r=e.layout&&function(t,e){const n=nt(t),{idx:r,type:a}=e.attrs;return(void 0!==r?n.find(t=>tt(t)?.attrs.idx===r):void 0)??(void 0!==a?n.find(t=>tt(t)?.attrs.type===a):void 0)}(e.layout,n),a=r?tt(r)??n:n,o=e.master&&function(t,e){const n=ot(e.attrs.type);return nt(t).find(t=>ot(tt(t)?.attrs.type)===n)}(e.master,a),s=ot(a.attrs.type);return{shapes:[r,o].filter(t=>!!t),style:"title"===s?"p:titleStyle":"body"===s?"p:bodyStyle":"p:otherStyle",isPlaceholder:!0}}function it(t,e,n,r){const a=t=>p(p(t,"p:txBody"),"a:lstStyle"),o=p(p(n.master?.root,"p:txStyles"),e.style),s=e.isPlaceholder?[o,r]:[r,o];return[a(t),...e.shapes.map(a),...s]}function lt(t,e,n){for(const r of[t,...e.shapes]){const t=p(p(r,"p:txBody"),"a:bodyPr")?.attrs[n];if(void 0!==t)return t}}var ct={l:"left",ctr:"center",r:"right"},pt=(t,e)=>t.lists.flatMap(t=>{const n=p(t,`a:lvl${e+1}pPr`);return n?[n]:[]});function ft(t,e){return"+mj-lt"===t?e.fonts.major:"+mn-lt"===t?e.fonts.minor:t}function ut(t,e,n,r){const a=[t,p(e,"a:defRPr"),...n.map(t=>p(t,"a:defRPr"))].filter(t=>!!t),o=t=>a.find(e=>void 0!==e.attrs[t])?.attrs[t],s=Number(o("sz")),i=o("b"),l=a.map(t=>O(t,r.palette)),c=a.map(t=>p(t,"a:latin")?.attrs.typeface).find(Boolean);return{sizePt:Number.isFinite(s)&&s>0?s/100:18,bold:"1"===i||"true"===i,colour:l.find(Boolean)??r.styleColour??j("tx1",r.palette)??"#000000",typeface:ft(c,r)??(r.isTitle?r.fonts.major:r.fonts.minor)}}function dt(t,e){for(const n of[t,...e]){if(p(n,"a:buNone"))return{kind:"none"};if(p(n,"a:buChar")||p(n,"a:buBlip"))return{kind:"bullet"};const t=p(n,"a:buAutoNum");if(t)return{kind:"number",startAt:Number(t.attrs.startAt)||1}}return{kind:"none"}}function mt(t,e){const n=[t,...e].map(t=>t?.attrs.algn).find(Boolean);return n&&ct[n]||"left"}function ht(t,e,n){const r=p(t,"a:pPr"),a=[];let o="";for(const s of t.children){if("a:br"===s.name&&(o+="\n"),"a:r"!==s.name&&"a:fld"!==s.name)continue;const t=p(s,"a:t")?.text??"";o+=t,t.trim()&&a.push({text:t,style:ut(p(s,"a:rPr"),r,e,n)})}return{text:o,runs:a}}var yt=(t,e)=>t.sizePt===e.sizePt&&t.bold===e.bold&&t.colour===e.colour;function gt(t,e){const n=[],r=[],a=function(){const t=[];return(e,n)=>"bullet"===e.kind?"• ":"none"===e.kind?(t.length=Math.min(t.length,n),""):(t.length=Math.min(t.length,n+1),t[n]=(t[n]??e.startAt-1)+1,`${t[n]}. `)}();let o;for(const s of f(t,"a:p")){const t=p(s,"a:pPr"),i=Number(t?.attrs.lvl)||0,l=pt(e,i),c=ht(s,l,e),f=dt(t,l),u=c.text.trim()?a(f,i):"";n.push(u?`${" ".repeat(i)}${u}${c.text}`:c.text),c.runs.length&&!o&&(o=mt(t,l)),r.push(...c.runs)}if(!r[0])return null;const s=function(t){const e=[];for(const n of t){const t=e.find(t=>yt(t.style,n.style));t?t.length+=n.text.length:e.push({style:n.style,length:n.text.length})}return e.reduce((t,e)=>e.length>t.length?e:t).style}(r),i=Number(p(p(t,"a:bodyPr"),"a:normAutofit")?.attrs.fontScale);return{text:n.join("\n").trimEnd(),sizePt:s.sizePt*(i>0?i/1e5:1),bold:s.bold,colour:s.colour,align:o??"left",mixed:r.some(t=>!yt(t.style,s)),typefaces:new Set(r.flatMap(t=>t.style.typeface?[t.style.typeface]:[]))}}function wt(t,e){const n=t.map(t=>t.map(e));return n.some(t=>t.some(Boolean))?n:void 0}var xt=t=>t.reduce((t,e)=>t+e,0);function bt(t,e,n,r){const a=E(p(t,"p:xfrm")),s=f(e,"a:tr");if(!a||!s.length)return void(n.tally.skipped+=1);const i=f(p(e,"a:tblGrid"),"a:gridCol").map(t=>Number(t.attrs.w)||0),l=s.map(t=>Number(t.attrs.h)||0),c=s.map(t=>f(t,"a:tc").map(t=>function(t,e){const n=p(t,"a:txBody"),r=gt(n,{palette:e.palette,fonts:e.master?.fonts??{},lists:[p(n,"a:lstStyle"),e.presentation.defaultTextStyle],isTitle:!1});for(const t of r?.typefaces??[])e.tally.typefaces.add(t);return{text:r?.text.replace(/\s*\n\s*/g," ")??"",block:r,fill:O(p(t,"a:tcPr"),e.palette)??null}}(t,n))),u=G({...a,w:xt(i)||a.w,h:xt(l)||a.h},r,n.frame),d=function(t){const e=new Map;for(const{block:n}of t)n&&e.set(n.sizePt,(e.get(n.sizePt)??0)+1);return[...e].sort((t,e)=>e[1]-t[1])[0]?.[0]}(c.flat()),m={...u,type:"table",rows:c.map(t=>t.map(t=>t.text)),headerFill:c[0].map(t=>t.fill).find(Boolean)??o,headerColor:c[0].map(t=>t.block?.colour).find(Boolean),fontSize:void 0===d?void 0:H(d,n.frame),columnWidths:xt(i)?i.map(t=>{return e=t,n=xt(i),Math.round(e/n*1e4)/1e4;var e,n}):void 0,rowHeights:xt(l)?l.map(t=>Math.round(t/xt(l)*u.h*100)/100):void 0,cellFills:wt(c,t=>t.fill),cellColors:wt(c,t=>t.block?.colour??null)};n.elements.push(m)}var vt={rect:"rect",ellipse:"ellipse",roundRect:"roundRect",diamond:"diamond",line:"line",straightConnector1:"line",flowChartProcess:"rect",flowChartAlternateProcess:"roundRect",flowChartDecision:"diamond",flowChartConnector:"ellipse"},Mt=new Set(["a:videoFile","a:audioFile","a:quickTimeFile","p14:media"]);function kt(t,e,n,r){const a=gt(p(t,"p:txBody"),function(t,e,n){const r=p(p(t,"p:style"),"a:fontRef")?.children[0];return{palette:n.palette,fonts:n.master?.fonts??{},lists:it(t,e,n,n.presentation.defaultTextStyle),isTitle:"p:titleStyle"===e.style,styleColour:z(r,n.palette)}}(t,n,r));if(!a)return;const{scale:o}=r.frame,s=(e,r)=>(Number(lt(t,n,e)??r)||0)*o,i=H(a.sizePt,r.frame),c=s("lIns",91440),f=s("tIns",45720),u=Math.max(e.w-c-s("rIns",91440),1),d=Math.max(e.h-f-s("bIns",45720),1),m=lt(t,n,"anchor"),h=Math.max(d-function(t,e,n){const r=Math.max(1,Math.floor(n/(.52*e)));return t.split("\n").reduce((t,e)=>t+Math.max(1,Math.ceil(e.length/r)),0)*e*1.25}(a.text,i,u),0),y="ctr"===m?h/2:"b"===m?h:0;r.elements.push({id:l(),type:"text",rotation:e.rotation,x:D(e.x+c),y:D(e.y+f+y),w:D(u),h:D(d-y),text:a.text,fontSize:i,bold:a.bold,color:a.colour,align:a.align});for(const t of a.typefaces)r.tally.typefaces.add(t);a.mixed&&(r.tally.mixedTextSimplified+=1)}function Pt(t,e){const n=p(t,"p:spPr");if(p(n,"a:noFill"))return{kind:"none"};if(p(n,"a:solidFill")){const t=O(n,e.palette);return t?{kind:"colour",colour:t}:{kind:"none"}}if(["a:gradFill","a:blipFill","a:pattFill","a:grpFill"].some(t=>p(n,t))){const t=function(t,e){const n=p(p(p(t,"a:gradFill"),"a:gsLst"),"a:gs")?.children[0],r=p(p(t,"a:pattFill"),"a:fgClr")?.children[0];return z(n??r,e.palette)}(n,e);return t?{kind:"colour",colour:t}:{kind:"undrawable"}}const r=p(p(t,"p:style"),"a:fillRef"),a=r&&"0"!==r.attrs.idx?z(r.children[0],e.palette):void 0;return a?{kind:"colour",colour:a}:{kind:"none"}}function St(t,e){const n=p(p(t,"p:spPr"),"a:ln");if(p(n,"a:noFill"))return;const r=p(p(t,"p:style"),"a:lnRef"),a=O(n,e.palette)??(r&&"0"!==r.attrs.idx?z(r.children[0],e.palette):void 0);return a?{stroke:a,strokeWidth:D((Number(n?.attrs.w)||9525)*e.frame.scale)}:void 0}function Nt(t,e){const n=p(p(p(t,"a:prstGeom"),"a:avLst"),"a:gd")?.attrs.fmla,r=Number(n?.replace("val ",""));return D((Number.isFinite(r)?r:16667)/1e5*Math.min(e.w,e.h))}var Ct=t=>!!t?.attrs.type&&"none"!==t.attrs.type;function At(t,e,n){const r=p(t,"p:spPr"),a=p(r,"a:xfrm"),s=E(a);if(!s)return void(e.tally.skipped+=1);const i=St(t,e);if(!i)return;const l=p(r,"a:ln");e.elements.push({...U(s,{flipH:R(a?.attrs.flipH),flipV:R(a?.attrs.flipV)},n,e.frame),type:"shape",shape:"line",fill:o,...i,...Ct(p(l,"a:tailEnd"))?{arrowEnd:!0}:{},...Ct(p(l,"a:headEnd"))?{arrowStart:!0}:{}})}function Bt(t,e,n){const r=st(t,e),a=p(t,"p:spPr"),s=function(t){return vt[p(t,"a:prstGeom")?.attrs.prst??"rect"]??"rect"}(a);if("line"===s)return void At(t,e,n);const i=E(p(a,"a:xfrm"))??r.shapes.map(t=>E(p(p(t,"p:spPr"),"a:xfrm"))).find(Boolean);if(!i)return void(p(t,"p:txBody")&&u(t,new Set(["a:t"])).length&&(e.tally.skipped+=1));const l=G(i,n,e.frame),c=Pt(t,e),f=St(t,e),d="colour"===c.kind||!!f;d&&function(t,e,n,r,a,s){s.elements.push({...t,type:"shape",shape:e,fill:"colour"===n.kind?n.colour:o,...r,..."roundRect"===e?{radius:Nt(a,t)}:{}})}(l,s,c,f,a,e),kt(t,l,r,e),"undrawable"!==c.kind||d||(e.tally.skipped+=1)}function It(t,e){const n=e.rels.get(t?.attrs["r:embed"]??"");return n&&!n.external?w(e.part,n.target):void 0}function Ft(t,e,n){const r=p(t,"p:nvPicPr"),a=st(t,e),o=E(p(p(t,"p:spPr"),"a:xfrm"))??a.shapes.map(t=>E(p(p(t,"p:spPr"),"a:xfrm"))).find(Boolean),s=p(t,"p:blipFill"),i=It(p(s,"a:blip"),e.slide),l=i&&!u(t,Mt).length?e.useImage(i,function(t){const e=e=>(Number(t?.attrs[e])||0)/1e5,n={left:e("l"),top:e("t"),right:e("r"),bottom:e("b")},r=Object.values(n);if(!r.every(t=>0===t)&&!r.some(t=>t<0))return n.left+n.right<1&&n.top+n.bottom<1?n:void 0}(p(s,"a:srcRect"))):void 0;o&&l?e.elements.push({...G(o,n,e.frame),type:"image",src:l,alt:p(r,"p:cNvPr")?.attrs.descr??""}):e.tally.skipped+=1}function Tt(t,e,n){const r=p(p(p(t,"a:graphic"),"a:graphicData"),"a:tbl");r?bt(t,r,e,n):e.tally.skipped+=1}function $t(t,e,n=[]){for(const r of t)switch(r.name){case"p:sp":Bt(r,e,n);break;case"p:pic":Ft(r,e,n);break;case"p:graphicFrame":Tt(r,e,n);break;case"p:cxnSp":At(r,e,n);break;case"p:contentPart":e.tally.skipped+=1;break;case"p:grpSp":{const t=V(r);$t(r.children,e,t?[t,...n]:n);break}case"mc:AlternateContent":$t(p(r,"mc:Fallback")?.children??[],e,n)}}function jt(t){const e=function(t){const e=h(t,"[Content_Types].xml"),n=e?m(e):void 0,r=new Map(f(n,"Override").map(t=>[t.attrs.PartName,t.attrs.ContentType])),a=new Map(f(n,"Default").map(t=>[t.attrs.Extension?.toLowerCase(),t.attrs.ContentType]));return t=>{const e=t.slice(t.lastIndexOf(".")+1).toLowerCase();return r.get(`/${t}`)??a.get(e)??K[e]??"application/octet-stream"}}(t),n=new Map;return{use:(t,r)=>{const a=e(t);if(!a.startsWith("image/"))return;const o=`${t}${function(t){return t?`#${t.left},${t.top},${t.right},${t.bottom}`:""}(r)}`;return n.has(o)||n.set(o,{key:o,part:t,contentType:a,crop:r}),o},uses:n}}function zt(t){return t.children.map(t=>"a:br"===t.name?"\n":"a:r"===t.name||"a:fld"===t.name?p(t,"a:t")?.text??"":"").join("")}function Ot(t,e){const n=Q(e,"/notesSlide"),r=n&&Z(t,w(e.part,n.target)),a=((r&&J(r.root)?.children)??[]).find(t=>"body"===p(p(p(t,"p:nvSpPr"),"p:nvPr"),"p:ph")?.attrs.type);return f(p(a,"p:txBody"),"a:p").map(zt).join("\n").trim()}function Rt(t,e){const n=p(p(t.root,"p:cSld"),"p:bg");if(!n)return;const r=p(n,"p:bgPr"),a=O(r,e.palette)??z(p(n,"p:bgRef")?.children[0],e.palette);if(a)return{colour:a};const o=It(p(p(r,"a:blipFill"),"a:blip"),t);return o?{picture:o}:void 0}var Dt=t=>"0"===t.root.attrs.showMasterSp||"false"===t.root.attrs.showMasterSp;function Ht(t,e){const n=function(t){for(const e of[t.slide,t.layout,t.master]){const n=e&&Rt(e,t);if(n)return n}return{}}(t);return n.picture&&function(t,e){const n=e.useImage(t,void 0);if(!n)return void(e.tally.skipped+=1);const{left:r,top:a,width:o,height:s}=e.frame;e.elements.push({id:l(),type:"image",x:r,y:a,w:o,h:s,rotation:0,src:n,alt:""})}(n.picture,t),function(t){const{layout:e,master:n,slide:r}=t;if(!Dt(r))for(const r of[e&&Dt(e)?void 0:n,e]){const e=r?J(r.root)?.children??[]:[];r&&$t(e.filter(t=>!et(t)),{...t,slide:r})}}(t),$t(J(t.slide.root)?.children??[],t),{id:l(),background:n.colour??"#ffffff",notes:Ot(e,t.slide),elements:(r=t.elements,a=t.tally,a.skipped+=Math.max(r.length-200,0),r.slice(0,200))};var r,a}var Lt=t=>"0"===t.root.attrs.show||"false"===t.root.attrs.show;function Et(t){const n=function(t){const n=y(t,"").find(t=>t.type.endsWith("/officeDocument")),r=Z(t,n?w("",n.target):"ppt/presentation.xml");if(!r||"p:presentation"!==r.root.name)throw new e;const a=f(p(r.root,"p:sldIdLst"),"p:sldId").flatMap(t=>{const e=r.rels.get(t.attrs["r:id"]);return e?[w(r.part,e.target)]:[]}),o=p(r.root,"p:sldSz")?.attrs;return{width:Number(o?.cx)||9144e3,height:Number(o?.cy)||5143500,slides:a,defaultTextStyle:p(r.root,"p:defaultTextStyle")}}(t),r=function(t){const e=new Map,n=new Map;return r=>{const a=Q(r,"/slideLayout"),o=a&&w(r.part,a.target);o&&!n.has(o)&&n.set(o,_(t,o,e));const s=o?n.get(o):void 0,i=s?.master,l=i?.palette??q;return{slide:r,layout:s,master:i,palette:B(s?B(l,s.root):l,r.root)}}}(t),a=jt(t),o=function(t,e){const n=Math.min(i/t,s/e);return{scale:n,left:(i-t*n)/2,top:(s-e*n)/2,width:t*n,height:e*n}}(n.width,n.height),l={skipped:0,mixedTextSimplified:0,typefaces:new Set},u=[];let d=0;for(const e of n.slides){const s=Z(t,e);s&&!Lt(s)&&(p(s.root,"p:timing")&&(d+=1),u.push(Ht({...r(s),presentation:n,frame:o,tally:l,elements:[],useImage:a.use},t)))}const m=new Set(u.flatMap(t=>t.elements.flatMap(t=>"image"===t.type?[t.src]:[])));return{document:{slides:u.length?u:[c()]},slideCount:u.length,images:[...a.uses.values()].filter(t=>m.has(t.key)),animationsDropped:d,tally:l}}var Vt=.15,Xt=1048576,Wt=/\.(xml|rels)$/i;async function Yt(n,a){if(await async function(t){const e=new Uint8Array(await t.slice(0,v.length).arrayBuffer());return v.every((t,n)=>e[n]===t)}(n))throw await async function(t,e){for(let n=0;n<t.size;n+=k-M.length)if(e?.throwIfAborted(),P(new Uint8Array(await t.slice(n,n+k).arrayBuffer())))return!0;return!1}(n,a)?new t:new e(r.pptxLegacyFormat)}function Gt(t){if(t.slides.length>300)throw new e(r.pptxTooManySlides(t.slides.length,300));const n=b(t);if(n>x)throw new e(r.pptxTooLarge((n/Xt).toFixed(1),2))}var Ut={"image/webp":"webp","image/png":"png","image/jpeg":"jpg","image/gif":"gif"};async function qt(t,e,n){try{return await(n.prepareImage?n.prepareImage(e,t.contentType):async function(t,e,n){const r=await createImageBitmap(new Blob([t],{type:e}));try{const t=r.width*(n?.left??0),e=r.height*(n?.top??0),a=r.width-t-r.width*(n?.right??0),o=r.height-e-r.height*(n?.bottom??0),s=Math.min(1,1920/Math.max(a,o)),i=new OffscreenCanvas(Math.max(1,Math.round(a*s)),Math.max(1,Math.round(o*s))),l=i.getContext("2d");if(!l)throw new Error("No drawing context");return l.imageSmoothingQuality="high",l.drawImage(r,t,e,a,o,0,0,i.width,i.height),await i.convertToBlob({type:"image/webp",quality:.85})}finally{r.close()}}(e,t.contentType,t.crop))}catch(e){return n.signal?.throwIfAborted(),console.warn("A picture in the deck could not be read",t.part,e),null}}async function Qt(t,e,n){const r={addresses:new Map,count:0,bytesBefore:0,bytesAfter:0},a=function(t,e){const n=new Map;for(const r of t){const t=e.prepareImage?r.part:r.key;n.set(t,[...n.get(t)??[],r])}return[...n.values()]}(t,n),o=new Map;let s=0;return await async function(t,e,n){let r=0,a=!1;await Promise.all(Array.from({length:Math.min(e,t.length)},async()=>{for(;!a&&r<t.length;){const e=t[r];r+=1;try{await n(e)}catch(t){throw a=!0,t}}}))}(a,4,async t=>{n.signal?.throwIfAborted();const[i]=t,l=o.get(i.part)??0;o.set(i.part,l+1);const c=await e.read(i.part).catch(()=>null),p=c&&await qt(i,c,n);if(c&&p){n.signal?.throwIfAborted();const e=await n.storeImage(p,function(t,e,n){return`${t.slice(t.lastIndexOf("/")+1).replace(/\.[^.]*$/,"")}${n?`-${n}`:""}.${Ut[e.type]??"img"}`}(i.part,p,l));for(const{key:n}of t)r.addresses.set(n,e);r.count+=1,r.bytesBefore+=c.length,r.bytesAfter+=p.size}s+=1,n.onProgress?.(Vt+.85*s/a.length)}),r}async function Jt(t,r){r.signal?.throwIfAborted(),await Yt(t,r.signal);const a=await async function(t){try{return await d(t)}catch{throw new e}}(t),o=await async function(t,e){const n=new Map,r=t.names.filter(t=>Wt.test(t));for(const[a,o]of r.entries())e.signal?.throwIfAborted(),n.set(o,await t.read(o)),e.onProgress?.(Vt*(a+1)/r.length);return n}(a,r).catch(t=>{throw r.signal?.throwIfAborted(),t instanceof e?t:new e}),s=function(t){try{return Et(t)}catch(t){if(t instanceof e)throw t;throw new e}}(o);Gt(s.document);const i=await Qt(s.images,a,r),l=function(t,e,n){const r=t=>{if("image"!==t.type)return[t];const r=e.get(t.src);return void 0===r&&(n.skipped+=1),void 0===r?[]:[{...t,src:r}]};return{slides:t.slides.map(t=>({...t,elements:t.elements.flatMap(r)}))}}(s.document,i.addresses,s.tally);return Gt(l),r.onProgress?.(1),{document:l,notes:{slides:s.slideCount,images:i.count,imageBytesBefore:i.bytesBefore,imageBytesAfter:i.bytesAfter,fontsReplaced:[...s.tally.typefaces].filter(t=>t!==n).sort(),animationsDropped:s.animationsDropped,mixedTextSimplified:s.tally.mixedTextSimplified,skipped:s.tally.skipped}}}export{Jt as importPptx};
1
+ import{PptxPasswordError as t,PptxUnreadableError as e}from"./chunk-MDG2ADZ7.js";import{DECK_FONT as n,ENGLISH_WORDS as r,MIN_SIZE as a,NO_FILL as o,SLIDE_H as s,SLIDE_W as i,newId as l,newSlide as c}from"./chunk-PXOQN7D6.js";import"./chunk-B32ASXHM.js";import{child as p,childrenOf as f,descendants as u,openZip as d,parseXml as m,partText as h,readRels as y,readThemeFonts as g,resolveTarget as w}from"./chunk-D3JKD7KW.js";var x=2097152;function b(t){if(Array.isArray(t))return t.reduce((t,e)=>t+b(e)+2,t.length?0:2);if(t&&"object"==typeof t){const e=Object.entries(t).filter(([,t])=>void 0!==t);return e.reduce((t,[e,n])=>t+b(e)+2+b(n)+2,e.length?0:2)}const e=JSON.stringify(t)??"null";return e.length+5*(e.match(/[^\x20-\x7e]/g)?.length??0)}var v=[208,207,17,224],M=Array.from("EncryptedPackage").flatMap(t=>[t.charCodeAt(0),0]),k=4194304;function P(t){for(let e=t.indexOf(M[0]);e>=0;e=t.indexOf(M[0],e+1))if(M.every((n,r)=>t[e+r]===n))return!0;return!1}var S={black:"000000",white:"ffffff",red:"ff0000",green:"008000",blue:"0000ff",yellow:"ffff00",gray:"808080",grey:"808080"},N={bg1:"lt1",tx1:"dk1",bg2:"lt2",tx2:"dk2"};function C(t){const e=t.children[0];return e?.attrs.lastClr??e?.attrs.val}function A(t,e){const n=new Map,r=p(p(t,"a:themeElements"),"a:clrScheme")?.children??[];for(const t of r){const e=C(t);e&&n.set(t.name.replace(/^a:/,""),e)}return{scheme:n,map:{...N,...e?.attrs}}}function B(t,e){const n=p(p(e,"p:clrMapOvr"),"a:overrideClrMapping");return n?{...t,map:{...t.map,...n.attrs}}:t}var I=t=>[0,2,4].map(e=>parseInt(t.slice(e,e+2),16)),F=t=>t.map(t=>{return(e=t,Math.max(0,Math.min(255,Math.round(e)))).toString(16).padStart(2,"0");var e}).join("");function T(t,e,n){const[r,a,o]=function([t,e,n]){const[r,a,o]=[t/255,e/255,n/255],s=Math.max(r,a,o),i=Math.min(r,a,o),l=(s+i)/2;if(s===i)return[0,0,l];const c=s-i;return[(s===r?(a-o)/c+(a<o?6:0):s===a?(o-r)/c+2:(r-a)/c+4)/6,l>.5?c/(2-s-i):c/(s+i),l]}(I(t));return F(function([t,e,n]){if(0===e)return[255*n,255*n,255*n];const r=n<.5?n*(1+e):n+e-n*e,a=2*n-r,o=t=>{const e=(t+1)%1;return e<1/6?a+6*(r-a)*e:e<.5?r:e<2/3?a+(r-a)*(2/3-e)*6:a};return[o(t+1/3),o(t),o(t-1/3)].map(t=>255*t)}([r,a,Math.max(0,Math.min(1,o*e+n))]))}function $(t,e){const n=Number(e.attrs.val)/1e5;if(!Number.isFinite(n))return t;switch(e.name){case"a:lumMod":return T(t,n,0);case"a:lumOff":return T(t,1,n);case"a:tint":return F(I(t).map(t=>t+(255-t)*(1-n)));case"a:shade":return F(I(t).map(t=>t*n));default:return t}}function j(t,e){const n=e.scheme.get(e.map[t]??t);return n?`#${n.toLowerCase()}`:void 0}function z(t,e){const n=t&&function(t,e){switch(t.name){case"a:srgbClr":return t.attrs.val;case"a:sysClr":return t.attrs.lastClr;case"a:prstClr":return S[t.attrs.val];case"a:schemeClr":return e.scheme.get(e.map[t.attrs.val]??t.attrs.val);default:return}}(t,e);if(t&&n&&/^[0-9a-f]{6}$/i.test(n)&&"0"!==p(t,"a:alpha")?.attrs.val)return`#${t.children.reduce($,n).toLowerCase()}`}function O(t,e){return z(p(t,"a:solidFill")?.children[0],e)}var D=t=>"1"===t||"true"===t,R=t=>Math.round(100*t)/100+0,L=(t,e)=>R(12700*t*e.scale),E=t=>t*Math.PI/180;function H(t){const e=p(t,"a:off")?.attrs,n=p(t,"a:ext")?.attrs;if(t&&e&&n)return{x:Number(e.x)||0,y:Number(e.y)||0,w:Number(n.cx)||0,h:Number(n.cy)||0,rotation:(Number(t.attrs.rot)||0)/6e4}}function V(t){const e=p(p(t,"p:grpSpPr"),"a:xfrm"),n=H(e),r=p(e,"a:chOff")?.attrs,a=p(e,"a:chExt")?.attrs;if(n&&r&&a)return{box:n,childX:Number(r.x)||0,childY:Number(r.y)||0,scaleX:Number(a.cx)?n.w/Number(a.cx):1,scaleY:Number(a.cy)?n.h/Number(a.cy):1,flipH:D(e?.attrs.flipH),flipV:D(e?.attrs.flipV)}}function X(t,e){const{box:n}=e,r=n.x+n.w/2,a=n.y+n.h/2;let o=n.x+(t.x-e.childX)*e.scaleX,s=n.y+(t.y-e.childY)*e.scaleY;e.flipH&&(o=2*r-o),e.flipV&&(s=2*a-s);const i=E(n.rotation),l=o-r,c=s-a;return{x:r+l*Math.cos(i)-c*Math.sin(i),y:a+l*Math.sin(i)+c*Math.cos(i)}}function W(t,e){const n=X({x:t.x+t.w/2,y:t.y+t.h/2},e),r=t.w*e.scaleX,a=t.h*e.scaleY,o=e.flipH!==e.flipV;return{x:n.x-r/2,y:n.y-a/2,w:r,h:a,rotation:(o?-t.rotation:t.rotation)+e.box.rotation}}var Y=t=>R((t%360+360)%360);function G(t,e,n){const r=e.reduce(W,t);return{id:l(),x:R(n.left+r.x*n.scale),y:R(n.top+r.y*n.scale),w:R(r.w*n.scale),h:R(r.h*n.scale),rotation:Y(r.rotation)}}function q(t,e,n,r){const o=t.x+t.w/2,s=t.y+t.h/2,i=E(t.rotation),c=a=>{const l=a*(e.flipH?-1:1)*t.w/2,c=a*(e.flipV?-1:1)*t.h/2,p={x:o+l*Math.cos(i)-c*Math.sin(i),y:s+l*Math.sin(i)+c*Math.cos(i)},f=n.reduce(X,p);return{x:r.left+f.x*r.scale,y:r.top+f.y*r.scale}},p=c(-1),f=c(1),u=Math.hypot(f.x-p.x,f.y-p.y);return{id:l(),x:R((p.x+f.x-u)/2),y:R((p.y+f.y-a)/2),w:R(u),h:a,rotation:Y(180*Math.atan2(f.y-p.y,f.x-p.x)/Math.PI)}}var J={scheme:new Map,map:{}},K=(t,e)=>[...t.rels.values()].find(t=>t.type.endsWith(e)),Q=t=>p(p(t,"p:cSld"),"p:spTree");function U(t,e){const n=h(t,e);if(n)return{part:e,root:m(n),rels:new Map(y(t,e).map(t=>[t.id,t]))}}function Z(t,e,n){const r=U(t,e);if(!r)return;const a=K(r,"/slideMaster"),o=a&&w(e,a.target);return o&&!n.has(o)&&n.set(o,function(t,e){const n=U(t,e);if(!n)return;const r=K(n,"/theme"),a=r?h(t,w(e,r.target)):void 0;return{...n,palette:A(a?m(a):void 0,p(n.root,"p:clrMap")),fonts:g(a)}}(t,o)),{...r,master:o?n.get(o):void 0}}var _={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",bmp:"image/bmp"};var tt=t=>p(p(p(t,"p:nvSpPr"),"p:nvPr"),"p:ph")??p(p(p(t,"p:nvPicPr"),"p:nvPr"),"p:ph"),et=t=>!!tt(t),nt=t=>(Q(t.root)?.children??[]).filter(t=>"p:sp"===t.name&&tt(t)),rt=new Set(["title","ctrTitle"]),at=new Set(["dt","ftr","sldNum"]);function ot(t){return t&&rt.has(t)?"title":t&&at.has(t)?t:"body"}function st(t,e){const n=tt(t);if(!n)return{shapes:[],style:"p:otherStyle",isPlaceholder:!1};const r=e.layout&&function(t,e){const n=nt(t),{idx:r,type:a}=e.attrs;return(void 0!==r?n.find(t=>tt(t)?.attrs.idx===r):void 0)??(void 0!==a?n.find(t=>tt(t)?.attrs.type===a):void 0)}(e.layout,n),a=r?tt(r)??n:n,o=e.master&&function(t,e){const n=ot(e.attrs.type);return nt(t).find(t=>ot(tt(t)?.attrs.type)===n)}(e.master,a),s=ot(a.attrs.type);return{shapes:[r,o].filter(t=>!!t),style:"title"===s?"p:titleStyle":"body"===s?"p:bodyStyle":"p:otherStyle",isPlaceholder:!0}}function it(t,e,n,r){const a=t=>p(p(t,"p:txBody"),"a:lstStyle"),o=p(p(n.master?.root,"p:txStyles"),e.style),s=e.isPlaceholder?[o,r]:[r,o];return[a(t),...e.shapes.map(a),...s]}function lt(t,e,n){for(const r of[t,...e.shapes]){const t=p(p(r,"p:txBody"),"a:bodyPr")?.attrs[n];if(void 0!==t)return t}}var ct={l:"left",ctr:"center",r:"right"},pt=(t,e)=>t.lists.flatMap(t=>{const n=p(t,`a:lvl${e+1}pPr`);return n?[n]:[]});function ft(t,e){return"+mj-lt"===t?e.fonts.major:"+mn-lt"===t?e.fonts.minor:t}function ut(t,e,n,r){const a=[t,p(e,"a:defRPr"),...n.map(t=>p(t,"a:defRPr"))].filter(t=>!!t),o=t=>a.find(e=>void 0!==e.attrs[t])?.attrs[t],s=Number(o("sz")),i=o("b"),l=a.map(t=>O(t,r.palette)),c=a.map(t=>p(t,"a:latin")?.attrs.typeface).find(Boolean);return{sizePt:Number.isFinite(s)&&s>0?s/100:18,bold:"1"===i||"true"===i,colour:l.find(Boolean)??r.styleColour??j("tx1",r.palette)??"#000000",typeface:ft(c,r)??(r.isTitle?r.fonts.major:r.fonts.minor)}}function dt(t,e){for(const n of[t,...e]){if(p(n,"a:buNone"))return{kind:"none"};if(p(n,"a:buChar")||p(n,"a:buBlip"))return{kind:"bullet"};const t=p(n,"a:buAutoNum");if(t)return{kind:"number",startAt:Number(t.attrs.startAt)||1}}return{kind:"none"}}function mt(t,e){const n=[t,...e].map(t=>t?.attrs.algn).find(Boolean);return n&&ct[n]||"left"}function ht(t,e,n){const r=p(t,"a:pPr"),a=[];let o="";for(const s of t.children){if("a:br"===s.name&&(o+="\n"),"a:r"!==s.name&&"a:fld"!==s.name)continue;const t=p(s,"a:t")?.text??"";o+=t,t.trim()&&a.push({text:t,style:ut(p(s,"a:rPr"),r,e,n)})}return{text:o,runs:a}}var yt=(t,e)=>t.sizePt===e.sizePt&&t.bold===e.bold&&t.colour===e.colour;function gt(t,e){const n=[],r=[],a=function(){const t=[];return(e,n)=>"bullet"===e.kind?"• ":"none"===e.kind?(t.length=Math.min(t.length,n),""):(t.length=Math.min(t.length,n+1),t[n]=(t[n]??e.startAt-1)+1,`${t[n]}. `)}();let o;for(const s of f(t,"a:p")){const t=p(s,"a:pPr"),i=Number(t?.attrs.lvl)||0,l=pt(e,i),c=ht(s,l,e),f=dt(t,l),u=c.text.trim()?a(f,i):"";n.push(u?`${" ".repeat(i)}${u}${c.text}`:c.text),c.runs.length&&!o&&(o=mt(t,l)),r.push(...c.runs)}if(!r[0])return null;const s=function(t){const e=[];for(const n of t){const t=e.find(t=>yt(t.style,n.style));t?t.length+=n.text.length:e.push({style:n.style,length:n.text.length})}return e.reduce((t,e)=>e.length>t.length?e:t).style}(r),i=Number(p(p(t,"a:bodyPr"),"a:normAutofit")?.attrs.fontScale);return{text:n.join("\n").trimEnd(),sizePt:s.sizePt*(i>0?i/1e5:1),bold:s.bold,colour:s.colour,align:o??"left",mixed:r.some(t=>!yt(t.style,s)),typefaces:new Set(r.flatMap(t=>t.style.typeface?[t.style.typeface]:[]))}}function wt(t,e){const n=t.map(t=>t.map(e));return n.some(t=>t.some(Boolean))?n:void 0}var xt=t=>t.reduce((t,e)=>t+e,0);function bt(t,e,n,r){const a=H(p(t,"p:xfrm")),s=f(e,"a:tr");if(!a||!s.length)return void(n.tally.skipped+=1);const i=f(p(e,"a:tblGrid"),"a:gridCol").map(t=>Number(t.attrs.w)||0),l=s.map(t=>Number(t.attrs.h)||0),c=s.map(t=>f(t,"a:tc").map(t=>function(t,e){const n=p(t,"a:txBody"),r=gt(n,{palette:e.palette,fonts:e.master?.fonts??{},lists:[p(n,"a:lstStyle"),e.presentation.defaultTextStyle],isTitle:!1});for(const t of r?.typefaces??[])e.tally.typefaces.add(t);return{text:r?.text.replace(/\s*\n\s*/g," ")??"",block:r,fill:O(p(t,"a:tcPr"),e.palette)??null}}(t,n))),u=G({...a,w:xt(i)||a.w,h:xt(l)||a.h},r,n.frame),d=function(t){const e=new Map;for(const{block:n}of t)n&&e.set(n.sizePt,(e.get(n.sizePt)??0)+1);return[...e].sort((t,e)=>e[1]-t[1])[0]?.[0]}(c.flat()),m={...u,type:"table",rows:c.map(t=>t.map(t=>t.text)),headerFill:c[0].map(t=>t.fill).find(Boolean)??o,headerColor:c[0].map(t=>t.block?.colour).find(Boolean),fontSize:void 0===d?void 0:L(d,n.frame),columnWidths:xt(i)?i.map(t=>{return e=t,n=xt(i),Math.round(e/n*1e4)/1e4;var e,n}):void 0,rowHeights:xt(l)?l.map(t=>Math.round(t/xt(l)*u.h*100)/100):void 0,cellFills:wt(c,t=>t.fill),cellColors:wt(c,t=>t.block?.colour??null)};n.elements.push(m)}var vt={rect:"rect",ellipse:"ellipse",roundRect:"roundRect",diamond:"diamond",line:"line",straightConnector1:"line",flowChartProcess:"rect",flowChartAlternateProcess:"roundRect",flowChartDecision:"diamond",flowChartConnector:"ellipse"},Mt=new Set(["a:videoFile","a:audioFile","a:quickTimeFile","p14:media"]);function kt(t,e,n,r){const a=gt(p(t,"p:txBody"),function(t,e,n){const r=p(p(t,"p:style"),"a:fontRef")?.children[0];return{palette:n.palette,fonts:n.master?.fonts??{},lists:it(t,e,n,n.presentation.defaultTextStyle),isTitle:"p:titleStyle"===e.style,styleColour:z(r,n.palette)}}(t,n,r));if(!a)return;const{scale:o}=r.frame,s=(e,r)=>(Number(lt(t,n,e)??r)||0)*o,i=L(a.sizePt,r.frame),c=s("lIns",91440),f=s("tIns",45720),u=Math.max(e.w-c-s("rIns",91440),1),d=Math.max(e.h-f-s("bIns",45720),1),m=lt(t,n,"anchor"),h=Math.max(d-function(t,e,n){const r=Math.max(1,Math.floor(n/(.52*e)));return t.split("\n").reduce((t,e)=>t+Math.max(1,Math.ceil(e.length/r)),0)*e*1.25}(a.text,i,u),0),y="ctr"===m?h/2:"b"===m?h:0;r.elements.push({id:l(),type:"text",rotation:e.rotation,x:R(e.x+c),y:R(e.y+f+y),w:R(u),h:R(d-y),text:a.text,fontSize:i,bold:a.bold,color:a.colour,align:a.align});for(const t of a.typefaces)r.tally.typefaces.add(t);a.mixed&&(r.tally.mixedTextSimplified+=1)}function Pt(t,e){const n=p(t,"p:spPr");if(p(n,"a:noFill"))return{kind:"none"};if(p(n,"a:solidFill")){const t=O(n,e.palette);return t?{kind:"colour",colour:t}:{kind:"none"}}if(["a:gradFill","a:blipFill","a:pattFill","a:grpFill"].some(t=>p(n,t))){const t=function(t,e){const n=p(p(p(t,"a:gradFill"),"a:gsLst"),"a:gs")?.children[0],r=p(p(t,"a:pattFill"),"a:fgClr")?.children[0];return z(n??r,e.palette)}(n,e);return t?{kind:"colour",colour:t}:{kind:"undrawable"}}const r=p(p(t,"p:style"),"a:fillRef"),a=r&&"0"!==r.attrs.idx?z(r.children[0],e.palette):void 0;return a?{kind:"colour",colour:a}:{kind:"none"}}function St(t,e){const n=p(p(t,"p:spPr"),"a:ln");if(p(n,"a:noFill"))return;const r=p(p(t,"p:style"),"a:lnRef"),a=O(n,e.palette)??(r&&"0"!==r.attrs.idx?z(r.children[0],e.palette):void 0);return a?{stroke:a,strokeWidth:R((Number(n?.attrs.w)||9525)*e.frame.scale)}:void 0}function Nt(t,e){const n=p(p(p(t,"a:prstGeom"),"a:avLst"),"a:gd")?.attrs.fmla,r=Number(n?.replace("val ",""));return R((Number.isFinite(r)?r:16667)/1e5*Math.min(e.w,e.h))}var Ct=t=>!!t?.attrs.type&&"none"!==t.attrs.type;function At(t,e,n){const r=p(t,"p:spPr"),a=p(r,"a:xfrm"),s=H(a);if(!s)return void(e.tally.skipped+=1);const i=St(t,e);if(!i)return;const l=p(r,"a:ln");e.elements.push({...q(s,{flipH:D(a?.attrs.flipH),flipV:D(a?.attrs.flipV)},n,e.frame),type:"shape",shape:"line",fill:o,...i,...Ct(p(l,"a:tailEnd"))?{arrowEnd:!0}:{},...Ct(p(l,"a:headEnd"))?{arrowStart:!0}:{}})}function Bt(t,e,n){const r=st(t,e),a=p(t,"p:spPr"),s=function(t){return vt[p(t,"a:prstGeom")?.attrs.prst??"rect"]??"rect"}(a);if("line"===s)return void At(t,e,n);const i=H(p(a,"a:xfrm"))??r.shapes.map(t=>H(p(p(t,"p:spPr"),"a:xfrm"))).find(Boolean);if(!i)return void(p(t,"p:txBody")&&u(t,new Set(["a:t"])).length&&(e.tally.skipped+=1));const l=G(i,n,e.frame),c=Pt(t,e),f=St(t,e),d="colour"===c.kind||!!f;d&&function(t,e,n,r,a,s){s.elements.push({...t,type:"shape",shape:e,fill:"colour"===n.kind?n.colour:o,...r,..."roundRect"===e?{radius:Nt(a,t)}:{}})}(l,s,c,f,a,e),kt(t,l,r,e),"undrawable"!==c.kind||d||(e.tally.skipped+=1)}function It(t,e){const n=e.rels.get(t?.attrs["r:embed"]??"");return n&&!n.external?w(e.part,n.target):void 0}function Ft(t,e,n){const r=p(t,"p:nvPicPr"),a=st(t,e),o=H(p(p(t,"p:spPr"),"a:xfrm"))??a.shapes.map(t=>H(p(p(t,"p:spPr"),"a:xfrm"))).find(Boolean),s=p(t,"p:blipFill"),i=It(p(s,"a:blip"),e.slide),l=i&&!u(t,Mt).length?e.useImage(i,function(t){const e=e=>(Number(t?.attrs[e])||0)/1e5,n={left:e("l"),top:e("t"),right:e("r"),bottom:e("b")},r=Object.values(n);if(!r.every(t=>0===t)&&!r.some(t=>t<0))return n.left+n.right<1&&n.top+n.bottom<1?n:void 0}(p(s,"a:srcRect"))):void 0;o&&l?e.elements.push({...G(o,n,e.frame),type:"image",src:l,alt:p(r,"p:cNvPr")?.attrs.descr??""}):e.tally.skipped+=1}function Tt(t,e,n){const r=p(p(p(t,"a:graphic"),"a:graphicData"),"a:tbl");r?bt(t,r,e,n):e.tally.skipped+=1}function $t(t,e,n=[]){for(const r of t)switch(r.name){case"p:sp":Bt(r,e,n);break;case"p:pic":Ft(r,e,n);break;case"p:graphicFrame":Tt(r,e,n);break;case"p:cxnSp":At(r,e,n);break;case"p:contentPart":e.tally.skipped+=1;break;case"p:grpSp":{const t=V(r);$t(r.children,e,t?[t,...n]:n);break}case"mc:AlternateContent":$t(p(r,"mc:Fallback")?.children??[],e,n)}}function jt(t){const e=function(t){const e=h(t,"[Content_Types].xml"),n=e?m(e):void 0,r=new Map(f(n,"Override").map(t=>[t.attrs.PartName,t.attrs.ContentType])),a=new Map(f(n,"Default").map(t=>[t.attrs.Extension?.toLowerCase(),t.attrs.ContentType]));return t=>{const e=t.slice(t.lastIndexOf(".")+1).toLowerCase();return r.get(`/${t}`)??a.get(e)??_[e]??"application/octet-stream"}}(t),n=new Map;return{use:(t,r)=>{const a=e(t);if(!a.startsWith("image/"))return;const o=`${t}${function(t){return t?`#${t.left},${t.top},${t.right},${t.bottom}`:""}(r)}`;return n.has(o)||n.set(o,{key:o,part:t,contentType:a,crop:r}),o},uses:n}}function zt(t){return t.children.map(t=>"a:br"===t.name?"\n":"a:r"===t.name||"a:fld"===t.name?p(t,"a:t")?.text??"":"").join("")}function Ot(t,e){const n=K(e,"/notesSlide"),r=n&&U(t,w(e.part,n.target)),a=((r&&Q(r.root)?.children)??[]).find(t=>"body"===p(p(p(t,"p:nvSpPr"),"p:nvPr"),"p:ph")?.attrs.type);return f(p(a,"p:txBody"),"a:p").map(zt).join("\n").trim()}function Dt(t,e){const n=p(p(t.root,"p:cSld"),"p:bg");if(!n)return;const r=p(n,"p:bgPr"),a=O(r,e.palette)??z(p(n,"p:bgRef")?.children[0],e.palette);if(a)return{colour:a};const o=It(p(p(r,"a:blipFill"),"a:blip"),t);return o?{picture:o}:void 0}var Rt=t=>"0"===t.root.attrs.showMasterSp||"false"===t.root.attrs.showMasterSp;function Lt(t,e){const n=function(t){for(const e of[t.slide,t.layout,t.master]){const n=e&&Dt(e,t);if(n)return n}return{}}(t);return n.picture&&function(t,e){const n=e.useImage(t,void 0);if(!n)return void(e.tally.skipped+=1);const{left:r,top:a,width:o,height:s}=e.frame;e.elements.push({id:l(),type:"image",x:r,y:a,w:o,h:s,rotation:0,src:n,alt:""})}(n.picture,t),function(t){const{layout:e,master:n,slide:r}=t;if(!Rt(r))for(const r of[e&&Rt(e)?void 0:n,e]){const e=r?Q(r.root)?.children??[]:[];r&&$t(e.filter(t=>!et(t)),{...t,slide:r})}}(t),$t(Q(t.slide.root)?.children??[],t),{id:l(),background:n.colour??"#ffffff",notes:Ot(e,t.slide),elements:(r=t.elements,a=t.tally,a.skipped+=Math.max(r.length-200,0),r.slice(0,200))};var r,a}var Et=t=>"0"===t.root.attrs.show||"false"===t.root.attrs.show;function Ht(t){const n=function(t){const n=y(t,"").find(t=>t.type.endsWith("/officeDocument")),r=U(t,n?w("",n.target):"ppt/presentation.xml");if(!r||"p:presentation"!==r.root.name)throw new e;const a=f(p(r.root,"p:sldIdLst"),"p:sldId").flatMap(t=>{const e=r.rels.get(t.attrs["r:id"]);return e?[w(r.part,e.target)]:[]}),o=p(r.root,"p:sldSz")?.attrs;return{width:Number(o?.cx)||9144e3,height:Number(o?.cy)||5143500,slides:a,defaultTextStyle:p(r.root,"p:defaultTextStyle")}}(t),r=function(t){const e=new Map,n=new Map;return r=>{const a=K(r,"/slideLayout"),o=a&&w(r.part,a.target);o&&!n.has(o)&&n.set(o,Z(t,o,e));const s=o?n.get(o):void 0,i=s?.master,l=i?.palette??J;return{slide:r,layout:s,master:i,palette:B(s?B(l,s.root):l,r.root)}}}(t),a=jt(t),o=function(t,e){const n=Math.min(i/t,s/e);return{scale:n,left:(i-t*n)/2,top:(s-e*n)/2,width:t*n,height:e*n}}(n.width,n.height),l={skipped:0,mixedTextSimplified:0,typefaces:new Set},u=[];let d=0;for(const e of n.slides){const s=U(t,e);s&&!Et(s)&&(p(s.root,"p:timing")&&(d+=1),u.push(Lt({...r(s),presentation:n,frame:o,tally:l,elements:[],useImage:a.use},t)))}const m=new Set(u.flatMap(t=>t.elements.flatMap(t=>"image"===t.type?[t.src]:[])));return{document:{slides:u.length?u:[c()]},slideCount:u.length,images:[...a.uses.values()].filter(t=>m.has(t.key)),animationsDropped:d,tally:l}}var Vt=.15,Xt=1048576,Wt=/\.(xml|rels)$/i;async function Yt(n,a){if(await async function(t){const e=new Uint8Array(await t.slice(0,v.length).arrayBuffer());return v.every((t,n)=>e[n]===t)}(n))throw await async function(t,e){for(let n=0;n<t.size;n+=k-M.length)if(e?.throwIfAborted(),P(new Uint8Array(await t.slice(n,n+k).arrayBuffer())))return!0;return!1}(n,a)?new t:new e(r.pptxLegacyFormat)}function Gt(t){if(t.slides.length>300)throw new e(r.pptxTooManySlides(t.slides.length,300));const n=b(t);if(n>x)throw new e(r.pptxTooLarge((n/Xt).toFixed(1),2))}var qt={"image/webp":"webp","image/png":"png","image/jpeg":"jpg","image/gif":"gif"};async function Jt(t,e,n){try{return await(n.prepareImage?n.prepareImage(e,t.contentType):async function(t,e,n){const r=await createImageBitmap(new Blob([t],{type:e}));try{const t=r.width*(n?.left??0),e=r.height*(n?.top??0),a=r.width-t-r.width*(n?.right??0),o=r.height-e-r.height*(n?.bottom??0),s=Math.min(1,1920/Math.max(a,o)),i=new OffscreenCanvas(Math.max(1,Math.round(a*s)),Math.max(1,Math.round(o*s))),l=i.getContext("2d");if(!l)throw new Error("No drawing context");return l.imageSmoothingQuality="high",l.drawImage(r,t,e,a,o,0,0,i.width,i.height),await i.convertToBlob({type:"image/webp",quality:.85})}finally{r.close()}}(e,t.contentType,t.crop))}catch(e){return n.signal?.throwIfAborted(),console.warn("A picture in the deck could not be read",t.part,e),null}}async function Kt(t,e,n){const r={addresses:new Map,count:0,bytesBefore:0,bytesAfter:0},a=function(t,e){const n=new Map;for(const r of t){const t=e.prepareImage?r.part:r.key;n.set(t,[...n.get(t)??[],r])}return[...n.values()]}(t,n),o=new Map;let s=0;return await async function(t,e,n){let r=0,a=!1;await Promise.all(Array.from({length:Math.min(e,t.length)},async()=>{for(;!a&&r<t.length;){const e=t[r];r+=1;try{await n(e)}catch(t){throw a=!0,t}}}))}(a,4,async t=>{n.signal?.throwIfAborted();const[i]=t,l=o.get(i.part)??0;o.set(i.part,l+1);const c=await e.read(i.part).catch(()=>null),p=c&&await Jt(i,c,n);if(c&&p){n.signal?.throwIfAborted();const e=await n.storeImage(p,function(t,e,n){return`${t.slice(t.lastIndexOf("/")+1).replace(/\.[^.]*$/,"")}${n?`-${n}`:""}.${qt[e.type]??"img"}`}(i.part,p,l));for(const{key:n}of t)r.addresses.set(n,e);r.count+=1,r.bytesBefore+=c.length,r.bytesAfter+=p.size}s+=1,n.onProgress?.(Vt+.85*s/a.length)}),r}async function Qt(t,r){r.signal?.throwIfAborted(),await Yt(t,r.signal);const a=await async function(t){try{return await d(t)}catch{throw new e}}(t),o=await async function(t,e){const n=new Map,r=t.names.filter(t=>Wt.test(t));for(const[a,o]of r.entries())e.signal?.throwIfAborted(),n.set(o,await t.read(o)),e.onProgress?.(Vt*(a+1)/r.length);return n}(a,r).catch(t=>{throw r.signal?.throwIfAborted(),t instanceof e?t:new e}),s=function(t){try{return Ht(t)}catch(t){if(t instanceof e)throw t;throw new e}}(o);Gt(s.document);const i=await Kt(s.images,a,r),l=function(t,e,n){const r=t=>{if("image"!==t.type)return[t];const r=e.get(t.src);return void 0===r&&(n.skipped+=1),void 0===r?[]:[{...t,src:r}]};return{slides:t.slides.map(t=>({...t,elements:t.elements.flatMap(r)}))}}(s.document,i.addresses,s.tally);return Gt(l),r.onProgress?.(1),{document:l,notes:{slides:s.slideCount,images:i.count,imageBytesBefore:i.bytesBefore,imageBytesAfter:i.bytesAfter,fontsReplaced:[...s.tally.typefaces].filter(t=>t!==n).sort(),animationsDropped:s.animationsDropped,mixedTextSimplified:s.tally.mixedTextSimplified,skipped:s.tally.skipped}}}export{Qt as importPptx};
@@ -1 +1 @@
1
- import{mergeDecks as o}from"../chunk-3RFDQOTI.js";import{importDeckFile as t}from"../chunk-6ZFEBY6H.js";import{PptxPasswordError as r,PptxUnreadableError as m}from"../chunk-MDG2ADZ7.js";import{SlidesConflict as i,SlidesProvider as p,browserSlidesStore as s}from"../chunk-BGAR3P46.js";import{SlideView as n}from"../chunk-B2X3NIQR.js";import{ENGLISH_WORDS as c,ZH_HANS_WORDS as e,asDocument as f}from"../chunk-PXOQN7D6.js";import{ENGLISH_FILE_WORDS as u,ZH_HANS_FILE_WORDS as a}from"../chunk-B32ASXHM.js";import{hasExtension as j}from"../chunk-XYVQTQ6N.js";import{lazy as h}from"react";var k=h(()=>import("../Slides-LJW5C24V.js")),d=h(()=>import("../Slides-LJW5C24V.js").then(o=>({default:o.OpenDeck}))),l={"/slides":{component:k,label:"Slides",size:"3xl",appStyle:!0,flushBody:!0,autoHeight:!1}};async function P(o,t){const{importPptx:r}=await(import("../pptxImport-Y7TB6PYP.js"));return r(o,t)}async function B(o,t){const{deckToPdf:r}=await(import("../deckPdf-4RC7QJ45.js"));return r(o,t)}export{d as DeckEditor,u as ENGLISH_FILE_WORDS,c as ENGLISH_WORDS,r as PptxPasswordError,m as PptxUnreadableError,n as SlideView,k as Slides,i as SlidesConflict,p as SlidesProvider,a as ZH_HANS_FILE_WORDS,e as ZH_HANS_WORDS,f as asDocument,s as browserSlidesStore,B as deckToPdf,j as hasExtension,t as importDeckFile,P as importPptx,o as mergeDecks,l as slidesApps};
1
+ import{mergeDecks as o}from"../chunk-3RFDQOTI.js";import{importDeckFile as t}from"../chunk-ADXHTZ3Q.js";import{PptxPasswordError as r,PptxUnreadableError as m}from"../chunk-MDG2ADZ7.js";import{SlidesConflict as i,SlidesProvider as p,browserSlidesStore as s}from"../chunk-BGAR3P46.js";import{SlideView as n}from"../chunk-B2X3NIQR.js";import{ENGLISH_WORDS as c,ZH_HANS_WORDS as e,asDocument as f}from"../chunk-PXOQN7D6.js";import{ENGLISH_FILE_WORDS as u,ZH_HANS_FILE_WORDS as a}from"../chunk-B32ASXHM.js";import{hasExtension as j}from"../chunk-XYVQTQ6N.js";import{lazy as h}from"react";var k=h(()=>import("../Slides-YZQXZJX4.js")),d=h(()=>import("../Slides-YZQXZJX4.js").then(o=>({default:o.OpenDeck}))),l={"/slides":{component:k,label:"Slides",size:"3xl",appStyle:!0,flushBody:!0,autoHeight:!1}};async function Q(o,t){const{importPptx:r}=await(import("../pptxImport-OACGHWQ6.js"));return r(o,t)}async function X(o,t){const{deckToPdf:r}=await(import("../deckPdf-4RC7QJ45.js"));return r(o,t)}export{d as DeckEditor,u as ENGLISH_FILE_WORDS,c as ENGLISH_WORDS,r as PptxPasswordError,m as PptxUnreadableError,n as SlideView,k as Slides,i as SlidesConflict,p as SlidesProvider,a as ZH_HANS_FILE_WORDS,e as ZH_HANS_WORDS,f as asDocument,s as browserSlidesStore,X as deckToPdf,j as hasExtension,t as importDeckFile,Q as importPptx,o as mergeDecks,l as slidesApps};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "efficient-office",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Efficient Office: the EFFICIENT office apps, on efficient-shell and efficient-easel.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{countWords as e,documentText as t,findInNodes as n,pageBlocks as r,pageDocument as o,pageStarts as a,pageStyles as i,replaceSpots as l,sanitizeHtml as s}from"./chunk-4NKXNXKY.js";import{DocumentsConflict as c,useDocumentsHost as d,useDocumentsWords as u}from"./chunk-HU4RI2OM.js";import"./chunk-I3AC6PYR.js";import{FileList as m}from"./chunk-PMGQ5GUH.js";import"./chunk-B32ASXHM.js";import{importDocumentFile as f}from"./chunk-JCSB2PHB.js";import{fingerprintOf as p,readDocx as h,readParts as g,stampFingerprints as w}from"./chunk-COXKOQPZ.js";import{BUILTIN_STYLES as b,HIGHLIGHTS as v,MARGIN_PRESETS as y,PAPER_SIZES as x,REL as C,WORD_NS as k,addContentDefault as S,addContentOverride as N,addRel as A,blankDocxParts as $,child as L,escapeXml as T,marginsOf as M,paperOf as E,parseParaProps as z,parseRunProps as R,parseXml as P,partText as j,readRels as D,resolveTarget as O,setPartText as F,withMargins as I,withPaper as H,writeZip as B}from"./chunk-RHW2M2UY.js";import{hasExtension as U,placeCopy as W}from"./chunk-XYVQTQ6N.js";import{useEffect as q,useRef as K,useState as G}from"react";import{WindowTitle as V,useWindowDirty as Q}from"efficient-shell";import{Button as X,EmptyState as Y,Input as J,LoadingSpinner as Z,confirmDestructive as _,toast as ee}from"efficient-shell/ui";import{useCallback as te,useEffect as ne,useId as re,useMemo as oe,useRef as ae,useState as ie}from"react";import{saveIndicator as le,useAutosave as se}from"efficient-easel/autosave";import{useEaselStrings as ce}from"efficient-easel/strings";import{Icon as de}from"efficient-shell/icons";import{Button as ue,ColorPickerPanel as me,ContextMenu as fe,DropdownMenu as pe,IconButton as he,Popover as ge,PopupMenu as we,PopupMenuDivider as be,PopupMenuItem as ve,PopupMenuLabel as ye,prompt as xe,registerModalEscapeInterceptor as Ce,toast as ke,useShellLocale as Se}from"efficient-shell/ui";import{SettingsColour as Ne}from"efficient-easel/panel";import{useEaselStrings as Ae}from"efficient-easel/strings";import{Button as $e,Select as Le}from"efficient-shell/ui";import{jsx as Te,jsxs as Me}from"react/jsx-runtime";function Ee({page:e,onPage:t,onMorePageSetup:n,colour:r,onColour:o,outline:a,onHeading:i}){const l=u(),s=Ae(),c=E(e),d=M(e),m={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},p={value:"custom",label:l.custom};return Me("aside",{className:"docs-panel",children:[Te("h3",{children:l.documentPanel}),Me("div",{className:"docs-panel-section",children:[Te("p",{className:"docs-panel-label",children:l.pagePanel}),Te(Le,{"aria-label":l.paperSize,value:c??"custom",onChange:n=>{"custom"!==n&&t(H(e,n))},options:[...c?[]:[p],...Object.keys(x).map(e=>({value:e,label:m[e]}))]}),Te(Le,{"aria-label":l.margins,value:d??"custom",onChange:n=>{"custom"!==n&&t(I(e,n))},options:[...d?[]:[p],...Object.keys(y).map(e=>({value:e,label:f[e]}))]}),Te($e,{variant:"secondary",block:!0,onClick:n,children:l.morePageSetup})]}),Te("div",{className:"docs-panel-section",children:Te(Ne,{label:l.textColor,value:r,onChange:o,words:s.colourRow})}),Me("div",{className:"docs-panel-section",children:[Te("p",{className:"docs-panel-label",children:l.outline}),0===a.length?Te("p",{className:"docs-panel-empty",children:l.outlineEmpty}):Te("ul",{className:"docs-outline",children:a.map((e,t)=>Te("li",{style:{paddingLeft:10*(e.level-1)+"px"},children:Te("button",{type:"button",onClick:()=>i(t),children:e.text})},t))})]})]})}import{EaselIconButton as ze,EaselTopBar as Re,SaveState as Pe,TopBarCluster as je,TopBarDivider as De}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 Oe}from"efficient-shell/icons";import{DropdownMenu as Fe}from"efficient-shell/ui";import{jsx as Ie,jsxs as He}from"react/jsx-runtime";function Be({onClose:e,fileMenu:t,name:n,saveState:r,canUndo:o,canRedo:a,onUndo:i,onRedo:l,exportControl:s}){const c=u();return He(Re,{children:[He(je,{children:[e&&Ie(ze,{label:c.backToFiles,onClick:e,children:Ie(Oe,{name:"chevron-left",size:16})}),t.length>0&&Ie(Fe,{trigger:c.menuFile,items:t,align:"start",triggerClassName:"docs-menu-trigger"}),n,Ie(Pe,{...r}),Ie(De,{}),He("span",{className:"docs-history",onMouseDown:e=>e.preventDefault(),children:[Ie(ze,{label:c.undo,disabled:!o,onClick:i,children:Ie(Oe,{name:"undo",size:16})}),Ie(ze,{label:c.redo,disabled:!a,onClick:l,children:Ie(Oe,{name:"redo",size:16})})]})]}),Ie(je,{kind:"right",children:s})]})}var Ue=["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"],We=["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"],qe=["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"],Ke=["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 Ge(e){if(!e)return[];return P(e).children.map(t=>({name:t.name,xml:e.slice(t.start,t.end)}))}function Ve(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 Qe(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 Xe={black:"#000000",white:"#ffffff",red:"#ff0000",blue:"#0000ff",green:"#008000",yellow:"#ffff00"};function Ye(e){if(!e)return;const t=e.trim().toLowerCase();if("transparent"===t||"inherit"===t||"initial"===t||"auto"===t)return;if(Xe[t])return Xe[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 Je(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 Ze=[10,13,16,18,24,32,48].map(e=>.75*e);var _e=(e,t)=>void 0===e||void 0===t?e===t:Math.abs(e-t)<.02,et=e=>Math.round(20*e);function tt(e,t){const n=D(e.parts,e.doc.docPath).find(e=>e.type===C.styles),r=n?j(e.parts,O(e.doc.docPath,n.target)):void 0;if(r)for(const e of P(r).children)if("w:style"===e.name&&L(e,"w:name")?.attrs["w:val"]?.toLowerCase()===t)return e.attrs["w:styleId"];return Object.entries(b).find(([,e])=>e.name===t)?.[0]??null}var nt=["•","o","▪"],rt=["decimal","lowerLetter","lowerRoman"];function ot(e){const t=D(e.parts,e.doc.docPath).find(e=>e.type===C.numbering);if(t){const n=O(e.doc.docPath,t.target);return{path:n,text:j(e.parts,n)??`<w:numbering ${k}></w:numbering>`}}const n="word/numbering.xml";return A(e.parts,e.doc.docPath,C.numbering,"numbering.xml"),N(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 ${k}></w:numbering>`}}function at(e,t){const{path:n,text:r}=ot(e),o=P(r),a=o.children.filter(e=>"w:abstractNum"===e.name).map(e=>Number(e.attrs["w:abstractNumId"])),i=String((a.length?Math.max(...a):-1)+1);let l="";for(let e=0;e<9;e++){l+=`<w:lvl w:ilvl="${e}"><w:start w:val="1"/><w:numFmt w:val="${t?rt[e%3]:"bullet"}"/><w:lvlText w:val="${t?`%${e+1}.`:nt[e%3]}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720*(e+1)}" w:hanging="360"/></w:pPr></w:lvl>`}const s=`<w:abstractNum w:abstractNumId="${i}"><w:multiLevelType w:val="hybridMultilevel"/>${l}</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)+s+r.slice(d):r.replace(/\/>\s*$/,`>${s}</w:numbering>`);return F(e.parts,n,u),i}function it(e,t,n){const{path:r,text:o}=ot(e),a=P(o),i=a.children.filter(e=>"w:num"===e.name).map(e=>Number(e.attrs["w:numId"])),l=String((i.length?Math.max(...i):0)+1),s=`<w:num w:numId="${l}"><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 F(e.parts,r,o.slice(0,d)+s+o.slice(d)),l}var lt={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/bmp":"bmp","image/webp":"webp","image/svg+xml":"svg"};function st(e,t){const n=t.getAttribute("data-raw"),r=function(e,t){const n=Qe(t),r=Je(n.get("width")),o=Je(n.get("height")),a=t.naturalWidth?.75*t.naturalWidth:0,i=t.naturalHeight?.75*t.naturalHeight:0,l=a&&i?i/a:o&&r?o/r:.75;let s=r??(a||e.contentWidth);return s>2*e.contentWidth&&(s=e.contentWidth),{width:s,height:o??s*l}}(e,t),o=Math.round(12700*r.width),a=Math.round(12700*r.height),i=n?e.doc.raw.get(n):void 0;if(i)return i.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 l=t.getAttribute("src")??"";let s=e.mediaBySrc.get(l);if(!s){const t=e.images.get(l)??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]}}(l);if(!t)return"";const n=lt[t.mime]??"png";S(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),s=A(e.parts,e.doc.docPath,C.image,`media/inserted${r}.${n}`),e.mediaBySrc.set(l,s)}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="${s}"/><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 ct(e,t,n,r={}){let o="",a=null;const i=()=>{a?.body&&(o+=`<w:r>${function(e,t,n){const r=n?e.runs.get(n):void 0,o=r?P(r):void 0,a=R(o,e.theme);let i=Ge(r);const l=(e,t)=>{i=i.filter(t=>!e.includes(t.name)),i.push(...t)},s=(e,t)=>void 0===t?[]:[{name:e,xml:t?`<${e}/>`:`<${e} w:val="0"/>`}];if(t.b!==a.b&&l(["w:b","w:bCs"],[...s("w:b",t.b),...s("w:bCs",t.b)]),t.i!==a.i&&l(["w:i","w:iCs"],[...s("w:i",t.i),...s("w:iCs",t.i)]),!!t.u!=!!a.u&&l(["w:u"],t.u?[{name:"w:u",xml:'<w:u w:val="single"/>'}]:a.u?[{name:"w:u",xml:'<w:u w:val="none"/>'}]:[]),t.strike!==a.strike&&!!t.strike!=!!a.strike&&l(["w:strike"],s("w:strike",t.strike)),t.vert!==a.vert&&l(["w:vertAlign"],t.vert?[{name:"w:vertAlign",xml:`<w:vertAlign w:val="${"sub"===t.vert?"subscript":"superscript"}"/>`}]:[]),t.font!==a.font){const e=T(t.font??"");l(["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!==a.size){const e=t.size?Math.round(2*t.size):0;l(["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!==a.color&&l(["w:color"],t.color?[{name:"w:color",xml:`<w:color w:val="${t.color.slice(1).toUpperCase()}"/>`}]:[]),t.hl!==a.hl){const e=t.hl?Object.entries(v).find(([,e])=>e===t.hl)?.[0]:void 0;l(["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 c=Ve(i,Ue);return c?`<w:rPr>${c}</w:rPr>`:""}(e.doc,a.format,a.runId)}${a.body}</w:r>`),a=null},l=(e,t,n)=>{n&&(a&&a.runId===t&&JSON.stringify(a.format)===JSON.stringify(e)?a.body+=n:(i(),a={format:e,runId:t,body:n}))},s=(t,r,a)=>{if(3===t.nodeType)return void l(r,a,function(e){let t="",n="";const r=()=>{n&&(t+=`<w:t xml:space="preserve">${T(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 i(),void(o+=st(e,c));const u=c.getAttribute("data-raw");if(u){const t=e.doc.raw.get(u);return void(t&&(i(),o+=t))}if(c.hasAttribute("data-page-break"))return void l(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)||l(r,a,"<w:br/>"));if("A"===d)return i(),void(o+=function(e,t,n,r){const o=t.getAttribute("data-anchor"),a=t.getAttribute("href")??"";let i=t.getAttribute("data-rel");const l=D(e.parts,e.doc.docPath),s=i?l.find(e=>e.id===i):void 0;a&&!a.startsWith("#")&&s?.target!==a&&(i=l.find(e=>e.external&&e.target===a)?.id??A(e.parts,e.doc.docPath,C.hyperlink,a,!0),t.setAttribute("data-rel",i));const c=t.querySelector("[data-r]")?n:{color:"#0563c1",u:!0,...n},d=ct(e,Array.from(t.childNodes),r,c);return`<w:hyperlink${o?` w:anchor="${T(o)}"`:i?` r:id="${T(i)}"`:a.startsWith("#")?` w:anchor="${T(a.slice(1))}"`:""} w:history="1">${d}</w:hyperlink>`}(e,c,r,n));const m=c.getAttribute("data-comment");m&&e.firstComment.get(m)===c&&(i(),o+=`<w:commentRangeStart w:id="${T(m)}"/>`);const f=c.getAttribute("data-r"),p=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=Ye(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=Ze[o-1])}const o=Qe(e),a=o.get("font-weight");a&&(n.b="bold"===a||"bolder"===a||Number(a)>=600);const i=o.get("font-style");i&&(n.i="italic"===i||"oblique"===i);const l=o.get("text-decoration-line")??o.get("text-decoration");l&&(/none/.test(l)?(n.u=!1,n.strike=!1):(/underline/.test(l)&&(n.u=!0),/line-through/.test(l)&&(n.strike=!0)));const s=o.get("font-family");s&&(n.font=s.split(",")[0].replace(/["']|&quot;/g,"").trim());const c=Je(o.get("font-size"));if(c&&(n.size=Math.round(2*c)/2),o.has("color")){const e=Ye(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=Ye(d);e?n.hl=e:delete n.hl}return n}(c,r);for(const e of Array.from(c.childNodes))s(e,p,f??a);m&&e.lastComment.get(m)===c&&(i(),o+=`<w:commentRangeEnd w:id="${T(m)}"/><w:r><w:commentReference w:id="${T(m)}"/></w:r>`)};for(const e of t)s(e,r,null);return i(),o}function dt(e,t,n,r,o){const a=n?P(n):void 0,i=z(a),l=function(e){const t=Qe(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=Je(t.get("margin-left"));void 0!==o&&(n.indentLeft=o);const a=Je(t.get("text-indent"));void 0!==a&&(n.firstLine=a);const i=Je(t.get("margin-top"));void 0!==i&&(n.before=i);const l=Je(t.get("margin-bottom"));void 0!==l&&(n.after=l);const s=t.get("line-height");if(s){const e=Je(s);e?n.linePoints=e:Number(s)&&(n.lineMultiple=Number(s))}return n}(t);let s=Ge(n);const c=(e,t)=>{s=s.filter(t=>t.name!==e),t&&s.push({name:e,xml:t})};if(c("w:pStyle",r?`<w:pStyle w:val="${T(r)}"/>`:null),c("w:numPr",o?`<w:numPr><w:ilvl w:val="${o.ilvl}"/><w:numId w:val="${T(o.numId)}"/></w:numPr>`:null),l.align!==i.align&&c("w:jc",l.align?`<w:jc w:val="${"justify"===l.align?"both":l.align}"/>`:null),!(o||_e(l.indentLeft,i.indentLeft)&&_e(l.firstLine,i.firstLine))){const e=[];void 0!==l.indentLeft&&e.push(`w:left="${et(l.indentLeft)}"`),void 0!==l.firstLine&&e.push(l.firstLine<0?`w:hanging="${et(-l.firstLine)}"`:`w:firstLine="${et(l.firstLine)}"`),c("w:ind",e.length?`<w:ind ${e.join(" ")}/>`:null)}if(!(_e(l.before,i.before)&&_e(l.after,i.after)&&_e(l.lineMultiple,i.lineMultiple)&&_e(l.linePoints,i.linePoints))){const e=[];void 0!==l.before&&e.push(`w:before="${et(l.before)}"`),void 0!==l.after&&e.push(`w:after="${et(l.after)}"`),void 0!==l.lineMultiple&&e.push(`w:line="${Math.round(240*l.lineMultiple)}" w:lineRule="auto"`),void 0!==l.linePoints&&e.push(`w:line="${et(l.linePoints)}" w:lineRule="exact"`),c("w:spacing",e.length?`<w:spacing ${e.join(" ")}/>`:null)}const d=Ve(s,We);return d?`<w:pPr>${d}</w:pPr>`:""}function ut(e,t){let n=t.getAttribute("data-pstyle");if(!n){const r=/^H([1-6])$/.exec(t.tagName);r?n=tt(e,`heading ${r[1]}`)??`Heading${r[1]}`:"BLOCKQUOTE"===t.tagName&&(n=tt(e,"quote"))}return n&&function(e,t){const n=D(e.parts,e.doc.docPath).find(e=>e.type===C.styles);if(!n)return;const r=O(e.doc.docPath,n.target),o=j(e.parts,r);if(!o||new RegExp(`w:styleId="${t}"`).test(o))return;const a=b[t];a&&F(e.parts,r,o.replace("</w:styles>",`${a.xml}</w:styles>`))}(e,n),n}function mt(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===p(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>${dt(0,t,a?.props,ut(e,t),r)}${ct(e,n,t)}</w:p>`}var ft=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","LI","HR","SECTION","ARTICLE"]);function pt(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??=at(e,!0),o=it(e,e.orderedAbstract,!0)):(e.bulletNum??=it(e,at(e,!1),!1),o=e.bulletNum),t.setAttribute("data-num-id",o),o}(e,t,n),a=t.getAttribute("data-ilvl"),i=null!==a&&Number(a)>r?Number(a):r+1;let l="";for(const n of Array.from(t.children)){if("UL"===n.tagName||"OL"===n.tagName){l+=pt(e,n,o,i);continue}if("LI"!==n.tagName)continue;const t=Array.from(n.children).filter(e=>"UL"===e.tagName||"OL"===e.tagName);l+=mt(e,n,Array.from(n.childNodes).filter(e=>!t.includes(e)),{numId:o,ilvl:i});for(const n of t)l+=pt(e,n,o,i)}return l}function ht(e){return Array.from(e.children).some(e=>ft.has(e.tagName))}function gt(e,t){let n="",r=[];const o=()=>{r.some(e=>1===e.nodeType||(e.nodeValue??"").trim())&&(n+=`<w:p>${ct(e,r,t)}</w:p>`),r=[]};for(const a of Array.from(t.childNodes)){const t=a;if(1!==a.nodeType||!ft.has(t.tagName)){r.push(a);continue}o();const i=t.getAttribute("data-docx"),l=i?e.doc.blocks.get(i):void 0;"UL"===t.tagName||"OL"===t.tagName?n+=pt(e,t,null,-1):"TABLE"===t.tagName?n+=wt(e,t):t.hasAttribute("data-locked")&&l?.xml?n+=l.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>':ht(t)?n+=gt(e,t):n+=mt(e,t,Array.from(t.childNodes),null)}return o(),n}function wt(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===p(t)))return r.xml;const o=Array.from(t.querySelectorAll(":scope > tbody > tr, :scope > tr, :scope > thead > tr, :scope > tfoot > tr")),a=[];let i=0;const l=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 i of Array.from(t.children).filter(e=>"TD"===e.tagName||"TH"===e.tagName)){o();const t=Math.max(1,Number(i.getAttribute("colspan")??1)),l=Math.max(1,Number(i.getAttribute("rowspan")??1));n.push({cell:i,span:t,col:r}),l>1&&(a[r]={left:l-1,span:t,props:e.doc.blocks.get(i.getAttribute("data-docx")??"")?.props}),r+=t}return o(),i=Math.max(i,r),n}),s=Array.from(t.querySelectorAll(":scope > colgroup > col")),c=[];for(let t=0;t<i;t++){const n=s[t]?Je(Qe(s[t]).get("width")):void 0;c.push(void 0!==n&&s.length===i?et(n):Math.round(20*e.contentWidth/Math.max(i,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??""}${l[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>${bt(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),i=Ye(Qe(t.cell).get("background-color"));let l=gt(e,t.cell);return l.endsWith("</w:p>")||l.endsWith("<w:p/>")||(l+="<w:p/>"),`<w:tc><w:tcPr>${bt(o?.props,r,n,a>1?"restart":null,i)}</w:tcPr>${l}</w:tc>`}).join("")}</w:tr>`).join("")}</w:tbl>`}function bt(e,t,n,r,o){const a=e?P(e):void 0;let i=Ge(e).filter(e=>!["w:tcW","w:gridSpan","w:vMerge"].includes(e.name));i.push({name:"w:tcW",xml:`<w:tcW w:w="${t}" w:type="dxa"/>`}),n>1&&i.push({name:"w:gridSpan",xml:`<w:gridSpan w:val="${n}"/>`}),r&&i.push({name:"w:vMerge",xml:"restart"===r?'<w:vMerge w:val="restart"/>':"<w:vMerge/>"});const l=L(a,"w:shd")?.attrs["w:fill"]?.toLowerCase();return"continue"!==r&&(o?.slice(1)??void 0)!==(l&&/^[0-9a-f]{6}$/.test(l)?l:void 0)&&(i=i.filter(e=>"w:shd"!==e.name),o&&i.push({name:"w:shd",xml:`<w:shd w:val="clear" w:color="auto" w:fill="${o.slice(1).toUpperCase()}"/>`})),Ve(i,qe)}function vt(e,t,n,r,o){let a=Ge(t);const i=e.doc.page;if(Object.keys(n).some(e=>n[e]!==i[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?P(t):void 0,i=L(o,"w:pgMar")?.attrs["w:gutter"]??"0",l=`<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="${i}"/>`;a=a.filter(e=>"w:pgSz"!==e.name&&"w:pgMar"!==e.name),a.push({name:"w:pgSz",xml:r},{name:"w:pgMar",xml:l})}const l=n.width-n.left-n.right,s=(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">${T(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} ${k}><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,l);if(t.part)return void F(e.parts,t.part,o);const i="hdr"===r?"header":"footer";let s=1;for(;e.parts.has(`word/${i}${s}.xml`);)s++;const c=`word/${i}${s}.xml`;F(e.parts,c,o),N(e.parts,c,`application/vnd.openxmlformats-officedocument.wordprocessingml.${i}+xml`);const d=A(e.parts,e.doc.docPath,"hdr"===r?C.header:C.footer,`${i}${s}.xml`);a.push({name:`w:${i}Reference`,xml:`<w:${i}Reference w:type="default" r:id="${d}"/>`}),t.part=c};s(e.doc.header,r,"hdr"),s(e.doc.footer,o,"ftr");return`<w:sectPr${t?/^<w:sectPr\b([^>]*?)\/?>/.exec(t)?.[1]??"":""}>${Ve(a,Ke)}</w:sectPr>`}async function yt(e,t,n){const r=new Map(e.parts),o=j(r,e.docPath);if(!o)throw new Error("Not a Word document");const a=P(o),i=L(a,"w:body"),l=L(i,"w:sectPr"),s={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");s.firstComment.has(t)||s.firstComment.set(t,e),s.lastComment.set(t,e)});let c=gt(s,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=vt(s,l?o.slice(l.start,l.end):void 0,n.page,n.headerText,n.footerText),u=o.slice(a.start,a.innerStart),m=[!/\bxmlns:r=/.test(u)&&/\br:(id|embed)=/.test(c+d)?' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"':""].join(""),f=(m?o.slice(0,a.innerStart-1)+m+">":o.slice(0,a.innerStart))+o.slice(a.innerStart,i.innerStart)+c+d+o.slice(i.innerEnd);return F(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},B(r)}function xt(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 Ct,useRef as kt}from"react";import{Icon as St}from"efficient-shell/icons";import{Button as Nt,Checkbox as At,IconButton as $t,Input as Lt}from"efficient-shell/ui";import{jsx as Tt,jsxs as Mt}from"react/jsx-runtime";function Et({query:e,replacement:t,matchCase:n,current:r,total:o,onQuery:a,onReplacement:i,onMatchCase:l,onStep:s,onReplace:c,onReplaceAll:d,onClose:m}){const f=u(),p=kt(null);return Ct(()=>{p.current?.focus(),p.current?.select()},[]),Mt("div",{className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-line bg-surface-sunken px-2 py-1",children:[Tt("div",{className:"w-40",children:Tt(Lt,{ref:p,size:"sm","aria-label":f.find,placeholder:f.find,value:e,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),s(!e.shiftKey))}})}),Tt("span",{className:"min-w-14 text-xs text-ink-muted","aria-live":"polite",children:e?o?f.matchCount(r+1,o):f.noMatches:""}),Tt($t,{size:"sm",variant:"ghost","aria-label":f.previousMatch,title:f.previousMatch,onClick:()=>s(!1),children:Tt(St,{name:"chevron-up",size:16})}),Tt($t,{size:"sm",variant:"ghost","aria-label":f.nextMatch,title:f.nextMatch,onClick:()=>s(!0),children:Tt(St,{name:"chevron-down",size:16})}),Tt("div",{className:"ml-1 w-40",children:Tt(Lt,{size:"sm","aria-label":f.replaceWith,placeholder:f.replaceWith,value:t,onChange:e=>i(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),c())}})}),Tt(Nt,{size:"sm",variant:"secondary",onClick:c,children:f.replace}),Tt(Nt,{size:"sm",variant:"secondary",onClick:d,children:f.replaceAll}),Mt("label",{className:"ml-1 flex items-center gap-1 text-xs text-ink-muted",children:[Tt(At,{checked:n,onChange:l,"aria-label":f.matchCase}),f.matchCase]}),Tt($t,{className:"ml-auto",size:"sm",variant:"ghost","aria-label":f.closeFind,title:f.closeFind,onClick:m,children:Tt(St,{name:"close",size:16})})]})}var zt=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 Rt(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 Pt(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)}}function jt(e){return Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6")).filter(e=>!e.closest("[data-hidden]")&&""!==(e.textContent??"").trim())}var Dt=["#000000","#404040","#7f7f7f","#c00000","#ff0000","#ffc000","#00b050","#0070c0","#002060","#7030a0"],Ot=["#ffff00","#00ff00","#00ffff","#ff00ff","#ff0000","#c0c0c0"],Ft=["#d9e2f3","#e2efd9","#fff2cc","#fbe4d5","#ededed","#bfbfbf"];function It(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 Ht}from"react";import{Button as Bt,Dialog as Ut,FormField as Wt,Input as qt,Select as Kt}from"efficient-shell/ui";import{Fragment as Gt,jsx as Vt,jsxs as Qt}from"react/jsx-runtime";function Xt({value:e,headerEditable:t,footerEditable:n,onApply:r,onClose:o}){const a=u(),[i,l]=Ht(e.page),[s,c]=Ht(e.header),[d,m]=Ht(e.footer),f=i.width>i.height,p=E(i),h=M(i),g={a4:"A4",a3:"A3",a5:"A5",letter:a.paperLetter,legal:a.paperLegal},w={normal:a.marginsNormal,narrow:a.marginsNarrow,moderate:a.marginsModerate,wide:a.marginsWide},b={value:"custom",label:a.custom};return Vt(Ut,{open:!0,onClose:o,title:a.pageSetup,size:"sm",footer:Qt(Gt,{children:[Vt(Bt,{variant:"secondary",onClick:o,children:a.cancel}),Vt(Bt,{variant:"primary",onClick:()=>r({page:i,header:s,footer:d}),children:a.ok})]}),children:Qt("div",{className:"space-y-3",children:[Vt(Wt,{label:a.paperSize,children:Vt(Kt,{value:p??"custom",onChange:e=>{"custom"!==e&&l(t=>H(t,e))},options:[...p?[]:[b],...Object.keys(x).map(e=>({value:e,label:g[e]}))]})}),Vt(Wt,{label:a.orientation,children:Vt(Kt,{value:f?"landscape":"portrait",onChange:e=>{"landscape"===e!==f&&l(e=>({...e,width:e.height,height:e.width}))},options:[{value:"portrait",label:a.portrait},{value:"landscape",label:a.landscape}]})}),Vt(Wt,{label:a.margins,children:Vt(Kt,{value:h??"custom",onChange:e=>{"custom"!==e&&l(t=>I(t,e))},options:[...h?[]:[b],...Object.keys(y).map(e=>({value:e,label:w[e]}))]})}),Vt(Wt,{label:a.header,hint:t?a.headerFooterHint:a.headerFooterLocked,children:Vt(qt,{value:s,disabled:!t,onChange:e=>c(e.target.value)})}),Vt(Wt,{label:a.footer,hint:n?void 0:a.headerFooterLocked,children:Vt(qt,{value:d,disabled:!n,onChange:e=>m(e.target.value)})})]})})}var Yt=e=>e.querySelectorAll("ul,ol").forEach(e=>e.removeAttribute("data-ilvl"));function Jt(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),Yt(e),!0}function Zt(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),Yt(e),t.children.length||t.remove(),!0}var _t=e=>Array.from(e.querySelectorAll(":scope > tbody > tr, :scope > tr, :scope > thead > tr, :scope > tfoot > tr")),en=(e,t)=>Math.max(1,Number(e.getAttribute(t)??1));function tn(e){const t=_t(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=en(a,"colspan"),i=en(a,"rowspan");for(let l=r;l<Math.min(r+i,t.length);l++)for(let t=o;t<o+e;t++)n[l][t]=a;o+=e}}),{table:e,slots:n,cols:Math.max(0,...n.map(e=>e.length))}}function nn(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 rn(e){const t=e.createElement("td");return t.innerHTML="<p><br></p>",t}function on(e,t,n){const r=tn(e),o=nn(r,t);if(!o)return;const a=_t(e),i=en(t,"rowspan"),l=n?o.row+i:o.row,s=e.ownerDocument.createElement("tr"),c=new Set;for(let t=0;t<r.cols;t++){const n=l>0?r.slots[l-1]?.[t]:void 0,o=r.slots[l]?.[t];n&&n===o?c.has(n)||(c.add(n),n.setAttribute("rowspan",String(en(n,"rowspan")+1))):s.appendChild(rn(e.ownerDocument))}const d=a[l];d?d.parentNode.insertBefore(s,d):a[a.length-1].parentNode.appendChild(s)}function an(e,t,n){const r=tn(e),o=nn(r,t);if(!o)return;const a=n?o.col+en(t,"colspan"):o.col,i=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(i.has(r)||(i.add(r),r.setAttribute("colspan",String(en(r,"colspan")+1))));if(o&&o.parentElement!==_t(e)[n])return;const l=_t(e)[n],s=t.slice(a).find(e=>e.parentElement===l);l.insertBefore(rn(e.ownerDocument),s??null)}),ln(e,r.cols+1,a,null)}function ln(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 sn,jsx as cn,jsxs as dn}from"react/jsx-runtime";var un=["Calibri","Arial","Cambria","Courier New","Georgia","Tahoma","Times New Roman","Verdana"],mn=[8,9,10,10.5,11,12,14,16,18,20,22,24,28,32,36,48,72],fn=[1,1.15,1.5,2,2.5,3],pn=[50,75,90,100,110,125,150,200],hn="p,h1,h2,h3,h4,h5,h6,li,blockquote,pre",gn=/^(https?:|mailto:|tel:)/i,wn={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 bn({sessionKey:d,doc:m,filename:f,images:p,fileEntries:h,title:g,startsDirty:w,dirty:b,onDirty:v,onOpenFile:y,onNewImageUrl:x,onClose:C,stored:k,onReload:S}){const N=u(),A=Se(),$=re().replace(/[^a-zA-Z0-9]/g,""),L=ae(null),T=ae(null),M=ae(null),z=ae(new zt),R=ae(null),P=ae(null),j=ae(null),D=ae(!!w),O=ae(0),F=ae(()=>{}),I=ae(null),H=ae(0),B=ae(k?.version??""),U=ae(null),[W,q]=ie({page:m.page,header:m.header.text,footer:m.footer.text}),[K,G]=ie(wn),[V,Q]=ie({undo:!1,redo:!1}),[X,Y]=ie({words:0,pageNow:1}),[J,Z]=ie([0]),[_,ee]=ie([]),[Ne,Ae]=ie(!1),[$e,Le]=ie(100),[Te,Me]=ie(!1),[ze,Re]=ie(!0),[Pe,je]=ie(!1),[De,Oe]=ie({rows:0,cols:0}),[Fe,Ie]=ie(null),[He,Ue]=ie(null),[We,qe]=ie(!1),[Ke,Ge]=ie(""),[Ve,Qe]=ie(""),[Xe,Ye]=ie(!1),[Je,Ze]=ie(0),[_e,et]=ie(0),tt=ae([]),nt=(W.page.width-W.page.left-W.page.right)/20,rt=e=>!!e&&!!T.current?.contains(e),ot=te(()=>{const e=T.current,t=document.getSelection();if(!(e&&t?.anchorNode&&t.focusNode&&rt(t.anchorNode))){const t=R.current;if(!e||!t)return null;const n=Rt(e,t.startContainer,t.startOffset),r=Rt(e,t.endContainer,t.endOffset);return n&&r?{anchor:n,focus:r}:null}const n=Rt(e,t.anchorNode,t.anchorOffset),r=Rt(e,t.focusNode,t.focusOffset);return n&&r?{anchor:n,focus:r}:null},[]),at=te(e=>{const t=T.current,n=document.getSelection();if(!t||!n||!e)return;const r=Pt(t,e.anchor),o=Pt(t,e.focus);r&&o&&n.setBaseAndExtent(r.node,r.offset,o.node,o.offset)},[]),it=te(e=>{const t=T.current;if(!t)return;const n=document.getSelection(),r=!e&&!!n&&rt(n.anchorNode);if(document.activeElement!==t&&t.focus({preventScroll:!0}),r&&n?.rangeCount)return void(R.current=n.getRangeAt(0).cloneRange());const o=e??R.current;n&&o&&(n.removeAllRanges(),n.addRange(o),R.current=o.cloneRange())},[]),lt=te(()=>{const e=T.current,t=R.current;if(!e||!t)return[];const n=Array.from(e.querySelectorAll(hn)).filter(e=>!e.closest("[data-locked]"));var r;return(t.collapsed?[(r=t.startContainer,(1===r.nodeType?r:r.parentElement)?.closest(hn))].filter(Boolean):n.filter(e=>t.intersectsNode(e))).filter(e=>rt(e)&&!e.closest("[data-locked]"))},[]),st=te(()=>{cancelAnimationFrame(O.current),O.current=requestAnimationFrame(()=>{const n=T.current;if(!n)return;const o=n.getBoundingClientRect().height/(n.offsetHeight||1)||1,i=n.getBoundingClientRect().top+W.page.top/20*(4/3)*o,l=(W.page.height-W.page.top-W.page.bottom)/20*(4/3),s=a(r(n,i,o),l);Z(e=>e.length===s.length&&e.every((e,t)=>e===s[t])?e:s);const c=document.getSelection();let d=1;if(c?.rangeCount&&rt(c.anchorNode)){const e=c.getRangeAt(0).getClientRects()[0]??c.anchorNode?.getBoundingClientRect?.();if(e){const t=(e.top-i)/o;for(let e=0;e<s.length;e++)s[e]<=t+1&&(d=e+1)}}Y({words:e(t(n)),pageNow:d});const u=function(e){return jt(e).map(e=>({level:Number(e.tagName[1]),text:(e.textContent??"").trim().replace(/\s+/g," ")}))}(n);ee(e=>{return n=u,(t=e).length===n.length&&t.every((e,t)=>e.level===n[t].level&&e.text===n[t].text)?e:u;var t,n})})},[W.page]),ct=te(()=>{const e=document.getSelection();if(!e?.anchorNode||!rt(e.anchorNode))return;const t=1===e.anchorNode.nodeType?e.anchorNode:e.anchorNode.parentElement;if(!t)return;const n=getComputedStyle(t),r=t.closest(hn),o=e=>{try{return document.queryCommandState(e)}catch{return!1}},a=n.textAlign,i=.75*parseFloat(n.fontSize);G({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:i?Math.round(2*i)/2:null,styleId:r?.getAttribute("data-pstyle")??null,color:It(n.color)})},[]),dt=async()=>{const e=I.current;if(!e)throw new Error("No page");if(!D.current&&W.page===m.page&&m.source)return m.source;const t=H.current,n=await yt(m,e,{page:W.page,headerText:W.header,footerText:W.footer,images:p});return D.current&&H.current===t&&(m.source=n,D.current=!1,q(e=>({...e,page:m.page}))),n},ut=ce(),mt=se({debounceMs:1500,maxWaitMs:4e3,save:async()=>{k&&(B.current=await k.store.save(k.id,await dt(),B.current))},onFailure:(e,t)=>{e instanceof c?(mt.stop(),Ae(!0)):0===t&&ke.error(N.saveFailed)}}),{push:ft,flush:pt}=mt,ht=!!k,gt=mt.state.pending;ne(()=>{ht&&v(gt||Ne)},[Ne,ht,v,gt]),ne(()=>()=>{pt()},[pt]);const wt=te(()=>{D.current=!0,H.current+=1,v(!0),ht&&ft(H.current),st(),Q({undo:z.current.canUndo,redo:z.current.canRedo})},[ht,st,v,ft]),bt=te(()=>({html:T.current?.innerHTML??"",caret:ot()}),[ot]),vt=()=>{P.current&&clearTimeout(P.current),P.current=null},Ct=te(e=>{e&&T.current&&(T.current.innerHTML=e.html,T.current.focus({preventScroll:!0}),at(e.caret),vt(),wt(),ct())},[at,wt,ct]),kt=te(()=>Ct(z.current.undo(bt())),[Ct,bt]),St=te(()=>Ct(z.current.redo(bt())),[Ct,bt]),Nt=te(e=>{it(),vt(),z.current.record(bt()),e(),wt(),ct()},[wt,ct,it,bt]),At=te((e,t)=>Nt(()=>{document.execCommand(e,!1,t)}),[Nt]),$t=e=>Nt(()=>{document.execCommand(e);const t=T.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)});ne(()=>{const e=T.current;if(!e)return;I.current=e,e.innerHTML=m.html;try{document.execCommand("defaultParagraphSeparator",!1,"p"),document.execCommand("styleWithCSS",!1,"true")}catch{}e.focus({preventScroll:!0});const t=e.querySelector(hn);t&&document.getSelection()?.collapse(t,0),st();const n=t=>"historyUndo"===t.inputType?(t.preventDefault(),void kt()):"historyRedo"===t.inputType?(t.preventDefault(),void St()):(P.current?clearTimeout(P.current):z.current.record({html:e.innerHTML,caret:ot()}),void(P.current=setTimeout(()=>{P.current=null},600))),r=()=>{(()=>{const t=j.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)})})(),wt(),ct()},o=()=>{const e=document.getSelection();e?.rangeCount&&rt(e.anchorNode)&&(R.current=e.getRangeAt(0).cloneRange(),ct(),st())};e.addEventListener("beforeinput",n),e.addEventListener("input",r),document.addEventListener("selectionchange",o);const a=new ResizeObserver(()=>st());return a.observe(e),()=>{e.removeEventListener("beforeinput",n),e.removeEventListener("input",r),document.removeEventListener("selectionchange",o),a.disconnect(),cancelAnimationFrame(O.current),vt(),U.current&&clearTimeout(U.current)}},[]),ne(()=>{st()},[st]),ne(()=>{w&&v(!0)},[]);const Lt=e=>Nt(()=>{const t=ot(),n=e?/^heading ([1-6])$/i.exec(m.styles.find(t=>t.id===e)?.name??"")?.[1]:void 0,r=n?`H${n}`:"P";for(const t of lt()){if("LI"===t.tagName){e?t.setAttribute("data-pstyle",e):t.removeAttribute("data-pstyle");continue}let n=t;if(t.tagName!==r){n=document.createElement(r);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")}at(t)}),Tt=e=>Nt(()=>{const t=lt(),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?Jt(t):Zt(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`:""}}),Mt=e=>At({left:"justifyLeft",center:"justifyCenter",right:"justifyRight",justify:"justifyFull"}[e]),Ht=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}));x(n),p.set(n,{bytes:e,mime:t.type});const r=new Image;r.src=n,await r.decode().catch(()=>{});const o=.75*r.naturalWidth,a=Math.min(o||nt,nt),i=o?a*(r.naturalHeight/r.naturalWidth):0;At("insertHTML",`<img src="${n}" alt="" style="width:${Math.round(100*a)/100}pt${i?`;height:${Math.round(100*i)/100}pt`:""}">`)}},Bt=async()=>{it();const e=R.current?.cloneRange()??null,t=e?.startContainer?1===e.startContainer.nodeType?e.startContainer:e.startContainer.parentElement:null,n=t?.closest("a")??null,r=await xe({title:N.link,message:N.linkPrompt,placeholder:"https://example.com",defaultValue:n?.getAttribute("href")??"",confirmLabel:N.ok,cancelLabel:N.cancel,allowEmpty:!0});if(await new Promise(e=>setTimeout(e,0)),it(e),null===r)return;const o=r.trim();if(!o)return void(n&&At("unlink"));const a=/^[a-z][a-z0-9+.-]*:/i.test(o)?o:`https://${o}`;if(gn.test(a))if(n)Nt(()=>{n.setAttribute("href",a)});else if(e?.collapsed){const e=document.createElement("a");e.href=a,e.textContent=o,At("insertHTML",e.outerHTML)}else At("createLink",a);else ke.error(N.linkInvalid)},Ut=()=>At("insertHTML",'<span data-page-break="" contenteditable="false"></span>​'),Wt=(e,t)=>{je(!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 i=e.createElement("tbody");for(let r=0;r<t;r++){const t=e.createElement("tr");for(let r=0;r<n;r++)t.appendChild(rn(e));i.appendChild(t)}return o.appendChild(i),o}(document,e,t,nt);n.setAttribute("data-new",""),At("insertHTML",`${n.outerHTML}<p><br></p>`);const r=T.current?.querySelector("table[data-new]");if(r){r.removeAttribute("data-new");const e=r.querySelector("td p");e&&document.getSelection()?.collapse(e,0)}};F.current=e=>{Ht(e)};const qt=e=>{if(!Fe)return;const t=Fe.el;Nt(()=>{const n=.75*t.naturalWidth,r=null===e?n:nt*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"}),Ie(null)},Kt=te((e,t)=>{const n=tt.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"})},[]),Gt=()=>{const e=globalThis.CSS?.highlights;e?.delete("docs-find"),e?.delete("docs-find-current")},Vt=te((e,t,r)=>{const o=T.current,a=o?n(o,e,t):[];tt.current=a,et(a.length);const i=a.length?Math.min(r,a.length-1):0;Ze(i),Kt(i,!0)},[Kt]),Qt=te(()=>{const e=tt.current[Je];qe(!1),Gt();const t=T.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),tt.current=[]},[Je]),Yt=()=>{const e=document.getSelection(),t=e&&rt(e.anchorNode)?e.toString():"";qe(!0);const n=t&&!t.includes("\n")?t:Ke;Ge(n),setTimeout(()=>Vt(n,Xe,0),0)},bn=ae(Qt);bn.current=Qt;const yn=ae(We);yn.current=We,ne(()=>Ce(()=>!(!yn.current||!L.current?.contains(document.activeElement))&&(bn.current(),!0)),[]),ne(()=>()=>Gt(),[]),ne(()=>{const e=e=>{const{key:t,files:n}=e.detail;t===d&&F.current(n)};return window.addEventListener("docs-insert-images",e),()=>window.removeEventListener("docs-insert-images",e)},[d]);const xn=k?f:(e=>e.replace(/\.[^.]+$/,"")||e)(f),Cn=`${xn}.docx`,kn=async()=>{try{const e=H.current;xt(await dt(),Cn,"application/vnd.openxmlformats-officedocument.wordprocessingml.document"),k||H.current!==e||v(!1)}catch{ke.error(N.saveFailed)}},Sn=e=>o({title:xn,html:e,doc:m,scope:$,page:W.page,header:W.header,footer:W.footer}),Nn=()=>{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(Sn(T.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()},An=h.length?[...h,{type:"divider",key:"d1"},{key:"save",label:cn(vn,{label:N.saveDocx,hint:"⌘S"}),onSelect:()=>{kn()}}]:[],$n=[{key:"docx",label:N.saveAsWord,onSelect:()=>{kn()}},{key:"pdf",label:N.saveAsPdf,onSelect:Nn},{key:"html",label:N.saveAsWeb,onSelect:()=>{(async()=>{const e=document.createElement("div");e.innerHTML=T.current?.innerHTML??"";for(const t of Array.from(e.querySelectorAll("img"))){const e=p.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()),xt(Sn(e.innerHTML),`${xn}.html`,"text/html")})()}},{key:"txt",label:N.saveAsText,onSelect:()=>{xt(t(T.current),`${xn}.txt`,"text/plain")}}],Ln=[{key:"table",label:N.table,onSelect:()=>je(!0)},{key:"image",label:N.image,onSelect:()=>M.current?.click()},{key:"link",label:cn(vn,{label:N.link,hint:"⌘K"}),onSelect:()=>{Bt()}},{key:"break",label:cn(vn,{label:N.pageBreak,hint:"⌘↵"}),onSelect:Ut},{key:"number",label:N.pageNumber,onSelect:()=>Me(!0)},{key:"line",label:N.horizontalLine,onSelect:()=>At("insertHorizontalRule")}],Tn=[{key:"setup",label:N.pageSetup,onSelect:()=>Me(!0)}],Mn={Title:N.styleTitle,"heading 1":N.styleHeading1,"heading 2":N.styleHeading2,"heading 3":N.styleHeading3,Quote:N.styleQuote},En=[{key:"normal",label:N.styleNormal,onSelect:()=>Lt(null)},...m.styles.map(e=>({key:e.id,label:Mn[e.name]??e.name,onSelect:()=>Lt(e.id)}))],zn=oe(()=>Array.from(new Set([...m.defaultFont?[m.defaultFont]:[],...un])),[m.defaultFont]).map(e=>({key:e,label:cn("span",{style:{fontFamily:`"${e}"`},children:e}),onSelect:()=>At("fontName",e)})),Rn=mn.map(e=>({key:String(e),label:String(e),onSelect:()=>(e=>Nt(()=>{j.current=e,document.execCommand("styleWithCSS",!1,"false"),document.execCommand("fontSize",!1,"7"),document.execCommand("styleWithCSS",!1,"true");const t=T.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)})),Pn=fn.map(e=>({key:String(e),label:e.toFixed(1.15===e?2:1),onSelect:()=>{return t=e,Nt(()=>{for(const e of lt())e.style.lineHeight=String(t)});var t}})),jn=e=>e.preventDefault(),Dn="rounded px-2 py-0.5 text-xs text-ink-muted hover:bg-line-subtle hover:text-ink",On="inline-flex h-7 items-center gap-1 rounded px-2 text-xs text-ink-muted hover:bg-line-subtle hover:text-ink",Fn=cn("div",{className:"mx-1 h-4 w-px bg-line"}),In=(e,t,n,r={})=>cn(he,{"aria-label":e,title:e,size:"sm",variant:"ghost",onMouseDown:jn,onClick:n,disabled:r.disabled,...void 0!==r.pressed?{"aria-pressed":r.pressed}:{},children:t}),Hn=(e,t,n,r="")=>cn(pe,{"aria-label":e,align:"start",items:n,triggerClassName:On,trigger:dn("span",{title:e,className:`flex items-center justify-between gap-1 ${r}`,children:[cn("span",{className:"truncate",children:t}),cn(de,{name:"chevron-down",size:12})]})}),Bn=(e,t,n,r,o)=>cn(ge,{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:dn(sn,{children:[t,cn("span",{className:"h-0.5 w-4 rounded-sm",style:{background:n}})]}),children:({close:t})=>cn(me,{label:e,value:"",presets:r,clearable:!0,dragWrites:"end",onChange:e=>{"hiliteColor"===o?At("hiliteColor",e||"transparent"):At("foreColor",e||Dt[0]),Wn(t=>({...t,[o]:e||("hiliteColor"===o?"var(--line)":"var(--ink)")})),t()}})}),[Un,Wn]=ie({foreColor:"var(--ink)",hiliteColor:"var(--line)"}),qn=E(W.page),Kn=qn?{a4:"A4",a3:"A3",a5:"A5",letter:N.paperLetter,legal:N.paperLegal}[qn]:N.custom,Gn=oe(()=>{if(!m.lang)return"";try{return new Intl.DisplayNames(A?[A]:void 0,{type:"language"}).of(m.lang)??m.lang}catch{return m.lang}},[m.lang,A]),Vn=W.page.width/20,Qn=W.page.top/20,Xn=W.header.split(/\s*\|\s*/),Yn=W.footer.split(/\s*\|\s*/),Jn=(e,t)=>e.replace(/\{page\}/g,String(t)).replace(/\{pages\}/g,String(J.length)),Zn=m.notices,_n=[Zn.comments&&N.noticeComments(Zn.comments),Zn.tracked&&N.noticeTracked(Zn.tracked),Zn.objects&&N.noticeObjects(Zn.objects),Zn.footnotes&&N.noticeFootnotes(Zn.footnotes)].filter(Boolean);return dn("div",{ref:L,className:"es-editor docs-frame",onKeyDown:e=>{const t=e.metaKey||e.ctrlKey,n=e.key.toLowerCase(),r=rt(e.target),o=()=>{e.preventDefault(),e.stopPropagation()};if(t&&!e.altKey){if("s"===n)return o(),void(k?pt():kn());if("o"===n)return o(),void y();if("p"===n)return o(),void Nn();if("f"===n)return o(),void Yt();if("k"===n)return o(),void Bt();if(r){if("z"===n&&!e.shiftKey)return o(),void kt();if("z"===n&&e.shiftKey||"y"===n)return o(),void St();if("b"===n)return o(),void At("bold");if("i"===n)return o(),void At("italic");if("u"===n)return o(),void At("underline");if("Enter"===e.key)return o(),void Ut()}}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&&Nt(()=>on(e.closest("table"),e,!0))})(r,!e.shiftKey);if(n?.closest("li"))return o(),void Tt(!e.shiftKey);if(!e.shiftKey)return o(),void At("insertText","\t")}},children:[cn("style",{children:i(m,$)}),cn("input",{ref:M,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:e=>{e.target.files?.length&&Ht(Array.from(e.target.files)),e.target.value=""}}),cn(Be,{onClose:C,fileMenu:An,name:g,saveState:k?le(mt.state,ut.save):{tone:b?"off-unsaved":"off",label:b?N.noStoreEdited:N.noStoreClean},canUndo:V.undo,canRedo:V.redo,onUndo:kt,onRedo:St,exportControl:cn(pe,{"aria-label":N.export,align:"end",items:$n,triggerClassName:"docs-export-trigger",trigger:dn(sn,{children:[cn(de,{name:"download",size:16}),N.export]})})}),Ne&&dn("div",{className:"docs-conflict",role:"alert",children:[cn("span",{children:N.conflict}),cn(ue,{variant:"secondary",onClick:S,children:N.reload})]}),dn("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[cn(pe,{trigger:N.menuInsert,items:Ln,align:"start",triggerClassName:Dn}),cn(ge,{open:Pe,onOpenChange:je,align:"start",triggerLabel:N.table,triggerClassName:"h-5 w-0 overflow-hidden",trigger:cn("span",{}),children:dn("div",{className:"p-1",children:[cn("div",{className:"mb-1 text-xs text-ink-muted",children:De.rows?N.tableSize(De.cols,De.rows):N.table}),cn("div",{className:"grid gap-0.5",style:{gridTemplateColumns:"repeat(8, 1fr)"},onMouseLeave:()=>Oe({rows:0,cols:0}),children:Array.from({length:48},(e,t)=>{const n=Math.floor(t/8)+1,r=t%8+1,o=n<=De.rows&&r<=De.cols;return cn("button",{type:"button","aria-label":N.tableSize(r,n),onMouseEnter:()=>Oe({rows:n,cols:r}),onFocus:()=>Oe({rows:n,cols:r}),onClick:()=>Wt(n,r),className:"h-4 w-4 rounded-sm border "+(o?"border-accent-fill bg-accent-tint-strong":"border-line bg-surface")},t)})})]})}),cn(pe,{trigger:N.menuLayout,items:Tn,align:"start",triggerClassName:Dn}),Fn,In(N.print,cn(de,{name:"print",size:16}),Nn),In(N.find,cn(de,{name:"search",size:16}),()=>We?Qt():Yt(),{pressed:We}),Fn,Hn(N.paragraphStyle,(e=>{if(!e)return N.styleNormal;const t=m.styles.find(t=>t.id===e);return t?Mn[t.name]??t.name:e})(K.styleId),En,"w-20"),Hn(N.font,K.font||m.defaultFont||"Calibri",zn,"w-20"),Hn(N.fontSize,K.size??m.defaultSize??11,Rn),Fn,In(N.bold,cn(de,{name:"bold",size:16}),()=>At("bold"),{pressed:K.bold}),In(N.italic,cn(de,{name:"italic",size:16}),()=>At("italic"),{pressed:K.italic}),In(N.underline,cn(de,{name:"underline",size:16}),()=>At("underline"),{pressed:K.underline}),In(N.strikethrough,cn(de,{name:"strike",size:16}),()=>At("strikeThrough"),{pressed:K.strike}),In(N.superscript,cn(de,{name:"superscript",size:16}),()=>At("superscript"),{pressed:K.sup}),In(N.subscript,cn(de,{name:"subscript",size:16}),()=>At("subscript"),{pressed:K.sub}),Bn(N.textColor,cn(de,{name:"text-color",size:14}),Un.foreColor,Dt,"foreColor"),Bn(N.highlight,cn(de,{name:"palette",size:14}),Un.hiliteColor,Ot,"hiliteColor"),In(N.clearFormatting,cn(de,{name:"clear-marks",size:16}),()=>Nt(()=>{document.execCommand("removeFormat");for(const e of lt())e.style.removeProperty("text-align"),e.style.removeProperty("line-height"),e.style.removeProperty("margin-left")})),Fn,In(N.bulletedList,cn(de,{name:"list",size:16}),()=>$t("insertUnorderedList"),{pressed:K.ul}),In(N.numberedList,cn(de,{name:"numbered-list",size:16}),()=>$t("insertOrderedList"),{pressed:K.ol}),In(N.decreaseIndent,cn(de,{name:"chevron-double-left",size:16}),()=>Tt(!1)),In(N.increaseIndent,cn(de,{name:"chevron-double-right",size:16}),()=>Tt(!0)),Fn,In(N.alignLeft,cn(de,{name:"align-left",size:16}),()=>Mt("left"),{pressed:"left"===K.align}),In(N.alignCenter,cn(de,{name:"align-center",size:16}),()=>Mt("center"),{pressed:"center"===K.align}),In(N.alignRight,cn(de,{name:"align-right",size:16}),()=>Mt("right"),{pressed:"right"===K.align}),In(N.justify,cn(de,{name:"align-justify",size:16}),()=>Mt("justify"),{pressed:"justify"===K.align}),cn(pe,{"aria-label":N.lineSpacing,align:"start",items:Pn,triggerClassName:On,trigger:dn("span",{title:N.lineSpacing,className:"flex items-center gap-0.5",children:[cn(de,{name:"line-spacing",size:16}),cn(de,{name:"chevron-down",size:12})]})})]}),ze&&_n.length>0&&dn("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:[cn(de,{name:"info",size:14}),cn("span",{className:"min-w-0 flex-1",children:N.noticeLead(_n)}),cn(he,{size:"sm",variant:"ghost",ink:"inherit","aria-label":N.dismiss,title:N.dismiss,onClick:()=>Re(!1),children:cn(de,{name:"close",size:14})})]}),We&&cn(Et,{query:Ke,replacement:Ve,matchCase:Xe,current:Je,total:_e,onQuery:e=>{Ge(e),Vt(e,Xe,0)},onReplacement:Qe,onMatchCase:e=>{Ye(e),Vt(Ke,e,0)},onStep:e=>{const t=tt.current.length;if(!t)return;const n=(Je+(e?1:-1)+t)%t;Ze(n),Kt(n,!0)},onReplace:()=>{const e=tt.current[Je];e&&(z.current.record(bt()),l(e,Ve),wt(),Vt(Ke,Xe,Je))},onReplaceAll:()=>{const e=tt.current;if(e.length){z.current.record(bt());for(let t=e.length-1;t>=0;t--)l(e[t],Ve);wt(),ke.success(N.replacedCount(e.length)),Vt(Ke,Xe,0)}},onClose:Qt}),dn("div",{className:"docs-body",children:[dn("div",{className:"docs-centre",children:[cn("div",{className:"min-h-0 flex-1 overflow-auto bg-surface-sunken px-6 py-6",children:dn("div",{className:"docs-sheet relative mx-auto shadow",style:{width:`${Vn}pt`,zoom:$e/100,minHeight:W.page.height/20+"pt"},children:[W.header&&dn("div",{className:"pointer-events-none absolute flex justify-between gap-4 text-xs","aria-hidden":"true",style:{top:W.page.header/20+"pt",left:W.page.left/20+"pt",right:W.page.right/20+"pt"},children:[cn("span",{children:Jn(Xn[0],1)}),void 0!==Xn[1]&&cn("span",{children:Jn(Xn[1],1)})]}),cn("div",{ref:T,contentEditable:!0,suppressContentEditableWarning:!0,spellCheck:!0,lang:m.lang,role:"textbox","aria-multiline":"true","aria-label":f,"data-doc":$,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=s(n);for(const e of Array.from(t.querySelectorAll("img"))){const t=e.getAttribute("src")??"";if(t.startsWith("blob:")&&!p.has(t))try{const e=await(await fetch(t)).blob();p.set(t,{bytes:new Uint8Array(await e.arrayBuffer()),mime:e.type})}catch{e.remove()}}return void At("insertHTML",t.innerHTML)}t.length&&(e.preventDefault(),Ht(t))})(e)},onClick:e=>{const t=e.target;if("IMG"===t.tagName&&null===t.closest('[contenteditable="false"]')&&!t.getAttribute("contenteditable"))return e.preventDefault(),void Ie({x:e.clientX,y:e.clientY,el:t});const n=t.closest("a");if(n&&(e.metaKey||e.ctrlKey)){const e=n.getAttribute("href")??"";gn.test(e)&&window.open(e,"_blank","noopener,noreferrer")}},onContextMenu:e=>{const t=e.target.closest?.("td,th");t&&!e.shiftKey&&!t.closest("[data-locked]")&&rt(t)&&(e.preventDefault(),Ue({x:e.clientX,y:e.clientY,cell:t}))},className:"docs-page",style:{paddingTop:`${Qn}pt`,paddingRight:W.page.right/20+"pt",paddingBottom:W.page.bottom/20+"pt",paddingLeft:W.page.left/20+"pt",minHeight:W.page.height/20+"pt",boxSizing:"border-box"}}),J.slice(1).map((e,t)=>cn("div",{className:"docs-sheet-line pointer-events-none absolute left-0 right-0 border-t border-dashed","aria-hidden":"true",style:{top:`calc(${Qn}pt + ${e}px)`},children:cn("span",{className:"docs-sheet absolute right-1 -top-2 px-1 text-2xs",children:N.pageLabel(t+2)})},e)),W.footer&&dn("div",{className:"pointer-events-none absolute flex justify-between gap-4 text-xs","aria-hidden":"true",style:{bottom:W.page.footer/20+"pt",left:W.page.left/20+"pt",right:W.page.right/20+"pt"},children:[cn("span",{children:Jn(Yn[0],J.length)}),void 0!==Yn[1]&&cn("span",{children:Jn(Yn[1],J.length)})]})]})}),dn("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:[cn("span",{children:N.pageOf(Math.min(X.pageNow,J.length),J.length)}),cn("span",{children:N.wordCount(X.words)}),cn("span",{children:Kn}),Gn&&cn("span",{children:Gn}),dn("span",{className:"ml-auto flex items-center gap-1",children:[cn(ue,{size:"sm",variant:"ghost","aria-label":N.zoomOut,onClick:()=>Le(e=>[...pn].reverse().find(t=>t<e)??e),children:"−"}),dn("span",{className:"w-9 text-center tabular-nums",children:[$e,"%"]}),cn(ue,{size:"sm",variant:"ghost","aria-label":N.zoomIn,onClick:()=>Le(e=>pn.find(t=>t>e)??e),children:"+"})]})]})]}),cn(Ee,{page:W.page,onPage:e=>{q(t=>({...t,page:e})),wt()},onMorePageSetup:()=>Me(!0),colour:K.color,onColour:e=>{G(t=>({...t,color:e})),Wn(t=>({...t,foreColor:e})),U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{U.current=null,At("foreColor",e)},150)},outline:_,onHeading:e=>{const t=T.current;t&&jt(t)[e]?.scrollIntoView({block:"start"})}})]}),Te&&cn(Xt,{value:W,headerEditable:m.header.editable,footerEditable:m.footer.editable,onClose:()=>Me(!1),onApply:e=>{q(e),Me(!1),wt()}}),Fe&&dn(we,{minWidth:150,portal:!0,style:{position:"fixed",left:Fe.x,top:Fe.y},onClose:()=>Ie(null),children:[cn(ye,{children:N.imageWidth}),cn(ve,{onClick:()=>qt(.25),children:"25%"}),cn(ve,{onClick:()=>qt(.5),children:"50%"}),cn(ve,{onClick:()=>qt(.75),children:"75%"}),cn(ve,{onClick:()=>qt(1),children:"100%"}),cn(ve,{onClick:()=>qt(null),children:N.imageOriginalSize}),cn(be,{}),cn(ve,{danger:!0,onClick:()=>{if(!Fe)return;const e=Fe.el;Nt(()=>{e.remove()}),Ie(null)},children:N.imageRemove})]}),He&&cn(fe,{at:{x:He.x,y:He.y},owner:He.cell,onClose:()=>Ue(null),items:(e=>{const t=e.closest("table"),n=(e,t,n,r={})=>({key:e,label:t,onSelect:()=>Nt(n),...r}),r=(e=>{const t=R.current;return t?Array.from(e.querySelectorAll("td,th")).filter(n=>n.closest("table")===e&&t.intersectsNode(n)):[]})(t);return[n("above",N.rowAbove,()=>on(t,e,!1)),n("below",N.rowBelow,()=>on(t,e,!0)),n("left",N.columnLeft,()=>an(t,e,!1)),n("right",N.columnRight,()=>an(t,e,!0)),{type:"divider",key:"d1"},n("merge",N.mergeCells,()=>{(function(e,t){if(t.length<2)return!1;const n=tn(e);let r=1/0,o=1/0,a=-1,i=-1;for(const e of t){const t=nn(n,e);if(!t)return!1;r=Math.min(r,t.row),o=Math.min(o,t.col),a=Math.max(a,t.row+en(e,"rowspan")-1),i=Math.max(i,t.col+en(e,"colspan")-1)}const l=new Set;for(let e=r;e<=a;e++)for(let t=o;t<=i;t++){const r=n.slots[e]?.[t];r&&l.add(r)}for(const e of l){const t=nn(n,e);if(t.row<r||t.col<o||t.row+en(e,"rowspan")-1>a||t.col+en(e,"colspan")-1>i)return!1}const s=n.slots[r][o];for(const e of l)if(e!==s){if((e.textContent??"").trim())for(;e.firstChild;)s.appendChild(e.firstChild);e.remove()}return s.setAttribute("colspan",String(i-o+1)),s.setAttribute("rowspan",String(a-r+1)),i===o&&s.removeAttribute("colspan"),a===r&&s.removeAttribute("rowspan"),!0})(t,r)||ke.error(N.mergeFailed)},{disabled:r.length<2}),{type:"submenu",key:"shade",label:N.cellShading,items:[...Ft.map(t=>({key:t,label:dn("span",{className:"flex items-center gap-2",children:[cn("span",{className:"h-3 w-5 rounded-sm border border-line",style:{background:t}}),t.toUpperCase()]}),onSelect:()=>Nt(()=>{for(const n of r.length?r:[e])n.style.backgroundColor=t})})),{key:"none",label:N.noColor,onSelect:()=>Nt(()=>{for(const t of r.length?r:[e])t.style.removeProperty("background-color")})}]},{type:"divider",key:"d2"},n("delRow",N.deleteRow,()=>{!function(e,t){const n=tn(e),r=nn(n,t);if(!r)return!1;const o=_t(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 i=en(t,"rowspan");if(1!==i)if(t.parentElement===o[r.row]){const a=o[r.row+1],l=n.slots[r.row+1].slice(e+en(t,"colspan")).find(e=>e.parentElement===a);t.setAttribute("rowspan",String(i-1)),a.insertBefore(t,l??null)}else t.setAttribute("rowspan",String(i-1))}o[r.row].remove()}(t,e)}),n("delCol",N.deleteColumn,()=>{!function(e,t){const n=tn(e),r=nn(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=en(t,"colspan");n>1?t.setAttribute("colspan",String(n-1)):t.remove()}ln(e,n.cols-1,null,r.col)}(t,e)}),n("delTable",N.deleteTable,()=>{t.remove()},{danger:!0})]})(He.cell)})]})}function vn({label:e,hint:t}){return dn("span",{className:"flex w-full items-center justify-between gap-4",children:[cn("span",{children:e}),cn("span",{className:"text-2xs text-ink-faint",children:t})]})}import{useEffect as yn,useRef as xn,useState as Cn}from"react";import{Icon as kn}from"efficient-shell/icons";import{Button as Sn,IconButton as Nn,registerModalEscapeInterceptor as An,toast as $n}from"efficient-shell/ui";var Ln={LF:"\n",CRLF:"\r\n",CR:"\r"};function Tn(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 Mn(e){let t=1;for(let n=e.indexOf("\n");n>=0;n=e.indexOf("\n",n+1))t++;return t}import{jsx as En,jsxs as zn}from"react/jsx-runtime";function Rn({filename:e,decoded:t,bytes:n,fileEntries:r,title:o,dirty:a,onDirty:i,onOpenFile:l,onClose:s}){const c=u(),d=xn(null),m=xn(null),f=xn(t.text),p=xn(!1),[h,g]=Cn(!0),[w,b]=Cn(!1),[v,y]=Cn({line:1,col:1,lines:Mn(t.text)}),[x,C]=Cn(!1),[k,S]=Cn(""),[N,A]=Cn(""),[$,L]=Cn(!1),[T,M]=Cn(0),[E,z]=Cn([]),R=()=>m.current?.value??"",P=xn(null),[j,D]=Cn(0),O=()=>{P.current&&m.current&&(P.current.scrollTop=m.current.scrollTop,P.current.scrollLeft=m.current.scrollLeft)};yn(()=>{const e=P.current?.querySelector("[data-current]"),t=m.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)),O()},[j,T,E,h]);const F=()=>{const e=m.current;e&&y({...Tn(e.value,e.selectionStart),lines:Mn(e.value)})},I=(e=k,t=$)=>{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,i=[];for(let e=a.indexOf(o);e>=0;e=a.indexOf(o,e+Math.max(o.length,1)))i.push(e);return i}(R(),e,t);return z(n),n},H=(e,t,n=k)=>{const r=m.current;if(!r||!e.length)return;const o=(t%e.length+e.length)%e.length;M(o),r.setSelectionRange(e[o],e[o]+n.length),D(e=>e+1)},B=()=>{xt(p.current?function(e,t,n){const r=e.replace(/\n/g,Ln[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):n,e,"text/plain"),p.current&&"windows-1252"===t.encoding&&$n.info(c.savedAsUtf8),f.current=R(),i(!1)},U=()=>{p.current=!0,b(!0),i(R()!==f.current),F(),x&&I()},W=e=>{document.execCommand("insertText",!1,e)||m.current?.setRangeText(e,m.current.selectionStart,m.current.selectionEnd,"end"),U()},q=e=>{m.current?.focus(),document.execCommand(e)},K=()=>{C(!1),m.current?.focus()};yn(()=>{m.current?.focus(),m.current?.setSelectionRange(0,0)},[]);const G=xn(x);G.current=x,yn(()=>An(()=>!(!G.current||!d.current?.contains(document.activeElement))&&(K(),!0)),[]);const V=[...r,{type:"divider",key:"d1"},{key:"save",label:c.saveKeepType,onSelect:B}],Q=a?c.noStoreEdited:c.noStoreClean;return zn("div",{ref:d,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(),C(!0);const t=m.current,n=t?t.value.slice(t.selectionStart,t.selectionEnd):"";n&&!n.includes("\n")&&(S(n),I(n))}else"Tab"!==e.key||t||e.shiftKey||e.target!==m.current||(e.preventDefault(),W("\t"))},children:[En(Be,{onClose:s,fileMenu:V,name:o,saveState:{tone:a?"off-unsaved":"off",label:Q},canUndo:w,canRedo:w,onUndo:()=>q("undo"),onRedo:()=>q("redo"),exportControl:En(Sn,{variant:"secondary",leftIcon:En(kn,{name:"download",size:16}),onClick:B,children:c.export})}),zn("div",{className:"flex shrink-0 flex-wrap items-center gap-0.5 border-b border-line bg-surface-sunken px-2 py-1",children:[En(Nn,{size:"sm",variant:"ghost","aria-label":c.find,title:c.find,"aria-pressed":x,onClick:()=>C(e=>!e),children:En(kn,{name:"search",size:16})}),En(Nn,{size:"sm",variant:"ghost","aria-label":c.wrapLines,title:c.wrapLines,"aria-pressed":h,onClick:()=>g(e=>!e),children:En(kn,{name:"wrap",size:16})})]}),x&&En(Et,{query:k,replacement:N,matchCase:$,current:T,total:E.length,onQuery:e=>{S(e);const t=I(e);M(0),H(t,0,e)},onReplacement:A,onMatchCase:e=>{L(e);const t=I(k,e);M(0),H(t,0)},onStep:e=>H(E,T+(e?1:-1)),onReplace:()=>{const e=m.current;if(!e||!E.length)return;e.focus(),e.setSelectionRange(E[T],E[T]+k.length),W(N);const t=I();H(t,T)},onReplaceAll:()=>{const e=m.current;if(!e||!E.length)return;const t=E.length;e.focus();for(let t=E.length-1;t>=0;t--)e.setSelectionRange(E[t],E[t]+k.length),W(N);I(),M(0),$n.success(c.replacedCount(t))},onClose:K}),zn("div",{className:"relative min-h-0 flex-1 bg-surface",children:[x&&k&&E.length>0&&E.length<=2e3&&En("div",{ref:P,"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 E.forEach((r,o)=>{t.push(e.slice(n,r)),n=r+k.length,t.push(En("mark",{...o===T?{"data-current":""}:{},className:"rounded-sm text-transparent "+(o===T?"bg-status-warning-line":"bg-status-warning-soft"),children:e.slice(r,n)},r))}),t.push(e.slice(n)),t})()}),En("textarea",{ref:m,defaultValue:t.text,"aria-label":e,spellCheck:!1,wrap:h?"soft":"off",onInput:U,onSelect:F,onKeyUp:F,onClick:F,onScroll:O,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")})]}),zn("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:[En("span",{children:e}),En("span",{children:c.lineColumn(v.line,v.col)}),En("span",{children:c.lineCount(v.lines)}),En("span",{children:t.eol})]})]})}import{jsx as Pn,jsxs as jn}from"react/jsx-runtime";var Dn=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"]),On=["docx"],Fn=`${Array.from(Dn,e=>`.${e}`).join(",")},.docx,text/*`,In=/^<!doctype html><meta charset="utf-8"><title>[^<]*<\/title>(?!<body style="font-family:ui-monospace)/,Hn=()=>"undefined"!=typeof navigator&&navigator.language||"en-AU";function Bn({value:e,onRename:t}){const n=u(),[r,o]=G(e);return q(()=>o(e),[e]),Pn("div",{className:"docs-title",children:Pn(J,{"aria-label":n.documentName,value:r,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()},onBlur:()=>{const n=r.trim();o(n||e),n&&n!==e&&t(n)}})})}function Un({documentId:e,onClose:t}){const n=u(),{store:r,canCreate:o=!0,canDelete:a=!0,chooseFile:i}=d(),[l,s]=G(null),[c,p]=G(null);if(!r||e)return Pn(Wn,{documentId:e,onClose:t});if(l)return Pn(Wn,{documentId:l.id,initialFile:l.file,onClose:()=>s(null)},l.key);return Pn(m,{words:{windowTitle:n.filesHeading,heading:n.filesHeading,newFile:n.newFile,emptyTitle:n.filesEmptyTitle,emptyBody:n.filesEmptyBody,deleteConfirm:n.deleteConfirm,createFailed:n.createFailed,deleteFailed:n.deleteFailed},files:n.files,list:r.list,create:()=>r.create(n.untitled),rename:r.rename,remove:r.remove,canCreate:o,canDelete:a,accept:Fn,choose:i&&{run:i,request:{title:n.files.choosing(n.fileKind,n.filesHeading),extensions:On}},onOpen:e=>s({key:Date.now(),id:e}),onOpenFile:(e,t)=>{U(e.name,On)?c||(p(n.files.opening(e.name)),f(r,e).then(async r=>{const o=await W(t,r.id);ee.success(n.files.savedCopy(r.title,e.name,o?t?.location:void 0)),s({key:Date.now(),id:r.id})}).catch(()=>ee.error(n.files.openFailed(e.name))).finally(()=>p(null))):s({key:Date.now(),file:e})},busy:c})}function Wn({documentId:e,onClose:t,initialFile:n}){const r=u(),{store:o}=d(),a=o&&e?e:null,i=K([]),l=K(0),c=K(null),m={textBox:r.objectTextBox,chart:r.objectChart,diagram:r.objectDiagram,equation:r.objectEquation,picture:r.objectPicture,object:r.objectOther,contents:r.objectField},f=e=>({labels:m,imageUrl:(t,n)=>{const r=URL.createObjectURL(new Blob([t],{type:n}));return i.current.push(r),e.set(r,{bytes:t,mime:n}),r}}),p=e=>{const t=new Map;return{key:++l.current,kind:"rich",filename:e,images:t,doc:g($(Hn()),null,f(t))}},[b,v]=G(()=>a?null:p(r.untitled)),[y,x]=G(!1),[C,k]=G(0),[S,N]=G(!1),[A,L]=G(!1),[T,M]=G(!1);Q(T),q(()=>()=>{i.current.forEach(e=>URL.revokeObjectURL(e))},[]),q(()=>{if(!o||!a)return;let e=!0;return x(!1),(async()=>{const t=await o.get(a),n=new Map,r=t.bytes?.length?await h(t.bytes,f(n)):g($(Hn()),null,f(n));e&&E({key:++l.current,kind:"rich",doc:r,images:n,filename:t.title,stored:{id:t.id,version:t.version}})})().catch(()=>{e&&x(!0)}),()=>{e=!1}},[o,a,C]);const E=e=>{const t=i.current;if(i.current=[],"rich"===e.kind)for(const t of e.images.keys())i.current.push(t);v(e),M(!1),setTimeout(()=>t.filter(e=>!i.current.includes(e)).forEach(e=>URL.revokeObjectURL(e)),0)},z=async()=>!T||_({title:r.discardTitle(b?.filename??""),message:r.discardMessage,confirmLabel:r.discard,cancelLabel:r.keepEditing}),R=async e=>{if(!await z())return;const t=(e.name.split(".").pop()||"").toLowerCase();N(!0);try{if("docx"===t){const t=new Map,n=new Uint8Array(await e.arrayBuffer());try{const r=await h(n,f(t));E({key:++l.current,kind:"rich",doc:r,filename:e.name,images:t})}catch{ee.error(r.cannotRead(e.name))}}else if("doc"===t)ee.error(r.legacyDoc);else if(Dn.has(t)||e.type.startsWith("text/")){const n=new Uint8Array(await e.arrayBuffer()),o=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,i=r>o&&r>=a?"CRLF":a>o?"CR":"LF";return{text:t.replace(/\r\n?/g,"\n"),encoding:n,eol:i}}(n);if("html"!==t&&"htm"!==t||!In.test(o.text))E({key:++l.current,kind:"text",decoded:o,bytes:n,filename:e.name});else{const t=new Map,n=g($(Hn()),null,f(t));n.html=s(o.text)||n.html,w(n),E({key:++l.current,kind:"rich",doc:n,images:t,filename:e.name.replace(/\.[^.]+$/,".docx"),imported:!0}),ee.info(r.openedOldSave)}}else ee.error(r.unsupported(t))}finally{N(!1)}};q(()=>{n&&R(n)},[]);const P=async()=>{await z()&&(M(!1),c.current?.click())},j="rich"===b?.kind&&!!b.stored,D=()=>ee.info(r.openFromFiles),O=[{key:"new",label:r.newDocument,onSelect:()=>{(async()=>{await z()&&E(p(r.untitled))})()}},{key:"open",label:jn("span",{className:"flex w-full items-center justify-between gap-4",children:[Pn("span",{children:r.open}),Pn("span",{className:"text-2xs text-ink-faint",children:"⌘O"})]}),onSelect:()=>{P()}}],F=b&&Pn(Bn,{value:b.filename,onRename:e=>{const t=b?.filename??e;v(t=>t?{...t,filename:e}:t),o&&"rich"===b?.kind&&b.stored&&o.rename(b.stored.id,e).catch(()=>{ee.error(r.renameFailed),v(e=>e?{...e,filename:t}:e)})}});return jn("div",{className:"relative flex h-full flex-col bg-surface text-ink",onDragOver:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),A||L(!0))},onDragLeave:e=>{e.currentTarget===e.target&&L(!1)},onDrop:e=>{if(!e.dataTransfer.types.includes("Files"))return;e.preventDefault(),L(!1);const t=Array.from(e.dataTransfer.files??[]);"rich"===b?.kind&&t.length&&t.every(e=>e.type.startsWith("image/"))?window.dispatchEvent(new CustomEvent("docs-insert-images",{detail:{key:b.key,files:t}})):t[0]&&j?D():t[0]&&R(t[0])},children:[b&&Pn(V,{title:`${I=b.filename,I.length>24?`${I.slice(0,23)}…`:I}${T?" •":""} - Documents`}),Pn("input",{ref:c,type:"file",accept:Fn,className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&R(t),e.target.value=""}}),y?Pn("div",{className:"docs-open-failed",children:Pn(Y,{title:r.openFailed,children:t&&Pn(X,{onClick:t,children:r.backToFiles})})}):S||!b?Pn(Z,{size:"sm",padding:"",className:"h-full",label:r.loading}):"rich"===b.kind?Pn(bn,{sessionKey:b.key,doc:b.doc,filename:b.filename,images:b.images,fileEntries:j?[]:O,title:F,startsDirty:b.imported,dirty:T,onDirty:M,onOpenFile:()=>{j?D():P()},onNewImageUrl:e=>{i.current.push(e)},onClose:t,stored:o&&b.stored?{store:o,...b.stored}:void 0,onReload:()=>{M(!1),v(null),k(e=>e+1)}},b.key):Pn(Rn,{filename:b.filename,decoded:b.decoded,bytes:b.bytes,fileEntries:O,title:F,dirty:T,onDirty:M,onOpenFile:()=>{P()},onClose:t},b.key),A&&Pn("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:Pn("div",{className:"rounded-md bg-accent-fill px-4 py-2 text-sm font-medium text-on-accent",children:r.dropHint})})]});var I}function qn({id:e,onClose:t}){return Pn(Un,{documentId:e,onClose:t})}export{qn as OpenDocument,Un as default};