polotno 3.16.0 → 3.17.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 (45) hide show
  1. package/canvas/element.js +1 -1
  2. package/canvas/figure-element.js +1 -1
  3. package/canvas/gif-element.js +1 -1
  4. package/canvas/html-element.js +1 -1
  5. package/canvas/image-element.d.ts +15 -2
  6. package/canvas/image-element.js +1 -1
  7. package/canvas/line-element.js +1 -1
  8. package/canvas/page.js +1 -1
  9. package/canvas/placed-node.d.ts +22 -0
  10. package/canvas/placed-node.js +1 -0
  11. package/canvas/render-tag-element.js +1 -1
  12. package/canvas/rich-editor.js +2 -2
  13. package/canvas/table-element.js +1 -1
  14. package/canvas/text-element/auto-delete-empty-text.d.ts +15 -0
  15. package/canvas/text-element/auto-delete-empty-text.js +1 -0
  16. package/canvas/text-element/font-specs-loader.js +1 -1
  17. package/canvas/text-element.js +1 -1
  18. package/canvas/use-color.d.ts +2 -4
  19. package/canvas/use-color.js +1 -1
  20. package/canvas/use-image.js +1 -1
  21. package/canvas/video-element.js +1 -1
  22. package/canvas/workspace-canvas.js +1 -1
  23. package/model/group-model.d.ts +3 -0
  24. package/model/page-model.d.ts +12 -0
  25. package/model/page-model.js +1 -1
  26. package/model/store.d.ts +5 -6
  27. package/model/store.js +1 -1
  28. package/model/table-model.d.ts +3 -0
  29. package/model/table-model.js +1 -1
  30. package/package.json +15 -15
  31. package/pages-timeline/page-preview.d.ts +9 -2
  32. package/pages-timeline/page-preview.js +1 -1
  33. package/polotno.bundle.js +150 -150
  34. package/side-panel/animations-panel.js +1 -1
  35. package/toolbar/image-toolbar.js +1 -1
  36. package/utils/fonts.js +1 -1
  37. package/utils/l10n.js +1 -1
  38. package/utils/loader.js +1 -1
  39. package/utils/px.d.ts +1 -0
  40. package/utils/px.js +1 -1
  41. package/utils/ref-counted.d.ts +5 -0
  42. package/utils/ref-counted.js +1 -0
  43. package/utils/validate-key.js +1 -1
  44. package/utils/wait.d.ts +0 -1
  45. package/utils/wait.js +0 -1
@@ -1921,6 +1921,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
1921
1921
  } & {
1922
1922
  getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
1923
1923
  readonly minWidth: number;
1924
+ readonly basePixelRowHeights: number[];
1925
+ contentFloors(divider?: number): number[];
1926
+ readonly rowContentFloors: number[];
1924
1927
  getRowContentOuterHeight(row: number): number;
1925
1928
  readonly minHeight: number;
1926
1929
  readonly actualHeight: number;
@@ -1983,6 +1986,7 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
1983
1986
  _exporting: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1984
1987
  _rendering: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1985
1988
  _forceMount: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1989
+ _exportRendered: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
1986
1990
  }, {
1987
1991
  readonly store: any;
1988
1992
  } & {
@@ -3934,6 +3938,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
3934
3938
  } & {
3935
3939
  getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
3936
3940
  readonly minWidth: number;
3941
+ readonly basePixelRowHeights: number[];
3942
+ contentFloors(divider?: number): number[];
3943
+ readonly rowContentFloors: number[];
3937
3944
  getRowContentOuterHeight(row: number): number;
3938
3945
  readonly minHeight: number;
3939
3946
  readonly actualHeight: number;
@@ -3996,6 +4003,7 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
3996
4003
  _exporting: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
3997
4004
  _rendering: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
3998
4005
  _forceMount: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
4006
+ _exportRendered: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
3999
4007
  }> & {
4000
4008
  readonly store: any;
4001
4009
  } & {
@@ -5929,6 +5937,9 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
5929
5937
  } & {
5930
5938
  getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
5931
5939
  readonly minWidth: number;
5940
+ readonly basePixelRowHeights: number[];
5941
+ contentFloors(divider?: number): number[];
5942
+ readonly rowContentFloors: number[];
5932
5943
  getRowContentOuterHeight(row: number): number;
5933
5944
  readonly minHeight: number;
5934
5945
  readonly actualHeight: number;
@@ -5991,6 +6002,7 @@ declare const PageImpl: import("mobx-state-tree").IModelType<{
5991
6002
  _exporting: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
5992
6003
  _rendering: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
5993
6004
  _forceMount: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
6005
+ _exportRendered: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
5994
6006
  }, {
5995
6007
  readonly store: any;
5996
6008
  } & {
@@ -1 +1 @@
1
- import{getParentOfType as e,getSnapshot as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as n}from"nanoid";import{resolveBleed as r}from"@polotno/schema";import{hasBlendMode as s}from"@polotno/core/page";import{ElementTypes as d,forEveryChild as a,forEveryNode as m,TYPES_MAP as c,zIndexOps as l}from"./group-model.js";import{Store as h}from"./store.js";import{getTotalClientRect as p}from"../utils/math.js";import{scaledFontSizeBounds as g}from"../utils/px.js";const u=i.model("Page",{id:i.identifier,children:i.array(i.late(()=>d)),width:i.optional(i.union(i.number,i.literal("auto")),"auto"),height:i.optional(i.union(i.number,i.literal("auto")),"auto"),background:"white",bleed:0,bleedTop:i.maybe(i.number),bleedRight:i.maybe(i.number),bleedBottom:i.maybe(i.number),bleedLeft:i.maybe(i.number),custom:i.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot(e=>{const t=Object.assign({},e),o={};for(var i in t){"_"!==i[0]&&(o[i]=e[i])}return o}).views(t=>({get store(){return e(t,h)}})).views(e=>({get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id){return t}t+=o.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering},get playheadLocalTime(){if(!o(e)){return null}const t=e.store;if(!(null==t?void 0:t.playheadAccurate)){return null}const i=t.effectiveTime-this.startTime;return i<0||i>e.duration?null:Math.min(i,Math.max(0,e.duration-1))}})).views(e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height},get computedBleed(){return r(e)},get hasBlendMode(){return s(e.children)}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify(t(e)))})).actions(e=>Object.assign(Object.assign({clone(t={}){const o=e.toJSON(),i=new Map;o.children.forEach(e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o,m(e,e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o})}),o.children.forEach(e=>{e.cells&&e.cells.forEach(e=>{e.mergedInto&&i.has(e.mergedInto)&&(e.mergedInto=i.get(e.mergedInto))})});const r=Object.assign(Object.assign(Object.assign({},o),{id:n(10)}),t),s=e.store.selectedPages.includes(e),d=e.store.addPage(r),a=e.store.pages.indexOf(e);return d.setZIndex(a+1),s&&e.store.selectPages([d.id]),d},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:o=!1}={}){const i=c[t.type];if(!i){return void console.error("Can not find model with type "+t.type)}"children"in t&&Array.isArray(t.children)&&m(t,e=>{e.id=e.id||n(10)});const r=e.children.reduce((e,o)=>{if("group"===o.type){const i=o.children.reduce((e,o)=>{var i;const n=null===(i=o.name)||void 0===i?void 0:i.match(new RegExp(`${t.type}-(\\d+)`));if(n){const t=parseInt(n[1],10);return Math.max(e,t||0)}},0);return Math.max(e,i||0)}{const i=o.name.match(new RegExp(`${t.type}-(\\d+)`));if(i){const t=parseInt(i[1],10);return Math.max(e,t||0)}}return e},0),s=i.create(Object.assign({id:n(10),name:`${t.type}-${r+1}`},t));return e.children.push(s),s.selectable&&!o&&e.store.selectElements([s.id]),s}},l(e)),{setSize({width:t,height:o,useMagic:i,softChange:n}){if(i){const i=[],n=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;a(e,e=>{"group"!==e.type&&(n(e)||i.push(e))});const r=i.length?p(i):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},s=1/4,d=Math.max(0,Math.min(r.x,e.computedWidth-r.x-r.width)),m=e.computedWidth*s,c=Math.max(0,d-m),l=Math.max(0,Math.min(r.y,e.computedHeight-r.y-r.height)),h=e.computedHeight*s,u=Math.max(0,l-h),f=e.computedWidth-2*c,b=e.computedHeight-2*u,y=t/f,w=o/b,v=Math.min(y,w),x=(t-f*v)/2-c*v,E=(o-b*v)/2-u*v;a(e,e=>{var t;if("group"!==e.type){if(n(e)){e.set({x:e.x*v,y:e.y*v,width:e.width*y,height:e.height*w,cropX:0,cropY:0,cropWidth:1,cropHeight:1})}else if(e.set({x:x+e.x*v,y:E+e.y*v,width:e.width*v,height:e.height*v}),"text"===e.type){e.set(Object.assign({fontSize:e.fontSize*v},g(e,v)))}else if("figure"===e.type){e.set({strokeWidth:e.strokeWidth*v})}else if("table"===e.type){e.set({borderWidth:e.borderWidth*v});for(const o of e.cells){const e={fontSize:o.fontSize*v,cellPadding:o.cellPadding*v};if(o.borders){const i=JSON.parse(JSON.stringify(o.borders));for(const e of["top","right","bottom","left"]){null!=(null===(t=i[e])||void 0===t?void 0:t.width)&&(i[e]=Object.assign(Object.assign({},i[e]),{width:i[e].width*v}))}e.borders=i}o.set(e)}}}})}n||(e.width=t),n||(e.height=o)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));export const Page=u;
1
+ import{getParentOfType as e,getSnapshot as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as n}from"nanoid";import{resolveBleed as r}from"@polotno/schema";import{hasBlendMode as s}from"@polotno/core/page";import{ElementTypes as d,forEveryChild as a,forEveryNode as m,TYPES_MAP as c,zIndexOps as l}from"./group-model.js";import{Store as h}from"./store.js";import{getTotalClientRect as p}from"../utils/math.js";import{scaledFontSizeBounds as g}from"../utils/px.js";const u=i.model("Page",{id:i.identifier,children:i.array(i.late(()=>d)),width:i.optional(i.union(i.number,i.literal("auto")),"auto"),height:i.optional(i.union(i.number,i.literal("auto")),"auto"),background:"white",bleed:0,bleedTop:i.maybe(i.number),bleedRight:i.maybe(i.number),bleedBottom:i.maybe(i.number),bleedLeft:i.maybe(i.number),custom:i.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1,_exportRendered:!1}).postProcessSnapshot(e=>{const t=Object.assign({},e),o={};for(var i in t){"_"!==i[0]&&(o[i]=e[i])}return o}).views(t=>({get store(){return e(t,h)}})).views(e=>({get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id){return t}t+=o.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering},get playheadLocalTime(){if(!o(e)){return null}const t=e.store;if(!(null==t?void 0:t.playheadAccurate)){return null}const i=t.effectiveTime-this.startTime;return i<0||i>e.duration?null:Math.min(i,Math.max(0,e.duration-1))}})).views(e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height},get computedBleed(){return r(e)},get hasBlendMode(){return s(e.children)}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify(t(e)))})).actions(e=>Object.assign(Object.assign({clone(t={}){const o=e.toJSON(),i=new Map;o.children.forEach(e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o,m(e,e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o})}),o.children.forEach(e=>{e.cells&&e.cells.forEach(e=>{e.mergedInto&&i.has(e.mergedInto)&&(e.mergedInto=i.get(e.mergedInto))})});const r=Object.assign(Object.assign(Object.assign({},o),{id:n(10)}),t),s=e.store.selectedPages.includes(e),d=e.store.addPage(r),a=e.store.pages.indexOf(e);return d.setZIndex(a+1),s&&e.store.selectPages([d.id]),d},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:o=!1}={}){const i=c[t.type];if(!i){return void console.error("Can not find model with type "+t.type)}"children"in t&&Array.isArray(t.children)&&m(t,e=>{e.id=e.id||n(10)});const r=e.children.reduce((e,o)=>{if("group"===o.type){const i=o.children.reduce((e,o)=>{var i;const n=null===(i=o.name)||void 0===i?void 0:i.match(new RegExp(`${t.type}-(\\d+)`));if(n){const t=parseInt(n[1],10);return Math.max(e,t||0)}},0);return Math.max(e,i||0)}{const i=o.name.match(new RegExp(`${t.type}-(\\d+)`));if(i){const t=parseInt(i[1],10);return Math.max(e,t||0)}}return e},0),s=i.create(Object.assign({id:n(10),name:`${t.type}-${r+1}`},t));return e.children.push(s),s.selectable&&!o&&e.store.selectElements([s.id]),s}},l(e)),{setSize({width:t,height:o,useMagic:i,softChange:n}){if(i){const i=[],n=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;a(e,e=>{"group"!==e.type&&(n(e)||i.push(e))});const r=i.length?p(i):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},s=1/4,d=Math.max(0,Math.min(r.x,e.computedWidth-r.x-r.width)),m=e.computedWidth*s,c=Math.max(0,d-m),l=Math.max(0,Math.min(r.y,e.computedHeight-r.y-r.height)),h=e.computedHeight*s,u=Math.max(0,l-h),f=e.computedWidth-2*c,b=e.computedHeight-2*u,y=t/f,w=o/b,x=Math.min(y,w),v=(t-f*x)/2-c*x,E=(o-b*x)/2-u*x;a(e,e=>{var t;if("group"!==e.type){if(n(e)){e.set({x:e.x*x,y:e.y*x,width:e.width*y,height:e.height*w,cropX:0,cropY:0,cropWidth:1,cropHeight:1})}else if(e.set({x:v+e.x*x,y:E+e.y*x,width:e.width*x,height:e.height*x}),"text"===e.type){e.set(Object.assign({fontSize:e.fontSize*x},g(e,x)))}else if("figure"===e.type){e.set({strokeWidth:e.strokeWidth*x})}else if("table"===e.type){e.set({borderWidth:e.borderWidth*x});for(const o of e.cells){const e={fontSize:o.fontSize*x,cellPadding:o.cellPadding*x};if(o.borders){const i=JSON.parse(JSON.stringify(o.borders));for(const e of["top","right","bottom","left"]){null!=(null===(t=i[e])||void 0===t?void 0:t.width)&&(i[e]=Object.assign(Object.assign({},i[e]),{width:i[e].width*x}))}e.borders=i}o.set(e)}}}})}n||(e.width=t),n||(e.height=o)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));export const Page=u;
package/model/store.d.ts CHANGED
@@ -22,7 +22,6 @@ export interface ExportOptions {
22
22
  includeBleed?: boolean;
23
23
  mimeType?: 'image/png' | 'image/jpeg';
24
24
  quality?: number;
25
- _skipTimeout?: boolean;
26
25
  quickMode?: boolean;
27
26
  _exportCanvases?: ReturnType<typeof createExportCanvases>;
28
27
  }
@@ -222,6 +221,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
222
221
  _validated: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
223
222
  }, {
224
223
  highlightedElementId: string | null;
224
+ _workspaces: number;
225
225
  } & {
226
226
  setTool: import("./image-tools.js").SetTool;
227
227
  _setImageEditPanelAvailable(value: boolean): void;
@@ -668,7 +668,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
668
668
  ungroupElements(ids: Array<string>): void;
669
669
  deleteElements(ids: Array<string>): void;
670
670
  on(event: any, callback: any): import("mobx-state-tree").IDisposer | undefined;
671
- _toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, quickMode, _exportCanvases, }?: ExportOptions): Promise<HTMLCanvasElement>;
671
+ _toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, quickMode, _exportCanvases, }?: ExportOptions): Promise<HTMLCanvasElement>;
672
672
  toDataURL({ mimeType, quality, dpi, dpiMetadata, ...rest }?: ImageExportOptions): Promise<string>;
673
673
  toBlob({ mimeType, quality, ...rest }?: ExportOptions): Promise<Blob>;
