polotno 4.17.0 → 4.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.
@@ -15,6 +15,7 @@ export declare function zIndexOps<T extends {
15
15
  }>(self: {
16
16
  children: ReadonlyArray<T> & {
17
17
  replace(items: T[]): unknown;
18
+ splice(start: number, deleteCount: number, ...items: T[]): unknown;
18
19
  };
19
20
  }): {
20
21
  canMoveElementsUp(ids: Array<string>): boolean;
@@ -26,6 +27,9 @@ export declare function zIndexOps<T extends {
26
27
  moveElementsTop(ids: Array<string>): void;
27
28
  moveElementsBottom(ids: Array<string>): void;
28
29
  setElementZIndex(id: string, zIndex: number): void;
30
+ _reconcileChildren(items: ReadonlyArray<{
31
+ id: string;
32
+ }>): void;
29
33
  };
30
34
  export declare const ElementTypes: any;
31
35
  type ElementUnion = (SVGElementType & {
@@ -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;
@@ -2016,6 +2016,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
2016
2016
  moveElementsTop(ids: Array<string>): void;
2017
2017
  moveElementsBottom(ids: Array<string>): void;
2018
2018
  setElementZIndex(id: string, zIndex: number): void;
2019
+ _reconcileChildren(items: readonly {
2020
+ id: string;
2021
+ }[]): void;
2019
2022
  clone(attrs?: {}): any;
2020
2023
  setZIndex(zIndex: number): void;
2021
2024
  set(attrs: Partial<SnapshotIn<import("mobx-state-tree").ModelInstanceTypeProps<{
package/model/store.d.ts CHANGED
@@ -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
674
  _toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, quickMode, _exportCanvases, }?: ExportOptions): Promise<HTMLCanvasElement>;
672
- toDataURL({ mimeType, quality, dpi, dpiMetadata, ...rest }?: ImageExportOptions): Promise<string>;
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;
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,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 S,createExportCanvases as O,releaseExportCanvases as k}from"../utils/canvas.js";import{whenLoaded as j,getAssetLoadTimeout as F}from"../utils/loader.js";import{polotnoError as R}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 B}from"./page-model.js";import{forEveryChild as D,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 G}from"../image-tools/sessions.js";function U(e){return!!e&&!!e.type&&"tablecell"!==e.type}function q(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 X=d.model("BrushOptions",{strokeWidth:d.optional(d.number,5),stroke:d.optional(d.string,"#000000"),opacity:d.optional(d.number,1)});export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=d.model("Store",{role:"",pages:d.array(B),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(X,{}),highlighter:d.optional(X,{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(U)},get children(){return e.pages},get selectedShapes(){const e=[];return D({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={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(()=>v.seek())},checkActivePage(){const e=l.pageAtTime(l.currentTime);e&&v.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),v.checkActivePage(),l.isPlaying&&l.currentTime<o?requestAnimationFrame(()=>v.seek()):l.isPlaying&&m?(l.currentTime=0,requestAnimationFrame(()=>v.seek())):v.pause()},pause(){l.isPlaying=!1,l.animatedElementsIds=o([])},stop(){v.pause(),l.currentTime=0,v.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=B.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(U);q(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))},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),v.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.")}q(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=v.toJSON();return r(l,o=>{const i=v.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 R("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)&&v.setElementsPixelRatio(p),c.set(a?{_forceMount:!0}:{_exporting:!0}),await u(()=>c._exportRendered||0===l._workspaces||!l.pages.includes(c),{timeout:F()}).catch(()=>{}),await j();const e=g.stages.filter(e=>e.getAttr("pageId")===o);if(!c._exportRendered||0===e.length){throw R("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 R("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"),y=h.clip();h.clip({x:null,y:null,width:null,height:null});const b=d.findOne(".elements-container"),P=b.clip();b.clip({x:null,y:null,width:null,height:null});const w=d.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const x=d.find(e=>e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&d.find(".page-background").forEach(e=>e.hide());const E=n?c.computedBleed:f;let I=E.left,_=E.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 O=c.computedWidth+E.left+E.right,k=c.computedHeight+E.top+E.bottom,A=d.scale();d.scale({x:1,y:1});const V=S(d,{x:d.x()-I,y:d.y()-_,width:O,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()),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),w.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(y),b.clip(P),s.position(m),null==c||c.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),C}finally{v.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 v._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 toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await v._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return g.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];y(await v.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 y=new r({unit:i,orientation:u>h?"landscape":"portrait",format:[u,h],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const b=((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 w=0;for(const l of b){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 v.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(++w/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})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.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 R("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){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await v._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 R("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=O(),u=l._elementsPixelRatio;v.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;v.setCurrentTime(n);for(const e of l.pages){e.set({_rendering:e.id===t.id})}const s=await v._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),v.setElementsPixelRatio(u);for(const e of l.pages){e.set({_rendering:!1})}v.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 v.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=v.toJSON();return C(t,{elementHook:e,textOverflow:T.textOverflow,textSplitAllowed:T.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await v.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=v.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 v.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 v._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},_setWorkspaceMounted(e){l._workspaces+=e?1:-1},async waitLoading(){await j()},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 G&&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"),D(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);v.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 v});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return E(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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "4.17.0",
3
+ "version": "4.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,10 +113,10 @@
113
113
  },
114
114
  "dependencies": {
115
115
  "@base-ui/react": "^1.9.0",
116
- "@polotno/core": "0.18.0",
117
- "@polotno/html-export": "0.9.2",
118
- "@polotno/schema": "0.9.0",
119
- "@polotno/svg-export": "0.10.2",
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",
@@ -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")]})]})]})})]})})});