polotno 4.6.0 → 4.8.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 (59) hide show
  1. package/LICENSE.md +22 -7
  2. package/README.md +1 -1
  3. package/blueprint/side-panel/text-panel.js +3 -3
  4. package/blueprint/toolbar/text-toolbar.js +2 -2
  5. package/blueprint.polotno.css +116 -116
  6. package/canvas/figure-element.js +1 -1
  7. package/canvas/gif-element.js +1 -1
  8. package/canvas/html-element.js +1 -1
  9. package/canvas/image-element.js +1 -1
  10. package/canvas/page.js +1 -1
  11. package/canvas/quill-font-formats.js +1 -1
  12. package/canvas/render-tag-element.js +1 -1
  13. package/canvas/rich-editor.d.ts +0 -4
  14. package/canvas/rich-editor.js +5 -2
  15. package/canvas/text-element.js +1 -1
  16. package/canvas/use-mediabunny-video.js +1 -1
  17. package/canvas/video-element.js +1 -1
  18. package/model/group-model.d.ts +2 -12
  19. package/model/image-model.js +1 -1
  20. package/model/page-model.d.ts +2 -12
  21. package/model/store.d.ts +18 -108
  22. package/model/store.js +1 -1
  23. package/model/table-model.d.ts +2 -12
  24. package/model/table-model.js +1 -1
  25. package/model/text-model.js +1 -1
  26. package/package.json +28 -28
  27. package/pages-timeline/audio-track.js +1 -1
  28. package/pages-timeline/current-time.js +1 -1
  29. package/pages-timeline/element-track.js +1 -1
  30. package/pages-timeline/page-preview.js +1 -1
  31. package/pages-timeline/pages-timeline.js +1 -1
  32. package/pages-timeline/pages.js +1 -1
  33. package/pages-timeline/play-button.js +1 -1
  34. package/pages-timeline/time-ruler.js +1 -1
  35. package/pages-timeline/track-styles.js +1 -1
  36. package/polotno.bundle.js +171 -168
  37. package/primitives/select.d.ts +1 -1
  38. package/side-panel/images-grid.d.ts +2 -1
  39. package/side-panel/images-grid.js +1 -1
  40. package/side-panel/select-svg.js +1 -1
  41. package/side-panel/text-panel.js +1 -1
  42. package/side-panel/text-template.d.ts +12 -0
  43. package/side-panel/text-template.js +1 -0
  44. package/toolbar/text-toolbar.js +1 -1
  45. package/toolbar/video-toolbar.js +1 -1
  46. package/ui.css +2 -2
  47. package/utils/font-metric.js +1 -1
  48. package/utils/fonts.js +1 -1
  49. package/utils/html-to-svg/font-inliner.js +1 -1
  50. package/utils/html2canvas.js +1 -1
  51. package/utils/measure-text.js +1 -1
  52. package/utils/pointer-drag.d.ts +13 -0
  53. package/utils/pointer-drag.js +1 -0
  54. package/utils/px.d.ts +2 -0
  55. package/utils/px.js +1 -1
  56. package/utils/rich-text-html.js +1 -1
  57. package/utils/text-format-state.js +1 -1
  58. package/utils/text-format.js +1 -1
  59. package/utils/validate-key.js +1 -1
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{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as I}from"../utils/canvas.js";import{whenLoaded as T}from"../utils/loader.js";import{polotnoError as _}from"@polotno/core/errors";import{pxToUnit as O}from"../utils/unit.js";import{deepEqual as S}from"../utils/deep-equal.js";import{waitTillAvailable as k}from"../utils/wait.js";import{jsonToHTML as j}from"@polotno/html-export";import{jsonToSVG as R}from"@polotno/svg-export";import{warnOnceDeprecated as F}from"../utils/deprecation.js";import{Page as A}from"./page-model.js";import{forEveryChild as V,forEveryNode as C}from"./group-model.js";import{Audio as L}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(A),fonts:l.array(Font),audios:l.array(L),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return C({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return V({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let o;return C({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=A.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:i,type:"group"},t);return a.children.push(l),r.selectedElementsIds=o([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(o,1)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!S(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 _("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;p>r._elementsPixelRatio&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const h=await k(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!h){throw null==g||g.set({_forceMount:!1,_exporting:!1}),f.setElementsPixelRatio(u),_("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})}h.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 v=h[0];await f.waitLoading({_skipTimeout:a});const b=v.findOne(".page-container");if(!b){throw f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),_("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const y=v.position();v.position({x:0,y:0}),v.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=b.findOne(".elements-container"),E=x.clip();x.clip({x:null,y:null,width:null,height:null});const T=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));T.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const S=n?g.computedBleed:m;let j=S.left,R=S.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+S.left+S.right,A=g.computedHeight+S.top+S.bottom,V=b.scale();b.scale({x:1,y:1});const C=I(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===i){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),T.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),v.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),x.clip(E),v.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),f.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>O({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:i,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let w=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw _("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,o=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),i=r.pages.filter(e=>o.includes(e.id));if(!i.length){throw _("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=i[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of i){const e=Math.max(1,Math.floor(l.duration/s));for(let o=0;o<e;o++){const e=l.startTime+o*s||1;f.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const i=await f._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(i.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return f.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){F("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return j(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;F("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 R(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:o})},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await T()},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,s;const l="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,d="boolean"!=typeof o&&null!==(n=null==o?void 0:o.modernizeTextBackground)&&void 0!==n&&n,p=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:d});delete p.schemaVersion;const c=r.activePage?r.pages.indexOf(r.activePage):0;let g=null===(s=p.pages[c]||p.pages[0])||void 0===s?void 0:s.id;p._activePageId=g,p._selectedPagesIds=[];const m=Object.assign({},a(r));Object.assign(m,p),m.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,m)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){f.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e))},addAudio(e){const t=L.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as I}from"../utils/canvas.js";import{whenLoaded as T}from"../utils/loader.js";import{polotnoError as _}from"@polotno/core/errors";import{pxToUnit as O}from"../utils/unit.js";import{deepEqual as S}from"../utils/deep-equal.js";import{waitTillAvailable as k}from"../utils/wait.js";import{jsonToHTML as j}from"@polotno/html-export";import{jsonToSVG as R}from"@polotno/svg-export";import{warnOnceDeprecated as F}from"../utils/deprecation.js";import{Page as A}from"./page-model.js";import{forEveryChild as V,forEveryNode as C}from"./group-model.js";import{Audio as L}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(A),fonts:l.array(Font),audios:l.array(L),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return C({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return V({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let o;return C({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=A.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:i,type:"group"},t);return a.children.push(l),r.selectedElementsIds=o([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(o,1)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!S(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 _("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;p>r._elementsPixelRatio&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const h=await k(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!h){throw null==g||g.set({_forceMount:!1,_exporting:!1}),f.setElementsPixelRatio(u),_("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})}h.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 v=h[0];await f.waitLoading({_skipTimeout:a});const b=v.findOne(".page-container");if(!b){throw f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),_("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const y=v.position();v.position({x:0,y:0}),v.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=b.findOne(".elements-container"),E=x.clip();x.clip({x:null,y:null,width:null,height:null});const T=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));T.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const S=n?g.computedBleed:m;let j=S.left,R=S.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+S.left+S.right,A=g.computedHeight+S.top+S.bottom,V=b.scale();b.scale({x:1,y:1});const C=I(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===i){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),T.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),v.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),x.clip(E),v.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),f.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>O({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:i,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let w=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw _("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,o=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),i=r.pages.filter(e=>o.includes(e.id));if(!i.length){throw _("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=i[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of i){const e=Math.max(1,Math.floor(l.duration/s));for(let o=0;o<e;o++){const e=l.startTime+o*s||1;f.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const i=await f._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(i.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return f.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){F("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return j(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;F("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 R(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:o})},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await T()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,l="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[];const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){f.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e))},addAudio(e){const t=L.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
@@ -471,6 +471,7 @@ export declare const TableElement: import("mobx-state-tree").IModelType<{
471
471
  height: number;
472
472
  } | null;
473
473
  } & {
474
+ set(attrs: any): void;
474
475
  setCellContentHeight(cellId: string, height: number): void;
475
476
  _applyFitRowsToContent(): void;
476
477
  focusCell(cellId: string, addToSelection?: boolean): void;
@@ -500,16 +501,5 @@ export declare const TableElement: import("mobx-state-tree").IModelType<{
500
501
  clone(attrs?: any, { skipSelect }?: {
501
502
  skipSelect?: boolean | undefined;
502
503
  }): any;
503
- }, import("mobx-state-tree").ModelCreationType<{
504
- id: string;
505
- type: string | undefined;
506
- name: string | undefined;
507
- opacity: number | undefined;
508
- custom: any;
509
- visible: boolean | undefined;
510
- selectable: boolean | undefined;
511
- removable: boolean | undefined;
512
- alwaysOnTop: boolean | undefined;
513
- showInExport: boolean | undefined;
514
- }>, any>;
504
+ }, any, any>;
515
505
  export type TableElementType = Instance<typeof TableElement>;
@@ -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{TABLE_CELL_OVERRIDABLE_KEYS as c}from"@polotno/schema/defaults";import{Shape as d}from"./shape-model.js";const a=.05,g=e.enumeration(["solid","dashed","dotted","none"]);function h(e){return t(e,2)}function u(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?h(e)[t]:o}function f(e){return t(e,1)}const b=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(g)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),w=e.model("CellBorders",{top:e.maybe(b),right:e.maybe(b),bottom:e.maybe(b),left:e.maybe(b)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),m=c,p=new Set(m),C=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],_=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],y=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),v={opacity:1,rowSpan:1,colSpan:1,name:""},I=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(w),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of _){o in e&&(t[o]=e[o])}for(const o of m){void 0!==e[o]&&(t[`_${o}`]=e[o])}return t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in v&&l===v[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=h(e),o=f(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=h(e),o=f(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return h(e).page}catch(t){return null}},get fontSize(){return u(e,"fontSize",30)},get fontFamily(){return u(e,"fontFamily","Roboto")},get fontWeight(){return u(e,"fontWeight","normal")},get fontStyle(){return u(e,"fontStyle","normal")},get textDecoration(){return u(e,"textDecoration","")},get textTransform(){return u(e,"textTransform","none")},get fill(){return u(e,"fill","black")},get align(){return u(e,"align","left")},get verticalAlign(){return u(e,"verticalAlign","top")},get lineHeight(){return u(e,"lineHeight",1.2)},get letterSpacing(){return u(e,"letterSpacing",0)},get strokeWidth(){return u(e,"strokeWidth",0)},get stroke(){return u(e,"stroke","black")},get cellBackground(){return u(e,"cellBackground","transparent")},get cellPadding(){return u(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get borderInsets(){if(!l(e)){return{top:0,right:0,bottom:0,left:0}}const o=h(e),r=(e,o)=>{const l=t.getEffectiveBorder(e);return"none"===l.style||0===l.width?0:o?l.width:l.width/2};return{top:r("top",0===t.row),bottom:r("bottom",t.row+e.rowSpan===o.rows),left:r("left",0===t.col),right:r("right",t.col+e.colSpan===o.cols)}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=h(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,{top:s,right:i,bottom:c,left:d}=t.borderInsets;return{x:r.x+d+n,y:r.y+s+n,width:Math.max(0,r.width-d-i-2*n),height:Math.max(0,r.height-s-c-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?h(e):null,g=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==g?void 0:g.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==g?void 0:g.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==g?void 0:g.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return I}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&t.fontSize<1&&(t=Object.assign(Object.assign({},t),{fontSize:1}));const o={};for(const[e,l]of Object.entries(t)){p.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:y.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}));function H(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of m){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function R(e){return Array.from({length:e},()=>1/e)}function S(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?R(e.length):e.map(e=>e/t)}export const TableElement=d.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){p.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of C){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(R(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(R(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},getRowContentOuterHeight(o){let l=0;for(let r=0;r<e.cols;r++){const n=t.getCell(o,r);if(!n){continue}const s=e._cellContentHeights.get(n.id);if(void 0===s){continue}const i=n.borderInsets,c=s+2*n.cellPadding+i.top+i.bottom;c>l&&(l=c)}return l},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}let l=0;for(let r=0;r<e.rows;r++){l+=t.getRowContentOuterHeight(r)}return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){var o,l;if(0===e._cellContentHeights.size){return null}const r=null!==(o=e._baseHeight)&&void 0!==o?o:e.height,n=null!==(l=e._baseRowHeights)&&void 0!==l?l:[...e.rowHeights];let s=!1;const i=[];for(let d=0;d<e.rows;d++){const o=e.rowHeights[d]*e.height,l=n[d]*r,c=t.getRowContentOuterHeight(d),a=Math.max(c,l);Math.abs(a-o)>1?(i.push(a),s=!0):i.push(o)}if(!s){return null}const c=i.reduce((e,t)=>e+t,0);return{rowHeights:i.map(e=>e/c),height:c}}};return t}).actions(e=>{const t={setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){if(!l(e)){return}null===e._baseRowHeights&&(e._baseRowHeights=[...e.rowHeights],e._baseHeight=e.height);const t=e._fitRowsToContent;t&&(e.height=t.height,e.rowHeights.replace(t.rowHeights))},focusCell(t,o=!1){o?e._focusedCellIds.includes(t)||(e._focusedCellIds=[...e._focusedCellIds,t]):(e._focusedCellIds=[t],e._anchorCellId=t)},selectRowRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.rows-1,Math.max(t,o)),n=[];for(let s=l;s<=r;s++){for(let t=0;t<e.cols;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectColumnRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.cols-1,Math.max(t,o)),n=[];for(let s=0;s<e.rows;s++){for(let t=l;t<=r;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectRow(e){t.selectRowRange(e,e)},selectColumn(e){t.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=[],n=[];let s=0;for(let h=0;h<o;h++){r.push(e.rowHeights[h]*l);const t=e.getRowContentOuterHeight(h);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(o){t._resetBaseRowHeights();const l=o>0?o-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let t=0;t<e.rows;t++){s.push(e.rowHeights[t]*e.height/n)}s.splice(o,0,r/n);const i=o>0?o-1:0,c=[];for(let t=0;t<e.cols;t++){c.push(e.cells[i*e.cols+t])}const d=o*e.cols,a=H(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(S(s))},removeRow(o){if(e.rows<=1){return}t._resetBaseRowHeights();const l=o*e.cols,r=[];for(let t=l;t<l+e.cols;t++){r.push(e.cells[t].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(o,1),e.rows-=1,e.rowHeights.replace(S(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=H(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(S(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(S(r))},removeRowRange(o,l){for(let r=l;r>=o&&!(e.rows<=1);r--){t.removeRow(r)}},removeColumnRange(o,l){for(let r=l;r>=o&&!(e.cols<=1);r--){t.removeColumn(r)}},distributeRowsEvenly(){const o=e.rows;let l=20;for(let t=0;t<o;t++){l=Math.max(l,e.getRowContentOuterHeight(t))}t._resetBaseRowHeights(),e.height=Math.max(e.height,l*o),e.rowHeights.replace(R(o))},distributeColumnsEvenly(){e.colWidths.replace(R(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<a?(l[t]=a,l[t+1]=r-a):s<a?(l[t+1]=a,l[t]=r-a):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=n>0?e.getRowContentOuterHeight(t)/n:0,i=n>0?e.getRowContentOuterHeight(t+1)/n:0,c=Math.max(a,s),d=Math.max(a,i),g=l[t]+o,h=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):h<d?(l[t+1]=d,l[t]=r-d):(l[t]=g,l[t+1]=h),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(o,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,h="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(h){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||h){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(o,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){t.setCellBorders(e,s,l)}}};return t}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
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){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 +1 @@
1
- import{types as e}from"mobx-state-tree";import{hasMeasuredHeight as t,parseNumericLineHeight as o}from"@polotno/core/text-types";import{Shape as n}from"./shape-model.js";const i=e=>{var t;return"string"!=typeof e?e:null!==(t=o(e))&&void 0!==t?t:e};export const TextElement=n.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",strokeLineJoin:"round",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5,legacyBackground:e.maybe(e.boolean),curveEnabled:!1,curvePower:.5}).preProcessSnapshot(e=>{const o=Object.assign(Object.assign({},e),{fontSize:null!=e.fontSize&&e.fontSize<1?1:e.fontSize,lineHeight:i(e.lineHeight)});return t(o)||delete o.height,o}).actions(e=>{const t=e.set;return{set(e){null!=e.fontSize&&e.fontSize<1&&(e=Object.assign(Object.assign({},e),{fontSize:1})),"string"==typeof e.lineHeight&&(e=Object.assign(Object.assign({},e),{lineHeight:i(e.lineHeight)})),t(e)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}});
1
+ import{types as e}from"mobx-state-tree";import{clampFontSize as t}from"@polotno/schema/defaults";import{hasMeasuredHeight as o,parseNumericLineHeight as n}from"@polotno/core/text-types";import{Shape as i}from"./shape-model.js";const r=e=>{var t;return"string"!=typeof e?e:null!==(t=n(e))&&void 0!==t?t:e};export const TextElement=i.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",strokeLineJoin:"round",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5,legacyBackground:e.maybe(e.boolean),curveEnabled:!1,curvePower:.5}).preProcessSnapshot(e=>{const n=Object.assign(Object.assign({},e),{fontSize:t(e.fontSize),lineHeight:r(e.lineHeight)});return o(n)||delete n.height,n}).actions(e=>{const o=e.set;return{set(e){null!=e.fontSize&&(e=Object.assign(Object.assign({},e),{fontSize:t(e.fontSize)})),"string"==typeof e.lineHeight&&(e=Object.assign(Object.assign({},e),{lineHeight:r(e.lineHeight)})),o(e)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())},beforeDestroy(){e._editModeEnabled&&e.store.history.endTransaction()}}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "4.6.0",
3
+ "version": "4.8.0",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
@@ -95,31 +95,31 @@
95
95
  "./polotno.blueprint.css": "./blueprint.polotno.css"
96
96
  },
97
97
  "dependencies": {
98
- "@base-ui/react": "^1.6.0",
99
- "@polotno/core": "0.4.0",
100
- "@polotno/html-export": "0.2.0",
101
- "@polotno/schema": "0.4.0",
102
- "@polotno/svg-export": "0.2.0",
98
+ "@base-ui/react": "^1.7.0",
99
+ "@polotno/core": "0.6.0",
100
+ "@polotno/html-export": "0.3.1",
101
+ "@polotno/schema": "0.6.0",
102
+ "@polotno/svg-export": "0.3.1",
103
103
  "class-variance-authority": "^0.7.1",
104
104
  "clsx": "^2.1.1",
105
105
  "gifuct-js": "^2.1.2",
106
106
  "konva": "^10.3.0",
107
107
  "lodash-es": "^4.18.1",
108
- "lucide-react": "^1.23.0",
109
- "mediabunny": "^1.50.8",
108
+ "lucide-react": "^1.29.0",
109
+ "mediabunny": "^1.52.3",
110
110
  "mobx": "6.16.1",
111
111
  "mobx-react-lite": "^4.1.1",
112
- "mobx-state-tree": "7.3.1",
113
- "nanoid": "^6.0.0",
112
+ "mobx-state-tree": "7.3.2",
113
+ "nanoid": "^6.0.1",
114
114
  "quill": "^2.0.3",
115
115
  "react-konva": "^19.2.5",
116
116
  "react-konva-utils": "^2.0.0",
117
117
  "react-sortablejs": "6.1.4",
118
- "react-window": "^2.2.7",
119
- "render-tag": "^0.1.26",
118
+ "react-window": "^2.3.0",
119
+ "render-tag": "^0.1.29",
120
120
  "sortablejs": "^1.15.7",
121
121
  "svg-round-corners": "^0.4.3",
122
- "swr": "^2.4.2",
122
+ "swr": "^2.5.0",
123
123
  "tailwind-merge": "^3.6.0",
124
124
  "tinycolor2": "^1.6.0",
125
125
  "use-image": "^1.1.4"
@@ -157,39 +157,39 @@
157
157
  "@babel/core": "^8.0.1",
158
158
  "@babel/parser": "^8.0.4",
159
159
  "@babel/traverse": "^8.0.4",
160
- "@blueprintjs/core": "6.17.2",
160
+ "@blueprintjs/core": "6.18.0",
161
161
  "@blueprintjs/icons": "^6.13.0",
162
- "@blueprintjs/select": "6.3.3",
162
+ "@blueprintjs/select": "6.3.4",
163
163
  "@canvas/image": "^2.0.0",
164
- "@tailwindcss/cli": "^4.3.2",
165
- "@tailwindcss/vite": "^4.3.2",
164
+ "@tailwindcss/cli": "^4.3.3",
165
+ "@tailwindcss/vite": "^4.3.3",
166
166
  "@testing-library/dom": "^10.4.1",
167
167
  "@testing-library/react": "^16.3.2",
168
- "@types/react": "^19.2.17",
169
- "@vitejs/plugin-react": "^6.0.3",
168
+ "@types/react": "^19.2.18",
169
+ "@vitejs/plugin-react": "^6.0.5",
170
170
  "@vitest/browser": "^4.1.10",
171
171
  "@vitest/browser-playwright": "^4.1.10",
172
172
  "assert": "^2.1.0",
173
- "bippy": "^0.5.43",
173
+ "bippy": "^0.6.1",
174
174
  "buffer": "^6.0.3",
175
175
  "canvas": "^3.2.3",
176
176
  "filehound": "^1.17.6",
177
177
  "glob": "^13.0.6",
178
178
  "jest-file-snapshot": "^0.7.0",
179
- "jsdom": "^29.1.1",
179
+ "jsdom": "^30.0.1",
180
180
  "license-checker": "^25.0.1",
181
- "playwright": "^1.61.1",
182
- "postcss": "^8.5.19",
181
+ "playwright": "^1.62.1",
182
+ "postcss": "^8.5.26",
183
183
  "postcss-selector-parser": "^7.1.4",
184
184
  "pptxgenjs": "^4.0.1",
185
185
  "process": "^0.11.10",
186
- "react": "^19.2.7",
187
- "react-dom": "^19.2.7",
188
- "tailwindcss": "^4.3.2",
189
- "terser": "^5.48.0",
186
+ "react": "^19.2.8",
187
+ "react-dom": "^19.2.8",
188
+ "tailwindcss": "^4.3.3",
189
+ "terser": "^5.49.2",
190
190
  "tw-animate-css": "^1.4.0",
191
191
  "typescript": "~6.0.3",
192
- "vite": "^8.1.4",
192
+ "vite": "^8.2.1",
193
193
  "vitest": "^4.1.10"
194
194
  },
195
195
  "homepage": "https://polotno.com/",
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var n={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++){t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}}return n};import{jsx as t,jsxs as n}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as a}from"../icons/registry.js";import{t as s}from"../utils/l10n.js";import{firstSliderValue as r}from"../lib/utils.js";import{DropdownMenu as l,DropdownMenuContent as m,DropdownMenuItem as d,DropdownMenuSeparator as p}from"../primitives/dropdown-menu.js";import{Slider as c}from"../primitives/slider.js";import{SpeedControl as u}from"../primitives/speed-control.js";import{Spinner as h}from"./spinner.js";import{useWaveformData as v,useWaveformPath as f}from"./waveform.js";import{TrackWrapper as x,TrackContainer as y,TrackMenu as g,TrackMenuButton as M,TrackHandleLeft as T,TrackHandleRight as w,TrackInlineLabel as b,TrackNameInput as j,WaveformSvg as I}from"./track-styles.js";export const AUDIO_ROW_HEIGHT=28;export const AUDIO_TRACK_HEIGHT=24;const D=({position:e,store:t,scale:n})=>{const i=t.pages;for(const o of i){const t=o.startTime,i=o.startTime+o.duration;if(Math.abs(e-t)<10/n){return t}if(Math.abs(e-i)<10/n){return i}}return null};export const AudioTrack=o(({audio:o,scale:O,store:E,label:S,row:A})=>{const[C,L]=i.useState(1),N=i.useRef(null),[P,_]=i.useState(!1),z=0===o.volume,X=()=>{z?o.set({volume:C>0?C:1}):(L(o.volume),o.set({volume:0}))},k=(e=o.startTime,t=o.endTime,n=o.speed)=>Math.max(0,(t-e)*(o.duration||0)/n),H=e=>Math.max(0,E.duration-e),R=(e,t=k())=>Math.min(Math.max(0,e),H(t)),$=k(),B=E.duration*O-o.delay*O,V=Math.min($*O,B),Y=o.delay*O,{data:F,isLoading:G}=v(o.src),U=o.visibleDuration*O,J=f(F,20).path,K=(e,t)=>{e.stopPropagation(),e.preventDefault();const n=e.clientX,i=Y,a=V,s=o.endTime,r=o.startTime,l=o.delay,m=o.duration||1,d=o.speed,p=e=>{e.preventDefault();const p=(e.clientX-n)/O;if("start"===t){if(p>=0){const e=p*d,t=Math.max(0,s-.1-r)*m,n=Math.min(e,t);if(n<=0){return}let i=r+n/m;const a=(o.endTime-i)*m/d,c=l+n/d,u=H(a);let h=Math.min(Math.max(0,c),u);const v=D({position:h,store:E,scale:O});h=Math.min(Math.max(0,null!=v?v:h),u);const f=h-c;i=Math.min(o.endTime-.1,Math.max(0,i+f*d/m)),o.set({delay:h,startTime:i})}else{const e=-p*d,t=r*m,n=Math.min(e,t);if(n<=0){return}const i=n/m;let a=Math.max(0,r-i);const s=(o.endTime-a)*m/d,c=l-n/d,u=H(s);let h=Math.min(Math.max(0,c),u);const v=D({position:h,store:E,scale:O});h=Math.min(Math.max(0,null!=v?v:h),u);const f=h-c;a=Math.max(0,Math.min(o.endTime-.1,a+f*d/m)),o.set({delay:h,startTime:a})}}else{const e=i/O+a/O;let t=e+p;const n=D({position:t,store:E,scale:O});t=null!=n?n:t;const r=(t-e)*d/o.duration,l=Math.min(1,Math.max(o.startTime+.1,s+r));o.set({endTime:l})}},c=()=>{if(window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",c),"start"===t){const e=D({position:o.delay,store:E,scale:O});if(null!=e&&e!==o.delay){const t=k(o.startTime,o.endTime),n=R(e,t),i=n-o.delay,a=Math.max(0,Math.min(o.endTime-.1,o.startTime+i*d/m));o.set({delay:n,startTime:a})}}};window.addEventListener("mousemove",p),window.addEventListener("mouseup",c)};return t(x,{ref:N,style:{left:`${Y}px`,top:28*A+"px",width:`${V}px`,height:"24px"},className:"polotno-audio-container",children:n(y,{style:{width:"100%",height:"100%"},onMouseDown:e=>{const t=e.clientX,n=Y;e.preventDefault();const i=e=>{e.preventDefault();const i=(e.clientX-t)/O;let a=n/O+i;const s=a+$,r=D({position:a,store:E,scale:O}),l=D({position:s,store:E,scale:O}),m=null!==r?Math.abs(a-r):Number.POSITIVE_INFINITY,d=null!==l?Math.abs(s-l):Number.POSITIVE_INFINITY;let p;p=R(null!==r&&m<d?r:null!==l?l-$:a),o.set({delay:R(p)})},a=()=>{window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",a)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",a)},children:[t("div",{style:{position:"absolute",left:"4px",top:"50%",transform:"translateY(-50%)",zIndex:10,pointerEvents:"auto"},onClick:e=>{e.stopPropagation(),X()},onMouseDown:e=>e.stopPropagation(),children:t(a,z?{name:"action.muted",className:"pn:size-3.5",style:{opacity:.7,cursor:"pointer"}}:{name:"action.unmuted",className:"pn:size-3.5",style:{opacity:.7,cursor:"pointer"}})}),t("div",{style:{position:"absolute",inset:"0 0 0 0",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:n("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%",gap:"8px",paddingLeft:"22px"},children:[!P&&t(b,{children:S}),J&&t("div",{style:{flex:1,height:"14px",overflow:"hidden",opacity:z?.4:1},children:t(I,{width:U,height:"14",viewBox:`0 0 ${U} 20`,preserveAspectRatio:"none",style:{width:U+"px",height:"14px",transform:`translateX(-${o.startTime*U}px)`},children:t("path",{d:J})})}),G&&t("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:t(h,{})})]})}),P&&t(j,{value:o.name,onCommit:e=>{o.set({name:e}),_(!1)},onCancel:()=>_(!1)}),t(T,{onMouseDown:e=>K(e,"start")}),t(w,{onMouseDown:e=>K(e,"end")}),t(g,{onClick:e=>{e.stopPropagation()},onMouseDown:e=>e.stopPropagation(),children:n(l,{children:[t(M,{}),n(m,{side:"top",align:"start",anchor:N,style:{width:"220px"},children:[n("div",{style:{padding:"8px 12px"},children:[n("div",{style:{fontSize:"12px",marginBottom:"6px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t("span",{children:s("pagesTimeline.volume")}),n("span",{children:[Math.round(100*o.volume),"%"]})]}),t(c,{value:[o.volume],min:0,max:1,step:.01,onValueChange:e=>(e=>{const t=Math.max(0,Math.min(1,e));t>0&&L(t),o.set({volume:t})})(r(e))})]}),n("div",{style:{padding:"8px 12px"},children:[t("div",{style:{fontSize:"12px",marginBottom:"6px"},children:s("pagesTimeline.speed")}),t(u,{value:o.speed,onChange:e=>{const t=k(o.startTime,o.endTime,e);o.set({speed:e,delay:R(o.delay,t)})}})]}),t(p,{}),n(d,{onSelect:e=>{e.preventDefault(),_(!0)},children:[t(a,{name:"action.rename"}),s("pagesTimeline.renameAudio")]}),n(d,{onSelect:e=>{e.preventDefault(),X()},children:[t(a,z?{name:"action.unmuted"}:{name:"action.muted"}),s(z?"pagesTimeline.unmuteAudio":"pagesTimeline.muteAudio")]}),n(d,{onSelect:t=>{t.preventDefault(),(()=>{const t=o.toJSON(),n=o.visibleDuration,i=o.delay+n,a=E.duration-i;let s=o.delay;a>=n?s=i:a>0&&(s=Math.max(0,E.duration-n));const{id:r}=t,l=e(t,["id"]);E.addAudio(Object.assign(Object.assign({},l),{delay:s}))})()},children:[t(a,{name:"action.duplicate"}),s("pagesTimeline.duplicateAudio")]}),t(p,{}),n(d,{onSelect:e=>{e.preventDefault(),E.removeAudio(o.id)},children:[t(a,{name:"action.remove"}),s("pagesTimeline.removeAudio")]})]})]})})]})})});
1
+ var e=this&&this.__rest||function(e,t){var n={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++){t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}}return n};import{jsx as t,jsxs as n}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as a}from"../icons/registry.js";import{t as s}from"../utils/l10n.js";import{firstSliderValue as r}from"../lib/utils.js";import{DRAG_SLOP_PX as l,isPrimaryDrag as m,startPointerDrag as d}from"../utils/pointer-drag.js";import{DropdownMenu as p,DropdownMenuContent as c,DropdownMenuItem as u,DropdownMenuSeparator as h}from"../primitives/dropdown-menu.js";import{Slider as f}from"../primitives/slider.js";import{SpeedControl as x}from"../primitives/speed-control.js";import{Spinner as y}from"./spinner.js";import{useWaveformData as v,useWaveformPath as g}from"./waveform.js";import{TrackWrapper as T,TrackContainer as M,TrackMenu as b,TrackMenuButton as j,TrackHandleLeft as w,TrackHandleRight as I,TrackInlineLabel as O,TrackNameInput as P,WaveformSvg as D}from"./track-styles.js";export const AUDIO_ROW_HEIGHT=28;export const AUDIO_TRACK_HEIGHT=24;const S=({position:e,store:t,scale:n})=>{const i=t.pages;for(const o of i){const t=o.startTime,i=o.startTime+o.duration;if(Math.abs(e-t)<10/n){return t}if(Math.abs(e-i)<10/n){return i}}return null};export const AudioTrack=o(({audio:o,scale:A,store:C,label:N,row:E})=>{const[_,X]=i.useState(1),z=i.useRef(null),[k,H]=i.useState(!1),R=0===o.volume,$=()=>{R?o.set({volume:_>0?_:1}):(X(o.volume),o.set({volume:0}))},B=(e=o.startTime,t=o.endTime,n=o.speed)=>Math.max(0,(t-e)*(o.duration||0)/n),V=e=>Math.max(0,C.duration-e),Y=(e,t=B())=>Math.min(Math.max(0,e),V(t)),F=B(),G=C.duration*A-o.delay*A,L=Math.min(F*A,G),U=o.delay*A,{data:J,isLoading:K}=v(o.src),W=o.visibleDuration*A,q=g(J,20).path,Q=(e,t)=>{if(!m(e)){return}e.stopPropagation();const n=e.clientX,i=U,a=L,s=o.endTime,r=o.startTime,p=o.delay,c=o.duration||1,u=o.speed;d(e,{slopX:l,onMove:e=>{const l=(e.clientX-n)/A;if("start"===t){if(l>=0){const e=l*u,t=Math.max(0,s-.1-r)*c,n=Math.min(e,t);if(n<=0){return}let i=r+n/c;const a=(o.endTime-i)*c/u,m=p+n/u,d=V(a);let h=Math.min(Math.max(0,m),d);const f=S({position:h,store:C,scale:A});h=Math.min(Math.max(0,null!=f?f:h),d);const x=h-m;i=Math.min(o.endTime-.1,Math.max(0,i+x*u/c)),o.set({delay:h,startTime:i})}else{const e=-l*u,t=r*c,n=Math.min(e,t);if(n<=0){return}const i=n/c;let a=Math.max(0,r-i);const s=(o.endTime-a)*c/u,m=p-n/u,d=V(s);let h=Math.min(Math.max(0,m),d);const f=S({position:h,store:C,scale:A});h=Math.min(Math.max(0,null!=f?f:h),d);const x=h-m;a=Math.max(0,Math.min(o.endTime-.1,a+x*u/c)),o.set({delay:h,startTime:a})}}else{const e=i/A+a/A;let t=e+l;const n=S({position:t,store:C,scale:A});t=null!=n?n:t;const r=(t-e)*u/o.duration,m=Math.min(1,Math.max(o.startTime+.1,s+r));o.set({endTime:m})}},onEnd:({moved:e})=>{e&&(()=>{if("start"===t){const e=S({position:o.delay,store:C,scale:A});if(null!=e&&e!==o.delay){const t=B(o.startTime,o.endTime),n=Y(e,t),i=n-o.delay,a=Math.max(0,Math.min(o.endTime-.1,o.startTime+i*u/c));o.set({delay:n,startTime:a})}}})()}})};return t(T,{ref:z,style:{left:`${U}px`,top:28*E+"px",width:`${L}px`,height:"24px"},className:"polotno-audio-container",children:n(M,{style:{width:"100%",height:"100%"},onPointerDown:e=>{if(!m(e)){return}const t=e.clientX,n=U;d(e,{slopX:l,onMove:e=>{const i=(e.clientX-t)/A;let a=n/A+i;const s=a+F,r=S({position:a,store:C,scale:A}),l=S({position:s,store:C,scale:A}),m=null!==r?Math.abs(a-r):Number.POSITIVE_INFINITY,d=null!==l?Math.abs(s-l):Number.POSITIVE_INFINITY;let p;p=Y(null!==r&&m<d?r:null!==l?l-F:a),o.set({delay:Y(p)})}})},children:[t("div",{style:{position:"absolute",left:"4px",top:"50%",transform:"translateY(-50%)",zIndex:10,pointerEvents:"auto"},onClick:e=>{e.stopPropagation(),$()},onPointerDown:e=>e.stopPropagation(),children:t(a,R?{name:"action.muted",className:"pn:size-3.5",style:{opacity:.7,cursor:"pointer"}}:{name:"action.unmuted",className:"pn:size-3.5",style:{opacity:.7,cursor:"pointer"}})}),t("div",{style:{position:"absolute",inset:"0 0 0 0",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:n("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%",gap:"8px",paddingLeft:"22px"},children:[!k&&t(O,{children:N}),q&&t("div",{style:{flex:1,height:"14px",overflow:"hidden",opacity:R?.4:1},children:t(D,{width:W,height:"14",viewBox:`0 0 ${W} 20`,preserveAspectRatio:"none",style:{width:W+"px",height:"14px",transform:`translateX(-${o.startTime*W}px)`},children:t("path",{d:q})})}),K&&t("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:t(y,{})})]})}),k&&t(P,{value:o.name,onCommit:e=>{o.set({name:e}),H(!1)},onCancel:()=>H(!1)}),t(w,{onPointerDown:e=>Q(e,"start")}),t(I,{onPointerDown:e=>Q(e,"end")}),t(b,{onClick:e=>{e.stopPropagation()},onPointerDown:e=>e.stopPropagation(),children:n(p,{children:[t(j,{}),n(c,{side:"top",align:"start",anchor:z,style:{width:"220px"},children:[n("div",{style:{padding:"8px 12px"},children:[n("div",{style:{fontSize:"12px",marginBottom:"6px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t("span",{children:s("pagesTimeline.volume")}),n("span",{children:[Math.round(100*o.volume),"%"]})]}),t(f,{value:[o.volume],min:0,max:1,step:.01,onValueChange:e=>(e=>{const t=Math.max(0,Math.min(1,e));t>0&&X(t),o.set({volume:t})})(r(e))})]}),n("div",{style:{padding:"8px 12px"},children:[t("div",{style:{fontSize:"12px",marginBottom:"6px"},children:s("pagesTimeline.speed")}),t(x,{value:o.speed,onChange:e=>{const t=B(o.startTime,o.endTime,e);o.set({speed:e,delay:Y(o.delay,t)})}})]}),t(h,{}),n(u,{onSelect:e=>{e.preventDefault(),H(!0)},children:[t(a,{name:"action.rename"}),s("pagesTimeline.renameAudio")]}),n(u,{onSelect:e=>{e.preventDefault(),$()},children:[t(a,R?{name:"action.unmuted"}:{name:"action.muted"}),s(R?"pagesTimeline.unmuteAudio":"pagesTimeline.muteAudio")]}),n(u,{onSelect:t=>{t.preventDefault(),(()=>{const t=o.toJSON(),n=o.visibleDuration,i=o.delay+n,a=C.duration-i;let s=o.delay;a>=n?s=i:a>0&&(s=Math.max(0,C.duration-n));const{id:r}=t,l=e(t,["id"]);C.addAudio(Object.assign(Object.assign({},l),{delay:s}))})()},children:[t(a,{name:"action.duplicate"}),s("pagesTimeline.duplicateAudio")]}),t(h,{}),n(u,{onSelect:e=>{e.preventDefault(),C.removeAudio(o.id)},children:[t(a,{name:"action.remove"}),s("pagesTimeline.removeAudio")]})]})]})})]})})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";const r="rgb(0, 161, 255)";export const CurrentTime=o(({store:o,scale:i,variant:a="timeline",dragAreaRef:s})=>{const l=n.useRef(null),c=o.effectiveTime,d=n.useCallback(e=>Math.max(0,Math.min(e,o.duration)),[o.duration]),u=n.useCallback(e=>{var t,n;const r=(null==s?void 0:s.current)||(null===(t=l.current)||void 0===t?void 0:t.parentElement);if(!r){return}const a=r.getBoundingClientRect(),c=r.scrollLeft||0;let u=e-a.left+c;const p=window.getComputedStyle(r);u-=parseFloat(p.paddingLeft)||0;const v=Math.max(0,u),m=d(v/i);o.setCurrentTime(m),null===(n=o.checkActivePage)||void 0===n||n.call(o)},[d,s,i,o]),p=n.useCallback(e=>{u(e);const t=e=>{e.preventDefault(),u(e.clientX)},n=()=>{window.removeEventListener("mousemove",t),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",t),window.addEventListener("mouseup",n)},[u]),v=n.useCallback(e=>{u(e);const t=e=>{const t=e.touches[0];t&&(e.preventDefault(),u(t.clientX))},n=()=>{window.removeEventListener("touchmove",t),window.removeEventListener("touchend",n),window.removeEventListener("touchcancel",n)};window.addEventListener("touchmove",t,{passive:!1}),window.addEventListener("touchend",n),window.addEventListener("touchcancel",n)},[u]),m=n.useCallback(e=>{e.preventDefault(),e.stopPropagation(),p(e.clientX)},[p]),w=n.useCallback(e=>{const t=e.touches[0];t&&(e.preventDefault(),e.stopPropagation(),v(t.clientX))},[v]),h=(e=>"ruler"===e?{wrapper:{top:0,width:12,height:"100%",transform:"translateX(-6px)",display:"flex",flexDirection:"column",alignItems:"center"},line:{flex:1}}:{wrapper:{top:0,width:12,height:"100%",transform:"translateX(-6px)"},line:{height:"100%",margin:"0 auto"}})(a);return t("div",{ref:l,onMouseDown:m,onTouchStart:w,style:Object.assign(Object.assign({position:"absolute",left:c*i+"px"},h.wrapper),{cursor:"col-resize",touchAction:"none"}),children:[e("svg",{width:"12",height:"8",viewBox:"0 0 12 8",style:{display:"block",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))"},children:e("path",{d:"M0 0 H12 L6 8 Z",fill:r,stroke:r,strokeWidth:"2",strokeLinejoin:"round"})}),e("div",{style:Object.assign({width:"2px",backgroundColor:r},h.line)})]})});
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import{observer as i}from"mobx-react-lite";import{clamp as o}from"../lib/utils.js";import{isPrimaryDrag as n,startPointerDrag as l}from"../utils/pointer-drag.js";const s="rgb(0, 161, 255)";export const CurrentTime=i(({store:i,scale:a,variant:c="timeline",dragAreaRef:p})=>{const d=r.useRef(null),u=i.effectiveTime,m=r.useCallback(e=>{var t,r;const n=(null==p?void 0:p.current)||(null===(t=d.current)||void 0===t?void 0:t.parentElement);if(!n){return}const l=n.getBoundingClientRect(),s=n.scrollLeft||0;let c=e-l.left+s;const u=window.getComputedStyle(n);c-=parseFloat(u.paddingLeft)||0,i.setCurrentTime(o(c/a,0,i.duration)),null===(r=i.checkActivePage)||void 0===r||r.call(i)},[p,a,i]),f=r.useCallback(e=>{n(e)&&(e.stopPropagation(),m(e.clientX),l(e,{onMove:e=>m(e.clientX)}))},[m]),g=(e=>"ruler"===e?{wrapper:{top:0,width:12,height:"100%",transform:"translateX(-6px)",display:"flex",flexDirection:"column",alignItems:"center"},line:{flex:1}}:{wrapper:{top:0,width:12,height:"100%",transform:"translateX(-6px)"},line:{height:"100%",margin:"0 auto"}})(c);return t("div",{ref:d,onPointerDown:f,className:"polotno-current-time pn:touch-pan-y",style:Object.assign(Object.assign({position:"absolute",left:u*a+"px"},g.wrapper),{cursor:"col-resize"}),children:[e("svg",{width:"12",height:"8",viewBox:"0 0 12 8",style:{display:"block",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))"},children:e("path",{d:"M0 0 H12 L6 8 Z",fill:s,stroke:s,strokeWidth:"2",strokeLinejoin:"round"})}),e("div",{style:Object.assign({width:"2px",backgroundColor:s},g.line)})]})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as i}from"../icons/registry.js";import{duplicateElements as s}from"../utils/duplicate.js";import{clamp as r}from"../lib/utils.js";import{getElementTimeRange as l,MIN_DURATION as a,revealElementAtPlayhead as m}from"../utils/timeline.js";import{canSplitAtPlayhead as c,splitElementAtPlayhead as p}from"../utils/split-element.js";import{t as d}from"../utils/l10n.js";import{DropdownMenu as u,DropdownMenuContent as v,DropdownMenuItem as f}from"../primitives/dropdown-menu.js";import{TrackWrapper as w,TrackContainer as x,TrackMenu as h,TrackMenuButton as E,TrackHandleLeft as D,TrackHandleRight as j,TrackLabel as y,TrackNameInput as M}from"./track-styles.js";export const ELEMENT_ROW_HEIGHT=26;const g=o(({element:n,store:o})=>{var s;const r=o.effectiveTime-((null===(s=n.page)||void 0===s?void 0:s.startTime)||0),l=c(n,r);return t(f,{disabled:!l,onSelect:e=>{e.preventDefault();const t=p(n,r);t&&o.selectElements([t.id])},children:[e(i,{name:"action.split"}),d("contextMenu.split")]})}),L=(e,t)=>{const n=e.animations.find(e=>e.type===t);n&&n.enabled||e.setAnimation(t,{name:"none",enabled:!0})},b=(e,t,n,o)=>{const i=r(n,0,t-a),s=r(o,i+a,t);L(e,"enter"),L(e,"exit"),e.setAnimation("enter",{delay:i}),e.setAnimation("exit",{delay:Math.max(0,t-s)})};export const ElementTrack=o(({element:o,page:c,store:p,scale:L,row:S})=>{const T=c.duration,P=c.startTime,X=P+T,{start:k,end:A}=l(o.animations,T),C=(A-k)*L,H=(P+k)*L,N=o.name||o.type||d("toolbar.element"),[O,W]=n.useState(!1),[$,_]=n.useState(null),G=()=>{_(e=>null===e?S:e)},I=()=>{_(null)},R=(e,t)=>{e.preventDefault(),e.stopPropagation(),G();const n=e.clientX,i=k,s=A,l=e=>{e.preventDefault();const l=(e.clientX-n)/L;if("start"===t){const e=r(P+i+l,P,P+s-a);b(o,T,e-P,s)}else{const e=r(P+s+l,P+i+a,X);b(o,T,i,e-P)}},m=()=>{window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",m),I()};window.addEventListener("mousemove",l),window.addEventListener("mouseup",m)};return e(w,{style:{left:`${H}px`,top:26*(null!=$?$:S)+"px",width:`${C}px`,minWidth:"6px",height:"22px"},children:t(x,{style:{width:"100%",height:"100%",outline:p.selectedElements.find(e=>e.id===o.id)?"2px solid var(--pn-primary, var(--primary, #137cbd))":"none",outlineOffset:"-1px"},onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),G();const t=e.clientX,n=k,i=A-n;let s=!1;const l=e=>{e.preventDefault(),s=!0;const l=(e.clientX-t)/L,a=r(P+n+l,P,X-i)-P;b(o,T,a,a+i)},a=()=>{window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",a),I(),s||(p.selectElements([o.id]),m(o))};window.addEventListener("mousemove",l),window.addEventListener("mouseup",a)},children:[O?e(M,{value:o.name||"",onCommit:e=>{o.set({name:e}),W(!1)},onCancel:()=>W(!1)}):e(y,{children:N}),e(D,{onMouseDown:e=>R(e,"start")}),e(j,{onMouseDown:e=>R(e,"end")}),e(h,{onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:t(u,{children:[e(E,{}),t(v,{side:"top",className:"pn:whitespace-nowrap",children:[e(g,{element:o,store:p}),t(f,{onSelect:e=>{e.preventDefault(),W(!0)},children:[e(i,{name:"action.rename"}),d("contextMenu.rename")]}),t(f,{onSelect:e=>{e.preventDefault(),s([o],p)},children:[e(i,{name:"action.duplicate"}),d("contextMenu.duplicate")]}),t(f,{onSelect:e=>{e.preventDefault(),p.deleteElements([o.id])},children:[e(i,{name:"action.remove"}),d("contextMenu.remove")]})]})]})})]})})});
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as i}from"../icons/registry.js";import{duplicateElements as r}from"../utils/duplicate.js";import{clamp as l}from"../lib/utils.js";import{getElementTimeRange as s,MIN_DURATION as a,revealElementAtPlayhead as m}from"../utils/timeline.js";import{canSplitAtPlayhead as c,splitElementAtPlayhead as p}from"../utils/split-element.js";import{t as d}from"../utils/l10n.js";import{DRAG_SLOP_PX as u,isPrimaryDrag as f,startPointerDrag as x}from"../utils/pointer-drag.js";import{DropdownMenu as h,DropdownMenuContent as v,DropdownMenuItem as j}from"../primitives/dropdown-menu.js";import{TrackWrapper as E,TrackContainer as g,TrackMenu as w,TrackMenuButton as y,TrackHandleLeft as D,TrackHandleRight as M,TrackLabel as P,TrackNameInput as b}from"./track-styles.js";export const ELEMENT_ROW_HEIGHT=26;const S=o(({element:n,store:o})=>{var r;const l=o.effectiveTime-((null===(r=n.page)||void 0===r?void 0:r.startTime)||0),s=c(n,l);return t(j,{disabled:!s,onSelect:e=>{e.preventDefault();const t=p(n,l);t&&o.selectElements([t.id])},children:[e(i,{name:"action.split"}),d("contextMenu.split")]})}),T=(e,t)=>{const n=e.animations.find(e=>e.type===t);n&&n.enabled||e.setAnimation(t,{name:"none",enabled:!0})},X=(e,t,n,o)=>{const i=l(n,0,t-a),r=l(o,i+a,t);T(e,"enter"),T(e,"exit"),e.setAnimation("enter",{delay:i}),e.setAnimation("exit",{delay:Math.max(0,t-r)})};export const ElementTrack=o(({element:o,page:c,store:p,scale:T,row:k})=>{const A=c.duration,C=c.startTime,H=C+A,{start:N,end:O}=s(o.animations,A),W=(O-N)*T,$=(C+N)*T,_=o.name||o.type||d("toolbar.element"),[G,I]=n.useState(!1),[L,R]=n.useState(null),q=()=>{R(e=>null===e?k:e)},z=()=>{R(null)},B=(e,t)=>{if(!f(e)){return}e.stopPropagation();const n=e.clientX,i=N,r=O;x(e,{slopX:u,onMove:e=>{q();const s=(e.clientX-n)/T;if("start"===t){const e=l(C+i+s,C,C+r-a);X(o,A,e-C,r)}else{const e=l(C+r+s,C+i+a,H);X(o,A,i,e-C)}},onEnd:z})};return e(E,{style:{left:`${$}px`,top:26*(null!=L?L:k)+"px",width:`${W}px`,minWidth:"6px",height:"22px"},children:t(g,{style:{width:"100%",height:"100%",outline:p.selectedElements.find(e=>e.id===o.id)?"2px solid var(--pn-primary, var(--primary, #137cbd))":"none",outlineOffset:"-1px"},onPointerDown:e=>{if(!f(e)){return}e.stopPropagation();const t=e.clientX,n=N,i=O-n;x(e,{slopX:u,onMove:e=>{q();const r=(e.clientX-t)/T,s=l(C+n+r,C,H-i)-C;X(o,A,s,s+i)},onEnd:({moved:e,cancelled:t})=>{z(),e||t||(p.selectElements([o.id]),m(o))}})},children:[G?e(b,{value:o.name||"",onCommit:e=>{o.set({name:e}),I(!1)},onCancel:()=>I(!1)}):e(P,{children:_}),e(D,{onPointerDown:e=>B(e,"start")}),e(M,{onPointerDown:e=>B(e,"end")}),e(w,{onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:t(h,{children:[e(y,{}),t(v,{side:"top",className:"pn:whitespace-nowrap",children:[e(S,{element:o,store:p}),t(j,{onSelect:e=>{e.preventDefault(),I(!0)},children:[e(i,{name:"action.rename"}),d("contextMenu.rename")]}),t(j,{onSelect:e=>{e.preventDefault(),r([o],p)},children:[e(i,{name:"action.duplicate"}),d("contextMenu.duplicate")]}),t(j,{onSelect:e=>{e.preventDefault(),p.deleteElements([o.id])},children:[e(i,{name:"action.remove"}),d("contextMenu.remove")]})]})]})})]})})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import o from"react";import{observer as n}from"mobx-react-lite";import{nodeReaction as i}from"../utils/mobx.js";import{onSnapshot as s}from"mobx-state-tree";import{PolotnoIcon as a}from"../icons/registry.js";import{flags as r}from"../utils/flags.js";import{t as l}from"../utils/l10n.js";import{deepEqual as d}from"../utils/deep-equal.js";import{DropdownMenu as c,DropdownMenuContent as p,DropdownMenuItem as u}from"../primitives/dropdown-menu.js";import{Spinner as g}from"./spinner.js";import{TrackMenuButton as m}from"./track-styles.js";let v=[],h=!1;const f=async()=>{var e;if(h||0===v.length){return}h=!0;const{page:t,setPreview:o}=v.shift();try{o(await t.store.toDataURL({pageId:t.id,pixelRatio:.1,quickMode:!0}))}catch(n){"EXPORT_FAILED"===(null==n?void 0:n.code)&&["workspace-not-mounted","unmounted-during-export"].includes(null===(e=n.details)||void 0===e?void 0:e.reason)||n instanceof Error&&"string"==typeof n.message&&(n.message.includes("Canvas was unmounted.")||n.message.includes("<Workspace /> component is not mounted"))||console.error(n)}finally{h=!1}f()};export const usePagePreview=({page:e,setPreview:t,groupRef:n})=>{const a=o.useRef(!1);o.useEffect(()=>{const o=()=>{v.push({page:e,setPreview:e=>t(e)}),f()};let r=null,l=null,c=Date.now();const p=()=>{r&&clearTimeout(r),a.current&&(l||(l=setTimeout(()=>{Date.now()-c>=6e3&&(o(),c=Date.now(),l=null)},6e3)),r=setTimeout(()=>{o(),c=Date.now(),r=null,l&&(clearTimeout(l),l=null)},300))};let u=null;const g=s(e,e=>{d(u,e)||(p(),u=e)}),m=i(e,()=>e.children.some(e=>e._editModeEnabled),e=>{e||p()}),h=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?(a.current=!0,p()):(r&&clearTimeout(r),l&&clearTimeout(l),a.current=!1)})},{threshold:.1});return n.current&&h.observe(n.current),()=>{h.disconnect(),r&&clearTimeout(r),l&&clearTimeout(l),g(),m(),v=v.filter(t=>t.page!==e)}},[n,e,t])};export const PagePreview=n(({page:n,scale:i})=>{const[s,d]=o.useState(null),[v,h]=o.useState(!1),f=n.store.activePage===n||n.store._selectedPagesIds.includes(n.id),x=o.useRef(null),b=n.store.pages.indexOf(n),w=60/n.computedHeight*n.computedWidth,P=r.animationsEnabled?n.duration*i:w,y=n.store.pages.length>1;o.useLayoutEffect(()=>{x.current&&(x.current.style.width=P+"px")},[b,P]),usePagePreview({page:n,setPreview:d,groupRef:x});const{handleStartDrag:E}=((e,t)=>({handleStartDrag:o.useCallback((o,n)=>{o.preventDefault();const i=o=>{if(o.preventDefault(),!t.current){return}const i="start"===n?7:-7,{clientX:s}=o,{left:a,width:r}=t.current.getBoundingClientRect(),l=(s-a-i)/r;"end"===n&&e.set({duration:Math.max(1e3,l*e.duration)})},s=()=>{window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},[t,e])}))(n,x);return t("div",{ref:x,style:{width:P+"px",marginRight:r.animationsEnabled?"0px":"10px",height:"60px",display:"flex",position:"relative",borderRadius:"15px",boxShadow:"0 1px 4px rgba(0, 0, 0, 0.18)"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),className:"polotno-page-container"+(f?" sortable-selected":""),children:[e("div",{style:{width:"100%",height:"100%",borderRadius:"15px",backgroundImage:s?`url("${s}")`:"none",backgroundRepeat:"repeat-x",backgroundSize:"auto 100%",backgroundColor:"white",display:"flex",justifyContent:"center",alignItems:"center"},onClick:e=>{const{store:t}=n,o=t._selectedPagesIds.length?t._selectedPagesIds:t.activePage?[t.activePage.id]:[],i=o.includes(n.id),s=e.shiftKey;if(s&&i){const e=o.filter(e=>e!==n.id);t.selectPages(e)}else if(s&&!i){const e=o.concat([n.id]);t.selectPages(e)}else{t.selectPages([n.id])}},children:!s&&e(g,{})}),e("div",{style:{position:"absolute",top:"0",left:"0px",bottom:"0px",right:"0px",borderRadius:"15px",border:f?"2px solid rgb(0, 161, 255, 0.9)":"2px solid var(--pn-border)",zIndex:1,pointerEvents:"none"}}),r.animationsEnabled&&t("div",{style:{position:"absolute",zIndex:1,bottom:"5px",left:"5px",backgroundColor:"rgba(0, 0, 0, 0.5)",color:"white",padding:"2px 7px",textAlign:"center",borderRadius:"4rem"},children:[(n.duration/1e3).toFixed(1),"s"]}),r.animationsEnabled&&e("div",{style:{position:"absolute",zIndex:1,top:"50%",right:"0px",width:"8px",height:"50%",transform:"translateY(-50%) translateX(-3px)",borderRadius:"5px",border:"1px solid rgb(255, 255, 255, 0.6)",backgroundColor:"rgb(0, 0, 0, 0.6)",cursor:"ew-resize"},onMouseDown:e=>E(e,"end")}),f&&e("div",{className:"polotno-page-menu",style:{position:"absolute",zIndex:20,top:"5px",right:"5px",opacity:v?1:0,pointerEvents:v?"auto":"none",transition:"opacity 0.15s"},onClick:e=>{e.stopPropagation()},children:t(c,{children:[e(m,{}),t(p,{side:"top",className:"pn:whitespace-nowrap",children:[t(u,{onSelect:e=>{e.preventDefault();const t=n.store,o=(t.selectedPages||[]).filter(Boolean),i=o.length?o:t.activePage?[t.activePage]:[];if(!i.length){return}const s=new Set(i.map(e=>e.id)),a=t.pages.filter(e=>s.has(e.id)),r=a[a.length-1],l=a.map(e=>e.clone()),d=t.pages.indexOf(r);l.forEach((e,t)=>{e.setZIndex(d+1+t)}),t.selectPages(l.map(e=>e.id))},children:[e(a,{name:"action.duplicate",className:"pn:size-4"}),l("pagesTimeline.duplicatePage")]}),t(u,{onSelect:e=>{var t,o,i;e.preventDefault();const s=n.store.addPage({bleed:(null===(t=n.store.activePage)||void 0===t?void 0:t.bleed)||0,width:(null===(o=n.store.activePage)||void 0===o?void 0:o.width)||"auto",height:(null===(i=n.store.activePage)||void 0===i?void 0:i.height)||"auto"}),a=n.store.pages.indexOf(n);s.setZIndex(a+1)},children:[e(a,{name:"action.add",className:"pn:size-4"}),l("pagesTimeline.addPage")]}),y&&t(u,{onSelect:e=>{e.preventDefault();const t=n.store,o=(t.selectedPages||[]).filter(Boolean),i=o.length?o.map(e=>e.id):t.activePage?[t.activePage.id]:[];i.length&&t.deletePages(i)},children:[e(a,{name:"action.remove",className:"pn:size-4"}),l("pagesTimeline.removePage")]})]})]})})]})});
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,startPointerDrag 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;return o.useLayoutEffect(()=>{w.current&&(w.current.style.width=k+"px")},[y,k]),usePagePreview({page:n,setPreview:c,groupRef:w}),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;h(e,{slopX:g,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 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as i}from"react/jsx-runtime";import n from"react";import{observer as r}from"mobx-react-lite";import{PolotnoIcon as s}from"../icons/registry.js";import{flags as o}from"../utils/flags.js";import{t as a}from"../utils/l10n.js";import{cn as l}from"../lib/utils.js";import{Button as p}from"../primitives/button.js";import{floatingControl as m}from"../primitives/floating-control.js";import{Navbar as d}from"../primitives/navbar.js";import{Pages as c}from"./pages.js";import{CurrentTime as u}from"./current-time.js";import{Audios as h}from"./audios.js";import{ElementsTimeline as v}from"./elements.js";import{PlayButton as f}from"./play-button.js";import{TimeRuler as g}from"./time-ruler.js";export const PagesTimeline=r(({store:r,defaultOpened:b=!1})=>{const x=n.useRef(null),[w,y]=n.useState(b),[j,E]=n.useState(.02),[z,k]=n.useState(()=>(e=>{if(!o.animationsEnabled){return 65}const t=e.pages.reduce((e,t)=>e+t.children.length,0),i=25*e.audios.length+20*t+140;return Math.min(Math.max(i,140),420)})(r)),[L,C]=n.useState(!1),N=n.useRef(0),M=n.useRef(z),R=n.useRef(!1),S=r.duration*j,D=n.useCallback(e=>{if(!R.current){return}const t=e.clientY-N.current,i=M.current-t,n=Math.min(420,Math.max(140,i));k(n)},[]),P=n.useCallback(()=>{R.current&&(R.current=!1,C(!1),window.removeEventListener("mousemove",D),window.removeEventListener("mouseup",P))},[D]);return n.useEffect(()=>()=>{window.removeEventListener("mousemove",D),window.removeEventListener("mouseup",P)},[D,P]),t(i,{children:[e("div",{style:{position:"relative",height:"0px"},children:t(p,{variant:"ghost",size:"sm",onClick:()=>{y(!w)},className:l(m(),"pn:absolute pn:bottom-[5px] pn:left-[5px] pn:z-[1] pn:dark:hover:bg-accent"),children:[o.animationsEnabled&&!w?e(s,{name:"pagesTimeline.play",className:"pn:size-4"}):null,a("pagesTimeline.pages")]})}),t(d,{attached:"top",style:{padding:"5px",height:"auto",zIndex:1,position:"relative",overflow:"visible",display:w?"block":"none"},className:"polotno-pages-timeline pn:whitespace-normal pn:bg-background",children:[o.animationsEnabled&&e("div",{onMouseDown:e=>{e.preventDefault(),N.current=e.clientY,M.current=z,R.current=!0,C(!0),window.addEventListener("mousemove",D),window.addEventListener("mouseup",P)},className:"pn:group/pn-resize-handle pn:absolute pn:top-0 pn:left-0 pn:right-0 pn:flex pn:h-[14px] pn:-translate-y-1/2 pn:cursor-ns-resize pn:items-center pn:justify-center"+(L?" active":""),title:"Drag to adjust timeline height",children:e("div",{className:"pn:h-1 pn:w-full pn:rounded-[2px] pn:transition-colors pn:group-hover/pn-resize-handle:bg-primary"+(L?" pn:bg-primary":" pn:bg-transparent")})}),o.animationsEnabled&&e("div",{style:{display:"flex",justifyContent:"center"},children:e(f,{store:r,scale:j,onScaleChange:E})}),e("div",{dir:"ltr",style:{width:"100%",position:"relative",height:z},children:e("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflowX:"auto",padding:"0 24px"},ref:x,children:t("div",{style:{position:"relative",minWidth:o.animationsEnabled?S+"px":void 0},children:[o.animationsEnabled&&e(g,{store:r,scale:j,minWidth:S}),t("div",{style:{position:"relative",display:"flex"},children:[e("div",{style:{position:"relative",minWidth:o.animationsEnabled?S+"px":void 0,height:"60px"},children:e(c,{store:r,scale:j})}),e(p,{variant:"ghost",size:"icon",style:{width:"60px",height:"60px",marginLeft:"12px"},onClick:()=>{var e;r.addPage({bleed:(null===(e=r.activePage)||void 0===e?void 0:e.bleed)||0})},children:e(s,{name:"action.add",className:"pn:size-4"})})]}),o.animationsEnabled&&t(i,{children:[e(v,{store:r,scale:j,width:S}),e(h,{store:r,scale:j,width:S})]}),o.animationsEnabled&&e(u,{store:r,scale:j,dragAreaRef:x,variant:"timeline"})]})})})]})]})});
1
+ import{jsx as e,jsxs as i,Fragment as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{PolotnoIcon as r}from"../icons/registry.js";import{flags as a}from"../utils/flags.js";import{t as s}from"../utils/l10n.js";import{clamp as l,cn as p}from"../lib/utils.js";import{Button as m}from"../primitives/button.js";import{floatingControl as d}from"../primitives/floating-control.js";import{Navbar as c}from"../primitives/navbar.js";import{Pages as h}from"./pages.js";import{CurrentTime as u}from"./current-time.js";import{Audios as g}from"./audios.js";import{ElementsTimeline as f}from"./elements.js";import{PlayButton as v}from"./play-button.js";import{TimeRuler as b}from"./time-ruler.js";import{isPrimaryDrag as x,startPointerDrag as j}from"../utils/pointer-drag.js";export const PagesTimeline=o(({store:o,defaultOpened:y=!1})=>{const E=n.useRef(null),[w,z]=n.useState(y),[N,k]=n.useState(.02),[S,C]=n.useState(()=>(e=>{if(!a.animationsEnabled){return 65}const i=e.pages.reduce((e,i)=>e+i.children.length,0),t=25*e.audios.length+20*i+140;return l(t,140,420)})(o)),[P,T]=n.useState(!1),W=o.duration*N;return i(t,{children:[e("div",{style:{position:"relative",height:"0px"},children:i(m,{variant:"ghost",size:"sm",onClick:()=>{z(!w)},className:p(d(),"pn:absolute pn:bottom-[5px] pn:left-[5px] pn:z-[1] pn:dark:hover:bg-accent"),children:[a.animationsEnabled&&!w?e(r,{name:"pagesTimeline.play",className:"pn:size-4"}):null,s("pagesTimeline.pages")]})}),i(c,{attached:"top",style:{padding:"5px",height:"auto",zIndex:1,position:"relative",overflow:"visible",display:w?"block":"none"},className:"polotno-pages-timeline pn:whitespace-normal pn:bg-background",children:[a.animationsEnabled&&e("div",{onPointerDown:e=>{if(!x(e)){return}const i=e.clientY,t=S;T(!0),j(e,{onMove:e=>{const n=t-(e.clientY-i);C(l(n,140,420))},onEnd:()=>T(!1)})},className:"pn:group/pn-resize-handle pn:absolute pn:top-0 pn:left-0 pn:right-0 pn:flex pn:h-[14px] pn:-translate-y-1/2 pn:cursor-ns-resize pn:touch-none pn:items-center pn:justify-center"+(P?" active":""),title:"Drag to adjust timeline height",children:e("div",{className:"pn:h-1 pn:w-full pn:rounded-[2px] pn:transition-colors pn:group-hover/pn-resize-handle:bg-primary"+(P?" pn:bg-primary":" pn:bg-transparent")})}),a.animationsEnabled&&e("div",{style:{display:"flex",justifyContent:"center"},children:e(v,{store:o,scale:N,onScaleChange:k})}),e("div",{dir:"ltr",style:{width:"100%",position:"relative",height:S},children:e("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflowX:"auto",padding:"0 24px"},ref:E,children:i("div",{style:{position:"relative",minWidth:a.animationsEnabled?W+"px":void 0},children:[a.animationsEnabled&&e(b,{store:o,scale:N,minWidth:W}),i("div",{style:{position:"relative",display:"flex"},children:[e("div",{style:{position:"relative",minWidth:a.animationsEnabled?W+"px":void 0,height:"60px"},children:e(h,{store:o,scale:N})}),e(m,{variant:"ghost",size:"icon",style:{width:"60px",height:"60px",marginLeft:"12px"},onClick:()=>{var e;o.addPage({bleed:(null===(e=o.activePage)||void 0===e?void 0:e.bleed)||0})},children:e(r,{name:"action.add",className:"pn:size-4"})})]}),a.animationsEnabled&&i(t,{children:[e(f,{store:o,scale:N,width:W}),e(g,{store:o,scale:N,width:W})]}),a.animationsEnabled&&e(u,{store:o,scale:N,dragAreaRef:E,variant:"timeline"})]})})})]})]})});
@@ -1 +1 @@
1
- import{jsx as e}from"react/jsx-runtime";import{observer as t}from"mobx-react-lite";import{ReactSortable as o}from"react-sortablejs";import{PagePreview as r}from"./page-preview.js";export const Pages=t(({store:t,scale:s})=>{const i=t.pages.map(e=>({id:e.id}));return e(o,{list:i,setList:e=>{e.forEach(({id:e},o)=>{const r=t.pages.find(t=>t.id===e);r&&t.pages.indexOf(r)!==o&&r.setZIndex(o)})},direction:"horizontal",style:{display:"flex",flexDirection:"row"},delay:500,delayOnTouchOnly:!0,className:"polotno-pages-container",children:i.map(({id:o})=>{const i=t.pages.find(e=>e.id===o);return i?e(r,{page:i,scale:s},o):null})})});
1
+ import{jsx as e}from"react/jsx-runtime";import{observer as t}from"mobx-react-lite";import{ReactSortable as r}from"react-sortablejs";import{PagePreview as o}from"./page-preview.js";export const Pages=t(({store:t,scale:i})=>{const a=t.pages.map(e=>({id:e.id}));return e(r,{list:a,setList:e=>{e.forEach(({id:e},r)=>{const o=t.pages.find(t=>t.id===e);o&&t.pages.indexOf(o)!==r&&o.setZIndex(r)})},direction:"horizontal",style:{display:"flex",flexDirection:"row"},delay:500,delayOnTouchOnly:!0,filter:".polotno-track-handle",preventOnFilter:!1,className:"polotno-pages-container",children:a.map(({id:r})=>{const a=t.pages.find(e=>e.id===r);return a?e(o,{page:a,scale:i},r):null})})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as i}from"react/jsx-runtime";import{observer as n}from"mobx-react-lite";import{PolotnoIcon as t}from"../icons/registry.js";import{Button as a}from"../primitives/button.js";import{ButtonGroup as s}from"../primitives/button-group.js";import{Switch as l}from"../primitives/switch.js";import{t as p}from"../utils/l10n.js";const r=e=>{const i=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${i.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`};export const PlayButton=n(({store:n,scale:o,onScaleChange:m})=>{const c=n.effectiveTime;return i("div",{className:"pn:grid pn:w-full pn:grid-cols-[1fr_auto_1fr] pn:items-center pn:gap-3",children:[i("div",{className:"pn:flex pn:items-center pn:justify-between pn:gap-2",children:[i("label",{className:"pn:flex pn:cursor-pointer pn:items-center pn:gap-2 pn:text-xs pn:font-medium pn:select-none",title:p("pagesTimeline.editAsVideoHint"),children:[e(l,{checked:"playhead"===n.timingPreview,onCheckedChange:e=>n.setTimingPreview(e?"playhead":"all")}),p("pagesTimeline.editAsVideo")]}),i("div",{className:"pn:text-[13px] pn:font-medium pn:tabular-nums pn:opacity-[0.85]",children:[r(c)," / ",r(n.duration)]})]}),i("div",{className:"polotno-play-button-container pn:inline-flex pn:items-center pn:justify-center pn:gap-2",children:[e(a,{variant:"ghost",size:"icon",className:"pn:size-[30px]","aria-label":p("pagesTimeline.rewind"),title:p("pagesTimeline.rewind"),onClick:()=>n.stop(),children:e(t,{name:"pagesTimeline.rewind",className:"pn:size-[20px]"})}),e(a,{variant:"ghost",size:"icon",className:"pn:size-[30px]","aria-label":n.isPlaying?"Pause":"Play",onClick:()=>{if(n.isPlaying){n.pause()}else{const e=n.currentTime>=n.duration?0:n.effectiveTime;n.play({startTime:e})}},children:n.isPlaying?e(t,{name:"pagesTimeline.pause",className:"pn:size-[25px]"}):e(t,{name:"pagesTimeline.play",className:"pn:size-[25px]"})})]}),m&&o&&i("div",{className:"pn:flex pn:items-center pn:justify-end pn:gap-1.5",children:[e("div",{className:"pn:text-xs pn:font-medium pn:tabular-nums pn:opacity-60",children:"Zoom timeline"}),i(s,{className:"pn:items-center",children:[e(a,{variant:"ghost",size:"icon-sm",className:"pn:size-[30px]",onClick:()=>{m&&o&&m(Math.max(o/1.5,.005))},title:"Zoom out timeline","aria-label":"Zoom out timeline",children:e("span",{className:"pn:font-bold",children:"−"})}),e(a,{variant:"ghost",size:"icon-sm",className:"pn:size-[30px]",onClick:()=>{m&&o&&m(Math.min(1.5*o,.2))},title:"Zoom in timeline","aria-label":"Zoom in timeline",children:e("span",{className:"pn:font-bold",children:"+"})})]})]})]})});
1
+ import{jsx as e,jsxs as i}from"react/jsx-runtime";import{observer as n}from"mobx-react-lite";import{PolotnoIcon as a}from"../icons/registry.js";import{Button as t}from"../primitives/button.js";import{ButtonGroup as s}from"../primitives/button-group.js";import{Switch as p}from"../primitives/switch.js";import{t as l}from"../utils/l10n.js";const r=e=>{const i=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${i.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`};export const PlayButton=n(({store:n,scale:m,onScaleChange:o})=>{const c=n.effectiveTime;return e("div",{className:"pn:@container pn:w-full",children:i("div",{className:"pn:grid pn:w-full pn:grid-cols-[1fr_auto_1fr] pn:items-center pn:gap-3 pn:@max-[520px]:flex pn:@max-[520px]:flex-wrap pn:@max-[520px]:justify-center pn:@max-[520px]:gap-x-2 pn:@max-[520px]:gap-y-1",children:[i("div",{className:"pn:flex pn:items-center pn:justify-between pn:gap-2",children:[i("label",{className:"pn:flex pn:cursor-pointer pn:items-center pn:gap-2 pn:whitespace-nowrap pn:text-xs pn:font-medium pn:select-none",title:l("pagesTimeline.editAsVideoHint"),children:[e(p,{"aria-label":l("pagesTimeline.editAsVideo"),checked:"playhead"===n.timingPreview,onCheckedChange:e=>n.setTimingPreview(e?"playhead":"all")}),l("pagesTimeline.editAsVideo")]}),i("div",{className:"pn:whitespace-nowrap pn:text-[13px] pn:font-medium pn:tabular-nums pn:opacity-[0.85]",children:[r(c)," / ",r(n.duration)]})]}),i("div",{className:"polotno-play-button-container pn:inline-flex pn:items-center pn:justify-center pn:gap-2 pn:@max-[520px]:gap-1",children:[e(t,{variant:"ghost",size:"icon",className:"pn:size-[30px]","aria-label":l("pagesTimeline.rewind"),title:l("pagesTimeline.rewind"),onClick:()=>n.stop(),children:e(a,{name:"pagesTimeline.rewind",className:"pn:size-[20px]"})}),e(t,{variant:"ghost",size:"icon",className:"pn:size-[30px]","aria-label":n.isPlaying?"Pause":"Play",onClick:()=>{if(n.isPlaying){n.pause()}else{const e=n.currentTime>=n.duration?0:n.effectiveTime;n.play({startTime:e})}},children:n.isPlaying?e(a,{name:"pagesTimeline.pause",className:"pn:size-[25px]"}):e(a,{name:"pagesTimeline.play",className:"pn:size-[25px]"})})]}),o&&m&&i("div",{className:"pn:flex pn:items-center pn:justify-end pn:gap-1.5",children:[e("div",{className:"pn:text-xs pn:font-medium pn:tabular-nums pn:opacity-60 pn:@max-[520px]:hidden",children:"Zoom timeline"}),i(s,{className:"pn:items-center",children:[e(t,{variant:"ghost",size:"icon-sm",className:"pn:size-[30px]",onClick:()=>{o&&m&&o(Math.max(m/1.5,.005))},title:"Zoom out timeline","aria-label":"Zoom out timeline",children:e("span",{className:"pn:font-bold",children:"−"})}),e(t,{variant:"ghost",size:"icon-sm",className:"pn:size-[30px]",onClick:()=>{o&&m&&o(Math.min(1.5*m,.2))},title:"Zoom in timeline","aria-label":"Zoom in timeline",children:e("span",{className:"pn:font-bold",children:"+"})})]})]})]})})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";export const TimeRuler=o(({store:o,scale:i,minWidth:r=0})=>{const a=n.useRef(null),s=Math.max(o.duration,0),l=Math.max(1,Math.ceil(s/1e3)),c=Math.max(s*i,r,120),u=1e3*i,m=[1,2,5,10,15,30,60,120,300,600],d=m.find(e=>e*u>=70)||m[m.length-1],p=Math.max(1,Math.ceil(20/u)),h=n.useCallback(e=>Math.max(0,Math.min(e,o.duration)),[o.duration]),v=n.useCallback(e=>{var t;if(!a.current){return}const n=a.current.getBoundingClientRect(),r=Math.min(Math.max(e-n.left,0),n.width),s=h(r/i);o.setCurrentTime(s),null===(t=o.checkActivePage)||void 0===t||t.call(o)},[h,i,o]),w=n.useCallback(e=>{v(e);const t=e=>{e.preventDefault(),v(e.clientX)},n=()=>{window.removeEventListener("mousemove",t),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",t),window.addEventListener("mouseup",n)},[v]),f=n.useCallback(e=>{v(e);const t=e=>{const t=e.touches[0];t&&(e.preventDefault(),v(t.clientX))},n=()=>{window.removeEventListener("touchmove",t),window.removeEventListener("touchend",n),window.removeEventListener("touchcancel",n)};window.addEventListener("touchmove",t,{passive:!1}),window.addEventListener("touchend",n),window.addEventListener("touchcancel",n)},[v]),x=n.useCallback(e=>{e.preventDefault(),w(e.clientX)},[w]),M=n.useCallback(e=>{const t=e.touches[0];t&&(e.preventDefault(),f(t.clientX))},[f]);return e("div",{ref:a,className:"polotno-time-ruler pn:relative pn:h-6 pn:cursor-pointer pn:select-none pn:text-inherit",onMouseDown:x,onTouchStart:M,style:{minWidth:c+"px",width:c+"px",touchAction:"none"},children:Array.from({length:l+1},(n,o)=>{const r=o%d===0,a=o%p===0&&!r;return r||a?t("div",{style:{position:"absolute",left:1e3*o*i+"px",top:0,transform:"translateX(-50%)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:4,pointerEvents:"none"},children:[a&&e("div",{className:"pn:size-1 pn:rounded-full pn:bg-current pn:opacity-50"}),r&&e("div",{className:"pn:mt-1 pn:text-center pn:text-[11px] pn:tabular-nums pn:opacity-70",children:o<60?`${o}s`:`${Math.floor(o/60)}m${o%60?o%60+"s":""}`})]},o):null})})});
1
+ import{jsx as t,jsxs as e}from"react/jsx-runtime";import n from"react";import{observer as r}from"mobx-react-lite";import{clamp as i}from"../lib/utils.js";import{isPrimaryDrag as l,startPointerDrag as o}from"../utils/pointer-drag.js";export const TimeRuler=r(({store:r,scale:a,minWidth:s=0})=>{const c=n.useRef(null),p=Math.max(r.duration,0),m=Math.max(1,Math.ceil(p/1e3)),u=Math.max(p*a,s,120),h=1e3*a,d=[1,2,5,10,15,30,60,120,300,600],f=d.find(t=>t*h>=70)||d[d.length-1],x=Math.max(1,Math.ceil(20/h)),g=n.useCallback(t=>{var e;if(!c.current){return}const n=c.current.getBoundingClientRect(),l=i(t-n.left,0,n.width);r.setCurrentTime(i(l/a,0,r.duration)),null===(e=r.checkActivePage)||void 0===e||e.call(r)},[a,r]),v=n.useCallback(t=>{l(t)&&(g(t.clientX),o(t,{onMove:t=>g(t.clientX)}))},[g]);return t("div",{ref:c,className:"polotno-time-ruler pn:relative pn:h-6 pn:cursor-pointer pn:touch-pan-y pn:select-none pn:text-inherit",onPointerDown:v,style:{minWidth:u+"px",width:u+"px"},children:Array.from({length:m+1},(n,r)=>{const i=r%f===0,l=r%x===0&&!i;return i||l?e("div",{style:{position:"absolute",left:1e3*r*a+"px",top:0,transform:"translateX(-50%)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:4,pointerEvents:"none"},children:[l&&t("div",{className:"pn:size-1 pn:rounded-full pn:bg-current pn:opacity-50"}),i&&t("div",{className:"pn:mt-1 pn:text-center pn:text-[11px] pn:tabular-nums pn:opacity-70",children:r<60?`${r}s`:`${Math.floor(r/60)}m${r%60?r%60+"s":""}`})]},r):null})})});
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,n){var a={};for(var r in e){Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(a[r]=e[r])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var t=0;for(r=Object.getOwnPropertySymbols(e);t<r.length;t++){n.indexOf(r[t])<0&&Object.prototype.propertyIsEnumerable.call(e,r[t])&&(a[r[t]]=e[r[t]])}}return a};import{jsx as n}from"react/jsx-runtime";import a from"react";import{PolotnoIcon as r}from"../icons/registry.js";import{cn as t}from"../lib/utils.js";import{Button as p}from"../primitives/button.js";import{DropdownMenuTrigger as o}from"../primitives/dropdown-menu.js";export const TrackLabel=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("pn:pointer-events-none pn:absolute pn:inset-0 pn:flex pn:items-center pn:overflow-hidden pn:text-ellipsis pn:whitespace-nowrap pn:px-3 pn:text-[11px] pn:font-medium pn:text-black/75 pn:dark:text-white/[0.92]",p)},o))});TrackLabel.displayName="TrackLabel";export const TrackInlineLabel=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("pn:pointer-events-none pn:max-w-[45%] pn:flex-none pn:overflow-hidden pn:text-ellipsis pn:whitespace-nowrap pn:text-[11px] pn:font-medium pn:text-black/75 pn:dark:text-white/[0.92]",p)},o))});TrackInlineLabel.displayName="TrackInlineLabel";export const TrackNameInput=r=>{var{value:p,onCommit:o,onCancel:s,className:i}=r,c=e(r,["value","onCommit","onCancel","className"]);const[l,m]=a.useState(p),f=a.useRef(!1);return n("input",Object.assign({autoFocus:!0,value:l,onFocus:e=>e.target.select(),onChange:e=>m(e.target.value),onBlur:()=>{f.current||(f.current=!0,o(l.trim()))},onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key?(e.preventDefault(),e.target.blur()):"Escape"===e.key&&(e.preventDefault(),f.current=!0,s())},onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:t("pn:absolute pn:inset-0 pn:z-30 pn:w-full pn:rounded-[10px] pn:bg-white/85 pn:px-3 pn:outline-none pn:ring-1 pn:ring-primary pn:text-[11px] pn:font-medium pn:text-black/75 pn:dark:bg-black/70 pn:dark:text-white/[0.92]",i)},c))};TrackNameInput.displayName="TrackNameInput";export const WaveformSvg=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("svg",Object.assign({ref:r,className:t("pn:[&_path]:fill-black/50 pn:dark:[&_path]:fill-white/70",p)},o))});WaveformSvg.displayName="WaveformSvg";export const TrackWrapper=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("pn:absolute pn:[&:hover_.polotno-track-menu]:pointer-events-auto pn:[&:hover_.polotno-track-menu]:opacity-100",p)},o))});TrackWrapper.displayName="TrackWrapper";export const TrackContainer=a.forwardRef((a,r)=>{var{className:p,style:o}=a,s=e(a,["className","style"]);return n("div",Object.assign({ref:r,className:t("pn:absolute pn:cursor-move pn:overflow-hidden pn:rounded-[10px] pn:border pn:border-primary/55 pn:bg-gradient-to-br pn:from-primary/15 pn:to-primary/35 pn:shadow-sm",p),style:o},s))});TrackContainer.displayName="TrackContainer";export const TrackMenu=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("polotno-track-menu pn:pointer-events-none pn:absolute pn:top-1/2 pn:right-3 pn:z-20 pn:-translate-y-1/2 pn:opacity-0",p)},o))});TrackMenu.displayName="TrackMenu";export const TrackMenuButton=()=>n(o,{render:n(p,{variant:"secondary",size:"icon-sm",style:{minHeight:"20px",borderRadius:"10px"},children:n(r,{name:"action.more",className:"pn:size-4"})})});TrackMenuButton.displayName="TrackMenuButton";const s=a.forwardRef((a,r)=>{var{className:p,side:o}=a,s=e(a,["className","side"]);return n("div",Object.assign({ref:r,className:t('pn:pointer-events-auto pn:absolute pn:top-px pn:flex pn:h-[calc(100%-2px)] pn:w-3 pn:cursor-ew-resize pn:items-center pn:justify-center pn:before:h-3/4 pn:before:w-2 pn:before:rounded pn:before:border pn:before:border-white/60 pn:before:bg-black/60 pn:before:content-[""]',"left"===o?"pn:left-0":"pn:right-0",p)},s))});s.displayName="TrackHandleBase";export const TrackHandleLeft=a.forwardRef((e,a)=>n(s,Object.assign({ref:a,side:"left"},e)));TrackHandleLeft.displayName="TrackHandleLeft";export const TrackHandleRight=a.forwardRef((e,a)=>n(s,Object.assign({ref:a,side:"right"},e)));TrackHandleRight.displayName="TrackHandleRight";
1
+ var e=this&&this.__rest||function(e,n){var a={};for(var r in e){Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(a[r]=e[r])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var t=0;for(r=Object.getOwnPropertySymbols(e);t<r.length;t++){n.indexOf(r[t])<0&&Object.prototype.propertyIsEnumerable.call(e,r[t])&&(a[r[t]]=e[r[t]])}}return a};import{jsx as n}from"react/jsx-runtime";import a from"react";import{PolotnoIcon as r}from"../icons/registry.js";import{cn as t}from"../lib/utils.js";import{Button as p}from"../primitives/button.js";import{DropdownMenuTrigger as o}from"../primitives/dropdown-menu.js";export const TrackLabel=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("pn:pointer-events-none pn:absolute pn:inset-0 pn:flex pn:items-center pn:overflow-hidden pn:text-ellipsis pn:whitespace-nowrap pn:px-3 pn:text-[11px] pn:font-medium pn:text-black/75 pn:dark:text-white/[0.92]",p)},o))});TrackLabel.displayName="TrackLabel";export const TrackInlineLabel=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("pn:pointer-events-none pn:max-w-[45%] pn:flex-none pn:overflow-hidden pn:text-ellipsis pn:whitespace-nowrap pn:text-[11px] pn:font-medium pn:text-black/75 pn:dark:text-white/[0.92]",p)},o))});TrackInlineLabel.displayName="TrackInlineLabel";export const TrackNameInput=r=>{var{value:p,onCommit:o,onCancel:s,className:i}=r,c=e(r,["value","onCommit","onCancel","className"]);const[l,m]=a.useState(p),f=a.useRef(!1);return n("input",Object.assign({autoFocus:!0,value:l,onFocus:e=>e.target.select(),onChange:e=>m(e.target.value),onBlur:()=>{f.current||(f.current=!0,o(l.trim()))},onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key?(e.preventDefault(),e.target.blur()):"Escape"===e.key&&(e.preventDefault(),f.current=!0,s())},onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:t("pn:absolute pn:inset-0 pn:z-30 pn:w-full pn:rounded-[10px] pn:bg-white/85 pn:px-3 pn:outline-none pn:ring-1 pn:ring-primary pn:text-[11px] pn:font-medium pn:text-black/75 pn:dark:bg-black/70 pn:dark:text-white/[0.92]",i)},c))};TrackNameInput.displayName="TrackNameInput";export const WaveformSvg=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("svg",Object.assign({ref:r,className:t("pn:[&_path]:fill-black/50 pn:dark:[&_path]:fill-white/70",p)},o))});WaveformSvg.displayName="WaveformSvg";export const TrackWrapper=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("pn:absolute pn:[&:hover_.polotno-track-menu]:pointer-events-auto pn:[&:hover_.polotno-track-menu]:opacity-100",p)},o))});TrackWrapper.displayName="TrackWrapper";export const TrackContainer=a.forwardRef((a,r)=>{var{className:p,style:o}=a,s=e(a,["className","style"]);return n("div",Object.assign({ref:r,className:t("pn:absolute pn:cursor-move pn:touch-pan-y pn:overflow-hidden pn:rounded-[10px] pn:border pn:border-primary/55 pn:bg-gradient-to-br pn:from-primary/15 pn:to-primary/35 pn:shadow-sm",p),style:o},s))});TrackContainer.displayName="TrackContainer";export const TrackMenu=a.forwardRef((a,r)=>{var{className:p}=a,o=e(a,["className"]);return n("div",Object.assign({ref:r,className:t("polotno-track-menu pn:pointer-events-none pn:absolute pn:top-1/2 pn:right-3 pn:z-20 pn:-translate-y-1/2 pn:opacity-0",p)},o))});TrackMenu.displayName="TrackMenu";export const TrackMenuButton=()=>n(o,{render:n(p,{variant:"secondary",size:"icon-sm",style:{minHeight:"20px",borderRadius:"10px"},children:n(r,{name:"action.more",className:"pn:size-4"})})});TrackMenuButton.displayName="TrackMenuButton";const s=a.forwardRef((a,r)=>{var{className:p,side:o}=a,s=e(a,["className","side"]);return n("div",Object.assign({ref:r,className:t('polotno-track-handle pn:pointer-events-auto pn:absolute pn:top-px pn:flex pn:h-[calc(100%-2px)] pn:w-[min(0.75rem,33%)] pn:cursor-ew-resize pn:touch-pan-y pn:items-center pn:justify-center pn:before:h-3/4 pn:before:w-2 pn:before:rounded pn:before:border pn:before:border-white/60 pn:before:bg-black/60 pn:before:content-[""] pn:pointer-coarse:w-[min(1.25rem,33%)]',"left"===o?"pn:left-0":"pn:right-0",p)},s))});s.displayName="TrackHandleBase";export const TrackHandleLeft=a.forwardRef((e,a)=>n(s,Object.assign({ref:a,side:"left"},e)));TrackHandleLeft.displayName="TrackHandleLeft";export const TrackHandleRight=a.forwardRef((e,a)=>n(s,Object.assign({ref:a,side:"right"},e)));TrackHandleRight.displayName="TrackHandleRight";