polotno 2.40.2 → 2.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/model/store.js CHANGED
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{addDpiMetadataToImage as v}from"../utils/image-dpi.js";import{nodeToCanvas as P}from"../utils/canvas.js";import{whenLoaded as w}from"../utils/loader.js";import{pxToUnit as E}from"../utils/unit.js";import{deepEqual as x}from"../utils/deep-equal.js";import{waitTillAvailable as _}from"../utils/wait.js";import{jsonToHTML as k}from"../utils/to-html.js";import{jsonToSVG as I}from"../utils/to-svg.js";import{Page as S}from"./page-model.js";import{forEveryChild as O,forEveryNode as T}from"./group-model.js";import{Audio as j}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(S),fonts:l.array(Font),audios:l.array(j),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:3,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return T({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return O({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},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return T({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 O={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(()=>O.seek())},checkActivePage(){let e=0;for(const t of r.pages){if(r.currentTime>=t.startTime&&r.currentTime<t.startTime+t.duration){O.selectPage(t.id);break}e+=t.duration}},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t,O.checkActivePage();const i=d||r.duration;r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>O.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>O.seek())):O.stop()},stop(){r.isPlaying=!1,r.currentTime=0,r.animatedElementsIds=i([]),O.checkActivePage()},__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=S.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},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=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),a=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const s=a.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=O.toJSON();return s(r,i=>{const o=O.toJSON();!x(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 c=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 new Error(`No page for export with id ${i}`)}const m=r._elementsPixelRatio;c>r._elementsPixelRatio&&O.setElementsPixelRatio(c),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const u=await _(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!u){throw null==g||g.set({_forceMount:!1,_exporting:!1}),O.setElementsPixelRatio(m),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}u.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 f=u[0];await O.waitLoading({_skipTimeout:a});const h=f.findOne(".page-container");if(!h){throw O.setElementsPixelRatio(m),null==g||g.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const b=f.position();f.position({x:0,y:0}),f.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),h.find(".page-background").forEach(e=>e.shadowEnabled(!1)),h.find(".page-background").forEach(e=>e.strokeEnabled(!1)),h.find(".highlighter").forEach(e=>e.visible(!1));const y=h.findOne(".page-background-group"),v=y.clip();y.clip({x:null,y:null,width:null,height:null});const w=h.findOne(".elements-container"),E=w.clip();w.clip({x:null,y:null,width:null,height:null});const x=h.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const k=h.find(e=>e.getAttr("hideInExport"));k.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&h.find(".page-background").forEach(e=>e.hide());const I=n?g.bleed:0;let S=I;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?S=0:r.bleedVisible&&!n&&(S=-g.bleed):S=0);const T=g.computedWidth+2*I,j=g.computedHeight+2*I,R=h.scale();h.scale({x:1,y:1});const F=P(h,{x:h.x()-S,y:h.y()-S,width:T,height:j,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(R);const C=F._canvas;if("image/jpeg"===o){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&&h.find(".page-background").forEach(e=>e.show()),k.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".page-background").forEach(e=>e.shadowEnabled(!0)),h.find(".page-background").forEach(e=>e.strokeEnabled(!0)),f.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".highlighter").forEach(e=>e.visible(!0)),y.clip(v),w.clip(E),f.position(b),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),O.setElementsPixelRatio(m),C},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await O._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",c=l.toDataURL(d,o);p.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?c:v(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await O._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];m(await O.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||r.pages.map(e=>e.id),s=r.pages.filter(e=>a.includes(e.id)),l=await u(),d=e=>E({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let v=0;for(const r of y){const t=r.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,r=d(o),l=d(s);let p=0,g=n;for(;p<10;){p+=1;const i=await O.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(i.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(++v/a.length*.9),{url:i,width:r,height:l,widthPx:o,heightPx:s}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await O._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let a=0;a<n-1;a++){const e=a*o||1;O.setCurrentTime(e);let n=0,s="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){s=t.id;break}}const l=await O._toCanvas({pixelRatio:t,pageId:s,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const a of r.pages){a.set({_rendering:!1})}return O.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await O.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=O.toJSON();return k({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await O.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=O.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 I({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await O.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await O._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await w()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,c=JSON.parse(JSON.stringify(e)),p=c.schemaVersion||0;p<1&&y.htmlRenderEnabled&&T({children:c.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),p<2&&T({children:c.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),p<3&&y.htmlRenderEnabled&&!d&&T({children:c.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete c.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=c.pages[g]||c.pages[0])||void 0===s?void 0:s.id;c._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,c),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);O.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){O.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=j.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||b.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"}))),b.injectCustomFont(n)):b.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>b.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 O});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
1
+ var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{addDpiMetadataToImage as v}from"../utils/image-dpi.js";import{nodeToCanvas as P}from"../utils/canvas.js";import{whenLoaded as w}from"../utils/loader.js";import{pxToUnit as E}from"../utils/unit.js";import{deepEqual as x}from"../utils/deep-equal.js";import{waitTillAvailable as I}from"../utils/wait.js";import{jsonToHTML as _}from"../utils/to-html.js";import{jsonToSVG as k}from"../utils/to-svg.js";import{Page as S}from"./page-model.js";import{forEveryChild as O,forEveryNode as T}from"./group-model.js";import{Audio as j}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(S),fonts:l.array(Font),audios:l.array(j),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:3,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return T({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 O({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},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return T({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 O={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(()=>O.seek())},checkActivePage(){let e=0;for(const t of r.pages){if(r.currentTime>=t.startTime&&r.currentTime<t.startTime+t.duration){O.selectPage(t.id);break}e+=t.duration}},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t,O.checkActivePage();const i=d||r.duration;r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>O.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>O.seek())):O.stop()},stop(){r.isPlaying=!1,r.currentTime=0,r.animatedElementsIds=i([]),O.checkActivePage()},__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=S.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).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},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=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).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:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.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=O.toJSON();return s(r,i=>{const o=O.toJSON();!x(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 c=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 new Error(`No page for export with id ${i}`)}const m=r._elementsPixelRatio;c>r._elementsPixelRatio&&O.setElementsPixelRatio(c),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const u=await I(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!u){throw null==g||g.set({_forceMount:!1,_exporting:!1}),O.setElementsPixelRatio(m),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}u.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 f=u[0];await O.waitLoading({_skipTimeout:a});const h=f.findOne(".page-container");if(!h){throw O.setElementsPixelRatio(m),null==g||g.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const b=f.position();f.position({x:0,y:0}),f.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),h.find(".page-background").forEach(e=>e.shadowEnabled(!1)),h.find(".page-background").forEach(e=>e.strokeEnabled(!1)),h.find(".highlighter").forEach(e=>e.visible(!1));const y=h.findOne(".page-background-group"),v=y.clip();y.clip({x:null,y:null,width:null,height:null});const w=h.findOne(".elements-container"),E=w.clip();w.clip({x:null,y:null,width:null,height:null});const x=h.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const _=h.find(e=>e.getAttr("hideInExport"));_.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&h.find(".page-background").forEach(e=>e.hide());const k=n?g.bleed:0;let S=k;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?S=0:r.bleedVisible&&!n&&(S=-g.bleed):S=0);const T=g.computedWidth+2*k,j=g.computedHeight+2*k,R=h.scale();h.scale({x:1,y:1});const F=P(h,{x:h.x()-S,y:h.y()-S,width:T,height:j,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(R);const C=F._canvas;if("image/jpeg"===o){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&&h.find(".page-background").forEach(e=>e.show()),_.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".page-background").forEach(e=>e.shadowEnabled(!0)),h.find(".page-background").forEach(e=>e.strokeEnabled(!0)),f.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".highlighter").forEach(e=>e.visible(!0)),y.clip(v),w.clip(E),f.position(b),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),O.setElementsPixelRatio(m),C},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await O._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",c=l.toDataURL(d,o);p.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?c:v(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await O._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];m(await O.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 u(),d=e=>E({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let v=0;for(const r of y){const t=r.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,r=d(o),l=d(s);let p=0,g=n;for(;p<10;){p+=1;const i=await O.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(i.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(++v/a.length*.9),{url:i,width:r,height:l,widthPx:o,heightPx:s}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await O._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 new Error("No pages found for GIF export")}const n=o[0],a=await f({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of o){const e=Math.max(1,Math.floor(l.duration/s));for(let i=0;i<e;i++){const e=l.startTime+i*s||1;O.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await O._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(o.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return O.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 O.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=O.toJSON();return _({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await O.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=O.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 k({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await O.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await O._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await w()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,c=JSON.parse(JSON.stringify(e)),p=c.schemaVersion||0;p<1&&y.htmlRenderEnabled&&T({children:c.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),p<2&&T({children:c.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),p<3&&y.htmlRenderEnabled&&!d&&T({children:c.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete c.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=c.pages[g]||c.pages[0])||void 0===s?void 0:s.id;c._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,c),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);O.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){O.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=j.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||b.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"}))),b.injectCustomFont(n)):b.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>b.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 O});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
@@ -84,6 +84,12 @@ export declare const TableCell: import("mobx-state-tree").IModelType<{
84
84
  readonly cellPadding: number;
85
85
  readonly width: number;
86
86
  readonly height: number;
87
+ readonly borderInsets: {
88
+ top: number;
89
+ right: number;
90
+ bottom: number;
91
+ left: number;
92
+ };
87
93
  readonly a: {
88
94
  x: number;
89
95
  y: number;
@@ -266,6 +272,12 @@ export declare const TableElement: import("mobx-state-tree").IModelType<{
266
272
  readonly cellPadding: number;
267
273
  readonly width: number;
268
274
  readonly height: number;
275
+ readonly borderInsets: {
276
+ top: number;
277
+ right: number;
278
+ bottom: number;
279
+ left: number;
280
+ };
269
281
  readonly a: {
270
282
  x: number;
271
283
  y: number;
@@ -1 +1 @@
1
- import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{Shape as c}from"./shape-model.js";const d=.05,a=e.enumeration(["solid","dashed","dotted","none"]);function g(e){return t(e,2)}function u(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?g(e)[t]:o}function h(e){return t(e,1)}const f=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(a)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),b=e.model("CellBorders",{top:e.maybe(f),right:e.maybe(f),bottom:e.maybe(f),left:e.maybe(f)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),w=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],m=new Set(w),p=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],C=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],_=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),y={opacity:1,rowSpan:1,colSpan:1,name:""},v=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(b),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of C){o in e&&(t[o]=e[o])}for(const o of w){void 0!==e[o]&&(t[`_${o}`]=e[o])}return t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in y&&l===y[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=g(e),o=h(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=g(e),o=h(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return g(e).page}catch(t){return null}},get fontSize(){return u(e,"fontSize",30)},get fontFamily(){return u(e,"fontFamily","Roboto")},get fontWeight(){return u(e,"fontWeight","normal")},get fontStyle(){return u(e,"fontStyle","normal")},get textDecoration(){return u(e,"textDecoration","")},get textTransform(){return u(e,"textTransform","none")},get fill(){return u(e,"fill","black")},get align(){return u(e,"align","left")},get verticalAlign(){return u(e,"verticalAlign","top")},get lineHeight(){return u(e,"lineHeight",1.2)},get letterSpacing(){return u(e,"letterSpacing",0)},get strokeWidth(){return u(e,"strokeWidth",0)},get stroke(){return u(e,"stroke","black")},get cellBackground(){return u(e,"cellBackground","transparent")},get cellPadding(){return u(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,s=e=>"none"===e.style?0:e.width,i=s(t.getEffectiveBorder("top")),c=s(t.getEffectiveBorder("right")),d=s(t.getEffectiveBorder("bottom")),a=s(t.getEffectiveBorder("left"));return{x:r.x+a+n,y:r.y+i+n,width:Math.max(0,r.width-a-c-2*n),height:Math.max(0,r.height-i-d-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?g(e):null,u=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==u?void 0:u.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==u?void 0:u.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==u?void 0:u.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return v}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&t.fontSize<1&&(t=Object.assign(Object.assign({},t),{fontSize:1}));const o={};for(const[e,l]of Object.entries(t)){m.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:_.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())}}));function H(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of w){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function I(e){return Array.from({length:e},()=>1/e)}function R(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?I(e.length):e.map(e=>e/t)}export const TableElement=c.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){m.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of p){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(n(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols)))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(I(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(I(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},getRowContentOuterHeight(o){let l=0;for(let r=0;r<e.cols;r++){const n=t.getCell(o,r);if(!n){continue}const s=e._cellContentHeights.get(n.id);void 0!==s&&(l=Math.max(l,s+2*n.cellPadding))}return l},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}let l=0;for(let r=0;r<e.rows;r++){l+=t.getRowContentOuterHeight(r)}return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){var o,l;if(0===e._cellContentHeights.size){return null}const r=null!==(o=e._baseHeight)&&void 0!==o?o:e.height,n=null!==(l=e._baseRowHeights)&&void 0!==l?l:[...e.rowHeights];let s=!1;const i=[];for(let d=0;d<e.rows;d++){const o=e.rowHeights[d]*e.height,l=n[d]*r;let c=0;for(let r=0;r<e.cols;r++){const o=t.getCell(d,r);if(!o){continue}const l=e._cellContentHeights.get(o.id);if(void 0!==l){const e=l+2*o.cellPadding;c=Math.max(c,e)}}const a=Math.max(c,l);Math.abs(a-o)>1?(i.push(a),s=!0):i.push(o)}if(!s){return null}const c=i.reduce((e,t)=>e+t,0);return{rowHeights:i.map(e=>e/c),height:c}}};return t}).actions(e=>{const t={setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){null===e._baseRowHeights&&(e._baseRowHeights=[...e.rowHeights],e._baseHeight=e.height);const t=e._fitRowsToContent;t&&(e.height=t.height,e.rowHeights.replace(t.rowHeights))},focusCell(t,o=!1){o?e._focusedCellIds.includes(t)||(e._focusedCellIds=[...e._focusedCellIds,t]):(e._focusedCellIds=[t],e._anchorCellId=t)},selectRowRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.rows-1,Math.max(t,o)),n=[];for(let s=l;s<=r;s++){for(let t=0;t<e.cols;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectColumnRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.cols-1,Math.max(t,o)),n=[];for(let s=0;s<e.rows;s++){for(let t=l;t<=r;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectRow(e){t.selectRowRange(e,e)},selectColumn(e){t.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=[],n=[];let s=0;for(let u=0;u<o;u++){r.push(e.rowHeights[u]*l);const t=e.getRowContentOuterHeight(u);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(o){t._resetBaseRowHeights();const l=o>0?o-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,s=e.height+r,i=[];for(let t=0;t<e.rows;t++){i.push(e.rowHeights[t]*e.height/s)}i.splice(o,0,r/s);const c=o>0?o-1:0,d=[];for(let t=0;t<e.cols;t++){d.push(e.cells[c*e.cols+t])}const a=o*e.cols,g=H(d,!0);e.cells.splice(a,0,...n(g)),e.rows+=1,e.height=s,e.rowHeights.replace(R(i))},removeRow(o){if(e.rows<=1){return}t._resetBaseRowHeights();const l=o*e.cols,r=[];for(let t=l;t<l+e.cols;t++){r.push(e.cells[t].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(o,1),e.rows-=1,e.rowHeights.replace(R(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=H(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(R(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(R(r))},removeRowRange(o,l){for(let r=l;r>=o&&!(e.rows<=1);r--){t.removeRow(r)}},removeColumnRange(o,l){for(let r=l;r>=o&&!(e.cols<=1);r--){t.removeColumn(r)}},distributeRowsEvenly(){t._resetBaseRowHeights(),e.rowHeights.replace(I(e.rows))},distributeColumnsEvenly(){e.colWidths.replace(I(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<d?(l[t]=d,l[t+1]=r-d):s<d?(l[t+1]=d,l[t]=r-d):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=n>0?e.getRowContentOuterHeight(t)/n:0,i=n>0?e.getRowContentOuterHeight(t+1)/n:0,c=Math.max(d,s),a=Math.max(d,i),g=l[t]+o,u=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):u<a?(l[t+1]=a,l[t]=r-a):(l[t]=g,l[t+1]=u),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(o,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(o,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){t.setCellBorders(e,s,l)}}};return t}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
1
+ import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{Shape as c}from"./shape-model.js";const d=.05,a=e.enumeration(["solid","dashed","dotted","none"]);function g(e){return t(e,2)}function u(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?g(e)[t]:o}function h(e){return t(e,1)}const f=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(a)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),b=e.model("CellBorders",{top:e.maybe(f),right:e.maybe(f),bottom:e.maybe(f),left:e.maybe(f)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),w=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],p=new Set(w),m=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],C=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],y=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),_={opacity:1,rowSpan:1,colSpan:1,name:""},v=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(b),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of C){o in e&&(t[o]=e[o])}for(const o of w){void 0!==e[o]&&(t[`_${o}`]=e[o])}return t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in _&&l===_[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=g(e),o=h(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=g(e),o=h(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return g(e).page}catch(t){return null}},get fontSize(){return u(e,"fontSize",30)},get fontFamily(){return u(e,"fontFamily","Roboto")},get fontWeight(){return u(e,"fontWeight","normal")},get fontStyle(){return u(e,"fontStyle","normal")},get textDecoration(){return u(e,"textDecoration","")},get textTransform(){return u(e,"textTransform","none")},get fill(){return u(e,"fill","black")},get align(){return u(e,"align","left")},get verticalAlign(){return u(e,"verticalAlign","top")},get lineHeight(){return u(e,"lineHeight",1.2)},get letterSpacing(){return u(e,"letterSpacing",0)},get strokeWidth(){return u(e,"strokeWidth",0)},get stroke(){return u(e,"stroke","black")},get cellBackground(){return u(e,"cellBackground","transparent")},get cellPadding(){return u(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get borderInsets(){if(!l(e)){return{top:0,right:0,bottom:0,left:0}}const o=g(e),r=(e,o)=>{const l=t.getEffectiveBorder(e);return"none"===l.style||0===l.width?0:o?l.width:l.width/2};return{top:r("top",0===t.row),bottom:r("bottom",t.row+e.rowSpan===o.rows),left:r("left",0===t.col),right:r("right",t.col+e.colSpan===o.cols)}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,{top:s,right:i,bottom:c,left:d}=t.borderInsets;return{x:r.x+d+n,y:r.y+s+n,width:Math.max(0,r.width-d-i-2*n),height:Math.max(0,r.height-s-c-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?g(e):null,u=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==u?void 0:u.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==u?void 0:u.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==u?void 0:u.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return v}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&t.fontSize<1&&(t=Object.assign(Object.assign({},t),{fontSize:1}));const o={};for(const[e,l]of Object.entries(t)){p.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:y.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())}}));function I(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of w){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function H(e){return Array.from({length:e},()=>1/e)}function R(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?H(e.length):e.map(e=>e/t)}export const TableElement=c.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){p.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of m){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(H(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(H(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},getRowContentOuterHeight(o){let l=0;for(let r=0;r<e.cols;r++){const n=t.getCell(o,r);if(!n){continue}const s=e._cellContentHeights.get(n.id);if(void 0===s){continue}const i=n.borderInsets,c=s+2*n.cellPadding+i.top+i.bottom;c>l&&(l=c)}return l},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}let l=0;for(let r=0;r<e.rows;r++){l+=t.getRowContentOuterHeight(r)}return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){var o,l;if(0===e._cellContentHeights.size){return null}const r=null!==(o=e._baseHeight)&&void 0!==o?o:e.height,n=null!==(l=e._baseRowHeights)&&void 0!==l?l:[...e.rowHeights];let s=!1;const i=[];for(let d=0;d<e.rows;d++){const o=e.rowHeights[d]*e.height,l=n[d]*r,c=t.getRowContentOuterHeight(d),a=Math.max(c,l);Math.abs(a-o)>1?(i.push(a),s=!0):i.push(o)}if(!s){return null}const c=i.reduce((e,t)=>e+t,0);return{rowHeights:i.map(e=>e/c),height:c}}};return t}).actions(e=>{const t={setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){null===e._baseRowHeights&&(e._baseRowHeights=[...e.rowHeights],e._baseHeight=e.height);const t=e._fitRowsToContent;t&&(e.height=t.height,e.rowHeights.replace(t.rowHeights))},focusCell(t,o=!1){o?e._focusedCellIds.includes(t)||(e._focusedCellIds=[...e._focusedCellIds,t]):(e._focusedCellIds=[t],e._anchorCellId=t)},selectRowRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.rows-1,Math.max(t,o)),n=[];for(let s=l;s<=r;s++){for(let t=0;t<e.cols;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectColumnRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.cols-1,Math.max(t,o)),n=[];for(let s=0;s<e.rows;s++){for(let t=l;t<=r;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectRow(e){t.selectRowRange(e,e)},selectColumn(e){t.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=[],n=[];let s=0;for(let u=0;u<o;u++){r.push(e.rowHeights[u]*l);const t=e.getRowContentOuterHeight(u);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(o){t._resetBaseRowHeights();const l=o>0?o-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let t=0;t<e.rows;t++){s.push(e.rowHeights[t]*e.height/n)}s.splice(o,0,r/n);const i=o>0?o-1:0,c=[];for(let t=0;t<e.cols;t++){c.push(e.cells[i*e.cols+t])}const d=o*e.cols,a=I(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(R(s))},removeRow(o){if(e.rows<=1){return}t._resetBaseRowHeights();const l=o*e.cols,r=[];for(let t=l;t<l+e.cols;t++){r.push(e.cells[t].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(o,1),e.rows-=1,e.rowHeights.replace(R(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=I(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(R(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(R(r))},removeRowRange(o,l){for(let r=l;r>=o&&!(e.rows<=1);r--){t.removeRow(r)}},removeColumnRange(o,l){for(let r=l;r>=o&&!(e.cols<=1);r--){t.removeColumn(r)}},distributeRowsEvenly(){t._resetBaseRowHeights(),e.rowHeights.replace(H(e.rows))},distributeColumnsEvenly(){e.colWidths.replace(H(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<d?(l[t]=d,l[t+1]=r-d):s<d?(l[t+1]=d,l[t]=r-d):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=n>0?e.getRowContentOuterHeight(t)/n:0,i=n>0?e.getRowContentOuterHeight(t+1)/n:0,c=Math.max(d,s),a=Math.max(d,i),g=l[t]+o,u=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):u<a?(l[t+1]=a,l[t]=r-a):(l[t]=g,l[t+1]=u),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(o,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(o,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){t.setCellBorders(e,s,l)}}};return t}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
@@ -163,18 +163,7 @@ export declare const TextElement: import("mobx-state-tree").IModelType<{
163
163
  set(attrs: any): void;
164
164
  afterCreate(): void;
165
165
  toggleEditMode(editing?: boolean): void;
166
- }, import("mobx-state-tree").ModelCreationType<{
167
- id: string;
168
- type: string | undefined;
169
- name: string | undefined;
170
- opacity: number | undefined;
171
- custom: any;
172
- visible: boolean | undefined;
173
- selectable: boolean | undefined;
174
- removable: boolean | undefined;
175
- alwaysOnTop: boolean | undefined;
176
- showInExport: boolean | undefined;
177
- }>, import("mobx-state-tree").ModelSnapshotType<{
166
+ }, any, import("mobx-state-tree").ModelSnapshotType<{
178
167
  id: import("mobx-state-tree").ISimpleType<string>;
179
168
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
180
169
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "2.40.2",
3
+ "version": "2.41.0",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
@@ -77,7 +77,7 @@
77
77
  "polotno": "^2.39.1",
78
78
  "quill": "^1.3.7",
79
79
  "react-color": "^2.19.3",
80
- "react-konva": "^18.2.14",
80
+ "react-konva": "^18.2.15",
81
81
  "react-konva-utils": "^2.0.0",
82
82
  "react-sortablejs": "6.1.4",
83
83
  "react-window": "^1.8.11",
@@ -1,5 +1,9 @@
1
1
  import React from 'react';
2
2
  import { PageType } from '../model/page-model.js';
3
+ export declare const usePagePreview: ({ page, ref, }: {
4
+ page: PageType;
5
+ ref: React.RefObject<HTMLDivElement>;
6
+ }) => string | null;
3
7
  export declare const PagePreview: (({ page, scale }: {
4
8
  page: PageType;
5
9
  scale: number;
@@ -1,4 +1,4 @@
1
- import e from"react";import{observer as t}from"mobx-react-lite";import{reaction as o}from"mobx";import{onSnapshot as n}from"mobx-state-tree";import{Button as i,Menu as r,MenuItem as a,Popover as s,Position as l}from"@blueprintjs/core";import{Duplicate as c,Insert as d,More as u,Trash as p}from"@blueprintjs/icons";import g from"../utils/styled.js";import{flags as m}from"../utils/flags.js";import{t as f}from"../utils/l10n.js";import{Spinner as h}from"./spinner.js";import{deepEqual as x}from"../utils/deep-equal.js";const v=g("div",e.forwardRef)`
1
+ import e from"react";import{observer as t}from"mobx-react-lite";import{reaction as o}from"mobx";import{onSnapshot as n}from"mobx-state-tree";import{Button as r,Menu as i,MenuItem as a,Popover as s,Position as l}from"@blueprintjs/core";import{Duplicate as c,Insert as d,More as u,Trash as p}from"@blueprintjs/icons";import g from"../utils/styled.js";import{flags as m}from"../utils/flags.js";import{t as f}from"../utils/l10n.js";import{Spinner as h}from"./spinner.js";import{deepEqual as x}from"../utils/deep-equal.js";const v=g("div",e.forwardRef)`
2
2
  display: flex;
3
3
  position: relative;
4
4
  border-radius: 15px;
@@ -20,4 +20,4 @@ import e from"react";import{observer as t}from"mobx-react-lite";import{reaction
20
20
  &:hover {
21
21
  display: block;
22
22
  }
23
- `;let w=[],E=!1;const P=async()=>{if(E||0===w.length){return}E=!0;const{page:e,setPreview:t}=w.shift();try{t(await e.store.toDataURL({pageId:e.id,pixelRatio:.1,quickMode:!0}))}catch(o){o instanceof Error&&"string"==typeof o.message&&(o.message.includes("Canvas was unmounted.")||o.message.includes("<Workspace /> component is not mounted"))||console.error(o)}finally{E=!1}P()};export const PagePreview=t(({page:t,scale:g})=>{const[E,y]=e.useState(null),k=t.store.activePage===t||t.store._selectedPagesIds.includes(t.id),R=e.useRef(null),I=t.store.pages.indexOf(t),C=60/t.computedHeight*t.computedWidth,T=m.animationsEnabled?t.duration*g:C,D=t.store.pages.length>1;e.useLayoutEffect(()=>{R.current&&(R.current.style.width=T+"px")},[I,T]),(({page:t,setPreview:i,groupRef:r})=>{const a=e.useRef(!1);e.useEffect(()=>{const e=()=>{w.push({page:t,setPreview:e=>i(e)}),P()};let s=null,l=null,c=Date.now();const d=()=>{s&&clearTimeout(s),a.current&&(l||(l=setTimeout(()=>{Date.now()-c>=6e3&&(e(),c=Date.now(),l=null)},6e3)),s=setTimeout(()=>{e(),c=Date.now(),s=null,l&&(clearTimeout(l),l=null)},300))};let u=null;const p=n(t,e=>{x(u,e)||(d(),u=e)}),g=o(()=>t.children.some(e=>e._editModeEnabled),e=>{e||d()}),m=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?(a.current=!0,d()):(s&&clearTimeout(s),l&&clearTimeout(l),a.current=!1)})},{threshold:.1});return r.current&&m.observe(r.current),()=>{m.disconnect(),s&&clearTimeout(s),l&&clearTimeout(l),p(),g(),w=w.filter(e=>e.page!==t)}},[r,t,i])})({page:t,setPreview:y,groupRef:R});const{handleStartDrag:j}=((t,o)=>({handleStartDrag:e.useCallback((e,n)=>{e.preventDefault();const i=e=>{if(e.preventDefault(),!o.current){return}const i="start"===n?7:-7,{clientX:r}=e,{left:a,width:s}=o.current.getBoundingClientRect(),l=(r-a-i)/s;"end"===n&&t.set({duration:Math.max(1e3,l*t.duration)})},r=()=>{window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",r)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",r)},[o,t])}))(t,R);return e.createElement(v,{style:{width:T+"px",marginRight:m.animationsEnabled?"0px":"10px",height:"60px"},ref:R,className:"polotno-page-container"+(k?" sortable-selected":"")},e.createElement("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:E?`url("${E}")`:"none",backgroundRepeat:"repeat-x",backgroundSize:"auto 100%",backgroundColor:"white",display:"flex",justifyContent:"center",alignItems:"center"},onClick:e=>{const{store:o}=t,n=o._selectedPagesIds.length?o._selectedPagesIds:o.activePage?[o.activePage.id]:[],i=n.includes(t.id),r=e.shiftKey;if(r&&i){const e=n.filter(e=>e!==t.id);o.selectPages(e)}else if(r&&!i){const e=n.concat([t.id]);o.selectPages(e)}else{o.selectPages([t.id])}}},!E&&e.createElement(h,null)),e.createElement("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:k?"2px solid rgb(0, 161, 255, 0.9)":"2px solid lightgrey",zIndex:1,pointerEvents:"none"}}),m.animationsEnabled&&e.createElement("div",{style:{position:"absolute",zIndex:1,bottom:"5px",left:"5px",backgroundColor:"rgba(0, 0, 0, 0.5)",color:"white",padding:"2px 7px",textAlign:"center",borderRadius:"4rem"}},(t.duration/1e3).toFixed(1),"s"),m.animationsEnabled&&e.createElement("div",{style:{position:"absolute",zIndex:1,top:"50%",right:"0px",width:"8px",height:"50%",transform:"translateY(-50%) translateX(-3px)",borderRadius:"5px",border:"1px solid rgb(255, 255, 255, 0.6)",backgroundColor:"rgb(0, 0, 0, 0.6)",cursor:"ew-resize"},onMouseDown:e=>j(e,"end")}),k&&e.createElement(b,{className:"polotno-page-menu",onClick:e=>{e.stopPropagation()}},e.createElement(s,{content:e.createElement(r,{style:{width:"140px"}},e.createElement(a,{icon:e.createElement(c,null),text:f("pagesTimeline.duplicatePage"),onClick:()=>{const e=t.store,o=(e.selectedPages||[]).filter(Boolean),n=o.length?o:e.activePage?[e.activePage]:[];if(!n.length){return}const i=new Set(n.map(e=>e.id)),r=e.pages.filter(e=>i.has(e.id)),a=r[r.length-1],s=r.map(e=>e.clone()),l=e.pages.indexOf(a);s.forEach((e,t)=>{e.setZIndex(l+1+t)}),e.selectPages(s.map(e=>e.id))}}),e.createElement(a,{icon:e.createElement(d,null),text:f("pagesTimeline.addPage"),onClick:()=>{var e,o,n;const i=t.store.addPage({bleed:(null===(e=t.store.activePage)||void 0===e?void 0:e.bleed)||0,width:(null===(o=t.store.activePage)||void 0===o?void 0:o.width)||"auto",height:(null===(n=t.store.activePage)||void 0===n?void 0:n.height)||"auto"}),r=t.store.pages.indexOf(t);i.setZIndex(r+1)}}),D&&e.createElement(a,{icon:e.createElement(p,null),text:f("pagesTimeline.removePage"),onClick:()=>{const e=t.store,o=(e.selectedPages||[]).filter(Boolean),n=o.length?o.map(e=>e.id):e.activePage?[e.activePage.id]:[];n.length&&e.deletePages(n)}})),position:l.TOP},e.createElement(i,{icon:e.createElement(u,null),style:{minHeight:"20px",borderRadius:"10px"}}))))});
23
+ `;let w=[],P=!1;const E=async()=>{if(P||0===w.length){return}P=!0;const{page:e,setPreview:t}=w.shift();try{t(await e.store.toDataURL({pageId:e.id,pixelRatio:.1,quickMode:!0}))}catch(o){o instanceof Error&&"string"==typeof o.message&&(o.message.includes("Canvas was unmounted.")||o.message.includes("<Workspace /> component is not mounted"))||console.error(o)}finally{P=!1}E()};export const usePagePreview=({page:t,ref:r})=>{const[i,a]=e.useState(null),s=e.useRef(!1);return e.useEffect(()=>{const e=()=>{w.push({page:t,setPreview:e=>a(e)}),E()};let i=null,l=null,c=Date.now();const d=()=>{i&&clearTimeout(i),s.current&&(l||(l=setTimeout(()=>{Date.now()-c>=6e3&&(e(),c=Date.now(),l=null)},6e3)),i=setTimeout(()=>{e(),c=Date.now(),i=null,l&&(clearTimeout(l),l=null)},300))};let u=null;const p=n(t,e=>{x(u,e)||(d(),u=e)}),g=o(()=>t.children.some(e=>e._editModeEnabled),e=>{e||d()}),m=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?(s.current=!0,d()):(i&&clearTimeout(i),l&&clearTimeout(l),s.current=!1)})},{threshold:.1});return r.current&&m.observe(r.current),()=>{m.disconnect(),i&&clearTimeout(i),l&&clearTimeout(l),p(),g(),w=w.filter(e=>e.page!==t)}},[r,t]),i};export const PagePreview=t(({page:t,scale:o})=>{const n=t.store.activePage===t||t.store._selectedPagesIds.includes(t.id),g=e.useRef(null),x=t.store.pages.indexOf(t),w=60/t.computedHeight*t.computedWidth,P=m.animationsEnabled?t.duration*o:w,E=t.store.pages.length>1;e.useLayoutEffect(()=>{g.current&&(g.current.style.width=P+"px")},[x,P]);const y=usePagePreview({page:t,ref:g}),{handleStartDrag:k}=((t,o)=>({handleStartDrag:e.useCallback((e,n)=>{e.preventDefault();const r=e=>{if(e.preventDefault(),!o.current){return}const r="start"===n?7:-7,{clientX:i}=e,{left:a,width:s}=o.current.getBoundingClientRect(),l=(i-a-r)/s;"end"===n&&t.set({duration:Math.max(1e3,l*t.duration)})},i=()=>{window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[o,t])}))(t,g);return e.createElement(v,{style:{width:P+"px",marginRight:m.animationsEnabled?"0px":"10px",height:"60px"},ref:g,className:"polotno-page-container"+(n?" sortable-selected":"")},e.createElement("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:y?`url("${y}")`:"none",backgroundRepeat:"repeat-x",backgroundSize:"auto 100%",backgroundColor:"white",display:"flex",justifyContent:"center",alignItems:"center"},onClick:e=>{const{store:o}=t,n=o._selectedPagesIds.length?o._selectedPagesIds:o.activePage?[o.activePage.id]:[],r=n.includes(t.id),i=e.shiftKey;if(i&&r){const e=n.filter(e=>e!==t.id);o.selectPages(e)}else if(i&&!r){const e=n.concat([t.id]);o.selectPages(e)}else{o.selectPages([t.id])}}},!y&&e.createElement(h,null)),e.createElement("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:n?"2px solid rgb(0, 161, 255, 0.9)":"2px solid lightgrey",zIndex:1,pointerEvents:"none"}}),m.animationsEnabled&&e.createElement("div",{style:{position:"absolute",zIndex:1,bottom:"5px",left:"5px",backgroundColor:"rgba(0, 0, 0, 0.5)",color:"white",padding:"2px 7px",textAlign:"center",borderRadius:"4rem"}},(t.duration/1e3).toFixed(1),"s"),m.animationsEnabled&&e.createElement("div",{style:{position:"absolute",zIndex:1,top:"50%",right:"0px",width:"8px",height:"50%",transform:"translateY(-50%) translateX(-3px)",borderRadius:"5px",border:"1px solid rgb(255, 255, 255, 0.6)",backgroundColor:"rgb(0, 0, 0, 0.6)",cursor:"ew-resize"},onMouseDown:e=>k(e,"end")}),n&&e.createElement(b,{className:"polotno-page-menu",onClick:e=>{e.stopPropagation()}},e.createElement(s,{content:e.createElement(i,{style:{width:"140px"}},e.createElement(a,{icon:e.createElement(c,null),text:f("pagesTimeline.duplicatePage"),onClick:()=>{const e=t.store,o=(e.selectedPages||[]).filter(Boolean),n=o.length?o:e.activePage?[e.activePage]:[];if(!n.length){return}const r=new Set(n.map(e=>e.id)),i=e.pages.filter(e=>r.has(e.id)),a=i[i.length-1],s=i.map(e=>e.clone()),l=e.pages.indexOf(a);s.forEach((e,t)=>{e.setZIndex(l+1+t)}),e.selectPages(s.map(e=>e.id))}}),e.createElement(a,{icon:e.createElement(d,null),text:f("pagesTimeline.addPage"),onClick:()=>{var e,o,n;const r=t.store.addPage({bleed:(null===(e=t.store.activePage)||void 0===e?void 0:e.bleed)||0,width:(null===(o=t.store.activePage)||void 0===o?void 0:o.width)||"auto",height:(null===(n=t.store.activePage)||void 0===n?void 0:n.height)||"auto"}),i=t.store.pages.indexOf(t);r.setZIndex(i+1)}}),E&&e.createElement(a,{icon:e.createElement(p,null),text:f("pagesTimeline.removePage"),onClick:()=>{const e=t.store,o=(e.selectedPages||[]).filter(Boolean),n=o.length?o.map(e=>e.id):e.activePage?[e.activePage.id]:[];n.length&&e.deletePages(n)}})),position:l.TOP},e.createElement(r,{icon:e.createElement(u,null),style:{minHeight:"20px",borderRadius:"10px"}}))))});