polotno 2.36.0 → 2.36.2

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/canvas/page.js CHANGED
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var n={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++){t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}}return n};import t from"react";import{observer as n,useLocalObservable as i}from"mobx-react-lite";import{action as o,runInAction as r}from"mobx";import{Group as l,Image as a,Label as s,Layer as c,Line as d,Rect as m,Stage as h,Tag as u,Text as g,Transformer as x}from"react-konva";import p from"use-image";import f from"konva";import b from"./element.js";import{DrawingLayer as v}from"./drawing-layer.js";import{ensureDragOrder as y,useSnap as E}from"./use-transformer-snap.js";import{useImageLoader as w}from"./image-element.js";import{getCrop as Y}from"../utils/crop.js";import{___ as X,isCreditVisible as S}from"../utils/validate-key.js";import{getClientRect as k,getTotalClientRect as A}from"../utils/math.js";import{pxToUnitRounded as R,pxToUnitString as C}from"../utils/unit.js";import{flags as M}from"../utils/flags.js";import{isTouchDevice as O}from"../utils/screen.js";import{useColor as P}from"./use-color.js";import{isGradient as L}from"../utils/gradient.js";import{Html as T}from"react-konva-utils";const j=f.DD._drag;window.removeEventListener("mousemove",j),f.DD._drag=function(e){r(()=>{j.call(this,e)})},window.addEventListener("mousemove",f.DD._drag);const I=new f.Group,D=20;I.add(new f.Rect({width:D,height:D,fill:"white"})),I.add(new f.Path({scaleX:D/24,scaleY:D/24,data:"M4.98313549,11.0001422 C5.49589839,10.9914935 5.92501998,11.3703506 5.99116425,11.8666444 L5.99985778,11.9831355 L6.00348884,12.2068855 C6.11245031,15.4321748 8.76323537,17.9999971 11.9999971,17.9999971 C12.1869612,17.9999971 12.3726725,17.9914753 12.5567465,17.9745765 L12.2928932,17.7071068 C11.9023689,17.3165825 11.9023689,16.6834175 12.2928932,16.2928932 C12.6834175,15.9023689 13.3165825,15.9023689 13.7071068,16.2928932 L15.7071068,18.2928932 C16.0976311,18.6834175 16.0976311,19.3165825 15.7071068,19.7071068 L13.7071068,21.7071068 C13.3165825,22.0976311 12.6834175,22.0976311 12.2928932,21.7071068 C11.9023689,21.3165825 11.9023689,20.6834175 12.2928932,20.2928932 L12.6111505,19.9769552 C12.4086045,19.9922816 12.2047796,19.9999971 11.9999971,19.9999971 C7.7687005,19.9999971 4.28886152,16.7094374 4.01666425,12.5105203 L4.00420123,12.2575143 L4.00014222,12.0168645 C3.9908282,11.4646583 4.43092928,11.0094562 4.98313549,11.0001422 Z M11.7071068,2.29289322 C12.0675907,2.65337718 12.0953203,3.22060824 11.7902954,3.61289944 L11.7071068,3.70710678 L11.3891629,4.0230186 C11.5916051,4.00770767 11.7953244,4 12,4 C16.418278,4 20,7.581722 20,12 C20,12.5522847 19.5522847,13 19,13 C18.4477153,13 18,12.5522847 18,12 C18,8.6862915 15.3137085,6 12,6 C11.8129339,6 11.6271216,6.00853145 11.4429483,6.02544919 L11.7071068,6.29289322 C12.0976311,6.68341751 12.0976311,7.31658249 11.7071068,7.70710678 C11.3466228,8.06759074 10.7793918,8.09532028 10.3871006,7.79029539 L10.2928932,7.70710678 L8.29289322,5.70710678 C7.93240926,5.34662282 7.90467972,4.77939176 8.20970461,4.38710056 L8.29289322,4.29289322 L10.2928932,2.29289322 C10.6834175,1.90236893 11.3165825,1.90236893 11.7071068,2.29289322 Z",fill:"black"}));const W=I.toCanvas({pixelRatio:2,width:D,height:D});export const TRANSFORMER_STYLE={enabledAnchors:["top-left","top-center","top-right","middle-left","bottom-left","bottom-right","bottom-center","middle-right"],borderEnabled:!0,rotateEnabled:!0,rotationSnaps:[0,45,90,135,180,225,270,315],ignoreStroke:!0,flipEnabled:!1,anchorStrokeWidth:2,borderStrokeWidth:2,rotateAnchorOffset:30,anchorStyleFunc:e=>{if(e.hasName("rotater")){const t=20;e.setAttrs({width:t,height:t,cornerRadius:t/2,offsetX:t/2,offsetY:t/2,fillPatternImage:W,fillPatternScaleX:t/D/2,fillPatternScaleY:t/D/2,fillPriority:"pattern",fillPatternRepeat:"no-repeat"})}}};export const setTransformerStyle=e=>{Object.assign(TRANSFORMER_STYLE,e)};const F={text:{enabledAnchors:["top-left","top-right","middle-left","bottom-left","bottom-right","middle-right"]},svg:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},gif:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},line:{enabledAnchors:[],borderEnabled:!1,rotateEnabled:!1},image:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},many:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},group:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]}};export function registerTransformerAttrs(e,t){F[e]=F[e]||t,Object.assign(F[e],t)}const B=e=>t.createElement(m,Object.assign({},e,{preventDefault:!1})),_=n=>{var{url:i}=n,o=e(n,["url"]);const[r,l]=p(i,"anonymous"),s=r?Y(r,{width:o.width,height:o.height},"center-middle"):{};return w(l,i,"page background"),t.createElement(a,Object.assign({image:r},o,s))},G=e=>{const n=P({fill:e.fill,a:{width:e.width,height:e.height}});return t.createElement(m,Object.assign({},e,n))},N=n=>{const{background:i,scale:o,borderColor:r}=n,l=e(n,["background","scale","borderColor"]),a=t.useMemo(()=>!!f.Util.colorToRGBA(i)||L(i),[i]),s=t.useMemo(()=>{const e=document.createElement("canvas"),t=30;e.width=60,e.height=60;const n=e.getContext("2d");return n&&(n.fillStyle="black",n.fillRect(t,0,t,t),n.fillRect(0,t,t,t)),e},[]);return t.createElement(t.Fragment,null,t.createElement(m,Object.assign({fillPatternImage:s},l,{opacity:.1,hideInExport:!0})),a?t.createElement(G,Object.assign({fill:i},l)):t.createElement(_,Object.assign({url:i},l)))},V=n(({selection:e,fill:n="rgba(0, 161, 255, 0.3)",stroke:i="rgb(0, 161, 255)",strokeWidth:o=1})=>e.visible?t.createElement(m,{name:"selection",x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),width:Math.abs(e.x1-e.x2),height:Math.abs(e.y1-e.y2),fill:n,stroke:i,strokeWidth:o}):null);function z(e){let t=180*e/Math.PI;return t%=360,t>180?t-=360:t<-180&&(t+=360),Math.round(t)}const H=n(({x:e,y:n,width:i,height:o,rotation:r,anchor:l,store:a,tagFill:c,textFill:d})=>{const m=k({x:e,y:n,width:i,height:o,rotation:f.Util.radToDeg(r)});if(void 0===l){return null}const h=(o/2+70)*Math.cos(r-Math.PI/2),x=(o/2+70)*Math.sin(r-Math.PI/2),p=R({unit:a.unit,dpi:a.dpi,px:i/a.scale,precious:"px"===a.unit?0:1})+" x "+R({unit:a.unit,dpi:a.dpi,px:o/a.scale,precious:"px"===a.unit?0:1})+("px"===a.unit?"":" "+a.unit);return t.createElement(t.Fragment,null,t.createElement(s,{x:(m.minX+m.maxX)/2+h,y:(m.minY+m.maxY)/2+x,offsetX:14,offsetY:14,visible:"rotater"===l},t.createElement(u,{cornerRadius:5,fill:c||"rgb(0, 161, 255)"}),t.createElement(g,{align:"center",verticalAlign:"middle",fill:d||"white",padding:8,text:z(r).toString()+"°"})),t.createElement(s,{x:(m.minX+m.maxX)/2,y:m.maxY+20,visible:"rotater"!==l},t.createElement(u,{cornerRadius:5,fill:c||"rgb(0, 161, 255)",pointerDirection:"up",pointerHeight:0,pointerWidth:0}),t.createElement(g,{align:"center",verticalAlign:"middle",fill:d||"white",padding:8,text:p})))}),Z=n(({elements:e,store:n})=>{const i=e.filter(e=>e.alwaysOnTop),o=e.filter(e=>!e.alwaysOnTop).concat(i);return t.createElement(t.Fragment,null,o.map(e=>t.createElement(b,{key:e.id,store:n,element:e,onClick:()=>{console.warn("Polotno warning: onClick callback is deprecated. Just stop using it. Polotno will do selection automatically.")}})))});export const useContextMenu=({store:e})=>{const[n,i]=t.useState(!1),[o,r]=t.useState({x:0,y:0}),l=t.useCallback(e=>{i(!0),r(e)},[]);return{open:l,close:t.useCallback(()=>{i(!1)},[]),props:{isOpen:n,offset:o,setIsOpen:i}}};let $=null;export const registerNextDomDrop=e=>{$=e};const K=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),U=atob("cmVk"),J=atob("djAuOS4y"),q=e=>t.createElement(t.Fragment,null,t.createElement(s,{fill:U,height:200},t.createElement(u,{fill:U}),t.createElement(g,Object.assign({},e,{fill:"white",text:K,height:void 0,padding:10,fontSize:20}))));export default n(({store:e,page:n,width:r,height:a,pageControlsEnabled:p,backColor:b,pageBorderColor:w,activePageBorderColor:Y,components:R,bleedColor:P,altCloneEnabled:L,viewportSize:j,selectionRectFill:I,selectionRectStroke:D,selectionRectStrokeWidth:W,snapGuideStroke:_,snapGuideStrokeWidth:G,snapGuideDash:z,transformLabelFill:K,transformLabelTextFill:U,distanceGuideStroke:Q,distanceLabelFill:ee,distanceLabelTextFill:te,layout:ne="vertical",tooltipSafeArea:ie,transformerSafeArea:oe})=>{const re=e.bleedVisible?n.bleed:0,le=n.computedWidth+2*re,ae=n.computedHeight+2*re,se=(r-le*e.scale)/2,ce=(a-ae*e.scale)/2,de=t.useRef(null),me=t.useRef(null),he=t.useRef(null),ue=null==p||p,[ge,xe]=t.useState(null),[pe,fe]=t.useState({}),[be,ve]=t.useState(0),ye=useContextMenu({store:e}),Ee=e.selectedElements.find(e=>e._cropModeEnabled),we=e.selectedElements.find(e=>e.curveEnabled),Ye=e.selectedShapes.filter(e=>!e.resizable).length>0,Xe=e.selectedShapes.filter(e=>!e.draggable).length>0,Se=e.selectedElements.filter(e=>!e.visible).length>0;t.useLayoutEffect(()=>{var t,n,i;if(!de.current){return}const o=de.current.getStage(),r=e.selectedShapes.map(e=>e._cropModeEnabled?null:o.findOne("#"+e.id)).filter(e=>e),l=1===e.selectedElements.length,a=l&&(null===(t=e.selectedElements[0])||void 0===t?void 0:t.type)||"many";F[a]?(de.current.setAttrs(Object.assign(Object.assign({},TRANSFORMER_STYLE),F[a])),"svg"!==a&&"image"!==a&&"gif"!==a||e.selectedElements[0].keepRatio||de.current.setAttrs({enabledAnchors:TRANSFORMER_STYLE.enabledAnchors}),"text"===a&&M.textVerticalResizeEnabled&&de.current.setAttrs({enabledAnchors:null===(n=F.text.enabledAnchors)||void 0===n?void 0:n.concat(["bottom-center"])}),"text"===a&&l&&e.selectedElements[0].curveEnabled&&de.current.setAttrs({enabledAnchors:F.many.enabledAnchors})):de.current.setAttrs(TRANSFORMER_STYLE),Ye&&de.current.enabledAnchors([]),Xe&&de.current.rotateEnabled(!1),r.find(e=>null==e?void 0:e.isDragging())&&r.forEach(e=>{e.isDragging()||null==e||e.startDrag()}),de.current.nodes(r),y(),null===(i=de.current.getLayer())||void 0===i||i.batchDraw()},[e.selectedShapes,Ee,Ye,Se,Xe,we]);const ke=()=>{const e=de.current;if(!e){return}if(!e.isTransforming()){return void fe({})}if(!e.nodes().length||!e.isTransforming()){return}const t=e.__getNodeRect(),n=null==e?void 0:e.getActiveAnchor(),i=e.getStage();fe({anchor:n,x:t.x-i.x(),y:t.y-i.y(),rotation:t.rotation,width:t.width,height:t.height})},Ae=t.useCallback(()=>{var e;if(null===(e=de.current)||void 0===e?void 0:e.isTransforming()){return}const t=de.current;if(!t||!t.nodes().length){return void ve(0)}const n=t.getClientRect();if(!t.getStage()){return}const i=function(e,t,n,i=0){const o=e.x+e.width/2,r=e.y+e.height/2,l=e.width/2,a=e.height/2,s=i*Math.PI/180,c=e=>{const t=e*Math.PI/180,i=(e%360+360)%360;let c;c=0===i||180===i?a:l;const d=Math.sin(t)*(c+n),m=-Math.cos(t)*(c+n),h=d*Math.cos(s)-m*Math.sin(s),u=d*Math.sin(s)+m*Math.cos(s);return{x:o+h,y:r+u}},d=e=>e.x>=t.left&&e.x<=t.right&&e.y>=t.top&&e.y<=t.bottom;if(d(c(0))){return 0}for(const m of[180,270,90]){if(d(c(m))){return m}}return 0}(n,{top:(null==oe?void 0:oe.top)||0,bottom:a-((null==oe?void 0:oe.bottom)||0),left:(null==oe?void 0:oe.left)||0,right:r-((null==oe?void 0:oe.right)||0)},TRANSFORMER_STYLE.rotateAnchorOffset||30,t.rotation());ve(i)},[oe,r,a]);t.useEffect(()=>{var e;null===(e=de.current)||void 0===e||e.update(),ke(),Ae()},[e.scale,Ae]),t.useEffect(()=>{Ae()},[e.selectedShapes,Ae]);const Re=i(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),Ce=t.useRef(!1),Me=O(),Oe=o(e=>{var t,n,i,o;if(Me){return}Ce.current=!1;const r=e.target.findAncestor(".elements-container"),l=e.target.findAncestor("Transformer"),a=e.target.findAncestor(".page-abs-container");if(r||l||a){return}const s=null===(t=e.target.getStage())||void 0===t?void 0:t.getPointerPosition();s.x-=null===(n=e.target.getStage())||void 0===n?void 0:n.x(),s.y-=null===(i=e.target.getStage())||void 0===i?void 0:i.y(),s&&(Re.visible=!0,Re.x1=s.x,Re.y1=s.y,Re.x2=s.x,Re.y2=s.y,(null===(o=e.target.getStage())||void 0===o?void 0:o.getPointersPositions().length)>=2&&(Re.visible=!1))});(({stageRef:e,containerRef:n,viewportSize:i})=>{t.useEffect(()=>{var t;const i=null===(t=n.current)||void 0===t?void 0:t.closest(".polotno-workspace-inner");function o(){var t;if(!e.current){return}const o=null===(t=n.current)||void 0===t?void 0:t.getBoundingClientRect(),r=null==i?void 0:i.getBoundingClientRect(),l=Math.max(0,r.left-o.left-100),a=Math.max(0,r.top-o.top-100);e.current.position({x:-l,y:-a}),e.current.container().style.transform=`translate(${l}px, ${a}px)`}return o(),i.addEventListener("scroll",o),()=>{i.removeEventListener("scroll",o)}},[i.width,i.height])})({stageRef:me,containerRef:he,viewportSize:j}),t.useEffect(()=>{const t=o(e=>{var t,n,i,o;if(!Re.visible){return}console.log("continueSelection"),null===(t=me.current)||void 0===t||t.setPointersPositions(e);let r=null===(n=me.current)||void 0===n?void 0:n.getPointerPosition();r?(r.x-=null===(i=me.current)||void 0===i?void 0:i.x(),r.y-=null===(o=me.current)||void 0===o?void 0:o.y()):r={x:Re.x2,y:Re.y2},Re.x2=r.x,Re.y2=r.y}),n=o(()=>{if(!Re.visible){return}if(!me.current){return}const t=me.current.findOne(".selection"),n=t?t.getClientRect({skipStroke:!0}):{width:0,height:0,x:0,y:0};if(n.width&&n.height){const t=[];me.current.find(".element").forEach(i=>{const o=i.getClientRect(),r=e.getElementById(i.id()),l=null==r?void 0:r.draggable,a=null==r?void 0:r.selectable;f.Util.haveIntersection(n,o)&&l&&a&&t.push(r.top.id)});const i=[...new Set(t)];Ce.current=!0,e.selectElements(i)}Re.visible=!1});return window.addEventListener("mousemove",t),window.addEventListener("touchmove",t),window.addEventListener("mouseup",n,{capture:!0}),window.addEventListener("touchend",n,{capture:!0}),()=>{window.removeEventListener("mousemove",t),window.removeEventListener("touchmove",t),window.removeEventListener("mouseup",n),window.removeEventListener("touchend",n)}},[]);const Pe=t.useCallback(t=>{if(!e.selectedElements[0]){return}if(t&&e.selectedElementsIds.includes(t)){return}const i=A(e.selectedShapes),o=t?e.getElementById(t):{x:0,y:0,width:n.computedWidth,height:n.computedHeight,rotation:0},r=k(o),l=[];i.minX>r.maxX&&l.push({distance:i.minX-r.maxX,box1:i,box2:r,points:[{x:i.minX,y:i.minY+i.height/2},{x:r.maxX,y:i.minY+i.height/2},{x:r.maxX,y:r.minY+r.height/2}]}),i.maxX<r.minX&&l.push({distance:r.minX-i.maxX,box1:i,box2:r,points:[{x:i.maxX,y:i.minY+i.height/2},{x:r.minX,y:i.minY+i.height/2},{x:r.minX,y:r.minY+r.height/2}]}),i.minY>r.maxY&&l.push({box1:i,box2:r,distance:i.minY-r.maxY,points:[{x:i.minX+i.width/2,y:i.minY},{x:i.minX+i.width/2,y:r.maxY},{x:r.minX+r.width/2,y:r.maxY}]}),i.maxY<r.minY&&l.push({box1:i,box2:r,distance:r.minY-i.maxY,points:[{x:i.minX+i.width/2,y:i.maxY},{x:i.minX+i.width/2,y:r.minY},{x:r.minX+r.width/2,y:r.minY}]});const a=i.minX>=r.minX&&i.maxX<=r.maxX&&i.minY>=r.minY&&i.maxY<=r.maxY;if(a&&(l.push({distance:i.minX-r.minX,box1:i,box2:r,points:[{x:i.minX,y:i.minY+i.height/2},{x:r.minX,y:i.minY+i.height/2},{x:r.minX,y:r.minY+r.height/2}]}),l.push({distance:r.maxX-i.maxX,box1:i,box2:r,points:[{x:i.maxX,y:i.minY+i.height/2},{x:r.maxX,y:i.minY+i.height/2},{x:r.maxX,y:r.minY+r.height/2}]}),l.push({box1:i,box2:r,distance:i.minY-r.minY,points:[{x:i.minX+i.width/2,y:i.minY},{x:i.minX+i.width/2,y:r.minY},{x:r.minX+r.width/2,y:r.minY}]}),l.push({box1:i,box2:r,distance:r.maxY-i.maxY,points:[{x:i.minX+i.width/2,y:i.maxY},{x:i.minX+i.width/2,y:r.maxY},{x:r.minX+r.width/2,y:r.maxY}]})),0===l.length&&!a){const e=i.minX<r.maxX&&i.maxX>r.minX,t=i.minY<r.maxY&&i.maxY>r.minY;if(e&&t){const e=(Math.max(i.minY,r.minY)+Math.min(i.maxY,r.maxY))/2,t=(Math.max(i.minX,r.minX)+Math.min(i.maxX,r.maxX))/2;i.minX<r.minX?l.push({distance:r.minX-i.minX,box1:i,box2:r,points:[{x:i.minX,y:e},{x:r.minX,y:e},{x:r.minX,y:e}]}):l.push({distance:i.minX-r.minX,box1:i,box2:r,points:[{x:i.minX,y:e},{x:r.minX,y:e},{x:r.minX,y:e}]}),i.maxX>r.maxX?l.push({distance:i.maxX-r.maxX,box1:i,box2:r,points:[{x:r.maxX,y:e},{x:i.maxX,y:e},{x:r.maxX,y:e}]}):l.push({distance:r.maxX-i.maxX,box1:i,box2:r,points:[{x:i.maxX,y:e},{x:r.maxX,y:e},{x:r.maxX,y:e}]}),i.minY<r.minY?l.push({box1:i,box2:r,distance:r.minY-i.minY,points:[{x:t,y:i.minY},{x:t,y:r.minY},{x:t,y:r.minY}]}):l.push({box1:i,box2:r,distance:i.minY-r.minY,points:[{x:t,y:i.minY},{x:t,y:r.minY},{x:t,y:r.minY}]}),i.maxY>r.maxY?l.push({box1:i,box2:r,distance:i.maxY-r.maxY,points:[{x:t,y:r.maxY},{x:t,y:i.maxY},{x:t,y:r.maxY}]}):l.push({box1:i,box2:r,distance:r.maxY-i.maxY,points:[{x:t,y:i.maxY},{x:t,y:r.maxY},{x:t,y:r.maxY}]})}}JSON.stringify(ge)!==JSON.stringify(l)&&xe(l)},[e,n]);t.useEffect(()=>{e.distanceGuidesVisible?Pe():ge&&xe(null)},[e.distanceGuidesVisible,Pe,e.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const Le=t.useRef(!1);t.useEffect(()=>{var e;let t;const n=null===(e=he.current)||void 0===e?void 0:e.closest(".polotno-workspace-inner"),i=()=>{Le.current=!0,clearTimeout(t),t=setTimeout(()=>{Le.current=!1},300)};return n.addEventListener("scroll",i),()=>{clearTimeout(t),n.removeEventListener("scroll",i)}},[]);const Te=t=>{if(e.activePage!==n&&n.select(),Le.current){return}if(Ce.current){return}const i=t.evt.ctrlKey||t.evt.metaKey||t.evt.shiftKey,o=t.target.findAncestor(".elements-container"),r=t.target.findAncestor(".page-abs-container"),l=t.target.findAncestor("Transformer");if(!(i||o||l||r||Re.visible)){return void e.selectElements([])}const a=t.target.findAncestor(".element-container",!0),s=(null==a?void 0:a.findOne(".element"))||t.target.findAncestor(".element",!0),c=e.getElementById(null==s?void 0:s.id()),d=null==c?void 0:c.top,m=null==d?void 0:d.id,h=e.selectedElementsIds.indexOf(m)>=0,u=t.target.findAncestor(".page-container",!0);m&&i&&!h?e.selectElements(e.selectedElementsIds.concat([m])):m&&i&&h?e.selectElements(e.selectedElementsIds.filter(e=>e!==m)):!m||i||h?u?e.selectPages([n.id]):e.selectPages([]):e.selectElements([m])};E(de,e,{stroke:_,strokeWidth:G,dash:z});const je=e.activePage===n,Ie=e._selectedPagesIds.includes(n.id),De=null==R?void 0:R.PageControls,We=null==R?void 0:R.Tooltip,Fe=null==R?void 0:R.ContextMenu,Be=1/e.scale,_e=0/e.scale;return t.createElement("div",{ref:he,onDragOver:e=>e.preventDefault(),onDrop:t=>{if(t.preventDefault(),!me.current){return}me.current.setPointersPositions(t);const i=me.current.findOne(".elements-container").getRelativePointerPosition(),o=me.current.getPointerPosition(),r=me.current.getAllIntersections(o).map(e=>e.findAncestor(".element",!0)).filter(Boolean),l=[...new Set(r.reverse())].map(t=>e.getElementById(t.id())),a=l[0];$&&($(i,a,{elements:l,page:n}),$=null)},style:{position:"relative",width:r+"px",height:a+"px",overflow:"hidden",flexShrink:0},className:"polotno-page-container"+(je?" active-page":"")},t.createElement(h,{ref:me,width:Math.min(r,j.width+200),height:Math.min(j.height+200,a),onClick:Te,onTap:Te,onContextMenu:t=>{t.evt.preventDefault();const n=t.target.findAncestor(".element",!0),i=e.getElementById(null==n?void 0:n.id()),o=null==i?void 0:i.top,r=null==o?void 0:o.id;r?e.selectedElementsIds.indexOf(r)>=0||e.selectElements([r]):e.selectElements([]),ye.open({x:t.evt.clientX,y:t.evt.clientY})},onMouseDown:Oe,onMouseMove:t=>{if(!e.distanceGuidesVisible&&!t.evt.altKey){return void(ge&&xe(null))}const n=t.target.findAncestor(".element",!0),i=null==n?void 0:n.id();Pe(i)},onDragStart:t=>{var n;const i=t.target.findAncestor(".element",!0);if(i){const o=e.getElementById(null==i?void 0:i.id()),r=null==o?void 0:o.top,l=null==r?void 0:r.id;!(e.selectedElementsIds.indexOf(l)>=0)&&l&&(e.selectElements([l]),t.target.stopDrag(),t.target.startDrag(t),null===(n=de.current)||void 0===n||n.startDrag(t))}ge&&xe(null)},pageId:n.id,style:{position:"absolute",overflow:"hidden",top:0,left:0}},t.createElement(c,null,t.createElement(B,{width:r,height:a,fill:b}),t.createElement(l,{x:se,y:ce,scaleX:e.scale,scaleY:e.scale,name:"page-container"},t.createElement(l,{name:"page-container-2"},t.createElement(l,{name:"page-background-group",x:re,y:re},t.createElement(N,{x:-n.bleed,y:-n.bleed,width:n.computedWidth+2*n.bleed,height:n.computedHeight+2*n.bleed,background:n.background,name:"page-background",preventDefault:!1,scale:e.scale})),t.createElement(l,{x:re,y:re,name:"elements-container",listening:!e.isPlaying},t.createElement(m,{name:"elements-area",width:n.computedWidth,height:n.computedHeight,listening:!1}),t.createElement(Z,{elements:n.children,store:e})),t.createElement(m,{stroke:P,name:"bleed",strokeWidth:n.bleed,x:n.bleed/2,y:n.bleed/2,width:n.computedWidth+n.bleed,height:n.computedHeight+n.bleed,listening:!1,visible:n.bleed>0&&e.bleedVisible,hideInExport:!0}),X()===J&&t.createElement(q,{name:"hit-detection",x:-Be/2-_e,y:-Be/2-_e,width:le+Be+2*_e,height:ae+Be+2*_e}))),t.createElement(d,{name:"workspace-background",points:[0,0,r,0,r,a,0,a,0,0,se,ce,se,a-ce,r-se,a-ce,r-se,ce,se,ce],listening:!1,closed:!0,fill:b}),t.createElement(l,{x:se,y:ce,scaleX:e.scale,scaleY:e.scale},t.createElement(m,{name:"page-highlight",hideInExport:!0,x:-Be/2-_e,y:-Be/2-_e,width:le+Be+2*_e,height:ae+Be+2*_e,stroke:Ie?Y:w,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})),t.createElement(l,{x:se+re*e.scale,y:ce+re*e.scale,scaleX:e.scale,scaleY:e.scale,name:"page-abs-container"},t.createElement(x,{ref:de,rotateAnchorAngle:be,onDragStart:t=>{var i;(null===(i=t.evt)||void 0===i?void 0:i.altKey)&&L&&e.selectedElements.forEach(e=>{const t=e.clone({},{skipSelect:!0}),i=n.children.indexOf(e);n.setElementZIndex(t.id,i)}),e.history.startTransaction()},onDragEnd:()=>{e.history.endTransaction(),Ae()},onTransformStart:()=>{e.history.startTransaction(),xe(null)},boundBoxFunc:(e,t)=>{const n=Math.abs(t.width)<1||Math.abs(t.height)<1,i=Math.abs(e.width)<1||Math.abs(e.height)<1;return n&&!i?e:t},onTransform:e=>{const t=de.current.nodes(),n=t[t.length-1];e.target===n&&setTimeout(()=>{ke()},0)},onTransformEnd:t=>{fe({}),e.history.endTransaction(),Ae()},visible:!e.isPlaying}),ge&&ge.map(({points:n,distance:i,box1:o,box2:r},a)=>t.createElement(l,{name:"distances-container",hideInExport:!0,key:a,listening:!1},t.createElement(m,Object.assign({},o,{stroke:Q,strokeWidth:1,strokeScaleEnabled:!1})),t.createElement(m,Object.assign({},r,{stroke:Q,strokeWidth:1,strokeScaleEnabled:!1})),t.createElement(d,{points:[n[0].x,n[0].y,n[1].x,n[1].y],stroke:Q,strokeWidth:1,strokeScaleEnabled:!1}),t.createElement(d,{points:[n[1].x,n[1].y,n[2].x,n[2].y],stroke:Q,strokeWidth:1,strokeScaleEnabled:!1}),t.createElement(s,{x:(n[0].x+n[1].x)/2,y:(n[0].y+n[1].y)/2,offsetY:-10,scaleX:1/e.scale,scaleY:1/e.scale},t.createElement(u,{cornerRadius:5,fill:ee,pointerDirection:"down"}),t.createElement(g,{align:"center",verticalAlign:"middle",fill:te,padding:5,text:C({unit:e.unit,dpi:e.dpi,px:i})})))),n._rendering&&t.createElement(l,null,t.createElement(m,{width:le,height:ae,fill:"rgba(255,255,255,0.9)"}),t.createElement(g,{text:"Rendering...",fontSize:60,width:le,height:ae,align:"center",verticalAlign:"middle"})),We&&t.createElement(We,{components:R,store:e,page:n,stageRef:me,tooltipSafeArea:ie}),Fe&&t.createElement(T,null,t.createElement(Fe,Object.assign({components:R,store:e},ye.props)))),t.createElement(v,{store:e,page:n,width:r,height:a,scale:e.scale,xPadding:se,yPadding:ce,bleed:re}),t.createElement(H,Object.assign({},pe,{store:e,tagFill:K,textFill:U})),t.createElement(V,{selection:Re,fill:I,stroke:D,strokeWidth:W}),S()&&t.createElement(g,{text:"Powered by polotno.com",fontSize:14,fill:"rgba(0,0,0,0.6)",x:r-170,y:a-18,onMouseEnter:e=>{e.target.getStage().container().style.cursor="pointer"},onMouseLeave:e=>{e.target.getStage().container().style.cursor=""},onTouchStart:e=>{e.cancelBubble=!0},onMouseDown:e=>{e.cancelBubble=!0},onClick:()=>{window.open("https://polotno.com")},onTap:()=>{window.open("https://polotno.com")}}),t.createElement(l,{name:"line-guides"}))),ue&&De&&t.createElement(De,{store:e,page:n,xPadding:se,yPadding:ce,layout:ne}))});
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 t from"react";import{observer as n,useLocalObservable as i}from"mobx-react-lite";import{action as o,runInAction as r}from"mobx";import{Group as l,Image as a,Label as s,Layer as c,Line as d,Rect as m,Stage as h,Tag as u,Text as g,Transformer as x}from"react-konva";import p from"use-image";import f from"konva";import b from"./element.js";import{DrawingLayer as y}from"./drawing-layer.js";import{ensureDragOrder as v,useSnap as E}from"./use-transformer-snap.js";import{useImageLoader as w}from"./image-element.js";import{getCrop as Y}from"../utils/crop.js";import{___ as X,____ as S,isCreditVisible as k}from"../utils/validate-key.js";import{getClientRect as R,getTotalClientRect as A}from"../utils/math.js";import{pxToUnitRounded as C,pxToUnitString as M}from"../utils/unit.js";import{flags as O}from"../utils/flags.js";import{isTouchDevice as P}from"../utils/screen.js";import{useColor as T}from"./use-color.js";import{isGradient as I}from"../utils/gradient.js";import{Html as L}from"react-konva-utils";const j=f.DD._drag;window.removeEventListener("mousemove",j),f.DD._drag=function(e){r(()=>{j.call(this,e)})},window.addEventListener("mousemove",f.DD._drag);const D=new f.Group,F=20;D.add(new f.Rect({width:F,height:F,fill:"white"})),D.add(new f.Path({scaleX:F/24,scaleY:F/24,data:"M4.98313549,11.0001422 C5.49589839,10.9914935 5.92501998,11.3703506 5.99116425,11.8666444 L5.99985778,11.9831355 L6.00348884,12.2068855 C6.11245031,15.4321748 8.76323537,17.9999971 11.9999971,17.9999971 C12.1869612,17.9999971 12.3726725,17.9914753 12.5567465,17.9745765 L12.2928932,17.7071068 C11.9023689,17.3165825 11.9023689,16.6834175 12.2928932,16.2928932 C12.6834175,15.9023689 13.3165825,15.9023689 13.7071068,16.2928932 L15.7071068,18.2928932 C16.0976311,18.6834175 16.0976311,19.3165825 15.7071068,19.7071068 L13.7071068,21.7071068 C13.3165825,22.0976311 12.6834175,22.0976311 12.2928932,21.7071068 C11.9023689,21.3165825 11.9023689,20.6834175 12.2928932,20.2928932 L12.6111505,19.9769552 C12.4086045,19.9922816 12.2047796,19.9999971 11.9999971,19.9999971 C7.7687005,19.9999971 4.28886152,16.7094374 4.01666425,12.5105203 L4.00420123,12.2575143 L4.00014222,12.0168645 C3.9908282,11.4646583 4.43092928,11.0094562 4.98313549,11.0001422 Z M11.7071068,2.29289322 C12.0675907,2.65337718 12.0953203,3.22060824 11.7902954,3.61289944 L11.7071068,3.70710678 L11.3891629,4.0230186 C11.5916051,4.00770767 11.7953244,4 12,4 C16.418278,4 20,7.581722 20,12 C20,12.5522847 19.5522847,13 19,13 C18.4477153,13 18,12.5522847 18,12 C18,8.6862915 15.3137085,6 12,6 C11.8129339,6 11.6271216,6.00853145 11.4429483,6.02544919 L11.7071068,6.29289322 C12.0976311,6.68341751 12.0976311,7.31658249 11.7071068,7.70710678 C11.3466228,8.06759074 10.7793918,8.09532028 10.3871006,7.79029539 L10.2928932,7.70710678 L8.29289322,5.70710678 C7.93240926,5.34662282 7.90467972,4.77939176 8.20970461,4.38710056 L8.29289322,4.29289322 L10.2928932,2.29289322 C10.6834175,1.90236893 11.3165825,1.90236893 11.7071068,2.29289322 Z",fill:"black"}));const W=D.toCanvas({pixelRatio:2,width:F,height:F});export const TRANSFORMER_STYLE={enabledAnchors:["top-left","top-center","top-right","middle-left","bottom-left","bottom-right","bottom-center","middle-right"],borderEnabled:!0,rotateEnabled:!0,rotationSnaps:[0,45,90,135,180,225,270,315],ignoreStroke:!0,flipEnabled:!1,anchorStrokeWidth:2,borderStrokeWidth:2,rotateAnchorOffset:30,anchorStyleFunc:e=>{if(e.hasName("rotater")){const t=20;e.setAttrs({width:t,height:t,cornerRadius:t/2,offsetX:t/2,offsetY:t/2,fillPatternImage:W,fillPatternScaleX:t/F/2,fillPatternScaleY:t/F/2,fillPriority:"pattern",fillPatternRepeat:"no-repeat"})}}};export const setTransformerStyle=e=>{Object.assign(TRANSFORMER_STYLE,e)};const G={text:{enabledAnchors:["top-left","top-right","middle-left","bottom-left","bottom-right","middle-right"]},svg:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},gif:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},line:{enabledAnchors:[],borderEnabled:!1,rotateEnabled:!1},image:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},many:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]},group:{enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]}};export function registerTransformerAttrs(e,t){G[e]=G[e]||t,Object.assign(G[e],t)}const B=e=>t.createElement(m,Object.assign({},e,{preventDefault:!1})),_=n=>{var{url:i}=n,o=e(n,["url"]);const[r,l]=p(i,"anonymous"),s=r?Y(r,{width:o.width,height:o.height},"center-middle"):{};return w(l,i,"page background"),t.createElement(a,Object.assign({image:r},o,s))},N=e=>{const n=T({fill:e.fill,a:{width:e.width,height:e.height}});return t.createElement(m,Object.assign({},e,n))},Z=n=>{const{background:i,scale:o,borderColor:r}=n,l=e(n,["background","scale","borderColor"]),a=t.useMemo(()=>!!f.Util.colorToRGBA(i)||I(i),[i]),s=t.useMemo(()=>{const e=document.createElement("canvas"),t=30;e.width=60,e.height=60;const n=e.getContext("2d");return n&&(n.fillStyle="black",n.fillRect(t,0,t,t),n.fillRect(0,t,t,t)),e},[]);return t.createElement(t.Fragment,null,t.createElement(m,Object.assign({fillPatternImage:s},l,{opacity:.1,hideInExport:!0})),a?t.createElement(N,Object.assign({fill:i},l)):t.createElement(_,Object.assign({url:i},l)))},z=n(({selection:e,fill:n="rgba(0, 161, 255, 0.3)",stroke:i="rgb(0, 161, 255)",strokeWidth:o=1})=>e.visible?t.createElement(m,{name:"selection",x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),width:Math.abs(e.x1-e.x2),height:Math.abs(e.y1-e.y2),fill:n,stroke:i,strokeWidth:o}):null);function U(e){let t=180*e/Math.PI;return t%=360,t>180?t-=360:t<-180&&(t+=360),Math.round(t)}const V=n(({x:e,y:n,width:i,height:o,rotation:r,anchor:l,store:a,tagFill:c,textFill:d})=>{const m=R({x:e,y:n,width:i,height:o,rotation:f.Util.radToDeg(r)});if(void 0===l){return null}const h=(o/2+70)*Math.cos(r-Math.PI/2),x=(o/2+70)*Math.sin(r-Math.PI/2),p=C({unit:a.unit,dpi:a.dpi,px:i/a.scale,precious:"px"===a.unit?0:1})+" x "+C({unit:a.unit,dpi:a.dpi,px:o/a.scale,precious:"px"===a.unit?0:1})+("px"===a.unit?"":" "+a.unit);return t.createElement(t.Fragment,null,t.createElement(s,{x:(m.minX+m.maxX)/2+h,y:(m.minY+m.maxY)/2+x,offsetX:14,offsetY:14,visible:"rotater"===l},t.createElement(u,{cornerRadius:5,fill:c||"rgb(0, 161, 255)"}),t.createElement(g,{align:"center",verticalAlign:"middle",fill:d||"white",padding:8,text:U(r).toString()+"°"})),t.createElement(s,{x:(m.minX+m.maxX)/2,y:m.maxY+20,visible:"rotater"!==l},t.createElement(u,{cornerRadius:5,fill:c||"rgb(0, 161, 255)",pointerDirection:"up",pointerHeight:0,pointerWidth:0}),t.createElement(g,{align:"center",verticalAlign:"middle",fill:d||"white",padding:8,text:p})))}),H=n(({elements:e,store:n})=>{const i=e.filter(e=>e.alwaysOnTop),o=e.filter(e=>!e.alwaysOnTop).concat(i);return t.createElement(t.Fragment,null,o.map(e=>t.createElement(b,{key:e.id,store:n,element:e,onClick:()=>{console.warn("Polotno warning: onClick callback is deprecated. Just stop using it. Polotno will do selection automatically.")}})))});export const useContextMenu=({store:e})=>{const[n,i]=t.useState(!1),[o,r]=t.useState({x:0,y:0}),l=t.useCallback(e=>{i(!0),r(e)},[]);return{open:l,close:t.useCallback(()=>{i(!1)},[]),props:{isOpen:n,offset:o,setIsOpen:i}}};let J=null;export const registerNextDomDrop=e=>{J=e};const K=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),$=atob("I2MwMzkyYg=="),Q=atob("djAuOS4y"),q=e=>t.createElement(t.Fragment,null,t.createElement(s,{fill:$,height:200},t.createElement(u,{fill:$}),t.createElement(g,Object.assign({},e,{fill:"white",text:K,height:void 0,padding:10,fontSize:20})))),ee=atob("RlJFRSAgVFJJQUwgIExJQ0VOU0U="),te=(atob("UG93ZXJlZCBieSBQb2xvdG5v"),atob("TElDRU5TRSAgS0VZICBJUyAgTUlTU0lORw==")),ne=atob("UGxlYXNlIGFjdGl2YXRlIHlvdXIgbGljZW5zZS4KTGljZW5zZSByZWxhdGVkIHF1ZXN0aW9uczoKcG9sb3Ruby5jb20vY29udGFjdA=="),ie=e=>{const n=1===S(),i=n?te:ee,o=n?230:195;return t.createElement(l,Object.assign({},e,{listening:!1}),t.createElement(m,{fill:$,width:o,height:24,cornerRadius:2}),t.createElement(g,{text:i,fill:"white",fontSize:13,fontFamily:"monospace",width:o,align:"center",y:5,listening:!1}),n&&t.createElement(g,{text:ne,fill:"rgba(0,0,0,0.6)",fontSize:14,y:30,listening:!1}))};export default n(({store:e,page:n,width:r,height:a,pageControlsEnabled:p,backColor:b,pageBorderColor:w,activePageBorderColor:Y,components:C,bleedColor:T,altCloneEnabled:I,viewportSize:j,selectionRectFill:D,selectionRectStroke:F,selectionRectStrokeWidth:W,snapGuideStroke:_,snapGuideStrokeWidth:N,snapGuideDash:U,transformLabelFill:K,transformLabelTextFill:$,distanceGuideStroke:ee,distanceLabelFill:te,distanceLabelTextFill:ne,layout:oe="vertical",tooltipSafeArea:re,transformerSafeArea:le})=>{const ae=e.bleedVisible?n.bleed:0,se=n.computedWidth+2*ae,ce=n.computedHeight+2*ae,de=(r-se*e.scale)/2,me=(a-ce*e.scale)/2,he=t.useRef(null),ue=t.useRef(null),ge=t.useRef(null),xe=null==p||p,[pe,fe]=t.useState(null),[be,ye]=t.useState({}),[ve,Ee]=t.useState(0),we=useContextMenu({store:e}),Ye=e.selectedElements.find(e=>e._cropModeEnabled),Xe=e.selectedElements.find(e=>e.curveEnabled),Se=e.selectedShapes.filter(e=>!e.resizable).length>0,ke=e.selectedShapes.filter(e=>!e.draggable).length>0,Re=e.selectedElements.filter(e=>!e.visible).length>0;t.useLayoutEffect(()=>{var t,n,i;if(!he.current){return}const o=he.current.getStage(),r=e.selectedShapes.map(e=>e._cropModeEnabled?null:o.findOne("#"+e.id)).filter(e=>e),l=1===e.selectedElements.length,a=l&&(null===(t=e.selectedElements[0])||void 0===t?void 0:t.type)||"many";G[a]?(he.current.setAttrs(Object.assign(Object.assign({},TRANSFORMER_STYLE),G[a])),"svg"!==a&&"image"!==a&&"gif"!==a||e.selectedElements[0].keepRatio||he.current.setAttrs({enabledAnchors:TRANSFORMER_STYLE.enabledAnchors}),"text"===a&&O.textVerticalResizeEnabled&&he.current.setAttrs({enabledAnchors:null===(n=G.text.enabledAnchors)||void 0===n?void 0:n.concat(["bottom-center"])}),"text"===a&&l&&e.selectedElements[0].curveEnabled&&he.current.setAttrs({enabledAnchors:G.many.enabledAnchors})):he.current.setAttrs(TRANSFORMER_STYLE),Se&&he.current.enabledAnchors([]),ke&&he.current.rotateEnabled(!1),r.find(e=>null==e?void 0:e.isDragging())&&r.forEach(e=>{e.isDragging()||null==e||e.startDrag()}),he.current.nodes(r),v(),null===(i=he.current.getLayer())||void 0===i||i.batchDraw()},[e.selectedShapes,Ye,Se,Re,ke,Xe]);const Ae=()=>{const e=he.current;if(!e){return}if(!e.isTransforming()){return void ye({})}if(!e.nodes().length||!e.isTransforming()){return}const t=e.__getNodeRect(),n=null==e?void 0:e.getActiveAnchor(),i=e.getStage();ye({anchor:n,x:t.x-i.x(),y:t.y-i.y(),rotation:t.rotation,width:t.width,height:t.height})},Ce=t.useCallback(()=>{var e;if(null===(e=he.current)||void 0===e?void 0:e.isTransforming()){return}const t=he.current;if(!t||!t.nodes().length){return void Ee(0)}const n=t.getClientRect();if(!t.getStage()){return}const i=function(e,t,n,i=0){const o=e.x+e.width/2,r=e.y+e.height/2,l=e.width/2,a=e.height/2,s=i*Math.PI/180,c=e=>{const t=e*Math.PI/180,i=(e%360+360)%360;let c;c=0===i||180===i?a:l;const d=Math.sin(t)*(c+n),m=-Math.cos(t)*(c+n),h=d*Math.cos(s)-m*Math.sin(s),u=d*Math.sin(s)+m*Math.cos(s);return{x:o+h,y:r+u}},d=e=>e.x>=t.left&&e.x<=t.right&&e.y>=t.top&&e.y<=t.bottom;if(d(c(0))){return 0}for(const m of[180,270,90]){if(d(c(m))){return m}}return 0}(n,{top:(null==le?void 0:le.top)||0,bottom:a-((null==le?void 0:le.bottom)||0),left:(null==le?void 0:le.left)||0,right:r-((null==le?void 0:le.right)||0)},TRANSFORMER_STYLE.rotateAnchorOffset||30,t.rotation());Ee(i)},[le,r,a]);t.useEffect(()=>{var e;null===(e=he.current)||void 0===e||e.update(),Ae(),Ce()},[e.scale,Ce]),t.useEffect(()=>{Ce()},[e.selectedShapes,Ce]);const Me=i(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),Oe=t.useRef(!1),Pe=P(),Te=o(e=>{var t,n,i,o;if(Pe){return}Oe.current=!1;const r=e.target.findAncestor(".elements-container"),l=e.target.findAncestor("Transformer"),a=e.target.findAncestor(".page-abs-container");if(r||l||a){return}const s=null===(t=e.target.getStage())||void 0===t?void 0:t.getPointerPosition();s.x-=null===(n=e.target.getStage())||void 0===n?void 0:n.x(),s.y-=null===(i=e.target.getStage())||void 0===i?void 0:i.y(),s&&(Me.visible=!0,Me.x1=s.x,Me.y1=s.y,Me.x2=s.x,Me.y2=s.y,(null===(o=e.target.getStage())||void 0===o?void 0:o.getPointersPositions().length)>=2&&(Me.visible=!1))});(({stageRef:e,containerRef:n,viewportSize:i})=>{t.useEffect(()=>{var t;const i=null===(t=n.current)||void 0===t?void 0:t.closest(".polotno-workspace-inner");function o(){var t;if(!e.current){return}const o=null===(t=n.current)||void 0===t?void 0:t.getBoundingClientRect(),r=null==i?void 0:i.getBoundingClientRect(),l=Math.max(0,r.left-o.left-100),a=Math.max(0,r.top-o.top-100);e.current.position({x:-l,y:-a}),e.current.container().style.transform=`translate(${l}px, ${a}px)`}return o(),i.addEventListener("scroll",o),()=>{i.removeEventListener("scroll",o)}},[i.width,i.height])})({stageRef:ue,containerRef:ge,viewportSize:j}),t.useEffect(()=>{const t=o(e=>{var t,n,i,o;if(!Me.visible){return}null===(t=ue.current)||void 0===t||t.setPointersPositions(e);let r=null===(n=ue.current)||void 0===n?void 0:n.getPointerPosition();r?(r.x-=null===(i=ue.current)||void 0===i?void 0:i.x(),r.y-=null===(o=ue.current)||void 0===o?void 0:o.y()):r={x:Me.x2,y:Me.y2},Me.x2=r.x,Me.y2=r.y}),n=o(()=>{if(!Me.visible){return}if(!ue.current){return}const t=ue.current.findOne(".selection"),n=t?t.getClientRect({skipStroke:!0}):{width:0,height:0,x:0,y:0};if(n.width&&n.height){const t=[];ue.current.find(".element").forEach(i=>{const o=i.getClientRect(),r=e.getElementById(i.id()),l=null==r?void 0:r.draggable,a=null==r?void 0:r.selectable;f.Util.haveIntersection(n,o)&&l&&a&&t.push(r.top.id)});const i=[...new Set(t)];Oe.current=!0,e.selectElements(i)}Me.visible=!1});return window.addEventListener("mousemove",t),window.addEventListener("touchmove",t),window.addEventListener("mouseup",n,{capture:!0}),window.addEventListener("touchend",n,{capture:!0}),()=>{window.removeEventListener("mousemove",t),window.removeEventListener("touchmove",t),window.removeEventListener("mouseup",n),window.removeEventListener("touchend",n)}},[]);const Ie=t.useCallback(t=>{if(!e.selectedElements[0]){return}if(t&&e.selectedElementsIds.includes(t)){return}const i=A(e.selectedShapes),o=t?e.getElementById(t):{x:0,y:0,width:n.computedWidth,height:n.computedHeight,rotation:0},r=R(o),l=[];i.minX>r.maxX&&l.push({distance:i.minX-r.maxX,box1:i,box2:r,points:[{x:i.minX,y:i.minY+i.height/2},{x:r.maxX,y:i.minY+i.height/2},{x:r.maxX,y:r.minY+r.height/2}]}),i.maxX<r.minX&&l.push({distance:r.minX-i.maxX,box1:i,box2:r,points:[{x:i.maxX,y:i.minY+i.height/2},{x:r.minX,y:i.minY+i.height/2},{x:r.minX,y:r.minY+r.height/2}]}),i.minY>r.maxY&&l.push({box1:i,box2:r,distance:i.minY-r.maxY,points:[{x:i.minX+i.width/2,y:i.minY},{x:i.minX+i.width/2,y:r.maxY},{x:r.minX+r.width/2,y:r.maxY}]}),i.maxY<r.minY&&l.push({box1:i,box2:r,distance:r.minY-i.maxY,points:[{x:i.minX+i.width/2,y:i.maxY},{x:i.minX+i.width/2,y:r.minY},{x:r.minX+r.width/2,y:r.minY}]});const a=i.minX>=r.minX&&i.maxX<=r.maxX&&i.minY>=r.minY&&i.maxY<=r.maxY;if(a&&(l.push({distance:i.minX-r.minX,box1:i,box2:r,points:[{x:i.minX,y:i.minY+i.height/2},{x:r.minX,y:i.minY+i.height/2},{x:r.minX,y:r.minY+r.height/2}]}),l.push({distance:r.maxX-i.maxX,box1:i,box2:r,points:[{x:i.maxX,y:i.minY+i.height/2},{x:r.maxX,y:i.minY+i.height/2},{x:r.maxX,y:r.minY+r.height/2}]}),l.push({box1:i,box2:r,distance:i.minY-r.minY,points:[{x:i.minX+i.width/2,y:i.minY},{x:i.minX+i.width/2,y:r.minY},{x:r.minX+r.width/2,y:r.minY}]}),l.push({box1:i,box2:r,distance:r.maxY-i.maxY,points:[{x:i.minX+i.width/2,y:i.maxY},{x:i.minX+i.width/2,y:r.maxY},{x:r.minX+r.width/2,y:r.maxY}]})),0===l.length&&!a){const e=i.minX<r.maxX&&i.maxX>r.minX,t=i.minY<r.maxY&&i.maxY>r.minY;if(e&&t){const e=(Math.max(i.minY,r.minY)+Math.min(i.maxY,r.maxY))/2,t=(Math.max(i.minX,r.minX)+Math.min(i.maxX,r.maxX))/2;i.minX<r.minX?l.push({distance:r.minX-i.minX,box1:i,box2:r,points:[{x:i.minX,y:e},{x:r.minX,y:e},{x:r.minX,y:e}]}):l.push({distance:i.minX-r.minX,box1:i,box2:r,points:[{x:i.minX,y:e},{x:r.minX,y:e},{x:r.minX,y:e}]}),i.maxX>r.maxX?l.push({distance:i.maxX-r.maxX,box1:i,box2:r,points:[{x:r.maxX,y:e},{x:i.maxX,y:e},{x:r.maxX,y:e}]}):l.push({distance:r.maxX-i.maxX,box1:i,box2:r,points:[{x:i.maxX,y:e},{x:r.maxX,y:e},{x:r.maxX,y:e}]}),i.minY<r.minY?l.push({box1:i,box2:r,distance:r.minY-i.minY,points:[{x:t,y:i.minY},{x:t,y:r.minY},{x:t,y:r.minY}]}):l.push({box1:i,box2:r,distance:i.minY-r.minY,points:[{x:t,y:i.minY},{x:t,y:r.minY},{x:t,y:r.minY}]}),i.maxY>r.maxY?l.push({box1:i,box2:r,distance:i.maxY-r.maxY,points:[{x:t,y:r.maxY},{x:t,y:i.maxY},{x:t,y:r.maxY}]}):l.push({box1:i,box2:r,distance:r.maxY-i.maxY,points:[{x:t,y:i.maxY},{x:t,y:r.maxY},{x:t,y:r.maxY}]})}}JSON.stringify(pe)!==JSON.stringify(l)&&fe(l)},[e,n]);t.useEffect(()=>{e.distanceGuidesVisible?Ie():pe&&fe(null)},[e.distanceGuidesVisible,Ie,e.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const Le=t.useRef(!1);t.useEffect(()=>{var e;let t;const n=null===(e=ge.current)||void 0===e?void 0:e.closest(".polotno-workspace-inner"),i=()=>{Le.current=!0,clearTimeout(t),t=setTimeout(()=>{Le.current=!1},300)};return n.addEventListener("scroll",i),()=>{clearTimeout(t),n.removeEventListener("scroll",i)}},[]);const je=t=>{if(e.activePage!==n&&n.select(),Le.current){return}if(Oe.current){return}const i=t.evt.ctrlKey||t.evt.metaKey||t.evt.shiftKey,o=t.target.findAncestor(".elements-container"),r=t.target.findAncestor(".page-abs-container"),l=t.target.findAncestor("Transformer");if(!(i||o||l||r||Me.visible)){return void e.selectElements([])}const a=t.target.findAncestor(".element-container",!0),s=(null==a?void 0:a.findOne(".element"))||t.target.findAncestor(".element",!0),c=e.getElementById(null==s?void 0:s.id()),d=null==c?void 0:c.top,m=null==d?void 0:d.id,h=e.selectedElementsIds.indexOf(m)>=0,u=t.target.findAncestor(".page-container",!0);m&&i&&!h?e.selectElements(e.selectedElementsIds.concat([m])):m&&i&&h?e.selectElements(e.selectedElementsIds.filter(e=>e!==m)):!m||i||h?u?e.selectPages([n.id]):e.selectPages([]):e.selectElements([m])};E(he,e,{stroke:_,strokeWidth:N,dash:U});const De=e.activePage===n,Fe=e._selectedPagesIds.includes(n.id),We=null==C?void 0:C.PageControls,Ge=null==C?void 0:C.Tooltip,Be=null==C?void 0:C.ContextMenu,_e=1/e.scale,Ne=0/e.scale;return t.createElement("div",{ref:ge,onDragOver:e=>e.preventDefault(),onDrop:t=>{if(t.preventDefault(),!ue.current){return}ue.current.setPointersPositions(t);const i=ue.current.findOne(".elements-container").getRelativePointerPosition(),o=ue.current.getPointerPosition(),r=ue.current.getAllIntersections(o).map(e=>e.findAncestor(".element",!0)).filter(Boolean),l=[...new Set(r.reverse())].map(t=>e.getElementById(t.id())),a=l[0];J&&(J(i,a,{elements:l,page:n}),J=null)},style:{position:"relative",width:r+"px",height:a+"px",overflow:"hidden",flexShrink:0},className:"polotno-page-container"+(De?" active-page":"")},t.createElement(h,{ref:ue,width:Math.min(r,j.width+200),height:Math.min(j.height+200,a),onClick:je,onTap:je,onContextMenu:t=>{t.evt.preventDefault();const n=t.target.findAncestor(".element",!0),i=e.getElementById(null==n?void 0:n.id()),o=null==i?void 0:i.top,r=null==o?void 0:o.id;r?e.selectedElementsIds.indexOf(r)>=0||e.selectElements([r]):e.selectElements([]),we.open({x:t.evt.clientX,y:t.evt.clientY})},onMouseDown:Te,onMouseMove:t=>{if(!e.distanceGuidesVisible&&!t.evt.altKey){return void(pe&&fe(null))}const n=t.target.findAncestor(".element",!0),i=null==n?void 0:n.id();Ie(i)},onDragStart:t=>{var n;const i=t.target.findAncestor(".element",!0);if(i){const o=e.getElementById(null==i?void 0:i.id()),r=null==o?void 0:o.top,l=null==r?void 0:r.id;!(e.selectedElementsIds.indexOf(l)>=0)&&l&&(e.selectElements([l]),t.target.stopDrag(),t.target.startDrag(t),null===(n=he.current)||void 0===n||n.startDrag(t))}pe&&fe(null)},pageId:n.id,style:{position:"absolute",overflow:"hidden",top:0,left:0}},t.createElement(c,null,t.createElement(B,{width:r,height:a,fill:b}),t.createElement(l,{x:de,y:me,scaleX:e.scale,scaleY:e.scale,name:"page-container"},t.createElement(l,{name:"page-container-2"},t.createElement(l,{name:"page-background-group",x:ae,y:ae},t.createElement(Z,{x:-n.bleed,y:-n.bleed,width:n.computedWidth+2*n.bleed,height:n.computedHeight+2*n.bleed,background:n.background,name:"page-background",preventDefault:!1,scale:e.scale})),t.createElement(l,{x:ae,y:ae,name:"elements-container",listening:!e.isPlaying},t.createElement(m,{name:"elements-area",width:n.computedWidth,height:n.computedHeight,listening:!1}),t.createElement(H,{elements:n.children,store:e})),t.createElement(m,{stroke:T,name:"bleed",strokeWidth:n.bleed,x:n.bleed/2,y:n.bleed/2,width:n.computedWidth+n.bleed,height:n.computedHeight+n.bleed,listening:!1,visible:n.bleed>0&&e.bleedVisible,hideInExport:!0}),X()===Q&&t.createElement(q,{name:"hit-detection",x:-_e/2-Ne,y:-_e/2-Ne,width:se+_e+2*Ne,height:ce+_e+2*Ne}))),t.createElement(d,{name:"workspace-background",points:[0,0,r,0,r,a,0,a,0,0,de,me,de,a-me,r-de,a-me,r-de,me,de,me],listening:!1,closed:!0,fill:b}),t.createElement(l,{x:de,y:me,scaleX:e.scale,scaleY:e.scale},t.createElement(m,{name:"page-highlight",hideInExport:!0,x:-_e/2-Ne,y:-_e/2-Ne,width:se+_e+2*Ne,height:ce+_e+2*Ne,stroke:Fe?Y:w,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})),t.createElement(l,{x:de+ae*e.scale,y:me+ae*e.scale,scaleX:e.scale,scaleY:e.scale,name:"page-abs-container"},t.createElement(x,{ref:he,rotateAnchorAngle:ve,onDragStart:t=>{var i;(null===(i=t.evt)||void 0===i?void 0:i.altKey)&&I&&e.selectedElements.forEach(e=>{const t=e.clone({},{skipSelect:!0}),i=n.children.indexOf(e);n.setElementZIndex(t.id,i)}),e.history.startTransaction()},onDragEnd:()=>{e.history.endTransaction(),Ce()},onTransformStart:()=>{e.history.startTransaction(),fe(null)},boundBoxFunc:(e,t)=>{const n=Math.abs(t.width)<1||Math.abs(t.height)<1,i=Math.abs(e.width)<1||Math.abs(e.height)<1;return n&&!i?e:t},onTransform:e=>{const t=he.current.nodes(),n=t[t.length-1];e.target===n&&setTimeout(()=>{Ae()},0)},onTransformEnd:t=>{ye({}),e.history.endTransaction(),Ce()},visible:!e.isPlaying}),pe&&pe.map(({points:n,distance:i,box1:o,box2:r},a)=>t.createElement(l,{name:"distances-container",hideInExport:!0,key:a,listening:!1},t.createElement(m,Object.assign({},o,{stroke:ee,strokeWidth:1,strokeScaleEnabled:!1})),t.createElement(m,Object.assign({},r,{stroke:ee,strokeWidth:1,strokeScaleEnabled:!1})),t.createElement(d,{points:[n[0].x,n[0].y,n[1].x,n[1].y],stroke:ee,strokeWidth:1,strokeScaleEnabled:!1}),t.createElement(d,{points:[n[1].x,n[1].y,n[2].x,n[2].y],stroke:ee,strokeWidth:1,strokeScaleEnabled:!1}),t.createElement(s,{x:(n[0].x+n[1].x)/2,y:(n[0].y+n[1].y)/2,offsetY:-10,scaleX:1/e.scale,scaleY:1/e.scale},t.createElement(u,{cornerRadius:5,fill:te,pointerDirection:"down"}),t.createElement(g,{align:"center",verticalAlign:"middle",fill:ne,padding:5,text:M({unit:e.unit,dpi:e.dpi,px:i})})))),n._rendering&&t.createElement(l,null,t.createElement(m,{width:se,height:ce,fill:"rgba(255,255,255,0.9)"}),t.createElement(g,{text:"Rendering...",fontSize:60,width:se,height:ce,align:"center",verticalAlign:"middle"})),Ge&&t.createElement(Ge,{components:C,store:e,page:n,stageRef:ue,tooltipSafeArea:re}),Be&&t.createElement(L,null,t.createElement(Be,Object.assign({components:C,store:e},we.props)))),t.createElement(y,{store:e,page:n,width:r,height:a,scale:e.scale,xPadding:de,yPadding:me,bleed:ae}),t.createElement(V,Object.assign({},be,{store:e,tagFill:K,textFill:$})),t.createElement(z,{selection:Me,fill:D,stroke:F,strokeWidth:W}),S()>0&&t.createElement(l,{hideInExport:!0},t.createElement(ie,{name:"cache-bounds",x:r-(1===S()?250:210),y:a-(1===S()?95:45)}),t.createElement(ie,{name:"cache-bounds-t",x:10,y:10})),k()&&t.createElement(g,{text:"Powered by polotno.com",fontSize:14,fill:"rgba(0,0,0,0.6)",x:r-170,y:a-18,onMouseEnter:e=>{e.target.getStage().container().style.cursor="pointer"},onMouseLeave:e=>{e.target.getStage().container().style.cursor=""},onTouchStart:e=>{e.cancelBubble=!0},onMouseDown:e=>{e.cancelBubble=!0},onClick:()=>{window.open("https://polotno.com")},onTap:()=>{window.open("https://polotno.com")}}),t.createElement(l,{name:"line-guides"}))),xe&&We&&t.createElement(We,{store:e,page:n,xPadding:de,yPadding:me,layout:oe}))});
package/canvas/rules.d.ts CHANGED
@@ -9,8 +9,14 @@ type TopRulesProps = {
9
9
  pageSizes?: number[];
10
10
  layout?: 'vertical' | 'horizontal';
11
11
  renderOnlyActivePage?: boolean;
12
+ rulerBackgroundColor?: string;
13
+ rulerTextColor?: string;
14
+ rulerBorderColor?: string;
15
+ rulerBorderSize?: number;
16
+ rulerTickColor?: string;
17
+ rulerTickSize?: number;
12
18
  };
13
- export declare const TopRules: (({ store, width, height, pageSizes, layout, renderOnlyActivePage }: TopRulesProps) => React.JSX.Element | null) & {
19
+ export declare const TopRules: (({ store, width, height, pageSizes, layout, renderOnlyActivePage, rulerBackgroundColor, rulerTextColor, rulerBorderColor, rulerBorderSize, rulerTickColor, rulerTickSize }: TopRulesProps) => React.JSX.Element | null) & {
14
20
  displayName: string;
15
21
  };
16
22
  export {};
package/canvas/rules.js CHANGED
@@ -1,4 +1,4 @@
1
- import e from"react";import{getTotalClientRect as t}from"../utils/math.js";import{unitToPx as o}from"../utils/unit.js";import{observer as i}from"mobx-react-lite";import{styled as l}from"../utils/goober.js";const r=l("div",e.forwardRef)`
1
+ import e from"react";import{getTotalClientRect as o}from"../utils/math.js";import{unitToPx as t}from"../utils/unit.js";import{observer as r}from"mobx-react-lite";import{styled as l}from"../utils/goober.js";const i=l("div",e.forwardRef)`
2
2
  position: absolute;
3
3
  top: 0;
4
4
  left: 0;
@@ -14,7 +14,7 @@ import e from"react";import{getTotalClientRect as t}from"../utils/math.js";impor
14
14
  border-bottom: 1px solid grey;
15
15
  background-color: #e8e8e8;
16
16
  overflow: hidden;
17
- `,n=l("div",e.forwardRef)`
17
+ `,s=l("div",e.forwardRef)`
18
18
  left: 0;
19
19
  width: 14px;
20
20
  position: sticky;
@@ -24,11 +24,11 @@ import e from"react";import{getTotalClientRect as t}from"../utils/math.js";impor
24
24
  border-right: 1px solid grey;
25
25
  background-color: #e8e8e8;
26
26
  overflow: hidden;
27
- `,s=l("div",e.forwardRef)`
27
+ `,n=l("div",e.forwardRef)`
28
28
  position: absolute;
29
29
  border-left: 1px solid grey;
30
30
  padding-left: 2px;
31
- `,p=l("div",e.forwardRef)`
31
+ `,d=l("div",e.forwardRef)`
32
32
  position: absolute;
33
33
  left: 14px;
34
34
  border-left: 1px solid grey;
@@ -36,4 +36,4 @@ import e from"react";import{getTotalClientRect as t}from"../utils/math.js";impor
36
36
  transform: rotate(90deg);
37
37
  transform-origin: left top;
38
38
  overflow: hidden;
39
- `,d=[.1,.2,.5,1,2,5,10,20,25,50,100,200,500,1e3,2e3,5e3,1e4];export const TopRules=i(({store:i,width:l,height:c,pageSizes:h,layout:u="vertical",renderOnlyActivePage:x})=>{const g=e.useRef(null);if(!i.activePage){return null}const m="horizontal"===u,f=i.activePage,y=(i.bleedVisible&&f.bleed,f.computedWidth*i.scale),b=f.computedHeight*i.scale,v=(l-y)/2,w=(c-b)/2,k=(E=e=>o({unitVal:e,dpi:i.dpi,unit:i.unit})*i.scale,d.find(e=>E(e)>30)||1e4);var E;const R=o({unitVal:k,dpi:i.dpi,unit:i.unit})*i.scale,S=Math.round(y/R)+1,z=Math.round(b/R)+1,F=t(i.selectedShapes);return e.createElement(r,{ref:g,className:"polotno-rulers",style:{display:"flex",flexDirection:"column"}},m?e.createElement(e.Fragment,null,e.createElement("div",{style:{display:"flex",flexDirection:"row",position:"sticky",top:0,zIndex:1}},e.createElement("div",{style:{width:"14px",height:"14px",flexShrink:0,backgroundColor:"#e8e8e8",borderRight:"1px solid grey",borderBottom:"1px solid grey",position:"sticky",left:0,zIndex:2}}),(x?[i.activePage]:i.pages).map((t,o)=>{var r;if(!t){return null}const n=h?h[o]:l,p=(n-t.computedWidth*i.scale)/2;return e.createElement(a,{key:t.id,style:{width:n+"px",flexShrink:0,position:"relative"},className:"polotno-x-ruler"},[...Array(S)].map((t,o)=>e.createElement(s,{key:o,style:{left:p+o*R+"px",width:R+"px"}},"px"===i.unit||k>=1?Math.round(k*o):(k*o).toFixed(1))),(null===(r=i.selectedShapes[0])||void 0===r?void 0:r.page)===t&&e.createElement("div",{style:{position:"absolute",left:p+F.x*i.scale+"px",height:"14px",width:F.width*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))})),e.createElement(n,{style:{height:c+"px",position:"sticky",left:0,marginTop:"-14px"},className:"polotno-y-ruler"},[...Array(z)].map((t,o)=>e.createElement(p,{key:o,style:{top:w+o*R+"px",width:R+"px"}},"px"===i.unit||k>=1?Math.round(k*o):(k*o).toFixed(1))),!!i.selectedShapes.length&&e.createElement("div",{style:{position:"absolute",top:w+F.y*i.scale+"px",width:"14px",height:F.height*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))):e.createElement(e.Fragment,null,e.createElement(a,{style:{width:l+"px"},className:"polotno-x-ruler"},[...Array(S)].map((t,o)=>e.createElement(s,{key:o,style:{left:v+o*R+"px",width:R+"px"}},"px"===i.unit||k>=1?Math.round(k*o):(k*o).toFixed(1))),!!i.selectedShapes.length&&e.createElement("div",{style:{position:"absolute",left:v+F.x*i.scale+"px",height:"14px",width:F.width*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}})),(x?[i.activePage]:i.pages).map((t,o)=>{var l;if(!t){return null}const r=h?h[o]:c,a=(r-t.computedHeight*i.scale)/2,s=0===o?14:0;return e.createElement(n,{key:t.id,style:{height:r-s+"px"},className:"polotno-y-ruler"},[...Array(z)].map((t,o)=>e.createElement(p,{key:o,style:{top:a+o*R-s+"px",width:R+"px"}},"px"===i.unit||k>=1?Math.round(k*o):(k*o).toFixed(1))),(null===(l=i.selectedShapes[0])||void 0===l?void 0:l.page)===t&&e.createElement("div",{style:{position:"absolute",top:a+F.y*i.scale-s+"px",width:"14px",height:F.height*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))})))});
39
+ `,p=[.1,.2,.5,1,2,5,10,20,25,50,100,200,500,1e3,2e3,5e3,1e4];export const TopRules=r(({store:r,width:l,height:c,pageSizes:u,layout:h="vertical",renderOnlyActivePage:x,rulerBackgroundColor:g,rulerTextColor:m,rulerBorderColor:f,rulerBorderSize:y,rulerTickColor:b,rulerTickSize:k})=>{const v=e.useRef(null);if(!r.activePage){return null}const w="horizontal"===h,$=r.activePage,E=(r.bleedVisible&&$.bleed,$.computedWidth*r.scale),N=$.computedHeight*r.scale,C=(l-E)/2,R=(c-N)/2,S=(z=e=>t({unitVal:e,dpi:r.dpi,unit:r.unit})*r.scale,p.find(e=>z(e)>30)||1e4);var z;const B=t({unitVal:S,dpi:r.dpi,unit:r.unit})*r.scale,F=Math.round(E/B)+1,M=Math.round(N/B)+1,A=o(r.selectedShapes),P=g||"#e8e8e8",T=m||"grey",L=f||"grey",j=null!=y?y:1,V=b||"grey",D=null!=k?k:1;return e.createElement(i,{ref:v,className:"polotno-rulers",style:{display:"flex",flexDirection:"column"}},w?e.createElement(e.Fragment,null,e.createElement("div",{style:{display:"flex",flexDirection:"row",position:"sticky",top:0,zIndex:1}},e.createElement("div",{className:"polotno-ruler-corner",style:{width:"14px",height:"14px",flexShrink:0,backgroundColor:P,borderRight:`${j}px solid ${L}`,borderBottom:`${j}px solid ${L}`,position:"sticky",left:0,zIndex:2}}),(x?[r.activePage]:r.pages).map((o,t)=>{var i;if(!o){return null}const s=u?u[t]:l,d=(s-o.computedWidth*r.scale)/2;return e.createElement(a,{key:o.id,style:{width:s+"px",flexShrink:0,position:"relative",backgroundColor:P,color:T,borderBottom:`${j}px solid ${L}`},className:"polotno-x-ruler"},[...Array(F)].map((o,t)=>e.createElement(n,{key:t,className:"polotno-ruler-tick",style:{left:d+t*B+"px",width:B+"px",borderLeft:`${D}px solid ${V}`}},"px"===r.unit||S>=1?Math.round(S*t):(S*t).toFixed(1))),(null===(i=r.selectedShapes[0])||void 0===i?void 0:i.page)===o&&e.createElement("div",{className:"polotno-ruler-selection",style:{position:"absolute",left:d+A.x*r.scale+"px",height:"14px",width:A.width*r.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))})),e.createElement(s,{style:{height:c+"px",position:"sticky",left:0,marginTop:"-14px",backgroundColor:P,color:T,borderRight:`${j}px solid ${L}`},className:"polotno-y-ruler"},[...Array(M)].map((o,t)=>e.createElement(d,{key:t,className:"polotno-ruler-tick",style:{top:R+t*B+"px",width:B+"px",borderLeft:`${D}px solid ${V}`}},"px"===r.unit||S>=1?Math.round(S*t):(S*t).toFixed(1))),!!r.selectedShapes.length&&e.createElement("div",{className:"polotno-ruler-selection",style:{position:"absolute",top:R+A.y*r.scale+"px",width:"14px",height:A.height*r.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))):e.createElement(e.Fragment,null,e.createElement(a,{style:{width:l+"px",backgroundColor:P,color:T,borderBottom:`${j}px solid ${L}`},className:"polotno-x-ruler"},[...Array(F)].map((o,t)=>e.createElement(n,{key:t,className:"polotno-ruler-tick",style:{left:C+t*B+"px",width:B+"px",borderLeft:`${D}px solid ${V}`}},"px"===r.unit||S>=1?Math.round(S*t):(S*t).toFixed(1))),!!r.selectedShapes.length&&e.createElement("div",{className:"polotno-ruler-selection",style:{position:"absolute",left:C+A.x*r.scale+"px",height:"14px",width:A.width*r.scale,backgroundColor:"rgba(0,0,0,0.15)"}})),(x?[r.activePage]:r.pages).map((o,t)=>{var l;if(!o){return null}const i=u?u[t]:c,a=(i-o.computedHeight*r.scale)/2,n=0===t?14:0;return e.createElement(s,{key:o.id,style:{height:i-n+"px",backgroundColor:P,color:T,borderRight:`${j}px solid ${L}`},className:"polotno-y-ruler"},[...Array(M)].map((o,t)=>e.createElement(d,{key:t,className:"polotno-ruler-tick",style:{top:a+t*B-n+"px",width:B+"px",borderLeft:`${D}px solid ${V}`}},"px"===r.unit||S>=1?Math.round(S*t):(S*t).toFixed(1))),(null===(l=r.selectedShapes[0])||void 0===l?void 0:l.page)===o&&e.createElement("div",{className:"polotno-ruler-selection",style:{position:"absolute",top:a+A.y*r.scale-n+"px",width:"14px",height:A.height*r.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))})))});
@@ -1 +1 @@
1
- import t from"react";import{observer as e}from"mobx-react-lite";import{Group as n,Path as o,Text as r,TextPath as i}from"react-konva";import{Html as a}from"react-konva-utils";import{autorun as l}from"mobx";import s from"konva";import{parsePath as d,roundCommands as c}from"svg-round-corners";import{useColor as h}from"./use-color.js";import{incrementLoader as u}from"../utils/loader.js";import{isFontLoaded as f}from"../utils/fonts.js";import{flags as g}from"../utils/flags.js";import{removeTags as m}from"../utils/text.js";import{getDir as w,getCurvePath as x,resolveLineHeight as p}from"../utils/text-html.js";import{applyFilter as v}from"./apply-filters.js";import{useFadeIn as y}from"./use-fadein.js";import{isTouchDevice as S}from"../utils/screen.js";import{isAlive as E}from"mobx-state-tree";import{getLimitedFontSize as b}from"./text-element/max-font-size.js";import{getOptimalCaretColor as z}from"./text-element/caret-color.js";let O;function k(){return O||(O=document.getElementById("polotno-text-style"),O||(O=document.createElement("style"),O.id="polotno-text-style",document.head.appendChild(O)),O)}s._fixTextRendering=!0;const A={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"../utils/text-html.js";const L=e(({textNodeRef:e,element:n,onBlur:o,selectAll:r,cursorPosition:i})=>{const[a,l]=t.useState(A),s=e.current;t.useLayoutEffect(()=>{const t={};t.width=s.width()-2*s.padding()+"px",t.height=s.height()-2*s.padding()+s.fontSize()*s.lineHeight()+"px",t.fontSize=s.fontSize()+"px",t.lineHeight=s.lineHeight()+.01,t.fontFamily=s.fontFamily(),t.textAlign=s.align(),t.color=s.fill(),t.fontWeight=n.fontWeight,t.fontStyle=n.fontStyle,t.letterSpacing=n.letterSpacing+"em",t.opacity=Math.max(n.a.opacity,.2),t.textTransform=n.textTransform,t.caretColor=z(n);const e=`\n .polotno-input::placeholder {\n color: ${a.color};\n opacity: 0.6;\n }\n `,o=k();o.innerHTML="",o.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(a)&&l(t)});const d=t.useRef(null);if(t.useLayoutEffect(()=>{var t;const e=d.current;if(!e){return}null===(t=d.current)||void 0===t||t.focus();const n=i||e.value.length;e.selectionStart=e.selectionEnd=n,r&&(null==e||e.select(),document.execCommand("selectAll",!1,null))},[]),t.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=d.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!s){return null}let c=0;const h=s.textArr.length*s.lineHeight()*s.fontSize();"middle"===n.verticalAlign&&(c=(n.a.height-h)/2),"bottom"===n.verticalAlign&&(c=n.a.height-h);const u=m(n.text);return t.createElement("textarea",{className:"polotno-input",ref:d,dir:w(u),style:Object.assign(Object.assign(Object.assign({},A),a),{paddingTop:c+"px"}),value:u,onChange:t=>{const e=b({oldText:n.text,newText:t.target.value,element:n});n.set({text:t.target.value,fontSize:e})},placeholder:n.placeholder,onBlur:o})}),$=e=>t.createElement(a,null,t.createElement(L,Object.assign({},e)));export const useFontLoader=(e,n)=>{const[o,r]=t.useReducer(t=>t+1,0),i=t.useRef(f(n)),a=t.useRef(null);return t.useLayoutEffect(()=>{if(i.current=f(n),i.current){return}let t=!0;return(async()=>{i.current=!1,r();const o=u(`text ${n}`);await e.loadFont(n),t?(a.current=o,i.current=!0,r()):o()})(),()=>{a.current&&(a.current(),a.current=null),t=!1}},[n]),t.useEffect(()=>{i.current&&setTimeout(()=>{a.current&&(a.current(),a.current=null)})},[i.current]),[i.current]};export const getLineHeight=({fontLoaded:e,fontFamily:n,fontSize:o,lineHeight:r})=>t.useMemo(()=>p({fontFamily:n,fontSize:o,lineHeight:r}),[e,n,o,r]);export function usePrevious(e){const n=t.useRef(e),o=t.useRef(e);return t.useMemo(()=>{o.current=n.current,n.current=e},[e]),o.current}export{getCurvePath}from"../utils/text-html.js";export const TextElement=e(({element:e,store:a})=>{const s=t.useRef(null),f=t.useRef(null),p=t.useRef(null),{editorEnabled:b,selectAll:z}=(e=>{const[n,o]=t.useState(!1),r=t.useRef(!1);return t.useEffect(()=>{var t=!0;return setTimeout(()=>{t&&(e._editModeEnabled&&(r.current=!0),o(!0),setTimeout(()=>{r.current=!1},50))},50),()=>{t=!1}},[]),{editorEnabled:n&&e._editModeEnabled,selectAll:r.current}})(e),[O,k]=t.useState(!1),A=t.useRef(e.a.height),L=a.selectedShapes.indexOf(e)>=0&&e.selectable,F=usePrevious(L),{textVerticalResizeEnabled:M}=g,R=g.autoDeleteEmptyText,j=usePrevious(e.fontFamily),[T,C]=t.useState([]);t.useEffect(()=>{var t,e;const n=null!==(e=null===(t=s.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(n)!==JSON.stringify(T)&&C(n)}),t.useEffect(()=>{if(e.a.width){return}const t=s.current;t.width(600),e.set({width:1.4*t.getTextWidth()})},[]),t.useEffect(()=>{F&&!L&&R&&""===e.text&&e.removable&&!e.placeholder&&a.deleteElements([e.id])},[R,e.placeholder,e.removable,e.text,L,F]),t.useLayoutEffect(()=>l(()=>{const t=s.current;v(t,e)}));const[H]=useFontLoader(a,e.fontFamily);let P=m(e.text);"uppercase"===e.textTransform&&(P=P.toUpperCase());const W=()=>{if(e.curveEnabled){const t=f.current;return t.getSelfRect().height||t.fontSize()}const t=s.current.clone({height:void 0}),n=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),n};t.useLayoutEffect(()=>{if(!H){return}const{textOverflow:t,textSplitAllowed:n}=g,o=(t,...n)=>{const o=u(`text ${e.id} before ignore`);a.history.ignore(t,...n).then(()=>{o()})};if(!e.a.height){const t=W();return void o(()=>{e.set({height:t})})}if(!a.isPlaying){if("change-font-size"!==t||O){if("resize"===t){const t=W();M&&e.a.height<t&&!O&&o(()=>{var n;E(e)&&e.set({height:t}),null===(n=s.current)||void 0===n||n.height(t)},!1,!0),M||e.a.height===t||O||o(()=>{var n;E(e)&&e.set({height:t}),null===(n=s.current)||void 0===n||n.height(t)},!1,!0)}}else{const t=function(t,e,n=!1){const o=t.fontSize(),r=t.height(),i=m(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const o=e.a.height&&t.height()>e.a.height;let r=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=r.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(o||s&&!n)){break}a-=.5,t.fontSize(a)}return t.fontSize(o),t.height(r),a}(s.current,e,n);if(t!==e.a.fontSize){return void o(()=>{e.set({fontSize:t})},!1,!0)}const r=W();e.a.height===r||M||o(()=>{e.set({height:r})},!1,!0)}}}),t.useLayoutEffect(()=>{var t;if(H&&e.curveEnabled){const n=null===(t=f.current)||void 0===t?void 0:t.getSelfRect().width;if(n){const t=n-e.a.width,o=e.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);e.set({width:n,x:e.a.x+r,y:e.a.y+i})}}},[H,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),t.useLayoutEffect(()=>{const t=s.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),v(t,e))},[H]);const X=t.useRef(null),Y=t.useRef(0),B=t=>{t.evt.preventDefault();const n=a.selectedShapes.find(t=>t===e);n&&e.contentEditable&&(Y.current=function(t){var e;const n=t.target,o=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var n=t.getStage().getPointerPosition();return e.point(n)}(n),r=n.textArr,i=Math.floor(o.y/(n.fontSize()*n.lineHeight())),a=r.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=r[i])&&void 0!==e?e:r[0];let s=0;return"right"===n.align()?s=n.width()-l.width:"center"===n.align()&&(s=n.width()/2-l.width/2),a+Math.round((o.x-s)/l.width*l.text.length)}(t),e.toggleEditMode())},D=!P&&e.placeholder?.6:e.a.opacity;y(s,D);const N=getLineHeight({fontLoaded:H,fontFamily:e.fontFamily,fontSize:e.a.fontSize,lineHeight:e.lineHeight}),I=e.selectable||"admin"===a.role,J=h(e),_=h(e,e.stroke,"stroke"),V=t.useMemo(()=>e.backgroundEnabled?e.curveEnabled?function({width:t,height:e,padding:n=0,cornerRadius:o=0}){const r=-n,i=-n,a=t+n,l=e+n,s=d(`M ${r} ${i} L ${a} ${i} L ${a} ${l} L ${r} ${l} Z`);return c(s,o).path}({width:e.a.width,height:e.a.height,cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*N*.5),padding:e.backgroundPadding*(e.a.fontSize*N*.5)}):function({lines:t,lineHeight:e,width:n,align:o="left",padding:r=0,cornerRadius:i=0}){var a;t.forEach((t,e)=>{t.cx=n/2,"right"===o?t.cx=n-t.width/2:"left"===o&&(t.cx=t.width/2),"justify"!==o||t.lastInParagraph||(t.width=n),"justify"===o&&(t.cx=t.width/2)});let l=`M ${null===(a=t[0])||void 0===a?void 0:a.cx} ${-r}`;t.forEach((n,o)=>{const{cx:i}=n,a=t[o-1];a&&a.width>n.width?l+=` L ${i+n.width/2+r} ${o*e+r}`:l+=` L ${i+n.width/2+r} ${o*e-r}`;const s=t[o+1];s&&s.width>n.width?l+=` L ${i+n.width/2+r} ${(o+1)*e-r}`:l+=` L ${i+n.width/2+r} ${(o+1)*e+r}`});for(var s=t.length-1;s>=0;s--){const n=t[s],{cx:o}=n,i=t[s+1];i&&i.width>n.width?l+=` L ${o-n.width/2-r} ${(s+1)*e-r}`:l+=` L ${o-n.width/2-r} ${(s+1)*e+r}`;const a=t[s-1];a&&a.width>n.width?l+=` L ${o-n.width/2-r} ${s*e+r}`:l+=` L ${o-n.width/2-r} ${s*e-r}`}l+=" Z";const h=d(l);return c(h,i).path}({lines:JSON.parse(JSON.stringify(T)),cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*N*.5),lineHeight:N*e.a.fontSize,padding:e.backgroundPadding*(e.a.fontSize*N*.5),width:e.a.width,align:e.align}):"",[e.backgroundEnabled,e.curveEnabled,e.backgroundCornerRadius,e.a.fontSize,e.a.height,N,e.backgroundPadding,e.a.width,e.align,T]),Z=S();let U=0;e.curveEnabled||("middle"===e.verticalAlign?U=(e.a.height-T.length*N*e.a.fontSize)/2:"bottom"===e.verticalAlign&&(U=e.a.height-T.length*N*e.a.fontSize));const q=e.curveEnabled?x(e.a.width,e.a.height,e.curvePower,e.a.fontSize):"",G=H?'"'+e.fontFamily+'"':j===e.fontFamily?"Arial":'"'+j+'"';return t.createElement(t.Fragment,null,t.createElement(o,{ref:p,x:e.a.x,y:e.a.y,rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*D,data:V,fill:e.backgroundColor,offsetY:-U}),t.createElement(o,{data:q,stroke:"red",strokeWidth:1,x:e.a.x,y:e.a.y,rotation:e.a.rotation,visible:!1}),t.createElement(i,Object.assign({ref:f,visible:e.curveEnabled,data:q,text:P||e.placeholder,listening:!1,align:"center",textBaseline:"middle"},J,_,{strokeWidth:e.strokeWidth,lineJoin:"round",fillAfterStrokeEnabled:!0,fontSize:e.a.fontSize,fontFamily:`"${e.fontFamily}", "${j}"`,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration.trim(),letterSpacing:e.letterSpacing*e.a.fontSize,x:e.a.x,y:e.a.y,rotation:e.a.rotation,opacity:e._editModeEnabled?.3:D,hideInExport:!e.showInExport,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity})),t.createElement(r,Object.assign({ref:s,id:e.id,name:"element",hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled,x:e.a.x,y:e.a.y,rotation:e.a.rotation,width:e.a.width,height:e.a.height,text:P||e.placeholder,direction:w(P)},J,_,{lineJoin:"round",strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.a.fontSize,fontFamily:G,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,verticalAlign:e.verticalAlign,draggable:Z?e.draggable&&L:e.draggable,preventDefault:!Z||L,opacity:e.curveEnabled?0:D,visible:!e._editModeEnabled,ellipsis:"ellipsis"===g.textOverflow,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,lineHeight:N,letterSpacing:e.letterSpacing*e.a.fontSize,listening:I,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},onClick:B,onTap:B,onTransformStart:()=>{k(!0),A.current=s.current.height()},onTransform:t=>{var n,o,r;const i=t.target;null===(n=p.current)||void 0===n||n.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(o=i.getStage())||void 0===o?void 0:o.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),n=i.width()*t,o=e.a.fontSize;let r=n;n<o&&(r=o,X.current&&i.position(X.current)),i.width(r),i.scaleX(1),i.scaleY(1);let a=W();if("ellipsis"===g.textOverflow){a=A.current}else{const t=Math.max(a,A.current);i.height(t),e.set({height:i.height()})}const l=g.textVerticalResizeEnabled?Math.max(a,A.current):W();e.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),v(i,e)}if("top-center"===a||"bottom-center"===a){let n="resize"===g.textOverflow?W():N*e.a.fontSize;t.target.height(Math.max(n,t.target.height()*t.target.scaleY())),t.target.scaleY(1)}X.current=t.target.position();const l=t.target.scaleX();null===(r=p.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:e.shadowBlur*l,shadowOffsetX:e.shadowOffsetX*l,shadowOffsetY:e.shadowOffsetY*l,strokeWidth:e.strokeWidth*l})},onTransformEnd:t=>{var n;const o=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:Math.round(e.a.fontSize*o),width:Math.ceil(t.target.width()*o),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*o,shadowBlur:e.shadowBlur*o,shadowOffsetX:e.shadowOffsetX*o,shadowOffsetY:e.shadowOffsetY*o,strokeWidth:e.strokeWidth*o}),null===(n=p.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),k(!1)}})),b&&t.createElement(n,{x:e.a.x,y:e.a.y,rotation:e.a.rotation},t.createElement($,{textNodeRef:s,element:e,selectAll:z,cursorPosition:Y.current,onBlur:()=>{e.toggleEditMode(!1)}})))});
1
+ import t from"react";import{observer as e}from"mobx-react-lite";import{Group as n,Path as o,Text as r,TextPath as i}from"react-konva";import{Html as a}from"react-konva-utils";import{autorun as l}from"mobx";import s from"konva";import{parsePath as c,roundCommands as d}from"svg-round-corners";import{useColor as h}from"./use-color.js";import{incrementLoader as u}from"../utils/loader.js";import{isFontLoaded as f}from"../utils/fonts.js";import{flags as g}from"../utils/flags.js";import{removeTags as m}from"../utils/text.js";import{getDir as w,getCurvePath as p,resolveLineHeight as x}from"../utils/text-html.js";import{applyFilter as v}from"./apply-filters.js";import{useFadeIn as y}from"./use-fadein.js";import{isTouchDevice as E}from"../utils/screen.js";import{isAlive as S}from"mobx-state-tree";import{getLimitedFontSize as b}from"./text-element/max-font-size.js";import{getOptimalCaretColor as z}from"./text-element/caret-color.js";let O;function k(){return O||(O=document.getElementById("polotno-text-style"),O||(O=document.createElement("style"),O.id="polotno-text-style",document.head.appendChild(O)),O)}s._fixTextRendering=!0;const A={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"../utils/text-html.js";const L=e(({textNodeRef:e,element:n,onBlur:o,selectAll:r,cursorPosition:i})=>{const[a,l]=t.useState(A),s=e.current;t.useLayoutEffect(()=>{const t={};t.width=s.width()-2*s.padding()+"px",t.height=s.height()-2*s.padding()+s.fontSize()*s.lineHeight()+"px",t.fontSize=s.fontSize()+"px",t.lineHeight=s.lineHeight()+.01,t.fontFamily=s.fontFamily(),t.textAlign=s.align(),t.color=s.fill(),t.fontWeight=n.fontWeight,t.fontStyle=n.fontStyle,t.letterSpacing=n.letterSpacing+"em",t.opacity=Math.max(n.a.opacity,.2),t.textTransform=n.textTransform,t.caretColor=z(n);const e=`\n .polotno-input::placeholder {\n color: ${a.color};\n opacity: 0.6;\n }\n `,o=k();o.innerHTML="",o.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(a)&&l(t)});const c=t.useRef(null);if(t.useLayoutEffect(()=>{var t;const e=c.current;if(!e){return}null===(t=c.current)||void 0===t||t.focus();const n=i||e.value.length;e.selectionStart=e.selectionEnd=n,r&&(null==e||e.select(),document.execCommand("selectAll",!1,null))},[]),t.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=c.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!s){return null}let d=0;const h=s.textArr.length*s.lineHeight()*s.fontSize();"middle"===n.verticalAlign&&(d=(n.a.height-h)/2),"bottom"===n.verticalAlign&&(d=n.a.height-h);const u=m(n.text);return t.createElement("textarea",{className:"polotno-input",ref:c,dir:w(u),style:Object.assign(Object.assign(Object.assign({},A),a),{paddingTop:d+"px"}),value:u,onChange:t=>{const e=b({oldText:n.text,newText:t.target.value,element:n});n.set({text:t.target.value,fontSize:e})},placeholder:n.placeholder,onBlur:o})}),$=e=>t.createElement(a,null,t.createElement(L,Object.assign({},e)));export const useFontLoader=(e,n)=>{const[o,r]=t.useReducer(t=>t+1,0),i=t.useRef(f(n)),a=t.useRef(null);return t.useLayoutEffect(()=>{if(i.current=f(n),i.current){return}let t=!0;return(async()=>{i.current=!1,r();const o=u(`text ${n}`);await e.loadFont(n),t?(a.current=o,i.current=!0,r()):o()})(),()=>{a.current&&(a.current(),a.current=null),t=!1}},[n]),t.useEffect(()=>{i.current&&setTimeout(()=>{a.current&&(a.current(),a.current=null)})},[i.current]),[i.current]};export const getLineHeight=({fontLoaded:e,fontFamily:n,fontSize:o,lineHeight:r})=>t.useMemo(()=>x({fontFamily:n,fontSize:o,lineHeight:r}),[e,n,o,r]);export function usePrevious(e){const n=t.useRef(e),o=t.useRef(e);return t.useMemo(()=>{o.current=n.current,n.current=e},[e]),o.current}export{getCurvePath}from"../utils/text-html.js";export const TextElement=e(({element:e,store:a})=>{const s=t.useRef(null),f=t.useRef(null),x=t.useRef(null),b=t.useRef([]),[,z]=t.useReducer(t=>t+1,0),{editorEnabled:O,selectAll:k}=(e=>{const[n,o]=t.useState(!1),r=t.useRef(!1);return t.useEffect(()=>{var t=!0;return setTimeout(()=>{t&&(e._editModeEnabled&&(r.current=!0),o(!0),setTimeout(()=>{r.current=!1},50))},50),()=>{t=!1}},[]),{editorEnabled:n&&e._editModeEnabled,selectAll:r.current}})(e),[A,L]=t.useState(!1),F=t.useRef(e.a.height),R=a.selectedShapes.indexOf(e)>=0&&e.selectable,M=usePrevious(R),{textVerticalResizeEnabled:j}=g,T=g.autoDeleteEmptyText,C=usePrevious(e.fontFamily),[H,P]=t.useState([]);t.useEffect(()=>{var t,e;const n=null!==(e=null===(t=s.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(n)!==JSON.stringify(H)&&P(n)}),t.useEffect(()=>{if(e.a.width){return}const t=s.current;t.width(600),e.set({width:1.4*t.getTextWidth()})},[]),t.useEffect(()=>{M&&!R&&T&&""===e.text&&e.removable&&!e.placeholder&&a.deleteElements([e.id])},[T,e.placeholder,e.removable,e.text,R,M]),t.useLayoutEffect(()=>l(()=>{const t=s.current;v(t,e)})),t.useEffect(()=>{const t=b.current;t.length>0&&(b.current=[],t.forEach(t=>t()))});const[W]=useFontLoader(a,e.fontFamily);let X=m(e.text);"uppercase"===e.textTransform&&(X=X.toUpperCase());const Y=()=>{if(e.curveEnabled){const t=f.current;return t.getSelfRect().height||t.fontSize()}const t=s.current.clone({height:void 0}),n=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),n};t.useLayoutEffect(()=>{if(!W){return}const{textOverflow:t,textSplitAllowed:n}=g,o=(t,...n)=>{const o=u(`text ${e.id} before ignore`);a.history.ignore(t,...n).then(()=>{b.current.push(o),z()})};if(!e.a.height){const t=Y();return void o(()=>{e.set({height:t})})}if(!a.isPlaying){if("change-font-size"!==t||A){if("resize"===t){const t=Y();j&&e.a.height<t&&!A&&o(()=>{var n;S(e)&&e.set({height:t}),null===(n=s.current)||void 0===n||n.height(t)},!1,!0),j||e.a.height===t||A||o(()=>{var n;S(e)&&e.set({height:t}),null===(n=s.current)||void 0===n||n.height(t)},!1,!0)}}else{const t=function(t,e,n=!1){const o=t.fontSize(),r=t.height(),i=m(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const o=e.a.height&&t.height()>e.a.height;let r=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=r.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(o||s&&!n)){break}a-=.5,t.fontSize(a)}return t.fontSize(o),t.height(r),a}(s.current,e,n);if(t!==e.a.fontSize){return void o(()=>{e.set({fontSize:t})},!1,!0)}const r=Y();e.a.height===r||j||o(()=>{e.set({height:r})},!1,!0)}}}),t.useLayoutEffect(()=>{var t;if(W&&e.curveEnabled){const n=null===(t=f.current)||void 0===t?void 0:t.getSelfRect().width;if(n){const t=n-e.a.width,o=e.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);e.set({width:n,x:e.a.x+r,y:e.a.y+i})}}},[W,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),t.useLayoutEffect(()=>{const t=s.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),v(t,e))},[W]);const B=t.useRef(null),D=t.useRef(0),N=t=>{t.evt.preventDefault();const n=a.selectedShapes.find(t=>t===e);n&&e.contentEditable&&(D.current=function(t){var e;const n=t.target,o=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var n=t.getStage().getPointerPosition();return e.point(n)}(n),r=n.textArr,i=Math.floor(o.y/(n.fontSize()*n.lineHeight())),a=r.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=r[i])&&void 0!==e?e:r[0];let s=0;return"right"===n.align()?s=n.width()-l.width:"center"===n.align()&&(s=n.width()/2-l.width/2),a+Math.round((o.x-s)/l.width*l.text.length)}(t),e.toggleEditMode())},I=!X&&e.placeholder?.6:e.a.opacity;y(s,I);const J=getLineHeight({fontLoaded:W,fontFamily:e.fontFamily,fontSize:e.a.fontSize,lineHeight:e.lineHeight}),_=e.selectable||"admin"===a.role,V=h(e),Z=h(e,e.stroke,"stroke"),U=t.useMemo(()=>e.backgroundEnabled?e.curveEnabled?function({width:t,height:e,padding:n=0,cornerRadius:o=0}){const r=-n,i=-n,a=t+n,l=e+n,s=c(`M ${r} ${i} L ${a} ${i} L ${a} ${l} L ${r} ${l} Z`);return d(s,o).path}({width:e.a.width,height:e.a.height,cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*J*.5),padding:e.backgroundPadding*(e.a.fontSize*J*.5)}):function({lines:t,lineHeight:e,width:n,align:o="left",padding:r=0,cornerRadius:i=0}){var a;t.forEach((t,e)=>{t.cx=n/2,"right"===o?t.cx=n-t.width/2:"left"===o&&(t.cx=t.width/2),"justify"!==o||t.lastInParagraph||(t.width=n),"justify"===o&&(t.cx=t.width/2)});let l=`M ${null===(a=t[0])||void 0===a?void 0:a.cx} ${-r}`;t.forEach((n,o)=>{const{cx:i}=n,a=t[o-1];a&&a.width>n.width?l+=` L ${i+n.width/2+r} ${o*e+r}`:l+=` L ${i+n.width/2+r} ${o*e-r}`;const s=t[o+1];s&&s.width>n.width?l+=` L ${i+n.width/2+r} ${(o+1)*e-r}`:l+=` L ${i+n.width/2+r} ${(o+1)*e+r}`});for(var s=t.length-1;s>=0;s--){const n=t[s],{cx:o}=n,i=t[s+1];i&&i.width>n.width?l+=` L ${o-n.width/2-r} ${(s+1)*e-r}`:l+=` L ${o-n.width/2-r} ${(s+1)*e+r}`;const a=t[s-1];a&&a.width>n.width?l+=` L ${o-n.width/2-r} ${s*e+r}`:l+=` L ${o-n.width/2-r} ${s*e-r}`}l+=" Z";const h=c(l);return d(h,i).path}({lines:JSON.parse(JSON.stringify(H)),cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*J*.5),lineHeight:J*e.a.fontSize,padding:e.backgroundPadding*(e.a.fontSize*J*.5),width:e.a.width,align:e.align}):"",[e.backgroundEnabled,e.curveEnabled,e.backgroundCornerRadius,e.a.fontSize,e.a.height,J,e.backgroundPadding,e.a.width,e.align,H]),q=E();let G=0;e.curveEnabled||("middle"===e.verticalAlign?G=(e.a.height-H.length*J*e.a.fontSize)/2:"bottom"===e.verticalAlign&&(G=e.a.height-H.length*J*e.a.fontSize));const K=e.curveEnabled?p(e.a.width,e.a.height,e.curvePower,e.a.fontSize):"",Q=W?'"'+e.fontFamily+'"':C===e.fontFamily?"Arial":'"'+C+'"';return t.createElement(t.Fragment,null,t.createElement(o,{ref:x,x:e.a.x,y:e.a.y,rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*I,data:U,fill:e.backgroundColor,offsetY:-G}),t.createElement(o,{data:K,stroke:"red",strokeWidth:1,x:e.a.x,y:e.a.y,rotation:e.a.rotation,visible:!1}),t.createElement(i,Object.assign({ref:f,visible:e.curveEnabled,data:K,text:X||e.placeholder,listening:!1,align:"center",textBaseline:"middle"},V,Z,{strokeWidth:e.strokeWidth,lineJoin:"round",fillAfterStrokeEnabled:!0,fontSize:e.a.fontSize,fontFamily:`"${e.fontFamily}", "${C}"`,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration.trim(),letterSpacing:e.letterSpacing*e.a.fontSize,x:e.a.x,y:e.a.y,rotation:e.a.rotation,opacity:e._editModeEnabled?.3:I,hideInExport:!e.showInExport,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity})),t.createElement(r,Object.assign({ref:s,id:e.id,name:"element",hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled,x:e.a.x,y:e.a.y,rotation:e.a.rotation,width:e.a.width,height:e.a.height,text:X||e.placeholder,direction:w(X)},V,Z,{lineJoin:"round",strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.a.fontSize,fontFamily:Q,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,verticalAlign:e.verticalAlign,draggable:q?e.draggable&&R:e.draggable,preventDefault:!q||R,opacity:e.curveEnabled?0:I,visible:!e._editModeEnabled,ellipsis:"ellipsis"===g.textOverflow,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,lineHeight:J,letterSpacing:e.letterSpacing*e.a.fontSize,listening:_,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},onClick:N,onTap:N,onTransformStart:()=>{L(!0),F.current=s.current.height()},onTransform:t=>{var n,o,r;const i=t.target;null===(n=x.current)||void 0===n||n.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(o=i.getStage())||void 0===o?void 0:o.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),n=i.width()*t,o=e.a.fontSize;let r=n;n<o&&(r=o,B.current&&i.position(B.current)),i.width(r),i.scaleX(1),i.scaleY(1);let a=Y();if("ellipsis"===g.textOverflow){a=F.current}else{const t=Math.max(a,F.current);i.height(t),e.set({height:i.height()})}const l=g.textVerticalResizeEnabled?Math.max(a,F.current):Y();e.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),v(i,e)}if("top-center"===a||"bottom-center"===a){let n="resize"===g.textOverflow?Y():J*e.a.fontSize;t.target.height(Math.max(n,t.target.height()*t.target.scaleY())),t.target.scaleY(1)}B.current=t.target.position();const l=t.target.scaleX();null===(r=x.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:e.shadowBlur*l,shadowOffsetX:e.shadowOffsetX*l,shadowOffsetY:e.shadowOffsetY*l,strokeWidth:e.strokeWidth*l})},onTransformEnd:t=>{var n;const o=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:Math.round(e.a.fontSize*o),width:Math.ceil(t.target.width()*o),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*o,shadowBlur:e.shadowBlur*o,shadowOffsetX:e.shadowOffsetX*o,shadowOffsetY:e.shadowOffsetY*o,strokeWidth:e.strokeWidth*o}),null===(n=x.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),L(!1)}})),O&&t.createElement(n,{x:e.a.x,y:e.a.y,rotation:e.a.rotation},t.createElement($,{textNodeRef:s,element:e,selectAll:k,cursorPosition:D.current,onBlur:()=>{e.toggleEditMode(!1)}})))});
@@ -19,6 +19,12 @@ export type WorkspaceProps = {
19
19
  distanceGuideStroke?: string;
20
20
  distanceLabelFill?: string;
21
21
  distanceLabelTextFill?: string;
22
+ rulerBackgroundColor?: string;
23
+ rulerTextColor?: string;
24
+ rulerBorderColor?: string;
25
+ rulerBorderSize?: number;
26
+ rulerTickColor?: string;
27
+ rulerTickSize?: number;
22
28
  components?: any;
23
29
  onKeyDown?: (e: KeyboardEvent, store: StoreType) => void;
24
30
  paddingX?: number;
@@ -34,7 +40,7 @@ export type WorkspaceProps = {
34
40
  right?: number;
35
41
  };
36
42
  };
