@betteroffice/pptx-react 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import {c,b,a as a$3}from'./chunk-EC75NVX7.js';import {a}from'./chunk-ZGEHLLWI.js';import {G,F}from'./chunk-HJN2B5PX.js';import'./chunk-BNLMNYZQ.js';import'./chunk-4TRQLEZF.js';import {e}from'./chunk-3WH2K5EA.js';import {d as d$1,J,p,o,M}from'./chunk-LFHLWZA4.js';import {d,a as a$1,b as b$1}from'./chunk-52U7UPKN.js';import'./chunk-PSW72ZJN.js';import'./chunk-PS7ULZVL.js';import {a as a$2}from'./chunk-O2XFH626.js';import {useEffect,useMemo,useState,useRef,useCallback,useLayoutEffect}from'react';import {sizeCanvasForSlide,paintSlide,openPresentationSession,createPptxWorkerEditorSession,PptxWorkerEditorDisposedError}from'@betteroffice/pptx';import {jsx,jsxs}from'react/jsx-runtime';var Ce={open:openPresentationSession};function Q(i,e,t){return !!i&&i===t&&i.slideIndex===e}var X=class{constructor(e,t,n,c,p,u=()=>true){a$2(this,"session",e);a$2(this,"changed",n);a$2(this,"report",c);a$2(this,"onReady",p);a$2(this,"isCurrent",u);a$2(this,"alive",true);a$2(this,"failed",false);a$2(this,"active");a$2(this,"navigation",0);a$2(this,"images",a$3());a$2(this,"visible",new Set);a$2(this,"cache",new Map);a$2(this,"pending",new Set);a$2(this,"waiters",new Set);a$2(this,"running",false);a$2(this,"painted");a$2(this,"ready",false);this.active=Math.max(0,Math.min(e.state.slides.length-1,Number.isInteger(t)?t-1:0));}get current(){return this.alive&&!this.failed&&this.isCurrent()}require(){if(!this.current)throw new Error("Presentation is no longer open");return this.session}frame(e){let t=this.session.state.slides[e]?.id;for(let[n,c]of this.cache)if(n===JSON.stringify([t,c.version]))return c}start(){this.session.state.slides.length&&this.pending.add(this.active),this.drain();}show(e){if(!this.current||!Number.isInteger(e)||e<1||e>this.session.state.slides.length)return false;if(this.active!==e-1){this.finish(false),this.active=e-1,this.navigation+=1,this.painted=void 0;let t=this.frame(this.active);if(t){let n=JSON.stringify([this.session.state.slides[this.active].id,t.version]);this.cache.delete(n),this.cache.set(n,t);}else this.pending.add(this.active);this.trim(),this.changed();}return this.drain(),true}async showAsync(e){return this.show(e)?this.painted&&this.painted===this.frame(this.active)?true:new Promise(t=>this.waiters.add(t)):false}visibility(e,t){this.current&&(t?(!this.visible.has(e)&&!this.frame(e)&&this.pending.add(e),this.visible.add(e)):(this.visible.delete(e),this.trim(),e!==this.active&&this.pending.delete(e)),this.changed(),this.drain());}didPaint(e){!this.current||!Q(e,this.active,this.frame(this.active))||(this.painted=e,this.finish(true),this.ready||(this.ready=true,this.onReady()),this.changed(),this.drain());}isPainted(e){return this.painted===e}fail(e){this.current&&(this.failed=true,this.pending.clear(),this.finish(false),this.report(e),this.changed());}dispose(){this.alive=false,this.finish(false),this.cache.clear(),this.pending.clear(),this.visible.clear(),this.painted=void 0,this.images.dispose(),this.session.dispose().catch(()=>{});}finish(e){for(let t of this.waiters)t(e);this.waiters.clear();}trim(){for(;this.cache.size>25;){let e=[...this.cache].find(([,t])=>t.slideIndex!==this.active&&!this.visible.has(t.slideIndex));if(!e)break;this.cache.delete(e[0]);}}async drain(){if(!(this.running||!this.current)){this.running=true;try{for(;this.current;){let e=this.pending.has(this.active)?this.active:this.painted===this.frame(this.active)?this.pending.values().next().value:void 0;if(e===void 0)break;if(this.pending.delete(e),!(e!==this.active&&!this.visible.has(e))&&!this.frame(e))try{let t=await this.session.call.frame(e);if(!this.current)break;if(t.slideIndex!==e)throw new Error("Unexpected slide frame");let n=this.session.state.slides[e].id;this.cache.set(JSON.stringify([n,t.version]),t),this.trim(),this.changed();}catch(t){if(!this.current)break;t instanceof Error&&t.name==="SessionSuperseded"?(e===this.active||this.visible.has(e))&&this.pending.add(e):this.fail(t);}}}finally{this.running=false;}}}};function ue(i,e,t){let n=d(i.fonts),c=useMemo(()=>({}),[i.file,i.clientId,n]),p=a$1(c),u=useRef({props:i,focus:t,fonts:n});u.current={props:i,focus:t,fonts:n};let f=useRef(0),[a,S]=useState(null),[,I]=useState(0),[L,R]=useState(null),[q,b]=useState(false),[d$1,M]=useState(null),W=useCallback(w=>{let h=w instanceof Error?w:new Error(String(w));R(h.message),u.current.props.onError?.(h);},[]);useEffect(()=>{let w=++f.current,h=false,U=false,y,T=()=>{},D=[],E=()=>!h&&w===f.current&&u.current.props.file===i.file&&u.current.fonts===n&&u.current.props.clientId===i.clientId,Y=()=>{E()&&I(r=>r+1);};return S(null),M(null),R(null),b(!!i.file),i.file&&(async()=>{try{let r=b$1(n,D,()=>E()&&!U&&(y?.current??!0),p);r.catch(()=>{});let l=await Ce.open(i.file,{fonts:n,clientId:i.clientId});if(!E()){l.dispose().catch(()=>{});return}y=new X(l,u.current.props.initialSlide,Y,v=>{E()&&W(v);},()=>{E()&&u.current.props.onReady?.(C);},E);let o=y,m=()=>o.require(),g=async v=>{if(!o.current)return null;try{let k=await v(m());return o.current?k:null}catch(k){if(!o.current)return null;throw k}},F=()=>g(async v=>({ok:!1,version:await v.call.version(),failure:{code:"read-only",message:"The editor is read-only"}})),C={handle:null,commands:e,save:()=>null,getPositionAtPoint:()=>null,selectText:()=>!1,clearSelection:()=>{},refreshProposals:()=>{},refresh:()=>{},flushPendingInput:async()=>{m();},focus:()=>{o.current&&u.current.focus();},goToSlide:v=>{let k=o.show(v);return k&&u.current.focus(),k},goToSlideAsync:async v=>{let k=await o.showAsync(v);return o.current&&k},saveAsync:()=>g(v=>v.save()),version:()=>g(v=>v.call.version()),readContent:v=>g(k=>k.call.readContent(v)),findText:v=>g(k=>k.call.findText(v)),validateEdits:F,applyEdits:F};if(T=l.onFailure(v=>o.fail(v)),l.failure&&o.fail(l.failure),await r,!E())return;S(o),b(!1),o.start();}catch(r){if(U=true,!E())return;if(y?.fail(r),!y){for(let l of D.splice(0))document.fonts.delete(l);W(r);}b(false);}})(),()=>{h=true,f.current+=1,T(),y?.dispose();for(let r of D)document.fonts.delete(r);}},[i.file,i.clientId,n,e,W,p]);let O=a?.current?a.session.state.slides[a.active]:void 0;return useEffect(()=>{if(M(null),!a?.current||!O)return;let w=false;return a.session.call.readContent({slideIds:[O.id]}).then(h=>{if(!(w||!a.current)){if(!h.ok)throw new Error(h.failure.message);M({id:O.id,text:h.slides[0]?.notes??""});}}).catch(h=>{!w&&a.current&&W(h);}),()=>{w=true;}},[a,O?.id,W]),{run:a,error:L,loading:q,reportError:W,notes:d$1?.id===O?.id?d$1?.text??"":""}}function ve(i){let{t:e$1}=d$1(),t=useRef(null),n=useRef(null),c=useRef(null),p$1=useRef(null),u=useRef(null),[f]=useState(J),[a,S]=useState("fit"),[I,L]=useState({width:0,height:0}),[R,q]=useState(he),b$1=useCallback(()=>n.current?.focus(),[]),{run:d,loading:M$1,error:W,notes:O,reportError:w}=ue(i,f.store,b$1),h=d?.current?d.frame(d.active):void 0,U=d?.navigation,y=useRef({run:d,props:i,zoom:a,loading:M$1,t:e$1,reportError:w});y.current={run:d,props:i,zoom:a,loading:M$1,t:e$1,reportError:w};let T=useRef(null),D=useMemo(()=>({environment:()=>{let{run:r,zoom:l,loading:o$1,t:m}=y.current,g=r?.session.state.slides[r.active];return {status:r?.current?"ready":o$1?"loading":"empty",readOnly:true,reviewing:false,pendingInput:false,canUndo:false,canRedo:false,slide:g??null,layouts:[],text:null,shape:null,tool:"select",zoom:l,fontFamilies:o,fontSizes:p,proposals:null,hostDisabled:F=>F==="slideshow"||F==="exportPng"||F==="tool",translate:m}},ordered:()=>false,admit:async r=>r(),perform:(r,l)=>{let{run:o,props:m,zoom:g}=y.current;if(!o?.current)return {ok:false,failure:{code:"document-replaced",message:"Presentation is no longer open"}};if(r==="zoom"){let C=l.scale;return S(C),{ok:true,status:C===g?"noop":"executed"}}if(r!=="save")return {ok:false,failure:{code:"read-only",message:"The editor is read-only"}};if(T.current?.run===o)return T.current.promise;let F=Promise.resolve().then(async()=>{if(m.onSaveRequest&&await m.onSaveRequest()!==true)return {ok:true,status:"requested"};if(!o.current)throw new Error("Presentation is no longer open");let C=await o.session.save();if(!o.current)throw new Error("Presentation is no longer open");return m.onSave?m.onSave(C):Le(C,m.fileName??"presentation.pptx"),{ok:true,status:"executed"}}).catch(C=>(o.current&&y.current.reportError(C),{ok:false,failure:{code:o.current?"command-failed":"document-replaced",message:String(C)}})).finally(()=>{T.current?.promise===F&&(T.current=null);});return T.current={run:o,promise:F},F},capture:()=>y.current.run?.current?{generation:0,viewer:y.current.run}:null,resume:r=>"viewer"in r&&r.viewer===y.current.run&&y.current.run?.current?null:"document-replaced",chrome:()=>({i18n:y.current.props.i18n}),focusEditor:b$1}),[b$1]);useLayoutEffect(()=>(f.attach(D),()=>f.detach(D)),[f,D]),useLayoutEffect(()=>f.refresh()),G({commands:f,containerRef:t,suspended:()=>false,shortcuts:i.shortcuts,onShortcutIssue:i.onShortcutIssue,unsupported:F}),useEffect(()=>{if(typeof window.matchMedia!="function")return;let r,l=()=>{let o=he();q(o),r?.removeEventListener("change",l),r=window.matchMedia(`(resolution: ${o}dppx)`),r.addEventListener("change",l);};return l(),()=>r?.removeEventListener("change",l)},[]),useEffect(()=>{let r=p$1.current;if(!r)return;let l=()=>L({width:r.clientWidth,height:r.clientHeight});l();let o=new ResizeObserver(l);return o.observe(r),()=>o.disconnect()},[]);let E=a==="fit"?!h||I.width<=0||I.height<=0?1:Math.min(Math.max(1,I.width-40)/Math.max(1,h.displayList.width),Math.max(1,I.height-40)/Math.max(1,h.displayList.height),1):a;useEffect(()=>{let r=u.current;if(!r||!h||!d?.current)return;let l=r.getContext("2d");if(!l)return;let o=false,m=()=>!o&&d.current&&d.frame(d.active)===h;return sizeCanvasForSlide(r,h.displayList,R,E),r.width<1&&(r.width=1),r.height<1&&(r.height=1),Promise.resolve().then(async()=>{if(!m())return;let g=d.images.resolve(h);try{await paintSlide(b(l,m),h.displayList,R,E,{resolveImage:g});}finally{g.release();}}).then(()=>{m()&&d.didPaint(h);}).catch(g=>{m()&&d.fail(g);}),()=>{o=true;}},[d,h,E,R,U]),useEffect(()=>{let r=c.current;if(!r||!d?.current||typeof IntersectionObserver>"u")return;let l=new IntersectionObserver(o=>{for(let m of o)d.visibility(Number(m.target.dataset.slideIndex),m.isIntersecting);},{root:r});for(let o of r.querySelectorAll("[data-slide-index]"))l.observe(o);return ()=>l.disconnect()},[d]);let Y=r=>{if(r.altKey||r.ctrlKey||r.metaKey||r.shiftKey||r.target.closest("input, textarea, select, [contenteditable]"))return;let l=["ArrowLeft","ArrowUp","PageUp"].includes(r.key),o=["ArrowRight","ArrowDown","PageDown"].includes(r.key);!l&&!o||(r.preventDefault(),d?.show(d.active+1+(l?-1:1))&&b$1());};return jsx(M.Provider,{value:f.store,children:jsxs("div",{dir:"ltr",ref:t,className:i.className,style:P.root,children:[i.showToolbar!==false&&i.toolbar!=null?jsx("div",{style:P.toolbarShell,children:jsx(e.Provider,{value:true,children:jsx("div",{style:{flex:"1 1 auto",minWidth:0},children:i.toolbar})})}):null,jsxs("div",{style:P.workspace,children:[jsx("aside",{ref:c,style:P.slideStrip,"aria-label":e$1("slides.panelLabel"),children:d?.session.state.slides.map((r,l)=>{let o=d.frame(l),m=d.visible.has(l),g=r.name||e$1("slides.fallbackTitle",{number:l+1});return jsxs("button",{type:"button","data-slide-index":l,"aria-current":l===d.active?"page":void 0,style:{...P.slideButton,border:l===d.active?"2px solid #325ee6":"2px solid transparent"},onClick:()=>{d.show(l+1)&&b$1();},children:[jsx("span",{style:P.slideNumber,children:l+1}),jsx("span",{style:P.slidePreview,children:m&&o&&h&&d.isPainted(h)?jsx(We,{run:d,frame:o,dpr:R}):jsx("span",{style:P.slideTitle,children:g})})]},r.id)})}),jsxs("div",{ref:n,tabIndex:0,style:P.stage,onKeyDown:Y,children:[jsx("div",{ref:p$1,style:P.canvasHost,children:h?jsx("canvas",{ref:u,style:P.canvas}):jsx("div",{style:P.empty,children:M$1?e$1("editor.opening"):i.file?e$1("editor.noSlides"):e$1("editor.openPrompt")})}),W?jsx("div",{style:P.error,children:W}):null]})]}),d?.session.state.slides[d.active]?jsxs("div",{style:P.notesPanel,children:[jsx("span",{style:P.notesLabel,children:e$1("notes.panelLabel")}),jsx("textarea",{"data-testid":"pptx-notes-textarea",style:P.notesTextarea,value:O,disabled:true,"aria-label":e$1("notes.panelLabel"),placeholder:e$1("notes.placeholder")})]}):null]})})}function We({run:i,frame:e,dpr:t}){let n=useRef(null);return useEffect(()=>{let c=n.current,p=c?.getContext("2d");if(!c||!p||!i.current)return;let u=false,f=()=>!u&&i.current&&i.visible.has(e.slideIndex),a=128/e.displayList.width;return sizeCanvasForSlide(c,e.displayList,t,a),c.width<1&&(c.width=1),c.height<1&&(c.height=1),Promise.resolve().then(async()=>{if(!f())return;let S=i.images.resolve(e);try{await paintSlide(b(p,f),e.displayList,t,a,{resolveImage:S});}finally{S.release();}}).catch(()=>{}),()=>{u=true;}},[i,e,t]),jsx("canvas",{ref:n,style:{display:"block",maxWidth:"100%",height:"auto"},"aria-hidden":"true"})}function he(){let i=typeof window>"u"?1:window.devicePixelRatio;return Number.isFinite(i)&&i>0?i:1}function Le(i,e){let t=new Blob([new Uint8Array(i)],{type:"application/vnd.openxmlformats-officedocument.presentationml.presentation"}),n=URL.createObjectURL(t),c=document.createElement("a");c.href=n,c.download=e,document.body.appendChild(c),c.click(),c.remove(),URL.revokeObjectURL(n);}var P={root:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:480,overflow:"hidden",color:"#172033",background:"#f3f5f8",fontFamily:"ui-sans-serif, system-ui, sans-serif"},toolbarShell:{display:"flex",alignItems:"center",flex:"0 0 auto",padding:"4px 0 5px",background:"#ffffff",borderBottom:"1px solid #e2e8f0"},workspace:{display:"flex",flex:1,minHeight:0},slideStrip:{width:184,padding:"14px 10px",overflowY:"auto",background:"#eef1f5",borderRight:"1px solid #d8dee9",boxSizing:"border-box"},slideButton:{display:"flex",alignItems:"flex-start",gap:7,width:"100%",marginBottom:12,padding:4,borderRadius:5,background:"transparent",cursor:"pointer"},slideNumber:{width:18,flex:"0 0 auto",paddingTop:3,fontSize:11,color:"#647087",textAlign:"right"},slidePreview:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:132,aspectRatio:"16 / 9",padding:8,overflow:"hidden",background:"#ffffff",boxSizing:"border-box",boxShadow:"0 1px 4px rgba(20, 31, 50, 0.16)"},slideTitle:{fontSize:9,lineHeight:1.25,color:"#39445a",textAlign:"center"},stage:{position:"relative",display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,outline:"none",overflow:"hidden"},canvasHost:{display:"flex",flex:1,minHeight:0,alignItems:"center",justifyContent:"center",width:"100%",overflow:"auto"},canvas:{display:"block",flex:"0 0 auto",background:"#fff",boxShadow:"0 8px 32px rgba(27, 39, 61, 0.2)",touchAction:"none"},notesPanel:{flex:"0 0 auto",display:"flex",flexDirection:"column",gap:4,padding:"8px 14px 10px",background:"#ffffff",borderTop:"1px solid #e2e8f0"},notesLabel:{fontSize:11,fontWeight:650,color:"#647087",textTransform:"uppercase",letterSpacing:"0.02em"},notesTextarea:{width:"100%",height:64,resize:"vertical",border:"1px solid #d8dee9",borderRadius:6,padding:"6px 8px",font:"13px ui-sans-serif, system-ui, sans-serif",color:"#172033",boxSizing:"border-box",outline:"none"},empty:{margin:"auto",color:"#6b7587",fontSize:14},error:{position:"absolute",left:16,right:16,bottom:14,padding:"9px 12px",color:"#8b1e2d",background:"#fff0f2",border:"1px solid #efb8c0",borderRadius:6,fontSize:12}};var Me={open:createPptxWorkerEditorSession},$=class{constructor(e,t,n=()=>true,c){a$2(this,"changed",t);a$2(this,"isCurrent",n);a$2(this,"owner");a$2(this,"images",a$3());a$2(this,"access",null);a$2(this,"active",0);a$2(this,"navigation",0);a$2(this,"alive",true);a$2(this,"onFirstPaint");a$2(this,"ready",false);a$2(this,"cache",new Map);a$2(this,"lists",new WeakMap);a$2(this,"waiters",new Set);a$2(this,"painted");a$2(this,"requesting",false);a$2(this,"requested",false);a$2(this,"off");a$2(this,"fonts",[]);a$2(this,"fontsReady");a$2(this,"resolveImage",async e=>{let t=this.frame(this.active);if(!t)return null;let n=this.images.resolve(t);try{return await n(e)}finally{n.release();}});this.active=Number.isInteger(e.initialSlide)?Math.max(0,e.initialSlide-1):0,this.owner=Me.open(e.file,{fonts:e.fonts,clientId:e.clientId,collaboration:e.collaboration,onError:p=>{this.current&&e.onError?.(p);}}),this.off=this.owner.subscribe(()=>{this.current&&(this.owner.failure&&this.finish(this.owner.failure),t(),this.request());}),this.fontsReady=b$1(e.fonts,this.fonts,()=>this.current,c),this.fontsReady.catch(()=>{});}get current(){return this.alive&&this.isCurrent()}get hydrated(){return this.current&&this.owner.hydrated&&this.access!==null}get overlays(){let e=this.frame(this.active);return this.hydrated&&!!e&&this.painted===e&&this.matches(e)}require(){if(!this.current)throw new PptxWorkerEditorDisposedError;if(this.owner.failure)throw this.owner.failure}async open(e){let t=await this.owner.handleAsync();return await this.fontsReady,this.require(),this.access=e.access(t),this.changed(),this.request(),this.access}snapshot(){if(this.hydrated)return this.access.snapshot();let e=this.owner.state.projection;return e?{widthEmu:e.size.width,heightEmu:e.size.height,slides:e.slides.map(t=>({...t,shapes:[],sourcePartPath:null}))}:null}frame(e){let t=this.owner.state.projection?.slides[e]?.id;return t?this.cache.get(t):void 0}matches(e){let t=this.owner.state;return this.current&&!t.failure&&e.sequence===t.sequence&&e.version===t.version&&t.projection?.slides[e.slideIndex]?.id===e.slideId&&this.cache.get(e.slideId)===e}currentPaint(e,t){return this.matches(e)&&t===this.navigation&&Q(e,this.active,this.frame(this.active))}thumbnailImages(e){let t=this.lists.get(e);return !t||!this.matches(t)?null:this.images.resolve(t)}isThumbnailCurrent(e){let t=this.lists.get(e);return !!t&&this.matches(t)}show(e){this.require();let t=this.access&&this.owner.hydrated?this.access.snapshot().slides.length:this.owner.state.projection?.slides.length??0;return !Number.isInteger(e)||e<1||e>t?false:(this.active!==e-1&&(this.finish(),this.active=e-1,this.navigation+=1,this.painted=void 0,this.changed()),this.request(),true)}async showAsync(e){return this.show(e)?this.overlays?true:new Promise((t,n)=>this.waiters.add({slide:e,resolve:t,reject:n})):false}didPaint(e,t){if(this.currentPaint(e,t)){this.painted=e;for(let n of this.waiters)n.resolve(n.slide===this.active+1);this.waiters.clear(),this.hydrated&&!this.ready&&this.onFirstPaint&&(this.ready=true,this.onFirstPaint()),this.changed();}}finish(e){for(let t of this.waiters)e?t.reject(e):t.resolve(false);this.waiters.clear();}async request(){if(this.requesting){this.requested=true;return}if(!this.current||this.owner.failure||!this.owner.state.projection||this.owner.state.sequence!==this.owner.state.acknowledgedSequence)return;this.requesting=true;let e=this.navigation,t=this.owner.state.sequence;try{let n=this.owner.state.projection.slides;this.active=Math.min(this.active,Math.max(0,n.length-1));let c=[this.active,...n.map((p,u)=>u).filter(p=>p!==this.active)];for(let p of c){let u=n[p];if(!u||!this.current||e!==this.navigation||t!==this.owner.state.sequence)break;let f=this.cache.get(u.id);if(f&&this.matches(f))continue;let a=await this.owner.frame(u.id);if(!this.current||this.owner.failure||e!==this.navigation||t!==this.owner.state.sequence)break;a.slideId!==u.id||a.slideIndex!==p||a.sequence!==t||a.version!==this.owner.state.version||!Number.isInteger(a.epoch)||a.epoch<=(f?.epoch??0)||(this.cache.set(u.id,a),this.lists.set(a.displayList,a),this.changed());}}catch(n){this.current&&!this.owner.failure&&this.finish(n);}finally{this.requesting=false;let n=this.requested;this.requested=false,this.current&&(n||e!==this.navigation||t!==this.owner.state.sequence)&&this.request();}}dispose(){this.alive=false,this.finish(new PptxWorkerEditorDisposedError),this.off(),this.cache.clear(),this.painted=void 0,this.images.dispose();for(let e of this.fonts)document.fonts.delete(e);this.owner.dispose().catch(()=>{});}};function Pe(i){let e=d(i.fonts),t=useRef(i),n=useRef(e);t.current=i,n.current=e;let c=useMemo(()=>({}),[i.file,i.clientId,i.collaboration,e]),p=a$1(c);return useCallback(u=>{let f=t.current;return new $({...f,fonts:e,onError:a=>t.current.onError?.(a)},u,()=>t.current.file===f.file&&n.current===e&&t.current.clientId===f.clientId&&t.current.collaboration===f.collaboration,p)},[i.file,i.clientId,i.collaboration,e,p])}function xe(i){let e=Pe(i),{onReady:t,...n}=i;return jsx(c,{...n,backend:e,onWorkerReady:t})}function De(i,e,t){if(i===false)return "deprecated";if(i!==true)return "in-thread";if(e!=null)return "collaboration";if(!t)return "no-worker"}function xt(i){useEffect(()=>{a("legacy-sync-api");},[]);let e=d(i.fonts),t=i.experimentalWorkerOpen,n=useMemo(()=>({}),[i.file,e,i.clientId,i.collaboration,t]),c$1=useMemo(()=>({}),[i.file,i.collaboration,t]),p=()=>({identity:c$1,reason:De(t,i.collaboration,typeof Worker=="function")}),[u,f]=useState(p),a$1=u.identity===c$1?u:p();u!==a$1&&f(a$1);let S=!i.readOnly||(i.plugins?.length??0)>0||i.onChange!==void 0,I=()=>({identity:n,editable:S}),[L,R]=useState(I),q=L.identity===n?L:I(),b=q.editable||S;(L!==q||L.editable!==b)&&R({...q,editable:b}),useEffect(()=>{a$1.reason&&a$1.reason!=="in-thread"&&a(a$1.reason);},[a$1.reason]);let d$1=xe;return a$1.reason?jsx(c,{...i}):b?jsx(d$1,{...i}):jsx(ve,{...i})}export{xt as PptxEditorSession};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-HQ2N3DQ7.js';import {c,b}from'./chunk-BNLMNYZQ.js';import {P,K as K$1,j,Q as Q$1,Z}from'./chunk-LFHLWZA4.js';import'./chunk-PS7ULZVL.js';import {a as a$1}from'./chunk-LEWN3FCH.js';import'./chunk-O2XFH626.js';import {lazy,useId,useState,useRef,useEffect,Suspense}from'react';import {sizeCanvasForSlide,decodePresentationImage,paintSlide}from'@betteroffice/pptx';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var K=lazy(()=>import('./chunk-OUJVNLXT.js').then(p=>({default:p.ProposalChangeDetails})));function Q(p,d,u,y,m,S){let f=y.slides.findIndex(a=>a.id===u),t=m.slides.findIndex(a=>a.id===u),g=f>=0?p.layoutSlide(f):null,v=t>=0?p.layoutProposalSlide(d,t):null,I=t>=0?p.layoutProposalDiffSlideById(d,u).media:void 0;if(!g&&!v)throw new Error(S);return {media:I,before:g??{...v,primitives:[]},after:v??{...g,primitives:[]}}}function M({command:p,proposalId:d,label:u,style:y,testId:m}){let S=P(),f={proposalId:d},t=Q$1(p,f),g=Z(!t.enabled,t.enabled?void 0:t.disabledReason.message);return jsxs(Fragment,{children:[jsx("button",{type:"button","data-testid":m,...g.props,title:g.reason,style:{...y,opacity:t.enabled?1:.45},onClick:()=>{t.enabled&&S.execute(p,f);},children:u}),g.node]})}function de({handle:p,proposals:d,snapshot:u,resolveImage:y,onNavigate:m,onClose:S,visualDisabledReason:f}){let{t,lang:g}=c(),v=P(),I=useId(),[a$2,b]=useState(null),x=useRef(a$2);x.current=a$2;let[n,h]=useState(null),[C,P$1]=useState(null),k=useRef(null),j$1=useRef(null);useEffect(()=>{if(a$2){if(!d.some(e=>e.id===a$2.id)){b(null);return}try{let e=p.previewProposal(a$2.id),r=e.proposal.changes[a$2.index];if(!r)throw new Error(t("proposals.targetMissing"));let{before:i,after:l,media:w}=Q(p,a$2.id,r.slideId,u,e.snapshot,t("proposals.targetMissing"));h({data:e,before:i,after:l,media:w}),P$1(null);}catch(e){h(null),P$1(e instanceof Error?e.message:String(e));}}},[p,d,u,a$2,t]),useEffect(()=>{let e=k.current;a$2&&e&&!e.open&&e.showModal(),!a$2&&e?.open&&e.close();},[a$2]);let A=(e,r)=>{let i=u.slides.findIndex(w=>w.id===e.slideId),l=a$1(e,r,t).join(", ")||(e.shapeId?(e.after??e.before)?.name||t("proposals.appearance"):e.kind==="inserted"?t("proposals.insertedSlide"):e.kind==="deleted"?t("proposals.deletedSlide"):e.before?.name||t("notes.panelLabel"));return i<0&&e.kind==="inserted"?t("proposals.target",{slide:(e.afterIndex??0)+1,name:l}):i<0?t("proposals.targetMissing"):t("proposals.target",{slide:i+1,name:l})},V=(e,r,i)=>{j$1.current=i;let l=e.changes[r];m(l.slideId,l.shapeId,e.id),h(null),P$1(null),b({id:e.id,index:r});},B=(e,r)=>{let i=()=>x.current?.id===e.id&&x.current.index===e.index;try{let l=p.previewProposal(e.id);if(JSON.stringify(l.proposal.changes)===JSON.stringify(r.proposal.changes))return !0;if(!i())return !1;let w=l.proposal.changes[e.index];h({data:l,...Q(p,e.id,w.slideId,u,l.snapshot,t("proposals.targetMissing"))}),P$1(t("proposals.changedAgain"));}catch(l){if(!i())return false;h(null),P$1(l instanceof Error?l.message:String(l));}return false},O=e=>{if(!a$2||!n)return;let r=a$2,i=n.data;if(!B(r,i))return;K$1(v)?.defer("proposalAccept",{proposalId:r.id,force:e})?.complete(w=>B(r,i)?w():{ok:false,failure:j("target-changed",{translate:t})});};return jsxs("aside",{"data-testid":"pptx-proposals-panel","aria-label":t("proposals.title"),style:a.panel,children:[jsxs("header",{style:a.header,children:[jsxs("strong",{children:[t("proposals.title")," ",jsx("span",{style:a.count,children:d.length})]}),jsx("button",{type:"button",onClick:()=>{v.execute("proposalsPanel",{open:false}).then(()=>S());},"aria-label":t("proposals.close"),style:a.button,children:"\xD7"})]}),d.length===0&&jsx("p",{style:a.muted,children:t("proposals.empty")}),d.map(e=>jsxs("section",{"data-testid":"pptx-proposal","data-proposal-id":e.id,style:a.card,children:[jsx("strong",{style:a.author,children:e.agentId}),e.note&&jsx("p",{style:a.note,children:e.note}),e.changes.map((r,i)=>jsxs("div",{style:a.change,children:[jsx("button",{type:"button",onClick:()=>m(r.slideId,r.shapeId,e.id),style:a.link,children:A(r,e)}),!f&&jsx(Suspense,{fallback:null,children:jsx(K,{change:r,proposal:e,t,lang:g})}),jsx("button",{type:"button","data-testid":"pptx-proposal-preview",disabled:!!f,title:f,style:a.button,onClick:l=>V(e,i,l.currentTarget),children:t("proposals.preview")}),f&&jsx("p",{style:a.muted,children:f})]},`${r.slideId}:${r.shapeId??"notes"}`)),e.staleTargets.length>0&&jsx("p",{role:"alert","data-testid":"pptx-proposal-stale",style:a.warning,children:t("proposals.stale")}),jsxs("div",{style:a.actions,children:[jsx(M,{command:"proposalAccept",proposalId:e.id,label:t("proposals.accept"),style:a.primary,testId:"pptx-proposal-accept"}),jsx(M,{command:"proposalReject",proposalId:e.id,label:t("proposals.reject"),style:a.button,testId:"pptx-proposal-reject"})]})]},e.id)),jsxs("dialog",{ref:k,"data-testid":"pptx-proposal-preview-dialog","aria-labelledby":I,style:a.dialog,onCancel:()=>b(null),onClose:()=>{b(null),j$1.current?.focus();},children:[jsxs("header",{style:a.header,children:[jsx("strong",{id:I,children:t("proposals.previewTitle")}),jsx("button",{type:"button",style:a.button,onClick:()=>b(null),children:t("proposals.close")})]}),C&&jsx("p",{role:"alert",style:a.warning,children:C}),n&&a$2&&jsxs(Fragment,{children:[jsxs("p",{children:[jsx("strong",{children:n.data.proposal.agentId}),n.data.proposal.note&&jsxs(Fragment,{children:[" \xB7 ",n.data.proposal.note]})]}),jsxs("label",{children:[t("proposals.targetLabel")," ",jsx("select",{"aria-label":t("proposals.targetLabel"),value:a$2.index,onChange:e=>{let r=Number(e.target.value),i=n.data.proposal.changes[r];m(i.slideId,i.shapeId,a$2.id),b({id:a$2.id,index:r});},children:n.data.proposal.changes.map((e,r)=>jsx("option",{value:r,children:A(e,n.data.proposal)},r))})]}),jsx(Suspense,{fallback:null,children:jsx(K,{change:n.data.proposal.changes[a$2.index],proposal:n.data.proposal,t,lang:g,textOnly:true})}),jsxs("div",{style:a.previews,children:[jsx(U,{label:t("proposals.before"),frame:n.before,resolveImage:y}),jsx(U,{label:t("proposals.after"),media:n.media,frame:n.after,snapshot:n.data.snapshot,resolveImage:y})]}),n.data.proposal.staleTargets.length>0&&jsx("p",{role:"alert",style:a.warning,children:t("proposals.stalePreview")}),jsxs("div",{style:a.actions,children:[n.data.proposal.staleTargets.length>0?jsx("button",{type:"button","data-testid":"pptx-proposal-force",style:a.primary,onClick:()=>O(true),children:t("proposals.force")}):jsx("button",{type:"button",style:a.primary,onClick:()=>O(false),children:t("proposals.accept")}),jsx(M,{command:"proposalReject",proposalId:a$2.id,label:t("proposals.reject"),style:a.button})]})]})]})]})}function U({label:p,frame:d,snapshot:u,media:y,resolveImage:m}){let{t:S}=c(),f=S("errors.decodeSlideImage"),t=useRef(null),[g,v]=useState(null);return useEffect(()=>{let I=false,a=t.current;if(!a)return;let b$1=document.createElement("canvas"),x=b$1.getContext("2d"),n=a.getContext("2d");if(!x||!n)return;let h=Math.min(1,560/d.width),C=window.devicePixelRatio||1;sizeCanvasForSlide(b$1,d,C,h),v(null);let P=u?b({snapshot:u,media:y},m,f,decodePresentationImage):null;return paintSlide(x,d,C,h,{resolveImage:P?.resolveImage??m}).then(()=>{I||(sizeCanvasForSlide(a,d,C,h),n.setTransform(1,0,0,1,0,0),n.drawImage(b$1,0,0));}).catch(k=>{I||v(k instanceof Error?k.message:String(k));}).finally(()=>P?.release()),()=>{I=true;}},[d,u,y,m,f]),jsxs("figure",{style:a.figure,children:[jsx("figcaption",{style:a.caption,children:p}),jsx("canvas",{ref:t,role:"img","aria-label":p,style:{maxWidth:"100%",height:"auto",display:"block",background:"#fff"}}),g&&jsx("p",{role:"alert",children:g})]})}export{de as ProposalsPanel};
@@ -0,0 +1 @@
1
+ import {a as a$1}from'./chunk-4TRQLEZF.js';var a={deprecated:`[PptxEditor] \`experimentalWorkerOpen={false}\` selects the deprecated in-thread engine. Omit it and \`${a$1}\` to use the worker-owned async editor.`,collaboration:"[PptxEditor] the legacy hybrid runtime does not support `collaboration`; using the deprecated in-thread engine.","no-worker":"[PptxEditor] `Worker` is not available in this environment; using the deprecated in-thread engine.","no-offscreen-canvas":"[PptxEditor] `OffscreenCanvas` is not available in this environment; using the deprecated in-thread engine.","legacy-sync-api":`[PptxEditor] \`${a$1}\` keeps the deprecated synchronous API on the in-thread engine, removed in 0.7.0. Omit it to use the async editor.`},t=Symbol.for("@betteroffice/pptx-react/engine-warnings"),r=globalThis,i=r[t]??(r[t]=new Set);function d(o){let e=a[o];i.has(e)||(i.add(e),console.warn(e));}export{d as a};
package/dist/index.d.ts CHANGED
@@ -1,10 +1,22 @@
1
+ import { BundledFontFace } from '@betteroffice/fonts';
2
+ export { BundledFontFace } from '@betteroffice/fonts';
1
3
  import * as _betteroffice_pptx from '@betteroffice/pptx';
2
4
  import { ParagraphAlignment, PptxEditRefusal, PptxReadRequest, PptxReadResult, PptxFindRequest, PptxFindResult, PptxEditRequest, PptxValidationResult, PptxEditResult, PptxFontFace, CollaborationReplica, PptxPresence, HitTestResult, PresentationHandle, DeckSnapshot } from '@betteroffice/pptx';
5
+ export { HeaderFooterSettings, PptxExportList, SlideDateText, SlideHeaderFooter, SlideHeaderFooterText, SlideLayoutSnapshot } from '@betteroffice/pptx';
3
6
  import * as react from 'react';
4
7
  import { ComponentType, ReactNode, CSSProperties, JSX } from 'react';
5
8
  import { TranslationKey, Translations, TFunction } from '@betteroffice/pptx-i18n';
6
9
  import { PptxWorkerEditorFailedError, PptxWorkerEditorAccess, PptxWorkerEditorRecovery, PresentationCommandAccessMethod, PresentationCommandAccessMethods, PresentationCommandMutationMethods } from '@betteroffice/pptx/worker';
7
10
 
11
+ /**
12
+ * A bundled face decoded before opening the presentation. It serves the font it substitutes
13
+ * (`face.metricCompatWith`, e.g. Arial for Liberation Sans), or its own family when it substitutes none.
14
+ */
15
+ interface PptxBundledFont {
16
+ face: BundledFontFace;
17
+ baseUrl?: string | URL;
18
+ }
19
+
8
20
  /**
9
21
  * A value that survives `JSON.stringify` / `JSON.parse` unchanged.
10
22
  * @experimental
@@ -92,6 +104,24 @@ type PluginCommandResult<Status extends string = string, Refusal extends {
92
104
  ok: false;
93
105
  failure: CommandReason;
94
106
  } | Refusal;
107
+ /** @experimental The plugin API may change in minor releases. */
108
+ interface PluginFocusChangeEvent {
109
+ type: 'focus-change';
110
+ generation: string;
111
+ focused: boolean;
112
+ }
113
+ /** @experimental The plugin API may change in minor releases. */
114
+ interface PluginLocaleChangeEvent {
115
+ type: 'locale-change';
116
+ generation: string;
117
+ locale: string;
118
+ }
119
+ /** @experimental The plugin API may change in minor releases. */
120
+ interface PluginViewportChangeEvent<Rect> {
121
+ type: 'viewport-change';
122
+ generation: string;
123
+ viewport: Rect | null;
124
+ }
95
125
 
