polotno 4.0.0-beta.49 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/blueprint/pages-timeline/current-time.d.ts +1 -1
- package/blueprint/pages-timeline/page-preview.d.ts +1 -1
- package/blueprint/side-panel/elements-panel.js +1 -1
- package/blueprint/side-panel/size-panel.d.ts +2 -2
- package/blueprint/toolbar/color-picker.js +1 -1
- package/blueprint/toolbar/text-ai-write.js +1 -1
- package/canvas/apply-filters.js +1 -1
- package/canvas/context-menu/context-menu.js +1 -1
- package/canvas/element.d.ts +1 -1
- package/canvas/element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/image-element.js +1 -1
- package/canvas/rich-editor.js +2 -2
- package/canvas/use-fadein.js +1 -1
- package/canvas/video-element.js +1 -1
- package/lib/utils.d.ts +1 -0
- package/lib/utils.js +1 -1
- package/model/group-model.d.ts +1 -0
- package/model/page-model.d.ts +1 -0
- package/model/store.d.ts +9 -1
- package/model/store.js +1 -1
- package/model/svg-model.d.ts +1 -0
- package/model/svg-model.js +1 -1
- package/model/table-model.js +1 -1
- package/package.json +11 -22
- package/pages-timeline/audio-track.js +1 -1
- package/pages-timeline/current-time.d.ts +1 -1
- package/pages-timeline/page-preview.d.ts +1 -1
- package/pages-timeline/track-styles.js +1 -1
- package/polotno.bundle.js +132 -176
- package/primitives/button.d.ts +1 -3
- package/primitives/button.js +1 -1
- package/primitives/dialog.d.ts +7 -7
- package/primitives/dialog.js +1 -1
- package/primitives/dropdown-menu.d.ts +28 -16
- package/primitives/dropdown-menu.js +1 -1
- package/primitives/navbar.d.ts +2 -2
- package/primitives/numeric-input.js +1 -1
- package/primitives/overflow-list.js +1 -1
- package/primitives/popover.d.ts +9 -3
- package/primitives/popover.js +1 -1
- package/primitives/select.d.ts +16 -10
- package/primitives/select.js +1 -1
- package/primitives/separator.d.ts +1 -2
- package/primitives/separator.js +1 -1
- package/primitives/slider-field.js +1 -1
- package/primitives/slider.d.ts +4 -2
- package/primitives/slider.js +1 -1
- package/primitives/switch.d.ts +1 -2
- package/primitives/switch.js +1 -1
- package/primitives/tabs.d.ts +4 -5
- package/primitives/tabs.js +1 -1
- package/primitives/toggle-group.d.ts +5 -7
- package/primitives/toggle-group.js +1 -1
- package/primitives/toggle.d.ts +2 -2
- package/primitives/toggle.js +1 -1
- package/primitives/tooltip-icon-button.js +1 -1
- package/primitives/tooltip.d.ts +8 -4
- package/primitives/tooltip.js +1 -1
- package/side-panel/animations-panel.js +1 -1
- package/side-panel/draw-panel.js +1 -1
- package/side-panel/effects-panel.js +1 -1
- package/side-panel/size-panel.js +1 -1
- package/toolbar/admin-button.js +1 -1
- package/toolbar/animations-picker.js +1 -1
- package/toolbar/color-picker.js +1 -1
- package/toolbar/copy-style.js +1 -1
- package/toolbar/download-button.js +1 -1
- package/toolbar/figure-toolbar.js +1 -1
- package/toolbar/filters-picker.js +1 -1
- package/toolbar/flip-button.js +1 -1
- package/toolbar/html-toolbar.js +4 -4
- package/toolbar/image-toolbar.js +1 -1
- package/toolbar/line-toolbar.js +1 -1
- package/toolbar/opacity-picker.js +1 -1
- package/toolbar/page-toolbar.js +1 -1
- package/toolbar/position-picker.js +1 -1
- package/toolbar/sketch.js +1 -1
- package/toolbar/svg-toolbar.js +1 -1
- package/toolbar/table-toolbar.js +1 -1
- package/toolbar/text-ai-write.js +1 -1
- package/toolbar/text-toolbar.d.ts +3 -1
- package/toolbar/text-toolbar.js +1 -1
- package/toolbar/toolbar.js +1 -1
- package/toolbar/video-toolbar.js +1 -1
- package/toolbar/zoom-buttons.js +1 -1
- package/ui.css +2 -2
- package/utils/crop.d.ts +2 -2
- package/utils/goober.d.ts +2 -2
- package/utils/l10n.d.ts +3 -0
- package/utils/l10n.js +1 -1
- package/utils/rich-text-html.js +1 -1
- package/utils/use-api.d.ts +2 -2
- package/utils/use-api.js +1 -1
- package/utils/validate-key.d.ts +2 -1
- package/utils/validate-key.js +1 -1
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{addDpiMetadataToImage as v}from"../utils/image-dpi.js";import{nodeToCanvas as P}from"../utils/canvas.js";import{whenLoaded as w}from"../utils/loader.js";import{pxToUnit as E}from"../utils/unit.js";import{deepEqual as x}from"../utils/deep-equal.js";import{waitTillAvailable as I}from"../utils/wait.js";import{jsonToHTML as _}from"../utils/to-html.js";import{jsonToSVG as k}from"../utils/to-svg.js";import{Page as S}from"./page-model.js";import{forEveryChild as T,forEveryNode as O}from"./group-model.js";import{Audio as j}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(S),fonts:l.array(Font),audios:l.array(j),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:3,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return O({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 T({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return O({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const T={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>T.seek())},checkActivePage(){let e=0;for(const t of r.pages){if(r.currentTime>=t.startTime&&r.currentTime<t.startTime+t.duration){T.selectPage(t.id);break}e+=t.duration}},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t,T.checkActivePage();const i=d||r.duration;r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>T.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>T.seek())):T.stop()},stop(){r.isPlaying=!1,r.currentTime=0,r.animatedElementsIds=i([]),T.checkActivePage()},__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=S.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=T.toJSON();return s(r,i=>{const o=T.toJSON();!x(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const c=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw new Error(`No page for export with id ${i}`)}const m=r._elementsPixelRatio;c>r._elementsPixelRatio&&T.setElementsPixelRatio(c),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const u=await I(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!u){throw null==g||g.set({_forceMount:!1,_exporting:!1}),T.setElementsPixelRatio(m),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}u.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const f=u[0];await T.waitLoading({_skipTimeout:a});const h=f.findOne(".page-container");if(!h){throw T.setElementsPixelRatio(m),null==g||g.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const b=f.position();f.position({x:0,y:0}),f.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),h.find(".page-background").forEach(e=>e.shadowEnabled(!1)),h.find(".page-background").forEach(e=>e.strokeEnabled(!1)),h.find(".highlighter").forEach(e=>e.visible(!1));const y=h.findOne(".page-background-group"),v=y.clip();y.clip({x:null,y:null,width:null,height:null});const w=h.findOne(".elements-container"),E=w.clip();w.clip({x:null,y:null,width:null,height:null});const x=h.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const _=h.find(e=>e.getAttr("hideInExport"));_.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&h.find(".page-background").forEach(e=>e.hide());const k=n?g.bleed:0;let S=k;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?S=0:r.bleedVisible&&!n&&(S=-g.bleed):S=0);const O=g.computedWidth+2*k,j=g.computedHeight+2*k,R=h.scale();h.scale({x:1,y:1});const F=P(h,{x:h.x()-S,y:h.y()-S,width:O,height:j,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(R);const C=F._canvas;if("image/jpeg"===o){const e=C.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,C.width,C.height),e.restore()}return t&&h.find(".page-background").forEach(e=>e.show()),_.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".page-background").forEach(e=>e.shadowEnabled(!0)),h.find(".page-background").forEach(e=>e.strokeEnabled(!0)),f.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".highlighter").forEach(e=>e.visible(!0)),y.clip(v),w.clip(E),f.position(b),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),T.setElementsPixelRatio(m),C},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await T._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",c=l.toDataURL(d,o);p.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?c:v(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await T._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];m(await T.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await u(),d=e=>E({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let v=0;for(const r of y){const t=r.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,r=d(o),l=d(s);let p=0,g=n;for(;p<10;){p+=1;const i=await T.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(i.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++v/a.length*.9),{url:i,width:r,height:l,widthPx:o,heightPx:s}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await T._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw new Error("No pages found for GIF export")}const n=o[0],a=await f({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of o){const e=Math.max(1,Math.floor(l.duration/s));for(let i=0;i<e;i++){const e=l.startTime+i*s||1;T.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await T._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(o.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return T.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await T.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=T.toJSON();return _({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await T.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=T.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return k({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await T.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await T._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await w()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,c=JSON.parse(JSON.stringify(e)),p=c.schemaVersion||0;p<1&&(y.htmlRenderEnabled||y.renderTagTextEnabled)&&O({children:c.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),p<2&&O({children:c.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),p<3&&(y.htmlRenderEnabled||y.renderTagTextEnabled)&&!d&&O({children:c.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete c.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=c.pages[g]||c.pages[0])||void 0===s?void 0:s.id;c._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,c),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);T.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){T.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=j.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(n)):b.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>b.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return T});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h,setKey as b}from"../utils/validate-key.js";import*as y from"../utils/fonts.js";import{flags as v}from"../utils/flags.js";import{addDpiMetadataToImage as P}from"../utils/image-dpi.js";import{nodeToCanvas as w}from"../utils/canvas.js";import{whenLoaded as E}from"../utils/loader.js";import{pxToUnit as x}from"../utils/unit.js";import{deepEqual as I}from"../utils/deep-equal.js";import{waitTillAvailable as _}from"../utils/wait.js";import{jsonToHTML as k}from"../utils/to-html.js";import{jsonToSVG as S}from"../utils/to-svg.js";import{Page as T}from"./page-model.js";import{forEveryChild as O,forEveryNode as j}from"./group-model.js";import{Audio as R}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(T),fonts:l.array(Font),audios:l.array(R),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:3,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return j({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return O({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return j({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const b={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>b.seek())},checkActivePage(){let e=0;for(const t of r.pages){if(r.currentTime>=t.startTime&&r.currentTime<t.startTime+t.duration){b.selectPage(t.id);break}e+=t.duration}},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t,b.checkActivePage();const i=d||r.duration;r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>b.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>b.seek())):b.stop()},stop(){r.isPlaying=!1,r.currentTime=0,r.animatedElementsIds=i([]),b.checkActivePage()},__(){r._validated||(h(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=T.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=b.toJSON();return s(r,i=>{const o=b.toJSON();!I(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const c=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw new Error(`No page for export with id ${i}`)}const m=r._elementsPixelRatio;c>r._elementsPixelRatio&&b.setElementsPixelRatio(c),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const u=await _(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!u){throw null==g||g.set({_forceMount:!1,_exporting:!1}),b.setElementsPixelRatio(m),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}u.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const f=u[0];await b.waitLoading({_skipTimeout:a});const h=f.findOne(".page-container");if(!h){throw b.setElementsPixelRatio(m),null==g||g.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const y=f.position();f.position({x:0,y:0}),f.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),h.find(".page-background").forEach(e=>e.shadowEnabled(!1)),h.find(".page-background").forEach(e=>e.strokeEnabled(!1)),h.find(".highlighter").forEach(e=>e.visible(!1));const v=h.findOne(".page-background-group"),P=v.clip();v.clip({x:null,y:null,width:null,height:null});const E=h.findOne(".elements-container"),x=E.clip();E.clip({x:null,y:null,width:null,height:null});const I=h.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));I.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const k=h.find(e=>e.getAttr("hideInExport"));k.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&h.find(".page-background").forEach(e=>e.hide());const S=n?g.bleed:0;let T=S;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?T=0:r.bleedVisible&&!n&&(T=-g.bleed):T=0);const O=g.computedWidth+2*S,j=g.computedHeight+2*S,R=h.scale();h.scale({x:1,y:1});const F=w(h,{x:h.x()-T,y:h.y()-T,width:O,height:j,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(R);const C=F._canvas;if("image/jpeg"===o){const e=C.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,C.width,C.height),e.restore()}return t&&h.find(".page-background").forEach(e=>e.show()),k.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),I.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".page-background").forEach(e=>e.shadowEnabled(!0)),h.find(".page-background").forEach(e=>e.strokeEnabled(!0)),f.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".highlighter").forEach(e=>e.visible(!0)),v.clip(P),E.clip(x),f.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),b.setElementsPixelRatio(m),C},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await b._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",c=l.toDataURL(d,o);p.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?c:P(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await b._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];m(await b.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await u(),d=e=>x({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var y=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const v=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let P=0;for(const r of v){const t=r.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,r=d(o),l=d(s);let p=0,g=n;for(;p<10;){p+=1;const i=await b.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(i.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++P/a.length*.9),{url:i,width:r,height:l,widthPx:o,heightPx:s}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{y.addPage([t,i],t>i?"landscape":"portrait");const s=y.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){y.setLineWidth(d(1));const e=p+d(m);y.line(e,0,e,p),y.line(0,e,p,e),y.line(t-e,0,t-e,p),y.line(t,e,t-p,e),y.line(0,i-e,p,i-e),y.line(e,i,e,i-p),y.line(t,i-e,t-p,i-e),y.line(t-e,i,t-e,i-p)}y.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await b._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw new Error("No pages found for GIF export")}const n=o[0],a=await f({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of o){const e=Math.max(1,Math.floor(l.duration/s));for(let i=0;i<e;i++){const e=l.startTime+i*s||1;b.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await b._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(o.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return b.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await b.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=b.toJSON();return k({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await b.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=b.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return S({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await b.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await b._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await E()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,c=JSON.parse(JSON.stringify(e)),p=c.schemaVersion||0;p<1&&(v.htmlRenderEnabled||v.renderTagTextEnabled)&&j({children:c.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),p<2&&j({children:c.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),p<3&&(v.htmlRenderEnabled||v.renderTagTextEnabled)&&!d&&j({children:c.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete c.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=c.pages[g]||c.pages[0])||void 0===s?void 0:s.id;c._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,c),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);b.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){b.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=R.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||y.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),y.injectCustomFont(n)):y.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>y.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return b});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return b(e),Store.create({_forceShowCredit:t})}export default createStore;
|
package/model/svg-model.d.ts
CHANGED
|
@@ -151,6 +151,7 @@ export declare const SVGElement: import("mobx-state-tree").IModelType<{
|
|
|
151
151
|
setFilter(type: any, value: any): void;
|
|
152
152
|
} & {
|
|
153
153
|
replaceColor(oldColor: any, newColor: any): void;
|
|
154
|
+
resetColors(): void;
|
|
154
155
|
}, any, import("mobx-state-tree").ModelSnapshotType<{
|
|
155
156
|
id: import("mobx-state-tree").ISimpleType<string>;
|
|
156
157
|
type: import("mobx-state-tree").IType<string | undefined, string, string>;
|
package/model/svg-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{types as e}from"mobx-state-tree";import{Shape as r}from"./shape-model.js";export const SVGElement=r.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,stretchEnabled:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:e.map(e.string)}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource,colorsReplace:Array.isArray(e.colorsReplace)?{}:e.colorsReplace})).actions(e=>({replaceColor(r,o){e.colorsReplace.set(r,o)}}));
|
|
1
|
+
import{types as e}from"mobx-state-tree";import{Shape as r}from"./shape-model.js";export const SVGElement=r.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,stretchEnabled:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:e.map(e.string)}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource,colorsReplace:Array.isArray(e.colorsReplace)?{}:e.colorsReplace})).actions(e=>({replaceColor(r,o){e.colorsReplace.set(r,o)},resetColors(){e.colorsReplace.clear()}}));
|
package/model/table-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{Shape as c}from"./shape-model.js";const d=.05,a=e.enumeration(["solid","dashed","dotted","none"]);function g(e){return t(e,2)}function u(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?g(e)[t]:o}function h(e){return t(e,1)}const f=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(a)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),b=e.model("CellBorders",{top:e.maybe(f),right:e.maybe(f),bottom:e.maybe(f),left:e.maybe(f)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),w=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],p=new Set(w),m=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],C=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],y=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),_={opacity:1,rowSpan:1,colSpan:1,name:""},v=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(b),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of C){o in e&&(t[o]=e[o])}for(const o of w){void 0!==e[o]&&(t[`_${o}`]=e[o])}return t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in _&&l===_[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=g(e),o=h(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=g(e),o=h(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return g(e).page}catch(t){return null}},get fontSize(){return u(e,"fontSize",30)},get fontFamily(){return u(e,"fontFamily","Roboto")},get fontWeight(){return u(e,"fontWeight","normal")},get fontStyle(){return u(e,"fontStyle","normal")},get textDecoration(){return u(e,"textDecoration","")},get textTransform(){return u(e,"textTransform","none")},get fill(){return u(e,"fill","black")},get align(){return u(e,"align","left")},get verticalAlign(){return u(e,"verticalAlign","top")},get lineHeight(){return u(e,"lineHeight",1.2)},get letterSpacing(){return u(e,"letterSpacing",0)},get strokeWidth(){return u(e,"strokeWidth",0)},get stroke(){return u(e,"stroke","black")},get cellBackground(){return u(e,"cellBackground","transparent")},get cellPadding(){return u(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get borderInsets(){if(!l(e)){return{top:0,right:0,bottom:0,left:0}}const o=g(e),r=(e,o)=>{const l=t.getEffectiveBorder(e);return"none"===l.style||0===l.width?0:o?l.width:l.width/2};return{top:r("top",0===t.row),bottom:r("bottom",t.row+e.rowSpan===o.rows),left:r("left",0===t.col),right:r("right",t.col+e.colSpan===o.cols)}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,{top:s,right:i,bottom:c,left:d}=t.borderInsets;return{x:r.x+d+n,y:r.y+s+n,width:Math.max(0,r.width-d-i-2*n),height:Math.max(0,r.height-s-c-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?g(e):null,u=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==u?void 0:u.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==u?void 0:u.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==u?void 0:u.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return v}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&t.fontSize<1&&(t=Object.assign(Object.assign({},t),{fontSize:1}));const o={};for(const[e,l]of Object.entries(t)){p.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:y.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())}}));function I(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of w){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function H(e){return Array.from({length:e},()=>1/e)}function R(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?H(e.length):e.map(e=>e/t)}export const TableElement=c.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){p.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of m){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(H(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(H(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},getRowContentOuterHeight(o){let l=0;for(let r=0;r<e.cols;r++){const n=t.getCell(o,r);if(!n){continue}const s=e._cellContentHeights.get(n.id);if(void 0===s){continue}const i=n.borderInsets,c=s+2*n.cellPadding+i.top+i.bottom;c>l&&(l=c)}return l},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}let l=0;for(let r=0;r<e.rows;r++){l+=t.getRowContentOuterHeight(r)}return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){var o,l;if(0===e._cellContentHeights.size){return null}const r=null!==(o=e._baseHeight)&&void 0!==o?o:e.height,n=null!==(l=e._baseRowHeights)&&void 0!==l?l:[...e.rowHeights];let s=!1;const i=[];for(let d=0;d<e.rows;d++){const o=e.rowHeights[d]*e.height,l=n[d]*r,c=t.getRowContentOuterHeight(d),a=Math.max(c,l);Math.abs(a-o)>1?(i.push(a),s=!0):i.push(o)}if(!s){return null}const c=i.reduce((e,t)=>e+t,0);return{rowHeights:i.map(e=>e/c),height:c}}};return t}).actions(e=>{const t={setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){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 u=0;u<o;u++){r.push(e.rowHeights[u]*l);const t=e.getRowContentOuterHeight(u);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(o){t._resetBaseRowHeights();const l=o>0?o-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let t=0;t<e.rows;t++){s.push(e.rowHeights[t]*e.height/n)}s.splice(o,0,r/n);const i=o>0?o-1:0,c=[];for(let t=0;t<e.cols;t++){c.push(e.cells[i*e.cols+t])}const d=o*e.cols,a=I(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(R(s))},removeRow(o){if(e.rows<=1){return}t._resetBaseRowHeights();const l=o*e.cols,r=[];for(let t=l;t<l+e.cols;t++){r.push(e.cells[t].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(o,1),e.rows-=1,e.rowHeights.replace(R(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=I(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(R(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(R(r))},removeRowRange(o,l){for(let r=l;r>=o&&!(e.rows<=1);r--){t.removeRow(r)}},removeColumnRange(o,l){for(let r=l;r>=o&&!(e.cols<=1);r--){t.removeColumn(r)}},distributeRowsEvenly(){t._resetBaseRowHeights(),e.rowHeights.replace(H(e.rows))},distributeColumnsEvenly(){e.colWidths.replace(H(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<d?(l[t]=d,l[t+1]=r-d):s<d?(l[t+1]=d,l[t]=r-d):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=n>0?e.getRowContentOuterHeight(t)/n:0,i=n>0?e.getRowContentOuterHeight(t+1)/n:0,c=Math.max(d,s),a=Math.max(d,i),g=l[t]+o,u=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):u<a?(l[t+1]=a,l[t]=r-a):(l[t]=g,l[t+1]=u),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(o,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,u="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(u){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||u){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(o,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){t.setCellBorders(e,s,l)}}};return t}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
|
|
1
|
+
import{types as e,getParent as t,getSnapshot as o,isAlive as l,getRoot as r,cast as n}from"mobx-state-tree";import{observable as s}from"mobx";import{nanoid as i}from"nanoid";import{Shape as c}from"./shape-model.js";const d=.05,a=e.enumeration(["solid","dashed","dotted","none"]);function g(e){return t(e,2)}function h(e,t,o){const r=e[`_${t}`];return null!=r?r:l(e)?g(e)[t]:o}function u(e){return t(e,1)}const f=e.model("BorderSide",{color:e.maybe(e.string),width:e.maybe(e.number),style:e.maybe(a)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&(t[o]=l)}return t}),b=e.model("CellBorders",{top:e.maybe(f),right:e.maybe(f),bottom:e.maybe(f),left:e.maybe(f)}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t[o]=l)}return t}),w=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],m=new Set(w),p=["blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","filters","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity"],C=["id","type","text","opacity","rowSpan","colSpan","mergedInto","name","custom","borders"],y=new Set(["row","col","x","y","width","height","rotation","draggable","resizable","selectable","removable","contentEditable","visible","showInExport","alwaysOnTop","backgroundEnabled","backgroundOpacity","backgroundColor","backgroundCornerRadius","backgroundPadding","curveEnabled","curvePower","shadowEnabled","shadowBlur","shadowOffsetX","shadowOffsetY","shadowColor","shadowOpacity","blurEnabled","blurRadius","brightnessEnabled","brightness","sepiaEnabled","grayscaleEnabled","placeholder","animations","filters"]),_={opacity:1,rowSpan:1,colSpan:1,name:""},v=[];export const TableCell=e.model("TableCell",{id:e.identifier,type:e.optional(e.literal("tablecell"),"tablecell"),text:"",_fontSize:e.maybe(e.number),_fontFamily:e.maybe(e.string),_fontWeight:e.maybe(e.string),_fontStyle:e.maybe(e.string),_textDecoration:e.maybe(e.string),_textTransform:e.maybe(e.string),_fill:e.maybe(e.string),_align:e.maybe(e.string),_verticalAlign:e.maybe(e.string),_lineHeight:e.maybe(e.union(e.number,e.string)),_letterSpacing:e.maybe(e.number),_strokeWidth:e.maybe(e.number),_stroke:e.maybe(e.string),_cellBackground:e.maybe(e.string),_cellPadding:e.maybe(e.number),opacity:1,rowSpan:1,colSpan:1,mergedInto:e.maybe(e.string),borders:e.maybe(b),name:"",custom:e.frozen()}).volatile(()=>({_editModeEnabled:!1,filters:s.map()})).preProcessSnapshot(e=>{if(!e){return e}for(const o in e){null===e[o]&&(e[o]=void 0)}const t={};for(const o of C){o in e&&(t[o]=e[o])}for(const o of w){void 0!==e[o]&&(t[`_${o}`]=e[o])}return t}).postProcessSnapshot(e=>{const t={};for(const[o,l]of Object.entries(e)){if(o.startsWith("_")){null!=l&&(t[o.slice(1)]=l)}else if("borders"===o){null!=l&&"object"==typeof l&&Object.keys(l).length>0&&(t.borders=l)}else{if(o in _&&l===_[o]){continue}t[o]=l}}return t}).views(e=>{const t={get row(){if(!l(e)){return 0}const t=g(e),o=u(e).indexOf(e);return-1===o?0:Math.floor(o/t.cols)},get col(){if(!l(e)){return 0}const t=g(e),o=u(e).indexOf(e);return-1===o?0:o%t.cols},get store(){return l(e)?r(e):null},get page(){if(!l(e)){return null}try{return g(e).page}catch(t){return null}},get fontSize(){return h(e,"fontSize",30)},get fontFamily(){return h(e,"fontFamily","Roboto")},get fontWeight(){return h(e,"fontWeight","normal")},get fontStyle(){return h(e,"fontStyle","normal")},get textDecoration(){return h(e,"textDecoration","")},get textTransform(){return h(e,"textTransform","none")},get fill(){return h(e,"fill","black")},get align(){return h(e,"align","left")},get verticalAlign(){return h(e,"verticalAlign","top")},get lineHeight(){return h(e,"lineHeight",1.2)},get letterSpacing(){return h(e,"letterSpacing",0)},get strokeWidth(){return h(e,"strokeWidth",0)},get stroke(){return h(e,"stroke","black")},get cellBackground(){return h(e,"cellBackground","transparent")},get cellPadding(){return h(e,"cellPadding",4)},get width(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).width}catch(o){return 100}},get height(){if(!l(e)){return 100}try{return g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan).height}catch(o){return 100}},get borderInsets(){if(!l(e)){return{top:0,right:0,bottom:0,left:0}}const o=g(e),r=(e,o)=>{const l=t.getEffectiveBorder(e);return"none"===l.style||0===l.width?0:o?l.width:l.width/2};return{top:r("top",0===t.row),bottom:r("bottom",t.row+e.rowSpan===o.rows),left:r("left",0===t.col),right:r("right",t.col+e.colSpan===o.cols)}},get a(){var o;if(!l(e)){return{x:0,y:0,width:100,height:100,rotation:0,opacity:1,fontSize:16}}const r=g(e).getCellRect(t.row,t.col,e.rowSpan,e.colSpan),n=t.cellPadding,{top:s,right:i,bottom:c,left:d}=t.borderInsets;return{x:r.x+d+n,y:r.y+s+n,width:Math.max(0,r.width-d-i-2*n),height:Math.max(0,r.height-s-c-2*n),rotation:0,opacity:null!==(o=e.opacity)&&void 0!==o?o:1,fontSize:t.fontSize}},getEffectiveBorder(t){var o,r,n,s,i,c,d;const a=l(e)?g(e):null,h=null===(o=e.borders)||void 0===o?void 0:o[t];return{color:null!==(n=null!==(r=null==h?void 0:h.color)&&void 0!==r?r:null==a?void 0:a.borderColor)&&void 0!==n?n:"#000000",width:null!==(i=null!==(s=null==h?void 0:h.width)&&void 0!==s?s:null==a?void 0:a.borderWidth)&&void 0!==i?i:1,style:null!==(d=null!==(c=null==h?void 0:h.style)&&void 0!==c?c:null==a?void 0:a.borderStyle)&&void 0!==d?d:"solid"}},get x(){return 0},get y(){return 0},get rotation(){return 0},get draggable(){return!1},get resizable(){return!1},get selectable(){return!1},get removable(){return!1},get contentEditable(){return!0},get visible(){return!0},get showInExport(){return!0},get alwaysOnTop(){return!1},get placeholder(){return""},get backgroundEnabled(){return!1},get backgroundOpacity(){return 1},get backgroundColor(){return"transparent"},get backgroundCornerRadius(){return 0},get backgroundPadding(){return 0},get curveEnabled(){return!1},get curvePower(){return 0},get shadowEnabled(){return!1},get shadowBlur(){return 0},get shadowOffsetX(){return 0},get shadowOffsetY(){return 0},get shadowColor(){return"black"},get shadowOpacity(){return 1},get blurEnabled(){return!1},get blurRadius(){return 0},get brightnessEnabled(){return!1},get brightness(){return 0},get sepiaEnabled(){return!1},get grayscaleEnabled(){return!1},get animations(){return v}};return t}).actions(e=>({toJSON:()=>Object.assign({},o(e)),set(t){null!=t.fontSize&&t.fontSize<1&&(t=Object.assign(Object.assign({},t),{fontSize:1}));const o={};for(const[e,l]of Object.entries(t)){m.has(e)?o[`_${e}`]=l:"borders"===e?o.borders=l?JSON.parse(JSON.stringify(l)):l:y.has(e)||(o[e]=l)}Object.assign(e,o)},setBorder(t,l){const r=e.borders?Object.assign({},o(e.borders)):{},s=r[t]||{},i=Object.assign({},s);void 0!==l.color&&(i.color=l.color),void 0!==l.width&&(i.width=l.width),void 0!==l.style&&(i.style=l.style),r[t]=i,e.borders=n(r)},toggleEditMode(t){const o=null!=t?t:!e._editModeEnabled;o!==e._editModeEnabled&&(e._editModeEnabled=o,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction())}}));function I(e,t){const l=[];for(const r of e){const e={id:i(10),text:""};if(!r){l.push(e);continue}for(const t of w){const o=r[`_${t}`];null!=o&&(e[t]=o)}const n=r.borders;if(n){const l={},r=t?["left","right","top"]:["top","bottom","left"];for(const e of r){const t=n[e];t&&(l[e]=o(t))}Object.keys(l).length>0&&(e.borders=l)}l.push(e)}return l}function H(e){return Array.from({length:e},()=>1/e)}function R(e){const t=e.reduce((e,t)=>e+t,0);return 0===t?H(e.length):e.map(e=>e/t)}export const TableElement=c.named("Table").props({type:"table",width:300,height:200,rows:3,cols:3,colWidths:e.array(e.number),rowHeights:e.array(e.number),cells:e.array(TableCell),borderColor:"#000000",borderWidth:1,borderStyle:e.optional(e.enumeration(["solid","dashed","dotted","none"]),"solid"),fontSize:30,fontFamily:"Roboto",fontWeight:"normal",fontStyle:"normal",textDecoration:"",textTransform:"none",fill:"black",align:"center",verticalAlign:"middle",lineHeight:e.optional(e.union(e.number,e.string),1.2),letterSpacing:0,strokeWidth:0,stroke:"black",cellBackground:"transparent",cellPadding:4}).postProcessSnapshot(e=>{e.cells&&((e=Object.assign({},e)).cells=e.cells.map(t=>{const o={};for(const[l,r]of Object.entries(t)){m.has(l)&&r===e[l]||(o[l]=r)}return o}));for(const t of p){delete e[t]}return e}).volatile(()=>({_focusedCellIds:[],_editingCellId:void 0,_anchorCellId:void 0,_cellContentHeights:s.map(),_baseRowHeights:null,_baseHeight:null})).actions(e=>({afterCreate(){const t=e.rows*e.cols;if(0===e.cells.length){e.cells.replace(function(e,t){const o=[];for(let l=0;l<e*t;l++){o.push({id:i(10),text:""})}return o}(e.rows,e.cols))}else if(e.cells.length<t){for(;e.cells.length<t;){e.cells.push(n({id:i(10),text:""}))}}else{e.cells.length>t&&e.cells.splice(t)}0===e.colWidths.length&&e.colWidths.replace(H(e.cols)),0===e.rowHeights.length&&e.rowHeights.replace(H(e.rows))}})).views(e=>({get _cellMap(){const t=new Map,o=e.cols;return e.cells.forEach((e,l)=>{t.set(`${Math.floor(l/o)}:${l%o}`,e)}),t},getActualRowHeight:t=>e.rowHeights[t]*e.height})).views(e=>{const t={getCell:(t,o)=>e._cellMap.get(`${t}:${o}`),get minWidth(){return 20*e.cols},getRowContentOuterHeight(o){let l=0;for(let r=0;r<e.cols;r++){const n=t.getCell(o,r);if(!n){continue}const s=e._cellContentHeights.get(n.id);if(void 0===s){continue}const i=n.borderInsets,c=s+2*n.cellPadding+i.top+i.bottom;c>l&&(l=c)}return l},get minHeight(){const o=20*e.rows;if(0===e._cellContentHeights.size){return o}let l=0;for(let r=0;r<e.rows;r++){l+=t.getRowContentOuterHeight(r)}return Math.max(o,l)},get actualHeight(){let t=0;for(let o=0;o<e.rows;o++){t+=e.getActualRowHeight(o)}return t},getCellRect(t,o,l=1,r=1){let n=0;for(let d=0;d<o;d++){n+=e.colWidths[d]*e.width}let s=0;for(let d=0;d<t;d++){s+=e.getActualRowHeight(d)}let i=0;for(let d=o;d<o+r;d++){i+=(e.colWidths[d]||0)*e.width}let c=0;for(let d=t;d<t+l;d++){c+=e.getActualRowHeight(d)}return{x:n,y:s,width:i,height:c}},get visibleCells(){return e.cells.filter(e=>!e.mergedInto)},get focusedCells(){return e.cells.filter(t=>e._focusedCellIds.includes(t.id))},get editingCell(){if(e._editingCellId){return e.cells.find(t=>t.id===e._editingCellId)}},getFocusedCellRange(){if(0===e._focusedCellIds.length){return null}let t=1/0,o=-1/0,l=1/0,r=-1/0;const n=new Set(e._focusedCellIds);for(const s of e.cells){n.has(s.id)&&(s.row<t&&(t=s.row),s.row>o&&(o=s.row),s.col<l&&(l=s.col),s.col>r&&(r=s.col))}return t===1/0?null:{minRow:t,maxRow:o,minCol:l,maxCol:r}},get _fitRowsToContent(){var o,l;if(0===e._cellContentHeights.size){return null}const r=null!==(o=e._baseHeight)&&void 0!==o?o:e.height,n=null!==(l=e._baseRowHeights)&&void 0!==l?l:[...e.rowHeights];let s=!1;const i=[];for(let d=0;d<e.rows;d++){const o=e.rowHeights[d]*e.height,l=n[d]*r,c=t.getRowContentOuterHeight(d),a=Math.max(c,l);Math.abs(a-o)>1?(i.push(a),s=!0):i.push(o)}if(!s){return null}const c=i.reduce((e,t)=>e+t,0);return{rowHeights:i.map(e=>e/c),height:c}}};return t}).actions(e=>{const t={setCellContentHeight(t,o){e._cellContentHeights.set(t,o)},_applyFitRowsToContent(){if(!l(e)){return}null===e._baseRowHeights&&(e._baseRowHeights=[...e.rowHeights],e._baseHeight=e.height);const t=e._fitRowsToContent;t&&(e.height=t.height,e.rowHeights.replace(t.rowHeights))},focusCell(t,o=!1){o?e._focusedCellIds.includes(t)||(e._focusedCellIds=[...e._focusedCellIds,t]):(e._focusedCellIds=[t],e._anchorCellId=t)},selectRowRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.rows-1,Math.max(t,o)),n=[];for(let s=l;s<=r;s++){for(let t=0;t<e.cols;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectColumnRange(t,o){const l=Math.max(0,Math.min(t,o)),r=Math.min(e.cols-1,Math.max(t,o)),n=[];for(let s=0;s<e.rows;s++){for(let t=l;t<=r;t++){const o=e.getCell(s,t);o&&n.push(o.id)}}e._focusedCellIds=n,e._anchorCellId=n[0]},selectRow(e){t.selectRowRange(e,e)},selectColumn(e){t.selectColumnRange(e,e)},focusCellRange(t,o){const l=e.cells.find(t=>t.id===e._anchorCellId);if(!l){return}const r=Math.min(l.row,t),n=Math.max(l.row,t),s=Math.min(l.col,o),i=Math.max(l.col,o),c=[];for(const d of e.cells){d.row>=r&&d.row<=n&&d.col>=s&&d.col<=i&&c.push(d.id)}e._focusedCellIds=c},clearCellFocus(){if(l(e)){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._focusedCellIds=[],e._editingCellId=void 0,e._anchorCellId=void 0}},enterCellEdit(t){e._editingCellId=t,e._focusedCellIds.includes(t)||(e._focusedCellIds=[t]);const o=e.cells.find(e=>e.id===t);o&&o.toggleEditMode(!0)},exitCellEdit(){if(e._editingCellId){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1)}e._editingCellId=void 0},_resetBaseRowHeights(){e._baseRowHeights=null,e._baseHeight=null},setHeightRedistribute(t){const o=e.rows;if(0===o||t<=0){return void(e.height=t)}const l=e.height;if(l<=0||t>=l){return void(e.height=t)}const r=[],n=[];let s=0;for(let h=0;h<o;h++){r.push(e.rowHeights[h]*l);const t=e.getRowContentOuterHeight(h);n.push(t),s+=t}if(t<=s||s<=0){return void(e.height=t)}const i=t-s;let c=0;const d=[];for(let e=0;e<o;e++){const t=Math.max(0,r[e]-n[e]);d.push(t),c+=t}const a=[];if(c<=0){const e=t/l;for(let t=0;t<o;t++){a.push(r[t]*e)}}else{for(let e=0;e<o;e++){a.push(n[e]+d[e]/c*i)}}const g=a.map(e=>e/t);e.height=t,e.rowHeights.replace(g)},addRow(o){t._resetBaseRowHeights();const l=o>0?o-1:0,r=(e.rowHeights[l]||1/(e.rows+1))*e.height,n=e.height+r,s=[];for(let t=0;t<e.rows;t++){s.push(e.rowHeights[t]*e.height/n)}s.splice(o,0,r/n);const i=o>0?o-1:0,c=[];for(let t=0;t<e.cols;t++){c.push(e.cells[i*e.cols+t])}const d=o*e.cols,a=I(c,!0);e.cells.splice(d,0,...a),e.rows+=1,e.height=n,e.rowHeights.replace(R(s))},removeRow(o){if(e.rows<=1){return}t._resetBaseRowHeights();const l=o*e.cols,r=[];for(let t=l;t<l+e.cols;t++){r.push(e.cells[t].id)}if(e._editingCellId&&r.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!r.includes(e)),r.forEach(t=>e._cellContentHeights.delete(t)),e.cells.splice(l,e.cols);const n=[...e.rowHeights];n.splice(o,1),e.rows-=1,e.rowHeights.replace(R(n))},addColumn(t){const o=t>0?t-1:0,l=(e.colWidths[o]||1/(e.cols+1))*e.width,r=e.width+l,s=[];for(let n=0;n<e.cols;n++){s.push(e.colWidths[n]*e.width/r)}s.splice(t,0,l/r);const i=e.cols,c=t>0?t-1:0,d=[];for(let n=0;n<e.rows;n++){d.push(e.cells[n*i+c])}const a=I(d,!1);for(let g=e.rows-1;g>=0;g--){e.cells.splice(g*i+t,0,n(a[g]))}e.cols+=1,e.width=r,e.colWidths.replace(R(s))},removeColumn(t){if(e.cols<=1){return}const o=e.cols,l=[];for(let n=0;n<e.rows;n++){l.push(e.cells[n*o+t].id)}if(e._editingCellId&&l.includes(e._editingCellId)){const t=e.cells.find(t=>t.id===e._editingCellId);t&&t.toggleEditMode(!1),e._editingCellId=void 0}e._focusedCellIds=e._focusedCellIds.filter(e=>!l.includes(e)),l.forEach(t=>e._cellContentHeights.delete(t));for(let n=e.rows-1;n>=0;n--){e.cells.splice(n*o+t,1)}const r=[...e.colWidths];r.splice(t,1),e.cols-=1,e.colWidths.replace(R(r))},removeRowRange(o,l){for(let r=l;r>=o&&!(e.rows<=1);r--){t.removeRow(r)}},removeColumnRange(o,l){for(let r=l;r>=o&&!(e.cols<=1);r--){t.removeColumn(r)}},distributeRowsEvenly(){const o=e.rows;let l=20;for(let t=0;t<o;t++){l=Math.max(l,e.getRowContentOuterHeight(t))}t._resetBaseRowHeights(),e.height=Math.max(e.height,l*o),e.rowHeights.replace(H(o))},distributeColumnsEvenly(){e.colWidths.replace(H(e.cols))},resizeColumn(t,o){if(t>=e.cols-1){return}const l=[...e.colWidths],r=l[t]+l[t+1],n=l[t]+o,s=l[t+1]-o;n<d?(l[t]=d,l[t+1]=r-d):s<d?(l[t+1]=d,l[t]=r-d):(l[t]=n,l[t+1]=s),e.colWidths.replace(l)},resizeRow(t,o){if(t>=e.rows-1){return}const l=[...e.rowHeights],r=l[t]+l[t+1],n=e.height,s=n>0?e.getRowContentOuterHeight(t)/n:0,i=n>0?e.getRowContentOuterHeight(t+1)/n:0,c=Math.max(d,s),a=Math.max(d,i),g=l[t]+o,h=l[t+1]-o;g<c?(l[t]=c,l[t+1]=r-c):h<a?(l[t+1]=a,l[t]=r-a):(l[t]=g,l[t+1]=h),e.rowHeights.replace(l)},setCellBorders(t,o,l){const r={top:{side:"bottom",dr:-1,dc:0},bottom:{side:"top",dr:1,dc:0},left:{side:"right",dr:0,dc:-1},right:{side:"left",dr:0,dc:1}};for(const n of t){const t=e.cells.find(e=>e.id===n);if(t){for(const n of o){t.setBorder(n,l);const o=r[n],s=t.row+o.dr,i=t.col+o.dc,c=e.getCell(s,i);c&&c.setBorder(o.side,l)}}}},applyBorderMode(o,l){var r;const n=function(e,t,o){const{minRow:l,maxRow:r,minCol:n,maxCol:s}=t,i=(e,t,l,r)=>{const n=[];for(let s=e;s<=t;s++){for(let e=l;e<=r;e++){const t=o(s,e);t&&n.push(t.id)}}return n};if("all"===e){return[{cellIds:i(l,r,n,s),sides:["top","right","bottom","left"]}]}const c=[],d="outer"===e||"topOnly"===e||"topBottom"===e,a="outer"===e||"bottomOnly"===e||"topBottom"===e,g="outer"===e||"leftOnly"===e,h="outer"===e||"rightOnly"===e;if(d){const e=i(l,l,n,s);e.length&&c.push({cellIds:e,sides:["top"]})}if(a){const e=i(r,r,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(g){const e=i(l,r,n,n);e.length&&c.push({cellIds:e,sides:["left"]})}if(h){const e=i(l,r,s,s);e.length&&c.push({cellIds:e,sides:["right"]})}if(d||a||g||h){return c}if(("inner"===e||"innerHorizontal"===e)&&r>l){const e=i(l,r-1,n,s);e.length&&c.push({cellIds:e,sides:["bottom"]})}if(("inner"===e||"innerVertical"===e)&&s>n){const e=i(l,r,n,s-1);e.length&&c.push({cellIds:e,sides:["right"]})}return c}(o,null!==(r=e.getFocusedCellRange())&&void 0!==r?r:{minRow:0,maxRow:e.rows-1,minCol:0,maxCol:e.cols-1},(t,o)=>e.getCell(t,o));for(const{cellIds:e,sides:s}of n){t.setCellBorders(e,s,l)}}};return t}).actions(e=>({clone(t={},{skipSelect:o=!1}={}){const l=JSON.parse(JSON.stringify(e.toJSON()));if(t.id=t.id||i(10),l.cells){const e=new Map;l.cells.forEach(t=>{const o=t.id,l=i(10);e.set(o,l),t.id=l}),l.cells.forEach(t=>{t.mergedInto&&e.has(t.mergedInto)&&(t.mergedInto=e.get(t.mergedInto))})}return Object.assign(l,t),e.page.addElement(l,{skipSelect:o})}}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno",
|
|
3
|
-
"version": "4.0.0
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Design Editor Framework",
|
|
5
5
|
"author": "Anton Lavrenov",
|
|
6
6
|
"keywords": [
|
|
@@ -94,13 +94,14 @@
|
|
|
94
94
|
"./polotno.blueprint.css": "./blueprint.polotno.css"
|
|
95
95
|
},
|
|
96
96
|
"dependencies": {
|
|
97
|
+
"@base-ui/react": "^1.5.0",
|
|
97
98
|
"class-variance-authority": "^0.7.1",
|
|
98
99
|
"clsx": "^2.1.1",
|
|
99
100
|
"gifuct-js": "^2.1.2",
|
|
100
101
|
"gradient-parser": "^1.2.0",
|
|
101
102
|
"konva": "^10.3.0",
|
|
102
103
|
"lodash-es": "^4.18.1",
|
|
103
|
-
"lucide-react": "^1.
|
|
104
|
+
"lucide-react": "^1.18.0",
|
|
104
105
|
"mediabunny": "^1.46.0",
|
|
105
106
|
"mensch": "^0.3.4",
|
|
106
107
|
"mobx": "6.16.1",
|
|
@@ -108,8 +109,6 @@
|
|
|
108
109
|
"mobx-state-tree": "7.2.0",
|
|
109
110
|
"nanoid": "^5.1.11",
|
|
110
111
|
"quill": "^2.0.3",
|
|
111
|
-
"radix-ui": "^1.5.0",
|
|
112
|
-
"rasterizehtml": "^1.4.1",
|
|
113
112
|
"react-konva": "^19.2.5",
|
|
114
113
|
"react-konva-utils": "^2.0.0",
|
|
115
114
|
"react-sortablejs": "6.1.4",
|
|
@@ -173,17 +172,13 @@
|
|
|
173
172
|
"@blueprintjs/icons": "^6.11.0",
|
|
174
173
|
"@blueprintjs/select": "6.3.0",
|
|
175
174
|
"@canvas/image": "^2.0.0",
|
|
176
|
-
"@polotno/video-export": "^0.0.11",
|
|
177
175
|
"@size-limit/preset-big-lib": "^12.1.0",
|
|
178
|
-
"@tailwindcss/cli": "^4.3.
|
|
179
|
-
"@tailwindcss/vite": "^4.3.
|
|
176
|
+
"@tailwindcss/cli": "^4.3.1",
|
|
177
|
+
"@tailwindcss/vite": "^4.3.1",
|
|
180
178
|
"@testing-library/dom": "^10.4.1",
|
|
181
|
-
"@testing-library/jest-dom": "^6.9.1",
|
|
182
179
|
"@testing-library/react": "^16.3.2",
|
|
183
180
|
"@types/gradient-parser": "^1.1.0",
|
|
184
|
-
"@types/jest": "^30",
|
|
185
181
|
"@types/react": "^19.2.17",
|
|
186
|
-
"@types/sanitize-html": "^2.16.1",
|
|
187
182
|
"@vitejs/plugin-react": "^6.0.2",
|
|
188
183
|
"@vitest/browser": "^4.1.8",
|
|
189
184
|
"@vitest/browser-playwright": "^4.1.8",
|
|
@@ -196,24 +191,18 @@
|
|
|
196
191
|
"jest-file-snapshot": "^0.7.0",
|
|
197
192
|
"jsdom": "^29.1.1",
|
|
198
193
|
"license-checker": "^25.0.1",
|
|
199
|
-
"parcel": "2.16.4",
|
|
200
|
-
"path-browserify": "^1.0.1",
|
|
201
194
|
"playwright": "^1.60.0",
|
|
202
|
-
"postcss-selector-parser": "^7.1.
|
|
195
|
+
"postcss-selector-parser": "^7.1.4",
|
|
203
196
|
"pptxgenjs": "^4.0.1",
|
|
204
197
|
"process": "^0.11.10",
|
|
205
|
-
"punycode": "^2.3.1",
|
|
206
|
-
"querystring-es3": "^0.2.1",
|
|
207
198
|
"react": "^19.2.7",
|
|
208
199
|
"react-dom": "^19.2.7",
|
|
209
200
|
"size-limit": "^12.1.0",
|
|
210
201
|
"skia-canvas": "^3.0.8",
|
|
211
|
-
"tailwindcss": "^4.3.
|
|
202
|
+
"tailwindcss": "^4.3.1",
|
|
212
203
|
"terser": "^5.48.0",
|
|
213
|
-
"ts-jest": "^29",
|
|
214
204
|
"tw-animate-css": "^1.4.0",
|
|
215
205
|
"typescript": "^6.0.3",
|
|
216
|
-
"uglifyjs-folder": "^3.3.0",
|
|
217
206
|
"vitest": "^4.1.8"
|
|
218
207
|
},
|
|
219
208
|
"homepage": "https://polotno.com/",
|
|
@@ -221,7 +210,8 @@
|
|
|
221
210
|
"start": "vite",
|
|
222
211
|
"clean": "rm -rf ./lib && rm -rf ./.pn-build",
|
|
223
212
|
"prefix-build": "node build/prefix-build.cjs",
|
|
224
|
-
"tsc": "tsc --project tsconfig.lib.json --removeComments --sourceMap false
|
|
213
|
+
"tsc": "tsc --project tsconfig.lib.json --removeComments --sourceMap false",
|
|
214
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
225
215
|
"build:css": "tailwindcss -i ./.pn-build/ui.css -o ./lib/ui.css --minify && node build/rename-keyframes.cjs ./lib/ui.css",
|
|
226
216
|
"check:css": "node build/check-css-hygiene.cjs ./lib/ui.css",
|
|
227
217
|
"check:agreement": "node build/check-agreement.cjs ./lib/ui.css ./lib/toolbar ./lib/side-panel ./lib/pages-timeline ./lib/primitives ./lib/canvas",
|
|
@@ -229,13 +219,12 @@
|
|
|
229
219
|
"test:parity": "npm run check:parity && npm run check:agreement && npm run check:css",
|
|
230
220
|
"minify": "node minify.cjs",
|
|
231
221
|
"build:schema": "node scripts/generate-schema.cjs",
|
|
232
|
-
"build": "npm run clean && npm run prefix-build && npm run tsc && npm run add_version && node rename-imports.js && npm run minify && npm run build:css && npm run check:css && npm run check:agreement && npm run build:bundle && node blueprint-scope.js && cp ./src/fonts.css ./lib/fonts.css && mkdir -p ./lib/themes && cp ./src/themes/blueprint.css ./lib/themes/blueprint.css && cp ./package.json ./lib && cp ./README.md ./lib && cp ./LICENSE.md ./lib && npm run remove-test-from-lib && npm run build:schema",
|
|
222
|
+
"build": "npm run typecheck && npm run clean && npm run prefix-build && npm run tsc && npm run add_version && node rename-imports.js && npm run minify && npm run build:css && npm run check:css && npm run check:agreement && npm run build:bundle && node blueprint-scope.js && cp ./src/fonts.css ./lib/fonts.css && mkdir -p ./lib/themes && cp ./src/themes/blueprint.css ./lib/themes/blueprint.css && cp ./package.json ./lib && cp ./README.md ./lib && cp ./LICENSE.md ./lib && npm run remove-test-from-lib && npm run build:schema",
|
|
233
223
|
"remove-test-from-lib": "find ./lib -type d -name \"__tests__\" -exec rm -rf {} + && find ./lib \\( -name \"*.test.js\" -o -name \"*.test.d.ts\" \\) -type f -delete",
|
|
234
224
|
"add_version": "sed -i.bak 's/SDK_VERSION/'$npm_package_version'/' ./lib/utils/validate-key.js && rm -f ./lib/utils/validate-key.js.bak",
|
|
235
225
|
"build:bundle": "vite build && find ./lib -name '*.js.map' -type f -delete",
|
|
236
226
|
"size": "npm run build && size-limit",
|
|
237
|
-
"test": "vitest"
|
|
238
|
-
"test:watch": "jest --watch"
|
|
227
|
+
"test": "vitest"
|
|
239
228
|
},
|
|
240
229
|
"license": "SEE LICENSE IN LICENSE.md"
|
|
241
230
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var n={};for(var
|
|
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 s}from"../icons/registry.js";import{t as a}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{Spinner as u}from"./spinner.js";import{useWaveformData as h,useWaveformPath as v}from"./waveform.js";import{TrackWrapper as f,TrackContainer as x,TrackMenu as y,TrackMenuButton as M,TrackHandleLeft as w,TrackHandleRight as g,WaveformSvg as T}from"./track-styles.js";export const AUDIO_ROW_HEIGHT=28;export const AUDIO_TRACK_HEIGHT=24;const b=({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:j,store:I,index:O})=>{const[D,E]=i.useState(1),A=0===o.volume,L=()=>{A?o.set({volume:D>0?D:1}):(E(o.volume),o.set({volume:0}))},N=(e=o.startTime,t=o.endTime)=>Math.max(0,(t-e)*(o.duration||0)),P=e=>Math.max(0,I.duration-e),S=(e,t=N())=>Math.min(Math.max(0,e),P(t)),_=N(),C=I.duration*j-o.delay*j,X=Math.min(_*j,C),k=o.delay*j,{data:z,isLoading:H}=h(o.src),$=o.visibleDuration*j,R=v(z,20).path,V=(e,t)=>{e.stopPropagation(),e.preventDefault();const n=e.clientX,i=k,s=X,a=o.endTime,r=o.startTime,l=o.delay,m=o.duration||1,d=e=>{e.preventDefault();const d=(e.clientX-n)/j;if("start"===t){if(d>=0){const e=d,t=Math.max(0,a-.1-r)*m,n=Math.min(e,t);if(n<=0){return}let i=r+n/m;const s=(o.endTime-i)*m,p=l+n,c=P(s);let u=Math.min(Math.max(0,p),c);const h=b({position:u,store:I,scale:j});u=Math.min(Math.max(0,null!=h?h:u),c);const v=u-p;i=Math.min(o.endTime-.1,Math.max(0,i+v/m)),o.set({delay:u,startTime:i})}else{const e=-d,t=r*m,n=Math.min(e,t);if(n<=0){return}const i=n/m;let s=Math.max(0,r-i);const a=(o.endTime-s)*m,p=l-n,c=P(a);let u=Math.min(Math.max(0,p),c);const h=b({position:u,store:I,scale:j});u=Math.min(Math.max(0,null!=h?h:u),c);const v=u-p;s=Math.max(0,Math.min(o.endTime-.1,s+v/m)),o.set({delay:u,startTime:s})}}else{const e=i/j+s/j;let t=e+d;const n=b({position:t,store:I,scale:j});t=null!=n?n:t;const r=(t-e)/o.duration,l=Math.min(1,Math.max(o.startTime+.1,a+r));o.set({endTime:l})}},p=()=>{if(window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",p),"start"===t){const e=b({position:o.delay,store:I,scale:j});if(null!=e&&e!==o.delay){const t=N(o.startTime,o.endTime),n=S(e,t),i=n-o.delay,s=Math.max(0,Math.min(o.endTime-.1,o.startTime+i/m));o.set({delay:n,startTime:s})}}};window.addEventListener("mousemove",d),window.addEventListener("mouseup",p)};return t(f,{style:{left:`${k}px`,top:28*O+"px",width:`${X}px`,height:"24px"},className:"polotno-audio-container",children:n(x,{style:{width:"100%",height:"100%"},onMouseDown:e=>{const t=e.clientX,n=k;e.preventDefault();const i=e=>{e.preventDefault();const i=(e.clientX-t)/j;let s=n/j+i;const a=s+_,r=b({position:s,store:I,scale:j}),l=b({position:a,store:I,scale:j}),m=null!==r?Math.abs(s-r):Number.POSITIVE_INFINITY,d=null!==l?Math.abs(a-l):Number.POSITIVE_INFINITY;let p;p=S(null!==r&&m<d?r:null!==l?l-_:s),o.set({delay:S(p)})},s=()=>{window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},children:[t("div",{style:{position:"absolute",left:"4px",top:"50%",transform:"translateY(-50%)",zIndex:10,pointerEvents:"auto"},onClick:e=>{e.stopPropagation(),L()},onMouseDown:e=>e.stopPropagation(),children:t(s,A?{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:[R&&t("div",{style:{flex:1,height:"14px",overflow:"hidden",opacity:A?.4:1},children:t(T,{width:$,height:"14",viewBox:`0 0 ${$} 20`,preserveAspectRatio:"none",style:{width:$+"px",height:"14px",transform:`translateX(-${o.startTime*$}px)`},children:t("path",{d:R})})}),H&&t("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:t(u,{})})]})}),t(w,{onMouseDown:e=>V(e,"start")}),t(g,{onMouseDown:e=>V(e,"end")}),t(y,{onClick:e=>{e.stopPropagation()},onMouseDown:e=>e.stopPropagation(),children:n(l,{children:[t(M,{}),n(m,{side:"top",style:{width:"180px"},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:a("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&&E(t),o.set({volume:t})})(r(e))})]}),t(p,{}),n(d,{onSelect:e=>{e.preventDefault(),L()},children:[t(s,A?{name:"action.unmuted"}:{name:"action.muted"}),a(A?"pagesTimeline.unmuteAudio":"pagesTimeline.muteAudio")]}),n(d,{onSelect:t=>{t.preventDefault(),(()=>{const t=o.toJSON(),n=o.visibleDuration,i=o.delay+n,s=I.duration-i;let a=o.delay;s>=n?a=i:s>0&&(a=Math.max(0,I.duration-n));const{id:r}=t,l=e(t,["id"]);I.addAudio(Object.assign(Object.assign({},l),{delay:a}))})()},children:[t(s,{name:"action.duplicate"}),a("pagesTimeline.duplicateAudio")]}),t(p,{}),n(d,{onSelect:e=>{e.preventDefault(),I.removeAudio(o.id)},children:[t(s,{name:"action.remove"}),a("pagesTimeline.removeAudio")]})]})]})})]})})});
|
|
@@ -5,7 +5,7 @@ interface CurrentTimeProps {
|
|
|
5
5
|
store: StoreType;
|
|
6
6
|
scale: number;
|
|
7
7
|
variant?: Variant;
|
|
8
|
-
dragAreaRef?: React.RefObject<HTMLElement>;
|
|
8
|
+
dragAreaRef?: React.RefObject<HTMLElement | null>;
|
|
9
9
|
}
|
|
10
10
|
export declare const CurrentTime: (({ store, scale, variant, dragAreaRef }: CurrentTimeProps) => React.JSX.Element) & {
|
|
11
11
|
displayName: string;
|
|
@@ -3,7 +3,7 @@ import type { PageType } from '../ui-types.js';
|
|
|
3
3
|
export declare const usePagePreview: ({ page, setPreview, groupRef, }: {
|
|
4
4
|
page: PageType;
|
|
5
5
|
setPreview: (src: string | null) => void;
|
|
6
|
-
groupRef: React.RefObject<HTMLDivElement>;
|
|
6
|
+
groupRef: React.RefObject<HTMLDivElement | null>;
|
|
7
7
|
}) => void;
|
|
8
8
|
export declare const PagePreview: (({ page, scale }: {
|
|
9
9
|
page: PageType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,r){var a={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(a[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var t=0;for(n=Object.getOwnPropertySymbols(e);t<n.length;t++){r.indexOf(n[t])<0&&Object.prototype.propertyIsEnumerable.call(e,n[t])&&(a[n[t]]=e[n[t]])}}return a};import{jsx as r}from"react/jsx-runtime";import a from"react";import{PolotnoIcon as n}from"../icons/registry.js";import{cn as t}from"../lib/utils.js";import{Button as s}from"../primitives/button.js";import{DropdownMenuTrigger as o}from"../primitives/dropdown-menu.js";export const TrackLabel=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("div",Object.assign({ref:n,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]",s)},o))});TrackLabel.displayName="TrackLabel";export const WaveformSvg=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("svg",Object.assign({ref:n,className:t("pn:[&_path]:fill-black/50 pn:dark:[&_path]:fill-white/70",s)},o))});WaveformSvg.displayName="WaveformSvg";export const TrackWrapper=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("div",Object.assign({ref:n,className:t("pn:absolute pn:[&:hover_.polotno-track-menu]:pointer-events-auto pn:[&:hover_.polotno-track-menu]:opacity-100",s)},o))});TrackWrapper.displayName="TrackWrapper";export const TrackContainer=a.forwardRef((a,n)=>{var{className:s,style:o}=a,p=e(a,["className","style"]);return r("div",Object.assign({ref:n,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",s),style:o},p))});TrackContainer.displayName="TrackContainer";export const TrackMenu=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("div",Object.assign({ref:n,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",s)},o))});TrackMenu.displayName="TrackMenu";export const TrackMenuButton=()=>r(o,{
|
|
1
|
+
var e=this&&this.__rest||function(e,r){var a={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(a[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var t=0;for(n=Object.getOwnPropertySymbols(e);t<n.length;t++){r.indexOf(n[t])<0&&Object.prototype.propertyIsEnumerable.call(e,n[t])&&(a[n[t]]=e[n[t]])}}return a};import{jsx as r}from"react/jsx-runtime";import a from"react";import{PolotnoIcon as n}from"../icons/registry.js";import{cn as t}from"../lib/utils.js";import{Button as s}from"../primitives/button.js";import{DropdownMenuTrigger as o}from"../primitives/dropdown-menu.js";export const TrackLabel=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("div",Object.assign({ref:n,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]",s)},o))});TrackLabel.displayName="TrackLabel";export const WaveformSvg=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("svg",Object.assign({ref:n,className:t("pn:[&_path]:fill-black/50 pn:dark:[&_path]:fill-white/70",s)},o))});WaveformSvg.displayName="WaveformSvg";export const TrackWrapper=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("div",Object.assign({ref:n,className:t("pn:absolute pn:[&:hover_.polotno-track-menu]:pointer-events-auto pn:[&:hover_.polotno-track-menu]:opacity-100",s)},o))});TrackWrapper.displayName="TrackWrapper";export const TrackContainer=a.forwardRef((a,n)=>{var{className:s,style:o}=a,p=e(a,["className","style"]);return r("div",Object.assign({ref:n,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",s),style:o},p))});TrackContainer.displayName="TrackContainer";export const TrackMenu=a.forwardRef((a,n)=>{var{className:s}=a,o=e(a,["className"]);return r("div",Object.assign({ref:n,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",s)},o))});TrackMenu.displayName="TrackMenu";export const TrackMenuButton=()=>r(o,{render:r(s,{variant:"secondary",size:"icon-sm",style:{minHeight:"20px",borderRadius:"10px"},children:r(n,{name:"action.more",className:"pn:size-4"})})});TrackMenuButton.displayName="TrackMenuButton";const p=a.forwardRef((a,n)=>{var{className:s,side:o}=a,p=e(a,["className","side"]);return r("div",Object.assign({ref:n,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",s)},p))});p.displayName="TrackHandleBase";export const TrackHandleLeft=a.forwardRef((e,a)=>r(p,Object.assign({ref:a,side:"left"},e)));TrackHandleLeft.displayName="TrackHandleLeft";export const TrackHandleRight=a.forwardRef((e,a)=>r(p,Object.assign({ref:a,side:"right"},e)));TrackHandleRight.displayName="TrackHandleRight";
|