674
674
  saveAsImage({ fileName, ...exportProps }?: ImageExportOptions & {
@@ -701,9 +701,8 @@ export declare const Store: import("mobx-state-tree").IModelType<{
701
701
  saveAsPDF({ fileName, ...exportProps }?: ExportOptions & {
702
702
  fileName?: string;
703
703
  }): Promise<void>;
704
- waitLoading({ _skipTimeout }?: {
705
- _skipTimeout?: boolean | undefined;
706
- }): Promise<void>;
704
+ _setWorkspaceMounted(mounted: boolean): void;
705
+ waitLoading(): Promise<void>;
707
706
  toJSON(): {
708
707
  width: number;
709
708
  height: number;
@@ -738,7 +737,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
738
737
  removeFont(fontFamily: string): void;
739
738
  addAudio(data: Partial<SnapshotIn<typeof Audio>>): void;
740
739
  removeAudio(audioId: string): void;
741
- loadFont(fontFamily: string, fontStyle?: string, fontWeight?: string, sampleText?: string): Promise<void[]>;
740
+ loadFont(fontFamily: string, fontStyle?: string, fontWeight?: string, sampleText?: string): Promise<void | any[]>;
742
741
  validate(json: any): {
743
742
  path: string;
744
743
  message: string | undefined;
package/model/store.js CHANGED
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{localFileToURL as v}from"../utils/file.js";import{getJsPDF as y}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as P,setKey as x}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as E}from"../utils/flags.js";import{addDpiMetadataToImage as I}from"../utils/image-dpi.js";import{nodeToCanvas as T,createExportCanvases as _,releaseExportCanvases as O}from"../utils/canvas.js";import{whenLoaded as S}from"../utils/loader.js";import{polotnoError as k}from"@polotno/core/errors";import{pxToUnit as j}from"../utils/unit.js";import{deepEqual as F}from"../utils/deep-equal.js";import{waitTillAvailable as R}from"../utils/wait.js";import{jsonToHTML as A}from"@polotno/html-export";import{jsonToSVG as V}from"@polotno/svg-export";import{warnOnceDeprecated as C}from"../utils/deprecation.js";import{Page as L}from"./page-model.js";import{forEveryChild as M,forEveryNode as B}from"./group-model.js";import{Audio as D}from"./audio-model.js";import{imageTools as H}from"./image-tools.js";import{IMAGE_TOOLS as W}from"../image-tools/sessions.js";function N(e){return!!e&&!!e.type&&"tablecell"!==e.type}r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));const G=l.model("BrushOptions",{strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)});export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(L),fonts:l.array(Font),audios:l.array(D),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser","crop","expand","inpaint","upscale","remove-background"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),brush:l.optional(G,{}),highlighter:l.optional(G,{strokeWidth:30,opacity:.5})}).views(e=>({get active(){return e[e.brushType]}})).views(e=>({get strokeWidth(){return e.active.strokeWidth},get stroke(){return e.active.stroke},get opacity(){return e.active.opacity}})),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).volatile(()=>({highlightedElementId:null})).extend(H).views(e=>{const t=g(()=>{const t={};return B({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(N)},get children(){return e.pages},get selectedShapes(){const e=[];return M({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){const t=e.activeTool;return"crop"===(null==t?void 0:t.name)?this.getElementById(t.elementId):void 0},find(t){let o;return B({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(P(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},setToolOptions(t){const{brushType:o}=t,i=e(t,["brushType"]);o&&(r.toolOptions.brushType=o),Object.assign(r.toolOptions.active,i)},addPage(e){const t=L.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){r._beforeToolSelection(e);const t=e.map(e=>r.getElementById(e)).filter(N);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},highlightElement(e){r.highlightedElementId=e},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&&("image-edit"!==e&&r._beforeToolPanel(),r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){r._beforeToolPanel();const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.sort((e,t)=>a.children.indexOf(e)-a.children.indexOf(t));const s=a.children.indexOf(i[i.length-1])-i.length+1;i.forEach(e=>n(e));const l=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),d=Object.assign({id:p(10),name:`group-${l+1}`,children:i,type:"group"},t);return a.children.splice(s,0,d),r.selectedElementsIds=o([d.id]),a.children.find(e=>e.id===d.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)});const a=e.children.slice();a.forEach(t=>{t.set({opacity:t.opacity*e.opacity}),n(t)}),t.children.splice(o,1,...a)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!F(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;o=o||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===o);if(!g){throw k("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;try{(s?p>r._elementsPixelRatio:p!==r._elementsPixelRatio)&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const e=await R(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!e){throw k("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const d=e[0];await f.waitLoading({_skipTimeout:a});const u=d.findOne(".page-container");if(!u){throw k("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const h=d.position();d.position({x:0,y:0}),d.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),u.find(".page-background").forEach(e=>e.shadowEnabled(!1)),u.find(".page-background").forEach(e=>e.strokeEnabled(!1)),u.find(".highlighter").forEach(e=>e.visible(!1));const v=u.findOne(".page-background-group"),y=v.clip();v.clip({x:null,y:null,width:null,height:null});const b=u.findOne(".elements-container"),P=b.clip();b.clip({x:null,y:null,width:null,height:null});const x=u.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const w=u.find(e=>e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&u.find(".page-background").forEach(e=>e.hide());const I=n?g.computedBleed:m;let _=I.left,O=I.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(_=0,O=0):r.bleedVisible&&!n&&(_=-g.computedBleed.left,O=-g.computedBleed.top):(_=0,O=0));const S=g.computedWidth+I.left+I.right,j=g.computedHeight+I.top+I.bottom,F=u.scale();u.scale({x:1,y:1});const A=T(u,{x:u.x()-_,y:u.y()-O,width:S,height:j,pixelRatio:p,imageSmoothingQuality:E.imageDownScalingEnabled&&!s?"high":void 0,sceneCanvas:null==l?void 0:l.sceneCanvas});u.scale(F);const V=A._canvas;if("image/jpeg"===i){const e=V.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,V.width,V.height),e.restore()}return t&&u.find(".page-background").forEach(e=>e.show()),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".page-background").forEach(e=>e.shadowEnabled(!0)),u.find(".page-background").forEach(e=>e.strokeEnabled(!0)),d.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".highlighter").forEach(e=>e.visible(!0)),v.clip(y),b.clip(P),d.position(h),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),V}finally{f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1})}},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:I(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await y(),d=e=>j({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),v=d(g.computedHeight+u.top+u.bottom+2*c);var b=new l({unit:i,orientation:h>v?"landscape":"portrait",format:[h,v],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let x=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++x/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{b.addPage([t,o],t>o?"landscape":"portrait");const r=b.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw k("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){b.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);b.line(e,0,e,c),b.line(0,n,c,n),b.line(t-i,0,t-i,c),b.line(t,n,t-c,n),b.line(0,o-a,c,o-a),b.line(e,o,e,o-c),b.line(t,o-a,t-c,o-a),b.line(t-i,o,t-i,o-c)}b.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){var t,o;const i=e.pixelRatio||1,n=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),a=r.pages.filter(e=>n.includes(e.id));if(!a.length){throw k("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}null===(t=e.onProgress)||void 0===t||t.call(e,0,"rendering");const s=a[0],l=await b({width:s.computedWidth*i,height:s.computedHeight*i}),d=1e3/(e.fps||10),p=a.map(e=>({page:e,frames:Math.max(1,Math.floor(e.duration/d))})),c=p.reduce((e,{frames:t})=>e+t,0);let g=0;const m=_(),u=r._elementsPixelRatio;f.setElementsPixelRatio(i);try{for(const{page:t,frames:n}of p){for(let a=0;a<n;a++){const n=t.startTime+a*d||1;f.setCurrentTime(n);for(const e of r.pages){e.set({_rendering:e.id===t.id})}const s=await f._toCanvas({pixelRatio:i,pageId:t.id,_skipTimeout:!0,_exportCanvases:m});l.addFrame(s.getContext("2d"),{delay:d,copy:!0}),g++,null===(o=e.onProgress)||void 0===o||o.call(e,g/c/2,"rendering")}}}finally{O(m),f.setElementsPixelRatio(u);for(const e of r.pages){e.set({_rendering:!1})}f.stop()}return new Promise((t,o)=>{let i=!1;e.onProgress&&l.on("progress",t=>{var n;if(!i){try{null===(n=e.onProgress)||void 0===n||n.call(e,.5+t/2,"encoding")}catch(a){i=!0,o(a)}}}),l.on("finished",e=>{i||v(e).then(t,o)}),l.render()})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){C("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return A(t,{elementHook:e,textOverflow:E.textOverflow,textSplitAllowed:E.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;C("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return V(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),Object.assign({elementHook:e,fontEmbedding:o,textSplitAllowed:E.textSplitAllowed},"fit"===E.textOverflow&&{textOverflow:"fit"}))},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await S()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,l="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=u(e,{modernTextRenderer:E.htmlRenderEnabled||E.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion,d.tool in W&&delete d.tool;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[],r._closeImageTool("discard"),M(r,e=>{var t;"pendingEdit"in e&&(null===(t=e.pendingEdit)||void 0===t||t.cancel())});const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.fonts.filter(t=>t.fontFamily===e.fontFamily).forEach(e=>i(e)),r.fonts.push(e),w.injectCustomFont(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e)),w.removeCustomFont(e)},addAudio(e){const t=D.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(n=>(n.fontStyle===(null!=t?t:"normal")&&n.fontWeight===(null!=o?o:"normal")?w.loadFont:w.loadFontFace)(e,n.fontStyle,n.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return x(e),Store.create({_forceShowCredit:t})}export default createStore;
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,isAlive as s,onSnapshot as r,setLivelinessChecking as l,types as d}from"mobx-state-tree";import{UndoManager as p}from"./history.js";import{nanoid as c}from"nanoid";import g from"konva";import{computed as m,when as u}from"mobx";import{ZERO_BLEED as f,migrateDesign as h,CURRENT_SCHEMA_VERSION as v}from"@polotno/schema";import{downloadFile as y}from"../utils/download.js";import{localFileToURL as b}from"../utils/file.js";import{getJsPDF as P}from"../utils/pdf.js";import{createGIF as w}from"../utils/gif-lib.js";import{validateKey as x,setKey as E}from"../utils/validate-key.js";import*as I from"../utils/fonts.js";import{flags as T}from"../utils/flags.js";import{addDpiMetadataToImage as _}from"../utils/image-dpi.js";import{nodeToCanvas as S,createExportCanvases as O,releaseExportCanvases as k}from"../utils/canvas.js";import{whenLoaded as j,getAssetLoadTimeout as F}from"../utils/loader.js";import{polotnoError as R}from"@polotno/core/errors";import{pxToUnit as A}from"../utils/unit.js";import{deepEqual as V}from"../utils/deep-equal.js";import{jsonToHTML as C}from"@polotno/html-export";import{jsonToSVG as L}from"@polotno/svg-export";import{warnOnceDeprecated as M}from"../utils/deprecation.js";import{Page as B}from"./page-model.js";import{forEveryChild as D,forEveryNode as H}from"./group-model.js";import{Audio as W}from"./audio-model.js";import{imageTools as N}from"./image-tools.js";import{IMAGE_TOOLS as G}from"../image-tools/sessions.js";function U(e){return!!e&&!!e.type&&"tablecell"!==e.type}function q(e){const t=new Map;for(const o of e){const e=o.parent;if(!e||t.has(o)){continue}let i=0;for(const o of e.children){t.set(o,i++)}}e.sort((e,o)=>{var i,n;return(null!==(i=t.get(e))&&void 0!==i?i:0)-(null!==(n=t.get(o))&&void 0!==n?n:0)})}l("ignore");export const Font=d.model("Font",{fontFamily:d.string,url:d.optional(d.string,""),styles:d.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));const X=d.model("BrushOptions",{strokeWidth:d.optional(d.number,5),stroke:d.optional(d.string,"#000000"),opacity:d.optional(d.number,1)});export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=d.model("Store",{role:"",pages:d.array(B),fonts:d.array(Font),audios:d.array(W),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:d.optional(d.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:v,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:d.optional(d.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:d.frozen(),tool:d.optional(d.enumeration("Tool",["selection","draw","pan","text","eraser","crop","expand","inpaint","upscale","remove-background"]),"selection"),toolOptions:d.optional(d.model({brushType:d.optional(d.enumeration("BrushType",["brush","highlighter"]),"brush"),brush:d.optional(X,{}),highlighter:d.optional(X,{strokeWidth:30,opacity:.5})}).views(e=>({get active(){return e[e.brushType]}})).views(e=>({get strokeWidth(){return e.active.strokeWidth},get stroke(){return e.active.stroke},get opacity(){return e.active.opacity}})),{}),selectedElementsIds:d.array(d.string),animatedElementsIds:d.array(d.string),history:d.optional(p,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:d.array(d.string),_forceShowCredit:!1,_validated:!1}).volatile(()=>({highlightedElementId:null,_workspaces:0})).extend(N).views(e=>{const t=m(()=>{const t={};return H({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(U)},get children(){return e.pages},get selectedShapes(){const e=[];return D({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){const t=e.activeTool;return"crop"===(null==t?void 0:t.name)?this.getElementById(t.elementId):void 0},find(t){let o;return H({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(l=>{let d=0,p=null,m=!1;const v={afterCreate(){l.history.canUndo},setCurrentTime(e){l.currentTime=e},_togglePlaying(e=!l.isPlaying){l.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=l.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),l.animatedElementsIds=o(e),l.currentTime=t,l.isPlaying=!0,d=Date.now(),p=n,m=a,requestAnimationFrame(()=>v.seek())},checkActivePage(){const e=l.pageAtTime(l.currentTime);e&&v.selectPage(e.id)},seek(){if(!l.isPlaying){return}const e=Date.now(),t=e-d;d=e,l.currentTime+=t;const o=p||l.duration;l.currentTime>=o&&!m&&(l.currentTime=o),v.checkActivePage(),l.isPlaying&&l.currentTime<o?requestAnimationFrame(()=>v.seek()):l.isPlaying&&m?(l.currentTime=0,requestAnimationFrame(()=>v.seek())):v.pause()},pause(){l.isPlaying=!1,l.animatedElementsIds=o([])},stop(){v.pause(),l.currentTime=0,v.checkActivePage()},__(){l._validated||(x(l._forceShowCredit),l._validated=!0)},set(e){Object.assign(l,e)},setUnit({unit:e,dpi:t}){l.unit=e||l.unit,l.dpi=t||l.dpi},setRole(e){l.role=e},setToolOptions(t){const{brushType:o}=t,i=e(t,["brushType"]);o&&(l.toolOptions.brushType=o),Object.assign(l.toolOptions.active,i)},addPage(e){const t=B.create(Object.assign({id:c(10)},e));return l.pages.push(t),l._activePageId=t.id,l._selectedPagesIds=o([]),t},selectPage(e){l._activePageId=e,1===l._selectedPagesIds.length&&(l._selectedPagesIds=o([e]))},selectPages(e){l._selectedPagesIds=o(e),1===l._selectedPagesIds.length&&(l._activePageId=l._selectedPagesIds[0])},selectElements(e){l._beforeToolSelection(e);const t=e.map(e=>l.getElementById(e)).filter(U);q(t),l.selectedElementsIds=o(t.map(e=>e.id))},highlightElement(e){l.highlightedElementId=e},toggleBleed(e){l.bleedVisible=null!=e?e:!l.bleedVisible},toggleRulers(e){l.rulesVisible=null!=e?e:!l.rulesVisible},setTimingPreview(e){l.timingPreview=e},toggleDistanceGuides(e){l.distanceGuidesVisible=null!=e?e:!l.distanceGuidesVisible},openSidePanel(e){l.openedSidePanel!==e&&("image-edit"!==e&&l._beforeToolPanel(),l.previousOpenedSidePanel=l.openedSidePanel,l.openedSidePanel=e)},restoreSidePanel(){l._beforeToolPanel();const e=l.previousOpenedSidePanel;e&&e!==l.openedSidePanel?l.openedSidePanel=e:l.openedSidePanel="photos"},setScale(e){l.scale=e},_setScaleToFit(e){l.scaleToFit=e},setElementsPixelRatio(e){l._elementsPixelRatio=e},setSize(e,t,o){l.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),l.width=e,l.height=t},setPageZIndex(e,t){const o=l.pages.find(t=>t.id===e);o&&(n(o),l.pages.remove(o),l.pages.splice(t,0,o))},deletePages(e){const t=l.pages.indexOf(l.activePage);e.forEach(e=>{const t=l.pages.find(t=>t.id===e);i(t)});const n=l._selectedPagesIds.filter(e=>l.pages.some(t=>t.id===e)),a=Math.min(l.pages.length-1,t),s=l.pages[a];s&&(l._activePageId=s.id),v.selectPages(n),l.selectedElementsIds=o(l.selectedElementsIds.filter(e=>l.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>l.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}q(i);const s=a.children.indexOf(i[i.length-1])-i.length+1;i.forEach(e=>n(e));const r=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),d=Object.assign({id:c(10),name:`group-${r+1}`,children:i,type:"group"},t);return a.children.splice(s,0,d),l.selectedElementsIds=o([d.id]),a.children.find(e=>e.id===d.id)},ungroupElements(e){const t=e.map(e=>l.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)});const a=e.children.slice();a.forEach(t=>{t.set({opacity:t.opacity*e.opacity}),n(t)}),t.children.splice(o,1,...a)}}),l.selectedElementsIds=o(i)},deleteElements(e){const t=[];l.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),l.selectedElementsIds=o(l.selectedElementsIds.filter(e=>l.getElementById(e)))},on(e,t){if("change"===e){let e=v.toJSON();return r(l,o=>{const i=v.toJSON();!V(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,quickMode:a=!1,_exportCanvases:r}={}){var d;const p=e||1;o=o||(null===(d=l.pages[0])||void 0===d?void 0:d.id);const c=l.pages.find(e=>e.id===o);if(!c){throw R("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:l.pages.map(e=>e.id)})}const m=l._elementsPixelRatio;try{(a?p>l._elementsPixelRatio:p!==l._elementsPixelRatio)&&v.setElementsPixelRatio(p),c.set(a?{_forceMount:!0}:{_exporting:!0}),await u(()=>c._exportRendered||0===l._workspaces||!l.pages.includes(c),{timeout:F()}).catch(()=>{}),await j();const e=g.stages.filter(e=>e.getAttr("pageId")===o);if(!c._exportRendered||0===e.length){throw R("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const s=e[0],d=s.findOne(".page-container");if(!d){throw R("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const m=s.position();s.position({x:0,y:0}),s.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),d.find(".page-background").forEach(e=>e.shadowEnabled(!1)),d.find(".page-background").forEach(e=>e.strokeEnabled(!1)),d.find(".highlighter").forEach(e=>e.visible(!1));const h=d.findOne(".page-background-group"),y=h.clip();h.clip({x:null,y:null,width:null,height:null});const b=d.findOne(".elements-container"),P=b.clip();b.clip({x:null,y:null,width:null,height:null});const w=d.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const x=d.find(e=>e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&d.find(".page-background").forEach(e=>e.hide());const E=n?c.computedBleed:f;let I=E.left,_=E.top;!l.bleedVisible&&n||(l.bleedVisible||n?l.bleedVisible&&n?(I=0,_=0):l.bleedVisible&&!n&&(I=-c.computedBleed.left,_=-c.computedBleed.top):(I=0,_=0));const O=c.computedWidth+E.left+E.right,k=c.computedHeight+E.top+E.bottom,A=d.scale();d.scale({x:1,y:1});const V=S(d,{x:d.x()-I,y:d.y()-_,width:O,height:k,pixelRatio:p,imageSmoothingQuality:T.imageDownScalingEnabled&&!a?"high":void 0,sceneCanvas:null==r?void 0:r.sceneCanvas});d.scale(A);const C=V._canvas;if("image/jpeg"===i){const e=C.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,C.width,C.height),e.restore()}return t&&d.find(".page-background").forEach(e=>e.show()),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),d.find(".page-background").forEach(e=>e.shadowEnabled(!0)),d.find(".page-background").forEach(e=>e.strokeEnabled(!0)),s.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),d.find(".highlighter").forEach(e=>e.visible(!0)),h.clip(y),b.clip(P),s.position(m),null==c||c.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),C}finally{v.setElementsPixelRatio(m),s(c)&&c.set({_forceMount:!1,_exporting:!1})}},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const r=await v._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=r.toDataURL(d,i);g.Util.releaseCanvas(r);const c=null!=n?n:l.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===c?p:_(p,d,c)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await v._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return g.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];y(await v.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||l.dpi,o=e.parallel||1,i=e.unit||("px"===l.unit?"mm":l.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:l.pages.map(e=>e.id)),s=l.pages.filter(e=>a.includes(e.id)),r=await P(),d=e=>A({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},m=e.includeBleed&&g.computedBleed||f,u=d(g.computedWidth+m.left+m.right+2*c),h=d(g.computedHeight+m.top+m.bottom+2*c);var y=new r({unit:i,orientation:u>h?"landscape":"portrait",format:[u,h],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const b=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let w=0;for(const l of b){const t=l.map(async t=>{const o=e.includeBleed?t.computedBleed:f,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await 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:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw R("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await v._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){var t,o;const i=e.pixelRatio||1,n=e.pageIds||(e.pageId?[e.pageId]:l.pages.map(e=>e.id)),a=l.pages.filter(e=>n.includes(e.id));if(!a.length){throw R("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:l.pages.map(e=>e.id)})}null===(t=e.onProgress)||void 0===t||t.call(e,0,"rendering");const s=a[0],r=await w({width:s.computedWidth*i,height:s.computedHeight*i}),d=1e3/(e.fps||10),p=a.map(e=>({page:e,frames:Math.max(1,Math.floor(e.duration/d))})),c=p.reduce((e,{frames:t})=>e+t,0);let g=0;const m=O(),u=l._elementsPixelRatio;v.setElementsPixelRatio(i);try{for(const{page:t,frames:n}of p){for(let a=0;a<n;a++){const n=t.startTime+a*d||1;v.setCurrentTime(n);for(const e of l.pages){e.set({_rendering:e.id===t.id})}const s=await v._toCanvas({pixelRatio:i,pageId:t.id,_exportCanvases:m});r.addFrame(s.getContext("2d"),{delay:d,copy:!0}),g++,null===(o=e.onProgress)||void 0===o||o.call(e,g/c/2,"rendering")}}}finally{k(m),v.setElementsPixelRatio(u);for(const e of l.pages){e.set({_rendering:!1})}v.stop()}return new Promise((t,o)=>{let i=!1;e.onProgress&&r.on("progress",t=>{var n;if(!i){try{null===(n=e.onProgress)||void 0===n||n.call(e,.5+t/2,"encoding")}catch(a){i=!0,o(a)}}}),r.on("finished",e=>{i||b(e).then(t,o)}),r.render()})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await v.toGIFDataURL(i);y(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){M("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=v.toJSON();return C(t,{elementHook:e,textOverflow:T.textOverflow,textSplitAllowed:T.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await v.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));y(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;M("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=v.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return L(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),Object.assign({elementHook:e,fontEmbedding:o,textSplitAllowed:T.textSplitAllowed},"fit"===T.textOverflow&&{textOverflow:"fit"}))},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await v.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));y(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await v._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},_setWorkspaceMounted(e){l._workspaces+=e?1:-1},async waitLoading(){await j()},toJSON:()=>({width:l.width,height:l.height,fonts:a(l.fonts),pages:a(l.pages),audios:a(l.audios),unit:l.unit,dpi:l.dpi,custom:l.custom,schemaVersion:l.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,r="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=h(e,{modernTextRenderer:T.htmlRenderEnabled||T.renderTagTextEnabled,modernizeTextBackground:r});delete d.schemaVersion,d.tool in G&&delete d.tool;const p=l.activePage?l.pages.indexOf(l.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[],l._closeImageTool("discard"),D(l,e=>{var t;"pendingEdit"in e&&(null===(t=e.pendingEdit)||void 0===t||t.cancel())});const g=Object.assign({},a(l));Object.assign(g,d),g.history=s?a(l.history):{history:[],undoIdx:-1,targetPath:""},t(l,g)},clear({keepHistory:e=!1}={}){const t=l.pages.map(e=>e.id);v.deletePages(t),l.custom=null,e||l.history.clear()},addFont(e){l.fonts.filter(t=>t.fontFamily===e.fontFamily).forEach(e=>i(e)),l.fonts.push(e),I.injectCustomFont(e)},removeFont(e){l.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e)),I.removeCustomFont(e)},addAudio(e){const t=W.create(Object.assign({id:c(10)},e));l.audios.push(t)},removeAudio(e){const t=l.audios.find(t=>t.id===e);t&&l.audios.remove(t)},async loadFont(e,t,o,i){var n,a;const s=l.fonts.find(t=>t.fontFamily===e)||I.globalFonts.find(t=>t.fontFamily===e);if(s?I.injectCustomFont(s):I.injectGoogleFont(e),T.renderTagTextEnabled){return I.loadFont(e,null!=t?t:"normal",null!=o?o:"normal",i)}const r=null!==(a=null===(n=null==s?void 0:s.styles)||void 0===n?void 0:n.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"})))&&void 0!==a?a:[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return t&&o&&!r.some(e=>e.fontStyle===t&&e.fontWeight===o)&&r.push({fontStyle:t,fontWeight:o}),Promise.all(r.map(n=>(n.fontStyle===(null!=t?t:"normal")&&n.fontWeight===(null!=o?o:"normal")?I.loadFont:I.loadFontFace)(e,n.fontStyle,n.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return v});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return E(e),Store.create({_forceShowCredit:t})}export default createStore;
@@ -482,6 +482,9 @@ export declare const TableElement: import("mobx-state-tree").IModelType<{
482
482
  } & {
483
483
  getCell(row: number, col: number): TableCellType | undefined;
484
484
  readonly minWidth: number;
485
+ readonly basePixelRowHeights: number[];
486
+ contentFloors(divider?: number): number[];
487
+ readonly rowContentFloors: number[];
485
488
  getRowContentOuterHeight(row: number): number;
486
489
  readonly minHeight: number;
487
490
  readonly actualHeight: number;
@@ -1 +1 @@
1
- import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{clampFontSize as c,TABLE_CELL_OVERRIDABLE_KEYS as d}from"@polotno/schema/defaults";import{Shape as a}from"./shape-model.js";const g=.05,u=e.enumeration(["solid","dashed","dotted","none"]);function h(e){return t(e,2)}function f(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?h(e)[t]:o}function b(e){return t(e,1)}const w=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(u)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),p=e.model("CellBorders",{top:e.maybe(w),right:e.maybe(w),bottom:e.maybe(w),left:e.maybe(w)}).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=d,C=new Set(m),_=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],y=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],v=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"]),I={opacity:1,rowSpan:1,colSpan:1,name:""},S=[];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(p),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 y){o in e&&(t[o]=e[o])}for(const o of m){void 0!==e[o]&&(t[`_${o}`]=e[o])}return void 0!==t._fontSize&&(t._fontSize=c(t._fontSize)),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 I&&l===I[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=h(e),o=b(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=h(e),o=b(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 f(e,"fontSize",30)},get fontFamily(){return f(e,"fontFamily","Roboto")},get fontWeight(){return f(e,"fontWeight","normal")},get fontStyle(){return f(e,"fontStyle","normal")},get textDecoration(){return f(e,"textDecoration","")},get textTransform(){return f(e,"textTransform","none")},get fill(){return f(e,"fill","black")},get align(){return f(e,"align","left")},get verticalAlign(){return f(e,"verticalAlign","top")},get lineHeight(){return f(e,"lineHeight",1.2)},get letterSpacing(){return f(e,"letterSpacing",0)},get strokeWidth(){return f(e,"strokeWidth",0)},get stroke(){return f(e,"stroke","black")},get cellBackground(){return f(e,"cellBackground","transparent")},get cellPadding(){return f(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 S}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&(t=Object.assign(Object.assign({},t),{fontSize:c(t.fontSize)}));const o={};for(const[e,l]of Object.entries(t)){C.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:v.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){if(!l(e)){return}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 O(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?R(e.length):e.map(e=>e/t)}export const TableElement=a.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}).preProcessSnapshot(e=>null==(null==e?void 0:e.fontSize)?e:Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){C.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of _){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=e.set,o={set(e){null!=e.fontSize&&(e=Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})),t(e)},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){o.selectRowRange(e,e)},selectColumn(e){o.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=[],n=[];let s=0;for(let u=0;u<o;u++){r.push(e.rowHeights[u]*l);const t=e.getRowContentOuterHeight(u);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(t){o._resetBaseRowHeights();const l=t>0?t-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let o=0;o<e.rows;o++){s.push(e.rowHeights[o]*e.height/n)}s.splice(t,0,r/n);const i=t>0?t-1:0,c=[];for(let o=0;o<e.cols;o++){c.push(e.cells[i*e.cols+o])}const d=t*e.cols,a=H(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(O(s))},removeRow(t){if(e.rows<=1){return}o._resetBaseRowHeights();const l=t*e.cols,r=[];for(let o=l;o<l+e.cols;o++){r.push(e.cells[o].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(t,1),e.rows-=1,e.rowHeights.replace(O(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(O(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(O(r))},removeRowRange(t,l){for(let r=l;r>=t&&!(e.rows<=1);r--){o.removeRow(r)}},removeColumnRange(t,l){for(let r=l;r>=t&&!(e.cols<=1);r--){o.removeColumn(r)}},distributeRowsEvenly(){const t=e.rows;let l=20;for(let o=0;o<t;o++){l=Math.max(l,e.getRowContentOuterHeight(o))}o._resetBaseRowHeights(),e.height=Math.max(e.height,l*t),e.rowHeights.replace(R(t))},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<g?(l[t]=g,l[t+1]=r-g):s<g?(l[t+1]=g,l[t]=r-g):(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(g,s),d=Math.max(g,i),a=l[t]+o,u=l[t+1]-o;a<c?(l[t]=c,l[t+1]=r-c):u<d?(l[t+1]=d,l[t]=r-d):(l[t]=a,l[t+1]=u),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(t,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(t,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){o.setCellBorders(e,s,l)}}};return o}).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{clampFontSize as c,TABLE_CELL_OVERRIDABLE_KEYS as d}from"@polotno/schema/defaults";import{Shape as a}from"./shape-model.js";const g=.05,u=e.enumeration(["solid","dashed","dotted","none"]);function h(e){return t(e,2)}function f(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?h(e)[t]:o}function b(e){return t(e,1)}const w=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(u)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),m=e.model("CellBorders",{top:e.maybe(w),right:e.maybe(w),bottom:e.maybe(w),left:e.maybe(w)}).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}),p=d,C=new Set(p),_=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],y=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],v=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"]),I={opacity:1,rowSpan:1,colSpan:1,name:""},S=[];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(m),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 y){o in e&&(t[o]=e[o])}for(const o of p){void 0!==e[o]&&(t[`_${o}`]=e[o])}return void 0!==t._fontSize&&(t._fontSize=c(t._fontSize)),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 I&&l===I[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=h(e),o=b(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=h(e),o=b(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 f(e,"fontSize",30)},get fontFamily(){return f(e,"fontFamily","Roboto")},get fontWeight(){return f(e,"fontWeight","normal")},get fontStyle(){return f(e,"fontStyle","normal")},get textDecoration(){return f(e,"textDecoration","")},get textTransform(){return f(e,"textTransform","none")},get fill(){return f(e,"fill","black")},get align(){return f(e,"align","left")},get verticalAlign(){return f(e,"verticalAlign","top")},get lineHeight(){return f(e,"lineHeight",1.2)},get letterSpacing(){return f(e,"letterSpacing",0)},get strokeWidth(){return f(e,"strokeWidth",0)},get stroke(){return f(e,"stroke","black")},get cellBackground(){return f(e,"cellBackground","transparent")},get cellPadding(){return f(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 S}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&(t=Object.assign(Object.assign({},t),{fontSize:c(t.fontSize)}));const o={};for(const[e,l]of Object.entries(t)){C.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:v.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){if(!l(e)){return}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 p){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 x(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?R(e.length):e.map(e=>e/t)}export const TableElement=a.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}).preProcessSnapshot(e=>null==(null==e?void 0:e.fontSize)?e:Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){C.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of _){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},get basePixelRowHeights(){var t,o;const l=null!==(t=e._baseHeight)&&void 0!==t?t:e.height;return(null!==(o=e._baseRowHeights)&&void 0!==o?o:e.rowHeights).map(e=>e*l)},contentFloors(o){const l=t.basePixelRowHeights,r=new Array(e.rows).fill(0),n=[];for(const s of t.visibleCells){const t=e._cellContentHeights.get(s.id);if(void 0===t){continue}const l=s.borderInsets,i=t+2*s.cellPadding+l.top+l.bottom,c=s.row,d=Math.min(c+s.rowSpan,e.rows);d-c===1?r[c]=Math.max(r[c],i):void 0!==o&&c<=o&&o+1<d||n.push({start:c,end:d,outer:i})}n.sort((e,t)=>e.end-e.start-(t.end-t.start));for(const{start:e,end:t,outer:s}of n){const o=r.slice(e,t),n=l.slice(e,t),i=s-o.reduce((e,t)=>e+t,0);if(i<=0){continue}const c=o.map((e,t)=>Math.max(0,n[t]-e)),d=c.reduce((e,t)=>e+t,0),a=n.reduce((e,t)=>e+t,0),g=Math.min(i,d);o.forEach((t,l)=>{r[e+l]=t+(d>0?g*c[l]/d:0)+(i-g)*(a>0?n[l]/a:1/o.length)})}return r},get rowContentFloors(){return t.contentFloors()},getRowContentOuterHeight(e){var o;return null!==(o=t.rowContentFloors[e])&&void 0!==o?o:0},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}const l=t.rowContentFloors.reduce((e,t)=>e+t,0);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(){if(0===e._cellContentHeights.size){return null}const o=t.basePixelRowHeights,l=t.rowContentFloors;let r=!1;const n=[];for(let t=0;t<e.rows;t++){const s=e.rowHeights[t]*e.height,i=Math.max(l[t],o[t]);Math.abs(i-s)>1?(n.push(i),r=!0):n.push(s)}if(!r){return null}const s=n.reduce((e,t)=>e+t,0);return{rowHeights:n.map(e=>e/s),height:s}}};return t}).actions(e=>{const t=e.set,o={set(e){null!=e.fontSize&&(e=Object.assign(Object.assign({},e),{fontSize:c(e.fontSize)})),t(e)},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){o.selectRowRange(e,e)},selectColumn(e){o.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=e.rowHeights.map(e=>e*l),n=e.rowContentFloors,s=n.reduce((e,t)=>e+t,0);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(t){o._resetBaseRowHeights();const l=t>0?t-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let o=0;o<e.rows;o++){s.push(e.rowHeights[o]*e.height/n)}s.splice(t,0,r/n);const i=t>0?t-1:0,c=[];for(let o=0;o<e.cols;o++){c.push(e.cells[i*e.cols+o])}const d=t*e.cols,a=H(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(x(s))},removeRow(t){if(e.rows<=1){return}o._resetBaseRowHeights();const l=t*e.cols,r=[];for(let o=l;o<l+e.cols;o++){r.push(e.cells[o].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(t,1),e.rows-=1,e.rowHeights.replace(x(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(x(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(x(r))},removeRowRange(t,l){for(let r=l;r>=t&&!(e.rows<=1);r--){o.removeRow(r)}},removeColumnRange(t,l){for(let r=l;r>=t&&!(e.cols<=1);r--){o.removeColumn(r)}},distributeRowsEvenly(){const t=e.rows,l=Math.max(20,...e.rowContentFloors);o._resetBaseRowHeights(),e.height=Math.max(e.height,l*t),e.rowHeights.replace(R(t))},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<g?(l[t]=g,l[t+1]=r-g):s<g?(l[t+1]=g,l[t]=r-g):(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=e.contentFloors(t),i=n>0?s[t]/n:0,c=n>0?s[t+1]/n:0,d=Math.max(g,i),a=Math.max(g,c),u=l[t]+o,h=l[t+1]-o;u<d?(l[t]=d,l[t+1]=r-d):h<a?(l[t+1]=a,l[t]=r-a):(l[t]=u,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(t,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(t,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){o.setCellBorders(e,s,l)}}};return o}).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})}}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "3.16.0",
3
+ "version": "3.17.0",
4
4
  "description": "Design editor SDK: embed a Canva-like editor, generate designs from templates and data, export PNG, PDF, and video in the browser or on a server.",
5
5
  "author": "Anton Lavrenov",
6
6
  "repository": {
@@ -113,17 +113,17 @@
113
113
  },
114
114
  "dependencies": {
115
115
  "@base-ui/react": "^1.9.0",
116
- "@polotno/core": "0.16.0",
117
- "@polotno/html-export": "0.9.0",
116
+ "@polotno/core": "0.18.0",
117
+ "@polotno/html-export": "0.9.2",
118
118
  "@polotno/schema": "0.9.0",
119
- "@polotno/svg-export": "0.10.0",
119
+ "@polotno/svg-export": "0.10.2",
120
120
  "class-variance-authority": "^0.7.1",
121
121
  "clsx": "^2.1.1",
122
122
  "gifuct-js": "^2.1.2",
123
- "konva": "^10.8.0",
123
+ "konva": "^10.9.0",
124
124
  "lodash-es": "^4.18.1",
125
- "lucide-react": "^1.57.0",
126
- "mediabunny": "^1.61.4",
125
+ "lucide-react": "^1.59.0",
126
+ "mediabunny": "^1.61.6",
127
127
  "mobx": "7.0.6",
128
128
  "mobx-react-lite": "^5.1.0",
129
129
  "mobx-state-tree": "8.0.0",
@@ -132,7 +132,7 @@
132
132
  "react-konva": "18.2.16",
133
133
  "react-konva-utils": "^2.1.0",
134
134
  "react-sortablejs": "6.1.4",
135
- "react-window": "^2.3.4",
135
+ "react-window": "^2.4.1",
136
136
  "render-tag": "0.3.2",
137
137
  "sortablejs": "^1.15.7",
138
138
  "svg-round-corners": "^0.4.3",
@@ -181,8 +181,8 @@
181
181
  "@testing-library/react": "^16.3.3",
182
182
  "@types/react": "^19.3.0",
183
183
  "@vitejs/plugin-react": "^6.1.2",
184
- "@vitest/browser": "^5.0.4",
185
- "@vitest/browser-playwright": "^5.0.4",
184
+ "@vitest/browser": "^5.0.5",
185
+ "@vitest/browser-playwright": "^5.0.5",
186
186
  "assemblyscript": "^0.28.20",
187
187
  "assert": "^2.1.0",
188
188
  "bippy": "^0.7.3",
@@ -191,20 +191,20 @@
191
191
  "filehound": "^1.17.6",
192
192
  "glob": "^13.0.6",
193
193
  "jest-file-snapshot": "^0.7.0",
194
- "jsdom": "^30.1.2",
194
+ "jsdom": "^30.1.3",
195
195
  "playwright": "^1.64.1",
196
- "postcss": "^8.5.30",
196
+ "postcss": "^8.5.31",
197
197
  "postcss-selector-parser": "^7.1.6",
198
198
  "pptxgenjs": "^4.0.1",
199
199
  "process": "^0.11.10",
200
- "react": "^19.3.0",
201
- "react-dom": "^19.3.0",
200
+ "react": "^19.3.1",
201
+ "react-dom": "^19.3.1",
202
202
  "tailwindcss": "^4.3.3",
203
203
  "terser": "^5.51.2",
204
204
  "tw-animate-css": "^1.4.0",
205
205
  "typescript": "~6.0.3",
206
206
  "vite": "^8.3.4",
207
- "vitest": "^5.0.4"
207
+ "vitest": "^5.0.5"
208
208
  },
209
209
  "homepage": "https://polotno.com/",
210
210
  "scripts": {
@@ -1,10 +1,16 @@
1
1
  import React from 'react';
2
2
  import type { PageType } from '../ui-types.js';
3
- export declare const usePagePreview: ({ page, setPreview, groupRef, }: {
3
+ type PagePreviewOptions = {
4
+ page: PageType;
5
+ ref: React.RefObject<HTMLDivElement | null>;
6
+ };
7
+ type LegacyPagePreviewOptions = {
4
8
  page: PageType;
5
9
  setPreview: (src: string | null) => void;
6
10
  groupRef: React.RefObject<HTMLDivElement | null>;
7
- }) => void;
11
+ };
12
+ export declare function usePagePreview(options: PagePreviewOptions): string | null;
13
+ export declare function usePagePreview(options: LegacyPagePreviewOptions): void;
8
14
  export declare const PagePreview: (({ page, scale }: {
9
15
  page: PageType;
10
16
  scale: number;
@@ -17,3 +23,4 @@ export declare const PagePreview: (({ page, scale }: {
17
23
  scale: number;
18
24
  }) => React.JSX.Element;
19
25
  };
26
+ export {};
@@ -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 a}from"mobx-state-tree";import{PolotnoIcon as s}from"../icons/registry.js";import{flags as r}from"../utils/flags.js";import{t as l}from"../utils/l10n.js";import{deepEqual as c}from"../utils/deep-equal.js";import{DropdownMenu as d,DropdownMenuContent as p,DropdownMenuItem as u}from"../primitives/dropdown-menu.js";import{DRAG_SLOP_PX as g,isPrimaryDrag as m,usePointerDrag as h}from"../utils/pointer-drag.js";import{Spinner as f}from"./spinner.js";import{TrackHandleRight as v,TrackMenu as x,TrackMenuButton as P}from"./track-styles.js";let b=[],w=!1;const y=async()=>{var e;if(w||0===b.length){return}w=!0;const{page:t,setPreview:o}=b.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{w=!1}y()};export const usePagePreview=({page:e,setPreview:t,groupRef:n})=>{const s=o.useRef(!1);o.useEffect(()=>{const o=()=>{b.push({page:e,setPreview:e=>t(e)}),y()};let r=null,l=null,d=Date.now();const p=()=>{r&&clearTimeout(r),s.current&&(l||(l=setTimeout(()=>{Date.now()-d>=6e3&&(o(),d=Date.now(),l=null)},6e3)),r=setTimeout(()=>{o(),d=Date.now(),r=null,l&&(clearTimeout(l),l=null)},300))};let u=null;const g=a(e,e=>{c(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?(s.current=!0,p()):(r&&clearTimeout(r),l&&clearTimeout(l),s.current=!1)})},{threshold:.1});return n.current&&h.observe(n.current),()=>{h.disconnect(),r&&clearTimeout(r),l&&clearTimeout(l),g(),m(),b=b.filter(t=>t.page!==e)}},[n,e,t])};export const PagePreview=n(({page:n,scale:i})=>{const[a,c]=o.useState(null),b=n.store.activePage===n||n.store._selectedPagesIds.includes(n.id),w=o.useRef(null),y=n.store.pages.indexOf(n),j=60/n.computedHeight*n.computedWidth,k=r.animationsEnabled?n.duration*i:j,E=n.store.pages.length>1;o.useLayoutEffect(()=>{w.current&&(w.current.style.width=k+"px")},[y,k]),usePagePreview({page:n,setPreview:c,groupRef:w});const I=h();return t("div",{ref:w,style:{width:k+"px",marginRight:r.animationsEnabled?"0px":"10px",height:"60px",display:"flex",position:"relative",borderRadius:"15px",boxShadow:"0 1px 4px rgba(0, 0, 0, 0.18)"},className:"polotno-page-container pn:[&:hover_.polotno-track-menu]:pointer-events-auto pn:[&:hover_.polotno-track-menu]:opacity-100"+(b?" sortable-selected":""),children:[e("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:a?`url("${a}")`:"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),a=e.shiftKey;if(a&&i){const e=o.filter(e=>e!==n.id);t.selectPages(e)}else if(a&&!i){const e=o.concat([n.id]);t.selectPages(e)}else{t.selectPages([n.id])}},children:!a&&e(f,{})}),e("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:b?"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(v,{className:"pn:z-[2] pn:before:h-1/2",onPointerDown:e=>{if(!m(e)){return}const t=e.clientX,o=n.duration;I(e,{slopX:g,node:n,onMove:e=>{const a=(e.clientX-t)/i;n.set({duration:Math.max(1e3,o+a)})}})}}),b&&e(x,{className:"polotno-page-menu pn:top-[5px] pn:right-4 pn:translate-y-0",onClick:e=>{e.stopPropagation()},children:t(d,{children:[e(P,{}),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 a=new Set(i.map(e=>e.id)),s=t.pages.filter(e=>a.has(e.id)),r=s[s.length-1],l=s.map(e=>e.clone()),c=t.pages.indexOf(r);l.forEach((e,t)=>{e.setZIndex(c+1+t)}),t.selectPages(l.map(e=>e.id))},children:[e(s,{name:"action.duplicate",className:"pn:size-4"}),l("pagesTimeline.duplicatePage")]}),t(u,{onSelect:e=>{var t,o,i;e.preventDefault();const a=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"}),s=n.store.pages.indexOf(n);a.setZIndex(s+1)},children:[e(s,{name:"action.add",className:"pn:size-4"}),l("pagesTimeline.addPage")]}),E&&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(s,{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 c}from"../utils/deep-equal.js";import{warnOnceDeprecated as d}from"../utils/deprecation.js";import{DropdownMenu as p,DropdownMenuContent as u,DropdownMenuItem as g}from"../primitives/dropdown-menu.js";import{DRAG_SLOP_PX as m,isPrimaryDrag as f,usePointerDrag as h}from"../utils/pointer-drag.js";import{Spinner as v}from"./spinner.js";import{TrackHandleRight as x,TrackMenu as P,TrackMenuButton as b}from"./track-styles.js";let w=[],y=!1;const R=async()=>{var e;if(y||0===w.length){return}y=!0;const{page:t,setPreview:o}=w.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{y=!1}R()};export function usePagePreview(e){const[t,n]=o.useState(null),a=o.useRef(!1),r="groupRef"in e;r&&d("usePagePreview.setPreview","usePagePreview({ page, setPreview, groupRef }) is deprecated: pass { page, ref } and use the returned data URL instead (https://polotno.com/docs/utils)");const{page:l}=e,p=r?e.groupRef:e.ref,u=r?e.setPreview:n;return o.useEffect(()=>{const e=()=>{w.push({page:l,setPreview:u}),R()};let t=null,o=null,n=Date.now();const r=()=>{t&&clearTimeout(t),a.current&&(o||(o=setTimeout(()=>{Date.now()-n>=6e3&&(e(),n=Date.now(),o=null)},6e3)),t=setTimeout(()=>{e(),n=Date.now(),t=null,o&&(clearTimeout(o),o=null)},300))};let d=null;const g=s(l,e=>{c(d,e)||(r(),d=e)}),m=i(l,()=>l.children.some(e=>e._editModeEnabled),e=>{e||r()}),f=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?(a.current=!0,r()):(t&&clearTimeout(t),o&&clearTimeout(o),a.current=!1)})},{threshold:.1});return p.current&&f.observe(p.current),()=>{f.disconnect(),t&&clearTimeout(t),o&&clearTimeout(o),g(),m(),w=w.filter(e=>e.page!==l)}},[p,l,u]),t}export const PagePreview=n(({page:n,scale:i})=>{const s=n.store.activePage===n||n.store._selectedPagesIds.includes(n.id),c=o.useRef(null),d=n.store.pages.indexOf(n),w=60/n.computedHeight*n.computedWidth,y=r.animationsEnabled?n.duration*i:w,R=n.store.pages.length>1;o.useLayoutEffect(()=>{c.current&&(c.current.style.width=y+"px")},[d,y]);const j=usePagePreview({page:n,ref:c}),k=h();return t("div",{ref:c,style:{width:y+"px",marginRight:r.animationsEnabled?"0px":"10px",height:"60px",display:"flex",position:"relative",borderRadius:"15px",boxShadow:"0 1px 4px rgba(0, 0, 0, 0.18)"},className:"polotno-page-container pn:[&:hover_.polotno-track-menu]:pointer-events-auto pn:[&:hover_.polotno-track-menu]:opacity-100"+(s?" sortable-selected":""),children:[e("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:j?`url("${j}")`:"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:!j&&e(v,{})}),e("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:s?"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(x,{className:"pn:z-[2] pn:before:h-1/2",onPointerDown:e=>{if(!f(e)){return}const t=e.clientX,o=n.duration;k(e,{slopX:m,node:n,onMove:e=>{const s=(e.clientX-t)/i;n.set({duration:Math.max(1e3,o+s)})}})}}),s&&e(P,{className:"polotno-page-menu pn:top-[5px] pn:right-4 pn:translate-y-0",onClick:e=>{e.stopPropagation()},children:t(p,{children:[e(b,{}),t(u,{side:"top",className:"pn:whitespace-nowrap",children:[t(g,{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()),c=t.pages.indexOf(r);l.forEach((e,t)=>{e.setZIndex(c+1+t)}),t.selectPages(l.map(e=>e.id))},children:[e(a,{name:"action.duplicate",className:"pn:size-4"}),l("pagesTimeline.duplicatePage")]}),t(g,{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")]}),R&&t(g,{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")]})]})]})})]})});