polotno 3.16.1 → 3.18.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.
Files changed (51) hide show
  1. package/canvas/element.js +1 -1
  2. package/canvas/figure-element.js +1 -1
  3. package/canvas/gif-element.js +1 -1
  4. package/canvas/html-element.js +1 -1
  5. package/canvas/image-element.d.ts +15 -2
  6. package/canvas/image-element.js +1 -1
  7. package/canvas/line-element.js +1 -1
  8. package/canvas/page.js +1 -1
  9. package/canvas/placed-node.d.ts +22 -0
  10. package/canvas/placed-node.js +1 -0
  11. package/canvas/render-tag-element.js +1 -1
  12. package/canvas/rich-editor.js +2 -2
  13. package/canvas/table-element.js +1 -1
  14. package/canvas/text-element/auto-delete-empty-text.d.ts +15 -0
  15. package/canvas/text-element/auto-delete-empty-text.js +1 -0
  16. package/canvas/text-element/font-specs-loader.js +1 -1
  17. package/canvas/text-element.js +1 -1
  18. package/canvas/use-color.d.ts +2 -4
  19. package/canvas/use-color.js +1 -1
  20. package/canvas/use-image.js +1 -1
  21. package/canvas/video-element.js +1 -1
  22. package/canvas/workspace-canvas.js +1 -1
  23. package/model/group-model.d.ts +7 -0
  24. package/model/group-model.js +1 -1
  25. package/model/history.js +1 -1
  26. package/model/page-model.d.ts +15 -0
  27. package/model/page-model.js +1 -1
  28. package/model/store.d.ts +10 -7
  29. package/model/store.js +1 -1
  30. package/model/table-model.d.ts +3 -0
  31. package/model/table-model.js +1 -1
  32. package/package.json +19 -18
  33. package/pages-timeline/element-track.js +1 -1
  34. package/pages-timeline/page-preview.d.ts +9 -2
  35. package/pages-timeline/page-preview.js +1 -1
  36. package/polotno.bundle.js +171 -171
  37. package/side-panel/animations-panel.js +1 -1
  38. package/side-panel/text-panel.js +1 -1
  39. package/side-panel/text-template.js +1 -1
  40. package/utils/duplicate.js +1 -1
  41. package/utils/fonts.js +1 -1
  42. package/utils/from-svg.js +1 -1
  43. package/utils/image-dpi.js +1 -1
  44. package/utils/loader.js +1 -1
  45. package/utils/px.d.ts +1 -0
  46. package/utils/px.js +1 -1
  47. package/utils/ref-counted.d.ts +5 -0
  48. package/utils/ref-counted.js +1 -0
  49. package/utils/validate-key.js +1 -1
  50. package/utils/wait.d.ts +0 -1
  51. package/utils/wait.js +0 -1
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++){t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(o[i[r]]=e[i[r]])}}return o};import{isAlive as t,types as o}from"mobx-state-tree";import{nanoid as i}from"nanoid";import{GROUP_BLEND_MODES as r}from"@polotno/schema/defaults";import{Node as n}from"./node-model.js";import{Animation as s,Shape as l}from"./shape-model.js";import{animate as a}from"../utils/animations.js";import{polotnoError as d}from"@polotno/core/errors";import{getPlayheadLocalTime as c}from"../utils/timeline.js";import{getCenter as p,getTotalClientRect as h}from"../utils/math.js";import{TextElement as m}from"./text-model.js";import{ImageElement as y}from"./image-model.js";import{VideoElement as f}from"./video-model.js";import{LineElement as u}from"./line-model.js";import{SVGElement as g}from"./svg-model.js";import{FigureElement as E}from"./figure-model.js";import{GifElement as b}from"./gif-model.js";import{TableElement as v}from"./table-model.js";export const forEveryChild=(e,t)=>{if(e.children){for(const o of e.children){if(!0===t(o)){break}forEveryChild(o,t)}}};export{forEveryNode}from"@polotno/core/for-every-node";export function zIndexOps(e){const t=(t,o,i)=>{const r=t.map(t=>e.children.findIndex(e=>e.id===t)).filter(e=>-1!==e).sort((e,t)=>(t-e)*o);for(const n of r){const r=e.children[n+o];!r||t.indexOf(r.id)>=0||i(n)}},o=(e,o)=>{let i=!1;return t(e,o,()=>{i=!0}),i},i=(o,i)=>{t(o,i,t=>{const o=e.children.slice();[o[t],o[t+i]]=[o[t+i],o[t]],e.children.replace(o)})},r=(t,o)=>{const i=[],r=[];e.children.forEach(e=>{(t.indexOf(e.id)>=0?i:r).push(e)}),e.children.replace(o?r.concat(i):i.concat(r))};return{canMoveElementsUp:e=>o(e,1),canMoveElementsTop:e=>o(e,1),canMoveElementsDown:e=>o(e,-1),canMoveElementsBottom:e=>o(e,-1),moveElementsUp(e){i(e,1)},moveElementsDown(e){i(e,-1)},moveElementsTop(e){r(e,!0)},moveElementsBottom(e){r(e,!1)},setElementZIndex(t,o){const i=e.children.find(e=>e.id===t);if(i){const t=e.children.filter(e=>e!==i);t.splice(o,0,i),e.children.replace(t)}}}}const x=[...new Array(20)].map((e,t)=>o.late(()=>S[t]));export const ElementTypes=o.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t){const t=`Unknown element type: "${e.type}"`;throw d("DESIGN_INVALID",t,{errors:[{path:"type",message:t}],knownTypes:Object.keys(TYPES_MAP)})}return t}},g,m,y,u,f,E,b,v,o.late(()=>GroupElement),...x);const w=Object.freeze({x:0,y:0,offsetX:0,offsetY:0,scaleX:1,scaleY:1,rotation:0,opacity:1});function j(e){return 1===e?w:Object.assign(Object.assign({},w),{opacity:e})}const O={x:0,y:0,width:0,height:0,rotation:0,opacity:1,fontSize:0,cropX:0,cropY:0,cropWidth:1,cropHeight:1},P=(e,t)=>"number"==typeof e&&isFinite(e)?e:t;function C(e,t,o,i){O.x=e.x,O.y=e.y,O.width=e.width,O.height=e.height,O.opacity=i;const r=a({element:O,animation:t,dTime:o})||{},n=P(r.width,e.width),s=P(r.height,e.height);return{x:P(r.x,e.x),y:P(r.y,e.y),width:n>0?n:e.width,height:s>0?s:e.height,rotation:P(r.rotation,0),opacity:P(r.opacity,i)}}export const GroupElement=n.named("Group").props({type:"group",blendMode:o.optional(o.enumeration([...r]),"pass-through"),children:o.array(ElementTypes),animations:o.array(s)}).views(e=>({get draggable(){let t=!0;return forEveryChild(e,e=>{e.draggable||(t=!1)}),t},get resizable(){let t=!0;return forEveryChild(e,e=>{e.resizable||(t=!1)}),t},get contentEditable(){let t=!0;return forEveryChild(e,e=>{e.contentEditable||(t=!1)}),t},get styleEditable(){let t=!0;return forEveryChild(e,e=>{e.styleEditable||(t=!1)}),t},get locked(){let t=!0;return forEveryChild(e,e=>{e.locked||(t=!1)}),t},get _restingBbox(){const t=[];if(forEveryChild(e,e=>{var o,i,r;if("group"===e.type){return}const n=e.width,s=e.height;!n||!s||n<=0||s<=0||t.push({x:null!==(o=e.x)&&void 0!==o?o:0,y:null!==(i=e.y)&&void 0!==i?i:0,width:n,height:s,rotation:null!==(r=e.rotation)&&void 0!==r?r:0})}),!t.length){return null}const o=h(t);return o.width<=0||o.height<=0?null:{x:o.x,y:o.y,width:o.width,height:o.height}},get a(){if(!t(e)){return w}const o=c(e);if(null===o){return j(e.opacity)}if(e.store.isEditingPaused&&this.isSelectedDirectly){return j(e.opacity)}const i=e.page,r=e.store.animatedElementsIds;if(r.length&&!r.includes(e.id)){return j(e.opacity)}let n,s,l;for(const t of e.animations){t.enabled&&("enter"===t.type?n=t:"exit"===t.type?s=t:"loop"===t.type&&(l=t))}const a=!!n&&o<n.delay,d=!!n&&o>=n.delay&&o<=n.delay+n.duration,h=!a&&!d&&!!s&&o>=i.duration-s.duration-s.delay&&o<=i.duration-s.delay,m=!!s&&o>=i.duration-s.delay;if(!(a||d||h||m||l)){return j(e.opacity)}const y=this._restingBbox;if(!y){return j(e.opacity)}let f={x:y.x,y:y.y,width:y.width,height:y.height,rotation:0,opacity:e.opacity};a&&(f.opacity=0),d&&(f=C(y,n,o-n.delay,e.opacity)),h&&(f=C(y,s,o-(i.duration-s.duration-s.delay),e.opacity)),m&&(f.opacity=0),l&&(f=C(f,l,o,f.opacity));const u=p(f);return{x:u.x,y:u.y,offsetX:y.x+y.width/2,offsetY:y.y+y.height/2,scaleX:f.width/y.width,scaleY:f.height/y.height,rotation:f.rotation,opacity:f.opacity}},get isSelectedDirectly(){return!!t(e)&&e.store.selectedElements.indexOf(e)>=0&&e.selectable},get active(){return!0}})).actions(t=>Object.assign(Object.assign({set(o){var{draggable:i,contentEditable:r,styleEditable:n,resizable:s}=o,l=e(o,["draggable","contentEditable","styleEditable","resizable"]);void 0!==i&&forEveryChild(t,e=>{e.set({draggable:i})}),void 0!==r&&forEveryChild(t,e=>{e.set({contentEditable:r})}),void 0!==n&&forEveryChild(t,e=>{e.set({styleEditable:n})}),void 0!==s&&forEveryChild(t,e=>{e.set({resizable:s})}),Object.assign(t,l)},addElement(e,{skipSelect:o=!1}={}){const r=TYPES_MAP[e.type];if(!r){return void console.error("Can not find model with type "+e.type)}e.children&&e.children.forEach(e=>{e.id=e.id||i(10)});const n=r.create(Object.assign({id:i(10)},e));return t.children.push(n),n.selectable&&!o&&t.store.selectElements([n.id]),n}},zIndexOps(t)),{setAnimation(e,o){const i=t.animations.find(t=>t.type===e);i?Object.assign(i,o):t.animations.push(Object.assign({type:e},o))}}));const S=[];export const TYPES_MAP={svg:g,text:m,image:y,group:GroupElement,line:u,video:f,figure:E,gif:b,table:v};export function registerShapeModel(e,t){const o=e.type;if(!o){throw new Error('You must pass "type" attribute to custom model.')}const i=l.named(o).props(e),r=t?t(i):i;TYPES_MAP[o]=r,S.push(r)}
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++){t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(o[i[r]]=e[i[r]])}}return o};import{isAlive as t,types as o}from"mobx-state-tree";import{nanoid as i}from"nanoid";import{GROUP_BLEND_MODES as r}from"@polotno/schema/defaults";import{Node as n}from"./node-model.js";import{Animation as l,Shape as s}from"./shape-model.js";import{animate as a}from"../utils/animations.js";import{polotnoError as d}from"@polotno/core/errors";import{getPlayheadLocalTime as c}from"../utils/timeline.js";import{getCenter as p,getTotalClientRect as h}from"../utils/math.js";import{TextElement as m}from"./text-model.js";import{ImageElement as y}from"./image-model.js";import{VideoElement as f}from"./video-model.js";import{LineElement as u}from"./line-model.js";import{SVGElement as g}from"./svg-model.js";import{FigureElement as E}from"./figure-model.js";import{GifElement as b}from"./gif-model.js";import{TableElement as v}from"./table-model.js";export const forEveryChild=(e,t)=>{if(e.children){for(const o of e.children){if(!0===t(o)){break}forEveryChild(o,t)}}};export{forEveryNode}from"@polotno/core/for-every-node";export function zIndexOps(e){const t=(t,o,i)=>{const r=t.map(t=>e.children.findIndex(e=>e.id===t)).filter(e=>-1!==e).sort((e,t)=>(t-e)*o);for(const n of r){const r=e.children[n+o];!r||t.indexOf(r.id)>=0||i(n)}},o=(e,o)=>{let i=!1;return t(e,o,()=>{i=!0}),i},i=(o,i)=>{t(o,i,t=>{const o=e.children.slice();[o[t],o[t+i]]=[o[t+i],o[t]],e.children.replace(o)})},r=(t,o)=>{const i=[],r=[];e.children.forEach(e=>{(t.indexOf(e.id)>=0?i:r).push(e)}),e.children.replace(o?r.concat(i):i.concat(r))};return{canMoveElementsUp:e=>o(e,1),canMoveElementsTop:e=>o(e,1),canMoveElementsDown:e=>o(e,-1),canMoveElementsBottom:e=>o(e,-1),moveElementsUp(e){i(e,1)},moveElementsDown(e){i(e,-1)},moveElementsTop(e){r(e,!0)},moveElementsBottom(e){r(e,!1)},setElementZIndex(t,o){const i=e.children.find(e=>e.id===t);if(i){const t=e.children.filter(e=>e!==i);t.splice(o,0,i),e.children.replace(t)}},_reconcileChildren(t){const o=new Map(e.children.map(e=>[e.id,e]));e.children.replace(t.flatMap(e=>{var t;return null!==(t=o.get(e.id))&&void 0!==t?t:[]})),t.forEach((t,i)=>{o.has(t.id)||e.children.splice(i,0,t)})}}}const x=[...new Array(20)].map((e,t)=>o.late(()=>M[t]));export const ElementTypes=o.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t){const t=`Unknown element type: "${e.type}"`;throw d("DESIGN_INVALID",t,{errors:[{path:"type",message:t}],knownTypes:Object.keys(TYPES_MAP)})}return t}},g,m,y,u,f,E,b,v,o.late(()=>GroupElement),...x);const w=Object.freeze({x:0,y:0,offsetX:0,offsetY:0,scaleX:1,scaleY:1,rotation:0,opacity:1});function j(e){return 1===e?w:Object.assign(Object.assign({},w),{opacity:e})}const O={x:0,y:0,width:0,height:0,rotation:0,opacity:1,fontSize:0,cropX:0,cropY:0,cropWidth:1,cropHeight:1},C=(e,t)=>"number"==typeof e&&isFinite(e)?e:t;function P(e,t,o,i){O.x=e.x,O.y=e.y,O.width=e.width,O.height=e.height,O.opacity=i;const r=a({element:O,animation:t,dTime:o})||{},n=C(r.width,e.width),l=C(r.height,e.height);return{x:C(r.x,e.x),y:C(r.y,e.y),width:n>0?n:e.width,height:l>0?l:e.height,rotation:C(r.rotation,0),opacity:C(r.opacity,i)}}export const GroupElement=n.named("Group").props({type:"group",blendMode:o.optional(o.enumeration([...r]),"pass-through"),children:o.array(ElementTypes),animations:o.array(l)}).views(e=>({get draggable(){let t=!0;return forEveryChild(e,e=>{e.draggable||(t=!1)}),t},get resizable(){let t=!0;return forEveryChild(e,e=>{e.resizable||(t=!1)}),t},get contentEditable(){let t=!0;return forEveryChild(e,e=>{e.contentEditable||(t=!1)}),t},get styleEditable(){let t=!0;return forEveryChild(e,e=>{e.styleEditable||(t=!1)}),t},get locked(){let t=!0;return forEveryChild(e,e=>{e.locked||(t=!1)}),t},get _restingBbox(){const t=[];if(forEveryChild(e,e=>{var o,i,r;if("group"===e.type){return}const n=e.width,l=e.height;!n||!l||n<=0||l<=0||t.push({x:null!==(o=e.x)&&void 0!==o?o:0,y:null!==(i=e.y)&&void 0!==i?i:0,width:n,height:l,rotation:null!==(r=e.rotation)&&void 0!==r?r:0})}),!t.length){return null}const o=h(t);return o.width<=0||o.height<=0?null:{x:o.x,y:o.y,width:o.width,height:o.height}},get a(){if(!t(e)){return w}const o=c(e);if(null===o){return j(e.opacity)}if(e.store.isEditingPaused&&this.isSelectedDirectly){return j(e.opacity)}const i=e.page,r=e.store.animatedElementsIds;if(r.length&&!r.includes(e.id)){return j(e.opacity)}let n,l,s;for(const t of e.animations){t.enabled&&("enter"===t.type?n=t:"exit"===t.type?l=t:"loop"===t.type&&(s=t))}const a=!!n&&o<n.delay,d=!!n&&o>=n.delay&&o<=n.delay+n.duration,h=!a&&!d&&!!l&&o>=i.duration-l.duration-l.delay&&o<=i.duration-l.delay,m=!!l&&o>=i.duration-l.delay;if(!(a||d||h||m||s)){return j(e.opacity)}const y=this._restingBbox;if(!y){return j(e.opacity)}let f={x:y.x,y:y.y,width:y.width,height:y.height,rotation:0,opacity:e.opacity};a&&(f.opacity=0),d&&(f=P(y,n,o-n.delay,e.opacity)),h&&(f=P(y,l,o-(i.duration-l.duration-l.delay),e.opacity)),m&&(f.opacity=0),s&&(f=P(f,s,o,f.opacity));const u=p(f);return{x:u.x,y:u.y,offsetX:y.x+y.width/2,offsetY:y.y+y.height/2,scaleX:f.width/y.width,scaleY:f.height/y.height,rotation:f.rotation,opacity:f.opacity}},get isSelectedDirectly(){return!!t(e)&&e.store.selectedElements.indexOf(e)>=0&&e.selectable},get active(){return!0}})).actions(t=>Object.assign(Object.assign({set(o){var{draggable:i,contentEditable:r,styleEditable:n,resizable:l}=o,s=e(o,["draggable","contentEditable","styleEditable","resizable"]);void 0!==i&&forEveryChild(t,e=>{e.set({draggable:i})}),void 0!==r&&forEveryChild(t,e=>{e.set({contentEditable:r})}),void 0!==n&&forEveryChild(t,e=>{e.set({styleEditable:n})}),void 0!==l&&forEveryChild(t,e=>{e.set({resizable:l})}),Object.assign(t,s)},addElement(e,{skipSelect:o=!1}={}){const r=TYPES_MAP[e.type];if(!r){return void console.error("Can not find model with type "+e.type)}e.children&&e.children.forEach(e=>{e.id=e.id||i(10)});const n=r.create(Object.assign({id:i(10)},e));return t.children.push(n),n.selectable&&!o&&t.store.selectElements([n.id]),n}},zIndexOps(t)),{setAnimation(e,o){const i=t.animations.find(t=>t.type===e);i?Object.assign(i,o):t.animations.push(Object.assign({type:e},o))}}));const M=[];export const TYPES_MAP={svg:g,text:m,image:y,group:GroupElement,line:u,video:f,figure:E,gif:b,table:v};export function registerShapeModel(e,t){const o=e.type;if(!o){throw new Error('You must pass "type" attribute to custom model.')}const i=s.named(o).props(e),r=t?t(i):i;TYPES_MAP[o]=r,M.push(r)}
package/model/history.js CHANGED
@@ -1 +1 @@
1
- import{types as t,resolvePath as e,onSnapshot as o,getSnapshot as a,applySnapshot as n}from"mobx-state-tree";import{deepEqual as r}from"../utils/deep-equal.js";import{observable as d,when as s}from"mobx";Object.assign(t);export const UndoManager=t.model("UndoManager",{history:t.array(t.frozen()),undoIdx:-1,targetPath:""}).views(t=>({get canUndo(){return t.undoIdx>0},get canRedo(){return t.undoIdx<t.history.length-1}})).actions(t=>{let i,c,u=!1,l=null,h=0;const g=d.box(0);let m=null;const f=()=>g.get()>0;function p(){const t=a(i);return{pages:t.pages,width:t.width,height:t.height,custom:t.custom,audios:t.audios}}function y(t,e,o){let a=!1;const n=t.map(t=>{if(t.id===e){return a=!0,Object.assign(Object.assign({},t),o)}if(!t.children){return t}const n=y(t.children,e,o);return n===t.children?t:(a=!0,Object.assign(Object.assign({},t),{children:n}))});return a?n:t}function S(){const t=p();return m?Object.assign(Object.assign({},t),{pages:t.pages.map(t=>Object.assign(Object.assign({},t),{children:y(t.children,m.id,m.entry)}))}):t}function x(t){const e=i.pages.map(t=>t.id),o=t.pages.map(t=>t.id),a=!r(e,o),d=!r(i.custom,t.custom);a?n(i.pages,t.pages):i.pages.forEach((e,o)=>{n(e,t.pages[o])}),d&&i.set({custom:t.custom}),n(i.audios,t.audios),i.setSize(t.width,t.height)}const U={startTransaction(){g.set(g.get()+1)},endTransaction(t){g.set(Math.max(0,g.get()-1)),t||U.requestAddState(S())},async ignore(t,e=!1,o=!1){o&&await new Promise(t=>setTimeout(t,10));const a=!!h;h&&U.addUndoState();let n=f();U.startTransaction();const r=g.get();try{await t()}catch(i){setTimeout(()=>{throw i})}const d=r!==g.get(),s=!d;U.endTransaction(s),e||n&&!a||U.replaceState(),d||(clearTimeout(h),h=0)},async transaction(t){await U.ignore(t,!0),f()||U.addUndoState()},_whenIdle:t=>s(()=>!f(),{signal:t}),_commitToolChange(t){if(f()){return!1}const e=p();U.requestAddState(S()),U.addUndoState();try{t()}catch(o){throw x(e),o}return U.requestAddState(S()),U.addUndoState(),!0},_startDraft(t,e){h&&U.addUndoState(),m={id:t,entry:e,state:p()}},_draftChange(t){t(),m&&(m.state=p())},_commitDraft(){m&&(h&&U.addUndoState(),l=m.state,m=null,U.addUndoState())},_discardDraft(){m=null},requestAddState(t){l=t,h||f()||(u?u=!1:h=setTimeout(()=>{h=0,clearTimeout(h),f()||U.addUndoState()},100))},addUndoState(){if(u){return void(u=!1)}const e=t.history[t.undoIdx];!r(l,e)&&(clearTimeout(h),h=0,t.history.splice(t.undoIdx+1),t.history.push(l),t.undoIdx=t.history.length-1)},afterCreate(){if(i=e(t,".."),!i){throw new Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment")}c=o(i,()=>{m&&(m.state=p()),U.requestAddState(S())}),0===t.history.length&&U.requestAddState(S())},clear(){clearTimeout(h),h=0,t.history.splice(0,t.history.length),t.undoIdx=-1,U.addUndoState()},beforeDestroy(){c()},undo(){var e;if(!(null===(e=i._beforeToolHistory)||void 0===e?void 0:e.call(i,"undo"))){if(h&&U.addUndoState(),f()){const e=t.history[t.undoIdx];return void(e&&x(e))}t.canUndo?(t.undoIdx--,u=!0,x(t.history[t.undoIdx])):console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.")}},redo(){var e;h&&U.addUndoState(),t.canRedo?(null===(e=i._beforeToolHistory)||void 0===e||e.call(i,"redo"),t.undoIdx++,u=!0,x(t.history[t.undoIdx])):console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.")},replaceState(){t.history[t.undoIdx]=S()}};return U});export default UndoManager;
1
+ import{types as t,resolvePath as e,onSnapshot as n,getSnapshot as o,applySnapshot as r}from"mobx-state-tree";import{deepEqual as a}from"../utils/deep-equal.js";import{observable as d,when as s}from"mobx";Object.assign(t);export const UndoManager=t.model("UndoManager",{history:t.array(t.frozen()),undoIdx:-1,targetPath:""}).views(t=>({get canUndo(){return t.undoIdx>0},get canRedo(){return t.undoIdx<t.history.length-1}})).actions(t=>{let i,c,l=!1,u=null,h=0;const g=d.box(0);let f=null;const m=()=>g.get()>0;function y(){const t=o(i);return{pages:t.pages,width:t.width,height:t.height,custom:t.custom,audios:t.audios}}function p(t,e,n){let o=!1;const r=t.map(t=>{if(t.id===e){return o=!0,Object.assign(Object.assign({},t),n)}if(!t.children){return t}const r=p(t.children,e,n);return r===t.children?t:(o=!0,Object.assign(Object.assign({},t),{children:r}))});return o?r:t}function S(){const t=y();return f?Object.assign(Object.assign({},t),{pages:t.pages.map(t=>Object.assign(Object.assign({},t),{children:p(t.children,f.id,f.entry)}))}):t}function b(t,e){return t.length===e.length&&t.every((t,n)=>t.id===e[n].id)}function x(t){return o(t.children,!1)}function U(t,e){var n;const d=null!==(n=e.children)&&void 0!==n?n:[];let s=x(t);b(s,d)||(t._reconcileChildren(d),s=x(t)),r(t,Object.assign(Object.assign({},e),{children:d.map((e,n)=>e.children&&e!==s[n]?(U(t.children[n],e),o(t.children[n])):a(e,s[n])?s[n]:e)}))}function w(t){const e=t.pages;let n=o(i.pages);b(n,e)||(i._reconcilePages(e),n=o(i.pages)),e.forEach((t,e)=>{t!==n[e]&&U(i.pages[e],t)}),a(i.custom,t.custom)||i.set({custom:t.custom}),r(i.audios,t.audios),i.setSize(t.width,t.height)}const I={startTransaction(){g.set(g.get()+1)},endTransaction(t){g.set(Math.max(0,g.get()-1)),t||I.requestAddState(S())},async ignore(t,e=!1,n=!1){n&&await new Promise(t=>setTimeout(t,10));const o=!!h;h&&I.addUndoState();let r=m();I.startTransaction();const a=g.get();try{await t()}catch(i){setTimeout(()=>{throw i})}const d=a!==g.get(),s=!d;I.endTransaction(s),e||r&&!o||I.replaceState(),d||(clearTimeout(h),h=0)},async transaction(t){await I.ignore(t,!0),m()||I.addUndoState()},_whenIdle:t=>s(()=>!m(),{signal:t}),_commitToolChange(t){if(m()){return!1}const e=y();I.requestAddState(S()),I.addUndoState();try{t()}catch(n){throw w(e),n}return I.requestAddState(S()),I.addUndoState(),!0},_startDraft(t,e){h&&I.addUndoState(),f={id:t,entry:e,state:y()}},_draftChange(t){t(),f&&(f.state=y())},_commitDraft(){f&&(h&&I.addUndoState(),u=f.state,f=null,I.addUndoState())},_discardDraft(){f=null},requestAddState(t){u=t,h||m()||(l?l=!1:h=setTimeout(()=>{h=0,clearTimeout(h),m()||I.addUndoState()},100))},addUndoState(){if(l){return void(l=!1)}const e=t.history[t.undoIdx];!a(u,e)&&(clearTimeout(h),h=0,t.history.splice(t.undoIdx+1),t.history.push(u),t.undoIdx=t.history.length-1)},afterCreate(){if(i=e(t,".."),!i){throw new Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment")}c=n(i,()=>{f&&(f.state=y()),I.requestAddState(S())}),0===t.history.length&&I.requestAddState(S())},clear(){clearTimeout(h),h=0,t.history.splice(0,t.history.length),t.undoIdx=-1,I.addUndoState()},beforeDestroy(){c()},undo(){var e;if(!(null===(e=i._beforeToolHistory)||void 0===e?void 0:e.call(i,"undo"))){if(h&&I.addUndoState(),m()){const e=t.history[t.undoIdx];return void(e&&w(e))}t.canUndo?(t.undoIdx--,l=!0,w(t.history[t.undoIdx])):console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.")}},redo(){var e;h&&I.addUndoState(),t.canRedo?(null===(e=i._beforeToolHistory)||void 0===e||e.call(i,"redo"),t.undoIdx++,l=!0,w(t.history[t.undoIdx])):console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.")},replaceState(){t.history[t.undoIdx]=S()}};return I});export default UndoManager;
@@ -1921,6 +1921,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
1921
1921
  } & {
1922
1922
  getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
1923
1923
  readonly minWidth: number;
1924
+ readonly basePixelRowHeights: number[];
1925
+ contentFloors(divider?: number): number[];
1926
+ readonly rowContentFloors: number[];
1924
1927
  getRowContentOuterHeight(row: number): number;
1925
1928
  readonly minHeight: number;
1926
1929
  readonly actualHeight: number;
@@ -1983,6 +1986,7 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
1983
1986
  _exporting: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1984
1987
  _rendering: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1985
1988
  _forceMount: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1989
+ _exportRendered: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1986
1990
  }, {
1987
1991
  readonly store: any;
1988
1992
  } & {
@@ -2012,6 +2016,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
2012
2016
  moveElementsTop(ids: Array<string>): void;
2013
2017
  moveElementsBottom(ids: Array<string>): void;
2014
2018
  setElementZIndex(id: string, zIndex: number): void;
2019
+ _reconcileChildren(items: readonly {
2020
+ id: string;
2021
+ }[]): void;
2015
2022
  clone(attrs?: {}): any;
2016
2023
  setZIndex(zIndex: number): void;
2017
2024
  set(attrs: Partial<SnapshotIn<import("mobx-state-tree").ModelInstanceTypeProps<{
@@ -3934,6 +3941,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
3934
3941
  } & {
3935
3942
  getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
3936
3943
  readonly minWidth: number;
3944
+ readonly basePixelRowHeights: number[];
3945
+ contentFloors(divider?: number): number[];
3946
+ readonly rowContentFloors: number[];
3937
3947
  getRowContentOuterHeight(row: number): number;
3938
3948
  readonly minHeight: number;
3939
3949
  readonly actualHeight: number;
@@ -3996,6 +4006,7 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
3996
4006
  _exporting: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
3997
4007
  _rendering: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
3998
4008
  _forceMount: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
4009
+ _exportRendered: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
3999
4010
  }> & {
4000
4011
  readonly store: any;
4001
4012
  } & {
@@ -5929,6 +5940,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
5929
5940
  } & {
5930
5941
  getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
5931
5942
  readonly minWidth: number;
5943
+ readonly basePixelRowHeights: number[];
5944
+ contentFloors(divider?: number): number[];
5945
+ readonly rowContentFloors: number[];
5932
5946
  getRowContentOuterHeight(row: number): number;
5933
5947
  readonly minHeight: number;
5934
5948
  readonly actualHeight: number;
@@ -5991,6 +6005,7 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
5991
6005
  _exporting: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
5992
6006
  _rendering: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
5993
6007
  _forceMount: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
6008
+ _exportRendered: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
5994
6009
  }, {
5995
6010
  readonly store: any;
5996
6011
  } & {
@@ -1 +1 @@
1
- import{getParentOfType as e,getSnapshot as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as n}from"nanoid";import{resolveBleed as r}from"@polotno/schema";import{hasBlendMode as s}from"@polotno/core/page";import{ElementTypes as d,forEveryChild as a,forEveryNode as m,TYPES_MAP as c,zIndexOps as l}from"./group-model.js";import{Store as h}from"./store.js";import{getTotalClientRect as p}from"../utils/math.js";import{scaledFontSizeBounds as g}from"../utils/px.js";const u=i.model("Page",{id:i.identifier,children:i.array(i.late(()=>d)),width:i.optional(i.union(i.number,i.literal("auto")),"auto"),height:i.optional(i.union(i.number,i.literal("auto")),"auto"),background:"white",bleed:0,bleedTop:i.maybe(i.number),bleedRight:i.maybe(i.number),bleedBottom:i.maybe(i.number),bleedLeft:i.maybe(i.number),custom:i.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot(e=>{const t=Object.assign({},e),o={};for(var i in t){"_"!==i[0]&&(o[i]=e[i])}return o}).views(t=>({get store(){return e(t,h)}})).views(e=>({get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id){return t}t+=o.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering},get playheadLocalTime(){if(!o(e)){return null}const t=e.store;if(!(null==t?void 0:t.playheadAccurate)){return null}const i=t.effectiveTime-this.startTime;return i<0||i>e.duration?null:Math.min(i,Math.max(0,e.duration-1))}})).views(e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height},get computedBleed(){return r(e)},get hasBlendMode(){return s(e.children)}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify(t(e)))})).actions(e=>Object.assign(Object.assign({clone(t={}){const o=e.toJSON(),i=new Map;o.children.forEach(e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o,m(e,e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o})}),o.children.forEach(e=>{e.cells&&e.cells.forEach(e=>{e.mergedInto&&i.has(e.mergedInto)&&(e.mergedInto=i.get(e.mergedInto))})});const r=Object.assign(Object.assign(Object.assign({},o),{id:n(10)}),t),s=e.store.selectedPages.includes(e),d=e.store.addPage(r),a=e.store.pages.indexOf(e);return d.setZIndex(a+1),s&&e.store.selectPages([d.id]),d},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:o=!1}={}){const i=c[t.type];if(!i){return void console.error("Can not find model with type "+t.type)}"children"in t&&Array.isArray(t.children)&&m(t,e=>{e.id=e.id||n(10)});const r=e.children.reduce((e,o)=>{if("group"===o.type){const i=o.children.reduce((e,o)=>{var i;const n=null===(i=o.name)||void 0===i?void 0:i.match(new RegExp(`${t.type}-(\\d+)`));if(n){const t=parseInt(n[1],10);return Math.max(e,t||0)}},0);return Math.max(e,i||0)}{const i=o.name.match(new RegExp(`${t.type}-(\\d+)`));if(i){const t=parseInt(i[1],10);return Math.max(e,t||0)}}return e},0),s=i.create(Object.assign({id:n(10),name:`${t.type}-${r+1}`},t));return e.children.push(s),s.selectable&&!o&&e.store.selectElements([s.id]),s}},l(e)),{setSize({width:t,height:o,useMagic:i,softChange:n}){if(i){const i=[],n=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;a(e,e=>{"group"!==e.type&&(n(e)||i.push(e))});const r=i.length?p(i):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},s=1/4,d=Math.max(0,Math.min(r.x,e.computedWidth-r.x-r.width)),m=e.computedWidth*s,c=Math.max(0,d-m),l=Math.max(0,Math.min(r.y,e.computedHeight-r.y-r.height)),h=e.computedHeight*s,u=Math.max(0,l-h),f=e.computedWidth-2*c,b=e.computedHeight-2*u,y=t/f,w=o/b,v=Math.min(y,w),x=(t-f*v)/2-c*v,E=(o-b*v)/2-u*v;a(e,e=>{var t;if("group"!==e.type){if(n(e)){e.set({x:e.x*v,y:e.y*v,width:e.width*y,height:e.height*w,cropX:0,cropY:0,cropWidth:1,cropHeight:1})}else if(e.set({x:x+e.x*v,y:E+e.y*v,width:e.width*v,height:e.height*v}),"text"===e.type){e.set(Object.assign({fontSize:e.fontSize*v},g(e,v)))}else if("figure"===e.type){e.set({strokeWidth:e.strokeWidth*v})}else if("table"===e.type){e.set({borderWidth:e.borderWidth*v});for(const o of e.cells){const e={fontSize:o.fontSize*v,cellPadding:o.cellPadding*v};if(o.borders){const i=JSON.parse(JSON.stringify(o.borders));for(const e of["top","right","bottom","left"]){null!=(null===(t=i[e])||void 0===t?void 0:t.width)&&(i[e]=Object.assign(Object.assign({},i[e]),{width:i[e].width*v}))}e.borders=i}o.set(e)}}}})}n||(e.width=t),n||(e.height=o)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));export const Page=u;
1
+ import{getParentOfType as e,getSnapshot as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as n}from"nanoid";import{resolveBleed as r}from"@polotno/schema";import{hasBlendMode as s}from"@polotno/core/page";import{ElementTypes as d,forEveryChild as a,forEveryNode as m,TYPES_MAP as c,zIndexOps as l}from"./group-model.js";import{Store as h}from"./store.js";import{getTotalClientRect as p}from"../utils/math.js";import{scaledFontSizeBounds as g}from"../utils/px.js";const u=i.model("Page",{id:i.identifier,children:i.array(i.late(()=>d)),width:i.optional(i.union(i.number,i.literal("auto")),"auto"),height:i.optional(i.union(i.number,i.literal("auto")),"auto"),background:"white",bleed:0,bleedTop:i.maybe(i.number),bleedRight:i.maybe(i.number),bleedBottom:i.maybe(i.number),bleedLeft:i.maybe(i.number),custom:i.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1,_exportRendered:!1}).postProcessSnapshot(e=>{const t=Object.assign({},e),o={};for(var i in t){"_"!==i[0]&&(o[i]=e[i])}return o}).views(t=>({get store(){return e(t,h)}})).views(e=>({get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id){return t}t+=o.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering},get playheadLocalTime(){if(!o(e)){return null}const t=e.store;if(!(null==t?void 0:t.playheadAccurate)){return null}const i=t.effectiveTime-this.startTime;return i<0||i>e.duration?null:Math.min(i,Math.max(0,e.duration-1))}})).views(e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height},get computedBleed(){return r(e)},get hasBlendMode(){return s(e.children)}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify(t(e)))})).actions(e=>Object.assign(Object.assign({clone(t={}){const o=e.toJSON(),i=new Map;o.children.forEach(e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o,m(e,e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o})}),o.children.forEach(e=>{e.cells&&e.cells.forEach(e=>{e.mergedInto&&i.has(e.mergedInto)&&(e.mergedInto=i.get(e.mergedInto))})});const r=Object.assign(Object.assign(Object.assign({},o),{id:n(10)}),t),s=e.store.selectedPages.includes(e),d=e.store.addPage(r),a=e.store.pages.indexOf(e);return d.setZIndex(a+1),s&&e.store.selectPages([d.id]),d},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:o=!1}={}){const i=c[t.type];if(!i){return void console.error("Can not find model with type "+t.type)}"children"in t&&Array.isArray(t.children)&&m(t,e=>{e.id=e.id||n(10)});const r=e.children.reduce((e,o)=>{if("group"===o.type){const i=o.children.reduce((e,o)=>{var i;const n=null===(i=o.name)||void 0===i?void 0:i.match(new RegExp(`${t.type}-(\\d+)`));if(n){const t=parseInt(n[1],10);return Math.max(e,t||0)}},0);return Math.max(e,i||0)}{const i=o.name.match(new RegExp(`${t.type}-(\\d+)`));if(i){const t=parseInt(i[1],10);return Math.max(e,t||0)}}return e},0),s=i.create(Object.assign({id:n(10),name:`${t.type}-${r+1}`},t));return e.children.push(s),s.selectable&&!o&&e.store.selectElements([s.id]),s}},l(e)),{setSize({width:t,height:o,useMagic:i,softChange:n}){if(i){const i=[],n=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;a(e,e=>{"group"!==e.type&&(n(e)||i.push(e))});const r=i.length?p(i):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},s=1/4,d=Math.max(0,Math.min(r.x,e.computedWidth-r.x-r.width)),m=e.computedWidth*s,c=Math.max(0,d-m),l=Math.max(0,Math.min(r.y,e.computedHeight-r.y-r.height)),h=e.computedHeight*s,u=Math.max(0,l-h),f=e.computedWidth-2*c,b=e.computedHeight-2*u,y=t/f,w=o/b,x=Math.min(y,w),v=(t-f*x)/2-c*x,E=(o-b*x)/2-u*x;a(e,e=>{var t;if("group"!==e.type){if(n(e)){e.set({x:e.x*x,y:e.y*x,width:e.width*y,height:e.height*w,cropX:0,cropY:0,cropWidth:1,cropHeight:1})}else if(e.set({x:v+e.x*x,y:E+e.y*x,width:e.width*x,height:e.height*x}),"text"===e.type){e.set(Object.assign({fontSize:e.fontSize*x},g(e,x)))}else if("figure"===e.type){e.set({strokeWidth:e.strokeWidth*x})}else if("table"===e.type){e.set({borderWidth:e.borderWidth*x});for(const o of e.cells){const e={fontSize:o.fontSize*x,cellPadding:o.cellPadding*x};if(o.borders){const i=JSON.parse(JSON.stringify(o.borders));for(const e of["top","right","bottom","left"]){null!=(null===(t=i[e])||void 0===t?void 0:t.width)&&(i[e]=Object.assign(Object.assign({},i[e]),{width:i[e].width*x}))}e.borders=i}o.set(e)}}}})}n||(e.width=t),n||(e.height=o)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));export const Page=u;
package/model/store.d.ts CHANGED
@@ -22,7 +22,6 @@ export interface ExportOptions {
22
22
  includeBleed?: boolean;
23
23
  mimeType?: 'image/png' | 'image/jpeg';
24
24
  quality?: number;
25
- _skipTimeout?: boolean;
26
25
  quickMode?: boolean;
27
26
  _exportCanvases?: ReturnType<typeof createExportCanvases>;
28
27
  }
@@ -222,6 +221,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
222
221
  _validated: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
223
222
  }, {
224
223
  highlightedElementId: string | null;
224
+ _workspaces: number;
225
225
  } & {
226
226
  setTool: import("./image-tools.js").SetTool;
227
227
  _setImageEditPanelAvailable(value: boolean): void;
@@ -663,13 +663,17 @@ export declare const Store: import("mobx-state-tree").IModelType<{
663
663
  setElementsPixelRatio(ratio: number): void;
664
664
  setSize(width: number, height: number, useMagic?: boolean): void;
665
665
  setPageZIndex(id: string, zIndex: number): void;
666
+ _reconcilePages(items: ReadonlyArray<{
667
+ id: string;
668
+ }>): void;
666
669
  deletePages(ids: Array<string>): void;
667
670
  groupElements(ids: Array<string>, attrs?: any): any;
668
671
  ungroupElements(ids: Array<string>): void;
669
672
  deleteElements(ids: Array<string>): void;
670
673
  on(event: any, callback: any): import("mobx-state-tree").IDisposer | undefined;
671
- _toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, quickMode, _exportCanvases, }?: ExportOptions): Promise<HTMLCanvasElement>;
672
- toDataURL({ mimeType, quality, dpi, dpiMetadata, ...rest }?: ImageExportOptions): Promise<string>;
674
+ _toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, quickMode, _exportCanvases, }?: ExportOptions): Promise<HTMLCanvasElement>;
675
+ _toDataURL({ mimeType, quality, dpi, dpiMetadata, ...rest }?: ImageExportOptions): Promise<string>;
676
+ toDataURL(exportProps?: ImageExportOptions): Promise<string>;
673
677
  toBlob({ mimeType, quality, ...rest }?: ExportOptions): Promise<Blob>;
674
678
  saveAsImage({ fileName, ...exportProps }?: ImageExportOptions & {
675
679
  fileName?: string;
@@ -701,9 +705,8 @@ export declare const Store: import("mobx-state-tree").IModelType<{
701
705
  saveAsPDF({ fileName, ...exportProps }?: ExportOptions & {
702
706
  fileName?: string;
703
707
  }): Promise<void>;
704
- waitLoading({ _skipTimeout }?: {
705
- _skipTimeout?: boolean | undefined;
706
- }): Promise<void>;
708
+ _setWorkspaceMounted(mounted: boolean): void;
709
+ waitLoading(): Promise<void>;
707
710
  toJSON(): {
708
711
  width: number;
709
712
  height: number;
@@ -738,7 +741,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
738
741
  removeFont(fontFamily: string): void;
739
742
  addAudio(data: Partial<SnapshotIn<typeof Audio>>): void;
740
743
  removeAudio(audioId: string): void;
741
- loadFont(fontFamily: string, fontStyle?: string, fontWeight?: string, sampleText?: string): Promise<void[]>;
744
+ loadFont(fontFamily: string, fontStyle?: string, fontWeight?: string, sampleText?: string): Promise<void | any[]>;
742
745
  validate(json: any): {
743
746
  path: string;
744
747
  message: string | undefined;
package/model/store.js CHANGED
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{localFileToURL as v}from"../utils/file.js";import{getJsPDF as y}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as P,setKey as x}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as E}from"../utils/flags.js";import{addDpiMetadataToImage as I}from"../utils/image-dpi.js";import{nodeToCanvas as T,createExportCanvases as _,releaseExportCanvases as O}from"../utils/canvas.js";import{whenLoaded as S}from"../utils/loader.js";import{polotnoError as k}from"@polotno/core/errors";import{pxToUnit as j}from"../utils/unit.js";import{deepEqual as F}from"../utils/deep-equal.js";import{waitTillAvailable as R}from"../utils/wait.js";import{jsonToHTML as A}from"@polotno/html-export";import{jsonToSVG as V}from"@polotno/svg-export";import{warnOnceDeprecated as C}from"../utils/deprecation.js";import{Page as L}from"./page-model.js";import{forEveryChild as M,forEveryNode as B}from"./group-model.js";import{Audio as D}from"./audio-model.js";import{imageTools as H}from"./image-tools.js";import{IMAGE_TOOLS as W}from"../image-tools/sessions.js";function N(e){return!!e&&!!e.type&&"tablecell"!==e.type}r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));const G=l.model("BrushOptions",{strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)});export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(L),fonts:l.array(Font),audios:l.array(D),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser","crop","expand","inpaint","upscale","remove-background"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),brush:l.optional(G,{}),highlighter:l.optional(G,{strokeWidth:30,opacity:.5})}).views(e=>({get active(){return e[e.brushType]}})).views(e=>({get strokeWidth(){return e.active.strokeWidth},get stroke(){return e.active.stroke},get opacity(){return e.active.opacity}})),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).volatile(()=>({highlightedElementId:null})).extend(H).views(e=>{const t=g(()=>{const t={};return B({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(N)},get children(){return e.pages},get selectedShapes(){const e=[];return M({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){const t=e.activeTool;return"crop"===(null==t?void 0:t.name)?this.getElementById(t.elementId):void 0},find(t){let o;return B({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(P(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setToolOptions(t){const{brushType:o}=t,i=e(t,["brushType"]);o&&(r.toolOptions.brushType=o),Object.assign(r.toolOptions.active,i)},addPage(e){const t=L.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){r._beforeToolSelection(e);const t=e.map(e=>r.getElementById(e)).filter(N);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},highlightElement(e){r.highlightedElementId=e},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&("image-edit"!==e&&r._beforeToolPanel(),r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){r._beforeToolPanel();const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.sort((e,t)=>a.children.indexOf(e)-a.children.indexOf(t));const s=a.children.indexOf(i[i.length-1])-i.length+1;i.forEach(e=>n(e));const l=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),d=Object.assign({id:p(10),name:`group-${l+1}`,children:i,type:"group"},t);return a.children.splice(s,0,d),r.selectedElementsIds=o([d.id]),a.children.find(e=>e.id===d.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)});const a=e.children.slice();a.forEach(t=>{t.set({opacity:t.opacity*e.opacity}),n(t)}),t.children.splice(o,1,...a)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!F(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;o=o||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===o);if(!g){throw k("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;try{(s?p>r._elementsPixelRatio:p!==r._elementsPixelRatio)&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const e=await R(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!e){throw k("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const d=e[0];await f.waitLoading({_skipTimeout:a});const u=d.findOne(".page-container");if(!u){throw k("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const h=d.position();d.position({x:0,y:0}),d.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),u.find(".page-background").forEach(e=>e.shadowEnabled(!1)),u.find(".page-background").forEach(e=>e.strokeEnabled(!1)),u.find(".highlighter").forEach(e=>e.visible(!1));const v=u.findOne(".page-background-group"),y=v.clip();v.clip({x:null,y:null,width:null,height:null});const b=u.findOne(".elements-container"),P=b.clip();b.clip({x:null,y:null,width:null,height:null});const x=u.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const w=u.find(e=>e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&u.find(".page-background").forEach(e=>e.hide());const I=n?g.computedBleed:m;let _=I.left,O=I.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(_=0,O=0):r.bleedVisible&&!n&&(_=-g.computedBleed.left,O=-g.computedBleed.top):(_=0,O=0));const S=g.computedWidth+I.left+I.right,j=g.computedHeight+I.top+I.bottom,F=u.scale();u.scale({x:1,y:1});const A=T(u,{x:u.x()-_,y:u.y()-O,width:S,height:j,pixelRatio:p,imageSmoothingQuality:E.imageDownScalingEnabled&&!s?"high":void 0,sceneCanvas:null==l?void 0:l.sceneCanvas});u.scale(F);const V=A._canvas;if("image/jpeg"===i){const e=V.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,V.width,V.height),e.restore()}return t&&u.find(".page-background").forEach(e=>e.show()),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".page-background").forEach(e=>e.shadowEnabled(!0)),u.find(".page-background").forEach(e=>e.strokeEnabled(!0)),d.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".highlighter").forEach(e=>e.visible(!0)),v.clip(y),b.clip(P),d.position(h),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),V}finally{f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1})}},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:I(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await y(),d=e=>j({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),v=d(g.computedHeight+u.top+u.bottom+2*c);var b=new l({unit:i,orientation:h>v?"landscape":"portrait",format:[h,v],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let x=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++x/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{b.addPage([t,o],t>o?"landscape":"portrait");const r=b.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw k("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){b.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);b.line(e,0,e,c),b.line(0,n,c,n),b.line(t-i,0,t-i,c),b.line(t,n,t-c,n),b.line(0,o-a,c,o-a),b.line(e,o,e,o-c),b.line(t,o-a,t-c,o-a),b.line(t-i,o,t-i,o-c)}b.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){var t,o;const i=e.pixelRatio||1,n=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),a=r.pages.filter(e=>n.includes(e.id));if(!a.length){throw k("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}null===(t=e.onProgress)||void 0===t||t.call(e,0,"rendering");const s=a[0],l=await b({width:s.computedWidth*i,height:s.computedHeight*i}),d=1e3/(e.fps||10),p=a.map(e=>({page:e,frames:Math.max(1,Math.floor(e.duration/d))})),c=p.reduce((e,{frames:t})=>e+t,0);let g=0;const m=_(),u=r._elementsPixelRatio;f.setElementsPixelRatio(i);try{for(const{page:t,frames:n}of p){for(let a=0;a<n;a++){const n=t.startTime+a*d||1;f.setCurrentTime(n);for(const e of r.pages){e.set({_rendering:e.id===t.id})}const s=await f._toCanvas({pixelRatio:i,pageId:t.id,_skipTimeout:!0,_exportCanvases:m});l.addFrame(s.getContext("2d"),{delay:d,copy:!0}),g++,null===(o=e.onProgress)||void 0===o||o.call(e,g/c/2,"rendering")}}}finally{O(m),f.setElementsPixelRatio(u);for(const e of r.pages){e.set({_rendering:!1})}f.stop()}return new Promise((t,o)=>{let i=!1;e.onProgress&&l.on("progress",t=>{var n;if(!i){try{null===(n=e.onProgress)||void 0===n||n.call(e,.5+t/2,"encoding")}catch(a){i=!0,o(a)}}}),l.on("finished",e=>{i||v(e).then(t,o)}),l.render()})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){C("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return A(t,{elementHook:e,textOverflow:E.textOverflow,textSplitAllowed:E.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;C("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return V(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),Object.assign({elementHook:e,fontEmbedding:o,textSplitAllowed:E.textSplitAllowed},"fit"===E.textOverflow&&{textOverflow:"fit"}))},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await S()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,l="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=u(e,{modernTextRenderer:E.htmlRenderEnabled||E.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion,d.tool in W&&delete d.tool;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[],r._closeImageTool("discard"),M(r,e=>{var t;"pendingEdit"in e&&(null===(t=e.pendingEdit)||void 0===t||t.cancel())});const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.fonts.filter(t=>t.fontFamily===e.fontFamily).forEach(e=>i(e)),r.fonts.push(e),w.injectCustomFont(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e)),w.removeCustomFont(e)},addAudio(e){const t=D.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(n=>(n.fontStyle===(null!=t?t:"normal")&&n.fontWeight===(null!=o?o:"normal")?w.loadFont:w.loadFontFace)(e,n.fontStyle,n.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return x(e),Store.create({_forceShowCredit:t})}export default createStore;
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,isAlive as s,onSnapshot as r,setLivelinessChecking as l,types as d}from"mobx-state-tree";import{UndoManager as p}from"./history.js";import{nanoid as c}from"nanoid";import g from"konva";import{computed as m,when as u}from"mobx";import{ZERO_BLEED as f,migrateDesign as h,CURRENT_SCHEMA_VERSION as v}from"@polotno/schema";import{downloadFile as y}from"../utils/download.js";import{localFileToURL as b}from"../utils/file.js";import{getJsPDF as P}from"../utils/pdf.js";import{createGIF as w}from"../utils/gif-lib.js";import{validateKey as x,setKey as E}from"../utils/validate-key.js";import*as I from"../utils/fonts.js";import{flags as T}from"../utils/flags.js";import{addDpiMetadataToImage as _}from"../utils/image-dpi.js";import{nodeToCanvas as O,createExportCanvases as S,releaseExportCanvases as k}from"../utils/canvas.js";import{whenLoaded as R,getAssetLoadTimeout as j}from"../utils/loader.js";import{polotnoError as F}from"@polotno/core/errors";import{pxToUnit as A}from"../utils/unit.js";import{deepEqual as V}from"../utils/deep-equal.js";import{jsonToHTML as C}from"@polotno/html-export";import{jsonToSVG as L}from"@polotno/svg-export";import{warnOnceDeprecated as M}from"../utils/deprecation.js";import{Page as D}from"./page-model.js";import{forEveryChild as B,forEveryNode as H}from"./group-model.js";import{Audio as W}from"./audio-model.js";import{imageTools as N}from"./image-tools.js";import{IMAGE_TOOLS as U}from"../image-tools/sessions.js";function G(e){return!!e&&!!e.type&&"tablecell"!==e.type}function X(e){const t=new Map;for(const o of e){const e=o.parent;if(!e||t.has(o)){continue}let i=0;for(const o of e.children){t.set(o,i++)}}e.sort((e,o)=>{var i,n;return(null!==(i=t.get(e))&&void 0!==i?i:0)-(null!==(n=t.get(o))&&void 0!==n?n:0)})}l("ignore");export const Font=d.model("Font",{fontFamily:d.string,url:d.optional(d.string,""),styles:d.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));const q=d.model("BrushOptions",{strokeWidth:d.optional(d.number,5),stroke:d.optional(d.string,"#000000"),opacity:d.optional(d.number,1)}),J="data:,";export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=d.model("Store",{role:"",pages:d.array(D),fonts:d.array(Font),audios:d.array(W),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:d.optional(d.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:v,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:d.optional(d.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:d.frozen(),tool:d.optional(d.enumeration("Tool",["selection","draw","pan","text","eraser","crop","expand","inpaint","upscale","remove-background"]),"selection"),toolOptions:d.optional(d.model({brushType:d.optional(d.enumeration("BrushType",["brush","highlighter"]),"brush"),brush:d.optional(q,{}),highlighter:d.optional(q,{strokeWidth:30,opacity:.5})}).views(e=>({get active(){return e[e.brushType]}})).views(e=>({get strokeWidth(){return e.active.strokeWidth},get stroke(){return e.active.stroke},get opacity(){return e.active.opacity}})),{}),selectedElementsIds:d.array(d.string),animatedElementsIds:d.array(d.string),history:d.optional(p,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:d.array(d.string),_forceShowCredit:!1,_validated:!1}).volatile(()=>({highlightedElementId:null,_workspaces:0})).extend(N).views(e=>{const t=m(()=>{const t={};return H({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(G)},get children(){return e.pages},get selectedShapes(){const e=[];return B({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){const t=e.activeTool;return"crop"===(null==t?void 0:t.name)?this.getElementById(t.elementId):void 0},find(t){let o;return H({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(l=>{let d=0,p=null,m=!1;const v=({pageId:e,mimeType:t="image/png",pixelRatio:o=1})=>{var i;return F("EXPORT_FAILED",`The browser could not encode the page as ${t}. The canvas is probably too large; try a lower pixelRatio.`,{reason:"empty-output",pageId:e||(null===(i=l.pages[0])||void 0===i?void 0:i.id),mimeType:t,pixelRatio:o})},E={afterCreate(){l.history.canUndo},setCurrentTime(e){l.currentTime=e},_togglePlaying(e=!l.isPlaying){l.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=l.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),l.animatedElementsIds=o(e),l.currentTime=t,l.isPlaying=!0,d=Date.now(),p=n,m=a,requestAnimationFrame(()=>E.seek())},checkActivePage(){const e=l.pageAtTime(l.currentTime);e&&E.selectPage(e.id)},seek(){if(!l.isPlaying){return}const e=Date.now(),t=e-d;d=e,l.currentTime+=t;const o=p||l.duration;l.currentTime>=o&&!m&&(l.currentTime=o),E.checkActivePage(),l.isPlaying&&l.currentTime<o?requestAnimationFrame(()=>E.seek()):l.isPlaying&&m?(l.currentTime=0,requestAnimationFrame(()=>E.seek())):E.pause()},pause(){l.isPlaying=!1,l.animatedElementsIds=o([])},stop(){E.pause(),l.currentTime=0,E.checkActivePage()},__(){l._validated||(x(l._forceShowCredit),l._validated=!0)},set(e){Object.assign(l,e)},setUnit({unit:e,dpi:t}){l.unit=e||l.unit,l.dpi=t||l.dpi},setRole(e){l.role=e},setToolOptions(t){const{brushType:o}=t,i=e(t,["brushType"]);o&&(l.toolOptions.brushType=o),Object.assign(l.toolOptions.active,i)},addPage(e){const t=D.create(Object.assign({id:c(10)},e));return l.pages.push(t),l._activePageId=t.id,l._selectedPagesIds=o([]),t},selectPage(e){l._activePageId=e,1===l._selectedPagesIds.length&&(l._selectedPagesIds=o([e]))},selectPages(e){l._selectedPagesIds=o(e),1===l._selectedPagesIds.length&&(l._activePageId=l._selectedPagesIds[0])},selectElements(e){l._beforeToolSelection(e);const t=e.map(e=>l.getElementById(e)).filter(G);X(t),l.selectedElementsIds=o(t.map(e=>e.id))},highlightElement(e){l.highlightedElementId=e},toggleBleed(e){l.bleedVisible=null!=e?e:!l.bleedVisible},toggleRulers(e){l.rulesVisible=null!=e?e:!l.rulesVisible},setTimingPreview(e){l.timingPreview=e},toggleDistanceGuides(e){l.distanceGuidesVisible=null!=e?e:!l.distanceGuidesVisible},openSidePanel(e){l.openedSidePanel!==e&&("image-edit"!==e&&l._beforeToolPanel(),l.previousOpenedSidePanel=l.openedSidePanel,l.openedSidePanel=e)},restoreSidePanel(){l._beforeToolPanel();const e=l.previousOpenedSidePanel;e&&e!==l.openedSidePanel?l.openedSidePanel=e:l.openedSidePanel="photos"},setScale(e){l.scale=e},_setScaleToFit(e){l.scaleToFit=e},setElementsPixelRatio(e){l._elementsPixelRatio=e},setSize(e,t,o){l.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),l.width=e,l.height=t},setPageZIndex(e,t){const o=l.pages.find(t=>t.id===e);o&&(n(o),l.pages.remove(o),l.pages.splice(t,0,o))},_reconcilePages(e){const t=new Map(l.pages.map(e=>[e.id,e]));l.pages.replace(e.flatMap(e=>{var o;return null!==(o=t.get(e.id))&&void 0!==o?o:[]})),e.forEach((e,i)=>{t.has(e.id)||l.pages.splice(i,0,o(e))})},deletePages(e){const t=l.pages.indexOf(l.activePage);e.forEach(e=>{const t=l.pages.find(t=>t.id===e);i(t)});const n=l._selectedPagesIds.filter(e=>l.pages.some(t=>t.id===e)),a=Math.min(l.pages.length-1,t),s=l.pages[a];s&&(l._activePageId=s.id),E.selectPages(n),l.selectedElementsIds=o(l.selectedElementsIds.filter(e=>l.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>l.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}X(i);const s=a.children.indexOf(i[i.length-1])-i.length+1;i.forEach(e=>n(e));const r=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),d=Object.assign({id:c(10),name:`group-${r+1}`,children:i,type:"group"},t);return a.children.splice(s,0,d),l.selectedElementsIds=o([d.id]),a.children.find(e=>e.id===d.id)},ungroupElements(e){const t=e.map(e=>l.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)});const a=e.children.slice();a.forEach(t=>{t.set({opacity:t.opacity*e.opacity}),n(t)}),t.children.splice(o,1,...a)}}),l.selectedElementsIds=o(i)},deleteElements(e){const t=[];l.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),l.selectedElementsIds=o(l.selectedElementsIds.filter(e=>l.getElementById(e)))},on(e,t){if("change"===e){let e=E.toJSON();return r(l,o=>{const i=E.toJSON();!V(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,quickMode:a=!1,_exportCanvases:r}={}){var d;const p=e||1;o=o||(null===(d=l.pages[0])||void 0===d?void 0:d.id);const c=l.pages.find(e=>e.id===o);if(!c){throw F("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:l.pages.map(e=>e.id)})}const m=l._elementsPixelRatio;try{(a?p>l._elementsPixelRatio:p!==l._elementsPixelRatio)&&E.setElementsPixelRatio(p),c.set(a?{_forceMount:!0}:{_exporting:!0}),await u(()=>c._exportRendered||0===l._workspaces||!l.pages.includes(c),{timeout:j()}).catch(()=>{}),await R();const e=g.stages.filter(e=>e.getAttr("pageId")===o);if(!c._exportRendered||0===e.length){throw F("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const s=e[0],d=s.findOne(".page-container");if(!d){throw F("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const m=s.position();s.position({x:0,y:0}),s.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),d.find(".page-background").forEach(e=>e.shadowEnabled(!1)),d.find(".page-background").forEach(e=>e.strokeEnabled(!1)),d.find(".highlighter").forEach(e=>e.visible(!1));const h=d.findOne(".page-background-group"),v=h.clip();h.clip({x:null,y:null,width:null,height:null});const y=d.findOne(".elements-container"),b=y.clip();y.clip({x:null,y:null,width:null,height:null});const P=d.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));P.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const w=d.find(e=>e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&d.find(".page-background").forEach(e=>e.hide());const x=n?c.computedBleed:f;let I=x.left,_=x.top;!l.bleedVisible&&n||(l.bleedVisible||n?l.bleedVisible&&n?(I=0,_=0):l.bleedVisible&&!n&&(I=-c.computedBleed.left,_=-c.computedBleed.top):(I=0,_=0));const S=c.computedWidth+x.left+x.right,k=c.computedHeight+x.top+x.bottom,A=d.scale();d.scale({x:1,y:1});const V=O(d,{x:d.x()-I,y:d.y()-_,width:S,height:k,pixelRatio:p,imageSmoothingQuality:T.imageDownScalingEnabled&&!a?"high":void 0,sceneCanvas:null==r?void 0:r.sceneCanvas});d.scale(A);const C=V._canvas;if("image/jpeg"===i){const e=C.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,C.width,C.height),e.restore()}return t&&d.find(".page-background").forEach(e=>e.show()),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),P.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),d.find(".page-background").forEach(e=>e.shadowEnabled(!0)),d.find(".page-background").forEach(e=>e.strokeEnabled(!0)),s.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),d.find(".highlighter").forEach(e=>e.visible(!0)),h.clip(v),y.clip(b),s.position(m),null==c||c.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),C}finally{E.setElementsPixelRatio(m),s(c)&&c.set({_forceMount:!1,_exporting:!1})}},async _toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const r=await E._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=r.toDataURL(d,i);g.Util.releaseCanvas(r);const c=null!=n?n:l.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===c?p:_(p,d,c)},async toDataURL(e={}){const t=await E._toDataURL(e);if(t===J){throw v(e)}return t},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await E._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});if(g.Util.releaseCanvas(a),!s){throw v(Object.assign({mimeType:o},n))}return s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];y(await E.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||l.dpi,o=e.parallel||1,i=e.unit||("px"===l.unit?"mm":l.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:l.pages.map(e=>e.id)),s=l.pages.filter(e=>a.includes(e.id)),r=await P(),d=e=>A({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},m=e.includeBleed&&g.computedBleed||f,u=d(g.computedWidth+m.left+m.right+2*c),h=d(g.computedHeight+m.top+m.bottom+2*c);var v=new r({unit:i,orientation:u>h?"landscape":"portrait",format:[u,h],compress:!0,putOnlyUsedFonts:!0});v.deletePage(1);const y=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let b=0;for(const l of y){const t=l.map(async t=>{const o=e.includeBleed?t.computedBleed:f,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await E._toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d!==J){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++b/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{v.addPage([t,o],t>o?"landscape":"portrait");const r=v.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw F("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){v.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);v.line(e,0,e,c),v.line(0,n,c,n),v.line(t-i,0,t-i,c),v.line(t,n,t-c,n),v.line(0,o-a,c,o-a),v.line(e,o,e,o-c),v.line(t,o-a,t-c,o-a),v.line(t-i,o,t-i,o-c)}v.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return v},toPDFDataURL:async e=>(await E._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){var t,o;const i=e.pixelRatio||1,n=e.pageIds||(e.pageId?[e.pageId]:l.pages.map(e=>e.id)),a=l.pages.filter(e=>n.includes(e.id));if(!a.length){throw F("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:l.pages.map(e=>e.id)})}null===(t=e.onProgress)||void 0===t||t.call(e,0,"rendering");const s=a[0],r=await w({width:s.computedWidth*i,height:s.computedHeight*i}),d=1e3/(e.fps||10),p=a.map(e=>({page:e,frames:Math.max(1,Math.floor(e.duration/d))})),c=p.reduce((e,{frames:t})=>e+t,0);let g=0;const m=S(),u=l._elementsPixelRatio;E.setElementsPixelRatio(i);try{for(const{page:t,frames:n}of p){for(let a=0;a<n;a++){const n=t.startTime+a*d||1;E.setCurrentTime(n);for(const e of l.pages){e.set({_rendering:e.id===t.id})}const s=await E._toCanvas({pixelRatio:i,pageId:t.id,_exportCanvases:m});r.addFrame(s.getContext("2d"),{delay:d,copy:!0}),g++,null===(o=e.onProgress)||void 0===o||o.call(e,g/c/2,"rendering")}}}finally{k(m),E.setElementsPixelRatio(u);for(const e of l.pages){e.set({_rendering:!1})}E.stop()}return new Promise((t,o)=>{let i=!1;e.onProgress&&r.on("progress",t=>{var n;if(!i){try{null===(n=e.onProgress)||void 0===n||n.call(e,.5+t/2,"encoding")}catch(a){i=!0,o(a)}}}),r.on("finished",e=>{i||b(e).then(t,o)}),r.render()})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await E.toGIFDataURL(i);y(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){M("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=E.toJSON();return C(t,{elementHook:e,textOverflow:T.textOverflow,textSplitAllowed:T.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await E.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));y(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;M("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=E.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return L(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),Object.assign({elementHook:e,fontEmbedding:o,textSplitAllowed:T.textSplitAllowed},"fit"===T.textOverflow&&{textOverflow:"fit"}))},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await E.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));y(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await E._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},_setWorkspaceMounted(e){l._workspaces+=e?1:-1},async waitLoading(){await R()},toJSON:()=>({width:l.width,height:l.height,fonts:a(l.fonts),pages:a(l.pages),audios:a(l.audios),unit:l.unit,dpi:l.dpi,custom:l.custom,schemaVersion:l.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,r="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=h(e,{modernTextRenderer:T.htmlRenderEnabled||T.renderTagTextEnabled,modernizeTextBackground:r});delete d.schemaVersion,d.tool in U&&delete d.tool;const p=l.activePage?l.pages.indexOf(l.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[],l._closeImageTool("discard"),B(l,e=>{var t;"pendingEdit"in e&&(null===(t=e.pendingEdit)||void 0===t||t.cancel())});const g=Object.assign({},a(l));Object.assign(g,d),g.history=s?a(l.history):{history:[],undoIdx:-1,targetPath:""},t(l,g)},clear({keepHistory:e=!1}={}){const t=l.pages.map(e=>e.id);E.deletePages(t),l.custom=null,e||l.history.clear()},addFont(e){l.fonts.filter(t=>t.fontFamily===e.fontFamily).forEach(e=>i(e)),l.fonts.push(e),I.injectCustomFont(e)},removeFont(e){l.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e)),I.removeCustomFont(e)},addAudio(e){const t=W.create(Object.assign({id:c(10)},e));l.audios.push(t)},removeAudio(e){const t=l.audios.find(t=>t.id===e);t&&l.audios.remove(t)},async loadFont(e,t,o,i){var n,a;const s=l.fonts.find(t=>t.fontFamily===e)||I.globalFonts.find(t=>t.fontFamily===e);if(s?I.injectCustomFont(s):I.injectGoogleFont(e),T.renderTagTextEnabled){return I.loadFont(e,null!=t?t:"normal",null!=o?o:"normal",i)}const r=null!==(a=null===(n=null==s?void 0:s.styles)||void 0===n?void 0:n.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"})))&&void 0!==a?a:[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return t&&o&&!r.some(e=>e.fontStyle===t&&e.fontWeight===o)&&r.push({fontStyle:t,fontWeight:o}),Promise.all(r.map(n=>(n.fontStyle===(null!=t?t:"normal")&&n.fontWeight===(null!=o?o:"normal")?I.loadFont:I.loadFontFace)(e,n.fontStyle,n.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return E});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return E(e),Store.create({_forceShowCredit:t})}export default createStore;
@@ -482,6 +482,9 @@ export declare const TableElement: import("mobx-state-tree").IModelType<{
482
482
  } & {
483
483
  getCell(row: number, col: number): TableCellType | undefined;
484
484
  readonly minWidth: number;
485
+ readonly basePixelRowHeights: number[];
486
+ contentFloors(divider?: number): number[];
487
+ readonly rowContentFloors: number[];
485
488
  getRowContentOuterHeight(row: number): number;
486
489
  readonly minHeight: number;
487
490
  readonly actualHeight: number;
@@ -1 +1 @@
1
- import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{clampFontSize as c,TABLE_CELL_OVERRIDABLE_KEYS as d}from"@polotno/schema/defaults";import{Shape as a}from"./shape-model.js";const g=.05,u=e.enumeration(["solid","dashed","dotted","none"]);function h(e){return t(e,2)}function f(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?h(e)[t]:o}function b(e){return t(e,1)}const w=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(u)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),p=e.model("CellBorders",{top:e.maybe(w),right:e.maybe(w),bottom:e.maybe(w),left:e.maybe(w)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),m=d,C=new Set(m),_=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],y=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],v=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),I={opacity:1,rowSpan:1,colSpan:1,name:""},S=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(p),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of y){o in e&&(t[o]=e[o])}for(const o of m){void 0!==e[o]&&(t[`_${o}`]=e[o])}return void 0!==t._fontSize&&(t._fontSize=c(t._fontSize)),t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in I&&l===I[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=h(e),o=b(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=h(e),o=b(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return h(e).page}catch(t){return null}},get fontSize(){return f(e,"fontSize",30)},get fontFamily(){return f(e,"fontFamily","Roboto")},get fontWeight(){return f(e,"fontWeight","normal")},get fontStyle(){return f(e,"fontStyle","normal")},get textDecoration(){return f(e,"textDecoration","")},get textTransform(){return f(e,"textTransform","none")},get fill(){return f(e,"fill","black")},get align(){return f(e,"align","left")},get verticalAlign(){return f(e,"verticalAlign","top")},get lineHeight(){return f(e,"lineHeight",1.2)},get letterSpacing(){return f(e,"letterSpacing",0)},get strokeWidth(){return f(e,"strokeWidth",0)},get stroke(){return f(e,"stroke","black")},get cellBackground(){return f(e,"cellBackground","transparent")},get cellPadding(){return f(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get borderInsets(){if(!l(e)){return{top:0,right:0,bottom:0,left:0}}const o=h(e),r=(e,o)=>{const l=t.getEffectiveBorder(e);return"none"===l.style||0===l.width?0:o?l.width:l.width/2};return{top:r("top",0===t.row),bottom:r("bottom",t.row+e.rowSpan===o.rows),left:r("left",0===t.col),right:r("right",t.col+e.colSpan===o.cols)}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,{top:s,right:i,bottom:c,left:d}=t.borderInsets;return{x:r.x+d+n,y:r.y+s+n,width:Math.max(0,r.width-d-i-2*n),height:Math.max(0,r.height-s-c-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?h(e):null,g=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==g?void 0:g.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==g?void 0:g.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==g?void 0:g.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return S}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&(t=Object.assign(Object.assign({},t),{fontSize:c(t.fontSize)}));const o={};for(const[e,l]of Object.entries(t)){C.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:v.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){if(!l(e)){return}const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}));function H(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of m){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function R(e){return Array.from({length:e},()=>1/e)}function O(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?R(e.length):e.map(e=>e/t)}export const TableElement=a.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).preProcessSnapshot(e=>null==(null==e?void 0:e.fontSize)?e:Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){C.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of _){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(R(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(R(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},getRowContentOuterHeight(o){let l=0;for(let r=0;r<e.cols;r++){const n=t.getCell(o,r);if(!n){continue}const s=e._cellContentHeights.get(n.id);if(void 0===s){continue}const i=n.borderInsets,c=s+2*n.cellPadding+i.top+i.bottom;c>l&&(l=c)}return l},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}let l=0;for(let r=0;r<e.rows;r++){l+=t.getRowContentOuterHeight(r)}return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){var o,l;if(0===e._cellContentHeights.size){return null}const r=null!==(o=e._baseHeight)&&void 0!==o?o:e.height,n=null!==(l=e._baseRowHeights)&&void 0!==l?l:[...e.rowHeights];let s=!1;const i=[];for(let d=0;d<e.rows;d++){const o=e.rowHeights[d]*e.height,l=n[d]*r,c=t.getRowContentOuterHeight(d),a=Math.max(c,l);Math.abs(a-o)>1?(i.push(a),s=!0):i.push(o)}if(!s){return null}const c=i.reduce((e,t)=>e+t,0);return{rowHeights:i.map(e=>e/c),height:c}}};return t}).actions(e=>{const t=e.set,o={set(e){null!=e.fontSize&&(e=Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})),t(e)},setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){if(!l(e)){return}null===e._baseRowHeights&&(e._baseRowHeights=[...e.rowHeights],e._baseHeight=e.height);const t=e._fitRowsToContent;t&&(e.height=t.height,e.rowHeights.replace(t.rowHeights))},focusCell(t,o=!1){o?e._focusedCellIds.includes(t)||(e._focusedCellIds=[...e._focusedCellIds,t]):(e._focusedCellIds=[t],e._anchorCellId=t)},selectRowRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.rows-1,Math.max(t,o)),n=[];for(let s=l;s<=r;s++){for(let t=0;t<e.cols;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectColumnRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.cols-1,Math.max(t,o)),n=[];for(let s=0;s<e.rows;s++){for(let t=l;t<=r;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectRow(e){o.selectRowRange(e,e)},selectColumn(e){o.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=[],n=[];let s=0;for(let u=0;u<o;u++){r.push(e.rowHeights[u]*l);const t=e.getRowContentOuterHeight(u);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(t){o._resetBaseRowHeights();const l=t>0?t-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let o=0;o<e.rows;o++){s.push(e.rowHeights[o]*e.height/n)}s.splice(t,0,r/n);const i=t>0?t-1:0,c=[];for(let o=0;o<e.cols;o++){c.push(e.cells[i*e.cols+o])}const d=t*e.cols,a=H(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(O(s))},removeRow(t){if(e.rows<=1){return}o._resetBaseRowHeights();const l=t*e.cols,r=[];for(let o=l;o<l+e.cols;o++){r.push(e.cells[o].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(t,1),e.rows-=1,e.rowHeights.replace(O(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=H(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(O(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(O(r))},removeRowRange(t,l){for(let r=l;r>=t&&!(e.rows<=1);r--){o.removeRow(r)}},removeColumnRange(t,l){for(let r=l;r>=t&&!(e.cols<=1);r--){o.removeColumn(r)}},distributeRowsEvenly(){const t=e.rows;let l=20;for(let o=0;o<t;o++){l=Math.max(l,e.getRowContentOuterHeight(o))}o._resetBaseRowHeights(),e.height=Math.max(e.height,l*t),e.rowHeights.replace(R(t))},distributeColumnsEvenly(){e.colWidths.replace(R(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<g?(l[t]=g,l[t+1]=r-g):s<g?(l[t+1]=g,l[t]=r-g):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=n>0?e.getRowContentOuterHeight(t)/n:0,i=n>0?e.getRowContentOuterHeight(t+1)/n:0,c=Math.max(g,s),d=Math.max(g,i),a=l[t]+o,u=l[t+1]-o;a<c?(l[t]=c,l[t+1]=r-c):u<d?(l[t+1]=d,l[t]=r-d):(l[t]=a,l[t+1]=u),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(t,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(t,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){o.setCellBorders(e,s,l)}}};return o}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
1
+ import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{clampFontSize as c,TABLE_CELL_OVERRIDABLE_KEYS as d}from"@polotno/schema/defaults";import{Shape as a}from"./shape-model.js";const g=.05,u=e.enumeration(["solid","dashed","dotted","none"]);function h(e){return t(e,2)}function f(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?h(e)[t]:o}function b(e){return t(e,1)}const w=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(u)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),m=e.model("CellBorders",{top:e.maybe(w),right:e.maybe(w),bottom:e.maybe(w),left:e.maybe(w)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),p=d,C=new Set(p),_=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],y=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],v=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),I={opacity:1,rowSpan:1,colSpan:1,name:""},S=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(m),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of y){o in e&&(t[o]=e[o])}for(const o of p){void 0!==e[o]&&(t[`_${o}`]=e[o])}return void 0!==t._fontSize&&(t._fontSize=c(t._fontSize)),t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in I&&l===I[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=h(e),o=b(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=h(e),o=b(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return h(e).page}catch(t){return null}},get fontSize(){return f(e,"fontSize",30)},get fontFamily(){return f(e,"fontFamily","Roboto")},get fontWeight(){return f(e,"fontWeight","normal")},get fontStyle(){return f(e,"fontStyle","normal")},get textDecoration(){return f(e,"textDecoration","")},get textTransform(){return f(e,"textTransform","none")},get fill(){return f(e,"fill","black")},get align(){return f(e,"align","left")},get verticalAlign(){return f(e,"verticalAlign","top")},get lineHeight(){return f(e,"lineHeight",1.2)},get letterSpacing(){return f(e,"letterSpacing",0)},get strokeWidth(){return f(e,"strokeWidth",0)},get stroke(){return f(e,"stroke","black")},get cellBackground(){return f(e,"cellBackground","transparent")},get cellPadding(){return f(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get borderInsets(){if(!l(e)){return{top:0,right:0,bottom:0,left:0}}const o=h(e),r=(e,o)=>{const l=t.getEffectiveBorder(e);return"none"===l.style||0===l.width?0:o?l.width:l.width/2};return{top:r("top",0===t.row),bottom:r("bottom",t.row+e.rowSpan===o.rows),left:r("left",0===t.col),right:r("right",t.col+e.colSpan===o.cols)}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,{top:s,right:i,bottom:c,left:d}=t.borderInsets;return{x:r.x+d+n,y:r.y+s+n,width:Math.max(0,r.width-d-i-2*n),height:Math.max(0,r.height-s-c-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?h(e):null,g=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==g?void 0:g.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==g?void 0:g.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==g?void 0:g.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return S}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&(t=Object.assign(Object.assign({},t),{fontSize:c(t.fontSize)}));const o={};for(const[e,l]of Object.entries(t)){C.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:v.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){if(!l(e)){return}const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}));function H(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of p){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function R(e){return Array.from({length:e},()=>1/e)}function x(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?R(e.length):e.map(e=>e/t)}export const TableElement=a.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).preProcessSnapshot(e=>null==(null==e?void 0:e.fontSize)?e:Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){C.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of _){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(R(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(R(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},get basePixelRowHeights(){var t,o;const l=null!==(t=e._baseHeight)&&void 0!==t?t:e.height;return(null!==(o=e._baseRowHeights)&&void 0!==o?o:e.rowHeights).map(e=>e*l)},contentFloors(o){const l=t.basePixelRowHeights,r=new Array(e.rows).fill(0),n=[];for(const s of t.visibleCells){const t=e._cellContentHeights.get(s.id);if(void 0===t){continue}const l=s.borderInsets,i=t+2*s.cellPadding+l.top+l.bottom,c=s.row,d=Math.min(c+s.rowSpan,e.rows);d-c===1?r[c]=Math.max(r[c],i):void 0!==o&&c<=o&&o+1<d||n.push({start:c,end:d,outer:i})}n.sort((e,t)=>e.end-e.start-(t.end-t.start));for(const{start:e,end:t,outer:s}of n){const o=r.slice(e,t),n=l.slice(e,t),i=s-o.reduce((e,t)=>e+t,0);if(i<=0){continue}const c=o.map((e,t)=>Math.max(0,n[t]-e)),d=c.reduce((e,t)=>e+t,0),a=n.reduce((e,t)=>e+t,0),g=Math.min(i,d);o.forEach((t,l)=>{r[e+l]=t+(d>0?g*c[l]/d:0)+(i-g)*(a>0?n[l]/a:1/o.length)})}return r},get rowContentFloors(){return t.contentFloors()},getRowContentOuterHeight(e){var o;return null!==(o=t.rowContentFloors[e])&&void 0!==o?o:0},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}const l=t.rowContentFloors.reduce((e,t)=>e+t,0);return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){if(0===e._cellContentHeights.size){return null}const o=t.basePixelRowHeights,l=t.rowContentFloors;let r=!1;const n=[];for(let t=0;t<e.rows;t++){const s=e.rowHeights[t]*e.height,i=Math.max(l[t],o[t]);Math.abs(i-s)>1?(n.push(i),r=!0):n.push(s)}if(!r){return null}const s=n.reduce((e,t)=>e+t,0);return{rowHeights:n.map(e=>e/s),height:s}}};return t}).actions(e=>{const t=e.set,o={set(e){null!=e.fontSize&&(e=Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})),t(e)},setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){if(!l(e)){return}null===e._baseRowHeights&&(e._baseRowHeights=[...e.rowHeights],e._baseHeight=e.height);const t=e._fitRowsToContent;t&&(e.height=t.height,e.rowHeights.replace(t.rowHeights))},focusCell(t,o=!1){o?e._focusedCellIds.includes(t)||(e._focusedCellIds=[...e._focusedCellIds,t]):(e._focusedCellIds=[t],e._anchorCellId=t)},selectRowRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.rows-1,Math.max(t,o)),n=[];for(let s=l;s<=r;s++){for(let t=0;t<e.cols;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectColumnRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.cols-1,Math.max(t,o)),n=[];for(let s=0;s<e.rows;s++){for(let t=l;t<=r;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectRow(e){o.selectRowRange(e,e)},selectColumn(e){o.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=e.rowHeights.map(e=>e*l),n=e.rowContentFloors,s=n.reduce((e,t)=>e+t,0);if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(t){o._resetBaseRowHeights();const l=t>0?t-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let o=0;o<e.rows;o++){s.push(e.rowHeights[o]*e.height/n)}s.splice(t,0,r/n);const i=t>0?t-1:0,c=[];for(let o=0;o<e.cols;o++){c.push(e.cells[i*e.cols+o])}const d=t*e.cols,a=H(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(x(s))},removeRow(t){if(e.rows<=1){return}o._resetBaseRowHeights();const l=t*e.cols,r=[];for(let o=l;o<l+e.cols;o++){r.push(e.cells[o].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(t,1),e.rows-=1,e.rowHeights.replace(x(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=H(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(x(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(x(r))},removeRowRange(t,l){for(let r=l;r>=t&&!(e.rows<=1);r--){o.removeRow(r)}},removeColumnRange(t,l){for(let r=l;r>=t&&!(e.cols<=1);r--){o.removeColumn(r)}},distributeRowsEvenly(){const t=e.rows,l=Math.max(20,...e.rowContentFloors);o._resetBaseRowHeights(),e.height=Math.max(e.height,l*t),e.rowHeights.replace(R(t))},distributeColumnsEvenly(){e.colWidths.replace(R(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<g?(l[t]=g,l[t+1]=r-g):s<g?(l[t+1]=g,l[t]=r-g):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=e.contentFloors(t),i=n>0?s[t]/n:0,c=n>0?s[t+1]/n:0,d=Math.max(g,i),a=Math.max(g,c),u=l[t]+o,h=l[t+1]-o;u<d?(l[t]=d,l[t+1]=r-d):h<a?(l[t+1]=a,l[t]=r-a):(l[t]=u,l[t+1]=h),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(t,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(t,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){o.setCellBorders(e,s,l)}}};return o}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "3.16.1",
3
+ "version": "3.18.0",
4
4
  "description": "Design editor SDK: embed a Canva-like editor, generate designs from templates and data, export PNG, PDF, and video in the browser or on a server.",
5
5
  "author": "Anton Lavrenov",
6
6
  "repository": {
@@ -113,17 +113,17 @@
113
113
  },
114
114
  "dependencies": {
115
115
  "@base-ui/react": "^1.9.0",
116
- "@polotno/core": "0.16.0",
117
- "@polotno/html-export": "0.9.0",
118
- "@polotno/schema": "0.9.0",
119
- "@polotno/svg-export": "0.10.0",
116
+ "@polotno/core": "0.19.0",
117
+ "@polotno/html-export": "0.10.0",
118
+ "@polotno/schema": "0.9.1",
119
+ "@polotno/svg-export": "0.11.0",
120
120
  "class-variance-authority": "^0.7.1",
121
121
  "clsx": "^2.1.1",
122
122
  "gifuct-js": "^2.1.2",
123
- "konva": "^10.8.0",
123
+ "konva": "^10.9.0",
124
124
  "lodash-es": "^4.18.1",
125
- "lucide-react": "^1.57.0",
126
- "mediabunny": "^1.61.4",
125
+ "lucide-react": "^1.59.0",
126
+ "mediabunny": "^1.61.6",
127
127
  "mobx": "7.0.6",
128
128
  "mobx-react-lite": "^5.1.0",
129
129
  "mobx-state-tree": "8.0.0",
@@ -132,7 +132,7 @@
132
132
  "react-konva": "18.2.16",
133
133
  "react-konva-utils": "^2.1.0",
134
134
  "react-sortablejs": "6.1.4",
135
- "react-window": "^2.3.4",
135
+ "react-window": "^2.4.1",
136
136
  "render-tag": "0.3.2",
137
137
  "sortablejs": "^1.15.7",
138
138
  "svg-round-corners": "^0.4.3",
@@ -181,8 +181,8 @@
181
181
  "@testing-library/react": "^16.3.3",
182
182
  "@types/react": "^19.3.0",
183
183
  "@vitejs/plugin-react": "^6.1.2",
184
- "@vitest/browser": "^5.0.4",
185
- "@vitest/browser-playwright": "^5.0.4",
184
+ "@vitest/browser": "^5.0.5",
185
+ "@vitest/browser-playwright": "^5.0.5",
186
186
  "assemblyscript": "^0.28.20",
187
187
  "assert": "^2.1.0",
188
188
  "bippy": "^0.7.3",
@@ -191,20 +191,20 @@
191
191
  "filehound": "^1.17.6",
192
192
  "glob": "^13.0.6",
193
193
  "jest-file-snapshot": "^0.7.0",
194
- "jsdom": "^30.1.2",
194
+ "jsdom": "^30.1.3",
195
195
  "playwright": "^1.64.1",
196
- "postcss": "^8.5.30",
196
+ "postcss": "^8.5.31",
197
197
  "postcss-selector-parser": "^7.1.6",
198
198
  "pptxgenjs": "^4.0.1",
199
199
  "process": "^0.11.10",
200
- "react": "^19.3.0",
201
- "react-dom": "^19.3.0",
200
+ "react": "^19.3.1",
201
+ "react-dom": "^19.3.1",
202
202
  "tailwindcss": "^4.3.3",
203
203
  "terser": "^5.51.2",
204
204
  "tw-animate-css": "^1.4.0",
205
205
  "typescript": "~6.0.3",
206
206
  "vite": "^8.3.4",
207
- "vitest": "^5.0.4"
207
+ "vitest": "^5.0.5"
208
208
  },
209
209
  "homepage": "https://polotno.com/",
210
210
  "scripts": {
@@ -212,18 +212,19 @@
212
212
  "clean": "rm -rf ./lib && rm -rf ./.pn-build",
213
213
  "prefix-build": "node build/prefix-build.cjs",
214
214
  "tsc": "tsc --project tsconfig.lib.json --removeComments --sourceMap false",
215
- "typecheck": "tsc --noEmit -p tsconfig.json",
215
+ "typecheck": "node ../../scripts/typecheck.mjs --noEmit -p tsconfig.json",
216
216
  "build:css": "tailwindcss -i ./.pn-build/ui.css -o ./lib/ui.css --minify && node build/rename-keyframes.cjs ./lib/ui.css",
217
217
  "check:css": "node build/check-css-hygiene.cjs ./lib/ui.css",
218
218
  "check:agreement": "node build/check-agreement.cjs ./lib/ui.css ./lib/toolbar ./lib/side-panel ./lib/pages-timeline ./lib/primitives ./lib/canvas",
219
219
  "check:parity": "node build/structural-parity.cjs",
220
220
  "test:parity": "pnpm run check:parity && pnpm run check:agreement && pnpm run check:css",
221
221
  "minify": "node minify.cjs",
222
- "build": "pnpm run check:wasm && pnpm run clean && pnpm run prefix-build && pnpm run tsc && pnpm run add_version && node rename-imports.js && pnpm run minify && pnpm run build:css && pnpm run check:css && pnpm run check:agreement && pnpm run build:bundle && node blueprint-scope.js && cp ./src/fonts.css ./lib/fonts.css && mkdir -p ./lib/themes && cp ./src/themes/blueprint.css ./lib/themes/blueprint.css && cp ./src/themes/carbon.css ./lib/themes/carbon.css && node build/copy-package-json.cjs && cp ./README.md ./lib && cp ./LICENSE.md ./lib && pnpm run remove-test-from-lib",
222
+ "build": "node build/build.mjs",
223
223
  "remove-test-from-lib": "find ./lib -type d -name \"__tests__\" -exec rm -rf {} + && find ./lib \\( -name \"*.test.js\" -o -name \"*.test.d.ts\" \\) -type f -delete",
224
224
  "add_version": "sed -i.bak 's/SDK_VERSION/'$npm_package_version'/' ./lib/utils/validate-key.js && rm -f ./lib/utils/validate-key.js.bak",
225
225
  "build:bundle": "vite build && find ./lib -name '*.js.map' -type f -delete",
226
226
  "test": "node scripts/run-tests-parallel.mjs",
227
+ "test:artifact": "POLOTNO_TEST_SCOPE=artifact node scripts/run-browser.mts",
227
228
  "test:unit": "vitest run --project unit",
228
229
  "test:browser": "node scripts/run-browser.mts",
229
230
  "test:serial": "vitest run",
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as i}from"../icons/registry.js";import{duplicateElements as r}from"../utils/duplicate.js";import{clamp as l}from"../lib/utils.js";import{getElementTimeRange as s,MIN_DURATION as a,revealElementAtPlayhead as m}from"../utils/timeline.js";import{canSplitAtPlayhead as c,splitElementAtPlayhead as p}from"../utils/split-element.js";import{t as d}from"../utils/l10n.js";import{DRAG_SLOP_PX as u,isPrimaryDrag as f,usePointerDrag as x}from"../utils/pointer-drag.js";import{DropdownMenu as h,DropdownMenuContent as v,DropdownMenuItem as j}from"../primitives/dropdown-menu.js";import{TrackWrapper as E,TrackContainer as g,TrackMenu as w,TrackMenuButton as y,TrackHandleLeft as D,TrackHandleRight as M,TrackLabel as P,TrackNameInput as b}from"./track-styles.js";export const ELEMENT_ROW_HEIGHT=26;const S=o(({element:n,store:o})=>{var r;const l=o.effectiveTime-((null===(r=n.page)||void 0===r?void 0:r.startTime)||0),s=c(n,l);return t(j,{disabled:!s,onSelect:e=>{e.preventDefault();const t=p(n,l);t&&o.selectElements([t.id])},children:[e(i,{name:"action.split"}),d("contextMenu.split")]})}),T=(e,t)=>{const n=e.animations.find(e=>e.type===t);n&&n.enabled||e.setAnimation(t,{name:"none",enabled:!0})},X=(e,t,n,o)=>{const i=l(n,0,t-a),r=l(o,i+a,t);T(e,"enter"),T(e,"exit"),e.setAnimation("enter",{delay:i}),e.setAnimation("exit",{delay:Math.max(0,t-r)})};export const ElementTrack=o(({element:o,page:c,store:p,scale:T,row:k})=>{const A=c.duration,C=c.startTime,H=C+A,{start:N,end:O}=s(o.animations,A),W=(O-N)*T,$=(C+N)*T,_=o.name||o.type||d("toolbar.element"),[G,I]=n.useState(!1),L=x(),[R,q]=n.useState(null),z=()=>{q(e=>null===e?k:e)},B=()=>{q(null)},F=(e,t)=>{if(!f(e)){return}e.stopPropagation();const n=e.clientX,i=N,r=O;L(e,{slopX:u,node:o,onMove:e=>{z();const s=(e.clientX-n)/T;if("start"===t){const e=l(C+i+s,C,C+r-a);X(o,A,e-C,r)}else{const e=l(C+r+s,C+i+a,H);X(o,A,i,e-C)}},onEnd:B})};return e(E,{style:{left:`${$}px`,top:26*(null!=R?R:k)+"px",width:`${W}px`,minWidth:"6px",height:"22px"},children:t(g,{style:{width:"100%",height:"100%",outline:p.selectedElements.find(e=>e.id===o.id)?"2px solid var(--pn-primary, var(--primary, #137cbd))":"none",outlineOffset:"-1px"},onPointerDown:e=>{if(!f(e)){return}e.stopPropagation();const t=e.clientX,n=N,i=O-n;L(e,{slopX:u,node:o,onMove:e=>{z();const r=(e.clientX-t)/T,s=l(C+n+r,C,H-i)-C;X(o,A,s,s+i)},onEnd:({moved:e,cancelled:t})=>{B(),e||t||(p.selectElements([o.id]),m(o))}})},children:[G?e(b,{value:o.name||"",onCommit:e=>{o.set({name:e}),I(!1)},onCancel:()=>I(!1)}):e(P,{children:_}),e(D,{onPointerDown:e=>F(e,"start")}),e(M,{onPointerDown:e=>F(e,"end")}),e(w,{onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:t(h,{children:[e(y,{}),t(v,{side:"top",className:"pn:whitespace-nowrap",children:[e(S,{element:o,store:p}),t(j,{onSelect:e=>{e.preventDefault(),I(!0)},children:[e(i,{name:"action.rename"}),d("contextMenu.rename")]}),t(j,{onSelect:e=>{e.preventDefault(),r([o],p)},children:[e(i,{name:"action.duplicate"}),d("contextMenu.duplicate")]}),t(j,{onSelect:e=>{e.preventDefault(),p.deleteElements([o.id])},children:[e(i,{name:"action.remove"}),d("contextMenu.remove")]})]})]})})]})})});
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as i}from"../icons/registry.js";import{duplicateElements as r}from"../utils/duplicate.js";import{clamp as l}from"../lib/utils.js";import{getElementTimeRange as s,MIN_DURATION as a,revealElementAtPlayhead as m}from"../utils/timeline.js";import{canSplitAtPlayhead as c,splitElementAtPlayhead as p}from"../utils/split-element.js";import{t as d}from"../utils/l10n.js";import{DRAG_SLOP_PX as u,isPrimaryDrag as f,usePointerDrag as x}from"../utils/pointer-drag.js";import{DropdownMenu as h,DropdownMenuContent as v,DropdownMenuItem as j}from"../primitives/dropdown-menu.js";import{TrackWrapper as E,TrackContainer as g,TrackMenu as y,TrackMenuButton as w,TrackHandleLeft as D,TrackHandleRight as M,TrackLabel as P,TrackNameInput as b}from"./track-styles.js";export const ELEMENT_ROW_HEIGHT=26;const S=o(({element:n,store:o})=>{var r;const l=o.effectiveTime-((null===(r=n.page)||void 0===r?void 0:r.startTime)||0),s=c(n,l);return t(j,{disabled:!s,onSelect:e=>{e.preventDefault();const t=p(n,l);t&&o.selectElements([t.id])},children:[e(i,{name:"action.split"}),d("contextMenu.split")]})}),T=(e,t)=>{const n=e.animations.find(e=>e.type===t);n&&n.enabled||e.setAnimation(t,{name:"none",enabled:!0})},X=(e,t,n,o)=>{const i=l(n,0,t-a),r=l(o,i+a,t);T(e,"enter"),T(e,"exit"),e.setAnimation("enter",{delay:i}),e.setAnimation("exit",{delay:Math.max(0,t-r)})};export const ElementTrack=o(({element:o,page:c,store:p,scale:T,row:k})=>{const A=c.duration,C=c.startTime,H=C+A,{start:I,end:N}=s(o.animations,A),O=(N-I)*T,W=(C+I)*T,$=o.name||o.type||d("toolbar.element"),[_,B]=n.useState(!1),G=x(),[L,R]=n.useState(null),q=()=>{R(e=>null===e?k:e)},z=()=>{R(null)},F=(e,t)=>{if(!f(e)){return}e.stopPropagation();const n=e.clientX,i=I,r=N;G(e,{slopX:u,node:o,onMove:e=>{q();const s=(e.clientX-n)/T;if("start"===t){const e=l(C+i+s,C,C+r-a);X(o,A,e-C,r)}else{const e=l(C+r+s,C+i+a,H);X(o,A,i,e-C)}},onEnd:z})};return e(E,{style:{left:`${W}px`,top:26*(null!=L?L:k)+"px",width:`${O}px`,minWidth:"6px",height:"22px"},children:t(g,{style:{width:"100%",height:"100%",outline:p.selectedElements.find(e=>e.id===o.id)?"2px solid var(--pn-primary, var(--primary, #137cbd))":"none",outlineOffset:"-1px"},onPointerDown:e=>{if(!f(e)){return}e.stopPropagation();const t=e.clientX,n=I,i=N-n;G(e,{slopX:u,node:o,onMove:e=>{q();const r=(e.clientX-t)/T,s=l(C+n+r,C,H-i)-C;X(o,A,s,s+i)},onEnd:({moved:e,cancelled:t})=>{z(),e||t||(p.selectElements([o.id]),m(o))}})},children:[_?e(b,{value:o.name||"",onCommit:e=>{o.set({name:e}),B(!1)},onCancel:()=>B(!1)}):e(P,{children:$}),e(D,{onPointerDown:e=>F(e,"start")}),e(M,{onPointerDown:e=>F(e,"end")}),e(y,{onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:t(h,{children:[e(w,{}),t(v,{side:"top",className:"pn:whitespace-nowrap",children:[e(S,{element:o,store:p}),t(j,{onSelect:e=>{e.preventDefault(),B(!0)},children:[e(i,{name:"action.rename"}),d("contextMenu.rename")]}),t(j,{onSelect:e=>{e.preventDefault();const t=p.getElementById(o.id);t&&r([t],p)},children:[e(i,{name:"action.duplicate"}),d("contextMenu.duplicate")]}),t(j,{onSelect:e=>{e.preventDefault(),p.deleteElements([o.id])},children:[e(i,{name:"action.remove"}),d("contextMenu.remove")]})]})]})})]})})});
@@ -1,10 +1,16 @@
1
1
  import React from 'react';
2
2
  import type { PageType } from '../ui-types.js';
3
- export declare const usePagePreview: ({ page, setPreview, groupRef, }: {
3
+ type PagePreviewOptions = {
4
+ page: PageType;
5
+ ref: React.RefObject<HTMLDivElement | null>;
6
+ };
7
+ type LegacyPagePreviewOptions = {
4
8
  page: PageType;
5
9
  setPreview: (src: string | null) => void;
6
10
  groupRef: React.RefObject<HTMLDivElement | null>;
7
- }) => void;
11
+ };
12
+ export declare function usePagePreview(options: PagePreviewOptions): string | null;
13
+ export declare function usePagePreview(options: LegacyPagePreviewOptions): void;
8
14
  export declare const PagePreview: (({ page, scale }: {
9
15
  page: PageType;
10
16
  scale: number;
@@ -17,3 +23,4 @@ export declare const PagePreview: (({ page, scale }: {
17
23
  scale: number;
18
24
  }) => React.JSX.Element;
19
25
  };
26
+ export {};