polotno 2.30.0 → 2.30.2
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/canvas/drawing-layer.js +1 -1
- package/model/store.d.ts +3 -3
- package/model/store.js +1 -1
- package/package.json +1 -1
- package/polotno.bundle.js +4 -4
- package/side-panel/draw-panel.js +4 -4
- package/utils/path-to-svg.d.ts +1 -1
- package/utils/path-to-svg.js +1 -1
- package/utils/validate-key.js +1 -1
package/canvas/drawing-layer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import{Group as r,Line as o,Rect as n}from"react-konva";import{pathToSVG as i}from"../utils/path-to-svg.js";export const DrawingLayer=t(({store:t,page:s,width:c,height:a,scale:l,xPadding:h,yPadding:u,bleed:g})=>{const[y,d]=e.useState(!1),[p,f]=e.useState([]),m=e.useRef(null),x="draw"===t.tool,{strokeWidth:k,
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{Group as r,Line as o,Rect as n}from"react-konva";import{pathToSVG as i}from"../utils/path-to-svg.js";export const DrawingLayer=t(({store:t,page:s,width:c,height:a,scale:l,xPadding:h,yPadding:u,bleed:g})=>{const[y,d]=e.useState(!1),[p,f]=e.useState([]),m=e.useRef(null),x="draw"===t.tool,{strokeWidth:k,stroke:w,opacity:$,brushType:b}=t.toolOptions,v="highlighter"===b?.5:$,E=e.useCallback(e=>{if(!x){return}if(d(!0),e.cancelBubble=!0,!e.target.getStage()){return}const t=m.current.getRelativePointerPosition();t&&f([{x:t.x,y:t.y}])},[x,l,h,u,g]),S=e.useCallback(e=>{if(!x||!y){return}if(e.cancelBubble=!0,!e.target.getStage()){return}const t=m.current.getRelativePointerPosition();t&&f(e=>[...e,{x:t.x,y:t.y}])},[x,y,l,h,u,g]),M=e.useCallback(()=>{if(x&&y){if(d(!1),p.length>1){try{const e=i(p,{stroke:w,strokeWidth:k,opacity:v,smooth:!0}),r=t.selectedElementsIds.slice();t.history.transaction(()=>{s.addElement({type:"svg",x:e.x,y:e.y,width:e.width,height:e.height,src:e.src},{skipSelect:!0})}),t.selectElements(r)}catch(e){console.error("Error creating path SVG:",e)}}f([])}},[x,y,p,w,k,v,s,t.history,t]),P=e.useMemo(()=>p.flatMap(e=>[e.x,e.y]),[p]);return e.useEffect(()=>{if(x&&m.current){const e=m.current.getStage();if(!e){return}const t=k*l;if(t>100||t<4){e.container().style.cursor="crosshair"}else{const r=t/2,o=t/2,n=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${t}" viewBox="0 0 ${t} ${t}">\n <circle cx="${o}" cy="${o}" r="${r-1}" fill="${w}" opacity="${v}" stroke="white" stroke-width="1"/>\n <circle cx="${o}" cy="${o}" r="${r-1}" fill="none" stroke="black" stroke-width="1" opacity="0.3"/>\n </svg>`)}`;e.container().style.cursor=`url("${n}") ${o} ${o}, crosshair`}return()=>{e.container()&&(e.container().style.cursor="")}}},[x,w,k,v,l]),x?e.createElement(r,{ref:m,listening:x,x:h+g*l,y:u+g*l,scaleX:l,scaleY:l},e.createElement(n,{x:-(h+g*l)/l,y:-(u+g*l)/l,width:c/l,height:a/l,fill:"transparent",onMouseDown:E,onMouseMove:S,onMouseUp:M,onTouchStart:E,onTouchMove:S,onTouchEnd:M}),p.length>0&&e.createElement(o,{points:P,stroke:w,strokeWidth:k,lineCap:"round",lineJoin:"round",opacity:v,tension:.5,listening:!1})):null});
|
package/model/store.d.ts
CHANGED
|
@@ -140,7 +140,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
140
140
|
toolOptions: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").IModelType<{
|
|
141
141
|
brushType: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<string>, [undefined]>;
|
|
142
142
|
strokeWidth: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<number>, [undefined]>;
|
|
143
|
-
|
|
143
|
+
stroke: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<string>, [undefined]>;
|
|
144
144
|
opacity: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<number>, [undefined]>;
|
|
145
145
|
}, {}, import("mobx-state-tree")._NotCustomized, import("mobx-state-tree")._NotCustomized>, [undefined]>;
|
|
146
146
|
selectedElementsIds: import("mobx-state-tree").IArrayType<import("mobx-state-tree").ISimpleType<string>>;
|
|
@@ -807,10 +807,10 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
807
807
|
}): void;
|
|
808
808
|
setRole(role: string): void;
|
|
809
809
|
setTool(tool: "selection" | "draw" | "pan" | "text" | "eraser"): void;
|
|
810
|
-
|
|
810
|
+
setToolOptions(options: Partial<{
|
|
811
811
|
brushType: "brush" | "highlighter";
|
|
812
812
|
strokeWidth: number;
|
|
813
|
-
|
|
813
|
+
stroke: string;
|
|
814
814
|
opacity: number;
|
|
815
815
|
}>): void;
|
|
816
816
|
addPage(attrs?: any): import("mobx-state-tree").ModelInstanceTypeProps<{
|
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{whenLoaded as w}from"../utils/loader.js";import{pxToUnit as v}from"../utils/unit.js";import{deepEqual as P}from"../utils/deep-equal.js";import{waitTillAvailable as E}from"../utils/wait.js";import{jsonToHTML as x}from"../utils/to-html.js";import{jsonToSVG as _}from"../utils/to-svg.js";import{Page as k}from"./page-model.js";import{forEveryChild as I}from"./group-model.js";import{Audio as O}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const Store=l.model("Store",{role:"",pages:l.array(k),fonts:l.array(Font),audios:l.array(O),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:2,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),strokeColor:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return I({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const t=[];return I({children:e.selectedElements},e=>{"group"!==e.type&&t.push(e)}),t},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return e.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return I({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(e=>{let t=0,o=null,n=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:a=[],startTime:s=0,currentTime:r=0,endTime:l=e.duration,repeat:d=!1}={}){r&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),s=r),e.animatedElementsIds=i(a),e.currentTime=s,e.isPlaying=!0,t=Date.now(),o=l,n=d,requestAnimationFrame(e.seek)},checkActivePage(){let t=0;for(const i of e.pages){if(e.currentTime>=i.startTime&&e.currentTime<i.startTime+i.duration){e.selectPage(i.id);break}t+=i.duration}},seek(){if(!e.isPlaying){return}const i=Date.now(),a=i-t;t=i,e.currentTime+=a,e.checkActivePage();const s=o||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&n?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=i([]),e.checkActivePage()}}}).actions(r=>({__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},updateToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=k.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),a=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const s=a.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=r.toJSON();return s(r,i=>{const o=r.toJSON();!P(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1}={}){var l;const d=e||1;i=i||(null===(l=r.pages[0])||void 0===l?void 0:l.id);const c=r.pages.find(e=>e.id===i);if(!c){throw new Error(`No page for export with id ${i}`)}const g=r._elementsPixelRatio;d>r._elementsPixelRatio&&r.setElementsPixelRatio(d),s?null==c||c.set({_forceMount:!0}):null==c||c.set({_exporting:!0});const m=await E(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!m){throw null==c||c.set({_forceMount:!1,_exporting:!1}),r.setElementsPixelRatio(g),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}m.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const u=m[0];await r.waitLoading({_skipTimeout:a});const f=u.findOne(".page-container");if(!f){throw r.setElementsPixelRatio(g),null==c||c.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const h=u.position();u.position({x:0,y:0}),u.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),f.find(".page-background").forEach(e=>e.shadowEnabled(!1)),f.find(".page-background").forEach(e=>e.strokeEnabled(!1)),f.find(".highlighter").forEach(e=>e.visible(!1));const b=f.findOne(".page-background-group"),y=b.clip();b.clip({x:null,y:null,width:null,height:null});const w=f.findOne(".elements-container"),v=w.clip();w.clip({x:null,y:null,width:null,height:null});const P=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));P.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const x=f.find(e=>e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&f.find(".page-background").forEach(e=>e.hide());const _=n?c.bleed:0;let k=_;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?k=0:r.bleedVisible&&!n&&(k=-c.bleed):k=0);const I=document.createElement("canvas");I.width=Math.round((c.computedWidth+2*_)*d),I.height=Math.round((c.computedHeight+2*_)*d);const O=I.getContext("2d");"image/jpeg"===o&&(O.fillStyle="white",O.fillRect(0,0,I.width,I.height));const T=f.scale();f.scale({x:1,y:1});const S=f.toCanvas({x:f.x()-k,y:f.y()-k,width:c.computedWidth+2*_,height:c.computedHeight+2*_,pixelRatio:d});return f.scale(T),O.drawImage(S,0,0,I.width,I.height),p.Util.releaseCanvas(S),t&&f.find(".page-background").forEach(e=>e.show()),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),P.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".page-background").forEach(e=>e.shadowEnabled(!0)),f.find(".page-background").forEach(e=>e.strokeEnabled(!0)),u.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".highlighter").forEach(e=>e.visible(!0)),b.clip(y),w.clip(v),u.position(h),null==c||c.set({_exporting:!1,_forceMount:!1}),await new Promise(e=>setTimeout(e)),r.setElementsPixelRatio(g),I},async toDataURL(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await r._toCanvas(Object.assign({mimeType:i},n)),s=a.toDataURL(i,o);return p.Util.releaseCanvas(a),s},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await r._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=o.mimeType||"image/png",a=n.split("/")[1];m(await r.toDataURL(o),i||"polotno."+a,n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||r.pages.map(e=>e.id),s=r.pages.filter(e=>a.includes(e.id)),l=await u(),d=e=>v({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{for(var i=[],o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const u of y){const t=u.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,l=d(o),p=d(s);let g=0,m=n;for(;g<10;){g+=1,2===g&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const i=await r.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:m}));if(i.length>20){return e.onProgress&&e.onProgress(++w/a.length*.9),{url:i,width:l,height:p,widthPx:o,heightPx:s}}m*=.8}});(await Promise.all(t)).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;case"pc":case"em":r=12;break;case"ex":r=6;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await r._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let a=0;a<n-1;a++){const e=a*o||1;r.setCurrentTime(e);let n=0,s="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){s=t.id;break}}const l=await r._toCanvas({pixelRatio:t,pageId:s,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const a of r.pages){a.set({_rendering:!1})}return r.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await r.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={elementHook:void 0}){const t=r.toJSON();return x({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await r.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=r.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return _({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await r.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await r._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await w()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o;const n=JSON.parse(JSON.stringify(e)),s=n.schemaVersion||0;s<1&&y.htmlRenderEnabled&&I({children:n.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),s<2&&I({children:n.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),delete n.schemaVersion;const l=r.pages.indexOf(r.activePage);let d=null===(o=n.pages[l]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=d;const c=Object.assign({},a(r));Object.assign(c,n),c.history=i?r.history.toJSON():{history:[],undoIdx:-1},t(r,c)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);r.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.removeFont(e.fontFamily),r.fonts.push(e),r.loadFont(e.fontFamily)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=O.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t=""){const i=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let o=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return i?(i.styles&&(o=i.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(i)):b.injectGoogleFont(e),Promise.all(o.map(i=>b.loadFont(e,i.fontStyle,i.fontWeight,t)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))}));export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{whenLoaded as w}from"../utils/loader.js";import{pxToUnit as v}from"../utils/unit.js";import{deepEqual as P}from"../utils/deep-equal.js";import{waitTillAvailable as E}from"../utils/wait.js";import{jsonToHTML as x}from"../utils/to-html.js";import{jsonToSVG as _}from"../utils/to-svg.js";import{Page as k}from"./page-model.js";import{forEveryChild as I}from"./group-model.js";import{Audio as O}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const Store=l.model("Store",{role:"",pages:l.array(k),fonts:l.array(Font),audios:l.array(O),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:2,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return I({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const t=[];return I({children:e.selectedElements},e=>{"group"!==e.type&&t.push(e)}),t},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return e.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return I({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(e=>{let t=0,o=null,n=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:a=[],startTime:s=0,currentTime:r=0,endTime:l=e.duration,repeat:d=!1}={}){r&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),s=r),e.animatedElementsIds=i(a),e.currentTime=s,e.isPlaying=!0,t=Date.now(),o=l,n=d,requestAnimationFrame(e.seek)},checkActivePage(){let t=0;for(const i of e.pages){if(e.currentTime>=i.startTime&&e.currentTime<i.startTime+i.duration){e.selectPage(i.id);break}t+=i.duration}},seek(){if(!e.isPlaying){return}const i=Date.now(),a=i-t;t=i,e.currentTime+=a,e.checkActivePage();const s=o||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&n?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=i([]),e.checkActivePage()}}}).actions(r=>({__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=k.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),a=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const s=a.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=r.toJSON();return s(r,i=>{const o=r.toJSON();!P(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1}={}){var l;const d=e||1;i=i||(null===(l=r.pages[0])||void 0===l?void 0:l.id);const c=r.pages.find(e=>e.id===i);if(!c){throw new Error(`No page for export with id ${i}`)}const g=r._elementsPixelRatio;d>r._elementsPixelRatio&&r.setElementsPixelRatio(d),s?null==c||c.set({_forceMount:!0}):null==c||c.set({_exporting:!0});const m=await E(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!m){throw null==c||c.set({_forceMount:!1,_exporting:!1}),r.setElementsPixelRatio(g),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}m.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const u=m[0];await r.waitLoading({_skipTimeout:a});const f=u.findOne(".page-container");if(!f){throw r.setElementsPixelRatio(g),null==c||c.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const h=u.position();u.position({x:0,y:0}),u.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),f.find(".page-background").forEach(e=>e.shadowEnabled(!1)),f.find(".page-background").forEach(e=>e.strokeEnabled(!1)),f.find(".highlighter").forEach(e=>e.visible(!1));const b=f.findOne(".page-background-group"),y=b.clip();b.clip({x:null,y:null,width:null,height:null});const w=f.findOne(".elements-container"),v=w.clip();w.clip({x:null,y:null,width:null,height:null});const P=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));P.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const x=f.find(e=>e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&f.find(".page-background").forEach(e=>e.hide());const _=n?c.bleed:0;let k=_;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?k=0:r.bleedVisible&&!n&&(k=-c.bleed):k=0);const I=document.createElement("canvas");I.width=Math.round((c.computedWidth+2*_)*d),I.height=Math.round((c.computedHeight+2*_)*d);const O=I.getContext("2d");"image/jpeg"===o&&(O.fillStyle="white",O.fillRect(0,0,I.width,I.height));const T=f.scale();f.scale({x:1,y:1});const S=f.toCanvas({x:f.x()-k,y:f.y()-k,width:c.computedWidth+2*_,height:c.computedHeight+2*_,pixelRatio:d});return f.scale(T),O.drawImage(S,0,0,I.width,I.height),p.Util.releaseCanvas(S),t&&f.find(".page-background").forEach(e=>e.show()),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),P.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".page-background").forEach(e=>e.shadowEnabled(!0)),f.find(".page-background").forEach(e=>e.strokeEnabled(!0)),u.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".highlighter").forEach(e=>e.visible(!0)),b.clip(y),w.clip(v),u.position(h),null==c||c.set({_exporting:!1,_forceMount:!1}),await new Promise(e=>setTimeout(e)),r.setElementsPixelRatio(g),I},async toDataURL(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await r._toCanvas(Object.assign({mimeType:i},n)),s=a.toDataURL(i,o);return p.Util.releaseCanvas(a),s},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await r._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=o.mimeType||"image/png",a=n.split("/")[1];m(await r.toDataURL(o),i||"polotno."+a,n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||r.pages.map(e=>e.id),s=r.pages.filter(e=>a.includes(e.id)),l=await u(),d=e=>v({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{for(var i=[],o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const u of y){const t=u.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,l=d(o),p=d(s);let g=0,m=n;for(;g<10;){g+=1,2===g&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const i=await r.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:m}));if(i.length>20){return e.onProgress&&e.onProgress(++w/a.length*.9),{url:i,width:l,height:p,widthPx:o,heightPx:s}}m*=.8}});(await Promise.all(t)).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;case"pc":case"em":r=12;break;case"ex":r=6;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await r._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let a=0;a<n-1;a++){const e=a*o||1;r.setCurrentTime(e);let n=0,s="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){s=t.id;break}}const l=await r._toCanvas({pixelRatio:t,pageId:s,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const a of r.pages){a.set({_rendering:!1})}return r.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await r.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={elementHook:void 0}){const t=r.toJSON();return x({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await r.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=r.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return _({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await r.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await r._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await w()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o;const n=JSON.parse(JSON.stringify(e)),s=n.schemaVersion||0;s<1&&y.htmlRenderEnabled&&I({children:n.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),s<2&&I({children:n.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),delete n.schemaVersion;const l=r.pages.indexOf(r.activePage);let d=null===(o=n.pages[l]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=d;const c=Object.assign({},a(r));Object.assign(c,n),c.history=i?r.history.toJSON():{history:[],undoIdx:-1},t(r,c)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);r.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.removeFont(e.fontFamily),r.fonts.push(e),r.loadFont(e.fontFamily)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=O.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t=""){const i=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let o=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return i?(i.styles&&(o=i.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(i)):b.injectGoogleFont(e),Promise.all(o.map(i=>b.loadFont(e,i.fontStyle,i.fontWeight,t)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))}));export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
|
package/package.json
CHANGED
package/polotno.bundle.js
CHANGED
|
@@ -299,11 +299,11 @@ https://polotno.com/docs/server-api`,lO={unsplashList:({query:e,page:t=1})=>`${l
|
|
|
299
299
|
font-weight: ${l};
|
|
300
300
|
src: url(${n});
|
|
301
301
|
}`}));return so("style",{},o.join("\n"))}catch(e){return console.error("Error embedding Google Font:",e),so("defs",{},so("style",{type:"text/css",innerHTML:`@import url('${t}');`.replace(/&/g,"&")}))}}}))}async function sp({json:e,elementHook:t,fontEmbedding:n="inline"}){let r=[];si({children:e.pages},e=>{"text"===e.type&&-1===r.indexOf(e.fontFamily)&&r.push(e.fontFamily)});let i="inline"===n?await sf(r,e.fonts):[],o=await Promise.all(e.pages.map(n=>sd({page:n,store:e,elementHook:t})));return so("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:`0 0 ${e.width} ${e.height}`,width:e.width,height:e.height},...i,...o)}let sg=({dom:e,nestLevel:t=0})=>{if("string"==typeof e)return e;if(!e)return"";let{innerHTML:n,...r}=e.props,i=Object.keys(r).map(e=>{var t;return"object"==typeof(t=r[e])?`${e}="${Object.keys(t).map(e=>`${e}:${t[e]};`).join(" ")}"`:null==t||""===t?"":`${e}="${t}"`}).filter(e=>e&&e.trim().length>0).join(" "),o=" ".repeat(t);return`${o}<${e.type}${i?" "+i:""}>${n||"\n"+e.children.map(e=>sg({dom:e,nestLevel:t+1})).join("")}${o}</${e.type}>
|
|
302
|
-
`};async function sm({json:e,elementHook:t,fontEmbedding:n="inline"}){return sg({dom:await sp({json:e,elementHook:t,fontEmbedding:n})})}var iH=x("58B0H");let sv=iH.types.model("Page",{id:iH.types.identifier,children:iH.types.array(iH.types.late(()=>sB)),width:iH.types.optional(iH.types.union(iH.types.number,iH.types.literal("auto")),"auto"),height:iH.types.optional(iH.types.union(iH.types.number,iH.types.literal("auto")),"auto"),background:"white",bleed:0,custom:iH.types.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot(e=>{let t={...e},n={};for(var r in t)"_"!==r[0]&&(n[r]=e[r]);return n}).views(e=>({get store(){return(0,iH.getParentOfType)(e,sx)}})).views(e=>({get startTime(){let t=0;for(let n of e.store.pages){if(n.id===e.id)break;t+=n.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering}})).views(e=>({get computedWidth(){if("auto"===e.width)return e.store.width;return e.width},get computedHeight(){if("auto"===e.height)return e.store.height;return e.height}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify((0,iH.getSnapshot)(e))),_forEachElementUp(t,n){let r=t.map(t=>({id:t,index:e.children.findIndex(e=>e.id===t)}));for(let{index:i}of(r.sort((e,t)=>t.index-e.index),r)){if(-1==i)continue;let r=i<e.children.length-1&&e.children[i+1],o=t.indexOf(r?.id)>=0;i===e.children.length-1||o||n(i)}},_forEachElementDown(t,n){let r=t.map(t=>({id:t,index:e.children.findIndex(e=>e.id===t)}));for(let{index:i}of(r.sort((e,t)=>e.index-t.index),r)){if(-1==i)continue;let r=i>0&&e.children[i-1],o=t.indexOf(r?.id)>=0;0===i||o||n(i)}return!1}})).actions(e=>({clone(t={}){let n=e.toJSON();n.children.forEach(e=>{e.id=lm(10),sz(e,e=>{e.id=lm(10)})});let r={...n,id:lm(10),...t},i=e.store.addPage(r),o=e.store.pages.indexOf(e);return i.setZIndex(o+1),i.select(),i},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:n=!1}={}){let r=sU[t.type];if(!r)return void console.error("Can not find model with type "+t.type);"children"in t&&Array.isArray(t.children)&&sz(t,e=>{e.id=e.id||lm(10)});let i=e.children.reduce((e,n)=>{if("group"===n.type)return Math.max(e,n.children.reduce((e,n)=>{let r=n.name?.match(RegExp(`${t.type}-(\\d+)`));if(r)return Math.max(e,parseInt(r[1],10)||0)},0)||0);{let r=n.name.match(RegExp(`${t.type}-(\\d+)`));if(r)return Math.max(e,parseInt(r[1],10)||0)}return e},0),o=r.create({id:lm(10),name:`${t.type}-${i+1}`,...t});return e.children.push(o),o.selectable&&!n&&e.store.selectElements([o.id]),o},canMoveElementsUp(t){let n=!1;return e._forEachElementUp(t,()=>{n=n||!0}),n},moveElementsUp(t){e._forEachElementUp(t,t=>{let n=e.children[t];(0,iH.detach)(n),e.children.splice(t+1,0,n)})},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(t){let n=[],r=[];e.children.forEach(e=>{t.indexOf(e.id)>=0?n.push(e):r.push(e)}),e.children.replace(r.concat(n))},canMoveElementsDown(t){let n=!1;return e._forEachElementDown(t,()=>{n=n||!0}),n},moveElementsDown(t){e._forEachElementDown(t,t=>{let n=e.children[t];(0,iH.detach)(n),e.children.splice(t-1,0,n)})},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(t){let n=[],r=[];e.children.forEach(e=>{t.indexOf(e.id)>=0?n.push(e):r.push(e)}),e.children.replace(n.concat(r))},setElementZIndex(t,n){let r=e.children.find(e=>e.id===t);r&&((0,iH.detach)(r),e.children.remove(r),e.children.splice(n,0,r))},setSize({width:t,height:n,useMagic:r,softChange:i}){if(r){let r=[],i=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;sz(e,e=>{"group"!==e.type&&(i(e)||r.push(e))});let o=r.length?aR(r):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},a=1/4,l=Math.max(0,Math.max(0,Math.min(o.x,e.computedWidth-o.x-o.width))-e.computedWidth*a),s=Math.max(0,Math.max(0,Math.min(o.y,e.computedHeight-o.y-o.height))-e.computedHeight*a),u=e.computedWidth-2*l,c=e.computedHeight-2*s,d=t/u,h=n/c,f=Math.min(d,h),p=(t-u*f)/2-l*f,g=(n-c*f)/2-s*f;sz(e,e=>{"group"!==e.type&&(i(e)?e.set({x:e.x*f,y:e.y*f,width:e.width*d,height:e.height*h,cropX:0,cropY:0,cropWidth:1,cropHeight:1}):(e.set({x:p+e.x*f,y:g+e.y*f,width:e.width*f,height:e.height*f}),"text"===e.type?e.set({fontSize:e.fontSize*f}):"figure"===e.type&&e.set({strokeWidth:e.strokeWidth*f})))})}i||(e.width=t),i||(e.height=n)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));var iH=x("58B0H");let sy=iH.types.model("Audio",{id:iH.types.identifier,src:"",duration:0,startTime:0,endTime:1,volume:1,delay:0,custom:iH.types.frozen()}).actions(e=>({toJSON:()=>({...(0,iH.getSnapshot)(e)})})).actions(e=>({set(t){Object.assign(e,t)}}));(0,iH.setLivelinessChecking)("ignore");let sb=iH.types.model("Font",{fontFamily:iH.types.string,url:iH.types.optional(iH.types.string,""),styles:iH.types.frozen()}).preProcessSnapshot(e=>({...e,fontFamily:e.fontFamily||e.name})),sx=iH.types.model("Store",{role:"",pages:iH.types.array(sv),fonts:iH.types.array(sb),audios:iH.types.array(sy),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:2,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:iH.types.frozen(),tool:iH.types.optional(iH.types.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:iH.types.optional(iH.types.model({brushType:iH.types.optional(iH.types.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:iH.types.optional(iH.types.number,5),strokeColor:iH.types.optional(iH.types.string,"#000000"),opacity:iH.types.optional(iH.types.number,1)}),{}),selectedElementsIds:iH.types.array(iH.types.string),animatedElementsIds:iH.types.array(iH.types.string),history:iH.types.optional(ly,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:iH.types.array(iH.types.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{let t=(0,k.computed)(()=>{let t={};return sz({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(let n of e.pages)for(let e of n.children)if(e.id===t)return e}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){let t=[];return sz({children:e.selectedElements},e=>{"group"!==e.type&&t.push(e)}),t},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return e.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let n;return sz({children:e.pages},e=>{if(!n&&t(e))return n=e,!0}),n},getElementById:t=>e._idsMap[t]})).actions(e=>{let t=0,n=null,r=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:i=[],startTime:o=0,currentTime:a=0,endTime:l=e.duration,repeat:s=!1}={}){a&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),o=a),e.animatedElementsIds=(0,iH.cast)(i),e.currentTime=o,e.isPlaying=!0,t=Date.now(),n=l,r=s,requestAnimationFrame(e.seek)},checkActivePage(){for(let t of e.pages){if(e.currentTime>=t.startTime&&e.currentTime<t.startTime+t.duration){e.selectPage(t.id);break}t.duration}},seek(){if(!e.isPlaying)return;let i=Date.now(),o=i-t;t=i,e.currentTime+=o,e.checkActivePage();let a=n||e.duration;e.isPlaying&&e.currentTime<a?requestAnimationFrame(e.seek):e.isPlaying&&r?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,iH.cast)([]),e.checkActivePage()}}}).actions(e=>({__(){e._validated||(lG(e._key,e._forceShowCredit),e._validated=!0)},set(t){Object.assign(e,t)},setUnit({unit:t,dpi:n}){e.unit=t||e.unit,e.dpi=n||e.dpi},setRole(t){e.role=t},setTool(t){e.tool=t},updateToolOptions(t){Object.assign(e.toolOptions,t)},addPage(t){let n=sv.create({id:lm(10),...t});return e.pages.push(n),e._activePageId=n.id,n},selectPage(t){e._activePageId=t,1===e._selectedPagesIds.length&&(e._selectedPagesIds=(0,iH.cast)([t]))},selectPages(t){e._selectedPagesIds=(0,iH.cast)(t),1===e._selectedPagesIds.length&&(e._activePageId=e._selectedPagesIds[0])},selectElements(t){let n=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,iH.cast)(n)},toggleBleed(t){e.bleedVisible=t??!e.bleedVisible},toggleRulers(t){e.rulesVisible=t??!e.rulesVisible},openSidePanel(t){e.openedSidePanel!==t&&(e.previousOpenedSidePanel=e.openedSidePanel,e.openedSidePanel=t)},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,n,r){e.pages.forEach(e=>{e.setSize({width:t,height:n,useMagic:r,softChange:!0})}),e.width=t,e.height=n},setPageZIndex(t,n){let r=e.pages.find(e=>e.id===t);r&&((0,iH.detach)(r),e.pages.remove(r),e.pages.splice(n,0,r))},deletePages(t){let n=e.pages.indexOf(e.activePage);t.forEach(t=>{let n=e.pages.find(e=>e.id===t);(0,iH.destroy)(n)});let r=Math.min(e.pages.length-1,n),i=e.pages[r];i&&(e._activePageId=i.id),e.selectedElementsIds=(0,iH.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},groupElements(t,n={}){let r=t.map(t=>e.getElementById(t)),i=r[0].page;if(r.forEach(e=>{e&&(0,iH.detach)(e)}),!r.length)return;let o=i.children.reduce((e,t)=>{if("group"===t.type){let n=t.name.match(/group-(\d+)/);if(n)return Math.max(e,parseInt(n[1],10))}return e},0),a={id:lm(10),name:`group-${o+1}`,children:r,type:"group",...n};return i.children.push(a),e.selectedElementsIds=(0,iH.cast)([a.id]),i.children.find(e=>e.id===a.id)},ungroupElements(t){let n=t.map(t=>e.getElementById(t)),r=[];n.forEach(e=>{if(e&&"group"===e.type){let t=e.page,n=t.children.indexOf(e);e.children.forEach(e=>{r.push(e.id)}),e.children.forEach(e=>{(0,iH.detach)(e),t.children.push(e)}),t.children.splice(n,1)}}),e.selectedElementsIds=(0,iH.cast)(r)},deleteElements(t){let n=[];e.find(e=>(t.includes(e.id)&&n.push(e),!1)),n.forEach(e=>{(0,iH.destroy)(e)}),e.selectedElementsIds=(0,iH.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},on(t,n){if("change"===t){let t=e.toJSON();return(0,iH.onSnapshot)(e,r=>{let i=e.toJSON();lv(t,i)||(t=i,n(i))})}},async _toCanvas({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o,_skipTimeout:a,quickMode:l=!1}={}){let s=t||1;r=r||e.pages[0]?.id;let u=e.pages.find(e=>e.id===r);if(!u)throw Error(`No page for export with id ${r}`);let c=e._elementsPixelRatio;s>e._elementsPixelRatio&&e.setElementsPixelRatio(s),l?u?.set({_forceMount:!0}):u?.set({_exporting:!0});let d=await lY(()=>{let e=nO.stages.filter(e=>e.getAttr("pageId")===r);return 0===e.length?null:e});if(!d)throw u?.set({_forceMount:!1,_exporting:!1}),e.setElementsPixelRatio(c),Error(`Export is failed. Can not find stage for page ${r}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);d.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${r}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);let h=d[0];await e.waitLoading({_skipTimeout:a});let f=h.findOne(".page-container");if(!f)throw e.setElementsPixelRatio(c),u?.set({_forceMount:!1,_exporting:!1}),Error("Export is failed. Canvas was unmounted.");let p=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),f.find(".page-background").forEach(e=>e.shadowEnabled(!1)),f.find(".page-background").forEach(e=>e.strokeEnabled(!1)),f.find(".highlighter").forEach(e=>e.visible(!1));let g=f.findOne(".page-background-group"),m=g.clip();g.clip({x:null,y:null,width:null,height:null});let v=f.findOne(".elements-container"),y=v.clip();v.clip({x:null,y:null,width:null,height:null});let b=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));b.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});let x=f.find(e=>e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),n&&f.find(".page-background").forEach(e=>e.hide());let w=o?u.bleed:0,C=w;!e.bleedVisible&&o||(e.bleedVisible||o?e.bleedVisible&&o?C=0:e.bleedVisible&&!o&&(C=-u.bleed):C=0);let _=document.createElement("canvas");_.width=Math.round((u.computedWidth+2*w)*s),_.height=Math.round((u.computedHeight+2*w)*s);let S=_.getContext("2d");"image/jpeg"===i&&(S.fillStyle="white",S.fillRect(0,0,_.width,_.height));let E=f.scale();f.scale({x:1,y:1});let k=f.toCanvas({x:f.x()-C,y:f.y()-C,width:u.computedWidth+2*w,height:u.computedHeight+2*w,pixelRatio:s});return f.scale(E),S.drawImage(k,0,0,_.width,_.height),nO.Util.releaseCanvas(k),n&&f.find(".page-background").forEach(e=>e.show()),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".page-background").forEach(e=>e.shadowEnabled(!0)),f.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".highlighter").forEach(e=>e.visible(!0)),g.clip(m),v.clip(y),h.position(p),u?.set({_exporting:!1,_forceMount:!1}),await new Promise(e=>setTimeout(e)),e.setElementsPixelRatio(c),_},async toDataURL({mimeType:t,quality:n,...r}={}){let i=await e._toCanvas({mimeType:t,...r}),o=i.toDataURL(t,n);return nO.Util.releaseCanvas(i),o},async toBlob({mimeType:t,quality:n,...r}={}){let i=await e._toCanvas({mimeType:t,...r}),o=await new Promise(e=>{i.toBlob(e,t,n)});return nO.Util.releaseCanvas(i),o},async saveAsImage({fileName:t,...n}={}){let r=n.mimeType||"image/png",i=r.split("/")[1];lb(await e.toDataURL(n),t||"polotno."+i,r)},async _toPDF(t){let n=t.dpi||e.dpi,r=t.parallel||1,i=t.unit||("px"===e.unit?"mm":e.unit),o=t.pixelRatio||1,a=t.pageIds||e.pages.map(e=>e.id),l=e.pages.filter(e=>a.includes(e.id)),s=await (window.jspdf?.jsPDF?Promise.resolve(window.jspdf.jsPDF):lx||(lx=new Promise(e=>{var t=document.createElement("script");t.onload=function(){e(window.jspdf.jsPDF)},t.src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.1/jspdf.umd.min.js",document.head.appendChild(t)}))),u=e=>lq({px:e,unit:i,dpi:n}),c=t.cropMarkSize||0,d=u(c),h=l[0]||{},f=t.includeBleed?h.bleed:0,p=u(h.computedWidth+2*f+2*d),g=u(h.computedHeight+2*f+2*d);var m=new s({unit:i,orientation:p>g?"landscape":"portrait",format:[p,g],compress:!0,putOnlyUsedFonts:!0});m.deletePage(1);let v=((e,t)=>{for(var n=[],r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n})(l,r),y=0;for(let n of v){let r=n.map(async n=>{let r=t.includeBleed?n.bleed:0,i=n.computedWidth+2*r+2*c,l=n.computedHeight+2*r+2*c,s=u(i),d=u(l),h=0,f=o;for(;h<10;){2===(h+=1)&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");let r=await e.toDataURL({...t,pageId:n.id,pixelRatio:f});if(r.length>20)return t.onProgress&&t.onProgress(++y/a.length*.9),{url:r,width:s,height:d,widthPx:i,heightPx:l};f*=.8}});(await Promise.all(r)).forEach(({url:e,width:t,height:n,widthPx:r,heightPx:o})=>{var a;m.addPage([t,n],t>n?"landscape":"portrait");let l=m.getCurrentPageInfo();switch(i){case"pt":a=1;break;case"mm":a=72/25.4;break;case"cm":a=72/2.54;break;case"in":a=72;break;case"px":a=.75;break;case"pc":case"em":a=12;break;case"ex":a=6;break;default:throw"Invalid unit: "+i}if(l.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*a,topRightY:n*a},l.pageContext.artBox={bottomLeftX:u(c+f)*a,bottomLeftY:u(c+f)*a,topRightX:u(r-c-f)*a,topRightY:u(o-c-f)*a},l.pageContext.bleedBox={bottomLeftX:u(c+f)*a,bottomLeftY:u(c+f)*a,topRightX:u(r-c-f)*a,topRightY:u(o-c-f)*a},d){m.setLineWidth(u(1));let e=d+u(f);m.line(e,0,e,d),m.line(0,e,d,e),m.line(t-e,0,t-e,d),m.line(t,e,t-d,e),m.line(0,n-e,d,n-e),m.line(e,n,e,n-d),m.line(t,n-e,t-d,n-e),m.line(t-e,n,t-e,n-d)}m.addImage(e,d,d,t-2*d,n-2*d,void 0,"FAST")})}return m},toPDFDataURL:async t=>(await e._toPDF({mimeType:"image/jpeg",...t})).output("datauristring"),async toGIFDataURL(t={}){let n=t.pixelRatio||1,r=await lw({width:e.width*n,height:e.height*n}),i=1e3/(t.fps||10),o=e.duration/i;for(let t=0;t<o-1;t++){let o=t*i||1;e.setCurrentTime(o);let a=0,l="";for(let t of e.pages)if(a+=t.duration,t.set({_rendering:a>o}),a>o){l=t.id;break}let s=await e._toCanvas({pixelRatio:n,pageId:l,_skipTimeout:!0});r.addFrame(s.getContext("2d"),{delay:i,copy:!0})}for(let t of e.pages)t.set({_rendering:!1});return e.stop(),r.render(),new Promise(e=>{r.on("finished",function(t){var n;(n=new FileReader).onload=function(t){e(t.target.result)},n.readAsDataURL(t)})})},async saveAsGIF({fileName:t,...n}={}){lb(await e.toGIFDataURL(n),t||"polotno.gif")},toHTML:async({elementHook:t}={elementHook:void 0})=>sr({json:e.toJSON(),elementHook:t}),async saveAsHTML({fileName:t,elementHook:n}={}){let r=await e.toHTML({elementHook:n});lb("data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(r))),t||"polotno.html")},async toSVG({elementHook:t,pageId:n,fontEmbedding:r="inline"}={fontEmbedding:"inline"}){let i=e.toJSON();n=n||i.pages[0]?.id;let o=i.pages.find(e=>e.id===n);return sm({json:{...i,pages:o?[o]:[]},elementHook:t,fontEmbedding:r})},async saveAsSVG({fileName:t,elementHook:n,pageId:r,fontEmbedding:i="inline"}={}){let o=await e.toSVG({elementHook:n,pageId:r,fontEmbedding:i});lb("data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(o))),t||"polotno.svg")},async saveAsPDF({fileName:t,...n}={}){(await e._toPDF({mimeType:"image/jpeg",...n})).save(t||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await new Promise(e=>{var t;return t=()=>{r0?setTimeout(e,300):e(!0)},void(0===r3?t():r4.push(t))})},toJSON:()=>({width:e.width,height:e.height,fonts:(0,iH.getSnapshot)(e.fonts),pages:(0,iH.getSnapshot)(e.pages),audios:(0,iH.getSnapshot)(e.audios),unit:e.unit,dpi:e.dpi,custom:e.custom,schemaVersion:e.schemaVersion}),loadJSON(t,n=!1){let r=JSON.parse(JSON.stringify(t)),i=r.schemaVersion||0;i<1&&ik.htmlRenderEnabled&&sz({children:r.pages},e=>{if("text"===e.type){let t=16*e.letterSpacing;e.letterSpacing=t/e.fontSize}}),i<2&&sz({children:r.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t))return;let n=e.filters[t];n&&"number"==typeof n.intensity&&(n.intensity=n.intensity/100)})}),delete r.schemaVersion;let o=e.pages.indexOf(e.activePage),a=(r.pages[o]||r.pages[0])?.id;r._activePageId=a;let l={...(0,iH.getSnapshot)(e)};Object.assign(l,r),n?l.history=e.history.toJSON():l.history={history:[],undoIdx:-1},(0,iH.applySnapshot)(e,l)},clear({keepHistory:t=!1}={}){let n=e.pages.map(e=>e.id);e.deletePages(n),e.custom=null,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,iH.destroy)(e))},addAudio(t){let n=sy.create({id:lm(10),...t});e.audios.push(n)},removeAudio(t){let n=e.audios.find(e=>e.id===t);n&&e.audios.remove(n)},async loadFont(t,n=""){let r=e.fonts.find(e=>e.fontFamily===t)||iu.find(e=>e.fontFamily===t),i=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return r?(r.styles&&(i=r.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),iE(r)):i_(t),Promise.all(i.map(e=>iy(t,e.fontStyle,e.fontWeight,n)))},validate:e=>sx.validate(e,[{path:"",type:sx}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))})),sw=iH.types.model("Node",{id:iH.types.identifier,type:"none",name:"",opacity:1,custom:iH.types.frozen(),visible:!0,selectable:!0,removable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot(e=>{for(var t in e)null===e[t]&&(e[t]=void 0);return e}).postProcessSnapshot(e=>{let t={...e},n={};for(var r in t)"_"!==r[0]&&(n[r]=e[r]);return n}).views(e=>({get locked(){return!e.draggable&&!e.contentEditable&&!e.styleEditable&&!e.resizable},get page(){return(0,iH.getParentOfType)(e,sv)},get store(){return(0,iH.getParentOfType)(e,sx)},get top(){let t=e;for(;;)if(!(0,iH.hasParentOfType)(t,sH))return t;else t=(0,iH.getParentOfType)(t,sH)},get parent(){if((0,iH.hasParentOfType)(e,sH)){let t=(0,iH.getParentOfType)(e,sH);return t&&t.children&&t.children.length,t}if((0,iH.hasParentOfType)(e,sv)){let t=(0,iH.getParentOfType)(e,sv);return t&&t.children&&t.children.length,t}if((0,iH.hasParentOfType)(e,sx)){let t=(0,iH.getParentOfType)(e,sx);return t&&t.pages&&t.pages.length,t}return null},get zIndex(){return e.parent.children.indexOf(e)}})).actions(e=>({toJSON:()=>({...(0,iH.getSnapshot)(e)})})).actions(e=>({clone(t={},{skipSelect:n=!1}={}){let r=JSON.parse(JSON.stringify(e.toJSON()));return t.id=t.id||lm(10),sz(r,e=>{e.id=lm(10)}),Object.assign(r,t),e.page.addElement(r,{skipSelect:n})},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])},setZIndex(t){e.parent.setElementZIndex(e.id,t)},beforeDestroy(){}}));var iH=x("58B0H");let sC={right:{from:{x:-200},to:{x:0}},left:{from:{x:200},to:{x:0}},up:{from:{y:200},to:{y:0}},down:{from:{y:-200},to:{y:0}},"bottom-right":{from:{x:-200,y:-200},to:{x:0,y:0}},"bottom-left":{from:{x:200,y:-200},to:{x:0,y:0}},"top-right":{from:{x:-200,y:200},to:{x:0,y:0}},"top-left":{from:{x:200,y:200},to:{x:0,y:0}}},s_={right:{cropX:-1},left:{cropX:1},up:{cropY:1},down:{cropY:-1}},sS={fade:({dTime:e,element:t,animation:n})=>{let r=e/n.duration;return"enter"===n.type?{opacity:r*t.opacity}:{opacity:(1-r)*t.opacity}},rotate:({dTime:e,element:t,animation:n})=>{let r=n.duration;return function(e,t){let n=function(e){let t=aA(e.rotation||0);return{x:e.x+e.width/2*Math.cos(t)+e.height/2*Math.sin(-t),y:e.y+e.height/2*Math.cos(t)+e.width/2*Math.sin(t)}}(e),r=aA(t),i=n.x+(e.x-n.x)*Math.cos(r)-(e.y-n.y)*Math.sin(r),o=n.y+(e.x-n.x)*Math.sin(r)+(e.y-n.y)*Math.cos(r);return{...e,rotation:e.rotation+t,x:i,y:o}}({x:t.x,y:t.y,width:t.width,height:t.height,rotation:t.rotation},e/r*360)},blink:({dTime:e,element:t,animation:n})=>{let r=n.duration,i=e%r/(r/2);return{opacity:t.opacity*(i<=1?i:2-i)}},bounce:({dTime:e,element:t,animation:n})=>{let r=n.duration,i=n.data.strength??1,o={},a={x:t.x+t.width/3*i,y:t.y+t.height/3*i,width:t.width/3*i,height:t.height/3*i,fontSize:t.fontSize/3*i},l={x:t.x,y:t.y,width:t.width,height:t.height,fontSize:t.fontSize},s=e%r/(r/2),u=s<=1?s:2-s;for(let e in a){let t=a[e],n=l[e]-t;o[e]=t+u*n}return o},move:({dTime:e,element:t,animation:n})=>{let r=sC[n.data.direction]||sC.right,i=n.data.strength??1,o={};for(var a in r.from){let l=r.from[a],s=r.to[a];"exit"===n.type&&(l=r.to[a],s=-r.from[a]),l*=i,s*=i;let u=t[a]+l,c=t[a]+s-u;o[a]=u+e/n.duration*c}return o},zoom:({dTime:e,element:t,animation:n})=>{let r={},i=n.data.direction||"in",o=1+(("in"===i?3/4:5/4)-1)*(n.data.strength??1),a=t.rotation*Math.PI/180,l=Math.cos(a),s=Math.sin(a),u=t.width*(1-o),c=t.height*(1-o),d={x:t.x+(u*l-c*s)/2,y:t.y+(u*s+c*l)/2,width:t.width*o,height:t.height*o,fontSize:t.fontSize*o},h={x:t.x,y:t.y,width:t.width,height:t.height,fontSize:t.fontSize};for(var f in d){let t=d[f],i=h[f];if("exit"===n.type){let e=t;t=i,i=e}let o=i-t;r[f]=t+e/n.duration*o}return r},cameraZoom:({dTime:e,element:t,animation:n})=>{let r,i,o={},a=s_[n.data.direction||"right"]||s_.right,l=n.data.movementStrength??.1,s=n.data.shakeStrength??.015,u=n.data.zoomStrength??.6,c=e/n.duration,d=s*(1-c),h=Math.sin(12*c)*d*.7+Math.sin(8*c)*d*.3;"exit"===n.type&&(u=Math.min(u,1-Math.max(t.cropWidth||1,t.cropHeight||1))),n.type;let f=1-Math.pow(1-c,2),p=t.cropX||0,g=t.cropY||0,m=t.cropWidth||1,v=t.cropHeight||1,y=0,b=0;return a.cropX&&(y=Math.min(a.cropX>0?1-(p+m):p,Math.abs(l))*a.cropX),a.cropY&&(b=Math.min(a.cropY>0?1-(g+v):g,Math.abs(l))*a.cropY),"enter"===n.type?(r=a.cropX?p+y*(1-f):p,i=a.cropY?g+b*(1-f):g):(r=a.cropX?p+y*f:p,i=a.cropY?g+b*f:g),o.cropX=Math.max(0,Math.min(1-m,r+h*m)),o.cropY=Math.max(0,Math.min(1-v,i+h*v)),o.cropWidth=m,o.cropHeight=v,o}},sE=({element:e,dTime:t,animation:n})=>{let r=sS[n.name];return r?r({element:e,dTime:t,animation:n}):(console.error("Can not find animation type: "+n.name),{})};var k=x("2SBKn");let sk=iH.types.model("Animation",{delay:0,duration:500,enabled:!0,type:iH.types.enumeration("Type",["enter","exit","loop"]),name:"none",data:iH.types.frozen({})}),sO=(e,t)=>{let n={};for(let r in t)if("number"==typeof e[r]&&"number"==typeof t[r]){let i=t[r]-e[r];0!==i&&(n[r]=i)}return n},sP=iH.types.model("ShapeFilter",{intensity:1}),sT=["temperature","contrast","highlights","shadows","white","black","saturation","vibrance"],sA=sw.named("Shape").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,animations:iH.types.array(sk),blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,filters:iH.types.map(sP),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=>{let t={...e,x:e.x||0,y:e.y||0,filters:Array.isArray(e.filters)?{}:e.filters};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.removable=!1),t}).views(e=>{let t=(0,k.observable)({x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,opacity:e.opacity,color:e.color,fontSize:e.fontSize}),n=(0,k.action)(e=>{Object.assign(t,e)}),r=(0,k.action)(e=>{for(let n in e)"number"==typeof t[n]&&(t[n]=t[n]+e[n])});return{get a(){let{currentTime:i}=e.store;if(n({x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,opacity:e.opacity,color:e.color,fontSize:e.fontSize,cropX:e.cropX,cropY:e.cropY,cropWidth:e.cropWidth,cropHeight:e.cropHeight}),0===i)return t;let o=i-e.page.startTime;if(o>e.page.duration||o<0)return t;let a=e.store.animatedElementsIds;if(a.length&&!a.includes(e.id))return t;let l=e.animations.find(e=>"enter"===e.type),s=l?.enabled&&o<l.delay;s&&n({opacity:0});let u=l?.enabled&&o>=l.delay&&o<=l.delay+l.duration;if(u){let t=o-l.delay,n=sE({element:e,animation:l,dTime:t});r(sO(e,n))}let c=e.animations.find(e=>"exit"===e.type);if(!s&&!u&&c?.enabled&&o>=e.page.duration-c.duration-c.delay&&o<=e.page.duration-c.delay){let t=o-(e.page.duration-c.duration-c.delay),n=sE({element:e,animation:c,dTime:t});r(sO(e,n))}c?.enabled&&o>=e.page.duration-c.delay&&n({opacity:0});let d=e.animations.find(e=>"loop"===e.type);if(d?.enabled){let t=sE({element:e,animation:d,dTime:o});r(sO(e,t))}return t},animated:t=>e.a[t]}}).actions(e=>({setAnimation(t,n){let r=e.animations.find(e=>e.type===t);r?Object.assign(r,n):e.animations.push({type:t,...n})},setFilter(t,n){sT.includes(t)||e.filters.forEach((t,n)=>{sT.includes(n.toString())||e.filters.delete(n.toString())}),null==n?e.filters.delete(t):e.filters.set(t,{intensity:n})}}));var iH=x("58B0H");let sj=sA.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:iH.types.optional(iH.types.union(iH.types.number,iH.types.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5,curveEnabled:!1,curvePower:.5}).preProcessSnapshot(e=>({...e})).actions(e=>({toggleEditMode(t){e._editModeEnabled=t??!e._editModeEnabled,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}));var k=x("2SBKn");let sL=sA.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,stretchEnabled:!1}).extend(e=>{let t=k.observable.box(!1),n=!1;return{views:{get _cropModeEnabled(){return t.get()}},actions:{toggleCropMode(r){let i=r??!t.get();t.set(i),i&&!n?(e.store.history.startTransaction(),n=!0):!i&&n&&(e.store.history.endTransaction(),n=!1)},beforeDestroy(){n&&(e.store.history.endTransaction(),n=!1)}}}}),sR=sL.named("Video").props({type:"video",duration:0,startTime:0,endTime:1,volume:1});var iH=x("58B0H");let sN=sA.named("Line").props({type:"line",width:400,height:10,color:"black",dash:iH.types.array(iH.types.number),startHead:"",endHead:""}).actions(e=>({}));var iH=x("58B0H");let sM=sA.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,stretchEnabled:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:iH.types.map(iH.types.string)}).preProcessSnapshot(e=>({...e,src:e.src||e.svgSource,colorsReplace:Array.isArray(e.colorsReplace)?{}:e.colorsReplace})).actions(e=>({replaceColor(t,n){e.colorsReplace.set(t,n)}}));var iH=x("58B0H");let sI=sA.named("Figure").props({type:"figure",subType:"rect",fill:"rgb(0, 161, 255)",dash:iH.types.array(iH.types.number),strokeWidth:0,stroke:"rgba(98, 197, 255, 1)",cornerRadius:0}),sD=sL.named("Gif").props({type:"gif",duration:0,keepRatio:!0}),sz=(e,t)=>{if(e.children)for(let n of e.children){if(!0===t(n))break;sz(n,t)}},sF=[...Array(20)].map((e,t)=>iH.types.late(()=>sV[t])),sB=iH.types.union({dispatcher:e=>{let t=sU[e.type];if(!t)throw Error(`Unknown element type: "${e.type}"`);return t}},sM,sj,sL,sN,sR,sI,sD,iH.types.late(()=>sH),...sF),sH=sw.named("Group").props({type:"group",children:iH.types.array(sB)}).views(e=>({get draggable(){let t=!0;return sz(e,e=>{e.draggable||(t=!1)}),t},get resizable(){let t=!0;return sz(e,e=>{e.resizable||(t=!1)}),t},get contentEditable(){let t=!0;return sz(e,e=>{e.contentEditable||(t=!1)}),t},get styleEditable(){let t=!0;return sz(e,e=>{e.styleEditable||(t=!1)}),t},get locked(){let t=!0;return sz(e,e=>{e.locked||(t=!1)}),t}})).actions(e=>({set({draggable:t,contentEditable:n,styleEditable:r,resizable:i,...o}){void 0!==t&&sz(e,e=>{e.set({draggable:t})}),void 0!==n&&sz(e,e=>{e.set({contentEditable:n})}),void 0!==r&&sz(e,e=>{e.set({styleEditable:r})}),void 0!==i&&sz(e,e=>{e.set({resizable:i})}),Object.assign(e,o)},addElement(t,{skipSelect:n=!1}={}){let r=sU[t.type];if(!r)return void console.error("Can not find model with type "+t.type);t.children&&t.children.forEach(e=>{e.id=e.id||lm(10)});let i=r.create({id:lm(10),...t});return e.children.push(i),i.selectable&&!n&&e.store.selectElements([i.id]),i},setElementZIndex(t,n){let r=e.children.find(e=>e.id===t);r&&((0,iH.detach)(r),e.children.remove(r),e.children.splice(n,0,r))}})),sV=[],sU={svg:sM,text:sj,image:sL,group:sH,line:sN,video:sR,figure:sI,gif:sD};function sG(e,t){let n=e.type;if(!n)throw Error('You must pass "type" attribute to custom model.');let r=sA.named(n).props(e);t&&(r=t(r)),sU[n]=r,sV.push(r)}let sq={text:iJ,image:ox,svg:ox,line:a$,video:a4,figure:le,group:I(e=>{let{element:t,store:n}=e,{children:r}=t,i=t.selectable||"admin"===n.role;return(0,C.jsx)(rP,{opacity:t.opacity,listening:i,hideInExport:!t.showInExport,children:r.map(t=>(0,E.createElement)(sW,{...e,key:t.id,store:n,element:t}))})}),gif:lh};function s$(e,t){sq[e]=t}let sW=I(e=>{let{element:t,store:n}=e,[r,i]=g(E).useState(!1),o=n.selectedElements.indexOf(t)>=0&&t.selectable,a=t.parent?.type==="group",l=(e=>{let[t,n]=g(E).useState(null);return g(E).useEffect(()=>{let t=setTimeout(()=>{let t=e.page.id,r=nO.stages.find(e=>e.getAttr("pageId")===t);r||console.error("No stage is found for element",e.id),n(r)});return()=>clearTimeout(t)},[e.id]),t})(t),s=l?.findOne("Transformer");g(E).useEffect(()=>{if(l){let e=e=>{let r=e.target.findAncestor(".element",!0),o=n.getElementById(r?.id()),a=o?.top;i(a?.id===t.id)};l.on("mouseover",e);let r=()=>{i(!1)};return l.on("mouseleave",r),()=>{l.off("mouseover",e),l.off("mouseleave",r)}}},[l]);let u=sq[e.element.type];return("text"===e.element.type&&ik.htmlRenderEnabled&&(u=aT),e.element.visible)?u?(0,C.jsxs)(g(E).Fragment,{children:[(0,C.jsx)(u,{...e}),(r||o)&&!a&&(0,C.jsx)(lg,{element:"group"===t.type?{a:((e,t)=>{let n=[];sz(e,e=>{"group"!==e.type&&n.push(e.a)});let r=[];n.forEach(e=>{let t=[{x:0,y:0},{x:0+e.width,y:0},{x:0+e.width,y:0+e.height},{x:0,y:0+e.height}],n=new nO.Transform;n.translate(e.x,e.y),n.rotate(nO.Util.degToRad(e.rotation)),t.forEach(e=>{let t=n.point(e);r.push(t)})});let i=new nO.Transform;i.rotate(-nO.Util.degToRad(t));let o=1/0,a=1/0,l=-1/0,s=-1/0;r.forEach(e=>{let t=i.point(e);o=Math.min(o,t.x),a=Math.min(a,t.y),l=Math.max(l,t.x),s=Math.max(s,t.y)}),i.invert();let u=i.point({x:o,y:a});return{x:u.x,y:u.y,width:l-o,height:s-a,rotation:t}})(t,s?.rotation()||0)}:t})]}):(console.error("Can not find component for "+e.element.type),null):null});var E=x("8NFma");let sY=I(({store:e,page:t,width:n,height:r,scale:i,xPadding:o,yPadding:a,bleed:l})=>{let[s,u]=g(E).useState(!1),[c,d]=g(E).useState([]),h=g(E).useRef(null),f="draw"===e.tool,{strokeWidth:p,strokeColor:m,opacity:v,brushType:y}=e.toolOptions,b="highlighter"===y?.5:v,x=g(E).useCallback(e=>{if(!f||(u(!0),e.cancelBubble=!0,!e.target.getStage()))return;let t=h.current.getRelativePointerPosition();t&&d([{x:t.x,y:t.y}])},[f,i,o,a,l]),w=g(E).useCallback(e=>{if(!f||!s||(e.cancelBubble=!0,!e.target.getStage()))return;let t=h.current.getRelativePointerPosition();t&&d(e=>[...e,{x:t.x,y:t.y}])},[f,s,i,o,a,l]),_=g(E).useCallback(()=>{if(f&&s){if(u(!1),c.length>1)try{let n=function(e,t){if(0===e.length)throw Error("Cannot create SVG from empty path");let n=t.smooth?function(e,t=.5){if(e.length<3)return e;let n=[];n.push(e[0]);for(let t=0;t<e.length-1;t++){let r=e[Math.max(0,t-1)],i=e[t],o=e[t+1],a=e[Math.min(e.length-1,t+2)];for(let e=0;e<10;e++){let t=e/10,l=t*t,s=l*t,u=.5*(2*i.x+(-r.x+o.x)*t+(2*r.x-5*i.x+4*o.x-a.x)*l+(-r.x+3*i.x-3*o.x+a.x)*s),c=.5*(2*i.y+(-r.y+o.y)*t+(2*r.y-5*i.y+4*o.y-a.y)*l+(-r.y+3*i.y-3*o.y+a.y)*s);n.push({x:u,y:c})}}return n.push(e[e.length-1]),n}(e):e,r=function(e){if(0===e.length)return{x:0,y:0,width:0,height:0};let t=e[0].x,n=e[0].y,r=e[0].x,i=e[0].y;for(let o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),i=Math.max(i,o.y);return{x:t,y:n,width:r-t,height:i-n}}(n),i=t.strokeWidth,o=r.x-i,a=r.y-i,l=r.width+2*i,s=r.height+2*i,u=function(e){if(0===e.length)return"";if(1===e.length){let t=e[0];return`M ${t.x},${t.y} L ${t.x+.1},${t.y}`}let t=`M ${e[0].x},${e[0].y}`;for(let n=1;n<e.length-1;n++){let r=e[n],i=e[n+1],o=(r.x+i.x)/2,a=(r.y+i.y)/2;t+=` Q ${r.x},${r.y} ${o},${a}`}if(e.length>1){let n=e[e.length-1];t+=` L ${n.x},${n.y}`}return t}(n.map(e=>({x:e.x-o,y:e.y-a})));return{src:i5(`
|
|
302
|
+
`};async function sm({json:e,elementHook:t,fontEmbedding:n="inline"}){return sg({dom:await sp({json:e,elementHook:t,fontEmbedding:n})})}var iH=x("58B0H");let sv=iH.types.model("Page",{id:iH.types.identifier,children:iH.types.array(iH.types.late(()=>sB)),width:iH.types.optional(iH.types.union(iH.types.number,iH.types.literal("auto")),"auto"),height:iH.types.optional(iH.types.union(iH.types.number,iH.types.literal("auto")),"auto"),background:"white",bleed:0,custom:iH.types.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot(e=>{let t={...e},n={};for(var r in t)"_"!==r[0]&&(n[r]=e[r]);return n}).views(e=>({get store(){return(0,iH.getParentOfType)(e,sx)}})).views(e=>({get startTime(){let t=0;for(let n of e.store.pages){if(n.id===e.id)break;t+=n.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering}})).views(e=>({get computedWidth(){if("auto"===e.width)return e.store.width;return e.width},get computedHeight(){if("auto"===e.height)return e.store.height;return e.height}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify((0,iH.getSnapshot)(e))),_forEachElementUp(t,n){let r=t.map(t=>({id:t,index:e.children.findIndex(e=>e.id===t)}));for(let{index:i}of(r.sort((e,t)=>t.index-e.index),r)){if(-1==i)continue;let r=i<e.children.length-1&&e.children[i+1],o=t.indexOf(r?.id)>=0;i===e.children.length-1||o||n(i)}},_forEachElementDown(t,n){let r=t.map(t=>({id:t,index:e.children.findIndex(e=>e.id===t)}));for(let{index:i}of(r.sort((e,t)=>e.index-t.index),r)){if(-1==i)continue;let r=i>0&&e.children[i-1],o=t.indexOf(r?.id)>=0;0===i||o||n(i)}return!1}})).actions(e=>({clone(t={}){let n=e.toJSON();n.children.forEach(e=>{e.id=lm(10),sz(e,e=>{e.id=lm(10)})});let r={...n,id:lm(10),...t},i=e.store.addPage(r),o=e.store.pages.indexOf(e);return i.setZIndex(o+1),i.select(),i},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:n=!1}={}){let r=sU[t.type];if(!r)return void console.error("Can not find model with type "+t.type);"children"in t&&Array.isArray(t.children)&&sz(t,e=>{e.id=e.id||lm(10)});let i=e.children.reduce((e,n)=>{if("group"===n.type)return Math.max(e,n.children.reduce((e,n)=>{let r=n.name?.match(RegExp(`${t.type}-(\\d+)`));if(r)return Math.max(e,parseInt(r[1],10)||0)},0)||0);{let r=n.name.match(RegExp(`${t.type}-(\\d+)`));if(r)return Math.max(e,parseInt(r[1],10)||0)}return e},0),o=r.create({id:lm(10),name:`${t.type}-${i+1}`,...t});return e.children.push(o),o.selectable&&!n&&e.store.selectElements([o.id]),o},canMoveElementsUp(t){let n=!1;return e._forEachElementUp(t,()=>{n=n||!0}),n},moveElementsUp(t){e._forEachElementUp(t,t=>{let n=e.children[t];(0,iH.detach)(n),e.children.splice(t+1,0,n)})},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(t){let n=[],r=[];e.children.forEach(e=>{t.indexOf(e.id)>=0?n.push(e):r.push(e)}),e.children.replace(r.concat(n))},canMoveElementsDown(t){let n=!1;return e._forEachElementDown(t,()=>{n=n||!0}),n},moveElementsDown(t){e._forEachElementDown(t,t=>{let n=e.children[t];(0,iH.detach)(n),e.children.splice(t-1,0,n)})},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(t){let n=[],r=[];e.children.forEach(e=>{t.indexOf(e.id)>=0?n.push(e):r.push(e)}),e.children.replace(n.concat(r))},setElementZIndex(t,n){let r=e.children.find(e=>e.id===t);r&&((0,iH.detach)(r),e.children.remove(r),e.children.splice(n,0,r))},setSize({width:t,height:n,useMagic:r,softChange:i}){if(r){let r=[],i=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;sz(e,e=>{"group"!==e.type&&(i(e)||r.push(e))});let o=r.length?aR(r):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},a=1/4,l=Math.max(0,Math.max(0,Math.min(o.x,e.computedWidth-o.x-o.width))-e.computedWidth*a),s=Math.max(0,Math.max(0,Math.min(o.y,e.computedHeight-o.y-o.height))-e.computedHeight*a),u=e.computedWidth-2*l,c=e.computedHeight-2*s,d=t/u,h=n/c,f=Math.min(d,h),p=(t-u*f)/2-l*f,g=(n-c*f)/2-s*f;sz(e,e=>{"group"!==e.type&&(i(e)?e.set({x:e.x*f,y:e.y*f,width:e.width*d,height:e.height*h,cropX:0,cropY:0,cropWidth:1,cropHeight:1}):(e.set({x:p+e.x*f,y:g+e.y*f,width:e.width*f,height:e.height*f}),"text"===e.type?e.set({fontSize:e.fontSize*f}):"figure"===e.type&&e.set({strokeWidth:e.strokeWidth*f})))})}i||(e.width=t),i||(e.height=n)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));var iH=x("58B0H");let sy=iH.types.model("Audio",{id:iH.types.identifier,src:"",duration:0,startTime:0,endTime:1,volume:1,delay:0,custom:iH.types.frozen()}).actions(e=>({toJSON:()=>({...(0,iH.getSnapshot)(e)})})).actions(e=>({set(t){Object.assign(e,t)}}));(0,iH.setLivelinessChecking)("ignore");let sb=iH.types.model("Font",{fontFamily:iH.types.string,url:iH.types.optional(iH.types.string,""),styles:iH.types.frozen()}).preProcessSnapshot(e=>({...e,fontFamily:e.fontFamily||e.name})),sx=iH.types.model("Store",{role:"",pages:iH.types.array(sv),fonts:iH.types.array(sb),audios:iH.types.array(sy),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:2,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:iH.types.frozen(),tool:iH.types.optional(iH.types.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:iH.types.optional(iH.types.model({brushType:iH.types.optional(iH.types.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:iH.types.optional(iH.types.number,5),stroke:iH.types.optional(iH.types.string,"#000000"),opacity:iH.types.optional(iH.types.number,1)}),{}),selectedElementsIds:iH.types.array(iH.types.string),animatedElementsIds:iH.types.array(iH.types.string),history:iH.types.optional(ly,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:iH.types.array(iH.types.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{let t=(0,k.computed)(()=>{let t={};return sz({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(let n of e.pages)for(let e of n.children)if(e.id===t)return e}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){let t=[];return sz({children:e.selectedElements},e=>{"group"!==e.type&&t.push(e)}),t},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return e.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let n;return sz({children:e.pages},e=>{if(!n&&t(e))return n=e,!0}),n},getElementById:t=>e._idsMap[t]})).actions(e=>{let t=0,n=null,r=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:i=[],startTime:o=0,currentTime:a=0,endTime:l=e.duration,repeat:s=!1}={}){a&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),o=a),e.animatedElementsIds=(0,iH.cast)(i),e.currentTime=o,e.isPlaying=!0,t=Date.now(),n=l,r=s,requestAnimationFrame(e.seek)},checkActivePage(){for(let t of e.pages){if(e.currentTime>=t.startTime&&e.currentTime<t.startTime+t.duration){e.selectPage(t.id);break}t.duration}},seek(){if(!e.isPlaying)return;let i=Date.now(),o=i-t;t=i,e.currentTime+=o,e.checkActivePage();let a=n||e.duration;e.isPlaying&&e.currentTime<a?requestAnimationFrame(e.seek):e.isPlaying&&r?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,iH.cast)([]),e.checkActivePage()}}}).actions(e=>({__(){e._validated||(lG(e._key,e._forceShowCredit),e._validated=!0)},set(t){Object.assign(e,t)},setUnit({unit:t,dpi:n}){e.unit=t||e.unit,e.dpi=n||e.dpi},setRole(t){e.role=t},setTool(t){e.tool=t},setToolOptions(t){Object.assign(e.toolOptions,t)},addPage(t){let n=sv.create({id:lm(10),...t});return e.pages.push(n),e._activePageId=n.id,n},selectPage(t){e._activePageId=t,1===e._selectedPagesIds.length&&(e._selectedPagesIds=(0,iH.cast)([t]))},selectPages(t){e._selectedPagesIds=(0,iH.cast)(t),1===e._selectedPagesIds.length&&(e._activePageId=e._selectedPagesIds[0])},selectElements(t){let n=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,iH.cast)(n)},toggleBleed(t){e.bleedVisible=t??!e.bleedVisible},toggleRulers(t){e.rulesVisible=t??!e.rulesVisible},openSidePanel(t){e.openedSidePanel!==t&&(e.previousOpenedSidePanel=e.openedSidePanel,e.openedSidePanel=t)},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,n,r){e.pages.forEach(e=>{e.setSize({width:t,height:n,useMagic:r,softChange:!0})}),e.width=t,e.height=n},setPageZIndex(t,n){let r=e.pages.find(e=>e.id===t);r&&((0,iH.detach)(r),e.pages.remove(r),e.pages.splice(n,0,r))},deletePages(t){let n=e.pages.indexOf(e.activePage);t.forEach(t=>{let n=e.pages.find(e=>e.id===t);(0,iH.destroy)(n)});let r=Math.min(e.pages.length-1,n),i=e.pages[r];i&&(e._activePageId=i.id),e.selectedElementsIds=(0,iH.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},groupElements(t,n={}){let r=t.map(t=>e.getElementById(t)),i=r[0].page;if(r.forEach(e=>{e&&(0,iH.detach)(e)}),!r.length)return;let o=i.children.reduce((e,t)=>{if("group"===t.type){let n=t.name.match(/group-(\d+)/);if(n)return Math.max(e,parseInt(n[1],10))}return e},0),a={id:lm(10),name:`group-${o+1}`,children:r,type:"group",...n};return i.children.push(a),e.selectedElementsIds=(0,iH.cast)([a.id]),i.children.find(e=>e.id===a.id)},ungroupElements(t){let n=t.map(t=>e.getElementById(t)),r=[];n.forEach(e=>{if(e&&"group"===e.type){let t=e.page,n=t.children.indexOf(e);e.children.forEach(e=>{r.push(e.id)}),e.children.forEach(e=>{(0,iH.detach)(e),t.children.push(e)}),t.children.splice(n,1)}}),e.selectedElementsIds=(0,iH.cast)(r)},deleteElements(t){let n=[];e.find(e=>(t.includes(e.id)&&n.push(e),!1)),n.forEach(e=>{(0,iH.destroy)(e)}),e.selectedElementsIds=(0,iH.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},on(t,n){if("change"===t){let t=e.toJSON();return(0,iH.onSnapshot)(e,r=>{let i=e.toJSON();lv(t,i)||(t=i,n(i))})}},async _toCanvas({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o,_skipTimeout:a,quickMode:l=!1}={}){let s=t||1;r=r||e.pages[0]?.id;let u=e.pages.find(e=>e.id===r);if(!u)throw Error(`No page for export with id ${r}`);let c=e._elementsPixelRatio;s>e._elementsPixelRatio&&e.setElementsPixelRatio(s),l?u?.set({_forceMount:!0}):u?.set({_exporting:!0});let d=await lY(()=>{let e=nO.stages.filter(e=>e.getAttr("pageId")===r);return 0===e.length?null:e});if(!d)throw u?.set({_forceMount:!1,_exporting:!1}),e.setElementsPixelRatio(c),Error(`Export is failed. Can not find stage for page ${r}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);d.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${r}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);let h=d[0];await e.waitLoading({_skipTimeout:a});let f=h.findOne(".page-container");if(!f)throw e.setElementsPixelRatio(c),u?.set({_forceMount:!1,_exporting:!1}),Error("Export is failed. Canvas was unmounted.");let p=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),f.find(".page-background").forEach(e=>e.shadowEnabled(!1)),f.find(".page-background").forEach(e=>e.strokeEnabled(!1)),f.find(".highlighter").forEach(e=>e.visible(!1));let g=f.findOne(".page-background-group"),m=g.clip();g.clip({x:null,y:null,width:null,height:null});let v=f.findOne(".elements-container"),y=v.clip();v.clip({x:null,y:null,width:null,height:null});let b=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));b.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});let x=f.find(e=>e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),n&&f.find(".page-background").forEach(e=>e.hide());let w=o?u.bleed:0,C=w;!e.bleedVisible&&o||(e.bleedVisible||o?e.bleedVisible&&o?C=0:e.bleedVisible&&!o&&(C=-u.bleed):C=0);let _=document.createElement("canvas");_.width=Math.round((u.computedWidth+2*w)*s),_.height=Math.round((u.computedHeight+2*w)*s);let S=_.getContext("2d");"image/jpeg"===i&&(S.fillStyle="white",S.fillRect(0,0,_.width,_.height));let E=f.scale();f.scale({x:1,y:1});let k=f.toCanvas({x:f.x()-C,y:f.y()-C,width:u.computedWidth+2*w,height:u.computedHeight+2*w,pixelRatio:s});return f.scale(E),S.drawImage(k,0,0,_.width,_.height),nO.Util.releaseCanvas(k),n&&f.find(".page-background").forEach(e=>e.show()),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".page-background").forEach(e=>e.shadowEnabled(!0)),f.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".highlighter").forEach(e=>e.visible(!0)),g.clip(m),v.clip(y),h.position(p),u?.set({_exporting:!1,_forceMount:!1}),await new Promise(e=>setTimeout(e)),e.setElementsPixelRatio(c),_},async toDataURL({mimeType:t,quality:n,...r}={}){let i=await e._toCanvas({mimeType:t,...r}),o=i.toDataURL(t,n);return nO.Util.releaseCanvas(i),o},async toBlob({mimeType:t,quality:n,...r}={}){let i=await e._toCanvas({mimeType:t,...r}),o=await new Promise(e=>{i.toBlob(e,t,n)});return nO.Util.releaseCanvas(i),o},async saveAsImage({fileName:t,...n}={}){let r=n.mimeType||"image/png",i=r.split("/")[1];lb(await e.toDataURL(n),t||"polotno."+i,r)},async _toPDF(t){let n=t.dpi||e.dpi,r=t.parallel||1,i=t.unit||("px"===e.unit?"mm":e.unit),o=t.pixelRatio||1,a=t.pageIds||e.pages.map(e=>e.id),l=e.pages.filter(e=>a.includes(e.id)),s=await (window.jspdf?.jsPDF?Promise.resolve(window.jspdf.jsPDF):lx||(lx=new Promise(e=>{var t=document.createElement("script");t.onload=function(){e(window.jspdf.jsPDF)},t.src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.1/jspdf.umd.min.js",document.head.appendChild(t)}))),u=e=>lq({px:e,unit:i,dpi:n}),c=t.cropMarkSize||0,d=u(c),h=l[0]||{},f=t.includeBleed?h.bleed:0,p=u(h.computedWidth+2*f+2*d),g=u(h.computedHeight+2*f+2*d);var m=new s({unit:i,orientation:p>g?"landscape":"portrait",format:[p,g],compress:!0,putOnlyUsedFonts:!0});m.deletePage(1);let v=((e,t)=>{for(var n=[],r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n})(l,r),y=0;for(let n of v){let r=n.map(async n=>{let r=t.includeBleed?n.bleed:0,i=n.computedWidth+2*r+2*c,l=n.computedHeight+2*r+2*c,s=u(i),d=u(l),h=0,f=o;for(;h<10;){2===(h+=1)&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");let r=await e.toDataURL({...t,pageId:n.id,pixelRatio:f});if(r.length>20)return t.onProgress&&t.onProgress(++y/a.length*.9),{url:r,width:s,height:d,widthPx:i,heightPx:l};f*=.8}});(await Promise.all(r)).forEach(({url:e,width:t,height:n,widthPx:r,heightPx:o})=>{var a;m.addPage([t,n],t>n?"landscape":"portrait");let l=m.getCurrentPageInfo();switch(i){case"pt":a=1;break;case"mm":a=72/25.4;break;case"cm":a=72/2.54;break;case"in":a=72;break;case"px":a=.75;break;case"pc":case"em":a=12;break;case"ex":a=6;break;default:throw"Invalid unit: "+i}if(l.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*a,topRightY:n*a},l.pageContext.artBox={bottomLeftX:u(c+f)*a,bottomLeftY:u(c+f)*a,topRightX:u(r-c-f)*a,topRightY:u(o-c-f)*a},l.pageContext.bleedBox={bottomLeftX:u(c+f)*a,bottomLeftY:u(c+f)*a,topRightX:u(r-c-f)*a,topRightY:u(o-c-f)*a},d){m.setLineWidth(u(1));let e=d+u(f);m.line(e,0,e,d),m.line(0,e,d,e),m.line(t-e,0,t-e,d),m.line(t,e,t-d,e),m.line(0,n-e,d,n-e),m.line(e,n,e,n-d),m.line(t,n-e,t-d,n-e),m.line(t-e,n,t-e,n-d)}m.addImage(e,d,d,t-2*d,n-2*d,void 0,"FAST")})}return m},toPDFDataURL:async t=>(await e._toPDF({mimeType:"image/jpeg",...t})).output("datauristring"),async toGIFDataURL(t={}){let n=t.pixelRatio||1,r=await lw({width:e.width*n,height:e.height*n}),i=1e3/(t.fps||10),o=e.duration/i;for(let t=0;t<o-1;t++){let o=t*i||1;e.setCurrentTime(o);let a=0,l="";for(let t of e.pages)if(a+=t.duration,t.set({_rendering:a>o}),a>o){l=t.id;break}let s=await e._toCanvas({pixelRatio:n,pageId:l,_skipTimeout:!0});r.addFrame(s.getContext("2d"),{delay:i,copy:!0})}for(let t of e.pages)t.set({_rendering:!1});return e.stop(),r.render(),new Promise(e=>{r.on("finished",function(t){var n;(n=new FileReader).onload=function(t){e(t.target.result)},n.readAsDataURL(t)})})},async saveAsGIF({fileName:t,...n}={}){lb(await e.toGIFDataURL(n),t||"polotno.gif")},toHTML:async({elementHook:t}={elementHook:void 0})=>sr({json:e.toJSON(),elementHook:t}),async saveAsHTML({fileName:t,elementHook:n}={}){let r=await e.toHTML({elementHook:n});lb("data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(r))),t||"polotno.html")},async toSVG({elementHook:t,pageId:n,fontEmbedding:r="inline"}={fontEmbedding:"inline"}){let i=e.toJSON();n=n||i.pages[0]?.id;let o=i.pages.find(e=>e.id===n);return sm({json:{...i,pages:o?[o]:[]},elementHook:t,fontEmbedding:r})},async saveAsSVG({fileName:t,elementHook:n,pageId:r,fontEmbedding:i="inline"}={}){let o=await e.toSVG({elementHook:n,pageId:r,fontEmbedding:i});lb("data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(o))),t||"polotno.svg")},async saveAsPDF({fileName:t,...n}={}){(await e._toPDF({mimeType:"image/jpeg",...n})).save(t||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await new Promise(e=>{var t;return t=()=>{r0?setTimeout(e,300):e(!0)},void(0===r3?t():r4.push(t))})},toJSON:()=>({width:e.width,height:e.height,fonts:(0,iH.getSnapshot)(e.fonts),pages:(0,iH.getSnapshot)(e.pages),audios:(0,iH.getSnapshot)(e.audios),unit:e.unit,dpi:e.dpi,custom:e.custom,schemaVersion:e.schemaVersion}),loadJSON(t,n=!1){let r=JSON.parse(JSON.stringify(t)),i=r.schemaVersion||0;i<1&&ik.htmlRenderEnabled&&sz({children:r.pages},e=>{if("text"===e.type){let t=16*e.letterSpacing;e.letterSpacing=t/e.fontSize}}),i<2&&sz({children:r.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t))return;let n=e.filters[t];n&&"number"==typeof n.intensity&&(n.intensity=n.intensity/100)})}),delete r.schemaVersion;let o=e.pages.indexOf(e.activePage),a=(r.pages[o]||r.pages[0])?.id;r._activePageId=a;let l={...(0,iH.getSnapshot)(e)};Object.assign(l,r),n?l.history=e.history.toJSON():l.history={history:[],undoIdx:-1},(0,iH.applySnapshot)(e,l)},clear({keepHistory:t=!1}={}){let n=e.pages.map(e=>e.id);e.deletePages(n),e.custom=null,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,iH.destroy)(e))},addAudio(t){let n=sy.create({id:lm(10),...t});e.audios.push(n)},removeAudio(t){let n=e.audios.find(e=>e.id===t);n&&e.audios.remove(n)},async loadFont(t,n=""){let r=e.fonts.find(e=>e.fontFamily===t)||iu.find(e=>e.fontFamily===t),i=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return r?(r.styles&&(i=r.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),iE(r)):i_(t),Promise.all(i.map(e=>iy(t,e.fontStyle,e.fontWeight,n)))},validate:e=>sx.validate(e,[{path:"",type:sx}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))})),sw=iH.types.model("Node",{id:iH.types.identifier,type:"none",name:"",opacity:1,custom:iH.types.frozen(),visible:!0,selectable:!0,removable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot(e=>{for(var t in e)null===e[t]&&(e[t]=void 0);return e}).postProcessSnapshot(e=>{let t={...e},n={};for(var r in t)"_"!==r[0]&&(n[r]=e[r]);return n}).views(e=>({get locked(){return!e.draggable&&!e.contentEditable&&!e.styleEditable&&!e.resizable},get page(){return(0,iH.getParentOfType)(e,sv)},get store(){return(0,iH.getParentOfType)(e,sx)},get top(){let t=e;for(;;)if(!(0,iH.hasParentOfType)(t,sH))return t;else t=(0,iH.getParentOfType)(t,sH)},get parent(){if((0,iH.hasParentOfType)(e,sH)){let t=(0,iH.getParentOfType)(e,sH);return t&&t.children&&t.children.length,t}if((0,iH.hasParentOfType)(e,sv)){let t=(0,iH.getParentOfType)(e,sv);return t&&t.children&&t.children.length,t}if((0,iH.hasParentOfType)(e,sx)){let t=(0,iH.getParentOfType)(e,sx);return t&&t.pages&&t.pages.length,t}return null},get zIndex(){return e.parent.children.indexOf(e)}})).actions(e=>({toJSON:()=>({...(0,iH.getSnapshot)(e)})})).actions(e=>({clone(t={},{skipSelect:n=!1}={}){let r=JSON.parse(JSON.stringify(e.toJSON()));return t.id=t.id||lm(10),sz(r,e=>{e.id=lm(10)}),Object.assign(r,t),e.page.addElement(r,{skipSelect:n})},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])},setZIndex(t){e.parent.setElementZIndex(e.id,t)},beforeDestroy(){}}));var iH=x("58B0H");let sC={right:{from:{x:-200},to:{x:0}},left:{from:{x:200},to:{x:0}},up:{from:{y:200},to:{y:0}},down:{from:{y:-200},to:{y:0}},"bottom-right":{from:{x:-200,y:-200},to:{x:0,y:0}},"bottom-left":{from:{x:200,y:-200},to:{x:0,y:0}},"top-right":{from:{x:-200,y:200},to:{x:0,y:0}},"top-left":{from:{x:200,y:200},to:{x:0,y:0}}},s_={right:{cropX:-1},left:{cropX:1},up:{cropY:1},down:{cropY:-1}},sS={fade:({dTime:e,element:t,animation:n})=>{let r=e/n.duration;return"enter"===n.type?{opacity:r*t.opacity}:{opacity:(1-r)*t.opacity}},rotate:({dTime:e,element:t,animation:n})=>{let r=n.duration;return function(e,t){let n=function(e){let t=aA(e.rotation||0);return{x:e.x+e.width/2*Math.cos(t)+e.height/2*Math.sin(-t),y:e.y+e.height/2*Math.cos(t)+e.width/2*Math.sin(t)}}(e),r=aA(t),i=n.x+(e.x-n.x)*Math.cos(r)-(e.y-n.y)*Math.sin(r),o=n.y+(e.x-n.x)*Math.sin(r)+(e.y-n.y)*Math.cos(r);return{...e,rotation:e.rotation+t,x:i,y:o}}({x:t.x,y:t.y,width:t.width,height:t.height,rotation:t.rotation},e/r*360)},blink:({dTime:e,element:t,animation:n})=>{let r=n.duration,i=e%r/(r/2);return{opacity:t.opacity*(i<=1?i:2-i)}},bounce:({dTime:e,element:t,animation:n})=>{let r=n.duration,i=n.data.strength??1,o={},a={x:t.x+t.width/3*i,y:t.y+t.height/3*i,width:t.width/3*i,height:t.height/3*i,fontSize:t.fontSize/3*i},l={x:t.x,y:t.y,width:t.width,height:t.height,fontSize:t.fontSize},s=e%r/(r/2),u=s<=1?s:2-s;for(let e in a){let t=a[e],n=l[e]-t;o[e]=t+u*n}return o},move:({dTime:e,element:t,animation:n})=>{let r=sC[n.data.direction]||sC.right,i=n.data.strength??1,o={};for(var a in r.from){let l=r.from[a],s=r.to[a];"exit"===n.type&&(l=r.to[a],s=-r.from[a]),l*=i,s*=i;let u=t[a]+l,c=t[a]+s-u;o[a]=u+e/n.duration*c}return o},zoom:({dTime:e,element:t,animation:n})=>{let r={},i=n.data.direction||"in",o=1+(("in"===i?3/4:5/4)-1)*(n.data.strength??1),a=t.rotation*Math.PI/180,l=Math.cos(a),s=Math.sin(a),u=t.width*(1-o),c=t.height*(1-o),d={x:t.x+(u*l-c*s)/2,y:t.y+(u*s+c*l)/2,width:t.width*o,height:t.height*o,fontSize:t.fontSize*o},h={x:t.x,y:t.y,width:t.width,height:t.height,fontSize:t.fontSize};for(var f in d){let t=d[f],i=h[f];if("exit"===n.type){let e=t;t=i,i=e}let o=i-t;r[f]=t+e/n.duration*o}return r},cameraZoom:({dTime:e,element:t,animation:n})=>{let r,i,o={},a=s_[n.data.direction||"right"]||s_.right,l=n.data.movementStrength??.1,s=n.data.shakeStrength??.015,u=n.data.zoomStrength??.6,c=e/n.duration,d=s*(1-c),h=Math.sin(12*c)*d*.7+Math.sin(8*c)*d*.3;"exit"===n.type&&(u=Math.min(u,1-Math.max(t.cropWidth||1,t.cropHeight||1))),n.type;let f=1-Math.pow(1-c,2),p=t.cropX||0,g=t.cropY||0,m=t.cropWidth||1,v=t.cropHeight||1,y=0,b=0;return a.cropX&&(y=Math.min(a.cropX>0?1-(p+m):p,Math.abs(l))*a.cropX),a.cropY&&(b=Math.min(a.cropY>0?1-(g+v):g,Math.abs(l))*a.cropY),"enter"===n.type?(r=a.cropX?p+y*(1-f):p,i=a.cropY?g+b*(1-f):g):(r=a.cropX?p+y*f:p,i=a.cropY?g+b*f:g),o.cropX=Math.max(0,Math.min(1-m,r+h*m)),o.cropY=Math.max(0,Math.min(1-v,i+h*v)),o.cropWidth=m,o.cropHeight=v,o}},sE=({element:e,dTime:t,animation:n})=>{let r=sS[n.name];return r?r({element:e,dTime:t,animation:n}):(console.error("Can not find animation type: "+n.name),{})};var k=x("2SBKn");let sk=iH.types.model("Animation",{delay:0,duration:500,enabled:!0,type:iH.types.enumeration("Type",["enter","exit","loop"]),name:"none",data:iH.types.frozen({})}),sO=(e,t)=>{let n={};for(let r in t)if("number"==typeof e[r]&&"number"==typeof t[r]){let i=t[r]-e[r];0!==i&&(n[r]=i)}return n},sP=iH.types.model("ShapeFilter",{intensity:1}),sT=["temperature","contrast","highlights","shadows","white","black","saturation","vibrance"],sA=sw.named("Shape").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,animations:iH.types.array(sk),blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,filters:iH.types.map(sP),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=>{let t={...e,x:e.x||0,y:e.y||0,filters:Array.isArray(e.filters)?{}:e.filters};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.removable=!1),t}).views(e=>{let t=(0,k.observable)({x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,opacity:e.opacity,color:e.color,fontSize:e.fontSize}),n=(0,k.action)(e=>{Object.assign(t,e)}),r=(0,k.action)(e=>{for(let n in e)"number"==typeof t[n]&&(t[n]=t[n]+e[n])});return{get a(){let{currentTime:i}=e.store;if(n({x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,opacity:e.opacity,color:e.color,fontSize:e.fontSize,cropX:e.cropX,cropY:e.cropY,cropWidth:e.cropWidth,cropHeight:e.cropHeight}),0===i)return t;let o=i-e.page.startTime;if(o>e.page.duration||o<0)return t;let a=e.store.animatedElementsIds;if(a.length&&!a.includes(e.id))return t;let l=e.animations.find(e=>"enter"===e.type),s=l?.enabled&&o<l.delay;s&&n({opacity:0});let u=l?.enabled&&o>=l.delay&&o<=l.delay+l.duration;if(u){let t=o-l.delay,n=sE({element:e,animation:l,dTime:t});r(sO(e,n))}let c=e.animations.find(e=>"exit"===e.type);if(!s&&!u&&c?.enabled&&o>=e.page.duration-c.duration-c.delay&&o<=e.page.duration-c.delay){let t=o-(e.page.duration-c.duration-c.delay),n=sE({element:e,animation:c,dTime:t});r(sO(e,n))}c?.enabled&&o>=e.page.duration-c.delay&&n({opacity:0});let d=e.animations.find(e=>"loop"===e.type);if(d?.enabled){let t=sE({element:e,animation:d,dTime:o});r(sO(e,t))}return t},animated:t=>e.a[t]}}).actions(e=>({setAnimation(t,n){let r=e.animations.find(e=>e.type===t);r?Object.assign(r,n):e.animations.push({type:t,...n})},setFilter(t,n){sT.includes(t)||e.filters.forEach((t,n)=>{sT.includes(n.toString())||e.filters.delete(n.toString())}),null==n?e.filters.delete(t):e.filters.set(t,{intensity:n})}}));var iH=x("58B0H");let sj=sA.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:iH.types.optional(iH.types.union(iH.types.number,iH.types.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5,curveEnabled:!1,curvePower:.5}).preProcessSnapshot(e=>({...e})).actions(e=>({toggleEditMode(t){e._editModeEnabled=t??!e._editModeEnabled,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}));var k=x("2SBKn");let sL=sA.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,stretchEnabled:!1}).extend(e=>{let t=k.observable.box(!1),n=!1;return{views:{get _cropModeEnabled(){return t.get()}},actions:{toggleCropMode(r){let i=r??!t.get();t.set(i),i&&!n?(e.store.history.startTransaction(),n=!0):!i&&n&&(e.store.history.endTransaction(),n=!1)},beforeDestroy(){n&&(e.store.history.endTransaction(),n=!1)}}}}),sR=sL.named("Video").props({type:"video",duration:0,startTime:0,endTime:1,volume:1});var iH=x("58B0H");let sN=sA.named("Line").props({type:"line",width:400,height:10,color:"black",dash:iH.types.array(iH.types.number),startHead:"",endHead:""}).actions(e=>({}));var iH=x("58B0H");let sM=sA.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,stretchEnabled:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:iH.types.map(iH.types.string)}).preProcessSnapshot(e=>({...e,src:e.src||e.svgSource,colorsReplace:Array.isArray(e.colorsReplace)?{}:e.colorsReplace})).actions(e=>({replaceColor(t,n){e.colorsReplace.set(t,n)}}));var iH=x("58B0H");let sI=sA.named("Figure").props({type:"figure",subType:"rect",fill:"rgb(0, 161, 255)",dash:iH.types.array(iH.types.number),strokeWidth:0,stroke:"rgba(98, 197, 255, 1)",cornerRadius:0}),sD=sL.named("Gif").props({type:"gif",duration:0,keepRatio:!0}),sz=(e,t)=>{if(e.children)for(let n of e.children){if(!0===t(n))break;sz(n,t)}},sF=[...Array(20)].map((e,t)=>iH.types.late(()=>sV[t])),sB=iH.types.union({dispatcher:e=>{let t=sU[e.type];if(!t)throw Error(`Unknown element type: "${e.type}"`);return t}},sM,sj,sL,sN,sR,sI,sD,iH.types.late(()=>sH),...sF),sH=sw.named("Group").props({type:"group",children:iH.types.array(sB)}).views(e=>({get draggable(){let t=!0;return sz(e,e=>{e.draggable||(t=!1)}),t},get resizable(){let t=!0;return sz(e,e=>{e.resizable||(t=!1)}),t},get contentEditable(){let t=!0;return sz(e,e=>{e.contentEditable||(t=!1)}),t},get styleEditable(){let t=!0;return sz(e,e=>{e.styleEditable||(t=!1)}),t},get locked(){let t=!0;return sz(e,e=>{e.locked||(t=!1)}),t}})).actions(e=>({set({draggable:t,contentEditable:n,styleEditable:r,resizable:i,...o}){void 0!==t&&sz(e,e=>{e.set({draggable:t})}),void 0!==n&&sz(e,e=>{e.set({contentEditable:n})}),void 0!==r&&sz(e,e=>{e.set({styleEditable:r})}),void 0!==i&&sz(e,e=>{e.set({resizable:i})}),Object.assign(e,o)},addElement(t,{skipSelect:n=!1}={}){let r=sU[t.type];if(!r)return void console.error("Can not find model with type "+t.type);t.children&&t.children.forEach(e=>{e.id=e.id||lm(10)});let i=r.create({id:lm(10),...t});return e.children.push(i),i.selectable&&!n&&e.store.selectElements([i.id]),i},setElementZIndex(t,n){let r=e.children.find(e=>e.id===t);r&&((0,iH.detach)(r),e.children.remove(r),e.children.splice(n,0,r))}})),sV=[],sU={svg:sM,text:sj,image:sL,group:sH,line:sN,video:sR,figure:sI,gif:sD};function sG(e,t){let n=e.type;if(!n)throw Error('You must pass "type" attribute to custom model.');let r=sA.named(n).props(e);t&&(r=t(r)),sU[n]=r,sV.push(r)}let sq={text:iJ,image:ox,svg:ox,line:a$,video:a4,figure:le,group:I(e=>{let{element:t,store:n}=e,{children:r}=t,i=t.selectable||"admin"===n.role;return(0,C.jsx)(rP,{opacity:t.opacity,listening:i,hideInExport:!t.showInExport,children:r.map(t=>(0,E.createElement)(sW,{...e,key:t.id,store:n,element:t}))})}),gif:lh};function s$(e,t){sq[e]=t}let sW=I(e=>{let{element:t,store:n}=e,[r,i]=g(E).useState(!1),o=n.selectedElements.indexOf(t)>=0&&t.selectable,a=t.parent?.type==="group",l=(e=>{let[t,n]=g(E).useState(null);return g(E).useEffect(()=>{let t=setTimeout(()=>{let t=e.page.id,r=nO.stages.find(e=>e.getAttr("pageId")===t);r||console.error("No stage is found for element",e.id),n(r)});return()=>clearTimeout(t)},[e.id]),t})(t),s=l?.findOne("Transformer");g(E).useEffect(()=>{if(l){let e=e=>{let r=e.target.findAncestor(".element",!0),o=n.getElementById(r?.id()),a=o?.top;i(a?.id===t.id)};l.on("mouseover",e);let r=()=>{i(!1)};return l.on("mouseleave",r),()=>{l.off("mouseover",e),l.off("mouseleave",r)}}},[l]);let u=sq[e.element.type];return("text"===e.element.type&&ik.htmlRenderEnabled&&(u=aT),e.element.visible)?u?(0,C.jsxs)(g(E).Fragment,{children:[(0,C.jsx)(u,{...e}),(r||o)&&!a&&(0,C.jsx)(lg,{element:"group"===t.type?{a:((e,t)=>{let n=[];sz(e,e=>{"group"!==e.type&&n.push(e.a)});let r=[];n.forEach(e=>{let t=[{x:0,y:0},{x:0+e.width,y:0},{x:0+e.width,y:0+e.height},{x:0,y:0+e.height}],n=new nO.Transform;n.translate(e.x,e.y),n.rotate(nO.Util.degToRad(e.rotation)),t.forEach(e=>{let t=n.point(e);r.push(t)})});let i=new nO.Transform;i.rotate(-nO.Util.degToRad(t));let o=1/0,a=1/0,l=-1/0,s=-1/0;r.forEach(e=>{let t=i.point(e);o=Math.min(o,t.x),a=Math.min(a,t.y),l=Math.max(l,t.x),s=Math.max(s,t.y)}),i.invert();let u=i.point({x:o,y:a});return{x:u.x,y:u.y,width:l-o,height:s-a,rotation:t}})(t,s?.rotation()||0)}:t})]}):(console.error("Can not find component for "+e.element.type),null):null});var E=x("8NFma");let sY=I(({store:e,page:t,width:n,height:r,scale:i,xPadding:o,yPadding:a,bleed:l})=>{let[s,u]=g(E).useState(!1),[c,d]=g(E).useState([]),h=g(E).useRef(null),f="draw"===e.tool,{strokeWidth:p,stroke:m,opacity:v,brushType:y}=e.toolOptions,b="highlighter"===y?.5:v,x=g(E).useCallback(e=>{if(!f||(u(!0),e.cancelBubble=!0,!e.target.getStage()))return;let t=h.current.getRelativePointerPosition();t&&d([{x:t.x,y:t.y}])},[f,i,o,a,l]),w=g(E).useCallback(e=>{if(!f||!s||(e.cancelBubble=!0,!e.target.getStage()))return;let t=h.current.getRelativePointerPosition();t&&d(e=>[...e,{x:t.x,y:t.y}])},[f,s,i,o,a,l]),_=g(E).useCallback(()=>{if(f&&s){if(u(!1),c.length>1)try{let n=function(e,t){if(0===e.length)throw Error("Cannot create SVG from empty path");let n=t.smooth?function(e,t=.5){if(e.length<3)return e;let n=[];n.push(e[0]);for(let t=0;t<e.length-1;t++){let r=e[Math.max(0,t-1)],i=e[t],o=e[t+1],a=e[Math.min(e.length-1,t+2)];for(let e=0;e<10;e++){let t=e/10,l=t*t,s=l*t,u=.5*(2*i.x+(-r.x+o.x)*t+(2*r.x-5*i.x+4*o.x-a.x)*l+(-r.x+3*i.x-3*o.x+a.x)*s),c=.5*(2*i.y+(-r.y+o.y)*t+(2*r.y-5*i.y+4*o.y-a.y)*l+(-r.y+3*i.y-3*o.y+a.y)*s);n.push({x:u,y:c})}}return n.push(e[e.length-1]),n}(e):e,r=function(e){if(0===e.length)return{x:0,y:0,width:0,height:0};let t=e[0].x,n=e[0].y,r=e[0].x,i=e[0].y;for(let o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),i=Math.max(i,o.y);return{x:t,y:n,width:r-t,height:i-n}}(n),i=t.strokeWidth,o=r.x-i,a=r.y-i,l=r.width+2*i,s=r.height+2*i,u=function(e){if(0===e.length)return"";if(1===e.length){let t=e[0];return`M ${t.x},${t.y} L ${t.x+.1},${t.y}`}let t=`M ${e[0].x},${e[0].y}`;for(let n=1;n<e.length-1;n++){let r=e[n],i=e[n+1],o=(r.x+i.x)/2,a=(r.y+i.y)/2;t+=` Q ${r.x},${r.y} ${o},${a}`}if(e.length>1){let n=e[e.length-1];t+=` L ${n.x},${n.y}`}return t}(n.map(e=>({x:e.x-o,y:e.y-a})));return{src:i5(`
|
|
303
303
|
<svg xmlns="http://www.w3.org/2000/svg" width="${l}" height="${s}" viewBox="0 0 ${l} ${s}">
|
|
304
304
|
<path
|
|
305
305
|
d="${u}"
|
|
306
|
-
stroke="${t.
|
|
306
|
+
stroke="${t.stroke}"
|
|
307
307
|
stroke-width="${t.strokeWidth}"
|
|
308
308
|
stroke-linecap="round"
|
|
309
309
|
stroke-linejoin="round"
|
|
@@ -311,7 +311,7 @@ https://polotno.com/docs/server-api`,lO={unsplashList:({query:e,page:t=1})=>`${l
|
|
|
311
311
|
opacity="${t.opacity}"
|
|
312
312
|
/>
|
|
313
313
|
</svg>
|
|
314
|
-
`.trim()),x:o,y:a,width:l,height:s}}(c,{
|
|
314
|
+
`.trim()),x:o,y:a,width:l,height:s}}(c,{stroke:m,strokeWidth:p,opacity:b,smooth:!0}),r=e.selectedElementsIds.slice();e.history.transaction(()=>{t.addElement({type:"svg",x:n.x,y:n.y,width:n.width,height:n.height,src:n.src},{skipSelect:!0})}),e.selectElements(r)}catch(e){console.error("Error creating path SVG:",e)}d([])}},[f,s,c,m,p,b,t,e.history,e]),S=g(E).useMemo(()=>c.flatMap(e=>[e.x,e.y]),[c]);return(g(E).useEffect(()=>{if(f&&h.current){let e=h.current.getStage();if(!e)return;let t=p*i;if(t>100||t<4)e.container().style.cursor="crosshair";else{let n=t/2,r=t/2,i=`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${t}" viewBox="0 0 ${t} ${t}">
|
|
315
315
|
<circle cx="${r}" cy="${r}" r="${n-1}" fill="${m}" opacity="${b}" stroke="white" stroke-width="1"/>
|
|
316
316
|
<circle cx="${r}" cy="${r}" r="${n-1}" fill="none" stroke="black" stroke-width="1" opacity="0.3"/>
|
|
317
317
|
</svg>`,o=`data:image/svg+xml;base64,${btoa(i)}`;e.container().style.cursor=`url("${o}") ${r} ${r}, crosshair`}return()=>{e.container()&&(e.container().style.cursor="")}}},[f,m,p,b,i]),f)?(0,C.jsxs)(rP,{ref:h,listening:f,x:o+l*i,y:a+l*i,scaleX:i,scaleY:i,children:[(0,C.jsx)(rA,{x:-(o+l*i)/i,y:-(a+l*i)/i,width:n/i,height:r/i,fill:"transparent",onMouseDown:x,onMouseMove:w,onMouseUp:_,onTouchStart:x,onTouchMove:w,onTouchEnd:_}),c.length>0&&(0,C.jsx)(rj,{points:S,stroke:m,strokeWidth:p,lineCap:"round",lineJoin:"round",opacity:b,tension:.5,listening:!1})]}):null}),sK=nO.DD._drag;window.removeEventListener("mousemove",sK),nO.DD._drag=function(e){(0,k.runInAction)(()=>{sK.call(this,e)})},window.addEventListener("mousemove",nO.DD._drag);let sX=new nO.Group;sX.add(new nO.Rect({width:20,height:20,fill:"white"})),sX.add(new nO.Path({scaleX:20/24,scaleY:20/24,data:"M4.98313549,11.0001422 C5.49589839,10.9914935 5.92501998,11.3703506 5.99116425,11.8666444 L5.99985778,11.9831355 L6.00348884,12.2068855 C6.11245031,15.4321748 8.76323537,17.9999971 11.9999971,17.9999971 C12.1869612,17.9999971 12.3726725,17.9914753 12.5567465,17.9745765 L12.2928932,17.7071068 C11.9023689,17.3165825 11.9023689,16.6834175 12.2928932,16.2928932 C12.6834175,15.9023689 13.3165825,15.9023689 13.7071068,16.2928932 L15.7071068,18.2928932 C16.0976311,18.6834175 16.0976311,19.3165825 15.7071068,19.7071068 L13.7071068,21.7071068 C13.3165825,22.0976311 12.6834175,22.0976311 12.2928932,21.7071068 C11.9023689,21.3165825 11.9023689,20.6834175 12.2928932,20.2928932 L12.6111505,19.9769552 C12.4086045,19.9922816 12.2047796,19.9999971 11.9999971,19.9999971 C7.7687005,19.9999971 4.28886152,16.7094374 4.01666425,12.5105203 L4.00420123,12.2575143 L4.00014222,12.0168645 C3.9908282,11.4646583 4.43092928,11.0094562 4.98313549,11.0001422 Z M11.7071068,2.29289322 C12.0675907,2.65337718 12.0953203,3.22060824 11.7902954,3.61289944 L11.7071068,3.70710678 L11.3891629,4.0230186 C11.5916051,4.00770767 11.7953244,4 12,4 C16.418278,4 20,7.581722 20,12 C20,12.5522847 19.5522847,13 19,13 C18.4477153,13 18,12.5522847 18,12 C18,8.6862915 15.3137085,6 12,6 C11.8129339,6 11.6271216,6.00853145 11.4429483,6.02544919 L11.7071068,6.29289322 C12.0976311,6.68341751 12.0976311,7.31658249 11.7071068,7.70710678 C11.3466228,8.06759074 10.7793918,8.09532028 10.3871006,7.79029539 L10.2928932,7.70710678 L8.29289322,5.70710678 C7.93240926,5.34662282 7.90467972,4.77939176 8.20970461,4.38710056 L8.29289322,4.29289322 L10.2928932,2.29289322 C10.6834175,1.90236893 11.3165825,1.90236893 11.7071068,2.29289322 Z",fill:"black"}));let sZ=sX.toCanvas({pixelRatio:2,width:20,height:20}),sQ={enabledAnchors:["top-left","top-center","top-right","middle-left","bottom-left","bottom-right","bottom-center","middle-right"],borderEnabled:!0,rotateEnabled:!0,rotationSnaps:[0,45,90,135,180,225,270,315],ignoreStroke:!0,flipEnabled:!1,anchorStrokeWidth:2,borderStrokeWidth:2,rotateAnchorOffset:30,anchorStyleFunc:e=>{e.hasName("rotater")&&e.setAttrs({width:20,height:20,cornerRadius:10,offsetX:10,offsetY:10,fillPatternImage:sZ,fillPatternScaleX:.5,fillPatternScaleY:.5,fillPriority:"pattern",fillPatternRepeat:"no-repeat"})}},sJ=e=>{Object.assign(sQ,e)},s0={text:{enabledAnchors:["top-left","top-right","middle-left","bottom-left","bottom-right","middle-right"]},svg:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},gif:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},line:{enabledAnchors:[],borderEnabled:!1,rotateEnabled:!1},image:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},many:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},group:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]}};function s1(e,t){s0[e]=s0[e]||t,Object.assign(s0[e],t)}let s2=e=>(0,C.jsx)(rA,{...e,preventDefault:!1}),s3=({url:e,...t})=>{let[n,r]=g(rz)(e,"anonymous"),i=n?function(e,t,n="scale"){let r,i,o=t.width/t.height;o>=e.width/e.height?(r=e.width,i=e.width/o):(r=e.height*o,i=e.height);let a=0,l=0;return"left-top"===n?(a=0,l=0):"left-middle"===n?(a=0,l=(e.height-i)/2):"left-bottom"===n?(a=0,l=e.height-i):"center-top"===n?(a=(e.width-r)/2,l=0):"center-middle"===n?(a=(e.width-r)/2,l=(e.height-i)/2):"center-bottom"===n?(a=(e.width-r)/2,l=e.height-i):"right-top"===n?(a=e.width-r,l=0):"right-middle"===n?(a=e.width-r,l=(e.height-i)/2):"right-bottom"===n?(a=e.width-r,l=e.height-i):"scale"===n?(a=0,l=0,r=e.width,i=e.height):console.error(Error("Unknown clip position property - "+n)),{cropX:a,cropY:l,cropWidth:r,cropHeight:i}}(n,{width:t.width,height:t.height},"center-middle"):{};return ob(r,e,"page background"),(0,C.jsx)(rL,{image:n,...t,...i})},s4=e=>{let t=rJ({fill:e.fill,a:{width:e.width,height:e.height}});return(0,C.jsx)(rA,{...e,...t})},s8=e=>{let{background:t,scale:n,borderColor:r,...i}=e,o=g(E).useMemo(()=>!!nO.Util.colorToRGBA(t)||rZ(t),[t]),a=g(E).useMemo(()=>{let e=document.createElement("canvas");e.width=60,e.height=60;let t=e.getContext("2d");return t&&(t.fillStyle="black",t.fillRect(30,0,30,30),t.fillRect(0,30,30,30)),e},[]);return(0,C.jsxs)(g(E).Fragment,{children:[(0,C.jsx)(rA,{fillPatternImage:a,...i,opacity:.1,hideInExport:!0}),o?(0,C.jsx)(s4,{fill:t,...i}):(0,C.jsx)(s3,{url:t,...i})]})},s6=I(({selection:e,fill:t="rgba(0, 161, 255, 0.3)",stroke:n="rgb(0, 161, 255)",strokeWidth:r=1})=>e.visible?(0,C.jsx)(rA,{name:"selection",x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),width:Math.abs(e.x1-e.x2),height:Math.abs(e.y1-e.y2),fill:t,stroke:n,strokeWidth:r}):null),s5=I(({x:e,y:t,width:n,height:r,rotation:i,anchor:o,store:a,tagFill:l,textFill:s})=>{let u=aL({x:e,y:t,width:n,height:r,rotation:nO.Util.radToDeg(i)});if(void 0===o)return null;let c=(r/2+70)*Math.cos(i-Math.PI/2),d=(r/2+70)*Math.sin(i-Math.PI/2),h=l$({unit:a.unit,dpi:a.dpi,px:n/a.scale,precious:+("px"!==a.unit)})+" x "+l$({unit:a.unit,dpi:a.dpi,px:r/a.scale,precious:+("px"!==a.unit)})+("px"===a.unit?"":" "+a.unit);return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(rT,{x:(u.minX+u.maxX)/2+c,y:(u.minY+u.maxY)/2+d,offsetX:14,offsetY:14,visible:"rotater"===o,children:[(0,C.jsx)("Tag",{cornerRadius:5,fill:l||"rgb(0, 161, 255)"}),(0,C.jsx)(rR,{align:"center",verticalAlign:"middle",fill:s||"white",padding:8,text:Math.round(nO.Util.radToDeg(i)).toString()+"°"})]}),(0,C.jsxs)(rT,{x:(u.minX+u.maxX)/2,y:u.maxY+20,visible:"rotater"!==o,children:[(0,C.jsx)("Tag",{cornerRadius:5,fill:l||"rgb(0, 161, 255)",pointerDirection:"up",pointerHeight:0,pointerWidth:0}),(0,C.jsx)(rR,{align:"center",verticalAlign:"middle",fill:s||"white",padding:8,text:h})]})]})}),s9=I(({elements:e,store:t})=>{let n=e.filter(e=>e.alwaysOnTop),r=e.filter(e=>!e.alwaysOnTop).concat(n);return(0,C.jsx)(g(E).Fragment,{children:r.map(e=>(0,C.jsx)(sW,{store:t,element:e,onClick:()=>{console.warn("Polotno warning: onClick callback is deprecated. Just stop using it. Polotno will do selection automatically.")}},e.id))})}),s7=null,ue=e=>{s7=e},ut=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),un=atob("cmVk"),ur=atob("djAuOS4y"),ui=e=>(0,C.jsx)(C.Fragment,{children:(0,C.jsxs)(rT,{fill:un,height:200,children:[(0,C.jsx)("Tag",{fill:un}),(0,C.jsx)(rR,{...e,fill:"white",text:ut,height:void 0,padding:10,fontSize:20})]})});var uo=I(({store:e,page:t,width:n,height:r,pageControlsEnabled:i,backColor:o,pageBorderColor:a,activePageBorderColor:l,components:s,bleedColor:u,altCloneEnabled:c,viewportSize:d,selectionRectFill:h,selectionRectStroke:f,selectionRectStrokeWidth:p,snapGuideStroke:m,snapGuideStrokeWidth:v,snapGuideDash:y,transformLabelFill:b,transformLabelTextFill:x,distanceGuideStroke:w,distanceLabelFill:_,distanceLabelTextFill:S})=>{var O;let P=e.bleedVisible?t.bleed:0,T=t.computedWidth+2*P,A=t.computedHeight+2*P,j=(n-T*e.scale)/2,L=(r-A*e.scale)/2,R=g(E).useRef(null),N=g(E).useRef(null),M=g(E).useRef(null),[I,D]=g(E).useState(null),[z,F]=g(E).useState({}),B=(({store:e})=>{let[t,n]=g(E).useState(!1),[r,i]=g(E).useState({x:0,y:0});return{open:g(E).useCallback(e=>{n(!0),i(e)},[]),close:g(E).useCallback(()=>{n(!1)},[]),props:{isOpen:t,offset:r,setIsOpen:n}}})({store:e}),H=e.selectedElements.find(e=>e._cropModeEnabled),V=e.selectedElements.find(e=>e.curveEnabled),U=e.selectedShapes.filter(e=>!e.resizable).length>0,G=e.selectedShapes.filter(e=>!e.draggable).length>0,q=e.selectedElements.filter(e=>!e.visible).length>0;g(E).useLayoutEffect(()=>{if(!R.current)return;let t=R.current.getStage(),n=e.selectedShapes.map(e=>e._cropModeEnabled?null:t.findOne("#"+e.id)).filter(e=>e),r=1===e.selectedElements.length,i=r&&e.selectedElements[0]?.type||"many";s0[i]?(R.current.setAttrs({...sQ,...s0[i]}),"svg"!==i&&"image"!==i&&"gif"!==i||e.selectedElements[0].keepRatio||R.current.setAttrs({enabledAnchors:sQ.enabledAnchors}),"text"===i&&ik.textVerticalResizeEnabled&&R.current.setAttrs({enabledAnchors:s0.text.enabledAnchors?.concat(["bottom-center"])}),"text"===i&&r&&e.selectedElements[0].curveEnabled&&R.current.setAttrs({enabledAnchors:s0.many.enabledAnchors})):R.current.setAttrs(sQ),U&&R.current.enabledAnchors([]),G&&R.current.rotateEnabled(!1),n.find(e=>e?.isDragging())&&n.forEach(e=>{e.isDragging()||e?.startDrag()}),R.current.nodes(n),az(),R.current.getLayer()?.batchDraw()},[e.selectedShapes,H,U,q,G,V]);let $=()=>{let e=R.current;if(!e||!e.nodes().length||!e.isTransforming())return;let t=e.__getNodeRect(),n=e?.getActiveAnchor(),r=e.getStage();F({anchor:n,x:t.x-r.x(),y:t.y-r.y(),rotation:t.rotation,width:t.width,height:t.height})};g(E).useEffect(()=>{R.current?.update(),$()},[e.scale]);let W=(O=()=>({visible:!1,x1:0,y1:0,x2:0,y2:0}),(0,E.useState)(function(){return(0,k.observable)(O(),void 0,{autoBind:!0})})[0]),Y=g(E).useRef(!1),K=iB(),X=(0,k.action)(e=>{if(K)return;Y.current=!1;let t=e.target.findAncestor(".elements-container"),n=e.target.findAncestor("Transformer"),r=e.target.findAncestor(".page-abs-container");if(t||n||r)return;let i=e.target.getStage()?.getPointerPosition();i.x-=e.target.getStage()?.x(),i.y-=e.target.getStage()?.y(),i&&(W.visible=!0,W.x1=i.x,W.y1=i.y,W.x2=i.x,W.y2=i.y,e.target.getStage()?.getPointersPositions().length>=2&&(W.visible=!1))});(({stageRef:e,containerRef:t,viewportSize:n})=>{g(E).useEffect(()=>{let n=t.current?.closest(".polotno-workspace-inner");function r(){if(!e.current)return;let r=t.current?.getBoundingClientRect(),i=n?.getBoundingClientRect(),o=Math.max(0,i.left-r.left-100),a=Math.max(0,i.top-r.top-100);e.current.position({x:-o,y:-a}),e.current.container().style.transform=`translate(${o}px, ${a}px)`}return r(),n.addEventListener("scroll",r),()=>{n.removeEventListener("scroll",r)}},[n.width,n.height])})({stageRef:N,containerRef:M,viewportSize:d}),g(E).useEffect(()=>{let t=(0,k.action)(e=>{if(!W.visible)return;N.current?.setPointersPositions(e);let t=N.current?.getPointerPosition();t?(t.x-=N.current?.x(),t.y-=N.current?.y()):t={x:W.x2,y:W.y2},W.x2=t.x,W.y2=t.y}),n=(0,k.action)(()=>{if(!W.visible||!N.current)return;let t=N.current.findOne(".selection"),n=t?t.getClientRect():{width:0,height:0,x:0,y:0};if(n.width&&n.height){let t=[];N.current.find(".element").forEach(r=>{let i=r.getClientRect(),o=e.getElementById(r.id()),a=o?.draggable,l=o?.selectable;nO.Util.haveIntersection(n,i)&&a&&l&&t.push(o.top.id)});let r=[...new Set(t)];e.selectElements(r)}W.visible=!1,Y.current=!0});return window.addEventListener("mousemove",t),window.addEventListener("touchmove",t),window.addEventListener("mouseup",n),window.addEventListener("touchend",n),()=>{window.removeEventListener("mousemove",t),window.removeEventListener("touchmove",t),window.removeEventListener("mouseup",n),window.removeEventListener("touchend",n)}},[]);let Z=g(E).useRef(!1);g(E).useEffect(()=>{let e,t=M.current?.closest(".polotno-workspace-inner"),n=()=>{Z.current=!0,clearTimeout(e),e=setTimeout(()=>{Z.current=!1},300)};return t.addEventListener("scroll",n),()=>{clearTimeout(e),t.removeEventListener("scroll",n)}},[]);let Q=n=>{if(e.activePage!==t&&t.select(),Z.current||Y.current)return;let r=n.evt.ctrlKey||n.evt.metaKey||n.evt.shiftKey,i=n.target.findAncestor(".elements-container"),o=n.target.findAncestor(".page-abs-container"),a=n.target.findAncestor("Transformer");if(!r&&!i&&!a&&!o&&!W.visible)return void e.selectElements([]);let l=n.target.findAncestor(".element",!0),s=e.getElementById(l?.id()),u=s?.top,c=u?.id,d=e.selectedElementsIds.indexOf(c)>=0,h=n.target.findAncestor(".page-container",!0);c&&r&&!d?e.selectElements(e.selectedElementsIds.concat([c])):c&&r&&d?e.selectElements(e.selectedElementsIds.filter(e=>e!==c)):!c||r||d?h?e.selectPages([t.id]):e.selectPages([]):e.selectElements([c])};!function(e,t,n){let r=g(E).useRef(null);(({stroke:e,strokeWidth:t,dash:n})=>{void 0!==e&&(aN.stroke=e),void 0!==t&&(aN.strokeWidth=t),void 0!==n&&(aN.dash=n)})(n);let i=e=>e.hasName("element")||e.hasName("page-background")||!r.current&&e.hasName("elements-area");function o(t){let n=e.current?.getStage(),r=[],o=[];return n.find(i).forEach(e=>{if(!(t.indexOf(e)>=0)){var n=e.getClientRect({skipShadow:!0,skipStroke:!0});r.push({offset:n.x,node:e,snap:"start"},{offset:n.x+n.width,node:e,snap:"end"},{offset:n.x+n.width/2,node:e,snap:"center"}),o.push({offset:n.y,node:e,snap:"start"},{offset:n.y+n.height,node:e,snap:"end"},{offset:n.y+n.height/2,node:e,snap:"center"})}}),{vertical:r,horizontal:o}}function a(t){let n=e.current?.getLayer(),r=n?.children.find(e=>"line-guides"===e.name());t.forEach(e=>{if("H"===e.orientation){var t=new nO.Line({x:-n.getStage().x(),y:-n.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:aN.stroke,strokeWidth:aN.strokeWidth,name:"guid-line",dash:aN.dash});r?.add(t),n.batchDraw()}else if("V"===e.orientation){var t=new nO.Line({x:-n.getStage().x(),y:-n.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:aN.stroke,strokeWidth:aN.strokeWidth,name:"guid-line",dash:aN.dash});r?.add(t)}})}let l=e=>{let t=e.target.getLayer().children.find(e=>"line-guides"===e.name());t?.destroyChildren();var n=aD(o(e.target.nodes()),function(e){let t=e.__getNodeRect(),n=aL({...t,rotation:nO.Util.radToDeg(t.rotation)}),r=e.getAbsolutePosition();return{vertical:[{guide:n.x,offset:r.x-n.x,snap:"start",nodes:e.nodes()},{guide:n.x+n.width/2,offset:r.x-n.x-n.width/2,snap:"center",nodes:e.nodes()},{guide:n.x+n.width,offset:r.x-n.x-n.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:n.y,offset:r.y-n.y,snap:"start",nodes:e.nodes()},{guide:n.y+n.height/2,offset:r.y-n.y-n.height/2,snap:"center",nodes:e.nodes()},{guide:n.y+n.height,offset:r.y-n.y-n.height,snap:"end",nodes:e.nodes()}]}}(e.target));if(!n.length)return;a(n);let r=e.target.getAbsolutePosition();e.target.nodes().map(e=>e.getAbsolutePosition());let i={...r};n.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":i.x=e.lineGuide+e.offset;break;case"H":i.y=e.lineGuide+e.offset}}});let l=i.x-r.x,s=i.y-r.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{let t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+l,y:t.y+s})})},s=(t,n,r)=>{let i=e.current,l=i.getLayer().children.find(e=>"line-guides"===e.name());if(l?.destroyChildren(),"rotater"===i.getActiveAnchor())return n;let s=aH[i.getActiveAnchor()],u=i.findOne(`.${s}`)?.getAbsolutePosition();if(!u)return n;let c={x:t.x-u.x,y:t.y-u.y},d=function(e,t){let n=aB(e,t)/aB(t,t);return{x:n*t.x,y:n*t.y}}({x:n.x-t.x,y:n.y-t.y},c),h={x:t.x+d.x,y:t.y+d.y};var f=aD(o(i.nodes()),{vertical:[{guide:h.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:h.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!f.length||(a(f),r.ctrlKey||r.metaKey))return n;let p=[];if(f.forEach(e=>{let t=function(e,t,n){if("V"===n.orientation){let r=n.lineGuide;if(1e-4>Math.abs(t.x-e.x))return null;let i=(t.y-e.y)/(t.x-e.x),o=e.y-i*e.x;return{x:r,y:i*r+o}}{let r=n.lineGuide;if(1e-4>Math.abs(t.y-e.y))return null;let i=(t.y-e.y)/(t.x-e.x);return{x:(r-e.y)/i+e.x,y:r}}}(h,u,{orientation:e.orientation,lineGuide:e.lineGuide});t&&p.push(t)}),p.length>0){let e=p[0],t=Math.sqrt(Math.pow(h.x-e.x,2)+Math.pow(h.y-e.y,2));if(p.forEach(n=>{let r=Math.sqrt(Math.pow(h.x-n.x,2)+Math.pow(h.y-n.y,2));r<t&&(t=r,e=n)}),t<10)return e}return h},u=e=>{if(!e.target)return;let t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());n?.destroyChildren(),t.batchDraw()};g(E).useEffect(()=>{e.current&&(e.current.anchorDragBoundFunc(s),e.current.on("dragstart",e=>{setTimeout(()=>{az()})}),e.current.on("dragmove",l),e.current.on("dragend",u),e.current.on("transformend",u),e.current.on("transform",t=>{t.evt.ctrlKey||t.evt.metaKey?e.current?.rotationSnapTolerance(0):e.current?.rotationSnapTolerance(5)}))},[])}(R,0,{stroke:m,strokeWidth:v,dash:y});let J=e.activePage===t,ee=e._selectedPagesIds.includes(t.id),et=s?.PageControls,en=s?.Tooltip,er=s?.ContextMenu,ei=1/e.scale,eo=0/e.scale;return(0,C.jsxs)("div",{ref:M,onDragOver:e=>e.preventDefault(),onDrop:n=>{if(n.preventDefault(),!N.current)return;N.current.setPointersPositions(n);let r=N.current.findOne(".elements-container").getRelativePointerPosition(),i=N.current.getPointerPosition(),o=[...new Set(N.current.getAllIntersections(i).map(e=>e.findAncestor(".element",!0)).filter(Boolean).reverse())].map(t=>e.getElementById(t.id())),a=o[0];s7&&(s7(r,a,{elements:o,page:t}),s7=null)},style:{position:"relative",width:n+"px",height:r+"px",overflow:"hidden"},className:"polotno-page-container"+(J?" active-page":""),children:[(0,C.jsx)(rD,{ref:N,width:Math.min(n,d.width+200),height:Math.min(d.height+200,r),onClick:Q,onTap:Q,onContextMenu:t=>{t.evt.preventDefault();let n=t.target.findAncestor(".element",!0),r=e.getElementById(n?.id()),i=r?.top,o=i?.id;o?e.selectedElementsIds.indexOf(o)>=0||e.selectElements([o]):e.selectElements([]),B.open({x:t.evt.clientX,y:t.evt.clientY})},onMouseDown:X,onMouseMove:n=>{if(!n.evt.altKey&&I)return void D(null);if(!n.evt.altKey)return;let r=n.target.findAncestor(".element",!0),i=r?.id();if(!e.selectedElements[0]||e.selectedElementsIds.includes(i))return;let o=aR(e.selectedShapes),a=aL(i?e.getElementById(i):{x:0,y:0,width:t.computedWidth,height:t.computedHeight,rotation:0}),l=[];o.minX>a.maxX&&l.push({distance:o.minX-a.maxX,box1:o,box2:a,points:[{x:o.minX,y:o.minY+o.height/2},{x:a.maxX,y:o.minY+o.height/2},{x:a.maxX,y:a.minY+a.height/2}]}),o.maxX<a.minX&&l.push({distance:a.minX-o.maxX,box1:o,box2:a,points:[{x:o.maxX,y:o.minY+o.height/2},{x:a.minX,y:o.minY+o.height/2},{x:a.minX,y:a.minY+a.height/2}]}),o.minY>a.maxY&&l.push({box1:o,box2:a,distance:o.minY-a.maxY,points:[{x:o.minX+o.width/2,y:o.minY},{x:o.minX+o.width/2,y:a.maxY},{x:a.minX+a.width/2,y:a.maxY}]}),o.maxY<a.minY&&l.push({box1:o,box2:a,distance:a.minY-o.maxY,points:[{x:o.minX+o.width/2,y:o.maxY},{x:o.minX+o.width/2,y:a.minY},{x:a.minX+a.width/2,y:a.minY}]}),o.minX>=a.minX&&o.maxX<=a.maxX&&o.minY>=a.minY&&o.maxY<=a.maxY&&(l.push({distance:o.minX-a.minX,box1:o,box2:a,points:[{x:o.minX,y:o.minY+o.height/2},{x:a.minX,y:o.minY+o.height/2},{x:a.minX,y:a.minY+a.height/2}]}),l.push({distance:a.maxX-o.maxX,box1:o,box2:a,points:[{x:o.maxX,y:o.minY+o.height/2},{x:a.maxX,y:o.minY+o.height/2},{x:a.maxX,y:a.minY+a.height/2}]}),l.push({box1:o,box2:a,distance:o.minY-a.minY,points:[{x:o.minX+o.width/2,y:o.minY},{x:o.minX+o.width/2,y:a.minY},{x:a.minX+a.width/2,y:a.minY}]}),l.push({box1:o,box2:a,distance:a.maxY-o.maxY,points:[{x:o.minX+o.width/2,y:o.maxY},{x:o.minX+o.width/2,y:a.maxY},{x:a.minX+a.width/2,y:a.maxY}]})),JSON.stringify(I)!==JSON.stringify(l)&&D(l)},onDragStart:t=>{let n=t.target.findAncestor(".element",!0);if(n){let r=e.getElementById(n?.id()),i=r?.top,o=i?.id;!(e.selectedElementsIds.indexOf(o)>=0)&&o&&(e.selectElements([o]),t.target.stopDrag(),t.target.startDrag(t),R.current?.startDrag(t))}I&&D(null)},pageId:t.id,style:{position:"absolute",overflow:"hidden",top:0,left:0},children:(0,C.jsxs)("Layer",{children:[(0,C.jsx)(s2,{width:n,height:r,fill:o}),(0,C.jsx)(rP,{x:j,y:L,scaleX:e.scale,scaleY:e.scale,name:"page-container",children:(0,C.jsxs)(rP,{name:"page-container-2",children:[(0,C.jsx)(rP,{name:"page-background-group",x:P,y:P,children:(0,C.jsx)(s8,{x:-t.bleed,y:-t.bleed,width:t.computedWidth+2*t.bleed,height:t.computedHeight+2*t.bleed,background:t.background,name:"page-background",preventDefault:!1,scale:e.scale})}),(0,C.jsxs)(rP,{x:P,y:P,name:"elements-container",listening:!e.isPlaying,children:[(0,C.jsx)(rA,{name:"elements-area",width:t.computedWidth,height:t.computedHeight,listening:!1}),(0,C.jsx)(s9,{elements:t.children,store:e})]}),(0,C.jsx)(rA,{stroke:u,name:"bleed",strokeWidth:t.bleed,x:t.bleed/2,y:t.bleed/2,width:t.computedWidth+t.bleed,height:t.computedHeight+t.bleed,listening:!1,visible:t.bleed>0&&e.bleedVisible,hideInExport:!0}),lN.value===ur&&(0,C.jsx)(ui,{name:"hit-detection",x:-ei/2-eo,y:-ei/2-eo,width:T+ei+2*eo,height:A+ei+2*eo})]})}),(0,C.jsx)(rj,{name:"workspace-background",points:[0,0,n,0,n,r,0,r,0,0,j,L,j,r-L,n-j,r-L,n-j,L,j,L],listening:!1,closed:!0,fill:o}),(0,C.jsx)(rP,{x:j,y:L,scaleX:e.scale,scaleY:e.scale,children:(0,C.jsx)(rA,{name:"page-highlight",hideInExport:!0,x:-ei/2-eo,y:-ei/2-eo,width:T+ei+2*eo,height:A+ei+2*eo,stroke:ee?l:a,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})}),(0,C.jsxs)(rP,{x:j+P*e.scale,y:L+P*e.scale,scaleX:e.scale,scaleY:e.scale,name:"page-abs-container",children:[(0,C.jsx)(rM,{ref:R,onDragStart:n=>{n.evt?.altKey&&c&&e.selectedElements.forEach(e=>{let n=e.clone({},{skipSelect:!0}),r=t.children.indexOf(e);t.setElementZIndex(n.id,r)}),e.history.startTransaction()},onDragEnd:()=>{e.history.endTransaction()},onTransformStart:()=>{e.history.startTransaction(),D(null)},boundBoxFunc:(e,t)=>{let n=1>Math.abs(t.width)||1>Math.abs(t.height),r=1>Math.abs(e.width)||1>Math.abs(e.height);return n&&!r?e:t},onTransform:e=>{let t=R.current.nodes(),n=t[t.length-1];e.target===n&&$()},onTransformEnd:t=>{F({}),e.history.endTransaction()},visible:!e.isPlaying}),I&&I.map(({points:t,distance:n,box1:r,box2:i},o)=>(0,C.jsxs)(rP,{name:"distances-container",hideInExport:!0,listening:!1,children:[(0,C.jsx)(rA,{...r,stroke:w,strokeWidth:1,strokeScaleEnabled:!1}),(0,C.jsx)(rA,{...i,stroke:w,strokeWidth:1,strokeScaleEnabled:!1}),(0,C.jsx)(rj,{points:[t[0].x,t[0].y,t[1].x,t[1].y],stroke:w,strokeWidth:1,strokeScaleEnabled:!1}),(0,C.jsx)(rj,{points:[t[1].x,t[1].y,t[2].x,t[2].y],stroke:w,strokeWidth:1,strokeScaleEnabled:!1}),(0,C.jsxs)(rT,{x:(t[0].x+t[1].x)/2,y:(t[0].y+t[1].y)/2,offsetY:-10,scaleX:1/e.scale,scaleY:1/e.scale,children:[(0,C.jsx)("Tag",{cornerRadius:5,fill:_,pointerDirection:"down"}),(0,C.jsx)(rR,{align:"center",verticalAlign:"middle",fill:S,padding:5,text:(e=>{let t=parseFloat(lq(e).toFixed(1));switch(e.unit){case"pt":return`${Math.round(t)}pt`;case"mm":return`${t}mm`;case"cm":return`${t}cm`;case"in":return`${t}in`;default:return`${Math.round(t)}px`}})({unit:e.unit,dpi:e.dpi,px:n})})]})]},o)),t._rendering&&(0,C.jsxs)(rP,{children:[(0,C.jsx)(rA,{width:T,height:A,fill:"rgba(255,255,255,0.9)"}),(0,C.jsx)(rR,{text:"Rendering...",fontSize:60,width:T,height:A,align:"center",verticalAlign:"middle"})]}),en&&(0,C.jsx)(en,{components:s,store:e,page:t,stageRef:N}),er&&(0,C.jsx)(rB,{children:(0,C.jsx)(er,{components:s,store:e,...B.props})})]}),(0,C.jsx)(sY,{store:e,page:t,width:n,height:r,scale:e.scale,xPadding:j,yPadding:L,bleed:P}),(0,C.jsx)(s5,{...z,store:e,tagFill:b,textFill:x}),(0,C.jsx)(s6,{selection:W,fill:h,stroke:f,strokeWidth:p}),lR.value&&(0,C.jsx)(rR,{text:"Powered by polotno.com",fontSize:14,fill:"rgba(0,0,0,0.6)",x:n-170,y:r-18,onMouseEnter:e=>{e.target.getStage().container().style.cursor="pointer"},onMouseLeave:e=>{e.target.getStage().container().style.cursor=""},onTouchStart:e=>{e.cancelBubble=!0},onMouseDown:e=>{e.cancelBubble=!0},onClick:()=>{window.open("https://polotno.com")},onTap:()=>{window.open("https://polotno.com")}}),(0,C.jsx)(rP,{name:"line-guides"})]})}),(i??!0)&&et&&(0,C.jsx)(et,{store:e,page:t,xPadding:j,yPadding:L})]})}),E=x("8NFma");let ua=av("div",g(E).forwardRef)`
|
|
@@ -688,7 +688,7 @@ Please read the updated README.md at https://github.com/SortableJS/react-sortabl
|
|
|
688
688
|
align-items: center;
|
|
689
689
|
justify-content: space-between;
|
|
690
690
|
padding: 5px 0;
|
|
691
|
-
`,No=(e,t,n)=>Math.max(t,Math.min(n,e)),Na=I(({store:e})=>{let{brushType:t,strokeWidth:n,
|
|
691
|
+
`,No=(e,t,n)=>Math.max(t,Math.min(n,e)),Na=I(({store:e})=>{let{brushType:t,strokeWidth:n,stroke:r,opacity:i}=e.toolOptions,o="selection"===e.tool,a=t=>{"selection"===t?e.setTool("selection"):(e.setTool("draw"),e.setToolOptions({brushType:t,opacity:"highlighter"===t?.5:1,strokeWidth:"highlighter"===t?30:n||5}))},l=t=>{e.setToolOptions({strokeWidth:t})},s=t=>{e.setToolOptions({opacity:t})};return g(E).useEffect(()=>()=>{e.setTool("selection")},[]),(0,C.jsxs)(Ne,{children:[(0,C.jsxs)(Nt,{children:[(0,C.jsx)(Nn,{children:"Tool"}),(0,C.jsxs)(bL,{fill:!0,style:{padding:"0 5px"},children:[(0,C.jsx)(Nr,{active:o,onClick:()=>a("selection"),icon:(0,C.jsx)(R7,{}),children:"Selection"}),(0,C.jsx)(Nr,{active:!o&&"brush"===t,onClick:()=>a("brush"),icon:(0,C.jsx)(Tx,{}),children:"Brush"}),(0,C.jsx)(Nr,{active:!o&&"highlighter"===t,onClick:()=>a("highlighter"),icon:(0,C.jsx)(R9,{}),children:"Highlighter"})]})]}),(0,C.jsxs)(Nt,{style:{opacity:o?.5:1},children:[(0,C.jsxs)(Ni,{children:[(0,C.jsx)("div",{children:"Stroke Width"}),(0,C.jsx)(bU,{value:n,onValueChange:e=>{Number.isNaN(e)||l(No(e,1,50))},style:{width:"60px"},min:1,max:50,buttonPosition:"none",disabled:o})]}),(0,C.jsx)("div",{style:{padding:"0 13px"},children:(0,C.jsx)(bQ,{min:1,max:50,stepSize:1,value:n,onChange:l,labelRenderer:!1,showTrackFill:!1,disabled:o})})]}),(0,C.jsx)(Nt,{style:{opacity:o?.5:1,pointerEvents:o?"none":"auto"},children:(0,C.jsxs)(Ni,{children:[(0,C.jsx)("div",{style:{lineHeight:"30px"},children:"Color"}),(0,C.jsx)(Oo,{value:r,size:30,onChange:t=>{e.setToolOptions({stroke:t})},store:e})]})}),(0,C.jsxs)(Nt,{style:{opacity:o?.5:1},children:[(0,C.jsxs)(Ni,{children:[(0,C.jsx)("div",{children:"Opacity"}),(0,C.jsx)(bU,{value:Math.round(100*i),onValueChange:e=>{Number.isNaN(e)||s(No(e,0,100)/100)},style:{width:"60px"},min:0,max:100,buttonPosition:"none",disabled:o})]}),(0,C.jsx)("div",{style:{padding:"0 13px"},children:(0,C.jsx)(bQ,{min:0,max:100,stepSize:1,value:Math.round(100*i),onChange:e=>s(e/100),labelRenderer:!1,showTrackFill:!1,disabled:o})})]})]})});var E=x("8NFma");let Nl=Object.keys(a5),Ns=[{width:300,height:300,fill:"lightgray",stroke:"#0c0c0c",strokeWidth:0,url:""}],Nu=[];Nl.forEach(e=>{Ns.forEach(t=>{Nu.push({subType:e,...t})})}),Nu.forEach(e=>{e.url=i5(a9(e))});let Nc=av("div")`
|
|
692
692
|
height: 220px;
|
|
693
693
|
`,Nd=I(({store:e})=>{let t=Math.ceil(Nu.length/4)||1,n=()=>e.selectedElements.map(e=>e.id).join(","),r=g(E).useMemo(n,[]),i=n();return g(E).useEffect(()=>{r!==i&&e.openSidePanel(e.previousOpenedSidePanel)},[r,i]),(0,C.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"auto"},children:[(0,C.jsxs)("div",{style:{display:"flex",justifyContent:"space-between"},children:[(0,C.jsx)("h3",{style:{margin:0,lineHeight:"30px"},children:uj("sidePanel.clipImage")}),(0,C.jsx)(ms,{minimal:!0,icon:(0,C.jsx)(Op,{}),onClick:()=>e.openSidePanel(e.previousOpenedSidePanel)})]}),(0,C.jsx)(Nc,{style:{height:110*t+"px"},children:(0,C.jsx)(TI,{shadowEnabled:!1,rowsNumber:4,images:Nu,getPreview:e=>e.url,isLoading:!1,itemHeight:100,onSelect:async(t,n,r)=>{(r?[r]:e.selectedElements).forEach(e=>{("image"===e.type||"video"===e.type)&&e.contentEditable&&e.set({clipSrc:t.url})})}})})]})});var E=x("8NFma");let Nh=av("div")`
|
|
694
694
|
padding: 10px;
|
package/side-panel/draw-panel.js
CHANGED
|
@@ -3,15 +3,15 @@ import e from"react";import{observer as t}from"mobx-react-lite";import{Button as
|
|
|
3
3
|
display: flex;
|
|
4
4
|
flex-direction: column;
|
|
5
5
|
overflow: auto;
|
|
6
|
-
`,
|
|
6
|
+
`,h=s("div")`
|
|
7
7
|
margin-bottom: 30px;
|
|
8
|
-
`,
|
|
8
|
+
`,d=s("h3")`
|
|
9
9
|
margin-bottom: 15px;
|
|
10
10
|
font-size: 14px;
|
|
11
11
|
font-weight: 600;
|
|
12
12
|
text-transform: uppercase;
|
|
13
13
|
color: var(--bp5-text-color-muted);
|
|
14
|
-
`,
|
|
14
|
+
`,u=s(l)`
|
|
15
15
|
flex: 1;
|
|
16
16
|
${e=>e.active&&"\n background-color: var(--bp5-intent-primary) !important;\n color: white !important;\n "}
|
|
17
17
|
`,E=s("div")`
|
|
@@ -19,4 +19,4 @@ import e from"react";import{observer as t}from"mobx-react-lite";import{Button as
|
|
|
19
19
|
align-items: center;
|
|
20
20
|
justify-content: space-between;
|
|
21
21
|
padding: 5px 0;
|
|
22
|
-
`,g=(e,t,l)=>Math.max(t,Math.min(l,e));export const DrawPanel=t(({store:t})=>{const{brushType:l,strokeWidth:s,
|
|
22
|
+
`,g=(e,t,l)=>Math.max(t,Math.min(l,e));export const DrawPanel=t(({store:t})=>{const{brushType:l,strokeWidth:s,stroke:b,opacity:x}=t.toolOptions,y="selection"===t.tool,v=e=>{"selection"===e?t.setTool("selection"):(t.setTool("draw"),t.setToolOptions({brushType:e,opacity:"highlighter"===e?.5:1,strokeWidth:"highlighter"===e?30:s||5}))},f=e=>{t.setToolOptions({strokeWidth:e})},k=e=>{t.setToolOptions({opacity:e})};return e.useEffect(()=>()=>{t.setTool("selection")},[]),e.createElement(p,null,e.createElement(h,null,e.createElement(d,null,"Tool"),e.createElement(o,{fill:!0,style:{padding:"0 5px"}},e.createElement(u,{active:y,onClick:()=>v("selection"),icon:e.createElement(c,null)},"Selection"),e.createElement(u,{active:!y&&"brush"===l,onClick:()=>v("brush"),icon:e.createElement(r,null)},"Brush"),e.createElement(u,{active:!y&&"highlighter"===l,onClick:()=>v("highlighter"),icon:e.createElement(a,null)},"Highlighter"))),e.createElement(h,{style:{opacity:y?.5:1}},e.createElement(E,null,e.createElement("div",null,"Stroke Width"),e.createElement(i,{value:s,onValueChange:e=>{Number.isNaN(e)||f(g(e,1,50))},style:{width:"60px"},min:1,max:50,buttonPosition:"none",disabled:y})),e.createElement("div",{style:{padding:"0 13px"}},e.createElement(n,{min:1,max:50,stepSize:1,value:s,onChange:f,labelRenderer:!1,showTrackFill:!1,disabled:y}))),e.createElement(h,{style:{opacity:y?.5:1,pointerEvents:y?"none":"auto"}},e.createElement(E,null,e.createElement("div",{style:{lineHeight:"30px"}},"Color"),e.createElement(m,{value:b,size:30,onChange:e=>{t.setToolOptions({stroke:e})},store:t}))),e.createElement(h,{style:{opacity:y?.5:1}},e.createElement(E,null,e.createElement("div",null,"Opacity"),e.createElement(i,{value:Math.round(100*x),onValueChange:e=>{Number.isNaN(e)||k(g(e,0,100)/100)},style:{width:"60px"},min:0,max:100,buttonPosition:"none",disabled:y})),e.createElement("div",{style:{padding:"0 13px"}},e.createElement(n,{min:0,max:100,stepSize:1,value:Math.round(100*x),onChange:e=>k(e/100),labelRenderer:!1,showTrackFill:!1,disabled:y}))))});
|
package/utils/path-to-svg.d.ts
CHANGED
package/utils/path-to-svg.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{svgToURL as t}from"./svg.js";export function smoothPath(t,n=.5){if(t.length<3){return t}const o=[];o.push(t[0]);for(let e=0;e<t.length-1;e++){const n=t[Math.max(0,e-1)],h=t[e],r=t[e+1],x=t[Math.min(t.length-1,e+2)],i=10;for(let t=0;t<i;t++){const e=t/i,y=e*e,s=y*e,a=.5*(2*h.x+(-n.x+r.x)*e+(2*n.x-5*h.x+4*r.x-x.x)*y+(-n.x+3*h.x-3*r.x+x.x)*s),g=.5*(2*h.y+(-n.y+r.y)*e+(2*n.y-5*h.y+4*r.y-x.y)*y+(-n.y+3*h.y-3*r.y+x.y)*s);o.push({x:a,y:g})}}return o.push(t[t.length-1]),o}export function pointsToPathData(t){if(0===t.length){return""}if(1===t.length){const n=t[0];return`M ${n.x},${n.y} L ${n.x+.1},${n.y}`}let n=`M ${t[0].x},${t[0].y}`;for(let o=1;o<t.length-1;o++){const e=t[o],h=t[o+1],r=(e.x+h.x)/2,x=(e.y+h.y)/2;n+=` Q ${e.x},${e.y} ${r},${x}`}if(t.length>1){const o=t[t.length-1];n+=` L ${o.x},${o.y}`}return n}export function getBoundingBox(t){if(0===t.length){return{x:0,y:0,width:0,height:0}}let n=t[0].x,o=t[0].y,e=t[0].x,h=t[0].y;for(const r of t){n=Math.min(n,r.x),o=Math.min(o,r.y),e=Math.max(e,r.x),h=Math.max(h,r.y)}return{x:n,y:o,width:e-n,height:h-o}}export function pathToSVG(n,o){if(0===n.length){throw new Error("Cannot create SVG from empty path")}const e=o.smooth?smoothPath(n):n,h=getBoundingBox(e),r=o.strokeWidth,x=h.x-r,i=h.y-r,y=h.width+2*r,s=h.height+2*r,a=`\n <svg xmlns="http://www.w3.org/2000/svg" width="${y}" height="${s}" viewBox="0 0 ${y} ${s}">\n <path\n d="${pointsToPathData(e.map(t=>({x:t.x-x,y:t.y-i})))}"\n stroke="${o.
|
|
1
|
+
import{svgToURL as t}from"./svg.js";export function smoothPath(t,n=.5){if(t.length<3){return t}const o=[];o.push(t[0]);for(let e=0;e<t.length-1;e++){const n=t[Math.max(0,e-1)],h=t[e],r=t[e+1],x=t[Math.min(t.length-1,e+2)],i=10;for(let t=0;t<i;t++){const e=t/i,y=e*e,s=y*e,a=.5*(2*h.x+(-n.x+r.x)*e+(2*n.x-5*h.x+4*r.x-x.x)*y+(-n.x+3*h.x-3*r.x+x.x)*s),g=.5*(2*h.y+(-n.y+r.y)*e+(2*n.y-5*h.y+4*r.y-x.y)*y+(-n.y+3*h.y-3*r.y+x.y)*s);o.push({x:a,y:g})}}return o.push(t[t.length-1]),o}export function pointsToPathData(t){if(0===t.length){return""}if(1===t.length){const n=t[0];return`M ${n.x},${n.y} L ${n.x+.1},${n.y}`}let n=`M ${t[0].x},${t[0].y}`;for(let o=1;o<t.length-1;o++){const e=t[o],h=t[o+1],r=(e.x+h.x)/2,x=(e.y+h.y)/2;n+=` Q ${e.x},${e.y} ${r},${x}`}if(t.length>1){const o=t[t.length-1];n+=` L ${o.x},${o.y}`}return n}export function getBoundingBox(t){if(0===t.length){return{x:0,y:0,width:0,height:0}}let n=t[0].x,o=t[0].y,e=t[0].x,h=t[0].y;for(const r of t){n=Math.min(n,r.x),o=Math.min(o,r.y),e=Math.max(e,r.x),h=Math.max(h,r.y)}return{x:n,y:o,width:e-n,height:h-o}}export function pathToSVG(n,o){if(0===n.length){throw new Error("Cannot create SVG from empty path")}const e=o.smooth?smoothPath(n):n,h=getBoundingBox(e),r=o.strokeWidth,x=h.x-r,i=h.y-r,y=h.width+2*r,s=h.height+2*r,a=`\n <svg xmlns="http://www.w3.org/2000/svg" width="${y}" height="${s}" viewBox="0 0 ${y} ${s}">\n <path\n d="${pointsToPathData(e.map(t=>({x:t.x-x,y:t.y-i})))}"\n stroke="${o.stroke}"\n stroke-width="${o.strokeWidth}"\n stroke-linecap="round"\n stroke-linejoin="round"\n fill="none"\n opacity="${o.opacity}"\n />\n </svg>\n `.trim();return{src:t(a),x,y:i,width:y,height:s}}
|
package/utils/validate-key.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"mobx";import{getAPI as o}from"./api.js";import{useRemoveBackground as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;export const isCreditVisible=()=>n.value;const i=e.action(()=>{n.value=!0});let r="";export const getKey=()=>r||"";let s="undefined"!=typeof window?window.location.origin:"";const l="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===s&&l&&(s="headless"),"file://"===s&&d&&(s="electron");const c=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${s}" here: https://polotno.com/cabinet`;let p=fetch;export const __=e=>{p=e};export async function isKeyPaid(n){for(let r=0;r<5;r++){try{const i=await p(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"2.30.
|
|
1
|
+
import*as e from"mobx";import{getAPI as o}from"./api.js";import{useRemoveBackground as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;export const isCreditVisible=()=>n.value;const i=e.action(()=>{n.value=!0});let r="";export const getKey=()=>r||"";let s="undefined"!=typeof window?window.location.origin:"";const l="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===s&&l&&(s="headless"),"file://"===s&&d&&(s="electron");const c=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${s}" here: https://polotno.com/cabinet`;let p=fetch;export const __=e=>{p=e};export async function isKeyPaid(n){for(let r=0;r<5;r++){try{const i=await p(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"2.30.2"})});if(e.runInAction(()=>{a.value=i.headers.get("x-api-version")}),!n){return console.warn("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),!1}if(200!==i.status){await new Promise(e=>setTimeout(e,3e3));continue}const r=await i.json();return r.is_valid||console.warn("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),r.is_paid||console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),r.is_domain_valid||console.log(c,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(r.remove_background_enabled),r.is_paid||!1}catch(i){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e,o){r=e,await isKeyPaid(e)&&!o||i()}
|