polotno 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/canvas/html-element.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/render-tag-element.js +1 -1
- package/canvas/rich-editor.d.ts +15 -0
- package/canvas/rich-editor.js +20 -4
- package/canvas/text-element.js +1 -1
- package/canvas/tooltip.js +1 -1
- package/model/page-model.js +1 -1
- package/model/store.js +1 -1
- package/package.json +4 -4
- package/polotno.bundle.js +164 -148
- package/toolbar/html-toolbar.js +4 -4
- package/utils/fonts.d.ts +1 -0
- package/utils/fonts.js +1 -1
- package/utils/html-to-svg/index.js +1 -1
- package/utils/html-to-svg/render-cache.js +1 -1
- package/utils/math.d.ts +6 -0
- package/utils/math.js +1 -1
- package/utils/px.d.ts +6 -0
- package/utils/px.js +1 -1
- package/utils/rich-text-html.d.ts +1 -0
- package/utils/rich-text-html.js +1 -1
- package/utils/text-format-state.d.ts +4 -4
- package/utils/text-format-state.js +1 -1
- package/utils/text-format.d.ts +11 -2
- package/utils/text-format.js +1 -1
- package/utils/validate-key.js +1 -1
- /package/utils/{html-to-svg/lru-cache.d.ts → lru-cache.d.ts} +0 -0
- /package/utils/{html-to-svg/lru-cache.js → lru-cache.js} +0 -0
package/canvas/html-element.js
CHANGED
|
@@ -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}from"../utils/px.js";import d from"konva";import{isAlive as u}from"mobx-state-tree";import{nodeAutorun as g}from"../utils/mobx.js";import{flags as m}from"../utils/flags.js";import{applyFilter as x}from"./apply-filters.js";import{getLineHeight as p,useFontFamiliesLoader as y,usePrevious as w}from"./text-element.js";import{getCurvePath as v}from"@polotno/core/text-html";import{useColor as b}from"./use-color.js";import{useWorkspaceStyle as E}from"./workspace-style.js";import{detectSize as S,detectLineRects as O,htmlToCanvas as k}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as z}from"@polotno/core/background-shape";import{useFadeIn as F}from"./use-fadein.js";import{Html as j}from"react-konva-utils";import{incrementLoader as M,triggerLoadError as R}from"../utils/loader.js";import{removeTags as X}from"@polotno/core/text";import*as Y from"../utils/fonts.js";import{isTouchDevice as I}from"../utils/screen.js";import{getLimitedFontSize as C}from"./text-element/max-font-size.js";import{useDelayer as T}from"./use-delayer.js";import{getHtml as A}from"@polotno/core/text-html";import{normalizeRichTextHtml as P,extractFontFamiliesFromHtml as B,scaleRichTextFontSizesInHtml as W}from"../utils/rich-text-html.js";import{findFitFontSize as $}from"./text-element/fit-font-size.js";import{RichEditor as D,RichTextContainer as H,applyOpacityToColor as _,quillRef as L,createQuill as J,setQuillContent as N,setQuillFormats as q,syncQuillFormatState as V,setCursorFromCoords as G}from"./rich-editor.js";export{L as quillRef,J as createQuill,N as setQuillContent,q as setQuillFormats,V as syncQuillFormatState,G as setCursorFromCoords};function K(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 Q=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),U=navigator.userAgent.includes("Firefox");export const HTMLElement=n(({element:n,store:L})=>{var J,N;const{textOverflowIndicatorStyle:q}=E(),V=r.useRef(null),[G,Z]=r.useState(),[tt,et]=r.useState(!1),[ot,rt]=r.useState(!1),nt=r.useRef(n.height),it=n.isSelected,at=w(it),st=n.fontSize/3,{textVerticalResizeEnabled:lt}=m,ct=m.autoDeleteEmptyText,ft=w(n.fontFamily),ht=r.useMemo(()=>P(n.text,{fontSize:n.fontSize,fontFamily:n.fontFamily}),[n.text,n.fontSize,n.fontFamily]),dt=r.useMemo(()=>[...new Set([n.fontFamily,...B(ht)])].filter(Boolean),[n.fontFamily,ht]),[ut]=y(L,dt,n.fontStyle,n.fontWeight,n.text||n.placeholder),gt=n._editModeEnabled;F(V);const mt=ut?n.fontFamily:ft!==n.fontFamily?ft:"Arial",xt=b(n).fill,pt=A(n,{fontFamily:mt,color:xt,textOverflow:m.textOverflow}),yt=r.useRef([]),wt=r.useRef(!0),[,vt]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=yt.current;t.length>0&&(yt.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{wt.current=!1;const t=yt.current;t.length>0&&(yt.current=[],t.forEach(t=>t()))},[]);let{width:bt,height:Et}=function(t,e,o){return r.useMemo(()=>S(t),[t,e.width,o])}(pt,n,ut);r.useEffect(()=>{if(!ut){return}const t=(t,e,o,r)=>{const i=M(`text ${n.id}`),a=()=>{L.history.ignore(t,e,o).then(()=>{wt.current?(yt.current.push(i),vt()):i()})};r?queueMicrotask(a):a()};if(n.curveEnabled&&Math.abs(bt-n.width)>1&&!tt&&t(()=>{if(u(n)&&Math.abs(bt-n.width)>1){const t=n.x+n.width/2;n.set({width:bt,x:t-bt/2})}},!1,!0),!n.height){return void t(()=>{u(n)&&(n.height||n.set({height:Et}))},void 0,void 0,!0)}const{textOverflow:e}=m;if("change-font-size"!==e||tt||gt||n.curveEnabled){"resize"===e&&(lt&&n.height<Et&&!tt&&t(()=>{u(n)&&n.set({height:Et})},!1,!0),lt||n.height===Et||tt||t(()=>{u(n)&&n.set({height:Et})},!1,!0))}else{const e=$(n,{fontFamily:n.fontFamily,textOverflow:m.textOverflow});e.fontSize!==n.fontSize?t(()=>{if(!u(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!==Et&&(lt&&n.height<Et?t(()=>{u(n)&&n.set({height:Et})},!1,!0):lt||t(()=>{u(n)&&n.set({height:Et})},!1,!0))}});const St=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 k(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),Ot=r.useRef(0),kt=r.useRef(null);r.useEffect(()=>{tt||gt||(async()=>{Ot.current++;const t=Ot.current;let e=M(`text ${n.id} ${t}`);kt.current&&kt.current(),kt.current=e,rt(!0);let o=null;const r=Q?5:1;for(let a=0;a<r;a++){const e=a>0?St:k;try{if(o=await e({skipCache:a>0,html:pt,width:bt||n.width||1,height:n.height||Et||1,fontFamily:mt,fontFamilies:B(pt),resolveFont:t=>L.fonts.find(e=>e.fontFamily===t)||Y.globalFonts.find(e=>e.fontFamily===t),padding:st,pixelRatio:L._elementsPixelRatio,font:L.fonts.find(t=>t.fontFamily===mt)||Y.globalFonts.find(t=>t.fontFamily===mt)}),t!==Ot.current){return}if((Q||U)&&o&&K(o)){await new Promise(t=>setTimeout(t,50*(a+1)));continue}break}catch(i){console.error(i),R(`Error rendering rich text with id ${n.id}`);break}}o?Z(o):e?(e(),e=null):console.error("Finish function is called twice!"),rt(!1)})()},[pt,tt,Et,gt,mt,n.height,L._elementsPixelRatio,ut]);const[zt,Ft]=T(ot,300),[jt]=T(tt,300,!0),Mt=jt||zt;r.useEffect(()=>{var t;if(!Mt){return g(n,()=>{const t=V.current;x(t,n)})}null===(t=V.current)||void 0===t||t.clearCache()},[G,Mt,n.shadowColor,n.shadowOffsetX,n.shadowOffsetY,n.shadowOpacity]),r.useEffect(()=>{G&&!ot&&kt.current&&(kt.current(),kt.current=null)},[G,ot]),r.useLayoutEffect(()=>{if(!ut){return}if(!n.curveEnabled){return}const t=new d.TextPath({data:v(n.a.width,n.a.height,n.curvePower,n.a.fontSize),text:X(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(()=>{u(n)&&n.set({width:e,x:n.a.x+r,y:n.a.y+i})})}t.destroy()},[ut,n.curveEnabled,n.curvePower,n.text,n.fontSize,n.fontFamily,n.fontWeight,n.fontStyle,n.letterSpacing]),r.useEffect(()=>()=>{kt.current&&kt.current()},[]),r.useEffect(()=>{at&&!it&&ct&&""===X(n.text)&&n.removable&&!n.placeholder&&L.deleteElements([n.id])},[ct,n.placeholder,n.removable,n.text,it,at]);let Rt=0;"middle"===n.verticalAlign&&(Rt=(n.height-Et)/2),"bottom"===n.verticalAlign&&(Rt=n.height-Et);const Xt=p({fontLoaded:ut,fontFamily:n.fontFamily,fontSize:n.fontSize,lineHeight:n.lineHeight}),Yt=n.backgroundPadding*(n.fontSize*Xt*.5),It=n.backgroundCornerRadius*(n.fontSize*Xt*.5),Ct=r.useMemo(()=>{if(!n.backgroundEnabled||n.curveEnabled||n.legacyBackground){return""}const t=O(pt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+st,right:t.right+st,top:t.top+st,bottom:t.bottom+st}));return z({rects:e,padding:Yt,cornerRadius:It})},[n.backgroundEnabled,n.curveEnabled,n.legacyBackground,pt,ut,Yt,It,st]),Tt=I(),At=v(n.a.width,Et,n.curvePower,n.fontSize),Pt=r.useRef(null),Bt=r.useRef(null),Wt=r.useRef(0),$t=r.useRef(0),Dt=r.useRef(null),Ht=gt&&n.strokeWidth>0&&!n.curveEnabled,_t=bt>0?(n.a.width+2*st)/(bt+2*st):1;return o(e,{children:[n.curveEnabled||n.legacyBackground?t(l,{x:n.a.x,y:n.a.y,offsetX:Yt/_t,offsetY:Yt/_t,rotation:n.a.rotation,scaleX:_t,scaleY:_t,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,width:n.width+2*Yt,height:n.height+2*Yt,cornerRadius:It}):t(s,{name:"html-background",x:n.a.x,y:n.a.y,offsetX:st/_t,offsetY:(st-Rt)/_t,rotation:n.a.rotation,scaleX:_t,scaleY:_t,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled&&Ct.length>0,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,data:Ct}),t(s,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,data:At,stroke:q.stroke,strokeWidth:1,visible:!1}),t(l,{ref:V,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:!Mt,draggable:Tt?n.draggable&&it:n.draggable,preventDefault:!Tt||it,opacity:gt?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&&(Dt.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];Dt.current=o?{x:o.clientX,y:o.clientY}:null,n.toggleEditMode(!0)}},onTransformStart:t=>{var e,o;et(!0),nt.current=n.height;const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");Bt.current=null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:null,Wt.current=n.a.rotation,$t.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=n.fontSize;let i=e;e<r&&(i=r,Pt.current&&o.position(Pt.current)),o.width(i),o.scaleX(1),o.scaleY(1);const a=A(Object.assign(Object.assign({},n.toJSON()),{width:i}),{fontFamily:mt,color:xt,textOverflow:m.textOverflow}),s=S(a).height,l=m.textVerticalResizeEnabled?Math.max(s,nt.current):s;o.height(l),n.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(a){const t="resize"===m.textOverflow,e="number"==typeof n.lineHeight?n.lineHeight:1,r=t?Et:e*n.fontSize,i=o.height()*o.scaleY();if(i<r){if(o.height(r),Pt.current){if("top-center"===Bt.current){const t=Wt.current*Math.PI/180,e=$t.current-r;o.x(Pt.current.x-e*Math.sin(t)),o.y(Pt.current.y+e*Math.cos(t))}else{o.position(Pt.current)}}}else{o.height(i)}o.scaleY(1),o.scaleX(1),$t.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:W(n.text,s)})}Pt.current=t.target.position()},onTransformEnd:t=>{et(!1),rt(!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:W(n.text,e)}))}}),t(a,{ref:V,image:G,x:n.a.x,y:n.a.y,offsetX:st,offsetY:st-Rt,listening:!1,rotation:n.a.rotation,width:n.a.width+2*st,height:(n.a.width+2*st)*((null!==(J=null==G?void 0:G.height)&&void 0!==J?J:0)/((null==G?void 0:G.width)||1)||1),visible:!Mt&&!gt,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||tt||Mt}),(Mt&&!gt||Ht)&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Rt,children:t(j,{divProps:{style:{pointerEvents:"none"}},children:t(H,{dangerouslySetInnerHTML:{__html:pt},style:{pointerEvents:"none",opacity:n.a.opacity,textShadow:n.shadowEnabled?`${n.shadowOffsetX}px ${n.shadowOffsetY}px ${n.shadowBlur}px ${_(n.shadowColor,null!==(N=n.shadowOpacity)&&void 0!==N?N:1)}`:void 0}})})}),gt&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Rt,children:t(j,{divProps:{style:{zIndex:20}},children:t(D,{element:n,onChange:t=>{const e=C({oldText:X(n.text),newText:X(t),element:n});n.set(Object.assign({text:t},c(n,e)))},onBlur:t=>{u(n)&&(n.set(h(n)),n.toggleEditMode(!1),Ft(!0))},clickCoords:Dt.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 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})})})]})});
|
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 u,Layer as h,Line as g,Rect as p,Shape as f,Stage as x,Tag as b,Text as v,Transformer as y,KonvaRenderer as E}from"react-konva";import w 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 I,useSnap as M}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,getTotalClientRect as B}from"../utils/math.js";import{pxToUnitRounded as T,pxToUnitString as G}from"../utils/unit.js";import{flags as W}from"../utils/flags.js";import{useColor as L}from"./use-color.js";import{isGradient as V}from"@polotno/core/gradient";import{Html as F}from"react-konva-utils";import{observerBatching as U}from"mobx-react-lite";const z=e=>E.batchedUpdates(e,null);U(e=>{E.isAlreadyRendering()?queueMicrotask(()=>z(e)):z(e)});const Z=S.DD._drag;window.removeEventListener("mousemove",Z),S.DD._drag=function(e){a(()=>{Z.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},H={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){H[e]=H[e]||t,Object.assign(H[e],t)}const J=e=>t(p,Object.assign({},e,{preventDefault:!1})),N=n=>{var{url:i}=n,o=e(n,["url"]);const[r,l]=w(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))},K=e=>{const n=L({a:{width:e.width,height:e.height},width:e.width,height:e.height},e.fill);return t(p,Object.assign({},e,n))},$=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)||V(r),[r]),m=o.useMemo(()=>{if(V(r)){return!0}const e=S.Util.colorToRGBA(r);return!e||e.a<1},[r]),u=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:u},d,{opacity:.1,hideInExport:!0})),c?t(K,Object.assign({fill:r},d)):t(N,Object.assign({url:r},d))]})},Q=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 q(e){let t=180*e/Math.PI;return t%=360,t>180?t-=360:t<-180&&(t+=360),Math.round(t)}const ee=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)}),h=(l/2+70)*Math.cos(s-Math.PI/2),g=(l/2+70)*Math.sin(s-Math.PI/2),p=T({unit:d.unit,dpi:d.dpi,px:r/d.scale,precious:"px"===d.unit?0:1})+" x "+T({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(u,{x:(m.minX+m.maxX)/2+h,y:(m.minY+m.maxY)/2+g,offsetX:14,offsetY:14,visible:"rotater"===a,children:[t(b,{cornerRadius:5,fill:c.fill}),t(v,{align:"center",verticalAlign:"middle",fill:c.textFill,padding:8,text:q(s).toString()+"°"})]}),n(u,{x:(m.minX+m.maxX)/2,y:m.maxY+20,visible:"rotater"!==a,children:[t(b,{cornerRadius:5,fill:c.fill,pointerDirection:"up",pointerHeight:0,pointerWidth:0}),t(v,{align:"center",verticalAlign:"middle",fill:c.textFill,padding:8,text:p})]})]})}),te=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 ne=null;export const registerNextDomDrop=e=>{ne=e};const ie=atob("UG9sb3RubyBmcmVlIGxpY2Vuc2UgbGltaXRhdGlvbiBleGNlZWRlZCAtIFBsZWFzZSB1cGdyYWRlIHlvdXIgYWNjb3VudC4="),oe=atob("I2MwMzkyYg=="),re=atob("djAuOS4y"),le=e=>t(i,{children:n(u,{fill:oe,height:200,children:[t(b,{fill:oe}),t(v,Object.assign({},e,{fill:"white",text:ie,height:void 0,padding:10,fontSize:20}))]})}),se=atob("RlJFRSAgVFJJQUwgIExJQ0VOU0U="),ae=(atob("UG93ZXJlZCBieSBQb2xvdG5v"),atob("TElDRU5TRSAgS0VZICBJUyAgTUlTU0lORw==")),de=atob("UGxlYXNlIGFjdGl2YXRlIHlvdXIgbGljZW5zZS4KTGljZW5zZSByZWxhdGVkIHF1ZXN0aW9uczoKcG9sb3Ruby5jb20vY29udGFjdA=="),ce=e=>{const i=1===j(),o=i?ae:se,r=i?230:195;return n(c,Object.assign({},e,{listening:!1,children:[t(p,{fill:oe,width:r,height:24,cornerRadius:2}),t(v,{text:o,fill:"white",fontSize:13,fontFamily:"monospace",width:r,align:"center",y:5,listening:!1}),i&&t(v,{text:de,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:E,altCloneEnabled:w,groupSelectionMode:k="drill",viewportSize:O,layout:P="vertical",tooltipSafeArea:T,transformerSafeArea:L})=>{const V=X(),U=V.transformerStyle,z=_,Z=i.computedBleed,N=e.bleedVisible?Z:d,K=i.computedWidth+N.left+N.right,q=i.computedHeight+N.top+N.bottom,ie=(r-K*e.scale)/2,oe=(a-q*e.scale)/2,se=o.useRef(null),ae=o.useRef(null),de=o.useRef(null),me=null==m||m,ue=o.useRef(!1),[he,ge]=o.useState(null),[pe,fe]=o.useState({}),[xe,be]=o.useState(0),ve=useContextMenu({store:e}),ye=e.selectedElements.find(e=>e._cropModeEnabled),Ee=e.selectedElements.find(e=>e.curveEnabled),we=e.selectedShapes.filter(e=>!e.resizable).length>0,Xe=e.selectedShapes.filter(e=>!e.draggable).length>0,Ye=e.selectedElements.filter(e=>!e.visible).length>0,Se=()=>{var t,n,i;const o=se.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=H[a],c=Object.assign(Object.assign({},z),d||{});return d&&("svg"!==a&&"image"!==a&&"gif"!==a||e.selectedElements[0].keepRatio||(c.enabledAnchors=z.enabledAnchors),"text"===a&&W.textVerticalResizeEnabled&&(c.enabledAnchors=null===(n=H.text.enabledAnchors)||void 0===n?void 0:n.concat(["bottom-center","top-center"])),"text"===a&&s&&e.selectedElements[0].curveEnabled&&(c.enabledAnchors=H.many.enabledAnchors)),o.setAttrs(Object.assign(Object.assign({},c),U)),we&&o.enabledAnchors([]),Xe&&o.rotateEnabled(!1),o.nodes(l),null===(i=o.getLayer())||void 0===i||i.batchDraw(),l};o.useLayoutEffect(()=>{const e=Se();e.find(e=>null==e?void 0:e.isDragging())&&(e.forEach(e=>{e.isDragging()||null==e||e.startDrag()}),I())},[e.selectedShapes,ye,we,Ye,Xe,Ee,U]);const ke=()=>{var e,t;const n=se.current;if(!n){return}if(!n.isTransforming()){return void fe({})}if(!n.nodes().length||!n.isTransforming()){return}const i=n.__getNodeRect(),o=null==n?void 0:n.getActiveAnchor(),r=n.getStage();fe({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})},Ae=o.useCallback(()=>{var e;if(null===(e=se.current)||void 0===e?void 0:e.isTransforming()){return}const t=se.current;if(!t||!t.nodes().length){return void be(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),u=c*Math.cos(a)-m*Math.sin(a),h=c*Math.sin(a)+m*Math.cos(a);return{x:o+u,y:r+h}},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==L?void 0:L.top)||0,bottom:a-((null==L?void 0:L.bottom)||0),left:(null==L?void 0:L.left)||0,right:r-((null==L?void 0:L.right)||0)},U.rotateAnchorOffset,t.rotation());be(i)},[L,r,a]);o.useEffect(()=>{var e;null===(e=se.current)||void 0===e||e.update(),ke(),Ae()},[e.scale,Ae]),o.useEffect(()=>{Ae()},[e.selectedShapes,Ae]);const Ie=l(()=>({visible:!1,x1:0,y1:0,x2:0,y2:0})),Me=o.useRef(!1),Oe=s(t=>{var n,i,o,r,l,s,a;if(e.role===Y.VIEWER){return}Me.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 u=null===(n=t.target.getStage())||void 0===n?void 0:n.getPointerPosition();u&&(u.x-=null!==(o=null===(i=t.target.getStage())||void 0===i?void 0:i.x())&&void 0!==o?o:0,u.y-=null!==(l=null===(r=t.target.getStage())||void 0===r?void 0:r.y())&&void 0!==l?l:0,Ie.visible=!0,Ie.x1=u.x,Ie.y1=u.y,Ie.x2=u.x,Ie.y2=u.y,(null!==(a=null===(s=t.target.getStage())||void 0===s?void 0:s.getPointersPositions().length)&&void 0!==a?a:0)>=2&&(Ie.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:ae,containerRef:de,viewportSize:O}),o.useEffect(()=>{const t=s(e=>{var t,n,i,o,r,l;if(!Ie.visible){return}null===(t=ae.current)||void 0===t||t.setPointersPositions(e);let s=null===(n=ae.current)||void 0===n?void 0:n.getPointerPosition();s?(s.x-=null!==(o=null===(i=ae.current)||void 0===i?void 0:i.x())&&void 0!==o?o:0,s.y-=null!==(l=null===(r=ae.current)||void 0===r?void 0:r.y())&&void 0!==l?l:0):s={x:Ie.x2,y:Ie.y2},Ie.x2=s.x,Ie.y2=s.y}),n=s(()=>{if(!Ie.visible){return}if(!ae.current){return}const t=ae.current.findOne(".selection"),n=t?t.getClientRect({skipStroke:!0}):{width:0,height:0,x:0,y:0};if(n.width&&n.height){const t=[];ae.current.find(".element").forEach(i=>{const o=i.getClientRect(),r=e.getElementById(i.id()),l=null==r?void 0:r.draggable,s=null==r?void 0:r.selectable;S.Util.haveIntersection(n,o)&&l&&s&&t.push(r.top.id)});const i=[...new Set(t)];Me.current=!0,e.selectElements(i)}Ie.visible=!1});return window.addEventListener("mousemove",t),window.addEventListener("touchmove",t),window.addEventListener("mouseup",n,{capture:!0}),window.addEventListener("touchend",n,{capture:!0}),()=>{window.removeEventListener("mousemove",t),window.removeEventListener("touchmove",t),window.removeEventListener("mouseup",n),window.removeEventListener("touchend",n)}},[]);const Pe=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(he)!==JSON.stringify(l)&&ge(l)},[e,i]);o.useEffect(()=>{e.selectedElements[0]&&e.distanceGuidesVisible?Pe():he&&ge(null)},[e.distanceGuidesVisible,Pe,e.selectedShapes.map(e=>`${e.x},${e.y},${e.width},${e.height},${e.rotation}`).join("|")]);const Re=o.useRef(!1);o.useEffect(()=>{var e;let t;const n=null===(e=de.current)||void 0===e?void 0:e.closest(".polotno-workspace-inner"),i=()=>{Re.current=!0,clearTimeout(t),t=setTimeout(()=>{Re.current=!1},300)};return null==n||n.addEventListener("scroll",i),()=>{clearTimeout(t),null==n||n.removeEventListener("scroll",i)}},[]),o.useEffect(()=>{const t=ae.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=se.current)||void 0===n?void 0:n.isDragging())&&se.current.stopDrag(),null===(o=se.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 je=t=>{if(e.role===Y.VIEWER){return}if(e.activePage!==i&&i.select(),Re.current){return}if(Me.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||Ie.visible)){return e.selectElements([]),void e.selectPages([])}if(o&&!n){const t=ae.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),u=e.getElementById(null==m?void 0:m.id()),h=null==u?void 0:u.top;let g;if("group"===k){g=null==h?void 0:h.id}else if(h){const t=e.selectedElements.some(e=>{var t;return(null===(t=e.top)||void 0===t?void 0:t.id)===h.id});g=t?null==u?void 0:u.id:null==h?void 0:h.id}else{g=void 0}const p=null==u?void 0:u.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([]))}};M(se,e);const De=e.activePage===i,Ce=e._selectedPagesIds.includes(i.id),Be=null==E?void 0:E.PageControls,Te=null==E?void 0:E.Tooltip,Ge=null==E?void 0:E.ContextMenu,We=1/e.scale,Le=0/e.scale;return n("div",{ref:de,onDragOver:e=>e.preventDefault(),onDrop:t=>{if(t.preventDefault(),e.role===Y.VIEWER){return}if(!ae.current){return}ae.current.setPointersPositions(t);const n=ae.current.findOne(".elements-container"),o=null==n?void 0:n.getRelativePointerPosition(),r=ae.current.getPointerPosition(),l=ae.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];ne&&o&&(ne(o,a,{elements:s,page:i}),ne=null)},style:{position:"relative",width:r+"px",height:a+"px",overflow:"hidden",flexShrink:0},className:"polotno-page-container"+(De?" active-page":""),children:[t(x,{ref:ae,width:Math.min(r,O.width+200),height:Math.min(O.height+200,a),onClick:je,onTap:je,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 ve.close()}e.selectedElementsIds.indexOf(r)>=0||e.selectElements([r]),ve.open({x:t.evt.clientX,y:t.evt.clientY})},onMouseDown:Oe,onMouseMove:t=>{if(!e.distanceGuidesVisible&&!t.evt.altKey){return void(he&&ge(null))}const n=t.target.findAncestor(".element",!0),i=null==n?void 0:n.id();Pe(i)},onDragStart:t=>{var n;const i=t.target.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=Se();t.target.stopDrag(),i.forEach(e=>{e.isDragging()||e.startDrag(t)}),null===(n=se.current)||void 0===n||n.startDrag(t),I()}}he&&ge(null)},pageId:i.id,style:{position:"absolute",overflow:"hidden",top:0,left:0},children:n(h,{children:[t(J,{width:r,height:a,fill:V.workspaceBackgroundColor}),t(c,{x:ie,y:oe,scaleX:e.scale,scaleY:e.scale,name:"page-container",children:n(c,{name:"page-container-2",children:[t(c,{name:"page-background-group",x:N.left,y:N.top,children:t($,{x:-Z.left,y:-Z.top,width:i.computedWidth+Z.left+Z.right,height:i.computedHeight+Z.top+Z.bottom,background:i.background,transparencyBackgroundColor:V.transparencyBackgroundColor,name:"page-background",preventDefault:!1,scale:e.scale})}),n(c,{x:N.left,y:N.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(te,{elements:i.children,store:e})]}),t(f,{name:"bleed",fill:V.bleedColor,listening:!1,visible:e.bleedVisible&&(N.top>0||N.right>0||N.bottom>0||N.left>0),hideInExport:!0,sceneFunc:(e,t)=>{const{top:n,right:o,bottom:r,left:l}=Z,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()===re&&t(le,{name:"hit-detection",x:-We/2-Le,y:-We/2-Le,width:K+We+2*Le,height:q+We+2*Le})]})}),t(g,{name:"workspace-background",points:[0,0,r,0,r,a,0,a,0,0,ie,oe,ie,a-oe,r-ie,a-oe,r-ie,oe,ie,oe],listening:!1,closed:!0,fill:V.workspaceBackgroundColor}),t(c,{x:ie,y:oe,scaleX:e.scale,scaleY:e.scale,children:t(p,{name:"page-highlight",hideInExport:!0,x:-We/2-Le,y:-We/2-Le,width:K+We+2*Le,height:q+We+2*Le,stroke:Ce?V.activePageBorderColor:V.pageBorderColor,strokeWidth:2,listening:!1,strokeScaleEnabled:!1})}),n(c,{x:ie+N.left*e.scale,y:oe+N.top*e.scale,scaleX:e.scale,scaleY:e.scale,name:"page-abs-container",children:[t(y,{ref:se,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)&&w&&e.selectedElements.forEach(e=>{const t=e.clone({},{skipSelect:!0}),n=i.children.indexOf(e);i.setElementZIndex(t.id,n)}),ue.current||(ue.current=!0,e.history.startTransaction()))},onDragEnd:()=>{ue.current&&(e.history.endTransaction(),ue.current=!1),Ae()},onTransformStart:()=>{e.history.startTransaction(),ge(null)},boundBoxFunc:(t,n)=>{var i;const o=Math.abs(n.width)<1||Math.abs(n.height)<1,r=Math.abs(t.width)<1||Math.abs(t.height)<1;if(o&&!r){return t}const l=e.selectedElements;if(1===l.length&&"table"===(null===(i=l[0])||void 0===i?void 0:i.type)){const e=l[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 n},onTransform:e=>{const t=se.current.nodes(),n=t[t.length-1];e.target===n&&setTimeout(()=>{ke()},0)},onTransformEnd:t=>{fe({}),e.history.endTransaction(),Ae()},visible:!e.isPlaying}),he&&he.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:V.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(p,Object.assign({},l,{stroke:V.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1})),t(g,{points:[i[0].x,i[0].y,i[1].x,i[1].y],stroke:V.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),t(g,{points:[i[1].x,i[1].y,i[2].x,i[2].y],stroke:V.distanceGuideStyle.stroke,strokeWidth:1,strokeScaleEnabled:!1}),n(u,{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(b,{cornerRadius:5,fill:V.distanceGuideStyle.labelFill,pointerDirection:"down"}),t(v,{align:"center",verticalAlign:"middle",fill:V.distanceGuideStyle.labelTextFill,padding:5,text:G({unit:e.unit,dpi:e.dpi,px:o})})]})]},s)),i._rendering&&n(c,{children:[t(p,{width:K,height:q,fill:"rgba(255,255,255,0.9)"}),t(v,{text:"Rendering...",fontSize:60,width:K,height:q,align:"center",verticalAlign:"middle"})]}),Te&&t(Te,{components:E,store:e,page:i,stageRef:ae,tooltipSafeArea:T}),Ge&&t(F,{children:t(Ge,Object.assign({components:E,store:e},ve.props))})]}),t(A,{store:e,page:i,width:r,height:a,scale:e.scale,xPadding:ie,yPadding:oe,bleedLeft:N.left,bleedTop:N.top}),t(ee,Object.assign({},pe,{store:e})),t(Q,{selection:Ie}),j()>0&&n(c,{hideInExport:!0,children:[t(ce,{name:"cache-bounds",x:r-(1===j()?250:210),y:a-(1===j()?95:45)}),t(ce,{name:"cache-bounds-t",x:10,y:10})]}),D()&&t(v,{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"})]})}),me&&Be&&t(Be,{store:e,page:i,xPadding:ie,yPadding:oe,layout:P})]})});
|
|
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 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{observer as i}from"mobx-react-lite";import{Group as n,Path as a,Rect as s,Shape as l}from"react-konva";import{nodeAutorun as c}from"../utils/mobx.js";import{isAlive as h}from"mobx-state-tree";import{Html as d}from"react-konva-utils";import{layout as f,drawLayout as u}from"render-tag";import{layoutTextOnPath as g,drawTextOnPathLayout as m}from"render-tag/path";import{scaledFontSizeAttrs as x,roundedFontSizeAttrs as p,roundedTextDecorationAttrs as y}from"../utils/px.js";import{flags as b}from"../utils/flags.js";import{applyFilter as w}from"./apply-filters.js";import{getLineHeight as v,usePrevious as E}from"./text-element.js";import{useFontSpecsLoader as O}from"./text-element/font-specs-loader.js";import{getHtml as S,getCurvePath as j,getCurveTextHeight as M}from"@polotno/core/text-html";import{useColor as z}from"./use-color.js";import{isGradient as k}from"@polotno/core/gradient";import{detectSize as Y}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as R}from"@polotno/core/background-shape";import{useFadeIn as X}from"./use-fadein.js";import{incrementLoader as F}from"../utils/loader.js";import{removeTags as T}from"@polotno/core/text";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as I}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as B,extractFontSpecsFromHtml as P,scaleRichTextFontSizesInHtml as A}from"../utils/rich-text-html.js";import{RichEditor as W}from"./rich-editor.js";import{findFitFontSize as D}from"./text-element/fit-font-size.js";import{wrapHtmlForRenderTag as J}from"@polotno/core/reset-style";import{xmlEscape as N}from"@polotno/core/xml";export{J as wrapHtmlForRenderTag};export const RenderTagElement=i(({element:i,store:L})=>{var H;const V=r.useRef(null),_=r.useRef(null),[q,$]=r.useState(!1),G=r.useRef(i.height),K=i.isSelected,Q=E(K),{textVerticalResizeEnabled:U}=b,Z=b.autoDeleteEmptyText,tt=E(i.fontFamily),et=r.useMemo(()=>B(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),ot=r.useMemo(()=>P(et,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[et,i.fontFamily,i.fontWeight,i.fontStyle]),[rt]=O(L,ot,i.text||i.placeholder),it=i._editModeEnabled;X(V);const nt=rt?i.fontFamily:tt&&tt!==i.fontFamily?tt:"Arial",at=z(i).fill,st=k(i.fill),lt=k(i.stroke)&&!!i.strokeWidth,ct=!!i.strokeWidth&&(lt||st),ht="ellipsis"===b.textOverflow&&!i.curveEnabled&&!!i.height&&!ct,dt=!T(i.text)&&!!i.placeholder,ft=dt?N(i.placeholder):i.text,ut=dt?.6:i.a.opacity,gt=S(dt?Object.assign(Object.assign({},i.toJSON()),{text:ft}):i,{fontFamily:nt,color:at,forEditor:!ht,textOverflow:b.textOverflow}),mt=i.width||1,xt=i.curveEnabled,pt=function(t,e,o,i){return r.useMemo(()=>{if(i){return null}try{return f({html:J(t),width:Math.max(1,e),accuracy:"performance"})}catch(o){return console.error("render-tag layout failed:",o),null}},[t,e,o,i])}(gt,mt,rt,xt),yt=function(t,e,o){return r.useMemo(()=>{if(!e.curveEnabled){return null}const o=e.width||1,r=M(e),i=j(o,r,e.curvePower,e.fontSize);try{return g({html:J(t),path:i,align:"center",textBaseline:"middle"})}catch(n){return console.error("render-tag/path layoutTextOnPath failed:",n),null}},[o,e.curveEnabled,e.curvePower,e.fontSize,e.width,e.height,t])}(gt,i,rt),bt=v({fontLoaded:rt,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),wt=xt?0:Math.max(null!==(H=null==pt?void 0:pt.height)&&void 0!==H?H:0,i.fontSize*bt),vt=yt?yt.bounds:null,Et=r.useMemo(()=>pt?pt.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})):[],[pt]),Ot=r.useRef([]),St=r.useRef(!0),[,jt]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=Ot.current;t.length>0&&(Ot.current=[],t.forEach(t=>t()))});const Mt=r.useCallback((t,e,o,r)=>{const n=F(`text ${i.id}`),a=()=>{L.history.ignore(t,e,o).then(()=>{St.current?(Ot.current.push(n),jt()):n()})};r?queueMicrotask(a):a()},[i.id,L]);r.useEffect(()=>{if(!rt){return}if(!pt){return}if(!i.height){return void Mt(()=>{h(i)&&(i.height||i.set({height:wt}))},void 0,void 0,!0)}if(L.isPlaying){return}const{textOverflow:t}=b,e=i.height!==wt&&(!U||i.height<wt),o=()=>Mt(()=>{h(i)&&i.set({height:wt})},!1,!0);if("change-font-size"!==t||q||it||i.curveEnabled){"resize"===t&&e&&!q&&o()}else{const t=D(dt?Object.assign(Object.assign({},i.toJSON()),{text:ft,toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:ft})}):i,{fontFamily:nt,color:at,forEditor:!0},t=>{try{return f({html:J(t),width:mt,accuracy:"performance"}).height}catch(H){return Y(t).height}});t.fontSize!==i.fontSize?Mt(()=>{if(!h(i)){return}const e=x(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&o()}}),r.useEffect(()=>()=>{St.current=!1;const t=Ot.current;t.length>0&&(Ot.current=[],t.forEach(t=>t()))},[]),r.useLayoutEffect(()=>{if(!rt||!i.curveEnabled||q){return}if(!vt||!vt.width){return}const t=t=>t&&U?Math.max(t,vt.height):vt.height;Math.abs(vt.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||Mt(()=>{if(!h(i)){return}const e=vt.width-i.width,o=t(i.height),r=o-i.height;if(Math.abs(e)<1&&Math.abs(r)<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:vt.width,height:o,x:i.a.x+a,y:i.a.y+s})},!1,!0,!0)},[rt,i.curveEnabled,vt,q,U,Mt]),r.useEffect(()=>{Q&&!K&&Z&&""===T(i.text)&&i.removable&&!i.placeholder&&L.deleteElements([i.id])},[Z,i.placeholder,i.removable,i.text,K,Q]),r.useEffect(()=>c(i,()=>{const t=V.current;t&&w(t,i)}),[pt,yt,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);let zt=0;xt||"middle"!==i.verticalAlign?xt||"bottom"!==i.verticalAlign||(zt=i.height-wt):zt=(i.height-wt)/2;const kt=i.backgroundPadding*(i.fontSize*bt*.5),Yt=i.backgroundCornerRadius*(i.fontSize*bt*.5),Rt=r.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===Et.length?"":R({rects:Et,padding:kt,cornerRadius:Yt}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,Et,kt,Yt]),Xt=C(),Ft=r.useRef(null),Tt=r.useRef(null),Ct=r.useRef(null),It=r.useRef(0),Bt=r.useRef(0),Pt=i.width>0?i.a.width/i.width:1;return o(e,{children:[i.curveEnabled||i.legacyBackground?t(s,{x:i.a.x,y:i.a.y,offsetX:kt/Pt,offsetY:kt/Pt,rotation:i.a.rotation,scaleX:Pt,scaleY:Pt,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*ut,fill:i.backgroundColor,width:i.width+2*kt,height:i.height+2*kt,cornerRadius:Yt}):t(a,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-zt/Pt,rotation:i.a.rotation,scaleX:Pt,scaleY:Pt,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&Rt.length>0,opacity:i.backgroundOpacity*ut,fill:i.backgroundColor,data:Rt}),t(l,{ref:V,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:Pt,scaleY:Pt,offsetY:Pt>0?-zt/Pt:0,width:i.width,height:Math.max(i.height,wt),listening:!1,visible:!it&&!!(xt?yt:pt),opacity:ut,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 o=t._context;if(o){try{if(xt){if(!yt||!vt){return}const t=(i.width-vt.width)/2-vt.x;o.save(),o.translate(t,-vt.y),m({layout:yt,ctx:o}),o.restore()}else{if(!pt){return}u({layout:pt,width:mt,ctx:o,pixelRatio:1})}}catch(r){console.error("render-tag draw failed:",r)}}}}),t(s,{ref:_,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:!it,draggable:Xt?i.draggable&&K:i.draggable,preventDefault:!Xt||K,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&&(Tt.current={x:t.evt.clientX,y:t.evt.clientY},i.toggleEditMode(!0))},onDblTap:t=>{var e;if(i.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Tt.current=o?{x:o.clientX,y:o.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{var e,o;$(!0),G.current=i.height;const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");Ct.current=null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:null,It.current=i.a.rotation,Bt.current=i.height},onTransform:t=>{var e;const o=t.target,r=(null===(e=o.getStage())||void 0===e?void 0:e.findOne("Transformer")).getActiveAnchor(),n="middle-left"===r||"middle-right"===r,a="top-center"===r||"bottom-center"===r,s=o.scaleX();if(n){const t=o.scaleX(),e=o.width()*t,r=i.fontSize;let n=e;e<r&&(n=r,Ft.current&&o.position(Ft.current)),o.width(n),o.scaleX(1),o.scaleY(1);let a=0;if(i.curveEnabled){a=M(Object.assign(Object.assign({},i.toJSON()),{width:n}))}else{const t=S(Object.assign(Object.assign({},i.toJSON()),{text:ft,width:n}),{fontFamily:nt,color:at,forEditor:!0});try{a=f({html:J(t),width:n,accuracy:"performance"}).height}catch(l){a=Y(t).height}}let s=b.textVerticalResizeEnabled?Math.max(a,G.current):a;"ellipsis"===b.textOverflow&&(s=G.current),o.height(s),i.set({width:o.width(),height:s,x:o.x(),y:o.y()})}else if(a){const t="resize"===b.textOverflow?xt?(null==vt?void 0:vt.height)||i.fontSize:wt:bt*i.fontSize,e=o.height()*o.scaleY();if(e<t){if(o.height(t),Ft.current){if("top-center"===Ct.current){const e=It.current*Math.PI/180,r=Bt.current-t;o.x(Ft.current.x-r*Math.sin(e)),o.y(Ft.current.y+r*Math.cos(e))}else{o.position(Ft.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Bt.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*s,letterSpacing:i.letterSpacing,width:o.width()*s,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*s,shadowBlur:i.shadowBlur*s,shadowOffsetX:i.shadowOffsetX*s,shadowOffsetY:i.shadowOffsetY*s,strokeWidth:i.strokeWidth*s,text:A(i.text,s)})}Ft.current=t.target.position()},onTransformEnd:t=>{$(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},p(i,i.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:A(i.text,e)}))}}),it&&t(n,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-zt,children:t(d,{divProps:{style:{zIndex:20}},children:t(W,{element:i,onChange:t=>{const e=I({oldText:T(i.text),newText:T(t),element:i});i.set(Object.assign({text:t},x(i,e)))},onBlur:()=>{h(i)&&(i.set(y(i)),i.toggleEditMode(!1))},clickCoords:Tt.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{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})})})]})});
|
package/canvas/rich-editor.d.ts
CHANGED
|
@@ -19,6 +19,21 @@ export declare function syncQuillFormatState(quill: any, range: {
|
|
|
19
19
|
index: number;
|
|
20
20
|
length: number;
|
|
21
21
|
} | null | undefined): void;
|
|
22
|
+
type MarkerVars = {
|
|
23
|
+
bulletLeft: number;
|
|
24
|
+
bulletTop: number;
|
|
25
|
+
bulletFontSize: number;
|
|
26
|
+
numberGap: number;
|
|
27
|
+
};
|
|
28
|
+
export type MarkerFont = {
|
|
29
|
+
fontFamily: string;
|
|
30
|
+
fontSize: number;
|
|
31
|
+
fontWeight: string | number;
|
|
32
|
+
fontStyle: string;
|
|
33
|
+
lineHeight: number | string;
|
|
34
|
+
letterSpacing: number | string;
|
|
35
|
+
};
|
|
36
|
+
export declare function computeMarkerVars(element: MarkerFont): MarkerVars | null;
|
|
22
37
|
export declare const RichTextContainer: any;
|
|
23
38
|
export declare const setQuillFormats: (formats: string[]) => void;
|
|
24
39
|
export declare const createQuill: (node: any, options?: {
|
package/canvas/rich-editor.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
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)`
|
|
2
2
|
.ql-editor {
|
|
3
3
|
outline: none;
|
|
4
4
|
/* anchor for the absolutely-positioned ::before placeholder below */
|
|
@@ -93,7 +93,9 @@ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype
|
|
|
93
93
|
}
|
|
94
94
|
.ql-editor li[data-list='ordered']::before {
|
|
95
95
|
content: counter(list-0) '.';
|
|
96
|
-
|
|
96
|
+
/* Exact render-tag number gap (space-width) computed per element; 0.32em
|
|
97
|
+
fallback until the vars are set (or on layout failure). */
|
|
98
|
+
padding-inline-end: var(--rt-number-gap, 0.32em);
|
|
97
99
|
}
|
|
98
100
|
.ql-editor li.ql-indent-1[data-list='ordered']::before {
|
|
99
101
|
content: counter(list-1) '.';
|
|
@@ -106,7 +108,21 @@ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype
|
|
|
106
108
|
}
|
|
107
109
|
.ql-editor li[data-list='bullet']::before {
|
|
108
110
|
content: '•';
|
|
109
|
-
padding-inline-end: 0.5em; /*
|
|
111
|
+
padding-inline-end: 0.5em; /* fallback gap (RTL, or before vars are set) */
|
|
112
|
+
}
|
|
113
|
+
/* LTR: pixel-match render-tag's synthetic disc. The canvas scales the '•'
|
|
114
|
+
glyph to ink-diameter ascent/3 and pins its ink-right edge / vertical
|
|
115
|
+
center; computeMarkerVars asks render-tag for the exact numbers and sets
|
|
116
|
+
them here. Gated on .rt-marker-geom (LTR + vars computed) so RTL and the
|
|
117
|
+
pre-measure frame keep the box+text-align fallback above. */
|
|
118
|
+
&.rt-marker-geom .ql-editor li[data-list='bullet']::before {
|
|
119
|
+
inset-inline-start: var(--rt-bullet-left);
|
|
120
|
+
top: var(--rt-bullet-top);
|
|
121
|
+
font-size: var(--rt-bullet-fs);
|
|
122
|
+
line-height: 1;
|
|
123
|
+
width: auto;
|
|
124
|
+
padding-inline-end: 0;
|
|
125
|
+
text-align: left;
|
|
110
126
|
}
|
|
111
127
|
|
|
112
128
|
strong {
|
|
@@ -136,4 +152,4 @@ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype
|
|
|
136
152
|
&[style*='--polotno-gradient'] .ql-editor [style*='color:'] {
|
|
137
153
|
-webkit-text-fill-color: currentColor;
|
|
138
154
|
}
|
|
139
|
-
`;let
|
|
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")}
|
package/canvas/text-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as 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 v}from"../model/store.js";import{incrementLoader as w}from"../utils/loader.js";import{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b}from"../utils/px.js";import{isFontLoaded as E}from"../utils/fonts.js";import{flags as z}from"../utils/flags.js";import{removeTags as k}from"@polotno/core/text";import{getDir as O,getCurvePath as R,resolveLineHeight as A,normalizeStrokeLineJoin as F}from"@polotno/core/text-html";import{applyFilter as M}from"./apply-filters.js";import{useFadeIn as j}from"./use-fadein.js";import{isTouchDevice as L}from"../utils/screen.js";import{isAlive as T,getParent as C}from"mobx-state-tree";import{getLimitedFontSize as H}from"./text-element/max-font-size.js";import{getOptimalCaretColor as P}from"./text-element/caret-color.js";let X;function Y(){return X||(X=document.getElementById("polotno-text-style"),X||(X=document.createElement("style"),X.id="polotno-text-style",document.head.appendChild(X)),X)}d._fixTextRendering=!0;const W={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 D=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(W),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=P(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=Y();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=k(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:O(h),style:Object.assign(Object.assign(Object.assign({},W),l),{paddingTop:d+"px"}),value:h,onChange:t=>{const e=H({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})}),$=e=>t(c,{children:t(D,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(E(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=E(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=w(`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=>E(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>E(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=w(`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(()=>A({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 B(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=k(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(),E=n.useRef(null),A=n.useRef(null),H=n.useRef(null),P=n.useRef([]),X=n.useRef(!0),[,Y]=n.useReducer(t=>t+1,0),{editorEnabled:W,selectAll:D}=(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),[I,N]=n.useState(!1),[J,_]=n.useState(!1),V=n.useRef(o.a.height),q=n.useRef(0),U=n.useRef(""),Z=n.useRef(0),G=o.isSelected,K=usePrevious(G),{textVerticalResizeEnabled:Q}=z,tt=z.autoDeleteEmptyText,et=usePrevious(o.fontFamily),[rt,nt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=E.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(rt)&&nt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=E.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{K&&!G&&tt&&""===o.text&&o.removable&&!o.placeholder&&c.deleteElements([o.id])},[tt,o.placeholder,o.removable,o.text,G,K]);const ot=()=>{if(o.curveEnabled){const t=E.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=A.current;e&&M(e,o)}else{const t=E.current;t&&M(t,o)}};n.useLayoutEffect(()=>{if(!J){return u(o,()=>{ot()})}}),n.useEffect(()=>{const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{X.current=!1;const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))},[]);let it=k(o.text);"uppercase"===o.textTransform&&(it=it.toUpperCase());const[at]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),lt=()=>{if(o.curveEnabled){const t=A.current;return t.getSelfRect().height||t.fontSize()}const t=E.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!at){return}if("tablecell"===o.type){const{textOverflow:t}=z;if("resize"===t){const t=lt(),e=T(o)?C(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=E.current;if(t){const e=B(t,o,z.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=z,r=(t,e,r,n)=>{const i=w(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{X.current?(P.current.push(i),Y()):i()})};n?queueMicrotask(a):a()};if(!o.height){const t=lt();return void r(()=>{o.height||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||I){if("resize"===t){const t=lt();Q&&o.height<t&&!I&&r(()=>{var e;T(o)&&o.set({height:t}),null===(e=E.current)||void 0===e||e.height(t)},!1,!0),Q||o.height===t||I||r(()=>{var e;T(o)&&o.set({height:t}),null===(e=E.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=E.current,n=o.curveEnabled?o.fontSize:B(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=lt();o.height===i||Q||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(at&&o.curveEnabled){const e=null===(t=A.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})}}},[at,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=E.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ot())},[at]);const st=n.useRef(null),ct=n.useRef(0),ut=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(ct.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())},dt=!it&&o.placeholder?.6:o.a.opacity;j(E,dt);const ft=getLineHeight({fontLoaded:at,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),ht=o.selectable||c.role===v.ADMIN,gt=m(o),pt=m(o,o.stroke,"stroke"),mt=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*ft*.5),padding:o.backgroundPadding*(o.a.fontSize*ft*.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(rt)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*ft*.5),lineHeight:ft*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*ft*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,ft,o.backgroundPadding,o.a.width,o.align,rt]),xt=L();let vt=0;o.curveEnabled||("middle"===o.verticalAlign?vt=(o.a.height-rt.length*ft*o.a.fontSize)/2:"bottom"===o.verticalAlign&&(vt=o.a.height-rt.length*ft*o.a.fontSize));const wt=o.curveEnabled?R(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",yt=at?'"'+o.fontFamily+'"':et===o.fontFamily?"Arial":'"'+et+'"',St=O(it);return r(e,{children:[t(a,{ref:H,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*dt,data:mt,fill:o.backgroundColor,offsetY:-vt}),t(a,{data:wt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:A,visible:o.curveEnabled,data:wt,text:it||o.placeholder,listening:!1,align:"center",textBaseline:"middle",direction:St},gt,pt,{strokeWidth:o.strokeWidth,lineJoin:F(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${et}"`,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:dt,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:E,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:it||o.placeholder,direction:St},gt,pt,{lineJoin:F(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:yt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:xt?o.draggable&&G:o.draggable,preventDefault:!xt||G,opacity:o.curveEnabled?0:dt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===z.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:ft,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&ht,onDragStart:()=>{_(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{_(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:ut,onTap:ut,onTransformStart:()=>{var t,e;N(!0);const r=E.current;V.current=r.height(),q.current=r.rotation(),Z.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");U.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=H.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=o.a.fontSize;let n=e;e<r&&(n=r,st.current&&i.position(st.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=lt();if("ellipsis"===z.textOverflow){a=V.current}else{const t=Math.max(a,V.current);i.height(t),o.set({height:i.height()})}const l=z.textVerticalResizeEnabled?Math.max(a,V.current):lt();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),ot()}if("top-center"===a||"bottom-center"===a){const e="resize"===z.textOverflow?lt():ft*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),st.current){if("top-center"===U.current){const r=q.current*Math.PI/180,n=Z.current-e;t.target.x(st.current.x-n*Math.sin(r)),t.target.y(st.current.y+n*Math.cos(r))}else{t.target.position(st.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(q.current),t.target.skewX(0),t.target.skewY(0),Z.current=Math.max(e,r)}st.current=t.target.position();const l=t.target.scaleX();null===(n=H.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=H.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),N(!1)}})),W&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t($,{textNodeRef:E,element:o,selectAll:D,cursorPosition:ct.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";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)}})})]})});
|
package/canvas/tooltip.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Html as r}from"react-konva-utils";import{getTotalClientRect as l}from"../utils/math.js";import{extendToolbar as i}from"../toolbar/element-container.js";import{TextAiWrite as s}from"../toolbar/text-ai-write.js";import{flags as u}from"../utils/flags.js";import{DuplicateButton as a}from"../toolbar/duplicate-button.js";import{RemoveButton as c}from"../toolbar/remove-button.js";import{PositionPicker as d}from"../toolbar/position-picker.js";import{GroupButton as m}from"../toolbar/group-button.js";import{Navbar as v}from"../primitives/navbar.js";function p(e,t){return e.classList.contains(t)?e:e.parentElement?p(e.parentElement,t):null}const f=()=>null,h=({stage:e})=>{var t,n;return(null===(t=null==e?void 0:e.container())||void 0===t?void 0:t.closest(".polotno-workspace-container"))||(null===(n=null==e?void 0:e.container())||void 0===n?void 0:n.parentNode)};export const Tooltip=o(({store:o,page:g,components:b,stageRef:x,tooltipSafeArea:j})=>{var E,w;const y=o.selectedShapes.every(e=>e.page===g),N=n.useRef(null),I=n.useRef(null),[O,S]=n.useState(!1),[,R]=n.useReducer(e=>e+1,0),C=n.useCallback(e=>{var t,n;e?(N.current=e,null===(t=I.current)||void 0===t||t.disconnect(),I.current=new ResizeObserver(R),I.current.observe(e),R()):N.current&&!N.current.isConnected&&(N.current=null,null===(n=I.current)||void 0===n||n.disconnect(),I.current=null)},[]),F=o._hasCroppedImages;n.useEffect(()=>{var e,t,n;const o=()=>{S(!0)},r=()=>{S(!1)};null===(e=null==x?void 0:x.current)||void 0===e||e.on("dragstart",o),null===(t=null==x?void 0:x.current)||void 0===t||t.on("dragend",r);const l=null===(n=null==x?void 0:x.current)||void 0===n?void 0:n.findOne("Transformer");return null==l||l.on("transformstart",o),null==l||l.on("transformend",r),()=>{var e,t;null===(e=null==x?void 0:x.current)||void 0===e||e.off("dragstart",o),null===(t=null==x?void 0:x.current)||void 0===t||t.off("dragend",r),null==l||l.off("transformstart",o),null==l||l.off("transformend",r)}},[]),n.useEffect(()=>{if(!(null==x?void 0:x.current)){return}const e=p(x.current.content,"polotno-workspace-inner");if(!e){return}const t=()=>{o.selectedShapes.length&&R()};return e.addEventListener("scroll",t),()=>{e.removeEventListener("scroll",t)}},[]);const T=o.selectedElements.map(e=>e.id).join(",");if(n.useEffect(()=>{if(!T){return}const e=requestAnimationFrame(()=>R());return()=>cancelAnimationFrame(e)},[T]),0===o.selectedShapes.length){return null}if(O){return null}if(!y){return null}if(o.activePage!==g){return null}if(F){return null}const k=l(o.selectedShapes),M=(null==b?void 0:b.Position)||d,P=(null==b?void 0:b.Duplicate)||a,X=(null==b?void 0:b.Remove)||c,Y=(null==b?void 0:b.Group)||m,A=(null==b?void 0:b.Lock)||f,L=null===(E=o.selectedElements[0])||void 0===E?void 0:E.type,B=Object.assign(Object.assign({},u.aiTextEnabled?{TextAiWrite:s}:{}),b||{}),_=i({components:B,type:L,usedItems:[]}),z=!!(null===(w=N.current)||void 0===w?void 0:w.isConnected);return e(r,{parentNodeFunc:h,transformFunc:e=>{var t,n,o;const r=k.x+k.width/2,l=null===(t=null==x?void 0:x.current)||void 0===t?void 0:t.container(),i=(null==l?void 0:l.getBoundingClientRect())||{left:0,top:0,width:0,height:0,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},s=null==l?void 0:l.closest(".polotno-workspace-container"),u=(null==s?void 0:s.getBoundingClientRect())||{left:0,top:0,width:Number.POSITIVE_INFINITY,height:Number.POSITIVE_INFINITY,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},a=i.left-u.left,c=i.top-u.top,d=(null===(n=N.current)||void 0===n?void 0:n.isConnected)?N.current.getBoundingClientRect():null,m=(null==d?void 0:d.width)||0,v=(null==d?void 0:d.height)||34,p=((null==j?void 0:j.top)||0)+8,f=(null!==(o=null==j?void 0:j.bottom)&&void 0!==o?o:45)+8,h=c+e.y+k.y*e.scaleY,g=c+e.y+(k.y+k.height)*e.scaleY,b=Number.isFinite(u.height),E=p+v/2,w=u.height-f-v/2;let y=h-80;b&&(y=Math.max(E,y));let I=y+v/2<=h-48?y:g+80;b&&(I=Math.min(w,Math.max(E,I)));let O=a+e.x+r*e.scaleX,S=O-k.width*e.scaleX/2,R=O+k.width*e.scaleX/2;const C=Math.min(50,k.width/2*e.scaleX),F=R>=C&&S<=u.width-C,T=(null==j?void 0:j.left)||0,M=(null==j?void 0:j.right)||0;if(Number.isFinite(u.width)&&m>0&&F){const e=8+m/2+T,t=u.width-8-m/2-M;t>=e&&(O=Math.max(e,Math.min(O,t)))}return R<C&&(O-=m+8),S>u.width-C&&(O+=m+8),Object.assign(Object.assign({},e),{x:O,y:I,scaleX:1,scaleY:1})},divProps:{style:{pointerEvents:"none",position:"absolute",visibility:z?"visible":"hidden",zIndex:9}},children:e("div",{ref:C,className:"polotno-selection-tooltip",style:{pointerEvents:"none"},children:t(v,{floating:!0,height:34,className:"pn:gap-0.5 pn:bg-popover pn:px-0.5",style:{transform:"translate(-50%, -50%)",pointerEvents:"auto"},children:[_.map(t=>{const n=B[t];return e(n,{elements:o.selectedElements,element:o.selectedElements[0],store:o},t)}),e(Y,{store:o}),e(A,{store:o}),e(P,{store:o}),e(X,{store:o}),e(M,{store:o})]})})})});
|
package/model/page-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getParentOfType as e,getSnapshot as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as n}from"nanoid";import{resolveBleed as r}from"@polotno/schema";import{ElementTypes as s,forEveryChild as d,forEveryNode as a,TYPES_MAP as m,zIndexOps as
|
|
1
|
+
import{getParentOfType as e,getSnapshot as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as n}from"nanoid";import{resolveBleed as r}from"@polotno/schema";import{ElementTypes as s,forEveryChild as d,forEveryNode as a,TYPES_MAP as m,zIndexOps as c}from"./group-model.js";import{Store as h}from"./store.js";import{getTotalClientRect as l}from"../utils/math.js";export const Page=i.model("Page",{id:i.identifier,children:i.array(i.late(()=>s)),width:i.optional(i.union(i.number,i.literal("auto")),"auto"),height:i.optional(i.union(i.number,i.literal("auto")),"auto"),background:"white",bleed:0,bleedTop:i.maybe(i.number),bleedRight:i.maybe(i.number),bleedBottom:i.maybe(i.number),bleedLeft:i.maybe(i.number),custom:i.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot(e=>{const t=Object.assign({},e),o={};for(var i in t){"_"!==i[0]&&(o[i]=e[i])}return o}).views(t=>({get store(){return e(t,h)}})).views(e=>({get startTime(){let t=0;for(const o of e.store.pages){if(o.id===e.id){return t}t+=o.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering},get playheadLocalTime(){if(!o(e)){return null}const t=e.store;if(!(null==t?void 0:t.playheadAccurate)){return null}const i=t.effectiveTime-this.startTime;return i<0||i>e.duration?null:Math.min(i,Math.max(0,e.duration-1))}})).views(e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height},get computedBleed(){return r(e)}})).actions(e=>({toJSON:()=>JSON.parse(JSON.stringify(t(e)))})).actions(e=>Object.assign(Object.assign({clone(t={}){const o=e.toJSON(),i=new Map;o.children.forEach(e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o,a(e,e=>{const t=e.id,o=n(10);i.set(t,o),e.id=o})}),o.children.forEach(e=>{e.cells&&e.cells.forEach(e=>{e.mergedInto&&i.has(e.mergedInto)&&(e.mergedInto=i.get(e.mergedInto))})});const r=Object.assign(Object.assign(Object.assign({},o),{id:n(10)}),t),s=e.store.selectedPages.includes(e),d=e.store.addPage(r),m=e.store.pages.indexOf(e);return d.setZIndex(m+1),s&&e.store.selectPages([d.id]),d},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t,{skipSelect:o=!1}={}){const i=m[t.type];if(!i){return void console.error("Can not find model with type "+t.type)}"children"in t&&Array.isArray(t.children)&&a(t,e=>{e.id=e.id||n(10)});const r=e.children.reduce((e,o)=>{if("group"===o.type){const i=o.children.reduce((e,o)=>{var i;const n=null===(i=o.name)||void 0===i?void 0:i.match(new RegExp(`${t.type}-(\\d+)`));if(n){const t=parseInt(n[1],10);return Math.max(e,t||0)}},0);return Math.max(e,i||0)}{const i=o.name.match(new RegExp(`${t.type}-(\\d+)`));if(i){const t=parseInt(i[1],10);return Math.max(e,t||0)}}return e},0),s=i.create(Object.assign({id:n(10),name:`${t.type}-${r+1}`},t));return e.children.push(s),s.selectable&&!o&&e.store.selectElements([s.id]),s}},c(e)),{setSize({width:t,height:o,useMagic:i,softChange:n}){if(i){const i=[],n=t=>"image"===t.type&&t.x<1&&t.y<1&&t.width>=e.computedWidth-2&&t.height>=e.computedHeight-2;d(e,e=>{"group"!==e.type&&(n(e)||i.push(e))});const r=i.length?l(i):{x:0,y:0,width:e.computedWidth,height:e.computedHeight},s=1/4,a=Math.max(0,Math.min(r.x,e.computedWidth-r.x-r.width)),m=e.computedWidth*s,c=Math.max(0,a-m),h=Math.max(0,Math.min(r.y,e.computedHeight-r.y-r.height)),p=e.computedHeight*s,g=Math.max(0,h-p),u=e.computedWidth-2*c,f=e.computedHeight-2*g,b=t/u,y=o/f,w=Math.min(b,y),v=(t-u*w)/2-c*w,x=(o-f*w)/2-g*w;d(e,e=>{var t;if("group"!==e.type){if(n(e)){e.set({x:e.x*w,y:e.y*w,width:e.width*b,height:e.height*y,cropX:0,cropY:0,cropWidth:1,cropHeight:1})}else if(e.set({x:v+e.x*w,y:x+e.y*w,width:e.width*w,height:e.height*w}),"text"===e.type){e.set({fontSize:e.fontSize*w})}else if("figure"===e.type){e.set({strokeWidth:e.strokeWidth*w})}else if("table"===e.type){e.set({borderWidth:e.borderWidth*w});for(const o of e.cells){const e={fontSize:o.fontSize*w,cellPadding:o.cellPadding*w};if(o.borders){const i=JSON.parse(JSON.stringify(o.borders));for(const e of["top","right","bottom","left"]){null!=(null===(t=i[e])||void 0===t?void 0:t.width)&&(i[e]=Object.assign(Object.assign({},i[e]),{width:i[e].width*w}))}e.borders=i}o.set(e)}}}})}n||(e.width=t),n||(e.height=o)}})).actions(e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}}));
|