polotno 1.11.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/model/store.d.ts CHANGED
@@ -537,6 +537,9 @@ export declare const Store: import("mobx-state-tree").IModelType<{
537
537
  dpi: number;
538
538
  };
539
539
  loadJSON(json: any, keepHistory?: boolean): void;
540
+ clear({ keepHistory }?: {
541
+ keepHistory?: boolean | undefined;
542
+ }): void;
540
543
  addFont(font: fonts.FONT): void;
541
544
  removeFont(fontFamily: string): void;
542
545
  loadFont(fontFamily: any): Promise<void>;
package/model/store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var a=Object.getOwnPropertyDescriptor(t,o);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,a)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&__createBinding(t,e,o);return __setModuleDefault(t,e),t},__rest=this&&this.__rest||function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(o[n[a]]=e[n[a]])}return o},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=exports.Store=exports.Font=exports.Page=exports.GroupElement=exports.registerShapeModel=exports.SVGElement=exports.LineElement=exports.VideoElement=exports.ImageElement=exports.TextElement=exports.Element=exports.Animation=exports.Node=void 0;const mobx_state_tree_1=require("mobx-state-tree"),history_1=require("./history"),nanoid_1=require("nanoid"),konva_1=__importDefault(require("konva")),download_1=require("../utils/download"),pdf_1=require("../utils/pdf"),gif_lib_1=require("../utils/gif-lib"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),loader_1=require("../utils/loader"),unit_1=require("../utils/unit"),deep_equal_1=require("../utils/deep-equal"),wait_1=require("../utils/wait"),html_1=require("../utils/html"),animations_1=require("../utils/animations");(0,mobx_state_tree_1.setLivelinessChecking)("ignore");const forEveryChild=(e,t)=>{e.children&&e.children.forEach((e=>{t(e),forEveryChild(e,t)}))};exports.Node=mobx_state_tree_1.types.model("Node",{id:mobx_state_tree_1.types.identifier,type:"none",name:"",opacity:1,custom:mobx_state_tree_1.types.frozen(),visible:!0,selectable:!0,removable:!0,alwaysOnTop:!1,showInExport:!0}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get locked(){return!(e.draggable||e.contentEditable||e.styleEditable||e.resizable)},get page(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Page)},get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get top(){let t=e;for(;;){if(!(0,mobx_state_tree_1.hasParentOfType)(t,exports.GroupElement))return t;t=(0,mobx_state_tree_1.getParentOfType)(t,exports.GroupElement)}},get parent(){return(0,mobx_state_tree_1.hasParentOfType)(e,exports.GroupElement)?(0,mobx_state_tree_1.getParentOfType)(e,exports.GroupElement):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Page)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Page):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Store)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Store):null}}))).actions((e=>({toJSON:()=>Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e))}))).actions((e=>({clone(t={}){const o=e.toJSON();return t.id=t.id||(0,nanoid_1.nanoid)(10),forEveryChild(o,(e=>{e.id=(0,nanoid_1.nanoid)(10)})),Object.assign(o,t),e.page.addElement(o)},set(t){Object.assign(e,t)},moveUp(){e.page.moveElementsUp([e.id])},moveTop(){e.page.moveElementsTop([e.id])},moveDown(){e.page.moveElementsDown([e.id])},moveBottom(){e.page.moveElementsBottom([e.id])},beforeDestroy(){e.store.history.endTransaction()}}))),exports.Animation=mobx_state_tree_1.types.model("Animation",{delay:0,duration:500,enabled:!0,type:mobx_state_tree_1.types.enumeration("Type",["enter","exit"]),name:"none",data:mobx_state_tree_1.types.frozen({})}),exports.Element=exports.Node.named("Element").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,animations:mobx_state_tree_1.types.array(exports.Animation),blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",shadowOpacity:1,visible:!0,draggable:!0,resizable:!0,selectable:!0,contentEditable:!0,styleEditable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot((e=>{const t=Object.assign(Object.assign({},e),{x:e.x||0,y:e.y||0});return"width"in e&&(t.width=t.width||1),"height"in e&&(t.height=t.height||1),e.locked&&(t.draggable=!1,t.contentEditable=!1,t.styleEditable=!1,t.resizable=!1),t})).views((e=>({get a(){const{currentTime:t}=e.store,o={x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,opacity:e.opacity,color:e.color,fontSize:e.fontSize};if(0===t)return o;const n=t-e.page.startTime;if(n>e.page.duration)return o;if(n<0)return o;const a=e.store.animatedElementsIds;if(a.length&&!a.includes(e.id))return o;const i=e.animations.find((e=>"enter"===e.type));(null==i?void 0:i.enabled)&&n<i.delay&&(o.opacity=0);if((null==i?void 0:i.enabled)&&n>=i.delay&&n<=i.delay+i.duration){const t=n-i.delay,a=(0,animations_1.animate)({element:e,animation:i,dTime:t});Object.assign(o,a)}const s=e.animations.find((e=>"exit"===e.type));if((null==s?void 0:s.enabled)&&n>=e.page.duration-s.duration){const t=n-(e.page.duration-s.duration),a=(0,animations_1.animate)({element:e,animation:s,dTime:t});Object.assign(o,a)}return o},animated:t=>e.a[t]}))).actions((e=>({setAnimation(t,o){const n=e.animations.find((e=>e.type===t));n?Object.assign(n,o):e.animations.push(Object.assign({type:t},o))}}))),exports.TextElement=exports.Element.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5}).preProcessSnapshot((e=>Object.assign({},e))).actions((e=>({toggleEditMode(t){e._editModeEnabled=null!=t?t:!e._editModeEnabled,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.ImageElement=exports.Element.named("Image").props({type:"image",width:100,height:100,src:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,cornerRadius:0,flipX:!1,flipY:!1,clipSrc:"",borderColor:"black",borderSize:0,keepRatio:!1,_cropModeEnabled:!1}).actions((e=>({toggleCropMode(t){e._cropModeEnabled=null!=t?t:!e._cropModeEnabled,e._cropModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.VideoElement=exports.ImageElement.named("Video").props({type:"video",duration:0}),exports.LineElement=exports.Element.named("Line").props({type:"line",width:400,height:10,color:"black",dash:mobx_state_tree_1.types.array(mobx_state_tree_1.types.number),startHead:"",endHead:""}).actions((e=>({}))),exports.SVGElement=exports.Element.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:mobx_state_tree_1.types.map(mobx_state_tree_1.types.string)}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource}))).actions((e=>({replaceColor(t,o){e.colorsReplace.set(t,o)}})));const ADDITIONAL_TYPES=[];function registerShapeModel(e){const t=e.type;if(!t)throw new Error('You must pass "type" attribute to custom model.');const o=exports.Element.named(t).props(e);TYPES_MAP[t]=o,ADDITIONAL_TYPES.push(o)}exports.registerShapeModel=registerShapeModel;const additionalTypesUnion=[...new Array(20)].map(((e,t)=>mobx_state_tree_1.types.late((()=>ADDITIONAL_TYPES[t])))),ElementTypes=mobx_state_tree_1.types.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t)throw new Error(`Unknown element type: "${e.type}"`);return t}},exports.SVGElement,exports.TextElement,exports.ImageElement,exports.LineElement,exports.VideoElement,mobx_state_tree_1.types.late((()=>exports.GroupElement)),...additionalTypesUnion);exports.GroupElement=exports.Node.named("Group").props({type:"group",children:mobx_state_tree_1.types.array(ElementTypes)}).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}}))).actions((e=>({set(t){var{draggable:o,contentEditable:n,styleEditable:a,resizable:i}=t,s=__rest(t,["draggable","contentEditable","styleEditable","resizable"]);void 0!==o&&forEveryChild(e,(e=>{e.set({draggable:o})})),void 0!==n&&forEveryChild(e,(e=>{e.set({contentEditable:n})})),void 0!==a&&forEveryChild(e,(e=>{e.set({styleEditable:a})})),void 0!==i&&forEveryChild(e,(e=>{e.set({resizable:i})})),Object.assign(e,s)}})));const TYPES_MAP={svg:exports.SVGElement,text:exports.TextElement,image:exports.ImageElement,group:exports.GroupElement,line:exports.LineElement,video:exports.VideoElement};function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){const o=exports.Store.create();return(0,validate_key_1.validateKey)(e,t),o}exports.Page=mobx_state_tree_1.types.model("Page",{id:mobx_state_tree_1.types.identifier,children:mobx_state_tree_1.types.array(ElementTypes),width:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),height:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),background:"white",bleed:0,custom:mobx_state_tree_1.types.frozen(),duration:5e3,_exporting:!1,_rendering:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id)return t;t+=o.duration}return t}}))).views((e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height}}))).actions((e=>({toJSON:()=>JSON.parse(JSON.stringify((0,mobx_state_tree_1.getSnapshot)(e))),_forEachElementUp(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>t.index-e.index));for(const{index:a}of n){if(-1==a)continue;const n=a<e.children.length-1&&e.children[a+1],i=t.indexOf(null==n?void 0:n.id)>=0;a===e.children.length-1||i||o(a)}},_forEachElementDown(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>e.index-t.index));for(const{index:a}of n){if(-1==a)continue;const n=a>0&&e.children[a-1],i=t.indexOf(null==n?void 0:n.id)>=0;0===a||i||o(a)}return!1}}))).actions((e=>({clone(t={}){const o=e.toJSON();o.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10),forEveryChild(e,(e=>{e.id=(0,nanoid_1.nanoid)(10)}))}));const n=Object.assign(Object.assign(Object.assign({},o),{id:(0,nanoid_1.nanoid)(10)}),t),a=e.store.addPage(n),i=e.store.pages.indexOf(e);a.setZIndex(i+1),a.select()},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t){const o=TYPES_MAP[t.type];if(!o)return void console.error("Can not find model with type "+t.type);t.children&&t.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10)}));const n=o.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.children.push(n),n.selectable&&e.store.selectElements([n.id]),n},canMoveElementsUp(t){let o=!1;return e._forEachElementUp(t,(()=>{o=o||!0})),o},moveElementsUp(t){e._forEachElementUp(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t+1,0,o)}))},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(n.concat(o))},canMoveElementsDown(t){let o=!1;return e._forEachElementDown(t,(()=>{o=o||!0})),o},moveElementsDown(t){e._forEachElementDown(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t-1,0,o)}))},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(o.concat(n))},setElementZIndex(t,o){const n=e.children.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.children.remove(n),e.children.splice(o,0,n))},setSize({width:t,height:o,useMagic:n,softChange:a}){if(n){const n=t/e.computedWidth,a=o/e.computedHeight;for(const t of e.children)t.set({x:t.x*n,y:t.y*a}),"text"===t.type?t.set({fontSize:t.fontSize*n,width:Math.max(t.width*n,2)}):"image"===t.type?t.set({width:t.width*n,height:t.height*a}):"svg"===t.type&&t.set({width:Math.max(t.width*n,2),height:Math.max(t.height*n,2)})}a||(e.width=t),a||(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])}}))),exports.Font=mobx_state_tree_1.types.model("Font",{fontFamily:mobx_state_tree_1.types.string,url:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.string,""),styles:mobx_state_tree_1.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=mobx_state_tree_1.types.model("Store",{role:"",pages:mobx_state_tree_1.types.array(exports.Page),fonts:mobx_state_tree_1.types.array(exports.Font),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",selectedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),animatedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),history:mobx_state_tree_1.types.optional(history_1.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).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=>{for(const o of e.pages)for(const e of o.children)if(e.id===t)return e})).filter((e=>!!e))},get children(){return e.pages},get selectedShapes(){const t=[];return e.selectedElementsIds.forEach((o=>{for(const n of e.pages)for(const e of n.children)e.id===o&&"group"!==e.type&&t.push(e),"group"===e.type&&e.id===o&&t.push(...e.children)})),t},get activePage(){return e.pages.slice().find((t=>t.id===e._activePageId))||(e.pages.length?e.pages[0]:null)},get duration(){let t=0;return e.pages.forEach((e=>{t+=e.duration})),t}}))).actions((e=>{let t=0;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},play({animatedElementsIds:o=[],currentTime:n=0}={}){e.animatedElementsIds=(0,mobx_state_tree_1.cast)(o),e.currentTime=n,e.isPlaying=!0,t=Date.now(),requestAnimationFrame(e.seek)},seek(){if(!e.isPlaying)return;const o=Date.now(),n=o-t;t=o,e.currentTime+=n;let a=0;for(const t of e.pages){if(e.currentTime>=t.startTime&&e.currentTime<t.startTime+t.duration){e.selectPage(t.id);break}a+=t.duration}e.isPlaying&&e.currentTime<e.duration?requestAnimationFrame(e.seek):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,mobx_state_tree_1.cast)([])}}})).actions((e=>({setUnit({unit:t,dpi:o}){e.unit=t||e.unit,e.dpi=o||e.dpi},setRole(t){e.role=t},find(t){let o;return forEveryChild({children:e.pages},(e=>{!o&&t(e)&&(o=e)})),o},getElementById:t=>e.find((e=>e.id===t)),addPage(t){const o=exports.Page.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.pages.push(o),e._activePageId=o.id,o},selectPage(t){e._activePageId=t},selectElements(t){const o=t.map((t=>e.getElementById(t))).sort(((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t))).filter((e=>!!e)).map((e=>e.id));e.selectedElementsIds=(0,mobx_state_tree_1.cast)(o)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,o,n){e.pages.forEach((e=>{e.setSize({width:t,height:o,useMagic:n,softChange:!0})})),e.width=t,e.height=o},setPageZIndex(t,o){const n=e.pages.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.pages.remove(n),e.pages.splice(o,0,n))},deletePages(t){const o=e.pages.indexOf(e.activePage);t.forEach((t=>{const o=e.pages.find((e=>e.id===t));(0,mobx_state_tree_1.destroy)(o)}));const n=Math.min(e.pages.length-1,o),a=e.pages[n];a&&(e._activePageId=a.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const o=t.map((t=>e.getElementById(t)));o.forEach((e=>{e&&(0,mobx_state_tree_1.detach)(e)}));const n=e.activePage,a=exports.GroupElement.create({id:(0,nanoid_1.nanoid)(10),children:(0,mobx_state_tree_1.cast)(o)});return n.children.push(a),e.selectedElementsIds=(0,mobx_state_tree_1.cast)([a.id]),a},ungroupElements(t){const o=t.map((t=>e.getElementById(t))),n=[];o.forEach((e=>{if(e&&"group"===e.type){const t=e.page,o=t.children.indexOf(e);e.children.forEach((e=>{n.push(e.id)})),e.children.forEach((e=>{(0,mobx_state_tree_1.detach)(e),t.children.push(e)})),t.children.splice(o,1)}})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(n)},deleteElements(t){t.forEach((t=>{e.pages.forEach((e=>{const o=e.children.find((e=>e.id===t));o&&(0,mobx_state_tree_1.destroy)(o)}))})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,o){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(n=>{const a=e.toJSON();!(0,deep_equal_1.deepEqual)(t,a)&&(t=a,o(a))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}={}){var s;const r=t||1;n=n||(null===(s=e.pages[0])||void 0===s?void 0:s.id);const l=e.pages.find((e=>e.id===n));if(!l)throw new Error(`No page for export with id ${n}`);null==l||l.set({_exporting:!0});const d=await(0,wait_1.waitTillAvailable)((()=>konva_1.default.stages.find((e=>e.getAttr("pageId")===n))));if(!d)throw new Error(`Export is failed. Can not find stage for page ${n}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);const c=!!d.findOne(".page-container");await e.waitLoading();const p=d.findOne(".page-container");if(!p)throw new Error(`Export is failed. Can't find page container. ${c}`);d.find("Transformer").forEach((e=>e.visible(!1))),p.find(".page-background").forEach((e=>e.shadowEnabled(!1))),p.find(".page-background").forEach((e=>e.strokeEnabled(!1))),p.find(".highlighter").forEach((e=>e.visible(!1)));const m=p.findOne(".page-background-group"),_=m.clip();m.clip({x:null,y:null,width:null,height:null});const g=p.findOne(".elements-container"),h=g.clip();g.clip({x:null,y:null,width:null,height:null});const u=p.find((e=>e.getAttr("hideInExport")));u.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const f=p.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));f.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),o&&p.find(".page-background").forEach((e=>e.hide()));const b=i?l.bleed:0;let x=b;e.bleedVisible&&i?x=0:e.bleedVisible&&!i&&(x=-l.bleed);const y=document.createElement("canvas");y.width=(l.computedWidth+2*b)*r,y.height=(l.computedHeight+2*b)*r;const E=y.getContext("2d");"image/jpeg"===a&&(E.fillStyle="white",E.fillRect(0,0,y.width,y.height));const v=p.toCanvas({x:p.x()-x*p.scaleX(),y:p.y()-x*p.scaleY(),width:(l.computedWidth+2*b)*p.scaleX(),height:(l.computedHeight+2*b)*p.scaleY(),pixelRatio:1/p.scaleX()*r});return E.drawImage(v,0,0),konva_1.default.Util.releaseCanvas(v),o&&p.find(".page-background").forEach((e=>e.show())),u.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),f.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),p.find(".page-background").forEach((e=>e.shadowEnabled(!0))),p.find(".page-background").forEach((e=>e.strokeEnabled(!0))),d.find("Transformer").forEach((e=>e.visible(!0))),p.find(".highlighter").forEach((e=>e.visible(!0))),m.clip(_),g.clip(h),null==l||l.set({_exporting:!1}),y},async toDataURL({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=r.toDataURL(a,s);return konva_1.default.Util.releaseCanvas(r),l},async toBlob({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=new Promise((e=>{r.toBlob(e,a,s)}));return konva_1.default.Util.releaseCanvas(r),l},async saveAsImage(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);const a=n.mimeType||"image/png",i=a.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(n),o||"polotno."+i,a)},async _toPDF(t){const o=t.dpi||e.dpi,n=t.parallel||1,a=t.unit||("px"===e.unit?"mm":e.unit),i=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,pdf_1.getJsPDF)(),d=e=>(0,unit_1.pxToUnit)({px:e,unit:a,dpi:o}),c=r[0]||{},p=t.includeBleed?c.bleed:0,m=d(c.computedWidth+2*p),_=d(c.computedHeight+2*p);var g=new l({unit:a,orientation:m>_?"landscape":"portrait",format:[m,_],compress:!0,putOnlyUsedFonts:!0});g.deletePage(1);const h=e._elementsPixelRatio;e.setElementsPixelRatio(i),await new Promise((e=>setTimeout(e)));const u=((e,t)=>{for(var o=[],n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o})(r,n);for(const o of u){const n=o.map((async o=>{const n=t.includeBleed?o.bleed:0,a=d(o.computedWidth+2*n),s=d(o.computedHeight+2*n);let r=0,l=i;for(;r<10;){r+=1,2===r&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const n=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:o.id,pixelRatio:l}));if(n.length>20)return{url:n,width:a,height:s};l*=.8}}));(await Promise.all(n)).forEach((({url:e,width:t,height:o})=>{g.addPage([t,o],t>o?"landscape":"portrait"),g.addImage(e,0,0,t,o,void 0,"FAST")}))}return e.setElementsPixelRatio(h),g},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toGIFDataURL(t={}){const o=t.pixelRatio||1,n=await(0,gif_lib_1.createGIF)({width:e.width*o,height:e.height*o}),a=1e3/(t.fps||10),i=e.duration/a;for(let t=0;t<i-1;t++){const i=t*a||1;e.setCurrentTime(i);let s=0,r="";for(const t of e.pages)if(s+=t.duration,t.set({_rendering:s>i}),s>i){r=t.id;break}const l=await e._toCanvas({pixelRatio:o,pageId:r});n.addFrame(l.getContext("2d"),{delay:a,copy:!0})}for(const t of e.pages)t.set({_rendering:!1});e.stop(),n.render();return new Promise((e=>{n.on("finished",(function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)}))}))},async saveAsGIF(t={}){const o=await e.toGIFDataURL(t);(0,download_1.downloadFile)(o,"polotno.gif")},async toHTML(){const t=e.toJSON();return(0,html_1.jsonToHTML)({json:t})},async saveAsHTML({filename:t}={}){const o=await e.toHTML(),n="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));(0,download_1.downloadFile)(n,t||"polotno.html")},async saveAsPDF(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},n))).save(o||"polotno.pdf")},async waitLoading(){await new Promise((e=>setTimeout(e,50))),await(0,loader_1.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,mobx_state_tree_1.getSnapshot)(e.fonts),pages:(0,mobx_state_tree_1.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi}),loadJSON(t,o=!1){var n;const a=Object.assign({},t),i=e.pages.indexOf(e.activePage);let s=null===(n=a.pages[i]||a.pages[0])||void 0===n?void 0:n.id;a._activePageId=s;const r=Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e));Object.assign(r,a),r.history=o?e.history.toJSON():{history:[],undoIdx:-1},(0,mobx_state_tree_1.applySnapshot)(e,r)},addFont(t){e.removeFont(t.fontFamily),e.fonts.push(t),e.loadFont(t.fontFamily)},removeFont(t){e.fonts.filter((e=>e.fontFamily===t)).forEach((e=>(0,mobx_state_tree_1.destroy)(e)))},async loadFont(t){const o=e.fonts.find((e=>e.fontFamily===t))||fonts.globalFonts.find((e=>e.fontFamily===t));o?fonts.injectCustomFont(o):fonts.injectGoogleFont(t),await fonts.loadFont(t)}}))),exports.createStore=createStore,exports.default=createStore;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var a=Object.getOwnPropertyDescriptor(t,o);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,a)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&__createBinding(t,e,o);return __setModuleDefault(t,e),t},__rest=this&&this.__rest||function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(o[n[a]]=e[n[a]])}return o},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=exports.Store=exports.Font=exports.Page=exports.GroupElement=exports.registerShapeModel=exports.SVGElement=exports.LineElement=exports.VideoElement=exports.ImageElement=exports.TextElement=exports.Element=exports.Animation=exports.Node=void 0;const mobx_state_tree_1=require("mobx-state-tree"),history_1=require("./history"),nanoid_1=require("nanoid"),konva_1=__importDefault(require("konva")),download_1=require("../utils/download"),pdf_1=require("../utils/pdf"),gif_lib_1=require("../utils/gif-lib"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),loader_1=require("../utils/loader"),unit_1=require("../utils/unit"),deep_equal_1=require("../utils/deep-equal"),wait_1=require("../utils/wait"),html_1=require("../utils/html"),animations_1=require("../utils/animations");(0,mobx_state_tree_1.setLivelinessChecking)("ignore");const forEveryChild=(e,t)=>{e.children&&e.children.forEach((e=>{t(e),forEveryChild(e,t)}))};exports.Node=mobx_state_tree_1.types.model("Node",{id:mobx_state_tree_1.types.identifier,type:"none",name:"",opacity:1,custom:mobx_state_tree_1.types.frozen(),visible:!0,selectable:!0,removable:!0,alwaysOnTop:!1,showInExport:!0}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get locked(){return!(e.draggable||e.contentEditable||e.styleEditable||e.resizable)},get page(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Page)},get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get top(){let t=e;for(;;){if(!(0,mobx_state_tree_1.hasParentOfType)(t,exports.GroupElement))return t;t=(0,mobx_state_tree_1.getParentOfType)(t,exports.GroupElement)}},get parent(){return(0,mobx_state_tree_1.hasParentOfType)(e,exports.GroupElement)?(0,mobx_state_tree_1.getParentOfType)(e,exports.GroupElement):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Page)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Page):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Store)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Store):null}}))).actions((e=>({toJSON:()=>Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e))}))).actions((e=>({clone(t={}){const o=e.toJSON();return t.id=t.id||(0,nanoid_1.nanoid)(10),forEveryChild(o,(e=>{e.id=(0,nanoid_1.nanoid)(10)})),Object.assign(o,t),e.page.addElement(o)},set(t){Object.assign(e,t)},moveUp(){e.page.moveElementsUp([e.id])},moveTop(){e.page.moveElementsTop([e.id])},moveDown(){e.page.moveElementsDown([e.id])},moveBottom(){e.page.moveElementsBottom([e.id])},beforeDestroy(){e.store.history.endTransaction()}}))),exports.Animation=mobx_state_tree_1.types.model("Animation",{delay:0,duration:500,enabled:!0,type:mobx_state_tree_1.types.enumeration("Type",["enter","exit"]),name:"none",data:mobx_state_tree_1.types.frozen({})}),exports.Element=exports.Node.named("Element").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,animations:mobx_state_tree_1.types.array(exports.Animation),blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",shadowOpacity:1,visible:!0,draggable:!0,resizable:!0,selectable:!0,contentEditable:!0,styleEditable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot((e=>{const t=Object.assign(Object.assign({},e),{x:e.x||0,y:e.y||0});return"width"in e&&(t.width=t.width||1),"height"in e&&(t.height=t.height||1),e.locked&&(t.draggable=!1,t.contentEditable=!1,t.styleEditable=!1,t.resizable=!1),t})).views((e=>({get a(){const{currentTime:t}=e.store,o={x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,opacity:e.opacity,color:e.color,fontSize:e.fontSize};if(0===t)return o;const n=t-e.page.startTime;if(n>e.page.duration)return o;if(n<0)return o;const a=e.store.animatedElementsIds;if(a.length&&!a.includes(e.id))return o;const i=e.animations.find((e=>"enter"===e.type));(null==i?void 0:i.enabled)&&n<i.delay&&(o.opacity=0);if((null==i?void 0:i.enabled)&&n>=i.delay&&n<=i.delay+i.duration){const t=n-i.delay,a=(0,animations_1.animate)({element:e,animation:i,dTime:t});Object.assign(o,a)}const s=e.animations.find((e=>"exit"===e.type));if((null==s?void 0:s.enabled)&&n>=e.page.duration-s.duration){const t=n-(e.page.duration-s.duration),a=(0,animations_1.animate)({element:e,animation:s,dTime:t});Object.assign(o,a)}return o},animated:t=>e.a[t]}))).actions((e=>({setAnimation(t,o){const n=e.animations.find((e=>e.type===t));n?Object.assign(n,o):e.animations.push(Object.assign({type:t},o))}}))),exports.TextElement=exports.Element.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5}).preProcessSnapshot((e=>Object.assign({},e))).actions((e=>({toggleEditMode(t){e._editModeEnabled=null!=t?t:!e._editModeEnabled,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.ImageElement=exports.Element.named("Image").props({type:"image",width:100,height:100,src:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,cornerRadius:0,flipX:!1,flipY:!1,clipSrc:"",borderColor:"black",borderSize:0,keepRatio:!1,_cropModeEnabled:!1}).actions((e=>({toggleCropMode(t){e._cropModeEnabled=null!=t?t:!e._cropModeEnabled,e._cropModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.VideoElement=exports.ImageElement.named("Video").props({type:"video",duration:0}),exports.LineElement=exports.Element.named("Line").props({type:"line",width:400,height:10,color:"black",dash:mobx_state_tree_1.types.array(mobx_state_tree_1.types.number),startHead:"",endHead:""}).actions((e=>({}))),exports.SVGElement=exports.Element.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:mobx_state_tree_1.types.map(mobx_state_tree_1.types.string)}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource}))).actions((e=>({replaceColor(t,o){e.colorsReplace.set(t,o)}})));const ADDITIONAL_TYPES=[];function registerShapeModel(e){const t=e.type;if(!t)throw new Error('You must pass "type" attribute to custom model.');const o=exports.Element.named(t).props(e);TYPES_MAP[t]=o,ADDITIONAL_TYPES.push(o)}exports.registerShapeModel=registerShapeModel;const additionalTypesUnion=[...new Array(20)].map(((e,t)=>mobx_state_tree_1.types.late((()=>ADDITIONAL_TYPES[t])))),ElementTypes=mobx_state_tree_1.types.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t)throw new Error(`Unknown element type: "${e.type}"`);return t}},exports.SVGElement,exports.TextElement,exports.ImageElement,exports.LineElement,exports.VideoElement,mobx_state_tree_1.types.late((()=>exports.GroupElement)),...additionalTypesUnion);exports.GroupElement=exports.Node.named("Group").props({type:"group",children:mobx_state_tree_1.types.array(ElementTypes)}).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}}))).actions((e=>({set(t){var{draggable:o,contentEditable:n,styleEditable:a,resizable:i}=t,s=__rest(t,["draggable","contentEditable","styleEditable","resizable"]);void 0!==o&&forEveryChild(e,(e=>{e.set({draggable:o})})),void 0!==n&&forEveryChild(e,(e=>{e.set({contentEditable:n})})),void 0!==a&&forEveryChild(e,(e=>{e.set({styleEditable:a})})),void 0!==i&&forEveryChild(e,(e=>{e.set({resizable:i})})),Object.assign(e,s)}})));const TYPES_MAP={svg:exports.SVGElement,text:exports.TextElement,image:exports.ImageElement,group:exports.GroupElement,line:exports.LineElement,video:exports.VideoElement};function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){const o=exports.Store.create();return(0,validate_key_1.validateKey)(e,t),o}exports.Page=mobx_state_tree_1.types.model("Page",{id:mobx_state_tree_1.types.identifier,children:mobx_state_tree_1.types.array(ElementTypes),width:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),height:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),background:"white",bleed:0,custom:mobx_state_tree_1.types.frozen(),duration:5e3,_exporting:!1,_rendering:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id)return t;t+=o.duration}return t}}))).views((e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height}}))).actions((e=>({toJSON:()=>JSON.parse(JSON.stringify((0,mobx_state_tree_1.getSnapshot)(e))),_forEachElementUp(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>t.index-e.index));for(const{index:a}of n){if(-1==a)continue;const n=a<e.children.length-1&&e.children[a+1],i=t.indexOf(null==n?void 0:n.id)>=0;a===e.children.length-1||i||o(a)}},_forEachElementDown(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>e.index-t.index));for(const{index:a}of n){if(-1==a)continue;const n=a>0&&e.children[a-1],i=t.indexOf(null==n?void 0:n.id)>=0;0===a||i||o(a)}return!1}}))).actions((e=>({clone(t={}){const o=e.toJSON();o.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10),forEveryChild(e,(e=>{e.id=(0,nanoid_1.nanoid)(10)}))}));const n=Object.assign(Object.assign(Object.assign({},o),{id:(0,nanoid_1.nanoid)(10)}),t),a=e.store.addPage(n),i=e.store.pages.indexOf(e);a.setZIndex(i+1),a.select()},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t){const o=TYPES_MAP[t.type];if(!o)return void console.error("Can not find model with type "+t.type);t.children&&t.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10)}));const n=o.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.children.push(n),n.selectable&&e.store.selectElements([n.id]),n},canMoveElementsUp(t){let o=!1;return e._forEachElementUp(t,(()=>{o=o||!0})),o},moveElementsUp(t){e._forEachElementUp(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t+1,0,o)}))},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(n.concat(o))},canMoveElementsDown(t){let o=!1;return e._forEachElementDown(t,(()=>{o=o||!0})),o},moveElementsDown(t){e._forEachElementDown(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t-1,0,o)}))},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(o.concat(n))},setElementZIndex(t,o){const n=e.children.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.children.remove(n),e.children.splice(o,0,n))},setSize({width:t,height:o,useMagic:n,softChange:a}){if(n){const n=t/e.computedWidth,a=o/e.computedHeight;for(const t of e.children)t.set({x:t.x*n,y:t.y*a}),"text"===t.type?t.set({fontSize:t.fontSize*n,width:Math.max(t.width*n,2)}):"image"===t.type?t.set({width:t.width*n,height:t.height*a}):"svg"===t.type&&t.set({width:Math.max(t.width*n,2),height:Math.max(t.height*n,2)})}a||(e.width=t),a||(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])}}))),exports.Font=mobx_state_tree_1.types.model("Font",{fontFamily:mobx_state_tree_1.types.string,url:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.string,""),styles:mobx_state_tree_1.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=mobx_state_tree_1.types.model("Store",{role:"",pages:mobx_state_tree_1.types.array(exports.Page),fonts:mobx_state_tree_1.types.array(exports.Font),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",selectedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),animatedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),history:mobx_state_tree_1.types.optional(history_1.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).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=>{for(const o of e.pages)for(const e of o.children)if(e.id===t)return e})).filter((e=>!!e))},get children(){return e.pages},get selectedShapes(){const t=[];return e.selectedElementsIds.forEach((o=>{for(const n of e.pages)for(const e of n.children)e.id===o&&"group"!==e.type&&t.push(e),"group"===e.type&&e.id===o&&t.push(...e.children)})),t},get activePage(){return e.pages.slice().find((t=>t.id===e._activePageId))||(e.pages.length?e.pages[0]:null)},get duration(){let t=0;return e.pages.forEach((e=>{t+=e.duration})),t}}))).actions((e=>{let t=0;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},play({animatedElementsIds:o=[],currentTime:n=0}={}){e.animatedElementsIds=(0,mobx_state_tree_1.cast)(o),e.currentTime=n,e.isPlaying=!0,t=Date.now(),requestAnimationFrame(e.seek)},seek(){if(!e.isPlaying)return;const o=Date.now(),n=o-t;t=o,e.currentTime+=n;let a=0;for(const t of e.pages){if(e.currentTime>=t.startTime&&e.currentTime<t.startTime+t.duration){e.selectPage(t.id);break}a+=t.duration}e.isPlaying&&e.currentTime<e.duration?requestAnimationFrame(e.seek):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,mobx_state_tree_1.cast)([])}}})).actions((e=>({setUnit({unit:t,dpi:o}){e.unit=t||e.unit,e.dpi=o||e.dpi},setRole(t){e.role=t},find(t){let o;return forEveryChild({children:e.pages},(e=>{!o&&t(e)&&(o=e)})),o},getElementById:t=>e.find((e=>e.id===t)),addPage(t){const o=exports.Page.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.pages.push(o),e._activePageId=o.id,o},selectPage(t){e._activePageId=t},selectElements(t){const o=t.map((t=>e.getElementById(t))).sort(((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t))).filter((e=>!!e)).map((e=>e.id));e.selectedElementsIds=(0,mobx_state_tree_1.cast)(o)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,o,n){e.pages.forEach((e=>{e.setSize({width:t,height:o,useMagic:n,softChange:!0})})),e.width=t,e.height=o},setPageZIndex(t,o){const n=e.pages.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.pages.remove(n),e.pages.splice(o,0,n))},deletePages(t){const o=e.pages.indexOf(e.activePage);t.forEach((t=>{const o=e.pages.find((e=>e.id===t));(0,mobx_state_tree_1.destroy)(o)}));const n=Math.min(e.pages.length-1,o),a=e.pages[n];a&&(e._activePageId=a.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const o=t.map((t=>e.getElementById(t)));o.forEach((e=>{e&&(0,mobx_state_tree_1.detach)(e)}));const n=e.activePage,a=exports.GroupElement.create({id:(0,nanoid_1.nanoid)(10),children:(0,mobx_state_tree_1.cast)(o)});return n.children.push(a),e.selectedElementsIds=(0,mobx_state_tree_1.cast)([a.id]),a},ungroupElements(t){const o=t.map((t=>e.getElementById(t))),n=[];o.forEach((e=>{if(e&&"group"===e.type){const t=e.page,o=t.children.indexOf(e);e.children.forEach((e=>{n.push(e.id)})),e.children.forEach((e=>{(0,mobx_state_tree_1.detach)(e),t.children.push(e)})),t.children.splice(o,1)}})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(n)},deleteElements(t){t.forEach((t=>{e.pages.forEach((e=>{const o=e.children.find((e=>e.id===t));o&&(0,mobx_state_tree_1.destroy)(o)}))})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,o){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(n=>{const a=e.toJSON();!(0,deep_equal_1.deepEqual)(t,a)&&(t=a,o(a))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}={}){var s;const r=t||1;n=n||(null===(s=e.pages[0])||void 0===s?void 0:s.id);const l=e.pages.find((e=>e.id===n));if(!l)throw new Error(`No page for export with id ${n}`);null==l||l.set({_exporting:!0});const d=await(0,wait_1.waitTillAvailable)((()=>konva_1.default.stages.find((e=>e.getAttr("pageId")===n))));if(!d)throw new Error(`Export is failed. Can not find stage for page ${n}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);const c=!!d.findOne(".page-container");await e.waitLoading();const p=d.findOne(".page-container");if(!p)throw new Error(`Export is failed. Can't find page container. ${c}`);d.find("Transformer").forEach((e=>e.visible(!1))),p.find(".page-background").forEach((e=>e.shadowEnabled(!1))),p.find(".page-background").forEach((e=>e.strokeEnabled(!1))),p.find(".highlighter").forEach((e=>e.visible(!1)));const m=p.findOne(".page-background-group"),_=m.clip();m.clip({x:null,y:null,width:null,height:null});const g=p.findOne(".elements-container"),h=g.clip();g.clip({x:null,y:null,width:null,height:null});const u=p.find((e=>e.getAttr("hideInExport")));u.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const f=p.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));f.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),o&&p.find(".page-background").forEach((e=>e.hide()));const b=i?l.bleed:0;let y=b;e.bleedVisible&&i?y=0:e.bleedVisible&&!i&&(y=-l.bleed);const x=document.createElement("canvas");x.width=(l.computedWidth+2*b)*r,x.height=(l.computedHeight+2*b)*r;const E=x.getContext("2d");"image/jpeg"===a&&(E.fillStyle="white",E.fillRect(0,0,x.width,x.height));const v=p.toCanvas({x:p.x()-y*p.scaleX(),y:p.y()-y*p.scaleY(),width:(l.computedWidth+2*b)*p.scaleX(),height:(l.computedHeight+2*b)*p.scaleY(),pixelRatio:1/p.scaleX()*r});return E.drawImage(v,0,0),konva_1.default.Util.releaseCanvas(v),o&&p.find(".page-background").forEach((e=>e.show())),u.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),f.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),p.find(".page-background").forEach((e=>e.shadowEnabled(!0))),p.find(".page-background").forEach((e=>e.strokeEnabled(!0))),d.find("Transformer").forEach((e=>e.visible(!0))),p.find(".highlighter").forEach((e=>e.visible(!0))),m.clip(_),g.clip(h),null==l||l.set({_exporting:!1}),x},async toDataURL({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=r.toDataURL(a,s);return konva_1.default.Util.releaseCanvas(r),l},async toBlob({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=new Promise((e=>{r.toBlob(e,a,s)}));return konva_1.default.Util.releaseCanvas(r),l},async saveAsImage(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);const a=n.mimeType||"image/png",i=a.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(n),o||"polotno."+i,a)},async _toPDF(t){const o=t.dpi||e.dpi,n=t.parallel||1,a=t.unit||("px"===e.unit?"mm":e.unit),i=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,pdf_1.getJsPDF)(),d=e=>(0,unit_1.pxToUnit)({px:e,unit:a,dpi:o}),c=r[0]||{},p=t.includeBleed?c.bleed:0,m=d(c.computedWidth+2*p),_=d(c.computedHeight+2*p);var g=new l({unit:a,orientation:m>_?"landscape":"portrait",format:[m,_],compress:!0,putOnlyUsedFonts:!0});g.deletePage(1);const h=e._elementsPixelRatio;e.setElementsPixelRatio(i),await new Promise((e=>setTimeout(e)));const u=((e,t)=>{for(var o=[],n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o})(r,n);for(const o of u){const n=o.map((async o=>{const n=t.includeBleed?o.bleed:0,a=d(o.computedWidth+2*n),s=d(o.computedHeight+2*n);let r=0,l=i;for(;r<10;){r+=1,2===r&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const n=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:o.id,pixelRatio:l}));if(n.length>20)return{url:n,width:a,height:s};l*=.8}}));(await Promise.all(n)).forEach((({url:e,width:t,height:o})=>{g.addPage([t,o],t>o?"landscape":"portrait"),g.addImage(e,0,0,t,o,void 0,"FAST")}))}return e.setElementsPixelRatio(h),g},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toGIFDataURL(t={}){const o=t.pixelRatio||1,n=await(0,gif_lib_1.createGIF)({width:e.width*o,height:e.height*o}),a=1e3/(t.fps||10),i=e.duration/a;for(let t=0;t<i-1;t++){const i=t*a||1;e.setCurrentTime(i);let s=0,r="";for(const t of e.pages)if(s+=t.duration,t.set({_rendering:s>i}),s>i){r=t.id;break}const l=await e._toCanvas({pixelRatio:o,pageId:r});n.addFrame(l.getContext("2d"),{delay:a,copy:!0})}for(const t of e.pages)t.set({_rendering:!1});e.stop(),n.render();return new Promise((e=>{n.on("finished",(function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)}))}))},async saveAsGIF(t={}){const o=await e.toGIFDataURL(t);(0,download_1.downloadFile)(o,"polotno.gif")},async toHTML(){const t=e.toJSON();return(0,html_1.jsonToHTML)({json:t})},async saveAsHTML({filename:t}={}){const o=await e.toHTML(),n="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));(0,download_1.downloadFile)(n,t||"polotno.html")},async saveAsPDF(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},n))).save(o||"polotno.pdf")},async waitLoading(){await new Promise((e=>setTimeout(e,50))),await(0,loader_1.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,mobx_state_tree_1.getSnapshot)(e.fonts),pages:(0,mobx_state_tree_1.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi}),loadJSON(t,o=!1){var n;const a=Object.assign({},t),i=e.pages.indexOf(e.activePage);let s=null===(n=a.pages[i]||a.pages[0])||void 0===n?void 0:n.id;a._activePageId=s;const r=Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e));Object.assign(r,a),r.history=o?e.history.toJSON():{history:[],undoIdx:-1},(0,mobx_state_tree_1.applySnapshot)(e,r)},clear({keepHistory:t=!1}={}){const o=e.pages.map((e=>e.id));e.deletePages(o),t||e.history.clear()},addFont(t){e.removeFont(t.fontFamily),e.fonts.push(t),e.loadFont(t.fontFamily)},removeFont(t){e.fonts.filter((e=>e.fontFamily===t)).forEach((e=>(0,mobx_state_tree_1.destroy)(e)))},async loadFont(t){const o=e.fonts.find((e=>e.fontFamily===t))||fonts.globalFonts.find((e=>e.fontFamily===t));o?fonts.injectCustomFont(o):fonts.injectGoogleFont(t),await fonts.loadFont(t)}}))),exports.createStore=createStore,exports.default=createStore;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const store_1=require("./store");jest.useFakeTimers(),jest.mock("../utils/validate-key",(()=>({__esModule:!0,validateKey:()=>{},isKeyPaid:()=>!0}))),test("move elements up",(()=>{var e,t,o,i,l,d,a,n,c,v,s,r,g;const p=(0,store_1.createStore)();p.addPage(),null===(e=p.activePage)||void 0===e||e.addElement({type:"text",id:"1"}),null===(t=p.activePage)||void 0===t||t.addElement({type:"text",id:"2"}),null===(o=p.activePage)||void 0===o||o.addElement({type:"text",id:"3"}),null===(i=p.activePage)||void 0===i||i.addElement({type:"text",id:"4"}),expect(null===(l=p.activePage)||void 0===l?void 0:l.canMoveElementsUp(["2","4"])).toEqual(!0),null===(d=p.activePage)||void 0===d||d.moveElementsUp(["2","4"]),expect(null===(a=p.activePage)||void 0===a?void 0:a.children.map((e=>e.id))).toStrictEqual(["1","3","2","4"]),expect(null===(n=p.activePage)||void 0===n?void 0:n.canMoveElementsUp(["2","4"])).toEqual(!1),null===(c=p.activePage)||void 0===c||c.moveElementsUp(["2","4"]),expect(null===(v=p.activePage)||void 0===v?void 0:v.children.map((e=>e.id))).toStrictEqual(["1","3","2","4"]),null===(s=p.activePage)||void 0===s||s.moveElementsUp(["3","1"]),expect(null===(r=p.activePage)||void 0===r?void 0:r.children.map((e=>e.id))).toStrictEqual(["2","1","3","4"]),null===(g=p.activePage)||void 0===g||g.moveElementsUp(["5","1"])})),test("move elements top",(()=>{var e,t,o,i,l,d,a,n,c;const v=(0,store_1.createStore)();v.addPage(),null===(e=v.activePage)||void 0===e||e.addElement({type:"text",id:"1"}),null===(t=v.activePage)||void 0===t||t.addElement({type:"text",id:"2"}),null===(o=v.activePage)||void 0===o||o.addElement({type:"text",id:"3"}),null===(i=v.activePage)||void 0===i||i.addElement({type:"text",id:"4"}),expect(null===(l=v.activePage)||void 0===l?void 0:l.canMoveElementsTop(["2","4"])).toEqual(!0),null===(d=v.activePage)||void 0===d||d.moveElementsTop(["1","4"]),expect(null===(a=v.activePage)||void 0===a?void 0:a.children.map((e=>e.id))).toStrictEqual(["2","3","1","4"]),expect(null===(n=v.activePage)||void 0===n?void 0:n.canMoveElementsTop(["1","4"])).toEqual(!1),null===(c=v.activePage)||void 0===c||c.moveElementsTop(["5","1"])})),test("move elements down",(()=>{var e,t,o,i,l,d,a,n,c,v,s;const r=(0,store_1.createStore)();r.addPage(),null===(e=r.activePage)||void 0===e||e.addElement({type:"text",id:"1"}),null===(t=r.activePage)||void 0===t||t.addElement({type:"text",id:"2"}),null===(o=r.activePage)||void 0===o||o.addElement({type:"text",id:"3"}),null===(i=r.activePage)||void 0===i||i.addElement({type:"text",id:"4"}),expect(null===(l=r.activePage)||void 0===l?void 0:l.canMoveElementsDown(["1","2"])).toEqual(!1),expect(null===(d=r.activePage)||void 0===d?void 0:d.canMoveElementsDown(["4","2"])).toEqual(!0),null===(a=r.activePage)||void 0===a||a.moveElementsDown(["4","2"]),expect(null===(n=r.activePage)||void 0===n?void 0:n.children.map((e=>e.id))).toStrictEqual(["2","1","4","3"]),null===(c=r.activePage)||void 0===c||c.moveElementsDown(["2","4"]),expect(null===(v=r.activePage)||void 0===v?void 0:v.children.map((e=>e.id))).toStrictEqual(["2","4","1","3"]),null===(s=r.activePage)||void 0===s||s.moveElementsDown(["5","1"])})),test("locking API should continue to work",(()=>{const e=(0,store_1.createStore)();e.loadJSON({width:100,height:100,pages:[{id:"page1",children:[{id:"element1",type:"text",text:"hello",locked:!0}]}]});const t=e.getElementById("element1");expect(null==t?void 0:t.locked).toEqual(!0),expect(null==t?void 0:t.draggable).toEqual(!1),expect(null==t?void 0:t.contentEditable).toEqual(!1)})),test("loading from JSON should keep UI settings",(()=>{const e=(0,store_1.createStore)();e.addPage().addElement({type:"text"});const t=e.toJSON();e.setScale(.5),e.toggleRulers(),e.toggleBleed(),e.loadJSON(t),expect(e.scale).toEqual(.5),expect(e.rulesVisible).toBe(!0),expect(e.bleedVisible).toBe(!0)})),test("loading from JSON should keep old instances",(()=>{const e=(0,store_1.createStore)(),t=e.addPage().addElement({type:"text",id:"el"}),o=e.toJSON();e.loadJSON(o),expect(t).toEqual(e.getElementById("el"))})),test("loading from JSON should not keep history by default",(()=>{const e=(0,store_1.createStore)(),t=e.addPage().addElement({type:"text",id:"el"}),o=e.toJSON(),i=e.history;jest.runAllTimers(),t.set({text:"1"}),jest.runAllTimers(),expect(e.history.history.length).toBe(2),e.loadJSON(o),jest.runAllTimers(),expect(e.history===i).toBe(!0),expect(e.history.history.length).toBe(1)})),test("loading from JSON may keep history",(()=>{const e=(0,store_1.createStore)(),t=e.addPage().addElement({type:"text",id:"el"}),o=e.toJSON();jest.runAllTimers(),t.set({text:"1"}),jest.runAllTimers(),expect(e.history.history.length).toBe(2),e.loadJSON(o,!0),jest.runAllTimers(),expect(e.history.history.length).toBe(3)})),test("can group shapes",(()=>{var e,t,o;const i=(0,store_1.createStore)(),l=i.addPage(),d=l.addElement({type:"text",id:"el1"}),a=l.addElement({type:"text",id:"el2"});i.groupElements([d.id,a.id]),expect(null===(e=i.activePage)||void 0===e?void 0:e.children.length).toBe(1),expect(null===(t=i.activePage)||void 0===t?void 0:t.children[0].type).toBe("group"),expect(null===(o=i.activePage)||void 0===o?void 0:o.children[0].children.length).toBe(2)})),test("can ungroup shapes",(()=>{var e,t,o,i;const l=(0,store_1.createStore)(),d=l.addPage(),a=d.addElement({type:"text",id:"el1"}),n=d.addElement({type:"text",id:"el2"});l.groupElements([a.id,n.id]);const c=null===(e=l.activePage)||void 0===e?void 0:e.children[0];l.ungroupElements([c.id]),expect(null===(t=l.activePage)||void 0===t?void 0:t.children.length).toBe(2),expect(null===(o=l.activePage)||void 0===o?void 0:o.children[0].type).toBe("text"),expect(null===(i=l.activePage)||void 0===i?void 0:i.children[1].type).toBe("text")})),test("create nested group",(()=>{var e,t,o,i,l,d,a,n,c,v;const s=(0,store_1.createStore)(),r=s.addPage(),g=r.addElement({type:"text",id:"el1"}),p=r.addElement({type:"text",id:"el2"});s.groupElements([g.id,p.id]);const u=null===(e=s.activePage)||void 0===e?void 0:e.children[0],h=r.addElement({type:"text",id:"el3"});s.groupElements([u.id,h.id]),expect(null===(t=s.activePage)||void 0===t?void 0:t.children.length).toBe(1),expect(null===(o=s.activePage)||void 0===o?void 0:o.children[0].type).toBe("group"),expect(null===(i=s.activePage)||void 0===i?void 0:i.children[0].children.length).toBe(2),expect(null===(l=s.activePage)||void 0===l?void 0:l.children[0].children[0].type).toBe("group"),expect(null===(d=s.activePage)||void 0===d?void 0:d.children[0].children[1].type).toBe("text"),s.ungroupElements([null===(a=s.activePage)||void 0===a?void 0:a.children[0].id]),expect(null===(n=s.activePage)||void 0===n?void 0:n.children.length).toBe(2),expect(null===(c=s.activePage)||void 0===c?void 0:c.children[0].type).toBe("group"),expect(null===(v=s.activePage)||void 0===v?void 0:v.children[1].type).toBe("text")})),test("change global store size",(()=>{var e,t;const o=(0,store_1.createStore)();o.addPage(),o.setSize(100,100),expect(o.width).toBe(100),expect(o.height).toBe(100),expect(null===(e=o.activePage)||void 0===e?void 0:e.width).toBe("auto"),expect(null===(t=o.activePage)||void 0===t?void 0:t.height).toBe("auto")})),test("change one page size",(()=>{const e=(0,store_1.createStore)().addPage();e.setSize({width:100,height:100}),expect(e.width).toBe(100),expect(e.height).toBe(100)})),test("changing global should not change local",(()=>{const e=(0,store_1.createStore)(),t=e.addPage();t.setSize({width:100,height:100}),e.setSize(200,200),expect(t.width).toBe(100),expect(t.height).toBe(100)})),test("set size directly again should have effect",(()=>{const e=(0,store_1.createStore)(),t=e.addPage();t.setSize({width:100,height:100}),e.setSize(200,200),expect(t.width).toBe(100),expect(t.height).toBe(100),t.setSize({width:300,height:300}),expect(t.width).toBe(300),expect(t.height).toBe(300)}));
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const store_1=require("./store");jest.useFakeTimers(),jest.mock("../utils/validate-key",(()=>({__esModule:!0,validateKey:()=>{},isKeyPaid:()=>!0}))),test("move elements up",(()=>{var e,t,o,i,l,d,a,n,c,v,s,r,g;const p=(0,store_1.createStore)();p.addPage(),null===(e=p.activePage)||void 0===e||e.addElement({type:"text",id:"1"}),null===(t=p.activePage)||void 0===t||t.addElement({type:"text",id:"2"}),null===(o=p.activePage)||void 0===o||o.addElement({type:"text",id:"3"}),null===(i=p.activePage)||void 0===i||i.addElement({type:"text",id:"4"}),expect(null===(l=p.activePage)||void 0===l?void 0:l.canMoveElementsUp(["2","4"])).toEqual(!0),null===(d=p.activePage)||void 0===d||d.moveElementsUp(["2","4"]),expect(null===(a=p.activePage)||void 0===a?void 0:a.children.map((e=>e.id))).toStrictEqual(["1","3","2","4"]),expect(null===(n=p.activePage)||void 0===n?void 0:n.canMoveElementsUp(["2","4"])).toEqual(!1),null===(c=p.activePage)||void 0===c||c.moveElementsUp(["2","4"]),expect(null===(v=p.activePage)||void 0===v?void 0:v.children.map((e=>e.id))).toStrictEqual(["1","3","2","4"]),null===(s=p.activePage)||void 0===s||s.moveElementsUp(["3","1"]),expect(null===(r=p.activePage)||void 0===r?void 0:r.children.map((e=>e.id))).toStrictEqual(["2","1","3","4"]),null===(g=p.activePage)||void 0===g||g.moveElementsUp(["5","1"])})),test("move elements top",(()=>{var e,t,o,i,l,d,a,n,c;const v=(0,store_1.createStore)();v.addPage(),null===(e=v.activePage)||void 0===e||e.addElement({type:"text",id:"1"}),null===(t=v.activePage)||void 0===t||t.addElement({type:"text",id:"2"}),null===(o=v.activePage)||void 0===o||o.addElement({type:"text",id:"3"}),null===(i=v.activePage)||void 0===i||i.addElement({type:"text",id:"4"}),expect(null===(l=v.activePage)||void 0===l?void 0:l.canMoveElementsTop(["2","4"])).toEqual(!0),null===(d=v.activePage)||void 0===d||d.moveElementsTop(["1","4"]),expect(null===(a=v.activePage)||void 0===a?void 0:a.children.map((e=>e.id))).toStrictEqual(["2","3","1","4"]),expect(null===(n=v.activePage)||void 0===n?void 0:n.canMoveElementsTop(["1","4"])).toEqual(!1),null===(c=v.activePage)||void 0===c||c.moveElementsTop(["5","1"])})),test("move elements down",(()=>{var e,t,o,i,l,d,a,n,c,v,s;const r=(0,store_1.createStore)();r.addPage(),null===(e=r.activePage)||void 0===e||e.addElement({type:"text",id:"1"}),null===(t=r.activePage)||void 0===t||t.addElement({type:"text",id:"2"}),null===(o=r.activePage)||void 0===o||o.addElement({type:"text",id:"3"}),null===(i=r.activePage)||void 0===i||i.addElement({type:"text",id:"4"}),expect(null===(l=r.activePage)||void 0===l?void 0:l.canMoveElementsDown(["1","2"])).toEqual(!1),expect(null===(d=r.activePage)||void 0===d?void 0:d.canMoveElementsDown(["4","2"])).toEqual(!0),null===(a=r.activePage)||void 0===a||a.moveElementsDown(["4","2"]),expect(null===(n=r.activePage)||void 0===n?void 0:n.children.map((e=>e.id))).toStrictEqual(["2","1","4","3"]),null===(c=r.activePage)||void 0===c||c.moveElementsDown(["2","4"]),expect(null===(v=r.activePage)||void 0===v?void 0:v.children.map((e=>e.id))).toStrictEqual(["2","4","1","3"]),null===(s=r.activePage)||void 0===s||s.moveElementsDown(["5","1"])})),test("locking API should continue to work",(()=>{const e=(0,store_1.createStore)();e.loadJSON({width:100,height:100,pages:[{id:"page1",children:[{id:"element1",type:"text",text:"hello",locked:!0}]}]});const t=e.getElementById("element1");expect(null==t?void 0:t.locked).toEqual(!0),expect(null==t?void 0:t.draggable).toEqual(!1),expect(null==t?void 0:t.contentEditable).toEqual(!1)})),test("loading from JSON should keep UI settings",(()=>{const e=(0,store_1.createStore)();e.addPage().addElement({type:"text"});const t=e.toJSON();e.setScale(.5),e.toggleRulers(),e.toggleBleed(),e.loadJSON(t),expect(e.scale).toEqual(.5),expect(e.rulesVisible).toBe(!0),expect(e.bleedVisible).toBe(!0)})),test("loading from JSON should keep old instances",(()=>{const e=(0,store_1.createStore)(),t=e.addPage().addElement({type:"text",id:"el"}),o=e.toJSON();e.loadJSON(o),expect(t).toEqual(e.getElementById("el"))})),test("loading from JSON should not keep history by default",(()=>{const e=(0,store_1.createStore)(),t=e.addPage().addElement({type:"text",id:"el"}),o=e.toJSON(),i=e.history;jest.runAllTimers(),t.set({text:"1"}),jest.runAllTimers(),expect(e.history.history.length).toBe(2),e.loadJSON(o),jest.runAllTimers(),expect(e.history===i).toBe(!0),expect(e.history.history.length).toBe(1)})),test("loading from JSON may keep history",(()=>{const e=(0,store_1.createStore)(),t=e.addPage().addElement({type:"text",id:"el"}),o=e.toJSON();jest.runAllTimers(),t.set({text:"1"}),jest.runAllTimers(),expect(e.history.history.length).toBe(2),e.loadJSON(o,!0),jest.runAllTimers(),expect(e.history.history.length).toBe(3)})),test("can group shapes",(()=>{var e,t,o;const i=(0,store_1.createStore)(),l=i.addPage(),d=l.addElement({type:"text",id:"el1"}),a=l.addElement({type:"text",id:"el2"});i.groupElements([d.id,a.id]),expect(null===(e=i.activePage)||void 0===e?void 0:e.children.length).toBe(1),expect(null===(t=i.activePage)||void 0===t?void 0:t.children[0].type).toBe("group"),expect(null===(o=i.activePage)||void 0===o?void 0:o.children[0].children.length).toBe(2)})),test("can ungroup shapes",(()=>{var e,t,o,i;const l=(0,store_1.createStore)(),d=l.addPage(),a=d.addElement({type:"text",id:"el1"}),n=d.addElement({type:"text",id:"el2"});l.groupElements([a.id,n.id]);const c=null===(e=l.activePage)||void 0===e?void 0:e.children[0];l.ungroupElements([c.id]),expect(null===(t=l.activePage)||void 0===t?void 0:t.children.length).toBe(2),expect(null===(o=l.activePage)||void 0===o?void 0:o.children[0].type).toBe("text"),expect(null===(i=l.activePage)||void 0===i?void 0:i.children[1].type).toBe("text")})),test("create nested group",(()=>{var e,t,o,i,l,d,a,n,c,v;const s=(0,store_1.createStore)(),r=s.addPage(),g=r.addElement({type:"text",id:"el1"}),p=r.addElement({type:"text",id:"el2"});s.groupElements([g.id,p.id]);const u=null===(e=s.activePage)||void 0===e?void 0:e.children[0],h=r.addElement({type:"text",id:"el3"});s.groupElements([u.id,h.id]),expect(null===(t=s.activePage)||void 0===t?void 0:t.children.length).toBe(1),expect(null===(o=s.activePage)||void 0===o?void 0:o.children[0].type).toBe("group"),expect(null===(i=s.activePage)||void 0===i?void 0:i.children[0].children.length).toBe(2),expect(null===(l=s.activePage)||void 0===l?void 0:l.children[0].children[0].type).toBe("group"),expect(null===(d=s.activePage)||void 0===d?void 0:d.children[0].children[1].type).toBe("text"),s.ungroupElements([null===(a=s.activePage)||void 0===a?void 0:a.children[0].id]),expect(null===(n=s.activePage)||void 0===n?void 0:n.children.length).toBe(2),expect(null===(c=s.activePage)||void 0===c?void 0:c.children[0].type).toBe("group"),expect(null===(v=s.activePage)||void 0===v?void 0:v.children[1].type).toBe("text")})),test("change global store size",(()=>{var e,t;const o=(0,store_1.createStore)();o.addPage(),o.setSize(100,100),expect(o.width).toBe(100),expect(o.height).toBe(100),expect(null===(e=o.activePage)||void 0===e?void 0:e.width).toBe("auto"),expect(null===(t=o.activePage)||void 0===t?void 0:t.height).toBe("auto")})),test("change one page size",(()=>{const e=(0,store_1.createStore)().addPage();e.setSize({width:100,height:100}),expect(e.width).toBe(100),expect(e.height).toBe(100)})),test("changing global should not change local",(()=>{const e=(0,store_1.createStore)(),t=e.addPage();t.setSize({width:100,height:100}),e.setSize(200,200),expect(t.width).toBe(100),expect(t.height).toBe(100)})),test("set size directly again should have effect",(()=>{const e=(0,store_1.createStore)(),t=e.addPage();t.setSize({width:100,height:100}),e.setSize(200,200),expect(t.width).toBe(100),expect(t.height).toBe(100),t.setSize({width:300,height:300}),expect(t.width).toBe(300),expect(t.height).toBe(300)})),test("reset store",(()=>{const e=(0,store_1.createStore)();e.addPage().setSize({width:100,height:100}),e.addPage().addElement({type:"text"}),e.clear(),expect(e.pages.length).toBe(0),expect(e.history.canRedo).toBe(!1),expect(e.history.canUndo).toBe(!1)}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "1.11.1",
3
+ "version": "1.12.0",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
package/polotno-app.d.ts CHANGED
@@ -528,6 +528,9 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
528
528
  dpi: number;
529
529
  };
530
530
  loadJSON(json: any, keepHistory?: boolean): void;
531
+ clear({ keepHistory }?: {
532
+ keepHistory?: boolean | undefined;
533
+ }): void;
531
534
  addFont(font: import("./utils/fonts").FONT): void;
532
535
  removeFont(fontFamily: string): void;
533
536
  loadFont(fontFamily: any): Promise<void>;
@@ -976,6 +979,9 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
976
979
  dpi: number;
977
980
  };
978
981
  loadJSON(json: any, keepHistory?: boolean): void;
982
+ clear({ keepHistory }?: {
983
+ keepHistory?: boolean | undefined;
984
+ }): void;
979
985
  addFont(font: import("./utils/fonts").FONT): void;
980
986
  removeFont(fontFamily: string): void;
981
987
  loadFont(fontFamily: any): Promise<void>;