polotno 3.5.0 → 3.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{observer as n}from"mobx-react-lite";import{Group as i,Image as a,Path as s,Rect as l}from"react-konva";import{scaledFontSizeAttrs as c,roundedFontSizeAttrs as f,roundedTextDecorationAttrs as h,textMinResizeWidth as d}from"../utils/px.js";import u from"konva";import{isAlive as g}from"mobx-state-tree";import{nodeAutorun as m}from"../utils/mobx.js";import{flags as x}from"../utils/flags.js";import{applyFilter as p}from"./apply-filters.js";import{getLineHeight as y,useFontFamiliesLoader as w,usePrevious as v}from"./text-element.js";import{getCurvePath as b}from"@polotno/core/text-html";import{useColor as E}from"./use-color.js";import{useWorkspaceStyle as S}from"./workspace-style.js";import{detectSize as O,detectLineRects as k,htmlToCanvas as z}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as j}from"./use-fadein.js";import{Html as M}from"react-konva-utils";import{incrementLoader as R,triggerLoadError as X}from"../utils/loader.js";import{removeTags as Y}from"@polotno/core/text";import*as I from"../utils/fonts.js";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as T}from"./text-element/max-font-size.js";import{useDelayer as A}from"./use-delayer.js";import{getHtml as P}from"@polotno/core/text-html";import{normalizeRichTextHtml as B,extractFontFamiliesFromHtml as W,scaleRichTextFontSizesInHtml as $}from"../utils/rich-text-html.js";import{findFitFontSize as D}from"./text-element/fit-font-size.js";import{RichEditor as H,RichTextContainer as _,applyOpacityToColor as L,quillRef as J,createQuill as N,setQuillContent as q,setQuillFormats as V,syncQuillFormatState as G,setCursorFromCoords as K}from"./rich-editor.js";export{J as quillRef,N as createQuill,q as setQuillContent,V as setQuillFormats,G as syncQuillFormatState,K as setCursorFromCoords};function Q(t){const e=document.createElement("canvas"),o=e.getContext("2d");return null==o||o.drawImage(t,0,0,e.width,e.height),function(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}(e)}const U=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),Z=navigator.userAgent.includes("Firefox");export const HTMLElement=n(({element:n,store:J})=>{var N,q;const{textOverflowIndicatorStyle:V}=S(),G=r.useRef(null),[K,tt]=r.useState(),[et,ot]=r.useState(!1),[rt,nt]=r.useState(!1),it=r.useRef(n.height),at=n.isSelected,st=v(at),lt=n.fontSize/3,{textVerticalResizeEnabled:ct}=x,ft=x.autoDeleteEmptyText,ht=v(n.fontFamily),dt=r.useMemo(()=>B(n.text,{fontSize:n.fontSize,fontFamily:n.fontFamily}),[n.text,n.fontSize,n.fontFamily]),ut=r.useMemo(()=>[...new Set([n.fontFamily,...W(dt)])].filter(Boolean),[n.fontFamily,dt]),[gt]=w(J,ut,n.fontStyle,n.fontWeight,n.text||n.placeholder),mt=n._editModeEnabled;j(G);const xt=gt?n.fontFamily:ht!==n.fontFamily?ht:"Arial",pt=E(n).fill,yt=P(n,{fontFamily:xt,color:pt,textOverflow:x.textOverflow}),wt=r.useRef([]),vt=r.useRef(!0),[,bt]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=wt.current;t.length>0&&(wt.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{vt.current=!1;const t=wt.current;t.length>0&&(wt.current=[],t.forEach(t=>t()))},[]);let{width:Et,height:St}=function(t,e,o){return r.useMemo(()=>O(t),[t,e.width,o])}(yt,n,gt);r.useEffect(()=>{if(!gt){return}const t=(t,e,o,r)=>{const i=R(`text ${n.id}`),a=()=>{J.history.ignore(t,e,o).then(()=>{vt.current?(wt.current.push(i),bt()):i()})};r?queueMicrotask(a):a()};if(n.curveEnabled&&Math.abs(Et-n.width)>1&&!et&&t(()=>{if(g(n)&&Math.abs(Et-n.width)>1){const t=n.x+n.width/2;n.set({width:Et,x:t-Et/2})}},!1,!0),!n.height){return void t(()=>{g(n)&&(n.height||n.set({height:St}))},void 0,void 0,!0)}const{textOverflow:e}=x;if("change-font-size"!==e||et||mt||n.curveEnabled){"resize"===e&&(ct&&n.height<St&&!et&&t(()=>{g(n)&&n.set({height:St})},!1,!0),ct||n.height===St||et||t(()=>{g(n)&&n.set({height:St})},!1,!0))}else{const e=D(n,{fontFamily:n.fontFamily,textOverflow:x.textOverflow});e.fontSize!==n.fontSize?t(()=>{if(!g(n)){return}const t=c(n,e.fontSize);void 0!==e.text&&e.text!==n.text&&(t.text=e.text),n.set(t)},!1,!0):n.height!==St&&(ct&&n.height<St?t(()=>{g(n)&&n.set({height:St})},!1,!0):ct||t(()=>{g(n)&&n.set({height:St})},!1,!0))}});const Ot=r.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,r=e,JSON.stringify(o)===JSON.stringify(r))||(t.lastResult=await z(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),kt=r.useRef(0),zt=r.useRef(null);r.useEffect(()=>{et||mt||(async()=>{kt.current++;const t=kt.current;let e=R(`text ${n.id} ${t}`);zt.current&&zt.current(),zt.current=e,nt(!0);let o=null;const r=U?5:1;for(let a=0;a<r;a++){const e=a>0?Ot:z;try{if(o=await e({skipCache:a>0,html:yt,width:Et||n.width||1,height:n.height||St||1,fontFamily:xt,fontFamilies:W(yt),resolveFont:t=>J.fonts.find(e=>e.fontFamily===t)||I.globalFonts.find(e=>e.fontFamily===t),padding:lt,pixelRatio:J._elementsPixelRatio,font:J.fonts.find(t=>t.fontFamily===xt)||I.globalFonts.find(t=>t.fontFamily===xt)}),t!==kt.current){return}if((U||Z)&&o&&Q(o)){await new Promise(t=>setTimeout(t,50*(a+1)));continue}break}catch(i){console.error(i),X(`Error rendering rich text with id ${n.id}`);break}}o?tt(o):e?(e(),e=null):console.error("Finish function is called twice!"),nt(!1)})()},[yt,et,St,mt,xt,n.height,J._elementsPixelRatio,gt]);const[Ft,jt]=A(rt,300),[Mt]=A(et,300,!0),Rt=Mt||Ft;r.useEffect(()=>{var t;if(!Rt){return m(n,()=>{const t=G.current;p(t,n)})}null===(t=G.current)||void 0===t||t.clearCache()},[K,Rt,n.shadowColor,n.shadowOffsetX,n.shadowOffsetY,n.shadowOpacity]),r.useEffect(()=>{K&&!rt&&zt.current&&(zt.current(),zt.current=null)},[K,rt]),r.useLayoutEffect(()=>{if(!gt){return}if(!n.curveEnabled){return}const t=new u.TextPath({data:b(n.a.width,n.a.height,n.curvePower,n.a.fontSize),text:Y(n.text),letterSpacing:n.letterSpacing*n.a.fontSize,fontSize:n.a.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,align:"center",textBaseline:"middle",fill:n.fill}),e=t.getSelfRect().width;if(e){const t=e-n.a.width,o=n.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);queueMicrotask(()=>{g(n)&&n.set({width:e,x:n.a.x+r,y:n.a.y+i})})}t.destroy()},[gt,n.curveEnabled,n.curvePower,n.text,n.fontSize,n.fontFamily,n.fontWeight,n.fontStyle,n.letterSpacing]),r.useEffect(()=>()=>{zt.current&&zt.current()},[]),r.useEffect(()=>{st&&!at&&ft&&""===Y(n.text)&&n.removable&&!n.placeholder&&J.deleteElements([n.id])},[ft,n.placeholder,n.removable,n.text,at,st]);let Xt=0;"middle"===n.verticalAlign&&(Xt=(n.height-St)/2),"bottom"===n.verticalAlign&&(Xt=n.height-St);const Yt=y({fontLoaded:gt,fontFamily:n.fontFamily,fontSize:n.fontSize,lineHeight:n.lineHeight}),It=n.backgroundPadding*(n.fontSize*Yt*.5),Ct=n.backgroundCornerRadius*(n.fontSize*Yt*.5),Tt=r.useMemo(()=>{if(!n.backgroundEnabled||n.curveEnabled||n.legacyBackground){return""}const t=k(yt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+lt,right:t.right+lt,top:t.top+lt,bottom:t.bottom+lt}));return F({rects:e,padding:It,cornerRadius:Ct})},[n.backgroundEnabled,n.curveEnabled,n.legacyBackground,yt,gt,It,Ct,lt]),At=C(),Pt=b(n.a.width,St,n.curvePower,n.fontSize),Bt=r.useRef(null),Wt=r.useRef(n.width),$t=r.useRef(null),Dt=r.useRef(0),Ht=r.useRef(0),_t=r.useRef(null),Lt=mt&&n.strokeWidth>0&&!n.curveEnabled,Jt=Et>0?(n.a.width+2*lt)/(Et+2*lt):1;return o(e,{children:[n.curveEnabled||n.legacyBackground?t(l,{x:n.a.x,y:n.a.y,offsetX:It/Jt,offsetY:It/Jt,rotation:n.a.rotation,scaleX:Jt,scaleY:Jt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,width:n.width+2*It,height:n.height+2*It,cornerRadius:Ct}):t(s,{name:"html-background",x:n.a.x,y:n.a.y,offsetX:lt/Jt,offsetY:(lt-Xt)/Jt,rotation:n.a.rotation,scaleX:Jt,scaleY:Jt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled&&Tt.length>0,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,data:Tt}),t(s,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,data:Pt,stroke:V.stroke,strokeWidth:1,visible:!1}),t(l,{ref:G,name:"element",x:n.a.x,y:n.a.y,listening:n.selectable,rotation:n.a.rotation,width:n.a.width,height:n.a.height,visible:!Rt,draggable:At?n.draggable&&at:n.draggable,preventDefault:!At||at,opacity:mt?0:n.a.opacity,hideInExport:!n.showInExport,onDragMove:t=>{n.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{n.set({x:t.target.x(),y:t.target.y()})},id:n.id,onDblClick:t=>{n.contentEditable&&(_t.current={x:t.evt.clientX,y:t.evt.clientY},n.toggleEditMode(!0))},onDblTap:t=>{var e;if(n.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];_t.current=o?{x:o.clientX,y:o.clientY}:null,n.toggleEditMode(!0)}},onTransformStart:t=>{var e,o;ot(!0),it.current=n.height,Wt.current=n.width,Bt.current=t.target.position();const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");$t.current=null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:null,Dt.current=n.a.rotation,Ht.current=n.height},onTransform:t=>{var e;const o=t.target,r=(null===(e=o.getStage())||void 0===e?void 0:e.findOne("Transformer")).getActiveAnchor(),i="middle-left"===r||"middle-right"===r,a="top-center"===r||"bottom-center"===r,s=o.scaleX();if(i){const t=o.scaleX(),e=o.width()*t,r=d(Wt.current,n.fontSize);let i=e;e<r&&(i=r,Bt.current&&o.position(Bt.current)),o.width(i),o.scaleX(1),o.scaleY(1);const a=P(Object.assign(Object.assign({},n.toJSON()),{width:i}),{fontFamily:xt,color:pt,textOverflow:x.textOverflow}),s=O(a).height,l=x.textVerticalResizeEnabled?Math.max(s,it.current):s;o.height(l),n.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(a){const t="resize"===x.textOverflow,e="number"==typeof n.lineHeight?n.lineHeight:1,r=t?St:e*n.fontSize,i=o.height()*o.scaleY();if(i<r){if(o.height(r),Bt.current){if("top-center"===$t.current){const t=Dt.current*Math.PI/180,e=Ht.current-r;o.x(Bt.current.x-e*Math.sin(t)),o.y(Bt.current.y+e*Math.cos(t))}else{o.position(Bt.current)}}}else{o.height(i)}o.scaleY(1),o.scaleX(1),Ht.current=Math.max(r,i),n.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),n.set({fontSize:n.fontSize*s,letterSpacing:n.letterSpacing,width:o.width()*s,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*s,shadowBlur:n.shadowBlur*s,shadowOffsetX:n.shadowOffsetX*s,shadowOffsetY:n.shadowOffsetY*s,strokeWidth:n.strokeWidth*s,text:$(n.text,s)})}Bt.current=t.target.position()},onTransformEnd:t=>{ot(!1),nt(!0);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),n.set(Object.assign(Object.assign({},f(n,n.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:$(n.text,e)}))}}),t(a,{ref:G,image:K,x:n.a.x,y:n.a.y,offsetX:lt,offsetY:lt-Xt,listening:!1,rotation:n.a.rotation,width:n.a.width+2*lt,height:(n.a.width+2*lt)*((null!==(N=null==K?void 0:K.height)&&void 0!==N?N:0)/((null==K?void 0:K.width)||1)||1),visible:!Rt&&!mt,opacity:n.a.opacity,shadowEnabled:n.shadowEnabled,shadowBlur:n.shadowBlur,shadowOffsetX:n.shadowOffsetX,shadowOffsetY:n.shadowOffsetY,shadowColor:n.shadowColor,shadowOpacity:n.shadowOpacity,hideInExport:!n.showInExport,editModeEnabled:n._editModeEnabled||et||Rt}),(Rt&&!mt||Lt)&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Xt,children:t(M,{divProps:{style:{pointerEvents:"none"}},children:t(_,{dangerouslySetInnerHTML:{__html:yt},style:{pointerEvents:"none",opacity:n.a.opacity,textShadow:n.shadowEnabled?`${n.shadowOffsetX}px ${n.shadowOffsetY}px ${n.shadowBlur}px ${L(n.shadowColor,null!==(q=n.shadowOpacity)&&void 0!==q?q:1)}`:void 0}})})}),mt&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Xt,children:t(M,{divProps:{style:{zIndex:20}},children:t(H,{element:n,onChange:t=>{const e=T({oldText:Y(n.text),newText:Y(t),element:n});n.set(Object.assign({text:t},c(n,e)))},onBlur:t=>{g(n)&&(n.set(h(n)),n.toggleEditMode(!1),jt(!0))},clickCoords:_t.current})})})]})});
1
+ import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{observer as n}from"mobx-react-lite";import{Group as i,Image as a,Path as s,Rect as l}from"react-konva";import{scaledFontSizeAttrs as c,roundedFontSizeAttrs as f,roundedTextDecorationAttrs as d,textMinResizeWidth as h}from"../utils/px.js";import u from"konva";import{isAlive as g}from"mobx-state-tree";import{nodeAutorun as m}from"../utils/mobx.js";import{flags as x}from"../utils/flags.js";import{applyFilter as p}from"./apply-filters.js";import{getLineHeight as y,useFontFamiliesLoader as w,usePrevious as v}from"./text-element.js";import{getCurvePath as b}from"@polotno/core/text-html";import{useColor as E}from"./use-color.js";import{useWorkspaceStyle as S}from"./workspace-style.js";import{detectSize as O,detectLineRects as k,htmlToCanvas as z}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as j}from"./use-fadein.js";import{Html as M}from"react-konva-utils";import{incrementLoader as R,triggerLoadError as X}from"../utils/loader.js";import{removeTags as Y}from"@polotno/core/text";import*as I from"../utils/fonts.js";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as T}from"./text-element/max-font-size.js";import{visiblePlaceholder as A}from"./text-element/placeholder.js";import{useDelayer as P}from"./use-delayer.js";import{getHtml as B}from"@polotno/core/text-html";import{hasMeasuredHeight as W,resolveTextBoxHeight as $}from"@polotno/core/text-types";import{normalizeRichTextHtml as D,extractFontFamiliesFromHtml as H,scaleRichTextFontSizesInHtml as _}from"../utils/rich-text-html.js";import{findFitFontSize as L}from"./text-element/fit-font-size.js";import{RichEditor as J,RichTextContainer as N,applyOpacityToColor as q,quillRef as V,createQuill as G,setQuillContent as K,setQuillFormats as Q,syncQuillFormatState as U,setCursorFromCoords as Z}from"./rich-editor.js";export{V as quillRef,G as createQuill,K as setQuillContent,Q as setQuillFormats,U as syncQuillFormatState,Z as setCursorFromCoords};function tt(t){const e=document.createElement("canvas"),o=e.getContext("2d");return null==o||o.drawImage(t,0,0,e.width,e.height),function(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}(e)}const et=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),ot=navigator.userAgent.includes("Firefox");export const HTMLElement=n(({element:n,store:V})=>{var G,K;const{textOverflowIndicatorStyle:Q}=S(),U=r.useRef(null),[Z,rt]=r.useState(),[nt,it]=r.useState(!1),[at,st]=r.useState(!1),lt=r.useRef(n.height),ct=n.isSelected,ft=v(ct),dt=n.fontSize/3,{textVerticalResizeEnabled:ht}=x,ut=x.autoDeleteEmptyText,gt=v(n.fontFamily),mt=r.useMemo(()=>D(n.text,{fontSize:n.fontSize,fontFamily:n.fontFamily}),[n.text,n.fontSize,n.fontFamily]),xt=r.useMemo(()=>[...new Set([n.fontFamily,...H(mt)])].filter(Boolean),[n.fontFamily,mt]),[pt]=w(V,xt,n.fontStyle,n.fontWeight,n.text||n.placeholder),yt=n._editModeEnabled;j(U);const wt=pt?n.fontFamily:gt!==n.fontFamily?gt:"Arial",vt=E(n).fill,bt=B(n,{fontFamily:wt,color:vt,textOverflow:x.textOverflow}),Et=r.useRef([]),St=r.useRef(!0),[,Ot]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=Et.current;t.length>0&&(Et.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{St.current=!1;const t=Et.current;t.length>0&&(Et.current=[],t.forEach(t=>t()))},[]);let{width:kt,height:zt}=function(t,e,o){return r.useMemo(()=>O(t),[t,e.width,o])}(bt,n,pt);r.useEffect(()=>{if(!pt){return}const t=(t,e,o,r)=>{const i=R(`text ${n.id}`),a=()=>{V.history.ignore(t,e,o).then(()=>{St.current?(Et.current.push(i),Ot()):i()})};r?queueMicrotask(a):a()};if(n.curveEnabled&&Math.abs(kt-n.width)>1&&!nt&&t(()=>{if(g(n)&&Math.abs(kt-n.width)>1){const t=n.x+n.width/2;n.set({width:kt,x:t-kt/2})}},!1,!0),!W(n)){return void t(()=>{g(n)&&(W(n)||n.set({height:zt}))},void 0,void 0,!0)}const{textOverflow:e}=x;if("change-font-size"!==e||nt||yt||n.curveEnabled){"resize"===e&&(ht&&n.height<zt&&!nt&&t(()=>{g(n)&&n.set({height:zt})},!1,!0),ht||n.height===zt||nt||t(()=>{g(n)&&n.set({height:zt})},!1,!0))}else{const e=L(n,{fontFamily:n.fontFamily,textOverflow:x.textOverflow});e.fontSize!==n.fontSize?t(()=>{if(!g(n)){return}const t=c(n,e.fontSize);void 0!==e.text&&e.text!==n.text&&(t.text=e.text),n.set(t)},!1,!0):n.height!==zt&&(ht&&n.height<zt?t(()=>{g(n)&&n.set({height:zt})},!1,!0):ht||t(()=>{g(n)&&n.set({height:zt})},!1,!0))}});const Ft=r.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,r=e,JSON.stringify(o)===JSON.stringify(r))||(t.lastResult=await z(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),jt=r.useRef(0),Mt=r.useRef(null);r.useEffect(()=>{nt||yt||(async()=>{jt.current++;const t=jt.current;let e=R(`text ${n.id} ${t}`);Mt.current&&Mt.current(),Mt.current=e,st(!0);let o=null;const r=et?5:1;for(let a=0;a<r;a++){const e=a>0?Ft:z;try{if(o=await e({skipCache:a>0,html:bt,width:kt||n.width||1,height:$(n,zt)||1,fontFamily:wt,fontFamilies:H(bt),resolveFont:t=>V.fonts.find(e=>e.fontFamily===t)||I.globalFonts.find(e=>e.fontFamily===t),padding:dt,pixelRatio:V._elementsPixelRatio,font:V.fonts.find(t=>t.fontFamily===wt)||I.globalFonts.find(t=>t.fontFamily===wt)}),t!==jt.current){return}if((et||ot)&&o&&tt(o)){await new Promise(t=>setTimeout(t,50*(a+1)));continue}break}catch(i){console.error(i),X(`Error rendering rich text with id ${n.id}`);break}}o?rt(o):e?(e(),e=null):console.error("Finish function is called twice!"),st(!1)})()},[bt,nt,zt,yt,wt,n.height,V._elementsPixelRatio,pt]);const[Rt,Xt]=P(at,300),[Yt]=P(nt,300,!0),It=Yt||Rt;r.useEffect(()=>{var t;if(!It){return m(n,()=>{const t=U.current;p(t,n)})}null===(t=U.current)||void 0===t||t.clearCache()},[Z,It,n.shadowColor,n.shadowOffsetX,n.shadowOffsetY,n.shadowOpacity]),r.useEffect(()=>{Z&&!at&&Mt.current&&(Mt.current(),Mt.current=null)},[Z,at]),r.useLayoutEffect(()=>{if(!pt){return}if(!n.curveEnabled){return}const t=new u.TextPath({data:b(n.a.width,n.a.height,n.curvePower,n.a.fontSize),text:Y(n.text),letterSpacing:n.letterSpacing*n.a.fontSize,fontSize:n.a.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,align:"center",textBaseline:"middle",fill:n.fill}),e=t.getSelfRect().width;if(e){const t=e-n.a.width,o=n.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);queueMicrotask(()=>{g(n)&&n.set({width:e,x:n.a.x+r,y:n.a.y+i})})}t.destroy()},[pt,n.curveEnabled,n.curvePower,n.text,n.fontSize,n.fontFamily,n.fontWeight,n.fontStyle,n.letterSpacing]),r.useEffect(()=>()=>{Mt.current&&Mt.current()},[]),r.useEffect(()=>{ft&&!ct&&ut&&""===Y(n.text)&&n.removable&&!A(n.placeholder)&&V.deleteElements([n.id])},[ut,n.placeholder,n.removable,n.text,ct,ft]);const Ct=$(n,zt);let Tt=0;"middle"===n.verticalAlign&&(Tt=(Ct-zt)/2),"bottom"===n.verticalAlign&&(Tt=Ct-zt);const At=y({fontLoaded:pt,fontFamily:n.fontFamily,fontSize:n.fontSize,lineHeight:n.lineHeight}),Pt=n.backgroundPadding*(n.fontSize*At*.5),Bt=n.backgroundCornerRadius*(n.fontSize*At*.5),Wt=r.useMemo(()=>{if(!n.backgroundEnabled||n.curveEnabled||n.legacyBackground){return""}const t=k(bt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+dt,right:t.right+dt,top:t.top+dt,bottom:t.bottom+dt}));return F({rects:e,padding:Pt,cornerRadius:Bt})},[n.backgroundEnabled,n.curveEnabled,n.legacyBackground,bt,pt,Pt,Bt,dt]),$t=C(),Dt=b(n.a.width,zt,n.curvePower,n.fontSize),Ht=r.useRef(null),_t=r.useRef(n.width),Lt=r.useRef(null),Jt=r.useRef(0),Nt=r.useRef(0),qt=r.useRef(null),Vt=yt&&n.strokeWidth>0&&!n.curveEnabled,Gt=kt>0?(n.a.width+2*dt)/(kt+2*dt):1;return o(e,{children:[n.curveEnabled||n.legacyBackground?t(l,{x:n.a.x,y:n.a.y,offsetX:Pt/Gt,offsetY:Pt/Gt,rotation:n.a.rotation,scaleX:Gt,scaleY:Gt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,width:n.width+2*Pt,height:Ct+2*Pt,cornerRadius:Bt}):t(s,{name:"html-background",x:n.a.x,y:n.a.y,offsetX:dt/Gt,offsetY:(dt-Tt)/Gt,rotation:n.a.rotation,scaleX:Gt,scaleY:Gt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled&&Wt.length>0,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,data:Wt}),t(s,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,data:Dt,stroke:Q.stroke,strokeWidth:1,visible:!1}),t(l,{ref:U,name:"element",x:n.a.x,y:n.a.y,listening:n.selectable,rotation:n.a.rotation,width:n.a.width,height:n.a.height,visible:!It,draggable:$t?n.draggable&&ct:n.draggable,preventDefault:!$t||ct,opacity:yt?0:n.a.opacity,hideInExport:!n.showInExport,onDragMove:t=>{n.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{n.set({x:t.target.x(),y:t.target.y()})},id:n.id,onDblClick:t=>{n.contentEditable&&(qt.current={x:t.evt.clientX,y:t.evt.clientY},n.toggleEditMode(!0))},onDblTap:t=>{var e;if(n.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];qt.current=o?{x:o.clientX,y:o.clientY}:null,n.toggleEditMode(!0)}},onTransformStart:t=>{var e,o;it(!0),lt.current=n.height,_t.current=n.width,Ht.current=t.target.position();const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");Lt.current=null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:null,Jt.current=n.a.rotation,Nt.current=n.height},onTransform:t=>{var e;const o=t.target,r=(null===(e=o.getStage())||void 0===e?void 0:e.findOne("Transformer")).getActiveAnchor(),i="middle-left"===r||"middle-right"===r,a="top-center"===r||"bottom-center"===r,s=o.scaleX();if(i){const t=o.scaleX(),e=o.width()*t,r=h(_t.current,n.fontSize);let i=e;e<r&&(i=r,Ht.current&&o.position(Ht.current)),o.width(i),o.scaleX(1),o.scaleY(1);const a=B(Object.assign(Object.assign({},n.toJSON()),{width:i}),{fontFamily:wt,color:vt,textOverflow:x.textOverflow}),s=O(a).height,l=x.textVerticalResizeEnabled?Math.max(s,lt.current):s;o.height(l),n.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(a){const t="resize"===x.textOverflow,e="number"==typeof n.lineHeight?n.lineHeight:1,r=t?zt:e*n.fontSize,i=o.height()*o.scaleY();if(i<r){if(o.height(r),Ht.current){if("top-center"===Lt.current){const t=Jt.current*Math.PI/180,e=Nt.current-r;o.x(Ht.current.x-e*Math.sin(t)),o.y(Ht.current.y+e*Math.cos(t))}else{o.position(Ht.current)}}}else{o.height(i)}o.scaleY(1),o.scaleX(1),Nt.current=Math.max(r,i),n.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),n.set({fontSize:n.fontSize*s,letterSpacing:n.letterSpacing,width:o.width()*s,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*s,shadowBlur:n.shadowBlur*s,shadowOffsetX:n.shadowOffsetX*s,shadowOffsetY:n.shadowOffsetY*s,strokeWidth:n.strokeWidth*s,text:_(n.text,s)})}Ht.current=t.target.position()},onTransformEnd:t=>{it(!1),st(!0);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),n.set(Object.assign(Object.assign({},f(n,n.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:_(n.text,e)}))}}),t(a,{ref:U,image:Z,x:n.a.x,y:n.a.y,offsetX:dt,offsetY:dt-Tt,listening:!1,rotation:n.a.rotation,width:n.a.width+2*dt,height:(n.a.width+2*dt)*((null!==(G=null==Z?void 0:Z.height)&&void 0!==G?G:0)/((null==Z?void 0:Z.width)||1)||1),visible:!It&&!yt,opacity:n.a.opacity,shadowEnabled:n.shadowEnabled,shadowBlur:n.shadowBlur,shadowOffsetX:n.shadowOffsetX,shadowOffsetY:n.shadowOffsetY,shadowColor:n.shadowColor,shadowOpacity:n.shadowOpacity,hideInExport:!n.showInExport,editModeEnabled:n._editModeEnabled||nt||It}),(It&&!yt||Vt)&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Tt,children:t(M,{divProps:{style:{pointerEvents:"none"}},children:t(N,{dangerouslySetInnerHTML:{__html:bt},style:{pointerEvents:"none",opacity:n.a.opacity,textShadow:n.shadowEnabled?`${n.shadowOffsetX}px ${n.shadowOffsetY}px ${n.shadowBlur}px ${q(n.shadowColor,null!==(K=n.shadowOpacity)&&void 0!==K?K:1)}`:void 0}})})}),yt&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Tt,children:t(M,{divProps:{style:{zIndex:20}},children:t(J,{element:n,onChange:t=>{const e=T({oldText:Y(n.text),newText:Y(t),element:n});n.set(Object.assign({text:t},c(n,e)))},onBlur:t=>{g(n)&&(n.set(d(n)),n.toggleEditMode(!1),Xt(!0))},clickCoords:qt.current})})})]})});
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 m,Label as h,Layer as u,Line as g,Rect as p,Shape as f,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 _}from"./use-color.js";import{isGradient as Z}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={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){Q[e]=Q[e]||t,Object.assign(Q[e],t)}const q=e=>t(p,Object.assign({},e,{preventDefault:!1})),ee=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(m,Object.assign({image:r},o,s))},te=e=>{const n=_({a:{width:e.width,height:e.height},width:e.width,height:e.height},e.fill);return t(p,Object.assign({},e,n))},ne=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)||Z(r),[r]),m=o.useMemo(()=>{if(Z(r)){return!0}const e=S.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(p,a?Object.assign({fill:a},d,{hideInExport:!0}):Object.assign({fillPatternImage:h},d,{opacity:.1,hideInExport:!0})),c?t(te,Object.assign({fill:r},d)):t(ee,Object.assign({url:r},d))]})},ie=r(({selection:e})=>{const{selectionRectStyle:n}=X();return e.visible?t(p,{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 oe(e){let t=180*e/Math.PI;return t%=360,t>180?t-=360:t<-180&&(t+=360),Math.round(t)}const re=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 m=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),p=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:oe(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:p})]})]})}),le=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 se=null;export const registerNextDomDrop=e=>{se=e};const ae=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),de=atob("I2MwMzkyYg=="),ce=atob("djAuOS4y"),me=e=>t(i,{children:n(h,{fill:de,height:200,children:[t(v,{fill:de}),t(b,Object.assign({},e,{fill:"white",text:ae,height:void 0,padding:10,fontSize:20}))]})}),he=atob("RlJFRSAgVFJJQUwgIExJQ0VOU0U="),ue=(atob("UG93ZXJlZCBieSBQb2xvdG5v"),atob("TElDRU5TRSAgS0VZICBJUyAgTUlTU0lORw==")),ge=atob("UGxlYXNlIGFjdGl2YXRlIHlvdXIgbGljZW5zZS4KTGljZW5zZSByZWxhdGVkIHF1ZXN0aW9uczoKcG9sb3Ruby5jb20vY29udGFjdA=="),pe=e=>{const i=1===j(),o=i?ue:he,r=i?230:195;return n(c,Object.assign({},e,{listening:!1,children:[t(p,{fill:de,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:ge,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:m,components:w,altCloneEnabled:E,groupSelectionMode:S="drill",viewportSize:k,layout:O="vertical",tooltipSafeArea:P,transformerSafeArea:G})=>{var _;const Z=X(),J=Z.transformerStyle,N=$,K=i.computedBleed,ee=e.bleedVisible?K:d,te=i.computedWidth+ee.left+ee.right,oe=i.computedHeight+ee.top+ee.bottom,ae=(r-te*e.scale)/2,de=(a-oe*e.scale)/2,he=o.useRef(null),ue=o.useRef(null),ge=o.useRef(null),fe=o.useRef(null),xe=null==m||m,ve=o.useRef(!1),[be,ye]=o.useState(null),[we,Ee]=o.useState({}),[Xe,Ye]=o.useState(0),Se=useContextMenu({store:e}),ke=e.selectedElements.find(e=>e._cropModeEnabled),Ae=e.selectedElements.find(e=>e.curveEnabled),Me=e.selectedShapes.filter(e=>!e.resizable).length>0,Ie=e.selectedShapes.filter(e=>!e.draggable).length>0,Oe=e.selectedElements.filter(e=>!e.visible).length>0,Pe=e.selectedShapes.filter(e=>!e._cropModeEnabled),Re=1!==e.selectedElements.length||"group"===(null===(_=e.selectedElements[0])||void 0===_?void 0:_.type),je=e=>Re&&Pe.length>0&&Pe.every(t=>((e,t)=>{if(!(e=>{const t=(e%180+180)%180;return t<.1||180-t<.1})(e.rotation)){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)),De=je("x"),Ce=je("y"),Te=()=>{var t,n,i;const o=he.current;if(!o){return[]}const r=o.getStage(),l=e.selectedShapes.map(e=>e._cropModeEnabled?null:r.findOne("#"+e.id)).filter(e=>!!e),s=1===e.selectedElements.length,a=s&&(null===(t=e.selectedElements[0])||void 0===t?void 0:t.type)||"many",d=Q[a],c=Object.assign(Object.assign({},N),d||{});d&&("svg"!==a&&"image"!==a&&"gif"!==a||e.selectedElements[0].keepRatio||(c.enabledAnchors=N.enabledAnchors),"text"===a&&U.textVerticalResizeEnabled&&(c.enabledAnchors=null===(n=Q.text.enabledAnchors)||void 0===n?void 0:n.concat(["bottom-center","top-center"])),"text"===a&&s&&e.selectedElements[0].curveEnabled&&(c.enabledAnchors=Q.many.enabledAnchors)),(De||Ce)&&(c.enabledAnchors=[...c.enabledAnchors||[],...De?["middle-left","middle-right"]:[],...Ce?["top-center","bottom-center"]:[]]),o.setAttrs(Object.assign(Object.assign({},c),J)),Me&&o.enabledAnchors([]),Ie&&o.rotateEnabled(!1);const m=o.nodes();return m.length===l.length&&l.every((e,t)=>m[t]===e)||o.nodes(l),null===(i=o.getLayer())||void 0===i||i.batchDraw(),l};o.useLayoutEffect(()=>{var e;if(null===(e=he.current)||void 0===e?void 0:e.isTransforming()){return}const t=Te();t.find(e=>null==e?void 0:e.isDragging())&&(t.forEach(e=>{e.isDragging()||null==e||e.startDrag()}),M())},[e.selectedShapes,ke,Me,Oe,Ie,Ae,De,Ce,J]);const Be=()=>{var e,t;const n=he.current;if(!n){return}if(!n.isTransforming()){return void Ee({})}if(!n.nodes().length||!n.isTransforming()){return}const i=n.__getNodeRect(),o=null==n?void 0:n.getActiveAnchor(),r=n.getStage();Ee({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})},We=o.useCallback(()=>{var e;if(null===(e=he.current)||void 0===e?void 0:e.isTransforming()){return}const t=he.current;if(!t||!t.nodes().length){return void Ye(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==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)},J.rotateAnchorOffset,t.rotation());Ye(i)},[G,r,a]);o.useEffect(()=>{var e;null===(e=he.current)||void 0===e||e.update(),Be(),We()},[e.scale,We]),o.useEffect(()=>{We()},[e.selectedShapes,We]);const Ge=l(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),Le=o.useRef(!1),Ve=s(t=>{var n,i,o,r,l,s,a;if(e.role===Y.VIEWER){return}Le.current=!1;const d=t.target.findAncestor(".elements-container"),c=t.target.findAncestor("Transformer"),m=t.target.findAncestor(".page-abs-container");if(d||c||m){return}const h=null===(n=t.target.getStage())||void 0===n?void 0:n.getPointerPosition();h&&(h.x-=null!==(o=null===(i=t.target.getStage())||void 0===i?void 0:i.x())&&void 0!==o?o:0,h.y-=null!==(l=null===(r=t.target.getStage())||void 0===r?void 0:r.y())&&void 0!==l?l:0,Ge.visible=!0,Ge.x1=h.x,Ge.y1=h.y,Ge.x2=h.x,Ge.y2=h.y,(null!==(a=null===(s=t.target.getStage())||void 0===s?void 0:s.getPointersPositions().length)&&void 0!==a?a:0)>=2&&(Ge.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:ge,containerRef:fe,viewportSize:k}),o.useEffect(()=>{const t=s(e=>{var t,n,i,o,r,l;if(!Ge.visible){return}null===(t=ge.current)||void 0===t||t.setPointersPositions(e);let s=null===(n=ge.current)||void 0===n?void 0:n.getPointerPosition();s?(s.x-=null!==(o=null===(i=ge.current)||void 0===i?void 0:i.x())&&void 0!==o?o:0,s.y-=null!==(l=null===(r=ge.current)||void 0===r?void 0:r.y())&&void 0!==l?l:0):s={x:Ge.x2,y:Ge.y2},Ge.x2=s.x,Ge.y2=s.y}),n=s(()=>{if(!Ge.visible){return}if(!ge.current){return}const t=ge.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=[];ge.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)];Le.current=!0,e.selectElements(o)}Ge.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 Fe=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(be)!==JSON.stringify(l)&&ye(l)},[e,i]);o.useEffect(()=>{e.selectedElements[0]&&e.distanceGuidesVisible?Fe():be&&ye(null)},[e.distanceGuidesVisible,Fe,e.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const ze=o.useRef(!1);o.useEffect(()=>{var e;let t;const n=null===(e=fe.current)||void 0===e?void 0:e.closest(".polotno-workspace-inner"),i=()=>{ze.current=!0,clearTimeout(t),t=setTimeout(()=>{ze.current=!1},300)};return null==n||n.addEventListener("scroll",i),()=>{clearTimeout(t),null==n||n.removeEventListener("scroll",i)}},[]),o.useEffect(()=>{const t=ge.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=he.current)||void 0===n?void 0:n.isDragging())&&he.current.stopDrag(),null===(o=he.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 Ue=t=>{if(e.role===Y.VIEWER){return}if(e.activePage!==i&&i.select(),ze.current){return}if(Le.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||Ge.visible)){return e.selectElements([]),void e.selectPages([])}if(o&&!n){const t=ge.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),m=(null==c?void 0:c.findOne(".element"))||t.target.findAncestor(".element",!0),h=e.getElementById(null==m?void 0:m.id()),u=null==h?void 0:h.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==h?void 0:h.id:null==u?void 0:u.id}else{g=void 0}const p=null==h?void 0:h.id;if(p&&e.selectedElementsIds.indexOf(p)>=0&&!n){return}const f=!!g&&e.selectedElementsIds.indexOf(g)>=0,x=t.target.findAncestor(".page-container",!0);if(g&&n&&!f){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&&f?e.selectElements(e.selectedElementsIds.filter(e=>e!==g)):!g||n||f?g&&!n&&f||(x?(n||e.selectElements([]),e.selectPages([i.id])):e.selectPages([])):(e.selectElements([g]),e.selectPages([]))}};I(he,e);const _e=e.activePage===i,Ze=e._selectedPagesIds.includes(i.id),He=null==w?void 0:w.PageControls,Je=null==w?void 0:w.Tooltip,Ne=null==w?void 0:w.ContextMenu,Ke=1/e.scale,$e=0/e.scale;return n("div",{ref:fe,onDragOver:e=>e.preventDefault(),onDrop:t=>{if(t.preventDefault(),e.role===Y.VIEWER){return}if(!ge.current){return}ge.current.setPointersPositions(t);const n=ge.current.findOne(".elements-container"),o=null==n?void 0:n.getRelativePointerPosition(),r=ge.current.getPointerPosition(),l=ge.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];se&&o&&(se(o,a,{elements:s,page:i}),se=null)},style:{position:"relative",width:r+"px",height:a+"px",overflow:"hidden",flexShrink:0},className:"polotno-page-container"+(_e?" active-page":""),children:[t(x,{ref:ge,width:Math.min(r,k.width+200),height:Math.min(k.height+200,a),onClick:Ue,onTap:Ue,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 Se.close()}e.selectedElementsIds.indexOf(r)>=0||e.selectElements([r]),Se.open({x:t.evt.clientX,y:t.evt.clientY})},onMouseDown:Ve,onMouseMove:t=>{if(!e.distanceGuidesVisible&&!t.evt.altKey){return void(be&&ye(null))}const n=t.target.findAncestor(".element",!0),i=null==n?void 0:n.id();Fe(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=Te();t.target.stopDrag(),i.forEach(e=>{e.isDragging()||e.startDrag(t)}),null===(n=he.current)||void 0===n||n.startDrag(t),M()}}be&&ye(null)},pageId:i.id,style:{position:"absolute",overflow:"hidden",top:0,left:0},children:n(u,{children:[t(q,{width:r,height:a,fill:Z.workspaceBackgroundColor}),t(c,{x:ae,y:de,scaleX:e.scale,scaleY:e.scale,name:"page-container",children:n(c,{name:"page-container-2",children:[t(c,{name:"page-background-group",x:ee.left,y:ee.top,children:t(ne,{x:-K.left,y:-K.top,width:i.computedWidth+K.left+K.right,height:i.computedHeight+K.top+K.bottom,background:i.background,transparencyBackgroundColor:Z.transparencyBackgroundColor,name:"page-background",preventDefault:!1,scale:e.scale})}),n(c,{x:ee.left,y:ee.top,name:"elements-container",listening:!e.isPlaying&&e.role!==Y.VIEWER,children:[t(p,{name:"elements-area",width:i.computedWidth,height:i.computedHeight,listening:!1}),t(le,{elements:i.children,store:e})]}),t(f,{name:"bleed",fill:Z.bleedColor,listening:!1,visible:e.bleedVisible&&(ee.top>0||ee.right>0||ee.bottom>0||ee.left>0),hideInExport:!0,sceneFunc:(e,t)=>{const{top:n,right:o,bottom:r,left:l}=K,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()===ce&&t(me,{name:"hit-detection",x:-Ke/2-$e,y:-Ke/2-$e,width:te+Ke+2*$e,height:oe+Ke+2*$e})]})}),t(g,{name:"workspace-background",points:[0,0,r,0,r,a,0,a,0,0,ae,de,ae,a-de,r-ae,a-de,r-ae,de,ae,de],listening:!1,closed:!0,fill:Z.workspaceBackgroundColor}),t(c,{x:ae,y:de,scaleX:e.scale,scaleY:e.scale,children:t(p,{name:"page-highlight",hideInExport:!0,x:-Ke/2-$e,y:-Ke/2-$e,width:te+Ke+2*$e,height:oe+Ke+2*$e,stroke:Ze?Z.activePageBorderColor:Z.pageBorderColor,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})}),n(c,{x:ae+ee.left*e.scale,y:de+ee.top*e.scale,scaleX:e.scale,scaleY:e.scale,name:"page-abs-container",children:[t(y,{ref:he,rotateAnchorAngle:Xe,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)}),ve.current||(ve.current=!0,e.history.startTransaction()))},onDragEnd:()=>{ve.current&&(e.history.endTransaction(),ve.current=!1),We()},onTransformStart:()=>{e.history.startTransaction(),ue.current=new Map(Pe.map(e=>[e.id,{width:e.width,height:e.height}])),ye(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,d.x=t.x),a<e.minHeight&&(d.height=t.height,d.y=t.y),d}}return Re&&Pe.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,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?F(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"),p=u||c("y"),f=p||!d&&g;return(g||!d&&p)&&(m.width=e.width,m.x=e.x),f&&(m.height=e.height,m.y=e.y),m})(t,n,(null===(o=he.current)||void 0===o?void 0:o.getActiveAnchor())||"",Pe,ue.current):n},onTransform:e=>{const t=he.current.nodes(),n=t[t.length-1];e.target===n&&setTimeout(()=>{Be()},0)},onTransformEnd:t=>{Ee({}),e.history.endTransaction(),ue.current=null,We(),Te()},visible:!e.isPlaying}),be&&be.map(({points:i,distance:o,box1:r,box2:l},s)=>n(c,{name:"distances-container",hideInExport:!0,listening:!1,children:[t(p,Object.assign({},r,{stroke:Z.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(p,Object.assign({},l,{stroke:Z.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(g,{points:[i[0].x,i[0].y,i[1].x,i[1].y],stroke:Z.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),t(g,{points:[i[1].x,i[1].y,i[2].x,i[2].y],stroke:Z.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),n(h,{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:Z.distanceGuideStyle.labelFill,pointerDirection:"down"}),t(b,{align:"center",verticalAlign:"middle",fill:Z.distanceGuideStyle.labelTextFill,padding:5,text:L({unit:e.unit,dpi:e.dpi,px:o})})]})]},s)),i._rendering&&n(c,{children:[t(p,{width:te,height:oe,fill:"rgba(255,255,255,0.9)"}),t(b,{text:"Rendering...",fontSize:60,width:te,height:oe,align:"center",verticalAlign:"middle"})]}),Je&&t(Je,{components:w,store:e,page:i,stageRef:ge,tooltipSafeArea:P}),Ne&&t(H,{children:t(Ne,Object.assign({components:w,store:e},Se.props))})]}),t(A,{store:e,page:i,width:r,height:a,scale:e.scale,xPadding:ae,yPadding:de,bleedLeft:ee.left,bleedTop:ee.top}),t(re,Object.assign({},we,{store:e})),t(ie,{selection:Ge}),j()>0&&n(c,{hideInExport:!0,children:[t(pe,{name:"cache-bounds",x:r-(1===j()?250:210),y:a-(1===j()?95:45)}),t(pe,{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"})]})}),xe&&He&&t(He,{store:e,page:i,xPadding:ae,yPadding:de,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 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=Ge("x"),Ve=Ge("y"),Fe=()=>{var t,n,i;const o=xe.current;if(!o){return[]}const r=o.getStage(),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)),(Le||Ve)&&(h.enabledAnchors=[...h.enabledAnchors||[],...Le?["middle-left","middle-right"]:[],...Ve?["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=Fe();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,Le,Ve,We,N]);const ze=()=>{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})},Ue=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(),ze(),Ue()},[e.scale,Ue]),o.useEffect(()=>{Ue()},[e.selectedShapes,Ue]);const Ze=l(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),_e=o.useRef(!1),He=s(t=>{var n,i,o,r,l,s,a;if(e.role===Y.VIEWER){return}_e.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,Ze.visible=!0,Ze.x1=m.x,Ze.y1=m.y,Ze.x2=m.x,Ze.y2=m.y,(null!==(a=null===(s=t.target.getStage())||void 0===s?void 0:s.getPointersPositions().length)&&void 0!==a?a:0)>=2&&(Ze.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(!Ze.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:Ze.x2,y:Ze.y2},Ze.x2=s.x,Ze.y2=s.y}),n=s(()=>{if(!Ze.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)];_e.current=!0,e.selectElements(o)}Ze.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 Je=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?Je():Ye&&Se(null)},[e.distanceGuidesVisible,Je,e.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const Ne=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=()=>{Ne.current=!0,clearTimeout(t),t=setTimeout(()=>{Ne.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 Ke=t=>{if(e.role===Y.VIEWER){return}if(e.activePage!==i&&i.select(),Ne.current){return}if(_e.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||Ze.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 $e=e.activePage===i,Qe=e._selectedPagesIds.includes(i.id),qe=null==w?void 0:w.PageControls,et=null==w?void 0:w.Tooltip,tt=null==w?void 0:w.ContextMenu,nt=1/e.scale,it=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"+($e?" active-page":""),children:[t(x,{ref:ye,width:Math.min(r,k.width+200),height:Math.min(k.height+200,a),onClick:Ke,onTap:Ke,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:He,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();Je(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=Fe();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:-nt/2-it,y:-nt/2-it,width:ae+nt+2*it,height:me+nt+2*it})]})}),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:-nt/2-it,y:-nt/2-it,width:ae+nt+2*it,height:me+nt+2*it,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),Ue()},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(()=>{ze()},0)},onTransformEnd:t=>{Ae({}),e.history.endTransaction(),ve.current=null,Ue(),Fe()},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"})]}),et&&t(et,{components:w,store:e,page:i,stageRef:ye,tooltipSafeArea:P}),tt&&t(H,{children:t(tt,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:Ze}),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&&qe&&t(qe,{store:e,page:i,xPadding:ue,yPadding:pe,layout:O})]})});
@@ -1 +1 @@
1
- import t from"quill";import{firstStopColor as e}from"@polotno/core/gradient";let r=!1;const o=["background-image","background-size","-webkit-background-clip","background-clip","-webkit-text-fill-color","color"];export function registerQuillUnrestrictedFontFormats(){if(r){return}r=!0;const i=t.import("attributors/style/size"),l=t.import("attributors/style/font");i&&(delete i.whitelist,t.register(i,!0)),l&&(delete l.whitelist,t.register(l,!0));const n=t.import("parchment");if((null==n?void 0:n.StyleAttributor)&&(null==n?void 0:n.Scope)){const r=new n.StyleAttributor("font-weight","font-weight",{scope:n.Scope.INLINE});t.register(r,!0),t.register(function(t){class r extends t.StyleAttributor{constructor(t,e,r){super(t,e,r)}add(t,r){if("string"!=typeof r||!r.includes("gradient")){return!1}t.style.setProperty("background-image",r),t.style.setProperty("background-size","100% 100%"),t.style.setProperty("-webkit-background-clip","text"),t.style.setProperty("background-clip","text"),t.style.setProperty("-webkit-text-fill-color","transparent");try{t.style.setProperty("color",e(r))}catch(o){}return!0}remove(t){for(const e of o){t.style.removeProperty(e)}}value(t){const e=t.style.getPropertyValue("-webkit-background-clip")||t.style.getPropertyValue("background-clip"),r=t.style.getPropertyValue("background-image");return"text"===e&&r.includes("gradient")?r:""}}return new r("gradient","background-image",{scope:t.Scope.INLINE})}(n),!0)}}
1
+ import t from"quill";import{firstStopColor as e}from"@polotno/core/gradient";import{isClipGradientSpan as r}from"../utils/rich-text-html.js";let o=!1;const i=["background-image","background-size","-webkit-background-clip","background-clip","-webkit-text-fill-color","color"];export function registerQuillUnrestrictedFontFormats(){if(o){return}o=!0;const s=t.import("attributors/style/size"),l=t.import("attributors/style/font");s&&(delete s.whitelist,t.register(s,!0)),l&&(delete l.whitelist,t.register(l,!0));const n=t.import("parchment");if((null==n?void 0:n.StyleAttributor)&&(null==n?void 0:n.Scope)){const o=new n.StyleAttributor("font-weight","font-weight",{scope:n.Scope.INLINE});t.register(o,!0),t.register(function(t){class o extends t.StyleAttributor{constructor(t,e,r){super(t,e,r)}add(t,r){if("string"!=typeof r||!r.includes("gradient")){return!1}t.style.setProperty("background-image",r),t.style.setProperty("background-size","100% 100%"),t.style.setProperty("-webkit-background-clip","text"),t.style.setProperty("background-clip","text"),t.style.setProperty("-webkit-text-fill-color","transparent");try{t.style.setProperty("color",e(r))}catch(o){}return!0}remove(t){for(const e of i){t.style.removeProperty(e)}}value(t){return r(t)?t.style.getPropertyValue("background-image"):""}}return new o("gradient","background-image",{scope:t.Scope.INLINE})}(n),!0);const s=t.import("attributors/style/color");if(s){const e=s.value.bind(s);s.value=t=>r(t)?"":e(t),t.register(s,!0)}}}
@@ -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 f}from"react-konva-utils";import{layout as u,drawLayout as g}from"render-tag";import{layoutTextOnPath as m,drawTextOnPathLayout as x}from"render-tag/path";import{scaledFontSizeAttrs as p,roundedFontSizeAttrs as y,roundedTextDecorationAttrs as b,textMinResizeWidth as w}from"../utils/px.js";import{flags as v}from"../utils/flags.js";import{applyFilter as O}from"./apply-filters.js";import{getLineHeight as E,usePrevious as S}from"./text-element.js";import{useFontSpecsLoader as j}from"./text-element/font-specs-loader.js";import{getHtml as M,getCurvePath as z,getCurveTextHeight as k}from"@polotno/core/text-html";import{useColor as R}from"./use-color.js";import{isGradient as Y}from"@polotno/core/gradient";import{detectSize as X}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as T}from"./use-fadein.js";import{incrementLoader as I}from"../utils/loader.js";import{removeTags as P}from"@polotno/core/text";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as B}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as A,extractFontSpecsFromHtml as W,scaleRichTextFontSizesInHtml as D}from"../utils/rich-text-html.js";import{RichEditor as J}from"./rich-editor.js";import{findFitFontSize as N}from"./text-element/fit-font-size.js";import{wrapHtmlForRenderTag as $}from"@polotno/core/reset-style";import{xmlEscape as _}from"@polotno/core/xml";export{$ as wrapHtmlForRenderTag};export const RenderTagElement=i(({element:i,store:L})=>{var H;const V=n.useRef(null),q=n.useRef(null),[G,K]=n.useState(!1),Q=n.useRef(i.height),U=i.isSelected,Z=S(U),{textVerticalResizeEnabled:tt}=v,et=v.autoDeleteEmptyText,rt=S(i.fontFamily),ot=n.useMemo(()=>A(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),nt=n.useMemo(()=>W(ot,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[ot,i.fontFamily,i.fontWeight,i.fontStyle]),[it]=j(L,nt,i.text||i.placeholder),at=i._editModeEnabled;T(V);const st=it?i.fontFamily:rt&&rt!==i.fontFamily?rt:"Arial",lt=R(i).fill,ct=Y(i.fill),ht=Y(i.stroke)&&!!i.strokeWidth,dt=!!i.strokeWidth&&(ht||ct),ft="ellipsis"===v.textOverflow&&!i.curveEnabled&&!!i.height&&!dt,ut=!P(i.text)&&!!i.placeholder,gt=ut?_(i.placeholder):i.text,mt=ut?.6:i.a.opacity,xt=M(ut?Object.assign(Object.assign({},i.toJSON()),{text:gt}):i,{fontFamily:st,color:lt,forEditor:!ft,textOverflow:v.textOverflow}),pt=i.width||1,yt=i.curveEnabled,bt=function(t,e,r,o){return n.useMemo(()=>{if(o){return null}try{return u({html:$(t),width:Math.max(1,e),accuracy:"performance"})}catch(r){return console.error("render-tag layout failed:",r),null}},[t,e,r,o])}(xt,pt,it,yt),wt=function(t,e,r){return n.useMemo(()=>{if(!e.curveEnabled){return null}const r=e.width||1,o=k(e),n=z(r,o,e.curvePower,e.fontSize);try{return m({html:$(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])}(xt,i,it),vt=E({fontLoaded:it,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),Ot=yt?0:Math.max(null!==(H=null==bt?void 0:bt.height)&&void 0!==H?H:0,i.fontSize*vt),Et=wt?wt.bounds:null,St=n.useMemo(()=>bt?bt.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})):[],[bt]),jt=n.useRef([]),Mt=n.useRef(!0),[,zt]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=jt.current;t.length>0&&(jt.current=[],t.forEach(t=>t()))});const kt=n.useCallback((t,e,r,o)=>{const n=I(`text ${i.id}`),a=()=>{L.history.ignore(t,e,r).then(()=>{Mt.current?(jt.current.push(n),zt()):n()})};o?queueMicrotask(a):a()},[i.id,L]);n.useEffect(()=>{if(!it){return}if(!bt){return}if(!i.height){return void kt(()=>{d(i)&&(i.height||i.set({height:Ot}))},void 0,void 0,!0)}if(L.isPlaying){return}const{textOverflow:t}=v,e=i.height!==Ot&&(!tt||i.height<Ot),r=()=>kt(()=>{d(i)&&i.set({height:Ot})},!1,!0);if("change-font-size"!==t||G||at||i.curveEnabled){"resize"===t&&e&&!G&&r()}else{const t=N(ut?Object.assign(Object.assign({},i.toJSON()),{text:gt,toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:gt})}):i,{fontFamily:st,color:lt,forEditor:!0},t=>{try{return u({html:$(t),width:pt,accuracy:"performance"}).height}catch(H){return X(t).height}});t.fontSize!==i.fontSize?kt(()=>{if(!d(i)){return}const e=p(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&r()}}),n.useEffect(()=>()=>{Mt.current=!1;const t=jt.current;t.length>0&&(jt.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!it||!i.curveEnabled||G){return}if(!Et||!Et.width){return}const t=t=>t&&tt?Math.max(t,Et.height):Et.height;Math.abs(Et.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||kt(()=>{if(!d(i)){return}const e=Et.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:Et.width,height:r,x:i.a.x+a,y:i.a.y+s})},!1,!0,!0)},[it,i.curveEnabled,Et,G,tt,kt]),n.useEffect(()=>{Z&&!U&&et&&""===P(i.text)&&i.removable&&!i.placeholder&&L.deleteElements([i.id])},[et,i.placeholder,i.removable,i.text,U,Z]),n.useEffect(()=>h(i,()=>{const t=V.current;t&&O(t,i)}),[bt,wt,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);let Rt=0;yt||"middle"!==i.verticalAlign?yt||"bottom"!==i.verticalAlign||(Rt=i.height-Ot):Rt=(i.height-Ot)/2;const Yt=i.backgroundPadding*(i.fontSize*vt*.5),Xt=i.backgroundCornerRadius*(i.fontSize*vt*.5),Ft=n.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===St.length?"":F({rects:St,padding:Yt,cornerRadius:Xt}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,St,Yt,Xt]),Tt=C(),It=n.useRef(null),Pt=n.useRef(i.width),Ct=n.useRef(null),Bt=n.useRef(null),At=n.useRef(null),Wt=n.useRef(0),Dt=n.useRef(0),Jt=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:Yt/Jt,offsetY:Yt/Jt,rotation:i.a.rotation,scaleX:Jt,scaleY:Jt,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*mt,fill:i.backgroundColor,width:i.width+2*Yt,height:i.height+2*Yt,cornerRadius:Xt}):e(s,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-Rt/Jt,rotation:i.a.rotation,scaleX:Jt,scaleY:Jt,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&Ft.length>0,opacity:i.backgroundOpacity*mt,fill:i.backgroundColor,data:Ft}),e(c,{ref:V,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:Jt,scaleY:Jt,offsetY:Jt>0?-Rt/Jt:0,width:i.width,height:Math.max(i.height,Ot),listening:!1,visible:!at&&!!(yt?wt:bt),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(yt){if(!wt||!Et){return}const t=(i.width-Et.width)/2-Et.x;r.save(),r.translate(t,-Et.y),x({layout:wt,ctx:r}),r.restore()}else{if(!bt){return}g({layout:bt,width:pt,ctx:r,pixelRatio:1})}}catch(o){console.error("render-tag draw failed:",o)}}}}),e(l,{ref:q,name:"element",x:i.a.x,y:i.a.y,listening:i.selectable,rotation:i.a.rotation,width:i.a.width,height:i.a.height,visible:!at,draggable:Tt?i.draggable&&U:i.draggable,preventDefault:!Tt||U,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&&(Bt.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];Bt.current=r?{x:r.clientX,y:r.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{var e,r;K(!0),Q.current=i.height,Pt.current=i.width,Ct.current=null,It.current=t.target.position();const o=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");At.current=null!==(r=null==o?void 0:o.getActiveAnchor())&&void 0!==r?r:null,Wt.current=i.a.rotation,Dt.current=i.height},onTransform:e=>{var r;const o=e.target,n=(null===(r=o.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor(),a="middle-left"===n||"middle-right"===n,s="top-center"===n||"bottom-center"===n,l=o.scaleX();if(a){const e=o.scaleX(),n=o.width()*e;let a=Math.max(n,w(Pt.current,i.fontSize));const s=i.toJSON();let l=0;if(i.curveEnabled){l=k(Object.assign(Object.assign({},s),{width:a}))}else{const{x:e,y:o,width:n,height:i}=s,c=t(s,["x","y","width","height"]),h=`${JSON.stringify(c)}|${st}|${it}|${lt}`;if(Ct.current&&Ct.current.signature===h&&a<=Ct.current.width){a=Ct.current.width,l=Ct.current.height}else{const t=t=>{const e=M(Object.assign(Object.assign({},s),{text:gt,width:t}),{fontFamily:st,color:lt,forEditor:!0});try{return u({html:$(e),width:t,accuracy:"performance"})}catch(r){return{height:X(e).height,lines:[]}}};let e=t(a);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width));o>a+.5&&o<=Pt.current+.5&&(a=Math.min(Math.ceil(o),Pt.current),e=t(a),Ct.current={signature:h,width:a,height:e.height}),l=e.height}}a>n&&It.current&&o.position(It.current),o.width(a),o.scaleX(1),o.scaleY(1);let c=v.textVerticalResizeEnabled?Math.max(l,Q.current):l;"ellipsis"===v.textOverflow&&(c=Q.current),o.height(c),i.set({width:o.width(),height:c,x:o.x(),y:o.y()})}else if(s){const t="resize"===v.textOverflow?yt?(null==Et?void 0:Et.height)||i.fontSize:Ot:vt*i.fontSize,e=o.height()*o.scaleY();if(e<t){if(o.height(t),It.current){if("top-center"===At.current){const e=Wt.current*Math.PI/180,r=Dt.current-t;o.x(It.current.x-r*Math.sin(e)),o.y(It.current.y+r*Math.cos(e))}else{o.position(It.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Dt.current=Math.max(t,e),i.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),i.set({fontSize:i.fontSize*l,letterSpacing:i.letterSpacing,width:o.width()*l,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*l,shadowBlur:i.shadowBlur*l,shadowOffsetX:i.shadowOffsetX*l,shadowOffsetY:i.shadowOffsetY*l,strokeWidth:i.strokeWidth*l,text:D(i.text,l)})}It.current=e.target.position()},onTransformEnd:t=>{K(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},y(i,i.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:D(i.text,e)}))}}),at&&e(a,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-Rt,children:e(f,{divProps:{style:{zIndex:20}},children:e(J,{element:i,onChange:t=>{const e=B({oldText:P(i.text),newText:P(t),element:i});i.set(Object.assign({text:t},p(i,e)))},onBlur:()=>{d(i)&&(i.set(b(i)),i.toggleEditMode(!1))},clickCoords:Bt.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 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 f}from"react-konva-utils";import{layout as u,drawLayout as g}from"render-tag";import{layoutTextOnPath as m,drawTextOnPathLayout as x}from"render-tag/path";import{scaledFontSizeAttrs as p,roundedFontSizeAttrs as y,roundedTextDecorationAttrs as b,textMinResizeWidth as w}from"../utils/px.js";import{flags as v}from"../utils/flags.js";import{applyFilter as O}from"./apply-filters.js";import{getLineHeight as E,usePrevious as S}from"./text-element.js";import{useFontSpecsLoader as j}from"./text-element/font-specs-loader.js";import{getHtml as M,getCurvePath as z,getCurveTextHeight as k}from"@polotno/core/text-html";import{useColor as R}from"./use-color.js";import{isGradient as Y}from"@polotno/core/gradient";import{detectSize as X}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as T}from"./use-fadein.js";import{incrementLoader as I}from"../utils/loader.js";import{removeTags as P}from"@polotno/core/text";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as B}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as A,extractFontSpecsFromHtml as W,scaleRichTextFontSizesInHtml as D}from"../utils/rich-text-html.js";import{RichEditor as J}from"./rich-editor.js";import{findFitFontSize as N}from"./text-element/fit-font-size.js";import{visiblePlaceholder as $}from"./text-element/placeholder.js";import{wrapHtmlForRenderTag as _}from"@polotno/core/reset-style";import{xmlEscape as L}from"@polotno/core/xml";import{hasMeasuredHeight as H,resolveTextBoxHeight as V}from"@polotno/core/text-types";export{_ as wrapHtmlForRenderTag};export const RenderTagElement=i(({element:i,store:q})=>{var G;const K=n.useRef(null),Q=n.useRef(null),[U,Z]=n.useState(!1),tt=n.useRef(i.height),et=i.isSelected,rt=S(et),{textVerticalResizeEnabled:ot}=v,nt=v.autoDeleteEmptyText,it=S(i.fontFamily),at=n.useMemo(()=>A(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),st=n.useMemo(()=>W(at,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[at,i.fontFamily,i.fontWeight,i.fontStyle]),[lt]=j(q,st,i.text||i.placeholder),ct=i._editModeEnabled;T(K);const ht=lt?i.fontFamily:it&&it!==i.fontFamily?it:"Arial",dt=R(i).fill,ft=Y(i.fill),ut=Y(i.stroke)&&!!i.strokeWidth,gt=!!i.strokeWidth&&(ut||ft),mt="ellipsis"===v.textOverflow&&!i.curveEnabled&&H(i)&&!gt,xt=$(i.placeholder),pt=!P(i.text)&&!!xt,yt=pt?L(xt):i.text,bt=pt?.6:i.a.opacity,wt=M(pt?Object.assign(Object.assign({},i.toJSON()),{text:yt}):i,{fontFamily:ht,color:dt,forEditor:!mt,textOverflow:v.textOverflow}),vt=i.width||1,Ot=i.curveEnabled,Et=function(t,e,r,o){return n.useMemo(()=>{if(o){return null}try{return u({html:_(t),width:Math.max(1,e),accuracy:"performance"})}catch(r){return console.error("render-tag layout failed:",r),null}},[t,e,r,o])}(wt,vt,lt,Ot),St=function(t,e,r){return n.useMemo(()=>{if(!e.curveEnabled){return null}const r=e.width||1,o=k(e),n=z(r,o,e.curvePower,e.fontSize);try{return m({html:_(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])}(wt,i,lt),jt=E({fontLoaded:lt,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),Mt=Ot?0:Math.max(null!==(G=null==Et?void 0:Et.height)&&void 0!==G?G:0,i.fontSize*jt),zt=St?St.bounds:null,kt=n.useMemo(()=>Et?Et.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})):[],[Et]),Rt=n.useRef([]),Yt=n.useRef(!0),[,Xt]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=Rt.current;t.length>0&&(Rt.current=[],t.forEach(t=>t()))});const Ft=n.useCallback((t,e,r,o)=>{const n=I(`text ${i.id}`),a=()=>{q.history.ignore(t,e,r).then(()=>{Yt.current?(Rt.current.push(n),Xt()):n()})};o?queueMicrotask(a):a()},[i.id,q]);n.useEffect(()=>{if(!lt){return}if(!Et){return}if(!H(i)){return void Ft(()=>{d(i)&&(H(i)||i.set({height:Mt}))},void 0,void 0,!0)}if(q.isPlaying){return}const{textOverflow:t}=v,e=i.height!==Mt&&(!ot||i.height<Mt),r=()=>Ft(()=>{d(i)&&i.set({height:Mt})},!1,!0);if("change-font-size"!==t||U||ct||i.curveEnabled){"resize"===t&&e&&!U&&r()}else{const t=N(pt?Object.assign(Object.assign({},i.toJSON()),{text:yt,toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:yt})}):i,{fontFamily:ht,color:dt,forEditor:!0},t=>{try{return u({html:_(t),width:vt,accuracy:"performance"}).height}catch(G){return X(t).height}});t.fontSize!==i.fontSize?Ft(()=>{if(!d(i)){return}const e=p(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&r()}}),n.useEffect(()=>()=>{Yt.current=!1;const t=Rt.current;t.length>0&&(Rt.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!lt||!i.curveEnabled||U){return}if(!zt||!zt.width){return}const t=t=>t&&ot?Math.max(t,zt.height):zt.height;Math.abs(zt.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||Ft(()=>{if(!d(i)){return}const e=zt.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:zt.width,height:r,x:i.a.x+a,y:i.a.y+s})},!1,!0,!0)},[lt,i.curveEnabled,zt,U,ot,Ft]),n.useEffect(()=>{rt&&!et&&nt&&""===P(i.text)&&i.removable&&!$(i.placeholder)&&q.deleteElements([i.id])},[nt,i.placeholder,i.removable,i.text,et,rt]),n.useEffect(()=>h(i,()=>{const t=K.current;t&&O(t,i)}),[Et,St,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);const Tt=V(i,Mt);let It=0;Ot||"middle"!==i.verticalAlign?Ot||"bottom"!==i.verticalAlign||(It=Tt-Mt):It=(Tt-Mt)/2;const Pt=i.backgroundPadding*(i.fontSize*jt*.5),Ct=i.backgroundCornerRadius*(i.fontSize*jt*.5),Bt=n.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===kt.length?"":F({rects:kt,padding:Pt,cornerRadius:Ct}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,kt,Pt,Ct]),At=C(),Wt=n.useRef(null),Dt=n.useRef(i.width),Jt=n.useRef(null),Nt=n.useRef(null),$t=n.useRef(null),_t=n.useRef(0),Lt=n.useRef(0),Ht=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:Pt/Ht,offsetY:Pt/Ht,rotation:i.a.rotation,scaleX:Ht,scaleY:Ht,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*bt,fill:i.backgroundColor,width:i.width+2*Pt,height:Tt+2*Pt,cornerRadius:Ct}):e(s,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-It/Ht,rotation:i.a.rotation,scaleX:Ht,scaleY:Ht,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&Bt.length>0,opacity:i.backgroundOpacity*bt,fill:i.backgroundColor,data:Bt}),e(c,{ref:K,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:Ht,scaleY:Ht,offsetY:Ht>0?-It/Ht:0,width:i.width,height:Math.max(i.height,Mt),listening:!1,visible:!ct&&!!(Ot?St:Et),opacity:bt,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(Ot){if(!St||!zt){return}const t=(i.width-zt.width)/2-zt.x;r.save(),r.translate(t,-zt.y),x({layout:St,ctx:r}),r.restore()}else{if(!Et){return}g({layout:Et,width:vt,ctx:r,pixelRatio:1})}}catch(o){console.error("render-tag draw failed:",o)}}}}),e(l,{ref:Q,name:"element",x:i.a.x,y:i.a.y,listening:i.selectable,rotation:i.a.rotation,width:i.a.width,height:i.a.height,visible:!ct,draggable:At?i.draggable&&et:i.draggable,preventDefault:!At||et,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&&(Nt.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];Nt.current=r?{x:r.clientX,y:r.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{var e,r;Z(!0),tt.current=i.height,Dt.current=i.width,Jt.current=null,Wt.current=t.target.position();const o=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");$t.current=null!==(r=null==o?void 0:o.getActiveAnchor())&&void 0!==r?r:null,_t.current=i.a.rotation,Lt.current=i.height},onTransform:e=>{var r;const o=e.target,n=(null===(r=o.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor(),a="middle-left"===n||"middle-right"===n,s="top-center"===n||"bottom-center"===n,l=o.scaleX();if(a){const e=o.scaleX(),n=o.width()*e;let a=Math.max(n,w(Dt.current,i.fontSize));const s=i.toJSON();let l=0;if(i.curveEnabled){l=k(Object.assign(Object.assign({},s),{width:a}))}else{const{x:e,y:o,width:n,height:i}=s,c=t(s,["x","y","width","height"]),h=`${JSON.stringify(c)}|${ht}|${lt}|${dt}`;if(Jt.current&&Jt.current.signature===h&&a<=Jt.current.width){a=Jt.current.width,l=Jt.current.height}else{const t=t=>{const e=M(Object.assign(Object.assign({},s),{text:yt,width:t}),{fontFamily:ht,color:dt,forEditor:!0});try{return u({html:_(e),width:t,accuracy:"performance"})}catch(r){return{height:X(e).height,lines:[]}}};let e=t(a);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width));o>a+.5&&o<=Dt.current+.5&&(a=Math.min(Math.ceil(o),Dt.current),e=t(a),Jt.current={signature:h,width:a,height:e.height}),l=e.height}}a>n&&Wt.current&&o.position(Wt.current),o.width(a),o.scaleX(1),o.scaleY(1);let c=v.textVerticalResizeEnabled?Math.max(l,tt.current):l;"ellipsis"===v.textOverflow&&(c=tt.current),o.height(c),i.set({width:o.width(),height:c,x:o.x(),y:o.y()})}else if(s){const t="resize"===v.textOverflow?Ot?(null==zt?void 0:zt.height)||i.fontSize:Mt:jt*i.fontSize,e=o.height()*o.scaleY();if(e<t){if(o.height(t),Wt.current){if("top-center"===$t.current){const e=_t.current*Math.PI/180,r=Lt.current-t;o.x(Wt.current.x-r*Math.sin(e)),o.y(Wt.current.y+r*Math.cos(e))}else{o.position(Wt.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Lt.current=Math.max(t,e),i.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),i.set({fontSize:i.fontSize*l,letterSpacing:i.letterSpacing,width:o.width()*l,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*l,shadowBlur:i.shadowBlur*l,shadowOffsetX:i.shadowOffsetX*l,shadowOffsetY:i.shadowOffsetY*l,strokeWidth:i.strokeWidth*l,text:D(i.text,l)})}Wt.current=e.target.position()},onTransformEnd:t=>{Z(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},y(i,i.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:D(i.text,e)}))}}),ct&&e(a,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-It,children:e(f,{divProps:{style:{zIndex:20}},children:e(J,{element:i,onChange:t=>{const e=B({oldText:P(i.text),newText:P(t),element:i});i.set(Object.assign({text:t},p(i,e)))},onBlur:()=>{d(i)&&(i.set(b(i)),i.toggleEditMode(!1))},clickCoords:Nt.current})})})]})});
@@ -1,4 +1,4 @@
1
- var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}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 d,isQuillFormatMixed as c,isBoldWeight as u}from"../utils/rich-text-html.js";import{resetStyleContent as f,wrapHtmlForRenderTag as p}from"@polotno/core/reset-style";import{layout as h}from"render-tag";import{removeTags as m}from"@polotno/core/text";import{isGradient as g,firstStopColor as b}from"@polotno/core/gradient";import{getOptimalCaretColor as v}from"./text-element/caret-color.js";import{registerQuillUnrestrictedFontFormats as x}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as y,setActiveTextEditor as w,updateActiveTextFormat as S,clearActiveTextEditor as k}from"../utils/text-format-state.js";import q from"../utils/styled.js";import{applyOpacityToColor as T}from"@polotno/core/svg";export{T as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},lastSelection:null,pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const E=y;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of E){c(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),S(o,n,e)}const C="polotno-saved-selection";function F(){const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const e=t.getRangeAt(0).cloneRange();CSS.highlights.set(C,new Highlight(e)),L()}function R(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(C)}function L(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(C)&&(document.querySelector(".polotno-portal")||P(document.activeElement)?L():R())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const A=document.createElement("style");A.setAttribute("data-polotno-highlight",""),A.textContent=`::highlight(${C}) { background-color: Highlight; }`,document.head.appendChild(A)}let $=null;function O(t,e){"text"===t.type&&e.push(t);for(const o of t.children||[]){O(o,e)}}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=/\s/.test(t.fontFamily)?`'${t.fontFamily}'`:t.fontFamily,l=u(t.fontWeight)?700:400,a="italic"===t.fontStyle?"italic":"normal",s=null!=$?$:$=document.createElement("canvas").getContext("2d");s.fontKerning="normal",s.font=`${r}px ${i}`;const d=s.measureText("M"),c=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,m=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${a};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,g=p(`<div style="${m}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let b;try{b=h({html:g,width:Math.max(12*r,600)})}catch(q){return null}const v=[];O(b.layoutRoot,v);const x=v.find(t=>"•"===t.text),y=v.find(t=>/^\d/.test(t.text));if(!x){return null}const w=x.style.fontSize,S=w*(1+c-f)/2,k=2.1*r;return{bulletLeft:x.x,bulletTop:x.y-S,bulletFontSize:w,numberGap:y?Math.max(0,k-y.x-(null!==(n=y.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=q("div",o.forwardRef)`
1
+ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}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 d,isQuillFormatMixed as c,isBoldWeight as u}from"../utils/rich-text-html.js";import{resetStyleContent as f,wrapHtmlForRenderTag as p}from"@polotno/core/reset-style";import{layout as h}from"render-tag";import{removeTags as m}from"@polotno/core/text";import{isGradient as g,firstStopColor as b}from"@polotno/core/gradient";import{getOptimalCaretColor as x}from"./text-element/caret-color.js";import{visiblePlaceholder as v}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as y}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as w,setActiveTextEditor as S,updateActiveTextFormat as k,clearActiveTextEditor as q}from"../utils/text-format-state.js";import T from"../utils/styled.js";import{applyOpacityToColor as E}from"@polotno/core/svg";export{E as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},lastSelection:null,pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const C=w;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of C){c(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),k(o,n,e)}const F="polotno-saved-selection";function R(){const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const e=t.getRangeAt(0).cloneRange();CSS.highlights.set(F,new Highlight(e)),$()}function L(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(F)}function $(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(F)&&(document.querySelector(".polotno-portal")||A(document.activeElement)?$():L())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const I=document.createElement("style");I.setAttribute("data-polotno-highlight",""),I.textContent=`::highlight(${F}) { background-color: Highlight; }`,document.head.appendChild(I)}let O=null;function M(t,e){"text"===t.type&&e.push(t);for(const o of t.children||[]){M(o,e)}}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=/\s/.test(t.fontFamily)?`'${t.fontFamily}'`:t.fontFamily,l=u(t.fontWeight)?700:400,a="italic"===t.fontStyle?"italic":"normal",s=null!=O?O:O=document.createElement("canvas").getContext("2d");s.fontKerning="normal",s.font=`${r}px ${i}`;const d=s.measureText("M"),c=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,m=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${a};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,g=p(`<div style="${m}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let b;try{b=h({html:g,width:Math.max(12*r,600)})}catch(q){return null}const x=[];M(b.layoutRoot,x);const v=x.find(t=>"•"===t.text),y=x.find(t=>/^\d/.test(t.text));if(!v){return null}const w=v.style.fontSize,S=w*(1+c-f)/2,k=2.1*r;return{bulletLeft:v.x,bulletTop:v.y-S,bulletFontSize:w,numberGap:y?Math.max(0,k-y.x-(null!==(n=y.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=T("div",o.forwardRef)`
2
2
  .ql-editor {
3
3
  outline: none;
4
4
  /* anchor for the absolutely-positioned ::before placeholder below */
@@ -152,4 +152,4 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
152
152
  &[style*='--polotno-gradient'] .ql-editor [style*='color:'] {
153
153
  -webkit-text-fill-color: currentColor;
154
154
  }
155
- `;let M=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{M=t};let j=!1;function N(){j||(j=!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 z(t){return t?"700":"400"}export const createQuill=(e,o)=>{x();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:M});!function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(N(),o("font-weight",z(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){N();const{bold:l}=r,a=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},a),{"font-weight":z(l)}),i)}return n(e,o,r,i)}return"bold"===r?(N(),n(e,o,"font-weight",z(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=u(e["font-weight"])),e}}(r);const i=n.import("delta"),l=(t,e)=>e.compose((new i).retain(e.length(),{"font-weight":"700"}));return r.clipboard.addMatcher("STRONG",l),r.clipboard.addMatcher("B",l),r};export const setQuillContent=(t,e)=>{var o=t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(t=>{"string"==typeof t.insert&&t.insert.includes("")&&(t.insert=t.insert.split("").join("\t"))}),t.setContents(o),t.history.clear()};export const RichEditor=({onBlur:t,onChange:n,element:c,clickCoords:u})=>{var f;const p=o.useRef(null),h=o.useRef(!1);o.useLayoutEffect(()=>{let e,o=!1,i=null,s=null,f=null,m=null,g=null;const b=()=>{if(!o&&p.current){try{e=createQuill(p.current,{placeholder:c.placeholder}),r.runInAction(()=>{quillRef.editor.instance=e}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=e,w({instance:e,store:c.store,element:c}),e.on("text-change",()=>{const t=e.getSelection();t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}})),setTimeout(()=>{var t,o;const r=e.root;if(!r||!r.isConnected){return}if(!l(c)){return}const i=r.innerHTML;h.current=!0,n(d(i,{fontSize:c.fontSize,fontFamily:c.fontFamily}));const a=e.getContents(),s=c.fill;let u=null,f=!0;for(const e of a.ops){if("string"!=typeof e.insert||"\n"===e.insert){continue}if(null===(t=e.attributes)||void 0===t?void 0:t.gradient){f=!1;break}const n=(null===(o=e.attributes)||void 0===o?void 0:o.color)||s;if(null===u){u=n}else if(n!==u){f=!1;break}}f&&u&&c.set({fill:u})},10)});const o=a(c,c.fontFamily);setQuillContent(e,o),h.current=!0;const b=p.current.closest(".polotno-workspace-inner"),v=null==b?void 0:b.scrollLeft,x=null==b?void 0:b.scrollTop;u?setCursorFromCoords(e,u):e.setSelection(0,0,"api"),b&&void 0!==v&&void 0!==x&&(b.scrollLeft=v,b.scrollTop=x),e.on("selection-change",(t,o,n)=>{t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}}))});const y=e.root;m=e=>{const o=e.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(P(o)||quillRef.pendingToolbarInteraction?F():setTimeout(()=>{quillRef.pendingToolbarInteraction||P(document.activeElement)?F():(R(),t())},0))},g=()=>{R()},y.addEventListener("blur",m),y.addEventListener("focus",g),i=y,s=t=>{var o,n;const r=e.getSelection();if(!r||0===r.length){return}const i=e.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let a="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==y&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),a=r.innerHTML}if(null===(o=t.clipboardData)||void 0===o||o.setData("text/plain",i),a){const e='<!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=t.clipboardData)||void 0===n||n.setData("text/html",e)}t.preventDefault()},f=t=>{s&&s(t);const o=e.getSelection();o&&o.length>0&&e.deleteText(o.index,o.length)},i.addEventListener("copy",s),i.addEventListener("cut",f)}catch(b){console.error("RichEditor init failed:",b)}}};return p.current?b():queueMicrotask(b),()=>{o=!0,i&&m&&i.removeEventListener("blur",m),i&&g&&i.removeEventListener("focus",g),R(),i&&s&&f&&(i.removeEventListener("copy",s),i.removeEventListener("cut",f)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={},quillRef.lastSelection=null}),k(e),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(c,()=>`${c.text}\0${c.fontSize}\0${c.fontFamily}`,()=>{const t=quillRef.editor.instance;if(!t){return}if(h.current){return void(h.current=!1)}const e=t.getSelection();setQuillContent(t,a(c,c.fontFamily)),h.current=!0,e&&(t.setSelection(e.index,e.length),syncQuillFormatState(t,t.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(c,()=>`${c.fontFamily}\0${c.fontSize}\0${c.fontWeight}\0${c.fontStyle}\0${c.lineHeight}\0${c.letterSpacing}\0${s(m(c.text))}`,()=>{const t=p.current;if(!t){return}const e="ltr"===s(m(c.text)),o=computeMarkerVars(c);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",t);const e=e=>{var o;(null===(o=p.current)||void 0===o?void 0:o.contains(e.target))||P(e.target)||quillRef.pendingToolbarInteraction||(R(),t())};return window.addEventListener("mousedown",e),window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e)}},[]);const x={color:c.fill};c.fill.indexOf("gradient")>=0&&(x["--polotno-gradient"]=c.fill,x.color="transparent"),c.strokeWidth>0&&(x.WebkitTextStroke=`${c.strokeWidth}px ${b(c.stroke)}`,x.paintOrder="stroke fill");const y=g(c.fill)?b(c.fill):v(c),S=c.a.rotation*Math.PI/180,q=c.shadowOffsetX*Math.cos(S)+c.shadowOffsetY*Math.sin(S),E=-c.shadowOffsetX*Math.sin(S)+c.shadowOffsetY*Math.cos(S);return e(RichTextContainer,{ref:p,style:Object.assign(Object.assign({},x),{fontSize:c.fontSize,fontFamily:c.fontFamily,fontWeight:c.fontWeight,fontStyle:c.fontStyle,"--polotno-text-decoration":c.textDecoration||"none",textTransform:c.textTransform,width:c.a.width,lineHeight:c.lineHeight,letterSpacing:c.letterSpacing*c.fontSize+"px",textAlign:c.align,opacity:Math.max(c.a.opacity,.2),textShadow:c.shadowEnabled?`${q}px ${E}px ${c.shadowBlur}px ${T(c.shadowColor,null!==(f=c.shadowOpacity)&&void 0!==f?f:1)}`:void 0,caretColor:y}),dir:s(m(c.text))})};function P(t){return!(!t||!t.closest(".sketch-picker")&&!t.closest("[data-polotno-keep-focus]")&&!t.closest(".polotno-portal")&&!t.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:r}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,r)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,r);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
155
+ `;let j=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{j=t};let N=!1;function z(){N||(N=!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 P(t){return t?"700":"400"}export const createQuill=(e,o)=>{y();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:j});!function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(z(),o("font-weight",P(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){z();const{bold:l}=r,a=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},a),{"font-weight":P(l)}),i)}return n(e,o,r,i)}return"bold"===r?(z(),n(e,o,"font-weight",P(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=u(e["font-weight"])),e}}(r);const i=n.import("delta"),l=(t,e)=>e.compose((new i).retain(e.length(),{"font-weight":"700"}));return r.clipboard.addMatcher("STRONG",l),r.clipboard.addMatcher("B",l),r};export const setQuillContent=(t,e)=>{var o=t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(t=>{"string"==typeof t.insert&&t.insert.includes("")&&(t.insert=t.insert.split("").join("\t"))}),t.setContents(o),t.history.clear()};export const RichEditor=({onBlur:t,onChange:n,element:c,clickCoords:u})=>{var f;const p=o.useRef(null),h=o.useRef(!1);o.useLayoutEffect(()=>{let e,o=!1,i=null,s=null,f=null,m=null,g=null;const b=()=>{if(!o&&p.current){try{e=createQuill(p.current,{placeholder:v(c.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=e}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=e,S({instance:e,store:c.store,element:c}),e.on("text-change",()=>{const t=e.getSelection();t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}})),setTimeout(()=>{var t,o;const r=e.root;if(!r||!r.isConnected){return}if(!l(c)){return}const i=r.innerHTML;h.current=!0,n(d(i,{fontSize:c.fontSize,fontFamily:c.fontFamily}));const a=e.getContents(),s=c.fill;let u=null,f=!0;for(const e of a.ops){if("string"!=typeof e.insert||"\n"===e.insert){continue}if(null===(t=e.attributes)||void 0===t?void 0:t.gradient){f=!1;break}const n=(null===(o=e.attributes)||void 0===o?void 0:o.color)||s;if(null===u){u=n}else if(n!==u){f=!1;break}}f&&u&&c.set({fill:u})},10)});const o=a(c,c.fontFamily);setQuillContent(e,o),h.current=!0;const b=p.current.closest(".polotno-workspace-inner"),x=null==b?void 0:b.scrollLeft,y=null==b?void 0:b.scrollTop;u?setCursorFromCoords(e,u):e.setSelection(0,0,"api"),b&&void 0!==x&&void 0!==y&&(b.scrollLeft=x,b.scrollTop=y),e.on("selection-change",(t,o,n)=>{t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}}))});const w=e.root;m=e=>{const o=e.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(A(o)||quillRef.pendingToolbarInteraction?R():setTimeout(()=>{quillRef.pendingToolbarInteraction||A(document.activeElement)?R():(L(),t())},0))},g=()=>{L()},w.addEventListener("blur",m),w.addEventListener("focus",g),i=w,s=t=>{var o,n;const r=e.getSelection();if(!r||0===r.length){return}const i=e.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let a="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==w&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),a=r.innerHTML}if(null===(o=t.clipboardData)||void 0===o||o.setData("text/plain",i),a){const e='<!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=t.clipboardData)||void 0===n||n.setData("text/html",e)}t.preventDefault()},f=t=>{s&&s(t);const o=e.getSelection();o&&o.length>0&&e.deleteText(o.index,o.length)},i.addEventListener("copy",s),i.addEventListener("cut",f)}catch(b){console.error("RichEditor init failed:",b)}}};return p.current?b():queueMicrotask(b),()=>{o=!0,i&&m&&i.removeEventListener("blur",m),i&&g&&i.removeEventListener("focus",g),L(),i&&s&&f&&(i.removeEventListener("copy",s),i.removeEventListener("cut",f)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={},quillRef.lastSelection=null}),q(e),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(c,()=>`${c.text}\0${c.fontSize}\0${c.fontFamily}`,()=>{const t=quillRef.editor.instance;if(!t){return}if(h.current){return void(h.current=!1)}const e=t.getSelection();setQuillContent(t,a(c,c.fontFamily)),h.current=!0,e&&(t.setSelection(e.index,e.length),syncQuillFormatState(t,t.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(c,()=>`${c.fontFamily}\0${c.fontSize}\0${c.fontWeight}\0${c.fontStyle}\0${c.lineHeight}\0${c.letterSpacing}\0${s(m(c.text))}`,()=>{const t=p.current;if(!t){return}const e="ltr"===s(m(c.text)),o=computeMarkerVars(c);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",t);const e=e=>{var o;(null===(o=p.current)||void 0===o?void 0:o.contains(e.target))||A(e.target)||quillRef.pendingToolbarInteraction||(L(),t())};return window.addEventListener("mousedown",e),window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e)}},[]);const y={color:c.fill};c.fill.indexOf("gradient")>=0&&(y["--polotno-gradient"]=c.fill,y.color="transparent"),c.strokeWidth>0&&(y.WebkitTextStroke=`${c.strokeWidth}px ${b(c.stroke)}`,y.paintOrder="stroke fill");const w=g(c.fill)?b(c.fill):x(c),k=c.a.rotation*Math.PI/180,T=c.shadowOffsetX*Math.cos(k)+c.shadowOffsetY*Math.sin(k),C=-c.shadowOffsetX*Math.sin(k)+c.shadowOffsetY*Math.cos(k);return e(RichTextContainer,{ref:p,style:Object.assign(Object.assign({},y),{fontSize:c.fontSize,fontFamily:c.fontFamily,fontWeight:c.fontWeight,fontStyle:c.fontStyle,"--polotno-text-decoration":c.textDecoration||"none",textTransform:c.textTransform,width:c.a.width,lineHeight:c.lineHeight,letterSpacing:c.letterSpacing*c.fontSize+"px",textAlign:c.align,opacity:Math.max(c.a.opacity,.2),textShadow:c.shadowEnabled?`${T}px ${C}px ${c.shadowBlur}px ${E(c.shadowColor,null!==(f=c.shadowOpacity)&&void 0!==f?f:1)}`:void 0,caretColor:w}),dir:s(m(c.text))})};function A(t){return!(!t||!t.closest(".sketch-picker")&&!t.closest("[data-polotno-keep-focus]")&&!t.closest(".polotno-portal")&&!t.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:r}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,r)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,r);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
@@ -0,0 +1 @@
1
+ export declare function visiblePlaceholder(placeholder: string): string;
@@ -0,0 +1 @@
1
+ import{removeTags as t}from"@polotno/core/text";export function visiblePlaceholder(o){return/<\/[a-z][a-z0-9]*>/i.test(o)&&!t(o).trim()?"":o}
@@ -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 l,TextPath as s}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{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b,textMinResizeWidth as E}from"../utils/px.js";import{isFontLoaded as z}from"../utils/fonts.js";import{flags as k}from"../utils/flags.js";import{removeTags as O}from"@polotno/core/text";import{getDir as R,getCurvePath as A,resolveLineHeight as F,normalizeStrokeLineJoin as M}from"@polotno/core/text-html";import{applyFilter as j}from"./apply-filters.js";import{useFadeIn as L}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{isAlive as C,getParent as H}from"mobx-state-tree";import{getLimitedFontSize as P}from"./text-element/max-font-size.js";import{getOptimalCaretColor as X}from"./text-element/caret-color.js";let Y;function W(){return Y||(Y=document.getElementById("polotno-text-style"),Y||(Y=document.createElement("style"),Y.id="polotno-text-style",document.head.appendChild(Y)),Y)}d._fixTextRendering=!0;const D={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 $=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(D),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=X(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=W();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(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();"middle"===r.verticalAlign&&(d=(r.a.height-f)/2),"bottom"===r.verticalAlign&&(d=r.a.height-f);const h=O(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:R(h),style:Object.assign(Object.assign(Object.assign({},D),l),{paddingTop:d+"px"}),value:h,onChange:t=>{const e=P({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:r.placeholder,onBlur:o})}),B=e=>t(c,{children:t($,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(z(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=z(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,s.current=!0,l()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{s.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[s.current]),[s.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=e.join("\0"),c=n.useRef(e.every(t=>z(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>z(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=v(`text fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,l()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[s,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(()=>F({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 I(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=O(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const n=e.a.height&&t.height()>e.a.height;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)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=o.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(n||s&&!r)){break}a-=.5,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(),z=n.useRef(null),F=n.useRef(null),P=n.useRef(null),X=n.useRef([]),Y=n.useRef(!0),[,W]=n.useReducer(t=>t+1,0),{editorEnabled:D,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),[N,J]=n.useState(!1),[_,V]=n.useState(!1),q=n.useRef(o.a.height),U=n.useRef(0),Z=n.useRef(""),G=n.useRef(0),K=o.isSelected,Q=usePrevious(K),{textVerticalResizeEnabled:tt}=k,et=k.autoDeleteEmptyText,rt=usePrevious(o.fontFamily),[nt,ot]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=z.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(nt)&&ot(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=z.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{Q&&!K&&et&&""===o.text&&o.removable&&!o.placeholder&&c.deleteElements([o.id])},[et,o.placeholder,o.removable,o.text,K,Q]);const it=()=>{if(o.curveEnabled){const t=z.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=F.current;e&&j(e,o)}else{const t=z.current;t&&j(t,o)}};n.useLayoutEffect(()=>{if(!_){return u(o,()=>{it()})}}),n.useEffect(()=>{const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{Y.current=!1;const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))},[]);let at=O(o.text);"uppercase"===o.textTransform&&(at=at.toUpperCase());const[lt]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),st=()=>{if(o.curveEnabled){const t=F.current;return t.getSelfRect().height||t.fontSize()}const t=z.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!lt){return}if("tablecell"===o.type){const{textOverflow:t}=k;if("resize"===t){const t=st(),e=C(o)?H(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=z.current;if(t){const e=I(t,o,k.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=k,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{Y.current?(X.current.push(i),W()):i()})};n?queueMicrotask(a):a()};if(!o.height){const t=st();return void r(()=>{o.height||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||N){if("resize"===t){const t=st();tt&&o.height<t&&!N&&r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0),tt||o.height===t||N||r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=z.current,n=o.curveEnabled?o.fontSize:I(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=st();o.height===i||tt||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(lt&&o.curveEnabled){const e=null===(t=F.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})}}},[lt,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=z.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),it())},[lt]);const ct=n.useRef(null),ut=n.useRef(o.width),dt=n.useRef(0),ft=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(dt.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),l=null!==(e=o[i])&&void 0!==e?e:o[0];let s=0;return"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2),a+Math.round((n.x-s)/l.width*l.text.length)}(t),o.toggleEditMode())},ht=!at&&o.placeholder?.6:o.a.opacity;L(z,ht);const gt=getLineHeight({fontLoaded:lt,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),pt=o.selectable||c.role===w.ADMIN,mt=m(o),xt=m(o,o.stroke,"stroke"),wt=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,l=e+r,s=f(`M ${o} ${i} L ${a} ${i} L ${a} ${l} L ${o} ${l} Z`);return h(s,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*gt*.5),padding:o.backgroundPadding*(o.a.fontSize*gt*.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(nt)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*gt*.5),lineHeight:gt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*gt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,gt,o.backgroundPadding,o.a.width,o.align,nt]),vt=T();let yt=0;o.curveEnabled||("middle"===o.verticalAlign?yt=(o.a.height-nt.length*gt*o.a.fontSize)/2:"bottom"===o.verticalAlign&&(yt=o.a.height-nt.length*gt*o.a.fontSize));const St=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",bt=lt?'"'+o.fontFamily+'"':rt===o.fontFamily?"Arial":'"'+rt+'"',Et=R(at);return r(e,{children:[t(a,{ref:P,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*ht,data:wt,fill:o.backgroundColor,offsetY:-yt}),t(a,{data:St,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:F,visible:o.curveEnabled,data:St,text:at||o.placeholder,listening:!1,align:"center",textBaseline:"middle",direction:Et},mt,xt,{strokeWidth:o.strokeWidth,lineJoin:M(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${rt}"`,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:ht,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(l,Object.assign({ref:z,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:o.a.height,text:at||o.placeholder,direction:Et},mt,xt,{lineJoin:M(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:bt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:vt?o.draggable&&K:o.draggable,preventDefault:!vt||K,opacity:o.curveEnabled?0:ht,visible:!o._editModeEnabled,ellipsis:"ellipsis"===k.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:gt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&pt,onDragStart:()=>{V(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{V(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:ft,onTap:ft,onTransformStart:()=>{var t,e;J(!0);const r=z.current;q.current=r.height(),ut.current=o.a.width,ct.current=r.position(),U.current=r.rotation(),G.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");Z.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=P.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=E(ut.current,o.a.fontSize);let n=e;e<r&&(n=r,ct.current&&i.position(ct.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=st();if("ellipsis"===k.textOverflow){a=q.current}else{const t=Math.max(a,q.current);i.height(t),o.set({height:i.height()})}const l=k.textVerticalResizeEnabled?Math.max(a,q.current):st();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),it()}if("top-center"===a||"bottom-center"===a){const e="resize"===k.textOverflow?st():gt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),ct.current){if("top-center"===Z.current){const r=U.current*Math.PI/180,n=G.current-e;t.target.x(ct.current.x-n*Math.sin(r)),t.target.y(ct.current.y+n*Math.cos(r))}else{t.target.position(ct.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(U.current),t.target.skewX(0),t.target.skewY(0),G.current=Math.max(e,r)}ct.current=t.target.position();const l=t.target.scaleX();null===(n=P.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:o.shadowBlur*l,shadowOffsetX:o.shadowOffsetX*l,shadowOffsetY:o.shadowOffsetY*l,strokeWidth:o.strokeWidth*l})},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=P.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),J(!1)}})),D&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(B,{textNodeRef:z,element:o,selectAll:$,cursorPosition:dt.current,onBlur:()=>{o.set(b(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 l,TextPath as s}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{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b,textMinResizeWidth as E}from"../utils/px.js";import{isFontLoaded as z}from"../utils/fonts.js";import{flags as k}from"../utils/flags.js";import{removeTags as O}from"@polotno/core/text";import{getDir as R,getCurvePath as A,resolveLineHeight as F,normalizeStrokeLineJoin as M}from"@polotno/core/text-html";import{applyFilter as j}from"./apply-filters.js";import{useFadeIn as L}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{isAlive as C,getParent as H}from"mobx-state-tree";import{getLimitedFontSize as P}from"./text-element/max-font-size.js";import{getOptimalCaretColor as X}from"./text-element/caret-color.js";import{visiblePlaceholder as Y}from"./text-element/placeholder.js";import{hasMeasuredHeight as W,resolveTextBoxHeight as D}from"@polotno/core/text-types";let $;function B(){return $||($=document.getElementById("polotno-text-style"),$||($=document.createElement("style"),$.id="polotno-text-style",document.head.appendChild($)),$)}d._fixTextRendering=!0;const I={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 N=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(I),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=X(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=B();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(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=D(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=O(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:R(g),style:Object.assign(Object.assign(Object.assign({},I),l),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=P({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:Y(r.placeholder),onBlur:o})}),J=e=>t(c,{children:t(N,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(z(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=z(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,s.current=!0,l()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{s.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[s.current]),[s.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=e.join("\0"),c=n.useRef(e.every(t=>z(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>z(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=v(`text fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,l()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[s,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(()=>F({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 _(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=O(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const n=W(e.a)&&t.height()>e.a.height;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)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=o.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(n||s&&!r)){break}a-=.5,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(),z=n.useRef(null),F=n.useRef(null),P=n.useRef(null),X=n.useRef([]),$=n.useRef(!0),[,B]=n.useReducer(t=>t+1,0),{editorEnabled:I,selectAll:N}=(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),[U,Z]=n.useState(!1),G=n.useRef(o.a.height),K=n.useRef(0),Q=n.useRef(""),tt=n.useRef(0),et=o.isSelected,rt=usePrevious(et),{textVerticalResizeEnabled:nt}=k,ot=k.autoDeleteEmptyText,it=usePrevious(o.fontFamily),[at,lt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=z.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(at)&&lt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=z.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{rt&&!et&&ot&&""===o.text&&o.removable&&!Y(o.placeholder)&&c.deleteElements([o.id])},[ot,o.placeholder,o.removable,o.text,et,rt]);const st=()=>{if(o.curveEnabled){const t=z.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=F.current;e&&j(e,o)}else{const t=z.current;t&&j(t,o)}};n.useLayoutEffect(()=>{if(!U){return u(o,()=>{st()})}}),n.useEffect(()=>{const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{$.current=!1;const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))},[]);let ct=O(o.text);"uppercase"===o.textTransform&&(ct=ct.toUpperCase());const[ut]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),dt=()=>{if(o.curveEnabled){const t=F.current;return t.getSelfRect().height||t.fontSize()}const t=z.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!ut){return}if("tablecell"===o.type){const{textOverflow:t}=k;if("resize"===t){const t=dt(),e=C(o)?H(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=z.current;if(t){const e=_(t,o,k.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=k,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{$.current?(X.current.push(i),B()):i()})};n?queueMicrotask(a):a()};if(!W(o)){const t=dt();return void r(()=>{W(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||V){if("resize"===t){const t=dt();nt&&o.height<t&&!V&&r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0),nt||o.height===t||V||r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=z.current,n=o.curveEnabled?o.fontSize:_(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=dt();o.height===i||nt||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(ut&&o.curveEnabled){const e=null===(t=F.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})}}},[ut,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=z.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),st())},[ut]);const ft=n.useRef(null),ht=n.useRef(o.width),gt=n.useRef(0),pt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(gt.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),l=null!==(e=o[i])&&void 0!==e?e:o[0];let s=0;return"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2),a+Math.round((n.x-s)/l.width*l.text.length)}(t),o.toggleEditMode())},mt=Y(o.placeholder),xt=!ct&&mt?.6:o.a.opacity;L(z,xt);const wt=getLineHeight({fontLoaded:ut,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),vt=o.selectable||c.role===w.ADMIN,yt=m(o),St=m(o,o.stroke,"stroke"),bt=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,l=e+r,s=f(`M ${o} ${i} L ${a} ${i} L ${a} ${l} L ${o} ${l} Z`);return h(s,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*wt*.5),padding:o.backgroundPadding*(o.a.fontSize*wt*.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(at)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*wt*.5),lineHeight:wt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*wt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,wt,o.backgroundPadding,o.a.width,o.align,at]),Et=T();let zt=0;if(!o.curveEnabled){const t=at.length*wt*o.a.fontSize,e=D(o.a,t);"middle"===o.verticalAlign?zt=(e-t)/2:"bottom"===o.verticalAlign&&(zt=e-t)}const kt=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Ot=ut?'"'+o.fontFamily+'"':it===o.fontFamily?"Arial":'"'+it+'"',Rt=R(ct);return r(e,{children:[t(a,{ref:P,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*xt,data:bt,fill:o.backgroundColor,offsetY:-zt}),t(a,{data:kt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:F,visible:o.curveEnabled,data:kt,text:ct||mt,listening:!1,align:"center",textBaseline:"middle",direction:Rt},yt,St,{strokeWidth:o.strokeWidth,lineJoin:M(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${it}"`,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:xt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(l,Object.assign({ref:z,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:W(o.a)?o.a.height:void 0,text:ct||mt,direction:Rt},yt,St,{lineJoin:M(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Ot,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:Et?o.draggable&&et:o.draggable,preventDefault:!Et||et,opacity:o.curveEnabled?0:xt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===k.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:wt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&vt,onDragStart:()=>{Z(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{Z(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:pt,onTap:pt,onTransformStart:()=>{var t,e;q(!0);const r=z.current;G.current=r.height(),ht.current=o.a.width,ft.current=r.position(),K.current=r.rotation(),tt.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");Q.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=P.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=E(ht.current,o.a.fontSize);let n=e;e<r&&(n=r,ft.current&&i.position(ft.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=dt();if("ellipsis"===k.textOverflow){a=G.current}else{const t=Math.max(a,G.current);i.height(t),o.set({height:i.height()})}const l=k.textVerticalResizeEnabled?Math.max(a,G.current):dt();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),st()}if("top-center"===a||"bottom-center"===a){const e="resize"===k.textOverflow?dt():wt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),ft.current){if("top-center"===Q.current){const r=K.current*Math.PI/180,n=tt.current-e;t.target.x(ft.current.x-n*Math.sin(r)),t.target.y(ft.current.y+n*Math.cos(r))}else{t.target.position(ft.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(K.current),t.target.skewX(0),t.target.skewY(0),tt.current=Math.max(e,r)}ft.current=t.target.position();const l=t.target.scaleX();null===(n=P.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:o.shadowBlur*l,shadowOffsetX:o.shadowOffsetX*l,shadowOffsetY:o.shadowOffsetY*l,strokeWidth:o.strokeWidth*l})},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=P.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),q(!1)}})),I&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(J,{textNodeRef:z,element:o,selectAll:N,cursorPosition:gt.current,onBlur:()=>{o.set(b(o)),o.toggleEditMode(!1)}})})]})});
@@ -1 +1 @@
1
- import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";import{useWorkspaceStyle as o}from"./workspace-style.js";let r=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:o})=>n<5;export const setSnapFilterFunc=e=>{r=e};function s(e,t){var n=[],o=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var o=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:o,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:o,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&o.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var s=[];const i=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=i[0],c=a[0];return d&&i.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"H"},e))}),s}export const ensureDragOrder=()=>{if(0===t.DD._dragElements.size){return}const e=[...t.DD._dragElements.entries()],n=e.find(([e,n])=>n.node instanceof t.Transformer);n&&(e.splice(e.indexOf(n),1),e.unshift(n),t.DD._dragElements.clear(),e.forEach(([e,n])=>{t.DD._dragElements.set(e,n)}))};function i(e,n,o){return new t.Line({x:-e.x(),y:-e.y(),points:o,stroke:n.stroke,strokeWidth:n.strokeWidth,name:"guid-line",dash:n.dash})}function a(e,t,n){const o=null==e?void 0:e.children.find(e=>"line-guides"===e.name()),r=e.getStage();n.forEach(e=>{"H"===e.orientation?null==o||o.add(i(r,t,[-6e3,e.lineGuide,6e3,e.lineGuide])):"V"===e.orientation&&(null==o||o.add(i(r,t,[e.lineGuide,-6e3,e.lineGuide,6e3])))})}export function useSnap(r,f){const u=e.useRef(null),l=e.useRef(null),h=e.useRef(new Map),g=e.useRef(null),{snapGuideStyle:y}=o(),p=e.useRef(y);p.current=y;const x=e=>e.hasName("element")||e.hasName("page-background")||!u.current&&e.hasName("elements-area");function v(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],s=[];return n.find(x).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});o.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:o,horizontal:s}}function m(e){var t;a(null===(t=r.current)||void 0===t?void 0:t.getLayer(),p.current,e)}const b=e=>{var o;const r=e.target.getLayer(),a=r.children.find(e=>"line-guides"===e.name());null==a||a.destroyChildren();const d=l.current;if((null===(o=e.evt)||void 0===o?void 0:o.shiftKey)&&d){const t=e.target.getAbsolutePosition();let n=t.x-d.x,o=t.y-d.y;const s=Math.abs(n),c=Math.abs(o);if(s>2.414*c){o=0}else if(c>2.414*s){n=0}else{const e=(s+c)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(s>0||c>0)){const e=Math.sign(n),t=Math.sign(o);null==a||a.add(i(r.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var c=v(e.target.nodes()),f=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),u=s(c,f);if(!u.length){return}m(u);const y=e.target.getAbsolutePosition(),x=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},y));u.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":x.x=e.lineGuide+e.offset;break;case"H":x.y=e.lineGuide+e.offset}}});const b=x.x-y.x,w=x.y-y.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+b,y:t.y+w})})},w=(e,t,n)=>{var o;const i=r.current,a=i.getLayer().children.find(e=>"line-guides"===e.name());if(null==a||a.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const f=i.getActiveAnchor(),u=c[f],l=null===(o=i.findOne(`.${u}`))||void 0===o?void 0:o.getAbsolutePosition();if(!l){return t}const h={x:e.x-l.x,y:e.y-l.y},g=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},h);if(Math.sqrt(Math.pow(g.x,2)+Math.pow(g.y,2))>5){return t}const y={x:e.x+g.x,y:e.y+g.y};var p=s(v(i.nodes()),{vertical:[{guide:y.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:y.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!p.length){return t}if(m(p),n.ctrlKey||n.metaKey){return t}const x=[];if(p.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(y,l,{orientation:e.orientation,lineGuide:e.lineGuide});t&&x.push(t)}),x.length>0){let e=x[0],t=Math.sqrt(Math.pow(y.x-e.x,2)+Math.pow(y.y-e.y,2));if(x.forEach(n=>{const o=Math.sqrt(Math.pow(y.x-n.x,2)+Math.pow(y.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return y},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var r,i=s(function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),{vertical:[{guide:(r=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[r]}],horizontal:[{guide:r.absolutePosition().y,offset:0,snap:"center",nodes:[r]}]});if(!i.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(i);const f=e.target.getAbsolutePosition(),u=Object.assign({},f);i.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":u.x=e.lineGuide+e.offset;break;case"H":u.y=e.lineGuide+e.offset}}});const l=u.x-f.x,h=u.y-f.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+l,y:t.y+h})}},u=e=>{if(!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};
1
+ import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";import{useWorkspaceStyle as o}from"./workspace-style.js";let r=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:o})=>n<5;export const setSnapFilterFunc=e=>{r=e};function s(e,t){var n=[],o=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var o=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:o,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:o,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&o.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var s=[];const i=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=i[0],c=a[0];return d&&i.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"H"},e))}),s}export const ensureDragOrder=()=>{if(0===t.DD._dragElements.size){return}const e=[...t.DD._dragElements.entries()],n=e.find(([e,n])=>n.node instanceof t.Transformer);n&&(e.splice(e.indexOf(n),1),e.unshift(n),t.DD._dragElements.clear(),e.forEach(([e,n])=>{t.DD._dragElements.set(e,n)}))};function i(e,n,o){return new t.Line({x:-e.x(),y:-e.y(),points:o,stroke:n.stroke,strokeWidth:n.strokeWidth,name:"guid-line",dash:n.dash})}function a(e,t,n){const o=null==e?void 0:e.children.find(e=>"line-guides"===e.name()),r=e.getStage();n.forEach(e=>{"H"===e.orientation?null==o||o.add(i(r,t,[-6e3,e.lineGuide,6e3,e.lineGuide])):"V"===e.orientation&&(null==o||o.add(i(r,t,[e.lineGuide,-6e3,e.lineGuide,6e3])))})}export function useSnap(r,f){const u=e.useRef(null),l=e.useRef(null),h=e.useRef(new Map),g=e.useRef(null),{snapGuideStyle:y}=o(),p=e.useRef(y);p.current=y;const x=e=>e.hasName("element")||e.hasName("page-background")||!u.current&&e.hasName("elements-area");function v(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],s=[];return n.find(x).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});o.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:o,horizontal:s}}function m(e){var t;a(null===(t=r.current)||void 0===t?void 0:t.getLayer(),p.current,e)}const b=e=>{var o,r;const a=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!a){return}const d=a.children.find(e=>"line-guides"===e.name());null==d||d.destroyChildren();const c=l.current;if((null===(r=e.evt)||void 0===r?void 0:r.shiftKey)&&c){const t=e.target.getAbsolutePosition();let n=t.x-c.x,o=t.y-c.y;const r=Math.abs(n),s=Math.abs(o);if(r>2.414*s){o=0}else if(s>2.414*r){n=0}else{const e=(r+s)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(r>0||s>0)){const e=Math.sign(n),t=Math.sign(o);null==d||d.add(i(a.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var f=v(e.target.nodes()),u=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),y=s(f,u);if(!y.length){return}m(y);const x=e.target.getAbsolutePosition(),b=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},x));y.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":b.x=e.lineGuide+e.offset;break;case"H":b.y=e.lineGuide+e.offset}}});const w=b.x-x.x,M=b.y-x.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+w,y:t.y+M})})},w=(e,t,n)=>{var o;const i=r.current;if(!i){return t}const a=i.getLayer();if(!a){return t}const f=a.children.find(e=>"line-guides"===e.name());if(null==f||f.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const u=i.getActiveAnchor(),l=c[u],h=null===(o=i.findOne(`.${l}`))||void 0===o?void 0:o.getAbsolutePosition();if(!h){return t}const g={x:e.x-h.x,y:e.y-h.y},y=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},g);if(Math.sqrt(Math.pow(y.x,2)+Math.pow(y.y,2))>5){return t}const p={x:e.x+y.x,y:e.y+y.y};var x=s(v(i.nodes()),{vertical:[{guide:p.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:p.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!x.length){return t}if(m(x),n.ctrlKey||n.metaKey){return t}const b=[];if(x.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(p,h,{orientation:e.orientation,lineGuide:e.lineGuide});t&&b.push(t)}),b.length>0){let e=b[0],t=Math.sqrt(Math.pow(p.x-e.x,2)+Math.pow(p.y-e.y,2));if(b.forEach(n=>{const o=Math.sqrt(Math.pow(p.x-n.x,2)+Math.pow(p.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return p},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{var o;const r=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!r){return}const i=r.children.find(e=>"line-guides"===e.name());null==i||i.destroyChildren();var f,u=function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),l=s(u,{vertical:[{guide:(f=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[f]}],horizontal:[{guide:f.absolutePosition().y,offset:0,snap:"center",nodes:[f]}]});if(!l.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(l);const h=e.target.getAbsolutePosition(),g=Object.assign({},h);l.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":g.x=e.lineGuide+e.offset;break;case"H":g.y=e.lineGuide+e.offset}}});const y=g.x-h.x,p=g.y-h.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+y,y:t.y+p})}},u=e=>{if(!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};