polotno 2.5.2 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/model/store.d.ts +2 -2
- package/model/store.js +1 -1
- package/package.json +1 -1
- package/polotno-app.d.ts +4 -4
- package/polotno.bundle.js +1 -1
package/model/store.d.ts
CHANGED
|
@@ -472,8 +472,8 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
472
472
|
deleteElements(ids: Array<string>): void;
|
|
473
473
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|
|
474
474
|
_toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, }?: ExportOptions): Promise<HTMLCanvasElement>;
|
|
475
|
-
toDataURL({
|
|
476
|
-
toBlob({
|
|
475
|
+
toDataURL({ mimeType, quality, ...rest }?: ExportOptions): Promise<any>;
|
|
476
|
+
toBlob({ mimeType, quality, ...rest }?: ExportOptions): Promise<unknown>;
|
|
477
477
|
saveAsImage({ fileName, ...exportProps }?: ExportOptions & {
|
|
478
478
|
fileName?: string;
|
|
479
479
|
}): Promise<void>;
|
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&__createBinding(t,e,i);return __setModuleDefault(t,e),t},__rest=this&&this.__rest||function(e,t){var i={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(i[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(a=Object.getOwnPropertySymbols(e);o<a.length;o++)t.indexOf(a[o])<0&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(i[a[o]]=e[a[o]])}return i},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=exports.Store=exports.Font=void 0;const mobx_state_tree_1=require("mobx-state-tree"),history_1=require("./history"),nanoid_1=require("nanoid"),konva_1=__importDefault(require("konva")),download_1=require("../utils/download"),pdf_1=require("../utils/pdf"),gif_lib_1=require("../utils/gif-lib"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),loader_1=require("../utils/loader"),unit_1=require("../utils/unit"),deep_equal_1=require("../utils/deep-equal"),wait_1=require("../utils/wait"),html_1=require("../utils/html"),to_svg_1=require("../utils/to-svg"),page_model_1=require("./page-model"),group_model_1=require("./group-model");function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){const i=exports.Store.create();return(0,validate_key_1.validateKey)(e,t),i}(0,mobx_state_tree_1.setLivelinessChecking)("ignore"),exports.Font=mobx_state_tree_1.types.model("Font",{fontFamily:mobx_state_tree_1.types.string,url:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.string,""),styles:mobx_state_tree_1.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=mobx_state_tree_1.types.model("Store",{role:"",pages:mobx_state_tree_1.types.array(page_model_1.Page),fonts:mobx_state_tree_1.types.array(exports.Font),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",custom:mobx_state_tree_1.types.frozen(),selectedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),animatedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),history:mobx_state_tree_1.types.optional(history_1.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).views((e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map((t=>{for(const 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(0,group_model_1.forEveryChild)({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 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(0,group_model_1.forEveryChild)({children:e.pages},(e=>{if(!i&&t(e))return i=e,!0})),i},getElementById:t=>e.find((e=>e.id===t))}))).actions((e=>{let t=0,i=null,a=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},play({animatedElementsIds:o=[],startTime:n=0,currentTime:s=0,endTime:r=e.duration,repeat:l=!1}={}){s&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),n=s),e.animatedElementsIds=(0,mobx_state_tree_1.cast)(o),e.currentTime=n,e.isPlaying=!0,t=Date.now(),i=r,a=l,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 o=Date.now(),n=o-t;t=o,e.currentTime+=n,e.checkActivePage();const s=i||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&a?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,mobx_state_tree_1.cast)([]),e.checkActivePage()}}})).actions((e=>({set(t){Object.assign(e,t)},setUnit({unit:t,dpi:i}){e.unit=t||e.unit,e.dpi=i||e.dpi},setRole(t){e.role=t},addPage(t){const i=page_model_1.Page.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.pages.push(i),e._activePageId=i.id,i},selectPage(t){e._activePageId=t},selectElements(t){const i=t.map((t=>e.getElementById(t))).sort(((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t))).filter((e=>!!e)).map((e=>e.id));e.selectedElementsIds=(0,mobx_state_tree_1.cast)(i)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,i,a){e.pages.forEach((e=>{e.setSize({width:t,height:i,useMagic:a,softChange:!0})})),e.width=t,e.height=i},setPageZIndex(t,i){const a=e.pages.find((e=>e.id===t));a&&((0,mobx_state_tree_1.detach)(a),e.pages.remove(a),e.pages.splice(i,0,a))},deletePages(t){const i=e.pages.indexOf(e.activePage);t.forEach((t=>{const i=e.pages.find((e=>e.id===t));(0,mobx_state_tree_1.destroy)(i)}));const a=Math.min(e.pages.length-1,i),o=e.pages[a];o&&(e._activePageId=o.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const i=t.map((t=>e.getElementById(t)));i.forEach((e=>{e&&(0,mobx_state_tree_1.detach)(e)}));const a=e.activePage,o={id:(0,nanoid_1.nanoid)(10),children:i,type:"group"};return a.children.push(o),e.selectedElementsIds=(0,mobx_state_tree_1.cast)([o.id]),o},ungroupElements(t){const i=t.map((t=>e.getElementById(t))),a=[];i.forEach((e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach((e=>{a.push(e.id)})),e.children.forEach((e=>{(0,mobx_state_tree_1.detach)(e),t.children.push(e)})),t.children.splice(i,1)}})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(a)},deleteElements(t){t.forEach((t=>{e.pages.forEach((e=>{const i=e.children.find((e=>e.id===t));i&&(0,mobx_state_tree_1.destroy)(i)}))})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,i){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(a=>{const o=e.toJSON();!(0,deep_equal_1.deepEqual)(t,o)&&(t=o,i(o))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:i,pageId:a,mimeType:o,includeBleed:n,_skipTimeout:s}={}){var r;const l=t||1;a=a||(null===(r=e.pages[0])||void 0===r?void 0:r.id);const d=e.pages.find((e=>e.id===a));if(!d)throw new Error(`No page for export with id ${a}`);null==d||d.set({_exporting:!0});const c=await(0,wait_1.waitTillAvailable)((()=>konva_1.default.stages.find((e=>e.getAttr("pageId")===a))));if(!c)throw new Error(`Export is failed. Can not find stage for page ${a}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);const p=!!c.findOne(".page-container"),u=e._elementsPixelRatio;l>e._elementsPixelRatio&&e.setElementsPixelRatio(l),await e.waitLoading({_skipTimeout:s});const g=c.findOne(".page-container");if(!g)throw e.setElementsPixelRatio(u),new Error(`Export is failed. Can't find page container. ${p}`);c.find("Transformer").forEach((e=>e.visible(!1))),g.find(".page-background").forEach((e=>e.shadowEnabled(!1))),g.find(".page-background").forEach((e=>e.strokeEnabled(!1))),g.find(".highlighter").forEach((e=>e.visible(!1)));const _=g.findOne(".page-background-group"),m=_.clip();_.clip({x:null,y:null,width:null,height:null});const f=g.findOne(".elements-container"),h=f.clip();f.clip({x:null,y:null,width:null,height:null});const b=g.find((e=>e.getAttr("hideInExport")));b.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const y=g.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));y.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),i&&g.find(".page-background").forEach((e=>e.hide()));const x=n?d.bleed:0;let v=x;!e.bleedVisible&&n||(e.bleedVisible||n?e.bleedVisible&&n?v=0:e.bleedVisible&&!n&&(v=-d.bleed):v=0);const w=document.createElement("canvas");w.width=Math.round((d.computedWidth+2*x)*l),w.height=Math.round((d.computedHeight+2*x)*l);const E=w.getContext("2d");"image/jpeg"===o&&(E.fillStyle="white",E.fillRect(0,0,w.width,w.height));const P=g.scale();g.scale({x:1,y:1});const I=g.toCanvas({x:g.x()-v,y:g.y()-v,width:d.computedWidth+2*x,height:d.computedHeight+2*x,pixelRatio:l});return g.scale(P),E.drawImage(I,0,0,w.width,w.height),konva_1.default.Util.releaseCanvas(I),i&&g.find(".page-background").forEach((e=>e.show())),b.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),y.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),g.find(".page-background").forEach((e=>e.shadowEnabled(!0))),g.find(".page-background").forEach((e=>e.strokeEnabled(!0))),c.find("Transformer").forEach((e=>e.visible(!0))),g.find(".highlighter").forEach((e=>e.visible(!0))),_.clip(m),f.clip(h),e.setElementsPixelRatio(u),null==d||d.set({_exporting:!1}),w},async toDataURL({pixelRatio:t,ignoreBackground:i,pageId:a,mimeType:o,includeBleed:n,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:i,pageId:a,mimeType:o,includeBleed:n}),l=r.toDataURL(o,s);return konva_1.default.Util.releaseCanvas(r),l},async toBlob({pixelRatio:t,ignoreBackground:i,pageId:a,mimeType:o,includeBleed:n,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:i,pageId:a,mimeType:o,includeBleed:n}),l=new Promise((e=>{r.toBlob(e,o,s)}));return konva_1.default.Util.releaseCanvas(r),l},async saveAsImage(t={}){var{fileName:i}=t,a=__rest(t,["fileName"]);const o=a.mimeType||"image/png",n=o.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(a),i||"polotno."+n,o)},async _toPDF(t){const i=t.dpi||e.dpi,a=t.parallel||1,o=t.unit||("px"===e.unit?"mm":e.unit),n=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,pdf_1.getJsPDF)(),d=e=>(0,unit_1.pxToUnit)({px:e,unit:o,dpi:i}),c=d(t.cropMarkSize||0),p=r[0]||{},u=t.includeBleed?p.bleed:0,g=d(p.computedWidth+2*u)+2*c,_=d(p.computedHeight+2*u)+2*c;var m=new l({unit:o,orientation:g>_?"landscape":"portrait",format:[g,_],compress:!0,putOnlyUsedFonts:!0});m.deletePage(1);const f=((e,t)=>{for(var i=[],a=0;a<e.length;a+=t)i.push(e.slice(a,a+t));return i})(r,a);for(const i of f){const a=i.map((async i=>{const a=t.includeBleed?i.bleed:0,o=d(i.computedWidth+2*a)+2*c,s=d(i.computedHeight+2*a)+2*c;let r=0,l=n;for(;r<10;){r+=1,2===r&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const a=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:i.id,pixelRatio:l}));if(a.length>20)return{url:a,width:o,height:s};l*=.8}}));(await Promise.all(a)).forEach((({url:e,width:t,height:i})=>{m.addPage([t,i],t>i?"landscape":"portrait"),c&&(m.setLineWidth(d(1)),m.line(2*c,0,2*c,c),m.line(0,2*c,c,2*c),m.line(t-2*c,0,t-2*c,c),m.line(t,2*c,t-c,2*c),m.line(0,i-2*c,c,i-2*c),m.line(2*c,i,2*c,i-c),m.line(t,i-2*c,t-c,i-2*c),m.line(t-2*c,i,t-2*c,i-c)),m.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")}))}return m},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toGIFDataURL(t={}){const i=t.pixelRatio||1,a=await(0,gif_lib_1.createGIF)({width:e.width*i,height:e.height*i}),o=1e3/(t.fps||10),n=e.duration/o;for(let t=0;t<n-1;t++){const n=t*o||1;e.setCurrentTime(n);let s=0,r="";for(const t of e.pages)if(s+=t.duration,t.set({_rendering:s>n}),s>n){r=t.id;break}const l=await e._toCanvas({pixelRatio:i,pageId:r,_skipTimeout:!0});a.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const t of e.pages)t.set({_rendering:!1});e.stop(),a.render();return new Promise((e=>{a.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,a=__rest(t,["fileName"]);const o=await e.toGIFDataURL(a);(0,download_1.downloadFile)(o,i||"polotno.gif")},async toHTML({elementHook:t}={elementHook:void 0}){const i=e.toJSON();return(0,html_1.jsonToHTML)({json:i,elementHook:t})},async saveAsHTML({fileName:t}={}){const i=await e.toHTML(),a="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));(0,download_1.downloadFile)(a,t||"polotno.html")},async toSVG(){const t=e.toJSON();return(0,to_svg_1.jsonToSVG)({json:t})},async saveAsSVG({fileName:t}={}){const i=await e.toSVG(),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(i)));(0,download_1.downloadFile)(a,t||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,a=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},a))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise((e=>setTimeout(e,50))),await(0,loader_1.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,mobx_state_tree_1.getSnapshot)(e.fonts),pages:(0,mobx_state_tree_1.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi,custom:e.custom}),loadJSON(t,i=!1){var a;const o=Object.assign({},t),n=e.pages.indexOf(e.activePage);let s=null===(a=o.pages[n]||o.pages[0])||void 0===a?void 0:a.id;o._activePageId=s;const r=Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e));Object.assign(r,o),r.history=i?e.history.toJSON():{history:[],undoIdx:-1},(0,mobx_state_tree_1.applySnapshot)(e,r)},clear({keepHistory:t=!1}={}){const i=e.pages.map((e=>e.id));e.deletePages(i),t||e.history.clear()},addFont(t){e.removeFont(t.fontFamily),e.fonts.push(t),e.loadFont(t.fontFamily)},removeFont(t){e.fonts.filter((e=>e.fontFamily===t)).forEach((e=>(0,mobx_state_tree_1.destroy)(e)))},async loadFont(t){const i=e.fonts.find((e=>e.fontFamily===t))||fonts.globalFonts.find((e=>e.fontFamily===t));i?fonts.injectCustomFont(i):fonts.injectGoogleFont(t),await fonts.loadFont(t)},validate:e=>exports.Store.validate(e,[{path:"",type:exports.Store}]).map((e=>({path:"store"+e.context.map((e=>e.path)).join("."),message:e.message})))}))),exports.createStore=createStore,exports.default=createStore;
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&__createBinding(t,e,i);return __setModuleDefault(t,e),t},__rest=this&&this.__rest||function(e,t){var i={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(i[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(a=Object.getOwnPropertySymbols(e);o<a.length;o++)t.indexOf(a[o])<0&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(i[a[o]]=e[a[o]])}return i},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=exports.Store=exports.Font=void 0;const mobx_state_tree_1=require("mobx-state-tree"),history_1=require("./history"),nanoid_1=require("nanoid"),konva_1=__importDefault(require("konva")),download_1=require("../utils/download"),pdf_1=require("../utils/pdf"),gif_lib_1=require("../utils/gif-lib"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),loader_1=require("../utils/loader"),unit_1=require("../utils/unit"),deep_equal_1=require("../utils/deep-equal"),wait_1=require("../utils/wait"),html_1=require("../utils/html"),to_svg_1=require("../utils/to-svg"),page_model_1=require("./page-model"),group_model_1=require("./group-model");function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){const i=exports.Store.create();return(0,validate_key_1.validateKey)(e,t),i}(0,mobx_state_tree_1.setLivelinessChecking)("ignore"),exports.Font=mobx_state_tree_1.types.model("Font",{fontFamily:mobx_state_tree_1.types.string,url:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.string,""),styles:mobx_state_tree_1.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=mobx_state_tree_1.types.model("Store",{role:"",pages:mobx_state_tree_1.types.array(page_model_1.Page),fonts:mobx_state_tree_1.types.array(exports.Font),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",custom:mobx_state_tree_1.types.frozen(),selectedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),animatedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),history:mobx_state_tree_1.types.optional(history_1.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).views((e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map((t=>{for(const 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(0,group_model_1.forEveryChild)({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 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(0,group_model_1.forEveryChild)({children:e.pages},(e=>{if(!i&&t(e))return i=e,!0})),i},getElementById:t=>e.find((e=>e.id===t))}))).actions((e=>{let t=0,i=null,a=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},play({animatedElementsIds:o=[],startTime:n=0,currentTime:s=0,endTime:r=e.duration,repeat:l=!1}={}){s&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),n=s),e.animatedElementsIds=(0,mobx_state_tree_1.cast)(o),e.currentTime=n,e.isPlaying=!0,t=Date.now(),i=r,a=l,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 o=Date.now(),n=o-t;t=o,e.currentTime+=n,e.checkActivePage();const s=i||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&a?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,mobx_state_tree_1.cast)([]),e.checkActivePage()}}})).actions((e=>({set(t){Object.assign(e,t)},setUnit({unit:t,dpi:i}){e.unit=t||e.unit,e.dpi=i||e.dpi},setRole(t){e.role=t},addPage(t){const i=page_model_1.Page.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.pages.push(i),e._activePageId=i.id,i},selectPage(t){e._activePageId=t},selectElements(t){const i=t.map((t=>e.getElementById(t))).sort(((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t))).filter((e=>!!e)).map((e=>e.id));e.selectedElementsIds=(0,mobx_state_tree_1.cast)(i)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,i,a){e.pages.forEach((e=>{e.setSize({width:t,height:i,useMagic:a,softChange:!0})})),e.width=t,e.height=i},setPageZIndex(t,i){const a=e.pages.find((e=>e.id===t));a&&((0,mobx_state_tree_1.detach)(a),e.pages.remove(a),e.pages.splice(i,0,a))},deletePages(t){const i=e.pages.indexOf(e.activePage);t.forEach((t=>{const i=e.pages.find((e=>e.id===t));(0,mobx_state_tree_1.destroy)(i)}));const a=Math.min(e.pages.length-1,i),o=e.pages[a];o&&(e._activePageId=o.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const i=t.map((t=>e.getElementById(t)));i.forEach((e=>{e&&(0,mobx_state_tree_1.detach)(e)}));const a=e.activePage,o={id:(0,nanoid_1.nanoid)(10),children:i,type:"group"};return a.children.push(o),e.selectedElementsIds=(0,mobx_state_tree_1.cast)([o.id]),o},ungroupElements(t){const i=t.map((t=>e.getElementById(t))),a=[];i.forEach((e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach((e=>{a.push(e.id)})),e.children.forEach((e=>{(0,mobx_state_tree_1.detach)(e),t.children.push(e)})),t.children.splice(i,1)}})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(a)},deleteElements(t){t.forEach((t=>{e.pages.forEach((e=>{const i=e.children.find((e=>e.id===t));i&&(0,mobx_state_tree_1.destroy)(i)}))})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,i){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(a=>{const o=e.toJSON();!(0,deep_equal_1.deepEqual)(t,o)&&(t=o,i(o))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:i,pageId:a,mimeType:o,includeBleed:n,_skipTimeout:s}={}){var r;const l=t||1;a=a||(null===(r=e.pages[0])||void 0===r?void 0:r.id);const d=e.pages.find((e=>e.id===a));if(!d)throw new Error(`No page for export with id ${a}`);null==d||d.set({_exporting:!0});const c=await(0,wait_1.waitTillAvailable)((()=>konva_1.default.stages.find((e=>e.getAttr("pageId")===a))));if(!c)throw new Error(`Export is failed. Can not find stage for page ${a}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);const p=!!c.findOne(".page-container"),u=e._elementsPixelRatio;l>e._elementsPixelRatio&&e.setElementsPixelRatio(l),await e.waitLoading({_skipTimeout:s});const _=c.findOne(".page-container");if(!_)throw e.setElementsPixelRatio(u),new Error(`Export is failed. Can't find page container. ${p}`);c.find("Transformer").forEach((e=>e.visible(!1))),_.find(".page-background").forEach((e=>e.shadowEnabled(!1))),_.find(".page-background").forEach((e=>e.strokeEnabled(!1))),_.find(".highlighter").forEach((e=>e.visible(!1)));const g=_.findOne(".page-background-group"),m=g.clip();g.clip({x:null,y:null,width:null,height:null});const f=_.findOne(".elements-container"),h=f.clip();f.clip({x:null,y:null,width:null,height:null});const b=_.find((e=>e.getAttr("hideInExport")));b.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const y=_.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));y.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),i&&_.find(".page-background").forEach((e=>e.hide()));const x=n?d.bleed:0;let v=x;!e.bleedVisible&&n||(e.bleedVisible||n?e.bleedVisible&&n?v=0:e.bleedVisible&&!n&&(v=-d.bleed):v=0);const w=document.createElement("canvas");w.width=Math.round((d.computedWidth+2*x)*l),w.height=Math.round((d.computedHeight+2*x)*l);const E=w.getContext("2d");"image/jpeg"===o&&(E.fillStyle="white",E.fillRect(0,0,w.width,w.height));const P=_.scale();_.scale({x:1,y:1});const O=_.toCanvas({x:_.x()-v,y:_.y()-v,width:d.computedWidth+2*x,height:d.computedHeight+2*x,pixelRatio:l});return _.scale(P),E.drawImage(O,0,0,w.width,w.height),konva_1.default.Util.releaseCanvas(O),i&&_.find(".page-background").forEach((e=>e.show())),b.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),y.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),_.find(".page-background").forEach((e=>e.shadowEnabled(!0))),_.find(".page-background").forEach((e=>e.strokeEnabled(!0))),c.find("Transformer").forEach((e=>e.visible(!0))),_.find(".highlighter").forEach((e=>e.visible(!0))),g.clip(m),f.clip(h),e.setElementsPixelRatio(u),null==d||d.set({_exporting:!1}),w},async toDataURL(t={}){var{mimeType:i,quality:a}=t,o=__rest(t,["mimeType","quality"]);const n=await e._toCanvas(Object.assign({mimeType:i},o)),s=n.toDataURL(i,a);return konva_1.default.Util.releaseCanvas(n),s},async toBlob(t={}){var{mimeType:i,quality:a}=t,o=__rest(t,["mimeType","quality"]);const n=await e._toCanvas(Object.assign({mimeType:i},o)),s=new Promise((e=>{n.toBlob(e,i,a)}));return konva_1.default.Util.releaseCanvas(n),s},async saveAsImage(t={}){var{fileName:i}=t,a=__rest(t,["fileName"]);const o=a.mimeType||"image/png",n=o.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(a),i||"polotno."+n,o)},async _toPDF(t){const i=t.dpi||e.dpi,a=t.parallel||1,o=t.unit||("px"===e.unit?"mm":e.unit),n=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,pdf_1.getJsPDF)(),d=e=>(0,unit_1.pxToUnit)({px:e,unit:o,dpi:i}),c=d(t.cropMarkSize||0),p=r[0]||{},u=t.includeBleed?p.bleed:0,_=d(p.computedWidth+2*u)+2*c,g=d(p.computedHeight+2*u)+2*c;var m=new l({unit:o,orientation:_>g?"landscape":"portrait",format:[_,g],compress:!0,putOnlyUsedFonts:!0});m.deletePage(1);const f=((e,t)=>{for(var i=[],a=0;a<e.length;a+=t)i.push(e.slice(a,a+t));return i})(r,a);for(const i of f){const a=i.map((async i=>{const a=t.includeBleed?i.bleed:0,o=d(i.computedWidth+2*a)+2*c,s=d(i.computedHeight+2*a)+2*c;let r=0,l=n;for(;r<10;){r+=1,2===r&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const a=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:i.id,pixelRatio:l}));if(a.length>20)return{url:a,width:o,height:s};l*=.8}}));(await Promise.all(a)).forEach((({url:e,width:t,height:i})=>{m.addPage([t,i],t>i?"landscape":"portrait"),c&&(m.setLineWidth(d(1)),m.line(2*c,0,2*c,c),m.line(0,2*c,c,2*c),m.line(t-2*c,0,t-2*c,c),m.line(t,2*c,t-c,2*c),m.line(0,i-2*c,c,i-2*c),m.line(2*c,i,2*c,i-c),m.line(t,i-2*c,t-c,i-2*c),m.line(t-2*c,i,t-2*c,i-c)),m.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")}))}return m},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toGIFDataURL(t={}){const i=t.pixelRatio||1,a=await(0,gif_lib_1.createGIF)({width:e.width*i,height:e.height*i}),o=1e3/(t.fps||10),n=e.duration/o;for(let t=0;t<n-1;t++){const n=t*o||1;e.setCurrentTime(n);let s=0,r="";for(const t of e.pages)if(s+=t.duration,t.set({_rendering:s>n}),s>n){r=t.id;break}const l=await e._toCanvas({pixelRatio:i,pageId:r,_skipTimeout:!0});a.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const t of e.pages)t.set({_rendering:!1});e.stop(),a.render();return new Promise((e=>{a.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,a=__rest(t,["fileName"]);const o=await e.toGIFDataURL(a);(0,download_1.downloadFile)(o,i||"polotno.gif")},async toHTML({elementHook:t}={elementHook:void 0}){const i=e.toJSON();return(0,html_1.jsonToHTML)({json:i,elementHook:t})},async saveAsHTML({fileName:t}={}){const i=await e.toHTML(),a="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));(0,download_1.downloadFile)(a,t||"polotno.html")},async toSVG(){const t=e.toJSON();return(0,to_svg_1.jsonToSVG)({json:t})},async saveAsSVG({fileName:t}={}){const i=await e.toSVG(),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(i)));(0,download_1.downloadFile)(a,t||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,a=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},a))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise((e=>setTimeout(e,50))),await(0,loader_1.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,mobx_state_tree_1.getSnapshot)(e.fonts),pages:(0,mobx_state_tree_1.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi,custom:e.custom}),loadJSON(t,i=!1){var a;const o=Object.assign({},t),n=e.pages.indexOf(e.activePage);let s=null===(a=o.pages[n]||o.pages[0])||void 0===a?void 0:a.id;o._activePageId=s;const r=Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e));Object.assign(r,o),r.history=i?e.history.toJSON():{history:[],undoIdx:-1},(0,mobx_state_tree_1.applySnapshot)(e,r)},clear({keepHistory:t=!1}={}){const i=e.pages.map((e=>e.id));e.deletePages(i),t||e.history.clear()},addFont(t){e.removeFont(t.fontFamily),e.fonts.push(t),e.loadFont(t.fontFamily)},removeFont(t){e.fonts.filter((e=>e.fontFamily===t)).forEach((e=>(0,mobx_state_tree_1.destroy)(e)))},async loadFont(t){const i=e.fonts.find((e=>e.fontFamily===t))||fonts.globalFonts.find((e=>e.fontFamily===t));i?fonts.injectCustomFont(i):fonts.injectGoogleFont(t),await fonts.loadFont(t)},validate:e=>exports.Store.validate(e,[{path:"",type:exports.Store}]).map((e=>({path:"store"+e.context.map((e=>e.path)).join("."),message:e.message})))}))),exports.createStore=createStore,exports.default=createStore;
|
package/package.json
CHANGED
package/polotno-app.d.ts
CHANGED
|
@@ -534,8 +534,8 @@ export declare function createPolotnoApp({ container, key, showCredit, sections
|
|
|
534
534
|
deleteElements(ids: string[]): void;
|
|
535
535
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|
|
536
536
|
_toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, }?: import("./model/store").ExportOptions): Promise<HTMLCanvasElement>;
|
|
537
|
-
toDataURL({
|
|
538
|
-
toBlob({
|
|
537
|
+
toDataURL({ mimeType, quality, ...rest }?: import("./model/store").ExportOptions): Promise<any>;
|
|
538
|
+
toBlob({ mimeType, quality, ...rest }?: import("./model/store").ExportOptions): Promise<unknown>;
|
|
539
539
|
saveAsImage({ fileName, ...exportProps }?: import("./model/store").ExportOptions & {
|
|
540
540
|
fileName?: string;
|
|
541
541
|
}): Promise<void>;
|
|
@@ -1032,8 +1032,8 @@ export declare function createPolotnoApp({ container, key, showCredit, sections
|
|
|
1032
1032
|
deleteElements(ids: string[]): void;
|
|
1033
1033
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|
|
1034
1034
|
_toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, }?: import("./model/store").ExportOptions): Promise<HTMLCanvasElement>;
|
|
1035
|
-
toDataURL({
|
|
1036
|
-
toBlob({
|
|
1035
|
+
toDataURL({ mimeType, quality, ...rest }?: import("./model/store").ExportOptions): Promise<any>;
|
|
1036
|
+
toBlob({ mimeType, quality, ...rest }?: import("./model/store").ExportOptions): Promise<unknown>;
|
|
1037
1037
|
saveAsImage({ fileName, ...exportProps }?: import("./model/store").ExportOptions & {
|
|
1038
1038
|
fileName?: string;
|
|
1039
1039
|
}): Promise<void>;
|
package/polotno.bundle.js
CHANGED
|
@@ -148,7 +148,7 @@ For more info see: https://github.com/konvajs/react-konva/issues/194
|
|
|
148
148
|
`,a2=[.1,.2,.5,1,2,5,10,20,25,50,100,200,500,1e3,2e3,5e3,1e4],a3=e=>a2.find(t=>e(t)>30)||1e4,a5=A(({store:e,width:t,height:n})=>{let r=u(b).useRef(null);if(!e.activePage)return null;let i=e.activePage;e.bleedVisible&&i.bleed;let o=i.computedWidth*e.scale,a=i.computedHeight*e.scale,l=(t-o)/2,s=a3(t=>aL({unitVal:t,dpi:e.dpi,unit:e.unit})*e.scale),c=aL({unitVal:s,dpi:e.dpi,unit:e.unit})*e.scale,d=Math.round(o/c)+1,h=Math.round(a/c)+1,f=oH(e.selectedShapes);return(0,m.jsxs)(aZ,{ref:r,className:"polotno-rulers",children:[(0,m.jsxs)(aQ,{style:{width:t+"px"},className:"polotno-x-ruler",children:[[...Array(d)].map((t,n)=>(0,m.jsx)(a0,{style:{left:l+n*c+"px",width:c+"px"},children:"px"===e.unit||s>=1?Math.round(s*n):(s*n).toFixed(1)},n)),!!e.selectedShapes.length&&(0,m.jsx)("div",{style:{position:"absolute",left:l+f.x*e.scale+"px",height:"14px",width:f.width*e.scale,backgroundColor:"rgba(0,0,0,0.15)"}})]}),e.pages.map((t,r)=>{let i=(n-t.computedHeight*e.scale)/2;return(0,m.jsxs)(aJ,{style:{height:n+"px"},className:"polotno-y-ruler",children:[[...Array(h)].map((t,n)=>(0,m.jsx)(a1,{style:{top:i+n*c-14+"px",width:c+"px"},children:"px"===e.unit||s>=1?Math.round(s*n):(s*n).toFixed(1)},n)),e.selectedShapes[0]?.page===t&&(0,m.jsx)("div",{style:{position:"absolute",top:i+f.y*e.scale-14+"px",width:"14px",height:f.height*e.scale,backgroundColor:"rgba(0,0,0,0.15)"}})]},t.id)})]})});var iV=(p("58B0H"),p("58B0H"));let a6=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>((t&=63)<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var iV=(p("58B0H"),p("58B0H"));let a4=function(e,t){if(e===t)return!0;if("object"!=typeof e||null==e||"object"!=typeof t||null==t||Object.keys(e).length!=Object.keys(t).length)return!1;for(var n in e)if(!t.hasOwnProperty(n)||!a4(e[n],t[n]))return!1;return!0};Object.assign(iV.types);let a8=(0,iV.types).model("UndoManager",{history:(0,iV.types).array((0,iV.types).frozen()),undoIdx:-1,targetPath:""}).views(e=>({get canUndo(){return e.undoIdx>0},get canRedo(){return e.undoIdx<e.history.length-1}})).actions(e=>{let t,n;let r=!1,i=null,o=0,a=0,l=()=>a>0;function s(){let e=(0,iV.getSnapshot)(t);return{pages:e.pages,width:e.width,height:e.height}}function u(e){a4(t.pages.map(e=>e.id),e.pages.map(e=>e.id))?t.pages.forEach((t,n)=>{(0,iV.applySnapshot)(t,e.pages[n])}):(0,iV.applySnapshot)(t.pages,e.pages),t.setSize(e.width,e.height)}return{startTransaction(){a++},endTransaction(e){a--,e||this.requestAddState(s())},async ignore(t,n=!1,r=!1){r&&await new Promise(e=>setTimeout(e,10)),o&&e.addUndoState();let i=l();e.startTransaction();let s=a;try{await t()}catch(e){setTimeout(()=>{throw e})}let u=s!==a;e.endTransaction(!u),n||i||e.replaceState(),u||(clearTimeout(o),o=0)},async transaction(t){await e.ignore(t,!0),this.addUndoState()},requestAddState(e){if(i=e,!o&&!l()){if(r){r=!1;return}o=setTimeout(()=>{clearTimeout(o=0),l()||this.addUndoState()},100)}},addUndoState(){if(r){r=!1;return}let t=e.history[e.undoIdx];a4(i,t)||(clearTimeout(o),o=0,e.history.splice(e.undoIdx+1),e.history.push(i),e.undoIdx=e.history.length-1)},afterCreate(){if(!(t=(0,iV.resolvePath)(e,"..")))throw Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment");n=(0,iV.onSnapshot)(t,()=>{this.requestAddState(s())}),0===e.history.length&&this.requestAddState(s())},clear(){clearTimeout(o),o=0,e.history.splice(0,e.history.length),e.undoIdx=-1,e.addUndoState(s())},beforeDestroy(){n()},undo(){if(o&&this.addUndoState(),!e.canUndo){console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.");return}e.undoIdx--,r=!0,u(e.history[e.undoIdx])},redo(){if(o&&this.addUndoState(),!e.canRedo){console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.");return}e.undoIdx++,r=!0,u(e.history[e.undoIdx])},replaceState(){e.history[e.undoIdx]=s()}}});async function a9(e,t){let n=await (await fetch(e)).blob(),r=document.createElement("a"),i=URL.createObjectURL(n);r.href=i,r.download=t,document.body.appendChild(r),r.click(),setTimeout(function(){document.body.removeChild(r),window.URL.revokeObjectURL(i)},0)}async function a7({width:e,height:t}){return new(await (window.GIF?Promise.resolve(window.GIF):new Promise(e=>{var t=document.createElement("script");t.onload=function(){e(window.GIF)},t.src="https://cdnjs.cloudflare.com/ajax/libs/gif.js/0.2.0/gif.js",document.head.appendChild(t)})))({workers:4,width:e,height:t,workerScript:URL.createObjectURL(new Blob([`// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js
|
|
149
149
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){var NeuQuant=require("./TypedNeuQuant.js");var LZWEncoder=require("./LZWEncoder.js");function ByteArray(){this.page=-1;this.pages=[];this.newPage()}ByteArray.pageSize=4096;ByteArray.charMap={};for(var i=0;i<256;i++)ByteArray.charMap[i]=String.fromCharCode(i);ByteArray.prototype.newPage=function(){this.pages[++this.page]=new Uint8Array(ByteArray.pageSize);this.cursor=0};ByteArray.prototype.getData=function(){var rv="";for(var p=0;p<this.pages.length;p++){for(var i=0;i<ByteArray.pageSize;i++){rv+=ByteArray.charMap[this.pages[p][i]]}}return rv};ByteArray.prototype.writeByte=function(val){if(this.cursor>=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i<l;i++)this.writeByte(string.charCodeAt(i))};ByteArray.prototype.writeBytes=function(array,offset,length){for(var l=length||array.length,i=offset||0;i<l;i++)this.writeByte(array[i])};function GIFEncoder(width,height){this.width=~~width;this.height=~~height;this.transparent=null;this.transIndex=0;this.repeat=-1;this.delay=0;this.image=null;this.pixels=null;this.indexedPixels=null;this.colorDepth=null;this.colorTab=null;this.neuQuant=null;this.usedEntry=new Array;this.palSize=7;this.dispose=-1;this.firstFrame=true;this.sample=10;this.dither=false;this.globalPalette=false;this.out=new ByteArray}GIFEncoder.prototype.setDelay=function(milliseconds){this.delay=Math.round(milliseconds/10)};GIFEncoder.prototype.setFrameRate=function(fps){this.delay=Math.round(100/fps)};GIFEncoder.prototype.setDispose=function(disposalCode){if(disposalCode>=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j<nPix;j++){var index=this.findClosestRGB(this.pixels[k++]&255,this.pixels[k++]&255,this.pixels[k++]&255);this.usedEntry[index]=true;this.indexedPixels[j]=index}};GIFEncoder.prototype.ditherPixels=function(kernel,serpentine){var kernels={FalseFloydSteinberg:[[3/8,1,0],[3/8,0,1],[2/8,1,1]],FloydSteinberg:[[7/16,1,0],[3/16,-1,1],[5/16,0,1],[1/16,1,1]],Stucki:[[8/42,1,0],[4/42,2,0],[2/42,-2,1],[4/42,-1,1],[8/42,0,1],[4/42,1,1],[2/42,2,1],[1/42,-2,2],[2/42,-1,2],[4/42,0,2],[2/42,1,2],[1/42,2,2]],Atkinson:[[1/8,1,0],[1/8,2,0],[1/8,-1,1],[1/8,0,1],[1/8,1,1],[1/8,0,2]]};if(!kernel||!kernels[kernel]){throw"Unknown dithering kernel: "+kernel}var ds=kernels[kernel];var index=0,height=this.height,width=this.width,data=this.pixels;var direction=serpentine?-1:1;this.indexedPixels=new Uint8Array(this.pixels.length/3);for(var y=0;y<height;y++){if(serpentine)direction=direction*-1;for(var x=direction==1?0:width-1,xend=direction==1?width:0;x!==xend;x+=direction){index=y*width+x;var idx=index*3;var r1=data[idx];var g1=data[idx+1];var b1=data[idx+2];idx=this.findClosestRGB(r1,g1,b1);this.usedEntry[idx]=true;this.indexedPixels[index]=idx;idx*=3;var r2=this.colorTab[idx];var g2=this.colorTab[idx+1];var b2=this.colorTab[idx+2];var er=r1-r2;var eg=g1-g2;var eb=b1-b2;for(var i=direction==1?0:ds.length-1,end=direction==1?ds.length:0;i!==end;i+=direction){var x1=ds[i][1];var y1=ds[i][2];if(x1+x>=0&&x1+x<width&&y1+y>=0&&y1+y<height){var d=ds[i][0];idx=index+x1+y1*width;idx*=3;data[idx]=Math.max(0,Math.min(255,data[idx]+er*d));data[idx+1]=Math.max(0,Math.min(255,data[idx+1]+eg*d));data[idx+2]=Math.max(0,Math.min(255,data[idx+2]+eb*d))}}}}};GIFEncoder.prototype.findClosest=function(c,used){return this.findClosestRGB((c&16711680)>>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i<len;index++){var dr=r-(this.colorTab[i++]&255);var dg=g-(this.colorTab[i++]&255);var db=b-(this.colorTab[i++]&255);var d=dr*dr+dg*dg+db*db;if((!used||this.usedEntry[index])&&d<dmin){dmin=d;minpos=index}}return minpos};GIFEncoder.prototype.getImagePixels=function(){var w=this.width;var h=this.height;this.pixels=new Uint8Array(w*h*3);var data=this.image;var srcPos=0;var count=0;for(var i=0;i<h;i++){for(var j=0;j<w;j++){this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];srcPos++}}};GIFEncoder.prototype.writeGraphicCtrlExt=function(){this.out.writeByte(33);this.out.writeByte(249);this.out.writeByte(4);var transp,disp;if(this.transparent===null){transp=0;disp=0}else{transp=1;disp=2}if(this.dispose>=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i<n;i++)this.out.writeByte(0)};GIFEncoder.prototype.writeShort=function(pValue){this.out.writeByte(pValue&255);this.out.writeByte(pValue>>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i<hsize;++i)htab[i]=-1}function compress(init_bits,outs){var fcode,c,i,ent,disp,hsize_reg,hshift;g_init_bits=init_bits;clear_flg=false;n_bits=g_init_bits;maxcode=MAXCODE(n_bits);ClearCode=1<<init_bits-1;EOFCode=ClearCode+1;free_ent=ClearCode+2;a_count=0;ent=nextPixel();hshift=0;for(fcode=HSIZE;fcode<65536;fcode*=2)++hshift;hshift=8-hshift;hsize_reg=HSIZE;cl_hash(hsize_reg);output(ClearCode,outs);outer_loop:while((c=nextPixel())!=EOF){fcode=(c<<BITS)+ent;i=c<<hshift^ent;if(htab[i]===fcode){ent=codetab[i];continue}else if(htab[i]>=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<<BITS){codetab[i]=free_ent++;htab[i]=fcode}else{cl_block(outs)}}output(ent,outs);output(EOFCode,outs)}function encode(outs){outs.writeByte(initCodeSize);remaining=width*height;curPixel=0;compress(initCodeSize+1,outs);outs.writeByte(0)}function flush_char(outs){if(a_count>0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<<n_bits)-1}function nextPixel(){if(remaining===0)return EOF;--remaining;var pix=pixels[curPixel++];return pix&255}function output(code,outs){cur_accum&=masks[cur_bits];if(cur_bits>0)cur_accum|=code<<cur_bits;else cur_accum=code;cur_bits+=n_bits;while(cur_bits>=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<<BITS;else maxcode=MAXCODE(n_bits)}}if(code==EOFCode){while(cur_bits>0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<<intbiasshift;var gammashift=10;var gamma=1<<gammashift;var betashift=10;var beta=intbias>>betashift;var betagamma=intbias<<gammashift-betashift;var initrad=netsize>>3;var radiusbiasshift=6;var radiusbias=1<<radiusbiasshift;var initradius=initrad*radiusbias;var radiusdec=30;var alphabiasshift=10;var initalpha=1<<alphabiasshift;var alphadec;var radbiasshift=8;var radbias=1<<radbiasshift;var alpharadbshift=alphabiasshift+radbiasshift;var alpharadbias=1<<alpharadbshift;var prime1=499;var prime2=491;var prime3=487;var prime4=503;var minpicturebytes=3*prime4;function NeuQuant(pixels,samplefac){var network;var netindex;var bias;var freq;var radpower;function init(){network=[];netindex=new Int32Array(256);bias=new Int32Array(netsize);freq=new Int32Array(netsize);radpower=new Int32Array(netsize>>3);var i,v;for(i=0;i<netsize;i++){v=(i<<netbiasshift+8)/netsize;network[i]=new Float64Array([v,v,v,0]);freq[i]=intbias/netsize;bias[i]=0}}function unbiasnet(){for(var i=0;i<netsize;i++){network[i][0]>>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(j<hi||k>lo){a=radpower[m++];if(j<hi){p=network[j++];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}if(k>lo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i<netsize;i++){n=network[i];dist=Math.abs(n[0]-b)+Math.abs(n[1]-g)+Math.abs(n[2]-r);if(dist<bestd){bestd=dist;bestpos=i}biasdist=dist-(bias[i]>>intbiasshift-netbiasshift);if(biasdist<bestbiasd){bestbiasd=biasdist;bestbiaspos=i}betafreq=freq[i]>>betashift;freq[i]-=betafreq;bias[i]+=betafreq<<gammashift}freq[bestpos]+=beta;bias[bestpos]-=betagamma;return bestbiaspos}function inxbuild(){var i,j,p,q,smallpos,smallval,previouscol=0,startpos=0;for(i=0;i<netsize;i++){p=network[i];smallpos=i;smallval=p[1];for(j=i+1;j<netsize;j++){q=network[j];if(q[1]<smallval){smallpos=j;smallval=q[1]}}q=network[smallpos];if(i!=smallpos){j=q[0];q[0]=p[0];p[0]=j;j=q[1];q[1]=p[1];p[1]=j;j=q[2];q[2]=p[2];p[2]=j;j=q[3];q[3]=p[3];p[3]=j}if(smallval!=previouscol){netindex[previouscol]=startpos+i>>1;for(j=previouscol+1;j<smallval;j++)netindex[j]=i;previouscol=smallval;startpos=i}}netindex[previouscol]=startpos+maxnetpos>>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i<netsize||j>=0){if(i<netsize){p=network[i];dist=p[1]-g;if(dist>=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}if(j>=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}}return best}function learn(){var i;var lengthcount=pixels.length;var alphadec=30+(samplefac-1)/3;var samplepixels=lengthcount/(3*samplefac);var delta=~~(samplepixels/ncycles);var alpha=initalpha;var radius=initradius;var rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i<rad;i++)radpower[i]=alpha*((rad*rad-i*i)*radbias/(rad*rad));var step;if(lengthcount<minpicturebytes){samplefac=1;step=3}else if(lengthcount%prime1!==0){step=3*prime1}else if(lengthcount%prime2!==0){step=3*prime2}else if(lengthcount%prime3!==0){step=3*prime3}else{step=3*prime4}var b,g,r,j;var pix=0;i=0;while(i<samplepixels){b=(pixels[pix]&255)<<netbiasshift;g=(pixels[pix+1]&255)<<netbiasshift;r=(pixels[pix+2]&255)<<netbiasshift;j=contest(b,g,r);altersingle(alpha,j,b,g,r);if(rad!==0)alterneigh(rad,j,b,g,r);pix+=step;if(pix>=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j<rad;j++)radpower[j]=alpha*((rad*rad-j*j)*radbias/(rad*rad))}}}function buildColormap(){init();learn();unbiasnet();inxbuild()}this.buildColormap=buildColormap;function getColormap(){var map=[];var index=[];for(var i=0;i<netsize;i++)index[network[i][3]]=i;var k=0;for(var l=0;l<netsize;l++){var j=index[l];map[k++]=network[j][0];map[k++]=network[j][1];map[k++]=network[j][2]}return map}this.getColormap=getColormap;this.lookupRGB=inxsearch}module.exports=NeuQuant},{}],4:[function(require,module,exports){var GIFEncoder,renderFrame;GIFEncoder=require("./GIFEncoder.js");renderFrame=function(frame){var encoder,page,stream,transfer;encoder=new GIFEncoder(frame.width,frame.height);if(frame.index===0){encoder.writeHeader()}else{encoder.firstFrame=false}encoder.setTransparent(frame.transparent);encoder.setRepeat(frame.repeat);encoder.setDelay(frame.delay);encoder.setQuality(frame.quality);encoder.setDither(frame.dither);encoder.setGlobalPalette(frame.globalPalette);encoder.addFrame(frame.data);if(frame.last){encoder.finish()}if(frame.globalPalette===true){frame.globalPalette=encoder.getGlobalPalette()}stream=encoder.stream();frame.data=stream.pages;frame.cursor=stream.cursor;frame.pageSize=stream.constructor.pageSize;if(frame.canTransfer){transfer=function(){var i,len,ref,results;ref=frame.data;results=[];for(i=0,len=ref.length;i<len;i++){page=ref[i];results.push(page.buffer)}return results}();return self.postMessage(frame,transfer)}else{return self.postMessage(frame)}};self.onmessage=function(event){return renderFrame(event.data)}},{"./GIFEncoder.js":1}]},{},[4]);
|
|
150
150
|
`],{type:"application/javascript"}))})}async function le(e){for(let t=0;t<30;t++){let t=await e();if(t)return t;await new Promise(e=>setTimeout(e,50))}}function lt(e){return new Promise(t=>{let n=document.createElement("img");n.onload=async()=>{0===n.width||0===n.height?t(await i6(e)):t({width:n.width,height:n.height})},n.crossOrigin="anonymous",n.src=e})}function ln(e){return new Promise((t,n)=>{let r=document.createElement("img");r.onload=()=>{t(r)},r.onerror=e=>{n(e)},r.crossOrigin="anonymous",r.src=e})}async function lr(e,t){let n,r;let i=await ln(e),o=document.createElement("canvas");o.width=2*i.width,o.height=2*i.height,o.getContext("2d").drawImage(i,0,0,o.width,o.height);let a=document.createElement("canvas");a.width=t.width,a.height=t.height;let l=a.getContext("2d"),{cropX:s,cropY:u}=t,c=o.width*t.cropWidth,d=o.height*t.cropHeight,h=t.width/t.height,f=c/d;return"svg"===t.type?(n=c,r=d):h>=f?(n=c,r=c/h):(n=d*h,r=d),l.drawImage(o,s*o.width,u*o.height,n,r,0,0,a.width,a.height),a.toDataURL("image/png")}function li(e,t){let n,r;let{width:i,height:o}=e,a=i/o;a>=t.width/t.height?(n=t.width,r=t.width/a):(n=t.height*a,r=t.height);let l=(t.width-n)/2,s=(t.height-r)/2;return{cropX:l/t.width,cropY:s/t.height,cropWidth:n/t.width,cropHeight:r/t.height}}let lo=(e,t,...n)=>({type:e,props:t,children:n||[]}),la=async({element:e,page:t,store:n})=>{let r,i,{src:o}=e;"svg"===e.type&&Object.keys(e.colorsReplace).length&&(o=i9(await i3(o),new Map(Object.entries(e.colorsReplace))));let a="";e.flipX&&(a+="scaleX(-1)"),e.flipY&&(a+="scaleY(-1)"),a||(a="none");let l={};if(e.clipSrc){let t=await i2(e.clipSrc);l["clip-path"]=`url(${t})`}let s=await ln(o),u=s.width*e.cropWidth,c=s.height*e.cropHeight,d=e.width/e.height;"svg"===e.type?(r=u,i=c):d>=u/c?(r=u,i=u/d):(r=c*d,i=c);let h=r/s.width,f=i/s.height,p=r/i>e.width/e.height?e.height/i:e.width/r,g=r*p/h,m=i*p/f,v=e.cropX*p*s.width,y=e.cropY*p*s.height;return lo("div",{style:{...l,width:"100%",height:"100%","border-radius":e.cornerRadius+"px",border:e.borderSize?`${e.borderSize}px solid ${e.borderColor}`:"none",background:`url(${o})`,transform:a,"background-size":`${Math.round(g)}px ${Math.round(m)}px`,"background-position-x":`${-Math.round(v)}px`,"background-position-y":`${-Math.round(y)}px`}})},ll=({element:e,type:t})=>{let n={"stroke-width":e.height,stroke:e.color,"line-cap":"round","stroke-linejoin":"round",opacity:e.opacity};return"arrow"===t||"triangle"===t?lo("polyline",{points:`${3*e.height},${-(2*e.height)} 0,0 ${3*e.height},${2*e.height}`,...n}):"bar"===t?lo("polyline",{points:`0,${-(2*e.height)} 0,${2*e.height}`,...n}):"circle"===t?lo("circle",{r:e.height,...n}):"square"===t?lo("polyline",{points:`${-e.height},${-e.height} ${-e.height},${e.height} ${e.height},${e.height} ${e.height},${-e.height}`,...n}):null},ls={image:la,svg:la,text:async({element:e,page:t,store:n})=>{let r={};e.fill.indexOf("gradient")>=0&&(r={...r,"background-color":e.fill,"background-image":e.fill,"background-clip":"text","text-fill-color":"transparent","-webkit-background-clip":"text","-webkit-text-fill-color":"transparent"});let i=e.backgroundPadding*(e.fontSize*e.lineHeight),o=lo("div",{style:{position:"absolute",top:-i/2+"px",left:-i/2+"px",display:e.backgroundEnabled?"block":"none",width:e.width+i+"px",height:e.height+i+"px","background-color":e.backgroundColor,"border-radius":e.backgroundCornerRadius*(e.fontSize*e.lineHeight*.5)+"px"}}),a=lo("div",{style:{...r,position:"absolute",top:0,left:0,width:e.width+"px",color:e.fill,"white-space":"pre-wrap","font-size":e.fontSize+"px","text-align":e.align,"font-family":e.fontFamily,"text-decoration":e.textDecoration||"none","line-height":e.lineHeight,"letter-spacing":e.letterSpacing+"em","font-style":e.fontStyle,"font-weight":e.fontWeight,"-webkit-text-stroke":`${e.strokeWidth}px ${e.stroke}`,"text-stroke":`${e.strokeWidth}px ${e.stroke}`}},e.text.split("\n").join("<br />"));return lo("div",{style:{position:"relative"}},o,a)},line:async({element:e,page:t,store:n})=>lo("svg",{style:{width:"100%",height:"100%",contain:"layout style size",overflow:"visible"}},lo("rect",{x:0,y:0,width:e.width,height:e.height,fill:e.color}),lo("g",{transform:`translate(0 ${e.height/2})`},ll({element:e,type:e.startHead})),lo("g",{transform:`translate(${e.width} ${e.height/2}) rotate(180)`},ll({element:e,type:e.endHead}))),figure:async({element:e,page:t,store:n,elementHook:r})=>{let i=lo("div",{innerHTML:an(e)});return r&&r({dom:i,element:e})||i},group:async({element:e,page:t,store:n,elementHook:r})=>{let i=await Promise.all(e.children.map(e=>lu({element:e,page:t,store:n,elementHook:r}))),o=lo("div",{style:{"transform-origin":"top left",opacity:e.opacity}},...i);return r&&r({dom:o,element:e})||o}};async function lu({element:e,page:t,store:n,elementHook:r}){let i=await ls[e.type];i||(i=()=>lo("div",{}),console.error(`HTML export does not support ${e.type} type...`));let o=await i({element:e,page:t,store:n}),a=[];e.blurEnabled&&a.push(`blur(${e.blurRadius/2}px)`),e.brightnessEnabled&&a.push(`brightness(${100*e.brightness+100}%)`),e.sepiaEnabled&&a.push("sepia()"),e.grayscaleEnabled&&a.push("grayscale()"),e.shadowEnabled&&a.push(`drop-shadow(${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${e.shadowColor})`);let l=lo("div",{style:{position:"absolute",left:e.x+"px",top:e.y+"px",width:e.width+"px",height:e.height+"px",transform:`rotate(${e.rotation}deg)`,"transform-origin":"top left",opacity:e.opacity,filter:a.join(" ")||"none"}},o);return r&&r({dom:l,element:e})||l}async function lc({page:e,store:t,elementHook:n}){let r=await Promise.all(e.children.map(r=>lu({element:r,page:e,store:t,elementHook:n}))),i="auto"===e.width?t.width:e.width,o="auto"===e.height?t.height:e.height,a={};if(e.background.indexOf("url")>=0||e.background.indexOf("http")>=0||e.background.indexOf(".jpg")>=0||e.background.indexOf(".png")>=0||e.background.indexOf(".jpeg")>=0){let{width:n,height:i}=await ln(e.background),o=await la({element:{x:0,y:0,width:n,height:i,src:e.background,cornerRadius:0,...li({width:n,height:i},{width:n,height:i})},page:e,store:t});r.unshift(o)}else a={...a,"background-color":e.background};return lo("div",{className:"page",style:{...a,width:i+"px",height:o+"px",border:"1px solid grey",overflow:"hidden",position:"relative"}},...r)}async function ld({json:e,elementHook:t}){let n=await Promise.all(e.pages.map(n=>lc({page:n,store:e,elementHook:t}))),r=[];e.pages.forEach(e=>{e.children.forEach(e=>{"text"===e.type&&-1===r.indexOf(e.fontFamily)&&r.push(e.fontFamily)})});let i=r.map(t=>e.fonts.find(e=>e.fontFamily===t)?lo("style",{},""):lo("link",{href:`https://fonts.googleapis.com/css?family=${t}`,rel:"stylesheet"}));return lo("div",{className:"design"},...i,...n)}let lh=(e,t)=>"object"==typeof t?`${e}="${Object.keys(t).map(e=>`${e}:${t[e]};`).join(" ")}"`:`${e}="${t}"`,lf=({dom:e})=>{if("string"==typeof e)return e;if(!e)return"";let{innerHTML:t,...n}=e.props;return`<${e.type} ${Object.keys(n).map(t=>lh(t,e.props[t])).join(" ")}>${t||e.children.map(e=>lf({dom:e})).join("")}</${e.type}>`};async function lp({json:e,elementHook:t}){return lf({dom:await ld({json:e,elementHook:t})})}let lg=(e,t,...n)=>({type:e,props:t,children:n||[]}),lm=async e=>{let t=await ln(e),n=document.createElement("canvas");return n.width=t.width,n.height=t.height,n.getContext("2d").drawImage(t,0,0),n.toDataURL("image/png")},lv=async({element:e,page:t,store:n})=>{let r,i,{src:o}=e;"svg"===e.type&&(o=i9(await i3(o),new Map(Object.entries(e.colorsReplace))));let a="";e.flipX&&(a+="scaleX(-1)"),e.flipY&&(a+="scaleY(-1)");let l={};if(e.clipSrc){let t=await i2(e.clipSrc);l["clip-path"]=`url(${t})`}let s=await ln(o),u=s.width*e.cropWidth,c=s.height*e.cropHeight,d=e.width/e.height;"svg"===e.type?(r=u,i=c):d>=u/c?(r=u,i=u/d):(r=c*d,i=c);let h=r/s.width,f=i/s.height,p=r/i>e.width/e.height?e.height/i:e.width/r,g=r*p/h,m=i*p/f,v=e.cropX*p*s.width,y=e.cropY*p*s.height,b=`clip-${Math.random()}`;return lg("g",{style:{"clip-path":l["clip-path"],transform:a}},lg("defs",{},lg("clipPath",{id:b},lg("rect",{x:v,y:y,width:g,height:m}))),lg("image",{"xlink:href":await lm(o),width:e.width,height:e.height,preserveAspectRatio:"none","clip-path":`url(#${b})`}))},ly=({element:e,type:t})=>{let n={"stroke-width":e.height,stroke:e.color,"line-cap":"round","stroke-linejoin":"round",opacity:e.opacity};return"arrow"===t||"triangle"===t?lg("polyline",{points:`${3*e.height},${-(2*e.height)} 0,0 ${3*e.height},${2*e.height}`,...n}):"bar"===t?lg("polyline",{points:`0,${-(2*e.height)} 0,${2*e.height}`,...n}):"circle"===t?lg("circle",{r:e.height,...n}):"square"===t?lg("polyline",{points:`${-e.height},${-e.height} ${-e.height},${e.height} ${e.height},${e.height} ${e.height},${-e.height}`,...n}):null},lb={image:lv,svg:lv,text:async({element:e,page:t,store:n})=>{let r={};e.fill.indexOf("gradient")>=0&&(r={...r,"background-color":e.fill,"background-image":e.fill,"background-clip":"text","text-fill-color":"transparent","-webkit-background-clip":"text","-webkit-text-fill-color":"transparent"});let i=e.backgroundPadding*(e.fontSize*e.lineHeight),o=lg("div",{style:{position:"absolute",top:-i/2+"px",left:-i/2+"px",display:e.backgroundEnabled?"block":"none",width:e.width+i+"px",height:e.height+i+"px","background-color":e.backgroundColor,"border-radius":e.backgroundCornerRadius*(e.fontSize*e.lineHeight*.5)+"px"}}),a=lg("div",{style:{...r,position:"absolute",top:0,left:0,width:e.width+"px",color:e.fill,"white-space":"pre-wrap","font-size":e.fontSize+"px","text-align":e.align,"font-family":e.fontFamily,"text-decoration":e.textDecoration||"none","line-height":e.lineHeight,"letter-spacing":e.letterSpacing+"em","font-style":e.fontStyle,"font-weight":e.fontWeight,"-webkit-text-stroke":`${e.strokeWidth}px ${e.stroke}`,"text-stroke":`${e.strokeWidth}px ${e.stroke}`}},e.text.split("\n").join("<br />"));return lg("foreignObject",{width:e.width,height:e.height},lg("div",{style:{position:"relative"},xmlns:"http://www.w3.org/1999/xhtml"},o,a))},line:async({element:e,page:t,store:n})=>lg("svg",{style:{width:"100%",height:"100%",contain:"layout style size",overflow:"visible"}},lg("rect",{x:0,y:0,width:e.width,height:e.height,fill:e.color}),lg("g",{transform:`translate(0 ${e.height/2})`},ly({element:e,type:e.startHead})),lg("g",{transform:`translate(${e.width} ${e.height/2}) rotate(180)`},ly({element:e,type:e.endHead}))),group:async({element:e,page:t,store:n,elementHook:r})=>{let i=await Promise.all(e.children.map(e=>lw({element:e,page:t,store:n,elementHook:r}))),o=lg("g",{opacity:e.opacity,style:{"transform-origin":"top left"}},...i);return r&&r({dom:o,element:e})||o}};async function lw({element:e,page:t,store:n,elementHook:r}){let i=await lb[e.type];i||(i=()=>lg("div",{}),console.error(`HTML export does not support ${e.type} type...`));let o=await i({element:e,page:t,store:n}),a=[];e.blurEnabled&&a.push(`blur(${e.blurRadius/2}px)`),e.brightnessEnabled&&a.push(`brightness(${100*e.brightness+100}%)`),e.sepiaEnabled&&a.push("sepia()"),e.grayscaleEnabled&&a.push("grayscale()"),e.shadowEnabled&&a.push(`drop-shadow(${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${e.shadowColor})`);let l=lg("g",{transform:`translate(${e.x}, ${e.y}) rotate(${e.rotation})`,rotation:e.rotation,width:e.width,height:e.height,opacity:e.opacity,style:{"transform-origin":"top left",filter:a.join(" ")}},o);return r&&r({dom:l,element:e})||l}async function lx({page:e,store:t,elementHook:n}){let r=await Promise.all(e.children.map(r=>lw({element:r,page:e,store:t,elementHook:n}))),i={};if(e.background.indexOf("url")>=0||e.background.indexOf("http")>=0||e.background.indexOf(".jpg")>=0||e.background.indexOf(".png")>=0||e.background.indexOf(".jpeg")>=0){let n=await ln(e.background),r=await lr(e.background,{width:t.width,height:t.height,x:0,y:0,...li({width:t.width,height:t.height},{width:n.width,height:n.height})});i={...i,"background-image":`url(${r})`}}return lg("g",{className:"page",style:{...i,background:e.background}},lg("rect",{x:0,y:0,width:t.width,height:t.height,fill:e.background}),...r)}async function l_({json:e,elementHook:t}){let n=await Promise.all(e.pages.map(n=>lx({page:n,store:e,elementHook:t}))),r=[];e.pages.forEach(e=>{e.children.forEach(e=>{"text"===e.type&&-1===r.indexOf(e.fontFamily)&&r.push(e.fontFamily)})});let i=r.map(t=>e.fonts.find(e=>e.fontFamily===t)?lg("style",{},""):lg("link",{href:`https://fonts.googleapis.com/css?family=${t}`,rel:"stylesheet"}));return lg("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:`0 0 ${e.width} ${e.height}`,preserveAspectRatio:"xMidYMin slice"},...i,...n)}let lE=(e,t)=>"object"==typeof t?`${e}="${Object.keys(t).map(e=>`${e}:${t[e]};`).join(" ")}"`:`${e}="${t}"`,lS=({dom:e})=>"string"==typeof e?e:e?`<${e.type} ${Object.keys(e.props).map(t=>lE(t,e.props[t])).join(" ")}>${e.children.map(e=>lS({dom:e})).join("")}</${e.type}>
|
|
151
|
-
`:"";async function lC({json:e,elementHook:t}){return lS({dom:await l_({json:e,elementHook:t})})}var iV=p("58B0H");let lO=(0,iV.types).model("Page",{id:iV.types.identifier,children:(0,iV.types).array((0,iV.types).late(()=>lV)),width:(0,iV.types).optional((0,iV.types).union(iV.types.number,(0,iV.types).literal("auto")),"auto"),height:(0,iV.types).optional((0,iV.types).union(iV.types.number,(0,iV.types).literal("auto")),"auto"),background:"white",bleed:0,custom:(0,iV.types).frozen(),duration:5e3,_exporting:!1,_rendering:!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,iV.getParentOfType)(e,lP)},get startTime(){let t=0;for(let n of e.store.pages){if(n.id===e.id)break;t+=n.duration}return t}})).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,iV.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=a6(10),lU(e,e=>{e.id=a6(10)})});let r={...n,id:a6(10),...t},i=e.store.addPage(r),o=e.store.pages.indexOf(e);i.setZIndex(o+1),i.select()},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=lW[t.type];if(!r){console.error("Can not find model with type "+t.type);return}t.children&&t.children.forEach(e=>{e.id=a6(10)});let i=r.create({id:a6(10),...t});return e.children.push(i),i.selectable&&!n&&e.store.selectElements([i.id]),i},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,iV.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,iV.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,iV.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=t/e.computedWidth,i=n/e.computedHeight,o=Math.min(r,i),a=Math.max(0,(t-e.computedWidth*o)/2),l=Math.max(0,(n-e.computedHeight*o)/2);lU(e,t=>{"group"!==t.type&&("image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2?t.set({x:t.x*o,y:t.y*o,width:t.width*r,height:t.height*i,cropX:0,cropY:0,cropWidth:1,cropHeight:1}):(t.set({x:a+t.x*o,y:l+t.y*o,width:t.width*o,height:t.height*o}),"text"===t.type?t.set({fontSize:t.fontSize*o}):"figure"===t.type&&t.set({strokeWidth:t.strokeWidth*o})))})}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})}}));(0,iV.setLivelinessChecking)("ignore");let lk=(0,iV.types).model("Font",{fontFamily:iV.types.string,url:(0,iV.types).optional(iV.types.string,""),styles:(0,iV.types).frozen()}).preProcessSnapshot(e=>({...e,fontFamily:e.fontFamily||e.name})),lP=(0,iV.types).model("Store",{role:"",pages:(0,iV.types).array(lO),fonts:(0,iV.types).array(lk),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",custom:(0,iV.types).frozen(),selectedElementsIds:(0,iV.types).array(iV.types.string),animatedElementsIds:(0,iV.types).array(iV.types.string),history:(0,iV.types).optional(a8,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(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 lU({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 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 lU({children:e.pages},e=>{if(!n&&t(e))return n=e,!0}),n},getElementById:t=>e.find(e=>e.id===t)})).actions(e=>{let t=0,n=null,r=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=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,iV.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,iV.cast)([]),e.checkActivePage()}}}).actions(e=>({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},addPage(t){let n=lO.create({id:a6(10),...t});return e.pages.push(n),e._activePageId=n.id,n},selectPage(t){e._activePageId=t},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,iV.cast)(n)},toggleBleed(t){e.bleedVisible=t??!e.bleedVisible},toggleRulers(t){e.rulesVisible=t??!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,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,iV.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,iV.destroy)(n)});let r=Math.min(e.pages.length-1,n),i=e.pages[r];i&&(e._activePageId=i.id),e.selectedElementsIds=(0,iV.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},groupElements(t){let n=t.map(t=>e.getElementById(t));n.forEach(e=>{e&&(0,iV.detach)(e)});let r=e.activePage,i={id:a6(10),children:n,type:"group"};return r.children.push(i),e.selectedElementsIds=(0,iV.cast)([i.id]),i},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,iV.detach)(e),t.children.push(e)}),t.children.splice(n,1)}}),e.selectedElementsIds=(0,iV.cast)(r)},deleteElements(t){t.forEach(t=>{e.pages.forEach(e=>{let n=e.children.find(e=>e.id===t);n&&(0,iV.destroy)(n)})}),e.selectedElementsIds=(0,iV.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},on(t,n){if("change"===t){let t=e.toJSON();return(0,iV.onSnapshot)(e,r=>{let i=e.toJSON();a4(t,i)||(t=i,n(i))})}},async _toCanvas({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o,_skipTimeout:a}={}){let l=t||1;r=r||e.pages[0]?.id;let s=e.pages.find(e=>e.id===r);if(!s)throw Error(`No page for export with id ${r}`);s?.set({_exporting:!0});let c=await le(()=>u(j).stages.find(e=>e.getAttr("pageId")===r));if(!c)throw 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.`);let d=!!c.findOne(".page-container"),h=e._elementsPixelRatio;l>e._elementsPixelRatio&&e.setElementsPixelRatio(l),await e.waitLoading({_skipTimeout:a});let f=c.findOne(".page-container");if(!f)throw e.setElementsPixelRatio(h),Error(`Export is failed. Can't find page container. ${d}`);c.find("Transformer").forEach(e=>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 p=f.findOne(".page-background-group"),g=p.clip();p.clip({x:null,y:null,width:null,height:null});let m=f.findOne(".elements-container"),v=m.clip();m.clip({x:null,y:null,width:null,height:null});let y=f.find(e=>e.getAttr("hideInExport"));y.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()});let b=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled"));b.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()}),n&&f.find(".page-background").forEach(e=>e.hide());let w=o?s.bleed:0,x=w;!e.bleedVisible&&o||(e.bleedVisible||o?e.bleedVisible&&o?x=0:e.bleedVisible&&!o&&(x=-s.bleed):x=0);let _=document.createElement("canvas");_.width=Math.round((s.computedWidth+2*w)*l),_.height=Math.round((s.computedHeight+2*w)*l);let E=_.getContext("2d");"image/jpeg"===i&&(E.fillStyle="white",E.fillRect(0,0,_.width,_.height));let S=f.scale();f.scale({x:1,y:1});let C=f.toCanvas({x:f.x()-x,y:f.y()-x,width:s.computedWidth+2*w,height:s.computedHeight+2*w,pixelRatio:l});return f.scale(S),E.drawImage(C,0,0,_.width,_.height),u(j).Util.releaseCanvas(C),n&&f.find(".page-background").forEach(e=>e.show()),y.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)),c.find("Transformer").forEach(e=>e.visible(!0)),f.find(".highlighter").forEach(e=>e.visible(!0)),p.clip(g),m.clip(v),e.setElementsPixelRatio(h),s?.set({_exporting:!1}),_},async toDataURL({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o,quality:a}={}){let l=await e._toCanvas({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o}),s=l.toDataURL(i,a);return u(j).Util.releaseCanvas(l),s},async toBlob({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o,quality:a}={}){let l=await e._toCanvas({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o}),s=new Promise(e=>{l.toBlob(e,i,a)});return u(j).Util.releaseCanvas(l),s},async saveAsImage({fileName:t,...n}={}){let r=n.mimeType||"image/png",i=r.split("/")[1];a9(await e.toDataURL(n),t||"polotno."+i,r)},async _toPDF(n){let r=n.dpi||e.dpi,i=n.parallel||1,o=n.unit||("px"===e.unit?"mm":e.unit),a=n.pixelRatio||1,l=n.pageIds||e.pages.map(e=>e.id),s=e.pages.filter(e=>l.includes(e.id)),u=await (t?Promise.resolve(t):new Promise(e=>{var n=document.createElement("script");n.onload=function(){e(t=window.jspdf.jsPDF)},n.src="https://unpkg.com/jspdf@2.2.0/dist/jspdf.umd.min.js",document.head.appendChild(n)})),c=e=>aj({px:e,unit:o,dpi:r}),d=c(n.cropMarkSize||0),h=s[0]||{},f=n.includeBleed?h.bleed:0,p=c(h.computedWidth+2*f)+2*d,g=c(h.computedHeight+2*f)+2*d;var m=new u({unit:o,orientation:p>g?"landscape":"portrait",format:[p,g],compress:!0,putOnlyUsedFonts:!0});for(let t of(m.deletePage(1),((e,t)=>{for(var n=[],r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n})(s,i))){let r=t.map(async t=>{let r=n.includeBleed?t.bleed:0,i=c(t.computedWidth+2*r)+2*d,o=c(t.computedHeight+2*r)+2*d,l=0,s=a;for(;l<10;){2===(l+=1)&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");let r=await e.toDataURL({...n,pageId:t.id,pixelRatio:s});if(r.length>20)return{url:r,width:i,height:o};s*=.8}});(await Promise.all(r)).forEach(({url:e,width:t,height:n})=>{m.addPage([t,n],t>n?"landscape":"portrait"),d&&(m.setLineWidth(c(1)),m.line(2*d,0,2*d,d),m.line(0,2*d,d,2*d),m.line(t-2*d,0,t-2*d,d),m.line(t,2*d,t-d,2*d),m.line(0,n-2*d,d,n-2*d),m.line(2*d,n,2*d,n-d),m.line(t,n-2*d,t-d,n-2*d),m.line(t-2*d,n,t-2*d,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 a7({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}={}){a9(await e.toGIFDataURL(n),t||"polotno.gif")},toHTML:async({elementHook:t}={elementHook:void 0})=>lp({json:e.toJSON(),elementHook:t}),async saveAsHTML({fileName:t}={}){let n=await e.toHTML();a9("data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(n))),t||"polotno.html")},toSVG:async()=>lC({json:e.toJSON()}),async saveAsSVG({fileName:t}={}){let n=await e.toSVG();a9("data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n))),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=()=>{id()?setTimeout(e,300):e(!0)},void(0===ip?t():ig.push(t))})},toJSON:()=>({width:e.width,height:e.height,fonts:(0,iV.getSnapshot)(e.fonts),pages:(0,iV.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi,custom:e.custom}),loadJSON(t,n=!1){let r={...t},i=e.pages.indexOf(e.activePage),o=(r.pages[i]||r.pages[0])?.id;r._activePageId=o;let a={...(0,iV.getSnapshot)(e)};Object.assign(a,r),n?a.history=e.history.toJSON():a.history={history:[],undoIdx:-1},(0,iV.applySnapshot)(e,a)},clear({keepHistory:t=!1}={}){let n=e.pages.map(e=>e.id);e.deletePages(n),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,iV.destroy)(e))},async loadFont(t){let n=e.fonts.find(e=>e.fontFamily===t)||iS.find(e=>e.fontFamily===t);n?function(e){let t=e.fontFamily;if(ij[t]||!e.url&&!e.styles)return;let n=document.createElement("style");n.type="text/css";let r=e.styles||(e.url?[{src:`url("${e.url}")`}]:[]),i="";r.forEach(e=>{i+=`
|
|
151
|
+
`:"";async function lC({json:e,elementHook:t}){return lS({dom:await l_({json:e,elementHook:t})})}var iV=p("58B0H");let lO=(0,iV.types).model("Page",{id:iV.types.identifier,children:(0,iV.types).array((0,iV.types).late(()=>lV)),width:(0,iV.types).optional((0,iV.types).union(iV.types.number,(0,iV.types).literal("auto")),"auto"),height:(0,iV.types).optional((0,iV.types).union(iV.types.number,(0,iV.types).literal("auto")),"auto"),background:"white",bleed:0,custom:(0,iV.types).frozen(),duration:5e3,_exporting:!1,_rendering:!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,iV.getParentOfType)(e,lP)},get startTime(){let t=0;for(let n of e.store.pages){if(n.id===e.id)break;t+=n.duration}return t}})).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,iV.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=a6(10),lU(e,e=>{e.id=a6(10)})});let r={...n,id:a6(10),...t},i=e.store.addPage(r),o=e.store.pages.indexOf(e);i.setZIndex(o+1),i.select()},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=lW[t.type];if(!r){console.error("Can not find model with type "+t.type);return}t.children&&t.children.forEach(e=>{e.id=a6(10)});let i=r.create({id:a6(10),...t});return e.children.push(i),i.selectable&&!n&&e.store.selectElements([i.id]),i},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,iV.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,iV.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,iV.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=t/e.computedWidth,i=n/e.computedHeight,o=Math.min(r,i),a=Math.max(0,(t-e.computedWidth*o)/2),l=Math.max(0,(n-e.computedHeight*o)/2);lU(e,t=>{"group"!==t.type&&("image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2?t.set({x:t.x*o,y:t.y*o,width:t.width*r,height:t.height*i,cropX:0,cropY:0,cropWidth:1,cropHeight:1}):(t.set({x:a+t.x*o,y:l+t.y*o,width:t.width*o,height:t.height*o}),"text"===t.type?t.set({fontSize:t.fontSize*o}):"figure"===t.type&&t.set({strokeWidth:t.strokeWidth*o})))})}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})}}));(0,iV.setLivelinessChecking)("ignore");let lk=(0,iV.types).model("Font",{fontFamily:iV.types.string,url:(0,iV.types).optional(iV.types.string,""),styles:(0,iV.types).frozen()}).preProcessSnapshot(e=>({...e,fontFamily:e.fontFamily||e.name})),lP=(0,iV.types).model("Store",{role:"",pages:(0,iV.types).array(lO),fonts:(0,iV.types).array(lk),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",custom:(0,iV.types).frozen(),selectedElementsIds:(0,iV.types).array(iV.types.string),animatedElementsIds:(0,iV.types).array(iV.types.string),history:(0,iV.types).optional(a8,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(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 lU({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 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 lU({children:e.pages},e=>{if(!n&&t(e))return n=e,!0}),n},getElementById:t=>e.find(e=>e.id===t)})).actions(e=>{let t=0,n=null,r=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=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,iV.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,iV.cast)([]),e.checkActivePage()}}}).actions(e=>({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},addPage(t){let n=lO.create({id:a6(10),...t});return e.pages.push(n),e._activePageId=n.id,n},selectPage(t){e._activePageId=t},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,iV.cast)(n)},toggleBleed(t){e.bleedVisible=t??!e.bleedVisible},toggleRulers(t){e.rulesVisible=t??!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,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,iV.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,iV.destroy)(n)});let r=Math.min(e.pages.length-1,n),i=e.pages[r];i&&(e._activePageId=i.id),e.selectedElementsIds=(0,iV.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},groupElements(t){let n=t.map(t=>e.getElementById(t));n.forEach(e=>{e&&(0,iV.detach)(e)});let r=e.activePage,i={id:a6(10),children:n,type:"group"};return r.children.push(i),e.selectedElementsIds=(0,iV.cast)([i.id]),i},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,iV.detach)(e),t.children.push(e)}),t.children.splice(n,1)}}),e.selectedElementsIds=(0,iV.cast)(r)},deleteElements(t){t.forEach(t=>{e.pages.forEach(e=>{let n=e.children.find(e=>e.id===t);n&&(0,iV.destroy)(n)})}),e.selectedElementsIds=(0,iV.cast)(e.selectedElementsIds.filter(t=>e.getElementById(t)))},on(t,n){if("change"===t){let t=e.toJSON();return(0,iV.onSnapshot)(e,r=>{let i=e.toJSON();a4(t,i)||(t=i,n(i))})}},async _toCanvas({pixelRatio:t,ignoreBackground:n,pageId:r,mimeType:i,includeBleed:o,_skipTimeout:a}={}){let l=t||1;r=r||e.pages[0]?.id;let s=e.pages.find(e=>e.id===r);if(!s)throw Error(`No page for export with id ${r}`);s?.set({_exporting:!0});let c=await le(()=>u(j).stages.find(e=>e.getAttr("pageId")===r));if(!c)throw 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.`);let d=!!c.findOne(".page-container"),h=e._elementsPixelRatio;l>e._elementsPixelRatio&&e.setElementsPixelRatio(l),await e.waitLoading({_skipTimeout:a});let f=c.findOne(".page-container");if(!f)throw e.setElementsPixelRatio(h),Error(`Export is failed. Can't find page container. ${d}`);c.find("Transformer").forEach(e=>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 p=f.findOne(".page-background-group"),g=p.clip();p.clip({x:null,y:null,width:null,height:null});let m=f.findOne(".elements-container"),v=m.clip();m.clip({x:null,y:null,width:null,height:null});let y=f.find(e=>e.getAttr("hideInExport"));y.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()});let b=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled"));b.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()}),n&&f.find(".page-background").forEach(e=>e.hide());let w=o?s.bleed:0,x=w;!e.bleedVisible&&o||(e.bleedVisible||o?e.bleedVisible&&o?x=0:e.bleedVisible&&!o&&(x=-s.bleed):x=0);let _=document.createElement("canvas");_.width=Math.round((s.computedWidth+2*w)*l),_.height=Math.round((s.computedHeight+2*w)*l);let E=_.getContext("2d");"image/jpeg"===i&&(E.fillStyle="white",E.fillRect(0,0,_.width,_.height));let S=f.scale();f.scale({x:1,y:1});let C=f.toCanvas({x:f.x()-x,y:f.y()-x,width:s.computedWidth+2*w,height:s.computedHeight+2*w,pixelRatio:l});return f.scale(S),E.drawImage(C,0,0,_.width,_.height),u(j).Util.releaseCanvas(C),n&&f.find(".page-background").forEach(e=>e.show()),y.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)),c.find("Transformer").forEach(e=>e.visible(!0)),f.find(".highlighter").forEach(e=>e.visible(!0)),p.clip(g),m.clip(v),e.setElementsPixelRatio(h),s?.set({_exporting:!1}),_},async toDataURL({mimeType:t,quality:n,...r}={}){let i=await e._toCanvas({mimeType:t,...r}),o=i.toDataURL(t,n);return u(j).Util.releaseCanvas(i),o},async toBlob({mimeType:t,quality:n,...r}={}){let i=await e._toCanvas({mimeType:t,...r}),o=new Promise(e=>{i.toBlob(e,t,n)});return u(j).Util.releaseCanvas(i),o},async saveAsImage({fileName:t,...n}={}){let r=n.mimeType||"image/png",i=r.split("/")[1];a9(await e.toDataURL(n),t||"polotno."+i,r)},async _toPDF(n){let r=n.dpi||e.dpi,i=n.parallel||1,o=n.unit||("px"===e.unit?"mm":e.unit),a=n.pixelRatio||1,l=n.pageIds||e.pages.map(e=>e.id),s=e.pages.filter(e=>l.includes(e.id)),u=await (t?Promise.resolve(t):new Promise(e=>{var n=document.createElement("script");n.onload=function(){e(t=window.jspdf.jsPDF)},n.src="https://unpkg.com/jspdf@2.2.0/dist/jspdf.umd.min.js",document.head.appendChild(n)})),c=e=>aj({px:e,unit:o,dpi:r}),d=c(n.cropMarkSize||0),h=s[0]||{},f=n.includeBleed?h.bleed:0,p=c(h.computedWidth+2*f)+2*d,g=c(h.computedHeight+2*f)+2*d;var m=new u({unit:o,orientation:p>g?"landscape":"portrait",format:[p,g],compress:!0,putOnlyUsedFonts:!0});for(let t of(m.deletePage(1),((e,t)=>{for(var n=[],r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n})(s,i))){let r=t.map(async t=>{let r=n.includeBleed?t.bleed:0,i=c(t.computedWidth+2*r)+2*d,o=c(t.computedHeight+2*r)+2*d,l=0,s=a;for(;l<10;){2===(l+=1)&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");let r=await e.toDataURL({...n,pageId:t.id,pixelRatio:s});if(r.length>20)return{url:r,width:i,height:o};s*=.8}});(await Promise.all(r)).forEach(({url:e,width:t,height:n})=>{m.addPage([t,n],t>n?"landscape":"portrait"),d&&(m.setLineWidth(c(1)),m.line(2*d,0,2*d,d),m.line(0,2*d,d,2*d),m.line(t-2*d,0,t-2*d,d),m.line(t,2*d,t-d,2*d),m.line(0,n-2*d,d,n-2*d),m.line(2*d,n,2*d,n-d),m.line(t,n-2*d,t-d,n-2*d),m.line(t-2*d,n,t-2*d,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 a7({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}={}){a9(await e.toGIFDataURL(n),t||"polotno.gif")},toHTML:async({elementHook:t}={elementHook:void 0})=>lp({json:e.toJSON(),elementHook:t}),async saveAsHTML({fileName:t}={}){let n=await e.toHTML();a9("data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(n))),t||"polotno.html")},toSVG:async()=>lC({json:e.toJSON()}),async saveAsSVG({fileName:t}={}){let n=await e.toSVG();a9("data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n))),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=()=>{id()?setTimeout(e,300):e(!0)},void(0===ip?t():ig.push(t))})},toJSON:()=>({width:e.width,height:e.height,fonts:(0,iV.getSnapshot)(e.fonts),pages:(0,iV.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi,custom:e.custom}),loadJSON(t,n=!1){let r={...t},i=e.pages.indexOf(e.activePage),o=(r.pages[i]||r.pages[0])?.id;r._activePageId=o;let a={...(0,iV.getSnapshot)(e)};Object.assign(a,r),n?a.history=e.history.toJSON():a.history={history:[],undoIdx:-1},(0,iV.applySnapshot)(e,a)},clear({keepHistory:t=!1}={}){let n=e.pages.map(e=>e.id);e.deletePages(n),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,iV.destroy)(e))},async loadFont(t){let n=e.fonts.find(e=>e.fontFamily===t)||iS.find(e=>e.fontFamily===t);n?function(e){let t=e.fontFamily;if(ij[t]||!e.url&&!e.styles)return;let n=document.createElement("style");n.type="text/css";let r=e.styles||(e.url?[{src:`url("${e.url}")`}]:[]),i="";r.forEach(e=>{i+=`
|
|
152
152
|
@font-face {
|
|
153
153
|
font-family: '${t}';
|
|
154
154
|
src: ${e.src};
|