polotno 0.39.13 → 0.40.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.
@@ -1 +1 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextElement=exports.useFontLoader=void 0;const react_1=__importDefault(require("react")),mobx_react_lite_1=require("mobx-react-lite"),react_konva_1=require("react-konva"),react_konva_utils_1=require("react-konva-utils"),mobx_1=require("mobx"),konva_1=__importDefault(require("konva")),loader_1=require("../utils/loader"),fonts_1=require("../utils/fonts"),flags_1=require("../utils/flags"),apply_filters_1=require("./apply-filters"),use_fadein_1=require("./use-fadein"),highlighter_1=require("./highlighter"),styleNode=document.createElement("style");styleNode.type="text/css",document.head.appendChild(styleNode);const initialStyles={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"normal",userSelect:"text",wordBreak:"normal"},TextInput=(0,mobx_react_lite_1.observer)((({textNodeRef:e,element:t,onBlur:r,selectAll:n,cursorPosition:o})=>{const[a,i]=react_1.default.useState(initialStyles),l=e.current;react_1.default.useLayoutEffect((()=>{const e={};e.width=l.width()-2*l.padding()+"px",e.height=l.height()-2*l.padding()+10+"px",e.fontSize=l.fontSize()+"px",e.lineHeight=l.lineHeight()+.01,e.fontFamily='"'+l.fontFamily()+'"',e.textAlign=l.align(),e.color=l.fill(),e.fontWeight=t.fontWeight,e.fontStyle=t.fontStyle;const r=`\n .polotno-input::placeholder {\n color: ${a.color};\n opacity: 0.6;\n }\n `;styleNode.innerHTML="",styleNode.appendChild(document.createTextNode(r)),JSON.stringify(e)!==JSON.stringify(a)&&i(e)}));const s=react_1.default.useRef(null);return react_1.default.useEffect((()=>{var e;const t=s.current;if(!t)return;null===(e=s.current)||void 0===e||e.focus();const r=o||t.value.length;t.selectionStart=t.selectionEnd=r,n&&(null==t||t.select(),document.execCommand("selectAll",!1,null))}),[]),react_1.default.createElement(react_konva_utils_1.Html,null,react_1.default.createElement("textarea",{className:"polotno-input",ref:s,style:Object.assign(Object.assign({},initialStyles),a),value:t.text,onChange:e=>{t.set({text:e.target.value})},placeholder:t.placeholder,onBlur:r}))})),useEditor=e=>{const[t,r]=react_1.default.useState(!1),n=react_1.default.useRef(!1);return react_1.default.useEffect((()=>{var t=!0;return setTimeout((()=>{t&&(e._editModeEnabled&&(n.current=!0),r(!0),setTimeout((()=>{n.current=!1}),50))}),50),()=>{t=!1}}),[]),{editorEnabled:t&&e._editModeEnabled,selectAll:n.current}},useFontLoader=(e,t)=>{const[r,n]=react_1.default.useState((0,fonts_1.isFontLoaded)(t));return react_1.default.useLayoutEffect((()=>{if((0,fonts_1.isFontLoaded)(t))return void n(!0);let o=!0;return(async()=>{r&&n(!1);const a=(0,loader_1.incrementLoader)(`text ${t}`);await e.loadFont(t),konva_1.default.Util.requestAnimFrame(a),o&&n(!0)})(),()=>{o=!1}}),[t]),[r]};exports.useFontLoader=useFontLoader;const getLineHeight=({fontLoaded:e,fontFamily:t,fontSize:r,lineHeight:n})=>react_1.default.useMemo((()=>{if("number"==typeof n)return n;const e=document.createElement("div");e.style.fontFamily=t,e.style.fontSize=r+"px",e.style.lineHeight=n,e.innerText="Test text",document.body.appendChild(e);const o=e.offsetHeight;return document.body.removeChild(e),o/r}),[e,t,r,n]);function getRelativePointerPosition(e){var t=e.getAbsoluteTransform().copy();t.invert();var r=e.getStage().getPointerPosition();return t.point(r)}function getCursorPosition(e){var t;const r=e.target,n=getRelativePointerPosition(r),o=r.textArr,a=Math.floor(n.y/(r.fontSize()*r.lineHeight())),i=o.slice(0,a).reduce(((e,t)=>e+t.text.length),a),l=null!==(t=o[a])&&void 0!==t?t:o[0];let s=0;"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2);return i+Math.round((n.x-s)/l.width*l.text.length)}exports.TextElement=(0,mobx_react_lite_1.observer)((({element:e,store:t})=>{const r=react_1.default.useRef(null),{editorEnabled:n,selectAll:o}=useEditor(e),[a,i]=react_1.default.useState(!1),[l,s]=react_1.default.useState(!1),d=t.selectedElements.indexOf(e)>=0;react_1.default.useEffect((()=>{if(e.width)return;const t=r.current;t.width(600),e.set({width:1.4*t.getTextWidth()})}),[]),react_1.default.useLayoutEffect((()=>(0,mobx_1.autorun)((()=>{const t=r.current;(0,apply_filters_1.applyFilter)(t,e)}))));const[u]=(0,exports.useFontLoader)(t,e.fontFamily),c=react_1.default.useRef(null);react_1.default.useEffect((()=>{if(!u)return;const t=r.current,n=e.height&&t.height()>e.height,{forceTextFitEnabled:o}=flags_1.flags;n&&o&&!l?(c.current||(c.current=(0,loader_1.incrementLoader)()),e.set({fontSize:e.fontSize-.1})):o&&c.current?c.current():e.height!==t.height()&&e.set({height:t.height()})})),react_1.default.useLayoutEffect((()=>{const t=r.current;t&&(t.width(t.width()+1e-8),t._setTextData(),(0,apply_filters_1.applyFilter)(t,e))}),[u]);const f=react_1.default.useRef(null),g=react_1.default.useRef(0),h=r=>{t.selectedElements.find((t=>t===e))&&!e.locked&&(g.current=getCursorPosition(r),e.toggleEditMode())},_=!e.text&&e.placeholder,m=e._editModeEnabled?0:_?.6:e.opacity;(0,use_fadein_1.useFadeIn)(r,m);const p=getLineHeight({fontLoaded:u,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),y=e.selectable||"admin"===t.role;return react_1.default.createElement(react_1.default.Fragment,null,react_1.default.createElement(react_konva_1.Text,{ref:r,id:e.id,name:"element",hideOnExport:!e.showInExport,x:e.x,y:e.y,rotation:e.rotation,width:e.width,text:e.text||e.placeholder,fill:e.fill,stroke:e.stroke,strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.fontSize,fontFamily:e.fontFamily,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,draggable:!e.locked,opacity:m,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,lineHeight:p,letterSpacing:e.letterSpacing*e.fontSize,listening:y,onDragStart:()=>{t.history.startTransaction()},onDragMove:t=>{setTimeout((()=>{e.set({x:t.target.x(),y:t.target.y()})}))},onDragEnd:r=>{e.set({x:r.target.x(),y:r.target.y()}),t.history.endTransaction()},onMouseEnter:()=>{i(!0)},onMouseLeave:()=>{i(!1)},onClick:h,onTap:h,onTransformStart:()=>{s(!0),t.history.startTransaction()},onTransform:t=>{var r;const n=(null===(r=t.target.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===n||"middle-right"===n){const r=t.target.scaleX(),n=t.target.width()*r,o=e.fontSize;let a=n;n<o&&(a=o,f.current&&t.target.position(f.current)),t.target.width(a),t.target.scaleX(1),e.set({x:t.target.x(),y:t.target.y(),width:t.target.width(),rotation:t.target.rotation()}),(0,apply_filters_1.applyFilter)(t.target,e)}t.target.strokeWidth(e.strokeWidth/t.target.scaleX()),f.current=t.target.position()},onTransformEnd:r=>{s(!1);const n=r.target.scaleX();r.target.scaleX(1),r.target.scaleY(1),r.target.strokeWidth(e.strokeWidth),e.set({fontSize:Math.round(e.fontSize*n),width:Math.ceil(r.target.width()*n),x:r.target.x(),y:r.target.y(),rotation:r.target.rotation()}),t.history.endTransaction()}}),n&&react_1.default.createElement(react_konva_1.Group,{x:e.x,y:e.y,rotation:e.rotation},react_1.default.createElement(TextInput,{textNodeRef:r,element:e,selectAll:o,cursorPosition:g.current,onBlur:()=>{e.toggleEditMode(!1)}})),!l&&(a||d)&&react_1.default.createElement(highlighter_1.Highlighter,{element:e}))}));
1
+ "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextElement=exports.useFontLoader=void 0;const react_1=__importDefault(require("react")),mobx_react_lite_1=require("mobx-react-lite"),react_konva_1=require("react-konva"),react_konva_utils_1=require("react-konva-utils"),mobx_1=require("mobx"),konva_1=__importDefault(require("konva")),loader_1=require("../utils/loader"),fonts_1=require("../utils/fonts"),flags_1=require("../utils/flags"),apply_filters_1=require("./apply-filters"),use_fadein_1=require("./use-fadein"),highlighter_1=require("./highlighter"),styleNode=document.createElement("style");styleNode.type="text/css",document.head.appendChild(styleNode);const initialStyles={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"normal",userSelect:"text",wordBreak:"normal"},TextInput=(0,mobx_react_lite_1.observer)((({textNodeRef:e,element:t,onBlur:r,selectAll:n,cursorPosition:o})=>{const[a,i]=react_1.default.useState(initialStyles),l=e.current;react_1.default.useLayoutEffect((()=>{const e={};e.width=l.width()-2*l.padding()+"px",e.height=l.height()-2*l.padding()+10+"px",e.fontSize=l.fontSize()+"px",e.lineHeight=l.lineHeight()+.01,e.fontFamily='"'+l.fontFamily()+'"',e.textAlign=l.align(),e.color=l.fill(),e.fontWeight=t.fontWeight,e.fontStyle=t.fontStyle;const r=`\n .polotno-input::placeholder {\n color: ${a.color};\n opacity: 0.6;\n }\n `;styleNode.innerHTML="",styleNode.appendChild(document.createTextNode(r)),JSON.stringify(e)!==JSON.stringify(a)&&i(e)}));const s=react_1.default.useRef(null);return react_1.default.useEffect((()=>{var e;const t=s.current;if(!t)return;null===(e=s.current)||void 0===e||e.focus();const r=o||t.value.length;t.selectionStart=t.selectionEnd=r,n&&(null==t||t.select(),document.execCommand("selectAll",!1,null))}),[]),react_1.default.createElement(react_konva_utils_1.Html,null,react_1.default.createElement("textarea",{className:"polotno-input",ref:s,style:Object.assign(Object.assign({},initialStyles),a),value:t.text,onChange:e=>{t.set({text:e.target.value})},placeholder:t.placeholder,onBlur:r}))})),useEditor=e=>{const[t,r]=react_1.default.useState(!1),n=react_1.default.useRef(!1);return react_1.default.useEffect((()=>{var t=!0;return setTimeout((()=>{t&&(e._editModeEnabled&&(n.current=!0),r(!0),setTimeout((()=>{n.current=!1}),50))}),50),()=>{t=!1}}),[]),{editorEnabled:t&&e._editModeEnabled,selectAll:n.current}},useFontLoader=(e,t)=>{const[r,n]=react_1.default.useState((0,fonts_1.isFontLoaded)(t));return react_1.default.useLayoutEffect((()=>{if((0,fonts_1.isFontLoaded)(t))return void n(!0);let o=!0;return(async()=>{r&&n(!1);const a=(0,loader_1.incrementLoader)(`text ${t}`);await e.loadFont(t),konva_1.default.Util.requestAnimFrame(a),o&&n(!0)})(),()=>{o=!1}}),[t]),[r]};exports.useFontLoader=useFontLoader;const getLineHeight=({fontLoaded:e,fontFamily:t,fontSize:r,lineHeight:n})=>react_1.default.useMemo((()=>{if("number"==typeof n)return n;const e=document.createElement("div");e.style.fontFamily=t,e.style.fontSize=r+"px",e.style.lineHeight=n,e.innerText="Test text",document.body.appendChild(e);const o=e.offsetHeight;return document.body.removeChild(e),o/r}),[e,t,r,n]);function getRelativePointerPosition(e){var t=e.getAbsoluteTransform().copy();t.invert();var r=e.getStage().getPointerPosition();return t.point(r)}function getCursorPosition(e){var t;const r=e.target,n=getRelativePointerPosition(r),o=r.textArr,a=Math.floor(n.y/(r.fontSize()*r.lineHeight())),i=o.slice(0,a).reduce(((e,t)=>e+t.text.length),a),l=null!==(t=o[a])&&void 0!==t?t:o[0];let s=0;"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2);return i+Math.round((n.x-s)/l.width*l.text.length)}exports.TextElement=(0,mobx_react_lite_1.observer)((({element:e,store:t})=>{const r=react_1.default.useRef(null),{editorEnabled:n,selectAll:o}=useEditor(e),[a,i]=react_1.default.useState(!1),[l,s]=react_1.default.useState(!1),d=t.selectedElements.indexOf(e)>=0;react_1.default.useEffect((()=>{if(e.width)return;const t=r.current;t.width(600),e.set({width:1.4*t.getTextWidth()})}),[]),react_1.default.useLayoutEffect((()=>(0,mobx_1.autorun)((()=>{const t=r.current;(0,apply_filters_1.applyFilter)(t,e)}))));const[u]=(0,exports.useFontLoader)(t,e.fontFamily),c=react_1.default.useRef(null);react_1.default.useEffect((()=>{if(!u)return;const t=r.current,n=e.height&&t.height()>e.height,{forceTextFitEnabled:o}=flags_1.flags;n&&o&&!l?(c.current||(c.current=(0,loader_1.incrementLoader)()),e.set({fontSize:e.fontSize-.1})):o&&c.current?(c.current(),c.current=null):e.height!==t.height()&&e.set({height:t.height()})})),react_1.default.useLayoutEffect((()=>{const t=r.current;t&&(t.width(t.width()+1e-8),t._setTextData(),(0,apply_filters_1.applyFilter)(t,e))}),[u]);const f=react_1.default.useRef(null),g=react_1.default.useRef(0),h=r=>{t.selectedElements.find((t=>t===e))&&!e.locked&&(g.current=getCursorPosition(r),e.toggleEditMode())},_=!e.text&&e.placeholder,m=e._editModeEnabled?0:_?.6:e.opacity;(0,use_fadein_1.useFadeIn)(r,m);const p=getLineHeight({fontLoaded:u,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),y=e.selectable||"admin"===t.role;return react_1.default.createElement(react_1.default.Fragment,null,react_1.default.createElement(react_konva_1.Text,{ref:r,id:e.id,name:"element",hideOnExport:!e.showInExport,x:e.x,y:e.y,rotation:e.rotation,width:e.width,text:e.text||e.placeholder,fill:e.fill,stroke:e.stroke,strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.fontSize,fontFamily:e.fontFamily,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,draggable:!e.locked,opacity:m,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,lineHeight:p,letterSpacing:e.letterSpacing*e.fontSize,listening:y,onDragStart:()=>{t.history.startTransaction()},onDragMove:t=>{setTimeout((()=>{e.set({x:t.target.x(),y:t.target.y()})}))},onDragEnd:r=>{e.set({x:r.target.x(),y:r.target.y()}),t.history.endTransaction()},onMouseEnter:()=>{i(!0)},onMouseLeave:()=>{i(!1)},onClick:h,onTap:h,onTransformStart:()=>{s(!0),t.history.startTransaction()},onTransform:t=>{var r;const n=(null===(r=t.target.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===n||"middle-right"===n){const r=t.target.scaleX(),n=t.target.width()*r,o=e.fontSize;let a=n;n<o&&(a=o,f.current&&t.target.position(f.current)),t.target.width(a),t.target.scaleX(1),e.set({x:t.target.x(),y:t.target.y(),width:t.target.width(),rotation:t.target.rotation()}),(0,apply_filters_1.applyFilter)(t.target,e)}t.target.strokeWidth(e.strokeWidth/t.target.scaleX()),f.current=t.target.position()},onTransformEnd:r=>{s(!1);const n=r.target.scaleX();r.target.scaleX(1),r.target.scaleY(1),r.target.strokeWidth(e.strokeWidth),e.set({fontSize:Math.round(e.fontSize*n),width:Math.ceil(r.target.width()*n),x:r.target.x(),y:r.target.y(),rotation:r.target.rotation()}),t.history.endTransaction()}}),n&&react_1.default.createElement(react_konva_1.Group,{x:e.x,y:e.y,rotation:e.rotation},react_1.default.createElement(TextInput,{textNodeRef:r,element:e,selectAll:o,cursorPosition:g.current,onBlur:()=>{e.toggleEditMode(!1)}})),!l&&(a||d)&&react_1.default.createElement(highlighter_1.Highlighter,{element:e}))}));
package/model/store.d.ts CHANGED
@@ -672,6 +672,12 @@ interface ExportOptions {
672
672
  mimeType?: 'image/png' | 'image/jpeg';
673
673
  quality?: number;
674
674
  }
675
+ interface PDFExportOptions extends ExportOptions {
676
+ dpi?: number;
677
+ parallel?: number;
678
+ unit?: 'pt' | 'mm' | 'cm' | 'in';
679
+ pixelUnitRatio?: number;
680
+ }
675
681
  export declare const Store: import("mobx-state-tree").IModelType<{
676
682
  role: import("mobx-state-tree").IType<string | undefined, string, string>;
677
683
  pages: import("mobx-state-tree").IArrayType<import("mobx-state-tree").IModelType<{
@@ -1180,8 +1186,8 @@ export declare const Store: import("mobx-state-tree").IModelType<{
1180
1186
  saveAsImage({ fileName, ...exportProps }?: ExportOptions & {
1181
1187
  fileName?: string | undefined;
1182
1188
  }): Promise<void>;
1183
- _toPDF(exportProps: any): Promise<any>;
1184
- toPDFDataURL(exportProps: any): Promise<any>;
1189
+ _toPDF(exportProps: PDFExportOptions): Promise<any>;
1190
+ toPDFDataURL(exportProps: ExportOptions): Promise<any>;
1185
1191
  saveAsPDF({ fileName, ...exportProps }?: ExportOptions & {
1186
1192
  fileName?: string | undefined;
1187
1193
  dpi?: number | undefined;
package/model/store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,s){void 0===s&&(s=o),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[o]}})}:function(e,t,o,s){void 0===s&&(s=o),e[s]=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 s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(o[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(o[s[n]]=e[s[n]])}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.registerShapeModel=exports.SVGElement=exports.ImageElement=exports.TextElement=exports.Element=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"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),svg_1=require("../utils/svg"),loader_1=require("../utils/loader");(0,mobx_state_tree_1.setLivelinessChecking)("ignore"),exports.Element=mobx_state_tree_1.types.model("Element",{id:mobx_state_tree_1.types.identifier,type:"none",x:0,y:0,rotation:0,opacity:1,visible:!0,locked:!1,blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",custom:mobx_state_tree_1.types.frozen(),selectable:!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),t})).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var s in t)"_"!==s[0]&&(o[s]=e[s]);return o})).views((e=>({get page(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Page)},get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)}}))).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),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.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:14,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}).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,_cropModeEnabled:!1}).actions((e=>({toggleCropMode(t){e._cropModeEnabled=null!=t?t:!e._cropModeEnabled,e._cropModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.SVGElement=exports.Element.named("SVG").props({type:"svg",src:"",maskSrc:"",__svgString:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize: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}))).views((e=>({get colors(){return e.__svgString?(0,svg_1.getColors)(e.__svgString):[]},get __finalSrc(){return e.__svgString?(0,svg_1.replaceColors)(e.__svgString,e.colorsReplace):this.src},get __isLoaded(){if(!e.__svgString)return!1;return!(Array.from(e.colorsReplace.keys()).length>0)||e.__finalSrc!==e.src}}))).actions((e=>{let t=()=>{};return{async _loadSVG(){if(!e.src)return;const t=await(0,svg_1.urlToString)(e.src);(0,mobx_state_tree_1.isAlive)(e)&&(0,mobx_state_tree_1.hasParent)(e)&&e.store.history.ignore((()=>{e.set({__svgString:(0,svg_1.fixSize)(t)})}))},async afterCreate(){e._loadSVG();let o=e.src;t=(0,mobx_state_tree_1.onSnapshot)(e,(t=>{t.src===o&&e.__svgString||(e._loadSVG(),o=e.src)}))},beforeDestroy(){t()},replaceColor(t,o){e.colorsReplace.set(t,o)}}}));const TYPES_MAP={svg:exports.SVGElement,text:exports.TextElement,image:exports.ImageElement},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,...additionalTypesUnion);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(),_exporting:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var s in t)"_"!==s[0]&&(o[s]=e[s]);return o})).views((e=>({get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)}}))).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 s=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));s.sort(((e,t)=>t.index-e.index));for(const{index:n}of s){if(-1==n)continue;const s=n<e.children.length-1&&e.children[n+1],a=t.indexOf(null==s?void 0:s.id)>=0;n===e.children.length-1||a||o(n)}},_forEachElementDown(t,o){const s=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));s.sort(((e,t)=>e.index-t.index));for(const{index:n}of s){if(-1==n)continue;const s=n>0&&e.children[n-1],a=t.indexOf(null==s?void 0:s.id)>=0;0===n||a||o(n)}return!1}}))).actions((e=>({clone(t){const o=e.toJSON();o.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10)}));const s=Object.assign(Object.assign(Object.assign({},o),{id:(0,nanoid_1.nanoid)(10)}),t),n=e.store.addPage(s),a=e.store.pages.indexOf(e);n.setZIndex(a+1),n.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);const s=o.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.children.push(s),s.selectable&&e.store.selectElements([s.id]),s},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=[],s=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):s.push(e)})),e.children.replace(s.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=[],s=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):s.push(e)})),e.children.replace(o.concat(s))}}))).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,scale:1,scaleToFit:1,_bleedVisible:!1,openedSidePanel:"",selectedElementsIds: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 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 activePage(){return e.pages.slice().find((t=>t.id===e._activePageId))||(e.pages.length?e.pages[0]:null)}}))).actions((e=>({setRole(t){e.role=t},getElementById(t){for(const o of e.pages)for(const e of o.children)if(e.id===t)return e},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){e.selectedElementsIds=(0,mobx_state_tree_1.cast)(t)},_toggleBleed(t){e._bleedVisible=null!=t?t:!e._bleedVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,o,s){if(s){const s=t/e.width,n=o/e.height;for(const t of e.pages)for(const e of t.children)e.set({x:e.x*s,y:e.y*n}),"text"===e.type?e.set({fontSize:e.fontSize*s,width:Math.max(e.width*s,2)}):"image"===e.type?e.set({width:e.width*s,height:e.height*n}):"svg"===e.type&&e.set({width:Math.max(e.width*s,2),height:Math.max(e.height*s,2)})}e.width=t,e.height=o},setPageZIndex(t,o){const s=e.pages.find((e=>e.id===t));s&&((0,mobx_state_tree_1.detach)(s),e.pages.remove(s),e.pages.splice(o,0,s))},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 s=Math.min(e.pages.length-1,o),n=e.pages[s];n&&(e._activePageId=n.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},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)([])},on(t,o){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(s=>{const n=e.toJSON();JSON.stringify(n)!==JSON.stringify(t)&&(t=n,o(n))}))}},async toDataURL({pixelRatio:t,ignoreBackground:o,pageId:s,mimeType:n,includeBleed:a,quality:r}={}){var i;const l=t||1;s=s||(null===(i=e.pages[0])||void 0===i?void 0:i.id);const d=e.pages.find((e=>e.id===s));if(!d)throw new Error(`No page for export with id ${s}`);null==d||d.set({_exporting:!0}),await new Promise((e=>{setTimeout(e,0)})),await e.waitLoading();const c=konva_1.default.stages.find((e=>e.getAttr("pageId")===s));if(!c)throw new Error(`Export is failed. Can not find stage for page ${s}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);const p=c.findOne(".page-container");c.find("Transformer").forEach((e=>e.visible(!1))),p.findOne(".page-background").shadowEnabled(!1),p.findOne(".page-background").strokeEnabled(!1),p.find(".highlighter").forEach((e=>e.visible(!1)));const _=p.findOne(".page-background-group"),m=_.clip();_.clip({x:null,y:null,width:null,height:null});const g=p.find((e=>e.getAttr("hideInExport")));g.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()})),o&&p.findOne(".page-background").hide();const h=a?d.bleed:0;let f=h;e._bleedVisible&&a?f=0:e._bleedVisible&&!a&&(f=-d.bleed);const u=p.toDataURL({x:p.x()-f*p.scaleX(),y:p.y()-f*p.scaleY(),width:(d.computedWidth+2*h)*p.scaleX(),height:(d.computedHeight+2*h)*p.scaleY(),pixelRatio:1/p.scaleX()*l,mimeType:n,quality:r});return o&&p.findOne(".page-background").show(),g.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),p.findOne(".page-background").shadowEnabled(!0),p.findOne(".page-background").strokeEnabled(!0),c.find("Transformer").forEach((e=>e.visible(!0))),p.find(".highlighter").forEach((e=>e.visible(!0))),_.clip(m),null==d||d.set({_exporting:!1}),u},async saveAsImage(t={}){var{fileName:o}=t,s=__rest(t,["fileName"]);const n=s.mimeType||"image/png",a=n.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(s),o||"polotno."+a,n)},async _toPDF(t){const o=t.dpi||300,s=t.parallel||1,n=await(0,pdf_1.getJsPDF)(),a=e=>.75*e;var r=new n({unit:"pt",orientation:e.width>e.height?"landscape":"portrait",format:[a(e.width),a(e.height)],compress:!0});r.deletePage(1);const i=e._elementsPixelRatio,l=o/72;e.setElementsPixelRatio(l),await new Promise((e=>setTimeout(e)));const d=((e,t)=>{for(var o=[],s=0;s<e.length;s+=t)o.push(e.slice(s,s+t));return o})(e.pages,s);for(const o of d){const s=o.map((async o=>{const s=t.includeBleed?o.bleed:0,n=a(o.computedWidth+s),r=a(o.computedHeight+s);let i=0,d=l;for(;i<10;){i+=1,2===i&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const s=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:o.id,pixelRatio:d}));if(s.length>20)return{url:s,width:n,height:r};d*=.8}}));(await Promise.all(s)).forEach((({url:e,width:t,height:o})=>{r.addPage([t,o],t>o?"landscape":"portrait"),r.addImage(e,0,0,t,o,void 0,"FAST")}))}return e.setElementsPixelRatio(i),r},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async saveAsPDF(t={}){var{fileName:o}=t,s=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},s))).save(o||"polotno.pdf")},async waitLoading(){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)}),loadJSON(t,o=!1){var s;const n=Object.assign({},t);e.pages.forEach((e=>e.children.forEach((e=>(0,mobx_state_tree_1.detach)(e)))));const a=e.pages.indexOf(e.activePage);let r=null===(s=n.pages[a]||n.pages[0])||void 0===s?void 0:s.id;e.pages=(0,mobx_state_tree_1.cast)([]),n._activePageId=r,n.scale=e.scale,n.openedSidePanel=e.openedSidePanel,n._bleedVisible=e._bleedVisible,o&&(n.history=e.history.toJSON()),(0,mobx_state_tree_1.applySnapshot)(e,n)},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,s){void 0===s&&(s=o),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[o]}})}:function(e,t,o,s){void 0===s&&(s=o),e[s]=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 s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(o[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(o[s[n]]=e[s[n]])}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.registerShapeModel=exports.SVGElement=exports.ImageElement=exports.TextElement=exports.Element=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"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),svg_1=require("../utils/svg"),loader_1=require("../utils/loader");(0,mobx_state_tree_1.setLivelinessChecking)("ignore"),exports.Element=mobx_state_tree_1.types.model("Element",{id:mobx_state_tree_1.types.identifier,type:"none",x:0,y:0,rotation:0,opacity:1,visible:!0,locked:!1,blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",custom:mobx_state_tree_1.types.frozen(),selectable:!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),t})).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var s in t)"_"!==s[0]&&(o[s]=e[s]);return o})).views((e=>({get page(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Page)},get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)}}))).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),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.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:14,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}).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,_cropModeEnabled:!1}).actions((e=>({toggleCropMode(t){e._cropModeEnabled=null!=t?t:!e._cropModeEnabled,e._cropModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.SVGElement=exports.Element.named("SVG").props({type:"svg",src:"",maskSrc:"",__svgString:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize: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}))).views((e=>({get colors(){return e.__svgString?(0,svg_1.getColors)(e.__svgString):[]},get __finalSrc(){return e.__svgString?(0,svg_1.replaceColors)(e.__svgString,e.colorsReplace):this.src},get __isLoaded(){if(!e.__svgString)return!1;return!(Array.from(e.colorsReplace.keys()).length>0)||e.__finalSrc!==e.src}}))).actions((e=>{let t=()=>{};return{async _loadSVG(){if(!e.src)return;const t=await(0,svg_1.urlToString)(e.src);(0,mobx_state_tree_1.isAlive)(e)&&(0,mobx_state_tree_1.hasParent)(e)&&e.store.history.ignore((()=>{e.set({__svgString:(0,svg_1.fixSize)(t)})}))},async afterCreate(){e._loadSVG();let o=e.src;t=(0,mobx_state_tree_1.onSnapshot)(e,(t=>{t.src===o&&e.__svgString||(e._loadSVG(),o=e.src)}))},beforeDestroy(){t()},replaceColor(t,o){e.colorsReplace.set(t,o)}}}));const TYPES_MAP={svg:exports.SVGElement,text:exports.TextElement,image:exports.ImageElement},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,...additionalTypesUnion);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(),_exporting:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var s in t)"_"!==s[0]&&(o[s]=e[s]);return o})).views((e=>({get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)}}))).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 s=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));s.sort(((e,t)=>t.index-e.index));for(const{index:n}of s){if(-1==n)continue;const s=n<e.children.length-1&&e.children[n+1],a=t.indexOf(null==s?void 0:s.id)>=0;n===e.children.length-1||a||o(n)}},_forEachElementDown(t,o){const s=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));s.sort(((e,t)=>e.index-t.index));for(const{index:n}of s){if(-1==n)continue;const s=n>0&&e.children[n-1],a=t.indexOf(null==s?void 0:s.id)>=0;0===n||a||o(n)}return!1}}))).actions((e=>({clone(t){const o=e.toJSON();o.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10)}));const s=Object.assign(Object.assign(Object.assign({},o),{id:(0,nanoid_1.nanoid)(10)}),t),n=e.store.addPage(s),a=e.store.pages.indexOf(e);n.setZIndex(a+1),n.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);const s=o.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.children.push(s),s.selectable&&e.store.selectElements([s.id]),s},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=[],s=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):s.push(e)})),e.children.replace(s.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=[],s=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):s.push(e)})),e.children.replace(o.concat(s))}}))).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,scale:1,scaleToFit:1,_bleedVisible:!1,openedSidePanel:"",selectedElementsIds: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 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 activePage(){return e.pages.slice().find((t=>t.id===e._activePageId))||(e.pages.length?e.pages[0]:null)}}))).actions((e=>({setRole(t){e.role=t},getElementById(t){for(const o of e.pages)for(const e of o.children)if(e.id===t)return e},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){e.selectedElementsIds=(0,mobx_state_tree_1.cast)(t)},_toggleBleed(t){e._bleedVisible=null!=t?t:!e._bleedVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,o,s){if(s){const s=t/e.width,n=o/e.height;for(const t of e.pages)for(const e of t.children)e.set({x:e.x*s,y:e.y*n}),"text"===e.type?e.set({fontSize:e.fontSize*s,width:Math.max(e.width*s,2)}):"image"===e.type?e.set({width:e.width*s,height:e.height*n}):"svg"===e.type&&e.set({width:Math.max(e.width*s,2),height:Math.max(e.height*s,2)})}e.width=t,e.height=o},setPageZIndex(t,o){const s=e.pages.find((e=>e.id===t));s&&((0,mobx_state_tree_1.detach)(s),e.pages.remove(s),e.pages.splice(o,0,s))},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 s=Math.min(e.pages.length-1,o),n=e.pages[s];n&&(e._activePageId=n.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},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)([])},on(t,o){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(s=>{const n=e.toJSON();JSON.stringify(n)!==JSON.stringify(t)&&(t=n,o(n))}))}},async toDataURL({pixelRatio:t,ignoreBackground:o,pageId:s,mimeType:n,includeBleed:a,quality:r}={}){var i;const l=t||1;s=s||(null===(i=e.pages[0])||void 0===i?void 0:i.id);const d=e.pages.find((e=>e.id===s));if(!d)throw new Error(`No page for export with id ${s}`);null==d||d.set({_exporting:!0}),await new Promise((e=>{setTimeout(e,0)})),await e.waitLoading();const c=konva_1.default.stages.find((e=>e.getAttr("pageId")===s));if(!c)throw new Error(`Export is failed. Can not find stage for page ${s}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);const p=c.findOne(".page-container");c.find("Transformer").forEach((e=>e.visible(!1))),p.findOne(".page-background").shadowEnabled(!1),p.findOne(".page-background").strokeEnabled(!1),p.find(".highlighter").forEach((e=>e.visible(!1)));const _=p.findOne(".page-background-group"),m=_.clip();_.clip({x:null,y:null,width:null,height:null});const g=p.find((e=>e.getAttr("hideInExport")));g.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()})),o&&p.findOne(".page-background").hide();const h=a?d.bleed:0;let f=h;e._bleedVisible&&a?f=0:e._bleedVisible&&!a&&(f=-d.bleed);const u=document.createElement("canvas");u.width=(d.computedWidth+2*h)*l,u.height=(d.computedHeight+2*h)*l;const b=u.getContext("2d");"image/jpeg"===n&&(b.fillStyle="white",b.fillRect(0,0,u.width,u.height));const x=p.toCanvas({x:p.x()-f*p.scaleX(),y:p.y()-f*p.scaleY(),width:(d.computedWidth+2*h)*p.scaleX(),height:(d.computedHeight+2*h)*p.scaleY(),pixelRatio:1/p.scaleX()*l});b.drawImage(x,0,0);const y=u.toDataURL(n,r);return o&&p.findOne(".page-background").show(),g.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),p.findOne(".page-background").shadowEnabled(!0),p.findOne(".page-background").strokeEnabled(!0),c.find("Transformer").forEach((e=>e.visible(!0))),p.find(".highlighter").forEach((e=>e.visible(!0))),_.clip(m),null==d||d.set({_exporting:!1}),y},async saveAsImage(t={}){var{fileName:o}=t,s=__rest(t,["fileName"]);const n=s.mimeType||"image/png",a=n.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(s),o||"polotno."+a,n)},async _toPDF(t){const o=t.dpi||300,s=t.parallel||1,n=t.unit||"mm",a=t.pixelUnitRatio||25.4/o,r=t.pixelRatio||1,i=await(0,pdf_1.getJsPDF)(),l=e=>e*a,d=e.pages[0]||{},c=t.includeBleed?d.bleed:0,p=l(d.computedWidth+2*c),_=l(d.computedHeight+2*c);var m=new i({unit:n,orientation:p>_?"landscape":"portrait",format:[p,_],compress:!0});m.deletePage(1);const g=e._elementsPixelRatio;e.setElementsPixelRatio(r),await new Promise((e=>setTimeout(e)));const h=((e,t)=>{for(var o=[],s=0;s<e.length;s+=t)o.push(e.slice(s,s+t));return o})(e.pages,s);for(const o of h){const s=o.map((async o=>{const s=t.includeBleed?o.bleed:0,n=l(o.computedWidth+2*s),a=l(o.computedHeight+2*s);let i=0,d=r;for(;i<10;){i+=1,2===i&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const s=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:o.id,pixelRatio:d}));if(s.length>20)return{url:s,width:n,height:a};d*=.8}}));(await Promise.all(s)).forEach((({url:e,width:t,height:o})=>{m.addPage([t,o],t>o?"landscape":"portrait"),m.addImage(e,0,0,t,o,void 0,"FAST")}))}return e.setElementsPixelRatio(g),m},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async saveAsPDF(t={}){var{fileName:o}=t,s=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},s))).save(o||"polotno.pdf")},async waitLoading(){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)}),loadJSON(t,o=!1){var s;const n=Object.assign({},t);e.pages.forEach((e=>e.children.forEach((e=>(0,mobx_state_tree_1.detach)(e)))));const a=e.pages.indexOf(e.activePage);let r=null===(s=n.pages[a]||n.pages[0])||void 0===s?void 0:s.id;e.pages=(0,mobx_state_tree_1.cast)([]),n._activePageId=r,n.scale=e.scale,n.openedSidePanel=e.openedSidePanel,n._bleedVisible=e._bleedVisible,o&&(n.history=e.history.toJSON()),(0,mobx_state_tree_1.applySnapshot)(e,n)},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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "0.39.13",
3
+ "version": "0.40.0",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [