polotno 4.10.0 → 4.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/blueprint/side-panel/select-video.d.ts +4 -0
- package/canvas/crop-overlay.d.ts +42 -0
- package/canvas/crop-overlay.js +1 -0
- package/canvas/downscale-bands.d.ts +10 -0
- package/canvas/downscale-bands.js +1 -0
- package/canvas/downscale-kernel.d.ts +7 -0
- package/canvas/downscale-kernel.js +1 -0
- package/canvas/downscale-kernel.wasm.d.ts +1 -0
- package/canvas/downscale-kernel.wasm.js +1 -0
- package/canvas/downscale-passes.d.ts +7 -0
- package/canvas/downscale-passes.js +1 -0
- package/canvas/downscale.d.ts +22 -1
- package/canvas/downscale.js +1 -1
- package/canvas/drawing-layer.js +1 -1
- package/canvas/element.js +1 -1
- package/canvas/figure-element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/hotkeys.js +1 -1
- package/canvas/html-element.js +1 -1
- package/canvas/image-element.d.ts +24 -1
- package/canvas/image-element.js +1 -1
- package/canvas/line-element.js +1 -1
- package/canvas/page-controls.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/render-tag-element.js +1 -1
- package/canvas/rich-editor.js +3 -3
- package/canvas/table-element.js +1 -1
- package/canvas/text-element.js +1 -1
- package/canvas/tooltip.js +1 -1
- package/canvas/transform-box.d.ts +9 -0
- package/canvas/transform-box.js +1 -0
- package/canvas/use-image.d.ts +4 -0
- package/canvas/use-image.js +1 -0
- package/canvas/use-mediabunny-video.js +1 -1
- package/canvas/use-transformer-snap.js +1 -1
- package/canvas/video-element.js +1 -1
- package/canvas/workspace-canvas.d.ts +3 -1
- package/canvas/workspace-canvas.js +1 -1
- package/canvas/workspace-style.d.ts +4 -0
- package/canvas/workspace-style.js +1 -1
- package/model/crop-mode.d.ts +34 -0
- package/model/crop-mode.js +1 -0
- package/model/gif-model.d.ts +2 -0
- package/model/group-model.d.ts +13 -0
- package/model/image-model.d.ts +2 -0
- package/model/image-model.js +1 -1
- package/model/page-model.d.ts +13 -0
- package/model/store.d.ts +144 -5
- package/model/store.js +1 -1
- package/model/svg-model.d.ts +7 -0
- package/model/svg-model.js +1 -1
- package/model/video-model.d.ts +2 -0
- package/package.json +25 -23
- package/polotno.bundle.js +179 -192
- package/primitives/tooltip.js +1 -1
- package/side-panel/draw-panel.js +1 -1
- package/side-panel/select-image.js +1 -1
- package/side-panel/select-video.d.ts +4 -0
- package/side-panel/size-panel.js +1 -1
- package/toolbar/duplicate-button.js +1 -1
- package/toolbar/html-toolbar.js +2 -2
- package/toolbar/image-toolbar.d.ts +7 -2
- package/toolbar/image-toolbar.js +1 -1
- package/toolbar/lock-button.js +1 -1
- package/toolbar/opacity-picker.js +1 -1
- package/toolbar/remove-button.js +1 -1
- package/toolbar/svg-toolbar.js +1 -1
- package/toolbar/text-toolbar.js +1 -1
- package/toolbar/toolbar.js +1 -1
- package/utils/base64.d.ts +1 -1
- package/utils/canvas.d.ts +1 -0
- package/utils/canvas.js +1 -1
- package/utils/fonts.d.ts +1 -0
- package/utils/fonts.js +1 -1
- package/utils/html2canvas.js +1 -1
- package/utils/l10n.d.ts +4 -0
- package/utils/l10n.js +1 -1
- package/utils/path-to-svg.d.ts +0 -2
- package/utils/path-to-svg.js +1 -1
- package/utils/px.d.ts +21 -0
- package/utils/px.js +1 -1
- package/utils/validate-key.js +1 -1
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{jsx as t,jsxs as n,Fragment as i}from"react/jsx-runtime";import o from"react";import{observer as r,useLocalObservable as l}from"mobx-react-lite";import{action as s,runInAction as a}from"mobx";import{ZERO_BLEED as d}from"@polotno/schema";import{Group as c,Image as h,Label as m,Layer as u,Line as g,Rect as f,Shape as p,Stage as x,Tag as v,Text as b,Transformer as y,KonvaRenderer as w}from"react-konva";import E from"use-image";import{useWorkspaceStyle as X}from"./workspace-style.js";import{ROLES as Y}from"../model/store.js";import S from"konva";import k from"./element.js";import{DrawingLayer as A}from"./drawing-layer.js";import{ensureDragOrder as M,useSnap as I}from"./use-transformer-snap.js";import{useImageLoader as O}from"./image-element.js";import{getCrop as P}from"../utils/crop.js";import{___ as R,____ as j,isCreditVisible as D}from"../utils/validate-key.js";import{getClientRect as C,getCorners as T,getTotalClientRect as B,polygonsIntersect as W}from"../utils/math.js";import{pxToUnitRounded as G,pxToUnitString as L}from"../utils/unit.js";import{isCornerAnchor as V,textMinResizeWidth as F,textMinWidthIsMeasured as z}from"../utils/px.js";import{flags as U}from"../utils/flags.js";import{useColor as Z}from"./use-color.js";import{isGradient as _}from"@polotno/core/gradient";import{Html as H}from"react-konva-utils";import{observerBatching as J}from"mobx-react-lite";const N=e=>w.batchedUpdates(e,null);J(e=>{w.isAlreadyRendering()?queueMicrotask(()=>N(e)):N(e)});const K=S.DD._drag;window.removeEventListener("mousemove",K),S.DD._drag=function(e){a(()=>{K.call(this,e)})},window.addEventListener("mousemove",S.DD._drag);const $={enabledAnchors:["top-left","top-center","top-right","middle-left","bottom-left","bottom-right","bottom-center","middle-right"],rotateEnabled:!0,rotationSnaps:[0,45,90,135,180,225,270,315],ignoreStroke:!0,flipEnabled:!1,keepRatio:!0},Q=e=>{const t=(e%180+180)%180;return t<.1||180-t<.1},q=e=>{if(!e.length){return null}const t=Q(e[0].rotation)?0:e[0].rotation;return e.every(e=>Q(e.rotation-t))?t:null},ee=e=>e.selectedShapes.filter(e=>!e._cropModeEnabled),te=(e,t,n)=>{const i=e.width!==t.width,o=e.height!==t.height;if(!i&&!o){return e}const r=Math.cos(t.rotation),l=Math.sin(t.rotation),s=t.x-n.x,a=t.y-n.y,d=i?0:s*r+a*l,c=o?0:-s*l+a*r;return e.x=n.x+d*r-c*l,e.y=n.y+d*l+c*r,e},ne={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"]},table:{keepRatio:!1,enabledAnchors:["top-left","top-center","top-right","middle-left","middle-right","bottom-left","bottom-center","bottom-right"]}};export function registerTransformerAttrs(e,t){ne[e]=ne[e]||t,Object.assign(ne[e],t)}const ie=e=>t(f,Object.assign({},e,{preventDefault:!1})),oe=n=>{var{url:i}=n,o=e(n,["url"]);const[r,l]=E(i,"anonymous"),s=r?P(r,{width:o.width,height:o.height},"center-middle"):{};return O(l,i,"page background"),t(h,Object.assign({image:r},o,s))},re=e=>{const n=Z({a:{width:e.width,height:e.height},width:e.width,height:e.height},e.fill);return t(f,Object.assign({},e,n))},le=i=>{const{background:r,scale:l,borderColor:s,transparencyBackgroundColor:a}=i,d=e(i,["background","scale","borderColor","transparencyBackgroundColor"]),c=o.useMemo(()=>!!S.Util.colorToRGBA(r)||_(r),[r]),h=o.useMemo(()=>{if(_(r)){return!0}const e=S.Util.colorToRGBA(r);return!e||e.a<1},[r]),m=o.useMemo(()=>{if(!h||a){return null}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},[h,a]);return n(o.Fragment,{children:[h&&t(f,a?Object.assign({fill:a},d,{hideInExport:!0}):Object.assign({fillPatternImage:m},d,{opacity:.1,hideInExport:!0})),c?t(re,Object.assign({fill:r},d)):t(oe,Object.assign({url:r},d))]})},se=r(({selection:e})=>{const{selectionRectStyle:n}=X();return e.visible?t(f,{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.fill,stroke:n.stroke,strokeWidth:n.strokeWidth}):null});function ae(e){let t=180*e/Math.PI;return t%=360,t>180?t-=360:t<-180&&(t+=360),Math.round(t)}const de=r(({x:e,y:o,width:r,height:l,rotation:s,anchor:a,store:d})=>{const{transformLabelStyle:c}=X();if(void 0===e||void 0===o||void 0===r||void 0===l||void 0===s||void 0===a){return null}const h=C({x:e,y:o,width:r,height:l,rotation:S.Util.radToDeg(s)}),u=(l/2+70)*Math.cos(s-Math.PI/2),g=(l/2+70)*Math.sin(s-Math.PI/2),f=G({unit:d.unit,dpi:d.dpi,px:r/d.scale,precious:"px"===d.unit?0:1})+" x "+G({unit:d.unit,dpi:d.dpi,px:l/d.scale,precious:"px"===d.unit?0:1})+("px"===d.unit?"":" "+d.unit);return n(i,{children:[n(m,{x:(h.minX+h.maxX)/2+u,y:(h.minY+h.maxY)/2+g,offsetX:14,offsetY:14,visible:"rotater"===a,children:[t(v,{cornerRadius:5,fill:c.fill}),t(b,{align:"center",verticalAlign:"middle",fill:c.textFill,padding:8,text:ae(s).toString()+"°"})]}),n(m,{x:(h.minX+h.maxX)/2,y:h.maxY+20,visible:"rotater"!==a,children:[t(v,{cornerRadius:5,fill:c.fill,pointerDirection:"up",pointerHeight:0,pointerWidth:0}),t(b,{align:"center",verticalAlign:"middle",fill:c.textFill,padding:8,text:f})]})]})}),ce=r(({elements:e,store:n})=>{const i=e.filter(e=>e.alwaysOnTop),r=e.filter(e=>!e.alwaysOnTop).concat(i);return t(o.Fragment,{children:r.map(e=>t(k,{store:n,element:e,onClick:()=>{console.warn("Polotno warning: onClick callback is deprecated. Just stop using it. Polotno will do selection automatically.")}},e.id))})});export const useContextMenu=({store:e})=>{const[t,n]=o.useState(!1),[i,r]=o.useState({x:0,y:0}),l=o.useCallback(e=>{n(!0),r(e)},[]);return{open:l,close:o.useCallback(()=>{n(!1)},[]),props:{isOpen:t,offset:i,setIsOpen:n}}};let he=null;export const registerNextDomDrop=e=>{he=e};const me=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),ue=atob("I2MwMzkyYg=="),ge=atob("djAuOS4y"),fe=e=>t(i,{children:n(m,{fill:ue,height:200,children:[t(v,{fill:ue}),t(b,Object.assign({},e,{fill:"white",text:me,height:void 0,padding:10,fontSize:20}))]})}),pe=atob("RlJFRSAgVFJJQUwgIExJQ0VOU0U="),xe=(atob("UG93ZXJlZCBieSBQb2xvdG5v"),atob("TElDRU5TRSAgS0VZICBJUyAgTUlTU0lORw==")),ve=atob("UGxlYXNlIGFjdGl2YXRlIHlvdXIgbGljZW5zZS4KTGljZW5zZSByZWxhdGVkIHF1ZXN0aW9uczoKcG9sb3Ruby5jb20vY29udGFjdA=="),be=e=>{const i=1===j(),o=i?xe:pe,r=i?230:195;return n(c,Object.assign({},e,{listening:!1,children:[t(f,{fill:ue,width:r,height:24,cornerRadius:2}),t(b,{text:o,fill:"white",fontSize:13,fontFamily:"monospace",width:r,align:"center",y:5,listening:!1}),i&&t(b,{text:ve,fill:"rgba(0,0,0,0.6)",fontSize:14,y:30,listening:!1})]}))};export default r(({store:e,page:i,width:r,height:a,pageControlsEnabled:h,components:w,altCloneEnabled:E,groupSelectionMode:S="drill",viewportSize:k,layout:O="vertical",tooltipSafeArea:P,transformerSafeArea:G})=>{var Z,_;const J=X(),N=J.transformerStyle,K=$,oe=i.computedBleed,re=e.bleedVisible?oe:d,ae=i.computedWidth+re.left+re.right,me=i.computedHeight+re.top+re.bottom,ue=(r-ae*e.scale)/2,pe=(a-me*e.scale)/2,xe=o.useRef(null),ve=o.useRef(null),ye=o.useRef(null),we=o.useRef(null),Ee=null==h||h,Xe=o.useRef(!1),[Ye,Se]=o.useState(null),[ke,Ae]=o.useState({}),[Me,Ie]=o.useState(0),Oe=useContextMenu({store:e}),Pe=e.selectedElements.find(e=>e._cropModeEnabled),Re=e.selectedElements.find(e=>e.curveEnabled),je=e.selectedShapes.filter(e=>!e.resizable).length>0,De=e.selectedShapes.filter(e=>!e.draggable).length>0,Ce=e.selectedElements.filter(e=>!e.visible).length>0,Te=ee(e),Be=1!==e.selectedElements.length||"group"===(null===(Z=e.selectedElements[0])||void 0===Z?void 0:Z.type),We=null!==(_=q(Te))&&void 0!==_?_:0,Ge=e=>Be&&Te.length>0&&Te.every(t=>((e,t,n)=>{if(!Q(e.rotation-n)){return!1}switch(e.type){case"text":return"x"===t&&!z(e);case"figure":case"video":case"table":return!0;case"image":case"svg":case"gif":return!e.keepRatio;default:return!1}})(t,e,We)),Le=!Be&&e.selectedElements[0].keepRatio,Ve=Ge("x"),Fe=Ge("y"),ze=()=>{var t,n,i;const o=xe.current;if(!o){return[]}const r=o.getStage();if(!r){return[]}const l=ee(e),s=l.map(e=>r.findOne("#"+e.id)).filter(e=>!!e),a=1===e.selectedElements.length,d=a&&(null===(t=e.selectedElements[0])||void 0===t?void 0:t.type)||"many",c=ne[d],h=Object.assign(Object.assign({},K),c||{});c&&("svg"!==d&&"image"!==d&&"gif"!==d||e.selectedElements[0].keepRatio||(h.enabledAnchors=K.enabledAnchors),"text"===d&&U.textVerticalResizeEnabled&&(h.enabledAnchors=null===(n=ne.text.enabledAnchors)||void 0===n?void 0:n.concat(["bottom-center","top-center"])),"text"===d&&a&&e.selectedElements[0].curveEnabled&&(h.enabledAnchors=ne.many.enabledAnchors)),(Ve||Fe)&&(h.enabledAnchors=[...h.enabledAnchors||[],...Ve?["middle-left","middle-right"]:[],...Fe?["top-center","bottom-center"]:[]]),o.setAttrs(Object.assign(Object.assign({},h),N)),je&&o.enabledAnchors([]),De&&o.rotateEnabled(!1);const m=o.nodes();if(m.length===s.length&&s.every((e,t)=>m[t]===e)||o.nodes(s),Be&&s.length){const e=q(l);null===e||Q(o.rotation()-e)||(o.rotation(e),o.forceUpdate())}return null===(i=o.getLayer())||void 0===i||i.batchDraw(),s};o.useLayoutEffect(()=>{var e;if(null===(e=xe.current)||void 0===e?void 0:e.isTransforming()){return}const t=ze();t.find(e=>null==e?void 0:e.isDragging())&&(t.forEach(e=>{e.isDragging()||null==e||e.startDrag()}),M())},[e.selectedShapes,Pe,je,Ce,De,Re,Ve,Fe,Le,We,N]);const Ue=()=>{var e,t;const n=xe.current;if(!n){return}if(!n.isTransforming()){return void Ae({})}if(!n.nodes().length||!n.isTransforming()){return}const i=n.__getNodeRect(),o=null==n?void 0:n.getActiveAnchor(),r=n.getStage();Ae({anchor:o,x:i.x-(null!==(e=null==r?void 0:r.x())&&void 0!==e?e:0),y:i.y-(null!==(t=null==r?void 0:r.y())&&void 0!==t?t:0),rotation:i.rotation,width:i.width,height:i.height})},Ze=o.useCallback(()=>{var e;if(null===(e=xe.current)||void 0===e?void 0:e.isTransforming()){return}const t=xe.current;if(!t||!t.nodes().length){return void Ie(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,s=e.height/2,a=i*Math.PI/180,d=e=>{const t=e*Math.PI/180,i=(e%360+360)%360;let d;d=0===i||180===i?s:l;const c=Math.sin(t)*(d+n),h=-Math.cos(t)*(d+n),m=c*Math.cos(a)-h*Math.sin(a),u=c*Math.sin(a)+h*Math.cos(a);return{x:o+m,y:r+u}},c=e=>e.x>=t.left&&e.x<=t.right&&e.y>=t.top&&e.y<=t.bottom;if(c(d(0))){return 0}for(const h of[180,270,90]){if(c(d(h))){return h}}return 0}(n,{top:(null==G?void 0:G.top)||0,bottom:a-((null==G?void 0:G.bottom)||0),left:(null==G?void 0:G.left)||0,right:r-((null==G?void 0:G.right)||0)},N.rotateAnchorOffset,t.rotation());Ie(i)},[G,r,a]);o.useEffect(()=>{var e;null===(e=xe.current)||void 0===e||e.update(),Ue(),Ze()},[e.scale,Ze]),o.useEffect(()=>{Ze()},[e.selectedShapes,Ze]);const _e=l(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),He=o.useRef(!1),Je=s(t=>{var n,i,o,r,l,s,a;if(e.role===Y.VIEWER){return}He.current=!1;const d=t.target.findAncestor(".elements-container"),c=t.target.findAncestor("Transformer"),h=t.target.findAncestor(".page-abs-container");if(d||c||h){return}const m=null===(n=t.target.getStage())||void 0===n?void 0:n.getPointerPosition();m&&(m.x-=null!==(o=null===(i=t.target.getStage())||void 0===i?void 0:i.x())&&void 0!==o?o:0,m.y-=null!==(l=null===(r=t.target.getStage())||void 0===r?void 0:r.y())&&void 0!==l?l:0,_e.visible=!0,_e.x1=m.x,_e.y1=m.y,_e.x2=m.x,_e.y2=m.y,(null!==(a=null===(s=t.target.getStage())||void 0===s?void 0:s.getPointersPositions().length)&&void 0!==a?a:0)>=2&&(_e.visible=!1))});(({stageRef:e,containerRef:t,viewportSize:n})=>{o.useEffect(()=>{var n;const i=null===(n=t.current)||void 0===n?void 0:n.closest(".polotno-workspace-inner");function o(){var n;if(!e.current){return}const o=null===(n=t.current)||void 0===n?void 0:n.getBoundingClientRect(),r=null==i?void 0:i.getBoundingClientRect();if(!o||!r){return}const l=Math.max(0,r.left-o.left-100),s=Math.max(0,r.top-o.top-100);e.current.position({x:-l,y:-s}),e.current.container().style.transform=`translate(${l}px, ${s}px)`}return o(),null==i||i.addEventListener("scroll",o),()=>{null==i||i.removeEventListener("scroll",o)}},[n.width,n.height])})({stageRef:ye,containerRef:we,viewportSize:k}),o.useEffect(()=>{const t=s(e=>{var t,n,i,o,r,l;if(!_e.visible){return}null===(t=ye.current)||void 0===t||t.setPointersPositions(e);let s=null===(n=ye.current)||void 0===n?void 0:n.getPointerPosition();s?(s.x-=null!==(o=null===(i=ye.current)||void 0===i?void 0:i.x())&&void 0!==o?o:0,s.y-=null!==(l=null===(r=ye.current)||void 0===r?void 0:r.y())&&void 0!==l?l:0):s={x:_e.x2,y:_e.y2},_e.x2=s.x,_e.y2=s.y}),n=s(()=>{if(!_e.visible){return}if(!ye.current){return}const t=ye.current.findOne(".selection"),n=t?t.getClientRect({skipStroke:!0}):{width:0,height:0,x:0,y:0};if(n.width&&n.height){const t=[{x:n.x,y:n.y},{x:n.x+n.width,y:n.y},{x:n.x+n.width,y:n.y+n.height},{x:n.x,y:n.y+n.height}],i=[];ye.current.find(".element").forEach(n=>{var o;const r=e.getElementById(n.id()),l=null==r?void 0:r.draggable,s=null==r?void 0:r.selectable;if(!l||!s){return}const a=null===(o=n.getParent())||void 0===o?void 0:o.getAbsoluteTransform();if(!a){return}const d=T(r.a).map(e=>a.point(e));W(t,d)&&i.push(r.top.id)});const o=[...new Set(i)];He.current=!0,e.selectElements(o)}_e.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 Ne=o.useCallback(t=>{if(!e.selectedElements[0]){return}if(t&&e.selectedElementsIds.includes(t)){return}const n=B(e.selectedShapes),o=t?e.getElementById(t):{x:0,y:0,width:i.computedWidth,height:i.computedHeight,rotation:0},r=C(o),l=[];n.minX>r.maxX&&l.push({distance:n.minX-r.maxX,box1:n,box2:r,points:[{x:n.minX,y:n.minY+n.height/2},{x:r.maxX,y:n.minY+n.height/2},{x:r.maxX,y:r.minY+r.height/2}]}),n.maxX<r.minX&&l.push({distance:r.minX-n.maxX,box1:n,box2:r,points:[{x:n.maxX,y:n.minY+n.height/2},{x:r.minX,y:n.minY+n.height/2},{x:r.minX,y:r.minY+r.height/2}]}),n.minY>r.maxY&&l.push({box1:n,box2:r,distance:n.minY-r.maxY,points:[{x:n.minX+n.width/2,y:n.minY},{x:n.minX+n.width/2,y:r.maxY},{x:r.minX+r.width/2,y:r.maxY}]}),n.maxY<r.minY&&l.push({box1:n,box2:r,distance:r.minY-n.maxY,points:[{x:n.minX+n.width/2,y:n.maxY},{x:n.minX+n.width/2,y:r.minY},{x:r.minX+r.width/2,y:r.minY}]});const s=n.minX>=r.minX&&n.maxX<=r.maxX&&n.minY>=r.minY&&n.maxY<=r.maxY;if(s&&(l.push({distance:n.minX-r.minX,box1:n,box2:r,points:[{x:n.minX,y:n.minY+n.height/2},{x:r.minX,y:n.minY+n.height/2},{x:r.minX,y:r.minY+r.height/2}]}),l.push({distance:r.maxX-n.maxX,box1:n,box2:r,points:[{x:n.maxX,y:n.minY+n.height/2},{x:r.maxX,y:n.minY+n.height/2},{x:r.maxX,y:r.minY+r.height/2}]}),l.push({box1:n,box2:r,distance:n.minY-r.minY,points:[{x:n.minX+n.width/2,y:n.minY},{x:n.minX+n.width/2,y:r.minY},{x:r.minX+r.width/2,y:r.minY}]}),l.push({box1:n,box2:r,distance:r.maxY-n.maxY,points:[{x:n.minX+n.width/2,y:n.maxY},{x:n.minX+n.width/2,y:r.maxY},{x:r.minX+r.width/2,y:r.maxY}]})),0===l.length&&!s){const e=n.minX<r.maxX&&n.maxX>r.minX,t=n.minY<r.maxY&&n.maxY>r.minY;if(e&&t){const e=(Math.max(n.minY,r.minY)+Math.min(n.maxY,r.maxY))/2,t=(Math.max(n.minX,r.minX)+Math.min(n.maxX,r.maxX))/2;n.minX<r.minX?l.push({distance:r.minX-n.minX,box1:n,box2:r,points:[{x:n.minX,y:e},{x:r.minX,y:e},{x:r.minX,y:e}]}):l.push({distance:n.minX-r.minX,box1:n,box2:r,points:[{x:n.minX,y:e},{x:r.minX,y:e},{x:r.minX,y:e}]}),n.maxX>r.maxX?l.push({distance:n.maxX-r.maxX,box1:n,box2:r,points:[{x:r.maxX,y:e},{x:n.maxX,y:e},{x:r.maxX,y:e}]}):l.push({distance:r.maxX-n.maxX,box1:n,box2:r,points:[{x:n.maxX,y:e},{x:r.maxX,y:e},{x:r.maxX,y:e}]}),n.minY<r.minY?l.push({box1:n,box2:r,distance:r.minY-n.minY,points:[{x:t,y:n.minY},{x:t,y:r.minY},{x:t,y:r.minY}]}):l.push({box1:n,box2:r,distance:n.minY-r.minY,points:[{x:t,y:n.minY},{x:t,y:r.minY},{x:t,y:r.minY}]}),n.maxY>r.maxY?l.push({box1:n,box2:r,distance:n.maxY-r.maxY,points:[{x:t,y:r.maxY},{x:t,y:n.maxY},{x:t,y:r.maxY}]}):l.push({box1:n,box2:r,distance:r.maxY-n.maxY,points:[{x:t,y:n.maxY},{x:t,y:r.maxY},{x:t,y:r.maxY}]})}}JSON.stringify(Ye)!==JSON.stringify(l)&&Se(l)},[e,i]);o.useEffect(()=>{e.selectedElements[0]&&e.distanceGuidesVisible?Ne():Ye&&Se(null)},[e.distanceGuidesVisible,Ne,e.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const Ke=o.useRef(!1);o.useEffect(()=>{var e;let t;const n=null===(e=we.current)||void 0===e?void 0:e.closest(".polotno-workspace-inner"),i=()=>{Ke.current=!0,clearTimeout(t),t=setTimeout(()=>{Ke.current=!1},300)};return null==n||n.addEventListener("scroll",i),()=>{clearTimeout(t),null==n||n.removeEventListener("scroll",i)}},[]),o.useEffect(()=>{const t=ye.current;if(!t){return}const n=t.container(),i=new Map,o=e=>{i.set(e.target,{x:e.target.x(),y:e.target.y()})},r=e=>{i.delete(e.target)};t.on("dragstart",o),t.on("dragend",r);const l=t=>{var n,o;t.touches.length>=2&&((null===(n=xe.current)||void 0===n?void 0:n.isDragging())&&xe.current.stopDrag(),null===(o=xe.current)||void 0===o||o.nodes().forEach(t=>{var n;const o=i.get(t);t.isDragging()&&t.stopDrag(),o&&(t.setAttrs(o),null===(n=e.getElementById(t.id()))||void 0===n||n.set({x:o.x,y:o.y}))}))};return n.addEventListener("touchstart",l,{passive:!0}),n.addEventListener("touchmove",l,{passive:!0}),()=>{t.off("dragstart",o),t.off("dragend",r),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",l)}},[e]);const $e=t=>{if(e.role===Y.VIEWER){return}if(e.activePage!==i&&i.select(),Ke.current){return}if(He.current){return}const n=t.evt.shiftKey,o=t.evt.ctrlKey||t.evt.metaKey,r=n||o,l=t.target.findAncestor(".elements-container"),s=t.target.findAncestor(".page-abs-container"),a=t.target.findAncestor("Transformer"),d=t.target.findAncestor(".page-container",!0);if(!(r||l||a||s||d||_e.visible)){return e.selectElements([]),void e.selectPages([])}if(o&&!n){const t=ye.current,n=null==t?void 0:t.getPointerPosition();if(!t||!n){return}const i=t.getAllIntersections(n),o=new Set,r=[];for(const s of[...i].reverse()){const t=s.findAncestor(".element",!0);if(!t){continue}const n=e.getElementById(t.id()),i=null==n?void 0:n.top;i&&(o.has(i.id)||(o.add(i.id),r.push(i.id)))}if(0===r.length){return}let l;if(1===e.selectedElementsIds.length){const t=e.selectedElementsIds[0],n=r.indexOf(t);l=-1===n?r[0]:r[(n+1)%r.length]}else{l=r[0]}return e.selectElements([l]),void e.selectPages([])}const c=t.target.findAncestor(".element-container",!0),h=(null==c?void 0:c.findOne(".element"))||t.target.findAncestor(".element",!0),m=e.getElementById(null==h?void 0:h.id()),u=null==m?void 0:m.top;let g;if("group"===S){g=null==u?void 0:u.id}else if(u){const t=e.selectedElements.some(e=>{var t;return(null===(t=e.top)||void 0===t?void 0:t.id)===u.id});g=t?null==m?void 0:m.id:null==u?void 0:u.id}else{g=void 0}const f=null==m?void 0:m.id;if(f&&e.selectedElementsIds.indexOf(f)>=0&&!n){return}const p=!!g&&e.selectedElementsIds.indexOf(g)>=0,x=t.target.findAncestor(".page-container",!0);if(g&&n&&!p){const t=e.selectedElementsIds.concat([g]),n=new Set(t),i=t.filter(t=>{const i=e.getElementById(t);if(!i){return!1}for(let e=i.parent;e;e=null==e?void 0:e.parent){if(n.has(e.id)){return!1}}return!0});e.selectElements(i),e.selectPages([])}else{g&&n&&p?e.selectElements(e.selectedElementsIds.filter(e=>e!==g)):!g||n||p?g&&!n&&p||(x?(n||e.selectElements([]),e.selectPages([i.id])):e.selectPages([])):(e.selectElements([g]),e.selectPages([]))}};I(xe,e);const Qe=e.activePage===i,qe=e._selectedPagesIds.includes(i.id),et=null==w?void 0:w.PageControls,tt=null==w?void 0:w.Tooltip,nt=null==w?void 0:w.ContextMenu,it=1/e.scale,ot=0/e.scale;return n("div",{ref:we,onDragOver:e=>e.preventDefault(),onDrop:t=>{if(t.preventDefault(),e.role===Y.VIEWER){return}if(!ye.current){return}ye.current.setPointersPositions(t);const n=ye.current.findOne(".elements-container"),o=null==n?void 0:n.getRelativePointerPosition(),r=ye.current.getPointerPosition(),l=ye.current.getAllIntersections(r).map(e=>e.findAncestor(".element",!0)).filter(Boolean),s=[...new Set(l.reverse())].map(t=>e.getElementById(t.id())).filter(e=>!!e),a=s[0];he&&o&&(he(o,a,{elements:s,page:i}),he=null)},style:{position:"relative",width:r+"px",height:a+"px",overflow:"hidden",flexShrink:0},className:"polotno-page-container"+(Qe?" active-page":""),children:[t(x,{ref:ye,width:Math.min(r,k.width+200),height:Math.min(k.height+200,a),onClick:$e,onTap:$e,onContextMenu:t=>{if(t.evt.preventDefault(),e.role===Y.VIEWER){return}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;if(!r){return e.selectElements([]),void Oe.close()}e.selectedElementsIds.indexOf(r)>=0||e.selectElements([r]),Oe.open({x:t.evt.clientX,y:t.evt.clientY})},onMouseDown:Je,onMouseMove:t=>{if(!e.distanceGuidesVisible&&!t.evt.altKey){return void(Ye&&Se(null))}const n=t.target.findAncestor(".element",!0),i=null==n?void 0:n.id();Ne(i)},onDragStart:t=>{var n;const i=t.target.getStage();if(i&&i.getPointersPositions().length>=2){return void t.target.stopDrag()}const o=t.target.findAncestor(".element",!0);if(o){const i=e.getElementById(null==o?void 0:o.id()),r=null==i?void 0:i.top,l=null==r?void 0:r.id;if(!(i&&e.selectedElementsIds.indexOf(i.id)>=0||l&&e.selectedElementsIds.indexOf(l)>=0)&&l){e.selectElements([l]);const i=ze();t.target.stopDrag(),i.forEach(e=>{e.isDragging()||e.startDrag(t)}),null===(n=xe.current)||void 0===n||n.startDrag(t),M()}}Ye&&Se(null)},pageId:i.id,style:{position:"absolute",overflow:"hidden",top:0,left:0},children:n(u,{children:[t(ie,{width:r,height:a,fill:J.workspaceBackgroundColor}),t(c,{x:ue,y:pe,scaleX:e.scale,scaleY:e.scale,name:"page-container",children:n(c,{name:"page-container-2",children:[t(c,{name:"page-background-group",x:re.left,y:re.top,children:t(le,{x:-oe.left,y:-oe.top,width:i.computedWidth+oe.left+oe.right,height:i.computedHeight+oe.top+oe.bottom,background:i.background,transparencyBackgroundColor:J.transparencyBackgroundColor,name:"page-background",preventDefault:!1,scale:e.scale})}),n(c,{x:re.left,y:re.top,name:"elements-container",listening:!e.isPlaying&&e.role!==Y.VIEWER,children:[t(f,{name:"elements-area",width:i.computedWidth,height:i.computedHeight,listening:!1}),t(ce,{elements:i.children,store:e})]}),t(p,{name:"bleed",fill:J.bleedColor,listening:!1,visible:e.bleedVisible&&(re.top>0||re.right>0||re.bottom>0||re.left>0),hideInExport:!0,sceneFunc:(e,t)=>{const{top:n,right:o,bottom:r,left:l}=oe,s=i.computedWidth,a=i.computedHeight,d=e._context;d.beginPath(),d.rect(0,0,l+s+o,n+a+r),d.rect(l,n,s,a),d.fillStyle=t.fill(),d.fill("evenodd")}}),R()===ge&&t(fe,{name:"hit-detection",x:-it/2-ot,y:-it/2-ot,width:ae+it+2*ot,height:me+it+2*ot})]})}),t(g,{name:"workspace-background",points:[0,0,r,0,r,a,0,a,0,0,ue,pe,ue,a-pe,r-ue,a-pe,r-ue,pe,ue,pe],listening:!1,closed:!0,fill:J.workspaceBackgroundColor}),t(c,{x:ue,y:pe,scaleX:e.scale,scaleY:e.scale,children:t(f,{name:"page-highlight",hideInExport:!0,x:-it/2-ot,y:-it/2-ot,width:ae+it+2*ot,height:me+it+2*ot,stroke:qe?J.activePageBorderColor:J.pageBorderColor,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})}),n(c,{x:ue+re.left*e.scale,y:pe+re.top*e.scale,scaleX:e.scale,scaleY:e.scale,name:"page-abs-container",children:[t(y,{ref:xe,rotateAnchorAngle:Me,onDragStart:t=>{var n;const o=t.target.getStage();o&&o.getPointersPositions().length>=2?t.target.stopDrag():((null===(n=t.evt)||void 0===n?void 0:n.altKey)&&E&&e.selectedElements.forEach(e=>{const t=e.clone({},{skipSelect:!0}),n=i.children.indexOf(e);i.setElementZIndex(t.id,n)}),Xe.current||(Xe.current=!0,e.history.startTransaction()))},onDragEnd:()=>{Xe.current&&(e.history.endTransaction(),Xe.current=!1),Ze()},onTransformStart:()=>{e.history.startTransaction(),ve.current=new Map(Te.map(e=>[e.id,{width:e.width,height:e.height}])),Se(null)},boundBoxFunc:(t,n)=>{var i,o;const r=Math.abs(n.width)<1||Math.abs(n.height)<1,l=Math.abs(t.width)<1||Math.abs(t.height)<1;if(r&&!l){return t}const s=e.selectedElements;if(1===s.length&&"table"===(null===(i=s[0])||void 0===i?void 0:i.type)){const e=s[0],i=Math.abs(t.width),o=Math.abs(t.height);if(i>0&&o>0){const r=Math.abs(n.width)/i,l=Math.abs(n.height)/o,s=e.width*r,a=e.height*l,d=Object.assign({},n);return s<e.minWidth&&(d.width=t.width),a<e.minHeight&&(d.height=t.height),te(d,n,t)}}return Be&&Te.length>0?((e,t,n,i,o)=>{const r=Math.abs(e.width),l=Math.abs(e.height);if(0===r||0===l){return t}const s=Math.abs(t.width)/r,a=Math.abs(t.height)/l,d=!V(n),c=e=>i.some(t=>{var n;const i=null==o?void 0:o.get(t.id),r=null!==(n="x"===e?null==i?void 0:i.width:null==i?void 0:i.height)&&void 0!==n?n:"x"===e?t.width:t.height,l="x"===e?t.width:t.height,c="x"===e?s:a,h=((e,t,n,i)=>{if("table"===e.type){const n=e;return"x"===t?n.minWidth:n.minHeight}return"text"===e.type&&"x"===t&&n?F(i,e.fontSize):1})(t,e,d,r);return r>=h&&l*c<h}),h=Object.assign({},t),m=t.width*e.width<0,u=t.height*e.height<0,g=m||c("x"),f=u||c("y"),p=f||!d&&g;return(g||!d&&f)&&(h.width=e.width),p&&(h.height=e.height),te(h,t,e)})(t,n,(null===(o=xe.current)||void 0===o?void 0:o.getActiveAnchor())||"",Te,ve.current):n},onTransform:e=>{const t=xe.current.nodes(),n=t[t.length-1];e.target===n&&setTimeout(()=>{Ue()},0)},onTransformEnd:t=>{Ae({}),e.history.endTransaction(),ve.current=null,Ze(),ze()},visible:!e.isPlaying}),Ye&&Ye.map(({points:i,distance:o,box1:r,box2:l},s)=>n(c,{name:"distances-container",hideInExport:!0,listening:!1,children:[t(f,Object.assign({},r,{stroke:J.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(f,Object.assign({},l,{stroke:J.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(g,{points:[i[0].x,i[0].y,i[1].x,i[1].y],stroke:J.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),t(g,{points:[i[1].x,i[1].y,i[2].x,i[2].y],stroke:J.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),n(m,{x:(i[0].x+i[1].x)/2,y:(i[0].y+i[1].y)/2,offsetY:-10,scaleX:1/e.scale,scaleY:1/e.scale,children:[t(v,{cornerRadius:5,fill:J.distanceGuideStyle.labelFill,pointerDirection:"down"}),t(b,{align:"center",verticalAlign:"middle",fill:J.distanceGuideStyle.labelTextFill,padding:5,text:L({unit:e.unit,dpi:e.dpi,px:o})})]})]},s)),i._rendering&&n(c,{children:[t(f,{width:ae,height:me,fill:"rgba(255,255,255,0.9)"}),t(b,{text:"Rendering...",fontSize:60,width:ae,height:me,align:"center",verticalAlign:"middle"})]}),tt&&t(tt,{components:w,store:e,page:i,stageRef:ye,tooltipSafeArea:P}),nt&&t(H,{children:t(nt,Object.assign({components:w,store:e},Oe.props))})]}),t(A,{store:e,page:i,width:r,height:a,scale:e.scale,xPadding:ue,yPadding:pe,bleedLeft:re.left,bleedTop:re.top}),t(de,Object.assign({},ke,{store:e})),t(se,{selection:_e}),j()>0&&n(c,{hideInExport:!0,children:[t(be,{name:"cache-bounds",x:r-(1===j()?250:210),y:a-(1===j()?95:45)}),t(be,{name:"cache-bounds-t",x:10,y:10})]}),D()&&t(b,{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","_blank","noopener")},onTap:()=>{window.open("https://polotno.com","_blank","noopener")}}),t(c,{name:"line-guides"})]})}),Ee&&et&&t(et,{store:e,page:i,xPadding:ue,yPadding:pe,layout:O})]})});
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var n={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++){t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}}return n};import{jsx as t,jsxs as n,Fragment as i}from"react/jsx-runtime";import o from"react";import{observer as r,useLocalObservable as l}from"mobx-react-lite";import{action as s,runInAction as a}from"mobx";import{ZERO_BLEED as d}from"@polotno/schema";import{Group as c,Image as m,Label as h,Layer as u,Line as g,Rect as f,Shape as p,Stage as x,Tag as v,Text as b,Transformer as y,KonvaRenderer as w}from"react-konva";import{useWorkspaceStyle as E}from"./workspace-style.js";import{ROLES as X}from"../model/store.js";import Y from"konva";import S from"./element.js";import{DrawingLayer as k}from"./drawing-layer.js";import{ensureDragOrder as A,useSnap as M}from"./use-transformer-snap.js";import{useCanvasImage as I,useImageLoader as O}from"./image-element.js";import{getCrop as P}from"../utils/crop.js";import{___ as R,____ as j,isCreditVisible as D}from"../utils/validate-key.js";import{getClientRect as B,getCorners as C,getTotalClientRect as T,polygonsIntersect as W}from"../utils/math.js";import{pxToUnitRounded as G,pxToUnitString as L}from"../utils/unit.js";import{isCornerAnchor as F,MAIN_TRANSFORMER_NAME as V,textMinResizeWidth as z,textMinWidthIsMeasured as U}from"../utils/px.js";import{restoreHeldPoint as Z}from"./transform-box.js";import{flags as _}from"../utils/flags.js";import{useColor as H}from"./use-color.js";import{isGradient as J}from"@polotno/core/gradient";import{Html as N}from"react-konva-utils";import{observerBatching as K}from"mobx-react-lite";const $=e=>w.batchedUpdates(e,null);K(e=>{w.isAlreadyRendering()?queueMicrotask(()=>$(e)):$(e)});const Q=Y.DD._drag;window.removeEventListener("mousemove",Q),Y.DD._drag=function(e){a(()=>{Q.call(this,e)})},window.addEventListener("mousemove",Y.DD._drag);const q={enabledAnchors:["top-left","top-center","top-right","middle-left","bottom-left","bottom-right","bottom-center","middle-right"],rotateEnabled:!0,rotationSnaps:[0,45,90,135,180,225,270,315],ignoreStroke:!0,flipEnabled:!1,keepRatio:!0},ee=e=>{const t=(e%180+180)%180;return t<.1||180-t<.1},te=e=>{if(!e.length){return null}const t=ee(e[0].rotation)?0:e[0].rotation;return e.every(e=>ee(e.rotation-t))?t:null},ne=e=>e.selectedShapes.filter(e=>!e._cropModeEnabled),ie={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"]},table:{keepRatio:!1,enabledAnchors:["top-left","top-center","top-right","middle-left","middle-right","bottom-left","bottom-center","bottom-right"]}};export function registerTransformerAttrs(e,t){ie[e]=ie[e]||t,Object.assign(ie[e],t)}const oe=e=>t(f,Object.assign({},e,{preventDefault:!1})),re=n=>{var{url:i}=n,o=e(n,["url"]);const[r,l]=I(i,"anonymous"),s=r?P(r,{width:o.width,height:o.height},"center-middle"):{};return O(l,i,"page background"),t(m,Object.assign({image:r},o,s))},le=e=>{const n=H({a:{width:e.width,height:e.height},width:e.width,height:e.height},e.fill);return t(f,Object.assign({},e,n))},se=i=>{const{background:r,scale:l,borderColor:s,transparencyBackgroundColor:a}=i,d=e(i,["background","scale","borderColor","transparencyBackgroundColor"]),c=o.useMemo(()=>!!Y.Util.colorToRGBA(r)||J(r),[r]),m=o.useMemo(()=>{if(J(r)){return!0}const e=Y.Util.colorToRGBA(r);return!e||e.a<1},[r]),h=o.useMemo(()=>{if(!m||a){return null}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},[m,a]);return n(o.Fragment,{children:[m&&t(f,a?Object.assign({fill:a},d,{hideInExport:!0}):Object.assign({fillPatternImage:h},d,{opacity:.1,hideInExport:!0})),c?t(le,Object.assign({fill:r},d)):t(re,Object.assign({url:r},d))]})},ae=r(({selection:e})=>{const{selectionRectStyle:n}=E();return e.visible?t(f,{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.fill,stroke:n.stroke,strokeWidth:n.strokeWidth}):null});function de(e){let t=180*e/Math.PI;return t%=360,t>180?t-=360:t<-180&&(t+=360),Math.round(t)}const ce=r(({x:e,y:o,width:r,height:l,rotation:s,anchor:a,store:d})=>{const{transformLabelStyle:c}=E();if(void 0===e||void 0===o||void 0===r||void 0===l||void 0===s||void 0===a){return null}const m=B({x:e,y:o,width:r,height:l,rotation:Y.Util.radToDeg(s)}),u=(l/2+70)*Math.cos(s-Math.PI/2),g=(l/2+70)*Math.sin(s-Math.PI/2),f=G({unit:d.unit,dpi:d.dpi,px:r/d.scale,precious:"px"===d.unit?0:1})+" x "+G({unit:d.unit,dpi:d.dpi,px:l/d.scale,precious:"px"===d.unit?0:1})+("px"===d.unit?"":" "+d.unit);return n(i,{children:[n(h,{x:(m.minX+m.maxX)/2+u,y:(m.minY+m.maxY)/2+g,offsetX:14,offsetY:14,visible:"rotater"===a,children:[t(v,{cornerRadius:5,fill:c.fill}),t(b,{align:"center",verticalAlign:"middle",fill:c.textFill,padding:8,text:de(s).toString()+"°"})]}),n(h,{x:(m.minX+m.maxX)/2,y:m.maxY+20,visible:"rotater"!==a,children:[t(v,{cornerRadius:5,fill:c.fill,pointerDirection:"up",pointerHeight:0,pointerWidth:0}),t(b,{align:"center",verticalAlign:"middle",fill:c.textFill,padding:8,text:f})]})]})}),me=r(({elements:e,store:n})=>{const i=e.filter(e=>e.alwaysOnTop),r=e.filter(e=>!e.alwaysOnTop).concat(i);return t(o.Fragment,{children:r.map(e=>t(S,{store:n,element:e,onClick:()=>{console.warn("Polotno warning: onClick callback is deprecated. Just stop using it. Polotno will do selection automatically.")}},e.id))})});export const useContextMenu=({store:e})=>{const[t,n]=o.useState(!1),[i,r]=o.useState({x:0,y:0}),l=o.useCallback(e=>{n(!0),r(e)},[]);return{open:l,close:o.useCallback(()=>{n(!1)},[]),props:{isOpen:t,offset:i,setIsOpen:n}}};let he=null;export const registerNextDomDrop=e=>{he=e};const ue=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),ge=atob("I2MwMzkyYg=="),fe=atob("djAuOS4y"),pe=e=>t(i,{children:n(h,{fill:ge,height:200,children:[t(v,{fill:ge}),t(b,Object.assign({},e,{fill:"white",text:ue,height:void 0,padding:10,fontSize:20}))]})}),xe=atob("RlJFRSAgVFJJQUwgIExJQ0VOU0U="),ve=(atob("UG93ZXJlZCBieSBQb2xvdG5v"),atob("TElDRU5TRSAgS0VZICBJUyAgTUlTU0lORw==")),be=atob("UGxlYXNlIGFjdGl2YXRlIHlvdXIgbGljZW5zZS4KTGljZW5zZSByZWxhdGVkIHF1ZXN0aW9uczoKcG9sb3Ruby5jb20vY29udGFjdA=="),ye=e=>{const i=1===j(),o=i?ve:xe,r=i?230:195;return n(c,Object.assign({},e,{listening:!1,children:[t(f,{fill:ge,width:r,height:24,cornerRadius:2}),t(b,{text:o,fill:"white",fontSize:13,fontFamily:"monospace",width:r,align:"center",y:5,listening:!1}),i&&t(b,{text:be,fill:"rgba(0,0,0,0.6)",fontSize:14,y:30,listening:!1})]}))};export default r(({store:i,page:r,width:a,height:m,pageControlsEnabled:w,components:Y,altCloneEnabled:S,groupSelectionMode:I="drill",viewportSize:O,layout:P="vertical",tooltipSafeArea:G,transformerSafeArea:H})=>{var J,K;const $=E(),Q=$.transformerStyle,re=q,le=r.computedBleed,de=i.bleedVisible?le:d,ue=r.computedWidth+de.left+de.right,ge=r.computedHeight+de.top+de.bottom,xe=(a-ue*i.scale)/2,ve=(m-ge*i.scale)/2,be=o.useRef(null),we=o.useRef(null),Ee=o.useRef(null),Xe=o.useRef(null),Ye=null==w||w,Se=o.useRef(!1),[ke,Ae]=o.useState(null),[Me,Ie]=o.useState({}),[Oe,Pe]=o.useState(0),Re=useContextMenu({store:i}),je=i.selectedElements.find(e=>e._cropModeEnabled),De=i.selectedElements.find(e=>e.curveEnabled),Be=i.selectedShapes.filter(e=>!e.resizable).length>0,Ce=i.selectedShapes.filter(e=>!e.draggable).length>0,Te=i.selectedElements.filter(e=>!e.visible).length>0,We=ne(i),Ge=1!==i.selectedElements.length||"group"===(null===(J=i.selectedElements[0])||void 0===J?void 0:J.type),Le=null!==(K=te(We))&&void 0!==K?K:0,Fe=e=>Ge&&We.length>0&&We.every(t=>((e,t,n)=>{if(!ee(e.rotation-n)){return!1}switch(e.type){case"text":return"x"===t&&!U(e);case"figure":case"video":case"table":return!0;case"image":case"svg":case"gif":return!e.keepRatio;default:return!1}})(t,e,Le)),Ve=!Ge&&i.selectedElements[0].keepRatio,ze=Fe("x"),Ue=Fe("y"),Ze=()=>{var t,n,o;const r=be.current;if(!r){return[]}const l=r.getStage();if(!l){return[]}const s=ne(i),a=s.map(e=>l.findOne("#"+e.id)).filter(e=>!!e),d=1===i.selectedElements.length,c=d&&(null===(t=i.selectedElements[0])||void 0===t?void 0:t.type)||"many",m=ie[c],h=Object.assign(Object.assign({},re),m||{});m&&("svg"!==c&&"image"!==c&&"gif"!==c||i.selectedElements[0].keepRatio||(h.enabledAnchors=re.enabledAnchors),"text"===c&&_.textVerticalResizeEnabled&&(h.enabledAnchors=null===(n=ie.text.enabledAnchors)||void 0===n?void 0:n.concat(["bottom-center","top-center"])),"text"===c&&d&&i.selectedElements[0].curveEnabled&&(h.enabledAnchors=ie.many.enabledAnchors)),(ze||Ue)&&(h.enabledAnchors=[...h.enabledAnchors||[],...ze?["middle-left","middle-right"]:[],...Ue?["top-center","bottom-center"]:[]]);const{boundBoxFunc:u}=Q,g=e(Q,["boundBoxFunc"]);r.setAttrs(Object.assign(Object.assign(Object.assign({},h),g),{name:V})),Be&&r.enabledAnchors([]),Ce&&r.rotateEnabled(!1);const f=r.nodes();if(f.length===a.length&&a.every((e,t)=>f[t]===e)||r.nodes(a),Ge&&a.length){const e=te(s);null===e||ee(r.rotation()-e)||(r.rotation(e),r.forceUpdate())}return null===(o=r.getLayer())||void 0===o||o.batchDraw(),a};o.useLayoutEffect(()=>{var e;if(null===(e=be.current)||void 0===e?void 0:e.isTransforming()){return}const t=Ze();t.find(e=>null==e?void 0:e.isDragging())&&(t.forEach(e=>{e.isDragging()||null==e||e.startDrag()}),A())},[i.selectedShapes,je,Be,Te,Ce,De,ze,Ue,Ve,Le,Q]);const _e=()=>{var e,t;const n=be.current;if(!n){return}if(!n.isTransforming()){return void Ie({})}if(!n.nodes().length||!n.isTransforming()){return}const i=n.__getNodeRect(),o=null==n?void 0:n.getActiveAnchor(),r=n.getStage();Ie({anchor:o,x:i.x-(null!==(e=null==r?void 0:r.x())&&void 0!==e?e:0),y:i.y-(null!==(t=null==r?void 0:r.y())&&void 0!==t?t:0),rotation:i.rotation,width:i.width,height:i.height})},He=o.useCallback(()=>{var e;if(null===(e=be.current)||void 0===e?void 0:e.isTransforming()){return}const t=be.current;if(!t||!t.nodes().length){return void Pe(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,s=e.height/2,a=i*Math.PI/180,d=e=>{const t=e*Math.PI/180,i=(e%360+360)%360;let d;d=0===i||180===i?s:l;const c=Math.sin(t)*(d+n),m=-Math.cos(t)*(d+n),h=c*Math.cos(a)-m*Math.sin(a),u=c*Math.sin(a)+m*Math.cos(a);return{x:o+h,y:r+u}},c=e=>e.x>=t.left&&e.x<=t.right&&e.y>=t.top&&e.y<=t.bottom;if(c(d(0))){return 0}for(const m of[180,270,90]){if(c(d(m))){return m}}return 0}(n,{top:(null==H?void 0:H.top)||0,bottom:m-((null==H?void 0:H.bottom)||0),left:(null==H?void 0:H.left)||0,right:a-((null==H?void 0:H.right)||0)},Q.rotateAnchorOffset,t.rotation());Pe(i)},[H,a,m]);o.useEffect(()=>{var e;null===(e=be.current)||void 0===e||e.update(),_e(),He()},[i.scale,He]),o.useEffect(()=>{He()},[i.selectedShapes,He]);const Je=l(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),Ne=o.useRef(!1),Ke=s(e=>{var t,n,o,r,l,s,a;if(i.role===X.VIEWER){return}Ne.current=!1;const d=e.target.findAncestor(".elements-container"),c=e.target.findAncestor("Transformer"),m=e.target.findAncestor(".page-abs-container");if(d||c||m){return}const h=null===(t=e.target.getStage())||void 0===t?void 0:t.getPointerPosition();h&&(h.x-=null!==(o=null===(n=e.target.getStage())||void 0===n?void 0:n.x())&&void 0!==o?o:0,h.y-=null!==(l=null===(r=e.target.getStage())||void 0===r?void 0:r.y())&&void 0!==l?l:0,Je.visible=!0,Je.x1=h.x,Je.y1=h.y,Je.x2=h.x,Je.y2=h.y,(null!==(a=null===(s=e.target.getStage())||void 0===s?void 0:s.getPointersPositions().length)&&void 0!==a?a:0)>=2&&(Je.visible=!1))});(({stageRef:e,containerRef:t,viewportSize:n})=>{o.useEffect(()=>{var n;const i=null===(n=t.current)||void 0===n?void 0:n.closest(".polotno-workspace-inner");function o(){var n;if(!e.current){return}const o=null===(n=t.current)||void 0===n?void 0:n.getBoundingClientRect(),r=null==i?void 0:i.getBoundingClientRect();if(!o||!r){return}const l=Math.max(0,r.left-o.left-100),s=Math.max(0,r.top-o.top-100);e.current.position({x:-l,y:-s}),e.current.container().style.transform=`translate(${l}px, ${s}px)`}return o(),null==i||i.addEventListener("scroll",o),()=>{null==i||i.removeEventListener("scroll",o)}},[n.width,n.height])})({stageRef:Ee,containerRef:Xe,viewportSize:O}),o.useEffect(()=>{const e=s(e=>{var t,n,i,o,r,l;if(!Je.visible){return}null===(t=Ee.current)||void 0===t||t.setPointersPositions(e);let s=null===(n=Ee.current)||void 0===n?void 0:n.getPointerPosition();s?(s.x-=null!==(o=null===(i=Ee.current)||void 0===i?void 0:i.x())&&void 0!==o?o:0,s.y-=null!==(l=null===(r=Ee.current)||void 0===r?void 0:r.y())&&void 0!==l?l:0):s={x:Je.x2,y:Je.y2},Je.x2=s.x,Je.y2=s.y}),t=s(()=>{if(!Je.visible){return}if(!Ee.current){return}const e=Ee.current.findOne(".selection"),t=e?e.getClientRect({skipStroke:!0}):{width:0,height:0,x:0,y:0};if(t.width&&t.height){const e=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}],n=[];Ee.current.find(".element").forEach(t=>{var o;const r=i.getElementById(t.id()),l=null==r?void 0:r.draggable,s=null==r?void 0:r.selectable;if(!l||!s){return}const a=null===(o=t.getParent())||void 0===o?void 0:o.getAbsoluteTransform();if(!a){return}const d=C(r.a).map(e=>a.point(e));W(e,d)&&n.push(r.top.id)});const o=[...new Set(n)];Ne.current=!0,i.selectElements(o)}Je.visible=!1});return window.addEventListener("mousemove",e),window.addEventListener("touchmove",e),window.addEventListener("mouseup",t,{capture:!0}),window.addEventListener("touchend",t,{capture:!0}),()=>{window.removeEventListener("mousemove",e),window.removeEventListener("touchmove",e),window.removeEventListener("mouseup",t),window.removeEventListener("touchend",t)}},[]);const $e=o.useCallback(e=>{if(!i.selectedElements[0]){return}if(e&&i.selectedElementsIds.includes(e)){return}const t=T(i.selectedShapes),n=e?i.getElementById(e):{x:0,y:0,width:r.computedWidth,height:r.computedHeight,rotation:0},o=B(n),l=[];t.minX>o.maxX&&l.push({distance:t.minX-o.maxX,box1:t,box2:o,points:[{x:t.minX,y:t.minY+t.height/2},{x:o.maxX,y:t.minY+t.height/2},{x:o.maxX,y:o.minY+o.height/2}]}),t.maxX<o.minX&&l.push({distance:o.minX-t.maxX,box1:t,box2:o,points:[{x:t.maxX,y:t.minY+t.height/2},{x:o.minX,y:t.minY+t.height/2},{x:o.minX,y:o.minY+o.height/2}]}),t.minY>o.maxY&&l.push({box1:t,box2:o,distance:t.minY-o.maxY,points:[{x:t.minX+t.width/2,y:t.minY},{x:t.minX+t.width/2,y:o.maxY},{x:o.minX+o.width/2,y:o.maxY}]}),t.maxY<o.minY&&l.push({box1:t,box2:o,distance:o.minY-t.maxY,points:[{x:t.minX+t.width/2,y:t.maxY},{x:t.minX+t.width/2,y:o.minY},{x:o.minX+o.width/2,y:o.minY}]});const s=t.minX>=o.minX&&t.maxX<=o.maxX&&t.minY>=o.minY&&t.maxY<=o.maxY;if(s&&(l.push({distance:t.minX-o.minX,box1:t,box2:o,points:[{x:t.minX,y:t.minY+t.height/2},{x:o.minX,y:t.minY+t.height/2},{x:o.minX,y:o.minY+o.height/2}]}),l.push({distance:o.maxX-t.maxX,box1:t,box2:o,points:[{x:t.maxX,y:t.minY+t.height/2},{x:o.maxX,y:t.minY+t.height/2},{x:o.maxX,y:o.minY+o.height/2}]}),l.push({box1:t,box2:o,distance:t.minY-o.minY,points:[{x:t.minX+t.width/2,y:t.minY},{x:t.minX+t.width/2,y:o.minY},{x:o.minX+o.width/2,y:o.minY}]}),l.push({box1:t,box2:o,distance:o.maxY-t.maxY,points:[{x:t.minX+t.width/2,y:t.maxY},{x:t.minX+t.width/2,y:o.maxY},{x:o.minX+o.width/2,y:o.maxY}]})),0===l.length&&!s){const e=t.minX<o.maxX&&t.maxX>o.minX,n=t.minY<o.maxY&&t.maxY>o.minY;if(e&&n){const e=(Math.max(t.minY,o.minY)+Math.min(t.maxY,o.maxY))/2,n=(Math.max(t.minX,o.minX)+Math.min(t.maxX,o.maxX))/2;t.minX<o.minX?l.push({distance:o.minX-t.minX,box1:t,box2:o,points:[{x:t.minX,y:e},{x:o.minX,y:e},{x:o.minX,y:e}]}):l.push({distance:t.minX-o.minX,box1:t,box2:o,points:[{x:t.minX,y:e},{x:o.minX,y:e},{x:o.minX,y:e}]}),t.maxX>o.maxX?l.push({distance:t.maxX-o.maxX,box1:t,box2:o,points:[{x:o.maxX,y:e},{x:t.maxX,y:e},{x:o.maxX,y:e}]}):l.push({distance:o.maxX-t.maxX,box1:t,box2:o,points:[{x:t.maxX,y:e},{x:o.maxX,y:e},{x:o.maxX,y:e}]}),t.minY<o.minY?l.push({box1:t,box2:o,distance:o.minY-t.minY,points:[{x:n,y:t.minY},{x:n,y:o.minY},{x:n,y:o.minY}]}):l.push({box1:t,box2:o,distance:t.minY-o.minY,points:[{x:n,y:t.minY},{x:n,y:o.minY},{x:n,y:o.minY}]}),t.maxY>o.maxY?l.push({box1:t,box2:o,distance:t.maxY-o.maxY,points:[{x:n,y:o.maxY},{x:n,y:t.maxY},{x:n,y:o.maxY}]}):l.push({box1:t,box2:o,distance:o.maxY-t.maxY,points:[{x:n,y:t.maxY},{x:n,y:o.maxY},{x:n,y:o.maxY}]})}}JSON.stringify(ke)!==JSON.stringify(l)&&Ae(l)},[i,r]);o.useEffect(()=>{i.selectedElements[0]&&i.distanceGuidesVisible?$e():ke&&Ae(null)},[i.distanceGuidesVisible,$e,i.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const Qe=o.useRef(!1);o.useEffect(()=>{var e;let t;const n=null===(e=Xe.current)||void 0===e?void 0:e.closest(".polotno-workspace-inner"),i=()=>{Qe.current=!0,clearTimeout(t),t=setTimeout(()=>{Qe.current=!1},300)};return null==n||n.addEventListener("scroll",i),()=>{clearTimeout(t),null==n||n.removeEventListener("scroll",i)}},[]),o.useEffect(()=>{const e=Ee.current;if(!e){return}const t=e.container(),n=new Map,o=e=>{n.set(e.target,{x:e.target.x(),y:e.target.y()})},r=e=>{n.delete(e.target)};e.on("dragstart",o),e.on("dragend",r);const l=e=>{var t,o;e.touches.length>=2&&((null===(t=be.current)||void 0===t?void 0:t.isDragging())&&be.current.stopDrag(),null===(o=be.current)||void 0===o||o.nodes().forEach(e=>{var t;const o=n.get(e);e.isDragging()&&e.stopDrag(),o&&(e.setAttrs(o),null===(t=i.getElementById(e.id()))||void 0===t||t.set({x:o.x,y:o.y}))}))};return t.addEventListener("touchstart",l,{passive:!0}),t.addEventListener("touchmove",l,{passive:!0}),()=>{e.off("dragstart",o),e.off("dragend",r),t.removeEventListener("touchstart",l),t.removeEventListener("touchmove",l)}},[i]);const qe=e=>{if(i.role===X.VIEWER){return}if(i.activePage!==r&&r.select(),Qe.current){return}if(Ne.current){return}const t=e.evt.shiftKey,n=e.evt.ctrlKey||e.evt.metaKey,o=t||n,l=e.target.findAncestor(".elements-container"),s=e.target.findAncestor(".page-abs-container"),a=e.target.findAncestor("Transformer"),d=e.target.findAncestor(".page-container",!0);if(!(o||l||a||s||d||Je.visible)){return i.selectElements([]),void i.selectPages([])}if(n&&!t){const e=Ee.current,t=null==e?void 0:e.getPointerPosition();if(!e||!t){return}const n=e.getAllIntersections(t),o=new Set,r=[];for(const s of[...n].reverse()){const e=s.findAncestor(".element",!0);if(!e){continue}const t=i.getElementById(e.id()),n=null==t?void 0:t.top;n&&(o.has(n.id)||(o.add(n.id),r.push(n.id)))}if(0===r.length){return}let l;if(1===i.selectedElementsIds.length){const e=i.selectedElementsIds[0],t=r.indexOf(e);l=-1===t?r[0]:r[(t+1)%r.length]}else{l=r[0]}return i.selectElements([l]),void i.selectPages([])}const c=e.target.findAncestor(".element-container",!0),m=(null==c?void 0:c.findOne(".element"))||e.target.findAncestor(".element",!0),h=i.getElementById(null==m?void 0:m.id()),u=null==h?void 0:h.top;let g;if("group"===I){g=null==u?void 0:u.id}else if(u){const e=i.selectedElements.some(e=>{var t;return(null===(t=e.top)||void 0===t?void 0:t.id)===u.id});g=e?null==h?void 0:h.id:null==u?void 0:u.id}else{g=void 0}const f=null==h?void 0:h.id;if(f&&i.selectedElementsIds.indexOf(f)>=0&&!t){return}const p=!!g&&i.selectedElementsIds.indexOf(g)>=0,x=e.target.findAncestor(".page-container",!0);if(g&&t&&!p){const e=i.selectedElementsIds.concat([g]),t=new Set(e),n=e.filter(e=>{const n=i.getElementById(e);if(!n){return!1}for(let i=n.parent;i;i=null==i?void 0:i.parent){if(t.has(i.id)){return!1}}return!0});i.selectElements(n),i.selectPages([])}else{g&&t&&p?i.selectElements(i.selectedElementsIds.filter(e=>e!==g)):!g||t||p?g&&!t&&p||(x?(t||i.selectElements([]),i.selectPages([r.id])):i.selectPages([])):(i.selectElements([g]),i.selectPages([]))}};M(be,i);const et=i.activePage===r,tt=i._selectedPagesIds.includes(r.id),nt=null==Y?void 0:Y.PageControls,it=null==Y?void 0:Y.Tooltip,ot=null==Y?void 0:Y.ContextMenu,rt=1/i.scale,lt=0/i.scale;return n("div",{ref:Xe,onDragOver:e=>e.preventDefault(),onDrop:e=>{if(e.preventDefault(),i.role===X.VIEWER){return}if(!Ee.current){return}Ee.current.setPointersPositions(e);const t=Ee.current.findOne(".elements-container"),n=null==t?void 0:t.getRelativePointerPosition(),o=Ee.current.getPointerPosition(),l=Ee.current.getAllIntersections(o).map(e=>e.findAncestor(".element",!0)).filter(Boolean),s=[...new Set(l.reverse())].map(e=>i.getElementById(e.id())).filter(e=>!!e),a=s[0];he&&n&&(he(n,a,{elements:s,page:r}),he=null)},style:{position:"relative",width:a+"px",height:m+"px",overflow:"hidden",flexShrink:0},className:"polotno-page-container"+(et?" active-page":""),children:[t(x,{ref:Ee,width:Math.min(a,O.width+200),height:Math.min(O.height+200,m),onClick:qe,onTap:qe,onContextMenu:e=>{if(e.evt.preventDefault(),i.role===X.VIEWER){return}const t=e.target.findAncestor(".element",!0),n=i.getElementById(null==t?void 0:t.id()),o=null==n?void 0:n.top,r=null==o?void 0:o.id;if(!r){return i.selectElements([]),void Re.close()}i.selectedElementsIds.indexOf(r)>=0||i.selectElements([r]),Re.open({x:e.evt.clientX,y:e.evt.clientY})},onMouseDown:Ke,onMouseMove:e=>{if(!i.distanceGuidesVisible&&!e.evt.altKey){return void(ke&&Ae(null))}const t=e.target.findAncestor(".element",!0),n=null==t?void 0:t.id();$e(n)},onDragStart:e=>{var t;const n=e.target.getStage();if(n&&n.getPointersPositions().length>=2){return void e.target.stopDrag()}const o=e.target.findAncestor(".element",!0);if(o){const n=i.getElementById(null==o?void 0:o.id()),r=null==n?void 0:n.top,l=null==r?void 0:r.id;if(!(n&&i.selectedElementsIds.indexOf(n.id)>=0||l&&i.selectedElementsIds.indexOf(l)>=0)&&l){i.selectElements([l]);const n=Ze();e.target.stopDrag(),n.forEach(t=>{t.isDragging()||t.startDrag(e)}),null===(t=be.current)||void 0===t||t.startDrag(e),A()}}ke&&Ae(null)},pageId:r.id,style:{position:"absolute",overflow:"hidden",top:0,left:0},children:n(u,{children:[t(oe,{width:a,height:m,fill:$.workspaceBackgroundColor}),t(c,{x:xe,y:ve,scaleX:i.scale,scaleY:i.scale,name:"page-container",children:n(c,{name:"page-container-2",children:[t(c,{name:"page-background-group",x:de.left,y:de.top,children:t(se,{x:-le.left,y:-le.top,width:r.computedWidth+le.left+le.right,height:r.computedHeight+le.top+le.bottom,background:r.background,transparencyBackgroundColor:$.transparencyBackgroundColor,name:"page-background",preventDefault:!1,scale:i.scale})}),n(c,{x:de.left,y:de.top,name:"elements-container",listening:!i.isPlaying&&i.role!==X.VIEWER,children:[t(f,{name:"elements-area",width:r.computedWidth,height:r.computedHeight,listening:!1}),t(me,{elements:r.children,store:i})]}),t(p,{name:"bleed",fill:$.bleedColor,listening:!1,visible:i.bleedVisible&&(de.top>0||de.right>0||de.bottom>0||de.left>0),hideInExport:!0,sceneFunc:(e,t)=>{const{top:n,right:i,bottom:o,left:l}=le,s=r.computedWidth,a=r.computedHeight,d=e._context;d.beginPath(),d.rect(0,0,l+s+i,n+a+o),d.rect(l,n,s,a),d.fillStyle=t.fill(),d.fill("evenodd")}}),R()===fe&&t(pe,{name:"hit-detection",x:-rt/2-lt,y:-rt/2-lt,width:ue+rt+2*lt,height:ge+rt+2*lt})]})}),t(g,{name:"workspace-background",points:[0,0,a,0,a,m,0,m,0,0,xe,ve,xe,m-ve,a-xe,m-ve,a-xe,ve,xe,ve],listening:!1,closed:!0,fill:$.workspaceBackgroundColor}),t(c,{x:xe,y:ve,scaleX:i.scale,scaleY:i.scale,children:t(f,{name:"page-highlight",hideInExport:!0,x:-rt/2-lt,y:-rt/2-lt,width:ue+rt+2*lt,height:ge+rt+2*lt,stroke:tt?$.activePageBorderColor:$.pageBorderColor,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})}),n(c,{x:xe+de.left*i.scale,y:ve+de.top*i.scale,scaleX:i.scale,scaleY:i.scale,name:"page-abs-container",children:[t(y,{ref:be,name:V,rotateAnchorAngle:Oe,onDragStart:e=>{var t;const n=e.target.getStage();n&&n.getPointersPositions().length>=2?e.target.stopDrag():((null===(t=e.evt)||void 0===t?void 0:t.altKey)&&S&&i.selectedElements.forEach(e=>{const t=e.clone({},{skipSelect:!0}),n=r.children.indexOf(e);r.setElementZIndex(t.id,n)}),Se.current||(Se.current=!0,i.history.startTransaction()))},onDragEnd:()=>{Se.current&&(i.history.endTransaction(),Se.current=!1),He()},onTransformStart:()=>{i.history.startTransaction(),we.current=new Map(We.map(e=>[e.id,{width:e.width,height:e.height}])),Ae(null)},boundBoxFunc:(e,t)=>{var n,o,r,l;const s=null!==(o=null===(n=Q.boundBoxFunc)||void 0===n?void 0:n.call(Q,e,t))&&void 0!==o?o:t,a=Math.abs(s.width)<1||Math.abs(s.height)<1,d=Math.abs(e.width)<1||Math.abs(e.height)<1;if(a&&!d){return e}const c=i.selectedElements;if(1===c.length&&"table"===(null===(r=c[0])||void 0===r?void 0:r.type)){const t=c[0],n=Math.abs(e.width),i=Math.abs(e.height);if(n>0&&i>0){const o=Math.abs(s.width)/n,r=Math.abs(s.height)/i,l=t.width*o,a=t.height*r,d=Object.assign({},s);return l<t.minWidth&&(d.width=e.width),a<t.minHeight&&(d.height=e.height),Z(d,s,e)}}return Ge&&We.length>0?((e,t,n,i,o)=>{const r=Math.abs(e.width),l=Math.abs(e.height);if(0===r||0===l){return t}const s=Math.abs(t.width)/r,a=Math.abs(t.height)/l,d=!F(n),c=e=>i.some(t=>{var n;const i=null==o?void 0:o.get(t.id),r=null!==(n="x"===e?null==i?void 0:i.width:null==i?void 0:i.height)&&void 0!==n?n:"x"===e?t.width:t.height,l="x"===e?t.width:t.height,c="x"===e?s:a,m=((e,t,n,i)=>{if("table"===e.type){const n=e;return"x"===t?n.minWidth:n.minHeight}return"text"===e.type&&"x"===t&&n?z(i,e.fontSize):1})(t,e,d,r);return r>=m&&l*c<m}),m=Object.assign({},t),h=t.width*e.width<0,u=t.height*e.height<0,g=h||c("x"),f=u||c("y"),p=f||!d&&g;return(g||!d&&f)&&(m.width=e.width),p&&(m.height=e.height),Z(m,t,e)})(e,s,(null===(l=be.current)||void 0===l?void 0:l.getActiveAnchor())||"",We,we.current):s},onTransform:e=>{const t=be.current.nodes(),n=t[t.length-1];e.target===n&&setTimeout(()=>{_e()},0)},onTransformEnd:e=>{Ie({}),i.history.endTransaction(),we.current=null,He(),Ze()},visible:!i.isPlaying}),ke&&ke.map(({points:e,distance:o,box1:r,box2:l},s)=>n(c,{name:"distances-container",hideInExport:!0,listening:!1,children:[t(f,Object.assign({},r,{stroke:$.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(f,Object.assign({},l,{stroke:$.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(g,{points:[e[0].x,e[0].y,e[1].x,e[1].y],stroke:$.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),t(g,{points:[e[1].x,e[1].y,e[2].x,e[2].y],stroke:$.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),n(h,{x:(e[0].x+e[1].x)/2,y:(e[0].y+e[1].y)/2,offsetY:-10,scaleX:1/i.scale,scaleY:1/i.scale,children:[t(v,{cornerRadius:5,fill:$.distanceGuideStyle.labelFill,pointerDirection:"down"}),t(b,{align:"center",verticalAlign:"middle",fill:$.distanceGuideStyle.labelTextFill,padding:5,text:L({unit:i.unit,dpi:i.dpi,px:o})})]})]},s)),r._rendering&&n(c,{children:[t(f,{width:ue,height:ge,fill:"rgba(255,255,255,0.9)"}),t(b,{text:"Rendering...",fontSize:60,width:ue,height:ge,align:"center",verticalAlign:"middle"})]}),it&&t(it,{components:Y,store:i,page:r,stageRef:Ee,tooltipSafeArea:G}),ot&&t(N,{children:t(ot,Object.assign({components:Y,store:i},Re.props))})]}),t(k,{store:i,page:r,width:a,height:m,scale:i.scale,xPadding:xe,yPadding:ve,bleedLeft:de.left,bleedTop:de.top}),t(ce,Object.assign({},Me,{store:i})),t(ae,{selection:Je}),j()>0&&n(c,{hideInExport:!0,children:[t(ye,{name:"cache-bounds",x:a-(1===j()?250:210),y:m-(1===j()?95:45)}),t(ye,{name:"cache-bounds-t",x:10,y:10})]}),D()&&t(b,{text:"Powered by polotno.com",fontSize:14,fill:"rgba(0,0,0,0.6)",x:a-170,y:m-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","_blank","noopener")},onTap:()=>{window.open("https://polotno.com","_blank","noopener")}}),t(c,{name:"line-guides"})]})}),Ye&&nt&&t(nt,{store:i,page:r,xPadding:xe,yPadding:ve,layout:P})]})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,e){var r={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]])}}return r};import{jsx as e,Fragment as r,jsxs as o}from"react/jsx-runtime";import n from"react";import{observer as i}from"mobx-react-lite";import{Group as a,Path as s,Rect as l,Shape as c}from"react-konva";import{nodeAutorun as h}from"../utils/mobx.js";import{isAlive as d}from"mobx-state-tree";import{Html as u}from"react-konva-utils";import{layout as f,drawLayout as g}from"render-tag";import{layoutTextOnPath as m,drawTextOnPathLayout as x}from"render-tag/path";import{activeAnchorOf as p,scaledFontSizeAttrs as y,roundedFontSizeAttrs as b,roundedTextDecorationAttrs as w,textMinResizeWidth as v}from"../utils/px.js";import{flags as E}from"../utils/flags.js";import{applyFilter as O}from"./apply-filters.js";import{getLineHeight as M,usePrevious as S}from"./text-element.js";import{useFontSpecsLoader as j}from"./text-element/font-specs-loader.js";import{getHtml as z,getCurvePath as k,getCurveTextHeight as R}from"@polotno/core/text-html";import{useColor as Y}from"./use-color.js";import{isGradient as X}from"@polotno/core/gradient";import{detectSize as F}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as I}from"@polotno/core/background-shape";import{useFadeIn as P}from"./use-fadein.js";import{incrementLoader as C}from"../utils/loader.js";import{removeTags as T}from"@polotno/core/text";import{isTouchDevice as B}from"../utils/screen.js";import{getLimitedFontSize as W}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as D,extractFontSpecsFromHtml as N,scaleRichTextFontSizesInHtml as $}from"../utils/rich-text-html.js";import{RichEditor as J}from"./rich-editor.js";import{findFitFontSize as _}from"./text-element/fit-font-size.js";import{visiblePlaceholder as A}from"./text-element/placeholder.js";import{wrapHtmlForRenderTag as L}from"@polotno/core/reset-style";import{xmlEscape as V}from"@polotno/core/xml";import{hasMeasuredHeight as H,resolveTextBoxHeight as q}from"@polotno/core/text-types";export{L as wrapHtmlForRenderTag};function G(t,e){return t!==e&&(!E.textVerticalResizeEnabled||t<e)}export const RenderTagElement=i(({element:i,store:K})=>{var Q;const U=n.useRef(null),Z=n.useRef(null),[tt,et]=n.useState(!1),rt=n.useRef(i.height),ot=i.isSelected,nt=S(ot),{textVerticalResizeEnabled:it}=E,at=E.autoDeleteEmptyText,st=S(i.fontFamily),lt=n.useMemo(()=>D(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),ct=n.useMemo(()=>N(lt,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[lt,i.fontFamily,i.fontWeight,i.fontStyle]),[ht]=j(K,ct,i.text||i.placeholder),dt=i._editModeEnabled;P(U);const ut=ht?i.fontFamily:st&&st!==i.fontFamily?st:"Arial",ft=Y(i).fill,gt=X(i.fill),mt=X(i.stroke)&&!!i.strokeWidth,xt=!!i.strokeWidth&&(mt||gt),pt="ellipsis"===E.textOverflow&&!i.curveEnabled&&H(i)&&!xt,yt=A(i.placeholder),bt=!!yt&&!T(i.text),wt=bt?V(yt):lt,vt=bt?.6:i.a.opacity,Et=z(i,{fontFamily:ut,color:ft,forEditor:!pt,textOverflow:E.textOverflow,text:wt,textIsNormalized:!0}),Ot=i.width||1,Mt=i.curveEnabled,St=function(t,e,r,o){return n.useMemo(()=>{if(o){return null}try{return f({html:L(t),width:Math.max(1,e),accuracy:"performance"})}catch(r){return console.error("render-tag layout failed:",r),null}},[t,e,r,o])}(Et,Ot,ht,Mt),jt=function(t,e,r){return n.useMemo(()=>{if(!e.curveEnabled){return null}const r=e.width||1,o=R(e),n=k(r,o,e.curvePower,e.fontSize);try{return m({html:L(t),path:n,align:"center",textBaseline:"middle"})}catch(i){return console.error("render-tag/path layoutTextOnPath failed:",i),null}},[r,e.curveEnabled,e.curvePower,e.fontSize,e.width,e.height,t])}(Et,i,ht),zt=M({fontLoaded:ht,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),kt=Mt?0:Math.max(null!==(Q=null==St?void 0:St.height)&&void 0!==Q?Q:0,i.fontSize*zt),Rt=jt?jt.bounds:null,Yt=n.useMemo(()=>St?St.lines.map(t=>({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height})):[],[St]),Xt=n.useRef([]),Ft=n.useRef(null),It=n.useRef(!0),[,Pt]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=Xt.current;t.length>0&&(Xt.current=[],t.forEach(t=>t()))});const Ct=n.useCallback((t,e,r,o)=>{const n=C(`text ${i.id}`),a=()=>{K.history.ignore(t,e,r).then(()=>{It.current?(Xt.current.push(n),Pt()):n()})};o?queueMicrotask(a):a()},[i.id,K]),Tt=n.useCallback(t=>{const e=null!==Ft.current;Ft.current=t,e||Ct(()=>{const t=Ft.current;Ft.current=null,d(i)&&G(i.height,t)&&i.set({height:t})},!1,!0)},[i,Ct]);n.useEffect(()=>{if(!ht){return}if(!St){return}if(!H(i)){return void Ct(()=>{d(i)&&(H(i)||i.set({height:kt}))},void 0,void 0,!0)}if(K.isPlaying){return}const{textOverflow:t}=E,e=G(i.height,kt),r=()=>Tt(kt);if("change-font-size"!==t||tt||dt||i.curveEnabled){"resize"===t&&e&&!tt&&r()}else{const t=_(bt?{toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:wt})}:i,{fontFamily:ut,color:ft,forEditor:!0},t=>{try{return f({html:L(t),width:Ot,accuracy:"performance"}).height}catch(Q){return F(t).height}});t.fontSize!==i.fontSize?Ct(()=>{if(!d(i)){return}const e=y(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&r()}}),n.useEffect(()=>()=>{It.current=!1;const t=Xt.current;t.length>0&&(Xt.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!ht||!i.curveEnabled||tt){return}if(!Rt||!Rt.width){return}const t=t=>t&&it?Math.max(t,Rt.height):Rt.height;Math.abs(Rt.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||Ct(()=>{if(!d(i)){return}const e=Rt.width-i.width,r=t(i.height),o=r-i.height;if(Math.abs(e)<1&&Math.abs(o)<1){return}const n=i.a.rotation*Math.PI/180,a=-e/2*Math.cos(n),s=-e/2*Math.sin(n);i.set({width:Rt.width,height:r,x:i.a.x+a,y:i.a.y+s})},!1,!0,!0)},[ht,i.curveEnabled,Rt,tt,it,Ct]),n.useEffect(()=>{nt&&!ot&&at&&""===T(i.text)&&i.removable&&!A(i.placeholder)&&K.deleteElements([i.id])},[at,i.placeholder,i.removable,i.text,ot,nt]),n.useEffect(()=>h(i,()=>{const t=U.current;t&&O(t,i)}),[St,jt,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);const Bt=q(i,kt),Wt=Mt||!ht||tt||K.isPlaying||"resize"!==E.textOverflow?i.a.height:it?Math.max(i.a.height,kt):kt;let Dt=0;Mt||"middle"!==i.verticalAlign?Mt||"bottom"!==i.verticalAlign||(Dt=Bt-kt):Dt=(Bt-kt)/2;const Nt=i.backgroundPadding*(i.fontSize*zt*.5),$t=i.backgroundCornerRadius*(i.fontSize*zt*.5),Jt=n.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===Yt.length?"":I({rects:Yt,padding:Nt,cornerRadius:$t}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,Yt,Nt,$t]),_t=B(),At=n.useRef(null),Lt=n.useRef(i.width),Vt=n.useRef(null),Ht=n.useRef(null),qt=n.useRef(""),Gt=n.useRef(0),Kt=n.useRef(0),Qt=i.width>0?i.a.width/i.width:1;return o(r,{children:[i.curveEnabled||i.legacyBackground?e(l,{x:i.a.x,y:i.a.y,offsetX:Nt/Qt,offsetY:Nt/Qt,rotation:i.a.rotation,scaleX:Qt,scaleY:Qt,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*vt,fill:i.backgroundColor,width:i.width+2*Nt,height:Bt+2*Nt,cornerRadius:$t}):e(s,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-Dt/Qt,rotation:i.a.rotation,scaleX:Qt,scaleY:Qt,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&Jt.length>0,opacity:i.backgroundOpacity*vt,fill:i.backgroundColor,data:Jt}),e(c,{ref:U,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:Qt,scaleY:Qt,offsetY:Qt>0?-Dt/Qt:0,width:i.width,height:Math.max(i.height,kt),listening:!1,visible:!dt&&!!(Mt?jt:St),editModeEnabled:dt,opacity:vt,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,hideInExport:!i.showInExport,sceneFunc:(t,e)=>{const r=t._context;if(r){try{if(Mt){if(!jt||!Rt){return}const t=(i.width-Rt.width)/2-Rt.x;r.save(),r.translate(t,-Rt.y),x({layout:jt,ctx:r}),r.restore()}else{if(!St){return}g({layout:St,width:Ot,ctx:r,pixelRatio:1})}}catch(o){console.error("render-tag draw failed:",o)}}}}),e(l,{ref:Z,name:"element",x:i.a.x,y:i.a.y,listening:i.selectable,rotation:i.a.rotation,width:i.a.width,height:Wt,visible:!dt,draggable:_t?i.draggable&&ot:i.draggable,preventDefault:!_t||ot,opacity:0,hideInExport:!0,id:i.id,onDragMove:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDblClick:t=>{i.contentEditable&&(Ht.current={x:t.evt.clientX,y:t.evt.clientY},i.toggleEditMode(!0))},onDblTap:t=>{var e;if(i.contentEditable){const r=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Ht.current=r?{x:r.clientX,y:r.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{et(!0),rt.current=i.height,Lt.current=i.width,Vt.current=null,At.current=t.target.position(),qt.current=p(t.target),Gt.current=i.a.rotation,Kt.current=i.height},onTransform:e=>{const r=e.target,o=qt.current,n="middle-left"===o||"middle-right"===o,a="top-center"===o||"bottom-center"===o,s=r.scaleX();if(n){const e=r.scaleX(),o=r.width()*e;let n=Math.max(o,v(Lt.current,i.fontSize));const a=i.toJSON();let s=0;if(i.curveEnabled){s=R(Object.assign(Object.assign({},a),{width:n}))}else{const{x:e,y:r,width:o,height:i}=a,l=t(a,["x","y","width","height"]),c=`${JSON.stringify(l)}|${ut}|${ht}|${ft}`;if(Vt.current&&Vt.current.signature===c&&n<=Vt.current.width){n=Vt.current.width,s=Vt.current.height}else{const t=t=>{const e=z(Object.assign(Object.assign({},a),{width:t}),{fontFamily:ut,color:ft,forEditor:!0,text:wt,textIsNormalized:!0});try{return f({html:L(e),width:t,accuracy:"performance"})}catch(Q){return{height:F(e).height,lines:[]}}};let e=t(n);const r=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width));r>n+.5&&r<=Lt.current+.5&&(n=Math.min(Math.ceil(r),Lt.current),e=t(n),Vt.current={signature:c,width:n,height:e.height}),s=e.height}}n>o&&At.current&&r.position(At.current),r.width(n),r.scaleX(1),r.scaleY(1);let l=E.textVerticalResizeEnabled?Math.max(s,rt.current):s;"ellipsis"===E.textOverflow&&(l=rt.current),r.height(l),i.set({width:r.width(),height:l,x:r.x(),y:r.y()})}else if(a){const t="resize"===E.textOverflow?Mt?(null==Rt?void 0:Rt.height)||i.fontSize:kt:zt*i.fontSize,e=r.height()*r.scaleY();if(e<t){if(r.height(t),At.current){if("top-center"===qt.current){const e=Gt.current*Math.PI/180,o=Kt.current-t;r.x(At.current.x-o*Math.sin(e)),r.y(At.current.y+o*Math.cos(e))}else{r.position(At.current)}}}else{r.height(e)}r.scaleY(1),r.scaleX(1),Kt.current=Math.max(t,e),i.set({x:r.x(),y:r.y(),height:r.height(),rotation:r.rotation()})}else{r.scaleX(1),r.scaleY(1),i.set({fontSize:i.fontSize*s,letterSpacing:i.letterSpacing,width:r.width()*s,x:r.x(),y:r.y(),rotation:r.rotation(),height:r.height()*s,shadowBlur:i.shadowBlur*s,shadowOffsetX:i.shadowOffsetX*s,shadowOffsetY:i.shadowOffsetY*s,strokeWidth:i.strokeWidth*s,text:$(i.text,s)})}At.current=e.target.position()},onTransformEnd:t=>{et(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},b(i,i.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:$(i.text,e)}))}}),dt&&e(a,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-Dt,children:e(u,{divProps:{style:{zIndex:20}},children:e(J,{element:i,onChange:t=>{const e=W({oldText:T(i.text),newText:T(t),element:i});i.set(Object.assign({text:t},y(i,e)))},onBlur:()=>{d(i)&&(i.set(w(i)),i.toggleEditMode(!1))},clickCoords:Ht.current})})})]})});
|
|
1
|
+
var t=this&&this.__rest||function(t,e){var r={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]])}}return r};import{jsx as e,Fragment as r,jsxs as o}from"react/jsx-runtime";import n from"react";import{observer as i}from"mobx-react-lite";import{Group as a,Path as l,Rect as s,Shape as c}from"react-konva";import{nodeAutorun as h}from"../utils/mobx.js";import{isAlive as d}from"mobx-state-tree";import{Html as u}from"react-konva-utils";import{layout as f,drawLayout as g}from"render-tag";import{layoutTextOnPath as m,drawTextOnPathLayout as x}from"render-tag/path";import{activeAnchorOf as p,scaledFontSizeAttrs as y,roundedFontSizeAttrs as b,roundedTextDecorationAttrs as w,roundedGeometryPx as v,roundedPosition as E,textMinResizeWidth as O}from"../utils/px.js";import{flags as S}from"../utils/flags.js";import{applyFilter as M}from"./apply-filters.js";import{getLineHeight as z,usePrevious as j}from"./text-element.js";import{useFontSpecsLoader as k}from"./text-element/font-specs-loader.js";import{getHtml as R,getCurvePath as Y,getCurveTextHeight as X,letterSpacingOverhang as F}from"@polotno/core/text-html";import{useColor as I}from"./use-color.js";import{isGradient as P}from"@polotno/core/gradient";import{detectSize as C}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as T,trimTrailingLetterSpace as B}from"@polotno/core/background-shape";import{useFadeIn as W}from"./use-fadein.js";import{incrementLoader as D}from"../utils/loader.js";import{removeTags as N}from"@polotno/core/text";import{isTouchDevice as $}from"../utils/screen.js";import{getLimitedFontSize as J}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as _,extractFontSpecsFromHtml as A,scaleRichTextFontSizesInHtml as L}from"../utils/rich-text-html.js";import{RichEditor as V}from"./rich-editor.js";import{findFitFontSize as H}from"./text-element/fit-font-size.js";import{visiblePlaceholder as q}from"./text-element/placeholder.js";import{wrapHtmlForRenderTag as G}from"@polotno/core/reset-style";import{xmlEscape as K}from"@polotno/core/xml";import{hasMeasuredHeight as Q,resolveTextBoxHeight as U}from"@polotno/core/text-types";export{G as wrapHtmlForRenderTag};function Z(t,e){return t!==e&&(!S.textVerticalResizeEnabled||t<e)}export const RenderTagElement=i(({element:i,store:tt})=>{var et;const rt=n.useRef(null),ot=n.useRef(null),[nt,it]=n.useState(!1),at=n.useRef(i.height),lt=i.isSelected,st=j(lt),{textVerticalResizeEnabled:ct}=S,ht=S.autoDeleteEmptyText,dt=j(i.fontFamily),ut=n.useMemo(()=>_(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),ft=n.useMemo(()=>A(ut,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[ut,i.fontFamily,i.fontWeight,i.fontStyle]),[gt]=k(tt,ft,i.text||i.placeholder),mt=i._editModeEnabled;W(rt);const xt=gt?i.fontFamily:dt&&dt!==i.fontFamily?dt:"Arial",pt=I(i).fill,yt=P(i.fill),bt=P(i.stroke)&&!!i.strokeWidth,wt=!!i.strokeWidth&&(bt||yt),vt="ellipsis"===S.textOverflow&&!i.curveEnabled&&Q(i)&&!wt,Et=q(i.placeholder),Ot=!!Et&&!N(i.text),St=Ot?K(Et):ut,Mt=Ot?.6:i.a.opacity,zt=R(i,{fontFamily:xt,color:pt,forEditor:!vt,textOverflow:S.textOverflow,text:St,textIsNormalized:!0}),jt=i.width||1,kt=F(i.letterSpacing,i.fontSize),Rt=i.curveEnabled,Yt=function(t,e,r,o){return n.useMemo(()=>{if(o){return null}try{return f({html:G(t),width:Math.max(1,e),accuracy:"performance"})}catch(r){return console.error("render-tag layout failed:",r),null}},[t,e,r,o])}(zt,jt,gt,Rt),Xt=function(t,e,r){return n.useMemo(()=>{if(!e.curveEnabled){return null}const r=e.width||1,o=X(e),n=Y(r,o,e.curvePower,e.fontSize);try{return m({html:G(t),path:n,align:"center",textBaseline:"middle"})}catch(i){return console.error("render-tag/path layoutTextOnPath failed:",i),null}},[r,e.curveEnabled,e.curvePower,e.fontSize,e.width,e.height,t])}(zt,i,gt),Ft=z({fontLoaded:gt,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),It=Rt?0:Math.max(null!==(et=null==Yt?void 0:Yt.height)&&void 0!==et?et:0,i.fontSize*Ft),Pt=Xt?Xt.bounds:null,Ct=n.useMemo(()=>Yt?Yt.lines.map(t=>B({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height},kt)):[],[Yt,kt]),Tt=n.useRef([]),Bt=n.useRef(null),Wt=n.useRef(!0),[,Dt]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=Tt.current;t.length>0&&(Tt.current=[],t.forEach(t=>t()))});const Nt=n.useCallback((t,e,r,o)=>{const n=D(`text ${i.id}`),a=()=>{tt.history.ignore(t,e,r).then(()=>{Wt.current?(Tt.current.push(n),Dt()):n()})};o?queueMicrotask(a):a()},[i.id,tt]),$t=n.useCallback(t=>{const e=null!==Bt.current;Bt.current=t,e||Nt(()=>{const t=Bt.current;Bt.current=null,d(i)&&Z(i.height,t)&&i.set({height:t})},!1,!0)},[i,Nt]);n.useEffect(()=>{if(!gt){return}if(!Yt){return}if(!Q(i)){return void Nt(()=>{d(i)&&(Q(i)||i.set({height:It}))},void 0,void 0,!0)}if(tt.isPlaying){return}const{textOverflow:t}=S,e=Z(i.height,It),r=()=>$t(It);if("change-font-size"!==t||nt||mt||i.curveEnabled){"resize"===t&&e&&!nt&&r()}else{const t=H(Ot?{toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:St})}:i,{fontFamily:xt,color:pt,forEditor:!0},t=>{try{return f({html:G(t),width:jt,accuracy:"performance"}).height}catch(et){return C(t).height}});t.fontSize!==i.fontSize?Nt(()=>{if(!d(i)){return}const e=y(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&r()}}),n.useEffect(()=>()=>{Wt.current=!1;const t=Tt.current;t.length>0&&(Tt.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!gt||!i.curveEnabled||nt){return}if(!Pt||!Pt.width){return}const t=t=>t&&ct?Math.max(t,Pt.height):Pt.height;Math.abs(Pt.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||Nt(()=>{if(!d(i)){return}const e=Pt.width-i.width,r=t(i.height),o=r-i.height;if(Math.abs(e)<1&&Math.abs(o)<1){return}const n=i.a.rotation*Math.PI/180,a=-e/2*Math.cos(n),l=-e/2*Math.sin(n);i.set({width:Pt.width,height:r,x:i.a.x+a,y:i.a.y+l})},!1,!0,!0)},[gt,i.curveEnabled,Pt,nt,ct,Nt]),n.useEffect(()=>{st&&!lt&&ht&&""===N(i.text)&&i.removable&&!q(i.placeholder)&&tt.deleteElements([i.id])},[ht,i.placeholder,i.removable,i.text,lt,st]),n.useEffect(()=>h(i,()=>{const t=rt.current;t&&M(t,i)}),[Yt,Xt,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);const Jt=U(i,It),_t=Rt||!gt||nt||tt.isPlaying||"resize"!==S.textOverflow?i.a.height:ct?Math.max(i.a.height,It):It;let At=0;Rt||"middle"!==i.verticalAlign?Rt||"bottom"!==i.verticalAlign||(At=Jt-It):At=(Jt-It)/2;const Lt=i.backgroundPadding*(i.fontSize*Ft*.5),Vt=i.backgroundCornerRadius*(i.fontSize*Ft*.5),Ht=n.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===Ct.length?"":T({rects:Ct,padding:Lt,cornerRadius:Vt}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,Ct,Lt,Vt]),qt=$(),Gt=n.useRef(null),Kt=n.useRef(i.width),Qt=n.useRef(null),Ut=n.useRef(null),Zt=n.useRef(""),te=n.useRef(0),ee=n.useRef(0),re=i.width>0?i.a.width/i.width:1;return o(r,{children:[i.curveEnabled||i.legacyBackground?e(s,{x:i.a.x,y:i.a.y,offsetX:Lt/re,offsetY:Lt/re,rotation:i.a.rotation,scaleX:re,scaleY:re,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*Mt,fill:i.backgroundColor,width:i.width+2*Lt,height:Jt+2*Lt,cornerRadius:Vt}):e(l,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-At/re,rotation:i.a.rotation,scaleX:re,scaleY:re,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&Ht.length>0,opacity:i.backgroundOpacity*Mt,fill:i.backgroundColor,data:Ht}),e(c,{ref:rt,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:re,scaleY:re,offsetY:re>0?-At/re:0,width:i.width,height:Math.max(i.height,It),listening:!1,visible:!mt&&!!(Rt?Xt:Yt),editModeEnabled:mt,opacity:Mt,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,hideInExport:!i.showInExport,sceneFunc:(t,e)=>{const r=t._context;if(r){try{if(Rt){if(!Xt||!Pt){return}const t=(i.width-Pt.width)/2-Pt.x;r.save(),r.translate(t,-Pt.y),x({layout:Xt,ctx:r}),r.restore()}else{if(!Yt){return}g({layout:Yt,width:jt,ctx:r,pixelRatio:1})}}catch(o){console.error("render-tag draw failed:",o)}}}}),e(s,{ref:ot,name:"element",x:i.a.x,y:i.a.y,listening:i.selectable,rotation:i.a.rotation,width:i.a.width,height:_t,visible:!mt,draggable:qt?i.draggable&<:i.draggable,preventDefault:!qt||lt,opacity:0,hideInExport:!0,id:i.id,onDragMove:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{i.set(E(t.target))},onDblClick:t=>{i.contentEditable&&(Ut.current={x:t.evt.clientX,y:t.evt.clientY},i.toggleEditMode(!0))},onDblTap:t=>{var e;if(i.contentEditable){const r=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Ut.current=r?{x:r.clientX,y:r.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{it(!0),at.current=i.height,Kt.current=i.width,Qt.current=null,Gt.current=t.target.position(),Zt.current=p(t.target),te.current=i.a.rotation,ee.current=i.height},onTransform:e=>{const r=e.target,o=Zt.current,n="middle-left"===o||"middle-right"===o,a="top-center"===o||"bottom-center"===o,l=r.scaleX();if(n){const e=r.scaleX(),o=r.width()*e;let n=Math.max(o,O(Kt.current,i.fontSize));const a=i.toJSON();let l=0;if(i.curveEnabled){l=X(Object.assign(Object.assign({},a),{width:n}))}else{const{x:e,y:r,width:o,height:i}=a,s=t(a,["x","y","width","height"]),c=`${JSON.stringify(s)}|${xt}|${gt}|${pt}`;if(Qt.current&&Qt.current.signature===c&&n<=Qt.current.width){n=Qt.current.width,l=Qt.current.height}else{const t=t=>{const e=R(Object.assign(Object.assign({},a),{width:t}),{fontFamily:xt,color:pt,forEditor:!0,text:St,textIsNormalized:!0});try{return f({html:G(e),width:t,accuracy:"performance"})}catch(et){return{height:C(e).height,lines:[]}}};let e=t(n);const r=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width-kt));r>n+.5&&r<=Kt.current+.5&&(n=Math.min(Math.ceil(r),Kt.current),e=t(n),Qt.current={signature:c,width:n,height:e.height}),l=e.height}}n>o&&Gt.current&&r.position(Gt.current),r.width(n),r.scaleX(1),r.scaleY(1);let s=S.textVerticalResizeEnabled?Math.max(l,at.current):l;"ellipsis"===S.textOverflow&&(s=at.current),r.height(s),i.set({width:r.width(),height:s,x:r.x(),y:r.y()})}else if(a){const t="resize"===S.textOverflow?Rt?(null==Pt?void 0:Pt.height)||i.fontSize:It:Ft*i.fontSize,e=r.height()*r.scaleY();if(e<t){if(r.height(t),Gt.current){if("top-center"===Zt.current){const e=te.current*Math.PI/180,o=ee.current-t;r.x(Gt.current.x-o*Math.sin(e)),r.y(Gt.current.y+o*Math.cos(e))}else{r.position(Gt.current)}}}else{r.height(e)}r.scaleY(1),r.scaleX(1),ee.current=Math.max(t,e),i.set({x:r.x(),y:r.y(),height:r.height(),rotation:r.rotation()})}else{r.scaleX(1),r.scaleY(1),i.set({fontSize:i.fontSize*l,letterSpacing:i.letterSpacing,width:r.width()*l,x:r.x(),y:r.y(),rotation:r.rotation(),height:r.height()*l,shadowBlur:i.shadowBlur*l,shadowOffsetX:i.shadowOffsetX*l,shadowOffsetY:i.shadowOffsetY*l,strokeWidth:i.strokeWidth*l,text:L(i.text,l)})}Gt.current=e.target.position()},onTransformEnd:t=>{it(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},b(i,i.fontSize*e)),{width:v(t.target.width()*e),x:v(t.target.x()),y:v(t.target.y()),rotation:v(t.target.rotation()),text:L(i.text,e)}))}}),mt&&e(a,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-At,children:e(u,{divProps:{style:{zIndex:20}},children:e(V,{element:i,onChange:t=>{const e=J({oldText:N(i.text),newText:N(t),element:i});i.set(Object.assign({text:t},y(i,e)))},onBlur:()=>{d(i)&&(i.set(w(i)),i.toggleEditMode(!1))},clickCoords:Ut.current})})})]})});
|
package/canvas/rich-editor.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++){t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(o[n[r]]=e[n[r]])}}return o};import{jsx as t}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{getQuillEditorHtml as a,getDir as s}from"@polotno/core/text-html";import{quillHtmlToModelText as
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++){t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(o[n[r]]=e[n[r]])}}return o};import{jsx as t}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{getQuillEditorHtml as a,getDir as s,textLayoutWidth as d}from"@polotno/core/text-html";import{quillHtmlToModelText as c,isQuillFormatMixed as u,isBoldWeight as f}from"../utils/rich-text-html.js";import{resetStyleContent as p,wrapHtmlForRenderTag as m}from"@polotno/core/reset-style";import{layout as h,lineBaselineOffset as g}from"render-tag";import{removeTags as b}from"@polotno/core/text";import{cssFontFamily as v}from"@polotno/core/fonts";import{isGradient as x,firstStopColor as y}from"@polotno/core/gradient";import{getOptimalCaretColor as w}from"./text-element/caret-color.js";import{visiblePlaceholder as S}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as k}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as q,setActiveTextEditor as T,updateActiveTextFormat as E,clearActiveTextEditor as C,getActiveTextEditor as L}from"../utils/text-format-state.js";import F from"../utils/styled.js";import{applyOpacityToColor as R}from"@polotno/core/svg";export{R as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const $=q;export function syncQuillFormatState(e,t){const o=t?e.getFormat(t):{},n=function(e,t){const o={};if(!t||t.length<=0){return o}const n=e.getContents(t.index,t.length);for(const r of $){u(n,r)&&(o[r]=!0)}return o}(e,t);r.runInAction(()=>{quillRef.currentFormat=o}),E(o,n,t)}const O="polotno-saved-selection";function M(){const e=window.getSelection();if(!e||0===e.rangeCount||e.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const t=e.getRangeAt(0).cloneRange();CSS.highlights.set(O,new Highlight(t)),N()}function j(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(O)}function N(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(O)&&(document.querySelector(".polotno-portal")||H(document.activeElement)?N():j())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const _=document.createElement("style");_.setAttribute("data-polotno-highlight",""),_.textContent=`::highlight(${O}) { background-color: Highlight; }`,document.head.appendChild(_)}let z=null;function P(e,t){"text"===e.type&&t.push(e);for(const o of e.children||[]){P(o,t)}}export function computeMarkerVars(e){var t,o,n;const r=e.fontSize;if(!r||r<=0){return null}const i=v(e.fontFamily),l=f(e.fontWeight)?700:400,a="italic"===e.fontStyle?"italic":"normal",s=null!=z?z:z=document.createElement("canvas").getContext("2d");s.fontKerning="normal",s.font=`${r}px ${i}`;const d=s.measureText("M"),c=(null!==(t=d.fontBoundingBoxAscent)&&void 0!==t?t:0)/r,u=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,p=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${a};line-height:${e.lineHeight};letter-spacing:${e.letterSpacing}em`,b=m(`<div style="${p}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let x;try{x=h({html:b,width:Math.max(12*r,600)})}catch(T){return null}const y=[];P(x.layoutRoot,y);const w=y.find(e=>"•"===e.text),S=y.find(e=>/^\d/.test(e.text));if(!w){return null}const k=w.style.fontSize,q=2.1*r;return{bulletLeft:w.x,bulletTop:w.y-g(k,k*c,k*u),bulletFontSize:k,numberGap:S?Math.max(0,q-S.x-(null!==(n=S.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=F("div",o.forwardRef)`
|
|
2
2
|
.ql-editor {
|
|
3
3
|
outline: none;
|
|
4
4
|
/* anchor for the absolutely-positioned ::before placeholder below */
|
|
@@ -25,7 +25,7 @@ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype
|
|
|
25
25
|
pointer-events: none;
|
|
26
26
|
opacity: 0;
|
|
27
27
|
}
|
|
28
|
-
${
|
|
28
|
+
${p}
|
|
29
29
|
|
|
30
30
|
/* ===== Editor-only list markers (Quill flat-DOM hack) ======================
|
|
31
31
|
Quill emits a FLAT <ol> with per-item data-list + ql-indent classes (not
|
|
@@ -155,4 +155,4 @@ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype
|
|
|
155
155
|
&[style*='--polotno-gradient'] .ql-editor [style*='color:'] {
|
|
156
156
|
-webkit-text-fill-color: currentColor;
|
|
157
157
|
}
|
|
158
|
-
`;let
|
|
158
|
+
`;let Q=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=e=>{Q=e};let A=!1;function I(){A||(A=!0,console.warn("[polotno] The Quill 'bold' format is deprecated. Use the numeric 'font-weight' format instead, e.g. quill.format('font-weight', '700') or applyTextFormat({ fontWeight: 700 })."))}function D(e){return e?"700":"400"}export const createQuill=(t,o)=>{k();const r=new n(t,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:Q});!function(t){const o=t.format.bind(t),n=t.formatText.bind(t),r=t.getFormat.bind(t);t.format=(e,t,n)=>"bold"===e?(I(),o("font-weight",D(t),n)):o(e,t,n),t.formatText=(t,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){I();const{bold:l}=r,a=e(r,["bold"]);return n(t,o,Object.assign(Object.assign({},a),{"font-weight":D(l)}),i)}return n(t,o,r,i)}return"bold"===r?(I(),n(t,o,"font-weight",D(i),l)):n(t,o,r,i,l)},t.getFormat=(...e)=>{const t=r(...e);return t&&null!=t["font-weight"]&&!("bold"in t)&&(t.bold=f(t["font-weight"])),t}}(r);const i=n.import("delta"),l=(e,t)=>t.compose((new i).retain(t.length(),{"font-weight":"700"}));return r.clipboard.addMatcher("STRONG",l),r.clipboard.addMatcher("B",l),r};export const setQuillContent=(e,t)=>{var o=e.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+t.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(e=>{"string"==typeof e.insert&&e.insert.includes("")&&(e.insert=e.insert.split("").join("\t"))}),e.setContents(o),e.history.clear()};export const RichEditor=({onBlur:e,onChange:n,element:u,clickCoords:f})=>{var p;const m=o.useRef(null),h=o.useRef(!1);o.useLayoutEffect(()=>{let t,o=!1,i=null,s=null,d=null,p=null,g=null;const b=()=>{if(!o&&m.current){try{t=createQuill(m.current,{placeholder:S(u.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,T({instance:t,store:u.store,element:u});const o=e=>{e&&syncQuillFormatState(t,e)};t.on("text-change",()=>{const e=L(),r=e&&e.instance===t?e.lastSelection:null;o(t.getSelection()||r),setTimeout(()=>{var e,o;const r=t.root;if(!r||!r.isConnected){return}if(!l(u)){return}const i=r.innerHTML;h.current=!0,n(c(i,{fontSize:u.fontSize,fontFamily:u.fontFamily}));const a=t.getContents(),s=u.fill;let d=null,f=!0;for(const t of a.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(e=t.attributes)||void 0===e?void 0:e.gradient){f=!1;break}const n=(null===(o=t.attributes)||void 0===o?void 0:o.color)||s;if(null===d){d=n}else if(n!==d){f=!1;break}}f&&d&&u.set({fill:d})},10)}),t.on("selection-change",o);const b=a(u,u.fontFamily);setQuillContent(t,b),h.current=!0;const v=m.current.closest(".polotno-workspace-inner"),x=null==v?void 0:v.scrollLeft,y=null==v?void 0:v.scrollTop;f?setCursorFromCoords(t,f):t.setSelection(0,0,"api"),v&&void 0!==x&&void 0!==y&&(v.scrollLeft=x,v.scrollTop=y);const w=t.root;p=t=>{const o=t.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(H(o)||quillRef.pendingToolbarInteraction?M():setTimeout(()=>{quillRef.pendingToolbarInteraction||H(document.activeElement)?M():(j(),e())},0))},g=()=>{j()},w.addEventListener("blur",p),w.addEventListener("focus",g),i=w,s=e=>{var o,n;const r=t.getSelection();if(!r||0===r.length){return}const i=t.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let a="";if(l&&l.rangeCount>0){const e=l.getRangeAt(0);let t=e.cloneContents(),o=e.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=e.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let e=o;for(;e&&e!==w&&e.nodeType===Node.ELEMENT_NODE;){const o=e.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=e.cloneNode(!1);n.appendChild(t),t=n,e=e.parentNode}}const r=document.createElement("div");r.appendChild(t),a=r.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",i),a){const t='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; overflow-wrap: break-word;">'+a+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},d=e=>{s&&s(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},i.addEventListener("copy",s),i.addEventListener("cut",d)}catch(b){console.error("RichEditor init failed:",b)}}};return m.current?b():queueMicrotask(b),()=>{o=!0,i&&p&&i.removeEventListener("blur",p),i&&g&&i.removeEventListener("focus",g),j(),i&&s&&d&&(i.removeEventListener("copy",s),i.removeEventListener("cut",d)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),C(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(u,()=>`${u.text}\0${u.fontSize}\0${u.fontFamily}`,()=>{const e=quillRef.editor.instance;if(!e){return}if(h.current){return void(h.current=!1)}const t=e.getSelection();setQuillContent(e,a(u,u.fontFamily)),h.current=!0,t&&(e.setSelection(t.index,t.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(u,()=>`${u.fontFamily}\0${u.fontSize}\0${u.fontWeight}\0${u.fontStyle}\0${u.lineHeight}\0${u.letterSpacing}\0${s(b(u.text))}`,()=>{const e=m.current;if(!e){return}const t="ltr"===s(b(u.text)),o=computeMarkerVars(u);o&&e.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&t?(e.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),e.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),e.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),e.classList.add("rt-marker-geom")):e.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",e);const t=t=>{var o;const n=t.target;"number"==typeof(null==n?void 0:n.nodeType)&&(null===(o=m.current)||void 0===o?void 0:o.contains(n))||H(n)||quillRef.pendingToolbarInteraction||(j(),e())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",e),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const g={color:u.fill};u.fill.indexOf("gradient")>=0&&(g["--polotno-gradient"]=u.fill,g.color="transparent"),u.strokeWidth>0&&(g.WebkitTextStroke=`${u.strokeWidth}px ${y(u.stroke)}`,g.paintOrder="stroke fill");const k=x(u.fill)?y(u.fill):w(u),q=u.a.rotation*Math.PI/180,E=u.shadowOffsetX*Math.cos(q)+u.shadowOffsetY*Math.sin(q),F=-u.shadowOffsetX*Math.sin(q)+u.shadowOffsetY*Math.cos(q);return t(RichTextContainer,{ref:m,style:Object.assign(Object.assign({},g),{fontSize:u.fontSize,fontFamily:v(u.fontFamily),fontWeight:u.fontWeight,fontStyle:u.fontStyle,"--polotno-text-decoration":u.textDecoration||"none",textTransform:u.textTransform,width:d(u.a.width,u.letterSpacing,u.fontSize),lineHeight:u.lineHeight,letterSpacing:u.letterSpacing*u.fontSize+"px",textAlign:u.align,opacity:Math.max(u.a.opacity,.2),textShadow:u.shadowEnabled?`${E}px ${F}px ${u.shadowBlur}px ${R(u.shadowColor,null!==(p=u.shadowOpacity)&&void 0!==p?p:1)}`:void 0,caretColor:k}),dir:s(b(u.text))})};function H(e){const t=e;return!("function"!=typeof(null==t?void 0:t.closest)||!t.closest(".sketch-picker")&&!t.closest("[data-polotno-keep-focus]")&&!t.closest(".polotno-portal")&&!t.closest(".polotno-toolbar"))}export function setCursorFromCoords(e,t){if(!e||!t){return}const{x:o,y:r}=t;try{let t=null;if(document.caretRangeFromPoint){t=document.caretRangeFromPoint(o,r)}else if(document.caretPositionFromPoint){const e=document.caretPositionFromPoint(o,r);e&&(t=document.createRange(),t.setStart(e.offsetNode,e.offset))}if(t){const o=n.find(t.startContainer,!0);if(o){const n=o.offset(e.scroll)+t.startOffset;return void e.setSelection(n,0,"api")}}}catch(i){}e.setSelection(0,0,"api")}
|
package/canvas/table-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import i from"react";import{observer as n}from"mobx-react-lite";import{observable as r,runInAction as l}from"mobx";import{nodeAutorun as s}from"../utils/mobx.js";import{Group as a,Rect as h,Line as c,Circle as d}from"react-konva";import{Html as g}from"react-konva-utils";import{ROLES as u}from"../model/store.js";import{isTouchDevice as w}from"../utils/screen.js";import{
|
|
1
|
+
import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import i from"react";import{observer as n}from"mobx-react-lite";import{observable as r,runInAction as l}from"mobx";import{nodeAutorun as s}from"../utils/mobx.js";import{Group as a,Rect as h,Line as c,Circle as d}from"react-konva";import{Html as g}from"react-konva-utils";import{ROLES as u}from"../model/store.js";import{isTouchDevice as w}from"../utils/screen.js";import{roundedGeometryPx as p,roundedPosition as f}from"../utils/px.js";import{TextElement as x}from"./text-element.js";const y="#0d83dd",v=(t,e)=>{const o=t.target.getStage();o&&(o.container().style.cursor=e)},m=n(({axis:i,hovered:n,pillX:r,pillY:l,pillW:s,pillH:a,hitX:c,hitY:d,hitW:g,hitH:u,tint:w,hoverKind:p,idx:f,onSelect:x,onHoverChange:m})=>o(e,{children:[n&&t(h,{x:w.x,y:w.y,width:w.width,height:w.height,fill:"rgba(13, 131, 221, 0.08)",listening:!1}),t(h,{x:r,y:l,width:s,height:a,cornerRadius:Math.min(s,a)/2,fill:n?y:"#9ca3af",opacity:n?.55:.18,listening:!1}),t(h,{x:c,y:d,width:g,height:u,fill:"transparent",onMouseEnter:t=>{m({kind:p,idx:f}),v(t,"pointer")},onMouseLeave:t=>{m(null),v(t,"")},onClick:x})]})),b=n(({x:i,y:n,hovered:r,hoverKind:l,idx:s,isTouch:g,sizes:u,onInsert:w,onHoverChange:p})=>{const{hit:f,r:x,halo:m,stroke:b}=u,C=r||g;return o(a,{x:i,y:n,onMouseEnter:t=>{p({kind:l,idx:s}),v(t,"pointer")},onMouseLeave:t=>{p(null),v(t,"")},onClick:t=>{t.cancelBubble=!0,w()},children:[t(h,{x:-f/2,y:-f/2,width:f,height:f,fill:"transparent"}),C&&o(e,{children:[t(d,{radius:x+m,fill:"white",listening:!1}),t(d,{radius:x,fill:y,listening:!1}),t(c,{points:[.55*-x,0,.55*x,0],stroke:"white",strokeWidth:b,lineCap:"round",listening:!1}),t(c,{points:[0,.55*-x,0,.55*x],stroke:"white",strokeWidth:b,lineCap:"round",listening:!1})]})]})}),C=n(({element:o,store:i,inv:n,isTouch:r,hover:l,setHover:s})=>{const a=16*n,h=2*n,c=10*n,d={hit:22*n,r:7*n,halo:2*n,stroke:2*n},g=(t,e)=>null!==l&&l.kind===t&&l.idx===e,u=(t,e)=>i=>{i.cancelBubble=!0;const n=o._anchorCellId?o.cells.find(t=>t.id===o._anchorCellId):void 0;i.evt.shiftKey&&n?"col"===t?o.selectColumnRange(n.col,e):o.selectRowRange(n.row,e):"col"===t?o.selectColumn(e):o.selectRow(e)},w=[0],p=[0];for(let t=0;t<o.cols;t++){w.push(w[t]+o.colWidths[t]*o.a.width)}for(let t=0;t<o.rows;t++){p.push(p[t]+o.rowHeights[t]*o.a.height)}const f=[];for(let e=0;e<o.cols;e++){const i=Math.max(0,w[e+1]-w[e]-6);i<=0||f.push(t(m,{axis:"col",hovered:g("colSelect",e),pillX:w[e]+3,pillY:-h-c,pillW:i,pillH:h,hitX:w[e]+1,hitY:-a-c+h,hitW:i+4,hitH:a,tint:{x:w[e],y:0,width:w[e+1]-w[e],height:o.a.height},hoverKind:"colSelect",idx:e,onSelect:u("col",e),onHoverChange:s},`col-pill-${e}`))}for(let e=0;e<=o.cols;e++){f.push(t(b,{x:w[e],y:-c-h/2,hovered:g("colInsert",e),hoverKind:"colInsert",idx:e,isTouch:r,sizes:d,onInsert:()=>i.history.transaction(()=>o.addColumn(e)),onHoverChange:s},`col-insert-${e}`))}for(let e=0;e<o.rows;e++){const i=Math.max(0,p[e+1]-p[e]-6);i<=0||f.push(t(m,{axis:"row",hovered:g("rowSelect",e),pillX:-h-c,pillY:p[e]+3,pillW:h,pillH:i,hitX:-a-c+h,hitY:p[e]+1,hitW:a,hitH:i+4,tint:{x:0,y:p[e],width:o.a.width,height:p[e+1]-p[e]},hoverKind:"rowSelect",idx:e,onSelect:u("row",e),onHoverChange:s},`row-pill-${e}`))}for(let e=0;e<=o.rows;e++){f.push(t(b,{x:-c-h/2,y:p[e],hovered:g("rowInsert",e),hoverKind:"rowInsert",idx:e,isTouch:r,sizes:d,onInsert:()=>i.history.transaction(()=>o.addRow(e)),onHoverChange:s},`row-insert-${e}`))}return t(e,{children:f})});export const TableElement=n(({element:n,store:d})=>{const y=i.useRef(null),v=i.useRef(null),m=n.selectable||d.role===u.ADMIN,b=w(),k=n.isSelected,S=n._focusedCellIds.length>0,E=n.editingCell,I=1/Math.max(.01,d.scale),[H,M]=i.useState(null);i.useEffect(()=>{k||(n.clearCellFocus(),M(null))},[k]);const R=null==E?void 0:E._editModeEnabled;i.useEffect(()=>{n._editingCellId&&E&&!E._editModeEnabled&&n.exitCellEdit()},[R]),i.useEffect(()=>{S&&!n._editingCellId&&setTimeout(()=>{var t;return null===(t=v.current)||void 0===t?void 0:t.focus()},0)},[S,n._editingCellId]);const W=i.useMemo(()=>r.box(!1),[]);i.useEffect(()=>s(n,()=>{W.get()||n._fitRowsToContent&&d.history.ignore(()=>{n._applyFitRowsToContent()})}),[n,d,W]);const T=t=>{const e=t.target.getStage();if(!e){return}const o=e.getPointerPosition();if(!o){return}const i=y.current;if(!i){return}const r=i.getAbsoluteTransform().copy().invert().point(o);for(const l of n.visibleCells){const t=n.getCellRect(l.row,l.col,l.rowSpan,l.colSpan);if(r.x>=t.x&&r.x<=t.x+t.width&&r.y>=t.y&&r.y<=t.y+t.height){return l}}},B=(t,e)=>"dashed"===t?[4*e,2*e]:"dotted"===t?[e,e]:void 0,$=[];for(const e of n.visibleCells){const o=n.getCellRect(e.row,e.col,e.rowSpan,e.colSpan),i=0===e.row,r=e.row+e.rowSpan===n.rows,l=0===e.col,s=e.col+e.colSpan===n.cols;if(0===e.row){const i=e.getEffectiveBorder("top");if("none"!==i.style&&i.width>0){const n=o.y+i.width/2,r=o.x-(l?0:i.width/2),a=o.x+o.width+(s?0:i.width/2);$.push(t(c,{points:[r,n,a,n],stroke:i.color,strokeWidth:i.width,dash:B(i.style,i.width),listening:!1},`bt-${e.id}`))}}if(0===e.col){const n=e.getEffectiveBorder("left");if("none"!==n.style&&n.width>0){const l=o.x+n.width/2,s=o.y-(i?0:n.width/2),a=o.y+o.height+(r?0:n.width/2);$.push(t(c,{points:[l,s,l,a],stroke:n.color,strokeWidth:n.width,dash:B(n.style,n.width),listening:!1},`bl-${e.id}`))}}{const i=e.getEffectiveBorder("bottom");if("none"!==i.style&&i.width>0){const n=r?o.y+o.height-i.width/2:o.y+o.height,a=o.x-(l?0:i.width/2),h=o.x+o.width+(s?0:i.width/2);$.push(t(c,{points:[a,n,h,n],stroke:i.color,strokeWidth:i.width,dash:B(i.style,i.width),listening:!1},`bb-${e.id}`))}}{const n=e.getEffectiveBorder("right");if("none"!==n.style&&n.width>0){const l=s?o.x+o.width-n.width/2:o.x+o.width,a=o.y-(i?0:n.width/2),h=o.y+o.height+(r?0:n.width/2);$.push(t(c,{points:[l,a,l,h],stroke:n.color,strokeWidth:n.width,dash:B(n.style,n.width),listening:!1},`br-${e.id}`))}}}return o(e,{children:[t(h,{id:n.id,name:"element",x:n.a.x,y:n.a.y,rotation:n.a.rotation,width:n.a.width,height:n.a.height,fill:"transparent",opacity:n.a.opacity,hideInExport:!n.showInExport,listening:m,draggable:b?n.draggable&&k:n.draggable,onClick:t=>{if(!k){return}if(n.locked||!n.contentEditable){return}const e=T(t);e&&(t.evt.shiftKey&&S?(t.cancelBubble=!0,n.focusCellRange(e.row,e.col)):n.focusCell(e.id))},onDblClick:t=>{if(!k){return}if(n.locked||!n.contentEditable){return}const e=T(t);e&&n.enterCellEdit(e.id)},onDragMove:t=>{var e;const o=t.target;n.set({x:o.x(),y:o.y()}),null===(e=y.current)||void 0===e||e.position({x:o.x(),y:o.y()})},onDragEnd:t=>{n.set(f(t.target))},onTransformStart:()=>{l(()=>W.set(!0))},onTransformEnd:()=>{n.set({x:p(n.x),y:p(n.y),width:p(n.width),rotation:p(n.rotation)}),n._resetBaseRowHeights(),l(()=>W.set(!1))},onTransform:t=>{var e,o;const i=t.target,r=i.scaleX(),l=i.scaleY();i.scaleX(1),i.scaleY(1);const s=n.width*r,a=n.height*l;i.width(s),i.height(a);const h=i.x(),c=i.y(),d=i.rotation();null===(e=y.current)||void 0===e||e.position({x:h,y:c}),null===(o=y.current)||void 0===o||o.rotation(d),n.set({width:s,x:h,y:c,rotation:d}),n.setHeightRedistribute(a)}}),o(a,{ref:y,x:n.a.x,y:n.a.y,rotation:n.a.rotation,opacity:n.a.opacity,hideInExport:!n.showInExport,scaleX:n.a.width/n.width,scaleY:n.a.height/n.height,children:[n.visibleCells.map(e=>{const o=n.getCellRect(e.row,e.col,e.rowSpan,e.colSpan);return"transparent"===e.cellBackground?null:t(h,{x:o.x,y:o.y,width:o.width,height:o.height,fill:e.cellBackground,listening:!1},`bg-${e.id}`)}),$,n.visibleCells.map(e=>t(x,{element:e,store:d},`text-${e.id}`)),k&&n._focusedCellIds.map(e=>{const o=n.cells.find(t=>t.id===e);if(!o){return null}const i=n.getCellRect(o.row,o.col,o.rowSpan,o.colSpan),r=2*I;return t(h,{x:i.x,y:i.y,width:i.width,height:i.height,fill:"rgba(13, 131, 221, 0.1)",stroke:"#0d83dd",strokeWidth:r,listening:!1},`focus-${e}`)}),S&&!E&&t(g,{children:t("div",{ref:v,tabIndex:-1,style:{position:"absolute",opacity:0,width:"1px",height:"1px",pointerEvents:"none",outline:"none"}})}),k&&!E&&!d.isPlaying&&(()=>{const e=[];let o=0;for(let i=0;i<n.cols-1;i++){o+=n.colWidths[i]*n.a.width;const r=o,l=i;e.push(t(c,{x:r,points:[0,0,0,n.a.height],stroke:"transparent",strokeWidth:1,hitStrokeWidth:16,draggable:!0,onMouseEnter:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor="col-resize"),M({kind:"colInsert",idx:l+1})},onMouseLeave:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor=""),M(null)},onDragStart:t=>{t.cancelBubble=!0,d.history.startTransaction()},onDragMove:t=>{t.cancelBubble=!0;const e=t.target,o=(e.x()-r)/n.width;e.x(r),n.resizeColumn(l,o)},onDragEnd:t=>{t.cancelBubble=!0,t.target.x(r),d.history.endTransaction()}},`col-resize-${i}`))}return e})(),k&&!E&&!d.isPlaying&&(()=>{const e=[];let o=0;for(let i=0;i<n.rows-1;i++){o+=n.rowHeights[i]*n.a.height;const r=o,s=i;e.push(t(c,{y:r,points:[0,0,n.a.width,0],stroke:"transparent",strokeWidth:1,hitStrokeWidth:16,draggable:!0,onMouseEnter:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor="row-resize"),M({kind:"rowInsert",idx:s+1})},onMouseLeave:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor=""),M(null)},onDragStart:t=>{t.cancelBubble=!0,l(()=>W.set(!0)),d.history.startTransaction()},onDragMove:t=>{t.cancelBubble=!0;const e=t.target,o=(e.y()-r)/n.height;e.y(r),n.resizeRow(s,o)},onDragEnd:t=>{t.cancelBubble=!0,t.target.y(r),n._resetBaseRowHeights(),l(()=>W.set(!1)),d.history.endTransaction()}},`row-resize-${i}`))}return e})(),k&&!E&&!d.isPlaying&&t(C,{element:n,store:d,inv:I,isTouch:b,hover:H,setHover:M})]})]})});
|
package/canvas/text-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as s,TextPath as l}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{activeAnchorOf as y,scaledFontSizeAttrs as b,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as E,textMinResizeWidth as z}from"../utils/px.js";import{isFontLoaded as k}from"../utils/fonts.js";import{flags as O}from"../utils/flags.js";import{removeTags as R}from"@polotno/core/text";import{getDir as F,getCurvePath as A,resolveLineHeight as M,normalizeStrokeLineJoin as j}from"@polotno/core/text-html";import{cssFontFamily as L}from"@polotno/core/fonts";import{FIT_FONT_SIZE_STEP as C,FIT_HEIGHT_EPSILON as T}from"@polotno/core/fit-text";import{applyFilter as H}from"./apply-filters.js";import{useFadeIn as P}from"./use-fadein.js";import{isTouchDevice as X}from"../utils/screen.js";import{isAlive as Y,getParent as W}from"mobx-state-tree";import{getLimitedFontSize as D}from"./text-element/max-font-size.js";import{getOptimalCaretColor as $}from"./text-element/caret-color.js";import{visiblePlaceholder as B}from"./text-element/placeholder.js";import{hasMeasuredHeight as I,resolveTextBoxHeight as N}from"@polotno/core/text-types";let J;function _(){return J||(J=document.getElementById("polotno-text-style"),J||(J=document.createElement("style"),J.id="polotno-text-style",document.head.appendChild(J)),J)}d._fixTextRendering=!0;const V={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"@polotno/core/text-html";const q=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[s,l]=n.useState(V),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=$(r);const e=`\n .polotno-input::placeholder {\n color: ${s.color};\n opacity: 0.6;\n }\n `,n=_();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(s)&&l(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=N(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=R(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:F(g),style:Object.assign(Object.assign(Object.assign({},V),s),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=D({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},b(r,e)))},placeholder:B(r.placeholder),onBlur:o})}),U=e=>t(c,{children:t(q,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=n.useRef(k(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(l.current=k(e,r,o),l.current){return}let n=!0;return(async()=>{l.current=!1,s();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,l.current=!0,s()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{l.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[l.current]),[l.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=e.join("\0"),c=n.useRef(e.every(t=>k(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>k(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,s();const a=v(`text fonts ${l}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,s()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[l,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>M({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function Z(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=R(e.text);let a=e.a.fontSize;t.height(void 0);const s=Math.round(2*e.a.fontSize)-1;for(let l=1;l<s;l++){const n=I(e.a)&&t.height()>e.a.height+T;let o=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)),[]),s=t.textArr.map(t=>t.text.toLowerCase()).join(";");const l=o.find(t=>!s.includes(t)||(s=s.replace(t,""),!1));if(!(n||l&&!r)){break}a-=C,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),k=n.useRef(null),M=n.useRef(null),C=n.useRef(null),T=n.useRef([]),D=n.useRef(!0),[,$]=n.useReducer(t=>t+1,0),{editorEnabled:J,selectAll:_}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[V,q]=n.useState(!1),[G,K]=n.useState(!1),Q=n.useRef(o.a.height),tt=n.useRef(0),et=n.useRef(""),rt=n.useRef(0),nt=o.isSelected,ot=usePrevious(nt),{textVerticalResizeEnabled:it}=O,at=O.autoDeleteEmptyText,st=usePrevious(o.fontFamily),[lt,ct]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=k.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(lt)&&ct(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=k.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{ot&&!nt&&at&&""===o.text&&o.removable&&!B(o.placeholder)&&c.deleteElements([o.id])},[at,o.placeholder,o.removable,o.text,nt,ot]);const ut=()=>{if(o.curveEnabled){const t=k.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=M.current;e&&H(e,o)}else{const t=k.current;t&&H(t,o)}};n.useLayoutEffect(()=>{if(!G){return u(o,()=>{ut()})}}),n.useEffect(()=>{const t=T.current;t.length>0&&(T.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{D.current=!1;const t=T.current;t.length>0&&(T.current=[],t.forEach(t=>t()))},[]);let dt=R(o.text);"uppercase"===o.textTransform&&(dt=dt.toUpperCase());const[ft]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),ht=()=>{if(o.curveEnabled){const t=M.current;return t.getSelfRect().height||t.fontSize()}const t=k.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!ft){return}if("tablecell"===o.type){const{textOverflow:t}=O;if("resize"===t){const t=ht(),e=Y(o)?W(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=k.current;if(t){const e=Z(t,o,O.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=O,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{D.current?(T.current.push(i),$()):i()})};n?queueMicrotask(a):a()};if(!I(o)){const t=ht();return void r(()=>{I(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||V){if("resize"===t){const t=ht();it&&o.height<t&&!V&&r(()=>{var e;Y(o)&&o.set({height:t}),null===(e=k.current)||void 0===e||e.height(t)},!1,!0),it||o.height===t||V||r(()=>{var e;Y(o)&&o.set({height:t}),null===(e=k.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=k.current,n=o.curveEnabled?o.fontSize:Z(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(b(o,n))},!1,!0)}const i=ht();o.height===i||it||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(ft&&o.curveEnabled){const e=null===(t=M.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[ft,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=k.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ut())},[ft]);const gt=n.useRef(null),pt=n.useRef(o.width),mt=n.useRef(0),xt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(mt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),s=null!==(e=o[i])&&void 0!==e?e:o[0];let l=0;return"right"===r.align()?l=r.width()-s.width:"center"===r.align()&&(l=r.width()/2-s.width/2),a+Math.round((n.x-l)/s.width*s.text.length)}(t),o.toggleEditMode())},wt=B(o.placeholder),vt=!dt&&wt?.6:o.a.opacity;P(k,vt);const yt=getLineHeight({fontLoaded:ft,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),bt=o.selectable||c.role===w.ADMIN,St=m(o),Et=m(o,o.stroke,"stroke"),zt=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,s=e+r,l=f(`M ${o} ${i} L ${a} ${i} L ${a} ${s} L ${o} ${s} Z`);return h(l,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*yt*.5),padding:o.backgroundPadding*(o.a.fontSize*yt*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(lt)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*yt*.5),lineHeight:yt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*yt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,yt,o.backgroundPadding,o.a.width,o.align,lt]),kt=X();let Ot=0;if(!o.curveEnabled){const t=lt.length*yt*o.a.fontSize,e=N(o.a,t);"middle"===o.verticalAlign?Ot=(e-t)/2:"bottom"===o.verticalAlign&&(Ot=e-t)}const Rt=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Ft=ft?L(o.fontFamily):st===o.fontFamily?"Arial":L(st),At=F(dt);return r(e,{children:[t(a,{ref:C,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*vt,data:zt,fill:o.backgroundColor,offsetY:-Ot}),t(a,{data:Rt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(l,Object.assign({ref:M,visible:o.curveEnabled,data:Rt,text:dt||wt,listening:!1,align:"center",textBaseline:"middle",direction:At},St,Et,{strokeWidth:o.strokeWidth,lineJoin:j(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`${L(o.fontFamily)}, ${L(st)}`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:vt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(s,Object.assign({ref:k,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:I(o.a)?o.a.height:void 0,text:dt||wt,direction:At},St,Et,{lineJoin:j(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Ft,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:kt?o.draggable&&nt:o.draggable,preventDefault:!kt||nt,opacity:o.curveEnabled?0:vt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===O.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:yt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&bt,onDragStart:()=>{K(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{K(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:xt,onTap:xt,onTransformStart:()=>{q(!0);const t=k.current;Q.current=t.height(),pt.current=o.a.width,gt.current=t.position(),tt.current=t.rotation(),rt.current=t.height(),et.current=y(t)},onTransform:t=>{var e,r;const n=t.target;null===(e=C.current)||void 0===e||e.setAttrs({x:n.x(),y:n.y(),rotation:n.rotation(),scale:n.scale()});const i=et.current;if("middle-left"===i||"middle-right"===i){const t=n.scaleX(),e=n.width()*t,r=z(pt.current,o.a.fontSize);let i=e;e<r&&(i=r,gt.current&&n.position(gt.current)),n.width(i),n.scaleX(1),n.scaleY(1);let a=ht();if("ellipsis"===O.textOverflow){a=Q.current}else{const t=Math.max(a,Q.current);n.height(t),o.set({height:n.height()})}const s=O.textVerticalResizeEnabled?Math.max(a,Q.current):ht();o.set({x:n.x(),width:n.width(),rotation:n.rotation(),height:s}),n.skewX(0),n.skewY(0),ut()}if("top-center"===i||"bottom-center"===i){const e="resize"===O.textOverflow?ht():yt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),gt.current){if("top-center"===et.current){const r=tt.current*Math.PI/180,n=rt.current-e;t.target.x(gt.current.x-n*Math.sin(r)),t.target.y(gt.current.y+n*Math.cos(r))}else{t.target.position(gt.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(tt.current),t.target.skewX(0),t.target.skewY(0),rt.current=Math.max(e,r)}gt.current=t.target.position();const a=t.target.scaleX();null===(r=C.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*a,width:t.target.width()*a,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*a,shadowBlur:o.shadowBlur*a,shadowOffsetX:o.shadowOffsetX*a,shadowOffsetY:o.shadowOffsetY*a,strokeWidth:o.strokeWidth*a})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=C.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),q(!1)}})),J&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(U,{textNodeRef:k,element:o,selectAll:_,cursorPosition:mt.current,onBlur:()=>{o.set(E(o)),o.toggleEditMode(!1)}})})]})});
|
|
1
|
+
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as s,TextPath as l}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{activeAnchorOf as y,scaledFontSizeAttrs as b,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as E,roundedGeometryPx as z,roundedPosition as k,textMinResizeWidth as O}from"../utils/px.js";import{isFontLoaded as R}from"../utils/fonts.js";import{flags as F}from"../utils/flags.js";import{removeTags as A}from"@polotno/core/text";import{getDir as M,getCurvePath as j,resolveLineHeight as L,normalizeStrokeLineJoin as C}from"@polotno/core/text-html";import{cssFontFamily as T}from"@polotno/core/fonts";import{FIT_FONT_SIZE_STEP as H,FIT_HEIGHT_EPSILON as P}from"@polotno/core/fit-text";import{applyFilter as X}from"./apply-filters.js";import{useFadeIn as Y}from"./use-fadein.js";import{isTouchDevice as W}from"../utils/screen.js";import{isAlive as D,getParent as $}from"mobx-state-tree";import{getLimitedFontSize as B}from"./text-element/max-font-size.js";import{getOptimalCaretColor as I}from"./text-element/caret-color.js";import{visiblePlaceholder as N}from"./text-element/placeholder.js";import{hasMeasuredHeight as J,resolveTextBoxHeight as _}from"@polotno/core/text-types";let V;function q(){return V||(V=document.getElementById("polotno-text-style"),V||(V=document.createElement("style"),V.id="polotno-text-style",document.head.appendChild(V)),V)}d._fixTextRendering=!0;const U={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"@polotno/core/text-html";const Z=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[s,l]=n.useState(U),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=I(r);const e=`\n .polotno-input::placeholder {\n color: ${s.color};\n opacity: 0.6;\n }\n `,n=q();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(s)&&l(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=_(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=A(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:M(g),style:Object.assign(Object.assign(Object.assign({},U),s),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=B({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},b(r,e)))},placeholder:N(r.placeholder),onBlur:o})}),G=e=>t(c,{children:t(Z,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=n.useRef(R(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(l.current=R(e,r,o),l.current){return}let n=!0;return(async()=>{l.current=!1,s();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,l.current=!0,s()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{l.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[l.current]),[l.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=e.join("\0"),c=n.useRef(e.every(t=>R(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>R(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,s();const a=v(`text fonts ${l}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,s()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[l,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>L({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function K(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=A(e.text);let a=e.a.fontSize;t.height(void 0);const s=Math.round(2*e.a.fontSize)-1;for(let l=1;l<s;l++){const n=J(e.a)&&t.height()>e.a.height+P;let o=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)),[]),s=t.textArr.map(t=>t.text.toLowerCase()).join(";");const l=o.find(t=>!s.includes(t)||(s=s.replace(t,""),!1));if(!(n||l&&!r)){break}a-=H,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),R=n.useRef(null),L=n.useRef(null),H=n.useRef(null),P=n.useRef([]),B=n.useRef(!0),[,I]=n.useReducer(t=>t+1,0),{editorEnabled:V,selectAll:q}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[U,Z]=n.useState(!1),[Q,tt]=n.useState(!1),et=n.useRef(o.a.height),rt=n.useRef(0),nt=n.useRef(""),ot=n.useRef(0),it=o.isSelected,at=usePrevious(it),{textVerticalResizeEnabled:st}=F,lt=F.autoDeleteEmptyText,ct=usePrevious(o.fontFamily),[ut,dt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=R.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(ut)&&dt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=R.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{at&&!it&<&&""===o.text&&o.removable&&!N(o.placeholder)&&c.deleteElements([o.id])},[lt,o.placeholder,o.removable,o.text,it,at]);const ft=()=>{if(o.curveEnabled){const t=R.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=L.current;e&&X(e,o)}else{const t=R.current;t&&X(t,o)}};n.useLayoutEffect(()=>{if(!Q){return u(o,()=>{ft()})}}),n.useEffect(()=>{const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{B.current=!1;const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))},[]);let ht=A(o.text);"uppercase"===o.textTransform&&(ht=ht.toUpperCase());const[gt]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),pt=()=>{if(o.curveEnabled){const t=L.current;return t.getSelfRect().height||t.fontSize()}const t=R.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!gt){return}if("tablecell"===o.type){const{textOverflow:t}=F;if("resize"===t){const t=pt(),e=D(o)?$(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=R.current;if(t){const e=K(t,o,F.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=F,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{B.current?(P.current.push(i),I()):i()})};n?queueMicrotask(a):a()};if(!J(o)){const t=pt();return void r(()=>{J(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||U){if("resize"===t){const t=pt();st&&o.height<t&&!U&&r(()=>{var e;D(o)&&o.set({height:t}),null===(e=R.current)||void 0===e||e.height(t)},!1,!0),st||o.height===t||U||r(()=>{var e;D(o)&&o.set({height:t}),null===(e=R.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=R.current,n=o.curveEnabled?o.fontSize:K(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(b(o,n))},!1,!0)}const i=pt();o.height===i||st||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(gt&&o.curveEnabled){const e=null===(t=L.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[gt,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=R.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ft())},[gt]);const mt=n.useRef(null),xt=n.useRef(o.width),wt=n.useRef(0),vt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(wt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),s=null!==(e=o[i])&&void 0!==e?e:o[0];let l=0;return"right"===r.align()?l=r.width()-s.width:"center"===r.align()&&(l=r.width()/2-s.width/2),a+Math.round((n.x-l)/s.width*s.text.length)}(t),o.toggleEditMode())},yt=N(o.placeholder),bt=!ht&&yt?.6:o.a.opacity;Y(R,bt);const St=getLineHeight({fontLoaded:gt,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),Et=o.selectable||c.role===w.ADMIN,zt=m(o),kt=m(o,o.stroke,"stroke"),Ot=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,s=e+r,l=f(`M ${o} ${i} L ${a} ${i} L ${a} ${s} L ${o} ${s} Z`);return h(l,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*St*.5),padding:o.backgroundPadding*(o.a.fontSize*St*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(ut)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*St*.5),lineHeight:St*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*St*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,St,o.backgroundPadding,o.a.width,o.align,ut]),Rt=W();let Ft=0;if(!o.curveEnabled){const t=ut.length*St*o.a.fontSize,e=_(o.a,t);"middle"===o.verticalAlign?Ft=(e-t)/2:"bottom"===o.verticalAlign&&(Ft=e-t)}const At=o.curveEnabled?j(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Mt=gt?T(o.fontFamily):ct===o.fontFamily?"Arial":T(ct),jt=M(ht);return r(e,{children:[t(a,{ref:H,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*bt,data:Ot,fill:o.backgroundColor,offsetY:-Ft}),t(a,{data:At,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(l,Object.assign({ref:L,visible:o.curveEnabled,data:At,text:ht||yt,listening:!1,align:"center",textBaseline:"middle",direction:jt},zt,kt,{strokeWidth:o.strokeWidth,lineJoin:C(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`${T(o.fontFamily)}, ${T(ct)}`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:bt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(s,Object.assign({ref:R,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:J(o.a)?o.a.height:void 0,text:ht||yt,direction:jt},zt,kt,{lineJoin:C(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Mt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:Rt?o.draggable&&it:o.draggable,preventDefault:!Rt||it,opacity:o.curveEnabled?0:bt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===F.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:St,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&Et,onDragStart:()=>{tt(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{tt(!1),o.set(k(t.target))},onClick:vt,onTap:vt,onTransformStart:()=>{Z(!0);const t=R.current;et.current=t.height(),xt.current=o.a.width,mt.current=t.position(),rt.current=t.rotation(),ot.current=t.height(),nt.current=y(t)},onTransform:t=>{var e,r;const n=t.target;null===(e=H.current)||void 0===e||e.setAttrs({x:n.x(),y:n.y(),rotation:n.rotation(),scale:n.scale()});const i=nt.current;if("middle-left"===i||"middle-right"===i){const t=n.scaleX(),e=n.width()*t,r=O(xt.current,o.a.fontSize);let i=e;e<r&&(i=r,mt.current&&n.position(mt.current)),n.width(i),n.scaleX(1),n.scaleY(1);let a=pt();if("ellipsis"===F.textOverflow){a=et.current}else{const t=Math.max(a,et.current);n.height(t),o.set({height:n.height()})}const s=F.textVerticalResizeEnabled?Math.max(a,et.current):pt();o.set({x:n.x(),width:n.width(),rotation:n.rotation(),height:s}),n.skewX(0),n.skewY(0),ft()}if("top-center"===i||"bottom-center"===i){const e="resize"===F.textOverflow?pt():St*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),mt.current){if("top-center"===nt.current){const r=rt.current*Math.PI/180,n=ot.current-e;t.target.x(mt.current.x-n*Math.sin(r)),t.target.y(mt.current.y+n*Math.cos(r))}else{t.target.position(mt.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(rt.current),t.target.skewX(0),t.target.skewY(0),ot.current=Math.max(e,r)}mt.current=t.target.position();const a=t.target.scaleX();null===(r=H.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*a,width:t.target.width()*a,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*a,shadowBlur:o.shadowBlur*a,shadowOffsetX:o.shadowOffsetX*a,shadowOffsetY:o.shadowOffsetY*a,strokeWidth:o.strokeWidth*a})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:z(t.target.x()),y:z(t.target.y()),rotation:z(t.target.rotation()),height:z(t.target.height()*r)})),null===(e=H.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),Z(!1)}})),V&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(G,{textNodeRef:R,element:o,selectAll:q,cursorPosition:wt.current,onBlur:()=>{o.set(E(o)),o.toggleEditMode(!1)}})})]})});
|
package/canvas/tooltip.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as t,jsxs as e}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Html as r}from"react-konva-utils";import{getTotalClientRect as l}from"../utils/math.js";import{extendToolbar as i}from"../toolbar/element-container.js";import{TextAiWrite as s}from"../toolbar/text-ai-write.js";import{flags as u}from"../utils/flags.js";import{DuplicateButton as a}from"../toolbar/duplicate-button.js";import{RemoveButton as c}from"../toolbar/remove-button.js";import{PositionPicker as d}from"../toolbar/position-picker.js";import{GroupButton as m}from"../toolbar/group-button.js";import{Navbar as v}from"../primitives/navbar.js";import{MAIN_TRANSFORMER_NAME as p}from"../utils/px.js";function f(t,e){return t.classList.contains(e)?t:t.parentElement?f(t.parentElement,e):null}const h=()=>null,g=({stage:t})=>{var e,n;return(null===(e=null==t?void 0:t.container())||void 0===e?void 0:e.closest(".polotno-workspace-container"))||(null===(n=null==t?void 0:t.container())||void 0===n?void 0:n.parentNode)};export const Tooltip=o(({store:o,page:b,components:x,stageRef:j,tooltipSafeArea:E})=>{var w,y;const N=o.selectedShapes.every(t=>t.page===b),I=n.useRef(null),O=n.useRef(null),[S,R]=n.useState(!1),[,C]=n.useReducer(t=>t+1,0),F=n.useCallback(t=>{var e,n;t?(I.current=t,null===(e=O.current)||void 0===e||e.disconnect(),O.current=new ResizeObserver(C),O.current.observe(t),C()):I.current&&!I.current.isConnected&&(I.current=null,null===(n=O.current)||void 0===n||n.disconnect(),O.current=null)},[]),k=o._hasCroppedImages;n.useEffect(()=>{var t,e,n;const o=()=>{R(!0)},r=()=>{R(!1)};null===(t=null==j?void 0:j.current)||void 0===t||t.on("dragstart",o),null===(e=null==j?void 0:j.current)||void 0===e||e.on("dragend",r);const l=null===(n=null==j?void 0:j.current)||void 0===n?void 0:n.findOne(`.${p}`);return null==l||l.on("transformstart",o),null==l||l.on("transformend",r),()=>{var t,e;null===(t=null==j?void 0:j.current)||void 0===t||t.off("dragstart",o),null===(e=null==j?void 0:j.current)||void 0===e||e.off("dragend",r),null==l||l.off("transformstart",o),null==l||l.off("transformend",r)}},[]),n.useEffect(()=>{if(!(null==j?void 0:j.current)){return}const t=f(j.current.content,"polotno-workspace-inner");if(!t){return}const e=()=>{o.selectedShapes.length&&C()};return t.addEventListener("scroll",e),()=>{t.removeEventListener("scroll",e)}},[]);const T=o.selectedElements.map(t=>t.id).join(",");if(n.useEffect(()=>{if(!T){return}const t=requestAnimationFrame(()=>C());return()=>cancelAnimationFrame(t)},[T]),0===o.selectedShapes.length){return null}if(S){return null}if(!N){return null}if(o.activePage!==b){return null}if(k){return null}const M=l(o.selectedShapes),P=(null==x?void 0:x.Position)||d,X=(null==x?void 0:x.Duplicate)||a,Y=(null==x?void 0:x.Remove)||c,A=(null==x?void 0:x.Group)||m,L=(null==x?void 0:x.Lock)||h,B=null===(w=o.selectedElements[0])||void 0===w?void 0:w.type,_=Object.assign(Object.assign({},u.aiTextEnabled?{TextAiWrite:s}:{}),x||{}),z=i({components:_,type:B,usedItems:[]}),J=!!(null===(y=I.current)||void 0===y?void 0:y.isConnected);return t(r,{parentNodeFunc:g,transformFunc:t=>{var e,n,o;const r=M.x+M.width/2,l=null===(e=null==j?void 0:j.current)||void 0===e?void 0:e.container(),i=(null==l?void 0:l.getBoundingClientRect())||{left:0,top:0,width:0,height:0,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},s=null==l?void 0:l.closest(".polotno-workspace-container"),u=(null==s?void 0:s.getBoundingClientRect())||{left:0,top:0,width:Number.POSITIVE_INFINITY,height:Number.POSITIVE_INFINITY,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},a=i.left-u.left,c=i.top-u.top,d=(null===(n=I.current)||void 0===n?void 0:n.isConnected)?I.current.getBoundingClientRect():null,m=(null==d?void 0:d.width)||0,v=(null==d?void 0:d.height)||34,p=((null==E?void 0:E.top)||0)+8,f=(null!==(o=null==E?void 0:E.bottom)&&void 0!==o?o:45)+8,h=c+t.y+M.y*t.scaleY,g=c+t.y+(M.y+M.height)*t.scaleY,b=Number.isFinite(u.height),x=p+v/2,w=u.height-f-v/2;let y=h-80;b&&(y=Math.max(x,y));let N=y+v/2<=h-48?y:g+80;b&&(N=Math.min(w,Math.max(x,N)));let O=a+t.x+r*t.scaleX,S=O-M.width*t.scaleX/2,R=O+M.width*t.scaleX/2;const C=Math.min(50,M.width/2*t.scaleX),F=R>=C&&S<=u.width-C,k=(null==E?void 0:E.left)||0,T=(null==E?void 0:E.right)||0;if(Number.isFinite(u.width)&&m>0&&F){const t=8+m/2+k,e=u.width-8-m/2-T;e>=t&&(O=Math.max(t,Math.min(O,e)))}return R<C&&(O-=m+8),S>u.width-C&&(O+=m+8),Object.assign(Object.assign({},t),{x:O,y:N,scaleX:1,scaleY:1})},divProps:{style:{pointerEvents:"none",position:"absolute",visibility:J?"visible":"hidden",zIndex:9}},children:t("div",{ref:F,className:"polotno-selection-tooltip",style:{pointerEvents:"none"},children:e(v,{floating:!0,height:34,className:"pn:gap-0.5 pn:bg-popover pn:px-0.5",style:{transform:"translate(-50%, -50%)",pointerEvents:"auto"},children:[z.map(e=>{const n=_[e];return t(n,{elements:o.selectedElements,element:o.selectedElements[0],store:o},e)}),t(A,{store:o}),t(L,{store:o}),t(X,{store:o}),t(Y,{store:o}),t(P,{store:o})]})})})});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type Konva from 'konva';
|
|
2
|
+
import type { Box } from 'konva/lib/shapes/Transformer';
|
|
3
|
+
export declare const restoreHeldPoint: (clamped: Box, newBox: Box, oldBox: Box) => Box;
|
|
4
|
+
export type CropBoundMode = 'cover' | 'contain';
|
|
5
|
+
type Ref<T> = {
|
|
6
|
+
current: T | null;
|
|
7
|
+
};
|
|
8
|
+
export declare const cropBoundBoxFunc: (moving: Ref<Konva.Node>, fixed: Ref<Konva.Node>, mode: CropBoundMode, themed?: (oldBox: Box, newBox: Box) => Box) => (oldBox: Box, newBox: Box) => Box;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{clamp as t}from"../lib/utils.js";const h=(h,i)=>{const e=Math.cos(i.rotation),n=Math.sin(i.rotation),r=i.x-h.x,a=i.y-h.y,o=h.width-i.width,d=h.height-i.height;return{x:0===o?0:t((r*e+a*n)/o,0,1),y:0===d?0:t((a*e-r*n)/d,0,1)}};export const restoreHeldPoint=(t,i,e)=>{if(t.width===i.width&&t.height===i.height){return t}const n=h(e,i),r=Math.cos(i.rotation),a=Math.sin(i.rotation),o=n.x*(e.width-t.width),d=n.y*(e.height-t.height);return t.x=e.x+o*r-d*a,t.y=e.y+o*a+d*r,t};const i=(h,i,e,n)=>i>e?n:t(h,i,e);export const cropBoundBoxFunc=(t,e,n,r)=>(a,o)=>{var d;const s=r&&null!==(d=r(a,o))&&void 0!==d?d:o;if(!(a.width>0&&a.height>0)){return s}const c=h(a,s),g=t.current&&e.current?((t,h,i,e,n)=>{const r=h.width()*h.scaleX(),a=h.height()*h.scaleY();if(!(r>0&&a>0)){return null}const o=(i.x()-h.x())/r,d=o+i.width()*i.scaleX()/r,s=(i.y()-h.y())/a,c=s+i.height()*i.scaleY()/a,g=(t,h,i)=>{const n="cover"===e?0:1/0,r=t>0?(t-h)/t:n,a=t<1?(i-t)/(1-t):n;return"cover"===e?Math.max(r,a):Math.min(r,a)},m=g(n.x,o,d)*t.width,x=g(n.y,s,c)*t.height;return"cover"===e?{minWidth:Math.max(m,5),minHeight:Math.max(x,5),maxWidth:1/0,maxHeight:1/0}:{minWidth:5,minHeight:5,maxWidth:m,maxHeight:x}})(a,t.current,e.current,n,c):null;if(!g){return s}const m=s.width/a.width,x=s.height/a.height,u=Math.abs(m-x)<=1e-9*Math.max(Math.abs(m),Math.abs(x),1),w=Object.assign({},s);if(u){const t=i(m,Math.max(g.minWidth/a.width,g.minHeight/a.height),Math.min(g.maxWidth/a.width,g.maxHeight/a.height),1);t!==m&&(w.width=a.width*t,w.height=a.height*t)}else{w.width=i(s.width,g.minWidth,g.maxWidth,a.width),w.height=i(s.height,g.minHeight,g.maxHeight,a.height)}return restoreHeldPoint(w,s,a)};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export type ImageStatus = 'loading' | 'loaded' | 'failed';
|
|
2
|
+
export type CrossOrigin = 'anonymous' | 'use-credentials';
|
|
3
|
+
export declare function useImage(url: string, crossOrigin?: CrossOrigin, referrerPolicy?: string): [HTMLImageElement | undefined, ImageStatus];
|
|
4
|
+
export default useImage;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"react";import{DEFAULT_RETRIES as r,isDeterministicUrl as t,retryDelayMs as n}from"@polotno/core/retry";export function useImage(o,u,c){const i=e.useRef("loading"),d=e.useRef(void 0),[,s]=e.useState(0),a=e.useRef(void 0),l=e.useRef(void 0),f=e.useRef(void 0);return a.current===o&&l.current===u&&f.current===c||(i.current="loading",d.current=void 0,a.current=o,l.current=u,f.current=c),e.useLayoutEffect(()=>{if(!o){return}const e=t(o)?1:r;let a,l,f=0,m=!1,v=!1;const g=(e,r)=>{i.current=r,d.current=e,s(Math.random())},E=()=>{f+=1;const r=document.createElement("img"),t=()=>{r.decode().catch(()=>{}).finally(()=>{m||(v=!0,g(r,"loaded"))})},i=()=>{if(!m){return!v&&f<e?(null==l||l(),void(a=setTimeout(E,n(f)))):void g(void 0,"failed")}};r.addEventListener("load",t),r.addEventListener("error",i),l=()=>{r.removeEventListener("load",t),r.removeEventListener("error",i)},u&&(r.crossOrigin=u),c&&(r.referrerPolicy=c),r.src=o};return E(),()=>{m=!0,clearTimeout(a),null==l||l()}},[o,u,c]),[d.current,i.current]}export default useImage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,
|
|
1
|
+
import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,VideoSampleSink as i,ALL_FORMATS as a}from"mediabunny";import{incrementLoader as c,triggerLoadError as o}from"../utils/loader.js";import{polotnoError as s}from"@polotno/core/errors";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";import{decodeBase64 as m}from"../utils/base64.js";function f(e,r){const t=p(e);return t>0&&r>=e.timestamp&&r<e.timestamp+t}function p(e){var r;const t=null!==(r=e.duration)&&void 0!==r?r:0;return Number.isFinite(t)&&t>0?t:0}function h(e){var r;null===(r=null==e?void 0:e.close)||void 0===r||r.call(e)}function v(e){for(const r of e.current){h(r.frame)}e.current=[]}export const useMediabunnyVideo=(g,y,w)=>{const[b,T]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1});e.useRef(b).current=b;const R=e.useRef(0),k=e.useRef(null),E=e.useRef(null),$=e.useRef(null),S=e.useRef(null),O=e.useRef(null),F=e.useRef(null),j=e.useRef(null),x=e.useRef(!1),D=e.useRef(null),I=e.useRef([]),A=e.useRef(null),L=e.useRef(!1),[,U]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!w){return}let e=!0;const r=++R.current;let l=null;return(async()=>{try{if(!e||r!==R.current){return}l=c(`mediabunny init ${g.id}`);const o=await async function(e){if(function(e){return e.startsWith("data:")}(e)){const r=function(e){const r=e.indexOf(",");if(-1===r){throw new Error("Invalid data URL format")}return m(e.slice(r+1)).buffer}(e);return new u(r)}if(function(e){return e.startsWith("file://")}(e)){try{const r=await fetch(e),t=await r.arrayBuffer();return new u(t)}catch(r){throw new Error(`Failed to load file URL: ${e}. File URLs may not be supported in this environment. Error: ${r}`)}}return new n(e)}(g.src);if(!e||r!==R.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:a}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw s("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw s("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw s("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const h=await p.canBeTransparent(),v=new i(p);if(!e||r!==R.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),T(e=>Object.assign(Object.assign({},e),{input:d,videoSink:v,duration:f,isReady:!0,error:null,hasAlpha:h}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===R.current){const e=`Failed to initialize mediabunny for video ${g.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),T(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[g.src,w]),e.useEffect(()=>()=>{E.current&&(E.current.return(),E.current=null),k.current&&(k.current(),k.current=null),$.current=null,S.current=null,O.current=null,F.current=null,x.current=!1,D.current=null,v(I),A.current=null,L.current=!1,T({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1})},[w]),e.useEffect(()=>{if(!w||!b.isReady||!b.videoSink){return}const e=++R.current,t="string"==typeof g.src?g.src.slice(0,120):String(g.src),n=(e,r={},n="debug")=>{var u;let i="";try{i=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:j.current}))}catch(c){i=`[unserializable extras: ${String(c)}]`}const a=`mediabunny event=${e} elementId=${g.id} targetTime=${F.current} duration=${b.duration} lastFrameTimestamp=${null===(u=O.current)||void 0===u?void 0:u.timestamp} hasIterator=${Boolean(E.current)} prefetchSize=${I.current.length} srcHint=${t} extras=${i}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=b.duration||0;return r&&Number.isFinite(r)?Math.max(0,Math.min(e,r)):e},i=e=>{const r=e.displayWidth,t=e.displayHeight;let n=$.current;n&&n.width===r&&n.height===t||(n||(n=document.createElement("canvas"),$.current=n,S.current=n.getContext("2d",{alpha:b.hasAlpha})),n.width=r,n.height=t);const u=S.current,i=e.timestamp,a=p(e);try{u&&(b.hasAlpha&&u.clearRect(0,0,n.width,n.height),e.drawWithFit(u,{fit:"contain"}))}finally{h(e)}O.current={timestamp:i,duration:a}},a=e=>{const r=E.current;r&&(L.current||(L.current=!0,A.current=(async()=>{try{for(;I.current.length<4&&e===R.current;){const t=await r.next();if(e!==R.current){return void h(t.value)}if(t.done||!t.value){break}I.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{L.current=!1,A.current=null}})()))},o=e=>{const r=I.current;let t=-1;for(let u=0;u<r.length&&!(r[u].timestamp>e);u++){t=u}if(-1===t){return null}const n=r[t];if(!(t<r.length-1||f(n.frame,e))){return null}for(let u=0;u<t;u++){h(r[u].frame)}return I.current=r.slice(t+1),n},s=()=>v(I),m=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=O.current;return!r||e<r.timestamp||e>r.timestamp+.5})(c)?"seek":"iterate";try{const t=b.videoSink,u=O.current;if(u&&f(u,c)){return void(F.current=e)}const d=o(c);if(d){return i(d.frame),F.current=e,a(r),void U()}if(A.current){await A.current;const t=o(c);if(t){return i(t.frame),F.current=e,a(r),void U()}}s();const m=()=>n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),p=async e=>{E.current&&(await E.current.return(),E.current=null),s();const n=t.samples(e);E.current=n;const u=await n.next();return r!==R.current?(u.value&&h(u.value),await n.return(),E.current===n&&(E.current=null),"cancelled"):u.done||!u.value?"empty":(i(u.value),a(r),"drawn")};if("seek"===l){const e=await p(c);if("cancelled"===e){return}if("empty"===e){return void m()}}else{const e=E.current;if(!e){return}for(;r===R.current;){const t=await e.next();if(r!==R.current){t.value&&h(t.value);break}if(t.done||!t.value){"empty"===await p(c)&&m();break}const n=t.value;if(f(n,c)||n.timestamp>=c){i(n),a(r);break}h(n)}}F.current=e,U()}catch(d){const u=d instanceof Error?{name:d.name,message:d.message,stack:d.stack}:{message:String(d)},i=d instanceof Error?`${d.name}: ${d.message}`:String(d),a=i.includes("Unsupported configuration")||i.includes("isConfigSupported")||i.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:a,error:u},"error"),a&&t<1){try{E.current&&(await E.current.return(),E.current=null),s(),A.current=null,L.current=!1,O.current=null,await m(e,r,t+1)}catch(p){}}}},T=r(g,()=>{const r=b.videoSink,t=b.duration;if(!r||!t){return}const n=g.startTime*t*1e3,i=t*(g.endTime-g.startTime)*1e3,{start:a}=l(g.animations,g.page.duration),o=d(y.currentTime,g.page.startTime,a,i,n,g.speed),s=o/1e3+1e-6,f=u(s);j.current={pageStartTime:g.page.startTime,storeCurrentTime:y.currentTime,offsetMs:n,durationMs:i,restMs:o,targetTime:s,clampedTargetTime:f,startTime:g.startTime,endTime:g.endTime,videoDuration:t},((e,r)=>{x.current?D.current=e:(x.current=!0,k.current||(k.current=c(`mediabunny video frame ${g.id}`)),(async()=>{let t=e;for(;null!==t&&r===R.current;){await m(t,r),t=D.current,D.current=null}k.current&&(k.current(),k.current=null),x.current=!1})())})(s,e)});return()=>{T(),R.current++,k.current&&(k.current(),k.current=null)}},[w,b.isReady,b.videoSink,b.duration,y,g]),w&&b.isReady?$.current:null};
|