37
- export declare const WorkspaceCanvas: (({ store, layout, pageControlsEnabled, backgroundColor, pageBorderColor, activePageBorderColor, bleedColor, snapGuideStroke, snapGuideStrokeWidth, snapGuideDash, selectionRectFill, selectionRectStroke, selectionRectStrokeWidth, transformLabelFill, transformLabelTextFill, distanceGuideStroke, distanceLabelFill, distanceLabelTextFill, components, onKeyDown, paddingX, paddingY, pageGap, altCloneEnabled, visiblePagesOffset, renderOnlyActivePage, tooltipSafeArea, }: WorkspaceProps) => React.JSX.Element) & {
43
+ export declare const WorkspaceCanvas: (({ store, layout, pageControlsEnabled, backgroundColor, pageBorderColor, activePageBorderColor, bleedColor, snapGuideStroke, snapGuideStrokeWidth, snapGuideDash, selectionRectFill, selectionRectStroke, selectionRectStrokeWidth, transformLabelFill, transformLabelTextFill, distanceGuideStroke, distanceLabelFill, distanceLabelTextFill, rulerBackgroundColor, rulerTextColor, rulerBorderColor, rulerBorderSize, rulerTickColor, rulerTickSize, components, onKeyDown, paddingX, paddingY, pageGap, altCloneEnabled, visiblePagesOffset, renderOnlyActivePage, tooltipSafeArea, }: WorkspaceProps) => React.JSX.Element) & {
38
44
  displayName: string;
39
45
  };
40
46
  export default WorkspaceCanvas;
@@ -1 +1 @@
1
- import e from"react";import{observer as t}from"mobx-react-lite";import r from"./page.js";import{TopRules as n}from"./rules.js";import{AudioElement as o}from"./audio.js";import{handleHotkey as i}from"./hotkeys.js";import{t as l}from"../utils/l10n.js";const a=(e,t,r)=>Math.max(t,Math.min(r,e)),s=(e,t)=>Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2)),c=({store:t})=>e.createElement("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"}},e.createElement("p",null,l("workspace.noPages")),e.createElement("button",{onClick:()=>{t.addPage()}},l("workspace.addPage"))),u=({width:t,height:r,xPadding:n,yPadding:o,backgroundColor:i})=>e.createElement("div",{style:{width:t+"px",height:r+"px",backgroundColor:i,paddingLeft:n+"px",paddingRight:n+"px",paddingTop:o+"px",paddingBottom:o+"px",flexShrink:0}},e.createElement("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})),d=[4,6];export const WorkspaceCanvas=t(({store:t,layout:l="vertical",pageControlsEnabled:h,backgroundColor:g,pageBorderColor:p,activePageBorderColor:f,bleedColor:m,snapGuideStroke:v,snapGuideStrokeWidth:b,snapGuideDash:w,selectionRectFill:x,selectionRectStroke:k,selectionRectStrokeWidth:E,transformLabelFill:y,transformLabelTextFill:L,distanceGuideStroke:T,distanceLabelFill:M,distanceLabelTextFill:P,components:R,onKeyDown:S,paddingX:C,paddingY:F,pageGap:O,altCloneEnabled:W=!0,visiblePagesOffset:z,renderOnlyActivePage:j,tooltipSafeArea:G})=>{var _;const B="horizontal"===l,Y=null!=C?C:20,D=null!=F?F:55,[X,A]=e.useState({width:100,height:100}),N=e.useRef(X),H=e.useRef(null),I=e.useRef(null),K=e.useRef(0),q=t.bleedVisible?Math.max(0,...t.pages.map(e=>e.bleed)):0,V=Math.max(...t.pages.map(e=>e.computedWidth)),J=Math.max(...t.pages.map(e=>e.computedHeight)),Q=(null===(_=t.activePage)||void 0===_?void 0:_.computedHeight)||0,U=V+2*q,Z=(j?Q:J)+2*q,$=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===H.current){return}const r=H.current.getBoundingClientRect();0!==r.width&&0!==r.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(H.current));const n=I.current.clientWidth||r.width,o={width:n,height:r.height};(N.current.width!==o.width||N.current.height!==o.height)&&(A(o),N.current=o);const i=(n-2*Y)/U,l=t.pages.length>1?3.1:2,a=(r.height-D*l)/Z,s=t.pages.length>1?3.1:2,c=(n-Y*s)/U,u=(r.height-2*D)/Z,d=t.pages.length?Math.max(Math.min(B?c:i,B?u:a),.01):1;t.scaleToFit!==d&&(t.setScale(d),t._setScaleToFit(d))};e.useLayoutEffect(()=>{$({skipTimeout:!0})},[]),e.useEffect(()=>{$()},[U,Z,F,C]),e.useLayoutEffect(()=>{$({skipTimeout:!0})},[t.openedSidePanel]),e.useEffect(()=>{t.__()},[]),e.useEffect(()=>{const e=H.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{$({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{$({skipTimeout:!0})},100);return()=>clearInterval(e)}},[U,Z]);const ee=j?1:t.pages.length;let te,re;if(B){const e=U*t.scale*ee;te=Math.max(Y,(X.width-e)/ee/2),re=Math.max(D,(X.height-Z*t.scale)/2)}else{te=Math.max(Y,(X.width-U*t.scale)/2);const e=Z*t.scale*ee;re=Math.max(D,(X.height-e)/ee/2)}e.useEffect(()=>{const e=e=>{(S||i)(e,t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),e.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const r=Math.max(5,t.scaleToFit);let n=Math.min(.1,t.scaleToFit);B&&U>0&&Number.isFinite(U)&&(n=Math.max(n,300/U)),n=Math.max(n,.01);const o=.03,i=a(e.deltaY<0?t.scale*(1+o):t.scale/(1+o),n,r);return void t.setScale(i)}},r=I.current;return null==r||r.addEventListener("wheel",e),()=>null==r?void 0:r.removeEventListener("wheel",e)},[B,U,t]),e.useEffect(()=>{const e=I.current;if(!e){return}const r=e=>{2===e.touches.length&&(K.current=s(e.touches[0],e.touches[1]))},n=r=>{if(2===r.touches.length&&K.current>0){r.preventDefault();const n=s(r.touches[0],r.touches[1]),o=n/K.current,i=Math.max(5,t.scaleToFit);let l=Math.min(.1,t.scaleToFit);B&&U>0&&Number.isFinite(U)&&(l=Math.max(l,300/U)),l=Math.max(l,.01);const c=t.scale,u=a(c*o,l,i),d=u/c,h=e.getBoundingClientRect(),g=(r.touches[0].clientX+r.touches[1].clientX)/2-h.left,p=(r.touches[0].clientY+r.touches[1].clientY)/2-h.top,f=e.scrollLeft+g,m=e.scrollTop+p;ae.current=!0,t.setScale(u),e.scrollLeft=f*d-g,e.scrollTop=m*d-p,K.current=n}},o=()=>{K.current=0};return e.addEventListener("touchstart",r,{passive:!0}),e.addEventListener("touchmove",n,{passive:!1}),e.addEventListener("touchend",o,{passive:!0}),()=>{e.removeEventListener("touchstart",r),e.removeEventListener("touchmove",n),e.removeEventListener("touchend",o)}},[B,U,t]);const ne=void 0!==O,oe=e.useMemo(()=>t.pages.map(e=>{if(B){const r=(e.computedWidth+2*q)*t.scale;return ne?r+O:r+2*te}{const r=(e.computedHeight+2*q)*t.scale;return ne?r+O:r+2*re}}),[t.pages,t.scale,q,te,re,O,B,ne]),ie=e.useMemo(()=>{const e=[];let t=ne?B?te:re:0;for(let r=0;r<oe.length;r++){e.push(t),t+=oe[r]}return e},[oe,ne,B,te,re]),le=e.useMemo(()=>{const e=oe.reduce((e,t)=>e+t,0);return ne?e+(B?2*te:2*re):e},[oe,ne,B,te,re]),ae=e.useRef(!1),[,se]=e.useReducer(e=>e+1,0);((t,r,n,o,i,l)=>{const a=e.useRef(r),s=e.useRef(0),c=e.useRef(!1),u=e.useRef(o.pages.length);c.current=u.current!==o.pages.length,u.current=o.pages.length,e.useEffect(()=>{const e=t.current,r=t=>{s.current=l?e.scrollLeft:e.scrollTop};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[l]),e.useLayoutEffect(()=>{if(!t.current){return}if(c.current){return}const e=t.current,n=l?e.offsetWidth:e.offsetHeight,o=(s.current+n/2)/a.current;i.current=!0;const u=o*r-n/2;l?e.scrollLeft=u:e.scrollTop=u,a.current=r},[n,r,l])})(I,le,t.scale,t,ae,B);const{handleScroll:ce}=((t,r,n,o,i,l,a,s,c)=>{const u=e.useRef(!1),d=e.useRef(null),h=e.useRef(!1),g="horizontal"===s;e.useEffect(()=>{const e=t.current,r=()=>{l.current};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[]);const p=o.pages.indexOf(o.activePage);return e.useLayoutEffect(()=>{if(a){return}if(!o.activePage){return}if(!t.current){return}if(u.current){return}const e=t.current,i=o.pages.indexOf(o.activePage),l=r[i]||0,s=g?e.scrollLeft:e.scrollTop,d=n[i]||n[0]||0;let p=()=>{};return(Math.abs(l-s)>.5*d||h.current)&&(h.current=!0,p=(({element:e,scrollTop:t,scrollLeft:r,duration:n=300,onFinish:o=()=>{}})=>{const i=void 0!==t,l=i?e.scrollTop:e.scrollLeft,a=i?t:r,s=a-l;let c=0,u=!1;if(0===n){return i?e.scrollTop=a:e.scrollLeft=a,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,l,s,n);i?e.scrollTop=t:e.scrollLeft=t,c<n?setTimeout(d,20):o()},h=(e,t,r,n)=>(e/=n/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:e},g?{scrollLeft:l}:{scrollTop:l}),{onFinish:()=>{h.current=!1,null==c||c()},duration:o.isPlaying?0:300}))),p},[o.activePage,p,o.isPlaying,a,s,r,n]),{handleScroll:e=>{if(a){return}if(h.current){return}u.current=!0,clearTimeout(d.current),d.current=setTimeout(()=>{u.current=!1},300);const t=(g?e.currentTarget.scrollLeft:e.currentTarget.scrollTop)+(g?i.width:i.height)/3;let n=0;for(let o=r.length-1;o>=0;o--){if(t>=r[o]){n=o;break}}const l=o.pages[n];l&&o.activePage!==l&&l.select()}}})(I,ie,oe,t,X,ae,j,l,se),ue=X.width>=U*t.scale+2*te,de=X.height>=Z*t.scale+2*re,he=g||"rgba(232, 232, 232, 0.9)",ge=(null==R?void 0:R.NoPages)||c,pe=B?X.width:X.height,fe=I.current?B?I.current.scrollLeft:I.current.scrollTop:0,me=e=>{for(let t=ie.length-1;t>=0;t--){if(e>=ie[t]){return t}}return 0},ve=Math.max(0,me(fe)),be=Math.min(t.pages.length-1,me(fe+pe)),we=null!=z?z:1,xe=Math.max(0,ve-we),ke=Math.min(t.pages.length-1,be+we);return e.createElement("div",{ref:H,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:he,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container"},e.createElement("div",{ref:I,onScroll:ce,style:Object.assign({position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:B?"row":"column",overflow:"auto",overflowX:B?"auto":ue?"hidden":"auto",overflowY:B&&de?"hidden":"auto"},ne&&{paddingTop:B?0:re,paddingBottom:B?0:re,paddingLeft:B?te:0,paddingRight:B?te:0,boxSizing:"border-box"}),className:"polotno-workspace-inner"},t.pages.map((n,o)=>{const i=n===t.activePage;if(j&&!i&&!n._exportingOrRendering&&!n._forceMount){return null}const a=i||o>=xe&&o<=ke||n._exportingOrRendering||n._forceMount,s=B?oe[o]:U*t.scale+2*te,c=B?Z*t.scale+2*re:oe[o];if(!a){return e.createElement("div",{key:n.id,style:{flexShrink:0}},e.createElement(u,{width:s,height:c,backgroundColor:he,xPadding:te,yPadding:re}))}const g=e.createElement(r,{key:n.id,page:n,xPadding:te,yPadding:re,width:s,height:c,store:t,pageControlsEnabled:h,backColor:he,pageBorderColor:p||"lightgrey",activePageBorderColor:f||"rgb(0, 161, 255)",altCloneEnabled:W,bleedColor:m||"rgba(255, 0, 0, 0.1)",selectionRectFill:x,selectionRectStroke:k,selectionRectStrokeWidth:E,snapGuideStroke:v||"rgb(0, 161, 255)",snapGuideStrokeWidth:b||1,snapGuideDash:w||d,transformLabelFill:y,transformLabelTextFill:L,distanceGuideStroke:T||"rgb(0, 161, 255)",distanceLabelFill:M||"rgb(0, 161, 255)",distanceLabelTextFill:P||"white",components:R,viewportSize:X,layout:l,tooltipSafeArea:G});return(n._exportingOrRendering||n._forceMount)&&!i&&j?e.createElement("div",{style:{display:"none",flexShrink:0},key:n.id},g):g}),t.rulesVisible&&e.createElement(n,{store:t,xPadding:te,yPadding:re,width:U*t.scale+2*te,height:Z*t.scale+2*re,pageSizes:oe,layout:l,renderOnlyActivePage:j}),0===t.pages.length&&e.createElement(ge,{store:t}),t.audios.map(r=>e.createElement(o,{key:r.id,audio:r,store:t}))))});export default WorkspaceCanvas;
1
+ import e from"react";import{observer as t}from"mobx-react-lite";import r from"./page.js";import{TopRules as n}from"./rules.js";import{AudioElement as o}from"./audio.js";import{handleHotkey as l}from"./hotkeys.js";import{t as i}from"../utils/l10n.js";const a=(e,t,r)=>Math.max(t,Math.min(r,e)),s=(e,t)=>Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2)),c=({store:t})=>e.createElement("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"}},e.createElement("p",null,i("workspace.noPages")),e.createElement("button",{onClick:()=>{t.addPage()}},i("workspace.addPage"))),u=({width:t,height:r,xPadding:n,yPadding:o,backgroundColor:l})=>e.createElement("div",{style:{width:t+"px",height:r+"px",backgroundColor:l,paddingLeft:n+"px",paddingRight:n+"px",paddingTop:o+"px",paddingBottom:o+"px",flexShrink:0}},e.createElement("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})),d=[4,6];export const WorkspaceCanvas=t(({store:t,layout:i="vertical",pageControlsEnabled:h,backgroundColor:g,pageBorderColor:p,activePageBorderColor:f,bleedColor:m,snapGuideStroke:v,snapGuideStrokeWidth:b,snapGuideDash:w,selectionRectFill:x,selectionRectStroke:k,selectionRectStrokeWidth:E,transformLabelFill:T,transformLabelTextFill:y,distanceGuideStroke:L,distanceLabelFill:M,distanceLabelTextFill:S,rulerBackgroundColor:C,rulerTextColor:P,rulerBorderColor:R,rulerBorderSize:F,rulerTickColor:z,rulerTickSize:B,components:O,onKeyDown:W,paddingX:j,paddingY:G,pageGap:_,altCloneEnabled:Y=!0,visiblePagesOffset:D,renderOnlyActivePage:X,tooltipSafeArea:A})=>{var N;const H="horizontal"===i,I=null!=j?j:20,K=null!=G?G:55,[q,V]=e.useState({width:100,height:100}),J=e.useRef(q),Q=e.useRef(null),U=e.useRef(null),Z=e.useRef(0),$=t.bleedVisible?Math.max(0,...t.pages.map(e=>e.bleed)):0,ee=Math.max(...t.pages.map(e=>e.computedWidth)),te=Math.max(...t.pages.map(e=>e.computedHeight)),re=(null===(N=t.activePage)||void 0===N?void 0:N.computedHeight)||0,ne=ee+2*$,oe=(X?re:te)+2*$,le=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===Q.current){return}const r=Q.current.getBoundingClientRect();0!==r.width&&0!==r.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(Q.current));const n=U.current.clientWidth||r.width,o={width:n,height:r.height};(J.current.width!==o.width||J.current.height!==o.height)&&(V(o),J.current=o);const l=(n-2*I)/ne,i=t.pages.length>1?3.1:2,a=(r.height-K*i)/oe,s=t.pages.length>1?3.1:2,c=(n-I*s)/ne,u=(r.height-2*K)/oe,d=t.pages.length?Math.max(Math.min(H?c:l,H?u:a),.01):1;t.scaleToFit!==d&&(t.setScale(d),t._setScaleToFit(d))};e.useLayoutEffect(()=>{le({skipTimeout:!0})},[]),e.useEffect(()=>{le()},[ne,oe,G,j]),e.useLayoutEffect(()=>{le({skipTimeout:!0})},[t.openedSidePanel]),e.useEffect(()=>{t.__()},[]),e.useEffect(()=>{const e=Q.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{le({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{le({skipTimeout:!0})},100);return()=>clearInterval(e)}},[ne,oe]);const ie=X?1:t.pages.length;let ae,se;if(H){const e=ne*t.scale*ie;ae=Math.max(I,(q.width-e)/ie/2),se=Math.max(K,(q.height-oe*t.scale)/2)}else{ae=Math.max(I,(q.width-ne*t.scale)/2);const e=oe*t.scale*ie;se=Math.max(K,(q.height-e)/ie/2)}e.useEffect(()=>{const e=e=>{(W||l)(e,t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),e.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const r=Math.max(5,t.scaleToFit);let n=Math.min(.1,t.scaleToFit);H&&ne>0&&Number.isFinite(ne)&&(n=Math.max(n,300/ne)),n=Math.max(n,.01);const o=.03,l=a(e.deltaY<0?t.scale*(1+o):t.scale/(1+o),n,r);return void t.setScale(l)}},r=U.current;return null==r||r.addEventListener("wheel",e),()=>null==r?void 0:r.removeEventListener("wheel",e)},[H,ne,t]),e.useEffect(()=>{const e=U.current;if(!e){return}const r=e=>{2===e.touches.length&&(Z.current=s(e.touches[0],e.touches[1]))},n=r=>{if(2===r.touches.length&&Z.current>0){r.preventDefault();const n=s(r.touches[0],r.touches[1]),o=n/Z.current,l=Math.max(5,t.scaleToFit);let i=Math.min(.1,t.scaleToFit);H&&ne>0&&Number.isFinite(ne)&&(i=Math.max(i,300/ne)),i=Math.max(i,.01);const c=t.scale,u=a(c*o,i,l),d=u/c,h=e.getBoundingClientRect(),g=(r.touches[0].clientX+r.touches[1].clientX)/2-h.left,p=(r.touches[0].clientY+r.touches[1].clientY)/2-h.top,f=e.scrollLeft+g,m=e.scrollTop+p;ge.current=!0,t.setScale(u),e.scrollLeft=f*d-g,e.scrollTop=m*d-p,Z.current=n}},o=()=>{Z.current=0};return e.addEventListener("touchstart",r,{passive:!0}),e.addEventListener("touchmove",n,{passive:!1}),e.addEventListener("touchend",o,{passive:!0}),()=>{e.removeEventListener("touchstart",r),e.removeEventListener("touchmove",n),e.removeEventListener("touchend",o)}},[H,ne,t]);const ce=void 0!==_,ue=e.useMemo(()=>t.pages.map(e=>{if(H){const r=(e.computedWidth+2*$)*t.scale;return ce?r+_:r+2*ae}{const r=(e.computedHeight+2*$)*t.scale;return ce?r+_:r+2*se}}),[t.pages,t.scale,$,ae,se,_,H,ce]),de=e.useMemo(()=>{const e=[];let t=ce?H?ae:se:0;for(let r=0;r<ue.length;r++){e.push(t),t+=ue[r]}return e},[ue,ce,H,ae,se]),he=e.useMemo(()=>{const e=ue.reduce((e,t)=>e+t,0);return ce?e+(H?2*ae:2*se):e},[ue,ce,H,ae,se]),ge=e.useRef(!1),[,pe]=e.useReducer(e=>e+1,0);((t,r,n,o,l,i)=>{const a=e.useRef(r),s=e.useRef(0),c=e.useRef(!1),u=e.useRef(o.pages.length);c.current=u.current!==o.pages.length,u.current=o.pages.length,e.useEffect(()=>{const e=t.current,r=t=>{s.current=i?e.scrollLeft:e.scrollTop};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[i]),e.useLayoutEffect(()=>{if(!t.current){return}if(c.current){return}const e=t.current,n=i?e.offsetWidth:e.offsetHeight,o=(s.current+n/2)/a.current;l.current=!0;const u=o*r-n/2;i?e.scrollLeft=u:e.scrollTop=u,a.current=r},[n,r,i])})(U,he,t.scale,t,ge,H);const{handleScroll:fe}=((t,r,n,o,l,i,a,s,c)=>{const u=e.useRef(!1),d=e.useRef(null),h=e.useRef(!1),g="horizontal"===s;e.useEffect(()=>{const e=t.current,r=()=>{i.current};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[]);const p=o.pages.indexOf(o.activePage);return e.useLayoutEffect(()=>{if(a){return}if(!o.activePage){return}if(!t.current){return}if(u.current){return}const e=t.current,l=o.pages.indexOf(o.activePage),i=r[l]||0,s=g?e.scrollLeft:e.scrollTop,d=n[l]||n[0]||0;let p=()=>{};return(Math.abs(i-s)>.5*d||h.current)&&(h.current=!0,p=(({element:e,scrollTop:t,scrollLeft:r,duration:n=300,onFinish:o=()=>{}})=>{const l=void 0!==t,i=l?e.scrollTop:e.scrollLeft,a=l?t:r,s=a-i;let c=0,u=!1;if(0===n){return l?e.scrollTop=a:e.scrollLeft=a,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,i,s,n);l?e.scrollTop=t:e.scrollLeft=t,c<n?setTimeout(d,20):o()},h=(e,t,r,n)=>(e/=n/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:e},g?{scrollLeft:i}:{scrollTop:i}),{onFinish:()=>{h.current=!1,null==c||c()},duration:o.isPlaying?0:300}))),p},[o.activePage,p,o.isPlaying,a,s,r,n]),{handleScroll:e=>{if(a){return}if(h.current){return}u.current=!0,clearTimeout(d.current),d.current=setTimeout(()=>{u.current=!1},300);const t=(g?e.currentTarget.scrollLeft:e.currentTarget.scrollTop)+(g?l.width:l.height)/3;let n=0;for(let o=r.length-1;o>=0;o--){if(t>=r[o]){n=o;break}}const i=o.pages[n];i&&o.activePage!==i&&i.select()}}})(U,de,ue,t,q,ge,X,i,pe),me=q.width>=ne*t.scale+2*ae,ve=q.height>=oe*t.scale+2*se,be=g||"rgba(232, 232, 232, 0.9)",we=(null==O?void 0:O.NoPages)||c,xe=H?q.width:q.height,ke=U.current?H?U.current.scrollLeft:U.current.scrollTop:0,Ee=e=>{for(let t=de.length-1;t>=0;t--){if(e>=de[t]){return t}}return 0},Te=Math.max(0,Ee(ke)),ye=Math.min(t.pages.length-1,Ee(ke+xe)),Le=null!=D?D:1,Me=Math.max(0,Te-Le),Se=Math.min(t.pages.length-1,ye+Le);return e.createElement("div",{ref:Q,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:be,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container"},e.createElement("div",{ref:U,onScroll:fe,style:Object.assign({position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:H?"row":"column",overflow:"auto",overflowX:H?"auto":me?"hidden":"auto",overflowY:H&&ve?"hidden":"auto"},ce&&{paddingTop:H?0:se,paddingBottom:H?0:se,paddingLeft:H?ae:0,paddingRight:H?ae:0,boxSizing:"border-box"}),className:"polotno-workspace-inner"},t.pages.map((n,o)=>{const l=n===t.activePage;if(X&&!l&&!n._exportingOrRendering&&!n._forceMount){return null}const a=l||o>=Me&&o<=Se||n._exportingOrRendering||n._forceMount,s=H?ue[o]:ne*t.scale+2*ae,c=H?oe*t.scale+2*se:ue[o];if(!a){return e.createElement("div",{key:n.id,style:{flexShrink:0}},e.createElement(u,{width:s,height:c,backgroundColor:be,xPadding:ae,yPadding:se}))}const g=e.createElement(r,{key:n.id,page:n,xPadding:ae,yPadding:se,width:s,height:c,store:t,pageControlsEnabled:h,backColor:be,pageBorderColor:p||"lightgrey",activePageBorderColor:f||"rgb(0, 161, 255)",altCloneEnabled:Y,bleedColor:m||"rgba(255, 0, 0, 0.1)",selectionRectFill:x,selectionRectStroke:k,selectionRectStrokeWidth:E,snapGuideStroke:v||"rgb(0, 161, 255)",snapGuideStrokeWidth:b||1,snapGuideDash:w||d,transformLabelFill:T,transformLabelTextFill:y,distanceGuideStroke:L||"rgb(0, 161, 255)",distanceLabelFill:M||"rgb(0, 161, 255)",distanceLabelTextFill:S||"white",components:O,viewportSize:q,layout:i,tooltipSafeArea:A});return(n._exportingOrRendering||n._forceMount)&&!l&&X?e.createElement("div",{style:{display:"none",flexShrink:0},key:n.id},g):g}),t.rulesVisible&&e.createElement(n,{store:t,xPadding:ae,yPadding:se,width:ne*t.scale+2*ae,height:oe*t.scale+2*se,pageSizes:ue,layout:i,renderOnlyActivePage:X,rulerBackgroundColor:C,rulerTextColor:P,rulerBorderColor:R,rulerBorderSize:F,rulerTickColor:z,rulerTickSize:B}),0===t.pages.length&&e.createElement(we,{store:t}),t.audios.map(r=>e.createElement(o,{key:r.id,audio:r,store:t}))))});export default WorkspaceCanvas;
@@ -1 +1 @@
1
- import{types as e}from"mobx-state-tree";import{animate as t}from"../utils/animations.js";import{observable as i,action as n}from"mobx";import{Node as a}from"./node-model.js";export const Animation=e.model("Animation",{delay:0,duration:500,enabled:!0,type:e.enumeration("Type",["enter","exit","loop"]),name:"none",data:e.frozen({})});export const getDiff=(e,t)=>{const i={};for(const n in t){if("number"==typeof e[n]&&"number"==typeof t[n]){const a=t[n]-e[n];0!==a&&(i[n]=a)}}return i};export const ShapeFilter=e.model("ShapeFilter",{intensity:1});export const INDEPENDENT_FILTERS=["temperature","contrast","highlights","shadows","white","black","saturation","vibrance"];export const Shape=a.named("Shape").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,animations:e.array(Animation),blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,filters:e.map(ShapeFilter),shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",shadowOpacity:1,visible:!0,draggable:!0,resizable:!0,selectable:!0,contentEditable:!0,styleEditable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot(e=>{const t=Object.assign(Object.assign({},e),{x:"x"in e&&e.x||0,y:"y"in e&&e.y||0,filters:"filters"in e?Array.isArray(e.filters)?{}:e.filters:void 0});return"width"in e&&(t.width=t.width||1),"height"in e&&(t.height=t.height||1),"locked"in e&&e.locked&&(t.draggable=!1,t.contentEditable=!1,t.styleEditable=!1,t.resizable=!1,t.removable=!1),t}).views(e=>{const a=["x","y","width","height","rotation","opacity","color","fontSize","cropX","cropY","cropWidth","cropHeight"],o=e,r={};for(const t of a){t in e&&(r[t]=o[t])}const s=i(r),l=n(()=>{for(const e in s){s[e]=o[e]}}),d=n(e=>{Object.assign(s,e)}),c=n(e=>{for(const t in e){"number"==typeof s[t]&&(s[t]=s[t]+e[t])}});return{get locked(){return!(e.draggable||e.contentEditable||e.styleEditable||e.resizable)},get a(){const{currentTime:i}=e.store;if(l(),0===i){return s}const n=i-e.page.startTime;if(n>e.page.duration){return s}if(n<0){return s}const a=e.store.animatedElementsIds;if(a.length&&!a.includes(e.id)){return s}const o=e.animations.find(e=>"enter"===e.type),r=(null==o?void 0:o.enabled)&&n<o.delay;r&&d({opacity:0});const p=(null==o?void 0:o.enabled)&&n>=o.delay&&n<=o.delay+o.duration;if(p){const i=n-o.delay,a=t({element:e,animation:o,dTime:i}),r=getDiff(e,a);c(r)}const f=e.animations.find(e=>"exit"===e.type);if(!r&&!p&&(null==f?void 0:f.enabled)&&n>=e.page.duration-f.duration-f.delay&&n<=e.page.duration-f.delay){const i=n-(e.page.duration-f.duration-f.delay),a=t({element:e,animation:f,dTime:i}),o=getDiff(e,a);c(o)}(null==f?void 0:f.enabled)&&n>=e.page.duration-f.delay&&d({opacity:0});const m=e.animations.find(e=>"loop"===e.type);if(null==m?void 0:m.enabled){const i=t({element:e,animation:m,dTime:n}),a=getDiff(e,i);c(a)}return s},animated(e){return this.a[e]}}}).actions(e=>({setAnimation(t,i){const n=e.animations.find(e=>e.type===t);n?Object.assign(n,i):e.animations.push(Object.assign({type:t},i))},setFilter(t,i){INDEPENDENT_FILTERS.includes(t)||e.filters.forEach((t,i)=>{INDEPENDENT_FILTERS.includes(i.toString())||e.filters.delete(i.toString())}),null==i?e.filters.delete(t):e.filters.set(t,{intensity:i})}}));
1
+ import{types as e}from"mobx-state-tree";import{animate as t}from"../utils/animations.js";import{observable as n,action as i}from"mobx";import{Node as o}from"./node-model.js";export const Animation=e.model("Animation",{delay:0,duration:500,enabled:!0,type:e.enumeration("Type",["enter","exit","loop"]),name:"none",data:e.frozen({})});export const getDiff=(e,t)=>{const n={};for(const i in t){if("number"==typeof e[i]&&"number"==typeof t[i]){const o=t[i]-e[i];0!==o&&(n[i]=o)}}return n};export const ShapeFilter=e.model("ShapeFilter",{intensity:1});export const INDEPENDENT_FILTERS=["temperature","contrast","highlights","shadows","white","black","saturation","vibrance"];export const Shape=o.named("Shape").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,animations:e.array(Animation),blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,filters:e.map(ShapeFilter),shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",shadowOpacity:1,visible:!0,draggable:!0,resizable:!0,selectable:!0,contentEditable:!0,styleEditable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot(e=>{const t=Object.assign(Object.assign({},e),{x:"x"in e&&e.x||0,y:"y"in e&&e.y||0,filters:"filters"in e?Array.isArray(e.filters)?{}:e.filters:void 0});return"width"in e&&(t.width=t.width||1),"height"in e&&(t.height=t.height||1),"locked"in e&&e.locked&&(t.draggable=!1,t.contentEditable=!1,t.styleEditable=!1,t.resizable=!1,t.removable=!1),t}).views(e=>{const o=["x","y","width","height","rotation","opacity","color","fontSize","cropX","cropY","cropWidth","cropHeight"],a=e,r={};for(const t of o){t in e&&(r[t]=a[t])}const s=n(r),l=i(e=>{for(const t in e){s[t]=e[t]}}),d=i(e=>{Object.assign(s,e)}),c=i(e=>{for(const t in e){"number"==typeof s[t]&&(s[t]=s[t]+e[t])}});return{get locked(){return!(e.draggable||e.contentEditable||e.styleEditable||e.resizable)},get a(){const{currentTime:n}=e.store,i={};for(const e in s){i[e]=a[e]}if(l(i),0===n){return s}const o=n-e.page.startTime;if(o>e.page.duration){return s}if(o<0){return s}const r=e.store.animatedElementsIds;if(r.length&&!r.includes(e.id)){return s}const p=e.animations.find(e=>"enter"===e.type),f=(null==p?void 0:p.enabled)&&o<p.delay;f&&d({opacity:0});const m=(null==p?void 0:p.enabled)&&o>=p.delay&&o<=p.delay+p.duration;if(m){const n=o-p.delay,i=t({element:e,animation:p,dTime:n}),a=getDiff(e,i);c(a)}const b=e.animations.find(e=>"exit"===e.type);if(!f&&!m&&(null==b?void 0:b.enabled)&&o>=e.page.duration-b.duration-b.delay&&o<=e.page.duration-b.delay){const n=o-(e.page.duration-b.duration-b.delay),i=t({element:e,animation:b,dTime:n}),a=getDiff(e,i);c(a)}(null==b?void 0:b.enabled)&&o>=e.page.duration-b.delay&&d({opacity:0});const h=e.animations.find(e=>"loop"===e.type);if(null==h?void 0:h.enabled){const n=t({element:e,animation:h,dTime:o}),i=getDiff(e,n);c(i)}return s},animated(e){return this.a[e]}}}).actions(e=>({setAnimation(t,n){const i=e.animations.find(e=>e.type===t);i?Object.assign(i,n):e.animations.push(Object.assign({type:t},n))},setFilter(t,n){INDEPENDENT_FILTERS.includes(t)||e.filters.forEach((t,n)=>{INDEPENDENT_FILTERS.includes(n.toString())||e.filters.delete(n.toString())}),null==n?e.filters.delete(t):e.filters.set(t,{intensity:n})}}));
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 s,onSnapshot as a,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{addDpiMetadataToImage as v}from"../utils/image-dpi.js";import{nodeToCanvas as P}from"../utils/canvas.js";import{whenLoaded as w}from"../utils/loader.js";import{pxToUnit as E}from"../utils/unit.js";import{deepEqual as x}from"../utils/deep-equal.js";import{waitTillAvailable as _}from"../utils/wait.js";import{jsonToHTML as I}from"../utils/to-html.js";import{jsonToSVG as k}from"../utils/to-svg.js";import{Page as O}from"./page-model.js";import{forEveryChild as j}from"./group-model.js";import{Audio as T}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 Store=l.model("Store",{role:"",pages:l.array(O),fonts:l.array(Font),audios:l.array(T),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:2,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 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=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return j({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},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 S={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:s=!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=s,requestAnimationFrame(()=>S.seek())},checkActivePage(){let e=0;for(const t of r.pages){if(r.currentTime>=t.startTime&&r.currentTime<t.startTime+t.duration){S.selectPage(t.id);break}e+=t.duration}},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t,S.checkActivePage();const i=d||r.duration;r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>S.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>S.seek())):S.stop()},stop(){r.isPlaying=!1,r.currentTime=0,r.animatedElementsIds=i([]),S.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=O.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},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),s=r.pages[n];s&&(r._activePageId=s.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),s=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const a=s.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${a+1}`,children:o,type:"group"},t);return s.children.push(l),r.selectedElementsIds=i([l.id]),s.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=S.toJSON();return a(r,i=>{const o=S.toJSON();!x(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:s,quickMode:a=!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&&S.setElementsPixelRatio(c),a?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}),S.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 S.waitLoading({_skipTimeout:s});const h=f.findOne(".page-container");if(!h){throw S.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 I=h.find(e=>e.getAttr("hideInExport"));I.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 O=k;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?O=0:r.bleedVisible&&!n&&(O=-g.bleed):O=0);const j=g.computedWidth+2*k,T=g.computedHeight+2*k,F=h.scale();h.scale({x:1,y:1});const R=P(h,{x:h.x()-O,y:h.y()-O,width:j,height:T,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(F);const C=R._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()),I.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(),S.setElementsPixelRatio(m),C},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:s="auto"}=t,a=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await S._toCanvas(Object.assign({mimeType:i},a)),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"===s||"auto"===s&&72===g?c:v(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const s=await S._toCanvas(Object.assign({mimeType:i},n)),a=await new Promise(e=>{s.toBlob(e,i,o)});return p.Util.releaseCanvas(s),a},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];m(await S.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,s=e.pageIds||r.pages.map(e=>e.id),a=r.pages.filter(e=>s.includes(e.id)),l=await u(),d=e=>E({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=a[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})(a,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,a=t.computedHeight+2*i+2*c,r=d(o),l=d(a);let p=0,g=n;for(;p<10;){p+=1,2===p&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const i=await S.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g}));if(i.length>20){return e.onProgress&&e.onProgress(++v/s.length*.9),{url:i,width:r,height:l,widthPx:o,heightPx:a}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:s})=>{b.addPage([t,i],t>i?"landscape":"portrait");const a=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(a.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},a.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(s-c-m)*r},a.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(s-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 S._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let s=0;s<n-1;s++){const e=s*o||1;S.setCurrentTime(e);let n=0,a="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){a=t.id;break}}const l=await S._toCanvas({pixelRatio:t,pageId:a,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const s of r.pages){s.set({_rendering:!1})}return S.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await S.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=S.toJSON();return I({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await S.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=S.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const s=n.pages.find(e=>e.id===t);return k({json:Object.assign(Object.assign({},n),{pages:s?[s]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await S.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),s="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(s,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await S._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:s(r.fonts),pages:s(r.pages),audios:s(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o;const n=JSON.parse(JSON.stringify(e)),a=n.schemaVersion||0;a<1&&y.htmlRenderEnabled&&j({children:n.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),a<2&&j({children:n.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)})}),delete n.schemaVersion;const l=r.activePage?r.pages.indexOf(r.activePage):0;let d=null===(o=n.pages[l]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=d;const c=Object.assign({},s(r));Object.assign(c,n),c.history=i?s(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,c)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);S.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){S.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=T.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=""){const i=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let o=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return i?(i.styles&&(o=i.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(i)):b.injectGoogleFont(e),Promise.all(o.map(i=>b.loadFont(e,i.fontStyle,i.fontWeight,t)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return S});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 s,onSnapshot as a,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 w}from"../utils/canvas.js";import{whenLoaded as P}from"../utils/loader.js";import{pxToUnit as x}from"../utils/unit.js";import{deepEqual as E}from"../utils/deep-equal.js";import{waitTillAvailable as _}from"../utils/wait.js";import{jsonToHTML as I}from"../utils/to-html.js";import{jsonToSVG as k}from"../utils/to-svg.js";import{Page as O}from"./page-model.js";import{forEveryChild as j}from"./group-model.js";import{Audio as T}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 Store=l.model("Store",{role:"",pages:l.array(O),fonts:l.array(Font),audios:l.array(T),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:2,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 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=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return j({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},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 S={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:s=!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=s,requestAnimationFrame(()=>S.seek())},checkActivePage(){let e=0;for(const t of r.pages){if(r.currentTime>=t.startTime&&r.currentTime<t.startTime+t.duration){S.selectPage(t.id);break}e+=t.duration}},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t,S.checkActivePage();const i=d||r.duration;r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>S.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>S.seek())):S.stop()},stop(){r.isPlaying=!1,r.currentTime=0,r.animatedElementsIds=i([]),S.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=O.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},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),s=r.pages[n];s&&(r._activePageId=s.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),s=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const a=s.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${a+1}`,children:o,type:"group"},t);return s.children.push(l),r.selectedElementsIds=i([l.id]),s.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=S.toJSON();return a(r,i=>{const o=S.toJSON();!E(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:s,quickMode:a=!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&&S.setElementsPixelRatio(c),a?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}),S.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 S.waitLoading({_skipTimeout:s});const h=f.findOne(".page-container");if(!h){throw S.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 P=h.findOne(".elements-container"),x=P.clip();P.clip({x:null,y:null,width:null,height:null});const E=h.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));E.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const I=h.find(e=>e.getAttr("hideInExport"));I.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 O=k;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?O=0:r.bleedVisible&&!n&&(O=-g.bleed):O=0);const j=g.computedWidth+2*k,T=g.computedHeight+2*k,F=h.scale();h.scale({x:1,y:1});const R=w(h,{x:h.x()-O,y:h.y()-O,width:j,height:T,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(F);const C=R._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()),I.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),E.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),P.clip(x),f.position(b),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),S.setElementsPixelRatio(m),C},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:s="auto"}=t,a=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await S._toCanvas(Object.assign({mimeType:i},a)),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"===s||"auto"===s&&72===g?c:v(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const s=await S._toCanvas(Object.assign({mimeType:i},n)),a=await new Promise(e=>{s.toBlob(e,i,o)});return p.Util.releaseCanvas(s),a},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];m(await S.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,s=e.pageIds||r.pages.map(e=>e.id),a=r.pages.filter(e=>s.includes(e.id)),l=await u(),d=e=>x({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=a[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})(a,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,a=t.computedHeight+2*i+2*c,r=d(o),l=d(a);let p=0,g=n;for(;p<10;){p+=1;const i=await S.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/s.length*.9),{url:i,width:r,height:l,widthPx:o,heightPx:a}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:s})=>{b.addPage([t,i],t>i?"landscape":"portrait");const a=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(a.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},a.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(s-c-m)*r},a.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(s-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 S._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let s=0;s<n-1;s++){const e=s*o||1;S.setCurrentTime(e);let n=0,a="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){a=t.id;break}}const l=await S._toCanvas({pixelRatio:t,pageId:a,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const s of r.pages){s.set({_rendering:!1})}return S.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await S.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=S.toJSON();return I({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await S.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=S.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const s=n.pages.find(e=>e.id===t);return k({json:Object.assign(Object.assign({},n),{pages:s?[s]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await S.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),s="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(s,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await S._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 P()},toJSON:()=>({width:r.width,height:r.height,fonts:s(r.fonts),pages:s(r.pages),audios:s(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o;const n=JSON.parse(JSON.stringify(e)),a=n.schemaVersion||0;a<1&&y.htmlRenderEnabled&&j({children:n.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),a<2&&j({children:n.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)})}),delete n.schemaVersion;const l=r.activePage?r.pages.indexOf(r.activePage):0;let d=null===(o=n.pages[l]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=d;const c=Object.assign({},s(r));Object.assign(c,n),c.history=i?s(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,c)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);S.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){S.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=T.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=""){const i=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let o=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return i?(i.styles&&(o=i.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(i)):b.injectGoogleFont(e),Promise.all(o.map(i=>b.loadFont(e,i.fontStyle,i.fontWeight,t)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return S});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "2.36.0",
3
+ "version": "2.36.2",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [