efficient-office 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Documents-CVV64UEH.js → Documents-ISV66NLW.js} +1 -1
- package/dist/Slides-JI73C3NW.js +1 -0
- package/dist/SlidesEditor-5WCXE27J.js +1 -0
- package/dist/{Spreadsheet-55AVNUEA.js → Spreadsheet-I3RO4HSS.js} +1 -1
- package/dist/chunk-3RFDQOTI.js +1 -0
- package/dist/{chunk-QFPW3KLL.js → chunk-6ZFEBY6H.js} +1 -1
- package/dist/chunk-B2X3NIQR.js +1 -0
- package/dist/{chunk-OB4MLAZC.js → chunk-BGAR3P46.js} +1 -1
- package/dist/{chunk-RLNXQG4T.js → chunk-MDG2ADZ7.js} +1 -1
- package/dist/chunk-PMGQ5GUH.js +1 -0
- package/dist/chunk-PXOQN7D6.js +1 -0
- package/dist/chunk-Q7NVDOCX.js +1 -0
- package/dist/deckPdf-4RC7QJ45.js +1 -0
- package/dist/documents/index.js +1 -1
- package/dist/pptxImport-Y7TB6PYP.js +1 -0
- package/dist/slides/index.d.ts +501 -6
- package/dist/slides/index.js +1 -1
- package/dist/slides/slides.css +79 -0
- package/dist/spreadsheet/index.js +1 -1
- package/package.json +1 -1
- package/dist/Slides-JMP36AJH.js +0 -1
- package/dist/SlidesEditor-MZM7IR46.js +0 -1
- package/dist/chunk-2AKHYM66.js +0 -1
- package/dist/chunk-2TZUCKZ7.js +0 -1
- package/dist/chunk-A5KQPSPX.js +0 -1
- package/dist/chunk-X6F3Z4KZ.js +0 -1
- package/dist/deckPdf-Y2RE7MFX.js +0 -1
- package/dist/pptxImport-STLMOUNE.js +0 -1
|
@@ -1 +1 @@
|
|
|
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-A5KQPSPX.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(/["']|"/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};
|
|
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(/["']|"/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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{FileList as e}from"./chunk-PMGQ5GUH.js";import{importDeckFile as t}from"./chunk-6ZFEBY6H.js";import{PptxPasswordError as n,PptxUnreadableError as i}from"./chunk-MDG2ADZ7.js";import{STARTERS as s,starterDeck as l}from"./chunk-Q7NVDOCX.js";import{useSlidesHost as o,useSlidesWords as r}from"./chunk-BGAR3P46.js";import{SlideView as a}from"./chunk-B2X3NIQR.js";import"./chunk-PXOQN7D6.js";import"./chunk-B32ASXHM.js";import{placeCopy as c}from"./chunk-XYVQTQ6N.js";import{lazy as d,Suspense as m,useCallback as p,useEffect as u,useState as h}from"react";import{Button as f,EmptyState as k,IconButton as y,toast as b}from"efficient-shell/ui";import{Icon as N}from"efficient-shell/icons";import{jsx as v,jsxs as C}from"react/jsx-runtime";var w=e=>({title:e.placeholderTitle,subtitle:e.placeholderSubtitle,body:e.placeholderBody,dealerPitch:e.dealerPitch,monthlyReport:e.monthlyReport}),F=d(()=>import("./SlidesEditor-5WCXE27J.js")),j=["pptx"];function D({id:e,onClose:t,note:n}){const i=r(),{store:s}=o(),[l,a]=h(null),[c,d]=h(!1),[b,w]=h(n??null),j=p(()=>{s.get(e).then(e=>a(t=>({deck:e,nonce:(t?.nonce??0)+1})),()=>d(!0))},[e,s]);if(u(j,[j]),c)return v("div",{className:"slides-list-empty",children:v(k,{title:i.openFailed,children:v(f,{onClick:t,children:i.backToDecks})})});if(!l)return null;const D=v(m,{fallback:null,children:v(F,{deck:l.deck,onClose:t,onReload:j},l.nonce)});return b?C("div",{className:"slides-with-note",children:[C("div",{className:"slides-import-note",role:"status",children:[v(N,{name:"info",size:16}),v("span",{children:b}),v(y,{"aria-label":i.dismiss,onClick:()=>w(null),children:v(N,{name:"close",size:14})})]}),v("div",{className:"slides-with-note-body",children:D})]}):D}function P(){const d=r(),{store:m,canCreate:u=!0,canDelete:f=!0,chooseFile:k,storeImage:y}=o(),[N,F]=h(null),[P,g]=h(null),x=p(()=>m.list(),[m]);if(N)return v(D,{id:N.id,note:N.note,onClose:()=>F(null)});const B=u&&v("div",{className:"slides-starters","aria-label":d.startFrom,role:"group",children:s.map(e=>{const t="blank"===e?null:l(e,w(d));return C("button",{type:"button",className:"slides-starter",disabled:!!P,onClick:()=>{(async e=>{if(!P)try{const t=await m.create("blank"===e?d.untitledDeck:d.starterName(e));"blank"!==e&&await m.save(t.id,l(e,w(d)),t.version),F({id:t.id})}catch{b.error(d.createFailed)}})(e)},children:[v("span",{className:"slides-starter-thumb",children:t?v(a,{slide:t.slides[0],width:128}):v("span",{className:"slides-starter-blank"})}),v("span",{children:d.starterName(e)})]},e)})});return v(e,{extra:B,words:{windowTitle:d.slidesPanel,heading:d.decks,newFile:d.newDeck,emptyTitle:d.emptyTitle,emptyBody:d.emptyBody,deleteConfirm:d.deleteConfirm,createFailed:d.createFailed,deleteFailed:d.deleteFailed},files:d.files,list:x,create:()=>m.create(d.untitledDeck),rename:m.rename,remove:m.remove,canCreate:u,canDelete:f,accept:".pptx,application/vnd.openxmlformats-officedocument.presentationml.presentation",choose:k&&{run:k,request:{title:d.files.choosing(d.fileKind,d.slidesPanel),extensions:j}},onOpen:e=>F({id:e}),onOpenFile:(e,s)=>{if(P)return;const l=d.files.opening(e.name);g(l),t(m,e,{storeImage:y,onProgress:e=>g(`${l} ${Math.round(100*e)}%`)}).then(async t=>{const n=await c(s,t.id);b.success(d.files.savedCopy(t.title,e.name,n?s?.location:void 0)),F({id:t.id,note:d.importNotes({skipped:t.notes.skipped,animations:t.notes.animationsDropped,fonts:t.notes.fontsReplaced})})}).catch(t=>{b.error(t instanceof n?d.pptxPasswordProtected:t instanceof i?t.message:d.files.openFailed(e.name))}).finally(()=>g(null))},busy:P})}export{D as OpenDeck,P as default,w as starterWords};
|