96
126
  declare const SHAPE_PRESETS: readonly [{
97
127
  readonly geometry: "rect";
@@ -154,10 +184,11 @@ interface SelectionFormatting {
154
184
  bold?: boolean;
155
185
  italic?: boolean;
156
186
  underline?: boolean;
187
+ strikethrough?: boolean;
157
188
  textColor?: string;
158
189
  align?: ParagraphAlignment;
159
190
  }
160
- type FormattingAction = 'bold' | 'italic' | 'underline' | {
191
+ type FormattingAction = 'bold' | 'italic' | 'underline' | 'strikethrough' | {
161
192
  type: 'fontFamily';
162
193
  value: string;
163
194
  } | {
@@ -210,9 +241,25 @@ type PptxZOrderMove = 'front' | 'forward' | 'backward' | 'back';
210
241
  * @experimental
211
242
  */
212
243
  interface PptxCommandArgs {
244
+ cut: null;
245
+ copy: null;
246
+ paste: null;
247
+ /** Pastes the clipboard's text without formatting. */
248
+ pasteAsPlainText: null;
249
+ deleteObject: null;
250
+ deleteSlide: null;
251
+ duplicateSlide: null;
252
+ tableInsert: {
253
+ kind: 'row' | 'column';
254
+ position: 'before' | 'after';
255
+ };
256
+ tableDelete: {
257
+ kind: 'row' | 'column' | 'table';
258
+ };
213
259
  bold: null;
214
260
  italic: null;
215
261
  underline: null;
262
+ strikethrough: null;
216
263
  fontFamily: {
217
264
  family: string;
218
265
  };
@@ -300,9 +347,19 @@ type PptxSelectCommandId = 'fontFamily' | 'fontSize' | 'alignment' | 'insertSlid
300
347
  * @experimental
301
348
  */
302
349
  interface PptxCommandValues {
350
+ cut: null;
351
+ copy: null;
352
+ paste: null;
353
+ pasteAsPlainText: null;
354
+ deleteObject: null;
355
+ deleteSlide: null;
356
+ duplicateSlide: null;
357
+ tableInsert: null;
358
+ tableDelete: null;
303
359
  bold: null;
304
360
  italic: null;
305
361
  underline: null;
362
+ strikethrough: null;
306
363
  /** `null` when the selection mixes families. */
307
364
  fontFamily: string | null;
308
365
  /** Points; `null` when the selection mixes sizes. */
@@ -347,7 +404,7 @@ interface PptxCommandValues {
347
404
  * Why a command is unavailable.
348
405
  * @experimental
349
406
  */
350
- type PptxCommandDisabledCode = 'editor-unavailable' | 'document-loading' | 'no-document' | 'read-only' | 'nothing-to-undo' | 'nothing-to-redo' | 'text-selection-required' | 'shape-required' | 'slide-required' | 'unsupported-selection' | 'invalid-layout' | 'invalid-adjustment' | 'z-order-boundary' | 'review-active'
407
+ type PptxCommandDisabledCode = 'clipboard-unavailable' | 'table-required' | 'last-slide' | 'editor-unavailable' | 'document-loading' | 'no-document' | 'read-only' | 'nothing-to-undo' | 'nothing-to-redo' | 'text-selection-required' | 'shape-required' | 'slide-required' | 'unsupported-selection' | 'invalid-layout' | 'invalid-adjustment' | 'z-order-boundary' | 'review-active'
351
408
  /** The canvas diff of a proposal has not painted yet; reported by the canvas review control. */
352
409
  | 'preview-pending'
353
410
  /** The canvas diff of a proposal could not be laid out; reported by the canvas review control. */
@@ -456,6 +513,61 @@ interface PptxCommandStore {
456
513
  execute(id: PptxPluginCommandId, args: null): Promise<PptxPluginCommandResult>;
457
514
  }
458
515
 
516
+ /**
517
+ * A chord such as `Mod+Shift+V`. `Mod` is Cmd on macOS and Ctrl elsewhere; `Ctrl` is the physical
518
+ * Control key on macOS and the same as `Mod` elsewhere.
519
+ * @experimental
520
+ */
521
+ type ShortcutChord = string;
522
+
523
+ /**
524
+ * What a host sets for one shortcut id: chords that replace the defaults, `null` to disable it,
525
+ * or a per-platform form where an absent platform keeps its default.
526
+ * @experimental
527
+ */
528
+ type ShortcutBinding = ShortcutChord | readonly ShortcutChord[] | null | {
529
+ mac?: ShortcutChord | readonly ShortcutChord[] | null;
530
+ other?: ShortcutChord | readonly ShortcutChord[] | null;
531
+ };
532
+ /**
533
+ * A host binding the editor changed or refused. `displaced-default` is informational: the host
534
+ * chord `chord` of `id` took over the default of `displaced`.
535
+ * @experimental
536
+ */
537
+ interface ShortcutIssue {
538
+ code: 'unknown-id' | 'invalid-chord' | 'reserved-chord' | 'duplicate-chord' | 'displaced-default';
539
+ id: string;
540
+ chord?: string;
541
+ /** The other shortcut id involved, for `duplicate-chord` and `displaced-default`. */
542
+ other?: string;
543
+ }
544
+ interface ResolvedShortcuts {
545
+ /** Effective canonical chords by id; an id without chords is absent or empty. */
546
+ chords: ReadonlyMap<string, readonly string[]>;
547
+ /** The id each effective canonical chord runs. */
548
+ owners: ReadonlyMap<string, string>;
549
+ issues: readonly ShortcutIssue[];
550
+ }
551
+
552
+ type PptxNullArgsCommandId = {
553
+ [K in PptxCommandId]: null extends PptxCommandArgs[K] ? K : never;
554
+ }[PptxCommandId];
555
+ /**
556
+ * Every id a host can bind: commands that run without arguments and plugin commands.
557
+ * @experimental
558
+ */
559
+ type PptxShortcutId = PptxNullArgsCommandId | PptxPluginCommandId;
560
+ /**
561
+ * Host changes to the editor's shortcuts. An omitted id keeps its default; chords replace all of
562
+ * its defaults; `null` disables it and leaves the keystroke to the host or browser. A chord taken
563
+ * from another command's default wins over it. `cut`, `copy`, `paste` and `pasteAsPlainText` on a
564
+ * chord other than their default use the async Clipboard API, which browsers may gate behind a
565
+ * prompt; the non-worker editor and the viewer have no clipboard and report them as `unknown-id`.
566
+ * Text navigation and editing keys, select all and the context menu key cannot be bound.
567
+ * @experimental
568
+ */
569
+ type PptxShortcuts = Readonly<Partial<Record<PptxShortcutId, ShortcutBinding>>>;
570
+
459
571
  /**
460
572
  * What the host lets one plugin do. Without a grant a plugin reads, validates and navigates only.
461
573
  * Built-in commands need their id listed and, when they mutate, `document: 'write'`; edit
@@ -555,6 +667,10 @@ type PptxPluginSelection = {
555
667
  };
556
668
  } | null;
557
669
  interface PptxPluginSnapshot {
670
+ /** @experimental Focus inside the document surface. */
671
+ focused: boolean;
672
+ /** @experimental The editor's resolved locale tag. */
673
+ locale: string;
558
674
  /** The open presentation; changes when a presentation replaces it. */
559
675
  generation: string;
560
676
  version: string;
@@ -569,12 +685,42 @@ type PptxPluginPointPosition = PptxPointPosition & {
569
685
  version: string;
570
686
  layoutId: string;
571
687
  };
688
+ /** @experimental The plugin API may change in minor releases. */
689
+ type PptxGeometryTarget =
690
+ /** Selection anchors are live-only; use a range target to keep a position. */
691
+ {
692
+ kind: 'selection';
693
+ } | {
694
+ kind: 'range';
695
+ version: string;
696
+ slideId: string;
697
+ shapeId: string;
698
+ storyId: string;
699
+ /** UTF-16 story offsets; `focus` may precede `anchor`. */
700
+ anchor: number;
701
+ focus: number;
702
+ };
703
+ /** @experimental The plugin API may change in minor releases. */
704
+ type PptxAnchorGeometryResult = {
705
+ ok: true;
706
+ rects: readonly PptxPluginRect[];
707
+ anchor: PptxPluginRect;
708
+ pageRect: PptxPluginRect;
709
+ version: string;
710
+ layoutId: string;
711
+ } | PluginRefusal<'stale-version' | 'missing-target' | 'layout-unavailable'>;
572
712
  /**
573
- * Geometry of the presented slide. Rectangles it returns are in pixels of the unscaled overlay
574
- * layer; every method returns null once its layout is no longer presented.
713
+ * Geometry in unscaled overlay-layer pixels. Unpresented layouts return null or a typed
714
+ * anchor failure.
575
715
  */
576
716
  interface PptxPluginGeometry {
717
+ /** @experimental The visible document area in overlay-layer pixels. */
718
+ viewport: PptxPluginRect;
577
719
  layout: PptxPluginLayout;
720
+ /** @experimental Line rectangles and a focus-end anchor; collapsed text has no rectangles. */
721
+ getAnchorGeometry(target: PptxGeometryTarget): PptxAnchorGeometryResult;
722
+ /** @experimental Resolves each target in order without pending answers. */
723
+ readAnchorGeometries(targets: readonly PptxGeometryTarget[]): Promise<PptxAnchorGeometryResult[]>;
578
724
  /**
579
725
  * Converts a slide rectangle into overlay pixels: `slide-emu` in EMU from the slide's top left
580
726
  * corner, `slide-px` in unzoomed display-list pixels.
@@ -627,8 +773,14 @@ interface PptxPluginNavigation {
627
773
  focus: number;
628
774
  }, options: PptxPluginNavigationOptions): Promise<PptxPluginNavigationResult>;
629
775
  }
776
+ /** @experimental The plugin API may change in minor releases. */
777
+ type PptxPluginFocusChangeEvent = PluginFocusChangeEvent;
778
+ /** @experimental The plugin API may change in minor releases. */
779
+ type PptxPluginLocaleChangeEvent = PluginLocaleChangeEvent;
780
+ /** @experimental The plugin API may change in minor releases. */
781
+ type PptxPluginViewportChangeEvent = PluginViewportChangeEvent<PptxPluginRect>;
630
782
  /** Lifecycle notifications describe current state; several changes may arrive as one. */
631
- type PptxPluginEvent = {
783
+ type PptxPluginEvent = PptxPluginFocusChangeEvent | PptxPluginLocaleChangeEvent | PptxPluginViewportChangeEvent | {
632
784
  type: 'load';
633
785
  generation: string;
634
786
  version: string;
@@ -778,7 +930,7 @@ interface PptxWorkerEditorApi extends Omit<PptxEditorApi, 'handle' | 'save'> {
778
930
  }
779
931
 
780
932
  type PptxWorkerEditorProps = Omit<PptxInThreadEditorProps, 'onReady' | 'readOnly' | 'experimentalWorkerOpen' | 'collaboration'> & {
781
- /** @deprecated Removed in 0.6.0. Omit for the async editor. */
933
+ /** @deprecated Removed in 0.7.0. Omit for the async editor. */
782
934
  [LEGACY_SYNC_API]: true;
783
935
  collaboration?: undefined;
784
936
  /** Edits in the worker; without it the legacy runtime runs in-thread. */
@@ -801,15 +953,21 @@ type PptxAsyncEditorApi = Omit<PptxWorkerEditorApi, 'handle' | 'save' | 'saveAsy
801
953
  [K in keyof AsyncOperations]: (...args: Parameters<AsyncOperations[K]>) => Promise<ReturnType<AsyncOperations[K]>>;
802
954
  } & Pick<PptxAsyncEditorAccess, 'exportStructured' | 'exportMarkdown'> & {
803
955
  handleAsync(): Promise<PptxAsyncEditorAccess>;
804
- /** Flushes pending input, then serializes the presentation to .pptx bytes. Does not call onSave or download. */
956
+ /** Flushes pending input, serializes the presentation to .pptx bytes and hands them to onSave. Does not download. */
805
957
  save(): Promise<Uint8Array>;
806
958
  /** @deprecated Use {@link save}, which is async on the default editor. */
807
959
  saveAsync(): Promise<Uint8Array>;
960
+ /** `unrecoveredIntents` lists edits made just before the failure that recovery left out because their outcome is unknown. */
808
961
  recoverySave(): Promise<{
809
962
  bytes: Uint8Array;
810
963
  recovery: true;
811
964
  throughSeq: number;
812
965
  version: string;
966
+ unrecoveredIntents?: {
967
+ seq: number;
968
+ kind: string;
969
+ reason: 'unknown-outcome';
970
+ }[];
813
971
  }>;
814
972
  };
815
973
 
@@ -904,7 +1062,7 @@ interface PptxEditorCollaborationOptions {
904
1062
  interface PptxInThreadEditorProps extends PptxEditorPluginProps {
905
1063
  file?: Uint8Array;
906
1064
  /** Font faces; equivalent inline arrays do not reopen the presentation. */
907
- fonts: ReadonlyArray<PptxFontFace>;
1065
+ fonts: ReadonlyArray<PptxFontFace | PptxBundledFont>;
908
1066
  clientId?: number;
909
1067
  /** Uses the deprecated in-thread engine when set. */
910
1068
  collaboration?: PptxEditorCollaborationOptions;
@@ -916,6 +1074,7 @@ interface PptxInThreadEditorProps extends PptxEditorPluginProps {
916
1074
  fileName?: string;
917
1075
  /** 1-based; clamped to the deck. */
918
1076
  initialSlide?: number;
1077
+ /** Called once an opened deck's first slide is painted. */
919
1078
  onReady?: (api: PptxEditorApi) => void;
920
1079
  onChange?: (snapshot: DeckSnapshot) => void;
921
1080
  onError?: (error: Error) => void;
@@ -934,10 +1093,21 @@ interface PptxInThreadEditorProps extends PptxEditorPluginProps {
934
1093
  toolbar?: ReactNode;
935
1094
  /** Shows the toolbar region; defaults to true. */
936
1095
  showToolbar?: boolean;
1096
+ /**
1097
+ * Remaps or disables keyboard shortcuts; menus and tooltips follow.
1098
+ * @experimental
1099
+ */
1100
+ shortcuts?: PptxShortcuts;
1101
+ /**
1102
+ * Reports each entry of `shortcuts` that was refused, and each default a host chord displaced.
1103
+ * Without it, refusals are logged in development builds.
1104
+ * @experimental
1105
+ */
1106
+ onShortcutIssue?: (issue: ShortcutIssue) => void;
937
1107
  }
938
- /** @deprecated Removed in 0.6.0. Use PptxAsyncEditorProps. */
1108
+ /** @deprecated Removed in 0.7.0. Use PptxAsyncEditorProps. */
939
1109
  type PptxWorkerViewerProps = Omit<PptxInThreadEditorProps, 'onReady' | 'readOnly' | 'experimentalWorkerOpen' | 'collaboration' | 'plugins' | 'onChange'> & {
940
- /** @deprecated Removed in 0.6.0. Omit for the async editor. */
1110
+ /** @deprecated Removed in 0.7.0. Omit for the async editor. */
941
1111
  [LEGACY_SYNC_API]: true;
942
1112
  collaboration?: undefined;
943
1113
  plugins?: readonly [];
@@ -962,19 +1132,31 @@ interface PptxAsyncPresentationProps {
962
1132
  loadingIndicator?: ReactNode;
963
1133
  /** Inline styles for the editor root. */
964
1134
  style?: CSSProperties;
1135
+ /**
1136
+ * Loads bundled faces before the first paint for document families that
1137
+ * `fonts` does not supply; supplied families keep the app's faces. Pass
1138
+ * false to fetch no default fonts. Defaults to true.
1139
+ */
1140
+ defaultFonts?: boolean;
1141
+ /**
1142
+ * Loads bundled Chinese, Japanese and Korean faces in slices as text needs them, instead of whole, in Chromium and
1143
+ * Firefox. Defaults to false.
1144
+ * @experimental
1145
+ */
1146
+ experimentalSlicedFonts?: boolean;
965
1147
  }
966
1148
  type PptxAsyncEditorProps = Omit<PptxInThreadEditorProps, 'file' | 'onReady' | 'collaboration' | 'experimentalWorkerOpen'> & PptxAsyncPresentationProps & {
967
1149
  file?: Uint8Array | ArrayBuffer;
968
- /** @deprecated Removed in 0.6.0. Omit for the async editor. */
1150
+ /** @deprecated Removed in 0.7.0. Omit for the async editor. */
969
1151
  [LEGACY_SYNC_API]?: false;
970
1152
  /** @deprecated False selects the in-thread engine. */
971
1153
  experimentalWorkerOpen?: boolean;
972
1154
  collaboration?: PptxAsyncCollaborationOptions;
973
1155
  onReady?: (api: PptxAsyncEditorApi) => void | (() => void);
974
1156
  };
975
- /** @deprecated Removed in 0.6.0. Use PptxAsyncEditorProps. */
1157
+ /** @deprecated Removed in 0.7.0. Use PptxAsyncEditorProps. */
976
1158
  type PptxLegacyEditorProps = PptxInThreadEditorProps & {
977
- /** @deprecated Removed in 0.6.0. Omit for the async editor. */
1159
+ /** @deprecated Removed in 0.7.0. Omit for the async editor. */
978
1160
  [LEGACY_SYNC_API]: true;
979
1161
  };
980
1162
  type WorkerSessionProps = Omit<PptxWorkerEditorProps, 'readOnly' | 'onReady' | 'experimentalWorkerOpen'> & {
@@ -1101,6 +1283,8 @@ interface ToolbarButtonProps {
1101
1283
  title: string;
1102
1284
  /** Keyboard shortcut shown in the tooltip and overflow menu, such as `Ctrl+B`. */
1103
1285
  shortcut?: string;
1286
+ /** The shortcut in `aria-keyshortcuts` form, such as `Control+B`. */
1287
+ ariaShortcut?: string;
1104
1288
  onClick?: () => void;
1105
1289
  children: ReactNode;
1106
1290
  className?: string;
@@ -1159,6 +1343,7 @@ interface LocaleProviderProps {
1159
1343
  declare function LocaleProvider({ i18n, children }: LocaleProviderProps): react.JSX.Element;
1160
1344
  declare function useTranslation(): {
1161
1345
  t: TFunction;
1346
+ lang: string;
1162
1347
  };
1163
1348
 
1164
1349
  /** @experimental */
@@ -1203,6 +1388,8 @@ interface PptxBoundCommand<K extends PptxCommandId> {
1203
1388
  label: string;
1204
1389
  /** The keyboard shortcut as people read it on this platform, such as `Ctrl+B`. */
1205
1390
  shortcut: string | null;
1391
+ /** The shortcut in `aria-keyshortcuts` form, such as `Control+B`. */
1392
+ ariaShortcut: string | null;
1206
1393
  /** Executes with `args`, falling back to the arguments bound to the hook. */
1207
1394
  execute(args?: PptxCommandArgs[K]): Promise<PptxCommandResult>;
1208
1395
  }
@@ -1218,6 +1405,8 @@ interface PptxBoundPluginCommand {
1218
1405
  /** The contributed label, or the id while no plugin contributes it. */
1219
1406
  label: string;
1220
1407
  shortcut: string | null;
1408
+ /** The shortcut in `aria-keyshortcuts` form. */
1409
+ ariaShortcut: string | null;
1221
1410
  execute(): Promise<PptxPluginCommandResult>;
1222
1411
  }
1223
1412
  /**
@@ -1324,4 +1513,4 @@ declare function definePptxPlugin<S>(definition: PptxPluginDefinition<S>): PptxP
1324
1513
  */
1325
1514
  declare function PptxPluginToolbar(): React.ReactElement | null;
1326
1515
 
1327
- export { type CommandReason, type CommandState, type CommandToolbarProps, EditorToolbar, type EditorToolbarCommandProps, EditorToolbarContext, type EditorToolbarProps, type FormattingAction, type JsonValue, LocaleProvider, type LocaleProviderProps, type MaybePromise, type PluginCleanupReason, type PluginGrant, type PluginLoadReason, type PptxAsyncCollaborationOptions, type PptxAsyncEditorAccess, type PptxAsyncEditorApi, type PptxAsyncEditorProps, type PptxBoundCommand, type PptxBoundPluginCommand, type PptxCommandAdmissionCode, PptxCommandAdmissionError, type PptxCommandArgs, type PptxCommandDescriptor, type PptxCommandDisabledCode, type PptxCommandFailureCode, type PptxCommandId, type PptxCommandOption, PptxCommandProvider, type PptxCommandProviderProps, type PptxCommandResult, type PptxCommandShortcut, type PptxCommandState, type PptxCommandStatus, type PptxCommandStore, type PptxCommandValues, type PptxControlCommandId, type PptxDocumentChange, PptxEditor, type PptxEditorApi, type PptxEditorCollaborationOptions, type PptxEditorPluginProps, type PptxEditorProps, type PptxEditorTool, type PptxLegacyEditorProps, type PptxPlugin, type PptxPluginCommand, type PptxPluginCommandClient, type PptxPluginCommandDescriptor, type PptxPluginCommandId, type PptxPluginCommandResult, type PptxPluginCommandState, type PptxPluginContext, type PptxPluginDefinition, type PptxPluginEditClient, type PptxPluginError, type PptxPluginErrorPhase, type PptxPluginEvent, type PptxPluginFailureCode, type PptxPluginGeometry, type PptxPluginGrant, type PptxPluginLayout, type PptxPluginNavigation, type PptxPluginNavigationFailureCode, type PptxPluginNavigationOptions, type PptxPluginNavigationResult, type PptxPluginPanel, type PptxPluginPointPosition, type PptxPluginReadClient, type PptxPluginRect, type PptxPluginRefusal, type PptxPluginSelection, type PptxPluginSnapshot, PptxPluginToolbar, type PptxPointPosition, type PptxSelectCommandId, type PptxShapePreset, type PptxTextSelection, type PptxTextSelectionTarget, Toolbar as PptxToolbar, type PptxWorkerEditorApi, PptxWorkerEditorChunkLoadError, type PptxWorkerEditorProps, type PptxWorkerViewerApi, type PptxWorkerViewerProps, type PptxZOrderMove, type PptxZoom, SHAPE_PRESETS, type SelectionFormatting, type ShapeFormatting, type ShapeFormattingAction, type SlideLayoutOption, Toolbar, ToolbarButton, type ToolbarButtonProps, ToolbarCommand, type ToolbarCommandArgs, ToolbarCommandButton, type ToolbarCommandButtonProps, type ToolbarCommandProps, ToolbarCommandSelect, type ToolbarCommandSelectProps, ToolbarDropdown, type ToolbarDropdownProps, ToolbarGroup, ToolbarMenuItem, type ToolbarMenuItemProps, ToolbarMenuSeparator, ToolbarOverflow, type ToolbarOverflowProps, type ToolbarProps, ToolbarSeparator, definePptxPlugin, useEditorToolbar, usePptxCommand, usePptxCommandState, usePptxCommands, useTranslation };
1516
+ export { type CommandReason, type CommandState, type CommandToolbarProps, EditorToolbar, type EditorToolbarCommandProps, EditorToolbarContext, type EditorToolbarProps, type FormattingAction, type JsonValue, LocaleProvider, type LocaleProviderProps, type MaybePromise, type PluginCleanupReason, type PluginGrant, type PluginLoadReason, type PptxAnchorGeometryResult, type PptxAsyncCollaborationOptions, type PptxAsyncEditorAccess, type PptxAsyncEditorApi, type PptxAsyncEditorProps, type PptxBoundCommand, type PptxBoundPluginCommand, type PptxBundledFont, type PptxCommandAdmissionCode, PptxCommandAdmissionError, type PptxCommandArgs, type PptxCommandDescriptor, type PptxCommandDisabledCode, type PptxCommandFailureCode, type PptxCommandId, type PptxCommandOption, PptxCommandProvider, type PptxCommandProviderProps, type PptxCommandResult, type PptxCommandShortcut, type PptxCommandState, type PptxCommandStatus, type PptxCommandStore, type PptxCommandValues, type PptxControlCommandId, type PptxDocumentChange, PptxEditor, type PptxEditorApi, type PptxEditorCollaborationOptions, type PptxEditorPluginProps, type PptxEditorProps, type PptxEditorTool, type PptxGeometryTarget, type PptxLegacyEditorProps, type PptxPlugin, type PptxPluginCommand, type PptxPluginCommandClient, type PptxPluginCommandDescriptor, type PptxPluginCommandId, type PptxPluginCommandResult, type PptxPluginCommandState, type PptxPluginContext, type PptxPluginDefinition, type PptxPluginEditClient, type PptxPluginError, type PptxPluginErrorPhase, type PptxPluginEvent, type PptxPluginFailureCode, type PptxPluginFocusChangeEvent, type PptxPluginGeometry, type PptxPluginGrant, type PptxPluginLayout, type PptxPluginLocaleChangeEvent, type PptxPluginNavigation, type PptxPluginNavigationFailureCode, type PptxPluginNavigationOptions, type PptxPluginNavigationResult, type PptxPluginPanel, type PptxPluginPointPosition, type PptxPluginReadClient, type PptxPluginRect, type PptxPluginRefusal, type PptxPluginSelection, type PptxPluginSnapshot, PptxPluginToolbar, type PptxPluginViewportChangeEvent, type PptxPointPosition, type PptxSelectCommandId, type PptxShapePreset, type PptxShortcutId, type PptxShortcuts, type PptxTextSelection, type PptxTextSelectionTarget, Toolbar as PptxToolbar, type PptxWorkerEditorApi, PptxWorkerEditorChunkLoadError, type PptxWorkerEditorProps, type PptxWorkerViewerApi, type PptxWorkerViewerProps, type PptxZOrderMove, type PptxZoom, type ResolvedShortcuts, SHAPE_PRESETS, type SelectionFormatting, type ShapeFormatting, type ShapeFormattingAction, type ShortcutBinding, type ShortcutChord, type ShortcutIssue, type SlideLayoutOption, Toolbar, ToolbarButton, type ToolbarButtonProps, ToolbarCommand, type ToolbarCommandArgs, ToolbarCommandButton, type ToolbarCommandButtonProps, type ToolbarCommandProps, ToolbarCommandSelect, type ToolbarCommandSelectProps, ToolbarDropdown, type ToolbarDropdownProps, ToolbarGroup, ToolbarMenuItem, type ToolbarMenuItemProps, ToolbarMenuSeparator, ToolbarOverflow, type ToolbarOverflowProps, type ToolbarProps, ToolbarSeparator, definePptxPlugin, useEditorToolbar, usePptxCommand, usePptxCommandState, usePptxCommands, useTranslation };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{b as PptxEditor,a as PptxWorkerEditorChunkLoadError}from'./chunk-66PPYFHW.js';export{E as EditorToolbar,v as EditorToolbarContext,B as PptxPluginToolbar,D as PptxToolbar,D as Toolbar,A as ToolbarCommand,y as ToolbarCommandButton,z as ToolbarCommandSelect,C as ToolbarOverflow,Q as definePptxPlugin,w as useEditorToolbar}from'./chunk-X6B77B3U.js';export{a as LocaleProvider,w as PptxCommandAdmissionError,B as PptxCommandProvider,k as SHAPE_PRESETS,Z as ToolbarButton,ba as ToolbarDropdown,_ as ToolbarGroup,ca as ToolbarMenuItem,da as ToolbarMenuSeparator,$ as ToolbarSeparator,E as usePptxCommand,D as usePptxCommandState,C as usePptxCommands,b as useTranslation}from'./chunk-X2M23RXQ.js';import'./chunk-O2XFH626.js';
1
+ import {a as a$2}from'./chunk-ZGEHLLWI.js';import {a as a$1}from'./chunk-4TRQLEZF.js';import {a as a$3}from'./chunk-3WH2K5EA.js';export{p as EditorToolbar,c as EditorToolbarContext,i as PptxPluginToolbar,o as PptxToolbar,o as Toolbar,h as ToolbarCommand,f as ToolbarCommandButton,g as ToolbarCommandSelect,n as ToolbarOverflow,q as definePptxPlugin,d as useEditorToolbar}from'./chunk-3WH2K5EA.js';import {b,d as d$1}from'./chunk-LFHLWZA4.js';export{b as LocaleProvider,I as PptxCommandAdmissionError,N as PptxCommandProvider,h as SHAPE_PRESETS,$ as ToolbarButton,da as ToolbarDropdown,aa as ToolbarGroup,ea as ToolbarMenuItem,fa as ToolbarMenuSeparator,ba as ToolbarSeparator,R as usePptxCommand,Q as usePptxCommandState,P as usePptxCommands,d as useTranslation}from'./chunk-LFHLWZA4.js';import'./chunk-PSW72ZJN.js';import'./chunk-PS7ULZVL.js';import {a}from'./chunk-O2XFH626.js';import {useMemo,useState,useEffect,lazy,Suspense,Component,useRef}from'react';import {jsx}from'react/jsx-runtime';var E=new WeakMap;function oe(e,t,o){let n=E.get(e),a=n?{Component:n}:{loading:true},[i,p]=useState(()=>({load:e,identity:t,chunk:a})),s=useRef(null);return useEffect(()=>{if(n)return;let P=true;if(!s.current||s.current.load!==e||s.current.identity!==t){let l;try{l=e();}catch(O){l=Promise.reject(O);}s.current={load:e,identity:t,promise:l};}let m=s.current;return m.promise.then(l=>{!P||s.current!==m||(E.set(e,l.PeerlessPptxSurface),p({load:e,identity:t,chunk:{Component:l.PeerlessPptxSurface}}));}).catch(l=>{!P||s.current!==m||(E.delete(e),p({load:e,identity:t,chunk:{error:new o(l)}}));}),()=>{P=false;}},[e,t,o]),n?{Component:n}:i.load===e&&i.identity===t?i.chunk:{loading:true}}function A({load:e,identity:t,ErrorType:o,fallback:n,editorProps:a}){let i=oe(e,t,o);if("error"in i)throw i.error;return "Component"in i?jsx(i.Component,{...a}):n}var ie={load:()=>(import('./chunk-ABH6B26J.js').catch(()=>{}),import('./chunk-HOGGA6FO.js'))},se={load:()=>import('./chunk-7DAM3J5E.js')},pe={load:()=>import('./chunk-TZYGGEUO.js')},ae=()=>globalThis.location?.reload(),d=class extends Error{constructor(o){super("Failed to load the editor code. Reload the page to retry.");a(this,"cause",o);a(this,"code","chunk-load-failed");this.name="PptxWorkerEditorChunkLoadError";}};function le({error:e,className:t,style:o}){let n=e instanceof d;return jsx("div",{dir:"ltr",className:t,style:{position:"relative",width:"100%",height:"100%",...o},children:jsx(a$3,{kind:n?"load":"open",details:e.message,onReload:n?ae:void 0})})}var x=class extends Component{constructor(){super(...arguments);a(this,"state",{error:null});a(this,"reported",null);}static getDerivedStateFromError(o){return {error:o instanceof Error?o:new Error(String(o))}}componentDidCatch(){let o=this.state.error;if(!(!o||this.reported===o)){this.reported=o;try{this.props.onError?.(o);}catch{}}}render(){return this.state.error?jsx(le,{error:this.state.error,className:this.props.className,style:this.props.style}):this.props.children}};function de(e){let t=e[a$1]===true,o=e.fonts.some(n=>"face"in n);return jsx(b,{i18n:e.i18n,children:o?jsx(ce,{...e,legacy:t}):t?jsx(w,{editorProps:e}):jsx(Pe,{...e})})}function Pe(e){let t=useMemo(()=>e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,[e.file]);return jsx(F,{...e,file:t})}function ue(){let[e,t]=useState();return useEffect(()=>{ie.load().then(o=>t({module:o}),o=>t({error:new d(o)}));},[]),e}function xe({error:e}){throw e}function ce({legacy:e,...t}){let o=ue(),n=useMemo(()=>t.file instanceof ArrayBuffer?new Uint8Array(t.file):t.file,[t.file]),a=jsx(C,{...t,file:n});return jsx(x,{onError:t.onError,className:t.className,style:t.style,children:o?.error?jsx(xe,{error:o.error}):o?.module?jsx(o.module.BundledFontsResolver,{file:n,fonts:t.fonts,fallback:a,session:t,onReady:t.onReady,onError:t.onError,children:(i,p,s)=>{let P={...t,file:n,fonts:i,onReady:p,onError:s};return e?jsx(w,{editorProps:P}):jsx(F,{...P})}}):a})}function me({fallback:e,editorProps:t}){let[o]=useState(()=>lazy(()=>import('./chunk-7NYXRM44.js').then(n=>({default:n.PptxAsyncInThreadSession}),n=>{throw new d(n)})));return jsx(Suspense,{fallback:e,children:jsx(o,{...t})})}function F(e){let t=e.experimentalWorkerOpen===false,o=useMemo(()=>({}),[e.file,t]),n=()=>({identity:o,reason:t?"deprecated":typeof Worker!="function"?"no-worker":typeof OffscreenCanvas!="function"?"no-offscreen-canvas":void 0}),[a,i]=useState(n),p=a.identity===o?a:n();a!==p&&i(p),useEffect(()=>{p.reason&&a$2(p.reason);},[p.reason]);let s=jsx(C,{...e});return jsx(x,{onError:e.onError,className:e.className,style:e.style,children:p.reason?jsx(me,{fallback:s,editorProps:e}):jsx(A,{load:se.load,identity:o,ErrorType:d,fallback:s,editorProps:e})})}function C(e){let{t}=d$1();return jsx("div",{dir:"ltr",className:e.className,style:e.style,role:"status",children:e.file&&e.loadingIndicator!==void 0?e.loadingIndicator:t("worker.preparing")})}function w({editorProps:e}){let[t]=useState(()=>lazy(()=>pe.load().then(o=>({default:o.PptxEditorSession}),o=>{throw new d(o)})));return jsx(x,{onError:e.onError,className:e.className,children:jsx(Suspense,{fallback:jsx(C,{...e}),children:jsx(t,{...e})})})}export{de as PptxEditor,d as PptxWorkerEditorChunkLoadError};