polotno 3.2.2 → 3.4.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.
Files changed (125) hide show
  1. package/blueprint/toolbar/text-toolbar.js +2 -2
  2. package/blueprint.polotno.css +297 -297
  3. package/canvas/apply-filters.d.ts +10 -0
  4. package/canvas/apply-filters.js +1 -1
  5. package/canvas/figure-element.js +1 -1
  6. package/canvas/gif-element.js +1 -1
  7. package/canvas/hotkeys.js +1 -1
  8. package/canvas/html-element.js +1 -1
  9. package/canvas/image-element.js +1 -1
  10. package/canvas/line-element.js +1 -1
  11. package/canvas/page.js +1 -1
  12. package/canvas/quill-font-formats.js +1 -1
  13. package/canvas/render-tag-element.d.ts +2 -2
  14. package/canvas/render-tag-element.js +1 -1
  15. package/canvas/rich-editor.d.ts +2 -2
  16. package/canvas/rich-editor.js +10 -3
  17. package/canvas/text-element/fit-font-size.d.ts +3 -6
  18. package/canvas/text-element/fit-font-size.js +1 -1
  19. package/canvas/text-element.d.ts +2 -2
  20. package/canvas/text-element.js +1 -1
  21. package/canvas/tooltip.js +1 -1
  22. package/canvas/use-color.js +1 -1
  23. package/canvas/use-filtered-source.d.ts +2 -0
  24. package/canvas/use-filtered-source.js +1 -0
  25. package/canvas/use-mediabunny-video.js +1 -1
  26. package/canvas/video-element.js +1 -1
  27. package/model/group-model.d.ts +2 -2
  28. package/model/group-model.js +1 -1
  29. package/model/page-model.d.ts +1 -0
  30. package/model/store.d.ts +9 -0
  31. package/model/store.js +1 -1
  32. package/model/table-model.js +1 -1
  33. package/model/text-model.d.ts +1 -0
  34. package/model/text-model.js +1 -1
  35. package/package.json +34 -48
  36. package/pages-timeline/page-preview.js +1 -1
  37. package/polotno.bundle.js +222 -221
  38. package/primitives/slider-field.d.ts +2 -1
  39. package/primitives/slider-field.js +1 -1
  40. package/primitives/slider.js +1 -1
  41. package/primitives/tabs.d.ts +1 -1
  42. package/side-panel/ai-images-panel.js +1 -1
  43. package/side-panel/draw-panel.js +1 -1
  44. package/side-panel/effect-card.d.ts +1 -1
  45. package/side-panel/effect-card.js +1 -1
  46. package/side-panel/effects-panel.js +1 -1
  47. package/side-panel/image-clip-panel.js +1 -1
  48. package/side-panel/layers-panel.js +1 -1
  49. package/side-panel/select-gif.js +1 -1
  50. package/side-panel/select-image.js +1 -1
  51. package/side-panel/select-svg.js +1 -1
  52. package/side-panel/select-video.js +1 -1
  53. package/toolbar/color-picker.js +1 -1
  54. package/toolbar/figure-toolbar.js +1 -1
  55. package/toolbar/html-toolbar.js +1 -1
  56. package/toolbar/image-toolbar.js +1 -1
  57. package/toolbar/svg-toolbar.js +1 -1
  58. package/toolbar/text-toolbar.js +1 -1
  59. package/toolbar/video-toolbar.js +1 -1
  60. package/ui.css +1 -1
  61. package/utils/background-shape.d.ts +1 -21
  62. package/utils/background-shape.js +1 -1
  63. package/utils/clipboard.d.ts +2 -0
  64. package/utils/clipboard.js +1 -1
  65. package/utils/css-optimizer.js +1 -1
  66. package/utils/deprecation.d.ts +1 -0
  67. package/utils/deprecation.js +7 -0
  68. package/utils/errors.d.ts +4 -0
  69. package/utils/errors.js +1 -0
  70. package/utils/figure-to-svg.d.ts +1 -650
  71. package/utils/figure-to-svg.js +1 -1
  72. package/utils/filters.d.ts +1 -19
  73. package/utils/filters.js +1 -1
  74. package/utils/flags.d.ts +2 -1
  75. package/utils/fonts.d.ts +1 -3
  76. package/utils/fonts.js +1 -1
  77. package/utils/from-svg.js +1 -1
  78. package/utils/gradient.d.ts +1 -8
  79. package/utils/gradient.js +1 -1
  80. package/utils/html-to-svg/font-inliner.js +1 -1
  81. package/utils/html-to-svg/index.js +1 -1
  82. package/utils/html-to-svg/render-cache.js +1 -1
  83. package/utils/html-to-svg/xhtml.js +1 -1
  84. package/utils/html.js +1 -1
  85. package/utils/html2canvas.d.ts +1 -10
  86. package/utils/html2canvas.js +1 -1
  87. package/utils/image.d.ts +1 -14
  88. package/utils/image.js +1 -1
  89. package/utils/l10n.d.ts +4 -0
  90. package/utils/l10n.js +1 -1
  91. package/utils/list-marker-geometry.d.ts +1 -14
  92. package/utils/list-marker-geometry.js +1 -1
  93. package/utils/loader.d.ts +3 -2
  94. package/utils/loader.js +1 -1
  95. package/utils/luma.js +1 -1
  96. package/utils/measure-text.js +1 -1
  97. package/utils/path-to-svg.js +1 -1
  98. package/utils/px.d.ts +48 -0
  99. package/utils/px.js +1 -0
  100. package/utils/reset-style.d.ts +1 -2
  101. package/utils/reset-style.js +1 -1
  102. package/utils/rich-text-html.d.ts +3 -16
  103. package/utils/rich-text-html.js +1 -1
  104. package/utils/svg.d.ts +2 -12
  105. package/utils/svg.js +2 -1
  106. package/utils/text-format-state.js +1 -1
  107. package/utils/text-format.js +1 -1
  108. package/utils/text-html.d.ts +3 -34
  109. package/utils/text-html.js +1 -1
  110. package/utils/text-types.d.ts +1 -46
  111. package/utils/text-types.js +1 -1
  112. package/utils/text.d.ts +1 -16
  113. package/utils/text.js +1 -1
  114. package/utils/to-html.d.ts +6 -17
  115. package/utils/to-html.js +1 -1
  116. package/utils/to-pptx.js +1 -1
  117. package/utils/to-svg.d.ts +6 -17
  118. package/utils/to-svg.js +1 -1
  119. package/utils/use-svg-colors.d.ts +1 -0
  120. package/utils/use-svg-colors.js +1 -0
  121. package/utils/validate-key.js +1 -1
  122. package/utils/video.d.ts +1 -7
  123. package/utils/video.js +1 -1
  124. package/utils/xml.d.ts +1 -1
  125. package/utils/xml.js +1 -7
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{ZERO_BLEED as m}from"@polotno/schema";import{downloadFile as u}from"../utils/download.js";import{getJsPDF as f}from"../utils/pdf.js";import{createGIF as h}from"../utils/gif-lib.js";import{validateKey as b,setKey as y}from"../utils/validate-key.js";import*as v from"../utils/fonts.js";import{flags as P}from"../utils/flags.js";import{addDpiMetadataToImage as w}from"../utils/image-dpi.js";import{nodeToCanvas as E}from"../utils/canvas.js";import{whenLoaded as x}from"../utils/loader.js";import{pxToUnit as T}from"../utils/unit.js";import{deepEqual as I}from"../utils/deep-equal.js";import{waitTillAvailable as _}from"../utils/wait.js";import{jsonToHTML as k}from"../utils/to-html.js";import{jsonToSVG as S}from"../utils/to-svg.js";import{Page as O}from"./page-model.js";import{forEveryChild as j,forEveryNode as R}from"./group-model.js";import{Audio as F}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(O),fonts:l.array(Font),audios:l.array(F),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:4,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 R({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 j({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 R({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 y={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(()=>y.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&y.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),y.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>y.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>y.seek())):y.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){y.pause(),r.currentTime=0,y.checkActivePage()},__(){r._validated||(b(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=O.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},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=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=y.toJSON();return s(r,i=>{const o=y.toJSON();!I(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 u=r._elementsPixelRatio;c>r._elementsPixelRatio&&y.setElementsPixelRatio(c),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const f=await _(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!f){throw null==g||g.set({_forceMount:!1,_exporting:!1}),y.setElementsPixelRatio(u),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.`)}f.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 h=f[0];await y.waitLoading({_skipTimeout:a});const b=h.findOne(".page-container");if(!b){throw y.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const v=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=b.findOne(".elements-container"),T=x.clip();x.clip({x:null,y:null,width:null,height:null});const I=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));I.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const k=b.find(e=>e.getAttr("hideInExport"));k.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const S=n?g.computedBleed:m;let O=S.left,j=S.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(O=0,j=0):r.bleedVisible&&!n&&(O=-g.computedBleed.left,j=-g.computedBleed.top):(O=0,j=0));const R=g.computedWidth+S.left+S.right,F=g.computedHeight+S.top+S.bottom,C=b.scale();b.scale({x:1,y:1});const V=E(b,{x:b.x()-O,y:b.y()-j,width:R,height:F,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(C);const A=V._canvas;if("image/jpeg"===o){const e=A.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,A.width,A.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),k.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),I.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),x.clip(T),h.position(v),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),y.setElementsPixelRatio(u),A},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await y._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:w(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await y._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];u(await y.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 f(),d=e=>T({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*p),b=d(g.computedHeight+u.top+u.bottom+2*p);var v=new l({unit:o,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});v.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*c,s=t.computedHeight+i.top+i.bottom+2*c,r=d(o),l=d(s);let p=0,g=n;for(;p<10;){p+=1;const d=await y.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})=>{v.addPage([t,i],t>i?"landscape":"portrait");const r=v.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"Invalid unit: "+o}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:i*l},r.pageContext.artBox={bottomLeftX:d(c+s.left)*l,bottomLeftY:d(c+s.bottom)*l,topRightX:d(n-c-s.right)*l,topRightY:d(a-c-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(c+s.left)*l,bottomLeftY:d(c+s.bottom)*l,topRightX:d(n-c-s.right)*l,topRightY:d(a-c-s.top)*l},p){v.setLineWidth(d(1));const e=p+d(s.left),o=p+d(s.right),n=p+d(s.top),a=p+d(s.bottom);v.line(e,0,e,p),v.line(0,n,p,n),v.line(t-o,0,t-o,p),v.line(t,n,t-p,n),v.line(0,i-a,p,i-a),v.line(e,i,e,i-p),v.line(t,i-a,t-p,i-a),v.line(t-o,i,t-o,i-p)}v.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return v},toPDFDataURL:async e=>(await y._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 h({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;y.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await y._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 y.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 y.toGIFDataURL(o);u(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=y.toJSON();return k({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await y.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));u(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=y.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 S({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 y.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));u(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await y._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 x()},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&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&R({children:c.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),p<2&&R({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&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&!d&&R({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);y.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){y.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=F.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)||v.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"}))),v.injectCustomFont(n)):v.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>v.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 y});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return y(e),Store.create({_forceShowCredit:t})}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 p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m}from"@polotno/schema";import{downloadFile as u}from"../utils/download.js";import{getJsPDF as f}from"../utils/pdf.js";import{createGIF as h}from"../utils/gif-lib.js";import{validateKey as b,setKey as v}from"../utils/validate-key.js";import*as y from"../utils/fonts.js";import{flags as P}from"../utils/flags.js";import{addDpiMetadataToImage as w}from"../utils/image-dpi.js";import{nodeToCanvas as x}from"../utils/canvas.js";import{whenLoaded as E}from"../utils/loader.js";import{polotnoError as I}from"@polotno/core/errors";import{pxToUnit as T}from"../utils/unit.js";import{deepEqual as _}from"../utils/deep-equal.js";import{waitTillAvailable as S}from"../utils/wait.js";import{jsonToHTML as O}from"@polotno/html-export";import{jsonToSVG as k}from"@polotno/svg-export";import{warnOnceDeprecated as j}from"../utils/deprecation.js";import{Page as R}from"./page-model.js";import{forEveryChild as F,forEveryNode as A}from"./group-model.js";import{Audio as V}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(R),fonts:l.array(Font),audios:l.array(V),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:4,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 A({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 F({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 A({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 v={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(()=>v.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&v.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),v.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>v.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>v.seek())):v.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){v.pause(),r.currentTime=0,v.checkActivePage()},__(){r._validated||(b(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=R.create(Object.assign({id:p(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},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=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: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=v.toJSON();return s(r,i=>{const o=v.toJSON();!_(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 I("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;p>r._elementsPixelRatio&&v.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const f=await S(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!f){throw null==g||g.set({_forceMount:!1,_exporting:!1}),v.setElementsPixelRatio(u),I("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})}f.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 h=f[0];await v.waitLoading({_skipTimeout:a});const b=h.findOne(".page-container");if(!b){throw v.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),I("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:i})}const y=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const E=b.findOne(".elements-container"),T=E.clip();E.clip({x:null,y:null,width:null,height:null});const _=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));_.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const k=n?g.computedBleed:m;let j=k.left,R=k.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+k.left+k.right,A=g.computedHeight+k.top+k.bottom,V=b.scale();b.scale({x:1,y:1});const C=x(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===o){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),_.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),E.clip(T),h.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),v.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await v._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:w(p,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await v._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];u(await v.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 f(),d=e=>T({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 v.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 I("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 v._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 I("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 h({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;v.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await v._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 v.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 v.toGIFDataURL(o);u(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){j("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=v.toJSON();return O(t,{elementHook:e,textOverflow:P.textOverflow,textSplitAllowed:P.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await v.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));u(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;j("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=v.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(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 v.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));u(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await v._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 E()},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,p=JSON.parse(JSON.stringify(e)),c=p.schemaVersion||0;c<1&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&A({children:p.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),c<2&&A({children:p.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)})}),c<3&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&!d&&A({children:p.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete p.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=p.pages[g]||p.pages[0])||void 0===s?void 0:s.id;p._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,p),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);v.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){v.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=V.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)||y.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"}))),y.injectCustomFont(n)):y.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>y.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 v});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return v(e),Store.create({_forceShowCredit:t})}export default createStore;
@@ -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 h(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?g(e)[t]:o}function u(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"],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=u(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=g(e),o=u(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 h(e,"fontSize",30)},get fontFamily(){return h(e,"fontFamily","Roboto")},get fontWeight(){return h(e,"fontWeight","normal")},get fontStyle(){return h(e,"fontStyle","normal")},get textDecoration(){return h(e,"textDecoration","")},get textTransform(){return h(e,"textTransform","none")},get fill(){return h(e,"fill","black")},get align(){return h(e,"align","left")},get verticalAlign(){return h(e,"verticalAlign","top")},get lineHeight(){return h(e,"lineHeight",1.2)},get letterSpacing(){return h(e,"letterSpacing",0)},get strokeWidth(){return h(e,"strokeWidth",0)},get stroke(){return h(e,"stroke","black")},get cellBackground(){return h(e,"cellBackground","transparent")},get cellPadding(){return h(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,h=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==h?void 0:h.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==h?void 0:h.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==h?void 0:h.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: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())},beforeDestroy(){e._editModeEnabled&&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)){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(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(){if(!l(e)){return}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 h=0;h<o;h++){r.push(e.rowHeights[h]*l);const t=e.getRowContentOuterHeight(h);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(){const o=e.rows;let l=20;for(let t=0;t<o;t++){l=Math.max(l,e.getRowContentOuterHeight(t))}t._resetBaseRowHeights(),e.height=Math.max(e.height,l*o),e.rowHeights.replace(H(o))},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,h=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):h<a?(l[t+1]=a,l[t]=r-a):(l[t]=g,l[t+1]=h),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,h="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(h){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||h){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{TABLE_CELL_OVERRIDABLE_KEYS as c}from"@polotno/schema/defaults";import{Shape as d}from"./shape-model.js";const a=.05,g=e.enumeration(["solid","dashed","dotted","none"]);function h(e){return t(e,2)}function u(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?h(e)[t]:o}function f(e){return t(e,1)}const b=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(g)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),w=e.model("CellBorders",{top:e.maybe(b),right:e.maybe(b),bottom:e.maybe(b),left:e.maybe(b)}).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}),m=c,p=new Set(m),C=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],_=["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"]),v={opacity:1,rowSpan:1,colSpan:1,name:""},I=[];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(w),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 _){o in e&&(t[o]=e[o])}for(const o of m){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 v&&l===v[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=h(e),o=f(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=h(e),o=f(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 h(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 h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return h(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=h(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=h(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)?h(e):null,g=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==g?void 0:g.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==g?void 0:g.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==g?void 0:g.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 I}};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())},beforeDestroy(){e._editModeEnabled&&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 m){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 R(e){return Array.from({length:e},()=>1/e)}function S(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?R(e.length):e.map(e=>e/t)}export const TableElement=d.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 C){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(R(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(R(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(){if(!l(e)){return}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 h=0;h<o;h++){r.push(e.rowHeights[h]*l);const t=e.getRowContentOuterHeight(h);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=H(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(S(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(S(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(S(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(S(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(){const o=e.rows;let l=20;for(let t=0;t<o;t++){l=Math.max(l,e.getRowContentOuterHeight(t))}t._resetBaseRowHeights(),e.height=Math.max(e.height,l*o),e.rowHeights.replace(R(o))},distributeColumnsEvenly(){e.colWidths.replace(R(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<a?(l[t]=a,l[t+1]=r-a):s<a?(l[t+1]=a,l[t]=r-a):(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(a,s),d=Math.max(a,i),g=l[t]+o,h=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):h<d?(l[t+1]=d,l[t]=r-d):(l[t]=g,l[t+1]=h),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,h="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(h){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||h){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})}}));
@@ -65,6 +65,7 @@ export declare const TextElement: import("mobx-state-tree").IModelType<{
65
65
  verticalAlign: import("mobx-state-tree").IType<string | undefined, string, string>;
66
66
  strokeWidth: import("mobx-state-tree").IType<number | undefined, number, number>;
67
67
  stroke: import("mobx-state-tree").IType<string | undefined, string, string>;
68
+ strokeLineJoin: import("mobx-state-tree").IType<string | undefined, string, string>;
68
69
  lineHeight: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree/dist/internal").IUnionType<[import("mobx-state-tree").ISimpleType<number>, import("mobx-state-tree").ISimpleType<string>]>, [undefined]>;
69
70
  letterSpacing: import("mobx-state-tree").IType<number | undefined, number, number>;
70
71
  _editModeEnabled: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -1 +1 @@
1
- import{types as e}from"mobx-state-tree";import{Shape as t}from"./shape-model.js";const n=e=>{if("string"!=typeof e){return e}const t=e.trim().match(/^(-?\d*\.?\d+)(%?)$/);if(!t){return e}const n=parseFloat(t[1]);return t[2]?n/100:n};export const TextElement=t.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5,legacyBackground:e.maybe(e.boolean),curveEnabled:!1,curvePower:.5}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontSize:null!=e.fontSize&&e.fontSize<1?1:e.fontSize,lineHeight:n(e.lineHeight)})).actions(e=>{const t=e.set;return{set(e){null!=e.fontSize&&e.fontSize<1&&(e=Object.assign(Object.assign({},e),{fontSize:1})),"string"==typeof e.lineHeight&&(e=Object.assign(Object.assign({},e),{lineHeight:n(e.lineHeight)})),t(e)},afterCreate(){if(!e.height){const t=e.lineHeight,n="number"==typeof t?t:parseFloat(t)||1.2;e.height=Math.round(e.fontSize*n)}},toggleEditMode(t){const n=null!=t?t:!e._editModeEnabled;n!==e._editModeEnabled&&(e._editModeEnabled=n,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}});
1
+ import{types as e}from"mobx-state-tree";import{Shape as t}from"./shape-model.js";const n=e=>{if("string"!=typeof e){return e}const t=e.trim().match(/^(-?\d*\.?\d+)(%?)$/);if(!t){return e}const n=parseFloat(t[1]);return t[2]?n/100:n};export const TextElement=t.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",strokeLineJoin:"round",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5,legacyBackground:e.maybe(e.boolean),curveEnabled:!1,curvePower:.5}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontSize:null!=e.fontSize&&e.fontSize<1?1:e.fontSize,lineHeight:n(e.lineHeight)})).actions(e=>{const t=e.set;return{set(e){null!=e.fontSize&&e.fontSize<1&&(e=Object.assign(Object.assign({},e),{fontSize:1})),"string"==typeof e.lineHeight&&(e=Object.assign(Object.assign({},e),{lineHeight:n(e.lineHeight)})),t(e)},afterCreate(){if(!e.height){const t=e.lineHeight,n="number"==typeof t?t:parseFloat(t)||1.2;e.height=Math.round(e.fontSize*n)}},toggleEditMode(t){const n=null!=t?t:!e._editModeEnabled;n!==e._editModeEnabled&&(e._editModeEnabled=n,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "3.2.2",
3
+ "version": "3.4.0",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
@@ -95,30 +95,31 @@
95
95
  "./polotno.blueprint.css": "./blueprint.polotno.css"
96
96
  },
97
97
  "dependencies": {
98
- "@base-ui/react": "^1.5.0",
99
- "@polotno/schema": "0.1.6",
98
+ "@base-ui/react": "^1.6.0",
99
+ "@polotno/core": "0.1.0",
100
+ "@polotno/html-export": "0.1.0",
101
+ "@polotno/schema": "0.3.0",
102
+ "@polotno/svg-export": "0.1.0",
100
103
  "class-variance-authority": "^0.7.1",
101
104
  "clsx": "^2.1.1",
102
105
  "gifuct-js": "^2.1.2",
103
- "gradient-parser": "^1.2.0",
104
106
  "konva": "^10.3.0",
105
107
  "lodash-es": "^4.18.1",
106
- "lucide-react": "^1.18.0",
107
- "mediabunny": "^1.47.0",
108
- "mensch": "^0.3.4",
108
+ "lucide-react": "^1.23.0",
109
+ "mediabunny": "^1.50.8",
109
110
  "mobx": "6.16.1",
110
111
  "mobx-react-lite": "^4.1.1",
111
- "mobx-state-tree": "7.2.0",
112
- "nanoid": "^5.1.11",
112
+ "mobx-state-tree": "7.3.1",
113
+ "nanoid": "^6.0.0",
113
114
  "quill": "^2.0.3",
114
115
  "react-konva": "18.2.16",
115
116
  "react-konva-utils": "^2.0.0",
116
117
  "react-sortablejs": "6.1.4",
117
- "react-window": "^1.8.11",
118
- "render-tag": "^0.1.16",
118
+ "react-window": "^2.2.7",
119
+ "render-tag": "^0.1.23",
119
120
  "sortablejs": "^1.15.7",
120
121
  "svg-round-corners": "^0.4.3",
121
- "swr": "^2.4.1",
122
+ "swr": "^2.4.2",
122
123
  "tailwind-merge": "^3.6.0",
123
124
  "tinycolor2": "^1.6.0",
124
125
  "use-image": "^1.1.4"
@@ -152,40 +153,24 @@
152
153
  "optional": true
153
154
  }
154
155
  },
155
- "size-limit": [
156
- {
157
- "path": "./lib/polotno-app.js",
158
- "limit": "395 KB"
159
- },
160
- {
161
- "path": "./lib/canvas/workspace.js",
162
- "limit": "395 KB"
163
- },
164
- {
165
- "path": "./lib/canvas/workspace-canvas.js",
166
- "limit": "395 KB"
167
- }
168
- ],
169
156
  "devDependencies": {
170
- "@babel/core": "^7.29.7",
171
- "@babel/parser": "^7.29.7",
172
- "@babel/traverse": "^7.29.7",
173
- "@blueprintjs/core": "6.16.0",
174
- "@blueprintjs/icons": "^6.11.0",
175
- "@blueprintjs/select": "6.3.0",
157
+ "@babel/core": "^8.0.1",
158
+ "@babel/parser": "^8.0.4",
159
+ "@babel/traverse": "^8.0.4",
160
+ "@blueprintjs/core": "6.17.2",
161
+ "@blueprintjs/icons": "^6.13.0",
162
+ "@blueprintjs/select": "6.3.3",
176
163
  "@canvas/image": "^2.0.0",
177
- "@size-limit/preset-big-lib": "^12.1.0",
178
- "@tailwindcss/cli": "^4.3.1",
179
- "@tailwindcss/vite": "^4.3.1",
164
+ "@tailwindcss/cli": "^4.3.2",
165
+ "@tailwindcss/vite": "^4.3.2",
180
166
  "@testing-library/dom": "^10.4.1",
181
167
  "@testing-library/react": "^16.3.2",
182
- "@types/gradient-parser": "^1.1.0",
183
168
  "@types/react": "^19.2.17",
184
- "@vitejs/plugin-react": "^6.0.2",
185
- "@vitest/browser": "^4.1.8",
186
- "@vitest/browser-playwright": "^4.1.8",
169
+ "@vitejs/plugin-react": "^6.0.3",
170
+ "@vitest/browser": "^4.1.10",
171
+ "@vitest/browser-playwright": "^4.1.10",
187
172
  "assert": "^2.1.0",
188
- "bippy": "^0.5.41",
173
+ "bippy": "^0.5.43",
189
174
  "buffer": "^6.0.3",
190
175
  "canvas": "^3.2.3",
191
176
  "filehound": "^1.17.6",
@@ -193,20 +178,19 @@
193
178
  "jest-file-snapshot": "^0.7.0",
194
179
  "jsdom": "^29.1.1",
195
180
  "license-checker": "^25.0.1",
196
- "playwright": "^1.60.0",
197
- "postcss": "^8.5.15",
181
+ "playwright": "^1.61.1",
182
+ "postcss": "^8.5.19",
198
183
  "postcss-selector-parser": "^7.1.4",
199
184
  "pptxgenjs": "^4.0.1",
200
185
  "process": "^0.11.10",
201
186
  "react": "^19.2.7",
202
187
  "react-dom": "^19.2.7",
203
- "size-limit": "^12.1.0",
204
- "tailwindcss": "^4.3.1",
188
+ "tailwindcss": "^4.3.2",
205
189
  "terser": "^5.48.0",
206
190
  "tw-animate-css": "^1.4.0",
207
191
  "typescript": "~6.0.3",
208
- "vite": "^8.0.16",
209
- "vitest": "^4.1.9"
192
+ "vite": "^8.1.4",
193
+ "vitest": "^4.1.10"
210
194
  },
211
195
  "homepage": "https://polotno.com/",
212
196
  "scripts": {
@@ -225,8 +209,10 @@
225
209
  "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",
226
210
  "add_version": "sed -i.bak 's/SDK_VERSION/'$npm_package_version'/' ./lib/utils/validate-key.js && rm -f ./lib/utils/validate-key.js.bak",
227
211
  "build:bundle": "vite build && find ./lib -name '*.js.map' -type f -delete",
228
- "size": "pnpm run build && size-limit",
229
- "test": "vitest run"
212
+ "test": "pnpm run test:unit && pnpm run test:browser",
213
+ "test:unit": "vitest run --project unit",
214
+ "test:browser": "node scripts/run-browser-sharded.mjs",
215
+ "test:serial": "vitest run"
230
216
  },
231
217
  "license": "SEE LICENSE IN LICENSE.md"
232
218
  }
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import o from"react";import{observer as n}from"mobx-react-lite";import{nodeReaction as i}from"../utils/mobx.js";import{onSnapshot as s}from"mobx-state-tree";import{PolotnoIcon as a}from"../icons/registry.js";import{flags as r}from"../utils/flags.js";import{t as l}from"../utils/l10n.js";import{deepEqual as d}from"../utils/deep-equal.js";import{DropdownMenu as c,DropdownMenuContent as p,DropdownMenuItem as u}from"../primitives/dropdown-menu.js";import{Spinner as g}from"./spinner.js";import{TrackMenuButton as m}from"./track-styles.js";let h=[],f=!1;const v=async()=>{if(f||0===h.length){return}f=!0;const{page:e,setPreview:t}=h.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{f=!1}v()};export const usePagePreview=({page:e,setPreview:t,groupRef:n})=>{const a=o.useRef(!1);o.useEffect(()=>{const o=()=>{h.push({page:e,setPreview:e=>t(e)}),v()};let r=null,l=null,c=Date.now();const p=()=>{r&&clearTimeout(r),a.current&&(l||(l=setTimeout(()=>{Date.now()-c>=6e3&&(o(),c=Date.now(),l=null)},6e3)),r=setTimeout(()=>{o(),c=Date.now(),r=null,l&&(clearTimeout(l),l=null)},300))};let u=null;const g=s(e,e=>{d(u,e)||(p(),u=e)}),m=i(e,()=>e.children.some(e=>e._editModeEnabled),e=>{e||p()}),f=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?(a.current=!0,p()):(r&&clearTimeout(r),l&&clearTimeout(l),a.current=!1)})},{threshold:.1});return n.current&&f.observe(n.current),()=>{f.disconnect(),r&&clearTimeout(r),l&&clearTimeout(l),g(),m(),h=h.filter(t=>t.page!==e)}},[n,e,t])};export const PagePreview=n(({page:n,scale:i})=>{const[s,d]=o.useState(null),[h,f]=o.useState(!1),v=n.store.activePage===n||n.store._selectedPagesIds.includes(n.id),x=o.useRef(null),b=n.store.pages.indexOf(n),w=60/n.computedHeight*n.computedWidth,P=r.animationsEnabled?n.duration*i:w,y=n.store.pages.length>1;o.useLayoutEffect(()=>{x.current&&(x.current.style.width=P+"px")},[b,P]),usePagePreview({page:n,setPreview:d,groupRef:x});const{handleStartDrag:E}=((e,t)=>({handleStartDrag:o.useCallback((o,n)=>{o.preventDefault();const i=o=>{if(o.preventDefault(),!t.current){return}const i="start"===n?7:-7,{clientX:s}=o,{left:a,width:r}=t.current.getBoundingClientRect(),l=(s-a-i)/r;"end"===n&&e.set({duration:Math.max(1e3,l*e.duration)})},s=()=>{window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},[t,e])}))(n,x);return t("div",{ref:x,style:{width:P+"px",marginRight:r.animationsEnabled?"0px":"10px",height:"60px",display:"flex",position:"relative",borderRadius:"15px",boxShadow:"0 1px 4px rgba(0, 0, 0, 0.18)"},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),className:"polotno-page-container"+(v?" sortable-selected":""),children:[e("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:s?`url("${s}")`:"none",backgroundRepeat:"repeat-x",backgroundSize:"auto 100%",backgroundColor:"white",display:"flex",justifyContent:"center",alignItems:"center"},onClick:e=>{const{store:t}=n,o=t._selectedPagesIds.length?t._selectedPagesIds:t.activePage?[t.activePage.id]:[],i=o.includes(n.id),s=e.shiftKey;if(s&&i){const e=o.filter(e=>e!==n.id);t.selectPages(e)}else if(s&&!i){const e=o.concat([n.id]);t.selectPages(e)}else{t.selectPages([n.id])}},children:!s&&e(g,{})}),e("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:v?"2px solid rgb(0, 161, 255, 0.9)":"2px solid var(--pn-border)",zIndex:1,pointerEvents:"none"}}),r.animationsEnabled&&t("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"},children:[(n.duration/1e3).toFixed(1),"s"]}),r.animationsEnabled&&e("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=>E(e,"end")}),v&&e("div",{className:"polotno-page-menu",style:{position:"absolute",zIndex:20,top:"5px",right:"5px",opacity:h?1:0,pointerEvents:h?"auto":"none",transition:"opacity 0.15s"},onClick:e=>{e.stopPropagation()},children:t(c,{children:[e(m,{}),t(p,{side:"top",className:"pn:whitespace-nowrap",children:[t(u,{onSelect:e=>{e.preventDefault();const t=n.store,o=(t.selectedPages||[]).filter(Boolean),i=o.length?o:t.activePage?[t.activePage]:[];if(!i.length){return}const s=new Set(i.map(e=>e.id)),a=t.pages.filter(e=>s.has(e.id)),r=a[a.length-1],l=a.map(e=>e.clone()),d=t.pages.indexOf(r);l.forEach((e,t)=>{e.setZIndex(d+1+t)}),t.selectPages(l.map(e=>e.id))},children:[e(a,{name:"action.duplicate",className:"pn:size-4"}),l("pagesTimeline.duplicatePage")]}),t(u,{onSelect:e=>{var t,o,i;e.preventDefault();const s=n.store.addPage({bleed:(null===(t=n.store.activePage)||void 0===t?void 0:t.bleed)||0,width:(null===(o=n.store.activePage)||void 0===o?void 0:o.width)||"auto",height:(null===(i=n.store.activePage)||void 0===i?void 0:i.height)||"auto"}),a=n.store.pages.indexOf(n);s.setZIndex(a+1)},children:[e(a,{name:"action.add",className:"pn:size-4"}),l("pagesTimeline.addPage")]}),y&&t(u,{onSelect:e=>{e.preventDefault();const t=n.store,o=(t.selectedPages||[]).filter(Boolean),i=o.length?o.map(e=>e.id):t.activePage?[t.activePage.id]:[];i.length&&t.deletePages(i)},children:[e(a,{name:"action.remove",className:"pn:size-4"}),l("pagesTimeline.removePage")]})]})]})})]})});
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import o from"react";import{observer as n}from"mobx-react-lite";import{nodeReaction as i}from"../utils/mobx.js";import{onSnapshot as s}from"mobx-state-tree";import{PolotnoIcon as a}from"../icons/registry.js";import{flags as r}from"../utils/flags.js";import{t as l}from"../utils/l10n.js";import{deepEqual as d}from"../utils/deep-equal.js";import{DropdownMenu as c,DropdownMenuContent as p,DropdownMenuItem as u}from"../primitives/dropdown-menu.js";import{Spinner as g}from"./spinner.js";import{TrackMenuButton as m}from"./track-styles.js";let v=[],h=!1;const f=async()=>{var e;if(h||0===v.length){return}h=!0;const{page:t,setPreview:o}=v.shift();try{o(await t.store.toDataURL({pageId:t.id,pixelRatio:.1,quickMode:!0}))}catch(n){"EXPORT_FAILED"===(null==n?void 0:n.code)&&["workspace-not-mounted","unmounted-during-export"].includes(null===(e=n.details)||void 0===e?void 0:e.reason)||n instanceof Error&&"string"==typeof n.message&&(n.message.includes("Canvas was unmounted.")||n.message.includes("<Workspace /> component is not mounted"))||console.error(n)}finally{h=!1}f()};export const usePagePreview=({page:e,setPreview:t,groupRef:n})=>{const a=o.useRef(!1);o.useEffect(()=>{const o=()=>{v.push({page:e,setPreview:e=>t(e)}),f()};let r=null,l=null,c=Date.now();const p=()=>{r&&clearTimeout(r),a.current&&(l||(l=setTimeout(()=>{Date.now()-c>=6e3&&(o(),c=Date.now(),l=null)},6e3)),r=setTimeout(()=>{o(),c=Date.now(),r=null,l&&(clearTimeout(l),l=null)},300))};let u=null;const g=s(e,e=>{d(u,e)||(p(),u=e)}),m=i(e,()=>e.children.some(e=>e._editModeEnabled),e=>{e||p()}),h=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?(a.current=!0,p()):(r&&clearTimeout(r),l&&clearTimeout(l),a.current=!1)})},{threshold:.1});return n.current&&h.observe(n.current),()=>{h.disconnect(),r&&clearTimeout(r),l&&clearTimeout(l),g(),m(),v=v.filter(t=>t.page!==e)}},[n,e,t])};export const PagePreview=n(({page:n,scale:i})=>{const[s,d]=o.useState(null),[v,h]=o.useState(!1),f=n.store.activePage===n||n.store._selectedPagesIds.includes(n.id),x=o.useRef(null),b=n.store.pages.indexOf(n),w=60/n.computedHeight*n.computedWidth,P=r.animationsEnabled?n.duration*i:w,y=n.store.pages.length>1;o.useLayoutEffect(()=>{x.current&&(x.current.style.width=P+"px")},[b,P]),usePagePreview({page:n,setPreview:d,groupRef:x});const{handleStartDrag:E}=((e,t)=>({handleStartDrag:o.useCallback((o,n)=>{o.preventDefault();const i=o=>{if(o.preventDefault(),!t.current){return}const i="start"===n?7:-7,{clientX:s}=o,{left:a,width:r}=t.current.getBoundingClientRect(),l=(s-a-i)/r;"end"===n&&e.set({duration:Math.max(1e3,l*e.duration)})},s=()=>{window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},[t,e])}))(n,x);return t("div",{ref:x,style:{width:P+"px",marginRight:r.animationsEnabled?"0px":"10px",height:"60px",display:"flex",position:"relative",borderRadius:"15px",boxShadow:"0 1px 4px rgba(0, 0, 0, 0.18)"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),className:"polotno-page-container"+(f?" sortable-selected":""),children:[e("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:s?`url("${s}")`:"none",backgroundRepeat:"repeat-x",backgroundSize:"auto 100%",backgroundColor:"white",display:"flex",justifyContent:"center",alignItems:"center"},onClick:e=>{const{store:t}=n,o=t._selectedPagesIds.length?t._selectedPagesIds:t.activePage?[t.activePage.id]:[],i=o.includes(n.id),s=e.shiftKey;if(s&&i){const e=o.filter(e=>e!==n.id);t.selectPages(e)}else if(s&&!i){const e=o.concat([n.id]);t.selectPages(e)}else{t.selectPages([n.id])}},children:!s&&e(g,{})}),e("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:f?"2px solid rgb(0, 161, 255, 0.9)":"2px solid var(--pn-border)",zIndex:1,pointerEvents:"none"}}),r.animationsEnabled&&t("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"},children:[(n.duration/1e3).toFixed(1),"s"]}),r.animationsEnabled&&e("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=>E(e,"end")}),f&&e("div",{className:"polotno-page-menu",style:{position:"absolute",zIndex:20,top:"5px",right:"5px",opacity:v?1:0,pointerEvents:v?"auto":"none",transition:"opacity 0.15s"},onClick:e=>{e.stopPropagation()},children:t(c,{children:[e(m,{}),t(p,{side:"top",className:"pn:whitespace-nowrap",children:[t(u,{onSelect:e=>{e.preventDefault();const t=n.store,o=(t.selectedPages||[]).filter(Boolean),i=o.length?o:t.activePage?[t.activePage]:[];if(!i.length){return}const s=new Set(i.map(e=>e.id)),a=t.pages.filter(e=>s.has(e.id)),r=a[a.length-1],l=a.map(e=>e.clone()),d=t.pages.indexOf(r);l.forEach((e,t)=>{e.setZIndex(d+1+t)}),t.selectPages(l.map(e=>e.id))},children:[e(a,{name:"action.duplicate",className:"pn:size-4"}),l("pagesTimeline.duplicatePage")]}),t(u,{onSelect:e=>{var t,o,i;e.preventDefault();const s=n.store.addPage({bleed:(null===(t=n.store.activePage)||void 0===t?void 0:t.bleed)||0,width:(null===(o=n.store.activePage)||void 0===o?void 0:o.width)||"auto",height:(null===(i=n.store.activePage)||void 0===i?void 0:i.height)||"auto"}),a=n.store.pages.indexOf(n);s.setZIndex(a+1)},children:[e(a,{name:"action.add",className:"pn:size-4"}),l("pagesTimeline.addPage")]}),y&&t(u,{onSelect:e=>{e.preventDefault();const t=n.store,o=(t.selectedPages||[]).filter(Boolean),i=o.length?o.map(e=>e.id):t.activePage?[t.activePage.id]:[];i.length&&t.deletePages(i)},children:[e(a,{name:"action.remove",className:"pn:size-4"}),l("pagesTimeline.removePage")]})]})]})})]})});