polotno 4.11.0 → 4.12.1
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/README.md +57 -22
- package/blueprint/side-panel/select-video.d.ts +6 -2
- package/canvas/crop-overlay.d.ts +42 -0
- package/canvas/crop-overlay.js +1 -0
- package/canvas/downscale-bands.d.ts +10 -0
- package/canvas/downscale-bands.js +1 -0
- package/canvas/downscale-kernel.d.ts +7 -0
- package/canvas/downscale-kernel.js +1 -0
- package/canvas/downscale-kernel.wasm.d.ts +1 -0
- package/canvas/downscale-kernel.wasm.js +1 -0
- package/canvas/downscale-passes.d.ts +7 -0
- package/canvas/downscale-passes.js +1 -0
- package/canvas/downscale.d.ts +16 -2
- package/canvas/downscale.js +1 -1
- package/canvas/drawing-layer.js +1 -1
- package/canvas/element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/hotkeys.js +1 -1
- package/canvas/image-element.d.ts +10 -0
- package/canvas/image-element.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/tooltip.js +1 -1
- package/canvas/transform-box.d.ts +9 -0
- package/canvas/transform-box.js +1 -0
- package/canvas/use-image.d.ts +4 -0
- package/canvas/use-image.js +1 -0
- package/canvas/video-element.js +1 -1
- package/canvas/workspace-canvas.d.ts +3 -1
- package/canvas/workspace-canvas.js +1 -1
- package/canvas/workspace-style.d.ts +4 -0
- package/canvas/workspace-style.js +1 -1
- package/model/crop-mode.d.ts +34 -0
- package/model/crop-mode.js +1 -0
- package/model/figure-model.d.ts +1 -1
- package/model/gif-model.d.ts +3 -1
- package/model/group-model.d.ts +21 -8
- package/model/image-model.d.ts +3 -1
- package/model/image-model.js +1 -1
- package/model/line-model.d.ts +1 -1
- package/model/page-model.d.ts +23 -10
- package/model/shape-model.d.ts +2 -2
- package/model/shape-model.js +1 -1
- package/model/store.d.ts +236 -97
- package/model/store.js +1 -1
- package/model/svg-model.d.ts +8 -1
- package/model/svg-model.js +1 -1
- package/model/table-model.d.ts +1 -1
- package/model/text-model.d.ts +1 -1
- package/model/video-model.d.ts +3 -1
- package/package.json +45 -26
- package/polotno.bundle.js +180 -194
- package/side-panel/draw-panel.js +1 -1
- package/side-panel/select-image.js +1 -1
- package/side-panel/select-video.d.ts +6 -2
- package/toolbar/image-toolbar.d.ts +7 -2
- package/toolbar/image-toolbar.js +1 -1
- package/toolbar/svg-toolbar.js +1 -1
- package/toolbar/toolbar.js +1 -1
- package/utils/base64.d.ts +1 -1
- package/utils/clipboard.d.ts +2 -2
- package/utils/fonts.d.ts +1 -0
- package/utils/fonts.js +1 -1
- package/utils/html2canvas.js +1 -1
- package/utils/l10n.d.ts +4 -0
- package/utils/l10n.js +1 -1
- package/utils/path-to-svg.d.ts +0 -2
- package/utils/path-to-svg.js +1 -1
- package/utils/px.d.ts +1 -0
- package/utils/px.js +1 -1
- package/utils/rich-text-html.d.ts +0 -10
- package/utils/rich-text-html.js +1 -1
- package/utils/validate-key.js +1 -1
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as I,createExportCanvases as T,releaseExportCanvases as _}from"../utils/canvas.js";import{whenLoaded as S}from"../utils/loader.js";import{polotnoError as O}from"@polotno/core/errors";import{pxToUnit as k}from"../utils/unit.js";import{deepEqual as R}from"../utils/deep-equal.js";import{waitTillAvailable as j}from"../utils/wait.js";import{jsonToHTML as F}from"@polotno/html-export";import{jsonToSVG as A}from"@polotno/svg-export";import{warnOnceDeprecated as V}from"../utils/deprecation.js";import{Page as C}from"./page-model.js";import{forEveryChild as L,forEveryNode as M}from"./group-model.js";import{Audio as D}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(C),fonts:l.array(Font),audios:l.array(D),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return M({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return L({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const i of e.pages){if(t>=i.startTime&&t<i.startTime+i.duration){return i}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return M({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const i=d||r.duration;r.currentTime>=i&&!g&&(r.currentTime=i),f.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=C.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=i([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,i=>{const o=f.toJSON();!R(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw O("EXPORT_FAILED",`No page for export with id ${i}`,{reason:"page-not-found",pageId:i,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;try{(s?p>r._elementsPixelRatio:p!==r._elementsPixelRatio)&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const e=await j(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!e){throw O("EXPORT_FAILED",`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:i})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const d=e[0];await f.waitLoading({_skipTimeout:a});const u=d.findOne(".page-container");if(!u){throw O("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:i})}const h=d.position();d.position({x:0,y:0}),d.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),u.find(".page-background").forEach(e=>e.shadowEnabled(!1)),u.find(".page-background").forEach(e=>e.strokeEnabled(!1)),u.find(".highlighter").forEach(e=>e.visible(!1));const v=u.findOne(".page-background-group"),b=v.clip();v.clip({x:null,y:null,width:null,height:null});const y=u.findOne(".elements-container"),P=y.clip();y.clip({x:null,y:null,width:null,height:null});const w=u.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const E=u.find(e=>e.getAttr("hideInExport"));E.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&u.find(".page-background").forEach(e=>e.hide());const T=n?g.computedBleed:m;let _=T.left,S=T.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(_=0,S=0):r.bleedVisible&&!n&&(_=-g.computedBleed.left,S=-g.computedBleed.top):(_=0,S=0));const k=g.computedWidth+T.left+T.right,R=g.computedHeight+T.top+T.bottom,F=u.scale();u.scale({x:1,y:1});const A=I(u,{x:u.x()-_,y:u.y()-S,width:k,height:R,pixelRatio:p,imageSmoothingQuality:x.imageDownScalingEnabled&&!s?"high":void 0,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});u.scale(F);const V=A._canvas;if("image/jpeg"===o){const e=V.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,V.width,V.height),e.restore()}return t&&u.find(".page-background").forEach(e=>e.show()),E.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".page-background").forEach(e=>e.shadowEnabled(!0)),u.find(".page-background").forEach(e=>e.strokeEnabled(!0)),d.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".highlighter").forEach(e=>e.visible(!0)),v.clip(b),y.clip(P),d.position(h),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),V}finally{f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1})}},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",p=l.toDataURL(d,o);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];h(await f.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>k({px:e,unit:o,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:o,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const r of P){const t=r.map(async t=>{const i=e.includeBleed?t.computedBleed:m,o=t.computedWidth+i.left+i.right+2*p,s=t.computedHeight+i.top+i.bottom+2*p,r=d(o),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:o,heightPx:s,cb:i}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,i],t>i?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(o){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw O("EXPORT_FAILED","Invalid unit: "+o,{reason:"invalid-options",option:"unit",value:o})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:i*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),o=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-o,0,t-o,c),y.line(t,n,t-c,n),y.line(0,i-a,c,i-a),y.line(e,i,e,i-c),y.line(t,i-a,t-c,i-a),y.line(t-o,i,t-o,i-c)}y.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw O("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=o[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10),l=T(),d=r._elementsPixelRatio;f.setElementsPixelRatio(t);try{for(const e of o){const i=Math.max(1,Math.floor(e.duration/s));for(let o=0;o<i;o++){const i=e.startTime+o*s||1;f.setCurrentTime(i);for(const t of r.pages){t.set({_rendering:t.id===e.id})}const n=await f._toCanvas({pixelRatio:t,pageId:e.id,_skipTimeout:!0,_exportCanvases:l});a.addFrame(n.getContext("2d"),{delay:s,copy:!0})}}}finally{_(l),f.setElementsPixelRatio(d)}for(const p of r.pages){p.set({_rendering:!1})}return f.stop(),a.render(),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,o=e(t,["fileName"]);const n=await f.toGIFDataURL(o);h(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){V("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return F(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await f.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));h(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;V("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return A(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await S()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n;const s="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,l="boolean"==typeof i||null==i?void 0:i.modernizeTextBackground,d=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[];const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){f.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=D.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as T,createExportCanvases as I,releaseExportCanvases as _}from"../utils/canvas.js";import{whenLoaded as O}from"../utils/loader.js";import{polotnoError as S}from"@polotno/core/errors";import{pxToUnit as k}from"../utils/unit.js";import{deepEqual as R}from"../utils/deep-equal.js";import{waitTillAvailable as j}from"../utils/wait.js";import{jsonToHTML as F}from"@polotno/html-export";import{jsonToSVG as A}from"@polotno/svg-export";import{warnOnceDeprecated as C}from"../utils/deprecation.js";import{Page as V}from"./page-model.js";import{forEveryChild as L,forEveryNode as M}from"./group-model.js";import{Audio as B}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));const D=l.model("BrushOptions",{strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)});export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(V),fonts:l.array(Font),audios:l.array(B),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),brush:l.optional(D,{}),highlighter:l.optional(D,{strokeWidth:30,opacity:.5})}).views(e=>({get active(){return e[e.brushType]}})).views(e=>({get strokeWidth(){return e.active.strokeWidth},get stroke(){return e.active.stroke},get opacity(){return e.active.opacity}})),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return M({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return L({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>!0===e._cropModeEnabled)},find(t){let o;return M({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(t){const{brushType:o}=t,i=e(t,["brushType"]);o&&(r.toolOptions.brushType=o),Object.assign(r.toolOptions.active,i)},addPage(e){const t=V.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:i,type:"group"},t);return a.children.push(l),r.selectedElementsIds=o([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(o,1)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!R(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;o=o||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===o);if(!g){throw S("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;try{(s?p>r._elementsPixelRatio:p!==r._elementsPixelRatio)&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const e=await j(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!e){throw S("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const d=e[0];await f.waitLoading({_skipTimeout:a});const u=d.findOne(".page-container");if(!u){throw S("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const h=d.position();d.position({x:0,y:0}),d.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),u.find(".page-background").forEach(e=>e.shadowEnabled(!1)),u.find(".page-background").forEach(e=>e.strokeEnabled(!1)),u.find(".highlighter").forEach(e=>e.visible(!1));const v=u.findOne(".page-background-group"),b=v.clip();v.clip({x:null,y:null,width:null,height:null});const y=u.findOne(".elements-container"),P=y.clip();y.clip({x:null,y:null,width:null,height:null});const w=u.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const E=u.find(e=>e.getAttr("hideInExport"));E.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&u.find(".page-background").forEach(e=>e.hide());const I=n?g.computedBleed:m;let _=I.left,O=I.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(_=0,O=0):r.bleedVisible&&!n&&(_=-g.computedBleed.left,O=-g.computedBleed.top):(_=0,O=0));const k=g.computedWidth+I.left+I.right,R=g.computedHeight+I.top+I.bottom,F=u.scale();u.scale({x:1,y:1});const A=T(u,{x:u.x()-_,y:u.y()-O,width:k,height:R,pixelRatio:p,imageSmoothingQuality:x.imageDownScalingEnabled&&!s?"high":void 0,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});u.scale(F);const C=A._canvas;if("image/jpeg"===i){const e=C.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,C.width,C.height),e.restore()}return t&&u.find(".page-background").forEach(e=>e.show()),E.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".page-background").forEach(e=>e.shadowEnabled(!0)),u.find(".page-background").forEach(e=>e.strokeEnabled(!0)),d.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".highlighter").forEach(e=>e.visible(!0)),v.clip(b),y.clip(P),d.position(h),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),C}finally{f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1})}},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>k({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:i,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let w=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw S("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,o=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),i=r.pages.filter(e=>o.includes(e.id));if(!i.length){throw S("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=i[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10),l=I(),d=r._elementsPixelRatio;f.setElementsPixelRatio(t);try{for(const e of i){const o=Math.max(1,Math.floor(e.duration/s));for(let i=0;i<o;i++){const o=e.startTime+i*s||1;f.setCurrentTime(o);for(const t of r.pages){t.set({_rendering:t.id===e.id})}const n=await f._toCanvas({pixelRatio:t,pageId:e.id,_skipTimeout:!0,_exportCanvases:l});a.addFrame(n.getContext("2d"),{delay:s,copy:!0})}}}finally{_(l),f.setElementsPixelRatio(d)}for(const p of r.pages){p.set({_rendering:!1})}return f.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){C("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return F(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;C("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return A(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:o})},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await O()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,l="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[];const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.fonts.filter(t=>t.fontFamily===e.fontFamily).forEach(e=>i(e)),r.fonts.push(e),w.injectCustomFont(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e)),w.removeCustomFont(e)},addAudio(e){const t=B.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
|
package/model/svg-model.d.ts
CHANGED
|
@@ -143,7 +143,7 @@ export declare const SVGElement: import("mobx-state-tree").IModelType<{
|
|
|
143
143
|
} & {
|
|
144
144
|
readonly locked: boolean;
|
|
145
145
|
readonly a: import("./shape-model.js").AnimatedAttrs;
|
|
146
|
-
animated(attr:
|
|
146
|
+
animated(attr: string): any;
|
|
147
147
|
readonly timeRange: {
|
|
148
148
|
start: number;
|
|
149
149
|
end: number;
|
|
@@ -157,6 +157,13 @@ export declare const SVGElement: import("mobx-state-tree").IModelType<{
|
|
|
157
157
|
} & {
|
|
158
158
|
replaceColor(oldColor: any, newColor: any): void;
|
|
159
159
|
resetColors(): void;
|
|
160
|
+
} & {
|
|
161
|
+
toggleCropMode(flag?: boolean): void;
|
|
162
|
+
cancelCropMode(): void;
|
|
163
|
+
beforeDestroy(): void;
|
|
164
|
+
} & {
|
|
165
|
+
readonly _cropModeEnabled: boolean;
|
|
166
|
+
readonly _cropEnabled: boolean;
|
|
160
167
|
}, any, import("mobx-state-tree").ModelSnapshotType<{
|
|
161
168
|
id: import("mobx-state-tree").ISimpleType<string>;
|
|
162
169
|
type: import("mobx-state-tree").IType<string | undefined, string, string>;
|
package/model/svg-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{types as e}from"mobx-state-tree";import{Shape as r}from"./shape-model.js";export const SVGElement=r.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,stretchEnabled:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:e.map(e.string)}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource,colorsReplace:Array.isArray(e.colorsReplace)?{}:e.colorsReplace})).actions(e=>({replaceColor(r,o){e.colorsReplace.set(r,o)},resetColors(){e.colorsReplace.clear()}}));
|
|
1
|
+
import{types as e}from"mobx-state-tree";import{Shape as r}from"./shape-model.js";import{cropMode as o}from"./crop-mode.js";export const SVGElement=r.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,stretchEnabled:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:e.map(e.string)}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource,colorsReplace:Array.isArray(e.colorsReplace)?{}:e.colorsReplace})).actions(e=>({replaceColor(r,o){e.colorsReplace.set(r,o)},resetColors(){e.colorsReplace.clear()}})).extend(o);
|
package/model/table-model.d.ts
CHANGED
|
@@ -427,7 +427,7 @@ export declare const TableElement: import("mobx-state-tree").IModelType<{
|
|
|
427
427
|
} & {
|
|
428
428
|
readonly locked: boolean;
|
|
429
429
|
readonly a: import("./shape-model.js").AnimatedAttrs;
|
|
430
|
-
animated(attr:
|
|
430
|
+
animated(attr: string): any;
|
|
431
431
|
readonly timeRange: {
|
|
432
432
|
start: number;
|
|
433
433
|
end: number;
|
package/model/text-model.d.ts
CHANGED
|
@@ -154,7 +154,7 @@ export declare const TextElement: import("mobx-state-tree").IModelType<{
|
|
|
154
154
|
} & {
|
|
155
155
|
readonly locked: boolean;
|
|
156
156
|
readonly a: import("./shape-model.js").AnimatedAttrs;
|
|
157
|
-
animated(attr:
|
|
157
|
+
animated(attr: string): any;
|
|
158
158
|
readonly timeRange: {
|
|
159
159
|
start: number;
|
|
160
160
|
end: number;
|
package/model/video-model.d.ts
CHANGED
|
@@ -149,7 +149,7 @@ export declare const VideoElement: import("mobx-state-tree").IModelType<{
|
|
|
149
149
|
} & {
|
|
150
150
|
readonly locked: boolean;
|
|
151
151
|
readonly a: import("./shape-model.js").AnimatedAttrs;
|
|
152
|
-
animated(attr:
|
|
152
|
+
animated(attr: string): any;
|
|
153
153
|
readonly timeRange: {
|
|
154
154
|
start: number;
|
|
155
155
|
end: number;
|
|
@@ -162,9 +162,11 @@ export declare const VideoElement: import("mobx-state-tree").IModelType<{
|
|
|
162
162
|
setFilter(type: any, value: any): void;
|
|
163
163
|
} & {
|
|
164
164
|
toggleCropMode(flag?: boolean): void;
|
|
165
|
+
cancelCropMode(): void;
|
|
165
166
|
beforeDestroy(): void;
|
|
166
167
|
} & {
|
|
167
168
|
readonly _cropModeEnabled: boolean;
|
|
169
|
+
readonly _cropEnabled: boolean;
|
|
168
170
|
}, import("mobx-state-tree").ModelCreationType<{
|
|
169
171
|
id: string;
|
|
170
172
|
type: string | undefined;
|
package/package.json
CHANGED
|
@@ -1,13 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno",
|
|
3
|
-
"version": "4.
|
|
4
|
-
"description": "Design
|
|
3
|
+
"version": "4.12.1",
|
|
4
|
+
"description": "Design editor SDK: embed a Canva-like editor, generate designs from templates and data, export PNG, PDF, and video in the browser or on a server.",
|
|
5
5
|
"author": "Anton Lavrenov",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/polotno-project/polotno.git",
|
|
9
|
+
"directory": "packages/polotno"
|
|
10
|
+
},
|
|
6
11
|
"keywords": [
|
|
7
12
|
"polotno",
|
|
13
|
+
"design editor sdk",
|
|
14
|
+
"design editor",
|
|
15
|
+
"canvas editor",
|
|
16
|
+
"canva-like",
|
|
17
|
+
"image editor",
|
|
18
|
+
"video editor",
|
|
19
|
+
"konva",
|
|
20
|
+
"react-konva",
|
|
21
|
+
"react",
|
|
8
22
|
"canvas",
|
|
9
|
-
"
|
|
10
|
-
"
|
|
23
|
+
"templates",
|
|
24
|
+
"pdf",
|
|
25
|
+
"psd",
|
|
26
|
+
"mcp",
|
|
27
|
+
"agent-skills"
|
|
11
28
|
],
|
|
12
29
|
"type": "module",
|
|
13
30
|
"exports": {
|
|
@@ -96,33 +113,32 @@
|
|
|
96
113
|
},
|
|
97
114
|
"dependencies": {
|
|
98
115
|
"@base-ui/react": "^1.7.0",
|
|
99
|
-
"@polotno/core": "0.
|
|
100
|
-
"@polotno/html-export": "0.5.
|
|
116
|
+
"@polotno/core": "0.11.0",
|
|
117
|
+
"@polotno/html-export": "0.5.2",
|
|
101
118
|
"@polotno/schema": "0.6.1",
|
|
102
|
-
"@polotno/svg-export": "0.6.
|
|
119
|
+
"@polotno/svg-export": "0.6.2",
|
|
103
120
|
"class-variance-authority": "^0.7.1",
|
|
104
121
|
"clsx": "^2.1.1",
|
|
105
122
|
"gifuct-js": "^2.1.2",
|
|
106
|
-
"konva": "^10.
|
|
123
|
+
"konva": "^10.5.0",
|
|
107
124
|
"lodash-es": "^4.18.1",
|
|
108
|
-
"lucide-react": "^1.
|
|
109
|
-
"mediabunny": "^1.
|
|
125
|
+
"lucide-react": "^1.39.0",
|
|
126
|
+
"mediabunny": "^1.55.5",
|
|
110
127
|
"mobx": "6.16.1",
|
|
111
128
|
"mobx-react-lite": "^4.1.1",
|
|
112
|
-
"mobx-state-tree": "7.
|
|
129
|
+
"mobx-state-tree": "7.4.0",
|
|
113
130
|
"nanoid": "^6.0.1",
|
|
114
131
|
"quill": "^2.0.3",
|
|
115
|
-
"react-konva": "^19.2.
|
|
132
|
+
"react-konva": "^19.2.7",
|
|
116
133
|
"react-konva-utils": "^2.0.0",
|
|
117
134
|
"react-sortablejs": "6.1.4",
|
|
118
135
|
"react-window": "^2.3.0",
|
|
119
136
|
"render-tag": "^0.1.35",
|
|
120
137
|
"sortablejs": "^1.15.7",
|
|
121
138
|
"svg-round-corners": "^0.4.3",
|
|
122
|
-
"swr": "^2.5.
|
|
139
|
+
"swr": "^2.5.1",
|
|
123
140
|
"tailwind-merge": "^3.6.0",
|
|
124
|
-
"tinycolor2": "^1.6.0"
|
|
125
|
-
"use-image": "^1.1.4"
|
|
141
|
+
"tinycolor2": "^1.6.0"
|
|
126
142
|
},
|
|
127
143
|
"targets": {
|
|
128
144
|
"bundle": {
|
|
@@ -164,13 +180,14 @@
|
|
|
164
180
|
"@tailwindcss/cli": "^4.3.3",
|
|
165
181
|
"@tailwindcss/vite": "^4.3.3",
|
|
166
182
|
"@testing-library/dom": "^10.4.1",
|
|
167
|
-
"@testing-library/react": "^16.3.
|
|
183
|
+
"@testing-library/react": "^16.3.3",
|
|
168
184
|
"@types/react": "^19.2.18",
|
|
169
|
-
"@vitejs/plugin-react": "^6.
|
|
170
|
-
"@vitest/browser": "^4.1.
|
|
171
|
-
"@vitest/browser-playwright": "^4.1.
|
|
185
|
+
"@vitejs/plugin-react": "^6.1.1",
|
|
186
|
+
"@vitest/browser": "^4.1.11",
|
|
187
|
+
"@vitest/browser-playwright": "^4.1.11",
|
|
188
|
+
"assemblyscript": "^0.28.20",
|
|
172
189
|
"assert": "^2.1.0",
|
|
173
|
-
"bippy": "^0.
|
|
190
|
+
"bippy": "^0.7.3",
|
|
174
191
|
"buffer": "^6.0.3",
|
|
175
192
|
"canvas": "^3.2.3",
|
|
176
193
|
"filehound": "^1.17.6",
|
|
@@ -180,17 +197,17 @@
|
|
|
180
197
|
"license-checker": "^25.0.1",
|
|
181
198
|
"playwright": "^1.62.1",
|
|
182
199
|
"postcss": "^8.5.26",
|
|
183
|
-
"postcss-selector-parser": "^7.1.
|
|
200
|
+
"postcss-selector-parser": "^7.1.5",
|
|
184
201
|
"pptxgenjs": "^4.0.1",
|
|
185
202
|
"process": "^0.11.10",
|
|
186
203
|
"react": "^19.2.8",
|
|
187
204
|
"react-dom": "^19.2.8",
|
|
188
205
|
"tailwindcss": "^4.3.3",
|
|
189
|
-
"terser": "^5.
|
|
206
|
+
"terser": "^5.51.2",
|
|
190
207
|
"tw-animate-css": "^1.4.0",
|
|
191
208
|
"typescript": "~6.0.3",
|
|
192
|
-
"vite": "^8.2.
|
|
193
|
-
"vitest": "^4.1.
|
|
209
|
+
"vite": "^8.2.2",
|
|
210
|
+
"vitest": "^4.1.11"
|
|
194
211
|
},
|
|
195
212
|
"homepage": "https://polotno.com/",
|
|
196
213
|
"scripts": {
|
|
@@ -205,14 +222,16 @@
|
|
|
205
222
|
"check:parity": "node build/structural-parity.cjs",
|
|
206
223
|
"test:parity": "pnpm run check:parity && pnpm run check:agreement && pnpm run check:css",
|
|
207
224
|
"minify": "node minify.cjs",
|
|
208
|
-
"build": "pnpm run clean && pnpm run prefix-build && pnpm run tsc && pnpm run add_version && node rename-imports.js && pnpm run minify && pnpm run build:css && pnpm run check:css && pnpm run check:agreement && pnpm run build:bundle && node blueprint-scope.js && cp ./src/fonts.css ./lib/fonts.css && mkdir -p ./lib/themes && cp ./src/themes/blueprint.css ./lib/themes/blueprint.css && cp ./src/themes/carbon.css ./lib/themes/carbon.css && node build/copy-package-json.cjs && cp ./README.md ./lib && cp ./LICENSE.md ./lib && pnpm run remove-test-from-lib",
|
|
225
|
+
"build": "pnpm run check:wasm && pnpm run clean && pnpm run prefix-build && pnpm run tsc && pnpm run add_version && node rename-imports.js && pnpm run minify && pnpm run build:css && pnpm run check:css && pnpm run check:agreement && pnpm run build:bundle && node blueprint-scope.js && cp ./src/fonts.css ./lib/fonts.css && mkdir -p ./lib/themes && cp ./src/themes/blueprint.css ./lib/themes/blueprint.css && cp ./src/themes/carbon.css ./lib/themes/carbon.css && node build/copy-package-json.cjs && cp ./README.md ./lib && cp ./LICENSE.md ./lib && pnpm run remove-test-from-lib",
|
|
209
226
|
"remove-test-from-lib": "find ./lib -type d -name \"__tests__\" -exec rm -rf {} + && find ./lib \\( -name \"*.test.js\" -o -name \"*.test.d.ts\" \\) -type f -delete",
|
|
210
227
|
"add_version": "sed -i.bak 's/SDK_VERSION/'$npm_package_version'/' ./lib/utils/validate-key.js && rm -f ./lib/utils/validate-key.js.bak",
|
|
211
228
|
"build:bundle": "vite build && find ./lib -name '*.js.map' -type f -delete",
|
|
212
229
|
"test": "node scripts/run-tests-parallel.mjs",
|
|
213
230
|
"test:unit": "vitest run --project unit",
|
|
214
231
|
"test:browser": "node scripts/run-browser-sharded.mjs",
|
|
215
|
-
"test:serial": "vitest run"
|
|
232
|
+
"test:serial": "vitest run",
|
|
233
|
+
"build:wasm": "node wasm/build.mjs",
|
|
234
|
+
"check:wasm": "node wasm/build.mjs --check"
|
|
216
235
|
},
|
|
217
236
|
"license": "SEE LICENSE IN LICENSE.md"
|
|
218
237
|
}
|